Skip to main content

moq_wasm/
session.rs

1mod connection_watch_task;
2mod token_refresh_task;
3
4use std::{
5    ops::Deref,
6    sync::{Arc, Mutex},
7};
8
9use moqt::{
10    AuthorizationTokenSource, CertificateVerification, ClientConfig, DEFAULT_VERSIONS,
11    TransportClose, Version, client,
12};
13use tokio::sync::watch;
14
15use crate::token::{RefreshToken, TokenKeeper};
16use connection_watch_task::ConnectionWatchTask;
17use token_refresh_task::TokenRefreshTask;
18
19#[derive(Clone, Default)]
20pub struct ConnectOptions {
21    /// The JWT presented in CLIENT_SETUP.
22    pub token: Option<String>,
23    /// Called with the current token five minutes before its `exp`, and
24    /// every 30 s while it fails, until the token expires; needs `token`.
25    pub refresh_token: Option<RefreshToken>,
26    pub certificate_verification: CertificateVerification,
27    /// The drafts offered, most preferred first; draft-18, then draft-14,
28    /// when empty.
29    pub versions: Vec<Version>,
30}
31
32#[derive(Debug, Clone, PartialEq, Eq)]
33#[non_exhaustive]
34pub enum SessionEnd {
35    /// `Session::close` was called.
36    Closed,
37    /// The relay connection ended and could not be replaced: retrying
38    /// stopped after 60 s, or the relay closed it with a termination code
39    /// other than EXPIRED_AUTH_TOKEN.
40    ConnectionLost(TransportClose),
41    /// The token expired while `RefreshToken` kept failing.
42    TokenExpired,
43}
44
45/// Connects to `url`: `moqt://` over raw QUIC, `https://` over
46/// WebTransport. Fails when the relay cannot be reached or refuses the
47/// session, when `refresh_token` is given without `token`, or when `token`
48/// is no JWT with an `appId` claim.
49pub async fn connect(url: &str, options: ConnectOptions) -> anyhow::Result<Session> {
50    let keeper = match (&options.token, options.refresh_token) {
51        (Some(token), Some(refresh)) => Some(TokenKeeper::new(token.clone(), refresh)?),
52        (None, Some(_)) => anyhow::bail!("refresh_token needs a token"),
53        _ => None,
54    };
55    let current_token = options.token.map(|token| Arc::new(Mutex::new(token)));
56    let config = ClientConfig {
57        certificate_verification: options.certificate_verification,
58        authorization_token: current_token.clone().map(|current| {
59            AuthorizationTokenSource::provider(move || {
60                let token = current.lock().unwrap().clone();
61                async move { Ok(token) }
62            })
63        }),
64        versions: if options.versions.is_empty() {
65            DEFAULT_VERSIONS.to_vec()
66        } else {
67            options.versions
68        },
69        ..ClientConfig::default()
70    };
71    let client = Arc::new(client::Session::connect(url, &config).await?);
72    let (end_sender, _) = watch::channel(None);
73    let end_sender = Arc::new(end_sender);
74    let token_refresh = keeper.zip(current_token).map(|(keeper, current_token)| {
75        TokenRefreshTask::run(keeper, current_token, client.clone(), end_sender.clone())
76    });
77    Ok(Session {
78        _connection_watch: ConnectionWatchTask::run(client.clone(), end_sender.clone()),
79        _token_refresh: token_refresh,
80        client,
81        end_sender,
82    })
83}
84
85/// A relay session: the requests of `moqt::client::Session`, through
86/// `Deref`, with its token kept fresh. It follows GOAWAY and replaces a lost
87/// connection for up to 60 s, sending its namespaces and subscriptions
88/// again; when it cannot, the session ends with `SessionEnd::ConnectionLost`.
89pub struct Session {
90    client: Arc<client::Session>,
91    end_sender: Arc<watch::Sender<Option<SessionEnd>>>,
92    _connection_watch: ConnectionWatchTask,
93    _token_refresh: Option<TokenRefreshTask>,
94}
95
96impl Session {
97    pub(crate) fn client(&self) -> &Arc<client::Session> {
98        &self.client
99    }
100
101    /// Waits for the session to end; returns at once if it already has.
102    pub async fn closed(&self) -> SessionEnd {
103        let mut end_receiver = self.end_sender.subscribe();
104        let end = end_receiver
105            .wait_for(Option::is_some)
106            .await
107            .map(|end| end.clone());
108        // `self` holds the sender, so `wait_for` cannot fail and the fallback is unreachable.
109        end.ok().flatten().unwrap_or(SessionEnd::Closed)
110    }
111
112    /// Closes the session with NO_ERROR; `closed` resolves with
113    /// `SessionEnd::Closed`.
114    pub async fn close(&self) {
115        end(&self.end_sender, SessionEnd::Closed);
116        self.client.close().await;
117    }
118}
119
120impl Deref for Session {
121    type Target = client::Session;
122
123    fn deref(&self) -> &client::Session {
124        &self.client
125    }
126}
127
128fn end(end_sender: &watch::Sender<Option<SessionEnd>>, session_end: SessionEnd) {
129    end_sender.send_if_modified(|end| {
130        if end.is_some() {
131            return false;
132        }
133        *end = Some(session_end);
134        true
135    });
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141
142    #[test]
143    fn the_first_end_of_a_session_stays() {
144        // Arrange
145        let (end_sender, end_receiver) = watch::channel(None);
146
147        // Act
148        end(&end_sender, SessionEnd::TokenExpired);
149        end(&end_sender, SessionEnd::Closed);
150
151        // Assert
152        assert_eq!(*end_receiver.borrow(), Some(SessionEnd::TokenExpired));
153    }
154
155    #[tokio::test]
156    async fn a_refresh_without_a_token_is_refused_before_connecting() {
157        // Arrange
158        let options = ConnectOptions {
159            refresh_token: Some(RefreshToken::new(|token| async { Ok(token) })),
160            ..Default::default()
161        };
162
163        // Act
164        let result = connect("moqt://127.0.0.1:1", options).await;
165
166        // Assert
167        assert!(result.is_err_and(|error| error.to_string().contains("needs a token")));
168    }
169}