| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/rand" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "net/http" |
| 9 | "strings" |
| 10 | |
| 11 | "amadan.net/oficina/equipo/internal/equipo/personapi" |
| 12 | "amadan.net/oficina/equipo/internal/wire" |
| 13 | "github.com/go-chi/chi/v5" |
| 14 | ) |
| 15 | |
| 16 | // MountAssistant adds the Assistant lane's routes under |
| 17 | // /api/v1/assistant: the interface Base calls (spec §6), in the shapes of |
| 18 | // the Coordinator's. Every route takes the person's device bearer and |
| 19 | // nothing else, the event stream included, and reads only the lane; PUT |
| 20 | // host says where the person's Base operations live. |
| 21 | func (h *HTTP) MountAssistant(r chi.Router) { |
| 22 | lane := h.Store.Lane(wire.LaneAssistant) |
| 23 | r.Get("/snapshot", h.assistantBearer(func(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| 24 | h.oficinaCatchUp(r, p) |
| 25 | h.warmAssistant(r, p) |
| 26 | out, err := lane.Snapshot(r.Context(), p.Address) |
| 27 | if err != nil { |
| 28 | h.fail(w, r, err) |
| 29 | return |
| 30 | } |
| 31 | if !knowsPaused(r) { |
| 32 | for i := range out.Cards { |
| 33 | out.Cards[i] = olderJobCard(out.Cards[i]) |
| 34 | } |
| 35 | } |
| 36 | if !drawsLookups(r) { |
| 37 | for i := range out.Messages { |
| 38 | out.Messages[i] = plainLookups(out.Messages[i], h.sourcesLine()) |
| 39 | } |
| 40 | } |
| 41 | writeJSON(w, 200, out) |
| 42 | })) |
| 43 | r.Get("/messages", h.assistantBearer(func(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| 44 | page := lane.Messages |
| 45 | if !drawsLookups(r) { |
| 46 | page = h.plainPage(lane.Messages) |
| 47 | } |
| 48 | h.messagesWith(w, r, p, page) |
| 49 | })) |
| 50 | r.Post("/messages", h.assistantBearer(func(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| 51 | h.turnStartRefresh(r, p) |
| 52 | h.sendWith(w, r, p, lane.Send) |
| 53 | })) |
| 54 | r.Post("/turns/{id}/cancel", h.assistantBearer(func(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| 55 | h.cancelWith(w, r, p, lane.Cancel) |
| 56 | })) |
| 57 | r.Post("/cards/{id}/answer", h.assistantBearer(func(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| 58 | h.turnStartRefresh(r, p) |
| 59 | h.assistantAnswer(w, r, p, lane) |
| 60 | })) |
| 61 | r.Get("/abilities", h.assistantBearer(h.ownAbilitiesRoute)) |
| 62 | r.Post("/abilities/refresh", h.assistantBearer(h.abilitiesHint)) |
| 63 | r.Get("/events", h.assistantBearer(func(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| 64 | h.oficinaCatchUp(r, p) |
| 65 | h.warmAssistant(r, p) |
| 66 | read := lane.Events |
| 67 | if !knowsPaused(r) { |
| 68 | read = olderJobEvents(lane.Events) |
| 69 | } |
| 70 | if !drawsLookups(r) { |
| 71 | read = h.plainEvents(read) |
| 72 | } |
| 73 | h.stream(w, r, p, lane.lane, read) |
| 74 | })) |
| 75 | r.Put("/host", h.assistantBearer(func(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| 76 | h.assistantHost(w, r, p, lane) |
| 77 | })) |
| 78 | r.Post("/cards/{id}/carry_on", h.assistantBearer(func(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| 79 | h.carryOn(w, r, p) |
| 80 | })) |
| 81 | r.Put("/time-zone", h.assistantBearer(h.setAssistantZone)) |
| 82 | if h.OficinaConnect != nil { |
| 83 | r.Post("/oficina/connect", h.assistantBearer(h.oficinaConnect)) |
| 84 | } |
| 85 | if h.OficinaFinish != nil { |
| 86 | r.Post("/oficina/connect/finish", h.assistantBearer(h.oficinaFinish)) |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | // assistantBearer is bearer for the Assistant's routes: before anything |
| 91 | // else, it records the Base-Capabilities the person's Base sent |
| 92 | // (noteCapabilities). |
| 93 | func (h *HTTP) assistantBearer(f func(http.ResponseWriter, *http.Request, personapi.PersonPrincipal)) http.HandlerFunc { |
| 94 | return h.bearer(func(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| 95 | h.noteCapabilities(r, p) |
| 96 | f(w, r, p) |
| 97 | }) |
| 98 | } |
| 99 | |
| 100 | // noteCapabilities records what the person's Base says it draws |
| 101 | // (Base-Capabilities), presentation only. The request never waits on it |
| 102 | // failing. |
| 103 | func (h *HTTP) noteCapabilities(r *http.Request, p personapi.PersonPrincipal) { |
| 104 | if err := h.Store.SetCapabilities(r.Context(), p.Address, r.Header.Get("Base-Capabilities")); err != nil && h.Logger != nil { |
| 105 | h.Logger.Warn("assistant capabilities", "err", err) |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | // oficinaFinish is POST oficina/connect/finish {state, code}: 200 |
| 110 | // {status}, or 403 forbidden when the consent was another person's. |
| 111 | func (h *HTTP) oficinaFinish(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| 112 | var in struct { |
| 113 | State string `json:"state"` |
| 114 | Code string `json:"code"` |
| 115 | } |
| 116 | if err := readJSON(r, &in); err != nil { |
| 117 | h.fail(w, r, err) |
| 118 | return |
| 119 | } |
| 120 | status, err := h.OficinaFinish(r.Context(), p.Address, in.State, in.Code) |
| 121 | if err != nil { |
| 122 | h.fail(w, r, err) |
| 123 | return |
| 124 | } |
| 125 | writeJSON(w, 200, map[string]string{"status": status}) |
| 126 | } |
| 127 | |
| 128 | // oficinaConnect is POST oficina/connect {return_to}: 200 {url}, the |
| 129 | // address of connect's consent page for the person, whose browser comes |
| 130 | // back to return_to (on an allowed Base origin, or 422 invalid_input). |
| 131 | func (h *HTTP) oficinaConnect(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| 132 | var in struct { |
| 133 | ReturnTo string `json:"return_to"` |
| 134 | } |
| 135 | if err := readJSON(r, &in); err != nil { |
| 136 | h.fail(w, r, err) |
| 137 | return |
| 138 | } |
| 139 | url, err := h.OficinaConnect(r.Context(), p.Address, in.ReturnTo) |
| 140 | if err != nil { |
| 141 | h.fail(w, r, err) |
| 142 | return |
| 143 | } |
| 144 | writeJSON(w, 200, map[string]string{"url": url}) |
| 145 | } |
| 146 | |
| 147 | // oficinaCatchUp settles what a failed settlement left open, before the |
| 148 | // lane is read. The read never waits on it failing. |
| 149 | func (h *HTTP) oficinaCatchUp(r *http.Request, p personapi.PersonPrincipal) { |
| 150 | if h.OficinaCatchUp == nil { |
| 151 | return |
| 152 | } |
| 153 | if err := h.OficinaCatchUp(r.Context(), p.Address); err != nil && h.Logger != nil { |
| 154 | h.Logger.Warn("oficina catch-up", "err", err) |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | // warmAssistant asks the person's runner to warm their Assistant: Base |
| 159 | // read its snapshot or opened its stream, so they are about to use it. |
| 160 | // The read never waits on it failing. |
| 161 | func (h *HTTP) warmAssistant(r *http.Request, p personapi.PersonPrincipal) { |
| 162 | if err := h.Store.WarmAssistant(r.Context(), p.Address); err != nil && h.Logger != nil { |
| 163 | h.Logger.Warn("assistant warm", "err", err) |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | // assistantHost is PUT host {origin, token}: 200 {origin, revision}, the |
| 168 | // token never given back; 403 host_not_allowed for an origin the |
| 169 | // operator has not allowed; 409 host_unverified when Base didn't honour |
| 170 | // the token, host_elsewhere when the person's Base is another. |
| 171 | func (h *HTTP) assistantHost(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal, lane *LaneStore) { |
| 172 | var in wire.AssistantHost |
| 173 | if err := readJSON(r, &in); err != nil { |
| 174 | h.fail(w, r, err) |
| 175 | return |
| 176 | } |
| 177 | out, err := lane.SetHost(r.Context(), p.Address, in) |
| 178 | switch { |
| 179 | case errors.Is(err, ErrHostNotAllowed): |
| 180 | personapi.WriteError(w, r, http.StatusForbidden, "host_not_allowed", nil) |
| 181 | return |
| 182 | case errors.Is(err, ErrHostUnverified): |
| 183 | personapi.WriteError(w, r, http.StatusConflict, "host_unverified", nil) |
| 184 | return |
| 185 | case errors.Is(err, ErrHostElsewhere): |
| 186 | personapi.WriteError(w, r, http.StatusConflict, "host_elsewhere", nil) |
| 187 | return |
| 188 | } |
| 189 | if err != nil { |
| 190 | h.fail(w, r, err) |
| 191 | return |
| 192 | } |
| 193 | writeJSON(w, 200, out) |
| 194 | } |
| 195 | |
| 196 | // assistantAnswer is POST cards/{id}/answer: 200 with the card, the |
| 197 | // answer as a message and its turn, or 409 with the card as it is now. |
| 198 | func (h *HTTP) assistantAnswer(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal, lane *LaneStore) { |
| 199 | var in wire.AnswerCard |
| 200 | if err := readJSON(r, &in); err != nil { |
| 201 | h.fail(w, r, err) |
| 202 | return |
| 203 | } |
| 204 | out, current, err := lane.Answer(r.Context(), p.Address, chi.URLParam(r, "id"), in) |
| 205 | if errors.Is(err, ErrCardConflict) { |
| 206 | code := "card_answered" |
| 207 | if current.State == wire.CardOpen { |
| 208 | code = "card_stale" |
| 209 | } |
| 210 | // The request id as personapi.WriteError gives it. |
| 211 | request := r.Header.Get("Idempotency-Key") |
| 212 | if request == "" || len(request) > 256 { |
| 213 | request = rand.Text() |
| 214 | } |
| 215 | writeJSON(w, http.StatusConflict, wire.AssistantConflict{Code: code, CopyKey: "api." + code, RequestID: request, Card: current}) |
| 216 | return |
| 217 | } |
| 218 | if err != nil { |
| 219 | h.fail(w, r, err) |
| 220 | return |
| 221 | } |
| 222 | writeJSON(w, 200, out) |
| 223 | } |
| 224 | |
| 225 | // knowsPaused: the client asked for paused job cards (job_states=paused |
| 226 | // on the snapshot and the stream). Base before paused work drops a job |
| 227 | // card in a state it does not know, so the job would vanish on a reload |
| 228 | // and stand still on the stream. |
| 229 | func knowsPaused(r *http.Request) bool { |
| 230 | for _, v := range r.URL.Query()["job_states"] { |
| 231 | for _, s := range strings.Split(v, ",") { |
| 232 | if s == wire.JobPaused { |
| 233 | return true |
| 234 | } |
| 235 | } |
| 236 | } |
| 237 | return false |
| 238 | } |
| 239 | |
| 240 | // olderJobCard is a card as a client that does not know paused reads it: |
| 241 | // a paused job card is working, with the paused words and no Carry on |
| 242 | // now. |
| 243 | func olderJobCard(c wire.AssistantCard) wire.AssistantCard { |
| 244 | if c.Kind == wire.CardJob && c.State == wire.JobPaused { |
| 245 | c.State, c.CarryOn = wire.JobWorking, false |
| 246 | } |
| 247 | return c |
| 248 | } |
| 249 | |
| 250 | // olderJobEvents reads the lane's events with each paused job card in |
| 251 | // them as olderJobCard words it. |
| 252 | func olderJobEvents(read func(context.Context, string, int64, int) ([]wire.Event, error)) func(context.Context, string, int64, int) ([]wire.Event, error) { |
| 253 | return func(ctx context.Context, person string, after int64, limit int) ([]wire.Event, error) { |
| 254 | events, err := read(ctx, person, after, limit) |
| 255 | if err != nil { |
| 256 | return nil, err |
| 257 | } |
| 258 | for i, e := range events { |
| 259 | if e.Type != wire.EventCard { |
| 260 | continue |
| 261 | } |
| 262 | var c wire.AssistantCard |
| 263 | if json.Unmarshal(e.Data, &c) != nil || c.Kind != wire.CardJob || c.State != wire.JobPaused { |
| 264 | continue |
| 265 | } |
| 266 | raw, err := json.Marshal(olderJobCard(c)) |
| 267 | if err != nil { |
| 268 | return nil, err |
| 269 | } |
| 270 | events[i].Data = raw |
| 271 | } |
| 272 | return events, nil |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | // carryOn is POST cards/{id}/carry_on {revision, idempotency_key}: 200 |
| 277 | // with the job card, or 409 card_stale, not_paused or |
| 278 | // carry_on_unavailable with the card as it is now. |
| 279 | func (h *HTTP) carryOn(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| 280 | var in wire.CarryOn |
| 281 | if err := readJSON(r, &in); err != nil { |
| 282 | h.fail(w, r, err) |
| 283 | return |
| 284 | } |
| 285 | out, err := h.Store.CarryOn(r.Context(), p.Address, chi.URLParam(r, "id"), in) |
| 286 | if err == nil { |
| 287 | writeJSON(w, 200, wire.AssistantCarriedOn{Card: out}) |
| 288 | return |
| 289 | } |
| 290 | // The request id as personapi.WriteError gives it. |
| 291 | request := r.Header.Get("Idempotency-Key") |
| 292 | if request == "" || len(request) > 256 { |
| 293 | request = rand.Text() |
| 294 | } |
| 295 | switch { |
| 296 | case errors.Is(err, ErrCardConflict): |
| 297 | writeJSON(w, http.StatusConflict, wire.AssistantConflict{Code: "card_stale", CopyKey: "api.card_stale", RequestID: request, Card: out}) |
| 298 | case errors.Is(err, ErrNotPaused): |
| 299 | writeJSON(w, http.StatusConflict, wire.AssistantConflict{Code: "not_paused", CopyKey: "api.not_paused", RequestID: request, Card: out}) |
| 300 | case errors.Is(err, ErrCarryOnUnavailable): |
| 301 | writeJSON(w, http.StatusConflict, wire.AssistantConflict{Code: "carry_on_unavailable", CopyKey: "api.carry_on_unavailable", RequestID: request, Card: out}) |
| 302 | case errors.Is(err, ErrAbilityOff): |
| 303 | // Building is off for the person: the card as it is now. |
| 304 | writeJSON(w, http.StatusForbidden, wire.AssistantConflict{Code: "ability_off", CopyKey: "api.ability_off", RequestID: request, Card: out}) |
| 305 | default: |
| 306 | h.fail(w, r, err) |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | // drawsLookups: the request's Base draws lookups' answers (its |
| 311 | // Base-Capabilities say lookup_answers). Without it a read gets each |
| 312 | // answer folded into its message's text (plainLookups). |
| 313 | func drawsLookups(r *http.Request) bool { |
| 314 | for _, v := range r.Header.Values("Base-Capabilities") { |
| 315 | for _, c := range strings.Split(v, ",") { |
| 316 | if strings.TrimSpace(c) == wire.CapLookupAnswers { |
| 317 | return true |
| 318 | } |
| 319 | } |
| 320 | } |
| 321 | return false |
| 322 | } |
| 323 | |
| 324 | // sourcesLine is the fallback's sources label (approved copy). |
| 325 | func (h *HTTP) sourcesLine() string { |
| 326 | if h.Store.authority.Copy != nil { |
| 327 | if s := h.Store.authority.Copy("assistant.lookup.fallback_sources"); s != "" { |
| 328 | return s |
| 329 | } |
| 330 | } |
| 331 | return "Sources:" |
| 332 | } |
| 333 | |
| 334 | // plainPage is a message page with each answer folded into its text. |
| 335 | func (h *HTTP) plainPage(page func(context.Context, string, string, int) (wire.MessagePage, error)) func(context.Context, string, string, int) (wire.MessagePage, error) { |
| 336 | return func(ctx context.Context, person, before string, limit int) (wire.MessagePage, error) { |
| 337 | out, err := page(ctx, person, before, limit) |
| 338 | for i := range out.Items { |
| 339 | out.Items[i] = plainLookups(out.Items[i], h.sourcesLine()) |
| 340 | } |
| 341 | return out, err |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | // plainEvents reads the lane's events with each message's answers folded |
| 346 | // into its text. |
| 347 | func (h *HTTP) plainEvents(read func(context.Context, string, int64, int) ([]wire.Event, error)) func(context.Context, string, int64, int) ([]wire.Event, error) { |
| 348 | return func(ctx context.Context, person string, after int64, limit int) ([]wire.Event, error) { |
| 349 | events, err := read(ctx, person, after, limit) |
| 350 | if err != nil { |
| 351 | return nil, err |
| 352 | } |
| 353 | for i, e := range events { |
| 354 | if e.Type != wire.EventMessage { |
| 355 | continue |
| 356 | } |
| 357 | var m wire.Message |
| 358 | if json.Unmarshal(e.Data, &m) != nil || len(m.Lookups) == 0 { |
| 359 | continue |
| 360 | } |
| 361 | raw, err := json.Marshal(plainLookups(m, h.sourcesLine())) |
| 362 | if err != nil { |
| 363 | return nil, err |
| 364 | } |
| 365 | events[i].Data = raw |
| 366 | } |
| 367 | return events, nil |
| 368 | } |
| 369 | } |
| 370 | |