Documentation
¶
Overview ¶
Package state owns Rotari's filesystem-backed project state.
It reads and writes model values as durable JSON files, validates path elements, lists run and attempt directories, and manages locks and other persistence details. It should not decide run orchestration, retry policy, dependency scheduling, or executor behavior.
Index ¶
- Constants
- Variables
- func AcquireRunLock(lockPath string, info model.LockInfo) error
- func AcquireStateLock(lockPath string) (func(), error)
- func AcquireStateReadLock(lockPath string) (func(), error)
- func AppendLoadSample(path string, sample model.LoadSample) error
- func AppendRunNote(runDir string, note model.RunNote) error
- func AttemptJobDir(runDir string, job model.JobSpec) (string, error)
- func AttemptSource(runDir, attemptDir string) (model.SourceRevision, bool)
- func CheckRunVersions(runDir string) error
- func ContextPath(runDir string) string
- func DefaultMeta() model.Meta
- func DirectoryMode() os.FileMode
- func FileMode() os.FileMode
- func FinalizeRun(meta model.Meta, runID string, exitCode int, now time.Time) (model.Meta, error)
- func IsValidPathElement(value string) bool
- func LatestAttempt(runDir, jobID string) (attemptID, jobDir string, err error)
- func LatestAttemptDirs(runDir string) ([]string, error)
- func LatestAttemptID(runDir, jobID string) (string, error)
- func LatestAttemptJobDir(runDir, jobID string) (string, error)
- func ListAttemptIDs(runDir, jobID string) []string
- func LoadContext(store Store, runDir string) (model.RunContext, error)
- func LoadLocalJobResult(jobDir string, job model.JobSpec) (model.JobResult, bool)
- func LoadLock(path string) (model.LockInfo, error)
- func LoadMeta(path string) (model.Meta, error)
- func LoadQueue(path string) (model.Queue, error)
- func LoadRunClientStatus(store Store, runDir string) (model.RunClientStatus, error)
- func LoadRunNotes(runDir string) ([]model.RunNote, error)
- func LoadRunOrigin(runDir, jobID string) *model.JobOrigin
- func LoadRunSources(runDir string) (model.RunSources, bool, error)
- func LoadRunStartedBy(store Store, runDir string) (*model.StartedBy, error)
- func LoadRunSummary(path string) (model.RunSummary, error)
- func LoadRunSummaryHead(path string) (model.RunSummary, error)
- func MakeAttemptID(runID, jobID string, number int) string
- func OtherPIDNamespace(lock model.LockInfo) bool
- func PIDNamespace() string
- func ProcessAlive(pid int) bool
- func ProcessStart(pid int) string
- func ProjectNameGiven(cliProjectName string) bool
- func ReadAttemptExecutor(attemptDir string) string
- func ReadAttemptTimestamp(jobDir, name string) string
- func ReadEach(count int, read func(index int))
- func ReadJobName(jobDir string) string
- func ReadJobTimestamp(runDir, jobID, name string) string
- func ReadLoadSamples(path string) []model.LoadSample
- func ReadQueueFile(path string) (model.Queue, error)
- func RequireRunStateFile(runDir, name, runID string) error
- func ResolveAttemptTimestamp(jobDir, name string) string
- func ResolveBaseDir(cliBaseDir string) (string, bool, error)
- func ResolveBaseDirDefault() (string, error)
- func ResolveMasterDir(cliMasterDir string) (string, error)
- func ResolveProjectName(baseDir, cliProjectName string) (string, error)
- func SafeJoin(basePath, element string) (string, error)
- func SaveContext(store Store, runDir string, context model.RunContext) error
- func SaveRunSources(runDir string, sources model.RunSources) error
- func ScriptMode() os.FileMode
- func SpecificAttemptJobDir(runDir, jobID, attemptID string) (string, error)
- func TryAcquireStateReadLock(lockPath string) (release func(), ok bool, err error)
- func ValidateRunDirectory(runsDir, runID string, requireCommands bool) (string, error)
- func ValidateStatePath(path string) error
- func ValidatedStateFile(basePath, fileName string) (string, error)
- func WriteJSON(path string, value any) error
- func WriteRunClientStatus(store Store, runDir string, status model.RunClientStatus) error
- type AttemptIDPayload
- type LockState
- type ProgressCursor
- type ProgressJournal
- type ProjectPaths
- type RunSnapshot
- type Store
Constants ¶
const ( StdoutFileName = "stdout" StderrFileName = "stderr" // SchedulerEventsFileName is a scheduler job's log of query outcomes. SchedulerEventsFileName = "scheduler_events.jsonl" )
const ArtifactsFileName = "artifacts.json"
ArtifactsFileName holds the artifact candidates discovered for an attempt when it started. It is best-effort metadata: an attempt without one has no discovery information, not no associated files.
const (
BaseDirEnv = "ROTARI_BASEDIR"
)
const CarriedResultsFileName = "carried.json"
CarriedResultsFileName is the run file in which a run records, before it dispatches any job, the results it carries forward from earlier runs instead of executing. It holds a model.RunSummary with only RunID and Results, and is read through LoadRunSummary until the run writes summary.json; see jobstatus.RecordedResults.
const DefaultProjectName = "default"
DefaultProjectName is the project used when none is given and the base directory does not have exactly one.
const FinalResultFileName = "final_result.json"
FinalResultFileName marks an attempt whose job will not be retried.
const LoadSamplesFileName = "load_samples.jsonl"
LoadSamplesFileName is the run-directory file that holds a run's load samples.
const ProgressFileName = "progress.jsonl"
const ProjectNameEnv = "ROTARI_PROJECT_NAME"
const ReadConcurrency = 16
ReadConcurrency bounds how many independent reads ReadEach runs at once. On a shared file system each open, stat, and directory listing is a round trip, so reading independent files concurrently overlaps their latency.
const RunClientStatusFileName = "client_status.json"
const RunNotesFileName = "notes.jsonl"
RunNotesFileName is the run file holding a run's notes, one JSON model.RunNote per line, in the order they were added. It is the one run file that changes after a run finishes, and only by appending.
const RunSourcesFileName = "sources.json"
RunSourcesFileName is the run file in which a run records, before it dispatches any job, the version-control revisions its executed jobs run from. A run started before rotari recorded sources has none.
const StaleLockRemovalFileName = "stale_lock_removed.json"
StaleLockRemovalFileName is the record, in a run's directory, of the reader that removed the run's stale lock.
Variables ¶
var ErrInvalidJSON = errors.New("invalid JSON")
var ErrNewerStateVersion = errors.New("state file is from a newer rotari")
ErrNewerStateVersion reports a state file written by a newer rotari whose format this binary cannot read safely.
Functions ¶
func AcquireRunLock ¶
AcquireRunLock publishes info as the run lock at lockPath. It fails while another run holds an active or remote lock, and never replaces an existing lock file. The caller holds the state lock exclusively and has checked the project, so a stale lock left at lockPath is removed first.
func AcquireStateLock ¶
AcquireStateLock takes the exclusive project state lock at lockPath and returns its release function.
func AcquireStateReadLock ¶
AcquireStateReadLock takes the shared project state lock at lockPath. A missing lock file needs no lock.
func AppendLoadSample ¶
func AppendLoadSample(path string, sample model.LoadSample) error
func AppendRunNote ¶
AppendRunNote adds a note to the run in runDir. Each note is written with one append, so notes added at the same time do not interleave.
func AttemptSource ¶
func AttemptSource(runDir, attemptDir string) (model.SourceRevision, bool)
AttemptSource returns the recorded revision of the repository the attempt in attemptDir ran from: its working directory, from its command.json, matched against its run's sources. It returns false when either is not recorded.
func CheckRunVersions ¶
CheckRunVersions returns ErrNewerStateVersion when the run's commands.json or summary.json was written by a newer rotari, and nil otherwise, leaving a missing or unreadable file to the caller. Readers that treat those files as optional call it first, so a newer file is refused instead of being read as absent.
func ContextPath ¶
func DefaultMeta ¶
func DirectoryMode ¶
func FinalizeRun ¶
FinalizeRun returns meta marked finished with runID's exit code.
func IsValidPathElement ¶
func LatestAttempt ¶
LatestAttempt lists jobID's attempts once and returns the latest attempt's ID, "" when there is none, and the directory holding the job's state: that attempt's directory, or the job directory without one.
func LatestAttemptDirs ¶
LatestAttemptDirs returns, sorted, the latest attempt directory of each job of runDir that has a command snapshot: JOB/attempts/ATTEMPT, or JOB itself in a run written before attempts had directories of their own.
func LatestAttemptID ¶
func LatestAttemptJobDir ¶
func ListAttemptIDs ¶
ListAttemptIDs lists a job's attempt IDs in the run, oldest first.
func LoadContext ¶
func LoadContext(store Store, runDir string) (model.RunContext, error)
func LoadLocalJobResult ¶
func LoadQueue ¶
LoadQueue reads a queue.json or commands.json file, treating a missing file as an empty queue.
func LoadRunClientStatus ¶
func LoadRunClientStatus(store Store, runDir string) (model.RunClientStatus, error)
LoadRunClientStatus reads the initiating client's persisted status for a run.
func LoadRunNotes ¶
LoadRunNotes reads a run's notes in the order they were added; a run without notes has none.
func LoadRunOrigin ¶
LoadRunOrigin returns jobID's origin from the run's commands.json snapshot, or nil when the job has none or the snapshot cannot be read; see model.Queue.OriginOf.
func LoadRunSources ¶
func LoadRunSources(runDir string) (model.RunSources, bool, error)
LoadRunSources reads a run's sources, and false when the run recorded none.
func LoadRunStartedBy ¶
LoadRunStartedBy reads how the run in runDir was started, nil when its context is missing or predates the record.
func LoadRunSummary ¶
func LoadRunSummary(path string) (model.RunSummary, error)
func LoadRunSummaryHead ¶
func LoadRunSummaryHead(path string) (model.RunSummary, error)
LoadRunSummaryHead is LoadRunSummary without the per-job results, which it leaves nil: a listing of many runs needs only their times, names, status, and exit code, and a run of many jobs has a large summary.
func MakeAttemptID ¶
func OtherPIDNamespace ¶
OtherPIDNamespace reports whether lock records a PID namespace other than this process's, where its PID names another process or none.
func PIDNamespace ¶
func PIDNamespace() string
PIDNamespace names this process's PID namespace, within which alone a PID identifies a process. It is empty when the platform does not expose it.
func ProcessAlive ¶
func ProcessStart ¶
ProcessStart is Linux's per-process start-time identity from field 22 of /proc/PID/stat, which tells a process from a later one reusing its PID. An empty value means the platform cannot verify PID reuse.
func ProjectNameGiven ¶
ProjectNameGiven reports whether a project was chosen explicitly, by cliProjectName or ROTARI_PROJECT_NAME, rather than inferred from the base directory.
func ReadAttemptExecutor ¶
ReadAttemptExecutor returns the executor an attempt ran on, as its command.json records it once submitted, or "" for an attempt that has none. It reflects a run-level --executor and the queue's default, which the job's definition alone does not.
func ReadAttemptTimestamp ¶
func ReadEach ¶
ReadEach calls read for every index in [0, count) from up to ReadConcurrency goroutines, and returns once all calls have returned. read must be safe to call concurrently; callers keep results in a slice indexed like their input, so output order does not depend on scheduling.
func ReadJobName ¶
ReadJobName returns the job name recorded in jobDir, or "" when there is none.
func ReadJobTimestamp ¶
func ReadLoadSamples ¶
func ReadLoadSamples(path string) []model.LoadSample
func ReadQueueFile ¶
ReadQueueFile reads a queue.json or commands.json file and returns an os.ErrNotExist error when it is missing.
func RequireRunStateFile ¶
func ResolveAttemptTimestamp ¶
ResolveAttemptTimestamp reads an attempt's submitted_at or finished_at, falling back to the times job.json and status.json record.
func ResolveBaseDirDefault ¶
ResolveBaseDirDefault resolves the local/XDG/home state directory without consulting ROTARI_BASEDIR. Aggregate views use it when only CLI scope selectors may narrow their target.
func ResolveMasterDir ¶
ResolveMasterDir resolves the master directory that holds the run and server registries: cliMasterDir, then ROTARI_MASTERDIR, then $XDG_STATE_HOME/rotari/master, then ~/.local/state/rotari/master.
func ResolveProjectName ¶
func SaveContext ¶
func SaveContext(store Store, runDir string, context model.RunContext) error
func SaveRunSources ¶
func SaveRunSources(runDir string, sources model.RunSources) error
SaveRunSources writes a run's sources.
func ScriptMode ¶
func SpecificAttemptJobDir ¶
func TryAcquireStateReadLock ¶
TryAcquireStateReadLock takes the shared project state lock at lockPath without waiting, creating the lock file as AcquireStateLock does. ok is false while another holder, possibly in this process, has it exclusively.
func ValidateRunDirectory ¶
func ValidateStatePath ¶
func ValidatedStateFile ¶
func WriteRunClientStatus ¶
func WriteRunClientStatus(store Store, runDir string, status model.RunClientStatus) error
WriteRunClientStatus persists the initiating client's last known status.
Types ¶
type AttemptIDPayload ¶
func DecodeAttemptID ¶
func DecodeAttemptID(attemptID string) (AttemptIDPayload, error)
func DecodeAttemptIDForRun ¶
func DecodeAttemptIDForRun(attemptID, runID string) (AttemptIDPayload, error)
DecodeAttemptIDForRun decodes an attempt belonging to runID, including imported runs whose IDs do not have the usual timestamp format.
type LockState ¶
type LockState string
func InspectLock ¶
InspectLock classifies the run lock at path without changing it. A lock whose coordinator PID cannot be checked here, because it was written on another host or in another PID namespace such as a sandbox or container, is remote. A stale lock is removed by internal/project, which checks the project first.
type ProgressCursor ¶
type ProgressCursor struct {
// contains filtered or unexported fields
}
ProgressCursor is an incremental reader for one run's append-only journal. Its zero value starts at the beginning. Use a separate cursor per run and consumer; it is not safe for concurrent reads.
func (*ProgressCursor) Read ¶
func (cursor *ProgressCursor) Read(runDir string) ([]model.ProgressEvent, error)
Read returns newly completed lines. An absent journal (including old runs) is an empty successful read. A trailing line without a newline is left at the cursor for the next read, even if it already contains valid JSON. A malformed complete line is consumed and returns ErrInvalidJSON along with any preceding events; a later Read can continue after it.
func (*ProgressCursor) SkipExisting ¶
func (cursor *ProgressCursor) SkipExisting(runDir string) (model.ProgressEvent, bool, error)
SkipExisting advances the cursor past complete events already in the journal and returns their latest progress-count snapshot, if one exists. If the final line is still being appended, the cursor stays at its start so Read can consume it once the line is complete.
type ProgressJournal ¶
type ProgressJournal struct {
// contains filtered or unexported fields
}
ProgressJournal appends progress events to one existing run directory. Share one instance between the run's writers; Append serializes whole lines. It holds no open file and does not create directories or rewrite history.
func NewProgressJournal ¶
func NewProgressJournal(runDir string) (*ProgressJournal, error)
func (*ProgressJournal) Append ¶
func (journal *ProgressJournal) Append(event model.ProgressEvent) error
Append writes one newline-terminated JSON event using the state file mode. Non-progress events are rejected. Errors are returned to the caller, which decides whether journaling is best-effort; Append does not fsync each event.
type ProjectPaths ¶
type ProjectPaths struct {
BaseDir string
BaseDirExplicit bool
ProjectName string
ProjectDir string
QueueFile string
MetaFile string
StateLockFile string
LockFile string
RunsDir string
}
func ResolveProjectPaths ¶
func ResolveProjectPaths(cliBaseDir, projectName string) (ProjectPaths, error)
type RunSnapshot ¶
type RunSnapshot struct {
Commands model.Queue
CommandsErr error
Summary model.RunSummary
SummaryErr error
Carried model.RunSummary
CarriedErr error
}
RunSnapshot is what a run directory records about the whole run: commands.json, summary.json, and carried.json, each read once. An error field is os.ErrNotExist for a missing file.
func LoadRunSnapshot ¶
func LoadRunSnapshot(runDir string) (RunSnapshot, error)
LoadRunSnapshot reads runDir's run files. It fails, with ErrNewerStateVersion, only when one was written by a newer rotari; any other error is kept in the snapshot for the caller.
func (RunSnapshot) Queue ¶
func (snapshot RunSnapshot) Queue() (model.Queue, error)
Queue is the run's command snapshot as LoadQueue reads it: empty when the file is missing.
func (RunSnapshot) RecordedSummary ¶
func (snapshot RunSnapshot) RecordedSummary() *model.RunSummary
RecordedSummary is the run's summary, or nil when it has no readable one.