oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

1// Package core hosts the Rust document core as a WebAssembly module.
2//
3// The module is plain wasm32 with a C ABI and no wasm-bindgen, because
4// wazero provides no JS glue. Everything crosses the boundary as integers
5// and offsets into the module's linear memory.
6//
7// # Two failure modes the host must contain, not merely survive
8//
9// yrs decodes wire bytes with std::str::from_utf8_unchecked in places
10// (core/src/abi.rs's module doc comment), so a sufficiently corrupted
11// update can reach real undefined behaviour and trap the module. A wasm
12// trap does not unwind — the module's linear memory is left exactly as it
13// was at the moment of the trap, which for a thread-local RefCell borrow
14// guard means "permanently borrowed". The instance is not recoverable;
15// every Handle here is backed by exactly one module instance per document
16// (spec §5.2), and a trap discards that instance rather than reusing it.
17//
18// Separately, a malformed update need not trap at all: Task 5's fuzzing
19// found a 36-byte corrupted update that ran docs_core_apply for 163 real
20// CPU seconds under wasmi's interpreter before returning an ordinary,
21// correct answer — not a hang, but on a server accepting updates from
22// anyone with a share link it is a denial-of-service vector no correctness
23// test can see. Every guest call here runs under a context.WithTimeout
24// (default one second, tunable per Runtime via WithGuestCallTimeout — see
25// its doc comment for why 1s and not the originally-chosen 5s), and the
26// Runtime is built with WithCloseOnContextDone(true) so wazero actually
27// terminates a call that overruns its budget rather than merely making the
28// caller stop waiting. A deadline exceeded is treated exactly like a trap:
29// the instance is discarded and a fresh one is rebuilt.
30//
31// # Rebuilding is log replay, not snapshot restore
32//
33// Spec §5.2 describes recovery as rebuilding "from its latest snapshot" —
34// a persisted, compacted state plus a bounded tail of subsequent updates.
35// As of ABI v4 the guest module can encode its whole state as one update
36// (docs_core_snapshot_len / docs_core_snapshot_read) and Handle.Snapshot
37// below returns those bytes, but a Handle's own recovery still does not
38// use them: every Handle keeps the updates it has itself applied
39// successfully, in memory, for the life of the Handle, and a discarded
40// instance is rebuilt by replaying that entire log from an empty
41// document. Nothing in here is persisted, so there is nothing in here
42// to restore from — §5.2's snapshot restore is the host's to perform
43// with what Handle.Snapshot hands it, and internal/docs does now
44// perform it, storing snapshots in doc_snapshots and starting each
45// document's replay from the newest one. This is a deliberate division,
46// not an oversight, and it is why the in-memory log still needs its own
47// bound (maxRetainedUpdates below): within this package "replay
48// everything" remains the only recovery available, so the log cannot be
49// allowed to grow without limit.
50package core
51
52import (
53 "context"
54 _ "embed"
55 "encoding/binary"
56 "errors"
57 "fmt"
58 "math"
59 "time"
60
61 "github.com/tetratelabs/wazero"
62 "github.com/tetratelabs/wazero/api"
63)
64
65//go:embed testdata/docs_core.wasm
66var moduleWASM []byte
67
68// abiVersion is the contract this host understands. A module reporting
69// anything else is refused at load, so a stale .wasm (see
70// scripts/build-wasm.sh and the copy step in Task 6's brief) fails loudly
71// rather than behaving strangely.
72//
73// Bumped to 4 alongside core/src/lib.rs's docs_core_abi_version for the
74// snapshot export pair (docs_core_snapshot_len / docs_core_snapshot_read)
75// that encodes a document's whole state as one update — see that
76// function's doc comment for why an added export forces a version bump
77// here even though it is, strictly, backwards compatible on the wasm
78// side: the module and this binary ship embedded together with no
79// version skew to tolerate, so the bump exists to catch a stale .wasm
80// at load time instead of "unknown export" deep inside a request.
81// Version 7 adds rich imports alongside initialization and semantic editing.
82// Version 8 adds docs_core_set_view, the view HTML and JSON draw images
83// for (Docs images spec §4.1).
84const abiVersion = 8
85
86// ABIVersion is abiVersion, exported for callers outside this package
87// (snapshot storage and its tests) that need to know which ABI contract
88// this host was built against. It is the same constant, not a second
89// number that could drift from it.
90const ABIVersion = abiVersion
91
92// defaultGuestCallTimeout bounds every single call into the wasm module,
93// unless overridden with WithGuestCallTimeout.
94//
95// This was originally 5s, chosen only from real-fixture timings (tens of
96// milliseconds at most). Fix-round-1 review measured the actual motivating
97// case — Task 5's 163-second-under-wasmi reproducer, replayed against
98// wazero's compiler engine at the memory-growth state that produces the
99// slowdown (core_internal_test.go's TestSlowUpdateIsCutOffByGuestCallTimeout)
100// — at ~4.34s. A 5s cap never fires for the input it exists to stop; it
101// would have been dead code for its own motivating case. One second keeps
102// roughly 1000x headroom over real fixtures (sub-millisecond) while
103// actually cutting off the pathological case at about a quarter of its
104// natural running time instead of letting it nearly finish first.
105const defaultGuestCallTimeout = 1 * time.Second
106
107// maxRetainedUpdates bounds how many previously-applied updates a Handle
108// will keep for the log-replay recovery described above. Without a bound,
109// a long-lived, actively-edited document's log — and so the O(n) cost of
110// any future rebuild, and the blast radius of a single trapped or
111// timed-out call forcing one — would grow without limit (fix-round-1
112// finding 5).
113//
114// The real fix is snapshot support: ABI v4 now exports a state-encode
115// pair (docs_core_snapshot_len / docs_core_snapshot_read) that encodes a
116// document's current state as one update, so a rebuild restores a
117// compacted snapshot plus only the updates since it, matching spec §5.2 and
118// the doc_snapshots table spec §4.1 describes — bounded, cheap recovery
119// regardless of a document's total history. This package exposes that
120// export (Handle.Snapshot, below); persisting the result is the host's
121// job, and internal/docs/store.go's Store.replay and Store.ApplyUpdate
122// now do it, writing a snapshot every 256 updates and replaying from
123// the newest one instead of from the whole log.
124//
125// This cap stays regardless, as the floor under that arrangement: once
126// a document's log is full, Apply refuses to accept further updates at
127// all (ErrUpdateLogFull), rather than either growing the log without
128// bound or silently dropping old entries — dropping old entries would
129// make a later rebuild replay an incomplete history and produce
130// silently wrong content, which is worse than refusing.
131//
132// How reachable this cap actually is, for whoever writes the
133// snapshot/compaction plan: the docs app persists one doc_updates row
134// per accepted POST (internal/docs/store.go's Store.ApplyUpdate), and
135// fixtures/editor-entry.js posts at most once per its own debounce
136// window — 400ms at Task 6's original writing, which put this 4096
137// cap within reach after roughly 27 minutes of one person typing
138// continuously (4096 * 400ms). Task 6 fix round 1 (F3) widened that
139// debounce to 2000ms as cheap headroom (4096 * 2s ≈ 136 minutes) and
140// made hitting the cap a reported, non-silent condition on the client
141// (editor-entry.js's save queue treats ErrUpdateLogFull's 400 as
142// permanent, same as any other 4xx) rather than a client-side fix
143// here — but headroom is all a wider debounce ever buys. The actual
144// fix for a document that keeps being edited past that point is this
145// comment's own snapshot support, not a bigger number here.
146const maxRetainedUpdates = 4096
147
148// MaxRetainedUpdates is maxRetainedUpdates, exported for callers outside
149// this package (snapshot storage and its tests) that need the same cap.
150// It is the same constant, not a second number that could drift from it.
151const MaxRetainedUpdates = maxRetainedUpdates
152
153// ErrUpdateLogFull is returned by Handle.Apply once a document's retained
154// update log has reached maxRetainedUpdates. See that constant's doc
155// comment: ABI v4 exports the snapshot/compaction primitive, this package
156// calls it (Handle.Snapshot, Handle.VerifySnapshot, below), and
157// internal/docs now persists the result, so an ordinary document replays
158// from a snapshot plus a short tail and never comes near this limit.
159//
160// It is still reachable, and deliberately so rather than raised or
161// removed. A document whose snapshot writes keep failing walks its tail
162// back to the cap; a document that was already past it before snapshots
163// shipped starts there. Both end here, refusing the write, which is the
164// one honest answer available — the alternative, dropping old entries to
165// make room, would make a later rebuild replay an incomplete history and
166// return silently wrong content. Refusing is visible; wrong content is
167// not.
168//
169// The two cases do not recover alike, and only one of them heals on its
170// own. Every attempt the host makes tries to write a snapshot from the
171// replayed state before it applies anything (the snapshots design, D3),
172// so the document that predates snapshots gets one on the very POST it
173// fails, and its caller's retry gets through — one visible failure, then
174// healed. The document whose snapshot writes keep failing gets no such
175// rescue: the retry's write fails for whatever reason the last fifteen
176// did, and it stays here until that cause is fixed. Those failures are
177// logged at Error on the way past, which is the only warning anyone
178// gets that a document is walking towards this.
179var ErrUpdateLogFull = errors.New("update log exceeds the retained limit; the document needs a snapshot before it can accept further updates")
180
181// Option configures a Runtime. See WithGuestCallTimeout.
182type Option func(*runtimeOptions)
183
184type runtimeOptions struct {
185 callTimeout time.Duration
186}
187
188// WithGuestCallTimeout overrides defaultGuestCallTimeout for one Runtime.
189// Exists so the cap can be tuned (for a slower/faster production host, or
190// for a test that wants a tight budget without waiting out the default) in
191// a config value instead of a recompile.
192func WithGuestCallTimeout(d time.Duration) Option {
193 return func(o *runtimeOptions) { o.callTimeout = d }
194}
195
196// Runtime owns the compiled module. Compiling is expensive and
197// instantiating is not, so one Runtime is shared and each document gets its
198// own instance (spec §5.2: instances are not safe for concurrent use).
199type Runtime struct {
200 rt wazero.Runtime
201 compiled wazero.CompiledModule
202
203 // callTimeout bounds every guest call made through this Runtime and
204 // every Handle it creates. See defaultGuestCallTimeout and
205 // WithGuestCallTimeout.
206 callTimeout time.Duration
207}
208
209func New(ctx context.Context, opts ...Option) (*Runtime, error) {
210 o := runtimeOptions{callTimeout: defaultGuestCallTimeout}
211 for _, opt := range opts {
212 opt(&o)
213 }
214
215 // WithCloseOnContextDone(true): without this, a context deadline or
216 // cancellation on a guest call only makes the *caller* stop waiting —
217 // the underlying goroutine executing wasm keeps running to completion.
218 // With it, wazero itself terminates the call and closes the module
219 // when the context is done, which is what turns a pathologically slow
220 // input into a bounded failure instead of a resource leak.
221 cfg := wazero.NewRuntimeConfig().WithCloseOnContextDone(true)
222 rt := wazero.NewRuntimeWithConfig(ctx, cfg)
223 compiled, err := rt.CompileModule(ctx, moduleWASM)
224 if err != nil {
225 rt.Close(ctx)
226 return nil, fmt.Errorf("compiling core module: %w", err)
227 }
228 return &Runtime{rt: rt, compiled: compiled, callTimeout: o.callTimeout}, nil
229}
230
231func (r *Runtime) Close(ctx context.Context) error { return r.rt.Close(ctx) }
232
233// instantiate creates a fresh module instance and checks its reported ABI
234// version. Used both for a brand-new document and to rebuild after a
235// discarded (trapped or timed-out) instance.
236func (r *Runtime) instantiate(ctx context.Context) (api.Module, error) {
237 cctx, cancel := context.WithTimeout(ctx, r.callTimeout)
238 defer cancel()
239 // Empty name: wazero treats an anonymous module (ModuleName == "") as
240 // exempt from its store's name-uniqueness check, so instantiating many
241 // of these concurrently — one per document, plus rebuilds — never
242 // collides (internal/wasm/store_module_list.go's registerModule).
243 mod, err := r.rt.InstantiateModule(cctx, r.compiled, wazero.NewModuleConfig().WithName(""))
244 if err != nil {
245 return nil, fmt.Errorf("instantiating core module: %w", err)
246 }
247
248 version, err := callGuest(ctx, r.callTimeout, mod.ExportedFunction("docs_core_abi_version"))
249 if err != nil {
250 mod.Close(ctx)
251 return nil, fmt.Errorf("reading abi version: %w", err)
252 }
253 if err := checkABIVersion(uint32(version[0]), abiVersion); err != nil {
254 mod.Close(ctx)
255 return nil, err
256 }
257 return mod, nil
258}
259
260// checkABIVersion reports whether reported (what a module's
261// docs_core_abi_version export returned) matches want (abiVersion, the
262// contract this host understands). Pulled out of instantiate as a pure
263// function so the decision itself is unit-testable without a compiled
264// wasm module standing in for every case — the previous test here
265// (TestABIVersionIsPinnedAtTwo) only ever called core.New, which never
266// reaches this check at all, and so passed even with the check deleted
267// outright.
268//
269// The error text names both numbers deliberately: whoever hits this in
270// production needs to know which side is stale (an old host against a
271// rebuilt module, or vice versa) without also reading wasm build logs.
272func checkABIVersion(reported, want uint32) error {
273 if reported != want {
274 return fmt.Errorf("core module reports ABI %d, host understands %d", reported, want)
275 }
276 return nil
277}
278
279// callGuest calls fn under the given timeout. A non-nil error here means
280// the call trapped, ran past its deadline (in which case wazero has
281// already closed the module — WithCloseOnContextDone(true)), or the
282// module was otherwise closed out from under it: in every case the
283// instance must be treated as poisoned, never merely retried. The error is
284// wrapped in trapFault so callers further up (Apply, Text) can tell it
285// apart from an ordinary clean rejection (a negative return code from the
286// guest), which does not poison anything — see isFatal.
287func callGuest(ctx context.Context, timeout time.Duration, fn api.Function, params ...uint64) ([]uint64, error) {
288 cctx, cancel := context.WithTimeout(ctx, timeout)
289 defer cancel()
290 res, err := fn.Call(cctx, params...)
291 if err != nil {
292 return nil, &trapFault{err}
293 }
294 return res, nil
295}
296
297// trapFault marks an error as meaning the module instance itself is no
298// longer trustworthy: the wasm call that produced it did not return
299// normally at all (a trap, a deadline exceeded, or the module having
300// already been closed), as opposed to returning normally with a negative
301// application error code. Every error that originates from a wazero
302// api.Function.Call failing carries this; every error this package
303// constructs itself from a clean negative return code does not, so
304// isFatal (via errors.As, walking any fmt.Errorf("...: %w", err) wrapping)
305// tells the two apart.
306type trapFault struct{ err error }
307
308func (t *trapFault) Error() string { return t.err.Error() }
309func (t *trapFault) Unwrap() error { return t.err }
310
311// isFatal reports whether err means the module instance must be discarded
312// (a trap or a deadline exceeded reaching all the way from callGuest) as
313// opposed to an ordinary clean rejection, which leaves the instance fully
314// usable (TestGarbageUpdateReturnsErrorNotTrap).
315func isFatal(err error) bool {
316 var t *trapFault
317 return errors.As(err, &t)
318}
319
320// RecoveredError wraps the error from an Apply call whose instance
321// trapped or timed out but was then successfully discarded and rebuilt —
322// so the *document* is intact (every previously-applied update survived),
323// even though this specific update was not (its outcome, applied or not,
324// is unknown; it is never retried). Callers that only check "err != nil"
325// cannot otherwise tell that apart from an ordinary clean rejection (where
326// the instance was never touched) or from a rebuild that itself failed
327// (a plain joined error — see Apply — where there is no usable instance at
328// all). Use Recovered(err) rather than a type assertion.
329type RecoveredError struct{ err error }
330
331func (e *RecoveredError) Error() string { return e.err.Error() }
332func (e *RecoveredError) Unwrap() error { return e.err }
333
334// Recovered reports whether err came from an Apply call that trapped or
335// timed out but whose instance was successfully discarded and rebuilt —
336// see RecoveredError.
337func Recovered(err error) bool {
338 var r *RecoveredError
339 return errors.As(err, &r)
340}
341
342// RejectedError wraps the error from an Apply call that cleanly refused
343// the update (a negative return code from the guest, e.g. malformed wire
344// bytes yrs's decoder catches) without the instance ever being touched —
345// the document's existing content is completely unaffected, and the
346// instance is exactly as usable afterward as it was before the call. This
347// is the ordinary, expected way most bad input is refused; see Apply's
348// own doc comment.
349//
350// A caller outside this package cannot otherwise distinguish this case
351// from a rebuild that itself failed (Apply's plain errors.Join branch —
352// a fatal error, and one this package genuinely could not recover from)
353// or from a wholly unrelated failure in a caller's own pipeline: neither
354// of those is "the client's fault" the way this is, and before this type
355// existed, both looked identical to this from the outside — a bare,
356// untyped error. Use Rejected(err) rather than a type assertion, the same
357// pattern Recovered(err) above already establishes for the trap-and-
358// rebuild-succeeded case.
359type RejectedError struct{ err error }
360
361func (e *RejectedError) Error() string { return e.err.Error() }
362func (e *RejectedError) Unwrap() error { return e.err }
363
364// Rejected reports whether err came from an Apply call that cleanly
365// refused the update with the instance left fully usable — see
366// RejectedError.
367func Rejected(err error) bool {
368 var r *RejectedError
369 return errors.As(err, &r)
370}
371
372// Handle is one document, backed by its own module instance. Not safe for
373// concurrent use; callers serialise access per document.
374//
375// applied records, in order, every update byte slice this handle has
376// itself applied successfully (rc == 0), up to maxRetainedUpdates. It
377// exists solely so a trapped or timed-out instance can be discarded and a
378// fresh one rebuilt by replaying only the updates already known to be good
379// — the update that triggered the discard is never replayed, matching
380// §5.2's "the request fails cleanly; the document does not." See the
381// package doc comment ("Rebuilding is log replay, not snapshot restore")
382// for why this is a log rather than an actual snapshot.
383type Handle struct {
384 rt *Runtime
385 guid string
386 clientID uint64
387
388 mod api.Module
389 handle uint64
390
391 applied [][]byte
392}
393
394// NewDoc creates a document. The GUID and client id are supplied by the
395// caller and never drawn from yrs: on wasm the CRDT library's entropy is a
396// constant seed, so a value it generates is identical in every process, and
397// a repeated client id or GUID corrupts the document (Global Constraints).
398func (r *Runtime) NewDoc(ctx context.Context, guid string, clientID uint64) (*Handle, error) {
399 mod, err := r.instantiate(ctx)
400 if err != nil {
401 return nil, err
402 }
403
404 handle := &Handle{rt: r, guid: guid, clientID: clientID, mod: mod}
405 docHandle, err := createDoc(ctx, r.callTimeout, mod, guid, clientID)
406 if err != nil {
407 mod.Close(ctx)
408 return nil, err
409 }
410 handle.handle = docHandle
411 return handle, nil
412}
413
414// createDoc allocates the guid in mod's linear memory, calls
415// docs_core_doc_new, and frees the buffer. Shared between NewDoc and a
416// post-trap rebuild.
417func createDoc(ctx context.Context, timeout time.Duration, mod api.Module, guid string, clientID uint64) (uint64, error) {
418 guidBytes := []byte(guid)
419 ptr, err := allocIn(ctx, timeout, mod, uint64(len(guidBytes)))
420 if err != nil {
421 return 0, fmt.Errorf("alloc for guid: %w", err)
422 }
423 defer freeIn(ctx, timeout, mod, ptr, uint64(len(guidBytes)))
424
425 if !mod.Memory().Write(uint32(ptr), guidBytes) {
426 return 0, fmt.Errorf("writing guid at %d: out of range", ptr)
427 }
428
429 res, err := callGuest(ctx, timeout, mod.ExportedFunction("docs_core_doc_new"), ptr, uint64(len(guidBytes)), clientID)
430 if err != nil {
431 return 0, fmt.Errorf("doc_new: %w", err)
432 }
433 if res[0] == 0 {
434 return 0, fmt.Errorf("doc_new returned a null handle")
435 }
436 return res[0], nil
437}
438
439// allocIn calls docs_core_alloc and checks the 0-on-failure sentinel
440// (including any length over isize::MAX — core/src/abi.rs's layout_for).
441func allocIn(ctx context.Context, timeout time.Duration, mod api.Module, length uint64) (uint64, error) {
442 res, err := callGuest(ctx, timeout, mod.ExportedFunction("docs_core_alloc"), length)
443 if err != nil {
444 return 0, fmt.Errorf("alloc trapped or timed out: %w", err)
445 }
446 if res[0] == 0 {
447 return 0, fmt.Errorf("alloc(%d) failed", length)
448 }
449 return res[0], nil
450}
451
452// freeIn best-efforts a free. A failure here (trap/timeout) is folded into
453// "the instance is now poisoned", which the caller's own callGuest error
454// (the one that actually matters) will already have triggered, so this
455// deliberately does not itself return an error to plumb through defers.
456func freeIn(ctx context.Context, timeout time.Duration, mod api.Module, ptr, length uint64) {
457 _, _ = callGuest(ctx, timeout, mod.ExportedFunction("docs_core_free"), ptr, length)
458}
459
460func (h *Handle) Close(ctx context.Context) error {
461 _, err := callGuest(ctx, h.rt.callTimeout, h.mod.ExportedFunction("docs_core_doc_free"), h.handle)
462 if closeErr := h.mod.Close(ctx); err == nil {
463 err = closeErr
464 }
465 return err
466}
467
468// rebuild discards h's current (poisoned) instance and replaces it with a
469// fresh one for the same document (guid, clientID), replaying every update
470// previously applied successfully. The update that triggered the discard
471// is not replayed — it is not in h.applied, since that log is only
472// appended to on a clean rc == 0.
473//
474// It deliberately does not run under ctx as given: ctx is the same context
475// whose deadline may be exactly what triggered this rebuild (a timed-out
476// Apply calls rebuild with its own ctx). Rebuilding under an
477// already-expired deadline would make recovery fail precisely in the case
478// it exists for, so this strips ctx's cancellation/deadline
479// (context.WithoutCancel) while keeping any values on it, and relies on
480// callTimeout to still bound each individual call made during the rebuild
481// itself.
482func (h *Handle) rebuild(ctx context.Context) error {
483 rebuildCtx := context.WithoutCancel(ctx)
484 timeout := h.rt.callTimeout
485
486 // Best-effort: the old instance may already be closed (a timeout under
487 // WithCloseOnContextDone(true) closes it as part of terminating the
488 // call), so an error here is expected and not itself a failure.
489 _ = h.mod.Close(rebuildCtx)
490
491 mod, err := h.rt.instantiate(rebuildCtx)
492 if err != nil {
493 return fmt.Errorf("rebuilding instance: %w", err)
494 }
495 docHandle, err := createDoc(rebuildCtx, timeout, mod, h.guid, h.clientID)
496 if err != nil {
497 mod.Close(rebuildCtx)
498 return fmt.Errorf("rebuilding instance: %w", err)
499 }
500 for i, update := range h.applied {
501 if err := applyOn(rebuildCtx, timeout, mod, docHandle, update); err != nil {
502 mod.Close(rebuildCtx)
503 return fmt.Errorf("rebuilding instance: replaying update %d/%d, previously applied cleanly: %w",
504 i+1, len(h.applied), err)
505 }
506 }
507 h.mod = mod
508 h.handle = docHandle
509 return nil
510}
511
512// applyOn runs docs_core_apply against a specific (mod, docHandle) pair —
513// factored out so both Handle.Apply and rebuild's replay share the same
514// alloc/write/call/free/error-code logic.
515func applyOn(ctx context.Context, timeout time.Duration, mod api.Module, docHandle uint64, update []byte) error {
516 ptr, err := allocIn(ctx, timeout, mod, uint64(len(update)))
517 if err != nil {
518 return fmt.Errorf("alloc: %w", err)
519 }
520 defer freeIn(ctx, timeout, mod, ptr, uint64(len(update)))
521
522 if !mod.Memory().Write(uint32(ptr), update) {
523 return fmt.Errorf("writing %d bytes at %d: out of range", len(update), ptr)
524 }
525
526 rc, err := callGuest(ctx, timeout, mod.ExportedFunction("docs_core_apply"), docHandle, ptr, uint64(len(update)))
527 if err != nil {
528 return fmt.Errorf("apply trapped or timed out: %w", err)
529 }
530 if code := int32(rc[0]); code != 0 {
531 return fmt.Errorf("apply rejected the update: code %d", code)
532 }
533 return nil
534}
535
536// Apply applies update to the document. A clean rejection (a negative
537// error code from the guest) leaves the instance usable — that is the
538// whole point of §5.2's per-document instance: most bad input never needs
539// the instance discarded at all. That case comes back as a *RejectedError
540// (see Rejected). "Usable" is not "untouched": bytes the decoder refuses
541// (ERR_DECODE) change nothing, but an update that decodes and then fails
542// part-way (ERR_APPLY, e.g. a later struct's InvalidParent) leaves the
543// structs integrated before the failure in the document, because yrs
544// integrates them one at a time and the transaction commits on drop. A
545// caller that keeps a handle after a rejection holds that partial state
546// (Docs' warm handles drop it; live-push review #174, finding 1). Making
547// the guest apply into a scratch transaction it can roll back would close
548// this here; that is a core change with its own ABI test, not done yet. A trap or a deadline exceeded is different: the
549// instance is discarded and rebuilt from every update applied here so
550// far, and the triggering update is reported as an error but never
551// retried or logged, so it can never itself be replayed into the rebuilt
552// instance. When that rebuild succeeds, the returned error is a
553// *RecoveredError (see Recovered) so a caller can tell "this update was
554// rejected but the document is fine" apart from "the document itself is
555// gone" (a rebuild that fails returns a plain joined error instead — the
556// one shape this method returns that is neither *RejectedError nor
557// *RecoveredError, and the one a caller must not mistake for either: the
558// document itself may now be unusable, not merely this one update).
559//
560// Once the document's retained update log is full (maxRetainedUpdates),
561// Apply refuses any further update — including one that would otherwise
562// apply cleanly — with ErrUpdateLogFull, rather than growing the log
563// without bound. See maxRetainedUpdates's doc comment.
564func (h *Handle) Apply(ctx context.Context, update []byte) error {
565 if len(h.applied) >= maxRetainedUpdates {
566 return ErrUpdateLogFull
567 }
568
569 err := applyOn(ctx, h.rt.callTimeout, h.mod, h.handle, update)
570 if err == nil {
571 // Copy: the caller may reuse or mutate its update slice after this
572 // call returns, and this log must survive a later rebuild.
573 stored := make([]byte, len(update))
574 copy(stored, update)
575 h.applied = append(h.applied, stored)
576 return nil
577 }
578 if isFatal(err) {
579 if rebuildErr := h.rebuild(ctx); rebuildErr != nil {
580 return errors.Join(err, rebuildErr)
581 }
582 return &RecoveredError{err}
583 }
584 return &RejectedError{err}
585}
586
587// RetainedUpdates is how many updates this handle has applied and keeps
588// for a rebuild: Apply refuses with ErrUpdateLogFull at MaxRetainedUpdates.
589// A caller that keeps a handle across many updates (Docs' warm handles)
590// watches it.
591func (h *Handle) RetainedUpdates() int { return len(h.applied) }
592
593// ResidentBytes estimates what this handle holds in memory: its module
594// instance's linear memory, which grows and never shrinks, plus the
595// retained updates. A caller that keeps handles bounds them by this.
596func (h *Handle) ResidentBytes() uint64 {
597 var n uint64
598 if h.mod != nil {
599 if m := h.mod.Memory(); m != nil {
600 n = uint64(m.Size())
601 }
602 }
603 for _, u := range h.applied {
604 n += uint64(len(u))
605 }
606 return n
607}
608
609// Text returns the document's current text content. If the read itself
610// traps or times out, the instance is discarded and rebuilt exactly as in
611// Apply, and the read is retried once against the freshly rebuilt
612// instance — the content is available at that point, and returning an
613// empty string plus an error instead of it would tell the caller the data
614// is gone when it is not.
615func (h *Handle) Text(ctx context.Context) (string, error) {
616 return h.read(ctx, "text")
617}
618
619// HTML returns the document's current content rendered as HTML (spec
620// §6.2: the read view is server-rendered, no script required), drawn for
621// no view: every image is the missing box. A page shows HTMLIn.
622func (h *Handle) HTML(ctx context.Context) (string, error) {
623 return h.readIn(ctx, "html", View{})
624}
625
626// HTMLIn is HTML drawn for one view (Docs images spec §4.1): this
627// document's own images are drawn under v.Base.
628func (h *Handle) HTMLIn(ctx context.Context, v View) (string, error) {
629 return h.readIn(ctx, "html", v)
630}
631
632// JSON returns the document's structure as ProseMirror-shaped JSON —
633// what the export paths (internal/export, internal/pdf) read, since
634// Markdown and PDF both need to know where a list ends and which run is
635// bold, and neither can get that from HTML without a parser. See
636// core/src/fragment.rs's fragment_json.
637//
638// The bytes are always a complete JSON document for a live handle,
639// never "" — an empty document is {"type":"doc","content":[]} — so a
640// caller may unmarshal the result without a special case for empty.
641//
642// Drawn for no view, so every image is {"missing":true}; JSONIn names
643// this document's own.
644func (h *Handle) JSON(ctx context.Context) (string, error) {
645 return h.readIn(ctx, "json", View{})
646}
647
648// JSONIn is JSON for one view (Docs images spec §4.2).
649func (h *Handle) JSONIn(ctx context.Context, v View) (string, error) {
650 return h.readIn(ctx, "json", v)
651}
652
653// View is where a rendering will be read (Docs images spec §4.1): the
654// document's own sqid, and the base its images are drawn under —
655// "/d/{sqid}" for a signed-in reader, "/p/{token}" for a link holder. The
656// zero View draws every image as missing. The core checks both against
657// their grammars and refuses the read otherwise.
658type View struct {
659 Sqid string
660 Base string
661}
662
663func (v View) wire() []byte {
664 if v == (View{}) {
665 return nil
666 }
667 return []byte(v.Sqid + "\n" + v.Base)
668}
669
670// Snapshot returns the document's entire state as one Yjs update — what
671// doc_snapshots stores so a later replay can start from it instead of
672// from the whole log (the snapshots design, D1).
673//
674// Bytes rather than a string, but it rides the same len/read machinery
675// as Text/HTML/JSON, including their trap-and-retry: a Go string is a
676// byte sequence and nothing here interprets it, so "snapshot" is simply
677// a fourth renderer name to readOn.
678func (h *Handle) Snapshot(ctx context.Context) ([]byte, error) {
679 s, err := h.read(ctx, "snapshot")
680 if err != nil {
681 return nil, err
682 }
683 return []byte(s), nil
684}
685
686// verifySnapshotOn allocates candidate into mod's linear memory, calls
687// docs_core_verify_snapshot against docHandle, frees the buffer, and
688// returns the raw i32 return code. Structured exactly like applyOn —
689// docs_core_verify_snapshot is the only other export besides
690// docs_core_apply that takes a caller-supplied byte buffer into guest
691// memory, so the alloc/write/call/free dance and its error handling are
692// copied from there rather than reinvented.
693func verifySnapshotOn(ctx context.Context, timeout time.Duration, mod api.Module, docHandle uint64, candidate []byte) (int32, error) {
694 ptr, err := allocIn(ctx, timeout, mod, uint64(len(candidate)))
695 if err != nil {
696 return 0, fmt.Errorf("alloc: %w", err)
697 }
698 defer freeIn(ctx, timeout, mod, ptr, uint64(len(candidate)))
699
700 if !mod.Memory().Write(uint32(ptr), candidate) {
701 return 0, fmt.Errorf("writing %d bytes at %d: out of range", len(candidate), ptr)
702 }
703
704 rc, err := callGuest(ctx, timeout, mod.ExportedFunction("docs_core_verify_snapshot"), docHandle, ptr, uint64(len(candidate)))
705 if err != nil {
706 return 0, fmt.Errorf("verify_snapshot trapped or timed out: %w", err)
707 }
708 return int32(rc[0]), nil
709}
710
711// VerifySnapshot asks the core whether candidate, replayed into an empty
712// document, is this document — state vector, delete set and structural
713// render (the snapshots design, D5). It is a smoke test rather than a
714// proof, and it cannot detect a snapshot taken from a stale state; see
715// core/src/snapshot.rs for both limits.
716//
717// docs_core_verify_snapshot's four outcomes map as: 0 (the candidate is
718// this document) -> true, nil; 1 (it is not) -> false, nil; ERR_DECODE
719// (candidate is not a decodable update at all) -> false, nil — bad bytes
720// are a "no" answer, not a failure of this call; anything else (a trap,
721// a deadline exceeded, ERR_NO_DOC, ERR_INVALID_LENGTH, or an
722// unrecognised code) -> false, error.
723//
724// A trap or timeout is handled exactly as in Apply: the instance is
725// discarded and rebuilt from every update applied here so far (the
726// document itself survives), and the returned error is a *RecoveredError
727// so a caller can tell that apart from a rebuild that itself failed.
728// Unlike Apply, there is no update to omit from replay — this call never
729// mutates h's document at all, only a throwaway one inside the guest.
730func (h *Handle) VerifySnapshot(ctx context.Context, candidate []byte) (bool, error) {
731 const errDecode = -2
732
733 code, err := verifySnapshotOn(ctx, h.rt.callTimeout, h.mod, h.handle, candidate)
734 if err != nil {
735 if isFatal(err) {
736 if rebuildErr := h.rebuild(ctx); rebuildErr != nil {
737 return false, errors.Join(err, rebuildErr)
738 }
739 return false, &RecoveredError{err}
740 }
741 return false, err
742 }
743
744 switch code {
745 case 0:
746 return true, nil
747 case 1:
748 return false, nil
749 case errDecode:
750 return false, nil
751 default:
752 return false, fmt.Errorf("verify_snapshot failed: code %d", code)
753 }
754}
755
756// read is the shared body of Text, HTML, JSON and Snapshot: call the named
757// renderer's len/read pair, and if the call itself traps or times out,
758// discard the instance, rebuild it exactly as Apply does, and retry the
759// read once against the fresh one. Retrying rather than reporting an
760// error is deliberate — the content is available at that point, and
761// returning an empty string plus an error would tell the caller the
762// data is gone when it is not.
763//
764// One function rather than three near-identical ones. It was three
765// (textOn/htmlOn, and jsonOn was about to be the third): the same forty
766// lines with two identifiers substituted, which is three places for a
767// fix like fix-round-1's finding 3 (read the written count, not the
768// buffer size) to be applied to two of.
769func (h *Handle) read(ctx context.Context, renderer string) (string, error) {
770 return h.readIn(ctx, renderer, View{})
771}
772
773// readIn is read with a view set first, for the two renderers that draw
774// images ("html" and "json"). The view is set before every attempt, the
775// retry included: a rebuilt instance holds none, and a warm handle may
776// hold the last caller's.
777func (h *Handle) readIn(ctx context.Context, renderer string, v View) (string, error) {
778 attempt := func() (string, error) {
779 if renderer == "html" || renderer == "json" {
780 if err := setViewOn(ctx, h.rt.callTimeout, h.mod, h.handle, v.wire()); err != nil {
781 return "", err
782 }
783 }
784 return readOn(ctx, h.rt.callTimeout, h.mod, h.handle, renderer)
785 }
786 s, err := attempt()
787 if err == nil {
788 return s, nil
789 }
790 if !isFatal(err) {
791 return "", err
792 }
793 if rebuildErr := h.rebuild(ctx); rebuildErr != nil {
794 return "", errors.Join(err, rebuildErr)
795 }
796 s, err = attempt()
797 if err != nil {
798 return "", fmt.Errorf("reading %s from the rebuilt instance: %w", renderer, err)
799 }
800 return s, nil
801}
802
803// setViewOn calls docs_core_set_view. An empty view sets the default.
804func setViewOn(ctx context.Context, timeout time.Duration, mod api.Module, docHandle uint64, view []byte) error {
805 ptr, n := uint64(0), uint64(len(view))
806 if n > 0 {
807 var err error
808 if ptr, err = allocIn(ctx, timeout, mod, n); err != nil {
809 return fmt.Errorf("alloc: %w", err)
810 }
811 defer freeIn(ctx, timeout, mod, ptr, n)
812 if !mod.Memory().Write(uint32(ptr), view) {
813 return fmt.Errorf("writing %d bytes at %d: out of range", n, ptr)
814 }
815 }
816 rc, err := callGuest(ctx, timeout, mod.ExportedFunction("docs_core_set_view"), docHandle, ptr, n)
817 if err != nil {
818 return fmt.Errorf("set_view trapped or timed out: %w", err)
819 }
820 if code := int32(rc[0]); code != 0 {
821 return fmt.Errorf("set_view refused the view: code %d", code)
822 }
823 return nil
824}
825
826// readOn performs one renderer's len-then-read dance against
827// docs_core_<renderer>_len and docs_core_<renderer>_read. renderer is
828// always one of this package's own four literals ("text", "html",
829// "json", "snapshot"), never anything derived from a request — the
830// export names it builds are a closed set, and a name that does not
831// resolve to an exported function surfaces below as a nil api.Function.
832func readOn(ctx context.Context, timeout time.Duration, mod api.Module, docHandle uint64, renderer string) (string, error) {
833 lenFn := mod.ExportedFunction("docs_core_" + renderer + "_len")
834 readFn := mod.ExportedFunction("docs_core_" + renderer + "_read")
835 if lenFn == nil || readFn == nil {
836 // Unreachable while abiVersion matches — the version check at
837 // load is what proves these exports exist — but a nil
838 // api.Function panics inside callGuest rather than erroring, so
839 // this turns a future ABI mistake into a returned error instead
840 // of a panic in a request handler.
841 return "", fmt.Errorf("module exports no %q renderer", renderer)
842 }
843
844 lenRes, err := callGuest(ctx, timeout, lenFn, docHandle)
845 if err != nil {
846 return "", fmt.Errorf("%s_len trapped or timed out: %w", renderer, err)
847 }
848 // The len functions return i32: negative is an error code, not a
849 // length. Reading it as unsigned would turn ERR_NO_DOC into
850 // 0xFFFFFFFF and then try to allocate four gigabytes.
851 if code := int32(lenRes[0]); code < 0 {
852 return "", fmt.Errorf("%s_len failed: code %d", renderer, code)
853 }
854 n := lenRes[0]
855 if n == 0 {
856 return "", nil
857 }
858
859 ptr, err := allocIn(ctx, timeout, mod, n)
860 if err != nil {
861 return "", fmt.Errorf("alloc: %w", err)
862 }
863 defer freeIn(ctx, timeout, mod, ptr, n)
864
865 rc, err := callGuest(ctx, timeout, readFn, docHandle, ptr, n)
866 if err != nil {
867 return "", fmt.Errorf("%s_read trapped or timed out: %w", renderer, err)
868 }
869 written := int32(rc[0])
870 if written < 0 {
871 return "", fmt.Errorf("%s_read failed: code %d", renderer, written)
872 }
873
874 // The read functions return s.len(), guaranteed only <= out_len
875 // (core/src/abi.rs — the buffer sized by the len call is an upper
876 // bound, not a promise the two calls agree exactly). Reading n bytes
877 // instead of the written count would, if they ever diverged, append
878 // uninitialised allocator bytes past the real content to the
879 // returned string (fix-round-1 finding 3) — read exactly what the
880 // read call says it wrote.
881 buf, ok := mod.Memory().Read(uint32(ptr), uint32(written))
882 if !ok {
883 return "", fmt.Errorf("reading %d bytes at %d: out of range", written, ptr)
884 }
885 return string(buf), nil
886}
887
888// ErrBuildMalformed and ErrBuildLimit are Build's refusals of an
889// instruction list: one that does not follow core/src/build.rs's format,
890// and one past its limits. Neither carries anything from the list.
891// buildTimeoutFactor is how many ordinary call limits Build's one call
892// into the builder may take. See Build.
893const buildTimeoutFactor = 5
894
895var (
896 ErrBuildMalformed = errors.New("core: import instructions are malformed")
897 ErrBuildLimit = errors.New("core: import instructions exceed the builder's limits")
898 // ErrBuildClientID: Build was asked to write under a client id past
899 // MaxBuildClientID, which no browser could decode.
900 ErrBuildClientID = errors.New("core: import client id is not safe for JavaScript")
901)
902
903// MaxBuildClientID is the largest client id Build writes under:
904// JavaScript's Number.MAX_SAFE_INTEGER. lib0 refuses a larger varuint,
905// so an update written under one would apply here (yrs reads it) and in
906// no editor. The builder refuses it too (core/src/build.rs); this check
907// fails before the call. Ids the server only reads with are not bound.
908const MaxBuildClientID = 1<<53 - 1
909
910// Build writes the document an import instruction list describes
911// (core/src/build.rs) into a fresh document with this guid and client id,
912// and returns that document's whole state as one update. The list is
913// checked in full before anything is written, and the instance is
914// discarded either way, so a refusal or a trap leaves nothing behind.
915//
916// The build call alone may run for buildTimeoutFactor times the usual
917// limit. Writing a document costs about three times what applying the
918// result costs, and the result must still apply within the ordinary
919// limit every time the document is opened; the instance a slow build
920// runs in is thrown away regardless, so the longer allowance risks
921// nothing that the ordinary one protects.
922func (r *Runtime) Build(ctx context.Context, guid string, clientID uint64, ops []byte) ([]byte, error) {
923 if clientID > MaxBuildClientID {
924 return nil, ErrBuildClientID
925 }
926 h, err := r.NewDoc(ctx, guid, clientID)
927 if err != nil {
928 return nil, err
929 }
930 defer h.Close(ctx)
931
932 ptr, err := allocIn(ctx, r.callTimeout, h.mod, uint64(len(ops)))
933 if err != nil {
934 return nil, fmt.Errorf("core: build: alloc: %w", err)
935 }
936 defer freeIn(ctx, r.callTimeout, h.mod, ptr, uint64(len(ops)))
937 if !h.mod.Memory().Write(uint32(ptr), ops) {
938 return nil, fmt.Errorf("core: build: writing %d bytes at %d: out of range", len(ops), ptr)
939 }
940 rc, err := callGuest(ctx, buildTimeoutFactor*r.callTimeout, h.mod.ExportedFunction("docs_core_build"), h.handle, ptr, uint64(len(ops)))
941 if err != nil {
942 return nil, fmt.Errorf("core: build trapped or timed out: %w", err)
943 }
944 switch code := int32(rc[0]); code {
945 case 0:
946 case -6:
947 return nil, ErrBuildMalformed
948 case -7:
949 return nil, ErrBuildLimit
950 case -9:
951 return nil, ErrBuildClientID
952 default:
953 return nil, fmt.Errorf("core: build refused: code %d", code)
954 }
955 return h.Snapshot(ctx)
956}
957
958// BuildBlock is one block of an import: a paragraph when Heading is 0,
959// otherwise a heading of that level (1 to 6).
960type BuildBlock struct {
961 Heading int
962 Runs []BuildRun
963}
964
965// BuildRun is one run of text and the names of its marks.
966type BuildRun struct {
967 Marks []string
968 Text string
969}
970
971// EncodeBuild writes blocks as core/src/build.rs's instruction list,
972// version 1. It checks only what the encoding itself needs (lengths that
973// fit their fields); everything else, the vocabulary included, is the
974// builder's to refuse.
975func EncodeBuild(blocks []BuildBlock) ([]byte, error) {
976 out := []byte{1}
977 out = binary.LittleEndian.AppendUint32(out, uint32(len(blocks)))
978 for _, b := range blocks {
979 if b.Heading == 0 {
980 out = append(out, 1)
981 } else {
982 if b.Heading < 0 || b.Heading > 255 {
983 return nil, ErrBuildMalformed
984 }
985 out = append(out, 2, byte(b.Heading))
986 }
987 out = binary.LittleEndian.AppendUint32(out, uint32(len(b.Runs)))
988 for _, r := range b.Runs {
989 if len(r.Marks) > 255 || uint64(len(r.Text)) > math.MaxUint32 {
990 return nil, ErrBuildLimit
991 }
992 out = append(out, byte(len(r.Marks)))
993 for _, m := range r.Marks {
994 if len(m) > 255 {
995 return nil, ErrBuildMalformed
996 }
997 out = append(out, byte(len(m)))
998 out = append(out, m...)
999 }
1000 out = binary.LittleEndian.AppendUint32(out, uint32(len(r.Text)))
1001 out = append(out, r.Text...)
1002 }
1003 }
1004 return out, nil
1005}
1006