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's module, or a module system widgets share, by its
52    /// file name — `"Callout.tsx"`, `"live.ts"` — for the document served
53    /// under `mount`, at its version `hash`.
54    SystemModule {
55        file: &'a str,
56        mount: &'a str,
57        hash: &'a str,
58    },
59    /// A project widget, or a helper a widget imports, by its `name` in the
60    /// served folder under `mount`, at its version `hash` — what the
61    /// [widgets](crate::widgets) say its compiled bytes are made from.
62    Module {
63        mount: &'a str,
64        name: &'a str,
65        hash: &'a str,
66    },
67}
68
69/// The address `owned` is served at, for a page to load: the only function
70/// that makes one.
71///
72/// Panics on an asset name that isn't built in — a mistake in devpage, not in
73/// a document.
74pub fn address(owned: Owned) -> String {
75    match owned {
76        Owned::Asset(name) => {
77            let asset = ASSETS
78                .iter()
79                .find(|asset| asset.name == name)
80                .unwrap_or_else(|| panic!("{name} is not a built-in asset"));
81            format!("/__devpage/{}", asset.hashed)
82        }
83        Owned::SystemModule { file, mount, hash } => {
84            format!("{mount}/__devpage/system-widgets/{file}?v={hash}")
85        }
86        Owned::Module { mount, name, hash } => {
87            format!("{mount}/__devpage/widgets/{name}?v={hash}")
88        }
89    }
90}
91
92/// The built-in asset a name under `/__devpage/` asks for, and whether it is
93/// its current content address. A bare name (`devpage.js`) and a stale hash
94/// (`devpage.0123456789abcdef.js`) find the asset, but not as current.
95pub fn asset(requested: &str) -> Option<(&'static Asset, bool)> {
96    if let Some(asset) = ASSETS.iter().find(|asset| asset.hashed == requested) {
97        return Some((asset, true));
98    }
99    let (stem, rest) = requested.split_once('.')?;
100    let ext = rest.rsplit_once('.').map_or(rest, |(_, ext)| ext);
101    ASSETS
102        .iter()
103        .find(|asset| asset.name == format!("{stem}.{ext}"))
104        .map(|asset| (asset, false))
105}
106
107/// The first 16 hex digits of a digest: what every address and validator
108/// carries.
109pub fn short(digest: &[u8]) -> String {
110    digest[..8].iter().map(|b| format!("{b:02x}")).collect()
111}
112
113/// The first 16 hex digits of the SHA-256 of `bytes`.
114pub fn hash(bytes: &[u8]) -> String {
115    short(&Sha256::digest(bytes))
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121
122    #[test]
123    fn every_asset_has_a_content_address_and_old_names_still_find_it() {
124        for asset in ASSETS {
125            let address = address(Owned::Asset(asset.name));
126            assert_eq!(address, format!("/__devpage/{}", asset.hashed));
127            assert_eq!(asset.hash, hash(asset.identity), "{}", asset.name);
128            let (found, current) = super::asset(asset.hashed).unwrap();
129            assert!(current && found.name == asset.name);
130            let (found, current) = super::asset(asset.name).unwrap();
131            assert!(!current && found.name == asset.name);
132            let (stem, ext) = asset.name.split_once('.').unwrap();
133            let (found, current) = super::asset(&format!("{stem}.0123456789abcdef.{ext}")).unwrap();
134            assert!(!current && found.name == asset.name);
135        }
136        assert!(super::asset("nope.js").is_none());
137    }
138
139    #[test]
140    fn an_asset_names_the_others_by_their_content_addresses() {
141        let text = |name: &str| {
142            let asset = ASSETS.iter().find(|a| a.name == name).unwrap();
143            String::from_utf8(asset.identity.to_vec()).unwrap()
144        };
145        assert!(text("devpage.js").contains(&address(Owned::Asset("design.js"))));
146        let design = text("design.js");
147        assert!(design.contains(&address(Owned::Asset("design-engine.js"))));
148        assert!(design.contains(&address(Owned::Asset("design-engine.wasm"))));
149        assert!(design.contains(&address(Owned::Asset("design-stream.js"))));
150        assert!(design.contains(&address(Owned::Asset("design-canvas.js"))));
151        assert!(text("design-canvas.js").contains(&address(Owned::Asset("design-tiles.js"))));
152        assert!(text("design-tiles.js").contains(&address(Owned::Asset("design-worker.js"))));
153    }
154
155    #[test]
156    fn a_widget_address_carries_its_mount_and_version() {
157        assert_eq!(
158            address(Owned::SystemModule {
159                file: "Callout.tsx",
160                mount: "/d/x/v/1",
161                hash: "0123456789abcdef",
162            }),
163            "/d/x/v/1/__devpage/system-widgets/Callout.tsx?v=0123456789abcdef"
164        );
165        assert_eq!(
166            address(Owned::Module {
167                mount: "",
168                name: "docs/widgets/Card.tsx",
169                hash: "fedcba9876543210",
170            }),
171            "/__devpage/widgets/docs/widgets/Card.tsx?v=fedcba9876543210"
172        );
173    }
174}