| 1 | package slides |
| 2 | |
| 3 | import ( |
| 4 | "io" |
| 5 | "net/http" |
| 6 | "sync" |
| 7 | ) |
| 8 | |
| 9 | // drain is the process going away. net/http's graceful shutdown waits for |
| 10 | // every request in progress and cancels none of their contexts, so a |
| 11 | // stream (the editor's, a projector's, a follower's), which ends only when |
| 12 | // its client leaves or its TTL runs out, held the shutdown for the whole |
| 13 | // of rastrillo's ten-second budget, and the process then exited 1 with |
| 14 | // "context deadline exceeded". Docs did exactly that on 2026-10-26 12:49, |
| 15 | // when the platform stopped every instance on the box; the listener closes |
| 16 | // as the shutdown begins, so for those ten seconds the instance took no |
| 17 | // new request either (Docs #94). Slides had the same three handlers |
| 18 | // believing r.Context() would end on a drain. |
| 19 | // |
| 20 | // Lazy, so the zero app works: New fills its app in with one assignment. |
| 21 | type drain struct { |
| 22 | once sync.Once |
| 23 | ch chan struct{} |
| 24 | closeOnce sync.Once |
| 25 | } |
| 26 | |
| 27 | func (d *drain) channel() chan struct{} { |
| 28 | d.once.Do(func() { d.ch = make(chan struct{}) }) |
| 29 | return d.ch |
| 30 | } |
| 31 | |
| 32 | func (d *drain) done() <-chan struct{} { return d.channel() } |
| 33 | |
| 34 | func (d *drain) close() { |
| 35 | ch := d.channel() |
| 36 | d.closeOnce.Do(func() { close(ch) }) |
| 37 | } |
| 38 | |
| 39 | // Drain ends every open stream, and every stream opened after it at once. |
| 40 | // cmd/slides calls it the moment SIGTERM or SIGINT arrives, beside |
| 41 | // rastrillo.Serve's own graceful shutdown. Safe to call more than once. |
| 42 | func (a *app) Drain() { a.draining.close() } |
| 43 | |
| 44 | // drained answers a stream opened while the process is stopping: an |
| 45 | // immediate, clean end, with a reconnection delay. Not an error status: |
| 46 | // the presenting pages rely on EventSource's own reconnection, which an |
| 47 | // error status ends for good, and the instance that answers the |
| 48 | // reconnection is the next one. The editor closes on the end and reopens |
| 49 | // on its next activity (fixtures/live-updates.mjs). |
| 50 | func drained(w http.ResponseWriter) { |
| 51 | w.Header().Set("Content-Type", "text/event-stream") |
| 52 | w.Header().Set("Cache-Control", "no-store") |
| 53 | w.WriteHeader(http.StatusOK) |
| 54 | _, _ = io.WriteString(w, "retry: 3000\n\n") |
| 55 | } |
| 56 | |
| 57 | // stopping reports whether Drain has been called. |
| 58 | func (a *app) stopping() bool { |
| 59 | select { |
| 60 | case <-a.draining.done(): |
| 61 | return true |
| 62 | default: |
| 63 | return false |
| 64 | } |
| 65 | } |
| 66 | |