// Package server is the producer half of the suite contract: the three // routes an app of record serves so a same-team consumer (memoria) can hold // and rule on its items. Doctrine §6; revision 10 (Paul, 2026-11-01) for what // is held. // // An app implements Producer — its feed, its own per-person read check, and // an item's text — and mounts Handler beside its router. Handler is the only // thing an app mounts; its conformance test is conformance.RunProducer, which // drives Handler through a bearer token it mints for itself. Everything the // contract fixes and an app could get subtly wrong lives here instead: the // bearer check, the strict S2 decode and cap, the wire shapes, the cache // headers on every response, the cursor reset, and the one byte-identical // refusal S3 gives for anything it will not serve. // // Like the rest of the module it has no dependencies beyond the standard // library, so an app's pin chain stays one deep (AGENTS.md). package server import ( "context" "encoding/json" "errors" "io" "log/slog" "net/http" "strconv" "strings" "amadan.net/oficina/suite" ) // Producer is an app's half of the contract. // // Revisions name bytes for ever (doctrine §6.6, revision 11). An (item, // revision) a producer has once issued names one byte sequence, and no // revision is ever issued twice — not after a restore from a backup either. // A counter or a clock is reissued by a restore: an old revision a consumer // holds then matches different bytes, and Rule says VISIBLE over text the // item no longer has. A producer whose revisions can be reissued is not // conformant. Draw them at random (Docs and Fichas use a random positive // int63) and redraw on a collision with ANY revision the log holds for the // item, not only the current one — a draw equal to a prior revision would // give an old name to new bytes. Decide STALE from the producer's own log, // never by comparing numbers. type Producer interface { // Feed returns the rows after cursor — "" is the beginning — at most // limit of them, in the app's own log order, and the cursor to ask from // next. At the tip it returns rows: [] and the SAME cursor it was given // (a consumer stops polling only when the cursor comes back unchanged // with no rows; a fresh cursor at the tip makes it page forever). The // cursor is opaque and never empty, and every row's revision is 1 or // more. // // A cursor the producer's log does not recognise — the log was restored // from a backup, another log issued it, or it names a position the log // has since expired or compacted away — is ErrCursorReset, never the tip // and never a failure: this package answers it with S1's one fixed 409, // the one way a consumer is told to start over, and the consumer hides // everything it holds from this producer and reads from "" (§6.6). So a // cursor must carry enough to be recognised: a position alone is // reissued by a restore. Its stamp is normative: either drawn at random // per event and written with that event, or minted when the log is // restored and never itself restored from a backup. A generation id kept // in the same restorable database is not enough — the restore brings the // old generation back with it. "" is never reset. // // Since revision 10 the feed carries every live item, private and // granted ones included; gone means deleted, and nothing else. Feed(ctx context.Context, cursor string, limit int) (suite.Feed, error) // Rule answers, for each pair in order, whether asker may open that item // now: the app's own read check (team rung, ownership, a live grant; // never a link). For a person removed from the team, doctrine gate 5's // reading stands: one holding no other grant gets NOT_VISIBLE, and losing // team standing does not by itself revoke what they own or were granted // individually. Revision 11 proposed that such a person reach nothing, // ownership included; Paul has not ruled, so that is not the contract // (doctrine §4.3, §14). VISIBLE at the current revision; STALE when // the asker may open it and the asked revision is one the log holds that // is not current; NOT_VISIBLE when the asker may not, or the item is // deleted or an id the app does not know; UNKNOWN when the app cannot // say (an asker of a kind it does not key on, a revision its log does not // hold, a roster it cannot reach). The person is checked before the // revision: a person who may not open the item learns nothing about its // revisions. Never cached. It returns exactly len(pairs) answers. Rule(ctx context.Context, asker suite.Subject, pairs []suite.ItemRevision) ([]suite.Authorization, error) // Content returns the item's text at revision, as the plain text a // consumer indexes. suite.ErrNotAvailable for a deleted item, an unknown // id, or a revision that is not the current one (one the log holds, or // one it never issued); this package turns it into the one refusal every // such case shares. Content(ctx context.Context, itemID string, revision int64) ([]byte, error) } // FeedPageLimit is how many rows one S1 page carries. memoria caps an S1 // response at 4 MiB; a row is under 200 bytes on the wire, so 256 rows sit // two orders of magnitude inside it, and memoria pages up to 50 times a poll. const FeedPageLimit = 256 // MaxContentBytes is the largest body S3 serves. memoria refuses a body over // 2 MiB + 64 KiB as an error and retries the same feed page for ever, so an // item over this is answered as not available instead — counted by the // consumer as missing, and the feed moves on. The slack keeps a body at // exactly this size well inside the consumer's cap. const MaxContentBytes = 2 << 20 // maxS2Body bounds an S2 request: 256 pairs of a long id and a revision, // and an asker, are far under it. const maxS2Body = 256 << 10 // ErrCursorReset is what Feed returns for a cursor its log does not // recognise. It is suite.ErrCursorReset itself, so either name matches with // errors.Is; this package answers it with suite.CursorResetStatus and // suite.CursorResetBody (doctrine §6.6). var ErrCursorReset = suite.ErrCursorReset // Handler returns the authenticated routes, or nil when no consumer is // configured: an app with no consumers serves no suite routes at all // (doctrine §3, A.2 — the routes exist wherever consumer tokens do). It is // the only thing an app mounts. func Handler(p Producer, consumers []Consumer, logger *slog.Logger) http.Handler { if len(consumers) == 0 { return nil } return Authenticate(consumers, routes(p, logger)) } // Routes is the three routes with NO bearer check: mounted, it serves every // live item — private ones included — to anybody who can reach the app. // // Deprecated: never mount it. Mount Handler, and test with // conformance.RunProducer or conformance.CheckProducer, which drive Handler // through a token they mint (revision 11). Routes stays only because the // module is additive (AGENTS.md) and Docs' and Fichas' tests call it. func Routes(p Producer, logger *slog.Logger) http.Handler { return routes(p, logger) } func routes(p Producer, logger *slog.Logger) http.Handler { if logger == nil { logger = slog.New(slog.NewTextHandler(io.Discard, nil)) } mux := http.NewServeMux() mux.HandleFunc("GET "+suite.RouteS1, func(w http.ResponseWriter, r *http.Request) { serveS1(p, logger, w, r) }) mux.HandleFunc("POST "+suite.RouteS2, func(w http.ResponseWriter, r *http.Request) { serveS2(p, logger, w, r) }) mux.HandleFunc("GET "+suite.RouteS3+"/{item}", func(w http.ResponseWriter, r *http.Request) { serveS3(p, logger, w, r) }) return noStore(mux) } // noStore marks every response this package writes, the mux's own 404 and // 405 included, as one nobody may keep: an S2 answer is one person's, and // an S3 body may be a private item's. no-store keeps a cache at the platform // edge from serving it to the next request (leak list item 11's shape); // Vary: Authorization says, to any cache that ignores no-store, that a // response belongs to the credential that fetched it. Set before anything // else is written, so a refusal carries exactly the headers every other // refusal does (Fable, review of c38e3ad, M3). func noStore(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Cache-Control", "no-store") w.Header().Set("Vary", "Authorization") next.ServeHTTP(w, r) }) } func serveS1(p Producer, logger *slog.Logger, w http.ResponseWriter, r *http.Request) { cursor := r.URL.Query().Get("cursor") feed, err := p.Feed(r.Context(), cursor, FeedPageLimit) if errors.Is(err, ErrCursorReset) { if cursor == "" { // The beginning names no position, so it cannot be one the log // lost; a reset here would send a consumer back to "" for ever. logger.Error("suite S1: the producer reset the beginning") w.WriteHeader(http.StatusInternalServerError) return } // The fixed body and nothing else: no position, no count, no reason. w.Header().Set("Content-Type", "application/json") w.WriteHeader(suite.CursorResetStatus) io.WriteString(w, suite.CursorResetBody) return } if err != nil { // Never an empty feed: an empty page for a failed read would move a // consumer's cursor past changes it never saw. // A fixed string, never the error: a producer's error can carry a // title or a passage, and logs are storage nobody can grep clean. logger.Error("suite S1: the producer's feed failed") w.WriteHeader(http.StatusServiceUnavailable) return } if err := checkFeed(feed); err != nil { logger.Error("suite S1: the producer's page broke the contract", "rule", err.Error()) w.WriteHeader(http.StatusInternalServerError) return } if feed.Rows == nil { feed.Rows = []suite.FeedRow{} } writeJSON(w, feed) } // checkFeed holds the producer to what DecodeS1 will demand, so a mistake is // a 500 here rather than a consumer stalling on a page it refuses. Its errors // are fixed strings of this package's own, never the producer's, so they may // be logged. func checkFeed(f suite.Feed) error { if f.Cursor == "" { return errors.New("empty cursor") } if len(f.Rows) > FeedPageLimit { return errors.New("page over the limit") } for _, row := range f.Rows { if row.ItemID == "" || row.TouchedAt.IsZero() { return errors.New("row without an item id or a time") } if row.Revision < 1 { // S2 and S3 refuse a revision under 1, so a row carrying one // could never be asked about or fetched. return errors.New("row with a revision under 1") } } return nil } type s2Result struct { ItemID string `json:"item_id"` Revision int64 `json:"revision"` Result suite.Authorization `json:"result"` } func serveS2(p Producer, logger *slog.Logger, w http.ResponseWriter, r *http.Request) { dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxS2Body)) dec.DisallowUnknownFields() var req suite.S2Request if err := dec.Decode(&req); err != nil || !atEOF(dec) { w.WriteHeader(http.StatusBadRequest) return } asker, err := suite.NewSubject(req.Asker.Kind, req.Asker.Value) if err != nil || req.Pairs == nil || suite.CheckS2Batch(req.Pairs) != nil { w.WriteHeader(http.StatusBadRequest) return } for _, pr := range req.Pairs { // No revision under 1, as S3 refuses one: no producer issues it, so // a pair carrying one is a consumer bug, refused rather than ruled // (Fable, review of c38e3ad, L5). if pr.ItemID == "" || pr.Revision < 1 { w.WriteHeader(http.StatusBadRequest) return } } answers, err := p.Rule(r.Context(), asker, req.Pairs) if err != nil { // A non-2xx is UNKNOWN for the whole call on the consumer's side: // withheld loudly, never silently. logger.Error("suite S2: the producer's rule failed") w.WriteHeader(http.StatusServiceUnavailable) return } if len(answers) != len(req.Pairs) { logger.Error("suite S2: the producer answered a different number of pairs") w.WriteHeader(http.StatusInternalServerError) return } out := struct { Results []s2Result `json:"results"` }{Results: make([]s2Result, len(answers))} for i, a := range answers { out.Results[i] = s2Result{ItemID: req.Pairs[i].ItemID, Revision: req.Pairs[i].Revision, Result: a} } writeJSON(w, out) } func serveS3(p Producer, logger *slog.Logger, w http.ResponseWriter, r *http.Request) { item := r.PathValue("item") rev, err := strconv.ParseInt(r.URL.Query().Get("revision"), 10, 64) if item == "" || err != nil || rev < 1 { notAvailable(w) return } body, err := p.Content(r.Context(), item, rev) switch { case errors.Is(err, suite.ErrNotAvailable): notAvailable(w) return case err != nil: logger.Error("suite S3: the producer's content failed") w.WriteHeader(http.StatusServiceUnavailable) return case len(body) > MaxContentBytes: notAvailable(w) return } w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.WriteHeader(http.StatusOK) w.Write(body) } // notAvailable is the one refusal S3 gives: the same status, headers and // (empty) body for a deleted item, an id that never existed, a superseded or // malformed revision and an item too large to serve, so none of them can be // told apart. Never 403. func notAvailable(w http.ResponseWriter) { w.WriteHeader(http.StatusNotFound) } func writeJSON(w http.ResponseWriter, v any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(v) } // contextKey carries the authenticated consumer. type contextKey struct{} // ConsumerFrom returns the consumer a request authenticated as, for an app // that keeps per-consumer state. func ConsumerFrom(ctx context.Context) (Consumer, bool) { c, ok := ctx.Value(contextKey{}).(Consumer) return c, ok } func bearer(r *http.Request) (string, bool) { h := r.Header.Get("Authorization") const prefix = "Bearer " if len(h) <= len(prefix) || !strings.EqualFold(h[:len(prefix)], prefix) { return "", false } return strings.TrimSpace(h[len(prefix):]), true } func contextWithConsumer(ctx context.Context, c Consumer) context.Context { return context.WithValue(ctx, contextKey{}, c) } // atEOF is the end-of-input check. Decoder.More is not one: it answers false // before a stray ']' or '}', so a valid document followed by either passed // as strict (Astra, 2026-11-01). Decoding once more must find nothing. func atEOF(dec *json.Decoder) bool { var extra json.RawMessage return dec.Decode(&extra) == io.EOF }