package ocapi import ( "bufio" "context" "encoding/json" "errors" "fmt" "io" "math/rand" "net/http" "net/url" "strings" "time" ) // StreamEvents subscribes to GET /api/event and calls fn for each event // until ctx is done or the connection fails. types filters the event // types; nil means every type. func (c *Client) StreamEvents(ctx context.Context, types []string, fn func(Event) error) error { return c.streamEvents(ctx, types, nil, fn) } func (c *Client) streamEvents(ctx context.Context, types []string, onOpen func(), fn func(Event) error) error { q := url.Values{} for _, t := range types { q.Add("types", t) } req, err := c.newRequest(ctx, http.MethodGet, "/api/event", requestOptions{query: q}, nil) if err != nil { return err } req.Header.Set("Accept", "text/event-stream") req.Header.Set("Cache-Control", "no-cache") // A streaming request must not inherit the client's overall timeout. hc := *c.http hc.Timeout = 0 res, err := hc.Do(req) if err != nil { return err } defer res.Body.Close() if res.StatusCode != http.StatusOK { raw, _ := io.ReadAll(io.LimitReader(res.Body, 1<<14)) return &APIError{Status: res.StatusCode, Raw: string(raw), Message: strings.TrimSpace(string(raw))} } if onOpen != nil { onOpen() } reader := bufio.NewReaderSize(res.Body, 64<<10) var data []byte for { line, err := reader.ReadString('\n') if err != nil { if errors.Is(err, io.EOF) || ctx.Err() != nil { return ctx.Err() } return err } line = strings.TrimRight(line, "\r\n") if line == "" { if len(data) == 0 { continue } var ev Event parseErr := json.Unmarshal(data, &ev) data = data[:0] if parseErr != nil { continue } if err := fn(ev); err != nil { return err } continue } if strings.HasPrefix(line, "data:") { chunk := strings.TrimPrefix(line, "data:") chunk = strings.TrimPrefix(chunk, " ") if len(data) > 0 { data = append(data, '\n') } data = append(data, chunk...) } } } // SubscriptionState reports the event stream's connection state. type SubscriptionState int const ( Subscribing SubscriptionState = iota Subscribed Disconnected ) // Subscription is a resilient event stream. type Subscription struct { Types []string OnEvent func(Event) OnState func(SubscriptionState, error) // MinBackoff and MaxBackoff bound the reconnect delay. MinBackoff time.Duration MaxBackoff time.Duration } // Subscribe keeps an event stream open until ctx is done, reconnecting with // exponential backoff. It blocks, so run it in a goroutine. func (c *Client) Subscribe(ctx context.Context, s Subscription) { minB, maxB := s.MinBackoff, s.MaxBackoff if minB <= 0 { minB = time.Second } if maxB <= 0 { maxB = 30 * time.Second } state := func(st SubscriptionState, err error) { if s.OnState != nil { s.OnState(st, err) } } backoff := minB for ctx.Err() == nil { state(Subscribing, nil) started := time.Now() err := c.streamEvents(ctx, s.Types, func() { state(Subscribed, nil) }, func(ev Event) error { if s.OnEvent != nil { s.OnEvent(ev) } return nil }) if ctx.Err() != nil { return } state(Disconnected, err) // A stream that stayed up for a while restarts at the minimum // delay; a failing one backs off. if time.Since(started) > 30*time.Second { backoff = minB } delay := backoff/2 + time.Duration(rand.Int63n(int64(backoff/2+1))) select { case <-ctx.Done(): return case <-time.After(delay): } if backoff < maxB { backoff *= 2 if backoff > maxB { backoff = maxB } } } } // WaitReady polls /api/opencode/health until OpenCode is ready or ctx ends. func (c *Client) WaitReady(ctx context.Context, wait time.Duration) error { if wait <= 0 { wait = 20 * time.Second } q := url.Values{} q.Set("wait", fmt.Sprint(wait.Milliseconds())) var payload struct { Healthy bool `json:"healthy"` Error string `json:"error"` } if err := c.do(ctx, http.MethodGet, "/api/opencode/health", requestOptions{query: q}, nil, &payload); err != nil { return err } if !payload.Healthy { if payload.Error != "" { return fmt.Errorf("ocapi: opencode not ready: %s", payload.Error) } return errors.New("ocapi: opencode not ready") } return nil }