| 1 | package fichas |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "strconv" |
| 8 | "strings" |
| 9 | |
| 10 | "gorm.io/gorm" |
| 11 | |
| 12 | "amadan.net/oficina/fichas/internal/fichas/seal" |
| 13 | "amadan.net/oficina/suite" |
| 14 | "amadan.net/oficina/suite/server" |
| 15 | ) |
| 16 | |
| 17 | // suiteProducer is Fichas' half of the suite contract (spec §6; suite |
| 18 | // doctrine revision 11, pinned at 91affa1, §6.5 and §6.6). server.Handler |
| 19 | // owns the wire — the bearer check, the decoding, the cache headers, the |
| 20 | // cursor reset's 409 and the one S3 refusal — and this owns only what Fichas |
| 21 | // knows: its log, its admission list, and a card's text. |
| 22 | // |
| 23 | // Paul, 2026-11-01: "Hold private too, check per person." Fichas has no |
| 24 | // sharing ladder — every admitted person sees every card that is not gone |
| 25 | // (Card.OwnerID is provenance, not authority) — so the feed carries every |
| 26 | // card, S3 serves any live card, and S2 is admission. |
| 27 | type suiteProducer struct { |
| 28 | g *gorm.DB |
| 29 | sealer *seal.Sealer |
| 30 | // admit is app.Admit: the one admission predicate sign-in and every |
| 31 | // session already run. Passed in rather than re-derived, so S2 cannot |
| 32 | // drift from who may open the app. |
| 33 | admit func(address string) bool |
| 34 | } |
| 35 | |
| 36 | var _ server.Producer = (*suiteProducer)(nil) |
| 37 | |
| 38 | // Feed pages the events table (spec §6.2): card events after the cursor, |
| 39 | // in id order, one row each. |
| 40 | // |
| 41 | // The cursor is "<event id>.<that event's nonce>", and the nonce is |
| 42 | // checked on every request. After a restore from an older |
| 43 | // backup, AUTOINCREMENT hands the same event ids out again to different |
| 44 | // events; a bare id would then continue silently from a position that now |
| 45 | // means something else. The nonce is drawn at random per event and written |
| 46 | // with it (migrations/0005, logEvent), which is the stamp doctrine §6.6 |
| 47 | // requires: a restored log holds only the nonces of the events it has. |
| 48 | // |
| 49 | // A cursor this log does not recognise is server.ErrCursorReset, which the |
| 50 | // package answers 409 {"code":"CURSOR_RESET"} and the consumer reads as |
| 51 | // "start over from the beginning" (doctrine §6.6, revision 11): one that |
| 52 | // does not parse, one whose event is not a card event this log holds — |
| 53 | // restored away, issued by another log, or ahead of the tip — and one whose |
| 54 | // event carries another nonce. Fichas expires and compacts nothing (the |
| 55 | // events table is append-only, §5), so an expired cursor is the same case: |
| 56 | // were events ever pruned, a cursor naming a pruned one finds no event and |
| 57 | // is reset. Never a page, and never a 503: a 503 stalls the consumer for |
| 58 | // ever, which is what revision 10's Fichas did. A failed READ is still an |
| 59 | // error — a 503 the consumer retries — because a database that did not |
| 60 | // answer has not said the cursor is wrong. |
| 61 | func (p *suiteProducer) Feed(ctx context.Context, cursor string, limit int) (suite.Feed, error) { |
| 62 | after, stamp, ok := parseCursor(cursor) |
| 63 | if !ok { |
| 64 | return suite.Feed{}, server.ErrCursorReset |
| 65 | } |
| 66 | g := p.g.WithContext(ctx) |
| 67 | if after > 0 { |
| 68 | var at []Event |
| 69 | if err := g.Model(&Event{}).Select("id", "nonce"). |
| 70 | Where("id = ? AND object_kind = ?", after, ObjectCard).Find(&at).Error; err != nil { |
| 71 | return suite.Feed{}, fmt.Errorf("fichas: reading the feed cursor's event: %w", err) |
| 72 | } |
| 73 | if len(at) != 1 || at[0].Nonce != stamp { |
| 74 | // Restored away, another log's, or ahead of the tip. |
| 75 | return suite.Feed{}, server.ErrCursorReset |
| 76 | } |
| 77 | } |
| 78 | var evs []Event |
| 79 | // Only plaintext columns: nothing sealed is read, so nothing sealed can |
| 80 | // reach a row. |
| 81 | if err := g.Model(&Event{}). |
| 82 | Select("id", "kind", "object_id", "revision", "created_at", "nonce"). |
| 83 | Where("id > ? AND object_kind = ?", after, ObjectCard). |
| 84 | Order("id").Limit(limit).Find(&evs).Error; err != nil { |
| 85 | return suite.Feed{}, fmt.Errorf("fichas: reading the feed: %w", err) |
| 86 | } |
| 87 | if len(evs) == 0 { |
| 88 | // At the tip: the same cursor, and no rows. "" becomes "0", the |
| 89 | // beginning, because the contract refuses an empty cursor. |
| 90 | if cursor == "" { |
| 91 | cursor = "0" |
| 92 | } |
| 93 | return suite.Feed{Cursor: cursor, Rows: []suite.FeedRow{}}, nil |
| 94 | } |
| 95 | nonces, err := p.cardNonces(ctx, evs) |
| 96 | if err != nil { |
| 97 | return suite.Feed{}, err |
| 98 | } |
| 99 | rows := make([]suite.FeedRow, len(evs)) |
| 100 | for i, e := range evs { |
| 101 | nonce, ok := nonces[e.ObjectID] |
| 102 | if !ok { |
| 103 | // Card rows are never deleted, so an event for a card with no |
| 104 | // row is a log this code did not write. Loud, not skipped. |
| 105 | return suite.Feed{}, fmt.Errorf("fichas: event %d names card %d, which has no row", e.ID, e.ObjectID) |
| 106 | } |
| 107 | rows[i] = suite.FeedRow{ |
| 108 | ItemID: itemID(e.ObjectID, nonce), |
| 109 | Revision: e.Revision, |
| 110 | Gone: e.Kind == EventDeleted, |
| 111 | TouchedAt: e.CreatedAt, |
| 112 | } |
| 113 | } |
| 114 | last := evs[len(evs)-1] |
| 115 | return suite.Feed{Cursor: stampedID(last.ID, last.Nonce), Rows: rows}, nil |
| 116 | } |
| 117 | |
| 118 | // cardNonces is each card's nonce, for the cards a page names. |
| 119 | func (p *suiteProducer) cardNonces(ctx context.Context, evs []Event) (map[int64]int64, error) { |
| 120 | ids := make([]int64, 0, len(evs)) |
| 121 | for _, e := range evs { |
| 122 | ids = append(ids, e.ObjectID) |
| 123 | } |
| 124 | var cards []Card |
| 125 | if err := p.g.WithContext(ctx).Model(&Card{}).Select("id", "nonce"). |
| 126 | Where("id IN ?", ids).Find(&cards).Error; err != nil { |
| 127 | return nil, fmt.Errorf("fichas: reading card nonces: %w", err) |
| 128 | } |
| 129 | out := make(map[int64]int64, len(cards)) |
| 130 | for _, c := range cards { |
| 131 | out[c.ID] = c.Nonce |
| 132 | } |
| 133 | return out, nil |
| 134 | } |
| 135 | |
| 136 | // itemID is a card's id on the wire: "<card id>.<card nonce>". The id alone |
| 137 | // is not enough: after a restore from an older backup, a card created |
| 138 | // afterwards can be given the id and event position of one the consumer |
| 139 | // already holds. The nonce is random and written once (migrations/0005), |
| 140 | // so the pair names one card in one history. Not created_at: with a clock |
| 141 | // frozen or set back, a recreated card can get that too. |
| 142 | func itemID(cardID, nonce int64) string { return stampedID(cardID, nonce) } |
| 143 | |
| 144 | func stampedID(id, stamp int64) string { |
| 145 | return strconv.FormatInt(id, 10) + "." + strconv.FormatInt(stamp, 10) |
| 146 | } |
| 147 | |
| 148 | // parseStamped reads "<id>.<stamp>", both canonical positive decimals, so a |
| 149 | // value has exactly one spelling ("042.7", "+42.7", "42" are not 42.7). |
| 150 | func parseStamped(s string) (id, stamp int64, ok bool) { |
| 151 | head, tail, found := strings.Cut(s, ".") |
| 152 | if !found { |
| 153 | return 0, 0, false |
| 154 | } |
| 155 | id, ok1 := canonicalPositive(head) |
| 156 | stamp, ok2 := canonicalPositive(tail) |
| 157 | return id, stamp, ok1 && ok2 |
| 158 | } |
| 159 | |
| 160 | func canonicalPositive(s string) (int64, bool) { |
| 161 | n, err := strconv.ParseInt(s, 10, 64) |
| 162 | if err != nil || n < 1 || strconv.FormatInt(n, 10) != s { |
| 163 | return 0, false |
| 164 | } |
| 165 | return n, true |
| 166 | } |
| 167 | |
| 168 | // parseCursor reads a cursor Fichas issued: "" or "0" is the beginning, |
| 169 | // anything else "<event id>.<stamp>". Anything else was not issued here: not |
| 170 | // ok, which Feed answers with the reset, never a guess. |
| 171 | func parseCursor(c string) (after, stamp int64, ok bool) { |
| 172 | if c == "" || c == "0" { |
| 173 | return 0, 0, true |
| 174 | } |
| 175 | return parseStamped(c) |
| 176 | } |
| 177 | |
| 178 | // Rule is S2 (spec §6.3). Fichas is lone-shape only, so it keys on an |
| 179 | // address; a person_ref is a kind it cannot read and answers UNKNOWN, |
| 180 | // loudly, rather than NOT_VISIBLE, which a consumer may act on silently. |
| 181 | // Nothing here is cached: admission and every revision are read per call. |
| 182 | func (p *suiteProducer) Rule(ctx context.Context, asker suite.Subject, pairs []suite.ItemRevision) ([]suite.Authorization, error) { |
| 183 | out := make([]suite.Authorization, len(pairs)) |
| 184 | if asker.Kind != suite.SubjectAddress { |
| 185 | for i := range out { |
| 186 | out[i] = suite.UNKNOWN |
| 187 | } |
| 188 | return out, nil |
| 189 | } |
| 190 | if !p.admit(asker.Value) { |
| 191 | for i := range out { |
| 192 | out[i] = suite.NOT_VISIBLE |
| 193 | } |
| 194 | return out, nil |
| 195 | } |
| 196 | |
| 197 | ids := make([]int64, 0, len(pairs)) |
| 198 | for _, pr := range pairs { |
| 199 | if id, _, ok := parseStamped(pr.ItemID); ok { |
| 200 | ids = append(ids, id) |
| 201 | } |
| 202 | } |
| 203 | live := map[int64]Card{} // live cards only |
| 204 | if len(ids) > 0 { |
| 205 | var cards []Card |
| 206 | if err := p.g.WithContext(ctx).Model(&Card{}).Select("id", "revision", "nonce"). |
| 207 | Where("id IN ? AND gone = ?", ids, false).Find(&cards).Error; err != nil { |
| 208 | return nil, fmt.Errorf("fichas: reading revisions: %w", err) |
| 209 | } |
| 210 | for _, c := range cards { |
| 211 | live[c.ID] = c |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | past, err := p.pastRevisions(ctx, pairs, live) |
| 216 | if err != nil { |
| 217 | return nil, err |
| 218 | } |
| 219 | |
| 220 | for i, pr := range pairs { |
| 221 | id, stamp, ok := parseStamped(pr.ItemID) |
| 222 | c, found := live[id] |
| 223 | switch { |
| 224 | case !ok || !found || c.Nonce != stamp: |
| 225 | // Gone, unknown, or a different card under a reused id. |
| 226 | out[i] = suite.NOT_VISIBLE |
| 227 | case pr.Revision == c.Revision: |
| 228 | out[i] = suite.VISIBLE |
| 229 | case past[cardRevision{id, pr.Revision}]: |
| 230 | // A revision this card had and has moved on from — read off |
| 231 | // its own log, never off the numbers, which are random. |
| 232 | out[i] = suite.STALE |
| 233 | default: |
| 234 | // A revision this card's log never issued: ahead of a restore, |
| 235 | // or anything else Fichas cannot vouch for. |
| 236 | out[i] = suite.UNKNOWN |
| 237 | } |
| 238 | } |
| 239 | return out, nil |
| 240 | } |
| 241 | |
| 242 | type cardRevision struct{ card, revision int64 } |
| 243 | |
| 244 | // pastRevisions is which asked (card, revision) pairs appear in a live |
| 245 | // card's own event log, in one query. Revisions are random (store.go |
| 246 | // nextRevision), so "older than current" is not a comparison of numbers: |
| 247 | // it is "this card's log once issued it" (spec §6.3). |
| 248 | func (p *suiteProducer) pastRevisions(ctx context.Context, pairs []suite.ItemRevision, live map[int64]Card) (map[cardRevision]bool, error) { |
| 249 | var ids, revs []int64 |
| 250 | for _, pr := range pairs { |
| 251 | id, _, ok := parseStamped(pr.ItemID) |
| 252 | if c, found := live[id]; ok && found && pr.Revision != c.Revision { |
| 253 | ids = append(ids, id) |
| 254 | revs = append(revs, pr.Revision) |
| 255 | } |
| 256 | } |
| 257 | out := map[cardRevision]bool{} |
| 258 | if len(ids) == 0 { |
| 259 | return out, nil |
| 260 | } |
| 261 | var evs []Event |
| 262 | if err := p.g.WithContext(ctx).Model(&Event{}).Select("object_id", "revision"). |
| 263 | Where("object_kind = ? AND object_id IN ? AND revision IN ?", ObjectCard, ids, revs). |
| 264 | Find(&evs).Error; err != nil { |
| 265 | return nil, fmt.Errorf("fichas: reading revision history: %w", err) |
| 266 | } |
| 267 | for _, e := range evs { |
| 268 | out[cardRevision{e.ObjectID, e.Revision}] = true |
| 269 | } |
| 270 | return out, nil |
| 271 | } |
| 272 | |
| 273 | // Content is S3 (spec §6.4): the card's text at its current revision, and |
| 274 | // suite.ErrNotAvailable for anything else. |
| 275 | func (p *suiteProducer) Content(ctx context.Context, itemID string, revision int64) ([]byte, error) { |
| 276 | id, stamp, ok := parseStamped(itemID) |
| 277 | if !ok { |
| 278 | return nil, suite.ErrNotAvailable |
| 279 | } |
| 280 | cv, err := LoadCard(ctx, p.g, p.sealer, id) |
| 281 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 282 | return nil, suite.ErrNotAvailable // unknown, or gone |
| 283 | } |
| 284 | if err != nil { |
| 285 | return nil, err |
| 286 | } |
| 287 | // Checked twice, and each check catches what the other cannot. |
| 288 | // LoadCard reads the card row, then its values and entries, in |
| 289 | // separate statements, so an edit can commit between them. This first |
| 290 | // check pins where the read STARTED: without it, an edit landing |
| 291 | // mid-read that produces the asked revision passes the second check |
| 292 | // with the old row's values under the new number. |
| 293 | if cv.Card.Nonce != stamp || cv.Card.Revision != revision { |
| 294 | // A different card under a reused id (a restore), or another |
| 295 | // revision. |
| 296 | return nil, suite.ErrNotAvailable |
| 297 | } |
| 298 | body := cardText(cv) |
| 299 | // The second pins that nothing committed since. A revision moves only |
| 300 | // in the same transaction as the values and entries — a delete too, |
| 301 | // which is why "gone" needs no check of its own here — so if it is |
| 302 | // unchanged now, everything above was read at that revision. |
| 303 | var now Card |
| 304 | if err := p.g.WithContext(ctx).Select("id", "revision").First(&now, id).Error; err != nil { |
| 305 | // Not ErrNotAvailable: a failed read is not a refusal, and the |
| 306 | // card was there a moment ago. An error is a 503, which the |
| 307 | // consumer retries. |
| 308 | return nil, fmt.Errorf("fichas: re-reading card %d's revision: %w", id, err) |
| 309 | } |
| 310 | if now.Revision != revision { |
| 311 | return nil, suite.ErrNotAvailable |
| 312 | } |
| 313 | return []byte(body), nil |
| 314 | } |
| 315 | |
| 316 | // cardText is the plain text a consumer indexes: the title, each other |
| 317 | // field with a value as "Label: value", then each entry, newest first, as |
| 318 | // its type label and its fields. Lines are joined with "\n" and there is no |
| 319 | // trailing newline, so a card with only a title is exactly its title. |
| 320 | func cardText(cv CardView) string { |
| 321 | lines := []string{cv.Title()} |
| 322 | for _, f := range cv.Fields { |
| 323 | if cv.IsTitle(f.Def.Key) || f.Value == "" { |
| 324 | continue |
| 325 | } |
| 326 | lines = append(lines, f.Label+": "+f.Value) |
| 327 | } |
| 328 | for _, e := range cv.Entries { |
| 329 | lines = append(lines, "", e.TypeLabel) |
| 330 | for _, f := range e.Fields { |
| 331 | if f.Value == "" { |
| 332 | continue |
| 333 | } |
| 334 | lines = append(lines, f.Label+": "+f.Value) |
| 335 | } |
| 336 | } |
| 337 | return strings.Join(lines, "\n") |
| 338 | } |
| 339 | |