deploy
import "github.com/nathabonfim59/pbvex/backend/internal/deploy"Index
- Constants
- Variables
- func AuthenticateComponentIDs(manifest DeploymentManifest, bundleSha string) error
- func CanonicalHash(value JSONValue) (string, error)
- func CanonicalJSON(value JSONValue) (string, error)
- func ComponentCollectionName(namespace, table string) (string, error)
- func ComponentNamespaceID(path string) (string, error)
- func ComponentNamespaces(graph *ComponentGraph) (map[string]ComponentNamespace, error)
- func ComputeComponentID(def ComponentDefinition, bundleSha string) string
- func HashSha256Bytes(b []byte) string
- func IsApplicationErrorCategory(category ApplicationErrorCategory) bool
- func IsExpectedApplicationError(err error) bool
- func IsIdentifier(s string) bool
- func IsSha256Hex(value any) bool
- func LogUnexpectedHandlerFailure(app core.App, err error, fields HandlerFailureContext) bool
- func UploadEnvelopeBytes(decodedLimit int64) int64
- func ValidateHTTPHeaderName(name string) error
- func ValidateHTTPHeaderValue(value string) error
- func ValidateHTTPHeaders(headers map[string][]string) error
- func VerifyModuleSources(modules []ModuleSource, manifest DeploymentManifest) error
- func WrapFunctionFailure(err error, name string, functionType FunctionType, phase FailurePhase) error
- type ActivationObserver
- type ApplicationError
- type ApplicationErrorCategory
- type CallSnapshot
- type ComponentDefinition
- type ComponentGraph
- type ComponentMount
- func ComponentMountForModule(graph *ComponentGraph, modulePath string) (ComponentMount, bool)
- func ComponentMountPathForModule(graph *ComponentGraph, modulePath string) (string, ComponentMount, bool)
- func (m ComponentMount) MarshalJSON() ([]byte, error)
- func (m ComponentMount) MountPath(parent string) string
- func (m *ComponentMount) UnmarshalJSON(data []byte) error
- type ComponentNamespace
- type Config
- type CronJobDescriptor
- type Deployment
- type DeploymentActivateRequest
- type DeploymentActivateResponse
- type DeploymentBundle
- type DeploymentConfig
- type DeploymentListResponse
- type DeploymentManifest
- type DeploymentRollbackResponse
- type DeploymentUploadRequest
- type DeploymentUploadResponse
- type EmailTemplate
- type EmailTemplateManifest
- type EnvArgDescriptor
- type ErrorCode
- type FailurePhase
- type FunctionDescriptor
- type FunctionFailure
- type FunctionRoute
- type FunctionType
- type FunctionVisibility
- type HTTPRequestEnvelope
- type HTTPResponseEnvelope
- type HandlerFailureContext
- type Invalidator
- type JSONValue
- type MigrationDescriptor
- type MigrationWarning
- type ModuleSource
- type Repo
- func NewRepo() *Repo
- func (r *Repo) ApiError(err error) *router.ApiError
- func (r *Repo) CountDeployments(ctx context.Context, app core.App) (int64, error)
- func (r *Repo) CreateDeployment(ctx context.Context, app core.App, manifest DeploymentManifest, bundleJS string, bundleHash string, bundleSize int64) (*core.Record, error)
- func (r *Repo) DeleteOldestInactive(ctx context.Context, app core.App, keep int) ([]string, error)
- func (r *Repo) GetDeployment(ctx context.Context, app core.App, id string) (*core.Record, error)
- func (r *Repo) GetState(ctx context.Context, app core.App) (*core.Record, error)
- func (r *Repo) ListDeployments(ctx context.Context, app core.App) ([]*core.Record, error)
- func (r *Repo) SaveState(ctx context.Context, app core.App, state *core.Record) error
- func (r *Repo) SetDeploymentActivatedAt(ctx context.Context, app core.App, id string, activatedAt types.DateTime) error
- func (r *Repo) SetDeploymentActive(ctx context.Context, app core.App, id string, active bool) error
- type RuntimeInvoker
- type Service
- func NewService(app core.App, repo *Repo, invoker RuntimeInvoker, config Config) *Service
- func (s *Service) Activate(id string, atomic bool) (*DeploymentActivateResponse, error)
- func (s *Service) ActivateContext(ctx context.Context, id string, atomic bool) (*DeploymentActivateResponse, error)
- func (s *Service) Active() (*Deployment, error)
- func (s *Service) ActiveContext(ctx context.Context) (*Deployment, error)
- func (s *Service) ActiveUploadEnvelopeBytes() int64
- func (s *Service) Call(ctx context.Context, functionName string, args any, authArgs ...any) (any, error)
- func (s *Service) CallQuery(ctx context.Context, functionName string, args any) (any, error)
- func (s *Service) Get(id string) (*Deployment, error)
- func (s *Service) GetContext(ctx context.Context, id string) (*Deployment, error)
- func (s *Service) HTTPAction(ctx context.Context, method, path string, envelope *HTTPRequestEnvelope, authArgs ...any) (*HTTPResponseEnvelope, error)
- func (s *Service) Invoke(ctx context.Context, deploymentID, functionName string, args any, authArgs ...any) (any, error)
- func (s *Service) InvokeDeploymentSnapshot(ctx context.Context, deploymentID, bundleHash, functionName string, args any) (any, error)
- func (s *Service) InvokeSnapshot(ctx context.Context, snap *CallSnapshot, args any) (any, error)
- func (s *Service) List() (*DeploymentListResponse, error)
- func (s *Service) ListContext(ctx context.Context) (*DeploymentListResponse, error)
- func (s *Service) LogUnexpectedHandlerFailure(err error, fields HandlerFailureContext) bool
- func (s *Service) MatchHTTPRoute(method, path string) (string, string, bool)
- func (s *Service) MatchHTTPRouteContext(ctx context.Context, method, path string) (string, string, bool)
- func (s *Service) MaxFunctionArgsBytes() int64
- func (s *Service) MaxUploadBytes() int64
- func (s *Service) Pin(ctx context.Context, deploymentID string, delta int) error
- func (s *Service) Resolve(ctx context.Context, deploymentID string) (DeploymentManifest, string, string, error)
- func (s *Service) ResolvePublic(ctx context.Context, functionName string) (*CallSnapshot, error)
- func (s *Service) ResolvePublicQuery(ctx context.Context, functionName string) (*CallSnapshot, error)
- func (s *Service) Rollback(id string) (*DeploymentRollbackResponse, error)
- func (s *Service) RollbackContext(ctx context.Context, id string) (*DeploymentRollbackResponse, error)
- func (s *Service) SetActivationObserver(observer ActivationObserver)
- func (s *Service) SetInvalidator(inv Invalidator)
- func (s *Service) Upload(raw any) (*DeploymentUploadResponse, error)
- func (s *Service) UploadContext(ctx context.Context, raw any) (*DeploymentUploadResponse, error)
- func (s *Service) WarmActive() error
- type StructuredError
- type UploadValidationError
- type ValueSizeError
Constants
const (
MaxHTTPHeaderCount = 100
MaxHTTPHeaderNameBytes = 256
MaxHTTPHeaderValueBytes = 8 << 10
MaxHTTPHeadersBytes = 64 << 10
)const (
SupportedProtocolVersion = "v1"
MaxIdentifierLength = 1024
MaxPathLength = 4096
MaxFieldLength = 1024
MaxValueDepth = 128
SHA256HexLength = 64
MaxEventEnvelopeOverhead = int64(4096)
// MaxFunctionArgsLimit is the canonical protocol ceiling for a deployment's
// maxFunctionArgsBytes config. Manifest validation rejects values above
// this bound so realtime body admission can use limit+overhead as a single
// static ceiling.
MaxFunctionArgsLimit = int64(16 * 1024 * 1024)
// MaxReturnValueLimit is the canonical protocol ceiling for maxReturnValueBytes.
MaxReturnValueLimit = int64(16 * 1024 * 1024)
// MaxDeploymentUploadBytes is the accepted v1 deployment upload contract
// from ADR 001: a 64 MiB decoded bundle. PocketBase's global body limit is
// only 32 MiB, so the deploy route binds an explicit apis.BodyLimit below
// that accepts a maximally base64-encoded bundle plus the bounded manifest
// envelope. ValidateUploadRequest still enforces the decoded cap.
MaxDeploymentUploadBytes int64 = 64 << 20
// MaxUploadEnvelopeBytes is the route-level body limit for the deploy
// endpoint. It overrides PocketBase's 32 MiB global default to accept the
// full v1 contract: a maximally base64-encoded 64 MiB bundle (4/3 ratio)
// plus the bounded manifest envelope. ((n+2)/3)*4 matches
// base64.StdEncoding.EncodedLen for the standard padded alphabet.
MaxUploadEnvelopeBytes int64 = ((MaxDeploymentUploadBytes+2)/3)*4 + maxManifestEnvelopeBytes
)const MaxEmailTemplateBytes = 512 * 1024const MaxEmailTemplates = 64const RootNamespace = "root"Variables
var (
ErrDeploymentNotFound = errors.New("deployment not found")
ErrFunctionNotFound = errors.New("function not found")
ErrActiveNotFound = errors.New("no active deployment")
ErrAlreadyActive = errors.New("deployment is already active")
ErrInvalidBundle = errors.New("bundle failed validation")
ErrInvalidManifest = errors.New("manifest failed validation")
ErrActivationFailed = errors.New("failed to activate deployment")
ErrForbidden = errors.New("forbidden")
ErrPinUnderflow = errors.New("pin count underflow")
)DefaultDeploymentConfig is the fallback configuration used when a manifest does not override it.
var DefaultDeploymentConfig = DeploymentConfig{
HTTPPathPrefix: "/api/pbvex",
RealtimePath: "/api/pbvex/realtime",
MaxUploadBytes: MaxDeploymentUploadBytes,
MaxFunctionArgsBytes: 1024 * 1024,
MaxReturnValueBytes: 1024 * 1024,
DefaultRequestTimeoutMs: 30000,
}func AuthenticateComponentIDs
func AuthenticateComponentIDs(manifest DeploymentManifest, bundleSha string) errorAuthenticateComponentIDs verifies every declared componentId is the canonical content-addressed hash of its definition, including the verified bundleSha. This binds componentId to the exact executable bundle bytes. It mirrors deploy.authenticateComponentID and the TS authenticateComponentIds.
func CanonicalHash
func CanonicalHash(value JSONValue) (string, error)CanonicalHash returns the SHA-256 of the canonical JSON of a value.
func CanonicalJSON
func CanonicalJSON(value JSONValue) (string, error)CanonicalJSON returns a deterministic JSON string for a JSON value.
func ComponentCollectionName
func ComponentCollectionName(namespace, table string) (string, error)ComponentCollectionName maps one logical component table to one durable PocketBase collection. It is deliberately independent of deployment and component content hashes, and bounded independently of user table length.
func ComponentNamespaceID
func ComponentNamespaceID(path string) (string, error)ComponentNamespaceID is stable for a canonical mount path across component upgrades and deployment IDs. Renaming a mount intentionally creates a new namespace and leaves the old data dormant.
func ComponentNamespaces
func ComponentNamespaces(graph *ComponentGraph) (map[string]ComponentNamespace, error)ComponentNamespaces builds the validated deployment catalog. The returned map is keyed by mount path and therefore permits the same definition to be mounted repeatedly without sharing storage.
func ComputeComponentID
func ComputeComponentID(def ComponentDefinition, bundleSha string) stringComputeComponentID returns the canonical content-addressed componentId for a component definition. bundleSha is the verified SHA-256 hex of the executable bundle; including it in the hash input binds the componentId to the exact bytes the runtime will execute, not just the declared module sources. It mirrors the TS bundler's buildComponentGraph hash so Go-generated and TS-generated ids are byte-identical.
func HashSha256Bytes
func HashSha256Bytes(b []byte) stringHashSha256Bytes returns the SHA-256 hex of bytes.
func IsApplicationErrorCategory
func IsApplicationErrorCategory(category ApplicationErrorCategory) boolIsApplicationErrorCategory reports whether category has a defined HTTP mapping.
func IsExpectedApplicationError
func IsExpectedApplicationError(err error) boolIsExpectedApplicationError reports whether err is a handler-authored normal outcome.
func IsIdentifier
func IsIdentifier(s string) boolIsIdentifier reports whether s is a valid protocol identifier.
func IsSha256Hex
func IsSha256Hex(value any) boolfunc LogUnexpectedHandlerFailure
func LogUnexpectedHandlerFailure(app core.App, err error, fields HandlerFailureContext) boolLogUnexpectedHandlerFailure records an unexpected function failure once at an outward execution boundary. ApplicationError and caller cancellation are normal outcomes and are deliberately excluded.
func UploadEnvelopeBytes
func UploadEnvelopeBytes(decodedLimit int64) int64UploadEnvelopeBytes returns the maximum wire-level body size that can carry a deployment upload whose decoded bundle is at most decodedLimit bytes. It accounts for base64 padding (((n+2)/3)*4, matching StdEncoding.EncodedLen) and the bounded manifest envelope overhead. When decodedLimit equals MaxDeploymentUploadBytes the result equals MaxUploadEnvelopeBytes.
func ValidateHTTPHeaderName
func ValidateHTTPHeaderName(name string) errorfunc ValidateHTTPHeaderValue
func ValidateHTTPHeaderValue(value string) errorfunc ValidateHTTPHeaders
func ValidateHTTPHeaders(headers map[string][]string) errorValidateHTTPHeaders applies the same deterministic bounds used by the JS Headers implementation. Count and aggregate size are measured per value.
func VerifyModuleSources
func VerifyModuleSources(modules []ModuleSource, manifest DeploymentManifest) errorVerifyModuleSources recomputes the canonical SHA-256 of each uploaded module from its actual bytes and rejects missing/extra/mismatched module paths for the component graph. This ties the manifest's declared moduleHashes (and therefore the content-addressed componentId) to the actual uploaded executable module bytes, not client-declared hashes.
func WrapFunctionFailure
func WrapFunctionFailure(err error, name string, functionType FunctionType, phase FailurePhase) errorWrapFunctionFailure adds function context unless an inner invocation already did.
type ActivationObserver
ActivationObserver is notified after a new active deployment commits and when the persisted active deployment is warmed during bootstrap.
type ActivationObserver interface {
ActiveDeploymentChanged(deploymentID string, manifest DeploymentManifest)
}type ApplicationError
ApplicationError carries validated PBVex wire data from a handler failure.
type ApplicationError struct {
Category ApplicationErrorCategory
Data any
HasData bool
}func (*ApplicationError) Error
func (e *ApplicationError) Error() stringtype ApplicationErrorCategory
ApplicationErrorCategory is a handler-selected, status-mapped error category.
type ApplicationErrorCategory stringconst (
ApplicationErrorBadRequest ApplicationErrorCategory = "bad_request"
ApplicationErrorUnauthorized ApplicationErrorCategory = "unauthorized"
ApplicationErrorForbidden ApplicationErrorCategory = "forbidden"
ApplicationErrorNotFound ApplicationErrorCategory = "not_found"
ApplicationErrorConflict ApplicationErrorCategory = "conflict"
)type CallSnapshot
CallSnapshot captures the resolved active deployment and function for a call. It is safe to use without invoking user code.
type CallSnapshot struct {
DeploymentID string
BundleJS string
Functions []FunctionDescriptor
Descriptor *FunctionDescriptor
Config DeploymentConfig
Manifest DeploymentManifest
}type ComponentDefinition
ComponentDefinition describes a reusable component package. It is independent of any mount name and is referenced by a deterministic hash.
type ComponentDefinition struct {
ComponentID string `json:"componentId"`
ModulePaths []string `json:"modulePaths"`
ModuleHashes map[string]string `json:"moduleHashes,omitempty"`
Schema JSONValue `json:"schema,omitempty"`
Args JSONValue `json:"args,omitempty"`
Env map[string]EnvArgDescriptor `json:"env,omitempty"`
Dependencies []string `json:"dependencies,omitempty"`
}type ComponentGraph
ComponentGraph is the canonical component DAG carried by a deployment manifest. The same component definition can be mounted multiple times; each mount is a node in the mount tree and has its own namespace.
type ComponentGraph struct {
Definitions []ComponentDefinition `json:"definitions,omitempty"`
Mounts []ComponentMount `json:"mounts,omitempty"`
}func ValidateComponents
func ValidateComponents(value any) (*ComponentGraph, error)ValidateComponents validates the component graph attached to a manifest. It checks identifiers, duplicate mounts, cycles, missing definitions, module path collisions, and component arg values against their definition.
type ComponentMount
ComponentMount is an instance of a component definition in the app tree. Name is the mount identity within the parent; full mount path is the path through the mount tree, e.g. "parent/child".
type ComponentMount struct {
Name string `json:"name"`
ComponentID string `json:"componentId"`
Args JSONValue `json:"args,omitempty"`
Children []ComponentMount `json:"children,omitempty"`
// ArgsPresent tracks whether the "args" key was present in the JSON,
// distinguishing explicit null from absent.
ArgsPresent bool `json:"-"`
}func ComponentMountForModule
func ComponentMountForModule(graph *ComponentGraph, modulePath string) (ComponentMount, bool)ComponentMountForModule returns the deepest mount owning modulePath. The manifest validator guarantees that the relative module belongs to the returned definition, so runtime and schema code can use this as the single namespace-resolution primitive.
func ComponentMountPathForModule
func ComponentMountPathForModule(graph *ComponentGraph, modulePath string) (string, ComponentMount, bool)ComponentMountPathForModule is the path-bearing companion used to derive a stable namespace. It deliberately hashes the canonical mount path, not the content-addressed component definition, so upgrades preserve data.
func (ComponentMount) MarshalJSON
func (m ComponentMount) MarshalJSON() ([]byte, error)MarshalJSON preserves omitted args versus explicit JSON null without exposing the internal ArgsPresent marker on the deployment protocol.
func (ComponentMount) MountPath
func (m ComponentMount) MountPath(parent string) stringMountPath returns the path of this mount from its parent path. The root mount path is empty.
func (*ComponentMount) UnmarshalJSON
func (m *ComponentMount) UnmarshalJSON(data []byte) errorUnmarshalJSON retains presence even when args is null.
type ComponentNamespace
type ComponentNamespace struct {
ID string
Path string
Mount ComponentMount
Definition ComponentDefinition
Schema JSONValue
PhysicalByTable map[string]string
}func NamespaceForModule
func NamespaceForModule(manifest DeploymentManifest, modulePath string) (ComponentNamespace, bool)NamespaceForModule resolves a function to its mount catalog entry.
type Config
Config controls deployment service behavior.
type Config struct {
HistoryLimit int
PoolSize int
}func DefaultConfig
func DefaultConfig() ConfigDefaultConfig returns the default deployment configuration.
type CronJobDescriptor
CronJobDescriptor is a recurring PocketBase cron tick that enqueues a durable PBVex mutation or action.
type CronJobDescriptor struct {
Name string `json:"name"`
Schedule string `json:"schedule"`
FunctionName string `json:"functionName"`
Args JSONValue `json:"args"`
}type Deployment
Deployment is a stored deployment record.
type Deployment struct {
DeploymentID string `json:"deploymentId"`
Manifest DeploymentManifest `json:"manifest"`
Bundle DeploymentBundle `json:"bundle"`
CreatedAt string `json:"createdAt"`
ActivatedAt *string `json:"activatedAt,omitempty"`
Active bool `json:"active"`
}func ValidateDeployment
func ValidateDeployment(value any) (Deployment, error)ValidateDeployment validates a stored deployment shape.
type DeploymentActivateRequest
DeploymentActivateRequest is the body of the activate API.
type DeploymentActivateRequest struct {
Atomic bool `json:"atomic"`
}func ValidateActivateRequest
func ValidateActivateRequest(value any) (DeploymentActivateRequest, error)ValidateActivateRequest validates the activate request body.
type DeploymentActivateResponse
DeploymentActivateResponse is the activate API response.
type DeploymentActivateResponse struct {
DeploymentID string `json:"deploymentId"`
ActivatedAt string `json:"activatedAt"`
PreviousDeploymentID *string `json:"previousDeploymentId,omitempty"`
Warnings []MigrationWarning `json:"warnings,omitempty"`
}type DeploymentBundle
DeploymentBundle is the stored representation of a bundle.
type DeploymentBundle struct {
JS string `json:"js"`
Sha256 string `json:"sha256"`
Size int64 `json:"size"`
}type DeploymentConfig
DeploymentConfig is the runtime config embedded in a manifest.
type DeploymentConfig struct {
HTTPPathPrefix string `json:"httpPathPrefix"`
RealtimePath string `json:"realtimePath"`
MaxUploadBytes int64 `json:"maxUploadBytes"`
MaxFunctionArgsBytes int64 `json:"maxFunctionArgsBytes"`
MaxReturnValueBytes int64 `json:"maxReturnValueBytes"`
DefaultRequestTimeoutMs int64 `json:"defaultRequestTimeoutMs"`
// contains filtered or unexported fields
}func NormalizeConfig
func NormalizeConfig(cfg *DeploymentConfig) DeploymentConfigNormalizeConfig fills missing fields with default values.
type DeploymentListResponse
DeploymentListResponse is the list API response.
type DeploymentListResponse struct {
Deployments []Deployment `json:"deployments"`
}func ValidateDeploymentListResponse
func ValidateDeploymentListResponse(value any) (DeploymentListResponse, error)ValidateDeploymentListResponse validates a list response.
type DeploymentManifest
DeploymentManifest is the v1 protocol deployment manifest.
type DeploymentManifest struct {
ProtocolVersion string `json:"protocolVersion"`
DeploymentID string `json:"deploymentId"`
Functions []FunctionDescriptor `json:"functions,omitempty"`
Components *ComponentGraph `json:"components,omitempty"`
Config *DeploymentConfig `json:"config,omitempty"`
Schema JSONValue `json:"schema,omitempty"`
EmailTemplates *EmailTemplateManifest `json:"emailTemplates,omitempty"`
CronJobs []CronJobDescriptor `json:"cronJobs,omitempty"`
Migrations []MigrationDescriptor `json:"migrations,omitempty"`
}func ValidateManifest
func ValidateManifest(value any) (DeploymentManifest, error)ValidateManifest validates the manifest per protocol v1.
type DeploymentRollbackResponse
DeploymentRollbackResponse is the rollback API response.
type DeploymentRollbackResponse struct {
DeploymentID string `json:"deploymentId"`
RolledBackAt string `json:"rolledBackAt"`
RestoredDeploymentID *string `json:"restoredDeploymentId,omitempty"`
}type DeploymentUploadRequest
DeploymentUploadRequest is the body of the upload API.
type DeploymentUploadRequest struct {
Manifest DeploymentManifest `json:"manifest"`
Bundle string `json:"bundle"`
Sha256 string `json:"sha256"`
Size int64 `json:"size"`
Modules []ModuleSource `json:"modules,omitempty"`
}func ValidateUploadRequest
func ValidateUploadRequest(value any) (DeploymentUploadRequest, []byte, error)ValidateUploadRequest validates the request body and decoded bundle bytes.
type DeploymentUploadResponse
DeploymentUploadResponse is the upload API response.
type DeploymentUploadResponse struct {
DeploymentID string `json:"deploymentId"`
BundleHash string `json:"bundleHash"`
AcceptedAt string `json:"acceptedAt"`
}type EmailTemplate
type EmailTemplate struct {
Name string `json:"name"`
Subject string `json:"subject"`
Text string `json:"text,omitempty"`
HTML string `json:"html,omitempty"`
}type EmailTemplateManifest
type EmailTemplateManifest struct {
Sha256 string `json:"sha256"`
Entries []EmailTemplate `json:"entries"`
}type EnvArgDescriptor
EnvArgDescriptor describes a component env value binding. Type is "value" for a literal string or "envVar" for a parent env reference.
type EnvArgDescriptor struct {
Type string `json:"type"`
Value string `json:"value,omitempty"`
Name string `json:"name,omitempty"`
}type ErrorCode
ErrorCode enumerates the protocol error codes.
type ErrorCode stringconst (
ErrorCodeBadRequest ErrorCode = "bad_request"
ErrorCodeInvalidManifest ErrorCode = "invalid_manifest"
ErrorCodeInvalidFunction ErrorCode = "invalid_function"
ErrorCodeBundleNotFound ErrorCode = "bundle_not_found"
ErrorCodeBundleHashMismatch ErrorCode = "bundle_hash_mismatch"
ErrorCodeActivationFailed ErrorCode = "activation_failed"
ErrorCodeNotFound ErrorCode = "not_found"
ErrorCodeUnauthorized ErrorCode = "unauthorized"
ErrorCodeForbidden ErrorCode = "forbidden"
ErrorCodeConflict ErrorCode = "conflict"
ErrorCodeInternal ErrorCode = "internal"
ErrorCodeUploadExpired ErrorCode = "upload_expired"
ErrorCodeUploadConsumed ErrorCode = "upload_consumed"
ErrorCodeUploadPending ErrorCode = "upload_pending"
ErrorCodeUploadTooLarge ErrorCode = "upload_too_large"
ErrorCodeInvalidContent ErrorCode = "invalid_content"
ErrorCodeStorageFull ErrorCode = "storage_full"
)type FailurePhase
FailurePhase identifies the stage at which a function invocation failed.
type FailurePhase stringconst (
FailurePhaseHandlerExecution FailurePhase = "handler_execution"
FailurePhaseArgumentValidation FailurePhase = "argument_validation"
FailurePhaseReturnValidation FailurePhase = "return_validation"
FailurePhaseTimeout FailurePhase = "timeout"
FailurePhaseArgumentLimit FailurePhase = "argument_limit"
FailurePhaseReturnLimit FailurePhase = "return_limit"
FailurePhaseRuntimeSetup FailurePhase = "runtime_setup"
)func FailurePhaseFor
func FailurePhaseFor(err error) FailurePhaseFailurePhaseFor classifies failures without inspecting or logging invocation values.
type FunctionDescriptor
FunctionDescriptor is the v1 protocol function descriptor.
type FunctionDescriptor struct {
Name string `json:"name"`
Type FunctionType `json:"type"`
Visibility FunctionVisibility `json:"visibility"`
ModulePath string `json:"modulePath"`
ExportName string `json:"exportName"`
Args JSONValue `json:"args,omitempty"`
Returns JSONValue `json:"returns,omitempty"`
Route *FunctionRoute `json:"route,omitempty"`
}type FunctionFailure
FunctionFailure adds safe invocation metadata while retaining the original error.
type FunctionFailure struct {
FunctionName string
FunctionType FunctionType
Phase FailurePhase
Err error
}func (*FunctionFailure) Error
func (e *FunctionFailure) Error() stringfunc (*FunctionFailure) Unwrap
func (e *FunctionFailure) Unwrap() errortype FunctionRoute
FunctionRoute is the HTTP route metadata for an httpAction.
type FunctionRoute struct {
Method string `json:"method,omitempty"`
Path string `json:"path,omitempty"`
PathPrefix string `json:"pathPrefix,omitempty"`
}type FunctionType
FunctionType enumerates the supported function types.
type FunctionType stringconst (
FunctionTypeQuery FunctionType = "query"
FunctionTypeMutation FunctionType = "mutation"
FunctionTypeAction FunctionType = "action"
FunctionTypeHTTPAction FunctionType = "httpAction"
)type FunctionVisibility
FunctionVisibility enumerates the supported function visibilities.
type FunctionVisibility stringconst (
FunctionVisibilityPublic FunctionVisibility = "public"
FunctionVisibilityInternal FunctionVisibility = "internal"
)type HTTPRequestEnvelope
HTTPRequestEnvelope is the representation of an HTTP request passed to an httpAction handler. The body is the raw bytes to avoid double JSON encoding.
type HTTPRequestEnvelope struct {
Method string `json:"method"`
URL string `json:"url"`
Headers map[string][]string `json:"headers,omitempty"`
Body []byte `json:"body,omitempty"`
}type HTTPResponseEnvelope
HTTPResponseEnvelope is the representation of an HTTP response returned from an httpAction handler. The body is the raw bytes.
type HTTPResponseEnvelope struct {
Status int `json:"status"`
Headers map[string][]string `json:"headers,omitempty"`
Body []byte `json:"body,omitempty"`
}type HandlerFailureContext
HandlerFailureContext contains only bounded, non-value invocation identifiers.
type HandlerFailureContext struct {
RequestID string
SubscriptionID string
JobID string
FunctionName string
FunctionType FunctionType
Phase FailurePhase
}type Invalidator
Invalidator is notified when the active deployment changes so that realtime subscriptions can be re-evaluated.
type Invalidator interface {
// InvalidateAll notifies active subscriptions to re-run their queries
// without dropping the connection (used for record mutations).
InvalidateAll()
// ReconnectAll closes all active subscription connections so clients
// reconnect and re-negotiate limits with the newly active deployment.
// Used on activation/rollback where config (maxReturnValueBytes etc.)
// may differ from the pinned snapshot.
ReconnectAll()
}type JSONValue
JSONValue is the Go equivalent of the protocol JSONValue union.
type JSONValue = anytype MigrationDescriptor
MigrationDescriptor is a pure, reversible document transform registered by the deployment bundle.
type MigrationDescriptor struct {
ID string `json:"id"`
Table string `json:"table"`
Mode string `json:"mode"`
From JSONValue `json:"from"`
To JSONValue `json:"to"`
SourceSchemaHash string `json:"sourceSchemaHash"`
TargetSchemaHash string `json:"targetSchemaHash"`
Checksum string `json:"checksum"`
ModulePath string `json:"modulePath"`
ExportName string `json:"exportName"`
Reversibility string `json:"reversibility"`
}type MigrationWarning
type MigrationWarning struct {
Code string `json:"code"`
Rows int `json:"rows"`
RowLimit int `json:"rowLimit"`
EstimatedBytes int64 `json:"estimatedBytes"`
ByteLimit int64 `json:"byteLimit"`
UtilizationPercent int `json:"utilizationPercent"`
}type ModuleSource
ModuleSource authenticates the unbundled source assigned to a component mount. The executable bundle remains the runtime artifact; these bytes bind each component definition and function namespace to reviewed source.
type ModuleSource struct {
Path string `json:"path"`
Bytes string `json:"bytes"`
}type Repo
Repo provides persistence access for deployment records.
type Repo struct{}func NewRepo
func NewRepo() *RepoNewRepo creates a new deployment repository.
func (*Repo) ApiError
func (r *Repo) ApiError(err error) *router.ApiErrorApiError maps deployment errors to router API errors.
func (*Repo) CountDeployments
func (r *Repo) CountDeployments(ctx context.Context, app core.App) (int64, error)CountDeployments returns the total number of deployments.
func (*Repo) CreateDeployment
func (r *Repo) CreateDeployment(ctx context.Context, app core.App, manifest DeploymentManifest, bundleJS string, bundleHash string, bundleSize int64) (*core.Record, error)CreateDeployment stores a new deployment record.
func (*Repo) DeleteOldestInactive
func (r *Repo) DeleteOldestInactive(ctx context.Context, app core.App, keep int) ([]string, error)DeleteOldestInactive removes the oldest inactive deployments beyond the limit. Protected (active/previous), pinned (pinCount > 0), and job-referenced deployments are filtered out BEFORE applying the keep quota so they cannot consume deletion slots and starve later eligible deployments. The remaining deletable candidates are ordered oldest-first; the newest `keep` are retained and the rest are deleted with a conditional DELETE (pinCount = 0 AND NOT EXISTS job) that remains atomic with concurrent job creation/retry.
func (*Repo) GetDeployment
func (r *Repo) GetDeployment(ctx context.Context, app core.App, id string) (*core.Record, error)GetDeployment returns a deployment record by deploymentId.
func (*Repo) GetState
func (r *Repo) GetState(ctx context.Context, app core.App) (*core.Record, error)GetState returns the active state record.
func (*Repo) ListDeployments
func (r *Repo) ListDeployments(ctx context.Context, app core.App) ([]*core.Record, error)ListDeployments returns deployments ordered by creation descending.
func (*Repo) SaveState
func (r *Repo) SaveState(ctx context.Context, app core.App, state *core.Record) errorSaveState persists the state record.
func (*Repo) SetDeploymentActivatedAt
func (r *Repo) SetDeploymentActivatedAt(ctx context.Context, app core.App, id string, activatedAt types.DateTime) errorSetDeploymentActivatedAt updates the activated timestamp on a deployment.
func (*Repo) SetDeploymentActive
func (r *Repo) SetDeploymentActive(ctx context.Context, app core.App, id string, active bool) errorSetDeploymentActive updates the active boolean on a deployment.
type RuntimeInvoker
RuntimeInvoker is the interface required by the deployment service for runtime operations. RuntimeInvoker is intentionally structural at the Service boundary. PBVex supports the original narrow embedder contract and the richer authenticated runtime without forcing existing embedders to change method signatures.
type RuntimeInvoker anytype Service
Service is the application layer for deployments.
type Service struct {
// contains filtered or unexported fields
}func NewService
func NewService(app core.App, repo *Repo, invoker RuntimeInvoker, config Config) *ServiceNewService creates a new deployment service.
func (*Service) Activate
func (s *Service) Activate(id string, atomic bool) (*DeploymentActivateResponse, error)Activate atomically switches the active deployment to id.
func (*Service) ActivateContext
func (s *Service) ActivateContext(ctx context.Context, id string, atomic bool) (*DeploymentActivateResponse, error)func (*Service) Active
func (s *Service) Active() (*Deployment, error)Active returns the currently active deployment.
func (*Service) ActiveContext
func (s *Service) ActiveContext(ctx context.Context) (*Deployment, error)func (*Service) ActiveUploadEnvelopeBytes
func (s *Service) ActiveUploadEnvelopeBytes() int64func (*Service) Call
func (s *Service) Call(ctx context.Context, functionName string, args any, authArgs ...any) (any, error)Call invokes a public function on the currently active deployment.
func (*Service) CallQuery
func (s *Service) CallQuery(ctx context.Context, functionName string, args any) (any, error)CallQuery invokes a public query function on the currently active deployment.
func (*Service) Get
func (s *Service) Get(id string) (*Deployment, error)Get returns a single deployment by deploymentId.
func (*Service) GetContext
func (s *Service) GetContext(ctx context.Context, id string) (*Deployment, error)func (*Service) HTTPAction
func (s *Service) HTTPAction(ctx context.Context, method, path string, envelope *HTTPRequestEnvelope, authArgs ...any) (*HTTPResponseEnvelope, error)HTTPAction resolves and invokes a public HTTP action on the active snapshot.
func (*Service) Invoke
func (s *Service) Invoke(ctx context.Context, deploymentID, functionName string, args any, authArgs ...any) (any, error)Invoke loads a deployment bundle and calls a registered function.
func (*Service) InvokeDeploymentSnapshot
func (s *Service) InvokeDeploymentSnapshot(ctx context.Context, deploymentID, bundleHash, functionName string, args any) (any, error)InvokeDeploymentSnapshot invokes a scheduled function against the exact deployment and bundle hash captured when the job was created.
func (*Service) InvokeSnapshot
func (s *Service) InvokeSnapshot(ctx context.Context, snap *CallSnapshot, args any) (any, error)InvokeSnapshot invokes a function against a pre-resolved CallSnapshot without re-resolving the active deployment. This guarantees the invocation runs against the exact deployment that was active at admission time, even if a new deployment is activated mid-connection.
func (*Service) List
func (s *Service) List() (*DeploymentListResponse, error)List returns all stored deployments with the active flag.
func (*Service) ListContext
func (s *Service) ListContext(ctx context.Context) (*DeploymentListResponse, error)func (*Service) LogUnexpectedHandlerFailure
func (s *Service) LogUnexpectedHandlerFailure(err error, fields HandlerFailureContext) boolLogUnexpectedHandlerFailure records a failure through the service's app logger.
func (*Service) MatchHTTPRoute
func (s *Service) MatchHTTPRoute(method, path string) (string, string, bool)func (*Service) MatchHTTPRouteContext
func (s *Service) MatchHTTPRouteContext(ctx context.Context, method, path string) (string, string, bool)func (*Service) MaxFunctionArgsBytes
func (s *Service) MaxFunctionArgsBytes() int64func (*Service) MaxUploadBytes
func (s *Service) MaxUploadBytes() int64func (*Service) Pin
func (s *Service) Pin(ctx context.Context, deploymentID string, delta int) errorPin atomically adjusts the deployment's durable scheduler reference count.
func (*Service) Resolve
func (s *Service) Resolve(ctx context.Context, deploymentID string) (DeploymentManifest, string, string, error)Resolve returns the immutable bundle metadata for a deployment. Scheduler jobs persist this snapshot and pin the deployment until the job is terminal.
func (*Service) ResolvePublic
func (s *Service) ResolvePublic(ctx context.Context, functionName string) (*CallSnapshot, error)ResolvePublic returns a snapshot for a public function on the active deployment.
func (*Service) ResolvePublicQuery
func (s *Service) ResolvePublicQuery(ctx context.Context, functionName string) (*CallSnapshot, error)ResolvePublicQuery returns a snapshot for a public query function on the active deployment.
func (*Service) Rollback
func (s *Service) Rollback(id string) (*DeploymentRollbackResponse, error)Rollback restores the previous active deployment.
func (*Service) RollbackContext
func (s *Service) RollbackContext(ctx context.Context, id string) (*DeploymentRollbackResponse, error)func (*Service) SetActivationObserver
func (s *Service) SetActivationObserver(observer ActivationObserver)SetActivationObserver installs the active-deployment lifecycle observer.
func (*Service) SetInvalidator
func (s *Service) SetInvalidator(inv Invalidator)SetInvalidator sets the invalidator that is notified on activation/rollback.
func (*Service) Upload
func (s *Service) Upload(raw any) (*DeploymentUploadResponse, error)Upload validates, stores, and prepares a new deployment.
func (*Service) UploadContext
func (s *Service) UploadContext(ctx context.Context, raw any) (*DeploymentUploadResponse, error)UploadContext is the request-aware form used by the HTTP API. The legacy Upload method remains for embedders, but lifecycle work must otherwise keep the caller's cancellation/deadline all the way through verification and DB writes.
func (*Service) WarmActive
func (s *Service) WarmActive() errorWarmActive loads and verifies the currently active deployment runtime.
type StructuredError
StructuredError is the protocol error envelope.
type StructuredError struct {
Error bool `json:"error"`
Code ErrorCode `json:"code"`
Message string `json:"message"`
Details []any `json:"details,omitempty"`
Data *any `json:"data,omitempty"`
RequestID string `json:"requestId,omitempty"`
}type UploadValidationError
type UploadValidationError struct {
Code ErrorCode
Err error
}func (*UploadValidationError) Error
func (e *UploadValidationError) Error() stringfunc (*UploadValidationError) Unwrap
func (e *UploadValidationError) Unwrap() errortype ValueSizeError
ValueSizeError is returned when a wire value exceeds a configured size limit.
type ValueSizeError struct {
Label string
Limit int64
}func (*ValueSizeError) Error
func (e *ValueSizeError) Error() stringGenerated by gomarkdoc