package agentapi import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "log/slog" "net/http" "strings" "sync" "time" "github.com/coder/websocket" ) // The stream is one WebSocket from an agent to the API. It carries the // agent's requests, which the API answers as if they had come over HTTP, // and events the API sends unasked, such as which status pages changed. // Agents fall back to plain HTTP while it is down, and an API without it // is asked again only now and then. const ( // Prefix is the path of the agent API. Prefix = "/agent/v1" // StreamPath is where agents open the stream, below Prefix. StreamPath = "/stream" // MaxFrame bounds a frame read from the stream. MaxFrame = 64 << 20 // EventPages lists pages that changed, as a PagesEvent. EventPages = "pages" ) // Frame is the header of a stream message. A message is the header as // JSON, a newline and the body. Requests carry ID, Method and Path, replies // the request's ID and Status, events Event; Cancel withdraws a request. type Frame struct { ID uint64 `json:"id,omitempty"` Method string `json:"method,omitempty"` // Path is below Prefix and includes the query. Path string `json:"path,omitempty"` Status int `json:"status,omitempty"` Header http.Header `json:"header,omitempty"` Cancel bool `json:"cancel,omitempty"` Event string `json:"event,omitempty"` } // PagesEvent names status pages that changed and should be fetched again. type PagesEvent struct { Pages []PageRef `json:"pages"` } // EncodeFrame builds a stream message. func EncodeFrame(f Frame, body []byte) []byte { head, _ := json.Marshal(f) out := make([]byte, 0, len(head)+1+len(body)) return append(append(append(out, head...), '\n'), body...) } // DecodeFrame splits a stream message into its header and body. func DecodeFrame(msg []byte) (Frame, []byte, error) { var f Frame head, body, ok := bytes.Cut(msg, []byte{'\n'}) if !ok { return f, nil, errors.New("agentapi: frame without header") } err := json.Unmarshal(head, &f) return f, body, err } // StreamOptions configure UseStream. type StreamOptions struct { Log *slog.Logger // OnEvent receives the events the API sends. It runs on the stream's // reader and must not block. OnEvent func(event string, body []byte) } const ( pingEvery = 20 * time.Second pingTimeout = 15 * time.Second // unsupportedRetry is how long an API without the stream is not asked // again. unsupportedRetry = 5 * time.Minute ) var ( errStreamClosed = errors.New("agentapi: stream closed") errStreamUnsupported = errors.New("agentapi: API has no stream") ) // UseStream sends the client's requests over a WebSocket to the API from // now on, while it is open, and keeps reopening it until ctx ends. Call it // before the client is used concurrently. func (c *Client) UseStream(ctx context.Context, o StreamOptions) { if o.Log == nil { o.Log = slog.New(slog.DiscardHandler) } fallback := c.hc.Transport if fallback == nil { fallback = http.DefaultTransport } // The handshake runs over the plain client; a client timeout would end // the stream, so only the context bounds it. dial := *c.hc dial.Timeout = 0 t := &streamTransport{c: c, fallback: fallback, dial: &dial, opts: o} hc := *c.hc hc.Transport = t c.hc = &hc go t.run(ctx) } // Streaming reports whether requests currently go over the stream. func (c *Client) Streaming() bool { t, ok := c.hc.Transport.(*streamTransport) return ok && t.current() != nil } // streamTransport sends requests over the stream while it is open and over // fallback otherwise. type streamTransport struct { c *Client fallback http.RoundTripper dial *http.Client opts StreamOptions mu sync.Mutex conn *streamConn } func (t *streamTransport) current() *streamConn { t.mu.Lock() defer t.mu.Unlock() return t.conn } func (t *streamTransport) set(sc *streamConn) { t.mu.Lock() t.conn = sc t.mu.Unlock() } // RoundTrip implements http.RoundTripper. func (t *streamTransport) RoundTrip(req *http.Request) (*http.Response, error) { sc := t.current() path, below := strings.CutPrefix(req.URL.Path, Prefix) if sc == nil || !below || path == StreamPath { return t.fallback.RoundTrip(req) } var body []byte if req.Body != nil { var err error body, err = io.ReadAll(req.Body) _ = req.Body.Close() if err != nil { return nil, err } } header := req.Header.Clone() // The stream is authenticated once, as the agent that opened it. for _, k := range []string{"Authorization", VersionHeader, InstanceHeader, ReleaseHeader} { header.Del(k) } if req.URL.RawQuery != "" { path += "?" + req.URL.RawQuery } f, rbody, sent, err := sc.roundTrip(req.Context(), Frame{Method: req.Method, Path: path, Header: header}, body) if err != nil { if !sent && req.Context().Err() == nil { // Never reached the API: plain HTTP can still deliver it. retry := req.Clone(req.Context()) retry.Body = io.NopCloser(bytes.NewReader(body)) return t.fallback.RoundTrip(retry) } return nil, err } if f.Header == nil { f.Header = http.Header{} } return &http.Response{ Status: fmt.Sprintf("%d %s", f.Status, http.StatusText(f.Status)), StatusCode: f.Status, Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Header: f.Header, Body: io.NopCloser(bytes.NewReader(rbody)), ContentLength: int64(len(rbody)), Request: req, }, nil } // run keeps the stream open until ctx ends. func (t *streamTransport) run(ctx context.Context) { backoff := time.Second var down time.Time for ctx.Err() == nil { sc, err := t.open(ctx) if err != nil { wait := backoff if errors.Is(err, errStreamUnsupported) { wait = unsupportedRetry t.opts.Log.Info("the API has no WebSocket stream yet; using HTTP", "retry_in", wait.String()) } else { t.opts.Log.Debug("opening the WebSocket to the API failed", "error", err, "retry_in", wait.String()) backoff = min(backoff*2, 30*time.Second) } sleepCtx(ctx, wait) continue } backoff = time.Second if down.IsZero() { t.opts.Log.Info("connected to the API over WebSocket") } else { t.opts.Log.Info("connected to the API over WebSocket again", "down_for", time.Since(down).Round(time.Second).String()) } t.set(sc) err = sc.serve(ctx, t.opts.OnEvent) t.set(nil) down = time.Now() if ctx.Err() == nil { t.opts.Log.Info("WebSocket to the API closed; using HTTP until it is back", "error", err) } } } func (t *streamTransport) open(ctx context.Context) (*streamConn, error) { u := t.c.base + Prefix + StreamPath switch { case strings.HasPrefix(u, "https://"): u = "wss://" + strings.TrimPrefix(u, "https://") case strings.HasPrefix(u, "http://"): u = "ws://" + strings.TrimPrefix(u, "http://") } h := http.Header{} h.Set("Authorization", "Bearer "+t.c.token) h.Set(VersionHeader, fmt.Sprint(Version)) h.Set(InstanceHeader, t.c.instance.String()) h.Set(ReleaseHeader, t.c.release) dctx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() ws, resp, err := websocket.Dial(dctx, u, &websocket.DialOptions{ HTTPClient: t.dial, HTTPHeader: h, CompressionMode: websocket.CompressionContextTakeover, }) if err != nil { if resp != nil { switch resp.StatusCode { case http.StatusNotFound, http.StatusMethodNotAllowed: return nil, errStreamUnsupported case http.StatusUnauthorized: return nil, ErrUnauthorized } } return nil, err } ws.SetReadLimit(MaxFrame) return &streamConn{ws: ws, waiting: map[uint64]chan reply{}, closed: make(chan struct{})}, nil } type reply struct { f Frame body []byte } // streamConn is one open stream. type streamConn struct { ws *websocket.Conn mu sync.Mutex next uint64 waiting map[uint64]chan reply closed chan struct{} } // roundTrip sends a request and waits for its reply. sent reports whether // the request may have reached the API. func (sc *streamConn) roundTrip(ctx context.Context, f Frame, body []byte) (Frame, []byte, bool, error) { ch := make(chan reply, 1) sc.mu.Lock() sc.next++ f.ID = sc.next sc.waiting[f.ID] = ch sc.mu.Unlock() defer func() { sc.mu.Lock() delete(sc.waiting, f.ID) sc.mu.Unlock() }() select { case <-sc.closed: return Frame{}, nil, false, errStreamClosed default: } if err := sc.ws.Write(ctx, websocket.MessageBinary, EncodeFrame(f, body)); err != nil { return Frame{}, nil, false, err } select { case r := <-ch: return r.f, r.body, true, nil case <-sc.closed: return Frame{}, nil, true, errStreamClosed case <-ctx.Done(): // The API stops working on it, e.g. ends a long poll. cctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) _ = sc.ws.Write(cctx, websocket.MessageBinary, EncodeFrame(Frame{ID: f.ID, Cancel: true}, nil)) cancel() return Frame{}, nil, true, ctx.Err() } } // serve reads replies and events until the stream closes or ctx ends. func (sc *streamConn) serve(ctx context.Context, onEvent func(string, []byte)) error { defer close(sc.closed) done := make(chan struct{}) defer close(done) go func() { tick := time.NewTicker(pingEvery) defer tick.Stop() for { select { case <-done: return case <-ctx.Done(): _ = sc.ws.Close(websocket.StatusNormalClosure, "agent stopping") return case <-tick.C: pctx, cancel := context.WithTimeout(ctx, pingTimeout) err := sc.ws.Ping(pctx) cancel() if err != nil && ctx.Err() == nil { _ = sc.ws.CloseNow() return } } } }() for { _, msg, err := sc.ws.Read(context.WithoutCancel(ctx)) if err != nil { _ = sc.ws.CloseNow() return err } f, body, err := DecodeFrame(msg) if err != nil { continue } if f.Event != "" { if onEvent != nil { onEvent(f.Event, body) } continue } sc.mu.Lock() ch := sc.waiting[f.ID] sc.mu.Unlock() if ch != nil { ch <- reply{f: f, body: body} } } } func sleepCtx(ctx context.Context, d time.Duration) { select { case <-ctx.Done(): case <-time.After(d): } }