apps

package
v0.41.1 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: MIT Imports: 33 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 apps validates host-app manifests and persists independent registrations.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrAPIRequest = errors.New("apps: invalid API request")
	ErrAPILimit   = errors.New("apps: API request byte limit exceeded")
)
View Source
var (
	ErrMintIdentity        = errors.New("apps: cannot mint app identity; retry creation")
	ErrIdentityUnavailable = errors.New("apps: app identity or destination occupied; retry with a fresh identity")
	ErrSourceWrite         = errors.New("apps: source generation failed; check private app storage and retain the unregistered attempt")
	ErrCreatePersistence   = errors.New("apps: registration persistence failed; check private registry storage; generated source remains unregistered")
)
View Source
var (
	ErrInvalidIdentity  = errors.New("apps: invalid identity")
	ErrInvalidStorage   = errors.New("apps: invalid storage")
	ErrConflict         = errors.New("apps: conflicting registration")
	ErrNotFound         = errors.New("apps: registration not found")
	ErrRemoved          = errors.New("apps: identity removed")
	ErrCapacity         = errors.New("apps: registration capacity reached")
	ErrExhausted        = errors.New("apps: revision exhausted")
	ErrInvalidLifecycle = errors.New("apps: invalid lifecycle")
	ErrStale            = errors.New("apps: obsolete observation")
)
View Source
var (
	ErrReleaseChanged   = errors.New("apps: active release changed")
	ErrResponseMetadata = errors.New("apps: invalid response metadata")
	ErrResponseLimit    = errors.New("apps: response byte limit exceeded")
	ErrResponseCapacity = errors.New("apps: response capacity unavailable")
	ErrResponseIO       = errors.New("apps: response I/O failed")
)
View Source
var ErrAssetPath = errors.New("apps: invalid asset path or query")
View Source
var ErrClosed = errors.New("apps: process owner shut down")
View Source
var ErrForeignHost = errors.New("apps: foreign host")
View Source
var ErrInvalidManifest = errors.New("apps: invalid manifest")
View Source
var ErrUnavailable = errors.New("apps: service unavailable")

Functions

func RestoreData

func RestoreData(ctx context.Context, root, server, app string, ref BackupReference, node string) error

RestoreData freshly verifies the persisted backup and restores its entire data tree without migrations or registry changes. Callers must serialize operations and quiesce all app writers. An error can leave partial current data; retry from the same backup. The backup is never changed or deleted by restoration.

func VerifyBackup

func VerifyBackup(ctx context.Context, root, server, app string, ref BackupReference, node string) error

VerifyBackup verifies persisted identity, the exact tree and SQL integrity. It needs no source tree, migrates nothing and never repairs sealed contents.

Types

type APIRequest

type APIRequest struct {
	Method, Path, Query string
	Headers             map[string]string
	Body                []byte
	Reserve             func(int64) bool
	Release             func(int64)
	// Progress has the optional positive-byte ResponseInput reporting contract.
	Progress func()
}

APIRequest carries validated-at-use escaped URL text and opaque decoded bytes. Headers must use the lowercase allowlist. Reserve/Release follow ResponseInput's ownership contract. Do not mutate the request during ForwardAPI.

type AssetRequest

type AssetRequest struct {
	Path, Query string
	Navigation  bool
	Reserve     func(int64) bool
	Release     func(int64)
	// Progress has the optional positive-byte ResponseInput reporting contract.
	Progress func()
}

AssetRequest carries native-stamped navigation and escaped origin-relative URL text. Query is optional opaque text, never used for file selection. Reserve/Release have the ResponseInput contract. The caller supplies authenticated host/app identity.

type BackupReference

type BackupReference struct {
	ServerID  string `json:"server_id"`
	AppID     string `json:"app_id"`
	PublishID string `json:"publish_id"`
	Root      string `json:"root"`
}

BackupReference locates a publisher-verified snapshot, without verifying it.

func SnapshotData

func SnapshotData(ctx context.Context, root, server, app, publish, node string) (BackupReference, error)

SnapshotData snapshots all data without running migrations or changing registry state. The caller must serialize operations and quiesce every app writer. Existing publish IDs are conflicts, including incomplete prior attempts.

type CandidateFailure added in v0.40.2

type CandidateFailure struct{ Phase, Reason string }

CandidateFailure contains static, actionable feedback without child diagnostics.

func (*CandidateFailure) Error added in v0.40.2

func (f *CandidateFailure) Error() string

type Change

type Change struct {
	ServerID string
	AppID    string
	Revision uint64
	Record   *Record
}

Change is a current-process committed update. Record is detached and complete; nil denotes an identity/revision tombstone. No prior changes are replayed.

type LastError

type LastError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

LastError holds a safe lifecycle failure, never process output or file paths.

type Lifecycle

type Lifecycle struct {
	Title          string
	Desired        string
	State          string
	ActiveRelease  string
	PendingRelease string
	LastError      *LastError
}

Lifecycle replaces the committed display and lifecycle fields as one change. Empty releases and a nil LastError mean unset. Callers supply confirmed observed state and static safe errors, never raw parser, process or I/O diagnostics.

type Manifest

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

Manifest is an immutable, validated v1 manifest. Validation proves no readiness. Its zero value is invalid. JSON returns a detached canonical representation.

func ValidateManifest

func ValidateManifest(data []byte, serverID string) (Manifest, error)

ValidateManifest accepts only canonical identities belonging to serverID. It neither restamps identities nor inspects files or executes manifest commands.

func (Manifest) AppID

func (m Manifest) AppID() string

func (Manifest) JSON

func (m Manifest) JSON() []byte

func (Manifest) MarshalJSON

func (m Manifest) MarshalJSON() ([]byte, error)

func (Manifest) ReleaseVersion

func (m Manifest) ReleaseVersion() string

func (Manifest) ServerID

func (m Manifest) ServerID() string

func (Manifest) Title

func (m Manifest) Title() string

func (*Manifest) UnmarshalJSON

func (m *Manifest) UnmarshalJSON(data []byte) error

type Observation

type Observation struct {
	Desired   string
	State     string
	LastError *LastError
}

Observation changes state/error and optionally explicit desired intent. Display fields and releases are preserved. Empty Desired retains the current intent. Empty State retains state/error; a supplied State replaces LastError too.

type Owner

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

Owner executes committed releases independently of conversation sessions. Use one owner per registry. Start proves spawn only, never readiness. Registry callbacks must not call Owner methods. Private generations remain package-owned.

func NewOwner

func NewOwner(registry *Registry, nodeExecutable string) (*Owner, error)

NewOwner selects Node once and starts asynchronous committed-intent reconciliation. Construction waits for neither service spawn nor fresh health confirmation.

func (*Owner) CheckRuntime added in v0.40.3

func (o *Owner) CheckRuntime(ctx context.Context) error

CheckRuntime probes the owner's selected executable with a bounded lifetime and output. Call before message processing and cache the result for readiness; this attests infrastructure independently of registrations and app health.

func (*Owner) ForwardAPI

func (o *Owner) ForwardAPI(ctx context.Context, serverID, appID, release string, in APIRequest) (*PreparedResponse, error)

ForwardAPI sends once to the authenticated host's exact active app generation. It never retries or claims rollback after cancellation of an uncertain mutation. The caller owns the returned response until Complete or Close.

func (*Owner) Lookup

func (o *Owner) Lookup(serverID, appID string) (*Target, error)

Lookup returns only a health-confirmed live target matching committed local state.

func (*Owner) Prepare

func (o *Owner) Prepare(ctx context.Context, serverID, appID, release string, in ResponseInput) (*PreparedResponse, error)

Prepare owns nonnil Body immediately, including on failure; success closes it. serverID comes from the authenticated boundary; this method authenticates no connection. Do not mutate source/headers during Prepare. Later changes cannot affect output. Consumers own status restrictions, header projection and HTTP no-body semantics.

func (*Owner) PrepareAsset

func (o *Owner) PrepareAsset(ctx context.Context, serverID, appID, release string, in AssetRequest) (*PreparedResponse, error)

PrepareAsset stages a confined active-release asset or ordinary HTTP 404. Consumers use checked Metadata/Read and Complete/Close, as with Prepare.

func (*Owner) Publish added in v0.40.2

func (o *Owner) Publish(ctx context.Context, serverID, appID string, tools Toolchain) (result PublishResult, err error)

Publish performs checked publication or update. Tools are selected by the daemon; Node must be the owner's executable. Success includes durable finalization.

func (*Owner) Shutdown

func (o *Owner) Shutdown() error

Shutdown closes launch admission and joins every owned group without changing desired intent. Repeated calls join the same retired workers.

func (*Owner) Start

func (o *Owner) Start(ctx context.Context, appID string) error

Start resumes available intent and waits for preparation/spawn or failure. Concurrent attempts coalesce; scheduled recovery returns the last failure or ErrUnavailable without bypassing backoff. Cancelling the initiating context retires its generation; a coalesced caller can cancel its own wait independently.

func (*Owner) Stop

func (o *Owner) Stop(appID string) error

Stop cancels owned work even if stopped intent cannot be persisted. Success includes durable intent and process-group retirement, followed by observation.

type PreparedResponse

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

PreparedResponse owns staged bytes/reservations until Complete or Close. Read and Metadata check cancellation/generation; copied metadata expires on retirement. EOF retains capacity: Complete(nil) confirms delivery, Complete(err) reports failure, and Close abandons it. Methods may race; cancellation cleans up retained results.

func (*PreparedResponse) Close

func (p *PreparedResponse) Close() error

Close abandons delivery. Repeated calls join the same cleanup and return nil.

func (*PreparedResponse) Complete

func (p *PreparedResponse) Complete(deliveryErr error) error

Complete releases ownership, reporting a sanitized delivery failure when nonnil.

func (*PreparedResponse) Done

func (p *PreparedResponse) Done() <-chan struct{}

Done closes when cancellation, backend retirement or disposal invalidates the response. Observing it performs no backend I/O or locking.

func (*PreparedResponse) Metadata

func (p *PreparedResponse) Metadata() (ResponseMetadata, error)

Metadata returns a detached snapshot only while the response remains usable.

func (*PreparedResponse) Read

func (p *PreparedResponse) Read(buf []byte) (int, error)

type PublishFailure added in v0.40.2

type PublishFailure struct{ Phase, Recovery string }

PublishFailure carries static phase and recovery feedback, never diagnostics.

func (*PublishFailure) Error added in v0.40.2

func (f *PublishFailure) Error() string

type PublishJournal

type PublishJournal struct {
	Candidate           ReleaseReference  `json:"candidate"`
	Previous            *ReleaseReference `json:"previous,omitempty"`
	VerifiedBackup      BackupReference   `json:"verified_backup"`
	ActivationCommitted bool              `json:"activation_committed"`
}

PublishJournal records recovery's durable choice. Before activation commit, restore previous data/release (Previous is absent on first publish); after it, use Candidate. Storage proves neither verification, health nor restoration.

type PublishResult added in v0.40.2

type PublishResult struct {
	ServerID, AppID, CandidateRelease             string
	Lifecycle                                     Lifecycle
	Revision                                      uint64
	Healthy, ActivationCommitted, RecoveryPending bool
}

PublishResult projects committed public fields without storage paths or history. Healthy confirms activation health; RecoveryPending forbids ordinary success.

type Record

type Record struct {
	AppID          string          `json:"app_id"`
	Manifest       Manifest        `json:"manifest"`
	Title          string          `json:"title"`
	Desired        string          `json:"desired"`
	State          string          `json:"state"`
	ActiveRelease  string          `json:"active_release,omitempty"`
	PendingRelease string          `json:"pending_release,omitempty"`
	LastError      *LastError      `json:"last_error,omitempty"`
	Revision       uint64          `json:"revision"`
	ReleaseHistory []Release       `json:"release_history,omitempty"`
	PublishJournal *PublishJournal `json:"publish_journal,omitempty"`
	// RetirementPending bars restoration and writers until all prior publication
	// writers are confirmed retired. It survives owner replacement.
	RetirementPending bool `json:"retirement_pending,omitempty"`
}

Record is a committed registration. Empty release strings mean unset. Manifest updates preserve all committed display and lifecycle fields.

type Registry

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

Registry serializes durable mutations and readers. Open one owner per root; concurrent independent owners or processes writing the same root are unsupported.

func Open

func Open(root, serverID string) (*Registry, error)

Open accepts a canonical host identity and absolute private app root. Missing storage is empty; invalid storage is never repaired or rewritten. Observed states are normalized and committed before exposure; stored running never proves readiness. Intent, releases and safe error metadata are preserved.

func (*Registry) CommitObservation

func (r *Registry) CommitObservation(serverID, appID string, expectedRevision uint64, observation Observation) (Record, bool, error)

CommitObservation rejects an obsolete app revision without writes or events. A successful no-op also returns the current detached record.

func (*Registry) Create

func (r *Registry) Create(ctx context.Context, title string) (Source, error)

Create mints an identity and generates bundled editable source before registration. It executes no commands. Failed attempts may retain unregistered source.

func (*Registry) Inspect

func (r *Registry) Inspect(ctx context.Context, serverID, appID string) (Source, error)

Inspect resolves only a committed local identity. It does not read or restamp source.

func (*Registry) List

func (r *Registry) List() ([]Record, uint64)

List returns detached records in app_id order and their committed host revision.

func (*Registry) PrepareCandidate added in v0.40.2

func (r *Registry) PrepareCandidate(ctx context.Context, serverID, appID string, tools Toolchain) (release Release, err error)

PrepareCandidate checks and records immutable bytes; it neither activates a service nor prepares persistent data. Trusted app commands are not sandboxed.

func (*Registry) RecordRelease

func (r *Registry) RecordRelease(serverID, appID string, release Release) (bool, error)

RecordRelease appends an immutable release version. Identical repeats are no-ops.

func (*Registry) Register

func (r *Registry) Register(data []byte) (bool, error)

Register persists a caller-minted local identity; equal manifests are no-ops.

func (*Registry) Remove

func (r *Registry) Remove(appID string) (bool, error)

Remove tombstones the identity permanently, retaining all source/build/data files. An owner joins writers/recovery first; unresolved recovery rejects removal. Removing an existing tombstone again is a no-op.

func (*Registry) Subscribe

func (r *Registry) Subscribe(consumer func(Change)) func()

Subscribe delivers future changes synchronously in increasing revision order. Each consumer owns its delivered data. Callbacks must return promptly and must not call registry methods, including the returned idempotent unsubscribe. A nil consumer installs nothing. Subscriptions are neither stored nor replayed.

func (*Registry) UpdateLifecycle

func (r *Registry) UpdateLifecycle(serverID, appID string, fields Lifecycle) (bool, error)

UpdateLifecycle commits confirmed observations for an existing local identity. A cutover supplies its new title/release, running state and unset pending/error together. The registry neither confirms health nor activates manifest candidates.

func (*Registry) UpdateManifest

func (r *Registry) UpdateManifest(appID string, data []byte) (bool, error)

UpdateManifest replaces only the manifest of an existing matching identity.

func (*Registry) UpdatePublish

func (r *Registry) UpdatePublish(serverID, appID string, journal *PublishJournal, fields *Lifecycle) (bool, error)

UpdatePublish replaces or clears a journal, optionally committing lifecycle fields atomically. Activation callers supply candidate active/title/state and cleared pending/error; recovery callers supply the resulting lifecycle. A new publish ID requires clearing the outstanding journal first. Inputs are detached.

type Release

type Release struct {
	ReleaseVersion string `json:"release_version"`
	BuildID        string `json:"build_id"`
	BuildRoot      string `json:"build_root"`
	NodeVersion    string `json:"node_version"`
	NPMVersion     string `json:"npm_version"`
	LockfileDigest string `json:"lockfile_digest"`
}

Release identifies an immutable build within its containing local registration. Recorded versions and digests do not prove a successful build or readiness.

type ReleaseReference

type ReleaseReference struct {
	ServerID       string `json:"server_id"`
	AppID          string `json:"app_id"`
	ReleaseVersion string `json:"release_version"`
}

ReleaseReference is app-scoped; legacy releases need no history entry.

type ResponseInput

type ResponseInput struct {
	Body        io.ReadCloser
	Size, Limit int64
	Status      int
	Headers     map[string]string
	Reserve     func(int64) bool
	Release     func(int64)
	// Progress reports each positive-byte source read. It must return promptly
	// and must not reenter the response. Nil disables reporting.
	Progress func()
}

ResponseInput supplies identity-encoded Body with a size hint (-1 unknown). Limit bounds decoded bytes; proving EOF can need one extra reserved byte. Reserve acquires all requested bytes atomically or returns false; Release returns them. Callbacks must be prompt and never reenter the result. Body must support concurrent Close that promptly unblocks Read, including on process retirement.

type ResponseMetadata

type ResponseMetadata struct {
	Status  int
	Headers map[string]string
	Size    int64
	SHA256  string
}

ResponseMetadata describes the complete stable body. Headers are detached.

type RetainedBuild

type RetainedBuild struct {
	Manifest   Manifest
	BuildID    string
	Inventory  []byte
	Migrations []string
}

RetainedBuild describes checked artifact bytes, not preparation success or readiness. Inventory and Migrations are detached from package state.

func InstallBuild

func InstallBuild(ctx context.Context, appsRoot, staging, serverID, appID string) (build RetainedBuild, err error)

InstallBuild copies and seals completed staging artifacts before exclusive publication. Existing destinations must verify; failures never repair them or change app data.

func ValidateArtifacts

func ValidateArtifacts(ctx context.Context, staging, serverID, appID string) (build RetainedBuild, err error)

ValidateArtifacts checks only retained artifacts in a completed private staging tree. It runs no commands and modifies neither staging nor registration state.

func VerifyBuild

func VerifyBuild(ctx context.Context, appsRoot, serverID, appID, buildID string) (build RetainedBuild, err error)

VerifyBuild independently checks a retained build without creating or repairing it.

type Source

type Source struct {
	ServerID, AppID          string
	SourcePath, ManifestPath string
	Record                   Record
	Revision                 uint64
}

Source describes editable locations and committed registration state, not readiness. Revision is the host revision; Record.Revision is the app revision.

type Target

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

Target is an opaque, generation-owned service handle. Its zero value is unusable. It exposes no address; every request and connection is checked against ownership.

func (*Target) Do

func (t *Target) Do(req *http.Request) (*http.Response, error)

Do routes an HTTP request to the private service using the caller's path/query. Redirects and proxies are disabled. Retirement cancels headers and body reads; callers must close the response body. Resource limits belong to the consumer.

type Toolchain added in v0.40.2

type Toolchain struct{ Node, NPM string }

Toolchain is daemon-selected: Node is an absolute executable and NPM is the absolute npm CLI JavaScript entry, executed directly by that Node.

Jump to

Keyboard shortcuts

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