Skip to main content

devpage_core/
addresses.rs

1//! Content addresses: the one place an address devpage serves for a page to
2//! load is made.
3//!
4//! Everything a page loads from devpage itself — a built-in asset, a system
5//! widget, a project widget or a helper it imports — is named by
6//! [`address`], and by nothing else. The page's tags, the import map, the
7//! widget list, the import inside a compiled widget, and the server's answer
8//! to "is this address current?" all come from it, so two of them never
9//! differ by a byte: a browser that preloads one address and imports another
10//! downloads twice.
11//!
12//! Every address but a built-in asset's is the document's: it starts with the
13//! served folder's mount, so a version in server mode, under `/d/<id>/v/<n>`,
14//! asks its own router. A built-in asset is the same for every document.
15//!
16//! An address changes exactly when the bytes it serves would: a built-in
17//! asset's carries the hash of its bytes (`/__devpage/devpage.<hash>.js`); a
18//! widget's carries `?v=<hash>` over what its compiled module is made from.
19//! What answers a current address never changes, so it is served
20//! `immutable`; any other — a bare name, a stale hash — still answers, with
21//! the current bytes and `no-cache`.
22
23use sha2::{Digest, Sha256};
24
25/// A built-in asset, as `build.rs` made it.
26pub struct Asset {
27    /// The name it is written by in the source: `devpage.js`.
28    pub name: &'static str,
29    /// Its name under its content address: `devpage.<hash>.js`.
30    pub hashed: &'static str,
31    /// The first 16 hex digits of the SHA-256 of its bytes.
32    pub hash: &'static str,
33    /// Its media type, sent as `Content-Type`: `text/javascript`.
34    pub mime: &'static str,
35    /// Its bytes, its references to other assets already content-addressed.
36    pub identity: &'static [u8],
37    /// The same bytes, compressed — `None` when that is no smaller.
38    pub brotli: Option<&'static [u8]>,
39    /// The same bytes, gzipped — `None` when that is no smaller.
40    pub gzip: Option<&'static [u8]>,
41}
42
43// `BUILD` and `ASSETS`.
44include!(concat!(env!("OUT_DIR"), "/manifest.rs"));
45
46/// Something a page loads from devpage itself.
47#[derive(Clone, Copy, Debug)]
48pub enum Owned<'a> {
49    /// A built-in asset, by the name it is written by: `"devpage.js"`.
50    Asset(&'a str),
51    /// A system widget, by name — `"Callout"` — for the document served under
52    /// `mount`, at its version `hash`.
53    SystemWidget {
54        name: &'a str,
55        mount: &'a str,
56        hash: &'a str,
57    },
58    /// A project widget, or a helper a widget imports, by its `name` in the
59    /// served folder under `mount`, at its version `hash` — what the
60    /// [widgets](crate::widgets) say its compiled bytes are made from.
61    Module {
62        mount: &'a str,
63        name: &'a str,
64        hash: &'a str,
65    },
66}
67
68/// The address `owned` is served at, for a page to load: the only function
69/// that makes one.
70///
71/// Panics on an asset name that isn't built in — a mistake in devpage, not in
72/// a document.
73pub fn address(owned: Owned) -> String {
74    match owned {
75        Owned::Asset(name) => {
76            let asset = ASSETS
77                .iter()
78                .find(|asset| asset.name == name)
79                .unwrap_or_else(|| panic!("{name} is not a built-in asset"));
80            format!("/__devpage/{}", asset.hashed)
81        }
82        Owned::SystemWidget { name, mount, hash } => {
83            format!("{mount}/__devpage/system-widgets/{name}.tsx?v={hash}")
84        }
85        Owned::Module { mount, name, hash } => {
86            format!("{mount}/__devpage/widgets/{name}?v={hash}")
87        }
88    }
89}
90
91/// The built-in asset a name under `/__devpage/` asks for, and whether it is
92/// its current content address. A bare name (`devpage.js`) and a stale hash
93/// (`devpage.0123456789abcdef.js`) find the asset, but not as current.
94pub fn asset(requested: &str) -> Option<(&'static Asset, bool)> {
95    if let Some(asset) = ASSETS.iter().find(|asset| asset.hashed == requested) {
96        return Some((asset, true));
97    }
98    let (stem, rest) = requested.split_once('.')?;
99    let ext = rest.rsplit_once('.').map_or(rest, |(_, ext)| ext);
100    ASSETS
101        .iter()
102        .find(|asset| asset.name == format!("{stem}.{ext}"))
103        .map(|asset| (asset, false))
104}
105
106/// The first 16 hex digits of a digest: what every address and validator
107/// carries.
108pub fn short(digest: &[u8]) -> String {
109    digest[..8].iter().map(|b| format!("{b:02x}")).collect()
110}
111
112/// The first 16 hex digits of the SHA-256 of `bytes`.
113pub fn hash(bytes: &[u8]) -> String {
114    short(&Sha256::digest(bytes))
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120
121    #[test]
122    fn every_asset_has_a_content_address_and_old_names_still_find_it() {
123        for asset in ASSETS {
124            let address = address(Owned::Asset(asset.name));
125            assert_eq!(address, format!("/__devpage/{}", asset.hashed));
126            assert_eq!(asset.hash, hash(asset.identity), "{}", asset.name);
127            let (found, current) = super::asset(asset.hashed).unwrap();
128            assert!(current && found.name == asset.name);
129            let (found, current) = super::asset(asset.name).unwrap();
130            assert!(!current && found.name == asset.name);
131            let (stem, ext) = asset.name.split_once('.').unwrap();
132            let (found, current) = super::asset(&format!("{stem}.0123456789abcdef.{ext}")).unwrap();
133            assert!(!current && found.name == asset.name);
134        }
135        assert!(super::asset("nope.js").is_none());
136    }
137
138    #[test]
139    fn an_asset_names_the_others_by_their_content_addresses() {
140        let text = |name: &str| {
141            let asset = ASSETS.iter().find(|a| a.name == name).unwrap();
142            String::from_utf8(asset.identity.to_vec()).unwrap()
143        };
144        assert!(text("devpage.js").contains(&address(Owned::Asset("design.js"))));
145        let design = text("design.js");
146        assert!(design.contains(&address(Owned::Asset("design-engine.js"))));
147        assert!(design.contains(&address(Owned::Asset("design-engine.wasm"))));
148        assert!(design.contains(&address(Owned::Asset("design-stream.js"))));
149        assert!(design.contains(&address(Owned::Asset("design-canvas.js"))));
150        assert!(text("design-canvas.js").contains(&address(Owned::Asset("design-tiles.js"))));
151        assert!(text("design-tiles.js").contains(&address(Owned::Asset("design-worker.js"))));
152    }
153
154    #[test]
155    fn a_widget_address_carries_its_mount_and_version() {
156        assert_eq!(
157            address(Owned::SystemWidget {
158                name: "Callout",
159                mount: "/d/x/v/1",
160                hash: "0123456789abcdef",
161            }),
162            "/d/x/v/1/__devpage/system-widgets/Callout.tsx?v=0123456789abcdef"
163        );
164        assert_eq!(
165            address(Owned::Module {
166                mount: "",
167                name: "docs/widgets/Card.tsx",
168                hash: "fedcba9876543210",
169            }),
170            "/__devpage/widgets/docs/widgets/Card.tsx?v=fedcba9876543210"
171        );
172    }
173}