oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package thintest
2
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "encoding/json"
8 "fmt"
9 "io"
10 "mime"
11 "net/http"
12 "net/url"
13 "strconv"
14 "strings"
15 "sync"
16 "time"
17
18 "amadan.net/oficina/equipo/internal/wire"
19)
20
21// Client is a person API v1 client with a device bearer. It is the only
22// way the headless suite touches Equipo.
23type Client struct {
24 Origin string
25 Token string
26 HTTP *http.Client
27 // Capabilities, when set, goes with each request as Base sends it
28 // (Base-Capabilities): what the person's Base draws.
29 Capabilities string
30}
31
32func NewClient(origin, token string) *Client {
33 return &Client{Origin: strings.TrimRight(origin, "/"), Token: token, HTTP: &http.Client{Timeout: 30 * time.Second}}
34}
35
36func (c *Client) do(ctx context.Context, method, path string, body, out any) error {
37 var reader io.Reader
38 if body != nil {
39 raw, err := json.Marshal(body)
40 if err != nil {
41 return err
42 }
43 reader = bytes.NewReader(raw)
44 }
45 r, err := http.NewRequestWithContext(ctx, method, c.Origin+path, reader)
46 if err != nil {
47 return err
48 }
49 r.Header.Set("Authorization", "Bearer "+c.Token)
50 if c.Capabilities != "" {
51 r.Header.Set("Base-Capabilities", c.Capabilities)
52 }
53 if body != nil {
54 r.Header.Set("Content-Type", "application/json")
55 }
56 res, err := c.HTTP.Do(r)
57 if err != nil {
58 return err
59 }
60 defer res.Body.Close()
61 raw, _ := io.ReadAll(io.LimitReader(res.Body, 4<<20))
62 if res.StatusCode/100 != 2 {
63 return &ErrStatus{Status: res.StatusCode, Body: raw}
64 }
65 if out != nil {
66 return json.Unmarshal(raw, out)
67 }
68 return nil
69}
70
71func (c *Client) Me(ctx context.Context) (out wire.Me, err error) {
72 return out, c.do(ctx, "GET", "/api/v1/me", nil, &out)
73}
74
75func (c *Client) Send(ctx context.Context, text, key string) (out wire.Sent, err error) {
76 return out, c.do(ctx, "POST", "/api/v1/messages", wire.SendMessage{Text: text, IdempotencyKey: key}, &out)
77}
78
79// SendWith sends a message with attachments (ids from Upload).
80func (c *Client) SendWith(ctx context.Context, text, key string, files []string) (out wire.Sent, err error) {
81 return out, c.do(ctx, "POST", "/api/v1/messages", wire.SendMessage{Text: text, IdempotencyKey: key, Attachments: files}, &out)
82}
83
84// DeleteAttachment is DELETE /api/v1/attachments/{id}: one of the
85// person's own unsent uploads.
86func (c *Client) DeleteAttachment(ctx context.Context, id string) error {
87 return c.do(ctx, "DELETE", "/api/v1/attachments/"+id, nil, nil)
88}
89
90// Upload is POST /api/v1/attachments: the bytes, their type and name.
91func (c *Client) Upload(ctx context.Context, name, mediaType string, data []byte) (out wire.MessageAttachment, err error) {
92 r, err := http.NewRequestWithContext(ctx, "POST", c.Origin+"/api/v1/attachments", bytes.NewReader(data))
93 if err != nil {
94 return out, err
95 }
96 r.Header.Set("Authorization", "Bearer "+c.Token)
97 r.Header.Set("Content-Type", mediaType)
98 r.Header.Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": name}))
99 return out, c.round(r, &out)
100}
101
102// Attachment reads an attachment's bytes (or its preview) and headers.
103func (c *Client) Attachment(ctx context.Context, id string, preview bool) ([]byte, http.Header, error) {
104 path := "/api/v1/attachments/" + id
105 if preview {
106 path += "/preview"
107 }
108 r, err := http.NewRequestWithContext(ctx, "GET", c.Origin+path, nil)
109 if err != nil {
110 return nil, nil, err
111 }
112 r.Header.Set("Authorization", "Bearer "+c.Token)
113 res, err := c.HTTP.Do(r)
114 if err != nil {
115 return nil, nil, err
116 }
117 defer res.Body.Close()
118 raw, _ := io.ReadAll(io.LimitReader(res.Body, 16<<20))
119 if res.StatusCode/100 != 2 {
120 return nil, res.Header, &ErrStatus{Status: res.StatusCode, Body: raw}
121 }
122 return raw, res.Header, nil
123}
124
125func (c *Client) round(r *http.Request, out any) error {
126 res, err := c.HTTP.Do(r)
127 if err != nil {
128 return err
129 }
130 defer res.Body.Close()
131 raw, _ := io.ReadAll(io.LimitReader(res.Body, 4<<20))
132 if res.StatusCode/100 != 2 {
133 return &ErrStatus{Status: res.StatusCode, Body: raw}
134 }
135 return json.Unmarshal(raw, out)
136}
137
138func (c *Client) Snapshot(ctx context.Context) (out wire.Snapshot, err error) {
139 return out, c.do(ctx, "GET", "/api/v1/snapshot", nil, &out)
140}
141
142func (c *Client) Turn(ctx context.Context, id string) (out wire.Turn, err error) {
143 return out, c.do(ctx, "GET", "/api/v1/turns/"+id, nil, &out)
144}
145
146func (c *Client) Cancel(ctx context.Context, id string) (out wire.CancelAccepted, err error) {
147 return out, c.do(ctx, "POST", "/api/v1/turns/"+id+"/cancel", struct{}{}, &out)
148}
149
150// Retry is POST /api/v1/turns/{id}/retry (Try again).
151func (c *Client) Retry(ctx context.Context, id string) (out wire.Turn, err error) {
152 return out, c.do(ctx, "POST", "/api/v1/turns/"+id+"/retry", nil, &out)
153}
154
155func (c *Client) Messages(ctx context.Context, before string, limit int) (out wire.MessagePage, err error) {
156 path := "/api/v1/messages?limit=" + strconv.Itoa(limit)
157 if before != "" {
158 path += "&before=" + before
159 }
160 return out, c.do(ctx, "GET", path, nil, &out)
161}
162
163func (c *Client) Projects(ctx context.Context) (out wire.ProjectList, err error) {
164 return out, c.do(ctx, "GET", "/api/v1/projects", nil, &out)
165}
166
167func (c *Client) AddProject(ctx context.Context, repo string) (out wire.Project, err error) {
168 return out, c.do(ctx, "POST", "/api/v1/projects", wire.AddProject{Repo: repo}, &out)
169}
170
171func (c *Client) RemoveProject(ctx context.Context, id string) (out wire.Project, err error) {
172 return out, c.do(ctx, "DELETE", "/api/v1/projects/"+id, nil, &out)
173}
174
175func (c *Client) Answer(ctx context.Context, id, choice string, revision int64) (out wire.Answered, err error) {
176 return out, c.do(ctx, "POST", "/api/v1/cards/"+id+"/answer", wire.AnswerCard{Choice: choice, Revision: revision}, &out)
177}
178
179// AnswerNote answers a card with the person's note (a direction card's
180// Try again).
181func (c *Client) AnswerNote(ctx context.Context, id, choice, note string, revision int64) (out wire.Answered, err error) {
182 return out, c.do(ctx, "POST", "/api/v1/cards/"+id+"/answer", wire.AnswerCard{Choice: choice, Revision: revision, Note: note}, &out)
183}
184
185// Specialists lists the team's data-defined specialists.
186func (c *Client) Specialists(ctx context.Context) (out wire.SpecialistList, err error) {
187 return out, c.do(ctx, "GET", "/api/v1/specialists", nil, &out)
188}
189
190// RevokeSpecialist revokes an active specialist's grants at its revision.
191func (c *Client) RevokeSpecialist(ctx context.Context, id string, revision int64) (out wire.Specialist, err error) {
192 return out, c.do(ctx, "POST", "/api/v1/specialists/"+id+"/revoke", wire.RevokeSpecialist{Revision: revision}, &out)
193}
194
195// SetKind switches a task between a change and an exploration.
196func (c *Client) SetKind(ctx context.Context, id, kind string, revision int64) (out wire.Task, err error) {
197 return out, c.do(ctx, "POST", "/api/v1/tasks/"+id+"/kind", wire.SetKind{Kind: kind, Revision: revision}, &out)
198}
199
200func (c *Client) Notebook(ctx context.Context) (out wire.Notebook, err error) {
201 return out, c.do(ctx, "GET", "/api/v1/notebook", nil, &out)
202}
203
204// ResetNotebook clears the notebook and starts the coordinator afresh.
205func (c *Client) ResetNotebook(ctx context.Context) (out wire.Coordinator, err error) {
206 return out, c.do(ctx, "POST", "/api/v1/notebook/reset", nil, &out)
207}
208
209// Tasks lists the team's tasks.
210func (c *Client) Tasks(ctx context.Context) (out wire.TaskList, err error) {
211 return out, c.do(ctx, "GET", "/api/v1/tasks", nil, &out)
212}
213
214// NeedsYou lists the person's tasks waiting for their decision.
215func (c *Client) Runners(ctx context.Context) (out wire.RunnerList, err error) {
216 err = c.do(ctx, "GET", "/api/v1/runners", nil, &out)
217 return
218}
219
220func (c *Client) NeedsYou(ctx context.Context) (out wire.TaskList, err error) {
221 return out, c.do(ctx, "GET", "/api/v1/needs-you", nil, &out)
222}
223
224// Task reads one task with its steps, findings and thread.
225func (c *Client) Task(ctx context.Context, id string) (out wire.Task, err error) {
226 return out, c.do(ctx, "GET", "/api/v1/tasks/"+id, nil, &out)
227}
228
229// CancelTask asks for the task's running step to end.
230func (c *Client) CancelTask(ctx context.Context, id string) (out wire.TaskAccepted, err error) {
231 return out, c.do(ctx, "POST", "/api/v1/tasks/"+id+"/cancel", nil, &out)
232}
233
234// MarkDuplicate folds the task into another open task of its project.
235func (c *Client) MarkDuplicate(ctx context.Context, id, of string) (out wire.Task, err error) {
236 return out, c.do(ctx, "POST", "/api/v1/tasks/"+id+"/duplicate", wire.MarkDuplicate{Of: of}, &out)
237}
238
239// RetryTask starts a new attempt once the last one's termination is known.
240// RecoverTask settles a step stopped when its machine was removed.
241func (c *Client) RecoverTask(ctx context.Context, id string) (out wire.TaskAccepted, err error) {
242 return out, c.do(ctx, "POST", "/api/v1/tasks/"+id+"/recover", nil, &out)
243}
244
245func (c *Client) RetryTask(ctx context.Context, id string) (out wire.TaskAccepted, err error) {
246 return out, c.do(ctx, "POST", "/api/v1/tasks/"+id+"/retry", nil, &out)
247}
248
249// SetPriority is the task creator's priority and deadline.
250func (c *Client) SetPriority(ctx context.Context, id string, in wire.SetPriority) (out wire.Task, err error) {
251 return out, c.do(ctx, "PUT", "/api/v1/tasks/"+id+"/priority", in, &out)
252}
253
254// RunNow is the task creator's Run it now anyway on a held step.
255func (c *Client) RunNow(ctx context.Context, id string, in wire.RunNow) (out wire.RunNowAccepted, err error) {
256 return out, c.do(ctx, "POST", "/api/v1/tasks/"+id+"/run-now", in, &out)
257}
258
259// RoundTask is Try another round on a task the automatic rounds did not
260// settle.
261func (c *Client) RoundTask(ctx context.Context, id string) (out wire.TaskAccepted, err error) {
262 return out, c.do(ctx, "POST", "/api/v1/tasks/"+id+"/round", nil, &out)
263}
264
265// MergeTask is the creator's Merge on a task left at Ready to merge.
266func (c *Client) MergeTask(ctx context.Context, id string) (out wire.TaskAccepted, err error) {
267 return out, c.do(ctx, "POST", "/api/v1/tasks/"+id+"/merge", nil, &out)
268}
269
270// StepLog reads a step's log tail.
271func (c *Client) StepLog(ctx context.Context, id string) (out wire.StepLog, err error) {
272 return out, c.do(ctx, "GET", "/api/v1/steps/"+id+"/log", nil, &out)
273}
274
275// PostThread adds the person's note to a task's thread.
276func (c *Client) PostThread(ctx context.Context, id, text, key string) (out wire.ThreadEntry, err error) {
277 return out, c.do(ctx, "POST", "/api/v1/tasks/"+id+"/thread", wire.PostThread{Text: text, IdempotencyKey: key}, &out)
278}
279
280// Ask asks one of a task's specialists a question.
281func (c *Client) Ask(ctx context.Context, task, text, specialist, key string) (out wire.Question, err error) {
282 return out, c.do(ctx, "POST", "/api/v1/tasks/"+task+"/questions", wire.AskQuestion{Text: text, IdempotencyKey: key, Specialist: specialist}, &out)
283}
284
285// Question reads one question and its answer.
286func (c *Client) Question(ctx context.Context, id string) (out wire.Question, err error) {
287 return out, c.do(ctx, "GET", "/api/v1/questions/"+id, nil, &out)
288}
289
290// CancelQuestion stops a question.
291func (c *Client) CancelQuestion(ctx context.Context, id string) (out wire.TaskAccepted, err error) {
292 return out, c.do(ctx, "POST", "/api/v1/questions/"+id+"/cancel", nil, &out)
293}
294
295// Connections lists the person's connections.
296func (c *Client) Connections(ctx context.Context) (out wire.ConnectionList, err error) {
297 return out, c.do(ctx, "GET", "/api/v1/connections", nil, &out)
298}
299
300// Connect starts a connection attempt.
301func (c *Client) Connect(ctx context.Context, in wire.Connect) (out wire.Connection, err error) {
302 return out, c.do(ctx, "POST", "/api/v1/connections", in, &out)
303}
304
305// Connection reads one connection.
306func (c *Client) Connection(ctx context.Context, id string) (out wire.Connection, err error) {
307 return out, c.do(ctx, "GET", "/api/v1/connections/"+id, nil, &out)
308}
309
310// SignOut signs a connection out.
311func (c *Client) SignOut(ctx context.Context, id string) (out wire.Connection, err error) {
312 return out, c.do(ctx, "DELETE", "/api/v1/connections/"+id, nil, &out)
313}
314
315// Preferences reads the person's preference.
316func (c *Client) Preferences(ctx context.Context) (out wire.Preferences, err error) {
317 return out, c.do(ctx, "GET", "/api/v1/connections/preference", nil, &out)
318}
319
320// SetPreferences changes it, against the revision read.
321func (c *Client) SetPreferences(ctx context.Context, in wire.Preferences) (out wire.Preferences, err error) {
322 return out, c.do(ctx, "PUT", "/api/v1/connections/preference", in, &out)
323}
324
325// CheckConnection is a connection's Check again.
326func (c *Client) CheckConnection(ctx context.Context, id string) error {
327 return c.do(ctx, "POST", "/api/v1/connections/"+id+"/check", nil, nil)
328}
329
330// Forget removes a signed-out connection's record.
331func (c *Client) Forget(ctx context.Context, id string) error {
332 return c.do(ctx, "POST", "/api/v1/connections/"+id+"/forget", nil, nil)
333}
334
335// CancelConnection ends an attempt.
336func (c *Client) CancelConnection(ctx context.Context, id string) (out wire.Connection, err error) {
337 return out, c.do(ctx, "POST", "/api/v1/connections/"+id+"/cancel", nil, &out)
338}
339
340// Secret posts a token attempt's sealed secret (202 with the attempt).
341func (c *Client) Secret(ctx context.Context, id string, in wire.Sealed) (out wire.Connection, err error) {
342 return out, c.do(ctx, "POST", "/api/v1/connections/"+id+"/secret", in, &out)
343}
344
345// ChooseModel picks a connecting API-key connection's model.
346func (c *Client) ChooseModel(ctx context.Context, id, model string) (out wire.Connection, err error) {
347 return out, c.do(ctx, "POST", "/api/v1/connections/"+id+"/model", wire.ChooseModel{Model: model}, &out)
348}
349
350// SetBudget changes a metered connection's budget.
351func (c *Client) SetBudget(ctx context.Context, id string, in wire.SetBudget) (out wire.Connection, err error) {
352 return out, c.do(ctx, "PUT", "/api/v1/connections/"+id+"/budget", in, &out)
353}
354
355// SetModels sets a metered connection's allowed set (§16.1).
356func (c *Client) SetModels(ctx context.Context, id string, in wire.SetModels) (out wire.Connection, err error) {
357 return out, c.do(ctx, "PUT", "/api/v1/connections/"+id+"/models", in, &out)
358}
359
360// ResumeSpend resumes a connection paused with its spend unknown.
361func (c *Client) ResumeSpend(ctx context.Context, id string, pause int64) error {
362 return c.do(ctx, "POST", "/api/v1/connections/"+id+"/resume", wire.ResumeSpend{PauseRevision: pause}, nil)
363}
364
365// Stream is one open SSE connection.
366type Stream struct {
367 Events <-chan wire.Event
368 Done <-chan error
369 cancel context.CancelFunc
370 body io.Closer
371}
372
373func (s *Stream) Close() { s.cancel(); s.body.Close() }
374
375// Open opens GET /api/v1/events?after=cursor. A 410 comes back as an
376// *ErrStatus before any event.
377func (c *Client) Open(ctx context.Context, after int64) (*Stream, error) {
378 return c.openEvents(ctx, "/api/v1/events", after)
379}
380
381// openEvents opens an SSE route at path?after=cursor.
382func (c *Client) openEvents(ctx context.Context, path string, after int64) (*Stream, error) {
383 ctx, cancel := context.WithCancel(ctx)
384 sep := "?"
385 if strings.HasSuffix(path, "&") {
386 sep = ""
387 }
388 r, err := http.NewRequestWithContext(ctx, "GET", c.Origin+path+sep+"after="+strconv.FormatInt(after, 10), nil)
389 if err != nil {
390 cancel()
391 return nil, err
392 }
393 r.Header.Set("Authorization", "Bearer "+c.Token)
394 r.Header.Set("Accept", "text/event-stream")
395 res, err := (&http.Client{}).Do(r)
396 if err != nil {
397 cancel()
398 return nil, err
399 }
400 if res.StatusCode != 200 {
401 raw, _ := io.ReadAll(io.LimitReader(res.Body, 1<<16))
402 res.Body.Close()
403 cancel()
404 return nil, &ErrStatus{Status: res.StatusCode, Body: raw}
405 }
406 events := make(chan wire.Event, 256)
407 done := make(chan error, 1)
408 go func() {
409 defer close(events)
410 done <- readSSE(res.Body, events)
411 }()
412 return &Stream{Events: events, Done: done, cancel: cancel, body: res.Body}, nil
413}
414
415func readSSE(body io.Reader, out chan<- wire.Event) error {
416 scan := bufio.NewScanner(body)
417 scan.Buffer(make([]byte, 0, 64<<10), wire.MaxFrameBytes*2)
418 var kind, data string
419 for scan.Scan() {
420 line := scan.Text()
421 switch {
422 case line == "":
423 if kind != "" && kind != wire.EventPing && data != "" {
424 var e wire.Event
425 if err := wire.Strict([]byte(data), &e); err != nil {
426 return fmt.Errorf("event %s: %w", kind, err)
427 }
428 out <- e
429 }
430 kind, data = "", ""
431 case strings.HasPrefix(line, "event: "):
432 kind = strings.TrimPrefix(line, "event: ")
433 case strings.HasPrefix(line, "data: "):
434 data = strings.TrimPrefix(line, "data: ")
435 }
436 }
437 return scan.Err()
438}
439
440// Conversation is what a client shows, built only from snapshot and events
441// with the documented dedup rules.
442type Conversation struct {
443 mu sync.Mutex
444 Cursor int64
445 Messages map[string]wire.Message
446 Order []string
447 Turns map[string]wire.Turn
448 Drafts map[string]string
449 // Connections are the person's connections, by id.
450 Connections map[string]wire.Connection
451 Runner wire.Runner
452 Cards map[string]wire.Card
453 Projects map[string]wire.Project
454 // Tasks are the team's tasks; Steps every step seen, by id.
455 Tasks map[string]wire.Task
456 Steps map[string]wire.Step
457 // Runners are the person's runners by id, from the snapshot and the
458 // runner events.
459 Runners map[string]wire.Runner
460 // Stages records each task's stages in the order seen.
461 Stages map[string][]string
462 // Activity is each turn's activity in arrival order, until its reply.
463 Activity map[string][]wire.Activity
464 // StepActivity is each step's activity events in arrival order.
465 StepActivity map[string][]wire.StepActivity
466 // FirstDelta records when each turn's first delta arrived;
467 // FirstActivity when its first activity line did.
468 FirstDelta map[string]time.Time
469 FirstActivity map[string]time.Time
470 // Questions are the task questions seen, by id; their streamed
471 // answers are in Drafts under the question's id until answered.
472 Questions map[string]wire.Question
473 // DeltaResources counts deltas by event resource (turn, question).
474 DeltaResources map[string]int
475 // Coordinator is whether the coordinator has moved in.
476 Coordinator wire.Coordinator
477 Applied int
478 changed chan struct{}
479}
480
481func NewConversation(s wire.Snapshot) *Conversation {
482 c := &Conversation{Messages: map[string]wire.Message{}, Turns: map[string]wire.Turn{}, Drafts: map[string]string{}, FirstDelta: map[string]time.Time{}, FirstActivity: map[string]time.Time{}, Activity: map[string][]wire.Activity{}, StepActivity: map[string][]wire.StepActivity{}, changed: make(chan struct{})}
483 c.Reset(s)
484 return c
485}
486
487// Reset replaces state with a snapshot, as after 410 Gone.
488func (c *Conversation) Reset(s wire.Snapshot) {
489 c.mu.Lock()
490 defer c.mu.Unlock()
491 c.Cursor, c.Runner, c.Coordinator = s.Cursor, s.Runner, s.Coordinator
492 c.Messages, c.Order, c.Turns, c.Drafts = map[string]wire.Message{}, nil, map[string]wire.Turn{}, map[string]string{}
493 c.Cards, c.Projects = map[string]wire.Card{}, map[string]wire.Project{}
494 c.Tasks, c.Steps, c.Stages = map[string]wire.Task{}, map[string]wire.Step{}, map[string][]string{}
495 c.Runners = map[string]wire.Runner{}
496 for _, r := range s.Runners {
497 c.Runners[r.ID] = r
498 }
499 c.Connections = map[string]wire.Connection{}
500 for _, v := range s.Connections {
501 c.Connections[v.ID] = v
502 }
503 c.Questions, c.DeltaResources = map[string]wire.Question{}, map[string]int{}
504 for _, k := range s.Tasks {
505 c.applyTask(k)
506 }
507 for _, k := range s.Cards {
508 c.Cards[k.ID] = k
509 }
510 for _, p := range s.Projects {
511 c.Projects[p.ID] = p
512 }
513 for _, m := range s.Messages {
514 c.Messages[m.ID] = m
515 c.Order = append(c.Order, m.ID)
516 }
517 for _, t := range s.Turns {
518 c.Turns[t.ID] = t
519 }
520 c.signal()
521}
522
523// applyTask keeps the newer revision of a task and its steps.
524func (c *Conversation) applyTask(k wire.Task) bool {
525 if old, ok := c.Tasks[k.ID]; ok && k.Revision <= old.Revision {
526 return false
527 }
528 c.Tasks[k.ID] = k
529 if st := c.Stages[k.ID]; len(st) == 0 || st[len(st)-1] != k.Stage {
530 c.Stages[k.ID] = append(st, k.Stage)
531 }
532 for _, s := range k.Steps {
533 if old, ok := c.Steps[s.ID]; !ok || s.Revision > old.Revision {
534 c.Steps[s.ID] = s
535 }
536 }
537 for _, q := range k.Questions {
538 c.applyQuestion(q)
539 }
540 return true
541}
542
543// applyQuestion keeps the newer revision; an ended question's draft goes.
544func (c *Conversation) applyQuestion(q wire.Question) bool {
545 if old, ok := c.Questions[q.ID]; ok && q.Revision <= old.Revision {
546 return false
547 }
548 c.Questions[q.ID] = q
549 if wire.QuestionTerminal(q.State) {
550 delete(c.Drafts, q.ID)
551 }
552 return true
553}
554
555func (c *Conversation) signal() {
556 close(c.changed)
557 c.changed = make(chan struct{})
558}
559
560// Apply folds one event in. It returns false for a duplicate or stale one.
561func (c *Conversation) Apply(e wire.Event) bool {
562 c.mu.Lock()
563 defer c.mu.Unlock()
564 if e.Cursor <= c.Cursor {
565 return false
566 }
567 c.Cursor = e.Cursor
568 applied := false
569 switch e.Type {
570 case wire.EventMessage:
571 var m wire.Message
572 if json.Unmarshal(e.Data, &m) == nil {
573 if old, ok := c.Messages[m.ID]; !ok || m.Revision > old.Revision {
574 if !ok {
575 c.Order = append(c.Order, m.ID)
576 }
577 c.Messages[m.ID] = m
578 if m.Role == wire.RoleCoordinator {
579 delete(c.Drafts, m.TurnID)
580 }
581 applied = true
582 }
583 }
584 case wire.EventTurn:
585 var t wire.Turn
586 if json.Unmarshal(e.Data, &t) == nil {
587 if old, ok := c.Turns[t.ID]; !ok || t.Revision > old.Revision {
588 c.Turns[t.ID] = t
589 // A failed or cancelled turn, or a new attempt (a failover,
590 // a recovery), drops the draft: the new attempt streams anew.
591 if t.State == wire.TurnCancelled || t.State == wire.TurnFailed || ok && t.Attempt != old.Attempt {
592 delete(c.Drafts, t.ID)
593 }
594 applied = true
595 }
596 }
597 case wire.EventConnection:
598 var v wire.Connection
599 if json.Unmarshal(e.Data, &v) == nil {
600 if old, ok := c.Connections[v.ID]; !ok || v.Revision > old.Revision {
601 c.Connections[v.ID] = v
602 if v.State == wire.ConnForgotten {
603 // The last event of a record the person removed.
604 delete(c.Connections, v.ID)
605 }
606 applied = true
607 }
608 }
609 case wire.EventDelta:
610 var d wire.Delta
611 if json.Unmarshal(e.Data, &d) == nil && int64(len(c.Drafts[d.TurnID])) == d.Offset {
612 if _, ok := c.FirstDelta[d.TurnID]; !ok {
613 c.FirstDelta[d.TurnID] = time.Now()
614 }
615 c.Drafts[d.TurnID] += d.Text
616 c.DeltaResources[e.Resource]++
617 applied = true
618 }
619 case wire.EventQuestion:
620 var q wire.Question
621 if json.Unmarshal(e.Data, &q) == nil {
622 applied = c.applyQuestion(q)
623 }
624 case wire.EventTask:
625 var k wire.Task
626 if json.Unmarshal(e.Data, &k) == nil {
627 applied = c.applyTask(k)
628 }
629 case wire.EventStep:
630 var k wire.Step
631 if json.Unmarshal(e.Data, &k) == nil {
632 if old, ok := c.Steps[k.ID]; !ok || k.Revision > old.Revision {
633 c.Steps[k.ID], applied = k, true
634 }
635 }
636 case wire.EventCard:
637 var k wire.Card
638 if json.Unmarshal(e.Data, &k) == nil {
639 if old, ok := c.Cards[k.ID]; !ok || k.Revision > old.Revision {
640 c.Cards[k.ID] = k
641 applied = true
642 }
643 }
644 case wire.EventProject:
645 var p wire.Project
646 if json.Unmarshal(e.Data, &p) == nil {
647 if old, ok := c.Projects[p.ID]; !ok || p.Revision > old.Revision {
648 c.Projects[p.ID] = p
649 applied = true
650 }
651 }
652 case wire.EventActivity:
653 var a wire.Activity
654 if e.Resource == wire.ResourceStep {
655 var sa wire.StepActivity
656 if wire.Strict(e.Data, &sa) == nil {
657 c.StepActivity[sa.StepID] = append(c.StepActivity[sa.StepID], sa)
658 applied = true
659 }
660 } else if json.Unmarshal(e.Data, &a) == nil {
661 if _, ok := c.FirstActivity[a.TurnID]; !ok {
662 c.FirstActivity[a.TurnID] = time.Now()
663 }
664 c.Activity[a.TurnID] = append(c.Activity[a.TurnID], a)
665 applied = true
666 }
667 case wire.EventCoordinator:
668 var k wire.Coordinator
669 if json.Unmarshal(e.Data, &k) == nil && k.Revision > c.Coordinator.Revision {
670 c.Coordinator = k
671 applied = true
672 }
673 case wire.EventRunner:
674 var r wire.Runner
675 if json.Unmarshal(e.Data, &r) == nil {
676 // Every runner has its own events; Runner stays the primary.
677 if old, ok := c.Runners[r.ID]; !ok || r.Revision > old.Revision {
678 c.Runners[r.ID] = r
679 applied = true
680 }
681 if r.Role != wire.RoleWorker && r.Revision > c.Runner.Revision {
682 c.Runner = r
683 }
684 }
685 }
686 if applied {
687 c.Applied++
688 c.signal()
689 }
690 return applied
691}
692
693// Follow applies a stream's events until it ends.
694func (c *Conversation) Follow(s *Stream) {
695 for e := range s.Events {
696 c.Apply(e)
697 }
698}
699
700// Wait blocks until cond holds or the timeout passes.
701func (c *Conversation) Wait(timeout time.Duration, cond func(*Conversation) bool) bool {
702 deadline := time.After(timeout)
703 for {
704 c.mu.Lock()
705 ok := cond(c)
706 changed := c.changed
707 c.mu.Unlock()
708 if ok {
709 return true
710 }
711 select {
712 case <-changed:
713 case <-deadline:
714 return false
715 }
716 }
717}
718
719// Replies returns coordinator messages in order. Call inside Wait or after.
720func (c *Conversation) Replies() []wire.Message {
721 var out []wire.Message
722 for _, id := range c.Order {
723 if m := c.Messages[id]; m.Role == wire.RoleCoordinator {
724 out = append(out, m)
725 }
726 }
727 return out
728}
729
730// Locked runs fn with the conversation locked.
731func (c *Conversation) Locked(fn func(*Conversation)) {
732 c.mu.Lock()
733 defer c.mu.Unlock()
734 fn(c)
735}
736
737// Housekeeping is GET /api/v1/housekeeping: the person's tidying loop.
738func (c *Client) Housekeeping(ctx context.Context) (out wire.Housekeeping, err error) {
739 return out, c.do(ctx, "GET", "/api/v1/housekeeping", nil, &out)
740}
741
742// SetHousekeeping is Pause and Resume.
743func (c *Client) SetHousekeeping(ctx context.Context, paused bool, revision int64) (out wire.Housekeeping, err error) {
744 return out, c.do(ctx, "PUT", "/api/v1/housekeeping", wire.SetHousekeeping{Paused: paused, Revision: revision}, &out)
745}
746
747// SetDetector switches one detector on or off for the person.
748func (c *Client) SetDetector(ctx context.Context, id string, enabled bool, revision int64) (out wire.Housekeeping, err error) {
749 return out, c.do(ctx, "PUT", "/api/v1/housekeeping/detectors/"+id, wire.SetDetector{Enabled: enabled, Revision: revision}, &out)
750}
751
752// HousekeepingActions pages the person's actions, newest first.
753func (c *Client) HousekeepingActions(ctx context.Context, before string, limit int) (out wire.HousekeepingActions, err error) {
754 q := "?limit=" + strconv.Itoa(limit)
755 if before != "" {
756 q += "&before=" + url.QueryEscape(before)
757 }
758 return out, c.do(ctx, "GET", "/api/v1/housekeeping/actions"+q, nil, &out)
759}
760
761// UndoAction is Undo on a housekeeping action.
762func (c *Client) UndoAction(ctx context.Context, id string) (out wire.HousekeepingAction, err error) {
763 return out, c.do(ctx, "POST", "/api/v1/housekeeping/actions/"+id+"/undo", nil, &out)
764}
765
766// SetQuiet sets the person's quiet hours, keeping Pause as it is.
767func (c *Client) SetQuiet(ctx context.Context, paused bool, from, until int, revision int64) (out wire.Housekeeping, err error) {
768 return out, c.do(ctx, "PUT", "/api/v1/housekeeping", wire.SetHousekeeping{Paused: paused, Quiet: &wire.QuietHours{From: from, Until: until}, Revision: revision}, &out)
769}
770