oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

1package docs
2
3import (
4 "context"
5 crand "crypto/rand"
6 "errors"
7 "fmt"
8 "html/template"
9 "log/slog"
10 "math"
11 mrand "math/rand/v2"
12 "strings"
13 "time"
14
15 "github.com/google/uuid"
16 "gorm.io/gorm"
17
18 "github.com/carlosframework/docs/internal/core"
19)
20
21// Store is documents' persistence: rows in SQLite for identity and
22// the update log, and the document's actual text read back through
23// the real CRDT core rather than any column here — see Text.
24type Store struct {
25 // recordOrigin is the push registry's record (push.go), nil when live
26 // push is off. logEpoch is this process's log epoch (logepoch.go).
27 recordOrigin func(docID, seq int64, o postOrigin, update []byte)
28 logEpoch string
29 // warm keeps a replayed handle per document between update POSTs
30 // (warm.go); nil means every POST replays, as it always did.
31 warm *warmCache
32 // warmBeforeCommit is a test seam: it runs inside commitUpdate's
33 // transaction, after the row is written and before the final
34 // permission check, so a test can revoke a writer or fail the
35 // transaction between a warm Apply and its commit. nil in production.
36 warmBeforeCommit func(ctx context.Context, tx *gorm.DB, doc *Document) error
37 // warmApplyHook is a test seam: an error it returns stands in for
38 // Handle.Apply's (warm.go, rule 2). nil in production.
39 warmApplyHook func(h *core.Handle) error
40 team *teamRuntime
41 db *gorm.DB
42 core *core.Runtime
43 content *contentCipher
44
45 // sampleDocuments mirrors Config.SampleDocuments, already parsed —
46 // see EnsurePerson's own doc comment for what it gates and why the
47 // gate lives here rather than at the HTTP layer.
48 sampleDocuments bool
49
50 // seedOnlyMembers, when set, keeps the sample library away from a
51 // person admitted only by a grant.
52 //
53 // The sample documents are "welcome to your instance" content. Somebody
54 // invited to read one document is not arriving at their instance; they
55 // are arriving at somebody else's, to read one thing. Seeding them six
56 // documents of ours is the outcome 0005_grants.sql's comment says the
57 // design avoids — it just avoided it at grant time and then did it at
58 // sign-in time instead. (Branch review, finding 9.)
59 //
60 // nil means "seed everybody", which is what every construction without
61 // an allowlist gets, and matches sampleDocuments' own default shape.
62 seedOnlyMembers func(address string) bool
63
64 // members answers "is this address a member of this instance" in lone
65 // shape — allowlist.configured, the same predicate seedOnlyMembers and
66 // handlers.isMember hold — for the team rung (permissionScope). nil
67 // means nobody reads the team rung in lone shape: it fails closed.
68 members func(address string) bool
69
70 // logger is where a sample-seeding failure goes — see
71 // seedIfEnabled's own doc comment for why that failure is logged
72 // and swallowed here rather than ever returned to EnsurePerson's
73 // caller.
74 logger *slog.Logger
75}
76
77// NewStore builds a Store over an already-migrated *gorm.DB and a
78// shared *core.Runtime — one Runtime compiles the wasm module once
79// and is reused for every document (core.New's doc comment); each
80// call into it below opens its own per-document instance (a
81// *core.Handle) and closes it again.
82//
83// sampleDocuments and logger back EnsurePerson's own per-person
84// sample seeding (see its doc comment): sampleDocuments is
85// Config.SampleDocuments already parsed by parseSampleDocuments
86// (app.go), and logger is where a seeding failure is reported rather
87// than propagated. A nil logger defaults to slog.Default(), the same
88// fallback New (app.go) applies to Config.Logger — this Store can be
89// built directly in a test (scope_test.go and others already do) with
90// no logger of its own to pass.
91func NewStore(db *gorm.DB, rt *core.Runtime, sampleDocuments bool, logger *slog.Logger) *Store {
92 if logger == nil {
93 logger = slog.Default()
94 }
95 return &Store{db: db, core: rt, sampleDocuments: sampleDocuments, logger: logger}
96}
97
98// sqidAlphabet avoids visually ambiguous characters (0/O, 1/l/I) —
99// sqids appear in URLs a person may read aloud or retype.
100const sqidAlphabet = "23456789abcdefghjkmnpqrstuvwxyz"
101
102const sqidLength = 10
103
104// newSqid generates a random opaque document identifier, distinct
105// from the row's integer id, safe to expose in a URL. len(sqidAlphabet)
106// is 31 (8 digits, 23 letters — 0/O, 1/l/I excluded), not a power of
107// two, so taking each random byte mod 31 is not perfectly uniform:
108// 256 % 31 == 8, so the first eight symbols (the digits '2'-'9', the
109// low end of sqidAlphabet) come out of this loop about 3% more often
110// than the rest. Fix round 3 corrected this comment, which used to
111// assert a false "32, so no bias" — a wrong claim about a
112// security-adjacent property is worse than admitting the real one.
113// The bias itself is harmless at sqidLength characters: it narrows
114// the effective keyspace by a small, bounded fraction, nowhere near
115// enough to make ten random symbols from a 31-letter alphabet
116// guessable.
117func newSqid() (string, error) {
118 raw := make([]byte, sqidLength)
119 if _, err := crand.Read(raw); err != nil {
120 return "", fmt.Errorf("docs: generate sqid: %w", err)
121 }
122 out := make([]byte, sqidLength)
123 for i, b := range raw {
124 out[i] = sqidAlphabet[int(b)%len(sqidAlphabet)]
125 }
126 return string(out), nil
127}
128
129// maxSqidAttempts bounds Create's retry loop on a sqid collision. At
130// sqidLength characters over sqidAlphabet's 31 symbols, a collision is
131// astronomically unlikely; this exists only so a UNIQUE violation is
132// handled rather than surprising, not because collisions are
133// expected.
134const maxSqidAttempts = 5
135
136// owned scopes g to documents owner may see — the one seam every
137// query in this file goes through, per the plan's own ruling.
138// Deliberately not rastrillo's scope.Owned (SKILL.md §3): that helper
139// is `g.Where("user_id = ?", owner)`, which is exactly what this is
140// today, but authored, versioned and tested outside this package.
141// Applied to a table that later grows sharing (spec §4.2's `grants`
142// join, out of scope for this plan), scope.Owned would keep silently
143// filtering to creator-only forever — a document library that looks
144// empty rather than broken, the worst available failure shape, on the
145// helper an author would naturally reach for. Writing `owned` here
146// instead means the day sharing lands, this is the one function that
147// changes (to add the join), not a search-and-replace across
148// scattered WHERE clauses — and TestOwnedScopesByOwner (scope_test.go)
149// pins its current, ownership-only contract so a future edit that
150// widens it does so on purpose.
151//
152// owner <= 0 matches nothing, deliberately, rather than trusting every
153// caller to reject it first. people.id starts at 1 (SQLite's INTEGER
154// PRIMARY KEY), so 0 is never a real person — it is exactly the value
155// 0002_owners.sql's migration backfilled onto every document that
156// existed before ownership did (see that file's own comment, and
157// TestOrphanedDocumentsAreVisibleToNobody in scope_test.go, which
158// pins this). Fix round 1 on this task: a reviewer found owned(g, 0),
159// Store.List(ctx, 0) and Store.Get(ctx, 0, ...) all happily returned
160// those orphaned rows — nothing upstream exploited that yet, but nothing
161// prevented a careless future caller from doing so either, and the
162// seam is the one place that can make it structurally impossible
163// rather than merely unexercised today. Matching nothing (a `1 = 0`
164// clause) rather than returning an error keeps every call site's
165// chaining (.Where/.Order/.Find) unchanged, and gives owner 0 the same
166// outcome as any other owner with no visible rows — no distinct error
167// shape for "invalid owner" to leak through a 500 or otherwise
168// distinguish itself from "you just have nothing here" (spec §4.2's
169// own reasoning against a distinguishable failure mode, applied here
170// to the seam itself rather than only to the 404-vs-403 handler
171// boundary).
172//
173// It does not filter deleted_at: that is not an ownership concern.
174// Folding it in here would make `owned` do two unrelated jobs under
175// one name, and would silently change behaviour for any future caller
176// that wants every one of an owner's rows regardless of deletion state
177// (an admin or export path, say) without ever needing to touch this
178// function. List and Get add `deleted_at IS NULL` themselves,
179// deliberately visible at the call site.
180func owned(g *gorm.DB, owner int64) *gorm.DB {
181 if owner <= 0 {
182 return g.Where("1 = 0")
183 }
184 return g.Where("owner_id = ?", owner)
185}
186
187// EnsurePerson maps an authenticated address to this app's own,
188// numeric Person id — get-or-create, keyed on a case-insensitive,
189// trimmed Email. This is the translation rastrillo SKILL.md §5
190// requires under the magic-link plugin: the session Subject is the
191// verified email itself, not a numeric id, so sessions.UserID returns
192// (0, false) and must never be used (see Document.OwnerID's doc
193// comment). handlers.go's owner helper calls this on every
194// authenticated request; TestPerson (testing.go) calls it directly so
195// a test can mint an owner id without going through HTTP at all — the
196// two must and do agree, since TestPerson is this method and nothing
197// else.
198//
199// The create branch below — and only the create branch — is also
200// where a brand-new person's sample documents get seeded
201// (seedIfEnabled), when this instance has opted in. That is
202// deliberate and is the whole reason this hangs off "a Person row was
203// just created" rather than off "List came back empty": a person who
204// deletes every one of their documents still has a Person row, so
205// their next sign-in takes the found branch just above and returns
206// early — never reaching seedIfEnabled — and gets nothing back.
207// Seeding is a one-time event in a person's history, tied to the one
208// moment that can only ever happen once: their row not existing yet.
209func (s *Store) EnsurePerson(ctx context.Context, email string) (int64, error) {
210 email = strings.TrimSpace(strings.ToLower(email))
211 if email == "" {
212 return 0, errors.New("docs: EnsurePerson: address is empty")
213 }
214
215 var p Person
216 err := s.db.WithContext(ctx).Where("email = ?", email).First(&p).Error
217 if err == nil {
218 return p.ID, nil
219 }
220 if !errors.Is(err, gorm.ErrRecordNotFound) {
221 return 0, fmt.Errorf("docs: look up person %q: %w", email, err)
222 }
223
224 p = Person{Email: email, CreatedAt: time.Now().UTC()}
225 if err := s.db.WithContext(ctx).Create(&p).Error; err != nil {
226 // A concurrent first sign-in from the same brand-new address
227 // can race two inserts against the unique index on email; the
228 // loser looks up what the winner just created rather than
229 // failing the request over a benign collision. The loser never
230 // seeds: only the goroutine whose INSERT actually won reaches
231 // seedIfEnabled below, so two simultaneous first sign-ins for
232 // the same address still produce exactly one set of sample
233 // documents, not two.
234 if errors.Is(err, gorm.ErrDuplicatedKey) {
235 if err2 := s.db.WithContext(ctx).Where("email = ?", email).First(&p).Error; err2 == nil {
236 return p.ID, nil
237 }
238 }
239 return 0, fmt.Errorf("docs: create person %q: %w", email, err)
240 }
241
242 s.seedIfEnabled(ctx, p.ID, email)
243 return p.ID, nil
244}
245
246// seedIfEnabled seeds newOwner's document list with CARLOS Docs' own
247// sample content, when this instance has opted in
248// (Config.SampleDocuments, threaded through as Store.sampleDocuments)
249// — called only from EnsurePerson's just-created-the-row branch above,
250// never from its found-an-existing-row branch, and never called twice
251// for the same person: EnsurePerson's own doc comment has the full
252// reasoning for why that hook point is the one that gives "seed once,
253// per person, ever" for free rather than needing its own bookkeeping.
254//
255// This runs after the Create above has already returned nil — not
256// wrapped in a transaction of its own, and deliberately not folded
257// into a transaction around Create either (there isn't one today:
258// that INSERT already autocommits on its own). Seed's own work below
259// is six Store.Create calls, six Store.ApplyUpdate calls — each of
260// which replays a document's update log and applies a fresh one
261// through internal/core's WebAssembly runtime, not a trivial
262// in-transaction operation — and six backdating UPDATEs. Holding all
263// of that, plus the person row's own INSERT, inside one atomic unit
264// would mean a slow seed holds whatever locks SQLite takes for the
265// duration, and would mean a seed failure could take the newly
266// created person row down with it on rollback. Neither is
267// acceptable: a person's own row must be durable the moment Create
268// above succeeds, regardless of what happens next.
269//
270// So the error boundary sits here, not in Seed and not in
271// EnsurePerson's return: a failure is logged, with the address and
272// the new person id for context, and then dropped on the floor.
273// EnsurePerson still returns (p.ID, nil) no matter what happens in
274// here. A person who cannot sign in because their sample content
275// failed to generate is a far worse outcome than a person who signs
276// in to an empty list — the second is this feature not having worked
277// yet; the first is this feature having broken sign-in, which is the
278// exact failure this whole plan exists to fix, not reintroduce.
279func (s *Store) seedIfEnabled(ctx context.Context, newOwner int64, email string) {
280 if s.team != nil || !s.sampleDocuments {
281 return
282 }
283 if s.seedOnlyMembers != nil && !s.seedOnlyMembers(email) {
284 return
285 }
286 if err := Seed(ctx, s, localActor(newOwner, email)); err != nil {
287 s.logger.Error("docs: seed sample documents for new person", "person", newOwner, "address", email, "err", err)
288 }
289}
290
291// Create makes a new document owned by owner: a GUID and a client id
292// assigned here by the app (never drawn from yrs — see Document's doc
293// comment) and stored, an app-generated sqid, and the given title. It
294// does not touch the CRDT core at all: an empty document needs no
295// update log entry, and Text/ApplyUpdate are what open a core handle
296// when there is work for one to do.
297//
298// owner is always a Person id the caller already resolved from the
299// signed-in session (handlers.go's owner helper, or TestPerson in
300// tests) — never a value read off the request body. rastrillo
301// SKILL.md §3: "Creating takes the owner from the session, never the
302// form."
303func (s *Store) Create(ctx context.Context, owner int64, title string) (*Document, error) {
304 return s.CreateDraft(ctx, owner, title, "")
305}
306
307// CreateDraft makes retries after a lost acknowledgement return the same document.
308// The token is scoped to the authenticated owner, never a document capability.
309//
310// A new document is on the team rung (spec §8.2.1, Paul 2026-11-01: "New docs
311// Team, old private"); its owner makes it private from the share page.
312func (s *Store) CreateDraft(ctx context.Context, owner int64, title, token string) (*Document, error) {
313 return s.createDocument(ctx, owner, title, token, VisibilityTeam)
314}
315
316// createDocument is CreateDraft with the rung chosen by the caller: team for
317// every document a person makes, private for the sample library (seed.go),
318// which is one person's welcome content and would otherwise sit in every
319// member's list. Creation writes its first revision (random, newRevision)
320// and its suite_feed row in the same transaction as the document.
321func (s *Store) createDocument(ctx context.Context, owner int64, title, token string, visibility Visibility) (*Document, error) {
322 if !visibility.valid() {
323 return nil, fmt.Errorf("docs: create document: unknown visibility %q", visibility)
324 }
325 actor := s.ownerActor(ctx, owner)
326 if err := s.requireMember(ctx, actor); err != nil {
327 return nil, err
328 }
329 guid := uuid.NewString()
330 // Initial content authors Yjs structs under this ID. Keep it in Yjs'
331 // uint32 client-ID range; a random int64 can exceed JS integer precision.
332 clientID := uint64(mrand.Uint32N(math.MaxUint32)) + 1
333 now := time.Now().UTC()
334
335 revision, err := newRevision(noRevisionTaken)
336 if err != nil {
337 return nil, err
338 }
339
340 var lastErr error
341 for attempt := 0; attempt < maxSqidAttempts; attempt++ {
342 sqid, err := newSqid()
343 if err != nil {
344 return nil, err
345 }
346 doc := &Document{
347 Sqid: sqid,
348 Title: title,
349 OwnerID: owner,
350 GUID: guid,
351 ClientID: clientID,
352 Visibility: visibility,
353 // Random, as every later revision is (newRevision): a
354 // restore never reissues a value.
355 Revision: revision,
356 CreatedAt: now,
357 UpdatedAt: now,
358 }
359 err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
360 if err := s.requireMember(ctx, actor); err != nil {
361 return err
362 }
363 if token != "" {
364 var existing Document
365 err := tx.Where("owner_id = ? AND creation_token = ?", owner, token).First(&existing).Error
366 if err == nil {
367 if existing.DeletedAt != nil {
368 return gorm.ErrRecordNotFound
369 }
370 *doc = existing
371 return s.requireMember(ctx, actor)
372 }
373 if !errors.Is(err, gorm.ErrRecordNotFound) {
374 return err
375 }
376 doc.CreationToken = &token
377 }
378 if err := tx.Create(doc).Error; err != nil {
379 return err
380 }
381 if err := announce(tx, doc.ID, doc.Revision, false); err != nil {
382 return err
383 }
384 return s.requireMember(ctx, actor)
385 })
386 if err == nil {
387 return doc, nil
388 }
389 lastErr = err
390 if !errors.Is(err, gorm.ErrDuplicatedKey) {
391 break
392 }
393 }
394 return nil, fmt.Errorf("docs: create document: %w", lastErr)
395}
396
397// List returns every one of owner's non-deleted documents, newest
398// first — "newest" meaning most recently touched (UpdatedAt), the same
399// clock handlers.go's groupByRecency/formatWhen bucket and display,
400// and the one ApplyUpdate now bumps on every applied update. Ordering
401// by CreatedAt instead (fix round 2's own bug: they agreed only by
402// accident, because nothing bumped UpdatedAt away from CreatedAt) let
403// this list and its own recency buckets disagree the moment a
404// document's UpdatedAt ever moved without a matching reorder here —
405// see store_test.go's TestListOrdersByUpdatedAt.
406//
407// A document owner does not own is not in this list — not filtered
408// out afterward, never selected in the first place, through owned
409// above.
410func (s *Store) List(ctx context.Context, owner int64) ([]*Document, error) {
411 var docs []*Document
412 err := s.permissionScope(ctx, s.db.WithContext(ctx), s.ownerActor(ctx, owner), permissionOwner).
413 Where("deleted_at IS NULL").
414 Order("updated_at DESC, id DESC").
415 Find(&docs).Error
416 if err != nil {
417 return nil, fmt.Errorf("docs: list documents: %w", err)
418 }
419 s.rememberResponse(ctx, permissionOwner, docs...)
420 return docs, nil
421}
422
423// Get looks up one of owner's documents by its sqid. A sqid that
424// exists but belongs to someone else is indistinguishable from a sqid
425// that does not exist at all — both return gorm.ErrRecordNotFound
426// through owned above, never a distinct "yes, but not yours" outcome —
427// which is what lets handlers.go answer 404 and never 403 for a
428// document (spec §4.2).
429func (s *Store) Get(ctx context.Context, owner int64, sqid string) (*Document, error) {
430 var doc Document
431 err := s.permissionScope(ctx, s.db.WithContext(ctx), s.ownerActor(ctx, owner), permissionOwner).
432 Where("sqid = ? AND deleted_at IS NULL", sqid).
433 First(&doc).Error
434 if err != nil {
435 return nil, s.permissionError(ctx, s.ownerActor(ctx, owner), fmt.Errorf("docs: get document %q: %w", sqid, err))
436 }
437 s.rememberResponse(ctx, permissionOwner, &doc)
438 return &doc, nil
439}
440
441// replay opens a fresh core.Handle for doc (guid and client id come
442// from the stored row, never from yrs — see Document) and rebuilds the
443// document's CRDT state into it: the newest usable snapshot, then only
444// the doc_updates rows after it, in seq order. With no usable snapshot
445// it applies every row instead. The caller owns the returned Handle
446// and must Close it.
447//
448// Snapshot-then-tail is the snapshots design's D6. It is what keeps
449// the retained-update count in a core.Handle clear of
450// core.MaxRetainedUpdates: while snapshot writes keep succeeding,
451// replay is one snapshot plus roughly snapshotCadence updates, so the
452// cliff ErrUpdateLogFull describes stops being reachable in the
453// ordinary case. That bound is conditional on those writes, and
454// snapshotCadence's own comment says what it costs when they stop
455// succeeding. The export it restores
456// from (ABI v4's docs_core_snapshot_len/read, via core.Handle.Snapshot)
457// is exactly the one core.go's maxRetainedUpdates comment asks for;
458// ApplyUpdate below is the host caller that persists it.
459//
460// A snapshot is an accelerator, never the source of truth (D2).
461// doc_updates keeps every row, and any snapshot that cannot be read —
462// unloadable row, bytes the core refuses, an ABI newestSnapshot
463// already filters out — is discarded and the whole log replayed
464// instead. That fallback is slower and always correct, which is the
465// bar every failure path in this file is held to.
466//
467// Slower, and correct even for a log longer than
468// core.MaxRetainedUpdates — which snapshots themselves made possible,
469// since before them ApplyUpdate refused once a handle filled and no log
470// could grow past the cap. A full-log replay of such a document would
471// meet core.ErrUpdateLogFull partway through and fail, leaving the
472// document unreadable AND unwritable (ApplyUpdate returns here, before
473// the writeSnapshot that would repair it). It would take one ABI bump
474// to do that to every long document at once, newestSnapshot's ABI
475// filter being exact. So the tail loop below does not fail there: it
476// re-seeds a fresh handle from the state it has reached, in memory,
477// and carries on. See reseedForReplay.
478//
479// The two seqs come back with the handle rather than being asked for
480// again: replayedSeq is the highest seq this replay actually
481// incorporated (the last row applied, or the snapshot's own seq when
482// the tail was empty), and lastSnapshotSeq is the seq of the snapshot
483// it started from, or 0 when it started from nothing — including when
484// a snapshot existed but was discarded, so the next write repairs it.
485// ApplyUpdate's cadence check is the difference between them, computed
486// from rows already read and never from a second query — the same
487// discipline the live-sync design's D2 sets for Docs-Seq, for the same
488// reason. Text, HTML and JSON below discard both: reading a document
489// never writes a snapshot, because a snapshot is only ever taken on
490// the write path (D3), where a request has already proved the instance
491// is awake.
492func (s *Store) replay(ctx context.Context, doc *Document) (h *core.Handle, replayedSeq int64, lastSnapshotSeq int64, err error) {
493 h, err = s.core.NewDoc(ctx, doc.GUID, doc.ClientID)
494 if err != nil {
495 return nil, 0, 0, fmt.Errorf("docs: open core handle for document %d: %w", doc.ID, err)
496 }
497
498 // A snapshot that cannot even be read out of the database is not
499 // an error to return: the log alone reproduces the document, so
500 // this is logged and abandoned rather than propagated.
501 snap, snapErr := s.newestSnapshot(ctx, doc.ID)
502 if snapErr != nil {
503 s.logger.Error("docs: load newest snapshot, replaying the whole log instead", "doc_id", doc.ID, "err", snapErr)
504 snap = nil
505 }
506 if snap != nil {
507 if applyErr := h.Apply(ctx, snap.State); applyErr != nil {
508 s.logger.Error("docs: apply snapshot, replaying the whole log instead", "doc_id", doc.ID, "snapshot_seq", snap.Seq, "err", applyErr)
509 // The handle is discarded along with the snapshot rather
510 // than reused. Handle.Apply leaves the instance usable
511 // after a clean rejection and rebuilds it after a trap,
512 // but its third shape — a rebuild that itself failed —
513 // makes no such promise, and a fresh NewDoc on this
514 // already-exceptional path costs less than reasoning
515 // about which shape this was.
516 h.Close(ctx)
517 snap = nil
518 h, err = s.core.NewDoc(ctx, doc.GUID, doc.ClientID)
519 if err != nil {
520 return nil, 0, 0, fmt.Errorf("docs: reopen core handle for document %d after a bad snapshot: %w", doc.ID, err)
521 }
522 }
523 }
524
525 tail := s.db.WithContext(ctx).Where("doc_id = ?", doc.ID)
526 if snap != nil {
527 lastSnapshotSeq = snap.Seq
528 replayedSeq = snap.Seq
529 tail = tail.Where("seq > ?", snap.Seq)
530 }
531
532 var updates []DocUpdate
533 if err := tail.Order("seq ASC").Find(&updates).Error; err != nil {
534 h.Close(ctx)
535 return nil, 0, 0, fmt.Errorf("docs: load updates for document %d: %w", doc.ID, err)
536 }
537
538 for _, u := range updates {
539 if err := s.openContentUpdate(doc.GUID, &u); err != nil {
540 h.Close(ctx)
541 return nil, 0, 0, err
542 }
543 applyErr := h.Apply(ctx, u.UpdateBin)
544 if errors.Is(applyErr, core.ErrUpdateLogFull) {
545 // This handle has retained core.MaxRetainedUpdates updates
546 // and will accept no more, but the document is not over —
547 // there are rows left, and reaching them is the difference
548 // between a slow document and an unreadable one. So the
549 // replay continues in a fresh handle re-seeded from this
550 // one's state; see reseedForReplay.
551 //
552 // u itself was NOT applied: Handle.Apply's cap check is its
553 // first statement and returns before it touches the guest,
554 // so this row is still owed and is applied below, into the
555 // fresh handle, exactly once.
556 //
557 // Warn, not Error, and not silence either. Not Error,
558 // because nothing is wrong with the document: it is
559 // complete, correct and merely slower to read (a re-seeding
560 // replay costs an apply per row, tens of milliseconds per
561 // thousand, against about a millisecond for snapshot plus a
562 // short tail), and this document's next write repairs it
563 // with an ordinary snapshot. That is precisely the
564 // distinction an operator needs — this line means "slow,
565 // self-healing", where the two Error lines above mean "a
566 // snapshot is unusable".
567 //
568 // And not silence, which is what this was at first, on the
569 // reasoning that the next write clears it. That reasoning
570 // assumes a write arrives. Reads write nothing (D3: Text,
571 // HTML and JSON discard both seqs), so a long document that
572 // is finished and only ever read again — a large share of
573 // what an ABI bump invalidates at once — re-seeds on every
574 // single read, forever, with latency as the only evidence.
575 // One line per read is the price of that not being invisible.
576 s.logger.Warn("docs: replay past the retained-update cap, re-seeding a fresh handle and continuing; slower until the next write writes a snapshot",
577 "doc_id", doc.ID, "seq", u.Seq)
578
579 h, err = s.reseedForReplay(ctx, doc, h, u.Seq)
580 if err != nil {
581 return nil, 0, 0, err
582 }
583 applyErr = h.Apply(ctx, u.UpdateBin)
584 }
585 if applyErr != nil {
586 h.Close(ctx)
587 // Surfaced, not swallowed: whether this is a clean
588 // rejection, core.ErrUpdateLogFull, or a *core.RecoveredError
589 // (the specific update's outcome unknown, never retried —
590 // see Handle.Apply's doc comment), the log this Store
591 // itself wrote can no longer be trusted to reproduce the
592 // document, and callers must see that rather than silently
593 // getting a wrong or truncated text back.
594 return nil, 0, 0, fmt.Errorf("docs: replay update seq %d for document %d: %w", u.Seq, doc.ID, applyErr)
595 }
596 replayedSeq = u.Seq
597 }
598 return h, replayedSeq, lastSnapshotSeq, nil
599}
600
601// reseedForReplay returns a fresh handle holding everything full holds,
602// so a replay that has exhausted full's retained-update budget
603// (core.MaxRetainedUpdates, core.ErrUpdateLogFull) can carry on instead
604// of failing. full is closed either way; on any error the fresh handle
605// is closed too and nothing is returned for the caller to close.
606//
607// The mechanism is the one this whole feature is built on, used
608// in memory rather than through the database: full.Snapshot encodes its
609// entire state as one Yjs update (Handle.Snapshot, ABI v4's
610// docs_core_snapshot_len/read), and applying that to an empty document
611// reproduces it — the same property doc_snapshots relies on, and the
612// one TestReSeedingMidReplayRendersTheSameDocument pins here. The fresh
613// handle's retained count is 1 afterwards, so the next
614// core.MaxRetainedUpdates rows fit and a log of any length gets through
615// in as many re-seeds as it needs. That also puts a ceiling on what a
616// replay retains regardless of how long the log is, which is what the
617// cap was protecting in the first place.
618//
619// Three things this deliberately does not do:
620//
621// It writes nothing. replay is the read path — Text, HTML and JSON all
622// go through it — and a read that wrote to the database would be a
623// different change with different consequences (D3 keeps snapshot
624// writes on the write path, where a request has already proved the
625// instance is awake). The persisted snapshot is still repaired the
626// ordinary way, and getting here guarantees it: reaching the cap means
627// more than core.MaxRetainedUpdates rows sat past whatever this replay
628// started from, so replayedSeq-lastSnapshotSeq is past snapshotCadence
629// by a factor of sixteen, and this document's next ApplyUpdate runs
630// writeSnapshot — at the current ABI, which is what an ABI bump needs.
631//
632// It invents no identity. The fresh handle is opened exactly as replay
633// opens its first one, from the stored row's GUID and ClientID, so the
634// CRDT library is never a source of entropy here either (see Document).
635//
636// It never continues on a failure. If the snapshot, the fresh handle or
637// its re-seeding fails, this returns the error rather than carrying on
638// with full — carrying on would meet ErrUpdateLogFull again on the very
639// next row and reintroduce the failure one row later, with the cause
640// two frames further away. Every message names the document and the seq
641// the replay had reached, because this is the one path here where an
642// operator has to go and look at a specific document.
643func (s *Store) reseedForReplay(ctx context.Context, doc *Document, full *core.Handle, atSeq int64) (*core.Handle, error) {
644 state, err := full.Snapshot(ctx)
645 if err != nil {
646 full.Close(ctx)
647 return nil, fmt.Errorf("docs: replay of document %d reached the retained-update cap at seq %d and could not snapshot its own state to continue: %w", doc.ID, atSeq, err)
648 }
649
650 fresh, err := s.core.NewDoc(ctx, doc.GUID, doc.ClientID)
651 full.Close(ctx)
652 if err != nil {
653 return nil, fmt.Errorf("docs: replay of document %d reached the retained-update cap at seq %d and could not open a fresh core handle to continue: %w", doc.ID, atSeq, err)
654 }
655 if err := fresh.Apply(ctx, state); err != nil {
656 fresh.Close(ctx)
657 return nil, fmt.Errorf("docs: replay of document %d reached the retained-update cap at seq %d and could not re-seed a fresh handle from its own state: %w", doc.ID, atSeq, err)
658 }
659 return fresh, nil
660}
661
662// Text returns doc's current text — read from the real CRDT core by
663// replaying its update log, never from a database column.
664func (s *Store) Text(ctx context.Context, doc *Document) (string, error) {
665 h, _, _, err := s.replay(ctx, doc)
666 if err != nil {
667 return "", err
668 }
669 defer h.Close(ctx)
670
671 text, err := h.Text(ctx)
672 if err != nil {
673 return "", fmt.Errorf("docs: read text for document %d: %w", doc.ID, err)
674 }
675 return text, nil
676}
677
678// HTML returns doc's current content rendered as HTML — read from the
679// real CRDT core by replaying its update log, never from a database
680// column. Mirrors Text exactly (same replay through s.replay, same
681// defer h.Close(ctx)); the only difference is the core call this
682// makes once the handle is open (h.HTML instead of h.Text) and the
683// wrapping return type.
684//
685// Returning template.HTML rather than string is deliberate, not a
686// convenience: core/src/fragment.rs escapes every text run and emits
687// no attributes at all (Task 2's renderer), so this markup is safe to
688// place in a template unescaped — and the typed return is where that
689// "this is trusted markup" decision is made, once, next to the
690// escaping that earns it, rather than left for views/show.html to
691// assert with a {{ ... | html }} pipeline of its own.
692func (s *Store) HTML(ctx context.Context, doc *Document) (template.HTML, error) {
693 h, _, _, err := s.replay(ctx, doc)
694 if err != nil {
695 return "", err
696 }
697 defer h.Close(ctx)
698
699 html, err := h.HTML(ctx)
700 if err != nil {
701 return "", fmt.Errorf("docs: read html for document %d: %w", doc.ID, err)
702 }
703 return template.HTML(html), nil
704}
705
706// Page returns both of what a document page needs from one replay: the
707// HTML it shows, and the structure internal/export reads the faces it
708// will be set in from (fontgate.go). Two replays would be the same work
709// twice on every page view.
710func (s *Store) Page(ctx context.Context, doc *Document) (template.HTML, string, error) {
711 h, _, _, err := s.replay(ctx, doc)
712 if err != nil {
713 return "", "", err
714 }
715 defer h.Close(ctx)
716
717 html, err := h.HTML(ctx)
718 if err != nil {
719 return "", "", fmt.Errorf("docs: read html for document %d: %w", doc.ID, err)
720 }
721 structure, err := h.JSON(ctx)
722 if err != nil {
723 return "", "", fmt.Errorf("docs: read structure for document %d: %w", doc.ID, err)
724 }
725 return template.HTML(html), structure, nil
726}
727
728// JSON returns doc's structure as ProseMirror-shaped JSON — the same
729// replay through the same core as Text and HTML above, reading the
730// third renderer instead (core/src/fragment.rs's fragment_json).
731//
732// Returns a plain string, not template.HTML: this is never written
733// into a page. It goes to internal/export, which decodes it and lays
734// out Markdown or a PDF from the tree, and the trust decision HTML's
735// typed return records has no counterpart here — a JSON string that
736// reached a template would need escaping like any other data.
737func (s *Store) JSON(ctx context.Context, doc *Document) (string, error) {
738 h, _, _, err := s.replay(ctx, doc)
739 if err != nil {
740 return "", err
741 }
742 defer h.Close(ctx)
743
744 structure, err := h.JSON(ctx)
745 if err != nil {
746 return "", fmt.Errorf("docs: read structure for document %d: %w", doc.ID, err)
747 }
748 return structure, nil
749}
750
751// updateRejection wraps whatever error Handle.Apply(update) itself
752// returned for the update just submitted to ApplyUpdate below — never
753// for a failure while replay (above) rebuilds this document's
754// existing history, and never for an ordinary database error further
755// down in ApplyUpdate. It exists purely so a caller outside this
756// package (handlers.go's updatesPost, fix round 1 on Task 5) can tell
757// "the core said no to the bytes the client just sent" apart from
758// "something on our own end broke", using core.Recovered/core.Rejected/
759// errors.Is(..., core.ErrUpdateLogFull) on the unwrapped error, without
760// mistaking a failure from replay for one — replay calls the exact
761// same core.Handle.Apply, on the exact same *core.Handle, and would
762// satisfy those same checks if it were not kept structurally distinct
763// from this wrapper. A replay failure means EXISTING, already-accepted
764// history came back corrupted or unreplayable — never the client's
765// fault, regardless of what shape the underlying core error happens to
766// take — so it is deliberately never given this wrapper.
767type updateRejection struct{ err error }
768
769func (e *updateRejection) Error() string { return e.err.Error() }
770func (e *updateRejection) Unwrap() error { return e.err }
771
772// currentSeq reports the highest seq in doc's update log, or 0 for a
773// document nothing has been written to yet.
774//
775// This is the stream handler's connect-time answer (stream.go) and
776// nothing else reads it. Note what it is NOT for: filling the
777// Docs-Seq header on GET /d/{sqid}/updates. That header is derived
778// from the rows being returned, precisely so that no query like this
779// one can observe a row the response does not carry — see the design
780// spec's D2 for the update that would otherwise go missing.
781func (s *Store) currentSeq(ctx context.Context, docID int64) (int64, error) {
782 var seq int64
783 if err := s.db.WithContext(ctx).
784 Model(&DocUpdate{}).
785 Where("doc_id = ?", docID).
786 Select("COALESCE(MAX(seq), 0)").
787 Scan(&seq).Error; err != nil {
788 return 0, fmt.Errorf("docs: current seq for document %d: %w", docID, err)
789 }
790 return seq, nil
791}
792
793// ApplyUpdate applies a new Yjs update to doc: it replays the
794// existing log to rebuild current state, applies update against that
795// live core instance, and only once the core has accepted it does it
796// persist the update as the next row in doc_updates. A rejection from
797// the core (a clean rejection, core.ErrUpdateLogFull, or a
798// *core.RecoveredError) is returned as-is, wrapped in *updateRejection
799// (above) so a caller can positively identify it as such, and the
800// update is never persisted — see the errors.Is-friendly wrapping in
801// replay's doc comment and Handle.Apply's for why an uncertain outcome
802// must not be written down as a fact.
803//
804// Before any of that, doc.OwnerID is verified against the row itself.
805// Fix round 2 on this task (Finding 1 again, this time for real): the
806// previous fix scoped only the trailing updated_at bump through
807// owned(doc.OwnerID), on the theory that it was "the one write in this
808// file that skipped the seam." That was wrong — the doc_updates INSERT
809// above (and the MAX(seq) query that sizes it) is keyed on doc.ID
810// alone and always has been, and it runs long before the bump. Scoping
811// only the last write meant a *Document carrying a stranger's OwnerID
812// still replayed, applied and persisted the content; only the
813// timestamp was refused, and a gorm UPDATE matching zero rows returns
814// no error, so the whole call returned nil. Content wrote, silently,
815// on a mismatched owner.
816//
817// The honest fix is not to scope some subset of the writes below — it
818// is to refuse the entire operation before any of them run. doc is a
819// value a caller can construct or mutate freely (as the regression
820// test below does); it is not a database guarantee. Store.Get is
821// reader-scoped, so doc.OwnerID is trustworthy *when doc came from
822// Get* — but nothing at this call site enforces that it did, which is
823// the entire defect. So rather than trust the struct, this re-derives
824// ownership from the database itself: look up document doc.ID through
825// the same owned(doc.OwnerID) seam every other query in this file
826// uses, and require the row to exist. owned's owner <= 0 rule (see
827// its own doc comment) still applies unchanged here: an orphaned
828// document with owner_id 0 cannot be "owned" by any doc.OwnerID,
829// including a tampered 0, so it can never pass this check and this
830// route can never make an orphan writable. A mismatched or missing
831// owner makes the Where match zero rows, First returns
832// gorm.ErrRecordNotFound, and this method returns before replay is
833// even called — no core touched, no row written.
834//
835// AN INVARIANT THIS METHOD OWNS, written down because something now
836// depends on it: every write that changes a document's content bumps
837// its updated_at. The document list's thumbnail cache (preview.go) is
838// keyed on that column, so a content write that left it alone would
839// serve a preview of the document as it used to be, with nothing
840// anywhere raising a hand. Today this is the only content write, so
841// the invariant holds by having one writer; the writes that will test
842// it are version restore (spec §14) and any future log compaction.
843// Both must also drop the document's warm handle (warm.go, rule 6): a
844// rewrite that leaves MAX(seq) where it was is invisible to rule 3.
845// Note also that this bumps the COLUMN and not the *Document it was
846// handed — a caller holding that struct has a stale UpdatedAt, which
847// is why the cache takes its key from the row Store.List returned.
848func (s *Store) ApplyUpdate(ctx context.Context, doc *Document, actor Actor, update []byte) (int64, error) {
849 // Authorize the ACTOR, not the document.
850 //
851 // This check used to be owned(db, doc.OwnerID).Where("id = ?", doc.ID) —
852 // the document against its own owner, which is true of every document by
853 // construction. That was harmless only because the sole way to hold a
854 // *Document was to have fetched it through a scoped query, so this
855 // was a belt on top of the read scope's braces. Sharing removes that
856 // guarantee: a reader can now legitimately fetch a document, and the old
857 // check would have waved their write through, because it never asked
858 // anything about the person doing the writing.
859 //
860 // Reader and stranger are refused identically. The write path does not
861 // tell somebody which of the two they are, for the same reason §4.2 gives
862 // about reads.
863 if err := s.checkPermission(ctx, s.db.WithContext(ctx), actor, doc.ID, permissionWrite); err != nil {
864 return 0, err
865 }
866 // A warm handle when this Store keeps them (warm.go, the live-push
867 // spec's §3.5); otherwise, and as its own fallback, the replay below.
868 if s.warm != nil {
869 return s.applyWarm(ctx, doc, actor, update)
870 }
871 return s.applyCold(ctx, doc, actor, update)
872}
873
874// applyCold is ApplyUpdate as it has always been: replay the document,
875// snapshot at the cadence, apply, commit. The caller has checked write
876// permission.
877func (s *Store) applyCold(ctx context.Context, doc *Document, actor Actor, update []byte) (int64, error) {
878 h, replayedSeq, lastSnapshotSeq, err := s.replay(ctx, doc)
879 if err != nil {
880 return 0, err
881 }
882 defer h.Close(ctx)
883
884 // The snapshot is taken HERE — from the replayed state, before the
885 // incoming update is applied — and the placement is the whole of
886 // its correctness (the snapshots design, D3).
887 //
888 // Taking it after a successful Apply is wrong twice. The replay
889 // above runs outside the transaction below, so a concurrent POST
890 // can commit a row this handle never saw; a snapshot taken from
891 // that handle would claim a seq whose content it does not hold,
892 // and D5's verification cannot notice, because it compares the
893 // candidate against this same stale handle. And a document already
894 // at core.MaxRetainedUpdates never reaches an after-success hook
895 // at all — Apply refuses with ErrUpdateLogFull first — so the one
896 // case this feature exists for would stay broken forever. Written
897 // here, that document gets its snapshot, fails this one POST, and
898 // the client's own retry replays snapshot plus an empty tail and
899 // succeeds.
900 //
901 // The replayed prefix is complete by construction: seq is gapless
902 // (MAX+1 inside the single-writer transaction below) and replay
903 // read every row that existed when it ran. So replayedSeq is
904 // unconditionally truthful about what the handle holds.
905 if replayedSeq-lastSnapshotSeq >= snapshotCadence {
906 if err := s.writeSnapshot(ctx, doc, h, replayedSeq); err != nil {
907 if s.team != nil {
908 if errors.Is(err, ErrNotWritable) {
909 return 0, err
910 }
911 return 0, errTeamUnavailable
912 }
913 // Never fatal: the update below still stands, the log is
914 // untouched, and the next POST tries again — and so does
915 // every one after it, since the distance only grows until
916 // a write succeeds. Error rather than Warn because the
917 // headroom that keeps ErrUpdateLogFull unreachable is
918 // spent by roughly fifteen consecutive failures here (D4).
919 s.logger.Error("docs: write snapshot", "doc_id", doc.ID, "seq", replayedSeq, "err", err)
920 }
921 }
922
923 if err := h.Apply(ctx, update); err != nil {
924 return 0, fmt.Errorf("docs: apply update to document %d: %w", doc.ID, &updateRejection{err})
925 }
926 seq, _, err := s.commitUpdate(ctx, doc, actor, update)
927 return seq, err
928}
929
930// commitUpdate writes update as doc's next row, in the single-writer
931// transaction, and returns the seq it was given and the log's MAX(seq)
932// before it (which a warm handle compares with its own). Both paths of
933// ApplyUpdate end here, so there is one transaction to reason about.
934func (s *Store) commitUpdate(ctx context.Context, doc *Document, actor Actor, update []byte) (int64, int64, error) {
935 // MAX(seq) then INSERT used to be two separate statements, not one
936 // atomic step: two concurrent POSTs to this same document (Task 6's
937 // flush timer and its beforeunload beacon are exactly the pair that
938 // races on a real page close) could both read the same MAX(seq)
939 // before either had committed its own INSERT, and both then write
940 // the same (doc_id, seq) pair. doc_updates' UNIQUE(doc_id, seq)
941 // index (migration 0003) is the backstop that would turn a second
942 // such bug into a loud error instead of silent duplicate data, but
943 // the actual fix is this transaction: rastrillo/db's pool (db.go's
944 // own doc comment) caps the WRITE pool at exactly one connection —
945 // SQLite allows one writer — and gorm.DB.Transaction always opens
946 // on that pool's underlying *sql.DB, never on the read replicas
947 // dbresolver would otherwise route a bare SELECT to. With only one
948 // connection available, a second concurrent call to this method
949 // cannot even begin its own transaction until this one commits and
950 // releases it — so by the time that second transaction's SELECT
951 // MAX(seq) runs, it is guaranteed to see this row already
952 // committed. That is a stronger guarantee than retrying on a
953 // UNIQUE-constraint collision (the migration's own alternative):
954 // a bounded retry loop can still be exhausted once enough requests
955 // race the same document at once, so a busy document would start
956 // returning errors under load that this queue-instead-of-fail
957 // approach never does — confirmed empirically: an earlier version
958 // of this fix used a 5-attempt retry loop, and
959 // updates_test.go's TestConcurrentUpdatesDoNotCollideOnSeq (21
960 // concurrent POSTs to one document) genuinely exhausted it on a
961 // real run before this transaction replaced it.
962 // assignedSeq is captured out of the transaction closure so this
963 // method can return it. It is only ever read after Transaction
964 // returns nil, so it names a row that is committed and durable —
965 // which is exactly the contract this method's callers rely on
966 // (design D4: the seq is meaningful only when err == nil). Nothing
967 // about the single-writer MAX(seq)->INSERT guarantee above changes
968 // by observing the number the closure already computed.
969 var assignedSeq, before int64
970 if err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
971 if err := s.checkPermission(ctx, tx, actor, doc.ID, permissionWrite); err != nil {
972 return err
973 }
974 var maxSeq int64
975 if err := tx.Model(&DocUpdate{}).
976 Where("doc_id = ?", doc.ID).
977 Select("COALESCE(MAX(seq), 0)").
978 Scan(&maxSeq).Error; err != nil {
979 return fmt.Errorf("docs: determine next seq for document %d: %w", doc.ID, err)
980 }
981
982 before = maxSeq
983 row := &DocUpdate{
984 DocID: doc.ID,
985 Seq: maxSeq + 1,
986 UpdateBin: update,
987 CreatedAt: time.Now().UTC(),
988 }
989 if err := s.prepareContentUpdate(tx, doc.GUID, row); err != nil {
990 return err
991 }
992 if err := tx.Create(row).Error; err != nil {
993 return fmt.Errorf("docs: persist update for document %d: %w", doc.ID, err)
994 }
995
996 if err := s.permissionScope(ctx, tx, actor, permissionWrite).Model(&Document{}).Where("documents.id = ?", doc.ID).Update("updated_at", time.Now().UTC()).Error; err != nil {
997 return s.permissionError(ctx, actor, err)
998 }
999 // The content changed, so a suite consumer must read it again.
1000 if err := bumpRevision(tx, doc.ID, false); err != nil {
1001 return err
1002 }
1003 assignedSeq = row.Seq
1004 // Live push (§3.4): who posted this row, recorded before commit so
1005 // a stream that reads the row always finds it.
1006 if o, ok := ctx.Value(postOriginKey{}).(postOrigin); ok && s.recordOrigin != nil {
1007 s.recordOrigin(doc.ID, assignedSeq, o, update)
1008 }
1009 if s.warmBeforeCommit != nil {
1010 if err := s.warmBeforeCommit(ctx, tx, doc); err != nil {
1011 return err
1012 }
1013 }
1014 return s.checkPermission(ctx, tx, actor, doc.ID, permissionWrite)
1015 }); err != nil {
1016 return 0, 0, err
1017 }
1018
1019 return assignedSeq, before, nil
1020}
1021
1022// Rename repeats write authorization within the transaction, as ApplyUpdate does.
1023func (s *Store) Rename(ctx context.Context, actor Actor, doc *Document, title string) error {
1024 if err := s.checkPermission(ctx, s.db.WithContext(ctx), actor, doc.ID, permissionWrite); err != nil {
1025 return err
1026 }
1027 return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
1028 if err := s.checkPermission(ctx, tx, actor, doc.ID, permissionWrite); err != nil {
1029 return err
1030 }
1031 if err := s.permissionScope(ctx, tx.Model(&Document{}), actor, permissionWrite).Where("documents.id = ? AND documents.deleted_at IS NULL", doc.ID).Updates(map[string]any{"title": title, "updated_at": time.Now().UTC()}).Error; err != nil {
1032 return err
1033 }
1034 // The title is the first line of what S3 serves.
1035 if err := bumpRevision(tx, doc.ID, false); err != nil {
1036 return err
1037 }
1038 return s.checkPermission(ctx, tx, actor, doc.ID, permissionWrite)
1039 })
1040}
1041