runtime

package
v0.4.20 Latest Latest
Warning

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

Go to latest
Published: Sep 17, 2026 License: Apache-2.0 Imports: 32 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AppSchemaPattern = regexp.MustCompile(`^app_[a-z0-9_]+$`)

AppSchemaPattern validates a per-app Postgres schema name (app_<uuid> with hyphens replaced by underscores). Exported so the dev runtime, which derives the schema from X-MS-App-ID instead of receiving it in the Lambda payload, validates it identically — keeping dev and prod from drifting on the shape.

View Source
var ErrAttemptAlreadyHandled = errors.New("mirrorstack: task attempt already claimed or terminal")

ErrAttemptAlreadyHandled means the broker definitively reported that this duplicate/losing process must exit without invoking the handler.

Functions

func AppSchemaName

func AppSchemaName(appID string) (string, bool)

AppSchemaName derives the per-app Postgres schema from an app id, matching the platform's ids.AppSchemaName convention (app_<uuid-with-underscores>). Returns ok=false if the result does not match AppSchemaPattern (e.g. appID is empty or contains characters outside [a-zA-Z0-9-]).

Shared by every caller that must derive app_<id> from a bare app id rather than receive the schema pre-resolved: the dev per-request schema middleware (core.devAppSchemaMiddleware, via its devAppSchemaName wrapper) and the dev-mount seed endpoint (system.SeedHandler), whose wire contract carries only appId — see api-platform's devseed.Seeder.

func InjectResources

func InjectResources(ctx context.Context, p InjectParams) (context.Context, error)

InjectResources populates ctx with DB/Cache/Storage credentials, app schema, and auth identity from the given params. This is the authoritative gate for AppSchema validation — callers do not need to validate separately.

Returns an error if AppSchema is non-empty and does not match the expected pattern, or if AppRole is not a recognized platform role.

func IsLambda

func IsLambda() bool

IsLambda reports whether the process is running inside AWS Lambda.

func IsOneShot

func IsOneShot() bool

IsOneShot reports whether the process is a managed one-shot task attempt.

func IsTaskWorker

func IsTaskWorker() bool

IsTaskWorker is retained internally as a compatibility alias for mode gates.

func NewLambdaHandler

func NewLambdaHandler(handler http.Handler) func(context.Context, json.RawMessage) (LambdaResponse, error)

NewLambdaHandler wraps an http.Handler into a function compatible with aws-lambda-go's lambda.Start().

func NewLambdaHandlerWithTasks

func NewLambdaHandlerWithTasks(handler http.Handler, moduleID, moduleRef string, handlers map[string]TaskEntry) func(context.Context, json.RawMessage) (LambdaResponse, error)

NewLambdaHandlerWithTasks multiplexes normal HTTP Lambda requests and the platform's typed Standard-task pointer. Task envelopes are recognized before HTTP decoding and execute one broker attempt; they never enter the router.

func RunOneShot

func RunOneShot(parent context.Context, cfg OneShotConfig) error

RunOneShot claims and executes exactly one attempt, then reports exactly one terminal outcome. ErrAttemptAlreadyHandled is returned as nil/no execution.

func TaskAppRefFrom

func TaskAppRefFrom(ctx context.Context) string

TaskAppRefFrom returns the broker-resolved app route reference for nested task enqueue/status/cancel calls.

func TaskDispatchURLFrom

func TaskDispatchURLFrom(ctx context.Context) string

TaskDispatchURLFrom returns the broker-attested dispatch ingress, if this is a one-shot handler context.

func WithModuleCallCapabilityProvider

func WithModuleCallCapabilityProvider(ctx context.Context, provider ModuleCallCapabilityProvider) context.Context

func WithTaskDispatchURL

func WithTaskDispatchURL(ctx context.Context, dispatchURL string) context.Context

WithTaskDispatchURL installs the broker-attested dispatch ingress for a one-shot attempt. It is context-scoped so concurrent warm Standard Lambda invocations never mutate or inherit process-global routing state.

Types

type BrokerArtifact

type BrokerArtifact struct {
	URL       string `json:"url"`
	SHA256    string `json:"sha256"`
	SizeBytes int64  `json:"sizeBytes"`
}

type BrokerCapability

type BrokerCapability struct {
	Token        string    `json:"token"`
	ExpiresAt    time.Time `json:"expiresAt"`
	RefreshAfter time.Time `json:"refreshAfter"`
}

BrokerCapability is the short-lived, attempt-scoped lease capability.

type BrokerClient

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

BrokerClient isolates the versioned task broker HTTP wire contract.

func NewBrokerClient

func NewBrokerClient(rawURL string, httpClient *http.Client) (*BrokerClient, error)

func (*BrokerClient) Claim

func (c *BrokerClient) Claim(ctx context.Context, jobID, attemptID, bootstrapToken string) (ClaimResponse, error)

func (*BrokerClient) Complete

func (c *BrokerClient) Complete(ctx context.Context, jobID, attemptID, token string, result json.RawMessage) error

func (*BrokerClient) Fail

func (c *BrokerClient) Fail(ctx context.Context, jobID, attemptID, token, code, message string, retryable bool) error

func (*BrokerClient) Heartbeat

func (c *BrokerClient) Heartbeat(ctx context.Context, jobID, attemptID, token string) (HeartbeatResponse, error)

func (*BrokerClient) Refresh

func (c *BrokerClient) Refresh(ctx context.Context, jobID, attemptID, token string, kinds []string) (RefreshResponse, error)

type BrokerJob

type BrokerJob struct {
	ID        string    `json:"id"`
	AttemptID string    `json:"attemptId"`
	Handler   string    `json:"handler"`
	Deadline  time.Time `json:"deadline"`
}

type BrokerResources

type BrokerResources struct {
	Database    *db.Credential        `json:"database,omitempty"`
	Storage     *storage.Credential   `json:"storage,omitempty"`
	Cache       *cache.Credential     `json:"cache,omitempty"`
	ModuleCalls *ModuleCallCapability `json:"moduleCalls,omitempty"`
}

BrokerResources is the typed renewable resource snapshot returned by claim and refresh. ModuleCalls is deliberately opaque and never projected as an ambient module/platform secret.

type BrokerWorkload

type BrokerWorkload struct {
	AppID              string `json:"appId"`
	AppRef             string `json:"appRef"`
	ModuleID           string `json:"moduleId"`
	ModuleRef          string `json:"moduleRef"`
	DispatchURL        string `json:"dispatchUrl"`
	VersionID          string `json:"versionId"`
	Version            string `json:"version"`
	AppSchema          string `json:"appSchema"`
	ModulePrefix       string `json:"modulePrefix"`
	Class              string `json:"class"`
	CPUUnits           int    `json:"cpuUnits"`
	MemoryMB           int    `json:"memoryMb"`
	EphemeralStorageMB int    `json:"ephemeralStorageMb"`
	GPUModel           string `json:"gpuModel"`
	GPUCount           int    `json:"gpuCount"`
}

type ClaimResponse

type ClaimResponse struct {
	Version    int              `json:"v"`
	Job        BrokerJob        `json:"job"`
	Workload   BrokerWorkload   `json:"workload"`
	Payload    json.RawMessage  `json:"payload"`
	Artifact   BrokerArtifact   `json:"artifact"`
	Resources  BrokerResources  `json:"resources"`
	Capability BrokerCapability `json:"capability"`
}

func LoadClaimFile

func LoadClaimFile(path string) (ClaimResponse, error)

LoadClaimFile reads the generic runner's preclaimed handoff. It rejects symlinks, non-regular files, group/world permissions, size ambiguity, and trailing JSON so an attacker cannot substitute a less protected source.

type DependencyGrant

type DependencyGrant = db.DependencyGrant

DependencyGrant is the deployed cross-module read manifest entry ridden down the envelope (decision 18 §3). Aliased to db.DependencyGrant so the ctx seam (db.WithDependencies) stores the canonical type without an import cycle (db must not import runtime); the wire tags live on db.DependencyGrant.

type HeartbeatResponse

type HeartbeatResponse struct {
	Version    int               `json:"v"`
	Cancelled  bool              `json:"cancelled"`
	Deadline   time.Time         `json:"deadline"`
	Capability *BrokerCapability `json:"capability,omitempty"`
}

type InjectParams

type InjectParams struct {
	Resources       *Resources
	Dependencies    []DependencyGrant
	UserID          string
	AppID           string
	AppRole         string
	AppSchema       string
	ActorDelegation string
}

InjectParams holds the trusted values to inject into a request context. Used by both the Lambda handler and the task worker — any change here applies to both paths automatically.

type LambdaRequest

type LambdaRequest struct {
	Method  string            `json:"method"`
	Path    string            `json:"path"`
	Headers map[string]string `json:"headers"`
	Body    string            `json:"body"`
	// Invocation is the canonical v1 request-serving context. Its exact bytes
	// are shared with direct HTTP and WSS transports. Control-plane envelopes
	// omit it and retain the legacy fields below.
	Invocation json.RawMessage `json:"invocation,omitempty"`
	Resources  *Resources      `json:"resources,omitempty"`
	// Dependencies is the platform-resolved cross-module read manifest — one
	// entry per installed declared producer, holding only exposed+consented
	// tables at the running version (decision 18 §3). Advisory routing only;
	// the install-time GRANT is the authorizer. omitempty keeps old-SDK
	// backward-compat and old-platform absence (nil → deployed reads stay
	// dev-plane-only, the rollout gate).
	Dependencies []DependencyGrant `json:"dependencies,omitempty"`
	// Trusted fields — injected by platform, not from user headers
	UserID    string `json:"userId,omitempty"`
	AppID     string `json:"appId,omitempty"`
	AppRole   string `json:"appRole,omitempty"`
	AppSchema string `json:"appSchema,omitempty"`
	// ActorDelegation is an opaque, short-lived dispatch-signed assertion.
	// It is a typed trusted field because every inbound X-MS-* claim header is
	// stripped before the module router runs.
	ActorDelegation string `json:"actorDelegation,omitempty"`
}

LambdaRequest is the payload format sent by the platform via Lambda Invoke SDK.

type LambdaResponse

type LambdaResponse struct {
	StatusCode int                 `json:"statusCode"`
	Headers    map[string][]string `json:"headers"`
	Body       string              `json:"body"`
	// IsBase64Encoded says Body is standard base64 of the handler's real bytes.
	//
	// 🔴 A Go string CANNOT CARRY ARBITRARY BYTES THROUGH encoding/json, which
	// is how this envelope travels. The marshaller substitutes U+FFFD for every
	// invalid UTF-8 sequence, silently and without error, so a handler that
	// writes binary gets a body of the right shape and the wrong bytes.
	//
	// Measured in production 2026-09-16: video-core's 16-byte AES playback key
	// reached the browser as 28 bytes — six invalid bytes, each replaced by the
	// three-byte replacement rune — and hls.js decrypted every segment to noise.
	// Nothing logged anything, on any side, because every side did exactly what
	// it was written to do.
	IsBase64Encoded bool `json:"isBase64Encoded,omitempty"`
}

LambdaResponse is returned to the platform after handling a request.

type LambdaTaskEvent

type LambdaTaskEvent struct {
	Version int               `json:"v"`
	Task    LambdaTaskPointer `json:"task"`
}

LambdaTaskEvent is the platform-owned Standard-task pointer. Payload, resources, actor identity, and authority are intentionally absent: the SDK exchanges this one-attempt bootstrap capability with the broker.

type LambdaTaskPointer

type LambdaTaskPointer struct {
	BrokerURL      string `json:"brokerUrl"`
	JobID          string `json:"jobId"`
	AttemptID      string `json:"attemptId"`
	BootstrapToken string `json:"bootstrapToken"`
	OneShot        bool   `json:"oneShot"`
}

type ModuleCallCapability

type ModuleCallCapability struct {
	Token     string    `json:"token"`
	ExpiresAt time.Time `json:"expiresAt"`
}

ModuleCallCapability is a short-lived, task-attempt-scoped credential for authenticated module-to-platform operations.

type ModuleCallCapabilityProvider

type ModuleCallCapabilityProvider interface {
	ModuleCallCapability(context.Context) (ModuleCallCapability, error)
}

ModuleCallCapabilityProvider renews the outbound attempt capability.

func ModuleCallCapabilityProviderFrom

func ModuleCallCapabilityProviderFrom(ctx context.Context) ModuleCallCapabilityProvider

type OneShotConfig

type OneShotConfig struct {
	Broker         *BrokerClient
	JobID          string
	AttemptID      string
	BootstrapToken string
	Preclaimed     *ClaimResponse
	ModuleID       string
	ModuleRef      string
	// ExpectedClass is set by class-specific runtimes such as Standard Lambda.
	// Generic Heavy/GPU runners leave it empty because the signed claim is the
	// authoritative class selection.
	ExpectedClass  string
	Handlers       map[string]TaskEntry
	HeartbeatEvery time.Duration
}

OneShotConfig contains process-local identity and registered handlers. The bootstrap capability is consumed only by Claim and is never placed in the handler context.

type RefreshResponse

type RefreshResponse struct {
	Version    int               `json:"v"`
	Cancelled  bool              `json:"cancelled"`
	Resources  BrokerResources   `json:"resources"`
	Capability *BrokerCapability `json:"capability,omitempty"`
}

type Resources

type Resources struct {
	DB      *db.Credential      `json:"db,omitempty"`
	Cache   *cache.Credential   `json:"cache,omitempty"`
	Storage *storage.Credential `json:"storage,omitempty"`
}

Resources holds per-invocation credentials for all platform services.

type TaskEntry

type TaskEntry struct {
	Handler TaskHandlerFunc
	Timeout time.Duration
}

type TaskHandlerFunc

type TaskHandlerFunc func(context.Context, json.RawMessage) error

Jump to

Keyboard shortcuts

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