package dataplane import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "os" "strings" "time" ) // Client is how the commands inside a Job reach the data plane. type Client struct { url string tokenFile string // session is zero in a probe Job, which speaks for an Account, and in // a schedule's Job, which speaks for a Mandate's duty. session SessionRef http *http.Client } // ClientFromEnvironment builds a Client from the settings the operator // gives a Job: SIMMER_DATAPLANE_URL, SIMMER_TOKEN_FILE, and, in a // Session's Job, SIMMER_SESSION as namespace/name. func ClientFromEnvironment(getenv func(string) string) (*Client, error) { c := &Client{ url: strings.TrimSuffix(getenv("SIMMER_DATAPLANE_URL"), "/"), tokenFile: getenv("SIMMER_TOKEN_FILE"), http: &http.Client{}, } if c.url == "" || c.tokenFile == "" { return nil, errors.New("SIMMER_DATAPLANE_URL and SIMMER_TOKEN_FILE must both be set") } if text := getenv("SIMMER_SESSION"); text != "" { session, err := ParseSessionRef(text) if err != nil { return nil, err } c.session = session } return c, nil } // ParseSessionRef reads a Session's namespace/name. func ParseSessionRef(text string) (SessionRef, error) { namespace, name, _ := strings.Cut(text, "/") session := SessionRef{Namespace: namespace, Name: name} if !validRef(session) { return SessionRef{}, fmt.Errorf("%q is not a Session's namespace/name", text) } return session, nil } // ParseDutyRef reads a Duty's namespace/name. func ParseDutyRef(text string) (DutyRef, error) { namespace, name, _ := strings.Cut(text, "/") duty := DutyRef{Namespace: namespace, Name: name} if !validRef(SessionRef(duty)) { return DutyRef{}, fmt.Errorf("%q is not a Duty's namespace/name", text) } return duty, nil } // Session is the Session the Client speaks for, or the zero SessionRef // in a probe Job. func (c *Client) Session() SessionRef { return c.session } // requestTimeout limits one attempt at a JSON request. A transcript // moves many megabytes, so it has a limit of its own. const ( requestTimeout = 30 * time.Second transcriptTimeout = 10 * time.Minute ) // The operator runs as one pod, and a rollout stops the old pod before // the new one serves, so for a few seconds no operator answers. A // request in that gap fails with a refused connection, or waits on a // connection to the old pod's address until its attempt times out. // The client sends such a request again, with a backoff, until retryFor // has passed since the first attempt, so a rollout does not fail the // turn. A request that the operator answers, even with an error, is // never sent again. Every route is safe to repeat: a second take of a // turn's events answers the events that the first one took. const ( retryFor = 2 * time.Minute firstRetry = time.Second lastRetry = 10 * time.Second ) func (c *Client) Turn(ctx context.Context) (Turn, error) { var turn Turn err := c.sessionJSON(ctx, retryFor, http.MethodGet, "turn", nil, &turn) return turn, err } // Transcript downloads the Session's transcript archive. It returns // ErrNoTranscript when there is none. The caller closes the archive. func (c *Client) Transcript(ctx context.Context) (io.ReadCloser, error) { resp, err := c.sessionRequest(ctx, transcriptTimeout, http.MethodGet, "transcript", nil) if errors.Is(err, errNotFound) { return nil, ErrNoTranscript } if err != nil { return nil, err } return resp.Body, nil } // PutTranscript uploads the Session's transcript archive. A retry sends // the archive again from its start, so the archive must be seekable. func (c *Client) PutTranscript(ctx context.Context, archive io.ReadSeeker) error { // The transport closes a request's body when the body is also an // io.Closer, such as an *os.File, and a retry must read the archive // again. This struct has only the archive's Read and Seek. resp, err := c.sessionRequest(ctx, transcriptTimeout, http.MethodPut, "transcript", struct{ io.ReadSeeker }{archive}) if err != nil { return err } return resp.Body.Close() } func (c *Client) Follow(ctx context.Context, key string) error { return c.sessionJSON(ctx, retryFor, http.MethodPost, "keys", keyRequest{Key: key}, nil) } func (c *Client) Release(ctx context.Context, key string) error { return c.sessionJSON(ctx, retryFor, http.MethodDelete, "keys", keyRequest{Key: key}, nil) } // Holders answers the other Sessions that hold a key now. func (c *Client) Holders(ctx context.Context, key string) ([]Holder, error) { var answer HoldersAnswer err := c.sessionJSON(ctx, retryFor, http.MethodGet, "holders?key="+url.QueryEscape(key), nil, &answer) return answer.Holders, err } // FollowUp sets or replaces the Session's follow-up, and answers when // it falls due. func (c *Client) FollowUp(ctx context.Context, after time.Duration, reason string) (time.Time, error) { var answer FollowUpAnswer err := c.sessionJSON(ctx, retryFor, http.MethodPut, "follow-up", FollowUpRequest{After: after.String(), Reason: reason}, &answer) // Only this route answers a 409 with the meaning of a refusal. if errors.Is(err, errConflict) { err = fmt.Errorf("%w: %w", ErrFollowUpRefused, err) } return answer.At, err } // Hook answers the context of the hook that runs in this Job. func (c *Client) Hook(ctx context.Context) (HookContext, error) { var context HookContext err := c.sessionJSON(ctx, retryFor, http.MethodGet, "hook", nil, &context) return context, err } // CancelFollowUp removes the Session's follow-up. func (c *Client) CancelFollowUp(ctx context.Context) error { return c.sessionJSON(ctx, retryFor, http.MethodDelete, "follow-up", nil, nil) } // SessionUsage posts a usage reading once, with no retry. The turn // posts each reading from claude's output stream, so a retry would block // claude's output, and the next reading replaces a lost one. func (c *Client) SessionUsage(ctx context.Context, info RateLimitInfo) error { return c.sessionJSON(ctx, 0, http.MethodPost, "usage", info, nil) } func (c *Client) SessionTokens(ctx context.Context, tokens TokensRequest) error { return c.sessionJSON(ctx, retryFor, http.MethodPost, "tokens", tokens, nil) } // Start asks the operator to start a Session of the Duty whose // schedule fell due. A retry is safe: while the Session that the first // request started is active, a second starts none. func (c *Client) Start(ctx context.Context, duty DutyRef) (StartAnswer, error) { var answer StartAnswer err := c.json(ctx, retryFor, http.MethodPost, "/v1/duties/"+duty.Namespace+"/"+duty.Name+"/start", nil, &answer) return answer, err } func (c *Client) AccountUsage(ctx context.Context, account string, info RateLimitInfo) error { return c.json(ctx, retryFor, http.MethodPost, "/v1/accounts/"+account+"/usage", info, nil) } func (c *Client) sessionPath(route string) (string, error) { if c.session == (SessionRef{}) { return "", errors.New("SIMMER_SESSION is not set, so this is not a Session's Job") } return "/v1/sessions/" + c.session.Namespace + "/" + c.session.Name + "/" + route, nil } func (c *Client) sessionJSON(ctx context.Context, retry time.Duration, method, route string, in, out any) error { path, err := c.sessionPath(route) if err != nil { return err } return c.json(ctx, retry, method, path, in, out) } func (c *Client) sessionRequest(ctx context.Context, timeout time.Duration, method, route string, body io.ReadSeeker) (*http.Response, error) { path, err := c.sessionPath(route) if err != nil { return nil, err } return c.request(ctx, timeout, retryFor, method, path, body) } // json sends a JSON request, and retries it for up to retry. A retry of // zero sends it once. func (c *Client) json(ctx context.Context, retry time.Duration, method, path string, in, out any) error { var body io.ReadSeeker if in != nil { data, err := json.Marshal(in) if err != nil { return err } body = bytes.NewReader(data) } resp, err := c.request(ctx, requestTimeout, retry, method, path, body) if err != nil { return err } defer resp.Body.Close() if out == nil { return nil } return json.NewDecoder(resp.Body).Decode(out) } var ( errNotFound = errors.New("not found") errConflict = errors.New("conflict") // errUnreachable marks a request that got no answer from the // operator, which is the only failure that a retry can fix. errUnreachable = errors.New("the operator did not answer") ) // request sends a request, and sends it again after each failure to // reach the operator until retry has passed. Each attempt has its own // timeout, which ends when the caller closes the answer's body. func (c *Client) request(ctx context.Context, timeout, retry time.Duration, method, path string, body io.ReadSeeker) (*http.Response, error) { start := time.Now() delay := firstRetry for { resp, err := c.attempt(ctx, timeout, method, path, body) if !errors.Is(err, errUnreachable) || time.Since(start)+delay > retry { return resp, err } select { case <-ctx.Done(): return nil, err case <-time.After(delay): } delay = min(delay*2, lastRetry) } } // attempt sends one request with the Job's token, which it reads from // the token file each time: the kubelet rotates a projected token, and // a token kept in memory expires. func (c *Client) attempt(ctx context.Context, timeout time.Duration, method, path string, body io.ReadSeeker) (*http.Response, error) { token, err := os.ReadFile(c.tokenFile) if err != nil { return nil, fmt.Errorf("reading the data plane token: %w", err) } var reader io.Reader if body != nil { if _, err := body.Seek(0, io.SeekStart); err != nil { return nil, err } reader = body } ctx, cancel := context.WithTimeout(ctx, timeout) req, err := http.NewRequestWithContext(ctx, method, c.url+path, reader) if err != nil { cancel() return nil, err } req.Header.Set("Authorization", "Bearer "+strings.TrimSpace(string(token))) resp, err := c.http.Do(req) if err != nil { cancel() return nil, fmt.Errorf("%w: %w", errUnreachable, err) } if resp.StatusCode >= 200 && resp.StatusCode < 300 { resp.Body = cancelOnClose{ReadCloser: resp.Body, cancel: cancel} return resp, nil } defer cancel() defer resp.Body.Close() var answer struct { Error string `json:"error"` } _ = json.NewDecoder(io.LimitReader(resp.Body, maxBody)).Decode(&answer) err = fmt.Errorf("%s %s: %s: %s", method, path, resp.Status, answer.Error) switch resp.StatusCode { case http.StatusNotFound: err = fmt.Errorf("%w: %w", errNotFound, err) case http.StatusConflict: err = fmt.Errorf("%w: %w", errConflict, err) } return nil, err } // cancelOnClose ends an attempt's context when the caller closes the // answer's body. type cancelOnClose struct { io.ReadCloser cancel context.CancelFunc } func (c cancelOnClose) Close() error { defer c.cancel() return c.ReadCloser.Close() }