1pub 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
81pub const DEFAULT_PORT: u16 = 8788;
85
86const TOKEN_COOKIE: &str = "quilt_token";
88
89const RESPONSE_MARK: &str = "__QUILT_RESP__";
91
92const WASM_PKG: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../quilt-wasm/pkg-web");
97
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
100pub enum Engine {
101 #[default]
103 Browser,
104 Server,
106}
107
108#[derive(Debug, Clone)]
110pub struct Config {
111 pub port: u16,
112 pub open: bool,
114 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#[derive(Debug, Clone)]
133pub struct Ready {
134 pub addr: SocketAddr,
135 pub token: String,
136 pub url: String,
138}
139
140pub 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
158pub 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 live.viewers
214 .lock()
215 .unwrap_or_else(|e| e.into_inner())
216 .clear();
217 });
218 drop(dir);
220 Ok(())
221}
222
223struct Session<'m, LS: Languages, MS: MetaLanguages> {
227 notebook: Notebook<'m, LS, MS>,
228 db: PathBuf,
230 typescript: Engine,
231 python_ready: bool,
233}
234
235struct Live<'m, LS: Languages, MS: MetaLanguages> {
237 session: Mutex<Session<'m, LS, MS>>,
238 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 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 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 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 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 fn delegates(&self, lang: &str) -> bool {
326 self.typescript == Engine::Browser && matches!(lang, "ts" | "typescript")
327 }
328}
329
330fn 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 ("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 ("GET", ["events"]) => {
400 let (tx, rx) = channel();
401 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 ("GET", ["page"]) => {
420 let session = lock(live);
421 done(Response::json(
422 json!({ "html": session.notebook.render() }).to_string(),
423 ))
424 }
425 ("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 ("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 ("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 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 ("POST", ["cells", id, "result"]) => {
548 let id = cell_number(id)?;
549 let body = body(req)?;
550 let mut session = lock(live);
551 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 ("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 (_, ["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 ("POST", ["shutdown"]) => {
583 live.stop.store(true, Ordering::SeqCst);
584 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
596fn lock<'a, 'm, LS: Languages, MS: MetaLanguages>(
599 live: &'a Live<'m, LS, MS>,
600) -> std::sync::MutexGuard<'a, Session<'m, LS, MS>> {
601 live.session.lock().unwrap_or_else(|e| e.into_inner())
604}
605
606fn 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
624fn 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
637fn 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
722fn 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
771fn 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 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
843fn py_str(s: &str) -> String {
846 format!("\"{}\"", crate::lift::py_dquote_escape(s))
847}
848
849fn local_host(req: &Request) -> bool {
855 let Some(host) = req.header("host") else {
856 return true; };
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
865fn 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
878fn 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
918fn 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
940fn 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
950const 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
1012mod 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#[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}