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 "encoding/json"
6 "errors"
7 "io"
8 "net/http"
9 "strings"
10 "sync"
11 "time"
12
13 "amadan.net/oficina/equipo/internal/wire"
14 "gorm.io/gorm"
15)
16
17// How Equipo learns a person's abilities from their Base (spec
18// 2026-11-26-assistant-abilities §5.3): with the member's host token,
19// over the host channel, never the member's own bearer.
20
21const (
22 // abilitiesBound bounds one fetch of the board (and of a legacy Base's
23 // operations).
24 abilitiesBound = 5 * time.Second
25 // maxBoard is the most of Base's answer read.
26 maxBoard = 16 << 10
27 // The audits of a board.
28 auditAbilitiesRevisionDown = "assistant.abilities.revision_down"
29 auditAbilitiesRevoked = "assistant.abilities.revoked"
30)
31
32// fetchOutcome is what Base's answer counts as (§5.3's table).
33type fetchOutcome int
34
35const (
36 // fetchFailed: no answer that counts (a 5xx, a timeout, a 404 once the
37 // origin has answered the board). The stored copy stands until it
38 // expires.
39 fetchFailed fetchOutcome = iota
40 // fetchOK: a 200 with a board.
41 fetchOK
42 // fetchLegacy: a Base older than the board (its board 404, its
43 // operations 200), considered only until the origin answers the board.
44 fetchLegacy
45 // fetchRevoked: Base no longer honours the token (401 on either route).
46 fetchRevoked
47)
48
49// abilityState is what the store keeps in memory about people's boards:
50// one fetch per person at a time (lock), the fetch order across them
51// (seq) and when each person was last fetched (for the hint's throttle).
52type abilityState struct {
53 locks sync.Map // person -> *sync.Mutex
54 mu sync.Mutex
55 seq int64
56 last map[string]time.Time
57}
58
59// nextFetchSeq is a number above every one taken before in this process,
60// and above the wall clock's nanoseconds, so another process's fetch
61// started earlier has a lower one.
62func (s *Store) nextFetchSeq() int64 {
63 s.abilities.mu.Lock()
64 defer s.abilities.mu.Unlock()
65 n := time.Now().UnixNano()
66 if n <= s.abilities.seq {
67 n = s.abilities.seq + 1
68 }
69 s.abilities.seq = n
70 return n
71}
72
73func (s *Store) personLock(person string) *sync.Mutex {
74 m, _ := s.abilities.locks.LoadOrStore(person, &sync.Mutex{})
75 return m.(*sync.Mutex)
76}
77
78// boardClient calls a person's Base: no redirect followed, so the host
79// token goes nowhere but the registered origin.
80var boardClient = &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
81
82// fetchBoard asks origin for the board with token, bounded by
83// abilitiesBound, outside any transaction. With legacy (the origin has
84// never answered the board), a 404 is followed by the operations route,
85// whose 200 makes it fetchLegacy. err is set only with fetchFailed, and
86// never carries the token.
87func (s *Store) fetchBoard(ctx context.Context, origin, token string, legacy bool) (wire.AbilityBoard, fetchOutcome, error) {
88 ctx, cancel := context.WithTimeout(ctx, abilitiesBound)
89 defer cancel()
90 var board wire.AbilityBoard
91 status, body, err := getWithToken(ctx, origin+"/api/v1/abilities", token)
92 switch {
93 case err != nil:
94 return board, fetchFailed, err
95 case status == http.StatusUnauthorized:
96 return board, fetchRevoked, nil
97 case status == http.StatusOK:
98 if err := json.Unmarshal(body, &board); err != nil || board.Revision < 0 || len(board.Ask) > 200 {
99 return wire.AbilityBoard{}, fetchFailed, errors.New("abilities: Base's board was not understood")
100 }
101 return board, fetchOK, nil
102 case status != http.StatusNotFound || !legacy:
103 return board, fetchFailed, errors.New("abilities: Base answered " + http.StatusText(status))
104 }
105 status, _, err = getWithToken(ctx, origin+"/api/v1/operations", token)
106 switch {
107 case err != nil:
108 return board, fetchFailed, err
109 case status == http.StatusUnauthorized:
110 return board, fetchRevoked, nil
111 case status == http.StatusOK:
112 return board, fetchLegacy, nil
113 }
114 return board, fetchFailed, errors.New("abilities: Base answered " + http.StatusText(status))
115}
116
117// getWithToken is one GET with the host token as bearer: its status and
118// the start of its body. A transport failure is reported without the
119// URL, which never holds the token but stays out of logs all the same.
120func getWithToken(ctx context.Context, url, token string) (int, []byte, error) {
121 req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
122 if err != nil {
123 return 0, nil, errors.New("abilities: bad host origin")
124 }
125 req.Header.Set("Authorization", "Bearer "+token)
126 req.Header.Set("Accept", "application/json")
127 res, err := boardClient.Do(req)
128 if err != nil {
129 return 0, nil, errors.New("abilities: Base did not answer")
130 }
131 defer res.Body.Close()
132 body, _ := io.ReadAll(io.LimitReader(res.Body, maxBoard))
133 return res.StatusCode, body, nil
134}
135
136// RefreshAbilities fetches the person's board from their registered Base
137// and applies it (§5.3), one fetch per person at a time, outside any
138// transaction but the one that applies it. revision is the board's
139// revision Equipo then holds; fresh says it applied a 200 or a legacy
140// renewal. A person with no host has nothing to fetch.
141func (s *Store) RefreshAbilities(ctx context.Context, person string) (revision int64, fresh bool, err error) {
142 m := s.personLock(person)
143 m.Lock()
144 defer m.Unlock()
145 origin, token, ok, err := s.Host(ctx, person)
146 if err != nil || !ok {
147 return 0, false, err
148 }
149 var seen []bool
150 if err := s.read(ctx, func(tx *gorm.DB) error {
151 return tx.Model(&abilitiesRecord{}).Where("person = ? AND origin = ?", person, origin).Pluck("coalesce(authoritative_seen, 0)", &seen).Error
152 }); err != nil {
153 return 0, false, err
154 }
155 seq := s.nextFetchSeq()
156 s.abilities.mu.Lock()
157 if s.abilities.last == nil {
158 s.abilities.last = map[string]time.Time{}
159 }
160 s.abilities.last[person] = time.Now()
161 s.abilities.mu.Unlock()
162 board, outcome, ferr := s.fetchBoard(ctx, origin, token, len(seen) == 0 || !seen[0])
163 if outcome == fetchFailed {
164 s.logAbilities(person, ferr)
165 }
166 var changed bool
167 err = s.tx(ctx, func(t *txn) error {
168 var err error
169 changed, err = t.applyBoard(person, origin, seq, board, outcome)
170 if err != nil {
171 return err
172 }
173 if changed {
174 // A held job's card says whether building is on again.
175 if err := t.reprojectHeld(person); err != nil {
176 return err
177 }
178 }
179 var r abilitiesRecord
180 if err := t.db.Where("person = ? AND origin = ?", person, origin).Limit(1).Find(&r).Error; err != nil {
181 return err
182 }
183 revision = r.Revision
184 return nil
185 })
186 if err != nil {
187 return 0, false, err
188 }
189 if changed {
190 if ops := s.operations(); ops != nil {
191 ops.Forget(person)
192 }
193 }
194 return revision, outcome == fetchOK || outcome == fetchLegacy, nil
195}
196
197// logAbilities reports a fetch that failed: by person, never a token.
198func (s *Store) logAbilities(person string, err error) {
199 if l := s.logger.Load(); l != nil && err != nil {
200 l.Warn("abilities: fetch failed", "person", person, "err", err)
201 }
202}
203
204// fetchedWithin reports whether the person's board was fetched less than
205// d ago (the hint's throttle).
206func (s *Store) fetchedWithin(person string, d time.Duration) bool {
207 s.abilities.mu.Lock()
208 defer s.abilities.mu.Unlock()
209 at, ok := s.abilities.last[person]
210 return ok && time.Since(at) < d
211}
212
213// applyBoard applies one fetch's outcome to the person's copy at origin,
214// by §5.3's table, unless a fetch started after it was applied first.
215// changed: what the person may do may have changed.
216func (t *txn) applyBoard(person, origin string, seq int64, b wire.AbilityBoard, outcome fetchOutcome) (changed bool, err error) {
217 if outcome == fetchFailed {
218 return false, nil
219 }
220 origin = strings.ToLower(origin)
221 var r abilitiesRecord
222 if err := t.db.Where("person = ? AND origin = ?", person, origin).Limit(1).Find(&r).Error; err != nil {
223 return false, err
224 }
225 if r.Person != "" && r.FetchSeq > seq {
226 return false, nil
227 }
228 prior := r
229 r.Person, r.Origin, r.FetchSeq = person, origin, seq
230 now := t.now()
231 switch outcome {
232 case fetchRevoked:
233 r.RevokedAt = &now
234 if r.Source == "" {
235 r.Source, r.Abilities = SourceBase, "{}"
236 }
237 if err := t.db.Save(&r).Error; err != nil {
238 return false, err
239 }
240 return prior.RevokedAt == nil, t.s.authority.Audit(t.db, person, auditAbilitiesRevoked, origin)
241 case fetchLegacy:
242 if r.AuthoritativeSeen {
243 return false, nil
244 }
245 raw, _ := json.Marshal(defaultBoard())
246 r.Abilities, r.Admin, r.Ask, r.Source, r.Revision = string(raw), false, "", SourceLegacy, 0
247 case fetchOK:
248 raw, err := json.Marshal(b.Abilities)
249 if err != nil {
250 return false, err
251 }
252 down := prior.Source == SourceBase && prior.Person != "" && b.Revision < prior.Revision
253 r.Abilities, r.Admin, r.Ask, r.Source, r.Revision, r.AuthoritativeSeen = string(raw), b.Admin, b.Ask, SourceBase, b.Revision, true
254 if down {
255 if err := t.s.authority.Audit(t.db, person, auditAbilitiesRevisionDown, origin); err != nil {
256 return false, err
257 }
258 }
259 }
260 r.ConfirmedAt, r.RevokedAt = &now, nil
261 if err := t.db.Save(&r).Error; err != nil {
262 return false, err
263 }
264 changed = prior.Person == "" || prior.Abilities != r.Abilities || prior.Admin != r.Admin || prior.RevokedAt != nil || prior.Source != r.Source
265 return changed, nil
266}
267