client

package
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 24, 2026 License: AGPL-3.0 Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package client is the load harness's REST and WebSocket client for a running sqi-server. Field and route names follow internal/api/openapi.yaml; each struct decodes only the fields the harness reads.

Index

Constants

View Source
const DefaultRetryBudget = 2 * time.Minute

DefaultRetryBudget is the longest one call spends retrying 429 and 503 answers on a client made with WithRetry(DefaultRetryBudget).

Variables

This section is empty.

Functions

func EachPage

func EachPage[T any](limit int, fetch func(limit, offset int) (Page[T], error), fn func(Page[T])) error

EachPage reads a paged listing: it calls fetch for successive pages of up to limit items, from offset zero, and fn with each page, until a page comes back empty or the pages read cover the Total the server reports. It returns fetch's first error.

Types

type APIError

type APIError struct {
	Status int
	Method string
	Path   string
	Detail string
}

APIError is a non-2xx response.

func (*APIError) Error

func (e *APIError) Error() string

type Attempt

type Attempt struct {
	ID            string
	AttemptNumber int
	WorkerID      string
	Status        string
	StartedAt     *time.Time
	EndedAt       *time.Time
}

Attempt is one execution attempt of a task. The API identifies an attempt by its number within the task and has no attempt id, so ID is that number in decimal.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client talks to one sqi-server. It is safe for concurrent use.

func New

func New(baseURL string, opts ...Option) *Client

New returns a client for the server at baseURL (for example http://127.0.0.1:8080).

func (*Client) CancelJob

func (c *Client) CancelJob(ctx context.Context, id string) error

CancelJob cancels a job (POST /jobs/{id}/cancel).

func (*Client) CreateAPIKey

func (c *Client) CreateAPIKey(ctx context.Context, name string) (string, error)

CreateAPIKey issues an API key for the logged-in account (POST /api-keys) and returns its secret, which the server shows once.

func (*Client) CreateFarm

func (c *Client) CreateFarm(ctx context.Context, name string) (string, error)

CreateFarm creates a farm (POST /farms) and returns its id.

func (*Client) CreateQueue

func (c *Client) CreateQueue(ctx context.Context, farmID, name string, maxConcurrent int) (string, error)

CreateQueue creates a queue (POST /queues) with the given concurrency cap (0 is unlimited) and returns its id.

func (*Client) CreateUsagePool

func (c *Client) CreateUsagePool(ctx context.Context, name string, limit int) (string, error)

CreateUsagePool creates a usage pool (POST /usage-pools) and returns its id.

func (*Client) DeleteFarm

func (c *Client) DeleteFarm(ctx context.Context, id string) error

DeleteFarm deletes a farm (DELETE /farms/{id}). The server refuses while the farm still has queues, jobs or workers.

func (*Client) DeleteJob

func (c *Client) DeleteJob(ctx context.Context, id string) error

DeleteJob deletes a job (DELETE /jobs/{id}), canceling its unfinished tasks first.

func (*Client) DeleteQueue

func (c *Client) DeleteQueue(ctx context.Context, id string) error

DeleteQueue deletes a queue (DELETE /queues/{id}).

func (*Client) DeleteUsagePool

func (c *Client) DeleteUsagePool(ctx context.Context, id string) error

DeleteUsagePool deletes a usage pool (DELETE /usage-pools/{id}).

func (*Client) Enroll

func (c *Client) Enroll(ctx context.Context, joinToken, workerID, publicKey, name string) error

Enroll exchanges a join token for a broker credential (POST /workers/enroll). The route is authenticated by the token alone, so the client sends no API key or session.

func (*Client) GetFarm

func (c *Client) GetFarm(ctx context.Context, id string) (Farm, error)

GetFarm returns a farm (GET /farms/{id}).

func (*Client) GetJob

func (c *Client) GetJob(ctx context.Context, id string) (Job, error)

GetJob returns a job with its task counts (GET /jobs/{id}).

func (*Client) GetRaw

func (c *Client) GetRaw(ctx context.Context, path string, maxBytes int64) ([]byte, error)

GetRaw fetches path, relative to the server root and with any query (for example /metrics), and returns its body read up to maxBytes. It sends the client's credentials, is bounded only by ctx and is never retried, so a caller with a deadline of its own, such as a profile request, sets it. A non-2xx answer is an *APIError.

func (*Client) HTTPClient

func (c *Client) HTTPClient() *http.Client

HTTPClient returns the client's underlying *http.Client, for dialing a WebSocket that trusts the same CA.

func (*Client) ListAttempts

func (c *Client) ListAttempts(ctx context.Context, taskID string) ([]Attempt, error)

ListAttempts returns a task's attempts, oldest first (GET /tasks/{id}/attempts).

func (*Client) ListFarms

func (c *Client) ListFarms(ctx context.Context) ([]Farm, error)

ListFarms lists every farm (GET /farms).

func (*Client) ListJobs

func (c *Client) ListJobs(ctx context.Context, farmID string, limit, offset int) (Page[Job], error)

ListJobs lists jobs (GET /jobs), optionally of one farm.

func (*Client) ListQueues

func (c *Client) ListQueues(ctx context.Context, farmID string) ([]Queue, error)

ListQueues returns every queue of a farm (GET /queues), reading page by page.

func (*Client) ListTasks

func (c *Client) ListTasks(ctx context.Context, jobID string, limit, offset int) (Page[Task], error)

ListTasks lists a job's tasks (GET /jobs/{id}/tasks).

func (*Client) ListUsagePools

func (c *Client) ListUsagePools(ctx context.Context) ([]UsagePool, error)

ListUsagePools lists every usage pool (GET /usage-pools). Pools are global, not per farm.

func (*Client) ListWorkers

func (c *Client) ListWorkers(ctx context.Context, farmID string, limit, offset int) (Page[Worker], error)

ListWorkers lists workers (GET /workers), optionally of one farm.

func (*Client) Login

func (c *Client) Login(ctx context.Context, user, pass string) (string, error)

Login authenticates with a local account (POST /auth/login). The server answers with a session cookie, which the client keeps and sends on later requests; Login returns the cookie's value.

func (*Client) PauseQueue

func (c *Client) PauseQueue(ctx context.Context, id string, paused bool) error

PauseQueue sets a queue's paused flag. The API has no partial update, so this reads the queue and writes it back whole (GET then PUT /queues/{id}); the run-as identity keys are left out of the PUT, which preserves them.

func (*Client) Ready

func (c *Client) Ready(ctx context.Context) error

Ready returns nil when the server's readiness probe (GET /readyz) answers 200.

func (*Client) RemoveWorker

func (c *Client) RemoveWorker(ctx context.Context, id string) error

RemoveWorker deletes a worker (DELETE /workers/{id}). The server refuses a worker that is not offline, or that still has a task assigned or running.

func (*Client) RetryJob

func (c *Client) RetryJob(ctx context.Context, id string) error

RetryJob revives a job's failed and canceled tasks (POST /jobs/{id}/retry).

func (*Client) RetryingReads

func (c *Client) RetryingReads() *Client

RetryingReads returns a client like c, with its credentials as they are now, that within c's retry budget also retries a GET that fails with a transport error or any 5xx: a read is safe to repeat, so a reader that must not give up on a passing fault (the verifier) needs no retry of its own. Once one read has retried such a failure for the whole budget, the copy stops retrying them, so a server that is down fails the remaining reads promptly; take a new copy for each pass that should start afresh. Other calls keep c's policy, and a call that is never retried still is not.

func (*Client) RevokeWorkerCredential

func (c *Client) RevokeWorkerCredential(ctx context.Context, workerID string) error

RevokeWorkerCredential revokes a worker's broker credential (DELETE /workers/{id}/credential). The server disconnects the worker from the broker before it answers, which can take a few seconds. A worker with no active credential is a 404.

func (*Client) SetWorkerDisabled

func (c *Client) SetWorkerDisabled(ctx context.Context, id string, disabled bool) error

SetWorkerDisabled disables or enables a worker (POST /workers/{id}/disable or /enable).

func (*Client) SubmitJob

func (c *Client) SubmitJob(ctx context.Context, r SubmitRequest) (jobID string, status int, err error)

SubmitJob submits a job (POST /jobs). It is never retried, so a 429 or 503 answer reaches the caller to be counted. It has no deadline of its own: a large job takes the server a long time to create, and giving up would orphan it. The caller's ctx bounds it. It returns the HTTP status of every response so callers can count 422, 429 and 503; a non-2xx status comes with an error carrying the server's message, and a transport error returns status 0.

func (*Client) TaskLogs

func (c *Client) TaskLogs(ctx context.Context, taskID string, after int64, limit int) ([]LogLine, int64, error)

TaskLogs returns the log chunks of a task's latest attempt with nats_seq greater than after (GET /tasks/{id}/logs). The returned cursor is the value to pass as after next time; on an empty page it equals after.

func (*Client) WithoutRetry

func (c *Client) WithoutRetry() *Client

WithoutRetry returns a client for the same server, with c's HTTP client and its credentials as they are now, that never retries a throttled call (see WithRetry).

type Farm

type Farm struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

Farm is a farm.

type Job

type Job struct {
	ID string `json:"id"`
	// Name is the name in the job's template.
	Name       string         `json:"name"`
	Status     string         `json:"status"`
	TaskCounts map[string]int `json:"task_counts"`
	CreatedAt  time.Time      `json:"created_at"`
	UpdatedAt  time.Time      `json:"updated_at"`
}

Job is a job summary or detail.

type LogLine

type LogLine struct {
	ID        string    `json:"id"`
	AttemptID string    `json:"attempt_id"`
	SeqNum    int64     `json:"seq_num"`
	NatsSeq   int64     `json:"nats_seq"`
	Stream    string    `json:"stream"`
	Data      string    `json:"data"`
	At        time.Time `json:"at"`
}

LogLine is one persisted task-log chunk.

type Option

type Option func(*Client)

Option configures New.

func WithAPIKey

func WithAPIKey(key string) Option

WithAPIKey sends "Authorization: Bearer <key>" on every request.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient replaces the default client. The Client applies per-request deadlines itself (30 s, none for SubmitJob or GetRaw), so the http.Client should not set a Timeout of its own.

func WithRetry

func WithRetry(budget time.Duration) Option

WithRetry makes every call but SubmitJob, Ready and GetRaw retry a 429 or 503 answer, waiting as the server's Retry-After says (or backing off from 250 ms to 10 s without one), until the call succeeds, fails otherwise, or would wait past budget in all. The harness's setup, actions, checks and teardown need this because a server's rate limiter answers 429, and an attached server keeps its limiter on. Submissions never retry: a 429 or 503 answer to one is what the run measures. A budget of 0 turns retries off, as for the UI pollers, whose errors are counted.

type Page

type Page[T any] struct {
	Items  []T `json:"items"`
	Total  int `json:"total"`
	Limit  int `json:"limit"`
	Offset int `json:"offset"`
}

Page is one page of a paginated list.

type Queue

type Queue struct {
	ID     string `json:"id"`
	FarmID string `json:"farm_id"`
	Name   string `json:"name"`
}

Queue is a queue.

type SubmitRequest

type SubmitRequest struct {
	FarmID    string
	QueueID   string
	Template  []byte
	DependsOn []string
	Priority  int
}

SubmitRequest describes a job submission. A zero Priority leaves the server default.

type Task

type Task struct {
	ID               string    `json:"id"`
	Status           string    `json:"status"`
	AssignedWorkerID string    `json:"assigned_worker_id"`
	FailureReason    string    `json:"failure_reason"`
	UpdatedAt        time.Time `json:"updated_at"`
}

Task is a task row.

type UsagePool

type UsagePool struct {
	ID            string `json:"id"`
	Name          string `json:"name"`
	MaxConcurrent int    `json:"max_concurrent"`
}

UsagePool is a usage pool.

type WSConn

type WSConn struct {
	// contains filtered or unexported fields
}

WSConn is a connection to /api/v1/ws. A background goroutine reads every frame, so Subscribe and Next may be called from different goroutines.

func DialWS

func DialWS(ctx context.Context, baseURL, apiKey string, opts ...WSOption) (*WSConn, error)

DialWS opens a WebSocket to the server at baseURL, authenticating with apiKey when it is non-empty.

func (*WSConn) Close

func (w *WSConn) Close() error

Close closes the connection and waits for the reader to stop. It is idempotent.

func (*WSConn) Next

func (w *WSConn) Next(ctx context.Context) (ws.Envelope, error)

Next returns the next envelope that is not an ack or a ping; pings are answered internally. Frames received before the connection ended are returned first, then the error that ended it.

func (*WSConn) Subscribe

func (w *WSConn) Subscribe(ctx context.Context, subject string, sinceSeq uint64) error

Subscribe subscribes to subject and waits for the server's ack. A non-zero sinceSeq replays buffered pushes with a greater seq. A refusal (an invalid subject, or one the principal may not read) is returned as an error.

type WSOption

type WSOption func(*websocket.DialOptions)

WSOption configures DialWS.

func WithWSHTTPClient

func WithWSHTTPClient(hc *http.Client) WSOption

WithWSHTTPClient dials with hc, so a wss:// connection trusts hc's CA and presents its client certificate.

type Worker

type Worker struct {
	ID       string `json:"id"`
	FarmID   string `json:"farm_id"`
	QueueID  string `json:"queue_id"`
	Name     string `json:"name"`
	Hostname string `json:"hostname"`
	Status   string `json:"status"`
	// LastHeartbeatAt is when the server last stored a heartbeat from it.
	LastHeartbeatAt time.Time `json:"last_heartbeat_at"`
}

Worker is a registered worker.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL