workspace

package
v0.9.3 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2026 License: MIT Imports: 22 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 workspace creates deterministic, path-safe plans and applies their explicit file transitions with verified snapshot preconditions.

Index

Constants

View Source
const (
	MaxDirectoryGuards    = 32
	MaxDirectoryEntries   = 8192
	MaxDirectoryPathBytes = 1 << 20
	DirectoryFile         = "file"
	DirectoryDir          = "directory"
)
View Source
const (
	PlanAPIVersion        = "appkit.dev/workspace-plan/v1alpha1"
	GuardedPlanAPIVersion = "appkit.dev/workspace-plan/v1alpha2"
	PlanKind              = "WorkspacePlan"
	MaxPlanDocumentBytes  = 16 << 20
)
View Source
const (
	// MaxPlanChanges is the implementation ceiling for one atomic target set.
	MaxPlanChanges = 4_096
	// MaxPlanContentBytes bounds the detached write payload retained by a Plan.
	MaxPlanContentBytes = 8 << 20
	// MaxPlanPathBytes bounds the aggregate target-path bytes retained by one
	// Plan. Combined with the content and change ceilings, this keeps every
	// serialized plan within a practical nested-wire allocation budget.
	MaxPlanPathBytes = 1 << 20
)

Variables

View Source
var (
	ErrInvalidPlanDocument = errors.New("workspace: invalid plan document")
	ErrNonCanonicalPlan    = errors.New("workspace: non-canonical plan document")
)
View Source
var (
	// ErrInvalidChange identifies a malformed or contradictory requested file
	// operation.
	ErrInvalidChange = errors.New("workspace: invalid change")
	// ErrInvalidPlan identifies a zero, corrupted, or internally inconsistent
	// plan. Plans are immutable values produced by BuildPlan.
	ErrInvalidPlan = errors.New("workspace: invalid plan")
	// ErrRollback identifies one or more failures while restoring the captured
	// precondition after a commit error.
	ErrRollback = errors.New("workspace: rollback failed")
)
View Source
var (
	ErrRecovery = errors.New("workspace: recovery required")
	// ErrRecoveryRestart identifies a successfully rolled-back admitted
	// transaction. A gated caller must invoke apply again so a fresh admission
	// is distinguishable from crash recovery.
	ErrRecoveryRestart = errors.New("workspace: admitted transaction recovered; retry required")
)
View Source
var (
	ErrInvalidPath  = errors.New("workspace: invalid path")
	ErrSymlink      = errors.New("workspace: symbolic link is not allowed")
	ErrChanged      = errors.New("workspace: precondition changed")
	ErrFileTooLarge = errors.New("workspace: file exceeds read limit")
)
View Source
var ErrCommitAdmission = errors.New("workspace: commit admission rejected")

ErrCommitAdmission identifies a commit gate that rejected or returned an invalid receipt. The callback's original error remains in the error chain.

View Source
var ErrLockUnsupported = errors.New("workspace: inter-process locking unsupported")

ErrLockUnsupported identifies a host or filesystem that cannot provide the cross-process exclusion required for workspace mutation.

Functions

func MarshalPlan

func MarshalPlan(plan Plan) ([]byte, error)

MarshalPlan returns the unique bounded JSON representation of a Plan. Write payloads are included so another process can apply the exact reviewed plan; the digest still binds both the before state and desired final state. The current wire format requires every existing precondition file to have owner-read permission and no special mode bits. Unsupported modes fail closed rather than producing a document that cannot represent the state losslessly.

func WithReadLock

func WithReadLock(ctx context.Context, root string, inspect func() error) (resultErr error)

WithReadLock runs inspect while cooperative workspace writers are excluded. Before calling inspect it rejects an active transaction, so framework readers never consume a crash-partial target set. Completed transaction debris is safe because its directory rename is the durable commit decision.

The callback should finish promptly and must not call Apply or recursively acquire another workspace lock for the same root. Writers outside the appkit locking protocol remain outside this guarantee.

Types

type ApplyDisposition

type ApplyDisposition string

ApplyDisposition distinguishes a new commit from an idempotent replay.

const (
	ApplyCommitted ApplyDisposition = "committed"
	ApplyReplayed  ApplyDisposition = "replayed"
)

type ApplyResult

type ApplyResult struct {
	PlanDigest             string
	Disposition            ApplyDisposition
	AdmissionReceiptDigest string
}

A non-empty ApplyResult disposition means every target reached the planned final state. Replayed means no filesystem mutation was necessary.

func Apply

func Apply(ctx context.Context, root string, plan Plan) (result ApplyResult, resultErr error)

Apply installs a valid plan after rechecking its exact precondition under a process-local and host-process workspace lock. Files are staged and backed up on the same filesystem, and a failed commit is rolled back in reverse order. A prepared transaction is durably recorded before the first public rename. If a process terminates mid-commit, only the exact same Plan may recover it; an unrelated plan fails closed with ErrRecovery.

Cooperative appkit processes are serialized. Unrelated writers that ignore the advisory lock are detected by target preconditions where possible and remain outside this primitive's authority.

func ApplyWithCommitGate

func ApplyWithCommitGate(
	ctx context.Context,
	root string,
	plan Plan,
	gate CommitGate,
) (result ApplyResult, resultErr error)

ApplyWithCommitGate applies a plan through a higher-level admission gate. It has the same crash recovery semantics as Apply, but an active prepared transaction can be recovered only by the exact gate domain and subject.

type Change

type Change struct {
	Path      string
	Operation Operation
	Content   []byte
	Mode      fs.FileMode
}

Change requests one file transition. Create and update content is copied by BuildPlan and their modes must permit owner reads so future digest verification remains possible. Delete requires nil Content and a zero Mode.

type CommitGate

type CommitGate struct {
	Domain        string
	SubjectDigest string
	Inspect       func(context.Context) error
	Admit         func(context.Context) (string, error)
	Recheck       func(context.Context, string) error
}

CommitGate runs inside the exclusive workspace lock. Inspect is an optional deterministic endpoint check performed after crash recovery but before staging or state classification. Admit runs after staging and returns a durable receipt digest; Recheck verifies it after the recovery journal is synced and immediately before the first public mutation. SubjectDigest binds a higher-level immutable plan (for example an upgrade apply plan). If the process dies after public mutation starts, recovery trusts only the persisted domain, subject, and receipt and never invokes any callback.

type DirectoryEntry

type DirectoryEntry struct {
	Path string `json:"path"`
	Kind string `json:"kind"`
}

DirectoryEntry is a path relative to its guarded directory. Membership includes empty directories, but not file contents; assert the relevant files separately to bind contents and permissions as well.

type DirectoryGuard

type DirectoryGuard struct {
	Before DirectorySnapshot `json:"before"`
	After  DirectorySnapshot `json:"after"`
}

DirectoryGuard binds both the captured tree and the membership derived from the plan's explicit file transitions. Callers cannot supply an arbitrary After.

type DirectorySnapshot

type DirectorySnapshot struct {
	Path    string           `json:"path"`
	Exists  bool             `json:"exists"`
	Entries []DirectoryEntry `json:"entries"`
}

DirectorySnapshot records exact recursive membership of a directory. Missing directories have Exists=false and no entries. Entries are lexical by Path. Path may be "."; reserved workspace transaction directories are excluded only at the workspace root, since the engine owns those temporary paths.

func CaptureDirectory

func CaptureDirectory(root, dir string) (snapshot DirectorySnapshot, resultErr error)

CaptureDirectory reads bounded recursive membership through a confined root. Symlinks and special files are rejected, including in directory ancestors. Two matching walks detect membership changes during capture. Callers composing several snapshots should use WithReadLock to exclude cooperative writers.

type File

type File struct {
	Path   string
	Exists bool
	Mode   fs.FileMode
	Digest string
}

File records the content state of one project-relative regular file. A missing file is a deliberate state used by plans that intend to create it.

func ReadFile

func ReadFile(root, name string, maxBytes int64) (content []byte, state File, resultErr error)

ReadFile reads one bounded regular file through the same symlink-safe root confinement and double-read stability checks used by Capture. A missing path is returned as an Exists=false File and nil content.

type Operation

type Operation string

Operation is one explicit target-file transition.

const (
	OperationCreate Operation = "create"
	OperationUpdate Operation = "update"
	OperationDelete Operation = "delete"
	// OperationAssert binds a file's captured state to a Plan without ever
	// renaming, writing, chmodding, creating, or deleting that path.
	OperationAssert Operation = "assert"
)

type Plan

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

Plan binds an explicit operation set to both the captured current snapshot and the desired final snapshot. Its zero value is invalid.

func BuildPlan

func BuildPlan(root string, input []Change) (Plan, error)

BuildPlan captures the current state of every explicit target and creates a deterministic immutable plan. Input order does not affect the result.

func BuildPlanWithGuards

func BuildPlanWithGuards(root string, changes []Change, before []DirectorySnapshot) (result Plan, resultErr error)

BuildPlanWithGuards binds captured directory snapshots and derives their final membership from changes. Each supplied snapshot is compared with live state; additions made after input enumeration therefore cannot disappear from a plan. An empty guard list has exactly BuildPlan's legacy digest and wire encoding.

func ParsePlan

func ParsePlan(data []byte) (Plan, error)

ParsePlan accepts only MarshalPlan's canonical representation. It performs no filesystem I/O and reconstructs an immutable Plan with detached payloads.

func (Plan) Changes

func (plan Plan) Changes() []PlannedChange

Changes returns a payload-free copy in canonical path order.

func (Plan) Digest

func (plan Plan) Digest() string

Digest returns the domain-separated digest binding precondition and desired state.

func (Plan) DirectoryGuards

func (plan Plan) DirectoryGuards() []DirectoryGuard

DirectoryGuards returns detached before/final memberships.

func (Plan) FinalDigest

func (plan Plan) FinalDigest() string

FinalDigest returns the desired target-set digest.

func (Plan) Preconditions

func (plan Plan) Preconditions() []File

Preconditions returns the exact file states captured for every change in the same canonical path order as Changes.

func (Plan) SnapshotDigest

func (plan Plan) SnapshotDigest() string

SnapshotDigest returns the captured precondition digest.

func (Plan) Validate

func (plan Plan) Validate() error

Validate detects zero values, mutation, contradictory file transitions, and payload/digest mismatches without consulting a workspace.

type PlannedChange

type PlannedChange struct {
	Path          string
	Operation     Operation
	ContentDigest string
	Mode          fs.FileMode
}

PlannedChange is the payload-free, deterministic representation of a change. ContentDigest is populated only for create and update.

type Snapshot

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

Snapshot is an immutable deterministic view of an explicit file set.

func Capture

func Capture(root string, paths []string) (Snapshot, error)

Capture snapshots paths below root. Paths must be normalized, slash- separated relative file names. Symbolic links are rejected in every path component below root so a precondition cannot escape or silently retarget its root.

func (Snapshot) Digest

func (snapshot Snapshot) Digest() string

Digest returns the canonical snapshot digest.

func (Snapshot) Files

func (snapshot Snapshot) Files() []File

Files returns a copy of the canonical file list.

func (Snapshot) Verify

func (snapshot Snapshot) Verify(root string) error

Verify recaptures the same paths below root and returns ErrChanged when any file's existence, permissions, type, or content differs. If recapturing a path fails, the error matches both ErrChanged and the underlying cause.

Jump to

Keyboard shortcuts

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