oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package chat
2
3import (
4 "context"
5 "crypto/rand"
6 "crypto/sha256"
7 "encoding/hex"
8 "encoding/json"
9 "errors"
10 "fmt"
11 "log/slog"
12 "net"
13 "slices"
14 "strconv"
15 "strings"
16 "sync"
17 "sync/atomic"
18 "time"
19 "unicode/utf8"
20
21 "amadan.net/oficina/equipo/internal/equipo/housekeeping"
22 "amadan.net/oficina/equipo/internal/wire"
23 "amadan.net/rastrillo/rastrillo/db"
24 "gorm.io/gorm"
25 "gorm.io/gorm/logger"
26 "gorm.io/plugin/dbresolver"
27)
28
29var (
30 ErrInvalid = errors.New("chat: invalid")
31 ErrNotFound = errors.New("chat: not found")
32 ErrConflict = errors.New("chat: idempotency conflict")
33 ErrTerminal = errors.New("chat: turn already ended")
34 ErrForbidden = errors.New("chat: forbidden")
35 // ErrAbilityOff: an ability the person needs is off (403 ability_off,
36 // spec 2026-11-26-assistant-abilities).
37 ErrAbilityOff = errors.New("chat: ability off")
38 ErrExpired = errors.New("chat: cursor expired")
39 ErrSuperseded = errors.New("chat: runner generation superseded")
40 ErrUnavailable = errors.New("chat: unavailable")
41 // ErrRefused refuses a runner frame without effect: a report or ack
42 // from a runner that does not own what it names. The frame is acked
43 // (it will never succeed) and logged; the connection stays.
44 ErrRefused = errors.New("chat: refused for this runner")
45 // ErrHeld refuses a runner frame for now, without effect and unacked:
46 // the runner keeps it in its outbox and sends it again on a later
47 // connection (a worker's Engineering report below protocol 37). The
48 // connection stays.
49 ErrHeld = errors.New("chat: held until the runner reconnects at a newer protocol")
50)
51
52// RunnerPrincipal is an authenticated runner credential.
53type RunnerPrincipal struct {
54 RunnerID, Person, CredentialID string
55}
56
57// Authority is supplied by the instance. Each function runs inside the
58// write transaction it is given, so roster changes apply immediately.
59type Authority struct {
60 // CurrentPerson re-checks the person principal carried by ctx.
61 CurrentPerson func(ctx context.Context, tx *gorm.DB) error
62 // Me reads the person's own resource.
63 Me func(tx *gorm.DB, address string) (wire.Me, error)
64 // PrimaryRunner is the runner that serves the person's coordinator:
65 // the person's newest unrevoked runner, only if the person is an
66 // active owner. Empty means nobody executes for this person.
67 PrimaryRunner func(tx *gorm.DB, person string) (string, error)
68 // CurrentRunner re-checks a runner credential and its owner.
69 CurrentRunner func(tx *gorm.DB, p RunnerPrincipal) error
70 // RunnerRole is the runner's enrolled role, wire.RolePrimary or
71 // wire.RoleWorker.
72 RunnerRole func(tx *gorm.DB, runnerID string) (string, error)
73 // FinishRemoval revokes a runner whose removal waited for its work's
74 // end, once that end is proven.
75 FinishRemoval func(tx *gorm.DB, runnerID string) error
76 // Audit records an action in the instance's audit log.
77 Audit func(tx *gorm.DB, actor, kind, record string) error
78 // ActivityLabel is the line a client shows for an activity, in a turn
79 // of turnKind (wire.TurnPerson, TurnMoveIn or TurnExplore). The subject
80 // is resolved from an authorised record, never copied from tool input.
81 ActivityLabel func(a wire.Activity, turnKind, subject string) string
82 // Copy is the instance's copy for a key (copy.go): the words the
83 // instance itself writes into a conversation (the merge card, the
84 // merged line). "" for an unknown key.
85 Copy func(key string) string
86 // TestPerson reports a test identity (staging's suite person): its
87 // tasks are listed only to itself and never paired with anyone else's.
88 TestPerson func(address string) bool
89 // Origin is the instance's own origin (EQUIPO_ORIGIN), for the links
90 // an Assistant card gives back to Equipo.
91 Origin string
92 // AssistantHosts are the origins a person may register as their
93 // Base host (EQUIPO_ASSISTANT_HOSTS), lowercased.
94 AssistantHosts []string
95 // PushDevice re-checks a device credential of the person's, for a
96 // push to it: nil while it is still valid (not revoked or expired).
97 // Unset, nothing pushes.
98 PushDevice func(tx *gorm.DB, person, credential string) error
99 // Seal and Open keep a secret sealed with the instance key, bound to
100 // domain (a host token).
101 Seal func(domain string, v any) (string, error)
102 Open func(domain, sealed string, v any) error
103}
104
105// Store owns the chat tables.
106type Store struct {
107 notificationActions atomic.Bool
108 db *db.DB
109 authority Authority
110 hub *Hub
111 now func() time.Time
112 process string
113 tap atomic.Pointer[func(runner string, raw []byte)]
114 // Housekeeping: the detectors (housekeeping.Default unless a test
115 // declares others), the team's id once read, and the loop's clock
116 // (quiet hours, the day's budget, the digest), nil for now.
117 detectors *housekeeping.Registry
118 hkMu sync.Mutex
119 teamID string
120 clock func() time.Time
121 // hops is how many proxies the runner stream trusts in
122 // X-Forwarded-For, when a test sets it (SetForwardedHops).
123 hops atomic.Pointer[int]
124 // instance is the instance inventory's listed prefixes and latest
125 // scan; ifaceAddrs replaces net.InterfaceAddrs, and procNet
126 // hostaddrs.ProcSelfNet, in tests.
127 instance instanceNet
128 ifaceAddrs func() ([]net.Addr, error)
129 procNet string
130 // live is the lookups' live channel to each runner (lookup_live.go);
131 // lookups their configuration, pace and deny lists (web_provider.go).
132 live lookupLive
133 lookups lookupState
134 // ops is the Assistant's registry (SetOperations); remote wakes
135 // ServeRemoteCalls after a commit that stored a pending call.
136 ops atomic.Pointer[Operations]
137 remote chan struct{}
138 // logger reports what ServeRemoteCalls could not do (SetLogger).
139 logger atomic.Pointer[slog.Logger]
140 // warm limits how often opening Base warms an Assistant (warm.go).
141 warm warmGate
142 // pushOn writes the push outbox (SetPush); pushWake wakes its sender.
143 pushOn atomic.Bool
144 pushWake chan struct{}
145 // projectJobHook stands in for projectJob in the minute's sweep (a
146 // test's failing card); nil projects as usual.
147 projectJobHook func(*txn, handoffRecord) error
148 // abilities is what the store keeps in memory about people's boards
149 // (abilities_fetch.go); fixed the operator's fixed keys (SetFixed).
150 abilities abilityState
151 fixed atomic.Pointer[Fixed]
152 // macEngineering is EQUIPO_MAC_ENGINEERING (SetMacEngineering):
153 // Engineering for Mac work is placed on a Mac worker. Off, it waits as
154 // mac-placement-wait left it.
155 macEngineering atomic.Bool
156}
157
158// SetFrameTap sees every frame the instance sends a runner, as sent
159// (tests: what a protocol 1 runner receives).
160func (s *Store) SetFrameTap(f func(runner string, raw []byte)) { s.tap.Store(&f) }
161
162func NewStore(d *db.DB, a Authority, hub *Hub) *Store {
163 if hub == nil {
164 hub = NewHub()
165 }
166 return &Store{db: d, authority: a, hub: hub, now: func() time.Time { return time.Now().UTC() }, process: newID("p"), detectors: housekeeping.Default(), remote: make(chan struct{}, 1), pushWake: make(chan struct{}, 1)}
167}
168
169// SetClock replaces the store's clock (tests: the 30-minute offline rule
170// with a fake clock).
171func (s *Store) SetClock(now func() time.Time) { s.now = now }
172
173// SetMacEngineering is EQUIPO_MAC_ENGINEERING, read at boot.
174func (s *Store) SetMacEngineering(on bool) { s.macEngineering.Store(on) }
175
176// Process identifies this instance process in runner leases.
177func (s *Store) Process() string { return s.process }
178
179// Hub returns the in-process wake-up hub.
180func (s *Store) Hub() *Hub { return s.hub }
181
182func newID(prefix string) string { return prefix + strings.ToLower(rand.Text()) }
183
184// tx runs fn in one write transaction and wakes streams for the persons
185// it touched after commit.
186func (s *Store) tx(ctx context.Context, fn func(*txn) error) error {
187 t := &txn{s: s, ctx: ctx, touched: map[string]bool{}}
188 err := s.transactionSession(ctx).Transaction(func(tx *gorm.DB) error {
189 t.db = tx
190 return fn(t)
191 })
192 if len(t.failures) > 0 {
193 // Housekeeping failures are counted after the transaction ends,
194 // committed or not, so an error cannot erase its own record.
195 if ferr := s.recordFailures(ctx, t.failures); ferr != nil && err == nil {
196 err = ferr
197 }
198 }
199 if err != nil {
200 return err
201 }
202 for _, l := range t.live {
203 s.hub.publish(l.person, l.lane, l.event)
204 }
205 for person := range t.touched {
206 s.hub.Wake(person)
207 }
208 if t.pending {
209 s.wakeRemote()
210 }
211 if t.pushed {
212 s.wakePush()
213 }
214 return nil
215}
216
217type privateReadsKey struct{}
218
219// WithPrivateReads keeps SQL, including parameters and database error text,
220// out of logs for delegated reads. It does not change read authority.
221func WithPrivateReads(ctx context.Context) context.Context {
222 return context.WithValue(ctx, privateReadsKey{}, true)
223}
224
225// transactionSession applies request SQL privacy to both read and tx paths.
226func (s *Store) transactionSession(ctx context.Context) *gorm.DB {
227 g := s.db.G.WithContext(ctx)
228 if private, _ := ctx.Value(privateReadsKey{}).(bool); private {
229 g = g.Session(&gorm.Session{Logger: logger.Discard})
230 }
231 return g.Clauses(dbresolver.Write)
232}
233
234func (s *Store) read(ctx context.Context, fn func(*gorm.DB) error) error {
235 return s.transactionSession(ctx).Transaction(fn)
236}
237
238type txn struct {
239 s *Store
240 ctx context.Context
241 db *gorm.DB
242 touched map[string]bool
243 // viewer is the person a read is for (their runner's catalog first);
244 // catalogs caches the runners' catalogs by repository.
245 viewer string
246 catalogs map[string]wire.RepoInfo
247 // makers caches specialists' profiles by id for the transaction (a
248 // specialist's profile never changes): every task view in a list
249 // reads each maker once (taskViewWith).
250 makers makerProfiles
251 // hk is the housekeeping principal while the loop acts: the shared
252 // store functions check it. failures are housekeeping failures to
253 // count once the transaction ends.
254 hk *Principal
255 failures []hkFailureRecord
256 // pending: the transaction stored a call for ServeRemoteCalls.
257 pending bool
258 // live are events for the streams following now, never stored,
259 // published once the transaction commits.
260 live []liveEvent
261 // pushed: the transaction wrote the push outbox.
262 pushed bool
263}
264
265func (t *txn) now() time.Time { return t.s.now() }
266
267// event appends one event to the person's log, in lane's stream.
268func (t *txn) event(lane, person, kind, resource, id string, revision int64, turnID, messageID string, attempt int64, data any) error {
269 raw, err := json.Marshal(data)
270 if err != nil {
271 return err
272 }
273 body, err := json.Marshal(wire.Event{Type: kind, Resource: resource, ID: id, Revision: revision, TurnID: turnID, MessageID: messageID, Attempt: attempt, Data: raw})
274 if err != nil {
275 return err
276 }
277 t.touched[person] = true
278 return t.db.Create(&eventRecord{Person: person, Type: kind, Body: string(body), CreatedAt: t.now(), Lane: lane}).Error
279}
280
281// liveEvent is one live-only event (Hub.publish).
282type liveEvent struct {
283 person, lane string
284 event wire.Event
285}
286
287func (t *txn) turnEvent(r turnRecord) error {
288 v, err := t.turnView(r)
289 if err != nil {
290 return err
291 }
292 return t.event(r.Lane, r.Person, wire.EventTurn, "turn", r.ID, r.Revision, r.ID, "", r.Attempt, v)
293}
294
295func messageView(m messageRecord) wire.Message {
296 v := wire.Message{ProjectID: m.ProjectID, ID: m.ID, Revision: m.Revision, Role: m.Role, Text: m.Text, TurnID: m.TurnID, CreatedAt: m.CreatedAt}
297 if m.Switched != "" {
298 v.Switched = &wire.Switched{}
299 if json.Unmarshal([]byte(m.Switched), v.Switched) != nil {
300 v.Switched = nil
301 }
302 }
303 return v
304}
305
306func (t *txn) messageEvent(m messageRecord) error {
307 v := []wire.Message{messageView(m)}
308 if err := withFiles(t.db, v); err != nil {
309 return err
310 }
311 if len(v[0].Lookups) > 0 {
312 // A reply carrying lookups' answers is written with SQL logging
313 // off: a slow or failed statement never prints them.
314 prior := t.db
315 t.db = quietDB(prior)
316 defer func() { t.db = prior }()
317 }
318 return t.event(m.Lane, m.Person, wire.EventMessage, "message", m.ID, m.Revision, m.TurnID, m.ID, 0, v[0])
319}
320
321// quietDB is db with SQL logging off, for writes that hold a lookup's
322// queries, addresses or answer.
323func quietDB(db *gorm.DB) *gorm.DB {
324 return db.Session(&gorm.Session{Logger: logger.Discard, NewDB: false})
325}
326
327func (t *txn) turnView(r turnRecord) (wire.Turn, error) {
328 ids := []string{}
329 if err := t.db.Model(&messageRecord{}).Where("turn_id = ? AND role = ?", r.ID, wire.RolePerson).Order("seq").Pluck("id", &ids).Error; err != nil {
330 return wire.Turn{}, err
331 }
332 v := wire.Turn{ID: r.ID, Revision: r.Revision, Kind: r.Kind, State: r.State, Reason: r.Reason, Attempt: r.Attempt, MessageIDs: ids, ReplyID: r.ReplyID, Connection: r.Connection, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt}
333 if r.Timing != "" && r.State == wire.TurnReplied {
334 v.Timing = &wire.TurnTiming{}
335 if err := json.Unmarshal([]byte(r.Timing), v.Timing); err != nil {
336 return wire.Turn{}, err
337 }
338 }
339 return v, nil
340}
341
342func (t *txn) saveTurn(r *turnRecord) error {
343 r.Revision++
344 r.UpdatedAt = t.now()
345 if err := t.db.Model(&turnRecord{}).Where("id = ?", r.ID).Select("state", "reason", "attempt", "dispatched", "dispatched_at", "timing", "reply_id", "revision", "updated_at", "yield", "connection").Updates(r).Error; err != nil {
346 return err
347 }
348 if err := t.turnEvent(*r); err != nil {
349 return err
350 }
351 if err := t.pushReply(*r); err != nil {
352 return err
353 }
354 // Every way a turn ends comes here: a hand-off's Coordinator turn
355 // that ends may leave its hand-off with nothing more to do, and once
356 // the Assistant's team_update turn about a job ends, its card may say
357 // what the Assistant was told (ruling P5j).
358 switch {
359 case !wire.Terminal(r.State):
360 case wire.CoordinatorRole(r.Lane):
361 return t.handoffTurnEnded(r.ID)
362 case r.Lane == wire.LaneAssistant && r.Kind == wire.TurnTeamUpdate:
363 return t.updateEnded(r.ID)
364 }
365 return nil
366}
367
368// command writes a durable command to the person's primary runner: the
369// conversation, merges, watches and publication live there. With no
370// primary yet it waits unaddressed; the primary's next connection takes
371// it (rebind).
372func (t *txn) command(person, kind string, body any) error {
373 primary, err := t.s.authority.PrimaryRunner(t.db, person)
374 if err != nil {
375 return err
376 }
377 return t.commandTo(primary, person, kind, body)
378}
379
380// commandTo writes a durable command to one runner's mailbox.
381func (t *txn) commandTo(runner, person, kind string, body any) error {
382 raw, err := json.Marshal(body)
383 if err != nil {
384 return err
385 }
386 t.touched[person] = true
387 return t.db.Create(&commandRecord{Person: person, RunnerID: runner, Kind: kind, Body: string(raw), CreatedAt: t.now()}).Error
388}
389
390// dispatch sends a queued turn to the runner with the person's messages
391// in one frame (turnText) and the conversation tail before them. A move-in
392// or explore turn carries no text: the runner writes its prompt.
393func (t *txn) dispatch(r *turnRecord) error {
394 if err := t.hkSpend(r.Person); err != nil {
395 return err
396 }
397 var mine []messageRecord
398 if err := t.db.Where("turn_id = ? AND role = ?", r.ID, wire.RolePerson).Order("seq").Find(&mine).Error; err != nil {
399 return err
400 }
401 if len(mine) == 0 && r.Kind == wire.TurnPerson {
402 return ErrInvalid
403 }
404 // The tail is what went before in the turn's lane: never this turn's
405 // messages, nor those of a batch still waiting behind it (a batch too
406 // big for one frame goes as several turns, one after another).
407 var prior []messageRecord
408 if err := t.db.Where("person = ? AND coalesce(lane, '') = ? AND turn_id <> ? AND turn_id NOT IN (SELECT id FROM chat_turns WHERE person = ? AND dispatched = ? AND state = ?)", r.Person, r.Lane, r.ID, r.Person, false, wire.TurnQueued).Order("seq DESC").Limit(wire.MaxTailMessages).Find(&prior).Error; err != nil {
409 return err
410 }
411 // The person's words in turns that failed before the model ran never
412 // reached the coordinator: they ride in this turn's frame, marked
413 // unanswered, and not in the tail as if answered.
414 var carried []messageRecord
415 if r.Kind == wire.TurnPerson {
416 var err error
417 if carried, err = t.unanswered(r); err != nil {
418 return err
419 }
420 }
421 inFrame := map[string]bool{}
422 for _, m := range carried {
423 inFrame[m.ID] = true
424 }
425 // A files-only person message has no words: the tail names its files.
426 var wordless []string
427 for _, m := range prior {
428 if m.Role == wire.RolePerson && m.Text == "" {
429 wordless = append(wordless, m.ID)
430 }
431 }
432 sentFiles, err := filesOf(t.db, wordless)
433 if err != nil {
434 return err
435 }
436 tail := make([]wire.TailMessage, 0, len(prior))
437 for i := len(prior) - 1; i >= 0; i-- {
438 if !inFrame[prior[i].ID] {
439 text := prior[i].Text
440 if files := sentFiles[prior[i].ID]; len(files) > 0 {
441 names := make([]string, 0, len(files))
442 for _, f := range files {
443 names = append(names, f.Name)
444 }
445 text = sentFilesLine(names)
446 }
447 tail = append(tail, wire.TailMessage{Role: prior[i].Role, Text: text})
448 }
449 }
450 texts := make([]string, 0, len(mine))
451 own := make([]string, 0, len(mine))
452 ids := make([]string, 0, len(mine))
453 for _, m := range mine {
454 ids = append(ids, m.ID)
455 }
456 // Attachment bytes go first, as their own frames.
457 files, names, err := t.relayFiles(r.Person, ids)
458 if err != nil {
459 return err
460 }
461 attached := make([][]string, 0, len(mine))
462 for _, m := range mine {
463 if m.Origin == originComposer {
464 own = append(own, m.Text)
465 }
466 text, err := t.answerPrefix(m)
467 if err != nil {
468 return err
469 }
470 if text, err = t.handoffContext(m, text); err != nil {
471 return err
472 }
473 texts = append(texts, text)
474 attached = append(attached, names[m.ID])
475 }
476 now := t.now()
477 r.Dispatched, r.DispatchedAt = true, &now
478 text := turnText(texts, attached)
479 if r.Kind == wire.TurnTeamUpdate || r.Kind == wire.TurnSpecialistAdded {
480 // The instance's news (handoff.go), or the opening of the
481 // continuation after an Add (specialist_added.go): written by the
482 // instance, never the person's words, which it quotes labelled.
483 text = r.Note
484 }
485 if r.Lane == wire.LaneAssistant && r.Kind == wire.TurnPerson {
486 // What the person's Assistant may do starts the reference
487 // (abilities §6.1); web_lookup isn't listed yet.
488 note, err := t.abilitiesNote(r.Person, false)
489 if err != nil {
490 return err
491 }
492 if note != "" {
493 text += "\n\n" + note
494 }
495 // The questions open on the person's jobs ride after their words,
496 // as reference (D8); PersonText and the stored messages stay theirs.
497 block, asked, err := t.openQuestionsNote(r.Person)
498 if err != nil {
499 return err
500 }
501 if block != "" {
502 text += "\n\n" + block
503 }
504 // And the cards waiting for them in Equipo (waiting_cards.go),
505 // less the questions just listed.
506 if block, err = t.waitingNote(r.Person, asked); err != nil {
507 return err
508 }
509 if block != "" {
510 text += "\n\n" + block
511 }
512 }
513 cmd := wire.MessageCommand{Person: r.Person, TurnID: r.ID, Attempt: r.Attempt, Kind: r.Kind, Attachments: files, Lane: r.Lane}
514 if r.Lane == wire.LaneAssistant && r.Kind == wire.TurnPerson {
515 // The files the person attached earlier in the conversation, that
516 // the runner may still hold (assistant attachments spec A4).
517 if cmd.Earlier, cmd.EarlierMore, err = t.earlierFiles(r.Person, r.Lane, ids, now.Add(-wire.RunnerKeepFiles), wire.MaxEarlierFiles); err != nil {
518 return err
519 }
520 }
521 if wire.CoordinatorRole(r.Lane) {
522 block, err := t.projectBlock(r.Person)
523 if err != nil {
524 return err
525 }
526 text += "\n\n" + block
527 if cmd.PlacementNotes, err = t.placementNotes(r.Person); err != nil {
528 return err
529 }
530 }
531 // The tail gives way first, then the oldest unanswered message: a
532 // runner refuses a frame too big, every time it is resent. The earlier
533 // files (at most MaxEarlierFiles refs, a few KiB) give way only to the
534 // turn's own messages: they go, oldest first and counted in
535 // earlier_more, only when those leave no room for them with no tail
536 // and nothing carried (batchRoom keeps that from happening).
537 for {
538 bare := cmd
539 bare.Text, bare.PersonText, bare.Tail = text, own, []wire.TailMessage{}
540 raw, err := json.Marshal(bare)
541 if err != nil {
542 return err
543 }
544 if len(raw) <= frameRoom || len(cmd.Earlier) == 0 {
545 break
546 }
547 cmd.Earlier, cmd.EarlierMore = cmd.Earlier[:len(cmd.Earlier)-1], cmd.EarlierMore+1
548 }
549 for {
550 words := make([]string, 0, len(carried)+len(own))
551 for _, m := range carried {
552 words = append(words, m.Text)
553 }
554 cmd.Text, err = t.withUnanswered(carried, text)
555 if err != nil {
556 return err
557 }
558 cmd.PersonText, cmd.Tail = append(words, own...), tail
559 if cmd.Tail, err = fitTail(cmd); err != nil {
560 return err
561 }
562 raw, err := json.Marshal(cmd)
563 if err != nil {
564 return err
565 }
566 if len(raw) <= frameRoom || len(carried) == 0 {
567 break
568 }
569 carried = carried[1:]
570 }
571 // In this turn the carried words are the person's too (quote).
572 for _, m := range carried {
573 if err := t.db.Create(&carriedRecord{TurnID: r.ID, MessageID: m.ID, Person: r.Person}).Error; err != nil {
574 return err
575 }
576 }
577 return t.command(r.Person, wire.FrameMessage, cmd)
578}
579
580// A turn carries the person's words from at most maxCarriedTurns failed
581// turns, and at most maxUnanswered messages: words that rode in two turns
582// that failed too may be what makes them fail, so they stop riding.
583const (
584 maxCarriedTurns = 2
585 maxUnanswered = 10
586)
587
588// reachedModel is SQL true when the chat_turns row reached the model: a
589// delta or an activity was recorded for it, or a tool call, or usage.
590// Events are kept a day (wire.EventRetention), longer than a session
591// resumes (the same UTC day); tool calls and usage are kept.
592const reachedModel = "(EXISTS (SELECT 1 FROM chat_tool_calls c WHERE c.turn_id = chat_turns.id) OR EXISTS (SELECT 1 FROM chat_usage u WHERE u.turn_id = chat_turns.id) OR EXISTS (SELECT 1 FROM chat_events e WHERE e.person = chat_turns.person AND e.type IN ('" + wire.EventDelta + "', '" + wire.EventActivity + "') AND e.body LIKE '%\"turn_id\":\"' || chat_turns.id || '\"%'))"
593
594// unanswered is the person's plain messages (composer words, not a card's
595// answer or reply, which reach the model with their card) in the lane's
596// failed person turns since the last that reached the model (answered,
597// or ended after it began), the newest maxCarriedTurns of them, oldest
598// first. So each failed before the model ran: its words are in no
599// transcript, and the tail showed them as if answered. A turn that
600// reached the model bounds them, its own words and those it carried: a
601// resumed session's transcript may hold them. A cancelled turn's are not
602// carried: the person stopped it.
603func (t *txn) unanswered(r *turnRecord) ([]messageRecord, error) {
604 turns := "SELECT id FROM chat_turns WHERE person = ? AND coalesce(lane, '') = ? AND coalesce(kind, '') = '' AND "
605 var last int64
606 if err := t.db.Model(&messageRecord{}).Select("coalesce(max(seq), 0)").Where("person = ? AND coalesce(lane, '') = ? AND role = ? AND turn_id IN ("+turns+"(state = ? OR state IN ? AND "+reachedModel+"))", r.Person, r.Lane, wire.RolePerson, r.Person, r.Lane, wire.TurnReplied, []string{wire.TurnFailed, wire.TurnCancelled}).Scan(&last).Error; err != nil {
607 return nil, err
608 }
609 var rows []messageRecord
610 if err := t.db.Where("person = ? AND coalesce(lane, '') = ? AND role = ? AND seq > ? AND turn_id <> ? AND turn_id IN ("+turns+"state = ?)", r.Person, r.Lane, wire.RolePerson, last, r.ID, r.Person, r.Lane, wire.TurnFailed).Order("seq DESC").Limit(wire.MaxTailMessages).Find(&rows).Error; err != nil {
611 return nil, err
612 }
613 var out []messageRecord
614 seen := map[string]bool{}
615 for _, m := range rows {
616 if !seen[m.TurnID] && len(seen) == maxCarriedTurns {
617 break
618 }
619 seen[m.TurnID] = true
620 if m.Origin != originComposer || len(out) == maxUnanswered {
621 continue
622 }
623 var cards int64
624 if err := t.db.Model(&cardRecord{}).Where("person = ? AND (answer_message = ? OR id IN (SELECT card_id FROM chat_card_threads WHERE message_id = ? AND person = ?))", m.Person, m.ID, m.ID, m.Person).Count(&cards).Error; err != nil {
625 return nil, err
626 }
627 if cards == 0 {
628 out = append(out, m)
629 }
630 }
631 slices.Reverse(out)
632 return out, nil
633}
634
635// withUnanswered is a turn's text with the unanswered messages before
636// it, each quoted under its label; text alone with none.
637func (t *txn) withUnanswered(carried []messageRecord, text string) (string, error) {
638 if len(carried) == 0 {
639 return text, nil
640 }
641 var b strings.Builder
642 b.WriteString(noteUnanswered + "\n")
643 for _, m := range carried {
644 b.WriteString(fmt.Sprintf(noteUnansweredMessage, m.Text) + "\n")
645 if m.ProjectID != "" {
646 p, err := t.messageProject(m)
647 if err != nil {
648 return "", err
649 }
650 if p.Repo != "" {
651 b.WriteString(fmt.Sprintf(t.s.authority.Copy("projects.carried_selection"), p.Repo) + "\n")
652 }
653 }
654 }
655 b.WriteString("\n" + noteNewest + text)
656 return b.String(), nil
657}
658
659// frameRoom is what a message command's body may take: the frame limit
660// less its envelope (id and type).
661const frameRoom = wire.MaxFrameBytes - 1<<10
662
663// fitTail drops the oldest tail messages until the command fits one
664// frame: a runner refuses a larger frame, every time it is resent.
665func fitTail(cmd wire.MessageCommand) ([]wire.TailMessage, error) {
666 raw, err := json.Marshal(cmd)
667 if err != nil {
668 return nil, err
669 }
670 size, tail := len(raw), cmd.Tail
671 for len(tail) > 0 && size > frameRoom {
672 one, err := json.Marshal(tail[0])
673 if err != nil {
674 return nil, err
675 }
676 size, tail = size-len(one)-1, tail[1:]
677 }
678 return tail, nil
679}
680
681// batchRoom bounds the person's own part of a batch (its words twice, as
682// Text and PersonText, and its files), leaving room for answer prefixes
683// and some tail.
684const batchRoom = wire.MaxFrameBytes - 64<<10
685
686// batchFull reports whether a queued turn has no room left for one more
687// message: its text and its number of files. A full batch stays as it is;
688// the message starts the next batch, which goes after it.
689func (t *txn) batchFull(turn, text string, files int) (bool, error) {
690 var rows []messageRecord
691 if err := t.db.Select("id", "text").Where("turn_id = ? AND role = ?", turn, wire.RolePerson).Find(&rows).Error; err != nil {
692 return false, err
693 }
694 ids := make([]string, 0, len(rows))
695 texts := []string{text}
696 for _, m := range rows {
697 ids, texts = append(ids, m.ID), append(texts, m.Text)
698 }
699 var held int64
700 if len(ids) > 0 {
701 if err := t.db.Model(&fileRecord{}).Where("message_id IN ?", ids).Count(&held).Error; err != nil {
702 return false, err
703 }
704 }
705 size := 256 + 512*(int(held)+files)
706 for _, text := range texts {
707 raw, err := json.Marshal(text)
708 if err != nil {
709 return false, err
710 }
711 size += 2*len(raw) + 64
712 }
713 return size > batchRoom, nil
714}
715
716// filesOnly stands for the words of a message that has files and none.
717const filesOnly = "(files only, no words)"
718
719// turnText is what the coordinator reads for a turn's messages. One
720// message is its words alone (none, for a move-in or explore turn), or
721// filesOnly when it has files and no words, in every lane.
722// Several (sent while another turn ran) are each set apart, oldest
723// first, with the names of the files each one carried, so the
724// coordinator can tell them apart and answer them together. Every runner
725// reads Text as the person's words, so the frame is the same at every
726// protocol.
727func turnText(texts []string, files [][]string) string {
728 if len(texts) == 1 && texts[0] == "" && len(files[0]) > 0 {
729 return filesOnly
730 }
731 if len(texts) < 2 {
732 return strings.Join(texts, "")
733 }
734 var b strings.Builder
735 n := strconv.Itoa(len(texts))
736 b.WriteString("[Equipo: the person sent " + n + " messages while you were busy, oldest first. Each is a separate message; answer them together in one reply.]")
737 for i, text := range texts {
738 b.WriteString("\n\nMessage " + strconv.Itoa(i+1) + " of " + n)
739 if len(files[i]) > 0 {
740 b.WriteString(" (attached: " + strings.Join(files[i], ", ") + ")")
741 }
742 b.WriteString(":\n")
743 if text == "" {
744 text = filesOnly
745 }
746 b.WriteString(text)
747 }
748 return b.String()
749}
750
751// personFirst orders queued turns: the person's own, and the continuation
752// of their request after an Add on a specialist card, before any move-in
753// or explore turn, and those before housekeeping, then oldest first.
754const personFirst = "CASE WHEN coalesce(kind, '') IN ('', '" + wire.TurnSpecialistAdded + "') THEN 0 WHEN kind = '" + wire.TurnHousekeeping + "' THEN 2 ELSE 1 END, created_at, id"
755
756// dispatchNext starts the lane's oldest undispatched turn once nothing
757// is in flight in that lane, the person's own turns first. Each lane
758// queues on its own, so the two run at once.
759func (t *txn) dispatchNext(person, lane string) error {
760 busy, err := t.inFlight(person, lane)
761 if err != nil || busy != 0 {
762 return err
763 }
764 // A held job's turns wait for the person's Carry on now.
765 if held, err := t.laneHeld(lane); err != nil || held {
766 return err
767 }
768 var next turnRecord
769 err = t.db.Where("person = ? AND coalesce(lane, '') = ? AND dispatched = ? AND state = ?", person, lane, false, wire.TurnQueued).Order(personFirst).First(&next).Error
770 if errors.Is(err, gorm.ErrRecordNotFound) {
771 return nil
772 }
773 if err != nil {
774 return err
775 }
776 if err = t.dispatch(&next); err != nil {
777 return err
778 }
779 return t.saveTurn(&next)
780}
781
782// inFlight counts the lane's dispatched turns not yet ended.
783func (t *txn) inFlight(person, lane string) (int64, error) {
784 var busy int64
785 err := t.db.Model(&turnRecord{}).Where("person = ? AND coalesce(lane, '') = ? AND dispatched = ? AND state IN ?", person, lane, true, wire.InFlight).Count(&busy).Error
786 return busy, err
787}
788
789func bodyHash(text string) string {
790 sum := sha256.Sum256([]byte(text))
791 return hex.EncodeToString(sum[:])
792}
793
794// Send records a person message. While a turn is in flight, new messages
795// join one queued turn, which goes to the coordinator as a single frame
796// (several, one turn after another, when they would not fit one).
797func (s *Store) Send(ctx context.Context, person string, in wire.SendMessage) (out wire.Sent, created bool, err error) {
798 // A message is words, attachments or both.
799 if in.Text = strings.TrimSpace(in.Text); in.Text == "" && len(in.Attachments) == 0 || len(in.Text) > wire.MaxMessageBytes || !utf8.ValidString(in.Text) || strings.ContainsRune(in.Text, 0) {
800 return out, false, ErrInvalid
801 }
802 if err := checkFiles(in.Attachments); err != nil {
803 return out, false, err
804 }
805 if !validKey(in.IdempotencyKey) {
806 return out, false, ErrInvalid
807 }
808 err = s.tx(ctx, func(t *txn) error {
809 if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
810 return err
811 }
812 var err error
813 out, created, err = t.composerSend(wire.LaneCoordinator, person, in)
814 return err
815 })
816 return out, created, err
817}
818
819// validKey: a client's idempotency key. reply:, card: and handoff: keys
820// belong to the instance.
821func validKey(key string) bool {
822 return len(key) >= 1 && len(key) <= 128 && !strings.HasPrefix(key, "reply:") && !strings.HasPrefix(key, "card:") && !strings.HasPrefix(key, handoffKey) && utf8.ValidString(key)
823}
824
825// send records a person message in lane, with its attachments (files,
826// the person's unsent uploads), inside a write transaction. before runs
827// after the message exists and before it can be dispatched.
828func (t *txn) send(lane, person, key, text string, files []string, before func(messageRecord) error) (out wire.Sent, created bool, err error) {
829 return t.sendOrigin(lane, person, key, text, files, originGenerated, before)
830}
831
832func (t *txn) sendOrigin(lane, person, key, text string, files []string, origin string, before func(messageRecord) error) (out wire.Sent, created bool, err error) {
833 return t.sendSelectedOrigin(lane, person, key, text, files, origin, "", before)
834}
835
836func (t *txn) sendSelectedOrigin(lane, person, key, text string, files []string, origin, projectID string, before func(messageRecord) error, separate ...bool) (out wire.Sent, created bool, err error) {
837 var prior messageRecord
838 err = t.db.Where("person = ? AND idempotency_key = ? AND coalesce(lane, '') = ?", person, key, lane).First(&prior).Error
839 if err == nil {
840 if prior.BodyHash != sendHash(text, files) || prior.ProjectID != projectID {
841 return out, false, ErrConflict
842 }
843 var turn turnRecord
844 if err = t.db.Where("id = ?", prior.TurnID).First(&turn).Error; err != nil {
845 return out, false, err
846 }
847 view, err := t.turnView(turn)
848 if err != nil {
849 return out, false, err
850 }
851 msg := []wire.Message{messageView(prior)}
852 return wire.Sent{Message: msg[0], Turn: view}, false, withFiles(t.db, msg)
853 }
854 if !errors.Is(err, gorm.ErrRecordNotFound) {
855 return out, false, err
856 }
857 if projectID != "" {
858 if _, err := t.selectedProject(person, projectID); err != nil {
859 return out, false, err
860 }
861 }
862 now := t.now()
863 var turn turnRecord
864 // The message joins the newest waiting batch, unless that batch would
865 // no longer fit one frame. A hand-off's words, and the answer to a
866 // card raised in a hand-off's turn, start a turn of their own, which
867 // nothing joins: its work is the hand-off's alone.
868 alone, err := t.handoffMessage(key)
869 alone = alone || strings.HasPrefix(key, "card:") || projectID != "" || len(separate) > 0 && separate[0]
870 if err != nil {
871 return out, false, err
872 }
873 err = t.db.Where("person = ? AND coalesce(lane, '') = ? AND dispatched = ? AND state = ? AND coalesce(kind, '') = '' AND NOT EXISTS (SELECT 1 FROM chat_handoff_turns WHERE turn_id = chat_turns.id) AND NOT EXISTS (SELECT 1 FROM chat_messages WHERE turn_id = chat_turns.id AND (idempotency_key LIKE 'card:%' OR coalesce(project_id, '') <> '' OR id IN (SELECT answer_message FROM chat_cards WHERE answer_message <> '')))", person, lane, false, wire.TurnQueued).Order("created_at DESC, id DESC").First(&turn).Error
874 fresh := errors.Is(err, gorm.ErrRecordNotFound) || err == nil && alone
875 if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
876 return out, false, err
877 }
878 if !fresh {
879 if fresh, err = t.batchFull(turn.ID, text, len(files)); err != nil {
880 return out, false, err
881 }
882 }
883 if fresh {
884 turn = turnRecord{ID: newID("t_"), Person: person, State: wire.TurnQueued, Attempt: 1, CreatedAt: now, UpdatedAt: now, Lane: lane}
885 if err = t.db.Create(&turn).Error; err != nil {
886 return out, false, err
887 }
888 }
889 m := messageRecord{ProjectID: projectID, Origin: origin, ID: newID("m_"), Person: person, IdempotencyKey: key, BodyHash: sendHash(text, files), Role: wire.RolePerson, Text: text, TurnID: turn.ID, Revision: 1, CreatedAt: now, Lane: lane}
890 if err = t.db.Create(&m).Error; err != nil {
891 return out, false, err
892 }
893 if err = t.linkFiles(m, files); err != nil {
894 return out, false, err
895 }
896 if err = t.messageEvent(m); err != nil {
897 return out, false, err
898 }
899 // The person's first message ends quiet hours for their receipts
900 // (Coordinator cards): one handed to a job thread too.
901 if wire.CoordinatorRole(lane) {
902 if err = t.hkRelease(person, t.hkNow()); err != nil {
903 return out, false, err
904 }
905 }
906 if before != nil {
907 if err = before(m); err != nil {
908 return out, false, err
909 }
910 }
911 busy, err := t.inFlight(person, lane)
912 if err != nil {
913 return out, false, err
914 }
915 held, err := t.laneHeld(lane)
916 if err != nil {
917 return out, false, err
918 }
919 if busy == 0 && !held {
920 if err = t.dispatch(&turn); err != nil {
921 return out, false, err
922 }
923 } else if lane == wire.LaneCoordinator {
924 err = t.yieldTurns(person)
925 }
926 if err != nil {
927 return out, false, err
928 }
929 if err = t.saveTurn(&turn); err != nil {
930 return out, false, err
931 }
932 view, err := t.turnView(turn)
933 if err != nil {
934 return out, false, err
935 }
936 msg := []wire.Message{messageView(m)}
937 return wire.Sent{Message: msg[0], Turn: view}, true, withFiles(t.db, msg)
938}
939
940// yieldTurns asks a move-in or explore turn in flight to give way to the
941// person: the runner ends the attempt (cancelled, reason yielded) and the
942// person's turn goes next; the move-in continues in a new turn after it.
943// A specialist_added turn is the person's own request carried on, bound
944// to its card: it never gives way (a new turn could not carry its card),
945// and the person's message waits behind it like behind their own.
946func (t *txn) yieldTurns(person string) error {
947 var rows []turnRecord
948 if err := t.db.Where("person = ? AND dispatched = ? AND state IN ? AND coalesce(kind, '') NOT IN ? AND (yield IS NULL OR yield = ?)", person, true, wire.InFlight, []string{wire.TurnPerson, wire.TurnSpecialistAdded}, false).Find(&rows).Error; err != nil {
949 return err
950 }
951 for i := range rows {
952 rows[i].Yield = true
953 if err := t.saveTurn(&rows[i]); err != nil {
954 return err
955 }
956 if err := t.command(person, wire.FrameCancel, wire.CancelCommand{Person: person, TurnID: rows[i].ID, Attempt: rows[i].Attempt}); err != nil {
957 return err
958 }
959 }
960 return nil
961}
962
963// Cancel asks for a turn to end. An undispatched turn ends at once; a
964// dispatched one ends only when the runner reports termination.
965func (s *Store) Cancel(ctx context.Context, person, id string) (attempt int64, current wire.Turn, err error) {
966 return s.cancel(ctx, wire.LaneCoordinator, person, id)
967}
968
969// cancel ends one of the lane's turns; a turn of another lane is unknown.
970func (s *Store) cancel(ctx context.Context, lane, person, id string) (attempt int64, current wire.Turn, err error) {
971 err = s.tx(ctx, func(t *txn) error {
972 if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
973 return err
974 }
975 var r turnRecord
976 if err := t.db.Where("id = ? AND person = ? AND coalesce(lane, '') = ?", id, person, lane).First(&r).Error; errors.Is(err, gorm.ErrRecordNotFound) {
977 return ErrNotFound
978 } else if err != nil {
979 return err
980 }
981 attempt = r.Attempt
982 if wire.Terminal(r.State) {
983 current, err = t.turnView(r)
984 if err != nil {
985 return err
986 }
987 return ErrTerminal
988 }
989 // An Assistant cancel is audited with the turn's id alone, in its
990 // transaction (the Coordinator's never has been).
991 if !wire.CoordinatorRole(lane) {
992 if err := t.s.authority.Audit(t.db, person, auditAssistantCancel, r.ID); err != nil {
993 return err
994 }
995 }
996 return t.cancelTurn(r)
997 })
998 return attempt, current, err
999}
1000
1001// cancelTurn asks a turn that has not ended to end. Only a turn never
1002// sent to a runner ends here. A dispatched turn may already be running
1003// even if its ack is missing, so it ends when the runner reports
1004// termination of the attempt.
1005func (t *txn) cancelTurn(r turnRecord) error {
1006 if !r.Dispatched {
1007 r.State, r.Reason = wire.TurnCancelled, "cancelled"
1008 if err := t.saveTurn(&r); err != nil {
1009 return err
1010 }
1011 if err := t.kindEnded(r); err != nil {
1012 return err
1013 }
1014 return t.dispatchNext(r.Person, r.Lane)
1015 }
1016 return t.command(r.Person, wire.FrameCancel, wire.CancelCommand{Person: r.Person, TurnID: r.ID, Attempt: r.Attempt})
1017}
1018
1019// Turn reads one of the person's turns.
1020func (s *Store) Turn(ctx context.Context, person, id string) (out wire.Turn, err error) {
1021 err = s.read(ctx, func(tx *gorm.DB) error {
1022 var r turnRecord
1023 if err := tx.Where("id = ? AND person = ? AND "+personLane, id, person).First(&r).Error; errors.Is(err, gorm.ErrRecordNotFound) {
1024 return ErrNotFound
1025 } else if err != nil {
1026 return err
1027 }
1028 out, err = (&txn{db: tx}).turnView(r)
1029 return err
1030 })
1031 return out, err
1032}
1033
1034// Messages pages history backwards from before, oldest first.
1035func (s *Store) Messages(ctx context.Context, person, before string, limit int) (out wire.MessagePage, err error) {
1036 return s.messages(ctx, wire.LaneCoordinator, person, before, limit)
1037}
1038
1039// messages pages the lane's history; before must be the lane's own.
1040func (s *Store) messages(ctx context.Context, lane, person, before string, limit int) (out wire.MessagePage, err error) {
1041 if limit <= 0 || limit > 200 {
1042 limit = 50
1043 }
1044 err = s.read(ctx, func(tx *gorm.DB) error {
1045 q := tx.Where("person = ? AND coalesce(lane, '') = ?", person, lane)
1046 if before != "" {
1047 var m messageRecord
1048 if err := tx.Where("id = ? AND person = ?", before, person).First(&m).Error; errors.Is(err, gorm.ErrRecordNotFound) {
1049 return ErrInvalid
1050 } else if err != nil {
1051 return err
1052 }
1053 if m.Lane != lane {
1054 // On the Coordinator's route another lane's message is an
1055 // id it does not have, as before lanes (422); on another
1056 // lane's route a Coordinator id is unknown (404). The 422
1057 // is deliberate, not the 404 Task 4 gives other lanes:
1058 // the Coordinator's API answers as it did before lanes,
1059 // for the clients built against it. Keep it.
1060 if lane == wire.LaneCoordinator {
1061 return ErrInvalid
1062 }
1063 return ErrNotFound
1064 }
1065 q = q.Where("seq < ?", m.Seq)
1066 }
1067 var rows []messageRecord
1068 if err := q.Order("seq DESC").Limit(limit + 1).Find(&rows).Error; err != nil {
1069 return err
1070 }
1071 more := len(rows) > limit
1072 if more {
1073 rows = rows[:limit]
1074 }
1075 out.Items = make([]wire.Message, 0, len(rows))
1076 for i := len(rows) - 1; i >= 0; i-- {
1077 out.Items = append(out.Items, messageView(rows[i]))
1078 }
1079 if err := withFiles(tx, out.Items); err != nil {
1080 return err
1081 }
1082 if more && len(out.Items) > 0 {
1083 out.Before = out.Items[0].ID
1084 }
1085 return nil
1086 })
1087 return out, err
1088}
1089
1090// Snapshot reads everything a client shows and the cursor to resume from.
1091func (s *Store) Snapshot(ctx context.Context, person string) (out wire.Snapshot, err error) {
1092 err = s.read(ctx, func(tx *gorm.DB) error {
1093 if err := s.authority.CurrentPerson(ctx, tx); err != nil {
1094 return err
1095 }
1096 var e error
1097 if out.Me, e = s.authority.Me(tx, person); e != nil {
1098 return e
1099 }
1100 if out.Cursor, e = maxEvent(tx); e != nil {
1101 return e
1102 }
1103 if out.Messages, out.Turns, e = laneTail(tx, wire.LaneCoordinator, person); e != nil {
1104 return e
1105 }
1106 if out.Runner, e = s.runnerView(tx, person); e != nil {
1107 return e
1108 }
1109 full := &txn{s: s, db: tx, viewer: person}
1110 if out.Projects, e = full.activeProjects(); e != nil {
1111 return e
1112 }
1113 c, e := full.coordinator(person)
1114 if e != nil {
1115 return e
1116 }
1117 out.Coordinator = coordinatorView(c)
1118 if out.Cards, e = full.snapshotCards(person); e != nil {
1119 return e
1120 }
1121 if out.Tasks, e = full.recentTasks(wire.MaxProjectCards); e != nil {
1122 return e
1123 }
1124 if out.HousekeepingSummary, e = full.hkSummary(person); e != nil {
1125 return e
1126 }
1127 conns, e := full.connections(person)
1128 if e != nil {
1129 return e
1130 }
1131 if out.Connections, e = full.connectionViews(person, conns); e != nil {
1132 return e
1133 }
1134 if out.Runners, e = full.runnerViews(person); e != nil {
1135 return e
1136 }
1137 return e
1138 })
1139 return out, err
1140}
1141
1142// laneTail is the lane's newest messages, oldest first, and its turns:
1143// those in flight and those the messages belong to.
1144func laneTail(tx *gorm.DB, lane, person string) ([]wire.Message, []wire.Turn, error) {
1145 var rows []messageRecord
1146 if e := tx.Where("person = ? AND coalesce(lane, '') = ?", person, lane).Order("seq DESC").Limit(wire.MaxTailMessages).Find(&rows).Error; e != nil {
1147 return nil, nil, e
1148 }
1149 messages := make([]wire.Message, 0, len(rows))
1150 for i := len(rows) - 1; i >= 0; i-- {
1151 messages = append(messages, messageView(rows[i]))
1152 }
1153 if e := withFiles(tx, messages); e != nil {
1154 return nil, nil, e
1155 }
1156 var turns []turnRecord
1157 if e := tx.Where("person = ? AND coalesce(lane, '') = ? AND (state IN ? OR id IN (SELECT turn_id FROM chat_messages WHERE person = ? AND coalesce(lane, '') = ? ORDER BY seq DESC LIMIT ?))", person, lane, wire.InFlight, person, lane, wire.MaxTailMessages).Order("created_at, id").Find(&turns).Error; e != nil {
1158 return nil, nil, e
1159 }
1160 out := make([]wire.Turn, 0, len(turns))
1161 t := &txn{db: tx}
1162 for _, r := range turns {
1163 v, e := t.turnView(r)
1164 if e != nil {
1165 return nil, nil, e
1166 }
1167 out = append(out, v)
1168 }
1169 return messages, out, nil
1170}
1171
1172func maxEvent(tx *gorm.DB) (int64, error) {
1173 var v *int64
1174 if err := tx.Model(&eventRecord{}).Select("max(id)").Scan(&v).Error; err != nil {
1175 return 0, err
1176 }
1177 if v == nil {
1178 return 0, nil
1179 }
1180 return *v, nil
1181}
1182
1183// runnerOnline is how long a runner stays online after its last hello.
1184const runnerOnline = 75 * time.Second
1185
1186// RunnerOnline is runnerOnline for the Machines screens, so a machine
1187// reads online there exactly when placement counts it online.
1188const RunnerOnline = runnerOnline
1189
1190func (s *Store) runnerView(tx *gorm.DB, person string) (wire.Runner, error) {
1191 id, err := s.authority.PrimaryRunner(tx, person)
1192 if err != nil || id == "" {
1193 return wire.Runner{}, err
1194 }
1195 rs, err := (&txn{s: s, db: tx}).runners(person)
1196 if err != nil {
1197 return wire.Runner{}, err
1198 }
1199 for _, r := range rs {
1200 if r.ID == id {
1201 return runnerView(r), nil
1202 }
1203 }
1204 return wire.Runner{ID: id}, nil
1205}
1206
1207// Events reads the person's events after cursor. A cursor older than the
1208// retention floor, or newer than any event, is expired.
1209func (s *Store) Events(ctx context.Context, person string, after int64, limit int) (out []wire.Event, err error) {
1210 return s.events(ctx, wire.LaneCoordinator, person, after, limit)
1211}
1212
1213// events reads the lane's events; the cursor is shared by both lanes.
1214func (s *Store) events(ctx context.Context, lane, person string, after int64, limit int) (out []wire.Event, err error) {
1215 err = s.read(ctx, func(tx *gorm.DB) error {
1216 top, err := maxEvent(tx)
1217 if err != nil {
1218 return err
1219 }
1220 var floor int64
1221 var low *int64
1222 if err = tx.Model(&eventRecord{}).Select("min(id)").Scan(&low).Error; err != nil {
1223 return err
1224 }
1225 if low != nil {
1226 floor = *low - 1
1227 }
1228 if after > top || after < floor {
1229 return ErrExpired
1230 }
1231 var rows []eventRecord
1232 if err = tx.Where("person = ? AND coalesce(lane, '') = ? AND id > ?", person, lane, after).Order("id").Limit(limit).Find(&rows).Error; err != nil {
1233 return err
1234 }
1235 for _, r := range rows {
1236 var e wire.Event
1237 if err := json.Unmarshal([]byte(r.Body), &e); err != nil {
1238 return err
1239 }
1240 e.Cursor = r.ID
1241 out = append(out, e)
1242 }
1243 return nil
1244 })
1245 return out, err
1246}
1247
1248// Cursor is the newest event id.
1249func (s *Store) Cursor(ctx context.Context) (top int64, err error) {
1250 err = s.read(ctx, func(tx *gorm.DB) error { top, err = maxEvent(tx); return err })
1251 return top, err
1252}
1253
1254// Sweep removes events past retention, keeping the newest row so ids are
1255// never reused, and old acked commands and inbox records.
1256func (s *Store) Sweep(ctx context.Context) error {
1257 cut := s.now().Add(-wire.EventRetention)
1258 return s.db.G.WithContext(ctx).Clauses(dbresolver.Write).Transaction(func(tx *gorm.DB) error {
1259 if err := tx.Exec("DELETE FROM chat_events WHERE created_at < ? AND id < (SELECT max(id) FROM chat_events)", cut).Error; err != nil {
1260 return err
1261 }
1262 if err := tx.Exec("DELETE FROM runner_commands WHERE acked_at IS NOT NULL AND acked_at < ? AND seq < (SELECT max(seq) FROM runner_commands)", cut).Error; err != nil {
1263 return err
1264 }
1265 if err := tx.Exec("DELETE FROM runner_inbox WHERE seen_at < ?", s.now().Add(-7*24*time.Hour)).Error; err != nil {
1266 return err
1267 }
1268 t := &txn{s: s, ctx: ctx, db: tx, touched: map[string]bool{}}
1269 if err := t.pruneChangeDiffs(); err != nil {
1270 return err
1271 }
1272 // Transfers past their TTL, and their chunks.
1273 var old []transferRecord
1274 if err := tx.Where("expires_at < ? AND state <> ?", s.now(), transferClosed).Find(&old).Error; err != nil {
1275 return err
1276 }
1277 for _, tr := range old {
1278 if err := t.dropChunks(tr); err != nil {
1279 return err
1280 }
1281 }
1282 if err := tx.Exec("DELETE FROM runner_transfers WHERE expires_at < ?", s.now()).Error; err != nil {
1283 return err
1284 }
1285 // Raw usage rows are kept 90 days (spec §6).
1286 if err := tx.Exec("DELETE FROM chat_usage WHERE recorded_at < ?", s.now().Add(-90*24*time.Hour)).Error; err != nil {
1287 return err
1288 }
1289 // Uploads never sent go after a day.
1290 if err := t.dropUnsent("", s.now().Add(-unsentFor)); err != nil {
1291 return err
1292 }
1293 return t.expireAttempts()
1294 })
1295}
1296