oficina / sheets Public

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

Plain git — no account needed to clone.

Download

Download this file

1package sheets
2
3import (
4 "net/http"
5 "time"
6)
7
8// The idle policy, written down rather than emergent (spec §7). Held
9// sockets and hibernation pull against each other, and this is where
10// that is resolved.
11//
12// pingEvery keeps the connection alive through proxies that drop a
13// silent stream, and gives the client something to notice when the
14// server has gone away.
15//
16// idleTimeout closes a stream that has carried no edit. maxStreamLife
17// closes one regardless of activity, so a tab left open all weekend
18// cannot hold an instance awake and billable indefinitely.
19//
20// Spec §7 words the idle policy as "no edits and no presence
21// heartbeat". There is no heartbeat here, and the reason is worth
22// stating rather than leaving as a gap: a heartbeat POST arrives as a
23// separate request with no way to reach the specific goroutine holding
24// the stream, so it would have had to be routed through the hub by
25// connection id — real machinery to reproduce something the connection
26// itself already tells us. Instead the client CLOSES its stream when
27// the tab is hidden and opens a new one when it comes back, which is
28// strictly stronger than a heartbeat that stops: a hidden tab holds no
29// socket at all rather than an idle one.
30//
31// That only works with the client's cooperation, and it is worth being
32// plain that the server cannot enforce it: EventSource reconnects on
33// its own after any close, so a client that ignores the "bye" event
34// below will simply come straight back. The server's timeouts are
35// therefore a backstop against clients that vanished without saying so
36// — a sleeping laptop, a dropped network — and not the whole policy.
37const (
38 pingEvery = 25 * time.Second
39 idleTimeout = 15 * time.Minute
40 maxStreamLife = 4 * time.Hour
41)
42
43// handleStream is the live connection: a streamed 200 carrying
44// text/event-stream, one message per committed write on this tab.
45//
46// A streamed 200, NOT a 101 (spec §7). SSE is an ordinary response with
47// a streaming body; 101 is the WebSocket upgrade, and a transport check
48// written against 101 would never pass here. The conflation is worth
49// naming because the source document this design came from made it.
50func (a *App) handleStream(w http.ResponseWriter, r *http.Request) {
51 _, ok := a.actor(r)
52 if !ok {
53 a.notFound(w, r)
54 return
55 }
56 sheetID, tabID := sheetIDFrom(r), tabIDFrom(r)
57 if sheetID == 0 || tabID == 0 || !a.tabBelongsTo(sheetID, tabID) {
58 a.notFound(w, r)
59 return
60 }
61 // The stream carries every cell of every edit on this tab, so it
62 // needs the same grant a read of the grid does. Without this check
63 // the fan-out would be the one route that ignored sharing entirely
64 // — and the quietest possible leak, since nothing renders it.
65 allowed, renew := a.streamAccess(r, sheetID)
66 if !allowed {
67 a.notFound(w, r)
68 return
69 }
70
71 sub := a.hub.Subscribe(tabID)
72 defer sub.Close()
73 rc := http.NewResponseController(w)
74
75 w.Header().Set("Content-Type", "text/event-stream")
76 w.Header().Set("Cache-Control", "no-store")
77 w.Header().Set("Connection", "keep-alive")
78 // The edge will happily buffer a streaming response into a complete
79 // one, which turns live sync into "everything arrives when you
80 // close the tab". This header is what stops it, and its absence is
81 // invisible in every test that does not run through a real proxy.
82 w.Header().Set("X-Accel-Buffering", "no")
83 w.WriteHeader(http.StatusOK)
84
85 // Flushed immediately after subscribing, so the client's onopen
86 // fires immediately rather than on the first edit. A grid that says
87 // "connecting" until somebody types looks broken for as long as
88 // nobody does.
89 if err := rc.Flush(); err != nil {
90 return
91 }
92
93 ping := time.NewTicker(pingEvery)
94 defer ping.Stop()
95 idle := time.NewTimer(idleTimeout)
96 defer idle.Stop()
97 life := time.NewTimer(maxStreamLife)
98 defer life.Stop()
99 // Team mode: access that rests on roster standing lasts only as long
100 // as its lease. At the deadline it is asked again, outside SQL, and
101 // the stream either carries on under the new lease or says bye — a
102 // silent stream must not outlive a removal. Never armed outside team
103 // mode, or for access that rests on a share alone (renew 0); a nil
104 // channel never fires.
105 var lease *time.Timer
106 var leaseC <-chan time.Time
107 arm := func(d time.Duration) {
108 if lease != nil {
109 lease.Stop()
110 }
111 lease, leaseC = nil, nil
112 if d > 0 {
113 lease = time.NewTimer(d)
114 leaseC = lease.C
115 }
116 }
117 arm(renew)
118 defer func() { arm(0) }()
119
120 for {
121 select {
122 case <-r.Context().Done():
123 return
124
125 case <-life.C:
126 // The ceiling. Say so rather than dropping silently: the
127 // client reconnects on a close either way, but a named
128 // reason is the difference between a debuggable log and a
129 // mystery.
130 writeEvent(w, rc, "bye", `{"reason":"max-life"}`)
131 return
132
133 case <-idle.C:
134 writeEvent(w, rc, "bye", `{"reason":"idle"}`)
135 return
136
137 case <-leaseC:
138 ok, d := a.streamAccess(r, sheetID)
139 if !ok {
140 writeEvent(w, rc, "bye", `{"reason":"access-changed"}`)
141 return
142 }
143 arm(d)
144
145 case <-ping.C:
146 // A comment line: valid SSE, ignored by EventSource, and
147 // enough to keep an intermediary from calling the
148 // connection dead.
149 if _, err := w.Write([]byte(": ping\n\n")); err != nil {
150 return
151 }
152 if err := rc.Flush(); err != nil {
153 return
154 }
155
156 case m := <-sub.C():
157 // The grant is re-checked before every delivery, not only
158 // at subscribe.
159 //
160 // Authorization on a long-lived connection is a question
161 // about NOW, and this stream lives for up to
162 // maxStreamLife with every edit resetting the idle timer
163 // that would otherwise end it. Checked once, a revoked
164 // guest keeps receiving cells written after their access
165 // was taken away — which is the quietest possible leak,
166 // because the owner has done the thing that should have
167 // stopped it and sees no sign that it did not. Found by an
168 // independent review (Codex, 2026-09-05); the gate at open
169 // was real and ran exactly once.
170 //
171 // One indexed read per delivered message, not per edit on
172 // the instance: a subscriber only reaches this line when a
173 // message is already addressed to its tab.
174 ok, d := a.streamAccess(r, sheetID)
175 if !ok {
176 writeEvent(w, rc, "bye", `{"reason":"access-changed"}`)
177 return
178 }
179 arm(d)
180 if sub.Lost() {
181 // This subscriber overran its buffer and has missed at
182 // least one message, so everything after it would paint
183 // a grid with holes in it. Tell the client to refetch
184 // and stop: a reload is cheap, and a silently wrong
185 // spreadsheet is not.
186 writeEvent(w, rc, "resync", `{"reason":"overrun"}`)
187 return
188 }
189 if !writeEvent(w, rc, "cells", string(m.Data)) {
190 return
191 }
192 // A delivered edit resets the idle clock: this tab is
193 // demonstrably part of a live session.
194 resetTimer(idle, idleTimeout)
195 }
196 }
197}
198
199// writeEvent sends one SSE event and flushes it. It returns false once
200// the connection is gone, which is the only error worth distinguishing:
201// there is nobody left to tell.
202//
203// The data is written as a single line. Every payload this app sends is
204// compact JSON, which contains no newline — and a newline inside an SSE
205// data field would split one message into two, producing a truncated
206// JSON parse on the client rather than an error anybody could read.
207func writeEvent(w http.ResponseWriter, rc *http.ResponseController, event, data string) bool {
208 if _, err := w.Write([]byte("event: " + event + "\ndata: " + data + "\n\n")); err != nil {
209 return false
210 }
211 return rc.Flush() == nil
212}
213
214// resetTimer restarts a timer that may or may not have fired. Stop then
215// Reset is the shape that is correct for both.
216func resetTimer(t *time.Timer, d time.Duration) {
217 t.Stop()
218 t.Reset(d)
219}
220