Files
uptimesebi/internal/agentapi/agentapi.go
T
Sebastian UnterschützandClaude Opus 5.5 9424824416
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 11m55s
ci / test (pull_request) Successful in 13m30s
ci / build (pull_request) Successful in 19m20s
ci / image (pull_request) Successful in 5m37s
fix(statuspages): encode a page once for all servers, gzipped
Every status page server asking for a page got it encoded anew: the
snapshot was marshalled once for its checksum and again for the answer,
then copied into a stream frame. A page of several thousand components
is about 20 MB of JSON, so servers fetching it together, as they do when
told it changed, ran both API pods out of their 512 MiB.

The shared build now also encodes the page once, as JSON and gzipped,
and every server asking at the same time gets those bytes. Servers ask
for gzip and unpack it, over HTTP and the stream; older ones still get
plain JSON. A 20 MB page shrinks to about 1 MB. Uptime ratios in the
snapshot are rounded to six decimals instead of up to 18 characters,
never to 100% for a component that failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-29 21:58:14 +01:00

232 lines
7.2 KiB
Go

// Package agentapi defines the protocol between the API and its agents,
// i.e. checkers and status page servers, and a client for it.
//
// Agents never touch Postgres or Redis. They authenticate with an agent
// token and exchange JSON with the API under /agent/v1, which keeps cloud,
// hybrid and self-hosted deployments on one code path.
package agentapi
import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/google/uuid"
)
// Version is the protocol version. The API accepts the current and the
// previous version so agents can be upgraded after the API.
const Version = 1
// Header names sent by agents.
const (
VersionHeader = "X-Agent-Protocol"
InstanceHeader = "X-Agent-Instance"
ReleaseHeader = "X-Agent-Release"
)
// Hello describes the agent the token belongs to.
type Hello struct {
AgentID uuid.UUID `json:"agent_id"`
Name string `json:"name"`
Kind string `json:"kind"`
// Region is the region key; RegionID identifies it uniquely.
Region string `json:"region,omitempty"`
RegionID *uuid.UUID `json:"region_id,omitempty"`
RegionName string `json:"region_name,omitempty"`
// OrgOwned is set for agents that serve a single organization.
OrgOwned bool `json:"org_owned"`
Protocol int `json:"protocol"`
}
// JobsRequest asks for up to Max jobs, waiting up to WaitMS if none are
// ready. Polling doubles as the instance's heartbeat; Max may be 0.
type JobsRequest struct {
Max int `json:"max"`
WaitMS int `json:"wait_ms"`
}
// Job is one check to run.
type Job struct {
MonitorID uuid.UUID `json:"monitor_id"`
ScheduledAt time.Time `json:"scheduled_at"`
Type string `json:"type"`
Target string `json:"target"`
TimeoutMS int `json:"timeout_ms"`
Config json.RawMessage `json:"config"`
// AllowPrivate permits targets on private networks.
AllowPrivate bool `json:"allow_private"`
}
// JobsResponse carries jobs for the polling instance.
type JobsResponse struct {
Jobs []Job `json:"jobs"`
}
// Result reports one finished check.
type Result struct {
MonitorID uuid.UUID `json:"monitor_id"`
ScheduledAt time.Time `json:"scheduled_at"`
StartedAt time.Time `json:"started_at"`
OK bool `json:"ok"`
LatencyMS int `json:"latency_ms"`
StatusCode int `json:"status_code,omitempty"`
Error string `json:"error,omitempty"`
// Evidence is what the check saw (check.Evidence), sent only now and
// then to bound traffic; see the checker's policy.
Evidence json.RawMessage `json:"evidence,omitempty"`
}
// ResultsRequest reports finished checks in a batch.
type ResultsRequest struct {
Results []Result `json:"results"`
}
// MaxResults bounds a results batch.
const MaxResults = 500
// ErrUnauthorized means the agent token was rejected.
var ErrUnauthorized = errors.New("agentapi: token rejected")
// Client talks to the agent API on behalf of one agent instance.
type Client struct {
base string
token string
instance uuid.UUID
release string
hc *http.Client
}
// NewClient returns a client for the API at base. instance identifies this
// process among several running with the same token.
func NewClient(base, token string, instance uuid.UUID, release string) *Client {
return &Client{
base: strings.TrimSuffix(base, "/"),
token: token,
instance: instance,
release: release,
hc: &http.Client{Timeout: 60 * time.Second},
}
}
// WithHTTPClient replaces the HTTP client, e.g. to trust a private CA.
func (c *Client) WithHTTPClient(hc *http.Client) *Client {
c.hc = hc
return c
}
// Instance returns the instance ID sent with every request.
func (c *Client) Instance() uuid.UUID { return c.instance }
func (c *Client) do(ctx context.Context, method, path string, in, out any) error {
return c.doWith(ctx, method, path, nil, in, out)
}
// doWith is do with extra request headers.
func (c *Client) doWith(ctx context.Context, method, path string, header http.Header, in, out any) error {
var body io.Reader
if in != nil {
b, err := json.Marshal(in)
if err != nil {
return err
}
body = bytes.NewReader(b)
}
req, err := http.NewRequestWithContext(ctx, method, c.base+"/agent/v1"+path, body)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+c.token)
req.Header.Set("Content-Type", "application/json")
req.Header.Set(VersionHeader, fmt.Sprint(Version))
req.Header.Set(InstanceHeader, c.instance.String())
req.Header.Set(ReleaseHeader, c.release)
for k, v := range header {
req.Header[k] = v
}
resp, err := c.hc.Do(req)
if err != nil {
return err
}
defer func() { _ = resp.Body.Close() }()
switch {
case resp.StatusCode == http.StatusUnauthorized:
return ErrUnauthorized
case resp.StatusCode == http.StatusNotFound:
return ErrNotFound
case resp.StatusCode == http.StatusNotModified:
return ErrNotModified
case resp.StatusCode == http.StatusTooManyRequests:
return ErrRateLimited
case resp.StatusCode == http.StatusUnprocessableEntity:
return ErrInvalidInput
case resp.StatusCode >= 300:
msg, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
return fmt.Errorf("agentapi: %s %s: %d %s", method, path, resp.StatusCode, bytes.TrimSpace(msg))
case out == nil:
return nil
}
// Asked for explicitly, a compressed answer is not unpacked by the
// transport, nor ever over the stream.
var r io.Reader = resp.Body
if strings.EqualFold(resp.Header.Get("Content-Encoding"), "gzip") {
zr, err := gzip.NewReader(resp.Body)
if err != nil {
return fmt.Errorf("agentapi: %s %s: %w", method, path, err)
}
defer func() { _ = zr.Close() }()
r = zr
}
return json.NewDecoder(r).Decode(out)
}
// Hello identifies the agent and checks connectivity.
func (c *Client) Hello(ctx context.Context) (Hello, error) {
var h Hello
err := c.do(ctx, http.MethodGet, "/hello", nil, &h)
return h, err
}
// Jobs long-polls for jobs.
func (c *Client) Jobs(ctx context.Context, max int, wait time.Duration) ([]Job, error) {
var resp JobsResponse
err := c.do(ctx, http.MethodPost, "/jobs", JobsRequest{Max: max, WaitMS: int(wait.Milliseconds())}, &resp)
return resp.Jobs, err
}
// Report sends finished checks.
func (c *Client) Report(ctx context.Context, results []Result) error {
return c.do(ctx, http.MethodPost, "/results", ResultsRequest{Results: results}, nil)
}
// Update tells a self-updating agent which release to run.
type Update struct {
// Version is the platform's release; agents follow it.
Version string `json:"version"`
// Image is the agent image of that release, e.g.
// git.example.com/owner/uptimesebi-checker:1.4.2. Empty when the
// platform runs an unreleased build, which agents do not follow.
Image string `json:"image,omitempty"`
}
// Update asks which release the agent should run. It does not count as a
// sign of life of an instance.
func (c *Client) Update(ctx context.Context) (Update, error) {
var u Update
err := c.do(ctx, http.MethodGet, "/update", nil, &u)
return u, err
}
// Release hands this instance's queued jobs back for other instances and
// deregisters it. Call it during graceful shutdown.
func (c *Client) Release(ctx context.Context) error {
return c.do(ctx, http.MethodPost, "/release", nil, nil)
}