jobs

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: MIT Imports: 17 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 jobs runs the web UI's long operations -- syncs, recipes, audits -- in the background, records what each one did as a stream of typed events, and keeps a bounded history on disk. It knows nothing about HTTP.

Index

Constants

View Source
const (
	EventLog       = "log"
	EventStage     = "stage"
	EventPackStart = "pack-start"
	EventPackDone  = "pack-done"
	EventDone      = "done"
	// EventResult carries a kind-specific payload in Data -- the audit's
	// resolutions -- so it is kept with the run and survives a restart.
	EventResult = "result"
)

Event types.

View Source
const (
	StageStarted  = "started"
	StageFinished = "finished"
	StageFailed   = "failed"
)

Stage states, on EventStage.

View Source
const DefaultCapacity = 10000

DefaultCapacity is how many events a job keeps in memory: enough for an aggregator pack's dozens of sets, a ceiling against a runaway logger.

View Source
const DefaultKeep = 50

DefaultKeep is how many finished jobs the history keeps. It is a ceiling: a test pins it, so raising it is a decision rather than drift.

Variables

View Source
var ErrNotFound = errors.New("no such job")

ErrNotFound is returned for a job ID this process and the history lack.

Functions

func Handler

func Handler(j *Job, level slog.Level) slog.Handler

Handler returns a slog.Handler that records every line into the job, at level and above. Passed to a run as its logger, it is what keeps two concurrent runs' logs apart.

func Observer

func Observer(j *Job) pipeline.Observer

Observer returns a pipeline.Observer that records stage events into j.

func ValidID

func ValidID(id string) bool

ValidID reports whether id has the shape newID produces, so a request cannot name a path outside the store.

Types

type ErrBusy

type ErrBusy struct {
	Pack  string
	JobID string
}

ErrBusy is returned when a pack the job needs is already being worked on.

func (*ErrBusy) Error

func (e *ErrBusy) Error() string

type Event

type Event struct {
	ID   int64     `json:"id"`
	Type string    `json:"type"`
	Time time.Time `json:"time"`

	// log
	Level string            `json:"level,omitempty"`
	Msg   string            `json:"msg,omitempty"`
	Attrs map[string]string `json:"attrs,omitempty"`

	// stage
	Pipeline string         `json:"pipeline,omitempty"`
	Stage    string         `json:"stage,omitempty"`
	State    string         `json:"state,omitempty"`
	Metrics  map[string]any `json:"metrics,omitempty"`

	// pack-start, pack-done, done
	Pack   string `json:"pack,omitempty"`
	Status string `json:"status,omitempty"`
	Err    string `json:"error,omitempty"`

	// result
	Data json.RawMessage `json:"data,omitempty"`
}

Event is one thing that happened in a job. ID increases by one per event within a job, so a reconnecting EventSource resumes exactly where it left off with Last-Event-ID.

type Info

type Info struct {
	ID      string    `json:"id"`
	Kind    Kind      `json:"kind"`
	Packs   []string  `json:"packs"`
	DryRun  bool      `json:"dry_run"`
	Label   string    `json:"label,omitempty"`
	Started time.Time `json:"started"`
	Ended   time.Time `json:"ended,omitzero"`
	Status  Status    `json:"status"`
	Err     string    `json:"error,omitempty"`
}

Info is a job's metadata, as listed and persisted.

func (Info) Duration

func (i Info) Duration(now time.Time) time.Duration

Duration is how long the job ran, or has been running.

type Job

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

Job is one background operation.

func (*Job) Done

func (j *Job) Done() <-chan struct{}

Done is closed when the job has finished and its done event is recorded.

func (*Job) Events

func (j *Job) Events() []Event

Events returns every retained event.

func (*Job) Info

func (j *Job) Info() Info

Info returns a snapshot of the job's metadata.

func (*Job) Logf

func (j *Job) Logf(level, format string, a ...any)

Logf records a log line from the job's own orchestration.

func (*Job) PackDone

func (j *Job) PackDone(pack, status, errText, detail string)

PackDone records how one pack ended.

func (*Job) PackStarted

func (j *Job) PackStarted(pack, detail string)

PackStarted and PackDone record a pack's boundaries.

func (*Job) Record

func (j *Job) Record(v any) error

Record stores a kind-specific payload as a result event.

func (*Job) Result

func (j *Job) Result() any

Result returns the payload SetResult stored.

func (*Job) SetResult

func (j *Job) SetResult(v any)

SetResult stores the kind-specific payload.

func (*Job) Since

func (j *Job) Since(id int64) ([]Event, bool, <-chan struct{})

Since returns the events after id, whether the job has finished, and a channel closed on the next event or on finish.

type Kind

type Kind string

Kind is what a job does.

const (
	KindSync    Kind = "sync"
	KindSyncAll Kind = "sync-all"
	KindRecipe  Kind = "recipe"
	KindAudit   Kind = "audit"
)

The kinds of job the web UI runs.

type Registry

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

Registry starts jobs, enforces one job per pack, and keeps them findable.

func NewRegistry

func NewRegistry(base context.Context, store *Store, now func() time.Time) *Registry

NewRegistry returns a Registry. store may be nil (no history on disk); base is cancelled to stop every job, as on shutdown.

func (*Registry) Cancel

func (r *Registry) Cancel(id string) bool

Cancel asks a running job to stop. It reports whether the job exists.

func (*Registry) Get

func (r *Registry) Get(id string) *Job

Get returns a job started by this process.

func (*Registry) List

func (r *Registry) List() []Info

List returns this process's jobs and the persisted history, newest first, each ID once.

func (*Registry) Running

func (r *Registry) Running(pack string) string

Running returns the job holding a pack's lock, if any.

func (*Registry) SetCapacity

func (r *Registry) SetCapacity(n int)

SetCapacity sets the per-job event capacity; for tests.

func (*Registry) Start

func (r *Registry) Start(spec Spec, fn RunFunc) (*Job, error)

Start runs fn in the background as a new job, after taking every pack's lock. A pack already locked fails the whole start with *ErrBusy, and no lock is taken: two runs racing on one pack repository's `git checkout -B` is exactly what the lock exists to prevent.

func (*Registry) Wait

func (r *Registry) Wait()

Wait blocks until every job has finished; for shutdown and tests.

type RunFunc

type RunFunc func(ctx context.Context, j *Job) (Status, error)

RunFunc does the work. It must honour ctx; the status it returns is the job's outcome unless ctx was cancelled, which always reads as cancelled.

type Spec

type Spec struct {
	Kind   Kind
	Packs  []string // the packs it touches, locked for its duration
	DryRun bool
	// Label is a one-line description for the history, e.g. "recipe 3.49.0".
	Label string
}

Spec describes a job to start.

type Status

type Status string

Status is how a job stands or ended.

const (
	StatusRunning   Status = "running"
	StatusSucceeded Status = "succeeded"
	StatusFailed    Status = "failed"
	StatusCancelled Status = "cancelled"
)

Job statuses.

type Store

type Store struct {
	Dir  string
	Keep int
}

Store persists finished jobs as JSON Lines, one file per job: the first line is the job's Info, every later line one Event. It only ever touches files in its own directory whose names it could have written.

func (*Store) List

func (s *Store) List() ([]Info, error)

List reads every stored job's Info, newest first.

func (*Store) Load

func (s *Store) Load(id string) (Info, []Event, error)

Load reads one stored job and its events.

func (*Store) Open

func (s *Store) Open(id string) (io.ReadCloser, error)

Open returns the raw JSON Lines file, for download.

func (*Store) Save

func (s *Store) Save(info Info, events []Event) error

Save writes a finished job and prunes the history to Keep.

Jump to

Keyboard shortcuts

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