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 std::path::Path;
24use std::sync::LazyLock;
25
26use sha2::{Digest, Sha256};
27
28/// A built-in asset, as `build.rs` made it.
29pub struct Asset {
30    /// The name it is written by in the source: `devpage.js`.
31    pub name: &'static str,
32    /// Its name under its content address: `devpage.<hash>.js`.
33    pub hashed: &'static str,
34    /// The first 16 hex digits of the SHA-256 of its bytes.
35    pub hash: &'static str,
36    pub mime: &'static str,
37    /// Its bytes, its references to other assets already content-addressed.
38    pub identity: &'static [u8],
39    /// The same bytes, compressed — `None` when that is no smaller.
40    pub brotli: Option<&'static [u8]>,
41    pub gzip: Option<&'static [u8]>,
42}
43
44// `BUILD` and `ASSETS`.
45include!(concat!(env!("OUT_DIR"), "/manifest.rs"));
46
47/// Something a page loads from devpage itself.
48#[derive(Clone, Copy, Debug)]
49pub enum Owned<'a> {
50    /// A built-in asset, by the name it is written by: `"devpage.js"`.
51    Asset(&'a str),
52    /// A system widget, by name — `"Callout"` — for the document served under
53    /// `mount`.
54    SystemWidget { name: &'a str, mount: &'a str },
55    /// A project widget, or a helper a widget imports: its file in the served
56    /// folder, the [snapshot](crate::widgets::Snapshot) of the files it is
57    /// made from, and the widget names it can render — those of the document
58    /// whose widgets folder holds it.
59    Module {
60        snapshot: &'a crate::widgets::Snapshot,
61        file: &'a Path,
62        known: &'a [String],
63    },
64}
65
66/// The address `owned` is served at, for a page to load: the only function
67/// that makes one.
68///
69/// Panics on an asset name that isn't built in — a mistake in devpage, not in
70/// a document.
71pub fn address(owned: Owned) -> String {
72    match owned {
73        Owned::Asset(name) => {
74            let asset = ASSETS
75                .iter()
76                .find(|asset| asset.name == name)
77                .unwrap_or_else(|| panic!("{name} is not a built-in asset"));
78            format!("/__devpage/{}", asset.hashed)
79        }
80        Owned::SystemWidget { name, mount } => format!(
81            "{mount}/__devpage/system-widgets/{name}.tsx?v={}",
82            system_widget_hash(name).unwrap_or_default()
83        ),
84        Owned::Module {
85            snapshot,
86            file,
87            known,
88        } => format!(
89            "{}/__devpage/widgets/{}?v={}",
90            snapshot.served().mount(),
91            snapshot.served().name(file),
92            snapshot.hash(file, known)
93        ),
94    }
95}
96
97/// The built-in asset a name under `/__devpage/` asks for, and whether it is
98/// its current content address. A bare name (`devpage.js`) and a stale hash
99/// (`devpage.0123456789abcdef.js`) find the asset, but not as current.
100pub fn asset(requested: &str) -> Option<(&'static Asset, bool)> {
101    if let Some(asset) = ASSETS.iter().find(|asset| asset.hashed == requested) {
102        return Some((asset, true));
103    }
104    let (stem, rest) = requested.split_once('.')?;
105    let ext = rest.rsplit_once('.').map_or(rest, |(_, ext)| ext);
106    ASSETS
107        .iter()
108        .find(|asset| asset.name == format!("{stem}.{ext}"))
109        .map(|asset| (asset, false))
110}
111
112/// A system widget's version: its source, the names it can render and the
113/// build. `None` for a name that isn't a system widget.
114pub fn system_widget_hash(name: &str) -> Option<&'static str> {
115    static HASHES: LazyLock<Vec<(&'static str, String)>> = LazyLock::new(|| {
116        let names: Vec<&str> = crate::widgets::SYSTEM.iter().map(|(n, _)| *n).collect();
117        crate::widgets::SYSTEM
118            .iter()
119            .map(|(name, source)| {
120                let mut hash = Sha256::new();
121                hash.update(BUILD);
122                hash.update(names.join("\0"));
123                hash.update(name);
124                hash.update(source);
125                (*name, short(&hash.finalize()))
126            })
127            .collect()
128    });
129    HASHES
130        .iter()
131        .find(|(n, _)| *n == name)
132        .map(|(_, hash)| hash.as_str())
133}
134
135/// The first 16 hex digits of a digest: what every address and validator
136/// carries.
137pub fn short(digest: &[u8]) -> String {
138    digest[..8].iter().map(|b| format!("{b:02x}")).collect()
139}
140
141/// The first 16 hex digits of the SHA-256 of `bytes`.
142pub fn hash(bytes: &[u8]) -> String {
143    short(&Sha256::digest(bytes))
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149
150    #[test]
151    fn every_asset_has_a_content_address_and_old_names_still_find_it() {
152        for asset in ASSETS {
153            let address = address(Owned::Asset(asset.name));
154            assert_eq!(address, format!("/__devpage/{}", asset.hashed));
155            assert_eq!(asset.hash, hash(asset.identity), "{}", asset.name);
156            let (found, current) = super::asset(asset.hashed).unwrap();
157            assert!(current && found.name == asset.name);
158            let (found, current) = super::asset(asset.name).unwrap();
159            assert!(!current && found.name == asset.name);
160            let (stem, ext) = asset.name.split_once('.').unwrap();
161            let (found, current) = super::asset(&format!("{stem}.0123456789abcdef.{ext}")).unwrap();
162            assert!(!current && found.name == asset.name);
163        }
164        assert!(super::asset("nope.js").is_none());
165    }
166
167    #[test]
168    fn an_asset_names_the_others_by_their_content_addresses() {
169        let text = |name: &str| {
170            let asset = ASSETS.iter().find(|a| a.name == name).unwrap();
171            String::from_utf8(asset.identity.to_vec()).unwrap()
172        };
173        assert!(text("devpage.js").contains(&address(Owned::Asset("design.js"))));
174        let design = text("design.js");
175        assert!(design.contains(&address(Owned::Asset("design-engine.js"))));
176        assert!(design.contains(&address(Owned::Asset("design-engine.wasm"))));
177        assert!(design.contains(&address(Owned::Asset("design-stream.js"))));
178        assert!(design.contains(&address(Owned::Asset("design-canvas.js"))));
179        assert!(text("design-canvas.js").contains(&address(Owned::Asset("design-tiles.js"))));
180        assert!(text("design-tiles.js").contains(&address(Owned::Asset("design-worker.js"))));
181    }
182
183    #[test]
184    fn a_system_widget_address_carries_its_version() {
185        let callout = address(Owned::SystemWidget {
186            name: "Callout",
187            mount: "",
188        });
189        assert_eq!(
190            callout,
191            format!(
192                "/__devpage/system-widgets/Callout.tsx?v={}",
193                system_widget_hash("Callout").unwrap()
194            )
195        );
196        assert_ne!(
197            system_widget_hash("Callout"),
198            system_widget_hash("Tabs"),
199            "each system widget has its own version"
200        );
201    }
202}