package web import ( "bufio" "context" "encoding/json" "errors" "io" "net/http" "strconv" "strings" "time" "unicode" "unicode/utf8" "github.com/go-chi/chi/v5" "amadan.net/oficina/base/internal/equipo" "amadan.net/oficina/base/internal/store" ) // maxAskForm bounds a chat form; Equipo takes 16 KiB of message text. const ( maxAskForm = 64 << 10 maxAskText = 16 << 10 ) // wantsJSON: the panel's script asks for JSON; a plain form gets a 303. func wantsJSON(r *http.Request) bool { return strings.Contains(r.Header.Get("Accept"), "application/json") } // askBearer is the member's bearer for a relayed write of a form, read // first (at most maxAskForm). Without one it answers for the caller: the // panel hears the state, a form goes to /ask. func (a *app) askBearer(w http.ResponseWriter, r *http.Request) (askConn, bool) { r.Body = http.MaxBytesReader(w, r.Body, maxAskForm) if err := r.ParseForm(); err != nil { http.Error(w, "bad request", http.StatusBadRequest) return askConn{}, false } return a.askState(w, r) } // askConn is a member's live connection for one relayed write. type askConn struct { me store.Member device, token string } // askDone finishes a relayed write. A 401 from Equipo means the member must // reconnect: Base answers 409 reconnect, never 401, which is only ever // 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 // runner that can answer (norunner, oldrunner), and what they wrote stays // unsent; any other 409 (a card already answered, a turn already ended) is // stale, and the conversation as it is now says so; anything else is a // problem to try again. func (a *app) askDone(w http.ResponseWriter, r *http.Request, c askConn, err error, out any) { var e *equipo.Error status, state := http.StatusOK, askReady switch { case errors.Is(err, equipo.ErrUnauthenticated): a.askLost(r.Context(), c.me, c.device) status, state = http.StatusConflict, askReconnect case errors.Is(err, equipo.ErrNoRunner): status, state = http.StatusConflict, askNoRunner case errors.Is(err, equipo.ErrRunnerTooOld): status, state = http.StatusConflict, askRunnerTooOld case errors.As(err, &e) && e.Status == http.StatusConflict: status = http.StatusConflict case err != nil: a.logger.Warn("ask: relay", "err", err) status, state = http.StatusBadGateway, askUnavailable } if !wantsJSON(r) && (state == askNoRunner || state == askRunnerTooOld) { a.askRunnerPage(w, r, c, state) return } if !wantsJSON(r) { target := "/ask" if status == http.StatusBadGateway { target += "?problem=1" } http.Redirect(w, r, target, http.StatusSeeOther) return } if err != nil { writeJSON(w, status, map[string]string{"state": state}) return } writeJSON(w, status, out) } // askKey is the key the form carries, made when the page was drawn (or by // the panel's script, kept until the outcome is known), so a form sent // twice is one request to Equipo; a missing or unusable one gets a fresh // key. func askKey(k string) string { if k == "" || len(k) > 128 || !utf8.ValidString(k) || strings.HasPrefix(k, "reply:") || strings.HasPrefix(k, "card:") || strings.HasPrefix(k, "handoff:") { return equipo.NewKey() } return k } // askSend is POST /ask/messages: text and, from the panel's script, up to // five attachments (uploaded first, their ids in order). Text may be // empty when files come. Base checks the text as Equipo does (UTF-8, no // NUL, at most maxAskText) and answers 422 {"state":"ready"} itself, so // Equipo's 422 on a send with files can only be about the files: 422 // {"state":"ready","files":"stale"} (one expired, or already sent). A // runner that can't take files (409 attachments_unavailable, or // runner_too_old) is 409 {"state":"ready","files":"unavailable"}: Ask // stays ready, and the words can go alone. Words alone keep askDone's // answers. func (a *app) askSend(w http.ResponseWriter, r *http.Request) { c, ok := a.askBearer(w, r) if !ok { return } text := strings.TrimSpace(r.PostFormValue("text")) files := r.PostForm["attachments"] valid := len(files) <= equipo.MaxFiles && (text != "" || len(files) > 0) && len(text) <= maxAskText && utf8.ValidString(text) && !strings.ContainsRune(text, 0) seen := map[string]bool{} for _, id := range files { valid = valid && equipo.ValidAttachmentID(id) && !seen[id] seen[id] = true } if !valid { if wantsJSON(r) { writeJSON(w, http.StatusUnprocessableEntity, map[string]string{"state": askReady}) } else { http.Redirect(w, r, "/ask", http.StatusSeeOther) } return } sent, err := a.ask.client.Send(r.Context(), c.token, text, askKey(r.PostFormValue("key")), files) sent.Message = sent.Message.Clean() var e *equipo.Error if len(files) > 0 && err != nil && wantsJSON(r) { switch { case errors.Is(err, equipo.ErrAttachmentsUnavailable) || errors.Is(err, equipo.ErrRunnerTooOld): writeJSON(w, http.StatusConflict, map[string]string{"state": askReady, "files": "unavailable"}) return case errors.As(err, &e) && e.Status == http.StatusUnprocessableEntity: writeJSON(w, http.StatusUnprocessableEntity, map[string]string{"state": askReady, "files": "stale"}) return } } a.askDone(w, r, c, err, sent) } // askCancel is POST /ask/turns/{id}/cancel: Stop. func (a *app) askCancel(w http.ResponseWriter, r *http.Request) { c, ok := a.askBearer(w, r) if !ok { return } err := a.ask.client.Cancel(r.Context(), c.token, chi.URLParam(r, "id"), askKey(r.PostFormValue("key"))) a.askDone(w, r, c, err, map[string]string{"state": askReady}) } // askAnswer is POST /ask/cards/{id}/answer: one of a card's buttons, // relayed as its option's value. The answer is the card, and the message // and turn the answer started, if any: an outcome card's answer starts // none (Equipo sends an empty message and a zero turn), so both are null // and the panel waits for nothing. func (a *app) askAnswer(w http.ResponseWriter, r *http.Request) { c, ok := a.askBearer(w, r) if !ok { return } rev, _ := strconv.ParseInt(r.PostFormValue("revision"), 10, 64) in, err := a.ask.client.Answer(r.Context(), c.token, chi.URLParam(r, "id"), r.PostFormValue("choice"), rev, askKey(r.PostFormValue("key"))) var out struct { Card equipo.Card `json:"card"` Message *equipo.Message `json:"message"` Turn *equipo.Turn `json:"turn"` } out.Card, _ = in.Card.CleanAt(a.cfg.Origin) if in.Message.ID != "" { m := in.Message.Clean() out.Message = &m } if in.Turn.ID != "" { out.Turn = &in.Turn } a.askDone(w, r, c, err, out) } // askCarryOn is POST /ask/cards/{id}/carry_on: a paused job's "Carry on // now", at the revision the person saw, relayed as card answers are. The // answer is {"card": the job card as it is now}, or {"card": null} when // Base does not draw the card Equipo gave (the clients then read the // conversation afresh). A 409 (card_stale, not_paused, // carry_on_unavailable) is stale: the conversation is read afresh, and // nothing is resent. So is a 404, which is final: Equipo has no such job // card for the person. func (a *app) askCarryOn(w http.ResponseWriter, r *http.Request) { c, ok := a.askBearer(w, r) if !ok { return } rev, _ := strconv.ParseInt(r.PostFormValue("revision"), 10, 64) in, err := a.ask.client.CarryOnNow(r.Context(), c.token, chi.URLParam(r, "id"), rev, askKey(r.PostFormValue("key"))) if e := (*equipo.Error)(nil); errors.As(err, &e) && e.Status == http.StatusNotFound { err = &equipo.Error{Status: http.StatusConflict, Code: e.Code} } var out struct { Card *equipo.Card `json:"card"` } if card, ok := in.CleanAt(a.cfg.Origin); ok { out.Card = &card } a.askDone(w, r, c, err, out) } // Stream bounds. Equipo pings every 20 seconds, so a minute of silence // means it is gone; a stream lives at most streamLife, after which the // browser reconnects with its cursor; one event is at most maxEventBytes // and maxEventLines; a write to a browser that has stopped reading gives // up after writeWindow. const ( streamIdle = 45 * time.Second streamLife = 10 * time.Minute writeWindow = 30 * time.Second maxEventBytes = 512 << 10 maxEventLines = 64 ) // askEvents is GET /ask/events: Equipo's event stream for the member, // relayed with their bearer. The cursor is Last-Event-ID when the browser // reconnects (it moves on with every event), else ?after=. func (a *app) askEvents(w http.ResponseWriter, r *http.Request) { me, _ := CurrentMember(r) after := r.Header.Get("Last-Event-ID") if after == "" { after = r.URL.Query().Get("after") } if _, err := strconv.ParseUint(after, 10, 63); after != "" && err != nil { http.Error(w, "bad request", http.StatusBadRequest) return } l, sec, state, err := a.askLink(r.Context(), me) if err != nil { a.logger.Error("ask: link", "err", err) http.Error(w, "unavailable", http.StatusServiceUnavailable) return } if state != askReady { endStream(w, homeState(state)) return } ctx, cancel := context.WithTimeout(r.Context(), streamLife) defer cancel() seen := a.askTurns(ctx, sec.Token) res, err := a.ask.client.Events(ctx, sec.Token, after) if errors.Is(err, equipo.ErrUnauthenticated) { a.askLost(r.Context(), me, l.DeviceID) endStream(w, askReconnect) return } if err != nil { a.logger.Warn("ask: events", "err", err) http.Error(w, "unavailable", http.StatusBadGateway) return } defer res.Body.Close() streamHeaders(w) down := downstream{w, http.NewResponseController(w)} if down.send("retry: 3000\n\n") != nil { return } seen.base, seen.plain = a.cfg.Origin, plainLookups(r) relay(down, res.Body, streamIdle, cancel, seen) } // snapshotForTurns bounds the snapshot a stream reads as it starts. const snapshotForTurns = 3 * time.Second // askTurns is what a stream knows of the turns as it starts, read from // the conversation's snapshot (seedTurns), so a glance can pass for a turn // that started before the stream did. Without an answer it knows none, and // passes no glance until a turn's events start one. func (a *app) askTurns(ctx context.Context, token string) turnsSeen { ctx, cancel := context.WithTimeout(ctx, snapshotForTurns) defer cancel() s, err := a.ask.client.Snapshot(ctx, token) if err != nil { return turnsSeen{} } return seedTurns(s) } // downstream is the browser's end of a stream. type downstream struct { w io.Writer rc *http.ResponseController } // send writes s and flushes it, giving up after writeWindow. func (d downstream) send(s string) error { _ = d.rc.SetWriteDeadline(time.Now().Add(writeWindow)) if _, err := io.WriteString(d.w, s); err != nil { return err } return d.rc.Flush() } func streamHeaders(w http.ResponseWriter) { w.Header().Set("Content-Type", "text/event-stream") w.Header().Set("Cache-Control", "no-store") w.Header().Set("X-Accel-Buffering", "no") w.WriteHeader(http.StatusOK) } // endStream answers a stream that cannot start with one "state" event // saying why, so the panel shows it instead of retrying. func endStream(w http.ResponseWriter, state string) { streamHeaders(w) raw, _ := json.Marshal(map[string]string{"state": state}) _ = downstream{w, http.NewResponseController(w)}.send("event: state\ndata: " + string(raw) + "\n\n") } // relay reads Equipo's events from upstream and writes the conversation's // to d as frames of its own (see frame; seen is what it knows of the // turns as it starts); upstream's lines never reach // the browser. It parses lines as a browser does (LF, CRLF or a bare CR // ends one), and ends the stream at an event over the size bounds, at // idle without a byte from upstream (calling stop, which must make the // pending read fail), or when the browser stops reading. func relay(d downstream, upstream io.Reader, idle time.Duration, stop func(), seen turnsSeen) { quiet := time.AfterFunc(idle, stop) defer quiet.Stop() in := bufio.NewReaderSize(upstream, 32<<10) var ev sseEvent size, lines := 0, 0 for { line, err := readLine(in, maxEventBytes-size) if err != nil { return } quiet.Reset(idle) size, lines = size+len(line)+1, lines+1 if lines > maxEventLines { return } if len(line) > 0 { ev.field(line) continue } out := ev.frame(&seen) ev, size, lines = sseEvent{}, 0, 0 if out != "" && d.send(out) != nil { return } } } // readLine reads one line of at most max bytes, ended by LF, CRLF or CR. func readLine(in *bufio.Reader, max int) ([]byte, error) { var line []byte for { b, err := in.ReadByte() if err != nil { return nil, err } switch b { case '\n': return line, nil case '\r': if next, err := in.Peek(1); err == nil && next[0] == '\n' { _, _ = in.ReadByte() } return line, nil } if len(line) >= max { return nil, errors.New("ask: event too large") } line = append(line, b) } } // sseEvent is one upstream event's fields. type sseEvent struct { typ, id string data []string } func (e *sseEvent) field(line []byte) { if line[0] == ':' { return } name, value, _ := strings.Cut(string(line), ":") value = strings.TrimPrefix(value, " ") switch name { case "event": e.typ = value case "id": e.id = value case "data": e.data = append(e.data, value) } } // frame is what the browser gets for the event: a ping as a comment, a // conversation event as a fresh frame with a numeric id and its data // projected (project, or seen.glance for a glance), and nothing for // anything else. A glance is live only: it comes without an id, and goes // without one, so the browser's cursor stays where the last conversation // event put it. seen hears every turn and delta that passes. func (e sseEvent) frame(seen *turnsSeen) string { if e.typ == "ping" { return ": ping\n\n" } live := e.typ == "glance" && e.id == "" if _, err := strconv.ParseUint(e.id, 10, 63); (err != nil && !live) || len(e.data) == 0 { return "" } var env struct { ID string `json:"id"` TurnID string `json:"turn_id"` Data json.RawMessage `json:"data"` } if err := json.Unmarshal([]byte(strings.Join(e.data, "\n")), &env); err != nil { return "" } var data any ok := false if e.typ == "glance" { data, ok = seen.glance(env.ID, env.Data) } else { data, ok = project(e.typ, env.Data, seen.base) } if m, msg := data.(equipo.Message); msg && seen.plain { data = m.PlainLookups() } if c, card := data.(equipo.Card); card { // A connect card waits for the reply of the turn that raised it. data = c.WithTurn(env.TurnID) } if !ok { return "" } seen.note(data) raw, err := json.Marshal(struct { Type string `json:"type"` Data any `json:"data"` }{e.typ, data}) if err != nil { return "" } if live { return "event: " + e.typ + "\ndata: " + string(raw) + "\n\n" } return "id: " + e.id + "\nevent: " + e.typ + "\ndata: " + string(raw) + "\n\n" } // project reduces an event's data to the conversation's shape, the one // /ask/state uses; ok is false for every other kind of event, and for // cards of a kind Base does not draw, or jobs in a state it does not know // (equipo.Card.Clean). func project(typ string, raw json.RawMessage, base string) (any, bool) { switch typ { case "message": var m equipo.Message if json.Unmarshal(raw, &m) != nil || m.ID == "" { return nil, false } return m.Clean(), true case "turn": var t equipo.Turn return t, json.Unmarshal(raw, &t) == nil && t.ID != "" case "card": var c equipo.Card if json.Unmarshal(raw, &c) != nil || c.ID == "" { return nil, false } return c.CleanAt(base) case "delta": var d delta return d, json.Unmarshal(raw, &d) == nil && d.TurnID != "" case "activity": var a struct { TurnID string `json:"turn_id"` Label string `json:"label"` } return a, json.Unmarshal(raw, &a) == nil && a.TurnID != "" } return nil, false } // delta is a few of the reply's words, streamed: Offset counts the UTF-8 // bytes before them. type delta struct { TurnID string `json:"turn_id"` Offset int64 `json:"offset"` Text string `json:"text"` } // glance is Equipo's one line on the turn in flight, said before its first // words (or never): Base shows it in the thinking bubble and keeps it // nowhere. type glance struct { TurnID string `json:"turn_id"` Text string `json:"text"` } // maxGlance bounds a glance, in characters; Equipo keeps to 60. const maxGlance = 60 // turnsSeen is what one stream knows of its turns, so a glance passes // only for the person's turn in flight before its first words: live holds // those turns, past every turn no glance may be for (a team_update turn, // an ended one, one whose words have started), which stays there even if // an older event replayed after the cursor has it running. A stream starts // knowing the turns in the conversation's snapshot (seedTurns), and passes // no glance for a turn it does not know. type turnsSeen struct { live, past map[string]bool // base is Base's origin, for Card.CleanAt; plain says the client // can't draw lookups, so a message's are folded into its text. base string plain bool } // seedTurns is what the snapshot s says of its turns. func seedTurns(s equipo.Snapshot) turnsSeen { var seen turnsSeen for _, t := range s.Turns { seen.note(t) } return seen } func (s *turnsSeen) note(data any) { switch v := data.(type) { case equipo.Turn: if v.Kind == equipo.TurnTeamUpdate || !equipo.InFlight(v.State) { s.over(v.ID) } else if !s.past[v.ID] { if s.live == nil { s.live = map[string]bool{} } s.live[v.ID] = true } case delta: s.over(v.TurnID) } } func (s *turnsSeen) over(id string) { if s.past == nil { s.past = map[string]bool{} } s.past[id] = true delete(s.live, id) } // glance projects a glance event for turn id (the event's own id, which // is the turn's), cleaned (cleanGlance), if it is for a turn in flight. func (s *turnsSeen) glance(id string, raw json.RawMessage) (any, bool) { var g glance if json.Unmarshal(raw, &g) != nil || g.TurnID == "" || (id != "" && id != g.TurnID) || !s.live[g.TurnID] { return nil, false } g.Text = cleanGlance(g.Text) return g, g.Text != "" } // cleanGlance makes text one line of plain text: no control or format // characters, no Markdown emphasis or code marks, runs of space as one, // trimmed, and at most maxGlance characters, cut at a word where it can be. func cleanGlance(text string) string { text = strings.Map(func(r rune) rune { switch { case r == '*' || r == '`': return -1 case unicode.IsSpace(r): return ' ' case unicode.In(r, unicode.Cc, unicode.Cf): return -1 } return r }, strings.ToValidUTF8(text, "")) r := []rune(strings.Join(strings.Fields(text), " ")) if len(r) <= maxGlance { return string(r) } cut := r[:maxGlance] if r[maxGlance] != ' ' { for i := len(cut) - 1; i > 0; i-- { if cut[i] == ' ' { cut = cut[:i] break } } } return strings.TrimRight(string(cut), " ,;:") }