deployment

package
v0.0.10 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2026 License: MIT Imports: 27 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 deployment owns the managed sandbox deployment: the provider, specification and configuration an administrator selects, its generations, and the sandbox nodes that enroll with it, authenticate, report their readiness and serve its generations. It is the one package that interprets the registered provider declarations for those rules.

Index

Constants

View Source
const (
	MinResetDeadlineSeconds = 300
	MaxResetDeadlineSeconds = 86400
)

MinResetDeadlineSeconds and MaxResetDeadlineSeconds bound an auto reset's deadline.

Variables

View Source
var (
	// ErrInvalidInput reports a malformed identifier, limit or request value.
	ErrInvalidInput = errors.New("invalid sandbox deployment input")
	// ErrNotFound reports a missing sandbox node, allocation or generation.
	ErrNotFound = errors.New("sandbox deployment resource not found")
	// ErrConflict reports a deployment that cannot change in its current state.
	ErrConflict = errors.New("sandbox deployment is already configured differently")
	// ErrSpecificationMismatch reports a node or stored generation whose
	// specification differs from the deployment's.
	ErrSpecificationMismatch = errors.New("node does not match the deployment specification")
	ErrResetInProgress       = errors.New("a sandbox reset is in progress")
	ErrNotConfigured         = errors.New("the sandbox deployment is not configured")
	ErrNodeInUse             = errors.New("sandbox node retains resources")
	ErrNodeCredential        = errors.New("invalid sandbox node credential")
	// ErrCredentialUnreadable reports a stored credential the credential key
	// cannot open or authenticate, such as after the key was replaced.
	ErrCredentialUnreadable = errors.New("sandbox deployment credential decryption failed")
	// ErrAllocationConflict rejects an allocation change whose owner no longer
	// matches the stored allocation, device binding, state or compute revision,
	// or a replay for another installation.
	ErrAllocationConflict = errors.New("the sandbox allocation changed")
	// ErrNotIdle means neither idle expiry nor current demand requires suspension.
	ErrNotIdle = errors.New("sandbox compute is not ready to suspend")
	// ErrNodeAddressMismatch rejects an enrollment whose Core address is not
	// the installation public URL. The token stays unconsumed.
	ErrNodeAddressMismatch = errors.New("sandbox node Core address differs from the public URL")
	// ErrNodeExists rejects an enrollment whose node ID is already in use.
	ErrNodeExists = errors.New("sandbox node ID is already enrolled")
	// ErrSandboxResetSessionBusy reports a hosted Session an automatic reset
	// does not archive yet because it has active work.
	ErrSandboxResetSessionBusy = errors.New("the hosted Session is busy")
)

Functions

This section is empty.

Types

type Activity

type Activity struct {
	LastActivity, ObservedAt time.Time
	Busy, WakeRequested      bool
}

Activity separates real work from the connection keepalive. ObservedAt is the database clock when it was read.

func (Activity) ReadyToSuspend

func (a Activity) ReadyToSuspend(idleTimeout time.Duration) bool

ReadyToSuspend evaluates the idle policy on one database-clock observation.

type ActivityTx

type ActivityTx interface {
	// TouchActivity records live-compute activity of the Environment.
	TouchActivity() error
}

ActivityTx is one Session-locked activity change.

type AddressBindings

type AddressBindings struct {
	Nodes               int64 `json:"nodes" binding:"required"`
	NodesOnOtherAddress int64 `json:"nodes_on_other_address" binding:"required"`
	HostedSandboxes     int64 `json:"hosted_sandboxes" binding:"required"`
	SelfHostedExecutors int64 `json:"self_hosted_executors" binding:"required"`
}

AddressBindings counts what is bound to an installation address: nodes connect to the address they enrolled with, hosted sandboxes were started with the address current at the time, and self-hosted executors were installed with an advertised remote_url.

type Allocation

type Allocation struct {
	DeploymentGeneration uint64
	// NodeID is empty for an allocation no node serves.
	NodeID               string
	ObservationError     string
	ComputePhase         string
	ComputeRevision      int64
	ComputeState         json.RawMessage
	ComputeActivityAt    time.Time
	ComputeWakeRequested bool
	ComputeRetainedUntil *time.Time
	ID, EnvironmentID    string
	SessionID, TenantID  string
	DeviceID             string
	// ProviderKey is the installation the allocation was provisioned for.
	ProviderKey string
	State       string
	// CreateSettled records evidence that the original Create can no longer
	// change resources.
	CreateSettled bool
	// SessionDeleted reports that the owning Session was publicly deleted.
	SessionDeleted bool
	// Replayed reports that ReserveAllocation returned an existing allocation,
	// which never authorizes another Create.
	Replayed bool
	// Expired reports, by the database clock, that the retention of the
	// allocation's suspended compute has passed.
	Expired   bool
	CreatedAt time.Time
}

Allocation retains a hosted Environment's compute ownership, not its public readiness. It survives Session deletion until cleanup is confirmed and keeps no bootstrap secret.

func (Allocation) Key

func (a Allocation) Key() AllocationKey

Key names the allocation's Environment.

type AllocationCleanupStorage

type AllocationCleanupStorage interface {
	// WithAllocationCleanup runs apply as WithAllocation does, with the
	// Session's cancellation and Environment termination bound to the same
	// transaction.
	WithAllocationCleanup(ctx context.Context, key AllocationKey, apply func(AllocationCleanupTx) error) error
}

AllocationCleanupStorage runs allocation cleanup, which settles the owning Session's work and Environment with the allocation.

type AllocationCleanupTx

type AllocationCleanupTx interface {
	AllocationTx
	sessions.EnvironmentTerminationTx
	// RevokeDevice revokes the allocation's device.
	RevokeDevice(current Allocation) error
	// RequestCleanup records that the allocation's resources await cleanup.
	RequestCleanup(current Allocation) (Allocation, error)
}

AllocationCleanupTx is one Session-locked allocation cleanup.

type AllocationKey

type AllocationKey struct{ TenantID, EnvironmentID string }

AllocationKey names a tenant's hosted Environment, which has at most one allocation.

type AllocationRecord

type AllocationRecord struct {
	ID string
	// Generation is zero when the allocation has none.
	Generation     uint64
	Released       bool
	InstallationID string
	Deployment     Record
	// Retained is the allocation's generation when it is not the deployment's
	// current one and is still retained.
	Retained *GenerationRecord
}

AllocationRecord is an allocation with the deployment that owns it.

type AllocationTx

type AllocationTx interface {
	// CanRetainEnvironment checks the ready retained filesystem, completed
	// initialization and selected Harness's qualified history under the Session lock.
	CanRetainEnvironment(current Allocation) (bool, error)

	// LoadAllocation returns the Environment's allocation.
	LoadAllocation() (Allocation, error)
	// LoadSessionDevice returns the device the Session is bound to and
	// whether it is bound to one.
	LoadSessionDevice() (SessionDevice, bool, error)
	// LoadActivity returns the allocation's activity.
	LoadActivity(current Allocation) (Activity, error)
	// LoadSuspensionDemand locks the deployment and reads demand and capacity.
	LoadSuspensionDemand(current Allocation) (SuspensionDemand, error)
	// PlacementDemand reads one qualified page; next advances past all inspected
	// rows, including ineligible receipts. An empty next.EnvironmentID ends the scan.
	PlacementDemand(after PlacementDemandCursor) ([]PlacementDemand, PlacementDemandCursor, error)
	// LoadGenerationSpecification reads immutable generation requirements.
	LoadGenerationSpecification(generation uint64) (GenerationSpecification, error)
	// LoadCheckpointPlacement locks the deployment and loads fresh readiness
	// for the allocation's exact immutable generation, including capacity.
	LoadCheckpointPlacement(current Allocation) (placement.Deployment, []placement.CheckpointNode, error)
	// MoveSuspended changes node ownership, placement and compute intent in one
	// transaction. Only a settled suspended allocation can change nodes.
	MoveSuspended(current Allocation, nodeID string, change ComputeChange) (Allocation, error)
	// ObserveRunning records the allocation running with its creation settled.
	ObserveRunning(current Allocation) (Allocation, error)
	// SettleCreation records that the original Create can no longer change
	// resources.
	SettleCreation(current Allocation) (Allocation, error)
	// Release releases the allocation and its node placement.
	Release(current Allocation) (Allocation, error)
	// SetCompute commits the compute phase and advances its revision.
	SetCompute(current Allocation, change ComputeChange) (Allocation, error)
	// RecordObservation records the diagnostic for current's compute
	// revision and state. It changes nothing once either moved on.
	RecordObservation(current Allocation, diagnostic string) error
}

AllocationTx is one Session-locked allocation change. Each write applies to current, the allocation LoadAllocation returned, and returns it changed. A write whose stored guard no longer holds is ErrAllocationConflict.

type Capacity

type Capacity struct {
	MaxActive   int `json:"max_active"`
	MaxRetained int `json:"max_retained"`
}

type CheckpointRestoreDemand added in v0.0.10

type CheckpointRestoreDemand struct {
	SourceNode    string
	Compatibility sandbox.CheckpointCompatibility
	Nodes         []placement.CheckpointNode
}

CheckpointRestoreDemand carries one stopped owner and exact-generation target evidence.

type ComputeChange

type ComputeChange struct {
	Phase string
	State json.RawMessage
	// RetainedUntil is nil only for the running phase.
	RetainedUntil *time.Time
}

ComputeChange is the compute phase an operation commits before its external effects.

type ConfigurationError

type ConfigurationError struct {
	Message    string
	Validation *sandbox.ValidationError
}

ConfigurationError contains only validated, non-secret configuration diagnostics.

func (*ConfigurationError) Error

func (e *ConfigurationError) Error() string

func (*ConfigurationError) Unwrap

func (e *ConfigurationError) Unwrap() error

type DeploymentTx

type DeploymentTx interface {
	LoadDeployment() (Record, error)
	LoadSnapshot() (Snapshot, error)
	CountResources() (Resources, error)
	// ClaimInstallation reserves the installation for Web setup and fences the
	// previous owner epoch's node presence.
	ClaimInstallation(installationID string) error
	// SaveSelection stores the next generation. It seals a secret bound to the
	// installation and generation.
	SaveSelection(selection SelectionRecord) error
	RecordConfigurationMetadata(metadata json.RawMessage) error
	// RetainGeneration keeps the current generation for the allocations that
	// still use it.
	RetainGeneration() error
	// CollectGenerations deletes retained generations nothing uses.
	CollectGenerations() error
	// StartReset pauses admission and records a reset in the clear mode,
	// with its request time, the auto deadline in seconds from now and the
	// administrator source that started it.
	StartReset(clear string, deadlineSeconds int32, source adminaudit.Source) error
	// ForceReset escalates a running auto reset to force.
	ForceReset() error
	// CancelReset forgets the running reset and restores admission.
	CancelReset() error
	// LoadResetSource returns the administrator source that started the
	// running reset.
	LoadResetSource() (adminaudit.Source, error)
	// CompleteReset forgets the selection and the reset, restores admission,
	// advances the generation and owner epoch by one, and retires the nodes,
	// enrollments and retained generations.
	CompleteReset() error
	// RecordAudit records an administrator mutation of the deployment by the
	// source the transaction's context carries.
	RecordAudit(action, installationID string) error
	// RecordAuditAs records an administrator mutation of the deployment by
	// the given source.
	RecordAuditAs(source adminaudit.Source, action, installationID string) error
}

DeploymentTx is one leased deployment change.

type Enrollment

type Enrollment struct {
	SpecificationDigest  string `json:"specification_digest"`
	DeploymentGeneration uint64 `json:"deployment_generation"`
	NodeID               string `json:"node_id"`
	Credential           string `json:"credential"`
	Name                 string `json:"name"`
	Provider             string `json:"provider"`
	BackendFingerprint   string `json:"backend_fingerprint"`
	// The Core origin this node stores and connects to, such as https://core.example. It must equal the installation public URL; otherwise enrollment gets 409 sandbox_node_address_mismatch and the token stays unused.
	CoreURL string `json:"core_url"`
}

type EnrollmentRecord

type EnrollmentRecord struct {
	ID, InstallationID     string
	ExpiresAt              time.Time
	Consumed               bool
	MaxActive, MaxRetained int
}

EnrollmentRecord is a stored enrollment token.

type EnrollmentToken

type EnrollmentToken struct {
	Token     string
	ExpiresAt time.Time
	ID        string
}

EnrollmentToken is an issued one-use node enrollment token. ID is a public, non-secret handle that never authenticates; the node the token registers reports it as enrollment_id.

type ExecutionOperations

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

ExecutionOperations are the deployment changes only the execution owner makes. Every change runs in a transaction on the connection that holds the execution lease and repeats its checks there; provider work runs between transactions, never inside one.

func NewExecutionOperations

func NewExecutionOperations(service *Service, storage ExecutionStorage, engines engine.Catalog) (*ExecutionOperations, error)

NewExecutionOperations binds the deployment changes to the lease-bound storage of one execution owner.

func (*ExecutionOperations) AdvanceResetDeadline

func (e *ExecutionOperations) AdvanceResetDeadline(ctx context.Context) error

AdvanceResetDeadline escalates an auto reset to force once its deadline has passed, before the reset selects work. The deadline is absolute, so a restart never extends it. The audit entry carries the administrator source that started the reset.

func (*ExecutionOperations) ArchiveResetSession added in v0.0.10

func (e *ExecutionOperations) ArchiveResetSession(ctx context.Context, tenantID, sessionID string, generation uint64, requestedAt time.Time) (sessions.ManagedArchive, error)

ArchiveResetSession archives a hosted Session for the running reset, which its generation and request time identify, so that a cancelled reset's candidates never affect its successor. An automatic reset skips a busy Session with ErrSandboxResetSessionBusy; an Environment that already ended only reports its disposal. The archive is audited with the reset's administrator source.

func (*ExecutionOperations) ArchiveSession added in v0.0.10

func (e *ExecutionOperations) ArchiveSession(ctx context.Context, tenantID, sessionID string, expectedGeneration uint64) (sessions.ManagedArchive, error)

ArchiveSession ends the lifetime of a hosted Session's Environment while keeping the public Session, its history and persisted files. It cancels the Session's work, revokes the allocation's device and requests its cleanup; the lifecycle performs the provider work, and only its confirmation releases the allocation. expectedGeneration must be the current generation of the Web managed deployment.

func (*ExecutionOperations) BeginRestore added in v0.0.10

func (e *ExecutionOperations) BeginRestore(ctx context.Context, owner Allocation, compatibility sandbox.CheckpointCompatibility, state json.RawMessage) (Allocation, error)

BeginRestore reserves a compatible destination before any native restore. The caller supplies a fresh restore intent without a target; the destination adapter derives the target after this commit. Snapshot portability proves that publication and source-local cleanup settled before suspension.

func (*ExecutionOperations) CancelReset

func (e *ExecutionOperations) CancelReset(ctx context.Context, installation string, generation uint64) error

CancelReset cancels a running reset and restores admission. Sessions it already archived stay archived. Without a running reset it only checks the generation. It returns no view: the caller reads the deployment after commit.

func (*ExecutionOperations) CheckRunning added in v0.0.10

func (e *ExecutionOperations) CheckRunning(ctx context.Context, owner Allocation) (Allocation, error)

CheckRunning returns the stored allocation while it is still the owner's running compute: its Session undeleted and bound to the allocation's device. It follows an authenticated connection and a successful provider observation and changes nothing.

func (*ExecutionOperations) CheckSetup

func (e *ExecutionOperations) CheckSetup(ctx context.Context, installation string, input sandbox.Selection) error

CheckSetup rejects a stale or reset deployment before provider preparation. Initialize repeats the check in its committing transaction.

func (*ExecutionOperations) Claim

func (e *ExecutionOperations) Claim(ctx context.Context, installationID string) error

Claim reserves the installation for Web setup, once per execution owner startup, and fences the previous owner epoch's node presence.

func (*ExecutionOperations) ClassifyChange

func (e *ExecutionOperations) ClassifyChange(ctx context.Context, installation string, input sandbox.Selection) (sandbox.Selection, bool, error)

ClassifyChange resolves an omitted credential before validation and reports whether the change leaves the deployment unchanged. An explicitly submitted credential is a verified change even when its bytes are unchanged.

func (*ExecutionOperations) ClearWake

func (e *ExecutionOperations) ClearWake(ctx context.Context, owner Allocation, observed time.Time) error

ClearWake consumes the allocation's wake request observed with the given activity time. A newer request stays.

func (*ExecutionOperations) CollectGenerations

func (e *ExecutionOperations) CollectGenerations(ctx context.Context) error

CollectGenerations deletes retained generations nothing uses, serialized with admission and deployment changes.

func (*ExecutionOperations) CompleteReset

func (e *ExecutionOperations) CompleteReset(ctx context.Context, installation string, generation uint64, requestedAt time.Time) (uint64, error)

CompleteReset clears the drained deployment: it forgets the selection, retires the nodes, enrollments and retained generations, and advances the generation and owner epoch by one. It runs after the manager has drained and takes no Session lock, because archive and admission lock the Session before the deployment. It returns the committed, unconfigured generation, and InUseError while hosted resources remain.

func (*ExecutionOperations) EnsurePlacement added in v0.0.10

func (e *ExecutionOperations) EnsurePlacement(ctx context.Context, key AllocationKey, installation string) (placement.Reserved, error)

EnsurePlacement reserves first or retained demand before entering a node lifecycle. The immutable engine profile and actual selected generation are validated before committing its reservation.

func (*ExecutionOperations) Initialize

func (e *ExecutionOperations) Initialize(ctx context.Context, installation string, input sandbox.Selection) (View, error)

Initialize stores the first selection of the installation. The same selection at the current generation is a no-op; a different one conflicts.

func (*ExecutionOperations) ObserveRunning

func (e *ExecutionOperations) ObserveRunning(ctx context.Context, owner Allocation) (Allocation, error)

ObserveRunning records verified original compute identity. It neither marks the Environment connected nor qualifies native preparation.

func (*ExecutionOperations) RecordObservation

func (e *ExecutionOperations) RecordObservation(ctx context.Context, owner Allocation, diagnostic string) error

RecordObservation records a diagnostic for the observed compute revision and state of a node-backed allocation. It never releases ownership, changes public readiness or authorizes replacement.

func (*ExecutionOperations) ReleaseAbsentCreation

func (e *ExecutionOperations) ReleaseAbsentCreation(ctx context.Context, owner Allocation) (Allocation, error)

ReleaseAbsentCreation consumes provider proof that the original Create is settled and owns no resources: it requests cleanup and releases the allocation in one commit.

func (*ExecutionOperations) ReleaseAllocation

func (e *ExecutionOperations) ReleaseAllocation(ctx context.Context, owner Allocation) (Allocation, error)

ReleaseAllocation follows successful cleanup of the owned compute and volumes. An unknown Create outcome keeps its cleanup record even when the compute is absent.

func (*ExecutionOperations) ReleaseFailedPlacement added in v0.0.10

func (e *ExecutionOperations) ReleaseFailedPlacement(ctx context.Context, key AllocationKey, expected placement.Reserved) error

ReleaseFailedPlacement yields a failed preparation attempt without touching filesystem identity or an allocation that already owns compute.

func (*ExecutionOperations) ReleaseLostCompute added in v0.0.10

func (e *ExecutionOperations) ReleaseLostCompute(ctx context.Context, owner Allocation) (Allocation, error)

ReleaseLostCompute consumes the owning node's confirmed cleanup of the owner's settled running incarnation after it observed that incarnation absent, stopped or crashed. It revokes the device and releases the allocation in one commit only while the owner's compute revision is current and its Session can continue on new compute; otherwise it changes nothing. The Session, its pending input, native identity and filesystem stay.

func (*ExecutionOperations) RelocateCleanup added in v0.0.10

func (e *ExecutionOperations) RelocateCleanup(ctx context.Context, owner Allocation, compatibility sandbox.CheckpointCompatibility) (Allocation, error)

RelocateCleanup durably assigns a portable suspended artifact to a node that can delete it. An unknown restore remains pinned to its existing target.

func (*ExecutionOperations) RequestCleanup

func (e *ExecutionOperations) RequestCleanup(ctx context.Context, owner Allocation) (Allocation, error)

RequestCleanup revokes the allocation's authority before external reclamation and settles the owning Session: a deleted Session's work is cancelled, and a live Environment fails with the generic provisioning reason unless its compute expired. Cancellation requests do not prove that native work has stopped.

func (*ExecutionOperations) ReserveAllocation

func (e *ExecutionOperations) ReserveAllocation(ctx context.Context, key AllocationKey, installation, credentialHash string) (Allocation, error)

ReserveAllocation commits the allocation of the tenant's hosted Environment and its dedicated device together, before the provider creates compute. installation is the provider key the allocation is provisioned for, and credentialHash the SHA-256 digest of the device credential. An existing allocation for the same installation returns Replayed; only a fresh one authorizes the one Create call.

func (*ExecutionOperations) SetCompute

func (e *ExecutionOperations) SetCompute(ctx context.Context, owner Allocation, phase string, state json.RawMessage, retainedUntil *time.Time, idleTimeout time.Duration) (Allocation, error)

SetCompute commits a compute phase before its external effects. The owner's revision and the Session lock fence a stale lifecycle observation. Moving running compute to quiescing requires idle compute and either the idle timeout or capacity pressure, rechecked in the transaction.

func (*ExecutionOperations) SettleCreation

func (e *ExecutionOperations) SettleCreation(ctx context.Context, owner Allocation) (Allocation, error)

SettleCreation records evidence that the original Create can no longer change resources. A timeout, missing compute or lost lease is not evidence.

func (*ExecutionOperations) StartReset

func (e *ExecutionOperations) StartReset(ctx context.Context, installation string, input ResetRequest) error

StartReset pauses admission and starts the reset, or escalates a running auto reset to force. Repeating the running mode is a no-op, and auto never downgrades force. The context must carry the administrator audit source, which the reset keeps for the audit entries it records later. It returns no view: the caller reads the deployment after commit.

func (*ExecutionOperations) Update

func (e *ExecutionOperations) Update(ctx context.Context, installation string, input sandbox.Selection) (View, error)

Update changes the selection on the same backend. A different selection or a submitted credential stores the next generation and retains the previous one for the allocations that still use it.

type ExecutionStorage

type ExecutionStorage interface {
	// WithDeployment runs apply in one leased transaction that begins by
	// locking the deployment. It commits only when apply returns nil.
	WithDeployment(ctx context.Context, apply func(DeploymentTx) error) error
	// WithReservation runs apply in one leased transaction that locks the
	// Session of the tenant's Environment and then prunes the Session's
	// journal. It commits only when both succeed. A missing Environment, or
	// one of a deleted Session, is sessions.ErrNotFound.
	WithReservation(ctx context.Context, key AllocationKey, apply func(sessions.LockedSession, ReservationTx) error) error
	// WithAllocation runs apply in one leased transaction that locks the
	// Session owning the Environment's allocation, deleted or not, and then
	// prunes the Session's journal. It commits only when both succeed. A
	// missing allocation is ErrNotFound.
	WithAllocation(ctx context.Context, key AllocationKey, apply func(AllocationTx) error) error
	AllocationCleanupStorage
	// WithSessionArchive runs apply in one leased transaction that locks the
	// tenant's Session, deleted or not, and then prunes the Session's journal.
	// It commits only when both succeed. A malformed tenant is
	// ErrInvalidInput; a malformed or missing Session is sessions.ErrNotFound.
	WithSessionArchive(ctx context.Context, tenantID, sessionID string, apply func(context.Context, sessions.LockedSession, SessionArchiveTx) error) error
	// ClearWake clears the allocation's wake request unless activity newer
	// than observed arrived. It runs on the lease.
	ClearWake(ctx context.Context, allocationID string, observed time.Time) error
}

ExecutionStorage is the persistence deployment changes write through. Only the execution owner holds it: every transaction runs on the connection that holds the execution lease.

type GenerationRecord

type GenerationRecord struct {
	Generation    uint64
	Provider      string
	Specification json.RawMessage
	Configuration sandbox.ConfigurationRecord
}

GenerationRecord is a retained generation without its credential.

type GenerationSpecification

type GenerationSpecification struct {
	Provider      string
	Specification json.RawMessage
}

GenerationSpecification is the provider and specification of a generation nodes may prepare.

type GenerationStaleError

type GenerationStaleError struct{ CurrentGeneration uint64 }

GenerationStaleError rejects a change whose expected generation is not the deployment's current one.

func (*GenerationStaleError) Error

func (e *GenerationStaleError) Error() string

func (*GenerationStaleError) Unwrap

func (e *GenerationStaleError) Unwrap() error

type GenerationStatusRecord

type GenerationStatusRecord struct {
	NodeID, ConnectionID string
	Generation           uint64
	SpecificationDigest  string
	OwnerEpoch           uint64
	State, Diagnostic    string
	Checkpoint           *sandbox.CheckpointCompatibility
}

GenerationStatusRecord is a node's preparation state of one generation.

type Heartbeat

type Heartbeat struct {
	NodeID, ConnectionID string
	Epoch                uint64
	Health               NodeHealth
}

Heartbeat is a node's health for one connection.

type HostHistory

type HostHistory struct {
	ResolutionSeconds int64              `json:"resolution_seconds" binding:"required"`
	Points            []HostHistoryPoint `json:"points" binding:"required"`
}

type HostHistoryPoint

type HostHistoryPoint struct {
	Start                 time.Time `json:"start" binding:"required"`
	CPUUtilizationMax     *float64  `json:"cpu_utilization_max" extensions:"x-nullable" binding:"required"`
	MemoryUsedBytesMax    *int64    `json:"memory_used_bytes_max" extensions:"x-nullable" binding:"required"`
	AvailableDiskBytesMin *int64    `json:"available_disk_bytes_min" extensions:"x-nullable" binding:"required"`
}

type InUseError

type InUseError struct{ Resources Resources }

InUseError rejects reset completion while hosted resources still belong to the deployment.

func (*InUseError) Error

func (e *InUseError) Error() string

func (*InUseError) Unwrap

func (e *InUseError) Unwrap() error

type LifecyclePlacement

type LifecyclePlacement struct {
	// Specification belongs to the current allocation or reserved generation.
	Specification  json.RawMessage
	Provider, Mode string
	// AllocationID and AllocationNodeID are empty without an allocation or
	// its node.
	AllocationID, AllocationNodeID string
	// PlacementNodeID is empty without a placement.
	PlacementNodeID     string
	PlacementReleased   bool
	PlacementGeneration uint64
}

LifecyclePlacement is what routing a hosted Environment to its node lifecycle reads: the deployment's provider and mode, the Environment's allocation and the node placement its Session reserved.

type NewAllocation

type NewAllocation struct {
	ID, EnvironmentID, DeviceID, ProviderKey string
	// NodeID is empty when no node serves the allocation.
	NodeID     string
	Generation uint64
}

NewAllocation is an allocation to store with its dedicated device.

type NewEnrollment

type NewEnrollment struct {
	ID, TokenDigest, InstallationID string
	MaxActive, MaxRetained          int
}

NewEnrollment is an enrollment token to store, by digest.

type NewNode

type NewNode struct {
	ID, InstallationID, Name, BackendFingerprint string
	CredentialDigest                             string
	MaxActive, MaxRetained                       int
	SpecificationDigest                          string
	DeploymentGeneration                         uint64
	CoreURL                                      string
	// EnrollmentID is empty for a node that no enrollment registered.
	EnrollmentID string
}

NewNode is a node to store.

type Node

type Node struct {
	Rollout NodeRollout `json:"rollout" binding:"required"`
	NodeHealth
	Running        int64      `json:"running" binding:"required"`
	Snapshots      int64      `json:"snapshots" binding:"required"`
	ID             string     `json:"id" binding:"required"`
	Name           string     `json:"name" binding:"required"`
	Provider       string     `json:"provider" binding:"required"`
	Online         bool       `json:"online" binding:"required"`
	LastSeenAt     *time.Time `json:"last_seen_at" extensions:"x-nullable" binding:"required"`
	MaxActive      int        `json:"max_active" binding:"required"`
	MaxRetained    int        `json:"max_retained" binding:"required"`
	Active         int64      `json:"active" binding:"required"`
	Reserved       int64      `json:"reserved" binding:"required"`
	Retained       int64      `json:"retained" binding:"required"`
	CleanupPending int64      `json:"cleanup_pending" binding:"required"`
	CreatedAt      time.Time  `json:"created_at" binding:"required"`
	// The Core address this node enrolled with. A node whose address differs
	// from the installation public URL receives no new sandboxes; re-add it.
	CoreURL string `json:"core_url" binding:"required"`
	// The enrollment_id of the command that registered this node (POST /core/v1/sandbox/enrollment-tokens); null for nodes enrolled before Core recorded it.
	EnrollmentID *string `json:"enrollment_id" extensions:"x-nullable" binding:"required"`
}

type NodeAllocation

type NodeAllocation struct {
	DeploymentGeneration uint64 `json:"deployment_generation" binding:"required"`
	Diagnostic           string `` /* 139-byte string literal not displayed */
	ID                   string `json:"id" binding:"required"`
	NodeID               string `json:"node_id" binding:"required"`
	TenantID             string `json:"tenant_id" binding:"required"`
	SessionID            string `json:"session_id" binding:"required"`
	EnvironmentID        string `json:"environment_id" binding:"required"`
	State                string `json:"state" binding:"required"`
	ComputePhase         string `json:"compute_phase" binding:"required"`
	// The time the allocation entered its current compute_phase, or null when unknown; an allocation that existed before Core recorded it reports null until its next phase change. For a suspended microsandbox allocation, this time plus the deployment's snapshot retention tells roughly when Core reclaims it.
	ComputePhaseChangedAt *time.Time `json:"compute_phase_changed_at" extensions:"x-nullable" binding:"required"`
	Initialization        string     `json:"initialization" binding:"required"`
	CreatedAt             time.Time  `json:"created_at" binding:"required"`
}

NodeAllocation is an unreleased allocation a node serves.

type NodeConfiguration

type NodeConfiguration struct {
	MaxActive           int                    `json:"max_active"`
	MaxRetained         int                    `json:"max_retained"`
	InstallationID      string                 `json:"installation_id"`
	Provider            string                 `json:"provider"`
	CoreURL             string                 `json:"core_url"`
	Generation          uint64                 `json:"generation"`
	Specification       sandbox.DeploymentSpec `json:"specification"`
	SpecificationDigest string                 `json:"specification_digest"`
}

type NodeDetail

type NodeDetail struct {
	Node
	Host    NodeHost    `json:"host" binding:"required"`
	History HostHistory `json:"history" binding:"required"`
}

type NodeHealth

type NodeHealth struct {
	Host *NodeHost `json:"-"`
	// Fixed reason for the last reported unreadiness; absent while the provider is ready. Clients treat an unknown value as provider_unavailable.
	Diagnostic           sandbox.NodeDiagnosticCode `json:"diagnostic,omitempty"`
	ProviderReady        bool                       `json:"provider_ready" binding:"required"`
	CPUCount             *int64                     `json:"cpu_count" extensions:"x-nullable" binding:"required"`
	AvailableMemoryBytes *int64                     `json:"available_memory_bytes" extensions:"x-nullable" binding:"required"`
	AvailableDiskBytes   *int64                     `json:"available_disk_bytes" extensions:"x-nullable" binding:"required"`
}

type NodeHost

type NodeHost struct {
	EffectiveCPUCores    *float64   `json:"effective_cpu_cores" extensions:"x-nullable" binding:"required"`
	CPUUtilization       *float64   `json:"cpu_utilization" extensions:"x-nullable" binding:"required"`
	TotalMemoryBytes     *int64     `json:"total_memory_bytes" extensions:"x-nullable" binding:"required"`
	AvailableMemoryBytes *int64     `json:"available_memory_bytes" extensions:"x-nullable" binding:"required"`
	AvailableDiskBytes   *int64     `json:"available_disk_bytes" extensions:"x-nullable" binding:"required"`
	ObservedAt           *time.Time `json:"observed_at" extensions:"x-nullable" binding:"required"`
}

NodeHost is deployment telemetry, not sandbox capacity authority.

type NodeIdentity

type NodeIdentity struct {
	SpecificationDigest  string `json:"specification_digest"`
	DeploymentGeneration uint64 `json:"deployment_generation"`
	NodeID               string `json:"node_id"`
	InstallationID       string `json:"installation_id"`
	Provider             string `json:"provider"`
	BackendFingerprint   string `json:"-"`
	MaxActive            int    `json:"max_active"`
	MaxRetained          int    `json:"max_retained"`
}

type NodeLimits

type NodeLimits struct {
	Name                   string
	MaxActive, MaxRetained int
}

NodeLimits is a node's name and capacity.

type NodeReads

type NodeReads interface {
	// LoadDeployment returns the deployment, locked when the transaction locks it.
	LoadDeployment() (Record, error)
	// LoadNode returns ErrInvalidInput for a malformed ID and ErrNotFound for
	// a missing or removed node.
	LoadNode(id string) (StoredNode, error)
	// LoadEnrollment returns ErrNotFound for an unknown token digest.
	LoadEnrollment(tokenDigest string) (EnrollmentRecord, error)
	// LoadGenerationSpecification returns ErrNotFound for a collected
	// generation.
	LoadGenerationSpecification(generation uint64) (GenerationSpecification, error)
	// GenerationKept reports whether the node may keep the generation: its
	// target, its serving pin or one with unreleased ownership on it.
	GenerationKept(nodeID string, generation uint64) (bool, error)
}

NodeReads loads node authentication facts.

type NodeRecord

type NodeRecord struct {
	ID, Name, Provider, CoreURL string
	EnrollmentID                *string
	CreatedAt                   time.Time
	LastSeenAt                  *time.Time
	Health                      NodeHealth
	Online, ServingReady        bool
	ProtocolVersion             int
	DeploymentGeneration        uint64
	TargetGeneration            uint64
	ReadyGeneration             *uint64
	TargetState                 string
	TargetDiagnostic            string
	MaxActive, MaxRetained      int
	Active, Retained, Reserved  int64
	CleanupPending              int64
	Running, Snapshots          int64
}

NodeRecord is a node of the installation with its presence and usage.

type NodeRollout

type NodeRollout struct {
	// Target preparation, independent of an old pin's serving readiness.
	State NodeRolloutState `json:"state" binding:"required"`
	// Durable serving-generation pin; online and provider_ready still gate placement.
	ReadyGeneration *uint64                    `json:"ready_generation" extensions:"x-nullable" binding:"required"`
	Diagnostic      sandbox.NodeDiagnosticCode `json:"diagnostic,omitempty"`
}

type NodeRolloutState added in v0.0.10

type NodeRolloutState string
const (
	NodeRolloutReady          NodeRolloutState = "ready"
	NodeRolloutPreparing      NodeRolloutState = "preparing"
	NodeRolloutFailed         NodeRolloutState = "failed"
	NodeRolloutUpdateRequired NodeRolloutState = "update_required"
	NodeRolloutUnknown        NodeRolloutState = "unknown"
)

type NodeStatus

type NodeStatus struct {
	NodeIdentity
	Connected     bool `json:"connected"`
	ProviderReady bool `json:"provider_ready"`
}

NodeStatus reports only the authenticated node's Core-owned presence.

type NodeTx

type NodeTx interface {
	NodeReads
	ListNodes() ([]NodeRecord, error)
	// InsertNode returns ErrNodeExists when the ID is in use, including by a
	// removed node, and ErrInvalidInput for a malformed ID.
	InsertNode(node NewNode) (StoredNode, error)
	UpdateNode(id string, limits NodeLimits) error
	RemoveNode(id string) error
	// CreateEnrollment stores a token that expires in ten minutes and returns
	// its expiry.
	CreateEnrollment(enrollment NewEnrollment) (time.Time, error)
	// ConsumeEnrollment marks an unexpired, unconsumed token of the current
	// installation used by the node and reports whether it did.
	ConsumeEnrollment(tokenDigest, nodeID string) (bool, error)
	// HeartbeatNode records the node's health for its current connection and
	// reports whether the connection is still current.
	HeartbeatNode(heartbeat Heartbeat) (bool, error)
	DeleteGenerationStatus(nodeID string, generation uint64) error
	UpsertGenerationStatus(status GenerationStatusRecord) error
	PromoteServingGeneration(nodeID string, generation uint64) error
	RefreshServingReadiness(nodeID string, protocol int) error
}

NodeTx is one node management transaction.

type NodeUpdate

type NodeUpdate struct {
	Name      string `json:"name" binding:"required"`
	MaxActive int    `json:"max_active" binding:"required"`
	// Docker never suspends, so Core replaces this with max_active; microsandbox uses both limits.
	MaxRetained int `json:"max_retained"`
}

type NodeValidationError

type NodeValidationError struct {
	Code, Param string
	MaxLength   int
}

NodeValidationError rejects a node name or capacity. Code is invalid_name or invalid_node_capacity, and Param names the field. It adds field identity without changing the ErrInvalidInput text or classification.

func (*NodeValidationError) Error

func (e *NodeValidationError) Error() string

func (*NodeValidationError) Unwrap

func (e *NodeValidationError) Unwrap() error

type ObservationResolver added in v0.0.10

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

ObservationResolver resolves a Session to the Runtime observation target of its Environment and allocation, and lists the hosted Sessions to observe.

func NewObservationResolver added in v0.0.10

func NewObservationResolver(sessionReader sessions.SessionReader, reader Reader) (*ObservationResolver, error)

func (*ObservationResolver) ListRuntimeObservationSessions added in v0.0.10

func (r *ObservationResolver) ListRuntimeObservationSessions(ctx context.Context, after string, limit int) (runtimeobs.SessionPage, error)

func (*ObservationResolver) Resolve added in v0.0.10

func (r *ObservationResolver) Resolve(ctx context.Context, tenantID, sessionID string) (runtimeobs.Target, error)

type ObservationSession

type ObservationSession struct{ TenantID, SessionID string }

ObservationSession is the minimum durable identity the deployment-wide read-only sampler needs. The observation service resolves the provider identity again before any external read.

type ObservationSessionPage

type ObservationSessionPage struct {
	Sessions   []ObservationSession
	NextCursor string
}

ObservationSessionPage is one page of ObservationSessions. NextCursor is empty on the last page.

type PlacementDemand added in v0.0.10

type PlacementDemand struct {
	UnallocatedEnvironment
	Engine string
	// Retained requires external storage because an allocation or filesystem identity already exists.
	Retained bool
	At       time.Time
}

PlacementDemand is committed work awaiting a node reservation. Demand time belongs to Session creation or its oldest pending input, not to a retry.

type PlacementDemandCursor added in v0.0.10

type PlacementDemandCursor struct {
	// Until fixes the database-clock horizon of one sweep, so new arrivals cannot prevent wraparound.
	Until         time.Time
	At            time.Time
	EnvironmentID string
}

PlacementDemandCursor continues the bounded, oldest-demand-first scan. An empty EnvironmentID ends a page scan; Until may still describe a nonempty final page for callers that yield before processing every row.

type PublicOrigin added in v0.0.10

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

PublicOrigin is OAC_PUBLIC_URL, the one origin applications, nodes, sandboxes and self-hosted executors use. Every Core address they are given is derived from it; none is parsed back into an origin.

func NewPublicOrigin added in v0.0.10

func NewPublicOrigin(value string) (PublicOrigin, error)

NewPublicOrigin accepts a canonical public origin, never a path or credential. It may be http or https: a reverse proxy in front of Web terminates TLS when the installation uses it.

func (PublicOrigin) API added in v0.0.10

func (o PublicOrigin) API() string

API is the base URL of the Agents API.

func (PublicOrigin) DaemonWebSocket added in v0.0.10

func (o PublicOrigin) DaemonWebSocket() string

DaemonWebSocket is the daemon transport: ws on an http origin, wss on https.

func (PublicOrigin) InstallerBase added in v0.0.10

func (o PublicOrigin) InstallerBase() string

InstallerBase is the prefix of the versioned native installer downloads.

func (PublicOrigin) RuntimeAPI added in v0.0.10

func (o PublicOrigin) RuntimeAPI() string

RuntimeAPI is the base URL sandboxes and nodes call.

func (PublicOrigin) String added in v0.0.10

func (o PublicOrigin) String() string

String is the origin itself.

type Reader

type Reader interface {
	// Deployment returns the stored deployment.
	Deployment(ctx context.Context) (Record, error)
	// Snapshot returns the deployment with the counts and projections its View
	// reports, read in one statement.
	Snapshot(ctx context.Context) (Snapshot, error)
	// OwnerEpoch returns the current execution owner epoch, which fences node
	// connections.
	OwnerEpoch(ctx context.Context) (uint64, error)
	// Allocation returns the allocation of the Environment the reference names
	// with the deployment, read in one snapshot. It returns ErrInvalidInput for
	// malformed identifiers and ErrNotFound for a missing allocation.
	Allocation(ctx context.Context, ref sandbox.Reference) (AllocationRecord, error)
	// Generations returns up to 32 retained generations after the given one,
	// in order, without their credential.
	Generations(ctx context.Context, after int64) ([]GenerationRecord, error)
	// Nodes returns the installation's nodes.
	Nodes(ctx context.Context) ([]NodeRecord, error)
	// NodeHistory returns one node and its host history samples in the window,
	// one per bucket that has samples. It returns ErrInvalidInput for a
	// malformed ID and ErrNotFound for a missing node.
	NodeHistory(ctx context.Context, nodeID string, window coremetrics.Range) (NodeRecord, []HostHistoryPoint, error)
	// ReadNodes runs apply in one read-only snapshot.
	ReadNodes(ctx context.Context, apply func(NodeReads) error) error
	// ResetSessions returns up to 32 hosted Sessions after the given Session
	// ID, in ID order, that still hold or await deployment resources. Without
	// force it skips Sessions with a running Turn or a pending file write. An
	// empty after starts at the beginning; a malformed one is ErrInvalidInput.
	ResetSessions(ctx context.Context, after string, force bool) ([]ResetSession, error)
	// AddressBindings counts what is bound to an installation address, read
	// in one snapshot. publicURL is the address nodes are compared against.
	AddressBindings(ctx context.Context, publicURL string) (AddressBindings, error)
	// EnvironmentAllocation returns the Environment's latest allocation receipt, including
	// for a deleted Session. It returns ErrInvalidInput for a malformed
	// identifier and ErrNotFound for a missing allocation.
	EnvironmentAllocation(ctx context.Context, key AllocationKey) (Allocation, error)
	// CredentialAllocations returns up to 32 unreleased allocations after the
	// given allocation ID, in ID order. An empty after starts at the
	// beginning.
	CredentialAllocations(ctx context.Context, after string) ([]Allocation, error)
	// ObservationSessions returns up to limit undeleted hosted Sessions after
	// the given Session ID, in ID order, whose allocation, if any, is
	// unreleased. limit is 1 to 100. It reads only and renews nothing.
	ObservationSessions(ctx context.Context, after string, limit int) (ObservationSessionPage, error)
	// NodeAllocations returns up to 1000 unreleased allocations of the node,
	// oldest first. A missing node is ErrNotFound.
	NodeAllocations(ctx context.Context, nodeID string) ([]NodeAllocation, error)
	// NodeOnline reports whether the node is connected; a missing node is
	// offline.
	NodeOnline(ctx context.Context, nodeID string) (bool, error)
	// LifecycleNodes returns the node of each allocation lifecycle, offline
	// ones included, with the empty ID for the lifecycle without a node.
	LifecycleNodes(ctx context.Context) ([]string, error)
	// LifecycleAllocations returns up to 32 allocations of the node's
	// lifecycle after the given allocation ID, in ID order. An empty nodeID
	// names the lifecycle without a node.
	LifecycleAllocations(ctx context.Context, nodeID, after string) ([]Allocation, error)
	// UnallocatedEnvironments returns up to 32 pending hosted Environments of
	// the node's lifecycle without an allocation, after the given Environment
	// ID, in ID order. It reads the committed placement and never selects a
	// replacement node.
	UnallocatedEnvironments(ctx context.Context, nodeID, after string) ([]UnallocatedEnvironment, error)
	// RetainedNativeHistory reports the latest owner's persisted retention eligibility.
	RetainedNativeHistory(ctx context.Context, key AllocationKey) (bool, error)
	// PlacementDemand lists up to 32 unreserved first or retained requests in demand-time and ID order.
	PlacementDemand(ctx context.Context, after PlacementDemandCursor) ([]PlacementDemand, PlacementDemandCursor, error)
	// LifecyclePlacement returns what routing the Environment to its
	// lifecycle reads, including for a deleted Session. A missing Environment
	// is sessions.ErrNotFound.
	LifecyclePlacement(ctx context.Context, key AllocationKey) (LifecyclePlacement, error)
	// Activity returns the allocation's activity; a missing allocation is
	// ErrNotFound.
	Activity(ctx context.Context, allocationID string) (Activity, error)
}

Reader answers deployment and node queries.

type Record

type Record struct {
	// InstallationID is empty until Web setup claims an installation.
	InstallationID     string
	Provider           string
	BackendFingerprint string
	Generation         uint64
	OwnerEpoch         uint64
	Mode               string
	// Specification is the stored specification document.
	Specification json.RawMessage
	// Configuration holds the public configuration and metadata and, when a
	// credential is stored and could be opened, its secret.
	Configuration    sandbox.ConfigurationRecord
	CredentialStored bool
	// CredentialError is why the stored credential could not be opened: a
	// ciphertext the key cannot open or authenticate (an internal error).
	CredentialError error
	// Reset is nil unless a reset is in progress.
	Reset *ResetState
}

Record is the stored deployment.

type ReservationTx

type ReservationTx interface {
	sessions.EnvironmentDeviceTx
	// LoadEnvironment reads the Session's Environment.
	LoadEnvironment(ctx context.Context) (sessions.Environment, error)
	// FindAllocation returns the Environment's allocation and whether it has
	// one.
	FindAllocation() (Allocation, bool, error)
	// LockDeployment locks the deployment and returns it as placement reads it.
	LockDeployment() (placement.Deployment, error)
	// LoadReserved returns the node placement the Session reserved for the
	// Environment.
	LoadReserved() (placement.Reserved, error)
	// InsertAllocation stores the allocation of the Session's Environment.
	InsertAllocation(allocation NewAllocation) (Allocation, error)
	// CanReplaceAllocation verifies retained storage and settled, revoked prior ownership.
	CanReplaceAllocation() (bool, error)
	// LoadGenerationSpecification reads immutable storage requirements for placement.
	LoadGenerationSpecification(generation uint64) (GenerationSpecification, error)
	// LoadNodes reads eligible placement facts under the deployment lock.
	LoadNodes() ([]placement.Node, error)
	// ReservePlacement inserts a first reservation or replaces a released reservation without changing historical receipts.
	ReservePlacement(placement.Placement) error
	// ReleaseFailedPlacement yields only the exact reservation without active compute.
	ReleaseFailedPlacement(placement.Reserved) error
}

ReservationTx is one Session-locked allocation reservation. The Session is the owner of the Environment the transaction was opened for.

type Reset

type Reset struct {
	Clear       ResetMode      `json:"clear" binding:"required"`
	RequestedAt time.Time      `json:"requested_at" binding:"required"`
	DeadlineAt  *time.Time     `json:"deadline_at" extensions:"x-nullable" binding:"required"`
	ForcedAt    *time.Time     `json:"forced_at" extensions:"x-nullable" binding:"required"`
	Remaining   ResetRemaining `json:"remaining" binding:"required"`
}

Reset contains only durable state and a single-snapshot resource partition.

type ResetMode added in v0.0.10

type ResetMode string
const (
	// ResetAuto archives idle Sessions and escalates to ResetForce at the
	// deadline.
	ResetAuto ResetMode = "auto"
	// ResetForce archives every hosted Session, busy ones included.
	ResetForce ResetMode = "force"
)

type ResetOfflineNode

type ResetOfflineNode struct {
	NodeID    string `json:"node_id" binding:"required"`
	Name      string `json:"name" binding:"required"`
	Resources int64  `json:"resources" binding:"required"`
}

type ResetRemaining

type ResetRemaining struct {
	Busy           int64              `json:"busy" binding:"required"`
	Idle           int64              `json:"idle" binding:"required"`
	Cleanup        int64              `json:"cleanup" binding:"required"`
	OnOfflineNodes int64              `json:"on_offline_nodes" binding:"required"`
	OfflineNodes   []ResetOfflineNode `json:"offline_nodes" binding:"required"`
}

type ResetRequest

type ResetRequest struct {
	ExpectedGeneration uint64    `json:"expected_generation" binding:"required" minimum:"0"`
	Clear              ResetMode `json:"clear" binding:"required"`
	DeadlineSeconds    *int32    `json:"deadline_seconds,omitempty" minimum:"300" maximum:"86400"`
}

ResetRequest starts or escalates a reset of the sandbox deployment.

type ResetRequiredError

type ResetRequiredError struct{ CurrentProvider, RequestedProvider string }

ResetRequiredError rejects a change that needs a reset first, such as a change of backend.

func (*ResetRequiredError) Error

func (e *ResetRequiredError) Error() string

func (*ResetRequiredError) Unwrap

func (e *ResetRequiredError) Unwrap() error

type ResetSession

type ResetSession struct{ SessionID, TenantID string }

ResetSession is a hosted Session a reset still has to archive.

type ResetState

type ResetState struct {
	Clear                string
	RequestedAt          time.Time
	DeadlineAt, ForcedAt *time.Time
}

ResetState is the durable state of a reset in progress.

type Resources

type Resources struct {
	Allocations int64 `json:"allocations" binding:"required"`
	Pending     int64 `json:"pending" binding:"required"`
}

Resources counts what still belongs to the deployment.

type Rollout

type Rollout struct {
	State                       RolloutState  `json:"state" binding:"required"`
	PreviousGenerationSandboxes int64         `json:"previous_generation_sandboxes" binding:"required"`
	Nodes                       *RolloutNodes `json:"nodes" extensions:"x-nullable" binding:"required"`
}

type RolloutNodes

type RolloutNodes struct {
	Ready          int64 `json:"ready" binding:"required"`
	Preparing      int64 `json:"preparing" binding:"required"`
	Failed         int64 `json:"failed" binding:"required"`
	UpdateRequired int64 `json:"update_required" binding:"required"`
	Unknown        int64 `json:"unknown" binding:"required"`
}

type RolloutState added in v0.0.10

type RolloutState string
const (
	RolloutSettled   RolloutState = "settled"
	RolloutPreparing RolloutState = "preparing"
)

type SelectionRecord

type SelectionRecord struct {
	InstallationID, Provider, BackendFingerprint, Mode string
	Generation                                         uint64
	Specification                                      json.RawMessage
	// Configuration carries the secret in plaintext; the adapter seals it.
	Configuration sandbox.ConfigurationRecord
}

SelectionRecord is one generation of the selection to store.

type Service

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

Service reads the deployment and manages its nodes. It grants no execution authority: deployment changes run through ExecutionOperations.

func NewService

func NewService(storage Storage, reader Reader, registry *providers.Registry, rules *placement.Rules) (*Service, error)

NewService returns the deployment service. rules are the installation's placement rules, built once with its provider declarations and validated public URL.

func (*Service) AddressBindings

func (s *Service) AddressBindings(ctx context.Context) (AddressBindings, error)

AddressBindings counts what is bound to the installation public URL.

func (*Service) AllocationGeneration

func (s *Service) AllocationGeneration(ctx context.Context, ref sandbox.Reference) (string, uint64, error)

AllocationGeneration returns the node and generation an unreleased allocation was created on, including for a deleted Session. It never substitutes the deployment's target.

func (*Service) AllocationSetup

func (s *Service) AllocationSetup(ctx context.Context, ref sandbox.Reference) (Setup, error)

AllocationSetup returns the immutable generation an allocation was created with, configured with the current credential. A released allocation stays historical and is never rebound.

func (*Service) AuthenticateNode

func (s *Service) AuthenticateNode(ctx context.Context, nodeID, credential string) (NodeIdentity, error)

AuthenticateNode checks a node credential and returns the node's identity.

func (*Service) ConnectNode

func (s *Service) ConnectNode(ctx context.Context, nodeID, connectionID string, epoch uint64) error

ConnectNode records a node connection for the owner epoch.

func (*Service) CreateEnrollment

func (s *Service) CreateEnrollment(ctx context.Context, capacity Capacity) (EnrollmentToken, error)

CreateEnrollment issues a one-use enrollment token. Its ID is a public, non-secret handle: the node the token registers reports it as enrollment_id.

func (*Service) DecodeConfiguration

func (s *Service) DecodeConfiguration(provider string, public, credential json.RawMessage) (sandbox.Configuration, error)

DecodeConfiguration reads a submitted provider configuration and credential.

func (*Service) DisconnectNode

func (s *Service) DisconnectNode(ctx context.Context, nodeID, connectionID string, epoch uint64) error

DisconnectNode clears the node's connection when it is still this one.

func (*Service) Enroll

func (s *Service) Enroll(ctx context.Context, token string, input Enrollment) (NodeIdentity, error)

Enroll registers a node with a one-use enrollment token.

func (*Service) GenerationPage

func (s *Service) GenerationPage(ctx context.Context, after int64) ([]Setup, error)

GenerationPage returns up to 32 retained generations after the given one, without their credential. Callers keep a deadline over the full scan.

func (*Service) Heartbeat

func (s *Service) Heartbeat(ctx context.Context, nodeID, connectionID string, epoch uint64, health NodeHealth, statuses []sandbox.GenerationStatus) error

Heartbeat records a protocol 1 node's health, which reports readiness of its enrollment generation only.

func (*Service) HeartbeatGenerations

func (s *Service) HeartbeatGenerations(ctx context.Context, nodeID, connectionID string, epoch uint64, health NodeHealth, statuses []sandbox.GenerationStatus) error

HeartbeatGenerations records a node's health and the preparation state of the generations it reports.

func (*Service) LifecycleNode

func (s *Service) LifecycleNode(ctx context.Context, tenant, environment string) (string, error)

LifecycleNode routes a hosted Environment to the node lifecycle that provisions it, before its allocation exists: empty without a node. An existing allocation must agree with the Session's immutable placement.

func (*Service) ListNodes

func (s *Service) ListNodes(ctx context.Context) ([]Node, error)

ListNodes returns the installation's nodes.

func (*Service) NodeConfiguration

func (s *Service) NodeConfiguration(ctx context.Context, nodeID, token string, generation uint64) (NodeConfiguration, error)

NodeConfiguration is the read-only bootstrap of an enrollment token or node credential. It never consumes tokens or reveals cloud credentials, and it authenticates the credential before reporting any deployment state. The deployment lock keeps authentication and the returned generation consistent.

A nonzero generation recovers that exact generation, restricted to this node's current target, serving pin and unreleased ownership. It is never a general history read.

func (*Service) NodeDetail

func (s *Service) NodeDetail(ctx context.Context, id, window string) (NodeDetail, error)

NodeDetail returns one node with its last host observation and its host history over the named window: 1h, 6h or 24h.

func (*Service) NodeRetention

func (s *Service) NodeRetention(ctx context.Context, nodeID, connectionID string, epoch uint64, refs []sandbox.GenerationReference) (sandbox.NodeDeployment, []sandbox.GenerationRetention, error)

NodeRetention answers which reported generations a node keeps, under the same serialization as pin promotion and placement, so a dropped generation cannot later gain fresh ownership. It deletes the status of the rest.

func (*Service) NodeStatus

func (s *Service) NodeStatus(ctx context.Context, nodeID, credential string) (NodeStatus, error)

NodeStatus reports the authenticated node's Core-owned presence.

func (*Service) RemoveNode

func (s *Service) RemoveNode(ctx context.Context, id string) error

RemoveNode removes a node that retains no resources and is not the local node.

func (*Service) Setup

func (s *Service) Setup(ctx context.Context) (Setup, error)

Setup returns the Web-managed selection with its credential.

func (*Service) SetupForSelection

func (s *Service) SetupForSelection(installationID string, input sandbox.Selection) (Setup, error)

SetupForSelection prepares a selection's setup without writing or allocating resources. It rejects a provider that requires a reachable public origin while the installation public URL is loopback.

func (*Service) TouchActivity

func (s *Service) TouchActivity(ctx context.Context, tenant, environment string) error

TouchActivity records live-compute activity of the tenant's Environment. Only operations that need live compute call it; history and published Artifact reads never do.

func (*Service) UpdateNode

func (s *Service) UpdateNode(ctx context.Context, id string, update NodeUpdate) error

UpdateNode renames a node and changes its capacity.

func (*Service) ValidateWorkspaceConfiguration added in v0.0.10

func (s *Service) ValidateWorkspaceConfiguration(ctx context.Context, declaration workspacefs.Declaration) error

ValidateWorkspaceConfiguration qualifies a filesystem selection against the stored generation without constructing a native Sandbox Provider.

func (*Service) View

func (s *Service) View(ctx context.Context) (View, error)

View returns the deployment as administrators read it.

func (*Service) WithCredential

func (s *Service) WithCredential(owner, candidate Setup) (Setup, error)

WithCredential returns owner configured with the credential of candidate, which selects the same provider.

type SessionArchiveTx added in v0.0.10

type SessionArchiveTx interface {
	sessions.CancellationTx
	sessions.InputActivityTx
	// LoadDeployment locks the deployment and returns it. The Session lock
	// precedes it, as in Turn, allocation and input admission.
	LoadDeployment() (Record, error)
	// LoadEnvironment reads the Session's Environment.
	LoadEnvironment(ctx context.Context) (sessions.Environment, error)
	// ExpireEnvironment sets the status of the Session's Environment to
	// expired.
	ExpireEnvironment(ctx context.Context, environment string) error
	// LoadResetBusy reports whether the Session has an in-progress or waiting
	// Turn or subagent Turn, or a pending Environment file write, which an
	// automatic reset does not archive.
	LoadResetBusy() (bool, error)
	// LoadResetSource returns the administrator source that started the
	// running reset.
	LoadResetSource() (adminaudit.Source, error)
	// LoadProject returns the ID of the tenant's Project.
	LoadProject() (string, error)
	// FindAllocation returns the Environment's allocation and whether it has
	// one.
	FindAllocation(environment string) (Allocation, bool, error)
	// RequestArchiveCleanup revokes the allocation's device and records that
	// its resources await cleanup. The device's first revocation records the
	// Session's active Turn whose cancellation was requested, which the
	// archived cancellation receipt reports.
	RequestArchiveCleanup(current Allocation) error
	// ReleasePlacement releases the node placement of the Session's
	// Environments that have no allocation.
	ReleasePlacement() error
	// RecordArchiveAudit records the administrator audit of the archive with
	// the source on ctx.
	RecordArchiveAudit(ctx context.Context) error
	// LoadArchive reads the resource disposal of the Session's hosted
	// Environment.
	LoadArchive(ctx context.Context) (sessions.ManagedArchive, error)
}

SessionArchiveTx is one Session-locked archive of the Session's hosted Environment, with the Session's cancellation bound to the same transaction.

type SessionDevice

type SessionDevice struct{ ID, EnvironmentID string }

SessionDevice is the Runtime device a Session is bound to.

type Setup

type Setup struct {
	Specification                                sandbox.DeploymentSpec
	InstallationID, Provider, BackendFingerprint string
	Generation                                   uint64
	// Mode is where the provider runs: "nodes" for enrolled sandbox nodes and
	// "direct" for a provider Core calls itself.
	Mode string
	// Operations is the provider's declared operation support, which the node
	// transport proxies.
	Operations    providercontract.Operations
	Configuration sandbox.Configuration `json:"-"`
	// Suspension is the idle suspension policy of a provider that declares
	// checkpoint support, and nil otherwise.
	Suspension *Suspension
	// UsesCredential reports whether the provider's configuration carries a
	// credential.
	UsesCredential bool
}

Setup is the immutable configuration selected by the deployment admin, or one generation of it. An empty Provider means that Web setup has not yet selected an adapter.

type Snapshot

type Snapshot struct {
	Record    Record
	Resources Resources
	Rollout   Rollout
	// Remaining partitions the resources while a reset is in progress.
	Remaining ResetRemaining
}

Snapshot is the deployment with the counts and projections of its View.

type Storage

type Storage interface {
	// WithNodes runs apply in one transaction that begins by locking the
	// deployment, so node changes serialize with deployment changes, pin
	// promotion and placement. It commits only when apply returns nil.
	WithNodes(ctx context.Context, apply func(NodeTx) error) error
	// ConnectNode records a node connection for the owner epoch, when the node
	// belongs to the installation and no newer epoch connected it. It reports
	// whether it did.
	ConnectNode(ctx context.Context, nodeID, connectionID string, epoch uint64) (bool, error)
	// DisconnectNode clears the node's connection when it is still this one. It
	// waits for the node row first, so an uncertain connect cannot outlive it.
	DisconnectNode(ctx context.Context, nodeID, connectionID string, epoch uint64) error
	// SampleHostHistory copies each fresh authenticated heartbeat into the
	// host history, at the Runtime sampler cadence, and returns the number of
	// samples. Neither reads nor offline nodes fill gaps.
	SampleHostHistory(ctx context.Context) (int64, error)
	// WithActivity runs apply in one transaction that locks the Session of
	// the tenant's Environment and then prunes the Session's journal. It
	// commits only when both succeed. A missing Environment, or one of a
	// deleted Session, is sessions.ErrNotFound.
	WithActivity(ctx context.Context, key AllocationKey, apply func(sessions.LockedSession, ActivityTx) error) error
}

Storage is the persistence node management writes through, on pooled connections. It grants no execution authority.

type StoredNode

type StoredNode struct {
	ID, InstallationID, Name, BackendFingerprint string
	CredentialDigest                             string
	MaxActive, MaxRetained                       int
	ConnectionID                                 string
	ConnectedEpoch                               uint64
	SpecificationDigest                          string
	DeploymentGeneration                         uint64
	ReadyGeneration                              *uint64
}

StoredNode is one node as stored.

type Suspension

type Suspension struct {
	IdleSeconds      int64 `json:"idle_seconds" binding:"required"`
	RetentionSeconds int64 `json:"retention_seconds" binding:"required"`
}

Suspension is Core's idle suspension policy, which applies to every Provider that declares checkpoint support.

type SuspensionDemand added in v0.0.10

type SuspensionDemand struct {
	Deployment         placement.Deployment
	Nodes              []placement.Node
	InFlightNodes      []string
	CheckpointRestores []CheckpointRestoreDemand
}

SuspensionDemand is a transaction-bound capacity observation. It is not a reservation: only a confirmed suspension frees an active slot.

type UnallocatedEnvironment

type UnallocatedEnvironment struct{ ID, TenantID string }

UnallocatedEnvironment is a committed hosted Environment awaiting its allocation. A missing allocation differs from an unknown Create outcome of an existing one.

type View

type View struct {
	Rollout              Rollout                 `json:"rollout" binding:"required"`
	Specification        *sandbox.DeploymentSpec `json:"specification,omitempty"`
	SpecificationDigest  string                  `json:"specification_digest,omitempty"`
	Generation           uint64                  `json:"generation" binding:"required"`
	Mode                 sandbox.DeploymentMode  `json:"mode" binding:"required"`
	Resources            Resources               `json:"resources" binding:"required"`
	Configuration        json.RawMessage         `json:"configuration,omitempty" swaggertype:"object"`
	Metadata             json.RawMessage         `json:"metadata,omitempty" swaggertype:"object"`
	CredentialConfigured bool                    `json:"credential_configured" binding:"required"`
	// Idle suspension policy; null unless the selected Provider declares checkpoint support.
	Suspension     *Suspension `json:"suspension" extensions:"x-nullable" binding:"required"`
	InstallationID string      `json:"installation_id" binding:"required"`
	Provider       string      `json:"provider" binding:"required"`
	Reset          *Reset      `json:"reset" extensions:"x-nullable" binding:"required"`
	OwnerEpoch     uint64      `json:"owner_epoch" binding:"required"`
	// Read-only: the installation public URL (OAC_PUBLIC_URL), which nodes and sandboxes use to reach Core. The deployment API does not accept it.
	CoreURL string `json:"core_url" binding:"required"`
}

View is the sandbox deployment as administrators read it.

Directories

Path Synopsis
Package placement decides whether the sandbox deployment admits new hosted work and which node receives it.
Package placement decides whether the sandbox deployment admits new hosted work and which node receives it.

Jump to

Keyboard shortcuts

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