oficina / base Public

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

Plain git — no account needed to clone.

Download

Download this file

1package web
2
3import (
4 "bufio"
5 "context"
6 "encoding/json"
7 "errors"
8 "io"
9 "net/http"
10 "strconv"
11 "strings"
12 "time"
13 "unicode"
14 "unicode/utf8"
15
16 "github.com/go-chi/chi/v5"
17
18 "amadan.net/oficina/base/internal/equipo"
19 "amadan.net/oficina/base/internal/store"
20)
21
22// maxAskForm bounds a chat form; Equipo takes 16 KiB of message text.
23const (
24 maxAskForm = 64 << 10
25 maxAskText = 16 << 10
26)
27
28// wantsJSON: the panel's script asks for JSON; a plain form gets a 303.
29func wantsJSON(r *http.Request) bool {
30 return strings.Contains(r.Header.Get("Accept"), "application/json")
31}
32
33// askBearer is the member's bearer for a relayed write of a form, read
34// first (at most maxAskForm). Without one it answers for the caller: the
35// panel hears the state, a form goes to /ask.
36func (a *app) askBearer(w http.ResponseWriter, r *http.Request) (askConn, bool) {
37 r.Body = http.MaxBytesReader(w, r.Body, maxAskForm)
38 if err := r.ParseForm(); err != nil {
39 http.Error(w, "bad request", http.StatusBadRequest)
40 return askConn{}, false
41 }
42 return a.askState(w, r)
43}
44
45// askConn is a member's live connection for one relayed write.
46type askConn struct {
47 me store.Member
48 device, token string
49}
50
51// askDone finishes a relayed write. A 401 from Equipo means the member must
52// reconnect: Base answers 409 reconnect, never 401, which is only ever
53// Base's own session ending (the native app signs in again on one); a 409 no_runner or runner_too_old means the person has no
54// runner that can answer (norunner, oldrunner), and what they wrote stays
55// unsent; any other 409 (a card already answered, a turn already ended) is
56// stale, and the conversation as it is now says so; anything else is a
57// problem to try again.
58func (a *app) askDone(w http.ResponseWriter, r *http.Request, c askConn, err error, out any) {
59 var e *equipo.Error
60 status, state := http.StatusOK, askReady
61 switch {
62 case errors.Is(err, equipo.ErrUnauthenticated):
63 a.askLost(r.Context(), c.me, c.device)
64 status, state = http.StatusConflict, askReconnect
65 case errors.Is(err, equipo.ErrNoRunner):
66 status, state = http.StatusConflict, askNoRunner
67 case errors.Is(err, equipo.ErrRunnerTooOld):
68 status, state = http.StatusConflict, askRunnerTooOld
69 case errors.As(err, &e) && e.Status == http.StatusConflict:
70 status = http.StatusConflict
71 case err != nil:
72 a.logger.Warn("ask: relay", "err", err)
73 status, state = http.StatusBadGateway, askUnavailable
74 }
75 if !wantsJSON(r) && (state == askNoRunner || state == askRunnerTooOld) {
76 a.askRunnerPage(w, r, c, state)
77 return
78 }
79 if !wantsJSON(r) {
80 target := "/ask"
81 if status == http.StatusBadGateway {
82 target += "?problem=1"
83 }
84 http.Redirect(w, r, target, http.StatusSeeOther)
85 return
86 }
87 if err != nil {
88 writeJSON(w, status, map[string]string{"state": state})
89 return
90 }
91 writeJSON(w, status, out)
92}
93
94// askKey is the key the form carries, made when the page was drawn (or by
95// the panel's script, kept until the outcome is known), so a form sent
96// twice is one request to Equipo; a missing or unusable one gets a fresh
97// key.
98func askKey(k string) string {
99 if k == "" || len(k) > 128 || !utf8.ValidString(k) || strings.HasPrefix(k, "reply:") || strings.HasPrefix(k, "card:") || strings.HasPrefix(k, "handoff:") {
100 return equipo.NewKey()
101 }
102 return k
103}
104
105// askSend is POST /ask/messages: text and, from the panel's script, up to
106// five attachments (uploaded first, their ids in order). Text may be
107// empty when files come. Base checks the text as Equipo does (UTF-8, no
108// NUL, at most maxAskText) and answers 422 {"state":"ready"} itself, so
109// Equipo's 422 on a send with files can only be about the files: 422
110// {"state":"ready","files":"stale"} (one expired, or already sent). A
111// runner that can't take files (409 attachments_unavailable, or
112// runner_too_old) is 409 {"state":"ready","files":"unavailable"}: Ask
113// stays ready, and the words can go alone. Words alone keep askDone's
114// answers.
115func (a *app) askSend(w http.ResponseWriter, r *http.Request) {
116 c, ok := a.askBearer(w, r)
117 if !ok {
118 return
119 }
120 text := strings.TrimSpace(r.PostFormValue("text"))
121 files := r.PostForm["attachments"]
122 valid := len(files) <= equipo.MaxFiles && (text != "" || len(files) > 0) && len(text) <= maxAskText &&
123 utf8.ValidString(text) && !strings.ContainsRune(text, 0)
124 seen := map[string]bool{}
125 for _, id := range files {
126 valid = valid && equipo.ValidAttachmentID(id) && !seen[id]
127 seen[id] = true
128 }
129 if !valid {
130 if wantsJSON(r) {
131 writeJSON(w, http.StatusUnprocessableEntity, map[string]string{"state": askReady})
132 } else {
133 http.Redirect(w, r, "/ask", http.StatusSeeOther)
134 }
135 return
136 }
137 sent, err := a.ask.client.Send(r.Context(), c.token, text, askKey(r.PostFormValue("key")), files)
138 sent.Message = sent.Message.Clean()
139 var e *equipo.Error
140 if len(files) > 0 && err != nil && wantsJSON(r) {
141 switch {
142 case errors.Is(err, equipo.ErrAttachmentsUnavailable) || errors.Is(err, equipo.ErrRunnerTooOld):
143 writeJSON(w, http.StatusConflict, map[string]string{"state": askReady, "files": "unavailable"})
144 return
145 case errors.As(err, &e) && e.Status == http.StatusUnprocessableEntity:
146 writeJSON(w, http.StatusUnprocessableEntity, map[string]string{"state": askReady, "files": "stale"})
147 return
148 }
149 }
150 a.askDone(w, r, c, err, sent)
151}
152
153// askCancel is POST /ask/turns/{id}/cancel: Stop.
154func (a *app) askCancel(w http.ResponseWriter, r *http.Request) {
155 c, ok := a.askBearer(w, r)
156 if !ok {
157 return
158 }
159 err := a.ask.client.Cancel(r.Context(), c.token, chi.URLParam(r, "id"), askKey(r.PostFormValue("key")))
160 a.askDone(w, r, c, err, map[string]string{"state": askReady})
161}
162
163// askAnswer is POST /ask/cards/{id}/answer: one of a card's buttons,
164// relayed as its option's value. The answer is the card, and the message
165// and turn the answer started, if any: an outcome card's answer starts
166// none (Equipo sends an empty message and a zero turn), so both are null
167// and the panel waits for nothing.
168func (a *app) askAnswer(w http.ResponseWriter, r *http.Request) {
169 c, ok := a.askBearer(w, r)
170 if !ok {
171 return
172 }
173 rev, _ := strconv.ParseInt(r.PostFormValue("revision"), 10, 64)
174 in, err := a.ask.client.Answer(r.Context(), c.token, chi.URLParam(r, "id"), r.PostFormValue("choice"), rev, askKey(r.PostFormValue("key")))
175 var out struct {
176 Card equipo.Card `json:"card"`
177 Message *equipo.Message `json:"message"`
178 Turn *equipo.Turn `json:"turn"`
179 }
180 out.Card, _ = in.Card.CleanAt(a.cfg.Origin)
181 if in.Message.ID != "" {
182 m := in.Message.Clean()
183 out.Message = &m
184 }
185 if in.Turn.ID != "" {
186 out.Turn = &in.Turn
187 }
188 a.askDone(w, r, c, err, out)
189}
190
191// askCarryOn is POST /ask/cards/{id}/carry_on: a paused job's "Carry on
192// now", at the revision the person saw, relayed as card answers are. The
193// answer is {"card": the job card as it is now}, or {"card": null} when
194// Base does not draw the card Equipo gave (the clients then read the
195// conversation afresh). A 409 (card_stale, not_paused,
196// carry_on_unavailable) is stale: the conversation is read afresh, and
197// nothing is resent. So is a 404, which is final: Equipo has no such job
198// card for the person.
199func (a *app) askCarryOn(w http.ResponseWriter, r *http.Request) {
200 c, ok := a.askBearer(w, r)
201 if !ok {
202 return
203 }
204 rev, _ := strconv.ParseInt(r.PostFormValue("revision"), 10, 64)
205 in, err := a.ask.client.CarryOnNow(r.Context(), c.token, chi.URLParam(r, "id"), rev, askKey(r.PostFormValue("key")))
206 if e := (*equipo.Error)(nil); errors.As(err, &e) && e.Status == http.StatusNotFound {
207 err = &equipo.Error{Status: http.StatusConflict, Code: e.Code}
208 }
209 var out struct {
210 Card *equipo.Card `json:"card"`
211 }
212 if card, ok := in.CleanAt(a.cfg.Origin); ok {
213 out.Card = &card
214 }
215 a.askDone(w, r, c, err, out)
216}
217
218// Stream bounds. Equipo pings every 20 seconds, so a minute of silence
219// means it is gone; a stream lives at most streamLife, after which the
220// browser reconnects with its cursor; one event is at most maxEventBytes
221// and maxEventLines; a write to a browser that has stopped reading gives
222// up after writeWindow.
223const (
224 streamIdle = 45 * time.Second
225 streamLife = 10 * time.Minute
226 writeWindow = 30 * time.Second
227 maxEventBytes = 512 << 10
228 maxEventLines = 64
229)
230
231// askEvents is GET /ask/events: Equipo's event stream for the member,
232// relayed with their bearer. The cursor is Last-Event-ID when the browser
233// reconnects (it moves on with every event), else ?after=.
234func (a *app) askEvents(w http.ResponseWriter, r *http.Request) {
235 me, _ := CurrentMember(r)
236 after := r.Header.Get("Last-Event-ID")
237 if after == "" {
238 after = r.URL.Query().Get("after")
239 }
240 if _, err := strconv.ParseUint(after, 10, 63); after != "" && err != nil {
241 http.Error(w, "bad request", http.StatusBadRequest)
242 return
243 }
244 l, sec, state, err := a.askLink(r.Context(), me)
245 if err != nil {
246 a.logger.Error("ask: link", "err", err)
247 http.Error(w, "unavailable", http.StatusServiceUnavailable)
248 return
249 }
250 if state != askReady {
251 endStream(w, homeState(state))
252 return
253 }
254 ctx, cancel := context.WithTimeout(r.Context(), streamLife)
255 defer cancel()
256 seen := a.askTurns(ctx, sec.Token)
257 res, err := a.ask.client.Events(ctx, sec.Token, after)
258 if errors.Is(err, equipo.ErrUnauthenticated) {
259 a.askLost(r.Context(), me, l.DeviceID)
260 endStream(w, askReconnect)
261 return
262 }
263 if err != nil {
264 a.logger.Warn("ask: events", "err", err)
265 http.Error(w, "unavailable", http.StatusBadGateway)
266 return
267 }
268 defer res.Body.Close()
269 streamHeaders(w)
270 down := downstream{w, http.NewResponseController(w)}
271 if down.send("retry: 3000\n\n") != nil {
272 return
273 }
274 seen.base, seen.plain = a.cfg.Origin, plainLookups(r)
275 relay(down, res.Body, streamIdle, cancel, seen)
276}
277
278// snapshotForTurns bounds the snapshot a stream reads as it starts.
279const snapshotForTurns = 3 * time.Second
280
281// askTurns is what a stream knows of the turns as it starts, read from
282// the conversation's snapshot (seedTurns), so a glance can pass for a turn
283// that started before the stream did. Without an answer it knows none, and
284// passes no glance until a turn's events start one.
285func (a *app) askTurns(ctx context.Context, token string) turnsSeen {
286 ctx, cancel := context.WithTimeout(ctx, snapshotForTurns)
287 defer cancel()
288 s, err := a.ask.client.Snapshot(ctx, token)
289 if err != nil {
290 return turnsSeen{}
291 }
292 return seedTurns(s)
293}
294
295// downstream is the browser's end of a stream.
296type downstream struct {
297 w io.Writer
298 rc *http.ResponseController
299}
300
301// send writes s and flushes it, giving up after writeWindow.
302func (d downstream) send(s string) error {
303 _ = d.rc.SetWriteDeadline(time.Now().Add(writeWindow))
304 if _, err := io.WriteString(d.w, s); err != nil {
305 return err
306 }
307 return d.rc.Flush()
308}
309
310func streamHeaders(w http.ResponseWriter) {
311 w.Header().Set("Content-Type", "text/event-stream")
312 w.Header().Set("Cache-Control", "no-store")
313 w.Header().Set("X-Accel-Buffering", "no")
314 w.WriteHeader(http.StatusOK)
315}
316
317// endStream answers a stream that cannot start with one "state" event
318// saying why, so the panel shows it instead of retrying.
319func endStream(w http.ResponseWriter, state string) {
320 streamHeaders(w)
321 raw, _ := json.Marshal(map[string]string{"state": state})
322 _ = downstream{w, http.NewResponseController(w)}.send("event: state\ndata: " + string(raw) + "\n\n")
323}
324
325// relay reads Equipo's events from upstream and writes the conversation's
326// to d as frames of its own (see frame; seen is what it knows of the
327// turns as it starts); upstream's lines never reach
328// the browser. It parses lines as a browser does (LF, CRLF or a bare CR
329// ends one), and ends the stream at an event over the size bounds, at
330// idle without a byte from upstream (calling stop, which must make the
331// pending read fail), or when the browser stops reading.
332func relay(d downstream, upstream io.Reader, idle time.Duration, stop func(), seen turnsSeen) {
333 quiet := time.AfterFunc(idle, stop)
334 defer quiet.Stop()
335 in := bufio.NewReaderSize(upstream, 32<<10)
336 var ev sseEvent
337 size, lines := 0, 0
338 for {
339 line, err := readLine(in, maxEventBytes-size)
340 if err != nil {
341 return
342 }
343 quiet.Reset(idle)
344 size, lines = size+len(line)+1, lines+1
345 if lines > maxEventLines {
346 return
347 }
348 if len(line) > 0 {
349 ev.field(line)
350 continue
351 }
352 out := ev.frame(&seen)
353 ev, size, lines = sseEvent{}, 0, 0
354 if out != "" && d.send(out) != nil {
355 return
356 }
357 }
358}
359
360// readLine reads one line of at most max bytes, ended by LF, CRLF or CR.
361func readLine(in *bufio.Reader, max int) ([]byte, error) {
362 var line []byte
363 for {
364 b, err := in.ReadByte()
365 if err != nil {
366 return nil, err
367 }
368 switch b {
369 case '\n':
370 return line, nil
371 case '\r':
372 if next, err := in.Peek(1); err == nil && next[0] == '\n' {
373 _, _ = in.ReadByte()
374 }
375 return line, nil
376 }
377 if len(line) >= max {
378 return nil, errors.New("ask: event too large")
379 }
380 line = append(line, b)
381 }
382}
383
384// sseEvent is one upstream event's fields.
385type sseEvent struct {
386 typ, id string
387 data []string
388}
389
390func (e *sseEvent) field(line []byte) {
391 if line[0] == ':' {
392 return
393 }
394 name, value, _ := strings.Cut(string(line), ":")
395 value = strings.TrimPrefix(value, " ")
396 switch name {
397 case "event":
398 e.typ = value
399 case "id":
400 e.id = value
401 case "data":
402 e.data = append(e.data, value)
403 }
404}
405
406// frame is what the browser gets for the event: a ping as a comment, a
407// conversation event as a fresh frame with a numeric id and its data
408// projected (project, or seen.glance for a glance), and nothing for
409// anything else. A glance is live only: it comes without an id, and goes
410// without one, so the browser's cursor stays where the last conversation
411// event put it. seen hears every turn and delta that passes.
412func (e sseEvent) frame(seen *turnsSeen) string {
413 if e.typ == "ping" {
414 return ": ping\n\n"
415 }
416 live := e.typ == "glance" && e.id == ""
417 if _, err := strconv.ParseUint(e.id, 10, 63); (err != nil && !live) || len(e.data) == 0 {
418 return ""
419 }
420 var env struct {
421 ID string `json:"id"`
422 TurnID string `json:"turn_id"`
423 Data json.RawMessage `json:"data"`
424 }
425 if err := json.Unmarshal([]byte(strings.Join(e.data, "\n")), &env); err != nil {
426 return ""
427 }
428 var data any
429 ok := false
430 if e.typ == "glance" {
431 data, ok = seen.glance(env.ID, env.Data)
432 } else {
433 data, ok = project(e.typ, env.Data, seen.base)
434 }
435 if m, msg := data.(equipo.Message); msg && seen.plain {
436 data = m.PlainLookups()
437 }
438 if c, card := data.(equipo.Card); card {
439 // A connect card waits for the reply of the turn that raised it.
440 data = c.WithTurn(env.TurnID)
441 }
442 if !ok {
443 return ""
444 }
445 seen.note(data)
446 raw, err := json.Marshal(struct {
447 Type string `json:"type"`
448 Data any `json:"data"`
449 }{e.typ, data})
450 if err != nil {
451 return ""
452 }
453 if live {
454 return "event: " + e.typ + "\ndata: " + string(raw) + "\n\n"
455 }
456 return "id: " + e.id + "\nevent: " + e.typ + "\ndata: " + string(raw) + "\n\n"
457}
458
459// project reduces an event's data to the conversation's shape, the one
460// /ask/state uses; ok is false for every other kind of event, and for
461// cards of a kind Base does not draw, or jobs in a state it does not know
462// (equipo.Card.Clean).
463func project(typ string, raw json.RawMessage, base string) (any, bool) {
464 switch typ {
465 case "message":
466 var m equipo.Message
467 if json.Unmarshal(raw, &m) != nil || m.ID == "" {
468 return nil, false
469 }
470 return m.Clean(), true
471 case "turn":
472 var t equipo.Turn
473 return t, json.Unmarshal(raw, &t) == nil && t.ID != ""
474 case "card":
475 var c equipo.Card
476 if json.Unmarshal(raw, &c) != nil || c.ID == "" {
477 return nil, false
478 }
479 return c.CleanAt(base)
480 case "delta":
481 var d delta
482 return d, json.Unmarshal(raw, &d) == nil && d.TurnID != ""
483 case "activity":
484 var a struct {
485 TurnID string `json:"turn_id"`
486 Label string `json:"label"`
487 }
488 return a, json.Unmarshal(raw, &a) == nil && a.TurnID != ""
489 }
490 return nil, false
491}
492
493// delta is a few of the reply's words, streamed: Offset counts the UTF-8
494// bytes before them.
495type delta struct {
496 TurnID string `json:"turn_id"`
497 Offset int64 `json:"offset"`
498 Text string `json:"text"`
499}
500
501// glance is Equipo's one line on the turn in flight, said before its first
502// words (or never): Base shows it in the thinking bubble and keeps it
503// nowhere.
504type glance struct {
505 TurnID string `json:"turn_id"`
506 Text string `json:"text"`
507}
508
509// maxGlance bounds a glance, in characters; Equipo keeps to 60.
510const maxGlance = 60
511
512// turnsSeen is what one stream knows of its turns, so a glance passes
513// only for the person's turn in flight before its first words: live holds
514// those turns, past every turn no glance may be for (a team_update turn,
515// an ended one, one whose words have started), which stays there even if
516// an older event replayed after the cursor has it running. A stream starts
517// knowing the turns in the conversation's snapshot (seedTurns), and passes
518// no glance for a turn it does not know.
519type turnsSeen struct {
520 live, past map[string]bool
521 // base is Base's origin, for Card.CleanAt; plain says the client
522 // can't draw lookups, so a message's are folded into its text.
523 base string
524 plain bool
525}
526
527// seedTurns is what the snapshot s says of its turns.
528func seedTurns(s equipo.Snapshot) turnsSeen {
529 var seen turnsSeen
530 for _, t := range s.Turns {
531 seen.note(t)
532 }
533 return seen
534}
535
536func (s *turnsSeen) note(data any) {
537 switch v := data.(type) {
538 case equipo.Turn:
539 if v.Kind == equipo.TurnTeamUpdate || !equipo.InFlight(v.State) {
540 s.over(v.ID)
541 } else if !s.past[v.ID] {
542 if s.live == nil {
543 s.live = map[string]bool{}
544 }
545 s.live[v.ID] = true
546 }
547 case delta:
548 s.over(v.TurnID)
549 }
550}
551
552func (s *turnsSeen) over(id string) {
553 if s.past == nil {
554 s.past = map[string]bool{}
555 }
556 s.past[id] = true
557 delete(s.live, id)
558}
559
560// glance projects a glance event for turn id (the event's own id, which
561// is the turn's), cleaned (cleanGlance), if it is for a turn in flight.
562func (s *turnsSeen) glance(id string, raw json.RawMessage) (any, bool) {
563 var g glance
564 if json.Unmarshal(raw, &g) != nil || g.TurnID == "" || (id != "" && id != g.TurnID) || !s.live[g.TurnID] {
565 return nil, false
566 }
567 g.Text = cleanGlance(g.Text)
568 return g, g.Text != ""
569}
570
571// cleanGlance makes text one line of plain text: no control or format
572// characters, no Markdown emphasis or code marks, runs of space as one,
573// trimmed, and at most maxGlance characters, cut at a word where it can be.
574func cleanGlance(text string) string {
575 text = strings.Map(func(r rune) rune {
576 switch {
577 case r == '*' || r == '`':
578 return -1
579 case unicode.IsSpace(r):
580 return ' '
581 case unicode.In(r, unicode.Cc, unicode.Cf):
582 return -1
583 }
584 return r
585 }, strings.ToValidUTF8(text, ""))
586 r := []rune(strings.Join(strings.Fields(text), " "))
587 if len(r) <= maxGlance {
588 return string(r)
589 }
590 cut := r[:maxGlance]
591 if r[maxGlance] != ' ' {
592 for i := len(cut) - 1; i > 0; i-- {
593 if cut[i] == ' ' {
594 cut = cut[:i]
595 break
596 }
597 }
598 }
599 return strings.TrimRight(string(cut), " ,;:")
600}
601