oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1//! Apple process boundary: only the safe WASM interpreter sees remote updates.
2use std::panic::{catch_unwind, AssertUnwindSafe};
3use std::sync::OnceLock;
4use wasmi::{Config, Engine, Instance, Linker, Memory, Module, Store, StoreLimits, StoreLimitsBuilder};
5const MAX_BYTES: usize = 8 * 1024 * 1024 + 1;
6const MAX_MEMORY: usize = 64 * 1024 * 1024;
7/// Fuel bounds every call, so no input (a crafted update, an engine bug) can
8/// keep the interpreter running for ever: a call that runs out traps, and the
9/// instance is discarded like any other failure. One fixed budget of 40M
10/// refused real documents, though. A call's honest work grows with the
11/// document (a projection costs about 1M fuel per page), so 40M stopped
12/// typing at about 20 edited pages and opening at about 40.
13///
14/// So the budget grows with what the call can legitimately touch: a floor,
15/// plus an allowance per byte of the instance's linear memory (which holds
16/// the document, its history and the undo stack; it never shrinks) and per
17/// byte of the request (an import is decoded byte by byte). Measured on
18/// edited documents of 1-400 pages, the costliest calls needed at most
19/// 38 fuel per memory byte (`display_edit`) and 491 per request byte
20/// (importing a heavily fragmented snapshot), so both allowances carry 2-3x
21/// headroom on top of the other term. Memory is capped at `MAX_MEMORY` and
22/// requests at `MAX_BYTES`, so the budget is still bounded: at most
23/// `MAX_FUEL`, about 17G, or some 20 s of interpretation on an M1 Max, and
24/// only for an instance already holding 64 MiB. A one-page document's calls
25/// get about 200M (a quarter of a second).
26const BASE_FUEL: u64 = 40_000_000;
27const FUEL_PER_MEMORY_BYTE: u64 = 128;
28const FUEL_PER_REQUEST_BYTE: u64 = 1_024;
29pub const MAX_FUEL: u64 = BASE_FUEL + FUEL_PER_MEMORY_BYTE * MAX_MEMORY as u64 + FUEL_PER_REQUEST_BYTE * MAX_BYTES as u64;
30/// The fuel one call may spend, given the instance's memory once the request
31/// is written into it and the request's length.
32pub fn fuel_budget(memory: usize, request: usize) -> u64 {
33 let memory = memory.min(MAX_MEMORY) as u64;
34 let request = request.min(MAX_BYTES) as u64;
35 BASE_FUEL + FUEL_PER_MEMORY_BYTE * memory + FUEL_PER_REQUEST_BYTE * request
36}
37const WASM: &[u8] = include_bytes!("../../crdt/target/wasm32-unknown-unknown/release/docs_native_crdt.wasm");
38pub struct Host {
39 store: Store<StoreLimits>,
40 instance: Instance,
41 memory: Memory,
42 output: Vec<u8>,
43 failed: bool,
44 ceiling: u64,
45}
46/// The module is immutable, so it is validated and compiled once per process
47/// (about 7 ms) and every host only instantiates it. Each host still has its
48/// own store, linear memory and fuel: the instance remains the isolation unit.
49static COMPILED: OnceLock<Option<(Engine, Module)>> = OnceLock::new();
50fn compiled() -> Result<&'static (Engine, Module), &'static str> {
51 COMPILED.get_or_init(|| {
52 let mut config = Config::default();
53 config.consume_fuel(true);
54 let engine = Engine::new(&config);
55 Module::new(&engine, WASM).ok().map(|module| (engine, module))
56 }).as_ref().ok_or("invalid_module")
57}
58impl Host {
59 pub fn new() -> Result<Self, &'static str> {
60 let (engine, module) = compiled()?;
61 // No imports are supplied: CRDT must remain independent of host JS,
62 // filesystem, entropy and clock functions. Identity is an input.
63 let linker = Linker::new(engine);
64 let limits = StoreLimitsBuilder::new().memory_size(MAX_MEMORY).instances(1).memories(1).tables(1).build();
65 let mut store = Store::new(engine, limits);
66 store.limiter(|limits| limits);
67 store.set_fuel(BASE_FUEL).map_err(|_| "fuel")?;
68 let instance = linker.instantiate(&mut store, module).map_err(|_| "invalid_module")?.start(&mut store).map_err(|_| "module_trap")?;
69 let memory = instance.get_memory(&store, "memory").ok_or("invalid_module")?;
70 Ok(Self {store, instance, memory, output: Vec::new(), failed: false, ceiling: MAX_FUEL})
71 }
72 /// The instance's linear memory, in bytes (it never shrinks).
73 #[doc(hidden)]
74 pub fn memory_bytes(&self) -> usize { self.memory.data(&self.store).len() }
75 /// Tests only: a lower ceiling, to show that running out of fuel is a
76 /// clean failure that discards the instance.
77 #[doc(hidden)]
78 pub fn limit_fuel_for_tests(&mut self, ceiling: u64) { self.ceiling = ceiling; }
79 pub fn call(&mut self, request: &[u8]) -> Result<&[u8], &'static str> {
80 if self.failed || request.len() > MAX_BYTES { return Err("replica_unavailable"); }
81 // Any failed mutation can have partially modified the WASM state. Once
82 // failed, discard the replica; never let callers continue using it.
83 self.failed = true;
84 self.store.set_fuel(BASE_FUEL).map_err(|_| "fuel")?;
85 let alloc = self.instance.get_typed_func::<u32, u32>(&self.store, "docs_editor_alloc").map_err(|_| "invalid_abi")?;
86 let ptr = alloc.call(&mut self.store, request.len() as u32).map_err(|_| "module_trap")?;
87 if ptr == 0 { return Err("allocation"); }
88 self.memory.write(&mut self.store, ptr as usize, request).map_err(|_| "invalid_memory")?;
89 // Measured after the write, so an import's own bytes count as memory too.
90 let budget = fuel_budget(self.memory.data(&self.store).len(), request.len()).min(self.ceiling);
91 self.store.set_fuel(budget).map_err(|_| "fuel")?;
92 let call = self.instance.get_typed_func::<(u32,u32), i32>(&self.store, "docs_editor_call").map_err(|_| "invalid_abi")?;
93 let status = call.call(&mut self.store, (ptr, request.len() as u32)).map_err(|_| "module_trap")?;
94 // Freeing and reading the output get their own small budget, so a
95 // call that finished just inside its budget is not failed by them.
96 self.store.set_fuel(BASE_FUEL).map_err(|_| "fuel")?;
97 let free = self.instance.get_typed_func::<(u32,u32), ()>(&self.store, "docs_editor_free").map_err(|_| "invalid_abi")?;
98 free.call(&mut self.store, (ptr, request.len() as u32)).map_err(|_| "module_trap")?;
99 if status != 0 {
100 // Report only a fixed whitelist of engine error codes, never content.
101 let len = self.instance.get_typed_func::<(),u32>(&self.store, "docs_editor_output_len").map_err(|_| "invalid_abi")?.call(&mut self.store, ()).map_err(|_| "module_trap")? as usize;
102 let start = self.instance.get_typed_func::<(),u32>(&self.store, "docs_editor_output_ptr").map_err(|_| "invalid_abi")?.call(&mut self.store, ()).map_err(|_| "module_trap")? as usize;
103 let mut code = [0u8; 64];
104 if len <= code.len() && self.memory.read(&self.store,start,&mut code[..len]).is_ok() {
105 return Err(match &code[..len] { b"unknown_command" => "unknown_command", b"invalid_range" => "invalid_range", b"invalid_anchor" => "invalid_anchor", b"missing_node" => "missing_node", _ => "rejected_command" });
106 }
107 return Err("rejected_command");
108 }
109 let length = self.instance.get_typed_func::<(),u32>(&self.store, "docs_editor_output_len").map_err(|_| "invalid_abi")?.call(&mut self.store, ()).map_err(|_| "module_trap")? as usize;
110 let start = self.instance.get_typed_func::<(),u32>(&self.store, "docs_editor_output_ptr").map_err(|_| "invalid_abi")?.call(&mut self.store, ()).map_err(|_| "module_trap")? as usize;
111 if length > MAX_BYTES { return Err("oversized_output"); }
112 self.output.resize(length, 0);
113 self.memory.read(&self.store, start, &mut self.output).map_err(|_| "invalid_memory")?;
114 self.failed = false;
115 Ok(&self.output)
116 }
117}
118#[no_mangle]
119pub extern "C" fn docs_host_new() -> *mut Host {
120 catch_unwind(|| Host::new().map(|h| Box::into_raw(Box::new(h))).unwrap_or(std::ptr::null_mut())).unwrap_or(std::ptr::null_mut())
121}
122/// # Safety
123/// `host` must be returned by docs_host_new, uniquely owned, and freed once.
124#[no_mangle]
125pub unsafe extern "C" fn docs_host_free(host: *mut Host) {
126 if !host.is_null() { let _ = catch_unwind(AssertUnwindSafe(|| drop(Box::from_raw(host)))); }
127}
128/// # Safety
129/// Host/input/output must be valid for their stated lengths. The caller serializes calls.
130#[no_mangle]
131pub unsafe extern "C" fn docs_host_call(host: *mut Host, input: *const u8, length: usize, output: *mut u8, capacity: usize) -> i64 {
132 if host.is_null() || input.is_null() || output.is_null() || length > MAX_BYTES || capacity > MAX_BYTES { return -1; }
133 catch_unwind(AssertUnwindSafe(|| {
134 let host = &mut *host;
135 let bytes = std::slice::from_raw_parts(input, length);
136 match host.call(bytes) {
137 Ok(result) if result.len() <= capacity => {
138 std::ptr::copy_nonoverlapping(result.as_ptr(), output, result.len()); result.len() as i64
139 },
140 _ => { host.failed = true; -1 },
141 }
142 })).unwrap_or_else(|_| { (*host).failed = true; -1 })
143}
144