devsession

package
v0.30.0 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: AGPL-3.0 Imports: 29 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 devsession provides persistent development-session ownership primitives. It does not supervise children or infer service readiness from a lease or PID.

Index

Constants

View Source
const (
	LeaseReserved   = "reserved"
	LeaseBound      = "bound"
	LeaseBindFailed = "bind-failed"
	LeaseReleased   = "released"
)

Variables

View Source
var (
	ErrPortConflict      = errors.New("devsession: port conflict")
	ErrInvalidTransition = errors.New("devsession: invalid lease transition")
	ErrAttemptsExhausted = errors.New("devsession: bind allocation attempts exhausted")
)
View Source
var (
	ErrOwnership           = errors.New("devsession: ownership conflict")
	ErrProcessGone         = errors.New("devsession: process no longer exists")
	ErrUnsupportedIdentity = errors.New("devsession: platform cannot safely verify or terminate this process")
)

Functions

func AcquirePrivateLock

func AcquirePrivateLock(ctx context.Context, directory, name string) (*flock.Flock, error)

AcquirePrivateLock acquires a stable-inode private flock in an already ensured dedicated runtime directory. Name must be one portable leaf filename. Never initialize a lock by atomically replacing its path: that can bypass a held inode. This creates without following a leaf symlink/reparse point, restricts the initial handle, and checks that flock acquired that exact inode.

func CaptureProcess

func CaptureProcess(pid int, owner ProcessOwner) (devcontract.ProcessIdentity, error)

CaptureProcess records a kernel-sourced start identity and executable for a process the caller owns. Call this immediately after starting the child, and persist the result privately. This is an ownership attestation, not adoption or authorization of arbitrary processes discovered by PID.

func EnsurePrivateDirectory

func EnsurePrivateDirectory(path string) (string, error)

EnsurePrivateDirectory creates/canonicalizes a dedicated private runtime directory and applies the platform's owner-only permissions. Callers choose the development root explicitly; this does not infer workspace identity.

func GenerateToken

func GenerateToken() ([]byte, error)

GenerateToken returns 256 bits of randomness encoded for a bearer token file. Callers must never serialize its value into discovery, inspect or log output.

func ProbeViteHMR

func ProbeViteHMR(ctx context.Context, address string) (string, error)

ProbeViteHMR discovers the websocket URL from the ACTUAL served Vite client, including configured hostname/clientPort/HMR path. It requires a real Vite protocol connected frame, not HTTP text, an open port or a guessed WS URL. Returned URL and all errors omit the ephemeral websocket token/source text.

func ReadPrivateJSON

func ReadPrivateJSON(path string, value any) error

ReadPrivateJSON decodes one complete private JSON document. Workspace and generation checks remain the consuming record's responsibility. Unknown fields and trailing documents are rejected rather than silently discarded.

func ReadUnixSocketDirectory

func ReadUnixSocketDirectory(runtimeRoot, workspaceID, generation, source string) (string, error)

ReadUnixSocketDirectory authorizes only the exact selected workspace and live supervisor generation. The caller must derive runtimeRoot from its profile, not from an inherited socket-directory environment variable.

func TerminateOwnedProcess

func TerminateOwnedProcess(record devcontract.ProcessIdentity, expected ProcessOwner) error

TerminateOwnedProcess terminates only the exact recorded process, through a process-stable OS handle. It never signals process groups or port owners. Linux uses pidfds; Windows uses a verified process handle. Darwin and other unsupported platforms fail closed rather than check-then-signal a numeric PID. Already exited processes are successful, but malformed/wrong-owner records always fail. No graceful-shutdown or escalation policy is imposed here.

func ValidatePrivateDirectory

func ValidatePrivateDirectory(path string) error

ValidatePrivateDirectory checks an existing directory without adopting it or repairing its permissions. Redirected ancestors and non-directory leaves are refused using the same platform ownership policy as private runtime files.

func ValidatePrivateFile

func ValidatePrivateFile(path string) error

ValidatePrivateFile rejects symlinks, nonregular files, foreign owners and permissions/ACLs that allow other principals. It does not repair/adopt files. This is a point-in-time pathname check, not a retained file handle: appenders must bind validation to their opened handle (SameFile/no-follow checks) and keep their own serialization. Initialize a new log with WritePrivateFile.

func ValidateUnixSocketDirectoriesRemoved

func ValidateUnixSocketDirectoriesRemoved(runtimeRoot string) error

ValidateUnixSocketDirectoriesRemoved is a read-only removal preflight. Even a malformed or interrupted record must survive: it may be the last provenance for an external namespace whose descendants have not been disposed.

func VerifyOwnedProcess

func VerifyOwnedProcess(record devcontract.ProcessIdentity, expected ProcessOwner) error

VerifyOwnedProcess compares all recorded provenance and the live kernel start identity/executable. Permission errors are not evidence of a stale process. Verification alone is not an atomic authorization for a subsequent PID kill.

func WritePrivateFile

func WritePrivateFile(path string, content []byte) error

WritePrivateFile atomically publishes exact raw bytes, without JSON encoding or stdout output. Use for supervisor/MCP secret files and initial empty logs; appending remains the owner's retained-handle responsibility. Ensure the dedicated private parent directory first.

func WritePrivateJSON

func WritePrivateJSON(path string, value any) error

WritePrivateJSON atomically publishes json.Encoder bytes, including its final newline, with platform-private ownership/permissions. Ensure the dedicated parent directory first. Existing public/foreign/nonregular files are rejected. This writes one file; callers own generation checks and multi-file locking.

Types

type DiscoveryStore

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

DiscoveryStore owns one dedicated profile runtime directory. Its shared lock serializes publication and generation-checked cleanup across host processes.

func OpenDiscoveryStore

func OpenDiscoveryStore(runtimeDirectory string) (*DiscoveryStore, error)

func (*DiscoveryStore) Publish

func (store *DiscoveryStore) Publish(ctx context.Context, descriptor devcontract.InstanceDescriptor, token []byte) (devcontract.Discovery, error)

Publish writes the private token before atomically advertising its reference. Refreshes within a generation preserve both process identity and token. A new generation may replace only a provably stale host, never an inaccessible one. A lease, PID or endpoint alone is not evidence of application readiness.

func (*DiscoveryStore) Read

func (store *DiscoveryStore) Read(ctx context.Context, workspaceID, generation string) (devcontract.Discovery, error)

Read requires an explicit workspace and never falls back to production. An empty generation selects its current discovery; a nonempty generation must match exactly. Callers must verify process and endpoint identity before use.

func (*DiscoveryStore) Remove

func (store *DiscoveryStore) Remove(ctx context.Context, workspaceID, generation string) error

Remove is idempotent only for absent discovery or its exact generation. It cannot remove another host's descriptor or an arbitrary token-file reference. Superseded/crash-orphan token files are intentionally not swept by a new host.

type Lease

type Lease struct {
	Key         ServiceKey                   `json:"key"`
	Port        int                          `json:"port"`
	Generation  string                       `json:"generation"`
	Owner       devcontract.ProcessIdentity  `json:"owner"`
	Process     *devcontract.ProcessIdentity `json:"process,omitempty"`
	State       string                       `json:"state"`
	Strict      bool                         `json:"strict"`
	Attempt     int                          `json:"attempt"`
	MaxAttempts int                          `json:"maxAttempts"`
	FailedPorts []int                        `json:"failedPorts,omitempty"`
}

Lease is a cooperating reservation, NOT an OS socket reservation or readiness claim. Bound means the caller acknowledged this exact port for Process after independently verifying the endpoint; it does not mean RPC/controllers ready.

type LeaseRequest

type LeaseRequest struct {
	Key ServiceKey
	// Owner is the supervisor's captured identity, not the future listener PID.
	Owner  devcontract.ProcessIdentity
	Strict bool
	// A nonzero explicit override is always strict, even outside the managed range.
	Override int
}

type ProcessBridgeClient

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

func NewProcessBridgeClient

func NewProcessBridgeClient(config ProcessBridgeConfig) (*ProcessBridgeClient, error)

func (*ProcessBridgeClient) Close

func (c *ProcessBridgeClient) Close()

func (*ProcessBridgeClient) Start

type ProcessBridgeConfig

type ProcessBridgeConfig struct {
	Endpoint      string
	TokenFile     string
	WorkspaceFile string
	WorkspaceID   string
	Generation    string
	Host          devcontract.ProcessIdentity
}

type ProcessExitError

type ProcessExitError struct{ Code int }

func (*ProcessExitError) Error

func (e *ProcessExitError) Error() string

func (*ProcessExitError) ExitCode

func (e *ProcessExitError) ExitCode() int

type ProcessIdentityMismatch added in v0.22.0

type ProcessIdentityMismatch struct {
	Record             devcontract.ProcessIdentity
	ObservedStart      string
	ObservedExecutable string
}

ProcessIdentityMismatch identifies the rejected kernel observation without exposing command arguments or environment variables.

func (*ProcessIdentityMismatch) Error added in v0.22.0

func (e *ProcessIdentityMismatch) Error() string

func (*ProcessIdentityMismatch) Unwrap added in v0.22.0

func (e *ProcessIdentityMismatch) Unwrap() error

type ProcessLogPage

type ProcessLogPage struct {
	Data       string             `json:"data"`
	NextCursor int64              `json:"nextCursor"`
	EOF        bool               `json:"eof"`
	Overflow   bool               `json:"overflow"`
	Error      *devcontract.Error `json:"error,omitempty"`
}

type ProcessObservation added in v0.21.0

type ProcessObservation struct {
	PID           int    `json:"pid"`
	StartIdentity string `json:"startIdentity"`
	Executable    string `json:"executable"`
}

ProcessObservation identifies one sampled process lifetime. It carries no ownership provenance and never authorizes lifecycle operations or signaling.

func ObserveProcess added in v0.21.0

func ObserveProcess(pid int) (ProcessObservation, error)

ObserveProcess reads kernel identity without adopting the process as owned. The platform reader fences executable lookup with process-start observations.

type ProcessOwner

type ProcessOwner struct {
	WorkspaceID string
	Generation  string
	Role        string
	Source      string
}

ProcessOwner is provenance recorded by the supervisor when it starts a child. Workspace and generation are not inferred from an executable name or a PID. Source is the resolved source/build identity, not a display name.

func (ProcessOwner) Validate added in v0.7.3

func (o ProcessOwner) Validate() error

Validate checks provenance before a caller starts or records an owned child.

type ProcessRequest

type ProcessRequest struct {
	RequestID   string                      `json:"requestID"`
	WorkspaceID string                      `json:"workspaceID"`
	Generation  string                      `json:"generation"`
	Host        devcontract.ProcessIdentity `json:"host"`
	Operation   string                      `json:"operation"`
	Start       *ProcessStart               `json:"start,omitempty"`
	ProcessID   string                      `json:"processID,omitempty"`
	TimeoutMS   int                         `json:"timeoutMS,omitempty"`
	Cursor      int64                       `json:"cursor,omitempty"`
	Limit       int                         `json:"limit,omitempty"`
}

type ProcessResponse

type ProcessResponse struct {
	RequestID   string             `json:"requestID"`
	WorkspaceID string             `json:"workspaceID"`
	Generation  string             `json:"generation"`
	Process     *ProcessStatus     `json:"process,omitempty"`
	Logs        *ProcessLogPage    `json:"logs,omitempty"`
	Error       *devcontract.Error `json:"error,omitempty"`
}

type ProcessStart

type ProcessStart struct {
	PluginID         string `json:"pluginID"`
	PluginGeneration string `json:"pluginGeneration"`
	Kind             string `json:"kind"`
	Source           string `json:"source"`
	Port             int    `json:"port,omitempty"`
	PNPMPath         string `json:"pnpmPath,omitempty"`
	NodePath         string `json:"nodePath,omitempty"`
}

type ProcessStatus

type ProcessStatus struct {
	ProcessID string                      `json:"processID"`
	Identity  devcontract.ProcessIdentity `json:"identity"`
	Running   bool                        `json:"running"`
	ExitCode  int                         `json:"exitCode"`
}

type Registry

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

func OpenRegistry

func OpenRegistry(root string, options RegistryOptions) (*Registry, error)

OpenRegistry uses one dedicated, private root shared by all cooperating workspaces. Canonical paths share the same OS lock, including across processes.

func (*Registry) BindFailed

func (r *Registry) BindFailed(ctx context.Context, key ServiceKey, generation string, port int) error

BindFailed records an observed strict-child bind failure. It does not retry or terminate anything. The caller must reap its failed child before Reallocate.

func (*Registry) ConfirmBound

func (r *Registry) ConfirmBound(ctx context.Context, key ServiceKey, generation string, actualPort int, process devcontract.ProcessIdentity) error

ConfirmBound rejects a child's hidden port increment and verifies its captured process identity. Callers must independently verify endpoint workspace and generation plus service-specific readiness before advertising a ready service.

func (*Registry) List

func (r *Registry) List(ctx context.Context, workspaceID string) ([]Lease, error)

List returns persisted assignments, including released/stale generations, for an explicit workspace. It makes no liveness or readiness claim.

func (*Registry) Reallocate

func (r *Registry) Reallocate(ctx context.Context, key ServiceKey, generation string) (Lease, error)

Reallocate is the only automatic bind-race retry. Each returned assignment is recorded, skips this generation's failed ports, and consumes a bounded attempt.

func (*Registry) Release

func (r *Registry) Release(ctx context.Context, key ServiceKey, generation string) error

Release ends only this generation's cooperating reservation. It never closes a socket or kills a child, and retains the sticky assignment across restarts.

func (*Registry) Reserve

func (r *Registry) Reserve(ctx context.Context, request LeaseRequest) (Lease, error)

Reserve persists the exact assignment before returning it. An existing live generation cannot be adopted. Explicit overrides never silently increment.

type RegistryOptions

type RegistryOptions struct {
	// Zero range adopts an existing registry's range, or 20000–44999 for a new registry.
	MinPort int
	MaxPort int
	// MaxAttempts includes the initial assignment; zero defaults to eight.
	MaxAttempts int
}

type RemoteProcess

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

func (*RemoteProcess) ID

func (p *RemoteProcess) ID() string

func (*RemoteProcess) Identity

func (*RemoteProcess) Logs

func (p *RemoteProcess) Logs(ctx context.Context, cursor int64, limit int) (ProcessLogPage, error)

func (*RemoteProcess) Status

func (p *RemoteProcess) Status(ctx context.Context) (ProcessStatus, error)

func (*RemoteProcess) Stop

func (p *RemoteProcess) Stop(ctx context.Context) error

func (*RemoteProcess) Wait

func (p *RemoteProcess) Wait(ctx context.Context) error

type ServiceKey

type ServiceKey struct {
	WorkspaceID string `json:"workspaceID"`
	Role        string `json:"role"`
	PluginID    string `json:"pluginID,omitempty"`
}

ServiceKey never depends on plugin selection order or a workspace slug.

type UnixSocketDirectory

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

UnixSocketDirectory belongs to one captured supervisor lifetime. Close must only be called after that supervisor has disposed all owned descendant groups. Retain the handle on failure so the same owner can retry cleanup.

func CreateUnixSocketDirectory

func CreateUnixSocketDirectory(runtimeRoot string, owner devcontract.ProcessIdentity) (*UnixSocketDirectory, error)

CreateUnixSocketDirectory publishes an intent before creating its exclusive namespace. A crash cannot leave an external path without a durable reference; incomplete intents are conflicts, never permission to adopt a directory.

func (*UnixSocketDirectory) Close

func (d *UnixSocketDirectory) Close() error

Jump to

Keyboard shortcuts

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