oficina / docs Public

Live push slice 1b: the stream carries the update bytes (DOCS_LIVE_PUSH, default off)

Spec 2026-11-26-live-push-design.md §3.1, §3.4, §3.6 (server side), §5,
§8; plan slice 1b. Off, push=1 is ignored and every client is on today's
path.
- stream.go: push=1 streams send hello <stream id> <current seq> <log
  epoch>, then the rows after Last-Event-ID or since (Last-Event-ID wins;
  400 on garbage) as push/own/update frames, one write and one flush per
  notification; without a cursor the connect-time update stays. Rows are
  read with updatesGet's query and openContentUpdate. A row over 32 KiB or
  unreadable is update (no id:), a client over 256 rows / 512 KiB behind
  gets one update for the current seq, and sent moves past both. bye ttl
  and bye drain before those closes; team-mode push streams end 2 s before
  their lease with bye lease.
- push.go: Docs-Stream "<stream id>.<counter>" counts only from the session
  that opened that stream (a hash of its session cookie or Authorization),
  on that document. commitUpdate records (doc, seq) -> (stream, counter,
  SHA-256 of the bytes) inside the transaction, so a stream reading the row
  always finds it, and own is written only on a matching id and hash. A
  per-document frame cache shares opened rows between streams (row reads
  -79% for 5 typists + 5 watchers; frames identical; CPU within noise).
  Late answers: over 30 updates/s per session per document, the next
  answer waits up to 1 s before ApplyUpdate takes the lock or the writer,
  ended by cancel or drain; at most 2 waiting per session, beyond that 503
  with Retry-After: 1 (never a 4xx).
- logepoch.go, migration 0013: the log epoch, rotated at a start that does
  not find the database where the last start left it (a boot counter in the
  database and in <db>.log-epoch). Not the spec's clean-shutdown marker,
  which would rotate at every overlapped deploy (CARLOS_SWAP=overlap); the
  spec is updated in the next commit. GET /updates carries Docs-Log-Epoch.
- cmd/docs: $DOCS_LIVE_PUSH on/off, unset off, anything else refuses to
  start. The gate's race step adds the push tests.
Tests: one POST -> one flushed push per watcher and own for the poster;
own only for the same session, stream and document, checked against the
row's bytes, and under concurrent writers; frames in seq order under 8
concurrent writers; resume from since and Last-Event-ID; hello and the
connect-time update; oversized and far-behind by fetch; bye ttl, drain and
lease (team mode); a reader receives and cannot post, and revocation ends
the stream; old clients unchanged with the switch on (Int64 data lines);
switch off; late answers (limiter and 503s); log epoch rotation (overlap,
restart, missing file, restored database); frame cache transparency; and
the relative timing gate (with a 20 ms round trip, POST -> bytes in hand
50.1 ms by the fetch path, 29.1 ms by push). Each was seen to fail with its
rule broken.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 0a5ed2769b3bb5a6e96a7375f53e082d110cae04 parent 2370192
14 files changed, +1,721 −17
  • .amadan/ci.d/10-gate +4 −3
  • cmd/docs/main.go +8 −0
  • internal/docs/app.go +15 −1
  • internal/docs/errors_test.go +2 −2
  • internal/docs/handlers.go +35 −1
  • internal/docs/hub.go +10 −0
  • internal/docs/logepoch.go +104 −0
  • internal/docs/migrations/0013_log_epoch.sql +11 −0
  • internal/docs/push.go +416 −0
  • internal/docs/push_test.go +992 −0
  • internal/docs/store.go +9 −0
  • internal/docs/stream.go +105 −8
  • internal/docs/testing.go +6 −0
  • internal/docs/warm.go +4 −2
diff --git a/.amadan/ci.d/10-gate b/.amadan/ci.d/10-gate
index b3ca718..0e05311 100755
--- a/.amadan/ci.d/10-gate
+++ b/.amadan/ci.d/10-gate
@@ -291,9 +291,10 @@ echo "=== go: race detector on warm handles and the stream"
# compiler; the runner already has one, since cargo links its host test
# binaries with it. Without one, this step fails loudly rather than skipping.
# Scoped to the code with its own locking: the warm-handle cache (warm.go,
-# the live-push spec's §3.5, including an 8-goroutine stress test) and the
-# stream. -short trims the 4,200-POST test, which needs no detector.
-CGO_ENABLED=1 go test -race -short -count=1 -run 'Warm|BoundToATransaction|Stream' ./internal/docs/
+# the live-push spec's §3.5, including an 8-goroutine stress test), the
+# stream, and live push (push.go: the stream and origin registries, the
+# frame cache, late answers). -short trims the 4,200-POST test, which needs no detector.
+CGO_ENABLED=1 go test -race -short -count=1 -run 'Warm|BoundToATransaction|Stream|Push|LateAnswers' ./internal/docs/
test -z "$(gofmt -l .)" || { echo "gate: gofmt"; gofmt -l .; exit 1; }
echo "=== go: build ./... (the app, not just the packages tests import)"
diff --git a/cmd/docs/main.go b/cmd/docs/main.go
index bd18046..7488c1b 100644
--- a/cmd/docs/main.go
+++ b/cmd/docs/main.go
@@ -265,6 +265,13 @@ func main() {
logger.Error("docs: refusing to start", "err", err)
os.Exit(1)
}
+ // $DOCS_LIVE_PUSH: let push=1 streams carry update bytes (the live-push
+ // spec's slice 1b). on/off; unset is off.
+ livePush, err := docs.ParseLivePush(os.Getenv("DOCS_LIVE_PUSH"))
+ if err != nil {
+ logger.Error("docs: refusing to start", "err", err)
+ os.Exit(1)
+ }
// $DOCS_SAMPLE_DOCUMENTS opts a deployed instance into
// docs.Config.SampleDocuments — see its own doc comment for the
@@ -319,6 +326,7 @@ func main() {
AllowedAddresses: allowedAddresses,
SampleDocuments: sampleDocuments,
WarmHandle: warmHandle,
+ LivePush: livePush,
Logger: logger,
// The hub directory the app switcher's "All apps" goes to. The
// same variable Home itself reads (home origins.go).
diff --git a/internal/docs/app.go b/internal/docs/app.go
index ed6d08a..571531f 100644
--- a/internal/docs/app.go
+++ b/internal/docs/app.go
@@ -51,6 +51,11 @@ type Config struct {
// every POST replays the document, as it always has. Off by default
// until slice 1a is proven on production, then on.
WarmHandle bool
+ // LivePush lets a stream opened with push=1 carry the update bytes
+ // ($DOCS_LIVE_PUSH, push.go; the live-push spec's §3.1-§3.4, §5, §8).
+ // Off, push=1 is ignored and every client is on today's path. Off by
+ // default.
+ LivePush bool
AgentIssuer string
AgentTeam string
@@ -488,6 +493,11 @@ func New(cfg Config) (*App, error) {
if cfg.WarmHandle {
store.warm = newWarmCache()
}
+ if store.logEpoch, err = loadLogEpoch(context.Background(), d.G, cfg.DBPath); err != nil {
+ rt.Close(context.Background())
+ d.Close()
+ return nil, err
+ }
if state != nil {
store.content = cipher
}
@@ -577,7 +587,11 @@ func New(cfg Config) (*App, error) {
d.Close()
return nil, err
}
- h = &handlers{render: render, logger: logger, store: store, hub: newHub(), previews: newPreviews(), origin: cfg.Origin, isMember: list.configured, oneShots: newOneShots(), directory: directory, google: cfg.GoogleImport, imports: make(chan struct{}, maxImportsAtOnce)}
+ h = &handlers{render: render, logger: logger, store: store, hub: newHub(), previews: newPreviews(), origin: cfg.Origin, isMember: list.configured, oneShots: newOneShots(), directory: directory, google: cfg.GoogleImport, imports: make(chan struct{}, maxImportsAtOnce),
+ livePush: cfg.LivePush, pushFrameCache: true, pushRegistry: newPushRegistry(), late: newLateAnswers(), pushStats: &pushStats{}}
+ if cfg.LivePush {
+ store.recordOrigin = h.pushRegistry.record
+ }
render.frame = h.frame
// peek: the viewer on routes no session guards (chrome.go). Standalone
// reads rastrillo/auth's own cookie; with Home, the Home bridge's.
diff --git a/internal/docs/errors_test.go b/internal/docs/errors_test.go
index dc51cd2..6ea7318 100644
--- a/internal/docs/errors_test.go
+++ b/internal/docs/errors_test.go
@@ -246,7 +246,7 @@ func TestEveryPlainTextErrorIsClassified(t *testing.T) {
"errors.go:handlers.recoverToErrorPage": {1, "the non-HTML half of a recovered panic"},
"errors.go:App.ErrorPage": {1, "the non-HTML half of rastrillo's recovered panic"},
"handlers.go:handlers.updatesGet": {3, "the update log, fetched by the editor"},
- "handlers.go:handlers.updatesPost": {9, "the update log, posted by the editor"},
+ "handlers.go:handlers.updatesPost": {10, "the update log, posted by the editor (and its late-answer 503, live push §5)"},
"handlers.go:parseSince": {1, "the update log's cursor"},
"home_return.go:returnMemory.guard": {1, "405 for a non-GET method"},
"home_connect.go:homeRoutes.render": {1, "connect's page before the handlers exist: unreachable once New returns"},
@@ -257,7 +257,7 @@ func TestEveryPlainTextErrorIsClassified(t *testing.T) {
"native.go:nativeJSON": {1, "native API JSON"},
"native.go:handlers.nativeList": {2, "native API JSON"},
"search.go:handlers.searchJSON": {3, "jump-to palette JSON"},
- "stream.go:handlers.stream": {7, "live update stream"},
+ "stream.go:handlers.stream": {8, "live update stream (and its 400 for a bad push cursor)"},
"team_access.go:teamRuntime.admission": {1, "shared guard, identity missing: a wiring failure, not a page state"},
"team_emission.go:writeGuardedBody": {1, "response already guarded"},
}
diff --git a/internal/docs/handlers.go b/internal/docs/handlers.go
index 6a43ce5..009bd4c 100644
--- a/internal/docs/handlers.go
+++ b/internal/docs/handlers.go
@@ -67,6 +67,17 @@ type handlers struct {
// sample seeding, which runs before any editor can be open.
hub *hub
+ // Live push (push.go; the live-push spec's slice 1b). livePush is
+ // $DOCS_LIVE_PUSH: off, a push=1 stream and every POST are exactly
+ // today's. pushFrameCache shares each document's recent rows, opened,
+ // between its streams. pushStats counts what the streams did.
+ livePush bool
+ pushFrameCache bool
+ pushRegistry *pushRegistry
+ late *lateAnswers
+ pushStats *pushStats
+ pushLeaseLead time.Duration // tests only; see leaseLead
+
// previews is the document list's thumbnail cache (preview.go).
// Here rather than on Store for the same reason hub is: Store is
// persistence, and a laid-out page of line boxes is presentation.
@@ -935,6 +946,11 @@ func (h *handlers) updatesGet(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Docs-Seq", strconv.FormatInt(highest, 10))
+ if h.livePush {
+ // A non-push client can check its cursor against the log's
+ // identity on its next fetch (§3.1, a rewound log).
+ w.Header().Set("Docs-Log-Epoch", h.store.logEpoch)
+ }
parts := make([][]byte, 0, len(updates)+1)
if snapshot != nil {
parts = append(parts, snapshot.State)
@@ -1032,7 +1048,25 @@ func (h *handlers) updatesPost(w http.ResponseWriter, r *http.Request) {
return
}
- seq, err := h.store.ApplyUpdate(r.Context(), doc, actor, update)
+ applyCtx := r.Context()
+ if h.livePush {
+ // §5: a session over the rate waits here, before ApplyUpdate takes
+ // the document's lock or the writer; too many waiting is a 503 the
+ // clients retry. Never a 4xx: the web save queue drops a 4xx batch.
+ if ok, busy := h.late.admit(r.Context(), h.hub.draining(), sessionBinding(r), doc.ID); !ok {
+ if busy || h.hub.isDraining() {
+ w.Header().Set("Retry-After", "1")
+ http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusServiceUnavailable)
+ }
+ return
+ }
+ // §3.4: a Docs-Stream header from this session's own push stream on
+ // this document is recorded with the row, inside its transaction.
+ if o, ok := h.pushRegistry.origin(r, doc.ID); ok {
+ applyCtx = context.WithValue(applyCtx, postOriginKey{}, o)
+ }
+ }
+ seq, err := h.store.ApplyUpdate(applyCtx, doc, actor, update)
if err != nil {
// A reader posting an update gets the same 404 a stranger gets —
// the same BODY too, which it did not used to be. This branch
diff --git a/internal/docs/hub.go b/internal/docs/hub.go
index f2a450b..157914d 100644
--- a/internal/docs/hub.go
+++ b/internal/docs/hub.go
@@ -56,6 +56,16 @@ func (h *hub) drain() {
// draining is closed once drain has been called.
func (h *hub) draining() <-chan struct{} { return h.done }
+// isDraining reports whether drain has been called.
+func (h *hub) isDraining() bool {
+ select {
+ case <-h.done:
+ return true
+ default:
+ return false
+ }
+}
+
// subscribe registers interest in docID and returns the channel to
// wait on plus the function that unregisters it. The channel is
// buffered one deep: it carries "something happened", not a queue of
diff --git a/internal/docs/logepoch.go b/internal/docs/logepoch.go
new file mode 100644
index 0000000..eceac45
--- /dev/null
+++ b/internal/docs/logepoch.go
@@ -0,0 +1,104 @@
+package docs
+
+// The log epoch (live-push spec §3.1). A client that holds a cursor into a
+// log that has since been rewound must resync from the start: a log
+// restored to 90 that has taken twenty commits since shows a client at 100
+// a current seq of 110, and without this it would skip the new 91-100.
+//
+// The spec asks for rotation "at startup whenever the process did not find
+// its own clean-shutdown marker". Built literally, that would rotate the
+// epoch at every deploy that overlaps generations (CARLOS_SWAP=overlap,
+// carlos/platform's zero-downtime spec): the new process starts before the
+// old one has drained and written its marker. So the marker is a boot
+// counter instead, held in the database (docs_log_epoch) and in a file
+// beside it (<db>.log-epoch), compared at every start:
+//
+// - equal: the database is the one the last start left; bump both, keep
+// the epoch. An ordinary deploy, overlapped or not, and a process
+// crash (which loses no committed row) keep it.
+// - the file missing (a new box or disk, a restore onto one), or naming
+// another epoch or boot (a database restored from a copy taken before
+// the last start): rotate.
+//
+// What neither scheme catches: a restore from a copy taken after the last
+// start, onto the same disk. The seq check (hello's seq below the
+// client's cursor) still covers a log that is behind; a restore runbook
+// can delete the file to force a rotation. Any operation that rewinds a
+// log (none exists yet; version restore will) must call rotateLogEpoch.
+
+import (
+ "context"
+ "crypto/rand"
+ "encoding/hex"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+
+ "gorm.io/gorm"
+)
+
+type logEpochRow struct {
+ ID int64 `gorm:"primaryKey"`
+ Epoch string
+ Boot int64
+}
+
+func (logEpochRow) TableName() string { return "docs_log_epoch" }
+
+func newLogEpoch() (string, error) {
+ b := make([]byte, 12)
+ if _, err := rand.Read(b); err != nil {
+ return "", err
+ }
+ return hex.EncodeToString(b), nil
+}
+
+// loadLogEpoch runs once at startup and returns the epoch this process
+// serves.
+func loadLogEpoch(ctx context.Context, db *gorm.DB, dbPath string) (string, error) {
+ sidecar := dbPath + ".log-epoch"
+ var row logEpochRow
+ err := db.WithContext(ctx).Where("id = 1").Limit(1).Find(&row).Error
+ if err != nil {
+ return "", fmt.Errorf("docs: read log epoch: %w", err)
+ }
+ keep := false
+ if row.ID == 1 {
+ if raw, err := os.ReadFile(sidecar); err == nil {
+ epoch, boot, ok := strings.Cut(strings.TrimSpace(string(raw)), " ")
+ n, err := strconv.ParseInt(boot, 10, 64)
+ keep = ok && err == nil && epoch == row.Epoch && n == row.Boot
+ }
+ }
+ if !keep {
+ epoch, err := newLogEpoch()
+ if err != nil {
+ return "", fmt.Errorf("docs: draw log epoch: %w", err)
+ }
+ row = logEpochRow{ID: 1, Epoch: epoch, Boot: row.Boot}
+ }
+ row.Boot++
+ if err := db.WithContext(ctx).Save(&row).Error; err != nil {
+ return "", fmt.Errorf("docs: write log epoch: %w", err)
+ }
+ tmp, err := os.CreateTemp(filepath.Dir(sidecar), ".log-epoch-*")
+ if err != nil {
+ return "", fmt.Errorf("docs: write %s: %w", sidecar, err)
+ }
+ if _, err := fmt.Fprintf(tmp, "%s %d\n", row.Epoch, row.Boot); err != nil {
+ tmp.Close()
+ os.Remove(tmp.Name())
+ return "", err
+ }
+ if err := tmp.Close(); err != nil {
+ os.Remove(tmp.Name())
+ return "", err
+ }
+ if err := os.Rename(tmp.Name(), sidecar); err != nil {
+ os.Remove(tmp.Name())
+ return "", fmt.Errorf("docs: write %s: %w", sidecar, err)
+ }
+ return row.Epoch, nil
+}
diff --git a/internal/docs/migrations/0013_log_epoch.sql b/internal/docs/migrations/0013_log_epoch.sql
new file mode 100644
index 0000000..0b79007
--- /dev/null
+++ b/internal/docs/migrations/0013_log_epoch.sql
@@ -0,0 +1,11 @@
+-- The log epoch (live-push spec §3.1, slice 1b): a random value a push
+-- stream's `hello` and every fetch's Docs-Log-Epoch carry, so a client whose
+-- cursor belongs to a log that has since been rewound (a restore, a move, a
+-- re-provisioned team) resyncs from the start. One row. boot counts the
+-- process starts that found the database where the last one left it; a
+-- copy of both beside the database file is how a start tells (logepoch.go).
+CREATE TABLE IF NOT EXISTS docs_log_epoch (
+ id INTEGER PRIMARY KEY CHECK (id = 1),
+ epoch TEXT NOT NULL,
+ boot INTEGER NOT NULL DEFAULT 0
+);
diff --git a/internal/docs/push.go b/internal/docs/push.go
new file mode 100644
index 0000000..70b9d60
--- /dev/null
+++ b/internal/docs/push.go
@@ -0,0 +1,416 @@
+package docs
+
+// Live push, slice 1b: the stream carries the update bytes
+// (docs/superpowers/specs/2026-11-26-live-push-design.md §3.1, §3.4, §5;
+// plan docs/superpowers/plans/2026-11-26-live-push.md). Behind
+// $DOCS_LIVE_PUSH: off, a `push=1` stream is exactly today's, and so is
+// every POST.
+//
+// What lives here:
+// - pushRegistry: the open push streams (id -> session binding and
+// document) and, per document, who posted each recent seq (seq ->
+// stream, counter, SHA-256 of the bytes), recorded inside the POST's
+// transaction (§3.4);
+// - pushFrames: the rows after a stream's cursor as hello/push/own/update
+// frames (§3.1), through an optional per-document frame cache;
+// - lateAnswers: the per-session pacing of §5.
+
+import (
+ "context"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "net/http"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+)
+
+const (
+ pushMaxRowBytes = 32 << 10 // a larger row goes by fetch (update)
+ pushMaxBehindRow = 256 // further behind than this: one update
+ pushMaxBehind = 512 << 10 // or than this many bytes
+ pushOriginsKept = 64 // seq -> origin entries per document
+ pushFrameCached = 64 // rows per document in the frame cache
+)
+
+// ParseLivePush reads $DOCS_LIVE_PUSH: on/off (also 1/0, true/false);
+// unset is off. Anything else is a startup refusal.
+func ParseLivePush(v string) (bool, error) { return parseOnOff("DOCS_LIVE_PUSH", v) }
+
+// sessionBinding identifies the session a request presents: a hash of its
+// session cookie (rastrillo's, which Home and the native apps' approved
+// sessions use too) or, failing that, its Authorization header. A stream
+// id is bound to it, so a Docs-Stream header from another session is
+// ignored (§3.4). Empty means nothing to bind to: that stream never gets
+// `own`.
+func sessionBinding(r *http.Request) string {
+ sum := sha256.New()
+ found := false
+ for _, c := range r.Cookies() {
+ if c.Name == "rastrillo_session" || c.Name == "__Host-rastrillo_session" {
+ sum.Write([]byte(c.Name + "=" + c.Value + ";"))
+ found = true
+ }
+ }
+ if !found {
+ if a := r.Header.Get("Authorization"); a != "" {
+ sum.Write([]byte(a))
+ found = true
+ }
+ }
+ if !found {
+ return ""
+ }
+ return hex.EncodeToString(sum.Sum(nil))
+}
+
+func newStreamID() string {
+ b := make([]byte, 16)
+ if _, err := rand.Read(b); err != nil {
+ panic("docs: stream id: " + err.Error())
+ }
+ return base64.RawURLEncoding.EncodeToString(b)
+}
+
+type pushStream struct {
+ session string
+ docID int64
+}
+
+type pushOrigin struct {
+ stream string
+ counter string
+ hash [32]byte
+}
+
+// postOrigin is what a POST's Docs-Stream header resolved to.
+type postOrigin struct {
+ stream string
+ counter string
+}
+
+type postOriginKey struct{}
+
+type pushRegistry struct {
+ mu sync.Mutex
+ streams map[string]pushStream
+ origins map[int64]map[int64]pushOrigin
+ frames map[int64]*frameCache
+}
+
+func newPushRegistry() *pushRegistry {
+ return &pushRegistry{streams: map[string]pushStream{}, origins: map[int64]map[int64]pushOrigin{}, frames: map[int64]*frameCache{}}
+}
+
+func (p *pushRegistry) open(id string, s pushStream) {
+ p.mu.Lock()
+ p.streams[id] = s
+ p.mu.Unlock()
+}
+
+func (p *pushRegistry) close(id string) {
+ p.mu.Lock()
+ delete(p.streams, id)
+ p.mu.Unlock()
+}
+
+// origin resolves a Docs-Stream header ("<stream id>.<counter>") on a POST
+// to docID: only a stream open on that document, bound to the same
+// session. Anything else is ignored, as if the header were absent.
+func (p *pushRegistry) origin(r *http.Request, docID int64) (postOrigin, bool) {
+ header := r.Header.Get("Docs-Stream")
+ id, counter, ok := strings.Cut(header, ".")
+ if !ok || id == "" || len(id) > 64 || counter == "" || len(counter) > 20 {
+ return postOrigin{}, false
+ }
+ if _, err := strconv.ParseUint(counter, 10, 64); err != nil {
+ return postOrigin{}, false
+ }
+ session := sessionBinding(r)
+ p.mu.Lock()
+ s, open := p.streams[id]
+ p.mu.Unlock()
+ if !open || s.docID != docID || session == "" || s.session != session {
+ return postOrigin{}, false
+ }
+ return postOrigin{stream: id, counter: counter}, true
+}
+
+// record notes who posted seq. Called inside the POST's transaction, before
+// commit, so a stream that reads the row always finds it (rows become
+// visible only at commit). A rolled-back transaction leaves an entry for a
+// seq that a later row may reuse; the hash keeps that from matching.
+func (p *pushRegistry) record(docID, seq int64, o postOrigin, update []byte) {
+ h := sha256.Sum256(update)
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ m := p.origins[docID]
+ if m == nil {
+ m = map[int64]pushOrigin{}
+ p.origins[docID] = m
+ }
+ m[seq] = pushOrigin{stream: o.stream, counter: o.counter, hash: h}
+ for k := range m {
+ if k <= seq-pushOriginsKept {
+ delete(m, k)
+ }
+ }
+}
+
+func (p *pushRegistry) lookup(docID, seq int64) (pushOrigin, bool) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ o, ok := p.origins[docID][seq]
+ return o, ok
+}
+
+// frameCache keeps recent rows of one document, opened, so W streams
+// woken by one POST read and unseal it once rather than W times (§4.2's
+// fan-out). Measured in slice 1b (TestLivePushFanoutProbe, 5 typists and
+// 5 watchers in one document): row reads fall ~79% (6,000 to ~1,270 for
+// 600 uploads) and the frames are identical (TestPushFrameCacheIsTransparent);
+// process CPU did not move beyond noise, so something else dominates a
+// flush. Kept on for the reads it saves SQLite. Rows are immutable once committed, so a cached row never
+// goes stale; the cache is bounded per document and dropped with the
+// document's last stream.
+type frameCache struct {
+ mu sync.Mutex
+ rows map[int64][]byte
+ refs int
+}
+
+func (p *pushRegistry) cacheFor(docID int64) *frameCache {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ c := p.frames[docID]
+ if c == nil {
+ c = &frameCache{rows: map[int64][]byte{}}
+ p.frames[docID] = c
+ }
+ c.refs++
+ return c
+}
+
+func (p *pushRegistry) releaseCache(docID int64) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if c := p.frames[docID]; c != nil {
+ c.refs--
+ if c.refs <= 0 {
+ delete(p.frames, docID)
+ }
+ }
+}
+
+func (c *frameCache) get(seq int64) ([]byte, bool) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ b, ok := c.rows[seq]
+ return b, ok
+}
+
+func (c *frameCache) put(seq int64, b []byte) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.rows[seq] = b
+ for k := range c.rows {
+ if k <= seq-pushFrameCached {
+ delete(c.rows, k)
+ }
+ }
+}
+
+// pushRow is one row read for a stream: its bytes, or why it has none.
+type pushRow struct {
+ seq int64
+ bytes []byte
+ unusable bool // could not be opened
+}
+
+// rowsAfter reads doc's rows after sent, in seq order, at most
+// pushMaxBehindRow+1 of them, through cache when it has them all. The
+// query and the opening are updatesGet's (§3.1: one code path for bytes).
+func (h *handlers) rowsAfter(ctx context.Context, doc *Document, sent int64, cache *frameCache) ([]pushRow, int64, error) {
+ var current int64
+ if err := h.store.db.WithContext(ctx).Model(&DocUpdate{}).Where("doc_id = ?", doc.ID).Select("COALESCE(MAX(seq), 0)").Scan(&current).Error; err != nil {
+ return nil, 0, err
+ }
+ if current <= sent {
+ return nil, current, nil
+ }
+ if cache != nil && current-sent <= pushMaxBehindRow {
+ rows := make([]pushRow, 0, current-sent)
+ for seq := sent + 1; seq <= current; seq++ {
+ b, ok := cache.get(seq)
+ if !ok {
+ rows = nil
+ break
+ }
+ rows = append(rows, pushRow{seq: seq, bytes: b})
+ }
+ if rows != nil {
+ if h.pushStats != nil {
+ h.pushStats.cacheHits.Add(int64(len(rows)))
+ }
+ return rows, current, nil
+ }
+ }
+ var updates []DocUpdate
+ if err := h.store.db.WithContext(ctx).
+ Where("doc_id = ? AND seq > ? AND seq <= ?", doc.ID, sent, current).
+ Order("seq ASC").Limit(pushMaxBehindRow + 1).
+ Find(&updates).Error; err != nil {
+ return nil, 0, err
+ }
+ if h.pushStats != nil {
+ h.pushStats.rowReads.Add(int64(len(updates)))
+ }
+ rows := make([]pushRow, 0, len(updates))
+ for i := range updates {
+ u := &updates[i]
+ if err := h.store.openContentUpdate(doc.GUID, u); err != nil {
+ rows = append(rows, pushRow{seq: u.Seq, unusable: true})
+ continue
+ }
+ if cache != nil {
+ cache.put(u.Seq, u.UpdateBin)
+ }
+ rows = append(rows, pushRow{seq: u.Seq, bytes: u.UpdateBin})
+ }
+ return rows, current, nil
+}
+
+// pushFrames renders rows as frames for stream id (§3.1): own for an update
+// this stream posted (matched by stream id and the bytes' hash), update
+// for a row too large or unreadable, push otherwise. Too far behind (more
+// than pushMaxBehindRow rows or pushMaxBehind bytes) is one update for the
+// log's current seq. It returns the text to write in one flush and the new
+// cursor.
+func (h *handlers) pushFrames(docID int64, id string, rows []pushRow, current, sent int64) (string, int64) {
+ if len(rows) == 0 {
+ return "", sent
+ }
+ total := 0
+ for _, r := range rows {
+ total += len(r.bytes)
+ }
+ last := rows[len(rows)-1].seq
+ if len(rows) > pushMaxBehindRow || total > pushMaxBehind {
+ return "event: update\ndata: " + strconv.FormatInt(current, 10) + "\n\n", current
+ }
+ var b strings.Builder
+ for _, r := range rows {
+ seq := strconv.FormatInt(r.seq, 10)
+ switch o, ok := h.pushRegistry.lookup(docID, r.seq); {
+ case r.unusable || len(r.bytes) > pushMaxRowBytes:
+ b.WriteString("event: update\ndata: " + seq + "\n\n")
+ case ok && o.stream == id && o.hash == sha256.Sum256(r.bytes):
+ b.WriteString("id: " + seq + "\nevent: own\ndata: " + seq + " " + o.counter + "\n\n")
+ default:
+ b.WriteString("id: " + seq + "\nevent: push\ndata: " + seq + " ")
+ b.WriteString(base64.StdEncoding.EncodeToString(r.bytes))
+ b.WriteString("\n\n")
+ }
+ }
+ return b.String(), last
+}
+
+// lateAnswers paces a session that posts too fast to one document (§5):
+// over lateLimit updates in a second, its next answer waits, before the
+// POST takes the document's lock or the writer, for at most lateMaxWait,
+// ended by the request's cancellation or the process draining. At most
+// lateMaxWaiting answers per session wait; beyond that, 503 with
+// Retry-After: 1 (never a 4xx: the web save queue drops a 4xx batch).
+type lateAnswers struct {
+ mu sync.Mutex
+ recent map[lateKey][]time.Time
+ waiting map[string]int
+ now func() time.Time
+ limit int // lateLimit; the fan-out probe raises it (its typists share a session)
+}
+
+type lateKey struct {
+ session string
+ docID int64
+}
+
+const (
+ lateLimit = 30
+ lateWindow = time.Second
+ lateMaxWait = time.Second
+ lateMaxWaiting = 2
+)
+
+func newLateAnswers() *lateAnswers {
+ return &lateAnswers{recent: map[lateKey][]time.Time{}, waiting: map[string]int{}, now: time.Now, limit: lateLimit}
+}
+
+// admit returns once the POST may proceed (true), or false when it should
+// be answered 503 (too many waiting) or was cancelled or drained while
+// waiting.
+func (l *lateAnswers) admit(ctx context.Context, draining <-chan struct{}, session string, docID int64) (ok bool, busy bool) {
+ if session == "" {
+ return true, false
+ }
+ key := lateKey{session, docID}
+ l.mu.Lock()
+ now := l.now()
+ times := l.recent[key]
+ cut := 0
+ for cut < len(times) && now.Sub(times[cut]) >= lateWindow {
+ cut++
+ }
+ times = times[cut:]
+ var wait time.Duration
+ if len(times) >= l.limit {
+ wait = min(times[len(times)-l.limit].Add(lateWindow).Sub(now), lateMaxWait)
+ }
+ if wait > 0 {
+ if l.waiting[session] >= lateMaxWaiting {
+ l.recent[key] = times
+ l.mu.Unlock()
+ return false, true
+ }
+ l.waiting[session]++
+ }
+ l.recent[key] = append(times, now.Add(wait))
+ if len(l.recent) > 4096 {
+ // Bounded: forget sessions idle for a window.
+ for k, ts := range l.recent {
+ if len(ts) == 0 || now.Sub(ts[len(ts)-1]) > lateWindow {
+ delete(l.recent, k)
+ }
+ }
+ }
+ l.mu.Unlock()
+ if wait <= 0 {
+ return true, false
+ }
+ defer func() {
+ l.mu.Lock()
+ l.waiting[session]--
+ if l.waiting[session] <= 0 {
+ delete(l.waiting, session)
+ }
+ l.mu.Unlock()
+ }()
+ t := time.NewTimer(wait)
+ defer t.Stop()
+ select {
+ case <-t.C:
+ return true, false
+ case <-ctx.Done():
+ return false, false
+ case <-draining:
+ return false, false
+ }
+}
+
+// pushStats count what push streams did (tests and the fan-out probe).
+type pushStats struct {
+ rowReads, cacheHits, frames atomic.Int64
+}
diff --git a/internal/docs/push_test.go b/internal/docs/push_test.go
new file mode 100644
index 0000000..60dca02
--- /dev/null
+++ b/internal/docs/push_test.go
@@ -0,0 +1,992 @@
+package docs
+
+// Live push, slice 1b (push.go, logepoch.go, stream.go; the live-push
+// spec's §3.1, §3.4, §5, §8 and the tests it lists in §9.1–§9.2).
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "encoding/base64"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/docs/internal/core"
+)
+
+type pushFixture struct {
+ t *testing.T
+ app *App
+ srv *httptest.Server
+ owner int64
+ doc *Document
+ ctx context.Context
+ // cookies is one signed-in session of owner@example.com: the stream and
+ // the POSTs present the same session, as one tab does.
+ cookies []*http.Cookie
+ // host, when set, is the Host every request names (team mode's bridge).
+ host string
+}
+
+func newPushFixture(t *testing.T, cfg Config) *pushFixture {
+ t.Helper()
+ app, err := NewForTestWith(t, cfg)
+ if err != nil {
+ t.Fatalf("NewForTestWith: %v", err)
+ }
+ ctx := context.Background()
+ owner := app.TestPerson(t, "owner@example.com")
+ doc, err := app.Store().Create(ctx, owner, "Push")
+ if err != nil {
+ t.Fatal(err)
+ }
+ srv := httptest.NewServer(app.Handler())
+ t.Cleanup(srv.Close)
+ f := &pushFixture{t: t, app: app, srv: srv, owner: owner, doc: doc, ctx: ctx}
+ f.cookies = f.session("owner@example.com")
+ return f
+}
+
+// session signs address in once and returns its cookies.
+func (f *pushFixture) session(address string) []*http.Cookie {
+ return f.app.TestRequest(f.t, address, http.MethodGet, "/", nil).Cookies()
+}
+
+// update is a valid update adding one paragraph from its own Yjs client.
+func (f *pushFixture) update(k int, text string) []byte {
+ f.t.Helper()
+ u, err := f.app.core.InitialUpdate(f.ctx, f.doc.GUID, uint64(500000+k), []core.InitialBlock{{Text: text}})
+ if err != nil {
+ f.t.Fatal(err)
+ }
+ return u
+}
+
+// post POSTs update with cookies and an optional Docs-Stream header, and
+// returns the status and Docs-Seq.
+func (f *pushFixture) post(cookies []*http.Cookie, update []byte, docsStream string) (int, int64) {
+ f.t.Helper()
+ req, _ := http.NewRequest(http.MethodPost, f.srv.URL+"/d/"+f.doc.Sqid+"/updates", bytes.NewReader(update))
+ req.Header.Set("Content-Type", "application/octet-stream")
+ req.Header.Set("Sec-Fetch-Site", "same-origin")
+ if docsStream != "" {
+ req.Header.Set("Docs-Stream", docsStream)
+ }
+ for _, c := range cookies {
+ req.AddCookie(c)
+ }
+ res, err := f.srv.Client().Do(req)
+ if err != nil {
+ f.t.Fatal(err)
+ }
+ io.Copy(io.Discard, res.Body)
+ res.Body.Close()
+ seq, _ := strconv.ParseInt(res.Header.Get("Docs-Seq"), 10, 64)
+ return res.StatusCode, seq
+}
+
+type frame struct{ id, event, data string }
+
+// testStream is an open stream with a frame reader.
+type testStream struct {
+ res *http.Response
+ frames chan frame
+ done chan struct{}
+}
+
+func (f *pushFixture) open(cookies []*http.Cookie, query string, header map[string]string) *testStream {
+ f.t.Helper()
+ req, _ := http.NewRequest(http.MethodGet, f.srv.URL+"/d/"+f.doc.Sqid+"/stream"+query, nil)
+ if f.host != "" {
+ req.Host = f.host
+ }
+ for k, v := range header {
+ req.Header.Set(k, v)
+ }
+ for _, c := range cookies {
+ req.AddCookie(c)
+ }
+ res, err := f.srv.Client().Do(req)
+ if err != nil {
+ f.t.Fatal(err)
+ }
+ if res.StatusCode != 200 {
+ res.Body.Close()
+ f.t.Fatalf("stream %s: %d", query, res.StatusCode)
+ }
+ s := &testStream{res: res, frames: make(chan frame, 1024), done: make(chan struct{})}
+ f.t.Cleanup(func() { res.Body.Close() })
+ go func() {
+ defer close(s.done)
+ r := bufio.NewReaderSize(res.Body, 1<<20)
+ var fr frame
+ for {
+ line, err := r.ReadString('\n')
+ if err != nil {
+ return
+ }
+ line = strings.TrimRight(line, "\r\n")
+ switch {
+ case strings.HasPrefix(line, ":"):
+ case strings.HasPrefix(line, "id: "):
+ fr.id = line[4:]
+ case strings.HasPrefix(line, "event: "):
+ fr.event = line[7:]
+ case strings.HasPrefix(line, "data: "):
+ fr.data = line[6:]
+ case line == "":
+ if fr.event != "" {
+ s.frames <- fr
+ }
+ fr = frame{}
+ }
+ }
+ }()
+ return s
+}
+
+func (s *testStream) next(t *testing.T) frame {
+ t.Helper()
+ select {
+ case fr := <-s.frames:
+ return fr
+ case <-s.done:
+ select {
+ case fr := <-s.frames:
+ return fr
+ default:
+ }
+ t.Fatal("the stream ended")
+ case <-time.After(5 * time.Second):
+ t.Fatal("no frame within 5 s")
+ }
+ return frame{}
+}
+
+// quiet asserts no frame arrives within d.
+func (s *testStream) quiet(t *testing.T, d time.Duration) {
+ t.Helper()
+ select {
+ case fr := <-s.frames:
+ t.Fatalf("unexpected frame %+v", fr)
+ case <-time.After(d):
+ }
+}
+
+// hello reads the hello frame and returns the stream id, seq and epoch.
+func (s *testStream) hello(t *testing.T) (string, int64, string) {
+ t.Helper()
+ fr := s.next(t)
+ parts := strings.Fields(fr.data)
+ if fr.event != "hello" || len(parts) != 3 {
+ t.Fatalf("first frame %+v, want hello <id> <seq> <epoch>", fr)
+ }
+ seq, err := strconv.ParseInt(parts[1], 10, 64)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return parts[0], seq, parts[2]
+}
+
+func pushOn() Config { return Config{LivePush: true} }
+
+// §9.1: one POST yields exactly one flushed push frame per watcher, with
+// the row's bytes, and `own` for the poster's stream; no update event.
+func TestPushOnePOSTOneFramePerWatcher(t *testing.T) {
+ f := newPushFixture(t, pushOn())
+ poster := f.open(f.cookies, "?push=1&since=0", nil)
+ id, _, _ := poster.hello(t)
+ var watchers []*testStream
+ for i := 0; i < 3; i++ {
+ w := f.open(f.session("owner@example.com"), "?push=1&since=0", nil)
+ w.hello(t)
+ watchers = append(watchers, w)
+ }
+ u := f.update(1, "hello push")
+ frames0 := f.app.handlers.pushStats.frames.Load()
+ code, seq := f.post(f.cookies, u, id+".7")
+ if code != http.StatusNoContent || seq != 1 {
+ t.Fatalf("POST: %d, seq %d", code, seq)
+ }
+ for i, w := range watchers {
+ fr := w.next(t)
+ parts := strings.SplitN(fr.data, " ", 2)
+ if fr.event != "push" || fr.id != "1" || len(parts) != 2 || parts[0] != "1" {
+ t.Fatalf("watcher %d: %+v, want push 1", i, fr)
+ }
+ got, err := base64.StdEncoding.DecodeString(parts[1])
+ if err != nil || !bytes.Equal(got, u) {
+ t.Fatalf("watcher %d: the frame's bytes are not the update's", i)
+ }
+ w.quiet(t, 150*time.Millisecond)
+ }
+ if fr := poster.next(t); fr.event != "own" || fr.id != "1" || fr.data != "1 7" {
+ t.Fatalf("poster: %+v, want own 1 7", fr)
+ }
+ poster.quiet(t, 150*time.Millisecond)
+ if n := f.app.handlers.pushStats.frames.Load() - frames0; n != 4 {
+ t.Errorf("%d flushes for one POST and four streams, want 4", n)
+ }
+}
+
+// §3.4: `own` only for the stream the header names, from the session that
+// opened it, on its document. Anything else is a push.
+func TestPushOwnNeedsTheSameSessionAndDocument(t *testing.T) {
+ f := newPushFixture(t, pushOn())
+ poster := f.open(f.cookies, "?push=1&since=0", nil)
+ id, _, _ := poster.hello(t)
+
+ // Another session of the same person names this stream.
+ f.post(f.session("owner@example.com"), f.update(1, "other session"), id+".1")
+ if fr := poster.next(t); fr.event != "push" {
+ t.Fatalf("another session's header: %+v, want push", fr)
+ }
+ // A stream on another document.
+ other, err := f.app.Store().Create(f.ctx, f.owner, "Other")
+ if err != nil {
+ t.Fatal(err)
+ }
+ g := *f
+ g.doc = other
+ otherStream := g.open(f.cookies, "?push=1&since=0", nil)
+ otherID, _, _ := otherStream.hello(t)
+ f.post(f.cookies, f.update(2, "wrong document"), otherID+".1")
+ if fr := poster.next(t); fr.event != "push" {
+ t.Fatalf("another document's stream id: %+v, want push", fr)
+ }
+ // Malformed and unknown headers.
+ for i, h := range []string{"nonsense", id + ".x", "unknown.1", id + "."} {
+ f.post(f.cookies, f.update(3+i, "bad header"), h)
+ if fr := poster.next(t); fr.event != "push" {
+ t.Fatalf("header %q: %+v, want push", h, fr)
+ }
+ }
+ // The real thing.
+ f.post(f.cookies, f.update(9, "mine"), id+".42")
+ if fr := poster.next(t); fr.event != "own" || !strings.HasSuffix(fr.data, " 42") {
+ t.Fatalf("own: %+v", fr)
+ }
+}
+
+// §3.4: a seq whose origin entry was recorded by a transaction that rolled
+// back, then reused by another POST, must not come back as `own`: the
+// entry's hash does not match the committed row.
+func TestPushOwnIsCheckedAgainstTheRowsBytes(t *testing.T) {
+ f := newPushFixture(t, pushOn())
+ poster := f.open(f.cookies, "?push=1&since=0", nil)
+ id, _, _ := poster.hello(t)
+ f.app.handlers.pushRegistry.record(f.doc.ID, 1, postOrigin{stream: id, counter: "5"}, []byte("a rolled-back update"))
+ f.post(f.session("owner@example.com"), f.update(1, "someone else"), "")
+ if fr := poster.next(t); fr.event != "push" {
+ t.Fatalf("%+v, want push: a stale origin entry was believed", fr)
+ }
+}
+
+// §9.1: frames in seq order, gapless, under concurrent POSTs.
+func TestPushFramesInSeqOrderUnderConcurrentPOSTs(t *testing.T) {
+ f := newPushFixture(t, pushOn())
+ w := f.open(f.cookies, "?push=1&since=0", nil)
+ w.hello(t)
+ const writers, each = 8, 10
+ sessions := make([][]*http.Cookie, writers)
+ for g := range sessions {
+ address := fmt.Sprintf("writer%d@example.com", g)
+ f.app.TestPerson(t, address)
+ if err := f.app.Store().Grant(f.ctx, f.owner, f.doc.Sqid, address, RoleWriter); err != nil {
+ t.Fatal(err)
+ }
+ sessions[g] = f.session(address)
+ }
+ var wg sync.WaitGroup
+ for g := 0; g < writers; g++ {
+ wg.Add(1)
+ go func(g int) {
+ defer wg.Done()
+ cookies := sessions[g]
+ for i := 0; i < each; i++ {
+ if code, _ := f.post(cookies, f.update(g*100+i, fmt.Sprintf("g%di%d", g, i)), ""); code != http.StatusNoContent {
+ t.Errorf("POST: %d", code)
+ }
+ }
+ }(g)
+ }
+ wg.Wait()
+ var last int64
+ for last < writers*each {
+ fr := w.next(t)
+ if fr.event != "push" {
+ t.Fatalf("%+v, want push", fr)
+ }
+ seq, _ := strconv.ParseInt(strings.Fields(fr.data)[0], 10, 64)
+ if seq != last+1 {
+ t.Fatalf("frame %d after %d: out of order or a gap", seq, last)
+ }
+ last = seq
+ }
+}
+
+// §3.1: resume from since; Last-Event-ID wins over since.
+func TestPushResumesFromSinceAndLastEventID(t *testing.T) {
+ f := newPushFixture(t, pushOn())
+ for k := 1; k <= 5; k++ {
+ f.post(f.cookies, f.update(k, fmt.Sprint("row", k)), "")
+ }
+ seqs := func(s *testStream, n int) []string {
+ var out []string
+ for i := 0; i < n; i++ {
+ fr := s.next(t)
+ if fr.event != "push" {
+ t.Fatalf("%+v, want push", fr)
+ }
+ out = append(out, fr.id)
+ }
+ s.quiet(t, 150*time.Millisecond)
+ return out
+ }
+ s := f.open(f.cookies, "?push=1&since=2", nil)
+ if _, cur, _ := s.hello(t); cur != 5 {
+ t.Fatalf("hello seq %d, want 5", cur)
+ }
+ if got := strings.Join(seqs(s, 3), ","); got != "3,4,5" {
+ t.Fatalf("since=2 sent %s", got)
+ }
+ s = f.open(f.cookies, "?push=1&since=1", map[string]string{"Last-Event-ID": "4"})
+ s.hello(t)
+ if got := strings.Join(seqs(s, 1), ","); got != "5" {
+ t.Fatalf("Last-Event-ID 4 over since=1 sent %s", got)
+ }
+ for _, q := range []string{"?push=1&since=banana", "?push=1&since=-1"} {
+ req, _ := http.NewRequest(http.MethodGet, f.srv.URL+"/d/"+f.doc.Sqid+"/stream"+q, nil)
+ for _, c := range f.cookies {
+ req.AddCookie(c)
+ }
+ res, err := f.srv.Client().Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ res.Body.Close()
+ if res.StatusCode != http.StatusBadRequest {
+ t.Errorf("%s: %d, want 400", q, res.StatusCode)
+ }
+ }
+}
+
+// §3.1: hello first, with the current seq and the log epoch; a push stream
+// with no cursor keeps today's connect-time update; fetches carry the
+// epoch too.
+func TestPushHelloAndTheConnectTimeUpdate(t *testing.T) {
+ f := newPushFixture(t, pushOn())
+ f.post(f.cookies, f.update(1, "one"), "")
+ s := f.open(f.cookies, "?push=1", nil)
+ id, seq, epoch := s.hello(t)
+ if id == "" || seq != 1 || epoch != f.app.store.logEpoch || epoch == "" {
+ t.Fatalf("hello %q %d %q (log epoch %q)", id, seq, epoch, f.app.store.logEpoch)
+ }
+ if fr := s.next(t); fr.event != "update" || fr.data != "1" || fr.id != "" {
+ t.Fatalf("%+v, want the connect-time update 1 without an id", fr)
+ }
+ rec := httptest.NewRecorder()
+ f.app.Handler().ServeHTTP(rec, f.app.TestRequest(t, "owner@example.com", http.MethodGet, "/d/"+f.doc.Sqid+"/updates?since=0", nil))
+ if rec.Header().Get("Docs-Log-Epoch") != epoch {
+ t.Fatalf("fetch Docs-Log-Epoch %q, want %q", rec.Header().Get("Docs-Log-Epoch"), epoch)
+ }
+}
+
+// §3.1: a row over 32 KiB goes as update (no id), and the cursor moves past
+// it; a client more than 256 rows behind gets one update.
+func TestPushOversizedAndFarBehindGoByFetch(t *testing.T) {
+ f := newPushFixture(t, pushOn())
+ s := f.open(f.cookies, "?push=1&since=0", nil)
+ s.hello(t)
+ big := f.update(1, strings.Repeat("x", pushMaxRowBytes+1024))
+ if len(big) <= pushMaxRowBytes {
+ t.Fatalf("test update is only %d bytes", len(big))
+ }
+ f.post(f.cookies, big, "")
+ if fr := s.next(t); fr.event != "update" || fr.data != "1" || fr.id != "" {
+ t.Fatalf("%+v, want update 1 with no id", fr)
+ }
+ f.post(f.cookies, f.update(2, "small"), "")
+ if fr := s.next(t); fr.event != "push" || fr.id != "2" {
+ t.Fatalf("%+v, want push 2 after the update moved the cursor", fr)
+ }
+
+ g := newPushFixture(t, pushOn())
+ for k := 1; k <= pushMaxBehindRow+10; k++ {
+ g.post(g.cookies, g.update(k, fmt.Sprint("r", k)), "")
+ }
+ behind := g.open(g.cookies, "?push=1&since=0", nil)
+ behind.hello(t)
+ want := strconv.Itoa(pushMaxBehindRow + 10)
+ if fr := behind.next(t); fr.event != "update" || fr.data != want {
+ t.Fatalf("%+v, want one update %s", fr, want)
+ }
+ behind.quiet(t, 150*time.Millisecond)
+ g.post(g.cookies, g.update(9999, "next"), "")
+ if fr := behind.next(t); fr.event != "push" || fr.id != strconv.Itoa(pushMaxBehindRow+11) {
+ t.Fatalf("%+v, want the next row as push", fr)
+ }
+}
+
+// §3.6: bye before the TTL close and on drain.
+func TestPushByeOnTTLAndDrain(t *testing.T) {
+ f := newPushFixture(t, pushOn())
+ streamDurations(t, f.app, time.Minute, 300*time.Millisecond)
+ s := f.open(f.cookies, "?push=1&since=0", nil)
+ s.hello(t)
+ if fr := s.next(t); fr.event != "bye" || fr.data != "ttl" {
+ t.Fatalf("%+v, want bye ttl", fr)
+ }
+ streamDurations(t, f.app, time.Minute, time.Minute)
+ d := f.open(f.cookies, "?push=1&since=0", nil)
+ d.hello(t)
+ f.app.Drain()
+ if fr := d.next(t); fr.event != "bye" || fr.data != "drain" {
+ t.Fatalf("%+v, want bye drain", fr)
+ }
+}
+
+// §3.6: a team-mode push stream says `bye lease` before its lease closes it.
+func TestPushByeLeaseInTeamMode(t *testing.T) {
+ tf := newTeamRouterFixtureWith(t, false, false)
+ tf.app.handlers.livePush = true
+ tf.app.store.recordOrigin = tf.app.handlers.pushRegistry.record
+ tf.app.handlers.pushLeaseLead = 24 * time.Hour // longer than any lease: at once
+ b := tf.browser()
+ b.localSignin(t, "alice@example.com")
+ b.linkProof(t, teamSubject('a'), "alice@example.com")
+ routerRedirect(t, b.do("POST", "/account/home/confirm", ""), connectedURL("/"))
+ srv := httptest.NewServer(tf.app.Handler())
+ defer srv.Close()
+ f := &pushFixture{t: t, app: tf.app, srv: srv, doc: tf.own, ctx: context.Background(), host: strings.TrimPrefix(strings.TrimPrefix(bridgeOrigin, "https://"), "http://")}
+ for _, c := range b.cookies {
+ f.cookies = append(f.cookies, c)
+ }
+ s := f.open(f.cookies, "?push=1&since=0", nil)
+ s.hello(t)
+ fr := s.next(t)
+ for fr.event == "push" { // the fixture's own row, resumed from 0
+ fr = s.next(t)
+ }
+ if fr.event != "bye" || fr.data != "lease" {
+ t.Fatalf("%+v, want bye lease", fr)
+ }
+}
+
+// §6 and §9.1: a reader's stream receives frames, and the reader cannot
+// post; access revoked between two frames ends the stream.
+func TestPushReaderAndRevocation(t *testing.T) {
+ f := newPushFixture(t, pushOn())
+ // Private: a Team document would stay readable to an allowlisted member
+ // after the grant goes.
+ f.doc = f.app.TestCreatePrivate(t, f.owner, "Private")
+ f.app.TestPerson(t, "reader@example.com")
+ if err := f.app.Store().Grant(f.ctx, f.owner, f.doc.Sqid, "reader@example.com", RoleReader); err != nil {
+ t.Fatal(err)
+ }
+ reader := f.session("reader@example.com")
+ s := f.open(reader, "?push=1&since=0", nil)
+ s.hello(t)
+ f.post(f.cookies, f.update(1, "for the reader"), "")
+ if fr := s.next(t); fr.event != "push" || fr.id != "1" {
+ t.Fatalf("reader: %+v, want push 1", fr)
+ }
+ if code, _ := f.post(reader, f.update(2, "from the reader"), ""); code != http.StatusNotFound {
+ t.Fatalf("reader POST: %d, want 404", code)
+ }
+ if err := f.app.Store().Revoke(f.ctx, f.owner, f.doc.Sqid, "reader@example.com"); err != nil {
+ t.Fatal(err)
+ }
+ f.post(f.cookies, f.update(3, "after revocation"), "")
+ select {
+ case fr := <-s.frames:
+ if fr.event == "push" {
+ t.Fatalf("a revoked reader received %+v", fr)
+ }
+ case <-s.done:
+ case <-time.After(3 * time.Second):
+ t.Fatal("the revoked reader's stream stayed open")
+ }
+}
+
+// §7: with the switch on, a client that does not ask for push sees exactly
+// today's stream: no hello, update events whose data parses as an Int64
+// (the old native parser's rule), and the POST answers as before.
+func TestPushOldClientsAreUnchanged(t *testing.T) {
+ f := newPushFixture(t, pushOn())
+ s := f.open(f.cookies, "", nil)
+ fr := s.next(t)
+ if fr.event != "update" || fr.data != "0" || fr.id != "" {
+ t.Fatalf("first event %+v, want update 0", fr)
+ }
+ code, seq := f.post(f.cookies, f.update(1, "old"), "")
+ if code != http.StatusNoContent || seq != 1 {
+ t.Fatalf("POST %d %d", code, seq)
+ }
+ fr = s.next(t)
+ if _, err := strconv.ParseInt(fr.data, 10, 64); fr.event != "update" || err != nil || fr.id != "" {
+ t.Fatalf("%+v, want update with an Int64 data line", fr)
+ }
+}
+
+// §8: off, push=1 is ignored and Docs-Stream changes nothing.
+func TestPushSwitchOff(t *testing.T) {
+ f := newPushFixture(t, Config{})
+ s := f.open(f.cookies, "?push=1&since=0", nil)
+ if fr := s.next(t); fr.event != "update" || fr.data != "0" {
+ t.Fatalf("%+v, want today's connect-time update", fr)
+ }
+ f.post(f.cookies, f.update(1, "x"), "anything.1")
+ if fr := s.next(t); fr.event != "update" || fr.data != "1" {
+ t.Fatalf("%+v, want update 1", fr)
+ }
+ rec := httptest.NewRecorder()
+ f.app.Handler().ServeHTTP(rec, f.app.TestRequest(t, "owner@example.com", http.MethodGet, "/d/"+f.doc.Sqid+"/updates?since=0", nil))
+ if rec.Header().Get("Docs-Log-Epoch") != "" {
+ t.Error("Docs-Log-Epoch with the switch off")
+ }
+ for _, c := range []struct {
+ in string
+ want bool
+ bad bool
+ }{{"", false, false}, {"off", false, false}, {"on", true, false}, {"maybe", false, true}} {
+ got, err := ParseLivePush(c.in)
+ if got != c.want || (err != nil) != c.bad {
+ t.Errorf("ParseLivePush(%q) = %v, %v", c.in, got, err)
+ }
+ }
+}
+
+// §5: late answers. Within the limit nothing waits; over it the next answer
+// waits (at most a second); a third waiter is busy (503); cancellation and
+// drain end a wait.
+func TestLateAnswers(t *testing.T) {
+ l := newLateAnswers()
+ clock := time.Unix(1000, 0)
+ var mu sync.Mutex
+ l.now = func() time.Time { mu.Lock(); defer mu.Unlock(); return clock }
+ drain := make(chan struct{})
+ ctx := context.Background()
+ for i := 0; i < lateLimit; i++ {
+ if ok, busy := l.admit(ctx, drain, "s", 1); !ok || busy {
+ t.Fatalf("POST %d within the limit refused", i)
+ }
+ }
+ if ok, busy := l.admit(ctx, drain, "", 1); !ok || busy {
+ t.Fatal("an unbound session is not paced")
+ }
+ if ok, _ := l.admit(ctx, drain, "s", 2); !ok {
+ t.Fatal("another document is not paced")
+ }
+ start := time.Now()
+ if ok, busy := l.admit(ctx, drain, "s", 1); !ok || busy {
+ t.Fatal("the paced POST was refused")
+ }
+ if waited := time.Since(start); waited < 900*time.Millisecond || waited > 2*time.Second {
+ t.Fatalf("waited %v, want about a second", waited)
+ }
+ // Two waiting, the third busy.
+ results := make(chan bool, 2)
+ cctx, cancel := context.WithCancel(ctx)
+ for i := 0; i < 2; i++ {
+ go func() { ok, _ := l.admit(cctx, drain, "s", 1); results <- ok }()
+ }
+ time.Sleep(100 * time.Millisecond)
+ if ok, busy := l.admit(ctx, drain, "s", 1); ok || !busy {
+ t.Fatalf("third waiter: ok %v busy %v, want busy", ok, busy)
+ }
+ cancel()
+ for i := 0; i < 2; i++ {
+ if <-results {
+ t.Fatal("a cancelled wait reported ok")
+ }
+ }
+ go func() { time.Sleep(100 * time.Millisecond); close(drain) }()
+ if ok, _ := l.admit(ctx, drain, "s", 1); ok {
+ t.Fatal("a drained wait reported ok")
+ }
+}
+
+// §5 at the handler: a session posting far over the limit gets 503 with
+// Retry-After for what cannot wait, never a 4xx.
+func TestLateAnswersAt503(t *testing.T) {
+ f := newPushFixture(t, pushOn())
+ var mu sync.Mutex
+ codes := map[int]int{}
+ var wg sync.WaitGroup
+ u := f.update(1, "same")
+ for i := 0; i < lateLimit+20; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ code, _ := f.post(f.cookies, u, "")
+ mu.Lock()
+ codes[code]++
+ mu.Unlock()
+ }()
+ }
+ wg.Wait()
+ for code := range codes {
+ if code >= 400 && code < 500 {
+ t.Fatalf("answers %v: a 4xx", codes)
+ }
+ }
+ if codes[http.StatusServiceUnavailable] == 0 {
+ t.Fatalf("answers %v: nothing was told to wait", codes)
+ }
+}
+
+// §3.1: the log epoch stays across ordinary restarts, overlapping ones
+// included, and rotates when the file beside the database is gone or the
+// database is older than the last start (a restore).
+func TestLogEpochRotation(t *testing.T) {
+ dir := t.TempDir()
+ cfg := Config{DBPath: filepath.Join(dir, "docs.db"), Env: "development"}
+ start := func() *App {
+ app, err := New(cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return app
+ }
+ a := start()
+ e1 := a.store.logEpoch
+ b := start() // an overlapping generation
+ if b.store.logEpoch != e1 {
+ t.Fatal("an overlapping start rotated the epoch")
+ }
+ b.Close()
+ a.Close()
+ backup := copyDB(t, cfg.DBPath, dir+"/backup")
+ c := start()
+ if c.store.logEpoch != e1 {
+ t.Fatal("an ordinary restart rotated the epoch")
+ }
+ c.Close()
+ os.Remove(cfg.DBPath + ".log-epoch")
+ d := start()
+ e2 := d.store.logEpoch
+ if e2 == e1 {
+ t.Fatal("a start without the file beside the database kept the epoch")
+ }
+ d.Close()
+ // A restore of the database from before the last start.
+ restoreDB(t, backup, cfg.DBPath)
+ e := start()
+ if e.store.logEpoch == e2 || e.store.logEpoch == e1 {
+ t.Fatal("a restored database kept an epoch")
+ }
+ e.Close()
+}
+
+func copyDB(t *testing.T, from, to string) string {
+ t.Helper()
+ for _, suffix := range []string{"", "-wal", "-shm"} {
+ b, err := os.ReadFile(from + suffix)
+ if err != nil {
+ continue
+ }
+ if err := os.WriteFile(to+suffix, b, 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return to
+}
+
+func restoreDB(t *testing.T, from, to string) {
+ t.Helper()
+ for _, suffix := range []string{"-wal", "-shm"} {
+ os.Remove(to + suffix)
+ }
+ copyDB(t, from, to)
+}
+
+// §9.2's timing gate: with a round trip injected, the time from POST to the
+// bytes in a watcher's hand is at least half a round trip shorter with
+// push than with the fetch path (update event, then GET), in the same
+// process, best of three medians. Push removes a request, so anything less
+// means it is not doing so. Relative only: no absolute threshold.
+func TestPushIsFasterThanTheFetchPath(t *testing.T) {
+ f := newPushFixture(t, pushOn())
+ const oneWay = 10 * time.Millisecond
+ proxy := delayProxy(t, strings.TrimPrefix(f.srv.URL, "http://"), oneWay)
+ base := "http://" + proxy
+ client := &http.Client{}
+
+ measure := func(push bool, from int) float64 {
+ watch := &pushFixture{t: t, app: f.app, srv: &httptest.Server{URL: base}, doc: f.doc, ctx: f.ctx, cookies: f.cookies}
+ query := ""
+ if push {
+ query = "?push=1&since=" + strconv.FormatInt(f.currentSeq(), 10)
+ }
+ s := watch.openClient(client, query)
+ if push {
+ s.hello(t)
+ } else {
+ s.next(t) // connect-time update
+ }
+ var times []float64
+ for k := from; k < from+15; k++ {
+ start := time.Now()
+ code, seq := watch.postWith(client, f.update(k, fmt.Sprint("t", k)))
+ if code != http.StatusNoContent {
+ t.Fatalf("POST %d", code)
+ }
+ for {
+ fr := s.next(t)
+ if push && fr.event == "push" && fr.id == strconv.FormatInt(seq, 10) {
+ break
+ }
+ if !push && fr.event == "update" {
+ // The fetch path: the GET for the announced rows.
+ watch.getWith(client, seq-1)
+ break
+ }
+ }
+ times = append(times, float64(time.Since(start).Microseconds())/1000)
+ }
+ s.res.Body.Close()
+ sort.Float64s(times)
+ return times[len(times)/2]
+ }
+ best := func(push bool, base int) float64 {
+ b := measure(push, base)
+ for r := 1; r < 3; r++ {
+ b = min(b, measure(push, base+r*100))
+ }
+ return b
+ }
+ fetch := best(false, 1000)
+ push := best(true, 2000)
+ t.Logf("POST -> bytes in hand, 20 ms round trip: fetch path %.1f ms, push %.1f ms", fetch, push)
+ if push > fetch-float64(oneWay.Milliseconds()) {
+ t.Fatalf("push (%.1f ms) is not half a round trip faster than the fetch path (%.1f ms)", push, fetch)
+ }
+}
+
+func (f *pushFixture) currentSeq() int64 {
+ seq, err := f.app.store.currentSeq(f.ctx, f.doc.ID)
+ if err != nil {
+ f.t.Fatal(err)
+ }
+ return seq
+}
+
+func (f *pushFixture) openClient(client *http.Client, query string) *testStream {
+ f.t.Helper()
+ req, _ := http.NewRequest(http.MethodGet, f.srv.URL+"/d/"+f.doc.Sqid+"/stream"+query, nil)
+ for _, c := range f.cookies {
+ req.AddCookie(c)
+ }
+ res, err := client.Do(req)
+ if err != nil || res.StatusCode != 200 {
+ f.t.Fatalf("stream: %v %v", err, res)
+ }
+ s := &testStream{res: res, frames: make(chan frame, 1024), done: make(chan struct{})}
+ go func() {
+ defer close(s.done)
+ r := bufio.NewReader(res.Body)
+ var fr frame
+ for {
+ line, err := r.ReadString('\n')
+ if err != nil {
+ return
+ }
+ line = strings.TrimRight(line, "\r\n")
+ switch {
+ case strings.HasPrefix(line, "id: "):
+ fr.id = line[4:]
+ case strings.HasPrefix(line, "event: "):
+ fr.event = line[7:]
+ case strings.HasPrefix(line, "data: "):
+ fr.data = line[6:]
+ case line == "":
+ if fr.event != "" {
+ s.frames <- fr
+ }
+ fr = frame{}
+ }
+ }
+ }()
+ return s
+}
+
+func (f *pushFixture) postWith(client *http.Client, update []byte) (int, int64) {
+ req, _ := http.NewRequest(http.MethodPost, f.srv.URL+"/d/"+f.doc.Sqid+"/updates", bytes.NewReader(update))
+ req.Header.Set("Content-Type", "application/octet-stream")
+ req.Header.Set("Sec-Fetch-Site", "same-origin")
+ for _, c := range f.cookies {
+ req.AddCookie(c)
+ }
+ res, err := client.Do(req)
+ if err != nil {
+ f.t.Fatal(err)
+ }
+ io.Copy(io.Discard, res.Body)
+ res.Body.Close()
+ seq, _ := strconv.ParseInt(res.Header.Get("Docs-Seq"), 10, 64)
+ return res.StatusCode, seq
+}
+
+func (f *pushFixture) getWith(client *http.Client, since int64) {
+ req, _ := http.NewRequest(http.MethodGet, f.srv.URL+"/d/"+f.doc.Sqid+"/updates?since="+strconv.FormatInt(since, 10), nil)
+ for _, c := range f.cookies {
+ req.AddCookie(c)
+ }
+ res, err := client.Do(req)
+ if err != nil {
+ f.t.Fatal(err)
+ }
+ io.Copy(io.Discard, res.Body)
+ res.Body.Close()
+}
+
+// delayProxy forwards loopback connections to upstream, holding each chunk
+// oneWay in each direction, in order.
+func delayProxy(t *testing.T, upstream string, oneWay time.Duration) string {
+ t.Helper()
+ l, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { l.Close() })
+ pump := func(src, dst net.Conn) {
+ type chunk struct {
+ b []byte
+ at time.Time
+ }
+ ch := make(chan chunk, 1<<12)
+ go func() {
+ for c := range ch {
+ time.Sleep(time.Until(c.at))
+ if _, err := dst.Write(c.b); err != nil {
+ break
+ }
+ }
+ dst.Close()
+ for range ch {
+ }
+ }()
+ buf := make([]byte, 32<<10)
+ for {
+ n, err := src.Read(buf)
+ if n > 0 {
+ ch <- chunk{append([]byte(nil), buf[:n]...), time.Now().Add(oneWay)}
+ }
+ if err != nil {
+ close(ch)
+ return
+ }
+ }
+ }
+ go func() {
+ for {
+ c, err := l.Accept()
+ if err != nil {
+ return
+ }
+ u, err := net.Dial("tcp", upstream)
+ if err != nil {
+ c.Close()
+ continue
+ }
+ go pump(c, u)
+ go pump(u, c)
+ }
+ }()
+ return l.Addr().String()
+}
+
+// §3.4: the origin entry is recorded inside the POST's transaction, so even
+// with other writers' POSTs waking the poster's stream in between, every
+// update the poster sent comes back to it as `own`, never as its own bytes.
+func TestPushOwnUnderConcurrentPOSTs(t *testing.T) {
+ f := newPushFixture(t, pushOn())
+ f.app.TestPerson(t, "other@example.com")
+ if err := f.app.Store().Grant(f.ctx, f.owner, f.doc.Sqid, "other@example.com", RoleWriter); err != nil {
+ t.Fatal(err)
+ }
+ other := f.session("other@example.com")
+ poster := f.open(f.cookies, "?push=1&since=0", nil)
+ id, _, _ := poster.hello(t)
+ const each = 20
+ mine := map[int64]string{}
+ var mu sync.Mutex
+ var wg sync.WaitGroup
+ wg.Add(2)
+ go func() {
+ defer wg.Done()
+ for i := 0; i < each; i++ {
+ _, seq := f.post(f.cookies, f.update(i, fmt.Sprint("mine", i)), fmt.Sprintf("%s.%d", id, i+1))
+ mu.Lock()
+ mine[seq] = strconv.Itoa(i + 1)
+ mu.Unlock()
+ }
+ }()
+ go func() {
+ defer wg.Done()
+ for i := 0; i < each; i++ {
+ f.post(other, f.update(100+i, fmt.Sprint("theirs", i)), "")
+ }
+ }()
+ wg.Wait()
+ for seen := 0; seen < 2*each; seen++ {
+ fr := poster.next(t)
+ seq, _ := strconv.ParseInt(fr.id, 10, 64)
+ counter, isMine := mine[seq]
+ switch {
+ case isMine && (fr.event != "own" || fr.data != fr.id+" "+counter):
+ t.Fatalf("my update %d came back as %+v", seq, fr)
+ case !isMine && fr.event != "push":
+ t.Fatalf("another writer's update %d came back as %+v", seq, fr)
+ }
+ }
+}
+
+// The frame cache changes nothing a stream sends: the same frames, bytes
+// included, with it on and off; with it on, W streams read each row once.
+func TestPushFrameCacheIsTransparent(t *testing.T) {
+ run := func(cache bool) ([]string, int64, int64) {
+ f := newPushFixture(t, pushOn())
+ f.app.handlers.pushFrameCache = cache
+ var streams []*testStream
+ for i := 0; i < 4; i++ {
+ s := f.open(f.cookies, "?push=1&since=0", nil)
+ s.hello(t)
+ streams = append(streams, s)
+ }
+ writer := f.session("owner@example.com")
+ for k := 1; k <= 10; k++ {
+ f.post(writer, f.update(k, fmt.Sprint("c", k)), "")
+ }
+ var got []string
+ for _, s := range streams {
+ for i := 0; i < 10; i++ {
+ fr := s.next(t)
+ got = append(got, fr.event+" "+fr.id+" "+fr.data)
+ }
+ }
+ st := f.app.handlers.pushStats
+ return got, st.rowReads.Load(), st.cacheHits.Load()
+ }
+ off, offReads, _ := run(false)
+ on, onReads, hits := run(true)
+ if strings.Join(off, "\n") != strings.Join(on, "\n") {
+ t.Fatal("the frame cache changed what streams send")
+ }
+ if hits == 0 || onReads >= offReads {
+ t.Fatalf("cache on: %d row reads and %d hits, against %d reads off", onReads, hits, offReads)
+ }
+ t.Logf("4 streams x 10 rows: %d row reads without the cache, %d with it (%d hits)", offReads, onReads, hits)
+}
diff --git a/internal/docs/store.go b/internal/docs/store.go
index 426c14e..005d65d 100644
--- a/internal/docs/store.go
+++ b/internal/docs/store.go
@@ -22,6 +22,10 @@ import (
// the update log, and the document's actual text read back through
// the real CRDT core rather than any column here — see Text.
type Store struct {
+ // recordOrigin is the push registry's record (push.go), nil when live
+ // push is off. logEpoch is this process's log epoch (logepoch.go).
+ recordOrigin func(docID, seq int64, o postOrigin, update []byte)
+ logEpoch string
// warm keeps a replayed handle per document between update POSTs
// (warm.go); nil means every POST replays, as it always did.
warm *warmCache
@@ -997,6 +1001,11 @@ func (s *Store) commitUpdate(ctx context.Context, doc *Document, actor Actor, up
return err
}
assignedSeq = row.Seq
+ // Live push (§3.4): who posted this row, recorded before commit so
+ // a stream that reads the row always finds it.
+ if o, ok := ctx.Value(postOriginKey{}).(postOrigin); ok && s.recordOrigin != nil {
+ s.recordOrigin(doc.ID, assignedSeq, o, update)
+ }
if s.warmBeforeCommit != nil {
if err := s.warmBeforeCommit(ctx, tx, doc); err != nil {
return err
diff --git a/internal/docs/stream.go b/internal/docs/stream.go
index 29b3dea..2f7f993 100644
--- a/internal/docs/stream.go
+++ b/internal/docs/stream.go
@@ -39,6 +39,10 @@ const (
// No timer here exists outside a live connection, so nothing in
// this file is a ticker that dies at hibernation.
defaultStreamTTL = 5 * time.Minute
+
+ // pushLeaseLead ends a team-mode push stream this long before its
+ // lease, so `bye lease` is written while the lease still admits it.
+ pushLeaseLead = 2 * time.Second
)
// stream serves GET /d/{sqid}/stream: a Server-Sent Events feed that
@@ -87,6 +91,11 @@ func (h *handlers) stream(w http.ResponseWriter, r *http.Request) {
ch, stop := h.hub.subscribe(doc.ID)
defer stop()
+ // A push stream (push.go; the live-push spec's §3.1) only when the
+ // server's switch is on. Otherwise push=1 is ignored and this stream is
+ // exactly today's.
+ push := h.livePush && r.URL.Query().Get("push") == "1"
+
var guard *teamStreamGuard
var leaseTimer *time.Timer
var leaseDeadline <-chan time.Time
@@ -110,6 +119,10 @@ func (h *handlers) stream(w http.ResponseWriter, r *http.Request) {
http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusServiceUnavailable)
return
}
+ if push {
+ // Early enough that `bye lease` can still be written.
+ remaining = max(remaining-h.leaseLead(), 0)
+ }
leaseTimer = time.NewTimer(remaining)
defer leaseTimer.Stop()
leaseDeadline = leaseTimer.C
@@ -127,6 +140,24 @@ func (h *handlers) stream(w http.ResponseWriter, r *http.Request) {
http.Error(w, rastrillo.T(r, "docs.error.generic"), h.internalFailureStatus())
return
}
+ // Where a push stream starts: Last-Event-ID (EventSource sends it on its
+ // own reconnects) wins over since; garbage in either is a 400, as
+ // parseSince answers. With neither, it starts at the current seq.
+ start, resume := current, false
+ if push {
+ raw := r.Header.Get("Last-Event-ID")
+ if raw == "" {
+ raw = r.URL.Query().Get("since")
+ }
+ if raw != "" {
+ n, err := strconv.ParseInt(raw, 10, 64)
+ if err != nil || n < 0 {
+ http.Error(w, rastrillo.T(r, "docs.error.badsince"), http.StatusBadRequest)
+ return
+ }
+ start, resume = n, true
+ }
+ }
rc := http.NewResponseController(w)
if guard != nil {
@@ -172,13 +203,63 @@ func (h *handlers) stream(w http.ResponseWriter, r *http.Request) {
return write("event: update\ndata: " + strconv.FormatInt(seq, 10) + "\n\n")
}
- // The connect-time event is load-bearing, not an optimisation. It
- // is what heals a tab whose cursor legitimately failed to advance
- // (a POST whose seq was not cursor+1, design D3), and it covers
- // the gap between the page rendering server-side and this stream
- // opening. Sending the current seq unconditionally costs a client
- // that is already current exactly one empty ?since= fetch.
- if !event(current) {
+ // A push stream: hello first (stream id, the log's current seq, the log
+ // epoch), registered with its session for Docs-Stream (§3.4).
+ var (
+ streamID string
+ sent = start
+ cache *frameCache
+ )
+ flushFrames := func() bool { return true }
+ if push {
+ streamID = newStreamID()
+ h.pushRegistry.open(streamID, pushStream{session: sessionBinding(r), docID: doc.ID})
+ defer h.pushRegistry.close(streamID)
+ if h.pushFrameCache {
+ cache = h.pushRegistry.cacheFor(doc.ID)
+ defer h.pushRegistry.releaseCache(doc.ID)
+ }
+ flushFrames = func() bool {
+ rows, current, err := h.rowsAfter(r.Context(), doc, sent, cache)
+ if err != nil {
+ h.logger.Error("docs: stream: read rows", "sqid", doc.Sqid, "err", err)
+ return false
+ }
+ text, next := h.pushFrames(doc.ID, streamID, rows, current, sent)
+ if text == "" {
+ return true
+ }
+ if !write(text) {
+ return false
+ }
+ h.pushStats.frames.Add(1)
+ sent = next
+ return true
+ }
+ if !write("event: hello\ndata: " + streamID + " " + strconv.FormatInt(current, 10) + " " + h.store.logEpoch + "\n\n") {
+ return
+ }
+ }
+ bye := func(reason string) {
+ if push {
+ write("event: bye\ndata: " + reason + "\n\n")
+ }
+ }
+
+ if push && resume {
+ // What the client missed since its cursor arrives as frames: the
+ // connect-time fetch goes away.
+ if !flushFrames() {
+ return
+ }
+ } else if !event(current) {
+ // The connect-time event is load-bearing, not an optimisation. It
+ // is what heals a tab whose cursor legitimately failed to advance
+ // (a POST whose seq was not cursor+1, design D3), and it covers
+ // the gap between the page rendering server-side and this stream
+ // opening. Sending the current seq unconditionally costs a client
+ // that is already current exactly one empty ?since= fetch. A push
+ // stream opened without a cursor keeps it, after hello.
return
}
@@ -190,6 +271,7 @@ func (h *handlers) stream(w http.ResponseWriter, r *http.Request) {
for {
select {
case <-leaseDeadline:
+ bye("lease")
return
case <-r.Context().Done():
// The client went away.
@@ -199,13 +281,19 @@ func (h *handlers) stream(w http.ResponseWriter, r *http.Request) {
// request's context: this is what lets the graceful shutdown
// finish instead of waiting out its deadline on an open
// stream (hub.drain).
+ bye("drain")
return
case <-ttl.C:
// A clean close, not an error: the client reopens if it
// still wants one, and a parked tab does not.
+ bye("ttl")
return
case seq := <-ch:
- if !event(seq) {
+ if push {
+ if !flushFrames() {
+ return
+ }
+ } else if !event(seq) {
return
}
heartbeat.Reset(h.heartbeatInterval())
@@ -234,6 +322,15 @@ func (h *handlers) heartbeatInterval() time.Duration {
return defaultStreamHeartbeat
}
+// leaseLead is pushLeaseLead, or the tests' override (a lead longer than
+// the lease ends the stream with `bye lease` at once).
+func (h *handlers) leaseLead() time.Duration {
+ if h.pushLeaseLead > 0 {
+ return h.pushLeaseLead
+ }
+ return pushLeaseLead
+}
+
func (h *handlers) ttlInterval() time.Duration {
if h.streamTTL > 0 {
return h.streamTTL
diff --git a/internal/docs/testing.go b/internal/docs/testing.go
index 2437157..8792862 100644
--- a/internal/docs/testing.go
+++ b/internal/docs/testing.go
@@ -421,3 +421,9 @@ func TestViewSources(t *testing.T) map[string]string {
}
return out
}
+
+// TestSetLateLimit raises (or lowers) the per-session late-answer limit
+// (push.go, the live-push spec's §5). For the live-push probe, whose
+// simulated clients all share one session where real ones each have their
+// own: without it, five probe typists in one document pace each other.
+func (a *App) TestSetLateLimit(n int) { a.handlers.late.limit = n }
diff --git a/internal/docs/warm.go b/internal/docs/warm.go
index 15269fb..f8c907d 100644
--- a/internal/docs/warm.go
+++ b/internal/docs/warm.go
@@ -404,12 +404,14 @@ func (s *Store) boundTo(tx *gorm.DB) *Store {
// ParseWarmHandle reads $DOCS_WARM_HANDLE: on/off (also 1/0, true/false);
// unset is off. Anything else is a startup refusal rather than a guess.
-func ParseWarmHandle(v string) (bool, error) {
+func ParseWarmHandle(v string) (bool, error) { return parseOnOff("DOCS_WARM_HANDLE", v) }
+
+func parseOnOff(name, v string) (bool, error) {
switch v {
case "", "off", "0", "false":
return false, nil
case "on", "1", "true":
return true, nil
}
- return false, fmt.Errorf("docs: DOCS_WARM_HANDLE must be on or off, not %q", v)
+ return false, fmt.Errorf("docs: %s must be on or off, not %q", name, v)
}