oficina / fichas Public

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

Plain git — no account needed to clone.

Download

Download this file

1package fichas
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "sort"
8 "strconv"
9 "strings"
10 "sync"
11
12 "amadan.net/oficina/fichas/internal/fichas/seal"
13 "gorm.io/gorm"
14)
15
16// Index is the in-memory, decrypted view of every live card, which search,
17// sort and filter run over.
18//
19// §4.1: sealed is not unqueryable. The durable file cannot answer a search —
20// every value in it is ciphertext — so the values come back into memory to
21// be searched, exactly as memoria's index lives in memory and is rebuilt from
22// sealed rows on wake. Paul, 2026-09-29: "any search we ever do across
23// records needs to feel instant, even when searching 1000s of rows." Over
24// plain Go values it is well under a millisecond at that size; decrypting
25// every card per request, which is what the list page did before this, was
26// tens of milliseconds and grew with every card.
27//
28// **The event log is its change feed.** Every write in store.go lands an
29// Event in the same transaction as the change (the ruling that a change that
30// is not logged did not happen), so the highest event id is a complete,
31// cheap answer to "has anything changed since I last looked", and the events
32// past it say exactly what. No write path has to remember to tell the index
33// anything, which is the property that keeps it from going quietly stale.
34//
35// It holds decrypted content in RAM for the life of the process. That is
36// memoria §3.2's "from a live host" entry, made here for the same reason:
37// the alternative is not a safer index, it is no search at all.
38type Index struct {
39 db *gorm.DB
40 s *seal.Sealer
41
42 mu sync.RWMutex
43 loaded bool
44 seen int64 // highest event id reflected in the index
45 types map[int64]*typeIndex
46 // fullLoads counts rebuilds after the first load, so a test can tell
47 // a named event kind from one that fell through to the rebuild.
48 fullLoads int
49}
50
51// typeIndex is one card type's cards and definitions.
52type typeIndex struct {
53 ct CardType
54 label string
55 plural string
56 defs []FieldDef // by ordinal
57 blank []FieldView
58 cards map[int64]*indexedCard
59}
60
61type indexedCard struct {
62 view CardView
63 search string // every value and the latest entry, lowercased, for matching
64 // lowered holds each field's value lowercased, computed once at load so
65 // a sort compares prepared strings instead of lowercasing both sides on
66 // every comparison — which was most of a 15ms sort at 5,000 cards.
67 lowered map[string]string
68}
69
70// NewIndex returns an empty index; it loads on first use.
71func NewIndex(db *gorm.DB, s *seal.Sealer) *Index {
72 return &Index{db: db, s: s, types: map[int64]*typeIndex{}}
73}
74
75// Sync brings the index up to date with the database.
76//
77// Cheap when nothing has changed: one MAX over the events primary key.
78func (ix *Index) Sync(ctx context.Context) error {
79 g := ix.db.WithContext(ctx)
80 var latest int64
81 if err := g.Model(&Event{}).Select("COALESCE(MAX(id), 0)").Scan(&latest).Error; err != nil {
82 return fmt.Errorf("fichas: reading the event log head: %w", err)
83 }
84
85 ix.mu.RLock()
86 current := ix.loaded && latest <= ix.seen
87 ix.mu.RUnlock()
88 if current {
89 return nil
90 }
91
92 ix.mu.Lock()
93 defer ix.mu.Unlock()
94 if ix.loaded && latest <= ix.seen {
95 return nil // another request caught it up while this one waited
96 }
97 if !ix.loaded {
98 // seen is read BEFORE loading, so a write that lands during the
99 // load is replayed on the next Sync rather than missed. Replaying
100 // a card that is already current is harmless.
101 if err := ix.loadAll(g); err != nil {
102 return err
103 }
104 ix.seen, ix.loaded = latest, true
105 return nil
106 }
107
108 var events []Event
109 if err := g.Where("id > ?", ix.seen).Order("id").Find(&events).Error; err != nil {
110 return fmt.Errorf("fichas: reading new events: %w", err)
111 }
112 cards := map[int64]bool{}
113 types := map[int64]bool{}
114 full := false
115 for _, e := range events {
116 // Each object kind is named, with what it reloads (level-up §9):
117 // a kind this switch does not name rebuilds everything, the safe
118 // default, and TestEveryObjectKindIsNamedInSync fails if a kind
119 // Fichas writes reaches it.
120 switch e.ObjectKind {
121 case ObjectCard:
122 cards[e.ObjectID] = true
123 case ObjectEntry:
124 // The card-level entry_added event carries the card; the
125 // entry's own event adds nothing the index needs.
126 case ObjectView, ObjectFile, ObjectDraft, ObjectMember:
127 // Nothing the index holds: views are read per request; files,
128 // drafts and a person's own format are not in it.
129 case ObjectType:
130 types[e.ObjectID] = true
131 case ObjectField:
132 var fd FieldDef
133 err := g.Select("card_type_id").First(&fd, e.ObjectID).Error
134 if err == gorm.ErrRecordNotFound {
135 // A field gone from under its event: rebuild, never stall.
136 full = true
137 continue
138 }
139 if err != nil {
140 return fmt.Errorf("fichas: finding field %d's type: %w", e.ObjectID, err)
141 }
142 types[fd.CardTypeID] = true
143 case ObjectGroup:
144 // A folder names types by its own id, not theirs; until Phase 6
145 // writes folders and says which types a change touches, a
146 // folder event rebuilds the index.
147 full = true
148 default:
149 ix.fullLoads++
150 if err := ix.loadAll(g); err != nil {
151 return err
152 }
153 ix.seen = latest
154 return nil
155 }
156 }
157 if full {
158 ix.fullLoads++
159 if err := ix.loadAll(g); err != nil {
160 return err
161 }
162 ix.seen = latest
163 return nil
164 }
165 for id := range types {
166 if err := ix.reloadType(g, id); err != nil {
167 return err
168 }
169 }
170 // Past a burst of this size, one batched full load is cheaper than
171 // reloading card by card (each reload is several queries); an import of
172 // calls from Calls would arrive as exactly such a burst.
173 if len(cards) > reloadBurst {
174 ix.fullLoads++
175 if err := ix.loadAll(g); err != nil {
176 return err
177 }
178 ix.seen = latest
179 return nil
180 }
181 for id := range cards {
182 if err := ix.reloadCard(g, id); err != nil {
183 return err
184 }
185 }
186 ix.seen = latest
187 return nil
188}
189
190// reloadBurst is where Sync stops patching and rebuilds.
191const reloadBurst = 200
192
193func (ix *Index) loadAll(g *gorm.DB) error {
194 var types []CardType
195 if err := g.Where("scope = ?", ScopeCard).Order("id").Find(&types).Error; err != nil {
196 return fmt.Errorf("fichas: loading card types: %w", err)
197 }
198 fresh := map[int64]*typeIndex{}
199 for _, ct := range types {
200 ti, err := ix.loadType(g, ct)
201 if err != nil {
202 return err
203 }
204 fresh[ct.ID] = ti
205 }
206 ix.types = fresh
207 return nil
208}
209
210func (ix *Index) loadType(g *gorm.DB, ct CardType) (*typeIndex, error) {
211 label, err := openLabel(ix.s, ct.SealedLabel)
212 if err != nil {
213 return nil, err
214 }
215 plural, err := openLabel(ix.s, ct.SealedPlural)
216 if err != nil {
217 return nil, err
218 }
219 if plural == "" {
220 plural = pluralLabel(label)
221 }
222 var defs []FieldDef
223 if err := g.Where("card_type_id = ?", ct.ID).Find(&defs).Error; err != nil {
224 return nil, fmt.Errorf("fichas: loading field definitions: %w", err)
225 }
226 sort.Slice(defs, func(i, j int) bool { return defs[i].Ordinal < defs[j].Ordinal })
227 blank, err := fieldViews(ix.s, append([]FieldDef(nil), defs...), nil)
228 if err != nil {
229 return nil, err
230 }
231 ti := &typeIndex{ct: ct, label: label, plural: plural, defs: defs, blank: blank, cards: map[int64]*indexedCard{}}
232
233 var cards []Card
234 if err := g.Where("card_type_id = ? AND gone = ?", ct.ID, false).Find(&cards).Error; err != nil {
235 return nil, fmt.Errorf("fichas: loading cards: %w", err)
236 }
237 if len(cards) == 0 {
238 return ti, nil
239 }
240 ids := make([]int64, len(cards))
241 for i, c := range cards {
242 ids[i] = c.ID
243 }
244 values, err := valuesByCard(g, ids)
245 if err != nil {
246 return nil, err
247 }
248 latest, err := latestEntries(g, ix.s, ids)
249 if err != nil {
250 return nil, err
251 }
252 for _, c := range cards {
253 ic, err := ix.build(ti, c, values[c.ID], latest[c.ID])
254 if err != nil {
255 return nil, err
256 }
257 ti.cards[c.ID] = ic
258 }
259 return ti, nil
260}
261
262// reloadCard refreshes one card, or drops it if it is gone.
263// reloadType reloads one type: its labels, fields and cards. A type
264// created since the last load is added; one that no longer exists, or
265// is not a card type, is dropped.
266func (ix *Index) reloadType(g *gorm.DB, id int64) error {
267 var ct CardType
268 err := g.First(&ct, id).Error
269 if err == gorm.ErrRecordNotFound || (err == nil && ct.Scope != ScopeCard) {
270 delete(ix.types, id)
271 return nil
272 }
273 if err != nil {
274 return fmt.Errorf("fichas: reloading type %d: %w", id, err)
275 }
276 ti, err := ix.loadType(g, ct)
277 if err != nil {
278 return err
279 }
280 ix.types[id] = ti
281 return nil
282}
283
284func (ix *Index) reloadCard(g *gorm.DB, id int64) error {
285 var c Card
286 err := g.First(&c, id).Error
287 if err == gorm.ErrRecordNotFound {
288 for _, ti := range ix.types {
289 delete(ti.cards, id)
290 }
291 return nil
292 }
293 if err != nil {
294 return fmt.Errorf("fichas: reloading card %d: %w", id, err)
295 }
296 ti, ok := ix.types[c.CardTypeID]
297 if !ok {
298 return nil // a type the index has not loaded: the next full load has it
299 }
300 if c.Gone {
301 delete(ti.cards, id)
302 return nil
303 }
304 values, err := valuesByCard(g, []int64{id})
305 if err != nil {
306 return err
307 }
308 latest, err := latestEntries(g, ix.s, []int64{id})
309 if err != nil {
310 return err
311 }
312 ic, err := ix.build(ti, c, values[id], latest[id])
313 if err != nil {
314 return err
315 }
316 ti.cards[id] = ic
317 return nil
318}
319
320func (ix *Index) build(ti *typeIndex, c Card, values map[int64][]byte, latest *EntryView) (*indexedCard, error) {
321 fields, err := fieldViews(ix.s, append([]FieldDef(nil), ti.defs...), values)
322 if err != nil {
323 return nil, err
324 }
325 view := CardView{Card: c, TypeKey: ti.ct.Key, TypeLabel: ti.label, Fields: fields, Latest: latest}
326 var b strings.Builder
327 lowered := make(map[string]string, len(fields))
328 for _, f := range fields {
329 if f.Value != "" {
330 l := strings.ToLower(f.Value)
331 lowered[f.Def.Key] = l
332 b.WriteString(l)
333 b.WriteByte('\n')
334 }
335 }
336 if latest != nil {
337 b.WriteString(strings.ToLower(latest.Body()))
338 }
339 return &indexedCard{view: view, search: b.String(), lowered: lowered}, nil
340}
341
342func valuesByCard(g *gorm.DB, ids []int64) (map[int64]map[int64][]byte, error) {
343 var values []CardValue
344 if err := g.Where("card_id IN ?", ids).Find(&values).Error; err != nil {
345 return nil, fmt.Errorf("fichas: loading values: %w", err)
346 }
347 out := map[int64]map[int64][]byte{}
348 for _, v := range values {
349 if out[v.CardID] == nil {
350 out[v.CardID] = map[int64][]byte{}
351 }
352 out[v.CardID][v.FieldDefID] = v.SealedValue
353 }
354 return out, nil
355}
356
357// Sort keys that are not field keys.
358const (
359 SortUpdated = "_updated"
360 SortLastCall = "_last_call"
361)
362
363// Query is a search over one card type.
364type Query struct {
365 Text string
366 Filters map[string]string // choice field key → exact value
367 Sort string // a field key, SortUpdated or SortLastCall
368 Desc bool
369 Page int // 1-based
370 PerPage int
371}
372
373// Result is one page of a Query.
374type Result struct {
375 Type CardType
376 Label string
377 Plural string
378 Fields []FieldView // the type's fields, blank, for headers and filters
379 Cards []CardView
380 Total int // matches, across all pages
381 All int // every live card of the type, unfiltered
382 Page, Pages int
383 First, Last int // 1-based positions of this page's first and last row
384}
385
386// Query answers a search from memory. Call Sync first.
387func (ix *Index) Query(typeKey string, q Query) (Result, error) {
388 ix.mu.RLock()
389 defer ix.mu.RUnlock()
390
391 var ti *typeIndex
392 for _, t := range ix.types {
393 if t.ct.Key == typeKey {
394 ti = t
395 }
396 }
397 if ti == nil {
398 return Result{}, gorm.ErrRecordNotFound
399 }
400
401 matched := ix.ordered(ti, q)
402
403 res := Result{
404 Type: ti.ct, Label: ti.label, Plural: ti.plural, Fields: ti.blank,
405 Total: len(matched), All: len(ti.cards),
406 }
407 per := q.PerPage
408 if per <= 0 {
409 per = 100
410 }
411 res.Pages = (len(matched) + per - 1) / per
412 if res.Pages == 0 {
413 res.Pages = 1
414 }
415 res.Page = q.Page
416 if res.Page < 1 {
417 res.Page = 1
418 }
419 if res.Page > res.Pages {
420 res.Page = res.Pages
421 }
422 start := (res.Page - 1) * per
423 end := start + per
424 if end > len(matched) {
425 end = len(matched)
426 }
427 for _, ic := range matched[start:end] {
428 res.Cards = append(res.Cards, ic.view)
429 }
430 if end > start {
431 res.First, res.Last = start+1, end
432 }
433 return res, nil
434}
435
436// matchesTerms: every term must appear somewhere. "bright ana" finds the card
437// whose name has one and whose email has the other.
438// ordered is a query's whole list, matched and sorted. The caller holds
439// the lock.
440func (ix *Index) ordered(ti *typeIndex, q Query) []*indexedCard {
441 terms := searchTerms(q.Text)
442 choice := choiceKeys(ti)
443 matched := make([]*indexedCard, 0, len(ti.cards))
444 for _, ic := range ti.cards {
445 if !matchesTerms(ic.search, terms) || !matchesFilters(ic.view, q.Filters, choice) {
446 continue
447 }
448 matched = append(matched, ic)
449 }
450 sortCards(matched, ti, q)
451 return matched
452}
453
454// Position is where a card sits in a query's whole list, across pages:
455// what the card beside the list needs for "2 of 7" and Next and
456// Previous (§5.4).
457type Position struct {
458 At, Total int // 1-based
459 Prev, Next int64 // card ids, 0 at either end
460 PrevPage int
461 NextPage int
462 Page int // the page the card is on
463}
464
465// Position finds a card in a query's list; false when it is not in it.
466func (ix *Index) Position(typeKey string, q Query, cardID int64) (Position, bool) {
467 ix.mu.RLock()
468 defer ix.mu.RUnlock()
469 ti := ix.typeByKey(typeKey)
470 if ti == nil {
471 return Position{}, false
472 }
473 list := ix.ordered(ti, q)
474 per := q.PerPage
475 if per <= 0 {
476 per = 100
477 }
478 for i, ic := range list {
479 if ic.view.Card.ID != cardID {
480 continue
481 }
482 p := Position{At: i + 1, Total: len(list), Page: i/per + 1}
483 if i > 0 {
484 p.Prev, p.PrevPage = list[i-1].view.Card.ID, (i-1)/per+1
485 }
486 if i+1 < len(list) {
487 p.Next, p.NextPage = list[i+1].view.Card.ID, (i+1)/per+1
488 }
489 return p, true
490 }
491 return Position{}, false
492}
493
494// Matches reports whether a card is in a query's list: live, of the
495// type, and matching its search and filters.
496func (ix *Index) Matches(typeKey string, q Query, cardID int64) bool {
497 ix.mu.RLock()
498 defer ix.mu.RUnlock()
499 ti := ix.typeByKey(typeKey)
500 if ti == nil {
501 return false
502 }
503 ic, ok := ti.cards[cardID]
504 if !ok {
505 return false
506 }
507 return matchesTerms(ic.search, searchTerms(q.Text)) && matchesFilters(ic.view, q.Filters, choiceKeys(ti))
508}
509
510// typeByKey is the loaded type with this key, or nil. The caller holds
511// the lock.
512func (ix *Index) typeByKey(key string) *typeIndex {
513 for _, t := range ix.types {
514 if t.ct.Key == key {
515 return t
516 }
517 }
518 return nil
519}
520
521func choiceKeys(ti *typeIndex) map[string]bool {
522 choice := map[string]bool{}
523 for _, d := range ti.defs {
524 if d.Kind == KindEnum {
525 choice[d.Key] = true
526 }
527 }
528 return choice
529}
530
531func matchesTerms(hay string, terms []string) bool {
532 for _, t := range terms {
533 if !strings.Contains(hay, t) {
534 return false
535 }
536 }
537 return true
538}
539
540// matchesFilters applies equality filters on CHOICE fields only. A filter on
541// any other key is ignored rather than honoured: a free-text equality filter
542// in a URL is a search that silently misses on case and spacing.
543func matchesFilters(v CardView, filters map[string]string, choice map[string]bool) bool {
544 for key, want := range filters {
545 if !choice[key] || want == "" {
546 continue
547 }
548 if v.Field(key).Value != want {
549 return false
550 }
551 }
552 return true
553}
554
555func sortCards(cards []*indexedCard, ti *typeIndex, q Query) {
556 key := q.Sort
557 kind := ""
558 for _, d := range ti.defs {
559 if d.Key == key {
560 kind = d.Kind
561 }
562 }
563 if key != SortLastCall && kind == "" {
564 key = SortUpdated
565 }
566 desc := q.Desc
567 if q.Sort == "" {
568 desc = true // the default: most recently touched first
569 }
570
571 // The comparator touches only prepared data — the lowered map and the
572 // card's timestamps — never Field(), which scans a card's fields, and
573 // never a copy of the whole view. At 5,000 cards it runs ~60,000 times.
574 sort.SliceStable(cards, func(i, j int) bool {
575 ci, cj := cards[i], cards[j]
576 idTie := ci.view.Card.ID < cj.view.Card.ID
577 switch key {
578 case SortUpdated:
579 a, b := ci.view.Card.UpdatedAt.UnixNano(), cj.view.Card.UpdatedAt.UnixNano()
580 return less(a < b, b < a, desc, idTie)
581 case SortLastCall:
582 at, bt := int64(0), int64(0)
583 if ci.view.Latest != nil {
584 at = ci.view.Latest.Entry.CreatedAt.UnixNano()
585 }
586 if cj.view.Latest != nil {
587 bt = cj.view.Latest.Entry.CreatedAt.UnixNano()
588 }
589 // Never-called sorts last in either direction.
590 if (at == 0) != (bt == 0) {
591 return at != 0
592 }
593 return less(at < bt, bt < at, desc, idTie)
594 }
595 av, aok := ci.lowered[key]
596 bv, bok := cj.lowered[key]
597 // An empty value sorts last in either direction: a column sorted
598 // by next action should lead with the next action, not with the
599 // cards that have none.
600 if aok != bok {
601 return aok
602 }
603 if kind == KindNumber {
604 af, aerr := strconv.ParseFloat(av, 64)
605 bf, berr := strconv.ParseFloat(bv, 64)
606 if aerr == nil && berr == nil {
607 return less(af < bf, bf < af, desc, idTie)
608 }
609 }
610 return less(av < bv, bv < av, desc, idTie)
611 })
612}
613
614// less orders by lt/gt in the requested direction, falling back to id so the
615// order is total and paging is stable.
616func less(lt, gt, desc, idTie bool) bool {
617 switch {
618 case lt:
619 return !desc
620 case gt:
621 return desc
622 default:
623 return idTie
624 }
625}
626
627// Fields returns a type's field definitions, blank, for parsing a list URL.
628// Call Sync first.
629func (ix *Index) Fields(typeKey string) ([]FieldView, error) {
630 ix.mu.RLock()
631 defer ix.mu.RUnlock()
632 for _, t := range ix.types {
633 if t.ct.Key == typeKey {
634 return t.blank, nil
635 }
636 }
637 return nil, gorm.ErrRecordNotFound
638}
639
640// TypeInfo is a card type's names, for the sidebar and page titles.
641type TypeInfo struct {
642 Key, Label, Plural string
643 Count int // live cards
644}
645
646// Types lists the card types in creation order. Call Sync first.
647func (ix *Index) Types() []TypeInfo {
648 ix.mu.RLock()
649 defer ix.mu.RUnlock()
650 out := make([]TypeInfo, 0, len(ix.types))
651 for _, t := range ix.types {
652 out = append(out, TypeInfo{Key: t.ct.Key, Label: t.label, Plural: t.plural, Count: len(t.cards)})
653 }
654 sort.Slice(out, func(i, j int) bool {
655 return out[i].Key == TypeCustomer || (out[j].Key != TypeCustomer && out[i].Key < out[j].Key)
656 })
657 return out
658}
659
660// Face is a type's card face: the field keys the Cards view shows, in order.
661// Call Sync first.
662func (ix *Index) Face(typeKey string) []string {
663 ix.mu.RLock()
664 defer ix.mu.RUnlock()
665 for _, t := range ix.types {
666 if t.ct.Key == typeKey {
667 return faceFor(t.ct, t.defs)
668 }
669 }
670 return nil
671}
672
673// faceFor is a type's saved face, or its default: for the seeded Customer,
674// the face the mockups settled on; for any other type, the title and the
675// latest call.
676func faceFor(ct CardType, defs []FieldDef) []string {
677 if ct.FaceKeys != "" {
678 var keys []string
679 if err := json.Unmarshal([]byte(ct.FaceKeys), &keys); err == nil {
680 return keys
681 }
682 }
683 if ct.Key == TypeCustomer {
684 return []string{FieldStage, FieldEmail, FaceLatestCall, FieldNextAction}
685 }
686 return []string{FaceLatestCall}
687}
688
689// maxTerms bounds a search. Matching is cards × terms, so an unbounded query
690// — 20,000 words took 357ms over 2,000 cards — holds the read lock against
691// every Sync. Nobody types seventeen words into a search box.
692const maxTerms = 16
693
694// searchTerms lowercases, splits, drops duplicates, and caps.
695func searchTerms(q string) []string {
696 seen := map[string]bool{}
697 var out []string
698 for _, t := range strings.Fields(strings.ToLower(q)) {
699 if seen[t] {
700 continue
701 }
702 seen[t] = true
703 out = append(out, t)
704 if len(out) == maxTerms {
705 break
706 }
707 }
708 return out
709}
710