Skip to main content

quilt/
serve.rs

1//! Live notebooks: `quilt notebook --serve`.
2//!
3//! `quilt notebook FILE` runs a page once and writes it out. This is the same
4//! [`Notebook`] session held open behind a socket, so the cells can be
5//! written, expanded, run and re-run while someone watches the page change.
6//! Nothing new happens to a cell here — [`Notebook::run_cell`] is what the
7//! file path calls too — what is new is *who* asks, and when.
8//!
9//! # The shape
10//!
11//! * **The page is the truth, the DOM is a view.** The server's
12//!   [`HtmlMachine`](crate::machine::HtmlMachine) holds the document; every
13//!   edit a cell makes is journalled ([`Change`]) and pushed to viewers over
14//!   `GET /events`, which patch by id. The other way round — DOM as truth,
15//!   server mirroring — would make the browser cheaper and every Python
16//!   `↙#id↘` a race against a page the server has not seen yet. Ids are the
17//!   page's definitions; definitions live with the machine.
18//! * **The browser is a machine.** A TypeScript cell's program is expanded
19//!   here and *evaluated there*, in the realm of the page itself, so its
20//!   `document` is the page, its event handlers outlive the cell, and its
21//!   `const`s are visible to the next TS cell — the "browser as a JavaScript
22//!   machine" of `docs/design/machines.md`, reached from inside the page
23//!   rather than over CDP. The answer comes back as an [`Answer`] and is
24//!   landed by [`Notebook::land_cell`], which cannot tell where it was
25//!   produced. `--ts server` runs them on the node kernel instead.
26//! * **Python cells can serve.** The session feeds the Python machine a
27//!   prelude with a `route` decorator; `/app/…` requests are dispatched *as a
28//!   feed* — `__quilt_dispatch(…)` on the kernel's stdin, the response read
29//!   back off stdout. No second port, no thread inside the kernel, and every
30//!   request serialized with cell execution, which is what a session wants.
31//!   A handler that needs real concurrency can still open its own listener.
32//! * **One database.** The session keeps a `sqlite3` file in a temp dir,
33//!   parks the SQL machine on it, and hands its path to the Python kernel as
34//!   `QUILT_DB`, so `db()` in a route sees the tables the SQL cells built.
35//! * **The page is the site.** `GET /site` is the page with the cell chrome
36//!   gone: SQL cells fill the database, Python cells serve `/app/…` from it,
37//!   TypeScript cells render into the page's own elements — and what is left
38//!   when the scaffolding is removed is a small website.
39//!
40//! Nothing persists: the machines die with the process and the temp dir goes
41//! with them. `GET /export` is the way out — the same page `quilt notebook`
42//! would have written.
43//!
44//! # What holds it together
45//!
46//! One [`Notebook`] behind one mutex. A cell run, a route dispatch and a page
47//! read are all the same lock, so a slow cell delays the next request — the
48//! honest consequence of machines that are single interpreters, and the same
49//! order a one-shot run has. Viewers are notified from a second, uncontended
50//! lock, so a stream cannot be blocked by a cell.
51//!
52//! # Reaching it
53//!
54//! The listener binds `127.0.0.1` only, and the notebook's own endpoints want
55//! a session token — printed in the URL at startup, kept in a `SameSite`
56//! cookie afterwards — so a page in another tab cannot drive the notebook.
57//! `GET /site` and `/app/…` are open, because they are the website the
58//! session exists to build. Cells run with the user's privileges, exactly as
59//! `↓` and `quilt run` already do.
60
61pub mod http;
62
63use std::fmt::Write as _;
64use std::net::{SocketAddr, TcpListener, TcpStream};
65use std::path::{Path, PathBuf};
66use std::sync::atomic::{AtomicBool, Ordering};
67use std::sync::mpsc::{channel, Sender};
68use std::sync::Mutex;
69
70use miette::IntoDiagnostic;
71use serde_json::{json, Value};
72
73use crate::lang::InnerKind;
74use crate::machine::{Answer, ReplMachine};
75use crate::multi::{Languages, MetaLanguages, Multi};
76use crate::notebook::{cell_element_id, Cell, CellDef, Change, Notebook};
77use crate::prelude::*;
78
79use http::{Event, Reply, Request, Response};
80
81/**************************************************************/
82
83/// The default port. Arbitrary, and above anything a system service wants.
84pub const DEFAULT_PORT: u16 = 8788;
85
86/// The cookie a viewer keeps its session token in.
87const TOKEN_COOKIE: &str = "quilt_token";
88
89/// The line the Python dispatcher prints its response on.
90const RESPONSE_MARK: &str = "__QUILT_RESP__";
91
92/// Where the browser-side runtime is looked for, relative to this crate —
93/// `bin/build-wasm web pkg-web` (what
94/// `examples/web/build.mjs` runs) puts it there. Absent, TypeScript cells
95/// still run; only the ones that *quote* need the builders.
96const WASM_PKG: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../quilt-wasm/pkg-web");
97
98/// Where a TypeScript cell runs.
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
100pub enum Engine {
101    /// In the page's own realm, in the viewer's browser.
102    #[default]
103    Browser,
104    /// On the node kernel in the park, like every other language.
105    Server,
106}
107
108/// How to run the session.
109#[derive(Debug, Clone)]
110pub struct Config {
111    pub port: u16,
112    /// Open the notebook in the default browser once it is listening.
113    pub open: bool,
114    /// Run the cells the page came with at startup, rather than leaving them
115    /// pending.
116    pub run: bool,
117    pub typescript: Engine,
118}
119
120impl Default for Config {
121    fn default() -> Config {
122        Config {
123            port: DEFAULT_PORT,
124            open: false,
125            run: false,
126            typescript: Engine::default(),
127        }
128    }
129}
130
131/// The session, once it is listening.
132#[derive(Debug, Clone)]
133pub struct Ready {
134    pub addr: SocketAddr,
135    pub token: String,
136    /// The URL to open: the address with the session token in it.
137    pub url: String,
138}
139
140/**************************************************************/
141
142/// Serve a notebook session until `POST /shutdown`, printing where it is.
143pub fn serve<LS, MS>(multi: &mut Multi<LS, MS>, src: Option<&str>, cfg: &Config) -> Result<()>
144where
145    LS: Languages + Send,
146    MS: MetaLanguages + Send,
147{
148    serve_with(multi, src, cfg, |ready| {
149        eprintln!("quilt notebook — the page is live at {}", ready.url);
150        eprintln!("  the site it builds: http://{}/site", ready.addr);
151        eprintln!("  ctrl-C, or POST /shutdown, ends the session; nothing persists");
152        if cfg.open {
153            open_in_browser(&ready.url);
154        }
155    })
156}
157
158/// [`serve`], telling `ready` where it landed — which is how a caller that
159/// asked for port 0 finds out, and how a test drives it.
160pub fn serve_with<LS, MS>(
161    multi: &mut Multi<LS, MS>,
162    src: Option<&str>,
163    cfg: &Config,
164    ready: impl FnOnce(&Ready),
165) -> Result<()>
166where
167    LS: Languages + Send,
168    MS: MetaLanguages + Send,
169{
170    let notebook = match src {
171        Some(src) => Notebook::open(multi, src)?,
172        None => Notebook::new(multi),
173    };
174    let dir = tempfile::Builder::new()
175        .prefix("quilt-notebook-")
176        .tempdir()
177        .into_diagnostic()?;
178    let db = dir.path().join("session.db");
179    let mut session = Session {
180        notebook,
181        db,
182        typescript: cfg.typescript,
183        python_ready: false,
184    };
185    if cfg.run {
186        session.run_all()?;
187    }
188    let listener = TcpListener::bind(("127.0.0.1", cfg.port)).into_diagnostic()?;
189    let addr = listener.local_addr().into_diagnostic()?;
190    let token = session_token();
191    let live = Live {
192        session: Mutex::new(session),
193        viewers: Mutex::new(Vec::new()),
194        token: token.clone(),
195        addr,
196        stop: AtomicBool::new(false),
197    };
198    ready(&Ready {
199        addr,
200        token: token.clone(),
201        url: format!("http://{addr}/?token={token}"),
202    });
203
204    std::thread::scope(|scope| {
205        for stream in listener.incoming() {
206            if live.stop.load(Ordering::SeqCst) {
207                break;
208            }
209            let Ok(stream) = stream else { continue };
210            scope.spawn(|| http::serve_connection(stream, &|req| handle(&live, req)));
211        }
212        // Dropping every sender ends the streams, so the scope can join.
213        live.viewers
214            .lock()
215            .unwrap_or_else(|e| e.into_inner())
216            .clear();
217    });
218    // `dir` drops here: the session's database goes with the session.
219    drop(dir);
220    Ok(())
221}
222
223/**************************************************************/
224
225/// The session: one notebook, and what the session added to it.
226struct Session<'m, LS: Languages, MS: MetaLanguages> {
227    notebook: Notebook<'m, LS, MS>,
228    /// The `sqlite3` file the SQL cells and the Python routes share.
229    db: PathBuf,
230    typescript: Engine,
231    /// Whether the Python machine has been given the session prelude.
232    python_ready: bool,
233}
234
235/// Everything a connection thread can reach.
236struct Live<'m, LS: Languages, MS: MetaLanguages> {
237    session: Mutex<Session<'m, LS, MS>>,
238    /// The event streams to push page changes to. A second lock, so a cell
239    /// that takes a minute does not hold up a viewer's stream.
240    viewers: Mutex<Vec<Sender<Event>>>,
241    token: String,
242    addr: SocketAddr,
243    stop: AtomicBool,
244}
245
246impl<LS: Languages, MS: MetaLanguages> Session<'_, LS, MS> {
247    /// Park the session's own machines before *any* cell runs.
248    ///
249    /// Not per-cell, because a cell's output creates cells: a bash cell that
250    /// writes a Python cell would otherwise have the park spawn a plain
251    /// Python machine — no `route`, no `db` — halfway through a run. The
252    /// session's machines have to be in place before the first feed, so this
253    /// is called before every run rather than for the language being run.
254    ///
255    /// A machine that cannot start (no `sqlite3`, no `python3`) is left
256    /// unparked: the cell that wants it then fails with the park's own
257    /// message, which says what is missing, instead of the session refusing
258    /// to run anything.
259    fn ensure_session(&mut self) {
260        for lang in ["sql", "py"] {
261            if let Err(e) = self.ensure(lang) {
262                tracing::debug!("no session machine for {lang}: {e}");
263            }
264        }
265    }
266
267    /// Run every cell the page came with, in page order — `--run`. Cells
268    /// whose machine is a browser are left pending: there is no viewer yet,
269    /// and the page is the one thing a session can wait for.
270    fn run_all(&mut self) -> Result<()> {
271        self.ensure_session();
272        let cells: Vec<(usize, Box<str>)> = self
273            .notebook
274            .cell_defs()
275            .iter()
276            .map(|def| (def.id, def.lang.clone()))
277            .collect();
278        for (id, lang) in cells {
279            if self.delegates(&lang) {
280                continue;
281            }
282            self.notebook.run_cell(id)?;
283        }
284        Ok(())
285    }
286
287    /// Make sure `lang`'s machine is the *session's* machine before anything
288    /// spawns the language's default one. SQL gets a file to write in; Python
289    /// gets that file's path and the session prelude.
290    fn ensure(&mut self, lang: &str) -> Result<()> {
291        match lang {
292            "sql" | "mysql" | "mariadb" if !self.notebook.has_machine("sql") => {
293                let Some(mut spec) = crate::machine::repl_spec("sql") else {
294                    return Ok(());
295                };
296                // `sqlite3 <file>` rather than the default in-memory database,
297                // so a Python route can open the same tables.
298                let mut args: Vec<Box<str>> = spec.args.to_vec();
299                args.push(self.db.display().to_string().into());
300                spec.args = args.into();
301                let machine = ReplMachine::spawn("sql", spec)?;
302                self.notebook.park_machine("sql", Box::new(machine));
303            }
304            "py" | "python" if !self.python_ready => {
305                if !self.notebook.has_machine("py") {
306                    let Some(mut spec) = crate::machine::repl_spec("py") else {
307                        return Ok(());
308                    };
309                    let mut env: Vec<(Box<str>, Box<str>)> = spec.env.to_vec();
310                    env.push(("QUILT_DB".into(), self.db.display().to_string().into()));
311                    spec.env = env.into();
312                    let machine = ReplMachine::spawn("py", spec)?;
313                    self.notebook.park_machine("py", Box::new(machine));
314                }
315                self.notebook
316                    .feed_lang("py", InnerKind::File, PYTHON_PRELUDE)?;
317                self.python_ready = true;
318            }
319            _ => {}
320        }
321        Ok(())
322    }
323
324    /// Whether this cell's machine is the viewer's browser.
325    fn delegates(&self, lang: &str) -> bool {
326        self.typescript == Engine::Browser && matches!(lang, "ts" | "typescript")
327    }
328}
329
330/**************************************************************/
331
332/// Route one request. Errors become a JSON `error`, so the editor can show
333/// what went wrong where it asked.
334fn handle<LS, MS>(live: &Live<'_, LS, MS>, req: &Request) -> Reply
335where
336    LS: Languages,
337    MS: MetaLanguages,
338{
339    if !local_host(req) {
340        return Reply::Done(Response::status(
341            403,
342            "a quilt notebook serves 127.0.0.1 under its own name only",
343        ));
344    }
345    if !authorized(live, req) {
346        return Reply::Done(Response::status(
347            403,
348            "this notebook wants its session token: open the URL quilt printed",
349        ));
350    }
351    match route(live, req) {
352        Ok(reply) => reply,
353        Err(e) => Reply::Done(Response::new(
354            500,
355            "application/json; charset=utf-8",
356            json!({ "error": format!("{e:?}") }).to_string(),
357        )),
358    }
359}
360
361#[allow(clippy::too_many_lines)]
362fn route<LS, MS>(live: &Live<'_, LS, MS>, req: &Request) -> Result<Reply>
363where
364    LS: Languages,
365    MS: MetaLanguages,
366{
367    let segments = req.segments();
368    let done = |response: Response| Ok(Reply::Done(response));
369    match (req.method.as_str(), segments.as_slice()) {
370        /* ── the editor ──────────────────────────────────────────────── */
371        ("GET", []) => {
372            let mut page = Response::html(assets::UI_HTML);
373            if let Some(token) = req.param("token") {
374                page = page.with_header(
375                    "Set-Cookie",
376                    &format!("{TOKEN_COOKIE}={token}; Path=/; SameSite=Strict"),
377                );
378            }
379            done(page)
380        }
381        ("GET", ["ui.css"]) => done(Response::new(
382            200,
383            "text/css; charset=utf-8",
384            assets::UI_CSS,
385        )),
386        ("GET", ["ui.js"]) => done(Response::new(
387            200,
388            "text/javascript; charset=utf-8",
389            assets::UI_JS,
390        )),
391        ("GET", ["runtime.js"]) => done(Response::new(
392            200,
393            "text/javascript; charset=utf-8",
394            runtime_js(),
395        )),
396        ("GET", ["quilt-wasm", file]) => done(wasm_asset(file)),
397
398        /* ── events ──────────────────────────────────────────────────── */
399        ("GET", ["events"]) => {
400            let (tx, rx) = channel();
401            // The first event is the whole state, so a viewer that connects
402            // late is not looking at a page it missed the changes to.
403            let hello = {
404                let mut session = lock(live);
405                Event {
406                    name: "hello".into(),
407                    data: state_json(&mut session, live).to_string(),
408                }
409            };
410            let _ = tx.send(hello);
411            live.viewers
412                .lock()
413                .unwrap_or_else(|e| e.into_inner())
414                .push(tx);
415            Ok(Reply::Events(rx))
416        }
417
418        /* ── the page ────────────────────────────────────────────────── */
419        ("GET", ["page"]) => {
420            let session = lock(live);
421            done(Response::json(
422                json!({ "html": session.notebook.render() }).to_string(),
423            ))
424        }
425        // The document itself, for the viewer's frame: exactly what the
426        // machine holds, with nothing injected — the frame's runtime is
427        // installed from outside, so the page stays the page.
428        // Not under `/page/`, where it would shadow an element whose id is
429        // `view` — the page's ids are the page's, not the protocol's.
430        ("GET", ["view"]) => {
431            let session = lock(live);
432            done(Response::html(session.notebook.render()))
433        }
434        ("GET", ["page", id]) => {
435            let session = lock(live);
436            match session.notebook.page().find(id) {
437                Some(el) => done(Response::json(
438                    json!({
439                        "id": id,
440                        "html": el.coparse(),
441                        "text": session.notebook.page().text(id),
442                    })
443                    .to_string(),
444                )),
445                None => done(Response::status(404, &format!("no element with id {id:?}"))),
446            }
447        }
448        // A viewer's edit coming home: the page the cells read is this one.
449        ("PUT", ["page", id]) => {
450            let html = string_field(&body(req)?, "html")?;
451            let mut session = lock(live);
452            let element = session.notebook.define_html(&html)?;
453            let changes = drain(&mut session, live);
454            done(Response::json(
455                json!({ "id": id, "defined": element, "changes": changes }).to_string(),
456            ))
457        }
458        ("GET", ["site"]) => {
459            let session = lock(live);
460            done(Response::html(session.notebook.site_html()))
461        }
462        ("GET", ["export"]) => {
463            let session = lock(live);
464            let html = format!(
465                "<!-- DO NOT EDIT. GENERATED BY `quilt notebook --serve`. -->\n{}\n",
466                session.notebook.render()
467            );
468            done(Response::html(html).with_header(
469                "Content-Disposition",
470                "attachment; filename=\"notebook.html\"",
471            ))
472        }
473
474        /* ── cells ───────────────────────────────────────────────────── */
475        ("GET", ["cells"]) => {
476            let session = lock(live);
477            done(Response::json(cells_json(&session).to_string()))
478        }
479        ("POST", ["cells"]) => {
480            let body = body(req)?;
481            let lang = string_field(&body, "lang")?;
482            let src = body
483                .get("src")
484                .and_then(Value::as_str)
485                .unwrap_or_default()
486                .to_string();
487            let after = body.get("after").and_then(Value::as_str);
488            let mut session = lock(live);
489            let id = match body.get("id").and_then(Value::as_u64) {
490                Some(id) => {
491                    let id = usize::try_from(id).into_diagnostic()?;
492                    session.notebook.set_cell(id, Some(&lang), &src)?;
493                    id
494                }
495                None => session.notebook.add_cell(&lang, &src, after)?,
496            };
497            let answer = cell_reply(&mut session, live, id);
498            done(Response::json(answer.to_string()))
499        }
500        ("PUT", ["cells", id]) => {
501            let id = cell_number(id)?;
502            let body = body(req)?;
503            let lang = body.get("lang").and_then(Value::as_str);
504            let src = string_field(&body, "src")?;
505            let mut session = lock(live);
506            session.notebook.set_cell(id, lang, &src)?;
507            let answer = cell_reply(&mut session, live, id);
508            done(Response::json(answer.to_string()))
509        }
510        ("DELETE", ["cells", id]) => {
511            let id = cell_number(id)?;
512            let mut session = lock(live);
513            session.notebook.remove_cell(id)?;
514            let changes = drain(&mut session, live);
515            done(Response::json(
516                json!({ "id": id, "removed": true, "changes": changes }).to_string(),
517            ))
518        }
519        ("GET", ["cells", id, "expand"]) => {
520            let id = cell_number(id)?;
521            let mut session = lock(live);
522            let program = session.notebook.expand_cell(id)?;
523            done(Response::json(program_json(&program).to_string()))
524        }
525        ("POST", ["cells", id, "run"]) => {
526            let id = cell_number(id)?;
527            let mut session = lock(live);
528            let Some(def) = session.notebook.cell_def(id).cloned() else {
529                return done(Response::status(404, &format!("no cell {id}")));
530            };
531            if session.delegates(&def.lang) {
532                // The machine is the viewer's browser: hand over the program
533                // and wait for `…/result`.
534                let program = session.notebook.expand_cell(id)?;
535                let mut answer = program_json(&program);
536                answer["id"] = json!(id);
537                answer["ran"] = json!("browser");
538                return done(Response::json(answer.to_string()));
539            }
540            session.ensure_session();
541            session.notebook.run_cell(id)?;
542            let mut answer = cell_reply(&mut session, live, id);
543            answer["ran"] = json!("server");
544            done(Response::json(answer.to_string()))
545        }
546        // A machine that is not in this process, answering.
547        ("POST", ["cells", id, "result"]) => {
548            let id = cell_number(id)?;
549            let body = body(req)?;
550            let mut session = lock(live);
551            // A cell the browser ran can still create cells, and those run
552            // here — on the session's machines.
553            session.ensure_session();
554            session.notebook.land_cell(id, answer_from(&body))?;
555            let mut answer = cell_reply(&mut session, live, id);
556            answer["ran"] = json!("browser");
557            done(Response::json(answer.to_string()))
558        }
559
560        /* ── the expander, for anyone ────────────────────────────────── */
561        ("POST", ["expand"]) => {
562            let body = body(req)?;
563            let lang = string_field(&body, "lang")?;
564            let src = string_field(&body, "src")?;
565            let mut session = lock(live);
566            let program = session.notebook.expand_source(&lang, &src)?;
567            done(Response::json(program_json(&program).to_string()))
568        }
569
570        /* ── the site the cells are building ─────────────────────────── */
571        (_, ["app", rest @ ..]) => {
572            let path = format!("/{}", rest.join("/"));
573            let mut session = lock(live);
574            let (response, stdout) = dispatch_app(&mut session, &req.method, &path, req)?;
575            if !stdout.trim().is_empty() {
576                notify(live, "app", &json!({ "path": path, "stdout": stdout }));
577            }
578            done(response)
579        }
580
581        /* ── the end ─────────────────────────────────────────────────── */
582        ("POST", ["shutdown"]) => {
583            live.stop.store(true, Ordering::SeqCst);
584            // Wake the accept loop, which is blocked on a socket that will
585            // not get another connection on its own.
586            let _ = TcpStream::connect(live.addr);
587            done(Response::text("the session is over\n"))
588        }
589        _ => done(Response::status(
590            404,
591            &format!("no route {} {}", req.method, req.path),
592        )),
593    }
594}
595
596/**************************************************************/
597
598fn lock<'a, 'm, LS: Languages, MS: MetaLanguages>(
599    live: &'a Live<'m, LS, MS>,
600) -> std::sync::MutexGuard<'a, Session<'m, LS, MS>> {
601    // A panicking handler leaves the notebook as it was mid-edit; the next
602    // request is still better served than refused.
603    live.session.lock().unwrap_or_else(|e| e.into_inner())
604}
605
606/// Take what the page did, tell every viewer, and answer it to the caller
607/// too — the caller is a viewer that asked a question.
608fn drain<LS: Languages, MS: MetaLanguages>(
609    session: &mut Session<'_, LS, MS>,
610    live: &Live<'_, LS, MS>,
611) -> Value {
612    let changes: Vec<Value> = session
613        .notebook
614        .take_changes()
615        .iter()
616        .map(change_json)
617        .collect();
618    if !changes.is_empty() {
619        notify(live, "page", &json!({ "changes": changes }));
620    }
621    Value::Array(changes)
622}
623
624/// Send an event to every viewer, dropping the ones that have gone.
625fn notify<LS: Languages, MS: MetaLanguages>(live: &Live<'_, LS, MS>, name: &str, data: &Value) {
626    let mut viewers = live.viewers.lock().unwrap_or_else(|e| e.into_inner());
627    let data = data.to_string();
628    viewers.retain(|tx| {
629        tx.send(Event {
630            name: name.to_string(),
631            data: data.clone(),
632        })
633        .is_ok()
634    });
635}
636
637/// One cell's state, its page changes, and the cell list — what every editing
638/// request answers, because every one of them can move all three.
639fn cell_reply<LS: Languages, MS: MetaLanguages>(
640    session: &mut Session<'_, LS, MS>,
641    live: &Live<'_, LS, MS>,
642    id: usize,
643) -> Value {
644    let changes = drain(session, live);
645    let cells = cells_json(session);
646    notify(live, "cells", &cells);
647    json!({
648        "id": id,
649        "cell": session
650            .notebook
651            .cell_def(id)
652            .map(|def| cell_json(def, session.notebook.cell(id))),
653        "figure": session.notebook.cell_figure(id),
654        "changes": changes,
655        "cells": cells["cells"],
656    })
657}
658
659fn state_json<LS: Languages, MS: MetaLanguages>(
660    session: &mut Session<'_, LS, MS>,
661    live: &Live<'_, LS, MS>,
662) -> Value {
663    let _ = live;
664    json!({
665        "html": session.notebook.render(),
666        "cells": cells_json(session)["cells"],
667        "typescript": match session.typescript {
668            Engine::Browser => "browser",
669            Engine::Server => "server",
670        },
671        "runtime": Path::new(WASM_PKG).join("quilt_wasm.js").exists(),
672    })
673}
674
675fn cells_json<LS: Languages, MS: MetaLanguages>(session: &Session<'_, LS, MS>) -> Value {
676    let cells: Vec<Value> = session
677        .notebook
678        .cell_defs()
679        .iter()
680        .map(|def| cell_json(def, session.notebook.cell(def.id)))
681        .collect();
682    json!({ "cells": cells })
683}
684
685fn cell_json(def: &CellDef, cell: Option<&Cell>) -> Value {
686    json!({
687        "id": def.id,
688        "lang": def.lang,
689        "src": def.src,
690        "generation": def.generation,
691        "element": cell_element_id(def.id),
692        "ran": cell.is_some_and(|c| c.ran),
693        "failed": cell.is_some_and(Cell::failed),
694        "value": cell.and_then(|c| c.value.as_deref()),
695        "stdout": cell.map_or("", |c| &c.stdout),
696        "stderr": cell.map_or("", |c| &c.stderr),
697        "error": cell.and_then(|c| c.error.as_deref()),
698        "edits": cell.map(|c| c.edits.clone()).unwrap_or_default(),
699        "spawned": cell.map(|c| c.spawned.clone()).unwrap_or_default(),
700    })
701}
702
703fn program_json(program: &crate::notebook::Program) -> Value {
704    json!({
705        "kind": format!("{:?}", program.kind),
706        "resolved": program.resolved,
707        "program": program.program,
708    })
709}
710
711fn change_json(change: &Change) -> Value {
712    match change {
713        Change::Define { id, html } => json!({ "kind": "define", "id": id, "html": html }),
714        Change::Insert { after, html } => {
715            json!({ "kind": "insert", "after": after, "html": html })
716        }
717        Change::Append { html } => json!({ "kind": "append", "html": html }),
718        Change::Remove { id } => json!({ "kind": "remove", "id": id }),
719    }
720}
721
722/// An [`Answer`] a browser produced, as this server's JSON spells it. An
723/// `error` is a cell that threw — the same outcome a rejected feed has.
724fn answer_from(body: &Value) -> Result<Answer> {
725    if let Some(error) = body.get("error").and_then(Value::as_str) {
726        if !error.trim().is_empty() {
727            return Err(miette!("{error}"));
728        }
729    }
730    Ok(Answer {
731        value: body
732            .get("value")
733            .and_then(Value::as_str)
734            .map(|v| v.to_string().into_boxed_str()),
735        name: None,
736        stdout: body
737            .get("stdout")
738            .and_then(Value::as_str)
739            .unwrap_or_default()
740            .into(),
741        stderr: body
742            .get("stderr")
743            .and_then(Value::as_str)
744            .unwrap_or_default()
745            .into(),
746    })
747}
748
749fn body(req: &Request) -> Result<Value> {
750    if req.body.is_empty() {
751        return Ok(json!({}));
752    }
753    serde_json::from_slice(&req.body)
754        .into_diagnostic()
755        .map_err(|e| e.context("the request body is not JSON"))
756}
757
758fn string_field(body: &Value, name: &str) -> Result<String> {
759    body.get(name)
760        .and_then(Value::as_str)
761        .map(ToString::to_string)
762        .ok_or_else(|| miette!("this request wants a string {name:?}"))
763}
764
765fn cell_number(segment: &str) -> Result<usize> {
766    segment
767        .parse()
768        .map_err(|_| miette!("{segment:?} is not a cell number"))
769}
770
771/**************************************************************/
772
773/// Dispatch an `/app/…` request to the Python machine as a feed: the
774/// kernel's own `__quilt_dispatch` runs the registered handler and prints
775/// one framed line, which is the response.
776fn dispatch_app<LS: Languages, MS: MetaLanguages>(
777    session: &mut Session<'_, LS, MS>,
778    method: &str,
779    path: &str,
780    req: &Request,
781) -> Result<(Response, String)> {
782    session.ensure_session();
783    // Fed as a statement, not a query: the dispatcher prints its response,
784    // so the machine's answer is on stdout rather than in a value.
785    let call = format!(
786        "__quilt_dispatch({}, {}, {}, {})",
787        py_str(method),
788        py_str(path),
789        py_str(&req.query),
790        py_str(&req.text()),
791    );
792    let answer = match session.notebook.feed_lang("py", InnerKind::Stmt, &call) {
793        Ok(answer) => answer,
794        Err(e) => {
795            return Ok((
796                Response::status(
797                    500,
798                    &format!("the python machine refused the request: {e:?}"),
799                ),
800                String::new(),
801            ))
802        }
803    };
804    let Some(line) = answer
805        .stdout
806        .lines()
807        .rev()
808        .find_map(|line| line.strip_prefix(RESPONSE_MARK))
809    else {
810        return Ok((
811            Response::status(
812                500,
813                &format!(
814                    "the python machine answered no response.\nstdout:\n{}\nstderr:\n{}",
815                    answer.stdout, answer.stderr
816                ),
817            ),
818            String::new(),
819        ));
820    };
821    let value: Value = serde_json::from_str(line).into_diagnostic()?;
822    let status =
823        u16::try_from(value.get("status").and_then(Value::as_u64).unwrap_or(200)).unwrap_or(500);
824    let content_type = value
825        .get("type")
826        .and_then(Value::as_str)
827        .unwrap_or("text/plain; charset=utf-8");
828    let body = value
829        .get("body")
830        .and_then(Value::as_str)
831        .unwrap_or_default();
832    let stdout = value
833        .get("stdout")
834        .and_then(Value::as_str)
835        .unwrap_or_default()
836        .to_string();
837    Ok((
838        Response::new(status, content_type, body.to_string()),
839        stdout,
840    ))
841}
842
843/// A Python string literal denoting `s` — the same escaping the `LiftTo`
844/// impls use, which is the only spelling a machine's wire ever needs.
845fn py_str(s: &str) -> String {
846    format!("\"{}\"", crate::lift::py_dquote_escape(s))
847}
848
849/**************************************************************/
850
851/// Whether the request is for this server under a name that resolves to this
852/// machine. A browser sends `Host`; a page on the internet that guesses the
853/// port cannot make it say `localhost` unless it already resolves here.
854fn local_host(req: &Request) -> bool {
855    let Some(host) = req.header("host") else {
856        return true; // HTTP/1.0, or a hand-written client: nothing to check.
857    };
858    let host = host.rsplit_once(':').map_or(host, |(h, _)| h);
859    matches!(
860        host.trim_matches(['[', ']']),
861        "localhost" | "127.0.0.1" | "::1"
862    )
863}
864
865/// Whether this request may drive the notebook. The site the notebook builds
866/// (`/site`, `/app/…`) is open — it is a website, and asking a website for a
867/// token is asking it not to be one.
868fn authorized<LS: Languages, MS: MetaLanguages>(live: &Live<'_, LS, MS>, req: &Request) -> bool {
869    if req.path == "/site" || req.path == "/app" || req.path.starts_with("/app/") {
870        return true;
871    }
872    let matches = |given: Option<String>| given.is_some_and(|g| g == live.token);
873    matches(req.param("token"))
874        || matches(req.cookie(TOKEN_COOKIE))
875        || matches(req.header("x-quilt-token").map(ToString::to_string))
876}
877
878/// A session token: 128 bits from the system, or — where that cannot be read
879/// — from the clock and this process's own addresses, which is weaker and
880/// still unguessable by a page that cannot see this machine.
881fn session_token() -> String {
882    let mut bytes = [0u8; 16];
883    if std::fs::File::open("/dev/urandom")
884        .and_then(|mut f| std::io::Read::read_exact(&mut f, &mut bytes))
885        .is_err()
886    {
887        use std::hash::{BuildHasher as _, Hasher as _};
888        let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
889        hasher.write_u128(
890            std::time::SystemTime::now()
891                .duration_since(std::time::UNIX_EPOCH)
892                .map_or(0, |d| d.as_nanos()),
893        );
894        hasher.write_usize(std::process::id() as usize);
895        hasher.write_usize(std::ptr::addr_of!(bytes) as usize);
896        let seed = hasher.finish().to_le_bytes();
897        for (i, byte) in bytes.iter_mut().enumerate() {
898            *byte = seed[i % seed.len()] ^ u8::try_from(i).unwrap_or(0).wrapping_mul(31);
899        }
900    }
901    bytes.iter().fold(String::new(), |mut out, b| {
902        let _ = write!(out, "{b:02x}");
903        out
904    })
905}
906
907fn open_in_browser(url: &str) {
908    let opener = if cfg!(target_os = "macos") {
909        "open"
910    } else if cfg!(target_os = "windows") {
911        "explorer"
912    } else {
913        "xdg-open"
914    };
915    let _ = std::process::Command::new(opener).arg(url).spawn();
916}
917
918/// One file of the browser runtime, when it has been built.
919fn wasm_asset(file: &str) -> Response {
920    if file.contains("..") || file.contains('/') {
921        return Response::status(403, "no");
922    }
923    let path = Path::new(WASM_PKG).join(file);
924    let content_type = match path.extension().and_then(|e| e.to_str()) {
925        Some("js") => "text/javascript; charset=utf-8",
926        Some("wasm") => "application/wasm",
927        Some("json") => "application/json; charset=utf-8",
928        Some("ts") => "text/plain; charset=utf-8",
929        _ => return Response::status(404, "not a runtime file"),
930    };
931    match std::fs::read(&path) {
932        Ok(bytes) => Response::new(200, content_type, bytes),
933        Err(_) => Response::status(
934            404,
935            "the browser runtime is not built: `bin/build-wasm web pkg-web`",
936        ),
937    }
938}
939
940/// The module a viewer installs in the page's realm: the quilt runtime a
941/// quoting TypeScript cell needs, and `↓`.
942fn runtime_js() -> String {
943    let built = Path::new(WASM_PKG).join("quilt_wasm.js").exists();
944    format!(
945        "export const RUNTIME_BUILT = {built};\n{}",
946        assets::RUNTIME_JS
947    )
948}
949
950/**************************************************************/
951
952/// The session prelude the Python machine is given: what a *notebook*
953/// Python kernel knows that a plain one does not — how to register a route,
954/// how to reach the session database, and how to answer one request.
955///
956/// It is fed like any other fragment, so it is ordinary Python and the cells
957/// can read it (`route`, `db`, `_quilt_routes` are just names in the
958/// namespace). The framing is one printed line, which is the same trick the
959/// kernel's own sentinel uses: a machine's wire is its stdout.
960const PYTHON_PRELUDE: &str = r#"
961import contextlib as _q_ctx, inspect as _q_inspect, io as _q_io, json as _q_json, os as _q_os, traceback as _q_tb
962_quilt_routes = {}
963def route(path, methods=("GET",)):
964    """Serve `path` from this notebook: the server proxies /app<path> here."""
965    if isinstance(methods, str):
966        methods = (methods,)
967    def register(fn):
968        for method in methods:
969            _quilt_routes[(method.upper(), path)] = fn
970        return fn
971    return register
972def db():
973    """A connection to the session database — the one the SQL cells write."""
974    import sqlite3
975    path = _q_os.environ.get("QUILT_DB")
976    if not path:
977        raise RuntimeError("no session database: QUILT_DB is unset")
978    con = sqlite3.connect(path)
979    con.row_factory = sqlite3.Row
980    return con
981def __quilt_dispatch(method, path, query, body):
982    handler = _quilt_routes.get((method, path))
983    out = _q_io.StringIO()
984    status, kind, text = 200, "text/plain; charset=utf-8", ""
985    if handler is None:
986        known = sorted("%s %s" % (m, p) for m, p in _quilt_routes)
987        status, text = 404, "no route for %s %s\nthis notebook serves: %s" % (
988            method, path, ", ".join(known) or "nothing yet")
989    else:
990        try:
991            with _q_ctx.redirect_stdout(out):
992                if len(_q_inspect.signature(handler).parameters):
993                    value = handler({"method": method, "path": path, "query": query, "body": body})
994                else:
995                    value = handler()
996            if isinstance(value, tuple) and len(value) == 2 and isinstance(value[0], int):
997                status, value = value
998            if value is None:
999                status, text = (204 if status == 200 else status), ""
1000            elif isinstance(value, (dict, list)):
1001                kind, text = "application/json; charset=utf-8", _q_json.dumps(value)
1002            else:
1003                text = value if isinstance(value, str) else str(value)
1004                if text.lstrip().startswith("<"):
1005                    kind = "text/html; charset=utf-8"
1006        except Exception:
1007            status, kind, text = 500, "text/plain; charset=utf-8", _q_tb.format_exc()
1008    print("__QUILT_RESP__" + _q_json.dumps(
1009        {"status": status, "type": kind, "body": text, "stdout": out.getvalue()}))
1010"#;
1011
1012/**************************************************************/
1013
1014/// The editor, as files. Held here rather than written to disk at startup:
1015/// a session server that unpacked assets would be a session server with a
1016/// cache to invalidate.
1017mod assets {
1018    pub const UI_HTML: &str = include_str!("serve/ui.html");
1019    pub const UI_CSS: &str = include_str!("serve/ui.css");
1020    pub const UI_JS: &str = include_str!("serve/ui.js");
1021    pub const RUNTIME_JS: &str = include_str!("serve/runtime.js");
1022}
1023
1024/**************************************************************/
1025
1026#[cfg(test)]
1027mod tests {
1028    use super::*;
1029
1030    #[test]
1031    fn a_token_is_unguessable_and_stable_for_the_session() {
1032        let a = session_token();
1033        assert_eq!(a.len(), 32, "128 bits, hex");
1034        assert_ne!(a, session_token());
1035    }
1036
1037    #[test]
1038    fn only_this_machines_names_are_served() {
1039        let host = |value: &str| {
1040            let mut req = Request::default();
1041            req.headers.insert("host".into(), value.into());
1042            local_host(&req)
1043        };
1044        assert!(host("localhost:8788"));
1045        assert!(host("127.0.0.1:8788"));
1046        assert!(host("[::1]:8788"));
1047        assert!(!host("notebook.example.com"));
1048    }
1049
1050    #[test]
1051    fn python_literals_survive_the_wire() {
1052        assert_eq!(py_str("a\"b\nc"), "\"a\\\"b\\nc\"");
1053    }
1054}