| 1 | // Package server is the producer half of the suite contract: the three |
| 2 | // routes an app of record serves so a same-team consumer (memoria) can hold |
| 3 | // and rule on its items. Doctrine §6; revision 10 (Paul, 2026-11-01) for what |
| 4 | // is held. |
| 5 | // |
| 6 | // An app implements Producer — its feed, its own per-person read check, and |
| 7 | // an item's text — and mounts Handler beside its router. Handler is the only |
| 8 | // thing an app mounts; its conformance test is conformance.RunProducer, which |
| 9 | // drives Handler through a bearer token it mints for itself. Everything the |
| 10 | // contract fixes and an app could get subtly wrong lives here instead: the |
| 11 | // bearer check, the strict S2 decode and cap, the wire shapes, the cache |
| 12 | // headers on every response, the cursor reset, and the one byte-identical |
| 13 | // refusal S3 gives for anything it will not serve. |
| 14 | // |
| 15 | // Like the rest of the module it has no dependencies beyond the standard |
| 16 | // library, so an app's pin chain stays one deep (AGENTS.md). |
| 17 | package server |
| 18 | |
| 19 | import ( |
| 20 | "context" |
| 21 | "encoding/json" |
| 22 | "errors" |
| 23 | "io" |
| 24 | "log/slog" |
| 25 | "net/http" |
| 26 | "strconv" |
| 27 | "strings" |
| 28 | |
| 29 | "amadan.net/oficina/suite" |
| 30 | ) |
| 31 | |
| 32 | // Producer is an app's half of the contract. |
| 33 | // |
| 34 | // Revisions name bytes for ever (doctrine §6.6, revision 11). An (item, |
| 35 | // revision) a producer has once issued names one byte sequence, and no |
| 36 | // revision is ever issued twice — not after a restore from a backup either. |
| 37 | // A counter or a clock is reissued by a restore: an old revision a consumer |
| 38 | // holds then matches different bytes, and Rule says VISIBLE over text the |
| 39 | // item no longer has. A producer whose revisions can be reissued is not |
| 40 | // conformant. Draw them at random (Docs and Fichas use a random positive |
| 41 | // int63) and redraw on a collision with ANY revision the log holds for the |
| 42 | // item, not only the current one — a draw equal to a prior revision would |
| 43 | // give an old name to new bytes. Decide STALE from the producer's own log, |
| 44 | // never by comparing numbers. |
| 45 | type Producer interface { |
| 46 | // Feed returns the rows after cursor — "" is the beginning — at most |
| 47 | // limit of them, in the app's own log order, and the cursor to ask from |
| 48 | // next. At the tip it returns rows: [] and the SAME cursor it was given |
| 49 | // (a consumer stops polling only when the cursor comes back unchanged |
| 50 | // with no rows; a fresh cursor at the tip makes it page forever). The |
| 51 | // cursor is opaque and never empty, and every row's revision is 1 or |
| 52 | // more. |
| 53 | // |
| 54 | // A cursor the producer's log does not recognise — the log was restored |
| 55 | // from a backup, another log issued it, or it names a position the log |
| 56 | // has since expired or compacted away — is ErrCursorReset, never the tip |
| 57 | // and never a failure: this package answers it with S1's one fixed 409, |
| 58 | // the one way a consumer is told to start over, and the consumer hides |
| 59 | // everything it holds from this producer and reads from "" (§6.6). So a |
| 60 | // cursor must carry enough to be recognised: a position alone is |
| 61 | // reissued by a restore. Its stamp is normative: either drawn at random |
| 62 | // per event and written with that event, or minted when the log is |
| 63 | // restored and never itself restored from a backup. A generation id kept |
| 64 | // in the same restorable database is not enough — the restore brings the |
| 65 | // old generation back with it. "" is never reset. |
| 66 | // |
| 67 | // Since revision 10 the feed carries every live item, private and |
| 68 | // granted ones included; gone means deleted, and nothing else. |
| 69 | Feed(ctx context.Context, cursor string, limit int) (suite.Feed, error) |
| 70 | |
| 71 | // Rule answers, for each pair in order, whether asker may open that item |
| 72 | // now: the app's own read check (team rung, ownership, a live grant; |
| 73 | // never a link). For a person removed from the team, doctrine gate 5's |
| 74 | // reading stands: one holding no other grant gets NOT_VISIBLE, and losing |
| 75 | // team standing does not by itself revoke what they own or were granted |
| 76 | // individually. Revision 11 proposed that such a person reach nothing, |
| 77 | // ownership included; Paul has not ruled, so that is not the contract |
| 78 | // (doctrine §4.3, §14). VISIBLE at the current revision; STALE when |
| 79 | // the asker may open it and the asked revision is one the log holds that |
| 80 | // is not current; NOT_VISIBLE when the asker may not, or the item is |
| 81 | // deleted or an id the app does not know; UNKNOWN when the app cannot |
| 82 | // say (an asker of a kind it does not key on, a revision its log does not |
| 83 | // hold, a roster it cannot reach). The person is checked before the |
| 84 | // revision: a person who may not open the item learns nothing about its |
| 85 | // revisions. Never cached. It returns exactly len(pairs) answers. |
| 86 | Rule(ctx context.Context, asker suite.Subject, pairs []suite.ItemRevision) ([]suite.Authorization, error) |
| 87 | |
| 88 | // Content returns the item's text at revision, as the plain text a |
| 89 | // consumer indexes. suite.ErrNotAvailable for a deleted item, an unknown |
| 90 | // id, or a revision that is not the current one (one the log holds, or |
| 91 | // one it never issued); this package turns it into the one refusal every |
| 92 | // such case shares. |
| 93 | Content(ctx context.Context, itemID string, revision int64) ([]byte, error) |
| 94 | } |
| 95 | |
| 96 | // FeedPageLimit is how many rows one S1 page carries. memoria caps an S1 |
| 97 | // response at 4 MiB; a row is under 200 bytes on the wire, so 256 rows sit |
| 98 | // two orders of magnitude inside it, and memoria pages up to 50 times a poll. |
| 99 | const FeedPageLimit = 256 |
| 100 | |
| 101 | // MaxContentBytes is the largest body S3 serves. memoria refuses a body over |
| 102 | // 2 MiB + 64 KiB as an error and retries the same feed page for ever, so an |
| 103 | // item over this is answered as not available instead — counted by the |
| 104 | // consumer as missing, and the feed moves on. The slack keeps a body at |
| 105 | // exactly this size well inside the consumer's cap. |
| 106 | const MaxContentBytes = 2 << 20 |
| 107 | |
| 108 | // maxS2Body bounds an S2 request: 256 pairs of a long id and a revision, |
| 109 | // and an asker, are far under it. |
| 110 | const maxS2Body = 256 << 10 |
| 111 | |
| 112 | // ErrCursorReset is what Feed returns for a cursor its log does not |
| 113 | // recognise. It is suite.ErrCursorReset itself, so either name matches with |
| 114 | // errors.Is; this package answers it with suite.CursorResetStatus and |
| 115 | // suite.CursorResetBody (doctrine §6.6). |
| 116 | var ErrCursorReset = suite.ErrCursorReset |
| 117 | |
| 118 | // Handler returns the authenticated routes, or nil when no consumer is |
| 119 | // configured: an app with no consumers serves no suite routes at all |
| 120 | // (doctrine §3, A.2 — the routes exist wherever consumer tokens do). It is |
| 121 | // the only thing an app mounts. |
| 122 | func Handler(p Producer, consumers []Consumer, logger *slog.Logger) http.Handler { |
| 123 | if len(consumers) == 0 { |
| 124 | return nil |
| 125 | } |
| 126 | return Authenticate(consumers, routes(p, logger)) |
| 127 | } |
| 128 | |
| 129 | // Routes is the three routes with NO bearer check: mounted, it serves every |
| 130 | // live item — private ones included — to anybody who can reach the app. |
| 131 | // |
| 132 | // Deprecated: never mount it. Mount Handler, and test with |
| 133 | // conformance.RunProducer or conformance.CheckProducer, which drive Handler |
| 134 | // through a token they mint (revision 11). Routes stays only because the |
| 135 | // module is additive (AGENTS.md) and Docs' and Fichas' tests call it. |
| 136 | func Routes(p Producer, logger *slog.Logger) http.Handler { |
| 137 | return routes(p, logger) |
| 138 | } |
| 139 | |
| 140 | func routes(p Producer, logger *slog.Logger) http.Handler { |
| 141 | if logger == nil { |
| 142 | logger = slog.New(slog.NewTextHandler(io.Discard, nil)) |
| 143 | } |
| 144 | mux := http.NewServeMux() |
| 145 | mux.HandleFunc("GET "+suite.RouteS1, func(w http.ResponseWriter, r *http.Request) { serveS1(p, logger, w, r) }) |
| 146 | mux.HandleFunc("POST "+suite.RouteS2, func(w http.ResponseWriter, r *http.Request) { serveS2(p, logger, w, r) }) |
| 147 | mux.HandleFunc("GET "+suite.RouteS3+"/{item}", func(w http.ResponseWriter, r *http.Request) { serveS3(p, logger, w, r) }) |
| 148 | return noStore(mux) |
| 149 | } |
| 150 | |
| 151 | // noStore marks every response this package writes, the mux's own 404 and |
| 152 | // 405 included, as one nobody may keep: an S2 answer is one person's, and |
| 153 | // an S3 body may be a private item's. no-store keeps a cache at the platform |
| 154 | // edge from serving it to the next request (leak list item 11's shape); |
| 155 | // Vary: Authorization says, to any cache that ignores no-store, that a |
| 156 | // response belongs to the credential that fetched it. Set before anything |
| 157 | // else is written, so a refusal carries exactly the headers every other |
| 158 | // refusal does (Fable, review of c38e3ad, M3). |
| 159 | func noStore(next http.Handler) http.Handler { |
| 160 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 161 | w.Header().Set("Cache-Control", "no-store") |
| 162 | w.Header().Set("Vary", "Authorization") |
| 163 | next.ServeHTTP(w, r) |
| 164 | }) |
| 165 | } |
| 166 | |
| 167 | func serveS1(p Producer, logger *slog.Logger, w http.ResponseWriter, r *http.Request) { |
| 168 | cursor := r.URL.Query().Get("cursor") |
| 169 | feed, err := p.Feed(r.Context(), cursor, FeedPageLimit) |
| 170 | if errors.Is(err, ErrCursorReset) { |
| 171 | if cursor == "" { |
| 172 | // The beginning names no position, so it cannot be one the log |
| 173 | // lost; a reset here would send a consumer back to "" for ever. |
| 174 | logger.Error("suite S1: the producer reset the beginning") |
| 175 | w.WriteHeader(http.StatusInternalServerError) |
| 176 | return |
| 177 | } |
| 178 | // The fixed body and nothing else: no position, no count, no reason. |
| 179 | w.Header().Set("Content-Type", "application/json") |
| 180 | w.WriteHeader(suite.CursorResetStatus) |
| 181 | io.WriteString(w, suite.CursorResetBody) |
| 182 | return |
| 183 | } |
| 184 | if err != nil { |
| 185 | // Never an empty feed: an empty page for a failed read would move a |
| 186 | // consumer's cursor past changes it never saw. |
| 187 | // A fixed string, never the error: a producer's error can carry a |
| 188 | // title or a passage, and logs are storage nobody can grep clean. |
| 189 | logger.Error("suite S1: the producer's feed failed") |
| 190 | w.WriteHeader(http.StatusServiceUnavailable) |
| 191 | return |
| 192 | } |
| 193 | if err := checkFeed(feed); err != nil { |
| 194 | logger.Error("suite S1: the producer's page broke the contract", "rule", err.Error()) |
| 195 | w.WriteHeader(http.StatusInternalServerError) |
| 196 | return |
| 197 | } |
| 198 | if feed.Rows == nil { |
| 199 | feed.Rows = []suite.FeedRow{} |
| 200 | } |
| 201 | writeJSON(w, feed) |
| 202 | } |
| 203 | |
| 204 | // checkFeed holds the producer to what DecodeS1 will demand, so a mistake is |
| 205 | // a 500 here rather than a consumer stalling on a page it refuses. Its errors |
| 206 | // are fixed strings of this package's own, never the producer's, so they may |
| 207 | // be logged. |
| 208 | func checkFeed(f suite.Feed) error { |
| 209 | if f.Cursor == "" { |
| 210 | return errors.New("empty cursor") |
| 211 | } |
| 212 | if len(f.Rows) > FeedPageLimit { |
| 213 | return errors.New("page over the limit") |
| 214 | } |
| 215 | for _, row := range f.Rows { |
| 216 | if row.ItemID == "" || row.TouchedAt.IsZero() { |
| 217 | return errors.New("row without an item id or a time") |
| 218 | } |
| 219 | if row.Revision < 1 { |
| 220 | // S2 and S3 refuse a revision under 1, so a row carrying one |
| 221 | // could never be asked about or fetched. |
| 222 | return errors.New("row with a revision under 1") |
| 223 | } |
| 224 | } |
| 225 | return nil |
| 226 | } |
| 227 | |
| 228 | type s2Result struct { |
| 229 | ItemID string `json:"item_id"` |
| 230 | Revision int64 `json:"revision"` |
| 231 | Result suite.Authorization `json:"result"` |
| 232 | } |
| 233 | |
| 234 | func serveS2(p Producer, logger *slog.Logger, w http.ResponseWriter, r *http.Request) { |
| 235 | dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxS2Body)) |
| 236 | dec.DisallowUnknownFields() |
| 237 | var req suite.S2Request |
| 238 | if err := dec.Decode(&req); err != nil || !atEOF(dec) { |
| 239 | w.WriteHeader(http.StatusBadRequest) |
| 240 | return |
| 241 | } |
| 242 | asker, err := suite.NewSubject(req.Asker.Kind, req.Asker.Value) |
| 243 | if err != nil || req.Pairs == nil || suite.CheckS2Batch(req.Pairs) != nil { |
| 244 | w.WriteHeader(http.StatusBadRequest) |
| 245 | return |
| 246 | } |
| 247 | for _, pr := range req.Pairs { |
| 248 | // No revision under 1, as S3 refuses one: no producer issues it, so |
| 249 | // a pair carrying one is a consumer bug, refused rather than ruled |
| 250 | // (Fable, review of c38e3ad, L5). |
| 251 | if pr.ItemID == "" || pr.Revision < 1 { |
| 252 | w.WriteHeader(http.StatusBadRequest) |
| 253 | return |
| 254 | } |
| 255 | } |
| 256 | answers, err := p.Rule(r.Context(), asker, req.Pairs) |
| 257 | if err != nil { |
| 258 | // A non-2xx is UNKNOWN for the whole call on the consumer's side: |
| 259 | // withheld loudly, never silently. |
| 260 | logger.Error("suite S2: the producer's rule failed") |
| 261 | w.WriteHeader(http.StatusServiceUnavailable) |
| 262 | return |
| 263 | } |
| 264 | if len(answers) != len(req.Pairs) { |
| 265 | logger.Error("suite S2: the producer answered a different number of pairs") |
| 266 | w.WriteHeader(http.StatusInternalServerError) |
| 267 | return |
| 268 | } |
| 269 | out := struct { |
| 270 | Results []s2Result `json:"results"` |
| 271 | }{Results: make([]s2Result, len(answers))} |
| 272 | for i, a := range answers { |
| 273 | out.Results[i] = s2Result{ItemID: req.Pairs[i].ItemID, Revision: req.Pairs[i].Revision, Result: a} |
| 274 | } |
| 275 | writeJSON(w, out) |
| 276 | } |
| 277 | |
| 278 | func serveS3(p Producer, logger *slog.Logger, w http.ResponseWriter, r *http.Request) { |
| 279 | item := r.PathValue("item") |
| 280 | rev, err := strconv.ParseInt(r.URL.Query().Get("revision"), 10, 64) |
| 281 | if item == "" || err != nil || rev < 1 { |
| 282 | notAvailable(w) |
| 283 | return |
| 284 | } |
| 285 | body, err := p.Content(r.Context(), item, rev) |
| 286 | switch { |
| 287 | case errors.Is(err, suite.ErrNotAvailable): |
| 288 | notAvailable(w) |
| 289 | return |
| 290 | case err != nil: |
| 291 | logger.Error("suite S3: the producer's content failed") |
| 292 | w.WriteHeader(http.StatusServiceUnavailable) |
| 293 | return |
| 294 | case len(body) > MaxContentBytes: |
| 295 | notAvailable(w) |
| 296 | return |
| 297 | } |
| 298 | w.Header().Set("Content-Type", "text/plain; charset=utf-8") |
| 299 | w.WriteHeader(http.StatusOK) |
| 300 | w.Write(body) |
| 301 | } |
| 302 | |
| 303 | // notAvailable is the one refusal S3 gives: the same status, headers and |
| 304 | // (empty) body for a deleted item, an id that never existed, a superseded or |
| 305 | // malformed revision and an item too large to serve, so none of them can be |
| 306 | // told apart. Never 403. |
| 307 | func notAvailable(w http.ResponseWriter) { |
| 308 | w.WriteHeader(http.StatusNotFound) |
| 309 | } |
| 310 | |
| 311 | func writeJSON(w http.ResponseWriter, v any) { |
| 312 | w.Header().Set("Content-Type", "application/json") |
| 313 | w.WriteHeader(http.StatusOK) |
| 314 | json.NewEncoder(w).Encode(v) |
| 315 | } |
| 316 | |
| 317 | // contextKey carries the authenticated consumer. |
| 318 | type contextKey struct{} |
| 319 | |
| 320 | // ConsumerFrom returns the consumer a request authenticated as, for an app |
| 321 | // that keeps per-consumer state. |
| 322 | func ConsumerFrom(ctx context.Context) (Consumer, bool) { |
| 323 | c, ok := ctx.Value(contextKey{}).(Consumer) |
| 324 | return c, ok |
| 325 | } |
| 326 | |
| 327 | func bearer(r *http.Request) (string, bool) { |
| 328 | h := r.Header.Get("Authorization") |
| 329 | const prefix = "Bearer " |
| 330 | if len(h) <= len(prefix) || !strings.EqualFold(h[:len(prefix)], prefix) { |
| 331 | return "", false |
| 332 | } |
| 333 | return strings.TrimSpace(h[len(prefix):]), true |
| 334 | } |
| 335 | |
| 336 | func contextWithConsumer(ctx context.Context, c Consumer) context.Context { |
| 337 | return context.WithValue(ctx, contextKey{}, c) |
| 338 | } |
| 339 | |
| 340 | // atEOF is the end-of-input check. Decoder.More is not one: it answers false |
| 341 | // before a stray ']' or '}', so a valid document followed by either passed |
| 342 | // as strict (Astra, 2026-11-01). Decoding once more must find nothing. |
| 343 | func atEOF(dec *json.Decoder) bool { |
| 344 | var extra json.RawMessage |
| 345 | return dec.Decode(&extra) == io.EOF |
| 346 | } |
| 347 | |