Skip to main content

compmd_host/registry/
local_registry.rs

1//! A registry on the machine, for tests ([the language server]'s testing): it serves the packs it is given over npm's
2//! protocol, their abbreviated metadata, their tarballs and each scope's search, from `http://127.0.0.1`, and records
3//! what it was asked.
4//!
5//! [the language server]: https://github.com/comp-markdown/compmd/blob/main/docs/language-server.md
6
7use std::collections::BTreeMap;
8use std::io::{self, BufRead, BufReader, Write};
9use std::net::{TcpListener, TcpStream};
10use std::sync::atomic::{AtomicBool, Ordering};
11use std::sync::{Arc, Mutex, PoisonError};
12use std::thread;
13
14use miniz_oxide::deflate::compress_to_vec;
15use serde_json::{Map, Value, json};
16
17use super::integrity::integrity_of;
18use super::search::{PACK_KEYWORD, search_path};
19
20/// A tar block.
21const BLOCK: usize = 512;
22
23/// A pack the registry serves: its name, each version with its files by path in the package.
24#[derive(Clone, Debug, Default)]
25pub struct ServedPack {
26    name: String,
27    versions: BTreeMap<String, BTreeMap<String, Vec<u8>>>,
28}
29
30impl ServedPack {
31    /// The pack `name`, `@kit/mermaid`, with no versions yet.
32    #[must_use]
33    pub fn new(name: &str) -> Self {
34        Self {
35            name: name.to_owned(),
36            versions: BTreeMap::new(),
37        }
38    }
39
40    /// The pack with `version` too, `1.2.0`, of `files`, each a path in the package and its text.
41    #[must_use]
42    pub fn version(mut self, version: &str, files: &[(&str, &str)]) -> Self {
43        let files = files
44            .iter()
45            .map(|(path, text)| ((*path).to_owned(), text.as_bytes().to_vec()))
46            .collect();
47        self.versions.insert(version.to_owned(), files);
48        self
49    }
50}
51
52/// What the registry answers a path with.
53type Routes = BTreeMap<String, (&'static str, Vec<u8>)>;
54
55/// A registry serving packs on the machine until it is dropped.
56///
57/// ```
58/// use compmd_host::registry::{LocalRegistry, ServedPack};
59///
60/// let mermaid = ServedPack::new("@kit/mermaid").version("1.2.0", &[("package.json", "{}")]);
61/// let registry = LocalRegistry::serve(&[mermaid])?;
62/// assert!(registry.url().starts_with("http://127.0.0.1:"));
63/// # Ok::<(), std::io::Error>(())
64/// ```
65#[derive(Debug)]
66pub struct LocalRegistry {
67    url: String,
68    asked: Arc<Mutex<Vec<String>>>,
69    stopped: Arc<AtomicBool>,
70}
71
72/// `files` as a pack's tarball: a tar of them under `package/`, gzipped, as npm publishes one.
73#[must_use]
74pub fn tarball(files: &BTreeMap<String, Vec<u8>>) -> Vec<u8> {
75    let mut archive = Vec::new();
76    for (path, bytes) in files {
77        let mut header = vec![0u8; BLOCK];
78        let name = format!("package/{path}");
79        header[..name.len()].copy_from_slice(name.as_bytes());
80        header[124..135].copy_from_slice(format!("{:011o}", bytes.len()).as_bytes());
81        header[156] = b'0';
82        archive.extend(header);
83        archive.extend(bytes);
84        archive.resize(archive.len().div_ceil(BLOCK) * BLOCK, 0);
85    }
86    archive.extend([0u8; BLOCK * 2]);
87    let mut gzipped = vec![0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 0, 3];
88    gzipped.extend(compress_to_vec(&archive, 6));
89    gzipped.extend([0; 8]);
90    gzipped
91}
92
93/// Whether `pack` is a pack by its keyword: one of its versions' `package.json` lists [`PACK_KEYWORD`].
94fn lists_the_keyword(pack: &ServedPack) -> bool {
95    pack.versions.values().any(|files| {
96        files
97            .get("package.json")
98            .and_then(|bytes| serde_json::from_slice::<Value>(bytes).ok())
99            .is_some_and(|manifest| {
100                manifest["keywords"]
101                    .as_array()
102                    .is_some_and(|keywords| keywords.iter().any(|keyword| keyword == PACK_KEYWORD))
103            })
104    })
105}
106
107/// The search's route of each scope of `packs` ([`search_path`]): the packs of the scope with the keyword.
108fn search_routes(packs: &[ServedPack]) -> Routes {
109    let mut scopes: BTreeMap<&str, Vec<Value>> = BTreeMap::new();
110    for pack in packs.iter().filter(|pack| lists_the_keyword(pack)) {
111        let scope = pack.name.split('/').next().unwrap_or_default();
112        scopes
113            .entry(scope)
114            .or_default()
115            .push(json!({ "package": { "name": pack.name } }));
116    }
117    scopes
118        .into_iter()
119        .map(|(scope, objects)| {
120            let answer = json!({ "objects": objects, "total": objects.len() });
121            (
122                format!("/{}", search_path(scope)),
123                ("application/json", answer.to_string().into_bytes()),
124            )
125        })
126        .collect()
127}
128
129/// The routes of `packs` at `url`: each pack's metadata at its escaped name, each version's tarball under it, and each
130/// scope's search.
131fn routes_of(packs: &[ServedPack], url: &str) -> Routes {
132    let mut routes = search_routes(packs);
133    for pack in packs {
134        let file_name = pack.name.rsplit('/').next().unwrap_or_default();
135        let mut versions = Map::new();
136        for (version, files) in &pack.versions {
137            let path = format!("{}/-/{file_name}-{version}.tgz", pack.name);
138            let bytes = tarball(files);
139            let size: usize = files.values().map(Vec::len).sum();
140            let dist = json!({ "tarball": format!("{url}{path}"), "integrity": integrity_of(&bytes), "unpackedSize": size });
141            versions.insert(version.clone(), json!({ "dist": dist }));
142            routes.insert(format!("/{path}"), ("application/octet-stream", bytes));
143        }
144        let metadata = json!({ "name": pack.name, "versions": Value::Object(versions) });
145        let escaped = pack.name.replacen('/', "%2f", 1);
146        routes.insert(
147            format!("/{escaped}"),
148            (
149                "application/vnd.npm.install-v1+json",
150                metadata.to_string().into_bytes(),
151            ),
152        );
153    }
154    routes
155}
156
157/// Answers one request on `stream` from `routes`, recording its path in `asked`.
158fn answer(stream: TcpStream, routes: &Routes, asked: &Mutex<Vec<String>>) -> io::Result<()> {
159    let mut reader = BufReader::new(stream);
160    let mut line = String::new();
161    reader.read_line(&mut line)?;
162    let path = line.split(' ').nth(1).unwrap_or_default().to_owned();
163    let mut header = String::new();
164    while reader.read_line(&mut header)? > 2 {
165        header.clear();
166    }
167    asked
168        .lock()
169        .unwrap_or_else(PoisonError::into_inner)
170        .push(path.clone());
171    let (status, (media_type, body)) = routes
172        .get(&path)
173        .map_or(("404 Not Found", ("text/plain", Vec::new())), |route| {
174            ("200 OK", route.clone())
175        });
176    let mut stream = reader.into_inner();
177    let head = format!(
178        "HTTP/1.1 {status}\r\nContent-Type: {media_type}\r\nContent-Length: {}\r\nCache-Control: public, max-age=300\r\nConnection: close\r\n\r\n",
179        body.len()
180    );
181    stream.write_all(head.as_bytes())?;
182    stream.write_all(&body)
183}
184
185impl LocalRegistry {
186    /// A registry serving `packs` on a port of its own.
187    ///
188    /// # Errors
189    ///
190    /// When no port can be had.
191    pub fn serve(packs: &[ServedPack]) -> io::Result<Self> {
192        let listener = TcpListener::bind("127.0.0.1:0")?;
193        let url = format!("http://{}/", listener.local_addr()?);
194        let routes = routes_of(packs, &url);
195        let asked = Arc::new(Mutex::new(Vec::new()));
196        let stopped = Arc::new(AtomicBool::new(false));
197        let (recorded, stopping) = (Arc::clone(&asked), Arc::clone(&stopped));
198        thread::spawn(move || {
199            for stream in listener.incoming().flatten() {
200                if stopping.load(Ordering::Relaxed) {
201                    break;
202                }
203                drop(answer(stream, &routes, &recorded));
204            }
205        });
206        Ok(Self {
207            url,
208            asked,
209            stopped,
210        })
211    }
212
213    /// Its URL, ending in `/`, as a configuration's `registries` names one.
214    #[must_use]
215    pub fn url(&self) -> &str {
216        &self.url
217    }
218
219    /// The paths it was asked for, in order.
220    #[must_use]
221    pub fn asked(&self) -> Vec<String> {
222        self.asked
223            .lock()
224            .unwrap_or_else(PoisonError::into_inner)
225            .clone()
226    }
227}
228
229/// Stops serving: the port is closed, so what asks it next can't connect.
230impl Drop for LocalRegistry {
231    fn drop(&mut self) {
232        self.stopped.store(true, Ordering::Relaxed);
233        drop(TcpStream::connect(
234            self.url.trim_start_matches("http://").trim_end_matches('/'),
235        ));
236    }
237}