Skip to main content

weirdnet_streaming/
net.rs

1//! Streams over weirdnet-net: a [`Hub`] served on a node, and a [`Subscriber`] to one stream.
2use crate::hub::Publisher;
3use crate::source::{FrameSource, MemorySource};
4use crate::stats::Stats;
5use crate::types::{Frame, Start, StreamError, StreamEvent, StreamId, StreamInfo, SubscribeOptions};
6use crate::wire::{self, Hello, Msg};
7use std::collections::HashMap;
8use std::sync::{Arc, Mutex};
9use std::time::Instant;
10use weirdnet_net::{Limits, Message, Multiaddr, Node, PeerId, Stream};
11
12/// The stream protocol id.
13pub const PROTOCOL: &str = "/weirdnet/audio-stream/1";
14
15/// Decides whether `peer` may subscribe to `stream`. A closure works.
16pub trait StreamAuth: Send + Sync {
17    /// `Err(reason)` refuses the subscription.
18    fn authorize(&self, peer: &PeerId, stream: &StreamId) -> Result<(), String>;
19}
20
21impl<F: Fn(&PeerId, &StreamId) -> Result<(), String> + Send + Sync> StreamAuth for F {
22    fn authorize(&self, peer: &PeerId, stream: &StreamId) -> Result<(), String> {
23        self(peer, stream)
24    }
25}
26
27/// Lets everyone subscribe (tests, or a node whose connections are already gated).
28pub struct AllowAll;
29
30impl StreamAuth for AllowAll {
31    fn authorize(&self, _: &PeerId, _: &StreamId) -> Result<(), String> {
32        Ok(())
33    }
34}
35
36/// The streams a node offers: live publishers and recorded sources.
37#[derive(Default)]
38pub struct Hub {
39    live: Mutex<HashMap<StreamId, Publisher>>,
40    recorded: Mutex<HashMap<StreamId, MemorySource>>,
41}
42
43impl Hub {
44    /// An empty hub.
45    pub fn new() -> Self {
46        Self::default()
47    }
48
49    /// Offer a live stream (replacing one with the same id).
50    pub fn publish(&self, p: &Publisher) {
51        self.live.lock().unwrap_or_else(|e| e.into_inner()).insert(p.info().id, p.clone());
52    }
53
54    /// Offer a recorded stream.
55    pub fn add_recorded(&self, s: MemorySource) {
56        self.recorded.lock().unwrap_or_else(|e| e.into_inner()).insert(s.info().id.clone(), s);
57    }
58
59    /// Stop offering a stream. Current subscribers of a live stream keep it until it ends.
60    pub fn remove(&self, id: &StreamId) {
61        self.live.lock().unwrap_or_else(|e| e.into_inner()).remove(id);
62        self.recorded.lock().unwrap_or_else(|e| e.into_inner()).remove(id);
63    }
64
65    /// The streams offered.
66    pub fn streams(&self) -> Vec<StreamInfo> {
67        let mut v: Vec<StreamInfo> = self.live.lock().unwrap_or_else(|e| e.into_inner()).values().map(|p| p.info()).collect();
68        v.extend(self.recorded.lock().unwrap_or_else(|e| e.into_inner()).values().map(|s| s.info().clone()));
69        v.sort_by(|a, b| a.id.cmp(&b.id));
70        v
71    }
72
73    fn find(&self, id: &StreamId) -> Option<Found> {
74        if let Some(p) = self.live.lock().unwrap_or_else(|e| e.into_inner()).get(id) {
75            return Some(Found::Live(p.clone()));
76        }
77        self.recorded.lock().unwrap_or_else(|e| e.into_inner()).get(id).map(|s| Found::Recorded(s.clone()))
78    }
79}
80
81enum Found {
82    Live(Publisher),
83    Recorded(MemorySource),
84}
85
86/// Serving a hub. Dropping it stops accepting new subscribers.
87pub struct Server {
88    task: tokio::task::JoinHandle<()>,
89}
90
91impl Drop for Server {
92    fn drop(&mut self) {
93        self.task.abort();
94    }
95}
96
97/// Serve `hub` on `node` at [`PROTOCOL`], asking `auth` about each subscription. Needs a tokio
98/// runtime context.
99pub fn serve<Q: Message, R: Message>(node: &Arc<Node<Q, R>>, hub: Arc<Hub>, auth: Arc<dyn StreamAuth>) -> Result<Server, StreamError> {
100    let mut incoming = node.accept_streams(PROTOCOL, Limits::default()).map_err(|e| StreamError::Net(e.to_string()))?;
101    let task = tokio::spawn(async move {
102        while let Some(s) = incoming.next().await {
103            let (hub, auth) = (hub.clone(), auth.clone());
104            tokio::spawn(async move {
105                let _ = handle(s, hub, auth).await;
106            });
107        }
108    });
109    Ok(Server { task })
110}
111
112async fn handle(mut s: Stream, hub: Arc<Hub>, auth: Arc<dyn StreamAuth>) -> std::io::Result<()> {
113    let hello = match tokio::time::timeout(std::time::Duration::from_secs(30), wire::read(&mut s)).await {
114        Ok(Ok(Some(Msg::Hello(h)))) => h,
115        _ => return Ok(()),
116    };
117    let peer = s.peer();
118    if let Err(reason) = auth.authorize(&peer, &hello.stream) {
119        return wire::write(&mut s, &Msg::Refused(reason)).await;
120    }
121    match hub.find(&hello.stream) {
122        None => wire::write(&mut s, &Msg::Refused("unknown stream".into())).await,
123        Some(Found::Live(p)) => {
124            let mut l = p.listen_as(&peer.to_string(), hello.options.buffer);
125            wire::write(&mut s, &Msg::Info(p.info())).await?;
126            while let Some(ev) = l.next().await {
127                let m = match ev {
128                    StreamEvent::Frame(f) => Msg::Frame(f),
129                    StreamEvent::InfoChanged(i) => Msg::Info(i),
130                    StreamEvent::Ended => Msg::Ended,
131                    StreamEvent::Gap { .. } => continue,
132                };
133                wire::write(&mut s, &m).await?;
134            }
135            if l.overrun() {
136                wire::write(&mut s, &Msg::Refused("fell too far behind".into())).await?;
137            }
138            Ok(())
139        }
140        Some(Found::Recorded(mut src)) => {
141            wire::write(&mut s, &Msg::Info(src.info().clone())).await?;
142            match hello.options.start {
143                Start::At(pts) => src.seek(pts),
144                Start::Live | Start::FromStart => {}
145            }
146            while let Some(f) = src.read() {
147                wire::write(&mut s, &Msg::Frame(f)).await?;
148            }
149            wire::write(&mut s, &Msg::Ended).await
150        }
151    }
152}
153
154/// One subscription to a stream on another node.
155pub struct Subscriber {
156    s: Stream,
157    info: StreamInfo,
158    stats: Stats,
159    held: Option<Frame>,
160    epoch: Instant,
161    done: bool,
162}
163
164impl Subscriber {
165    /// Subscribe to `stream` on `peer` (reached through `addrs` if not connected).
166    pub async fn connect<Q: Message, R: Message>(
167        node: &Node<Q, R>,
168        peer: PeerId,
169        addrs: &[Multiaddr],
170        stream: &StreamId,
171        options: SubscribeOptions,
172    ) -> Result<Subscriber, StreamError> {
173        let mut s = node.open_stream_async(peer, addrs, PROTOCOL, Limits::default()).await.map_err(|e| StreamError::Net(e.to_string()))?;
174        let net = |e: std::io::Error| StreamError::Net(e.to_string());
175        wire::write(&mut s, &Msg::Hello(Hello { stream: stream.clone(), options })).await.map_err(net)?;
176        match wire::read(&mut s).await.map_err(net)? {
177            Some(Msg::Info(info)) => Ok(Subscriber { s, info, stats: Stats::default(), held: None, epoch: Instant::now(), done: false }),
178            Some(Msg::Refused(r)) if r == "unknown stream" => Err(StreamError::UnknownStream),
179            Some(Msg::Refused(r)) => Err(StreamError::Refused(r)),
180            Some(_) => Err(StreamError::Protocol("expected the stream info".into())),
181            None => Err(StreamError::Net("closed before answering".into())),
182        }
183    }
184
185    /// The stream's info (updated by [`StreamEvent::InfoChanged`]).
186    pub fn info(&self) -> &StreamInfo {
187        &self.info
188    }
189
190    /// Arrival statistics so far.
191    pub fn stats(&self) -> &Stats {
192        &self.stats
193    }
194
195    /// The next event; `None` after [`StreamEvent::Ended`] or when the connection fails.
196    pub async fn next(&mut self) -> Option<StreamEvent> {
197        if let Some(f) = self.held.take() {
198            return Some(StreamEvent::Frame(f));
199        }
200        if self.done {
201            return None;
202        }
203        match wire::read(&mut self.s).await {
204            Ok(Some(Msg::Frame(f))) => {
205                let at = self.epoch.elapsed().as_secs_f64() * 1000.0;
206                let missed = self.stats.observe(f.seq, f.pts, f.payload.len(), self.info.clock_rate, at);
207                if missed > 0 {
208                    self.held = Some(f);
209                    return Some(StreamEvent::Gap { missed });
210                }
211                Some(StreamEvent::Frame(f))
212            }
213            Ok(Some(Msg::Info(i))) => {
214                self.info = i.clone();
215                Some(StreamEvent::InfoChanged(i))
216            }
217            Ok(Some(Msg::Ended)) => {
218                self.done = true;
219                Some(StreamEvent::Ended)
220            }
221            _ => {
222                self.done = true;
223                None
224            }
225        }
226    }
227}