| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "net/http" |
| 8 | "strings" |
| 9 | "time" |
| 10 | |
| 11 | "amadan.net/oficina/equipo/internal/wire" |
| 12 | "amadan.net/rastrillo/rastrillo" |
| 13 | "github.com/coder/websocket" |
| 14 | ) |
| 15 | |
| 16 | // Runner stream timings. A runner says hello every 30 seconds. |
| 17 | const ( |
| 18 | helloTimeout = 10 * time.Second |
| 19 | silentLimit = 90 * time.Second |
| 20 | drainRetry = 1 |
| 21 | ) |
| 22 | |
| 23 | // RunnerStream is GET /api/runner/stream: one WebSocket per runner with a |
| 24 | // bearer runner credential. The handler grants the generation, delivers |
| 25 | // unacked commands for the runner's person, and applies runner frames |
| 26 | // exactly once. |
| 27 | func (h *HTTP) RunnerStream(process string) http.Handler { |
| 28 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 29 | w.Header().Set("Cache-Control", "no-store") |
| 30 | auth := r.Header.Values("Authorization") |
| 31 | if len(r.Header.Values("Cookie")) != 0 || len(auth) != 1 || !strings.HasPrefix(auth[0], "Bearer ") { |
| 32 | http.Error(w, "forbidden", http.StatusForbidden) |
| 33 | return |
| 34 | } |
| 35 | p, err := h.AuthenticateRunner(r.Context(), strings.TrimPrefix(auth[0], "Bearer ")) |
| 36 | if err != nil { |
| 37 | http.Error(w, "forbidden", http.StatusForbidden) |
| 38 | return |
| 39 | } |
| 40 | // The address the runner connected from, for Research's site |
| 41 | // inventory: read only as the proxies in front of the instance |
| 42 | // wrote it (ObservedAddress), never from anything else. |
| 43 | observed := h.Store.ObservedAddress(r) |
| 44 | c, err := websocket.Accept(w, r, &websocket.AcceptOptions{CompressionMode: websocket.CompressionDisabled}) |
| 45 | if err != nil { |
| 46 | return |
| 47 | } |
| 48 | c.SetReadLimit(wire.MaxFrameBytes) |
| 49 | (&runnerConn{h: h, c: c, principal: p, process: process, observed: observed}).serve() |
| 50 | }) |
| 51 | } |
| 52 | |
| 53 | type runnerConn struct { |
| 54 | h *HTTP |
| 55 | c *websocket.Conn |
| 56 | principal RunnerPrincipal |
| 57 | process string |
| 58 | observed string |
| 59 | lease Lease |
| 60 | seen chan struct{} |
| 61 | // live is this connection's lookup channel (attachLive). |
| 62 | live *liveConn |
| 63 | } |
| 64 | |
| 65 | func (rc *runnerConn) log(msg string, err error) { |
| 66 | if rc.h.Logger != nil { |
| 67 | rc.h.Logger.Warn(msg, "runner", rc.principal.RunnerID, "err", err) |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | // send writes one frame as this connection's protocol speaks it. A frame |
| 72 | // the protocol cannot carry is never sent (a pinned Run now to a runner |
| 73 | // below 29, or anything new to an old runner; this is the last guard). |
| 74 | func (rc *runnerConn) send(ctx context.Context, f wire.Frame) error { |
| 75 | f, err := wire.Encode(f, rc.lease.Protocol) |
| 76 | if errors.Is(err, wire.ErrProtocol) { |
| 77 | if rc.h.Logger != nil { |
| 78 | rc.h.Logger.Warn("runner frame not sent at its protocol", "runner", rc.principal.RunnerID, "type", f.Type, "protocol", rc.lease.Protocol, "err", err) |
| 79 | } |
| 80 | return nil |
| 81 | } |
| 82 | if err != nil { |
| 83 | return err |
| 84 | } |
| 85 | raw, err := jsonFrame(f) |
| 86 | if err != nil { |
| 87 | return err |
| 88 | } |
| 89 | if tap := rc.h.Store.tap.Load(); tap != nil && *tap != nil { |
| 90 | (*tap)(rc.principal.RunnerID, raw) |
| 91 | } |
| 92 | wctx, cancel := context.WithTimeout(ctx, 15*time.Second) |
| 93 | defer cancel() |
| 94 | return rc.c.Write(wctx, websocket.MessageText, raw) |
| 95 | } |
| 96 | |
| 97 | func (rc *runnerConn) serve() { |
| 98 | // The socket outlives the request context once hijacked; drain and |
| 99 | // supersession end it explicitly. |
| 100 | ctx, cancel := context.WithCancel(context.Background()) |
| 101 | defer cancel() |
| 102 | defer rc.c.CloseNow() |
| 103 | store := rc.h.Store |
| 104 | |
| 105 | hctx, stop := context.WithTimeout(ctx, helloTimeout) |
| 106 | kind, raw, err := rc.c.Read(hctx) |
| 107 | stop() |
| 108 | if err != nil || kind != websocket.MessageText { |
| 109 | return |
| 110 | } |
| 111 | f, body, err := wire.ParseFrame(raw) |
| 112 | hello, ok := body.(*wire.Hello) |
| 113 | if err != nil || !ok || f.Type != wire.FrameHello { |
| 114 | rc.c.Close(websocket.StatusPolicyViolation, "hello first") |
| 115 | return |
| 116 | } |
| 117 | rc.lease, err = store.Connect(ctx, rc.principal, rc.process, *hello, rc.observed) |
| 118 | if errors.Is(err, ErrSuperseded) { |
| 119 | rc.c.Close(wire.CloseSuperseded, "superseded") |
| 120 | return |
| 121 | } |
| 122 | if err != nil { |
| 123 | rc.log("runner connect", err) |
| 124 | rc.c.Close(wire.CloseRevoked, "refused") |
| 125 | return |
| 126 | } |
| 127 | release := store.Hub().claim(rc.principal.RunnerID, cancel) |
| 128 | defer release() |
| 129 | defer func() { |
| 130 | dctx, done := context.WithTimeout(context.Background(), 5*time.Second) |
| 131 | defer done() |
| 132 | if err := store.Disconnect(dctx, rc.lease); err != nil { |
| 133 | rc.log("runner disconnect", err) |
| 134 | } |
| 135 | }() |
| 136 | welcome, _ := wire.NewFrame("w"+newID(""), wire.FrameWelcome, wire.Welcome{Generation: rc.lease.Generation, RunnerID: rc.principal.RunnerID, Protocol: rc.lease.Protocol, Role: rc.lease.Role, Release: rastrillo.BuildVersion, Tainted: rc.lease.Tainted}) |
| 137 | if rc.send(ctx, welcome) != nil { |
| 138 | return |
| 139 | } |
| 140 | // Lookup steps go to this connection, live, until it ends. |
| 141 | live, detach := store.attachLive(rc.principal.RunnerID, rc.lease.Protocol, rc.send) |
| 142 | rc.live = live |
| 143 | defer detach() |
| 144 | rc.seen = make(chan struct{}, 1) |
| 145 | closeCode := make(chan websocket.StatusCode, 1) |
| 146 | go func() { |
| 147 | defer cancel() |
| 148 | code := rc.read(ctx) |
| 149 | closeCode <- code |
| 150 | }() |
| 151 | rc.write(ctx) |
| 152 | select { |
| 153 | case code := <-closeCode: |
| 154 | if code != 0 { |
| 155 | rc.c.Close(code, "") |
| 156 | } |
| 157 | default: |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | // read applies runner frames until the socket ends. It returns a close |
| 162 | // code when the runner must be told why. |
| 163 | func (rc *runnerConn) read(ctx context.Context) websocket.StatusCode { |
| 164 | store := rc.h.Store |
| 165 | for { |
| 166 | kind, raw, err := rc.c.Read(ctx) |
| 167 | if err != nil { |
| 168 | return 0 |
| 169 | } |
| 170 | if kind != websocket.MessageText { |
| 171 | return websocket.StatusUnsupportedData |
| 172 | } |
| 173 | f, body, err := wire.ParseFrame(raw) |
| 174 | if err != nil { |
| 175 | return websocket.StatusPolicyViolation |
| 176 | } |
| 177 | // A protocol 1 runner speaks only the slice 4 frames. |
| 178 | if !wire.Speaks(rc.lease.Protocol, f.Type) { |
| 179 | return websocket.StatusPolicyViolation |
| 180 | } |
| 181 | select { |
| 182 | case rc.seen <- struct{}{}: |
| 183 | default: |
| 184 | } |
| 185 | switch v := body.(type) { |
| 186 | case *wire.Hello: |
| 187 | err = store.Heartbeat(ctx, rc.lease, *v) |
| 188 | case *wire.LookupResult: |
| 189 | // Live only: handed to the step waiting on it, never stored. |
| 190 | store.deliverLookup(rc.live, *v) |
| 191 | case *wire.ChangeDiffUpload, *wire.AccessReport, *wire.Sync, *wire.Ack, *wire.DeltaReport, *wire.Reply, *wire.TurnReport, *wire.ToolCall, *wire.ActivityReport, *wire.MoveIn, *wire.NotebookReport, *wire.StepReport, *wire.MergedReport, *wire.AnswerReport, *wire.BranchReport, *wire.ConnectionReport, *wire.UsageReport, *wire.StepActivityReport, *wire.Blob, *wire.PublishedReport, *wire.ResearchFile, *wire.RenderFile, *wire.GlanceReport, *wire.BaseReport: |
| 192 | err = store.Apply(ctx, rc.lease, f, body) |
| 193 | case *wire.LeaseCheck: |
| 194 | // Answered only while this connection holds the lease; at |
| 195 | // protocol 2 a lease naming a step attempt is its start |
| 196 | // authorization (or a publication's, before the push). |
| 197 | refused := "" |
| 198 | switch { |
| 199 | case v.AccessCard != "": |
| 200 | refused, err = store.AuthorizeAccess(ctx, rc.lease, v.AccessCard) |
| 201 | case v.StepID != "" && v.Publication != "": |
| 202 | refused, err = store.AuthorizePublication(ctx, rc.lease, v.StepID, v.Attempt, v.Publication) |
| 203 | case v.StepID != "": |
| 204 | refused, err = store.Authorize(ctx, rc.lease, v.StepID, v.Attempt, v.Purpose, v.Digest, v.Destination) |
| 205 | default: |
| 206 | err = store.Confirm(ctx, rc.lease) |
| 207 | } |
| 208 | if err == nil && refused != "" { |
| 209 | no, _ := wire.NewFrame("n"+f.ID, wire.FrameRefused, wire.Refused{ID: f.ID, Reason: refused}) |
| 210 | if rc.send(ctx, no) != nil { |
| 211 | return 0 |
| 212 | } |
| 213 | } else if err == nil { |
| 214 | ack, _ := wire.NewFrame("a"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}) |
| 215 | if rc.send(ctx, ack) != nil { |
| 216 | return 0 |
| 217 | } |
| 218 | } |
| 219 | default: |
| 220 | return websocket.StatusPolicyViolation |
| 221 | } |
| 222 | switch { |
| 223 | case errors.Is(err, ErrHeld): |
| 224 | // Not applied and not acked: the runner sends it again later. |
| 225 | rc.log("runner frame held", err) |
| 226 | continue |
| 227 | case errors.Is(err, ErrRefused): |
| 228 | rc.log("runner frame refused", err) |
| 229 | case errors.Is(err, ErrSuperseded): |
| 230 | return wire.CloseSuperseded |
| 231 | case errors.Is(err, ErrInvalid): |
| 232 | return websocket.StatusPolicyViolation |
| 233 | case errors.Is(err, ErrForbidden): |
| 234 | rc.log("runner frame", err) |
| 235 | return wire.CloseRevoked |
| 236 | case err != nil && !errors.Is(err, ErrNotFound): |
| 237 | // The frame's transaction rolled back and it stays unacked. The |
| 238 | // runner reconnects and sends it again; a credential revoked |
| 239 | // meanwhile is refused at the handshake (403), which is how |
| 240 | // every runner learns it is revoked. |
| 241 | rc.log("runner frame", err) |
| 242 | return websocket.StatusInternalError |
| 243 | } |
| 244 | if f.Durable() { |
| 245 | ack, _ := wire.NewFrame("a"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}) |
| 246 | if rc.send(ctx, ack) != nil { |
| 247 | return 0 |
| 248 | } |
| 249 | } |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | // write delivers commands for the runner's person in order, resending |
| 254 | // everything unacked on each new connection. |
| 255 | func (rc *runnerConn) write(ctx context.Context) { |
| 256 | store := rc.h.Store |
| 257 | var sent int64 |
| 258 | poll := time.NewTicker(streamPoll) |
| 259 | defer poll.Stop() |
| 260 | ping := time.NewTicker(wire.PingInterval) |
| 261 | defer ping.Stop() |
| 262 | silent := time.NewTimer(silentLimit) |
| 263 | defer silent.Stop() |
| 264 | for { |
| 265 | wake := store.Hub().Wait(rc.principal.Person) |
| 266 | frames, last, err := store.Pending(ctx, rc.lease, sent) |
| 267 | if err != nil { |
| 268 | return |
| 269 | } |
| 270 | for _, f := range frames { |
| 271 | if rc.send(ctx, f) != nil { |
| 272 | return |
| 273 | } |
| 274 | } |
| 275 | sent = last |
| 276 | select { |
| 277 | case <-ctx.Done(): |
| 278 | return |
| 279 | case <-store.Hub().Closing(): |
| 280 | drain, _ := wire.NewFrame("d"+newID(""), wire.FrameDrain, wire.Drain{RetryAfter: drainRetry}) |
| 281 | _ = rc.send(ctx, drain) |
| 282 | rc.c.Close(websocket.StatusServiceRestart, "drain") |
| 283 | return |
| 284 | case <-rc.seen: |
| 285 | if !silent.Stop() { |
| 286 | <-silent.C |
| 287 | } |
| 288 | silent.Reset(silentLimit) |
| 289 | case <-silent.C: |
| 290 | rc.c.Close(websocket.StatusGoingAway, "silent") |
| 291 | return |
| 292 | case <-ping.C: |
| 293 | pctx, done := context.WithTimeout(ctx, 10*time.Second) |
| 294 | err := rc.c.Ping(pctx) |
| 295 | done() |
| 296 | if err != nil { |
| 297 | return |
| 298 | } |
| 299 | case <-wake: |
| 300 | case <-poll.C: |
| 301 | } |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | func jsonFrame(f wire.Frame) ([]byte, error) { return json.Marshal(f) } |
| 306 | |