Documentation
¶
Index ¶
- func LoadEnvFiles()
- func ProfileBanner() string
- func ResolveSecretEnv(name string) (string, error)
- func SystemConfigPaths() []string
- func UserConfigPath() string
- func ValidateCORS(c CORSConfig) error
- func ValidateCallout(c CalloutConfig) error
- func ValidateDispatch(c cluster.Config) error
- func ValidateGRPCKeepAlive(c GRPCConfig) error
- func ValidateHTTP(c HTTPConfig) error
- func ValidateIAM(iam IAMConfig) error
- func ValidateScheduler(c SchedulerConfig) error
- func ValidateSearchAsync(c SearchAsyncConfig) error
- func ValidateSearchJobHeartbeat(interval time.Duration) error
- func ValidateSearchJobMaxAttempts(n int) error
- func ValidateSearchJobStaleAfter(staleAfter, interval time.Duration) error
- func ValidateSearchSnapshot(ttl, reapInterval time.Duration) error
- type AdminConfig
- type App
- func (a *App) AuthService() *auth.AuthService
- func (a *App) AuthenticationService() contract.AuthenticationService
- func (a *App) Close() error
- func (a *App) DrainScheduler(ctx context.Context)
- func (a *App) GRPCServer() *internalgrpc.Server
- func (a *App) Handler() http.Handler
- func (a *App) MemberRegistry() *internalgrpc.MemberRegistry
- func (a *App) NodeRegistry() contract.NodeRegistry
- func (a *App) ReadinessCheck() error
- func (a *App) SearchService() *search.SearchService
- func (a *App) Shutdown()
- func (a *App) StopGRPC()
- func (a *App) StoreFactory() spi.StoreFactory
- func (a *App) TokenSigner() *token.Signer
- func (a *App) TransactionManager() spi.TransactionManager
- func (a *App) WorkflowEngine() *workflow.Engine
- type CORSConfig
- type CalloutConfig
- type Config
- type GRPCConfig
- type HTTPConfig
- type IAMConfig
- type JWTSettings
- type SchedulerConfig
- type SearchAsyncConfig
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func LoadEnvFiles ¶
func LoadEnvFiles()
LoadEnvFiles loads environment variables from .env files using a profile-based layering system inspired by Spring's spring.profiles.active.
Loading order (later values override earlier; shell env always wins):
- System config (per OS) — lowest precedence among loaded files
- User config (per OS)
- CWD .env
- CWD .env.{profile} in declaration order
- Shell environment — never overridden
Profiles are specified via CYODA_PROFILES (comma-separated). Example: CYODA_PROFILES=postgres,otel loads .env, .env.postgres, .env.otel.
Missing files are silently skipped.
func ProfileBanner ¶
func ProfileBanner() string
ProfileBanner returns a human-readable string for the startup banner.
func ResolveSecretEnv ¶
Mirrors plugins/postgres.resolveSecretWith (separate go.mod; keep behavior in sync). Exported so cmd/cyoda can share the same _FILE resolution (including trailing-whitespace trim) without duplicating the logic.
ResolveSecretEnv returns the contents of the file at the path given by <name>_FILE when that env var is set, and otherwise the value of the named env var. <name>_FILE wins whenever it is set, whatever <name> holds. The _FILE path is the canonical Docker/Kubernetes pattern for passing credentials without exposing them in `env` output.
Trailing whitespace (spaces, tabs, \n, \r) is stripped from file contents — safe for both DSN strings and multi-line PEM keys. A file whose contents trim to empty yields an empty value, with no fallback to <name>; the caller's normal downstream validation reports the real problem.
Errors: returned only when <name>_FILE points at a path that cannot be read. Silent fallthrough to empty would let a typo'd path look like a missing credential, which is hard to debug.
func SystemConfigPaths ¶
func SystemConfigPaths() []string
SystemConfigPaths returns the OS-appropriate system-wide cyoda config paths (not necessarily existing on disk). macOS returns an empty slice by design — Homebrew formulas cannot cleanly write to a system path.
func UserConfigPath ¶
func UserConfigPath() string
UserConfigPath returns the OS-appropriate path to the per-user cyoda config file (not necessarily existing on disk). Callers: LoadEnvFiles (for autoload) and the 'cyoda init' subcommand (to know where to write). Returns "" if the user home directory cannot be determined and the relevant OS env var is unset.
func ValidateCORS ¶
func ValidateCORS(c CORSConfig) error
ValidateCORS verifies the CORS configuration. Checked by Config.Validate at startup, and returns an error for any invalid origin or mode combination. A non-nil return causes the binary to slog the error and os.Exit(1).
Validation rules (full set):
- Wildcard==true and AllowedOrigins non-empty is a programming error (parser rejects this earlier; defensive check here).
- Each origin in AllowedOrigins must be a valid RFC 6454 origin: scheme + host + optional non-default port; no userinfo, path, query, fragment, or trailing slash; lowercase scheme and host; no non-ASCII characters in host (use punycode); not the literal string "null"; not the literal "*" (use Wildcard mode).
func ValidateCallout ¶
func ValidateCallout(c CalloutConfig) error
ValidateCallout rejects callout settings no callout could be run under. Config is a QA'd artefact: an out-of-range value is a hard startup error, not a clamp. A default answer limit above the upper bound is rejected because import would then refuse a workflow that merely spells out the default.
func ValidateDispatch ¶
ValidateDispatch rejects peer-call durations that cannot be honoured. The patience may be zero (waiting disabled) but not negative; the connect timeout bounds a network call and must be positive; the proxy timeout bounds a proxied request, a platform clock confirmation round and each status ask of the cluster status read (half of it the database check), and must be positive. They are checked whether or not clustering is enabled: a value that would fail the moment clustering is switched on is a configuration error today.
func ValidateGRPCKeepAlive ¶
func ValidateGRPCKeepAlive(c GRPCConfig) error
ValidateGRPCKeepAlive rejects a keep-alive interval or timeout that is not positive. Both drive tickers and transport deadlines; zero or negative would panic the ticker or disable eviction, neither of which is a configuration anyone means. Config is a QA'd artefact: an invalid value is a startup error.
func ValidateHTTP ¶
func ValidateHTTP(c HTTPConfig) error
ValidateHTTP rejects a negative timeout; zero means disabled. The fields are walked as a slice, not a map, so that a config with more than one negative value always names the same one — a map's iteration order would make the startup error differ between runs of the same binary on the same configuration.
func ValidateIAM ¶
ValidateIAM enforces startup-time IAM correctness. When CYODA_REQUIRE_JWT is set, mock mode is rejected and the signing key must be present. In JWT mode (regardless of RequireJWT) IAMFeatures are validated so that invalid env values for TrustedKeyMaxPerTenant, MaxValidityDays, etc. fail startup rather than being silently ignored. Called from Config.Validate, which New runs before wiring auth.
func ValidateScheduler ¶
func ValidateScheduler(c SchedulerConfig) error
ValidateScheduler rejects scheduler settings no scheduler could run under. Config is a QA'd artefact: an out-of-range value is a startup error, not a clamp. STALE_AFTER must leave the watchdog room for one slow or failed heartbeat, so it grows with the heartbeat interval.
func ValidateSearchAsync ¶
func ValidateSearchAsync(c SearchAsyncConfig) error
ValidateSearchAsync enforces startup-time correctness for the async-search worker pool sizing. Checked by Config.Validate at startup; a non-nil return causes the binary to slog the error and os.Exit(1).
Config is a QA'd artefact, not runtime input: an invalid value is a hard error here rather than silently clamped to the default the way CYODA_STATS_GROUP_MAX / CYODA_SEARCH_MAX_SORT_KEYS are (those predate this policy). Workers < 1 would start a pool with zero goroutines draining the queue — every Submit would eventually return ErrQueueFull once the buffer fills, with nothing ever running. QueueLen < 0 panics inside make(chan jobFunc, n). MaxPerTenant < 0 is neither a cap nor the documented disable sentinel (0), so it is rejected rather than guessed at.
func ValidateSearchJobHeartbeat ¶
ValidateSearchJobHeartbeat enforces startup-time correctness for CYODA_SEARCH_JOB_HEARTBEAT_INTERVAL. Checked by Config.Validate at startup; a non-nil return causes the binary to slog the error and os.Exit(1).
Config is a QA'd artefact, not runtime input: a non-positive interval is a hard startup error rather than silently clamped to the default, matching ValidateSearchAsync's policy. time.NewTicker panics on a non-positive duration, so this guards a startup crash, not just a slow default.
func ValidateSearchJobMaxAttempts ¶
ValidateSearchJobMaxAttempts rejects a cap below 1. Config is a QA'd artefact: an invalid value is a hard startup error, not a clamp. A cap of 1 disables re-execution (a job is failed on its first executor loss); anything below 1 would fail a job before it ever ran.
func ValidateSearchJobStaleAfter ¶
ValidateSearchJobStaleAfter enforces startup-time correctness for CYODA_SEARCH_JOB_STALE_AFTER against CYODA_SEARCH_JOB_HEARTBEAT_INTERVAL. Checked by Config.Validate at startup, after ValidateSearchJobHeartbeat has already rejected a non-positive interval; a non-nil return causes the binary to slog the error and os.Exit(1).
Config is a QA'd artefact: the interval « staleAfter invariant (spi.AsyncSearchStore.ClaimStale's doc comment) is made mechanically checkable here rather than left as a documentation-only convention — staleAfter < 4×interval is a hard startup error, not silently accepted.
func ValidateSearchSnapshot ¶
ValidateSearchSnapshot rejects a non-positive snapshot TTL or reap interval. A finished job is readable for the TTL, and its expirationDate reports it, so a non-positive one has no meaning. time.NewTicker panics on a non-positive reap interval.
Types ¶
type AdminConfig ¶
type AdminConfig struct {
Port int
BindAddress string
// MetricsRequireAuth (CYODA_METRICS_REQUIRE_AUTH) makes bearer auth
// on /metrics mandatory at startup. Coupled predicate with
// MetricsBearerToken — startup fails if required but token is empty.
// Default false; the Helm chart sets it true.
MetricsRequireAuth bool
// MetricsBearerToken (CYODA_METRICS_BEARER, with _FILE suffix
// support) is the static Bearer token required on GET /metrics when
// non-empty. /livez and /readyz stay unauth regardless.
MetricsBearerToken string
}
type App ¶
type App struct {
// contains filtered or unexported fields
}
func (*App) AuthService ¶
func (a *App) AuthService() *auth.AuthService
AuthService returns the underlying *auth.AuthService when JWT IAM mode is active, or nil when running in mock IAM mode. Exposed for tests that inspect the auth stores.
func (*App) AuthenticationService ¶
func (a *App) AuthenticationService() contract.AuthenticationService
func (*App) Close ¶
Close performs graceful shutdown of all backend resources.
Close is the single teardown path for storeFactory and the gRPC server; Shutdown only releases background goroutines and cluster registration. Order: storage first, then gRPC. The gRPC server can block waiting on in-flight streams, so we want pools released before that blocks.
gRPC is stopped via GracefulStop bounded by gRPCGracefulStopBudget; if the budget elapses without graceful completion (a stuck stream, a non-cooperative client) we fall back to a hard Stop and emit a slog.Warn so operators can see the budget was hit.
func (*App) DrainScheduler ¶
DrainScheduler runs the scheduler's shutdown steps 1-5. The binary calls it on a signal before the servers drain, so runs still in progress keep their compute-node streams and callback routes. Shutdown and Close drain it again; every call after the first does nothing. It also sets the node to DRAINING.
func (*App) GRPCServer ¶
func (a *App) GRPCServer() *internalgrpc.Server
func (*App) MemberRegistry ¶
func (a *App) MemberRegistry() *internalgrpc.MemberRegistry
func (*App) NodeRegistry ¶
func (a *App) NodeRegistry() contract.NodeRegistry
func (*App) ReadinessCheck ¶
ReadinessCheck returns nil when the instance is ready to serve external traffic. Called synchronously by the /readyz admin endpoint on every probe — keep it cheap; each condition below is a pointer test or a short mutex-guarded read, and none performs I/O.
Three conditions fail it independently, and the returned reasons differ so the admin handler's server-side log tells an operator which fired:
- Storage is not initialized. A defensive guard rather than a live window: cmd/cyoda builds the admin listener from an App that New() has already returned, so a probe never observes it. It costs nothing and keeps the check honest for any other caller.
- A panic was recovered on some door. The node's state is then unverified, so it must stop receiving traffic — fail closed. Nothing resets the latch.
- Shutdown has begun and the node is draining. Readiness fails from the start of the drain so load balancers stop sending new requests; GET /health stays on the latch alone. When the latch has also tripped, its reason is returned.
What failing readiness achieves is bounded: Kubernetes drops the pod from the client-facing Service, so new client connections stop. Peers resolve each other through the gossip registry rather than the Service, so forwarded work keeps arriving, and /livez is deliberately unaffected so a deterministic panic does not become a restart loop. Replacing a drained node is an operator action.
func (*App) SearchService ¶
func (a *App) SearchService() *search.SearchService
func (*App) Shutdown ¶
func (a *App) Shutdown()
Shutdown performs graceful cleanup of background goroutines and cluster resources. The storeFactory is intentionally NOT closed here — Close() is the single teardown path for that, so callers invoking Shutdown() followed by Close() (the runServers sequence) close the factory exactly once. It also sets the node to DRAINING.
func (*App) StopGRPC ¶
func (a *App) StopGRPC()
StopGRPC drains the gRPC server with a deadline-bounded graceful-stop (gRPCGracefulStopBudget). The drain runs at most once across the lifetime of the App via sync.Once — runServers' watcher invokes this when rootCtx cancels, and Close() calls it again as a belt-and-braces teardown. Without the once, a stuck stream could burn up to 2× the budget across the runServers + Close layers.
func (*App) StoreFactory ¶
func (a *App) StoreFactory() spi.StoreFactory
func (*App) TokenSigner ¶
func (*App) TransactionManager ¶
func (a *App) TransactionManager() spi.TransactionManager
func (*App) WorkflowEngine ¶
type CORSConfig ¶
type CORSConfig struct {
Enabled bool // CYODA_CORS_ENABLED, default true
Wildcard bool // derived: true iff CYODA_CORS_ALLOWED_ORIGINS=="*"
AllowedOrigins []string // populated only in allowlist mode (Wildcard==false, len > 0)
}
CORSConfig controls cross-origin resource sharing for the public HTTP surface. See cmd/cyoda/help/content/config/cors.md for full operator-facing documentation.
Modes (mutually exclusive):
- Disabled: Enabled=false. Middleware is not installed; deployers handle CORS at an upstream ingress. OPTIONS returns chi default 405.
- Wildcard: Wildcard=true (CYODA_CORS_ALLOWED_ORIGINS=*). The literal "*" is emitted in Access-Control-Allow-Origin.
- Allowlist: AllowedOrigins is non-empty. Exact-match only.
- Loopback: Enabled=true and AllowedOrigins is empty and Wildcard is false. Default mode. Allows http(s)://localhost, 127.0.0.1, [::1] on any port.
func (CORSConfig) Mode ¶
func (c CORSConfig) Mode() string
Mode returns a human-readable label describing the CORS mode this config resolves to. Values: "disabled", "loopback", "wildcard", "allowlist".
type CalloutConfig ¶
type CalloutConfig struct {
// FixedNumRetries is the number of retries after the first try for a
// callout whose retryPolicy is FIXED or unset; NONE always means one try.
// CYODA_RETRY_FIXED_NUM_RETRIES, default 3, must be >= 0.
FixedNumRetries int
// ResponseTimeout is the answer limit used when the workflow author set no
// positive responseTimeoutMs on the callout.
// CYODA_CALLOUT_RESPONSE_TIMEOUT_MS, default 30000, must be >= 1 and no
// larger than ResponseTimeoutMax.
ResponseTimeout time.Duration
// ResponseTimeoutMax is the largest responseTimeoutMs a workflow may carry.
// Workflow import refuses a larger value; a stored workflow whose value
// exceeds a bound lowered after import fails its callout rather than
// being clamped. CYODA_CALLOUT_RESPONSE_TIMEOUT_MAX_MS, default 60000,
// must be >= 1.
ResponseTimeoutMax time.Duration
// HandoverAllowance is what the owner allows a hand-over to another node
// on top of (tries left × answer limit), and the last term of a callout's
// deadline. CYODA_CALLOUT_HANDOVER_ALLOWANCE, default 30s, must be > 0.
HandoverAllowance time.Duration
// PassAllowance is how long a pass outlives its try's answer limit: the
// margin for routing a callback and for clocks that differ between nodes.
// CYODA_CALLOUT_PASS_ALLOWANCE, default 30s, must be > 0.
PassAllowance time.Duration
// JoinedResponseMaxBytes is the most a compute member's callback may
// answer with while it holds its transaction's gate — the owner's next
// move waits behind those bytes. An answer past it fails the callback with
// 413 JOINED_RESPONSE_TOO_LARGE rather than being cut short.
// CYODA_CALLOUT_JOINED_RESPONSE_MAX_BYTES, default 10485760 (10 MiB),
// must be > 0.
JoinedResponseMaxBytes int
// JoinedMaxWaiters is how many of a compute member's callbacks may queue
// for one transaction behind the callback that holds it. Callbacks of one
// transaction are served one at a time, so a member that fires many at once
// buys no speed by it. Past the cap a callback is refused with
// 503 TOO_MANY_JOINED_REQUESTS, retryable.
//
// It bounds the queue's LENGTH, not its bytes. The cap is read before a
// callback's body is, so a refusal costs no buffer, but the reading
// reserves nothing — callbacks that arrive together can all pass it — and
// each then buffers its whole request, up to httpmw's compile-time 10 MiB,
// before it queues. The request side has no setting, and the queue has no
// byte ceiling: at this default, 10 MiB bodies reach a gigabyte for one
// transaction. JoinedResponseMaxBytes bounds the answers, not these.
// CYODA_CALLOUT_JOINED_MAX_WAITERS, default 128, must be > 0 — there is no
// "unlimited" value, an unbounded queue being what the cap exists to
// prevent.
JoinedMaxWaiters int
}
CalloutConfig holds the server-side settings of a compute-node callout (a processor, criterion or function request).
type Config ¶
type Config struct {
HTTPPort int
HTTP HTTPConfig
ContextPath string
ErrorResponseMode string
MaxStateVisits int
LogLevel string
// Version is the ldflag-injected binary version string reported in the
// REST /help payload. Defaults to "dev" when unset.
Version string
IAM IAMConfig
GRPC GRPCConfig
Admin AdminConfig
CORS CORSConfig
StorageBackend string
// ClockControlEnabled builds the controllable test clock, gives it to the
// storage plugin and every business-time reader, and accepts POST
// /platform/clock. A test feature: CYODA_CLOCK_CONTROL_ENABLED, default
// false.
ClockControlEnabled bool
StartupTimeout time.Duration
Cluster cluster.Config
SearchSnapshotTTL time.Duration
SearchReapInterval time.Duration
// ModelCacheLease is the baseline TTL for cached LOCKED model
// descriptors: the bound on a stale entry when a model.invalidate
// broadcast is lost. Actual expiry is jittered ±10% to prevent cross-
// node herding. Defaults to 5m; tune via CYODA_MODEL_CACHE_LEASE.
ModelCacheLease time.Duration
OTelEnabled bool
// ExternalProcessing overrides the default gRPC processor dispatcher.
// Used in tests to inject a LocalProcessingService.
ExternalProcessing contract.ExternalProcessingService
// StatsGroupMax is the cardinality ceiling for grouped-stats results
// (POST /api/entity/stats/{entityName}/{modelVersion}/query). When the
// service produces more distinct groupKey combinations than this value,
// the request fails with 422 GROUP_CARDINALITY_EXCEEDED. Defaults to
// 10000; tune via CYODA_STATS_GROUP_MAX. See spec D2.
StatsGroupMax int
// SearchMaxSortKeys caps the number of sort keys per search request.
// Defaults to 16; tune via CYODA_SEARCH_MAX_SORT_KEYS.
SearchMaxSortKeys int
// SearchAsync bounds the async-search worker pool
// (internal/domain/search.WorkerPool): how many workers drain the
// submit queue and how deep that queue is before Submit starts
// rejecting new jobs with a retryable 503. See SearchAsyncConfig.
SearchAsync SearchAsyncConfig
// SearchJobHeartbeatInterval is how often a running async-search
// executor stamps its job's liveness (spi.AsyncSearchStore.Heartbeat)
// and polls for a cross-node cancel/terminal status — starting the
// moment the job is submitted (it heartbeats while queued, not only
// while scanning), independent of scan progress.
// CYODA_SEARCH_JOB_HEARTBEAT_INTERVAL, default 15s. Must be > 0
// (time.NewTicker panics on a non-positive duration); validated at
// startup by ValidateSearchJobHeartbeat.
SearchJobHeartbeatInterval time.Duration
// SearchJobStaleAfter is how long a RUNNING async-search job may go
// without a heartbeat (spi.AsyncSearchStore.ClaimStale's staleness
// baseline — HeartbeatTime, stamped at CreateJob)
// before the reaper (internal/domain/search.ReclaimStaleJobs, wired into
// the reclaim ticker in app.go) claims it and re-executes it on a live
// node (or fails it past the attempt cap). Must dominate
// SearchJobHeartbeatInterval by a wide
// margin so a merely slow heartbeat tick is never mistaken for a dead
// executor — see ValidateSearchJobStaleAfter.
// CYODA_SEARCH_JOB_STALE_AFTER, default 5m.
SearchJobStaleAfter time.Duration
// SearchJobMaxAttempts bounds how many executions an async-search job may
// consume before it is failed: the initial run plus one per executor lost
// without a graceful release (SearchJob.StaleClaims). A graceful handoff
// (Release then reclaim) does not count. CYODA_SEARCH_JOB_MAX_ATTEMPTS,
// default 3, minimum 1; 1 disables re-execution (a job is failed on its first executor loss).
SearchJobMaxAttempts int
// Scheduler configures how this node claims and runs due scheduled
// tasks. See SchedulerConfig.
Scheduler SchedulerConfig
// Callout frames one compute-node callout: how many tries it gets and how
// long a pnode waits for one cnode's answer. See CalloutConfig.
Callout CalloutConfig
}
func DefaultConfig ¶
func DefaultConfig() Config
func (Config) Validate ¶
Validate enforces the config invariants App.New's own wiring depends on.
It lives here, and is called by New itself, because the dependency is New's: it builds the async-search worker pool straight from cfg.SearchAsync, and NewWorkerPool deliberately does not validate (a negative QueueLen panics inside make(chan jobFunc, n)), while cfg.SearchJobHeartbeatInterval reaches a time.NewTicker that panics on a non-positive duration. Checking only in cmd/cyoda/main.go left every in-process embedder of app.New — internal/e2e included — outside the guard. Config is a QA'd artefact rather than untrusted input, so this is an invariant held where it is relied on, not input hardening.
The binary calls Validate in cmd/cyoda/main.go, before printing the startup banner, and app.New calls it again. An invalid config exits in main before New is ever reached, so the error is reported once. Each validator's error names its offending CYODA_* setting.
type GRPCConfig ¶
type HTTPConfig ¶
type HTTPConfig struct {
// BindAddress (CYODA_HTTP_BIND_ADDRESS) is the host the API listener
// binds: a bare host, an IPv6 literal without brackets. Loopback by
// default, as for the admin listener; a container sets 0.0.0.0.
BindAddress string
ReadHeaderTimeout time.Duration
ReadTimeout time.Duration
WriteTimeout time.Duration
IdleTimeout time.Duration
}
HTTPConfig holds the receive-side timeouts applied to both the API server and the admin server. ReadHeaderTimeout, ReadTimeout and IdleTimeout bound how a request is received and how long an idle keep-alive connection is kept; none of them limits how long a handler runs (Go clears the read deadline once the body is drained). WriteTimeout does limit handler execution and ships disabled: the server imposes no time budget on work. Zero disables ReadTimeout and WriteTimeout outright. For ReadHeaderTimeout and IdleTimeout, zero instead means "use ReadTimeout" — Go's own net/http.Server fallback — so those two are off only when ReadTimeout is also zero.
type IAMConfig ¶
type IAMConfig struct {
Mode string
MockUserID string
MockUserName string
MockTenantID string
MockTenantName string
MockRoles []string
// MockKind is the spi.PrincipalKind (as a string — "user", "service", or
// "system") assigned to the mock-mode default UserContext. CYODA_IAM_MOCK_KIND,
// default "service": every mock-mode caller is a client, as every caller
// is in jwt mode. "user" and "system" let local/CI setups exercise
// user- or system-attributed code paths without standing up real JWT auth.
// Any other value refuses to start (ValidateIAM).
MockKind string
JWTSigningKey string // PEM-encoded RSA private key (CYODA_JWT_SIGNING_KEY)
JWTIssuer string // JWT issuer claim (CYODA_JWT_ISSUER)
JWTAudience string // Expected JWT audience (CYODA_JWT_AUDIENCE); empty disables aud check
JWTExpiry int // Token expiry in seconds (CYODA_JWT_EXPIRY_SECONDS)
RequireJWT bool // CYODA_REQUIRE_JWT — when true, refuses to start unless mode=jwt and signing key set
// IAM feature-flag fields — passed through to auth.IAMFeatures via AuthIAMFeatures().
// Individual fields document their own purpose; this block covers both
// /oauth/keys/* (TrustedKey* + KeypairDefault*) and /clients (M2M*).
TrustedKeyRegistrationEnabled bool
TrustedKeyMaxPerTenant int
TrustedKeyMaxValidityDays int
TrustedKeyMaxJWKProperties int
KeypairDefaultValidityDays int
// AuthCacheReconcileInterval is the periodic KV-reconcile interval of
// the per-node signing-key cache.
// Jittered ±10% per tick; the fail-closed staleness bound is fixed at
// 10× this value. CYODA_AUTH_CACHE_RECONCILE_INTERVAL, default 60s,
// floor 1s.
AuthCacheReconcileInterval time.Duration
// M2MAdminRoleEnabled — see auth.IAMFeatures.M2MAdminRoleEnabled.
// env CYODA_IAM_M2M_ADMIN_ROLE_ENABLED, default false.
M2MAdminRoleEnabled bool
// M2MClientMaxPerTenant — see auth.IAMFeatures.M2MClientMaxPerTenant.
// env CYODA_IAM_M2M_CLIENT_MAX_PER_TENANT, default 100; 0=unbounded.
M2MClientMaxPerTenant int
// TokenRequestsPerMinute limits each client's POST /tenants/{tenant}/oauth/token requests
// on one node, across both grants; over it the answer is 429 slow_down.
// env CYODA_IAM_TOKEN_REQUESTS_PER_MINUTE, default 600; 0=unlimited.
TokenRequestsPerMinute int
// TokenMaxConcurrentSecretChecks bounds the bcrypt comparisons
// POST /tenants/{tenant}/oauth/token runs at once on one node; a request that gets no slot
// within 1 s answers 503. env CYODA_IAM_TOKEN_MAX_CONCURRENT_SECRET_CHECKS,
// default runtime.GOMAXPROCS(0), the CPUs the process may use (it follows a
// container CPU limit); at least 1.
TokenMaxConcurrentSecretChecks int
}
func (IAMConfig) AuthIAMFeatures ¶
func (c IAMConfig) AuthIAMFeatures() auth.IAMFeatures
AuthIAMFeatures projects the new IAM-feature fields out of IAMConfig into the auth-package value struct.
type JWTSettings ¶
JWTSettings are the four variables a token signer needs. LoadJWTSettings resolves exactly these, so `cyoda token` does not depend on (or panic over) any other part of the configuration.
func LoadJWTSettings ¶
func LoadJWTSettings() (JWTSettings, error)
LoadJWTSettings resolves CYODA_JWT_SIGNING_KEY (or _FILE; PEM or base64-encoded PEM), CYODA_JWT_ISSUER (default "cyoda" when unset; an explicitly empty value is an error), CYODA_JWT_AUDIENCE (default empty) and CYODA_JWT_EXPIRY_SECONDS (default 300; an integer from 1 to auth.MaxJWTExpirySeconds). Errors name the variable, never its value. The server (DefaultConfig) and `cyoda token` both read these variables here, so they accept and refuse the same values.
type SchedulerConfig ¶
type SchedulerConfig struct {
// Enabled: CYODA_SCHEDULER_ENABLED, default true.
Enabled bool
// ScanInterval: CYODA_SCHEDULER_SCAN_INTERVAL, default 1s, > 0.
ScanInterval time.Duration
// MaxRuns: CYODA_SCHEDULER_MAX_RUNS, default 8, >= 1.
MaxRuns int
// MaxRunsPerTenant: CYODA_SCHEDULER_MAX_RUNS_PER_TENANT, default 4, 1..MaxRuns.
MaxRunsPerTenant int
// HeartbeatInterval: CYODA_SCHEDULER_HEARTBEAT_INTERVAL, default 15s, > 0.
HeartbeatInterval time.Duration
// StaleAfter: CYODA_SCHEDULER_STALE_AFTER, default 2m,
// >= scheduler.MinStaleAfter(HeartbeatInterval). The same on every node.
StaleAfter time.Duration
// MaxLostOwners: CYODA_SCHEDULER_MAX_LOST_OWNERS, default 3, >= 1.
MaxLostOwners int
// RetryDelay: CYODA_SCHEDULER_RETRY_DELAY, default 30s, > 0.
RetryDelay time.Duration
// RetryDelayMax: CYODA_SCHEDULER_RETRY_DELAY_MAX, default 15m, >= RetryDelay.
RetryDelayMax time.Duration
// ShutdownDrain: CYODA_SCHEDULER_SHUTDOWN_DRAIN, default 20s, >= 0.
ShutdownDrain time.Duration
}
SchedulerConfig controls the scheduler: how often a node claims due scheduled tasks, how many runs it holds, how it proves itself alive, how it retries and how it drains. Same fields, names and order as scheduler.Config, which it converts to.
type SearchAsyncConfig ¶
type SearchAsyncConfig struct {
// Workers is the number of goroutines draining the async-search submit
// queue. CYODA_SEARCH_ASYNC_WORKERS, default 8.
//
// Documented default, not computed: a streaming search job holds its
// scan connection for the run's duration plus, per chunk, a save
// connection — so the worker count must stay within the postgres
// connection budget. 8 workers <= (default 25 max conns - reserve) / 2
// connections held at a job's peak.
Workers int
// QueueLen is the submit queue's capacity beyond the workers already
// running. Once both are exhausted, Submit returns ErrQueueFull,
// surfaced as a retryable 503 SEARCH_QUEUE_FULL.
// CYODA_SEARCH_ASYNC_QUEUE, default 256.
QueueLen int
// MaxPerTenant caps how many async-search jobs one tenant may have in
// flight on this node — queued and executing together. Over-cap
// submissions get the same retryable 503 SEARCH_QUEUE_FULL as pool
// backpressure. CYODA_SEARCH_ASYNC_MAX_PER_TENANT, default: Workers.
//
// The pool is shared by every tenant, so without this one tenant's
// burst takes every worker AND fills the queue, and every other tenant
// is answered 503 until those jobs finish — for an async search, up to
// the backend's whole async-scan ceiling.
//
// Defaulting to Workers (rather than a fraction of it) is deliberate: a
// tenant may still saturate the RUNNING set, so a single-tenant
// deployment never idles workers it paid for, but it can never hold
// more than Workers queue slots, so the remaining QueueLen always
// belongs to other tenants and their submissions are accepted and
// served as workers free up.
//
// 0 disables the cap entirely, restoring first-come-first-served across
// tenants. Negative is a hard startup error (ValidateSearchAsync).
MaxPerTenant int
}
SearchAsyncConfig bounds the async-search worker pool (internal/domain/search.WorkerPool). Validated by ValidateSearchAsync at startup — config is a QA'd artefact, so an invalid value is a hard error, not silently clamped to the default.