Skip to content

deploy

go
import "github.com/nathabonfim59/pbvex/backend/internal/deploy"

Index

Constants

go
const (
    MaxHTTPHeaderCount      = 100
    MaxHTTPHeaderNameBytes  = 256
    MaxHTTPHeaderValueBytes = 8 << 10
    MaxHTTPHeadersBytes     = 64 << 10
)

go
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
)

go
const MaxEmailTemplateBytes = 512 * 1024

go
const MaxEmailTemplates = 64

go
const RootNamespace = "root"

Variables

go
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.

go
var DefaultDeploymentConfig = DeploymentConfig{
    HTTPPathPrefix:          "/api/pbvex",
    RealtimePath:            "/api/pbvex/realtime",
    MaxUploadBytes:          MaxDeploymentUploadBytes,
    MaxFunctionArgsBytes:    1024 * 1024,
    MaxReturnValueBytes:     1024 * 1024,
    DefaultRequestTimeoutMs: 30000,
}

func AuthenticateComponentIDs

go
func AuthenticateComponentIDs(manifest DeploymentManifest, bundleSha string) error

AuthenticateComponentIDs 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

go
func CanonicalHash(value JSONValue) (string, error)

CanonicalHash returns the SHA-256 of the canonical JSON of a value.

func CanonicalJSON

go
func CanonicalJSON(value JSONValue) (string, error)

CanonicalJSON returns a deterministic JSON string for a JSON value.

func ComponentCollectionName

go
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

go
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

go
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

go
func ComputeComponentID(def ComponentDefinition, bundleSha string) string

ComputeComponentID 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

go
func HashSha256Bytes(b []byte) string

HashSha256Bytes returns the SHA-256 hex of bytes.

func IsApplicationErrorCategory

go
func IsApplicationErrorCategory(category ApplicationErrorCategory) bool

IsApplicationErrorCategory reports whether category has a defined HTTP mapping.

func IsExpectedApplicationError

go
func IsExpectedApplicationError(err error) bool

IsExpectedApplicationError reports whether err is a handler-authored normal outcome.

func IsIdentifier

go
func IsIdentifier(s string) bool

IsIdentifier reports whether s is a valid protocol identifier.

func IsSha256Hex

go
func IsSha256Hex(value any) bool

func LogUnexpectedHandlerFailure

go
func LogUnexpectedHandlerFailure(app core.App, err error, fields HandlerFailureContext) bool

LogUnexpectedHandlerFailure records an unexpected function failure once at an outward execution boundary. ApplicationError and caller cancellation are normal outcomes and are deliberately excluded.

func UploadEnvelopeBytes

go
func UploadEnvelopeBytes(decodedLimit int64) int64

UploadEnvelopeBytes 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

go
func ValidateHTTPHeaderName(name string) error

func ValidateHTTPHeaderValue

go
func ValidateHTTPHeaderValue(value string) error

func ValidateHTTPHeaders

go
func ValidateHTTPHeaders(headers map[string][]string) error

ValidateHTTPHeaders applies the same deterministic bounds used by the JS Headers implementation. Count and aggregate size are measured per value.

func VerifyModuleSources

go
func VerifyModuleSources(modules []ModuleSource, manifest DeploymentManifest) error

VerifyModuleSources 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

go
func WrapFunctionFailure(err error, name string, functionType FunctionType, phase FailurePhase) error

WrapFunctionFailure 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.

go
type ActivationObserver interface {
    ActiveDeploymentChanged(deploymentID string, manifest DeploymentManifest)
}

type ApplicationError

ApplicationError carries validated PBVex wire data from a handler failure.

go
type ApplicationError struct {
    Category ApplicationErrorCategory
    Data     any
    HasData  bool
}

func (*ApplicationError) Error

go
func (e *ApplicationError) Error() string

type ApplicationErrorCategory

ApplicationErrorCategory is a handler-selected, status-mapped error category.

go
type ApplicationErrorCategory string

go
const (
    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.

go
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.

go
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.

go
type ComponentGraph struct {
    Definitions []ComponentDefinition `json:"definitions,omitempty"`
    Mounts      []ComponentMount      `json:"mounts,omitempty"`
}

func ValidateComponents

go
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".

go
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

go
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

go
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

go
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

go
func (m ComponentMount) MountPath(parent string) string

MountPath returns the path of this mount from its parent path. The root mount path is empty.

func (*ComponentMount) UnmarshalJSON

go
func (m *ComponentMount) UnmarshalJSON(data []byte) error

UnmarshalJSON retains presence even when args is null.

type ComponentNamespace

go
type ComponentNamespace struct {
    ID              string
    Path            string
    Mount           ComponentMount
    Definition      ComponentDefinition
    Schema          JSONValue
    PhysicalByTable map[string]string
}

func NamespaceForModule

go
func NamespaceForModule(manifest DeploymentManifest, modulePath string) (ComponentNamespace, bool)

NamespaceForModule resolves a function to its mount catalog entry.

type Config

Config controls deployment service behavior.

go
type Config struct {
    HistoryLimit int
    PoolSize     int
}

func DefaultConfig

go
func DefaultConfig() Config

DefaultConfig returns the default deployment configuration.

type CronJobDescriptor

CronJobDescriptor is a recurring PocketBase cron tick that enqueues a durable PBVex mutation or action.

go
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.

go
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

go
func ValidateDeployment(value any) (Deployment, error)

ValidateDeployment validates a stored deployment shape.

type DeploymentActivateRequest

DeploymentActivateRequest is the body of the activate API.

go
type DeploymentActivateRequest struct {
    Atomic bool `json:"atomic"`
}

func ValidateActivateRequest

go
func ValidateActivateRequest(value any) (DeploymentActivateRequest, error)

ValidateActivateRequest validates the activate request body.

type DeploymentActivateResponse

DeploymentActivateResponse is the activate API response.

go
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.

go
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.

go
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

go
func NormalizeConfig(cfg *DeploymentConfig) DeploymentConfig

NormalizeConfig fills missing fields with default values.

type DeploymentListResponse

DeploymentListResponse is the list API response.

go
type DeploymentListResponse struct {
    Deployments []Deployment `json:"deployments"`
}

func ValidateDeploymentListResponse

go
func ValidateDeploymentListResponse(value any) (DeploymentListResponse, error)

ValidateDeploymentListResponse validates a list response.

type DeploymentManifest

DeploymentManifest is the v1 protocol deployment manifest.

go
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

go
func ValidateManifest(value any) (DeploymentManifest, error)

ValidateManifest validates the manifest per protocol v1.

type DeploymentRollbackResponse

DeploymentRollbackResponse is the rollback API response.

go
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.

go
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

go
func ValidateUploadRequest(value any) (DeploymentUploadRequest, []byte, error)

ValidateUploadRequest validates the request body and decoded bundle bytes.

type DeploymentUploadResponse

DeploymentUploadResponse is the upload API response.

go
type DeploymentUploadResponse struct {
    DeploymentID string `json:"deploymentId"`
    BundleHash   string `json:"bundleHash"`
    AcceptedAt   string `json:"acceptedAt"`
}

type EmailTemplate

go
type EmailTemplate struct {
    Name    string `json:"name"`
    Subject string `json:"subject"`
    Text    string `json:"text,omitempty"`
    HTML    string `json:"html,omitempty"`
}

type EmailTemplateManifest

go
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.

go
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.

go
type ErrorCode string

go
const (
    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.

go
type FailurePhase string

go
const (
    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

go
func FailurePhaseFor(err error) FailurePhase

FailurePhaseFor classifies failures without inspecting or logging invocation values.

type FunctionDescriptor

FunctionDescriptor is the v1 protocol function descriptor.

go
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.

go
type FunctionFailure struct {
    FunctionName string
    FunctionType FunctionType
    Phase        FailurePhase
    Err          error
}

func (*FunctionFailure) Error

go
func (e *FunctionFailure) Error() string

func (*FunctionFailure) Unwrap

go
func (e *FunctionFailure) Unwrap() error

type FunctionRoute

FunctionRoute is the HTTP route metadata for an httpAction.

go
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.

go
type FunctionType string

go
const (
    FunctionTypeQuery      FunctionType = "query"
    FunctionTypeMutation   FunctionType = "mutation"
    FunctionTypeAction     FunctionType = "action"
    FunctionTypeHTTPAction FunctionType = "httpAction"
)

type FunctionVisibility

FunctionVisibility enumerates the supported function visibilities.

go
type FunctionVisibility string

go
const (
    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.

go
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.

go
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.

go
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.

go
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.

go
type JSONValue = any

type MigrationDescriptor

MigrationDescriptor is a pure, reversible document transform registered by the deployment bundle.

go
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

go
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.

go
type ModuleSource struct {
    Path  string `json:"path"`
    Bytes string `json:"bytes"`
}

type Repo

Repo provides persistence access for deployment records.

go
type Repo struct{}

func NewRepo

go
func NewRepo() *Repo

NewRepo creates a new deployment repository.

func (*Repo) ApiError

go
func (r *Repo) ApiError(err error) *router.ApiError

ApiError maps deployment errors to router API errors.

func (*Repo) CountDeployments

go
func (r *Repo) CountDeployments(ctx context.Context, app core.App) (int64, error)

CountDeployments returns the total number of deployments.

func (*Repo) CreateDeployment

go
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

go
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

go
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

go
func (r *Repo) GetState(ctx context.Context, app core.App) (*core.Record, error)

GetState returns the active state record.

func (*Repo) ListDeployments

go
func (r *Repo) ListDeployments(ctx context.Context, app core.App) ([]*core.Record, error)

ListDeployments returns deployments ordered by creation descending.

func (*Repo) SaveState

go
func (r *Repo) SaveState(ctx context.Context, app core.App, state *core.Record) error

SaveState persists the state record.

func (*Repo) SetDeploymentActivatedAt

go
func (r *Repo) SetDeploymentActivatedAt(ctx context.Context, app core.App, id string, activatedAt types.DateTime) error

SetDeploymentActivatedAt updates the activated timestamp on a deployment.

func (*Repo) SetDeploymentActive

go
func (r *Repo) SetDeploymentActive(ctx context.Context, app core.App, id string, active bool) error

SetDeploymentActive 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.

go
type RuntimeInvoker any

type Service

Service is the application layer for deployments.

go
type Service struct {
    // contains filtered or unexported fields
}

func NewService

go
func NewService(app core.App, repo *Repo, invoker RuntimeInvoker, config Config) *Service

NewService creates a new deployment service.

func (*Service) Activate

go
func (s *Service) Activate(id string, atomic bool) (*DeploymentActivateResponse, error)

Activate atomically switches the active deployment to id.

func (*Service) ActivateContext

go
func (s *Service) ActivateContext(ctx context.Context, id string, atomic bool) (*DeploymentActivateResponse, error)

func (*Service) Active

go
func (s *Service) Active() (*Deployment, error)

Active returns the currently active deployment.

func (*Service) ActiveContext

go
func (s *Service) ActiveContext(ctx context.Context) (*Deployment, error)

func (*Service) ActiveUploadEnvelopeBytes

go
func (s *Service) ActiveUploadEnvelopeBytes() int64

func (*Service) Call

go
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

go
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

go
func (s *Service) Get(id string) (*Deployment, error)

Get returns a single deployment by deploymentId.

func (*Service) GetContext

go
func (s *Service) GetContext(ctx context.Context, id string) (*Deployment, error)

func (*Service) HTTPAction

go
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

go
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

go
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

go
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

go
func (s *Service) List() (*DeploymentListResponse, error)

List returns all stored deployments with the active flag.

func (*Service) ListContext

go
func (s *Service) ListContext(ctx context.Context) (*DeploymentListResponse, error)

func (*Service) LogUnexpectedHandlerFailure

go
func (s *Service) LogUnexpectedHandlerFailure(err error, fields HandlerFailureContext) bool

LogUnexpectedHandlerFailure records a failure through the service's app logger.

func (*Service) MatchHTTPRoute

go
func (s *Service) MatchHTTPRoute(method, path string) (string, string, bool)

func (*Service) MatchHTTPRouteContext

go
func (s *Service) MatchHTTPRouteContext(ctx context.Context, method, path string) (string, string, bool)

func (*Service) MaxFunctionArgsBytes

go
func (s *Service) MaxFunctionArgsBytes() int64

func (*Service) MaxUploadBytes

go
func (s *Service) MaxUploadBytes() int64

func (*Service) Pin

go
func (s *Service) Pin(ctx context.Context, deploymentID string, delta int) error

Pin atomically adjusts the deployment's durable scheduler reference count.

func (*Service) Resolve

go
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

go
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

go
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

go
func (s *Service) Rollback(id string) (*DeploymentRollbackResponse, error)

Rollback restores the previous active deployment.

func (*Service) RollbackContext

go
func (s *Service) RollbackContext(ctx context.Context, id string) (*DeploymentRollbackResponse, error)

func (*Service) SetActivationObserver

go
func (s *Service) SetActivationObserver(observer ActivationObserver)

SetActivationObserver installs the active-deployment lifecycle observer.

func (*Service) SetInvalidator

go
func (s *Service) SetInvalidator(inv Invalidator)

SetInvalidator sets the invalidator that is notified on activation/rollback.

func (*Service) Upload

go
func (s *Service) Upload(raw any) (*DeploymentUploadResponse, error)

Upload validates, stores, and prepares a new deployment.

func (*Service) UploadContext

go
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

go
func (s *Service) WarmActive() error

WarmActive loads and verifies the currently active deployment runtime.

type StructuredError

StructuredError is the protocol error envelope.

go
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

go
type UploadValidationError struct {
    Code ErrorCode
    Err  error
}

func (*UploadValidationError) Error

go
func (e *UploadValidationError) Error() string

func (*UploadValidationError) Unwrap

go
func (e *UploadValidationError) Unwrap() error

type ValueSizeError

ValueSizeError is returned when a wire value exceeds a configured size limit.

go
type ValueSizeError struct {
    Label string
    Limit int64
}

func (*ValueSizeError) Error

go
func (e *ValueSizeError) Error() string

Generated by gomarkdoc

Generated API reference. Source of truth is the codebase.