api

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2026 License: AGPL-3.0 Imports: 42 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 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)

  1. chi Recoverer — catches panics, returns 500, logs stack trace
  2. go-chi/cors — CORS preflight + headers (origins from Config)
  3. chi RequestID — sets X-Request-ID; chi's version generates a UUID when the header is absent
  4. chi Compress — gzip response bodies for clients that accept it
  5. middleware.RequestLogger — structured slog request logging
  6. middleware.RequestMetrics — Prometheus HTTP metrics

/api/v1 sub-router middleware

  1. middleware.APIVersion("1") — sets X-API-Version: 1 on every API response. To mark individual endpoints as deprecated, wrap their handler with middleware.Deprecated.

Note: the structured-logging and metrics middleware are mounted here instead of the now-removed obsServer so every HTTP and WebSocket request continues to be logged and counted.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

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 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. Must never be enabled 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

	// WorkerOfflineThreshold is the heartbeat-timeout window used to decide
	// whether a disabled worker is dead (and thus removable). It mirrors the
	// scheduler's WorkerTimeout. Zero is treated as "no grace" (a disabled
	// worker with any past heartbeat is considered dead).
	WorkerOfflineThreshold time.Duration

	// 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, all three
	// are byte-for-byte unchanged from pre-A1 behavior.
	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 (EXPR sub-project H1's wall-clock
	// backstop). The submission handlers turn it into an absolute instant per
	// request.
	//
	// The zero value means no backstop, which is what a router built without
	// it — every test in this package — gets, and it reproduces the
	// pre-H1 behavior exactly.
	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, so a router built without it
	// behaves exactly as it did before EXPR sub-project H1.
	//
	// NEVER SET [openjd.ExprLimits.Deadline] ON THIS FIELD. It is exported and
	// embedder-settable, and a Config is built once per server: a deadline
	// stored here would be one absolute instant that every later request is
	// measured against, refusing everything once it passed. It is inert today
	// only because [openjd.ValidateWithBudget] overwrites the field from
	// ValidateOptions.Deadline at every call site that matters — a property of
	// those call sites, not a guarantee this type makes. Both handlers that
	// read this field turn the configured DURATION
	// (ExprSubmissionDeadline) into an instant per request instead.
	ExprLimits openjd.ExprLimits
}

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 future task/retry 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 degrades gracefully by accepting 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

	// 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 login behaves exactly as it did before C1.
	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
}

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

type DiagReader interface {
	Query(diag.Filter) []diag.Record
}

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 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. Keeping it an interface — the same reason [jobCanceler] is one, and the same reason Deps.Store is store.Store rather than *sqlite.Store — lets the handlers' error mapping be tested without driving the whole OpenJD pipeline. That mattered most for the one error the pipeline could not produce: while the EXPR extension was StatusInProgress an EXPR template was rejected before any expression was evaluated, so a wall-clock deadline breach was unreachable end to end. Sub-project H2 flipped the status and the real path is now covered directly (submitdeadline_test.go's end-to-end cases); the stub remains the cheap way to pin the status mapping alone.

It is EXPORTED, and Deps.Submitter is typed as it rather than as *openjd.Submitter, so that a test can drive a router built by NewRouter with a recording stub. Without that, nothing could observe the Config → handler hop that carries the submission deadline: the value would reach a real Submitter and vanish into a pipeline that cannot currently spend it.

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.

Jump to

Keyboard shortcuts

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