server

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: 31 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 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)
  • bus (NATS JetStream)
  • scheduler
  • httpServer (chi router) — REST + WebSocket + UI routes
  • discovery (mDNS)

Index

Constants

View Source
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

This section is empty.

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 actually enforces (EXPR sub-project E4d).

It lives here, and is exported, for one reason: this package is the ONLY one that may see both sides. internal/config must not import internal/openjd (a cross-import between two same-level internal packages, and internal/openjd pulls in internal/store), so the mapping cannot live next to either definition -- and left inline in cmd/sqi-server's Config literal it would be four assignments between four same-typed int64 fields with nothing testing that they are paired correctly. Transposing two of them would compile, start, and quietly enforce the wrong bounds. TestExprLimitsFromConfig gives each field a distinct value precisely to catch that.

The ranges these values must fall in are enforced by config.Validate at startup, not here: by the time this runs the configuration has already been accepted or the process has already exited.

Types

type BootstrapParams added in v0.3.0

type BootstrapParams struct {
	Username string
	Password string
}

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"

	// 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

	// NATSAddr is the TCP address the embedded NATS server listens on.
	// It defaults to all interfaces so that workers discovering the server
	// via mDNS can connect to NATS at the advertised LAN host. (Broker
	// authentication does not exist: any host that can reach this port can
	// register as a worker and receive assignments. Deferred to Phase 4.)
	NATSAddr string // default "0.0.0.0:4222"

	// NATSDataDir is the directory used by JetStream for file-backed stream
	// storage. It is created at startup if it does not exist.
	NATSDataDir string // default "data/nats"

	// NATSMaxStoreMB is the maximum disk space JetStream may use, in
	// megabytes.  0 means unlimited (not recommended for production).
	NATSMaxStoreMB int // default 1024

	// 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

	// 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

	// 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 — EXPR sub-project E4d. Mirror of
	// config.OpenJDConfig's four expr_* keys, mapped in cmd/sqi-server.
	//
	// The ZERO VALUE means "use openjd's defaults", so a Config built without
	// it (every test in this repo that constructs a server.Config literal)
	// behaves exactly as it did before this field existed.
	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 —
	// EXPR sub-project H1's 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, so a Config built without it (every
	// test in this repo that constructs a server.Config literal) behaves
	// exactly as it did before this field existed.
	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. Carried as a nested struct
	// rather than flattened into Auth* fields like its siblings: the block
	// has seventeen fields, and flattening them would bury the rest of this
	// struct. Only consulted when AuthEnabled is true.
	AuthLDAP config.LDAPConfig

	// AuthOIDC mirrors config.AuthConfig.OIDC, carried whole for the same
	// reason as AuthLDAP above. 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
}

Config holds runtime parameters for the server.

This struct is a stand-in used by the serve subcommand; the serve subcommand can also load a config.Config and derive a Config from it rather than using 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

func New(cfg Config, logger *slog.Logger, diagBuf *diag.Buffer) *Server

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

func (s *Server) Health() *health.Registry

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

func (s *Server) Metrics() *metrics.Metrics

Metrics returns the *metrics.Metrics instance owned by this server. Other components (scheduler, bus, store) use it to record observations.

func (*Server) Run

func (s *Server) Run(ctx context.Context) error

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.

Jump to

Keyboard shortcuts

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