Documentation
¶
Overview ¶
Package server owns the sqi-server component lifecycle: starting and stopping the store, message bus, scheduler, HTTP server, and mDNS responder in the correct dependency order.
The server owns these components, started and stopped in dependency order:
- store (SQLite, or PostgreSQL when store.driver says so)
- bus (NATS JetStream)
- scheduler
- httpServer (chi router) — REST + WebSocket + UI routes
- discovery (mDNS)
Index ¶
Constants ¶
const ExitDemoted = 75
ExitDemoted is the exit code of a demoted server. It is documented, so a supervisor and its alerting can tell a demotion, after which a restart brings the server back as a standby, from a crash.
const ShutdownTimeout = 30 * time.Second
ShutdownTimeout is the maximum time Server.Run waits for all components to stop cleanly before returning. Components that do not respect context cancellation within this window are abandoned.
Variables ¶
var ErrDemoted error = demotedError{}
ErrDemoted is what Server.Run returns, wrapping the *ha.LostError, when this server lost its leadership and stopped so that its supervisor restarts it as a standby. It names its own exit code, ExitDemoted, through an ExitCode method, which is how the Windows service reports it to the SCM without internal/winsvc importing this package.
Functions ¶
func ExprLimitsFromConfig ¶ added in v0.3.0
func ExprLimitsFromConfig(c config.OpenJDConfig) openjd.ExprLimits
ExprLimitsFromConfig maps the operator's four openjd.expr_* settings onto the value internal/openjd enforces.
It is exported and lives here because this package is the only one that may import both sides: internal/config must not import internal/openjd (two same-level internal packages, and internal/openjd imports internal/store). The four fields are same-typed int64s, so a transposed pair would compile and enforce the wrong bounds; TestExprLimitsFromConfig gives each field a distinct value to catch that.
config.Validate enforces the ranges these values must fall in at startup.
func RemoteBrokerConfig ¶ added in v0.4.0
func RemoteBrokerConfig(c config.NATSConfig) bus.RemoteConfig
RemoteBrokerConfig maps the nats configuration onto the external broker's own view of it. internal/bus does not import internal/config, so the fields are copied one by one. Auth.Lookup is left nil: the caller supplies the store-backed credential lookup.
Types ¶
type BootstrapParams ¶ added in v0.3.0
BootstrapParams are the seed credentials for the first admin, sourced from config.AuthConfig.Bootstrap (SQI_AUTH_BOOTSTRAP_USERNAME / SQI_AUTH_BOOTSTRAP_PASSWORD).
type Config ¶
type Config struct {
// HTTPAddr is the TCP address the REST + WebSocket server listens on.
HTTPAddr string // default "0.0.0.0:8080"
// HTTPTLS terminates HTTPS in-process on the REST/WebSocket listener.
// Zero value leaves it plaintext, which is the default.
HTTPTLS config.TLSConfig
// CORSOrigins is the list of origins that the CORS middleware permits.
// Use ["*"] to allow all origins (suitable for local / dev deployments).
// An empty slice is treated as ["*"]. Tighten this for production
// deployments once the web UI's origin is known.
CORSOrigins []string // default ["*"]
// EnablePprof registers the Go runtime profiling endpoints at
// /debug/pprof/ when true. Should never be enabled on servers accessible
// to untrusted networks. Default false.
EnablePprof bool
// NATS carries the whole nats block: broker mode, worker authentication
// and the embedded and external broker settings. The embedded broker's
// address defaults to all interfaces so that workers discovering the
// server via mDNS can connect at the advertised LAN host; broker
// authentication is opt-in (NATS.Auth.Enabled) and off by default, and
// warnIfBrokerUnauthenticated logs the exposure at startup.
NATS config.NATSConfig
// SQLitePath is the path to the SQLite database file used in simple mode.
// It is created at startup if it does not exist.
SQLitePath string // default "sqi.db"
// CheckpointInterval is how often the background WAL checkpointer runs.
// See internal/config.StoreConfig.CheckpointInterval for semantics.
CheckpointInterval time.Duration // default 5m
// StoreDriver is "sqlite" (default) or "postgres". An empty value means
// sqlite.
StoreDriver string
// PostgresDSN and PostgresMaxConns configure the PostgreSQL store. They
// are used only when StoreDriver is "postgres", in which case SQLitePath
// and CheckpointInterval are not.
PostgresDSN string
PostgresMaxConns int // default 16
// Scheduler holds tuning parameters for the assignment loop, worker
// registry, and heartbeat sweep. Zero values use scheduler.DefaultConfig().
Scheduler scheduler.Config
// DiscoveryEnabled controls whether the mDNS responder advertises this
// server on the local network. Disable in environments that forbid
// multicast (most cloud VPCs). Default true.
DiscoveryEnabled bool
// DiscoveryInterfaces restricts mDNS advertisement to specific interfaces.
// Nil — the production value — advertises on all multicast-capable ones.
// Set by tests to loopback; see internal/discovery.Config.Interfaces.
DiscoveryInterfaces []net.Interface
// DiscoveryInstanceName is the mDNS service instance name advertised on
// the network. Each server on the same subnet should use a distinct name.
// Default "sqi-server".
DiscoveryInstanceName string
// DisableRateLimit turns off per-IP API rate limiting. Only set this in
// tests and benchmarks; never in production.
DisableRateLimit bool
// EnforceOpenJDLimits controls whether quantitative OpenJD limit checks
// (name lengths, element counts, reserved-name rules) are enforced during
// job submission. Default true. Mirror of config.OpenJDConfig.EnforceLimits.
EnforceOpenJDLimits bool
// OpenJDExprLimits bounds what one submitted template may spend inside the
// EXPR expression checker. Mirror of config.OpenJDConfig's four expr_*
// keys, mapped in cmd/sqi-server.
//
// The zero value means "use openjd's defaults", which is what every test
// that constructs a server.Config literal without it gets.
OpenJDExprLimits openjd.ExprLimits
// OpenJDExprSubmissionDeadline is how long the expression checker may work
// on one submission before this server gives up on it and answers 503 — the
// EXPR wall-clock backstop. Mirror of
// config.OpenJDConfig.ExprSubmissionDeadline, mapped in cmd/sqi-server.
//
// A duration, never an instant: the API layer turns it into an absolute
// deadline per request. See openjd.SubmitOptions.Deadline for what goes
// wrong if that conversion is hoisted anywhere that runs once.
//
// The zero value means no backstop, which is what every test that
// constructs a server.Config literal without it gets.
OpenJDExprSubmissionDeadline time.Duration
// PresetLibraryURL is the URL of the community preset library index JSON.
// When empty the /api/v1/presets endpoints respond 503.
// Mirror of config.PresetLibraryConfig.URL.
PresetLibraryURL string
// AuthEnabled mirrors config.AuthConfig.Enabled. When true, start()
// bootstraps the first admin (if needed) and selects the session
// authenticator instead of the anonymous one. Default false.
AuthEnabled bool
// AuthValidateJobOwner mirrors config.AuthConfig.ValidateJobOwner: when
// true, a submit-as owner override must name a known user, else 400.
// Default true.
AuthValidateJobOwner bool
// AuthSessionTTL mirrors config.AuthConfig.Session.TTL: the absolute
// lifetime of sessions minted by POST /auth/login. Only consulted when
// AuthEnabled is true.
AuthSessionTTL time.Duration
// AuthCookieName mirrors config.AuthConfig.Session.CookieName: the
// session cookie name read by the session authenticator and set/cleared
// by the login/logout handlers. Only consulted when AuthEnabled is true.
AuthCookieName string
// AuthCookieSecure mirrors config.AuthConfig.Session.CookieSecure: one of
// "auto", "true", or "false". Only consulted when AuthEnabled is true.
AuthCookieSecure string
// AuthBootstrapUsername mirrors config.AuthConfig.Bootstrap.Username: the
// username for the first admin, seeded once on an empty users table.
AuthBootstrapUsername string
// AuthBootstrapPassword mirrors config.AuthConfig.Bootstrap.Password: the
// plaintext password for the first admin. Never logged; hashed with
// password.Hash before it reaches the store.
AuthBootstrapPassword string
// AuthLDAP mirrors config.AuthConfig.LDAP. It is carried as a nested struct
// rather than flattened into Auth* fields like its siblings, because the
// block is large. Only consulted when AuthEnabled is true.
AuthLDAP config.LDAPConfig
// AuthOIDC mirrors config.AuthConfig.OIDC, carried whole like AuthLDAP. Only consulted when AuthEnabled is true.
AuthOIDC config.OIDCConfig
// SeedDefaults, when true, creates a "default" farm and queue on first
// startup if the store has no farms yet. No-op once any farm exists.
// Default true.
SeedDefaults bool
// Capacity mirrors config.CapacityConfig: the script capacity providers
// and the wake-on-LAN sender. The scheduler runs the providers and sends
// the packets ([schedulerConfig]); the API learns only the providers'
// names ([Server.apiDeps]).
Capacity config.CapacityConfig
// HA mirrors config.HAConfig. With HA.Enabled the server joins a
// high-availability group: it starts as a warm standby and leads only
// while it holds the leader lease (see ha.go). The zero value, as without
// an ha section, is a single server.
HA config.HAConfig
}
Config holds runtime parameters for the server. The serve command derives it from a loaded config.Config; DefaultConfig supplies development defaults.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a Config with sensible development defaults. Production deployments override these via the config file or environment variables.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server coordinates the startup and shutdown of all sqi-server components. It is created by New and driven by [Run].
func New ¶
New creates a Server with the given configuration and logger.
diagBuf is the diagnostic-log ring buffer fed by the server's own logs (via the logger's server sink) and by worker diagnostics (via the scheduler). It must be created before the logger so startup logs are captured; pass nil to disable diagnostics.
func (*Server) Health ¶
Health returns the *health.Registry owned by this server. Components (store, bus) call Health().Register(...) during startup to participate in readiness gating via GET /readyz.
func (*Server) Metrics ¶
Metrics returns the *metrics.Metrics instance owned by this server. Other components (scheduler, bus, store) use it to record observations.
func (*Server) RevokeWorker ¶ added in v0.4.0
RevokeWorker revokes workerID's active broker credential and, when broker authentication is enabled, disconnects it. With broker authentication on, the scheduler leases the worker nothing from then on (scheduler.Scheduler.NoteWorkerRevoked), including a request it parked before the revoke, and the heartbeat sweep returns its in-flight work to ready once its heartbeats stop. It implements api.WorkerRevoker and is what makes DELETE /api/v1/workers/{id}/credential the synchronous revocation path: the offline "sqi-server worker revoke" CLI command writes the same store row from a separate process holding no broker handle, so it takes effect at the worker's next connect; this method runs inside the server process where the broker handle lives, so it can disconnect the worker immediately.
The store is written before the broker is called: once the row is revoked, the auth callout refuses the worker's reconnect, so the disconnect makes the revocation take effect immediately instead of at its user JWT's expiry. A broker failure after a successful store write leaves the worker connected until that expiry at the latest, and it is not trusted again afterwards. The failure is returned to the caller, since the synchronous disconnect did not happen, but the store write is never rolled back.
The broker call runs on a context detached from ctx and bounded by the larger of [revokeBrokerTimeout] and the broker's own bus.Broker.RevokeBudget. bus.Broker.Revoke takes seconds, and its final pass is what closes the window for a connection whose authorization began before the revocation: neither an HTTP client disconnecting mid-request nor a bound shorter than the broker's auth timeout may cut that pass off.
func (*Server) Run ¶
Run starts all server components and blocks until ctx is canceled (typically by a SIGINT or SIGTERM delivered via [signal.NotifyContext]). It then initiates a graceful shutdown and returns once all components have stopped or ShutdownTimeout is exceeded.
A nil return value means the server started and shut down without errors. Startup failures return immediately with a non-nil error.