Documentation
¶
Overview ¶
Package api wires together the sqi-server HTTP surface: the chi router, standard middleware stack, and all route groups.
Router layout ¶
GET /healthz — liveness probe GET /readyz — readiness probe GET /metrics — Prometheus scrape endpoint GET /debug/pprof/* — Go runtime profiling (gated by config) /api/v1/* — REST API GET /api/v1/ws — WebSocket upgrade GET /api/v1/openapi.yaml — OpenAPI 3.1 spec /* — embedded SPA + static assets
Middleware stack (outermost → innermost) ¶
- chi Recoverer — catches panics, returns 500, logs stack trace
- go-chi/cors — CORS preflight + headers (origins from Config)
- chi RequestID — sets X-Request-ID; chi's version generates a UUID when the header is absent
- chi Compress — gzip response bodies for clients that accept it
- middleware.RequestLogger — structured slog request logging
- middleware.RequestMetrics — Prometheus HTTP metrics
/api/v1 sub-router middleware ¶
- middleware.APIVersion("1") — sets X-API-Version: 1 on every API response. To mark individual endpoints as deprecated, wrap their handler with middleware.Deprecated.
The structured-logging and metrics middleware are mounted on this router, so every HTTP and WebSocket request is logged and counted.
Index ¶
- Variables
- func MountProbes(r ProbeRouter, haGroup bool, hr *health.Registry, m *metrics.Metrics)
- func NewRouter(cfg Config, deps Deps, logger *slog.Logger, m *metrics.Metrics, ...) chi.Router
- type CapacityStatusReader
- type Config
- type Deps
- type DiagReader
- type HAGate
- type JobSubmitter
- type PresetLibrary
- type ProbeRouter
- type ServerSelf
- type ServersConfig
- type WorkerRevoker
Constants ¶
This section is empty.
Variables ¶
var ProbePaths = []string{pathHealthz, pathReadyz, pathLeaderz, pathMetrics}
ProbePaths are the paths MountProbes mounts: the probes a supervisor or load balancer reads, and /metrics. A standby serves exactly these (middleware.Standby) and answers everything else 503.
Functions ¶
func MountProbes ¶ added in v0.4.0
MountProbes mounts the probes and /metrics (ProbePaths) on r. /leaderz is the leader probe of a server in a high-availability group (haGroup); outside one it is mounted as a 404, so the web UI's catch-all cannot answer it 200: a load balancer pointed at /leaderz of a server outside a group must not take it for a leader.
func NewRouter ¶
func NewRouter(cfg Config, deps Deps, logger *slog.Logger, m *metrics.Metrics, hr *health.Registry) chi.Router
NewRouter builds and returns the chi router that serves the full sqi-server HTTP surface. The returned router is ready to be handed to http.Server.
Pass a Deps value carrying every application-layer dependency the handlers need; optional ones (Hub, Scheduler, Products) may be nil.
Types ¶
type CapacityStatusReader ¶ added in v0.4.0
type CapacityStatusReader interface {
// CapacityStatus returns the last evaluation of the group, and false when
// there is none: before the first sweep, or when the group is disabled.
CapacityStatus(id string) (capacity.Status, bool)
}
CapacityStatusReader supplies a group's last evaluation. The scheduler satisfies it. The returned status shares its slices with the evaluation that produced it: treat them as read-only.
type Config ¶
type Config struct {
// CORSOrigins is the list of origins the CORS middleware allows.
// Use ["*"] to permit all origins (suitable for local/dev deployments).
// Defaults to ["*"] when empty.
CORSOrigins []string
// EnablePprof registers Go runtime profiling endpoints at /debug/pprof/
// when true. Do not enable it on servers exposed to untrusted networks.
EnablePprof bool
// DisableRateLimit turns off per-IP rate limiting when true.
// Use in tests and benchmarks where the loopback address would cause all
// concurrent requests to share one bucket and trigger 429s.
DisableRateLimit bool
// AuthEnabled reflects config.AuthConfig.Enabled. When true, the session
// cookie is in play and this router activates the browser-security
// surface it requires: CORS AllowCredentials, the Origin-based CSRF guard
// on the authenticated route group, and WebSocket Origin enforcement
// (OriginPatterns instead of InsecureSkipVerify). When false, none of
// the three is active.
AuthEnabled bool
// ValidateJobOwner mirrors config.AuthConfig.ValidateJobOwner: when true,
// a submit-as owner override on POST /jobs and POST /products/{name}/jobs
// must name a known user, else 400. Default true.
ValidateJobOwner bool
// ExprSubmissionDeadline mirrors config.OpenJDConfig.ExprSubmissionDeadline:
// how long the OpenJD expression checker may work on one submission before
// this server gives up and answers 503 (the wall-clock backstop). The
// submission handlers turn it into an absolute instant per request.
//
// The zero value means no backstop.
ExprSubmissionDeadline time.Duration
// ExprLimits mirrors the operator's four openjd.expr_* settings, for the
// routes that validate an OpenJD template without going through the
// Submitter: POST/PUT /api/v1/products (a client-supplied body) and
// GET /api/v1/presets/{name} + POST /api/v1/presets/{name}/install (a
// sha256-pinned body from the operator's index). Every other production
// path reads these off the Submitter built at boot.
//
// The zero value means openjd's defaults.
//
// Leave [openjd.ExprLimits.Deadline] unset on this field. A Config is built
// once per server, so a deadline stored here would be one absolute instant
// that every later request is measured against, and every request would be
// refused once it passed. [openjd.ValidateWithBudget] overwrites the field
// from ValidateOptions.Deadline, and both handlers that read this field
// turn ExprSubmissionDeadline into an instant per request.
ExprLimits openjd.ExprLimits
// HA is set on a server in a high-availability group: GET /leaderz is
// mounted, and while the server is a standby every route other than the
// probes and /metrics answers 503 naming the leader. Nil, as without HA,
// mounts no /leaderz (404) and gates nothing.
HA *HAGate
}
Config holds HTTP-layer configuration for NewRouter.
type Deps ¶
type Deps struct {
// Store provides access to all persistent state (jobs, tasks, workers, …).
Store store.Store
// Submitter handles the full OpenJD parse → validate → persist pipeline
// used by POST /api/v1/jobs. Production always supplies an
// *openjd.Submitter; it is typed as the interface so a test can substitute
// a recording stub — see [JobSubmitter] for why that matters.
Submitter JobSubmitter
// Scheduler is the running scheduler instance. It is called by
// DELETE /api/v1/jobs/{id} to propagate cancellation to workers
// and by the task retry and cancel endpoints.
Scheduler *scheduler.Scheduler
// Hub is the WebSocket fan-out hub used by the /api/v1/ws handler.
// May be nil in tests that do not exercise WebSocket push;
// the handler then accepts subscriptions without delivering any pushes.
Hub *ws.Hub
// DiagReader exposes the in-memory diagnostic log buffer to
// GET /api/v1/diagnostics/logs. It is nil-tolerant: when nil (diagnostics
// disabled) the endpoint responds with 503.
DiagReader DiagReader
// Products is the product catalog (built-ins + stored), used by the
// /api/v1/products endpoints. Required for product routes.
Products *product.Catalog
// PresetLib is the community preset library client used by the
// /api/v1/presets endpoints. Nil-tolerant: when nil or unconfigured the
// endpoints respond 503.
PresetLib PresetLibrary
// Servers describes this server and its high-availability group for
// GET /api/v1/servers. The zero value is acceptable: the endpoint then
// reports one server with no identity, as a farm without HA does.
Servers ServersConfig
// Version is the server build metadata reported by GET /api/v1/version.
// The zero value is acceptable (fields default to empty strings).
Version version.Info
// Auth authenticates each REST request and the WebSocket upgrade. Nil is
// treated as auth.Anonymous() (auth disabled): every request is the
// anonymous superuser principal and behavior is unchanged.
Auth auth.Authenticator
// SessionTTL is the absolute lifetime of sessions minted by
// POST /api/v1/auth/login. Mirrors config.AuthConfig.Session.TTL.
SessionTTL time.Duration
// CookieName is the session cookie name set by login and cleared by
// logout. Mirrors config.AuthConfig.Session.CookieName; must match the
// name the Auth authenticator (e.g. session.Authenticator) reads.
CookieName string
// CookieSecure controls the session cookie's Secure attribute: "auto"
// (Secure when the request is TLS or carries X-Forwarded-Proto: https),
// "true", or "false". Mirrors config.AuthConfig.Session.CookieSecure.
CookieSecure string
// LDAPVerifier authenticates accounts whose AuthSource is
// store.AuthSourceLDAP. Nil when directory auth is disabled, in which
// case only local accounts can log in.
LDAPVerifier ldap.Verifier
// LDAPConfig supplies the role mapping and role-source mode. Only read
// when LDAPVerifier is non-nil.
LDAPConfig ldap.Config
// OIDCProvider authenticates SSO logins. Nil when SSO is disabled, in
// which case the /auth/oidc/* routes are not registered at all.
OIDCProvider oidc.Provider
// OIDCConfig supplies claim names, role mapping, and the reauth/logout
// modes. Only read when OIDCProvider is non-nil.
OIDCConfig oidc.Config
// OIDCStateKey signs the per-login state cookie. Generated per boot by
// the server, never persisted: a restart invalidating in-flight logins is
// cheaper than a key to configure, distribute, and rotate. Only read when
// OIDCProvider is non-nil.
OIDCStateKey []byte
// NATSAuthEnabled mirrors config.NATSAuthConfig.Enabled: the broker
// requires a per-worker nkey credential. POST /api/v1/workers/enroll is
// mounted only when this and NATSAuthEnrollmentEndpointEnabled are both
// true: with broker auth off there is no credential for it to issue, and
// an operator who wants no self-service enrollment surface can turn
// EnrollmentEndpointEnabled off independently.
NATSAuthEnabled bool
// NATSAuthEnrollmentEndpointEnabled mirrors
// config.NATSAuthConfig.EnrollmentEndpointEnabled. See NATSAuthEnabled.
NATSAuthEnrollmentEndpointEnabled bool
// JoinTokenTTL is how long a join token minted by
// POST /api/v1/workers/join-tokens remains valid. Mirrors
// config.NATSAuthConfig.JoinTokenTTL, which is bounds-checked at config
// load; this handler does not re-validate it.
JoinTokenTTL time.Duration
// JoinTokenSingleUse consumes a join token on its first successful
// enrollment, rejecting a second attempt with the same token. Mirrors
// config.NATSAuthConfig.JoinTokenSingleUse.
JoinTokenSingleUse bool
// WorkerRevoker handles DELETE /api/v1/workers/{id}/credential. Required
// on any router that mounts REST resource routes — that route is always
// registered, regardless of NATSAuthEnabled, so a nil value panics the
// first time it is called. Production supplies *server.Server, which
// revokes in the store and then disconnects the worker from the broker;
// this package depends only on the [WorkerRevoker] interface, never on
// internal/bus or internal/server.
WorkerRevoker WorkerRevoker
// CapacityStatus supplies each capacity group's last evaluation for the
// /api/v1/capacity-groups endpoints. Nil-tolerant: with none, every
// group's status is null. Production supplies the scheduler.
CapacityStatus CapacityStatusReader
// CapacityProviderNames are the script capacity providers the server's
// configuration defines (capacity.providers), by bare name: "aws" here is
// what a group names as "script:aws". Only the names reach the API; a
// provider's command, environment and timeout never do. A group may name
// only a configured script provider, and GET /capacity-providers lists
// them. Nil means none.
CapacityProviderNames []string
}
Deps holds the application-layer dependencies injected into the REST handlers. All fields are required; a nil field will cause a panic when the corresponding endpoint is first called.
type DiagReader ¶
DiagReader is the read-only view of the diagnostic log buffer the handler depends on. *diag.Buffer satisfies it. When diagnostics are disabled the server injects a nil reader, in which case the endpoint returns 503.
type HAGate ¶ added in v0.4.0
type HAGate struct {
// IsLeader reports whether this server currently leads.
IsLeader func() bool
// LeaderName names the server leading, "" when none is known.
LeaderName func() string
}
HAGate is how the router asks a server in a high-availability group for its role, on every request.
type JobSubmitter ¶ added in v0.3.0
type JobSubmitter interface {
Submit(
ctx context.Context, rawTemplate string, format store.TemplateFormat, opts openjd.SubmitOptions,
) (*openjd.SubmitResult, error)
}
JobSubmitter is the subset of openjd.Submitter the submission handlers use. It is an interface so tests can stub the OpenJD pipeline to check the handlers' error mapping. It is exported because Deps.Submitter has this type rather than *openjd.Submitter, which lets a test drive a router built by NewRouter with a recording stub and observe the submission deadline passed from Config to the handler.
type PresetLibrary ¶ added in v0.2.0
type PresetLibrary interface {
Configured() bool
FetchIndex(ctx context.Context, forceRefresh bool) ([]presetlib.IndexEntry, error)
FetchDefinition(
ctx context.Context, entry presetlib.IndexEntry, opts product.ValidateOptions,
) (store.Product, error)
}
PresetLibrary is the subset of *presetlib.Service the preset handlers use. Nil (or an unconfigured library) makes every preset endpoint respond 503.
type ProbeRouter ¶ added in v0.4.0
type ProbeRouter interface {
Get(pattern string, h http.HandlerFunc)
Handle(pattern string, h http.Handler)
}
ProbeRouter is what MountProbes mounts on. A chi.Router is one; Get registers a GET-only route, Handle one for every method.
type ServerSelf ¶ added in v0.4.0
type ServerSelf struct {
InstanceID string
Name string
Host string
PID int
Version string
StartedAt time.Time
}
ServerSelf is a server's own identity, for a farm without HA.
type ServersConfig ¶ added in v0.4.0
type ServersConfig struct {
// HA is set on a server in a high-availability group: the response then
// lists the group's members from the database. Unset, the response is
// Self alone and the database is not read.
HA bool
// LeaseTTL is the group's ha.lease_ttl, which decides whether a member
// counts as seen and whether its broker is working. Only read with HA.
LeaseTTL time.Duration
// Self is this server, reported as the leader when HA is unset.
Self ServerSelf
}
ServersConfig is what GET /api/v1/servers needs to know about the server serving it. The zero value describes a single server with no identity, which is what a router built without HA and without this field reports.
type WorkerRevoker ¶ added in v0.4.0
type WorkerRevoker interface {
// RevokeWorker revokes workerID's active credential. It returns
// [store.ErrNotFound] if the worker has no active credential — never
// enrolled, or already revoked; those two cases are indistinguishable
// here for the same reason store.RevokeWorkerCredential collapses them.
RevokeWorker(ctx context.Context, workerID string) error
}
WorkerRevoker revokes a worker's broker credential and, when the implementation holds a live broker handle, disconnects it and lets the heartbeat-sweep/reclaim path return its in-flight work to ready. internal/api depends only on this interface so that DELETE /api/v1/workers/{id}/credential can be synchronous where a broker handle is available (internal/server, which runs in the same process) without this package importing internal/bus or internal/server.
Source Files
¶
- apikeys.go
- apikeys_admin.go
- auth.go
- authproviders.go
- authz.go
- capacity_groups.go
- compute_locations.go
- diagnostics.go
- errors.go
- estimate.go
- externallogin.go
- farms.go
- jobs.go
- jobscope.go
- ldaplogin.go
- oidclogin.go
- openapi.go
- params.go
- presets.go
- products.go
- queues.go
- retryoverrides.go
- router.go
- selfservice.go
- servers.go
- storage_locations.go
- submitidentity.go
- tasks.go
- usage_pools.go
- users.go
- version.go
- workerenroll.go
- workers.go
- ws.go