Skip to main content

weirdnet_push/server/
relay.rs

1use crate::api::Announcement;
2use crate::error::{Error, Result};
3use crate::handle::WakeHandle;
4use crate::wake::Payload96;
5use axum::body::Body;
6use axum::response::Response;
7use serde::Deserialize;
8use sha2::{Digest, Sha256};
9use std::time::Duration;
10use tokio::sync::broadcast;
11
12/// The relay wake path: relays that follow this server get every relay-path wake and pass
13/// it on when the device with that handle is connected to them.
14#[derive(Debug, Clone, Deserialize)]
15#[serde(deny_unknown_fields)]
16pub struct RelayConfig {
17    /// SHA-256 digests (hex) of the relay tokens allowed to follow.
18    pub token_digests: Vec<String>,
19}
20
21/// Fans relay-path wakes out to the following relays.
22#[derive(Debug)]
23pub struct RelayHub {
24    digests: Vec<String>,
25    tx: broadcast::Sender<Announcement>,
26}
27
28/// The digest a relay token is listed by.
29pub fn token_digest(token: &str) -> String {
30    hex::encode(Sha256::digest(token.as_bytes()))
31}
32
33impl RelayHub {
34    /// A hub for `config`.
35    pub fn new(config: &RelayConfig) -> Result<Self> {
36        for d in &config.token_digests {
37            if d.len() != 64 || !d.bytes().all(|b| b.is_ascii_hexdigit()) {
38                return Err(Error::Invalid("relay token_digests must be hex SHA-256".into()));
39            }
40        }
41        Ok(Self { digests: config.token_digests.iter().map(|d| d.to_ascii_lowercase()).collect(), tx: broadcast::channel(4096).0 })
42    }
43
44    /// True if `token` may follow.
45    pub fn allows(&self, token: &str) -> bool {
46        use subtle::ConstantTimeEq;
47        let d = token_digest(token);
48        !token.is_empty() && self.digests.iter().fold(false, |ok, x| ok | bool::from(x.as_bytes().ct_eq(d.as_bytes())))
49    }
50
51    /// How many relays follow now.
52    pub fn followers(&self) -> usize {
53        self.tx.receiver_count()
54    }
55
56    pub(crate) fn announce(&self, handle: &WakeHandle, payload: Payload96) {
57        let _ = self.tx.send(Announcement { handle: handle.clone(), payload });
58    }
59
60    pub(crate) fn stream(&self) -> Response {
61        let rx = self.tx.subscribe();
62        let s = futures_util::stream::unfold(rx, |mut rx| async move {
63            loop {
64                match tokio::time::timeout(Duration::from_secs(25), rx.recv()).await {
65                    Err(_) => return Some((Ok::<_, std::io::Error>(b"\n".to_vec()), rx)), // keepalive
66                    Ok(Ok(a)) => {
67                        let mut line = serde_json::to_vec(&a).unwrap();
68                        line.push(b'\n');
69                        return Some((Ok(line), rx));
70                    }
71                    Ok(Err(broadcast::error::RecvError::Lagged(n))) => {
72                        tracing::warn!(dropped = n, "a relay fell behind");
73                    }
74                    Ok(Err(broadcast::error::RecvError::Closed)) => return None,
75                }
76            }
77        });
78        Response::builder().header("content-type", "application/x-ndjson").header("cache-control", "no-store").body(Body::from_stream(s)).unwrap()
79    }
80}