moq_transfork/model/
router.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
use std::ops;

use tokio::sync::{mpsc, oneshot};

use crate::{Error, Track, TrackConsumer, TrackProducer};

/// Used to respond to arbitrary track requests.
pub struct Router {
	/// The maximum number of requests that can be queued before blocking.
	pub capacity: usize,
}

impl Router {
	pub fn produce(&self) -> (RouterProducer, RouterConsumer) {
		let (send, recv) = mpsc::channel(self.capacity);

		let writer = RouterProducer::new(recv);
		let reader = RouterConsumer::new(send);

		(writer, reader)
	}
}

impl Default for Router {
	fn default() -> Self {
		Self { capacity: 32 }
	}
}

/// Receive broadcast/track requests and return if we can fulfill them.
pub struct RouterProducer {
	queue: mpsc::Receiver<RouterRequest>,
}

impl RouterProducer {
	fn new(queue: mpsc::Receiver<RouterRequest>) -> Self {
		Self { queue }
	}

	pub async fn requested(&mut self) -> Option<RouterRequest> {
		self.queue.recv().await
	}
}

/// Subscribe to abitrary broadcast/tracks.
#[derive(Clone)]
pub struct RouterConsumer {
	queue: mpsc::Sender<RouterRequest>,
}

impl RouterConsumer {
	fn new(queue: mpsc::Sender<RouterRequest>) -> Self {
		Self { queue }
	}

	pub async fn subscribe(&self, track: Track) -> Result<TrackConsumer, Error> {
		let (send, recv) = oneshot::channel();
		let request = RouterRequest { track, reply: send };

		if self.queue.send(request).await.is_err() {
			return Err(Error::Cancel);
		}

		recv.await.map_err(|_| Error::Cancel)?
	}

	pub async fn closed(&self) {
		self.queue.closed().await;
	}
}

/// An outstanding request for a path.
pub struct RouterRequest {
	pub track: Track,
	reply: oneshot::Sender<Result<TrackConsumer, Error>>,
}

impl RouterRequest {
	pub fn serve(self, reader: TrackConsumer) {
		self.reply.send(Ok(reader)).ok();
	}

	pub fn produce(self) -> TrackProducer {
		let (writer, reader) = self.track.produce();
		self.reply.send(Ok(reader)).ok();
		writer
	}

	pub fn close(self, error: Error) {
		self.reply.send(Err(error)).ok();
	}
}

impl ops::Deref for RouterRequest {
	type Target = Track;

	fn deref(&self) -> &Self::Target {
		&self.track
	}
}