engine

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: AGPL-3.0, AGPL-3.0-or-later Imports: 88 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 engine owns the running Engine process boundary.

Index

Constants

View Source
const (
	DefaultAsyncHookQueueSize      = 1000
	DefaultAsyncHookMaxQueuedBytes = 64 << 20
	DefaultAsyncHookMaxEventBytes  = 1 << 20
)
View Source
const (
	DefaultRealtimeMaxStreams = 128
	MaxRealtimeMaxStreams     = 4096
)
View Source
const (
	DefaultUploadMaxActive   = 4
	MaxUploadMaxActive       = 256
	DefaultUploadActiveBytes = uint64(512 << 20)
	MaxUploadActiveBytes     = uint64(4 << 30)
)
View Source
const DefaultMaxActivationWaiters uint16 = 32
View Source
const DefaultMaxResidentTenants uint32 = 256

Variables

View Source
var (
	ErrAsyncHookQueueSize   = errors.New("async hook queue size must be positive")
	ErrAsyncHookPayloadSize = errors.New("async hook payload exceeds its byte limit")
)
View Source
var (
	ErrReloadTenantNotFound = errors.New("tenant not found in directory")
	ErrReloadTenantConflict = errors.New("tenant runtime reload conflict")
)
View Source
var (
	ErrUploadCapacity          = errors.New("upload process capacity exhausted")
	ErrUploadReservationTooBig = errors.New("upload reservation exceeds process byte budget")
)
View Source
var ErrAlreadyRun = errors.New("engine Run may only be called once")
View Source
var ErrAlreadyShutdown = errors.New("engine cannot run after shutdown has started")
View Source
var ErrDurableScanCursorMoved = errors.New("durable work scan cursor moved concurrently")
View Source
var ErrRealtimeStreamCapacity = errors.New("realtime stream capacity exhausted")
View Source
var ErrServerRequired = errors.New("engine HTTP server is required")
View Source
var ErrShutdownIncomplete = errors.New("engine shutdown incomplete; dependent resources retained")

Functions

func ActiveConfigMinKoraVersion

func ActiveConfigMinKoraVersion(ctx context.Context, database *sql.DB, dialect kdb.Dialect, siteName string) (string, error)

ActiveConfigMinKoraVersion reads the binary-version floor pinned by the active tenant config snapshot. An empty result means no active version exists. It honors ctx so a canceled reload stops promptly.

func AnalyticsSiteWALDir

func AnalyticsSiteWALDir(baseDir, siteName string) string

AnalyticsSiteWALDir returns the legacy route-name-keyed WAL partition. New Engine writers use AnalyticsTenantWALDir; this helper remains for migration and source compatibility with existing tests/tools.

func AnalyticsTenantWALDir

func AnalyticsTenantWALDir(baseDir, tenantID string) string

AnalyticsTenantWALDir returns a path-safe WAL partition keyed by stable tenant identity. Hashing avoids leaking IDs into paths and prevents route names, aliases, or untrusted path characters from changing the partition.

func BuildHTTPServer

func BuildHTTPServer(config HTTPServerConfig) (*knet.Server, error)

BuildHTTPServer creates the production Engine listener with request tracing and only overrides the established defaults when a timeout is configured.

func DecodeOutboxDelivery

func DecodeOutboxDelivery(delivery contract.Delivery) (analytics.ChangeEvent, error)

func DrainRetiredTenantRuntime

func DrainRetiredTenantRuntime(runtime *knet.LoadedSite, timeout time.Duration) error

DrainRetiredTenantRuntime retries a timed drain without closing resources beneath an admitted request. The caller must retain and join its goroutine.

func InitializeTelemetry

func InitializeTelemetry(ctx context.Context, config TelemetryConfig) (func(context.Context) error, error)

InitializeTelemetry constructs exporters without publishing partial global providers. The returned shutdown function is owned by ProcessResources.

func LoadTenantRuntime

func LoadTenantRuntime(ctx context.Context, info site.DBSiteInfo, common *site.CommonConfig, reusable *knet.LoadedSite, binaryVersion string) (runtime *knet.LoadedSite, err error)

LoadTenantRuntime prepares a tenant generation's database-backed registry before it is published to the runtime manager. A compatible previous generation may lend its stable DB and session manager; failed preparation never closes those borrowed resources.

func NewStorageResolver

func NewStorageResolver(base storage.Config) func(*site.Config) (storage.Backend, error)

NewStorageResolver creates tenant storage backends and initializes their buckets under Engine ownership. The deployment-specific base config is supplied by the process configuration layer.

func NewTenantDirectoryConsumer

func NewTenantDirectoryConsumer(config TenantDirectoryConfig) (*site.DirectoryConsumer, error)

NewTenantDirectoryConsumer builds the durable tenant activation policy used by both feed polling and snapshot resync. It updates directory revision metadata even when config revision is unchanged and delegates construction of non-core sidecars to the process composition root.

func NewTenantServiceInstaller

func NewTenantServiceInstaller(config TenantServiceConfig) (func(site.DBSiteInfo, *knet.LoadedSite) error, error)

NewTenantServiceInstaller validates process dependencies once and returns a tenant-generation installer used for startup activation and hot replacement.

func OutboxEventOperation

func OutboxEventOperation(eventType string) analytics.EventOp

func OutboxSideEffectSubject

func OutboxSideEffectSubject(prefix string) string

func PlatformReadinessHandler

func PlatformReadinessHandler(platformDB *sql.DB, admissions ...readinessWorkAdmission) gin.HandlerFunc

func PrepareScheduler

func PrepareScheduler(options SchedulerOptions) (*scheduler.Scheduler, error)

PrepareScheduler registers explicitly supplied jobs without starting goroutines. The caller owns the worker activation boundary.

func RegisterApplicationRoutes

func RegisterApplicationRoutes(config ApplicationRouteConfig) (*auth.SessionManager, error)

RegisterApplicationRoutes installs the canonical, compatibility, request, public, auth and workspace route sets. It returns the process-owned session manager so the caller can register it for rollback and shutdown.

func RegisterConsoleRoutes

func RegisterConsoleRoutes(router *gin.Engine, handler *api.ConsoleHandler) error

RegisterConsoleRoutes installs the platform console API after its handler has been assembled by the startup composition root.

func RegisterPlatformRoutes

func RegisterPlatformRoutes(config PlatformRouteConfig) error

RegisterPlatformRoutes installs liveness, health, readiness, and optional authenticated management-inspection endpoints on the platform router.

func RegisterTenantReloadRoute

func RegisterTenantReloadRoute(router *gin.Engine, token string, controller *TenantReloadController) error

RegisterTenantReloadRoute binds the protected admin endpoint to the Engine controller. The token remains a dedicated reload credential.

func RunAnalyticsRebuildConsumer

func RunAnalyticsRebuildConsumer(ctx context.Context, siteName string, provider *natsprovider.Provider, runner *analytics.RebuildRunner)

func RunDurableLifecycleHookWorker

func RunDurableLifecycleHookWorker(ctx context.Context, w LifecycleHookWorker)

RunDurableLifecycleHookWorker is owned by one tenant runtime generation. Its SQL rows are the recovery authority; process cancellation only stops new claims and causes an in-flight transaction to roll back.

func RunNATSConsumerWithBackoff

func RunNATSConsumerWithBackoff(ctx context.Context, siteName, consumerName string, run func(context.Context) error)

RunNATSConsumerWithBackoff restarts a durable consumer after transport or settlement errors. The JetStream durable retains unsettled messages while the generation-owned worker waits; cancellation stops the retry timer and lets the runtime join this worker before closing its provider.

func RunNATSOutboxSideEffects

func RunNATSOutboxSideEffects(ctx context.Context, siteName string, provider *natsprovider.Provider, bus analytics.EventBus)

func RunOutboxPublisher

func RunOutboxPublisher(ctx context.Context, p *outbox.Publisher, admission *dbaccess.Admission, backlog ...*outbox.BacklogMetrics)

RunOutboxPublisher repeatedly publishes bounded due batches from the durable tenant outbox through its configured destination.

func RunRealtimeBridge

func RunRealtimeBridge(ctx context.Context, siteName string, bus analytics.EventBus, provider *natsprovider.Provider)

func RunRequestNotificationDispatcher

func RunRequestNotificationDispatcher(ctx context.Context, dispatcher *outbox.Dispatcher)

RunRequestNotificationDispatcher durably plans request notifications from tenant outbox rows. Failed planning leaves the event unreceipted for retry.

func RunRequestNotificationWorker

func RunRequestNotificationWorker(ctx context.Context, worker *notifications.Worker)

RunRequestNotificationWorker retries transient database and local-bus failures while the durable delivery row remains available for recovery.

func RunWebhookOutboxDispatcher

func RunWebhookOutboxDispatcher(ctx context.Context, dispatcher *outbox.Dispatcher, admission *dbaccess.Admission)

RunWebhookOutboxDispatcher consumes durable document events and keeps the event-level receipt behind successful external delivery. Its batch and active-work admission are bounded; idle tenants retain no polling goroutine after their runtime generation is retired.

func RunWorkflowTriggerDispatcher

func RunWorkflowTriggerDispatcher(ctx context.Context, dispatcher *outbox.Dispatcher)

func StartHumanWaitRecoveryWorker

func StartHumanWaitRecoveryWorker(runtime *knet.LoadedSite, processCtx context.Context) error

StartHumanWaitRecoveryWorker starts the tenant-owned sweeper that expires requests and resumes workflows waiting on terminal request or timer states. The runtime generation owns cancellation and joins it before DB closure.

func StartScheduler

func StartScheduler(ctx context.Context, options SchedulerOptions) (*scheduler.Scheduler, error)

StartScheduler starts the scheduler for standalone callers.

func StopTenantServiceBundle

func StopTenantServiceBundle(services tenantruntime.Services)

StopTenantServiceBundle stops request-visible sidecars before closing their event bus. The runtime generation remains responsible for joining its own registered worker loops.

func TransferStableTenantResources

func TransferStableTenantResources(retired, active *knet.LoadedSite) bool

TransferStableTenantResources gives the newly published generation ownership of the database and session manager shared with its retired predecessor.

Types

type ActivationAdmissionSnapshot

type ActivationAdmissionSnapshot struct {
	Waiters      uint16
	MaxWaiters   uint16
	WaitCount    uint64
	WaitDuration time.Duration
	Rejected     uint64
}

type Application

type Application struct {
	Router              *gin.Engine
	Registry            *doctype.Registry
	Transactions        *orm.TxManager
	SessionManager      *auth.SessionManager
	AnalyticsCache      *api.AnalyticsQueryCache
	RealtimeConnections *api.RealtimeConnectionOwner
}

Application is the coherent HTTP composition returned to the process owner. The session manager must be registered for startup rollback and shutdown.

func BuildApplication

func BuildApplication(config ApplicationConfig) (*Application, error)

BuildApplication constructs the request router and installs its application routes and middleware. Process and platform-only routes are added by Engine to the same router before listener assembly.

type ApplicationConfig

type ApplicationConfig struct {
	Common              *site.CommonConfig
	Tenants             *knet.SiteRouter
	Database            *sql.DB
	Mailer              *email.Sender
	ScriptRunner        script.Runner
	HTTPAllowlist       []string
	CORSAllowedOrigins  []string
	AsyncHookSink       orm.AsyncHookSink
	KernelCommands      *kernel.CommandRegistry
	BinaryVersion       string
	SessionCacheBudget  *auth.SessionCacheBudget
	PublicAppBaseURL    string
	CloudIdentityURL    string
	CloudIdentityToken  string
	RealtimeConnections *api.RealtimeConnectionOwner
}

ApplicationConfig is the concrete Engine-owned dependency set required to build the tenant router, request middleware and application route groups.

type ApplicationRouteConfig

type ApplicationRouteConfig struct {
	Router              *gin.Engine
	Tenants             *knet.SiteRouter
	Database            *sql.DB
	Registry            *doctype.Registry
	Transactions        *orm.TxManager
	Mailer              *email.Sender
	ScriptRunner        script.Runner
	HTTPAllowlist       []string
	AsyncHookSink       orm.AsyncHookSink
	KernelCommands      *kernel.CommandRegistry
	SessionLifetime     time.Duration
	CSRFSecure          bool
	AdminRole           string
	AppName             string
	PrimaryColor        string
	APIDefaultLimit     int
	APIMaxLimit         int
	BinaryVersion       string
	PublicAppBaseURL    string
	CloudIdentityURL    string
	CloudIdentityToken  string
	AnalyticsCache      *api.AnalyticsQueryCache
	RealtimeConnections *api.RealtimeConnectionOwner

	// ExtensionTokenCacheTTL caches extension token verification per process;
	// zero disables it. It bounds cross-replica revocation lag.
	ExtensionTokenCacheTTL time.Duration
}

ApplicationRouteConfig is the concrete dependency set used to compose Engine-owned tenant and public APIs. These references are assembled once at startup and route handlers resolve tenant-owned state through SiteRouter.

type AsyncHookOptions

type AsyncHookOptions struct {
	QueueSize      int
	MaxQueuedBytes uint64
	MaxEventBytes  uint64
	Runner         script.Runner
	Sites          *knet.SiteRouter
	DBType         string
	HTTPAllowlist  []string
}

AsyncHookOptions configures an AsyncHookWorker. A zero MaxQueuedBytes or MaxEventBytes selects the default limit.

type AsyncHookQueueSnapshot

type AsyncHookQueueSnapshot struct {
	QueuedBytes    uint64
	MaxQueuedBytes uint64
	MaxEventBytes  uint64
	RejectedItems  uint64
	QueuedItems    int
	MaxQueuedItems int
}

type AsyncHookWorker

type AsyncHookWorker struct {
	// contains filtered or unexported fields
}

AsyncHookWorker owns the bounded hook queue and its consumer goroutine. Stop accepting before waiting on Done; Cancel is reserved for a timed-out drain.

func NewAsyncHookWorker

func NewAsyncHookWorker(opts AsyncHookOptions) (*AsyncHookWorker, error)

NewAsyncHookWorker prepares the bounded queue without launching its consumer. It bounds both the queued request count and the estimated serialized bytes; the estimate is conservative and stops once a limit is hit.

func StartAsyncHookWorker

func StartAsyncHookWorker(opts AsyncHookOptions) (*AsyncHookWorker, error)

StartAsyncHookWorker creates one process-owned worker. Its independent context lets the process owner drain accepted work before cancellation.

func (*AsyncHookWorker) Cancel

func (w *AsyncHookWorker) Cancel()

func (*AsyncHookWorker) Done

func (w *AsyncHookWorker) Done() <-chan struct{}

func (*AsyncHookWorker) QueueSnapshot

func (w *AsyncHookWorker) QueueSnapshot() AsyncHookQueueSnapshot

QueueSnapshot reports the async-hook queue's bounded count and byte usage.

func (*AsyncHookWorker) Sink

func (w *AsyncHookWorker) Sink() orm.AsyncHookSink

func (*AsyncHookWorker) Start

func (w *AsyncHookWorker) Start() error

Start launches the consumer exactly once.

func (*AsyncHookWorker) StopAccepting

func (w *AsyncHookWorker) StopAccepting()

type CheckpointVerifier

type CheckpointVerifier interface {
	Verify(context.Context, string, string, string) (VerifiedCheckpoint, error)
}

CheckpointVerifier resolves an opaque provider reference and verifies it against Engine's current tenant allocation. Implementations must be safe for concurrent calls and honor context cancellation and deadlines.

type Config

type Config struct {
	Telemetry               TelemetryConfig
	DBDriver                string
	DBDSN                   string
	DBDialect               string
	RawCellID               string
	Common                  *site.CommonConfig
	BinaryVersion           string
	TenantConcurrency       uint16
	MaxResidentTenants      uint32
	TenantActivationWaiters uint16
	TenantActivationWait    time.Duration
	RetirementLimit         uint16
	ResolveStorage          func(*site.Config) (storage.Backend, error)
	CellURLs                map[string]string
	DirectoryConsumerID     string
	NATSConfig              *natsprovider.Config
	ScriptsEnabled          bool
	KernelCommands          *kernel.CommandRegistry
	Workflow                *WorkflowTenantConfig
	// RequestAuthorizer and WorkflowApprovals are supplied by registered
	// application-domain integrations; generic Engine composition has no
	// built-in business policy or transition mapping.
	RequestAuthorizer                 RequestAuthorizerFactory
	WorkflowApprovals                 map[string]process.WorkflowApproval
	ModuleSchemas                     workflow.PayloadSchemaRegistry
	ModuleProviders                   func(site.DBSiteInfo, *sql.DB) ([]plugin.ProviderRegistration, []plugin.ProviderSelection, error)
	SchedulerHandlerFactory           ScheduledJobHandlerFactory
	SchedulerExecutionResolverFactory ScheduledJobExecutionResolverFactory
	HTTPAllowlist                     []string
	CORSAllowedOrigins                []string
	CloudRelay                        *analytics.CloudRelayConfig
	Analytics                         *analytics.Config
	OutboxEnabled                     bool
	SystemGuard                       *auth.SystemGuard
	PlatformDBUser                    string
	PlatformDBPassword                string
	AllowConsoleOnboarding            bool
	ManagementToken                   string
	ReloadToken                       string
	ManagementCallerID                string
	PublicAppBaseURL                  string
	CloudIdentityURL                  string
	CloudIdentityToken                string
	DeploymentID                      string
	ManagementDatabaseAllocationRef   string
	ManagementPackageResolver         ManagementPackageArtifactResolver
	ManagementCheckpointVerifier      CheckpointVerifier
	Listener                          HTTPServerConfig
	OnReady                           func(Metrics)
	DirectoryLagMetricsEnabled        bool
	AsyncHookQueueSize                int
	AsyncHookMaxQueuedBytes           uint64
	AsyncHookMaxEventBytes            uint64
	ScriptBudget                      script.BudgetConfig
	RealtimeMaxStreams                int
	SessionCacheBudgetBytes           uint64
	UploadMaxActive                   int
	UploadActiveBudgetBytes           uint64
	AnalyticsQueueBudgetBytes         uint64
	AnalyticsMaxSubscribers           int
}

Config is the fully validated, transport-neutral process configuration. Environment parsing belongs to the executable; resource acquisition and runtime composition belong to Engine.

type ConsoleAssemblyConfig

type ConsoleAssemblyConfig struct {
	SystemGuard           *auth.SystemGuard
	PlatformWorkAdmission interface {
		Acquire(context.Context) (func(), error)
	}
	DBType          string
	DBHost          string
	DBUser          string
	DBPassword      string
	DBPort          int
	PlatformDB      *sql.DB
	AllowOnboarding bool
	ResolveStorage  func(*site.Config) (storage.Backend, error)
}

ConsoleAssemblyConfig contains the platform-only values needed to install the optional console API alongside the tenant application routes.

type DirectoryFeedWorker

type DirectoryFeedWorker struct {
	// contains filtered or unexported fields
}

DirectoryFeedWorker owns the SQL poller, optional broker relay, and wakeup consumer. Shutdown cancels and joins every goroutine started by the worker.

func StartDirectoryFeed

func StartDirectoryFeed(parent context.Context, consumer *site.DirectoryConsumer, wakeups SiteDirectoryWakeups) (*DirectoryFeedWorker, error)

StartDirectoryFeed starts the durable SQL consumer and, when configured, its best-effort broker wakeup relay. Feed application and resync policy stay on the supplied consumer so they use the caller's tenant activation rules.

func (*DirectoryFeedWorker) Shutdown

func (w *DirectoryFeedWorker) Shutdown(ctx context.Context) error

Shutdown cancels the feed and waits for its goroutines to release their leases and stop using shared directory/provider resources.

type DirectoryLagMetrics

type DirectoryLagMetrics struct {
	// contains filtered or unexported fields
}

DirectoryLagMetrics instruments the durable site-directory consumer cursor.

func NewDirectoryLagMetrics

func NewDirectoryLagMetrics(cellID string) (*DirectoryLagMetrics, error)

func (*DirectoryLagMetrics) Record

func (m *DirectoryLagMetrics) Record(ctx context.Context, lag uint64, staleAge time.Duration, success bool)

type DirectoryLagMonitor

type DirectoryLagMonitor struct {
	// contains filtered or unexported fields
}

DirectoryLagMonitor owns the process poller for a directory consumer.

func PrepareDirectoryLagMonitor

func PrepareDirectoryLagMonitor(parent context.Context, registry *site.SQLSiteRegistry, consumerID string, metrics *DirectoryLagMetrics, admissions ...directoryWorkAdmission) (*DirectoryLagMonitor, error)

PrepareDirectoryLagMonitor constructs the owned poller without starting its goroutine; Engine.Run activates it through the process worker registry.

func StartDirectoryLagMonitor

func StartDirectoryLagMonitor(parent context.Context, registry *site.SQLSiteRegistry, consumerID string, metrics *DirectoryLagMetrics) (*DirectoryLagMonitor, error)

StartDirectoryLagMonitor starts and owns the periodic directory-lag poller.

func (*DirectoryLagMonitor) Shutdown

func (m *DirectoryLagMonitor) Shutdown(ctx context.Context) error

Shutdown cancels and joins the monitor before its directory DB is closed.

func (*DirectoryLagMonitor) Start

func (m *DirectoryLagMonitor) Start() error

Start begins the monitor after the process owner activates its workers.

type DurableWorkScanner

type DurableWorkScanner struct {
	// contains filtered or unexported fields
}

DurableWorkScanner walks local credential-free descriptors in bounded pages, briefly opens at most one cold tenant database at a time, and wakes the tenant runtime that owns pending work. Durable SQL state remains the recovery authority; scanner notifications are never the work queue.

func NewDurableWorkScanner

func NewDurableWorkScanner(config DurableWorkScannerConfig) (*DurableWorkScanner, error)

func (*DurableWorkScanner) ScanOnce

func (s *DurableWorkScanner) ScanOnce(ctx context.Context) error

ScanOnce processes one bounded directory page. A full page advances the durable keyset cursor; the final/empty page closes the sweep and resets it.

func (*DurableWorkScanner) Shutdown

func (s *DurableWorkScanner) Shutdown(ctx context.Context) error

Shutdown cancels and joins the process-owned scanner before its database and tenant runtime dependencies are closed.

func (*DurableWorkScanner) Snapshot

func (*DurableWorkScanner) Start

func (s *DurableWorkScanner) Start() error

Start starts one joined process-owned scanner. Schema and cursor readiness are checked before the goroutine is published.

type DurableWorkScannerConfig

type DurableWorkScannerConfig struct {
	ParentContext   context.Context
	PlatformDB      *sql.DB
	PlatformDialect db.Dialect
	Directory       durableScanDirectory
	Tenants         *net.SiteRouter
	Coordinator     *TenantRuntimeCoordinator
	WorkAdmission   interface {
		Acquire(context.Context) (func(), error)
	}
	TenantWorkAdmission func(*site.Config) (interface {
		Acquire(context.Context) (func(), error)
	}, error)
	Common              *site.CommonConfig
	Analytics           *analytics.Config
	CellID              string
	DirectoryConsumerID string
	PageSize            uint16
	ProbeTimeout        time.Duration
	PageYield           time.Duration
	Interval            time.Duration
}

type DurableWorkScannerSnapshot

type DurableWorkScannerSnapshot struct {
	Probes                uint64
	DueTenants            uint64
	ProbeFailures         uint64
	ScanFailures          uint64
	WakeFailures          uint64
	CapacityRejections    uint64
	CompletedSweeps       uint64
	LastCompletedSweep    time.Time
	LastCompletedSweepAge time.Duration
	ColdWALPending        bool
	ColdWALAgeUnknown     bool
	ColdWALOldestAge      time.Duration
	ColdWALBytes          int64
	ColdWALBytesKnown     bool
}

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine owns the listener and the assembled runtime's shutdown boundary. Runtime construction remains explicit in the composition root.

func New

func New(ctx context.Context, config Config) (_ *Engine, err error)

New assembles the complete Engine runtime and immediately assumes ownership of every acquired resource. On failure it unwinds the partial assembly using the same bounded shutdown path used after serving begins.

func NewFromListener

func NewFromListener(server *knet.Server, onReady func(), resources ShutdownOwner) *Engine

NewFromListener wraps an already constructed HTTP server. Production process startup should use New so Engine owns configuration assembly and rollback.

func (*Engine) Readiness

func (e *Engine) Readiness() Readiness

func (*Engine) Run

func (e *Engine) Run(ctx context.Context) error

Run serves until listener failure or termination signal, always joining the signal watcher and completing runtime shutdown before returning.

func (*Engine) Shutdown

func (e *Engine) Shutdown(ctx context.Context) (result error)

Shutdown runs the composed resource cleanup exactly once and joins callers.

type HTTPManagementPackageArtifactResolver

type HTTPManagementPackageArtifactResolver struct {
	// contains filtered or unexported fields
}

func NewHTTPManagementPackageArtifactResolver

func NewHTTPManagementPackageArtifactResolver(baseURL, token string, client *http.Client) (*HTTPManagementPackageArtifactResolver, error)

func (*HTTPManagementPackageArtifactResolver) ResolvePackage

func (r *HTTPManagementPackageArtifactResolver) ResolvePackage(ctx context.Context, artifactRef, digest string, componentReleaseIDs []string) (ManagementPackageArtifact, error)

type HTTPProcessAssembly

type HTTPProcessAssembly struct {
	Application     *Application
	Server          *knet.Server
	AsyncHookWorker *AsyncHookWorker
}

func AssembleHTTPProcess

func AssembleHTTPProcess(config HTTPProcessAssemblyConfig) (*HTTPProcessAssembly, error)

AssembleHTTPProcess builds the request application, installs platform routes/workers, creates the listener and transfers every acquired worker to ProcessResources before continuing to the next fallible startup stage.

type HTTPProcessAssemblyConfig

type HTTPProcessAssemblyConfig struct {
	ProcessContext          context.Context
	Resources               *ProcessResources
	Application             ApplicationConfig
	NATS                    *natsprovider.Provider
	DirectoryConsumer       *site.DirectoryConsumer
	ReloadController        *TenantReloadController
	ReloadToken             string
	Console                 *ConsoleAssemblyConfig
	PlatformRoutes          PlatformRouteConfig
	PlatformDBDriver        string
	PlatformDBDSN           string
	StartScheduler          bool
	Listener                HTTPServerConfig
	WrapHandler             func(http.Handler) http.Handler
	AsyncHookQueueSize      int
	AsyncHookMaxQueuedBytes uint64
	AsyncHookMaxEventBytes  uint64
}

HTTPProcessAssemblyConfig is the typed input to Engine's HTTP and process worker assembly. Resources takes ownership incrementally; callers must use it for rollback whenever this function returns an error.

type HTTPServerConfig

type HTTPServerConfig struct {
	Handler       http.Handler
	ListenAddress string
	TLS           knet.TLSConfig
	ReadTimeout   time.Duration
	WriteTimeout  time.Duration
	IdleTimeout   time.Duration
}

HTTPServerConfig contains the HTTP listener settings assembled by Engine.

type LifecycleHookWorker

type LifecycleHookWorker struct {
	Runner        script.Runner
	Store         *script.Store
	DB            *sql.DB
	Registry      *doctype.Registry
	Outbox        outbox.Writer
	TenantID      string
	Site          string
	DBType        string
	Secrets       *secret.Store
	HTTPAllowlist []string
	Admission     hookWorkAdmission
}

LifecycleHookWorker holds the dependencies of one tenant's durable lifecycle hook worker. An omitted Outbox, Secrets, HTTPAllowlist or Admission is treated as absent.

type ManagementPackageArtifact

type ManagementPackageArtifact struct {
	Manifest contract.MarketplacePackageManifest
	Files    []contract.PackFile
}

ManagementPackageArtifact is an immutable marketplace release projection. The resolver is deployment-owned and must resolve only configured providers; it must never interpret ArtifactRef as a URL, path, or database coordinate.

type ManagementPackageArtifactResolver

type ManagementPackageArtifactResolver interface {
	ResolvePackage(context.Context, string, string, []string) (ManagementPackageArtifact, error)
}

type Metrics

type Metrics struct {
	DiscoveredTenants int
	LoadedTenants     int
	OpenConnections   int
	InUseConnections  int
	IdleConnections   int
	PoolWaitCount     int
	PoolWaitDuration  time.Duration
	HeapAllocBytes    uint64
	HeapSysBytes      uint64
	StartupDuration   time.Duration
}

Metrics is a low-cardinality startup snapshot provided to the host application after the HTTP listener begins accepting requests.

type PendingDeletionWorker

type PendingDeletionWorker struct {
	// contains filtered or unexported fields
}

PendingDeletionWorker owns recovery of durable tenant-deletion intents. Construction starts the cancellable worker; Start releases its initial wait after the Engine becomes ready. Shutdown cancels and joins it before the platform database is closed.

func StartPendingDeletionWorker

func StartPendingDeletionWorker(parent context.Context, platformDB *sql.DB, dbType string, common *site.CommonConfig) (*PendingDeletionWorker, error)

StartPendingDeletionWorker starts the Engine-owned deletion recovery worker.

func (*PendingDeletionWorker) Shutdown

func (w *PendingDeletionWorker) Shutdown(ctx context.Context) error

Shutdown cancels the current recovery attempt and joins the worker.

func (*PendingDeletionWorker) Snapshot

func (*PendingDeletionWorker) Start

func (w *PendingDeletionWorker) Start()

Start releases the initial readiness gate exactly once.

type PendingDeletionWorkerSnapshot

type PendingDeletionWorkerSnapshot struct {
	Attempts            uint64
	Failures            uint64
	AdmissionRejections uint64
}

type PlatformRouteConfig

type PlatformRouteConfig struct {
	Router                          *gin.Engine
	Directory                       api.ManagementDirectory
	ManagementToken                 string
	ManagementCallerID              string
	PublicAppBaseURL                string
	ManagementOperations            *api.ManagementOperationRoutes
	TenantConfigRevision            api.TenantConfigRevisionResolver
	ManagementCheckpointVerifier    CheckpointVerifier
	ManagementPackageResolver       ManagementPackageArtifactResolver
	DeploymentID                    string
	ManagementDatabaseAllocationRef string
	PrimaryDB                       *sql.DB
	PrimaryDBWorkAdmission          interface {
		Acquire(context.Context) (func(), error)
	}
	PlatformDB            *sql.DB
	PlatformWorkAdmission interface {
		Acquire(context.Context) (func(), error)
	}
	BinaryVersion string
}

PlatformRouteConfig contains platform-plane routes that do not depend on a tenant runtime. Management inspection is optional for Cloud-free self-hosting.

type PlatformSiteDirectory

type PlatformSiteDirectory struct {
	DB          *sql.DB
	Directory   *site.SQLSiteRegistry
	StartCursor uint64
	CellID      string
	Sites       []site.DBSiteInfo
	Descriptors []contract.SiteDescriptor
}

PlatformSiteDirectory is the validated platform directory snapshot Engine acquires before assembling tenant runtimes. Engine owns DB until ownership transfers to ProcessResources.

func OpenPlatformSiteDirectory

func OpenPlatformSiteDirectory(driver, dsn, dialectName, rawCellID string) (PlatformSiteDirectory, error)

OpenPlatformSiteDirectory opens and validates the platform database and discovers credential-free tenant routing metadata. Any failure closes the acquired DB and joins a close failure with the primary startup error.

type ProcessResources

type ProcessResources struct {
	StopAsyncHookWorker     func()
	CancelAsyncHookWorker   context.CancelFunc
	AsyncHookWorkerDone     <-chan struct{}
	CancelProcess           context.CancelFunc
	CloseRealtimeStreams    func()
	SystemGuard             *auth.SystemGuard
	CloseOnboardingJobs     func(context.Context) error
	Scheduler               *scheduler.Scheduler
	DeletionWorker          *PendingDeletionWorker
	DirectoryLagMonitor     *DirectoryLagMonitor
	DirectoryFeed           *DirectoryFeedWorker
	DurableWorkScanner      *DurableWorkScanner
	TenantCoordinator       *TenantRuntimeCoordinator
	UnregisteredTenants     []*knet.LoadedSite
	Tenants                 *knet.SiteRouter
	SessionManager          *auth.SessionManager
	ManagementWorkerDone    <-chan struct{}
	ScriptRunner            script.Runner
	NATSProvider            interface{ Close() }
	PlatformDB              *sql.DB
	PlatformDialect         db.Dialect
	TelemetryShutdown       func(context.Context) error
	ResourceMetrics         *ResourceMetrics
	RealtimeStreams         *RealtimeStreamAdmission
	SessionCacheBudget      *auth.SessionCacheBudget
	UploadAdmission         *UploadAdmission
	AnalyticsQueueAdmission *analytics.QueueAdmission
	// contains filtered or unexported fields
}

ProcessResources is the explicit process-level ownership set registered during startup and handed to Engine for normal shutdown. It also owns startup rollback before that transfer completes. Tenant-scoped services remain owned by each LoadedSite generation.

func (*ProcessResources) RegisterWorkerStart

func (r *ProcessResources) RegisterWorkerStart(start func() error) error

RegisterWorkerStart defers worker execution until Engine.Run begins. If the process is already running, newly activated tenant generations start at once.

func (*ProcessResources) RetainUnregisteredTenant

func (r *ProcessResources) RetainUnregisteredTenant(runtime *knet.LoadedSite)

RetainUnregisteredTenant transfers a failed-to-publish runtime candidate to the process owner so startup rollback/shutdown can retry its close.

func (*ProcessResources) Shutdown

func (r *ProcessResources) Shutdown(ctx context.Context) error

Shutdown stops process producers, joins their goroutines, and closes shared resources in dependency order. If a bounded worker join expires, dependent resources are retained rather than being closed beneath a live goroutine.

func (*ProcessResources) StartRegisteredWorkers

func (r *ProcessResources) StartRegisteredWorkers() error

StartRegisteredWorkers starts assembly-time registrations exactly once and before the listener can publish readiness.

type ProcessStartupAssembly

type ProcessStartupAssembly struct {
	Context             context.Context
	Span                trace.Span
	Started             time.Time
	DiscoveredTenants   int
	Platform            PlatformSiteDirectory
	Tenants             StartupTenants
	Ingress             *ingress.Gateway
	DirectoryConsumerID string
}

func AssembleProcessStartup

func AssembleProcessStartup(ctx context.Context, config ProcessStartupConfig, resources *ProcessResources) (*ProcessStartupAssembly, error)

AssembleProcessStartup acquires process telemetry, the canonical platform directory, and the bounded cold-start tenant set in dependency order. Every successful acquisition is immediately registered with ProcessResources so the caller can roll back the same owner if a later stage fails.

type ProcessStartupConfig

type ProcessStartupConfig struct {
	Telemetry                  TelemetryConfig
	DBDriver                   string
	DBDSN                      string
	DBDialect                  string
	RawCellID                  string
	Common                     *site.CommonConfig
	BinaryVersion              string
	TenantConcurrency          uint16
	MaxResidentTenants         uint32
	ResolveStorage             func(*site.Config) (storage.Backend, error)
	CellURLs                   map[string]string
	DirectoryConsumerID        string
	DirectoryLagMetricsEnabled bool
}

type Readiness

type Readiness struct {
	Ready   bool
	Reasons []string
}

Readiness reports listener state with bounded, stable reason codes. It never includes raw startup or shutdown errors.

type RealtimeStreamAdmission

type RealtimeStreamAdmission struct {
	// contains filtered or unexported fields
}

RealtimeStreamAdmission is a process-owned, fail-fast limit for long-lived realtime connections. It is separate from database work admission because streams retain a slot for their lifetime but perform only intermittent DB authorization checks.

func NewRealtimeStreamAdmission

func NewRealtimeStreamAdmission(maxStreams int) (*RealtimeStreamAdmission, error)

func (*RealtimeStreamAdmission) Acquire

func (a *RealtimeStreamAdmission) Acquire(ctx context.Context) (func(), error)

func (*RealtimeStreamAdmission) Snapshot

type RealtimeStreamSnapshot

type RealtimeStreamSnapshot struct {
	Active   int
	Capacity int
	Rejected uint64
}

type RequestAuthorizerFactory

type RequestAuthorizerFactory func(*sql.DB, kdb.Dialect, *doctype.Registry, requests.Authorizer) (requests.Authorizer, error)

RequestAuthorizerFactory lets an owning domain add governed request policies to the generic direct-task policy at the application composition boundary. The Engine owns the request service and SQL lifecycle; the domain owns policy.

type ResourceMetricSources

type ResourceMetricSources struct {
	PlatformDB              *sql.DB
	RealtimeStreams         *RealtimeStreamAdmission
	SessionCache            *auth.SessionCacheBudget
	Uploads                 *UploadAdmission
	AnalyticsQueueAdmission *analytics.QueueAdmission
	TenantActivation        interface {
		AdmissionSnapshot() ActivationAdmissionSnapshot
	}
	DurableWorkScan interface {
		Snapshot() DurableWorkScannerSnapshot
	}
	NATSRealtime        *natsprovider.Provider
	DeletionWorker      *PendingDeletionWorker
	AnalyticsQueryCache interface {
		AnalyticsQueryCacheSnapshot() api.AnalyticsQueryCacheSnapshot
	}
}

type ResourceMetrics

type ResourceMetrics struct {
	// contains filtered or unexported fields
}

ResourceMetrics registers low-cardinality gauges for process and tenant resource budgets. Tenant/user IDs and endpoint names are never metric labels.

func RegisterResourceMetrics

func RegisterResourceMetrics(tenants *knet.SiteRouter, hooks *AsyncHookWorker, scripts *script.BudgetedRunner, sources ...ResourceMetricSources) (*ResourceMetrics, error)

func (*ResourceMetrics) Unregister

func (m *ResourceMetrics) Unregister() error

type ScheduledJobExecutionResolverFactory

type ScheduledJobExecutionResolverFactory func(TenantJobRuntime) scheduler.ExecutionResolver

ScheduledJobExecutionResolverFactory binds legal-entity scheduled work to trusted service grants owned by the application domain.

type ScheduledJobHandlerFactory

type ScheduledJobHandlerFactory func(TenantJobRuntime) map[scheduler.JobType]scheduler.JobHandler

ScheduledJobHandlerFactory creates application handlers for one tenant generation. The application decides which configured types apply there.

type SchedulerOptions

type SchedulerOptions struct {
	Jobs         []*scheduler.JobConfig
	Database     *sql.DB
	Registry     *doctype.Registry
	Transactions *orm.TxManager
	Mailer       *email.Sender
}

SchedulerOptions describes explicitly supplied scheduler definitions and the tenant-scoped dependencies required to execute them.

type SharedRuntime

type SharedRuntime struct {
	ScriptRunner script.Runner
	NATSProvider *natsprovider.Provider
}

SharedRuntime is the typed provider set consumed by tenant service assembly.

func InitializeSharedRuntime

func InitializeSharedRuntime(ctx context.Context, config SharedRuntimeConfig, resources *ProcessResources) (*SharedRuntime, error)

InitializeSharedRuntime constructs process-wide script and optional NATS providers and registers each acquired resource with ProcessResources before it can be used by tenant workers.

type SharedRuntimeConfig

type SharedRuntimeConfig struct {
	ScriptsEnabled         bool
	NATSConfig             *natsprovider.Config
	BootstrapSiteDirectory bool
}

SharedRuntimeConfig contains process-wide execution providers. NATS is optional: connection or bootstrap failure preserves the supported local SQL-polling and in-process delivery mode.

type ShutdownOwner

type ShutdownOwner interface {
	Shutdown(context.Context) error
}

ShutdownOwner is the process resource boundary owned by Engine. Shutdown must stop producers and join users before closing the resources they use.

type SiteDirectoryWakeups

type SiteDirectoryWakeups interface {
	SubscribeSiteDirectoryWakeups(context.Context, string) (<-chan uint64, error)
	PublishSiteDirectoryRevision(context.Context, uint64) error
}

SiteDirectoryWakeups provides best-effort wakeups for the durable SQL directory feed. SQL polling remains authoritative when the broker is absent.

type StartupTenantConfig

type StartupTenantConfig struct {
	Sites             []site.DBSiteInfo
	Common            *site.CommonConfig
	BinaryVersion     string
	Concurrency       uint16
	SharedPlatformDSN string
	ResolveStorage    func(*site.Config) (storage.Backend, error)
}

StartupTenantConfig carries the validated directory projection and only the process-specific storage resolver into Engine's cold tenant activation.

type StartupTenants

type StartupTenants struct {
	Runtimes  []*knet.LoadedSite
	Domains   []string
	PrimaryDB *sql.DB
}

StartupTenants is the coherent cold-start result transferred to the process owner after every discovered tenant has either activated or rolled back.

func LoadStartupTenants

func LoadStartupTenants(ctx context.Context, config StartupTenantConfig) (StartupTenants, error)

LoadStartupTenants activates the startup directory snapshot with bounded parallelism. On any tenant failure it closes every successful sibling and joins rollback failures into the returned error.

type TelemetryConfig

type TelemetryConfig struct {
	ServiceName    string
	ServiceVersion string
	TracesEnabled  bool
	MetricsEnabled bool
}

TelemetryConfig selects process telemetry providers. Endpoint and exporter protocol details remain controlled by the standard OTEL environment options.

type TenantDirectory

type TenantDirectory interface {
	site.DirectoryChangeFeed
	GetDescriptorByID(string) (site.Descriptor, error)
	GetByID(string) (site.DBSiteInfo, error)
	GetDirectoryDescriptors() ([]contract.SiteDescriptor, error)
	GetDirectorySnapshotForCell(string) ([]site.DBSiteInfo, error)
}

TenantDirectory is the Engine-owned directory read/change-feed boundary used to activate local tenant runtimes from durable platform state.

type TenantDirectoryConfig

type TenantDirectoryConfig struct {
	Directory     TenantDirectory
	Tenants       *knet.SiteRouter
	CellID        string
	ConsumerID    string
	InitialCursor uint64
	Coordinator   *TenantRuntimeCoordinator
	WorkAdmission interface {
		Acquire(context.Context) (func(), error)
	}
}

TenantDirectoryConfig injects the process-specific runtime service installer through one Engine runtime coordinator while keeping directory policy inside Engine.

type TenantIngressDirectory

type TenantIngressDirectory interface {
	ValidateDirectory([]contract.SiteDescriptor) error
	ApplyDescriptor(contract.SiteDescriptor) error
	MarkLocalReady(string, bool)
	ReplaceDirectory([]contract.SiteDescriptor) error
}

TenantIngressDirectory is the credential-free placement projection consumed by optional deployment ingress. It never owns tenant data or routing state.

type TenantJobRuntime

type TenantJobRuntime struct {
	Database       *sql.DB
	Registry       *doctype.Registry
	Dialect        kdb.Dialect
	Kernel         *kernel.Kernel
	ModuleBindings *plugin.BindingPlan
	TenantID       string
	SiteName       string
	ConfigRevision uint64
}

TenantJobRuntime provides tenant-bound infrastructure to application-owned scheduled-job handlers without teaching Engine about domain job types.

type TenantReloadController

type TenantReloadController struct {
	Tenants       *knet.SiteRouter
	Directory     TenantRuntimeDirectory
	PlatformDB    *sql.DB
	WorkAdmission interface {
		Acquire(context.Context) (func(), error)
	}
	Coordinator *TenantRuntimeCoordinator
}

TenantReloadController binds the protected admin operation to the same Engine runtime coordinator used by directory feed and resync activation.

func (*TenantReloadController) Reload

func (c *TenantReloadController) Reload(ctx context.Context, name string) (string, error)

Reload activates a currently registered tenant or adds one that is present in the platform registry but not yet loaded in this Engine.

type TenantRuntimeAssembly

type TenantRuntimeAssembly struct {
	Tenants            *knet.SiteRouter
	Coordinator        *TenantRuntimeCoordinator
	DirectoryConsumer  *site.DirectoryConsumer
	DurableWorkScanner *DurableWorkScanner
	ReloadController   *TenantReloadController
}

TenantRuntimeAssembly is the coherent runtime and directory control plane consumed by HTTP routes and the process-owned directory feed.

func AssembleTenantRuntime

func AssembleTenantRuntime(config TenantRuntimeAssemblyConfig) (*TenantRuntimeAssembly, error)

AssembleTenantRuntime constructs the startup tenant manager, installs the same service bundle used for future activation, and wires directory reload through the single runtime coordinator. On any error, Resources retains the partially assembled state for the caller's normal startup rollback path.

type TenantRuntimeAssemblyConfig

type TenantRuntimeAssemblyConfig struct {
	Runtimes               []*knet.LoadedSite
	DirectoryDescriptors   []contract.SiteDescriptor
	Directory              TenantRuntimeDirectory
	DirectoryRevision      uint64
	DirectoryConsumerID    string
	DirectoryWorkAdmission interface {
		Acquire(context.Context) (func(), error)
	}
	TenantActivationWorkAdmission func(context.Context, *site.Config) (func(), error)
	CellID                        string
	RetirementLimit               uint16
	MaxResidentTenants            uint32
	MaxActivationWaiters          uint16
	ActivationWait                time.Duration
	Common                        *site.CommonConfig
	BinaryVersion                 string
	Ingress                       TenantIngressDirectory
	Services                      TenantServiceConfig
	Resources                     *ProcessResources
}

TenantRuntimeAssemblyConfig contains the typed dependencies needed to publish the startup tenant set and its directory-backed activation policy. The ProcessResources owner must already own Runtimes until this constructor installs the SiteRouter; after that point it owns the router and generations.

type TenantRuntimeCoordinator

type TenantRuntimeCoordinator struct {
	// contains filtered or unexported fields
}

TenantRuntimeCoordinator owns cold activation, replacement, retirement and joined drain for tenant generations after the process manager is assembled.

func (*TenantRuntimeCoordinator) ActivateFromDirectory

func (c *TenantRuntimeCoordinator) ActivateFromDirectory(ctx context.Context, siteID string) error

ActivateFromDirectory resolves one credential-free descriptor first, then fetches that tenant's data-plane credentials and publishes at most one generation even when many first requests race on a cold alias.

func (*TenantRuntimeCoordinator) Add

func (c *TenantRuntimeCoordinator) Add(ctx context.Context, info site.DBSiteInfo, directoryRevision uint64) error

func (*TenantRuntimeCoordinator) AdmissionSnapshot

func (*TenantRuntimeCoordinator) Install

func (c *TenantRuntimeCoordinator) Install(info site.DBSiteInfo, runtime *knet.LoadedSite) error

func (*TenantRuntimeCoordinator) Replace

func (c *TenantRuntimeCoordinator) Replace(ctx context.Context, info site.DBSiteInfo, directoryRevision uint64) error

func (*TenantRuntimeCoordinator) ResidentCapacity

func (c *TenantRuntimeCoordinator) ResidentCapacity() int

func (*TenantRuntimeCoordinator) Retain

func (c *TenantRuntimeCoordinator) Retain(runtime *knet.LoadedSite)

func (*TenantRuntimeCoordinator) Retire

func (c *TenantRuntimeCoordinator) Retire(ctx context.Context, siteID string) error

func (*TenantRuntimeCoordinator) WaitRetired

func (c *TenantRuntimeCoordinator) WaitRetired(ctx context.Context) error

type TenantRuntimeCoordinatorConfig

type TenantRuntimeCoordinatorConfig struct {
	Tenants                 *knet.SiteRouter
	Directory               TenantRuntimeDirectory
	Common                  *site.CommonConfig
	BinaryVersion           string
	Installer               TenantRuntimeInstaller
	Ingress                 TenantIngressDirectory
	RetainRuntime           func(*knet.LoadedSite)
	DrainTimeout            time.Duration
	MaxResidentTenants      uint32
	MaxActivationWaiters    uint16
	ActivationWait          time.Duration
	ActivationWorkAdmission func(context.Context, site.DBSiteInfo) (func(), error)
}

type TenantRuntimeDirectory

type TenantRuntimeDirectory interface {
	TenantDirectory
	CurrentDirectoryRevision() (uint64, error)
	GetByIDContext(context.Context, string) (site.DBSiteInfo, error)
	GetDirectoryDescriptorPageContext(context.Context, string, string, uint16) ([]site.Descriptor, error)
}

TenantRuntimeDirectory is the startup/reload directory contract used by the runtime assembly and administrative reload service.

type TenantRuntimeInstaller

type TenantRuntimeInstaller func(site.DBSiteInfo, *knet.LoadedSite) error

type TenantServiceConfig

type TenantServiceConfig struct {
	ProcessContext          context.Context
	Common                  *site.CommonConfig
	Analytics               *analytics.Config
	CloudRelay              *analytics.CloudRelayConfig
	AnalyticsQueueAdmission *analytics.QueueAdmission
	NATS                    *natsprovider.Provider
	ScriptRunner            script.Runner
	HTTPAllowlist           []string
	RealtimeAdmission       interface {
		Acquire(context.Context) (func(), error)
	}
	SessionCacheBudget *auth.SessionCacheBudget
	UploadAdmission    interface {
		Acquire(context.Context, uint64) (func(), error)
	}
	OutboxEnabled                     bool
	Workflow                          *WorkflowTenantConfig
	RequestAuthorizer                 RequestAuthorizerFactory
	WorkflowApprovals                 map[string]process.WorkflowApproval
	KernelCommands                    *kernel.CommandRegistry
	ModuleSchemas                     workflow.PayloadSchemaRegistry
	ModuleProviders                   func(site.DBSiteInfo, *sql.DB) ([]plugin.ProviderRegistration, []plugin.ProviderSelection, error)
	SchedulerHandlerFactory           ScheduledJobHandlerFactory
	SchedulerExecutionResolverFactory ScheduledJobExecutionResolverFactory
	Mailer                            *email.Sender
	ResolveStorage                    func(*site.Config) (storage.Backend, error)
	RegisterWorkerStart               func(func() error) error
}

TenantServiceConfig is the concrete dependency set for constructing services owned by one tenant generation. Deployment-specific storage construction is supplied by the process composition root; worker and service ownership stays in Engine.

type UploadAdmission

type UploadAdmission struct {
	// contains filtered or unexported fields
}

UploadAdmission reserves a conservative process-wide memory allowance for an upload's multipart body, decoded bytes, and image-processing copy.

func NewUploadAdmission

func NewUploadAdmission(maxActive int, maxBytes uint64) (*UploadAdmission, error)

func (*UploadAdmission) Acquire

func (a *UploadAdmission) Acquire(ctx context.Context, bytes uint64) (func(), error)

func (*UploadAdmission) Snapshot

type UploadAdmissionSnapshot

type UploadAdmissionSnapshot struct {
	Active      int
	Capacity    int
	ActiveBytes uint64
	MaxBytes    uint64
	Rejected    uint64
}

type VerifiedCheckpoint

type VerifiedCheckpoint struct {
	Reference    string
	TenantID     string
	DataPlaneRef string
	Complete     bool
	Immutable    bool
	Restorable   bool
}

VerifiedCheckpoint is returned by a trusted backup-provider adapter. Engine still compares every identity and readiness field before allowing teardown.

type WorkflowTenantConfig

type WorkflowTenantConfig struct {
	ModuleSnapshot   func(contract.TenantID) (contract.ModuleSnapshot, error)
	Registrations    []workflow.ActionRegistration
	LocalBuilders    map[workflow.ActionKey]process.WorkflowOperationBuilder
	Schemas          workflow.PayloadSchemaRegistry
	CapabilityLeases workflow.CapabilityLeaseManager
	Waits            workflow.WaitFieldRegistry
	// ServiceGrants are exact trusted policy grants for non-action workflow
	// operations, such as one registered human-request policy or a condition
	// subject read. Action grants are derived from ActionRegistration instead.
	ServiceGrants []policy.Grant
	// Identity is retained for source compatibility with early injected
	// workflow assemblies. Engine wraps it, checks its service/tenant/site
	// binding on each use, and replaces its grants with the trusted set above.
	// New assemblies should leave it nil so Engine mints the identity itself.
	Identity     func(contract.TenantID) (workflow.ExecutionIdentityProvider, error)
	Conditions   func(*knet.LoadedSite) workflow.ConditionScopeProvider
	Definitions  workflow.DefinitionAuthorizer
	Instances    workflow.InstanceAuthorizer
	Evaluator    expression.Evaluator
	Concurrency  uint16
	Batch        uint16
	Lease        time.Duration
	PollInterval time.Duration
	Mailer       *email.Sender
	EventBus     eventstream.Bus
}

WorkflowTenantConfig supplies verified policy and domain adapters to the tenant-owned durable orchestration runtime. Catalog construction, SQL stores, claim handling, and worker lifecycle remain owned by Engine.

func SelfHostedWorkflowConfig

func SelfHostedWorkflowConfig() *WorkflowTenantConfig

SelfHostedWorkflowConfig enables the domain-neutral durable workflow runtime for human waits, conditions, and timers. Business capabilities are supplied by separately registered domain integrations; the generic Engine grants no domain permissions and registers no domain actions by default.

Source Files

Jump to

Keyboard shortcuts

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