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    pub mime: &'static str,
34    /// Its bytes, its references to other assets already content-addressed.
35    pub identity: &'static [u8],
36    /// The same bytes, compressed — `None` when that is no smaller.
37    pub brotli: Option<&'static [u8]>,
38    pub gzip: Option<&'static [u8]>,
39}
40
41// `BUILD` and `ASSETS`.
42include!(concat!(env!("OUT_DIR"), "/manifest.rs"));
43
44/// Something a page loads from devpage itself.
45#[derive(Clone, Copy, Debug)]
46pub enum Owned<'a> {
47    /// A built-in asset, by the name it is written by: `"devpage.js"`.
48    Asset(&'a str),
49    /// A system widget, by name — `"Callout"` — for the document served under
50    /// `mount`, at its version `hash`.
51    SystemWidget {
52        name: &'a str,
53        mount: &'a str,
54        hash: &'a str,
55    },
56    /// A project widget, or a helper a widget imports, by its `name` in the
57    /// served folder under `mount`, at its version `hash` — what the
58    /// [widgets](crate::widgets) say its compiled bytes are made from.
59    Module {
60        mount: &'a str,
61        name: &'a str,
62        hash: &'a str,
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, hash } => {
81            format!("{mount}/__devpage/system-widgets/{name}.tsx?v={hash}")
82        }
83        Owned::Module { mount, name, hash } => {
84            format!("{mount}/__devpage/widgets/{name}?v={hash}")
85        }
86    }
87}
88
89/// The built-in asset a name under `/__devpage/` asks for, and whether it is
90/// its current content address. A bare name (`devpage.js`) and a stale hash
91/// (`devpage.0123456789abcdef.js`) find the asset, but not as current.
92pub fn asset(requested: &str) -> Option<(&'static Asset, bool)> {
93    if let Some(asset) = ASSETS.iter().find(|asset| asset.hashed == requested) {
94        return Some((asset, true));
95    }
96    let (stem, rest) = requested.split_once('.')?;
97    let ext = rest.rsplit_once('.').map_or(rest, |(_, ext)| ext);
98    ASSETS
99        .iter()
100        .find(|asset| asset.name == format!("{stem}.{ext}"))
101        .map(|asset| (asset, false))
102}
103
104/// The first 16 hex digits of a digest: what every address and validator
105/// carries.
106pub fn short(digest: &[u8]) -> String {
107    digest[..8].iter().map(|b| format!("{b:02x}")).collect()
108}
109
110/// The first 16 hex digits of the SHA-256 of `bytes`.
111pub fn hash(bytes: &[u8]) -> String {
112    short(&Sha256::digest(bytes))
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118
119    #[test]
120    fn every_asset_has_a_content_address_and_old_names_still_find_it() {
121        for asset in ASSETS {
122            let address = address(Owned::Asset(asset.name));
123            assert_eq!(address, format!("/__devpage/{}", asset.hashed));
124            assert_eq!(asset.hash, hash(asset.identity), "{}", asset.name);
125            let (found, current) = super::asset(asset.hashed).unwrap();
126            assert!(current && found.name == asset.name);
127            let (found, current) = super::asset(asset.name).unwrap();
128            assert!(!current && found.name == asset.name);
129            let (stem, ext) = asset.name.split_once('.').unwrap();
130            let (found, current) = super::asset(&format!("{stem}.0123456789abcdef.{ext}")).unwrap();
131            assert!(!current && found.name == asset.name);
132        }
133        assert!(super::asset("nope.js").is_none());
134    }
135
136    #[test]
137    fn an_asset_names_the_others_by_their_content_addresses() {
138        let text = |name: &str| {
139            let asset = ASSETS.iter().find(|a| a.name == name).unwrap();
140            String::from_utf8(asset.identity.to_vec()).unwrap()
141        };
142        assert!(text("devpage.js").contains(&address(Owned::Asset("design.js"))));
143        let design = text("design.js");
144        assert!(design.contains(&address(Owned::Asset("design-engine.js"))));
145        assert!(design.contains(&address(Owned::Asset("design-engine.wasm"))));
146        assert!(design.contains(&address(Owned::Asset("design-stream.js"))));
147        assert!(design.contains(&address(Owned::Asset("design-canvas.js"))));
148        assert!(text("design-canvas.js").contains(&address(Owned::Asset("design-tiles.js"))));
149        assert!(text("design-tiles.js").contains(&address(Owned::Asset("design-worker.js"))));
150    }
151
152    #[test]
153    fn a_widget_address_carries_its_mount_and_version() {
154        assert_eq!(
155            address(Owned::SystemWidget {
156                name: "Callout",
157                mount: "/d/x/v/1",
158                hash: "0123456789abcdef",
159            }),
160            "/d/x/v/1/__devpage/system-widgets/Callout.tsx?v=0123456789abcdef"
161        );
162        assert_eq!(
163            address(Owned::Module {
164                mount: "",
165                name: "docs/widgets/Card.tsx",
166                hash: "fedcba9876543210",
167            }),
168            "/__devpage/widgets/docs/widgets/Card.tsx?v=fedcba9876543210"
169        );
170    }
171}