Skip to main content

tilo_net/
caps.rs

1//! What this crate provides on each target, as data an app can query.
2
3pub use tilo_platform_caps::{Availability, availability, available};
4
5pub type Unsupported = tilo_platform_caps::Unsupported<Feature>;
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
8#[non_exhaustive]
9pub enum Feature {
10    Http,
11    CrossOriginHttp,
12    WebSocket,
13    WebTransport,
14    Sockets,
15    PeerToPeer,
16    Status,
17    Metered,
18}
19
20pub(crate) const WEB_CROSS_ORIGIN: &str = "The browser only reads responses from sites that allow it; the host can relay others through its fetch proxy.";
21pub(crate) const WEB_SOCKETS: &str = "A browser page cannot open raw network connections.";
22pub(crate) const WEB_PEER_TO_PEER: &str = "A browser page cannot accept connections from peers.";
23#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
24pub(crate) const NO_WEBTRANSPORT: &str = "This browser has no WebTransport.";
25pub(crate) const NOT_YET: &str = "Tilo cannot do this yet.";
26
27impl tilo_platform_caps::Feature for Feature {
28    /// Availability on Linux, macOS and web, in that order.
29    fn targets(self) -> [Availability; 3] {
30        use Availability::{Available, Unsupported};
31        match self {
32            Self::Http | Self::WebSocket | Self::WebTransport | Self::Status => {
33                [Available, Available, Available]
34            }
35            Self::CrossOriginHttp => [Available, Available, Unsupported(WEB_CROSS_ORIGIN)],
36            Self::Sockets => [Available, Available, Unsupported(WEB_SOCKETS)],
37            Self::PeerToPeer => [Available, Available, Unsupported(WEB_PEER_TO_PEER)],
38            // Linux asks the session portal, which may be unavailable or refuse.
39            Self::Metered => [Available, Unsupported(NOT_YET), Available],
40        }
41    }
42
43    fn availability(self) -> Availability {
44        #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
45        if self == Self::WebTransport && !crate::web::has_global("WebTransport") {
46            return Availability::Unsupported(NO_WEBTRANSPORT);
47        }
48        self.targets()[tilo_platform_caps::COLUMN]
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55    use tilo_platform_caps::Feature as _;
56
57    #[test]
58    fn the_desktop_reads_its_own_column() {
59        assert_eq!(availability(Feature::Sockets), Availability::Available);
60        assert_eq!(
61            availability(Feature::CrossOriginHttp),
62            Availability::Available
63        );
64        let web = Feature::Sockets.targets()[2];
65        assert_eq!(web, Availability::Unsupported(WEB_SOCKETS));
66    }
67}