jobs

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2026 License: MIT 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 jobs keeps batch recognitions as resumable jobs and runs them.

Every batch (a folder, glob, list, or several inputs) becomes a job with a short ID. Each item is written to DataDir()/jobs.db as soon as it finishes, so an interruption (Ctrl-C, a crash, a dropped SSH session) never loses or re-bills finished work: `audd jobs resume <id>` picks up where the job stopped.

Index

Constants

View Source
const (
	StatusPending     = "pending"     // created, not started yet
	StatusRunning     = "running"     // a process is working on it now
	StatusInterrupted = "interrupted" // stopped by Ctrl-C or a crash; resumable
	StatusStopped     = "stopped"     // stopped by a limit or an account error; resumable
	StatusDone        = "done"        // every item finished
	StatusPartial     = "partial"     // every item ran, some failed
)

Job states.

View Source
const (
	StatePending = "pending"
	StateDone    = "done" // recognized, or no match (Result is null or [])
	StateFailed  = "failed"
)

Item states.

View Source
const BudgetLimitedHint = "To recognize them in full, run them again with a larger --max-requests (results cut short are not reused from the cache)."

BudgetLimitedHint says how to recognize budget-limited files in full.

View Source
const ErrCodeInFlight = "interrupted_in_flight"

ErrCodeInFlight is the error code of an item whose request was sent but whose process stopped before the response was saved.

View Source
const ErrCodeTakenOver = "job_taken_over"

ErrCodeTakenOver is the error code when another process took a job over.

View Source
const ExitInterrupted = 130

ExitInterrupted is the exit code after Ctrl-C (128 + SIGINT).

Variables

View Source
var (
	// Recognize identifies one input and returns the API's result: an
	// object or null (standard endpoint), or an array of matches
	// (enterprise). Errors may be audd-go errors or *output.Error; a hook
	// that maps SDK errors should return both (errors.Join(mapped, sdkErr))
	// so classify can still tell a connection that never opened, which is
	// safe to retry, from one that dropped after the upload.
	Recognize = RecognizeSDK

	// CacheGet returns a cached result for the input and params. It must
	// use the same key as single recognitions (the request's cache params,
	// with their defaults such as accurate_offsets=true), or batch runs
	// miss results that are already cached.
	CacheGet func(a *app.App, in media.Input, p Params) (json.RawMessage, bool)
	// CachePut stores a fresh result under the same key as CacheGet.
	CachePut func(a *app.App, in media.Input, p Params, result json.RawMessage)

	// Durations gives a local file's length for enterprise estimates
	// (ffprobe by default).
	Durations = defaultDurations
)

Hooks the API layer replaces, so a batch uses the same results cache, token self-healing and error wording as a single recognition. The defaults call the SDK directly and use no cache.

View Source
var EnterpriseFields = []string{"start_offset", "end_offset", "start_seconds", "end_seconds"}

EnterpriseFields are the fields an enterprise match has besides MatchFields.

View Source
var MatchFields = []string{"artist", "title", "album", "release_date", "label", "timecode", "song_link", "isrc", "upc", "score"}

MatchFields are the fields of a recognition result (and of each enterprise match). A result lacks some of them at times (no ISRC on a plan without it, say); --fields accepts them all and prints a missing one as null.

View Source
var ProviderBlocks = []string{"apple_music", "spotify", "deezer", "musicbrainz"}

ProviderBlocks are the optional metadata blocks --return adds.

Functions

func CheckFields

func CheckFields(out *output.Printer) error

CheckFields checks --fields for the result lines of a batch before anything is sent.

func Describe

func Describe(it Item) string

Describe is a short human summary of an item's outcome.

func EnterpriseJSON

func EnterpriseJSON(matches []audd.EnterpriseMatch) json.RawMessage

EnterpriseJSON renders enterprise matches as the API sent them, plus start_seconds and end_seconds (the match's place in the whole file).

func ErrorFor

func ErrorFor(err error) *output.Error

ErrorFor maps a recognition error to the CLI's error (exit code, stable code, and hint).

func HumanLine

func HumanLine(w io.Writer, st output.Styles, it Item)

HumanLine writes one item as a line for people.

func ItemStatus

func ItemStatus(it Item) string

ItemStatus is matched, no_match, failed, or pending.

func PrintDryRun

func PrintDryRun(out *output.Printer, input, jobID, endpoint string, plan any, human func(w io.Writer)) error

PrintDryRun prints a DryRunDoc (input and jobID may be ""), with human for people.

func RecognizeSDK

func RecognizeSDK(ctx context.Context, a *app.App, in media.Input, p Params) (json.RawMessage, error)

RecognizeSDK is the default Recognize: one call through audd-go.

func RequestsUsed

func RequestsUsed(spent, reserved, unknown int) string

RequestsUsed describes the requests a run or job used, for people: "12 requests used", "up to 500 requests used (file lengths were not known)", or "12 requests used, plus up to 500 for files of unknown length". reserved is the limit sent with calls for files of unknown length (the most they can have used); unknown counts such files sent without a limit.

func ResultFields

func ResultFields(prefix string) []string

ResultFields are the --fields paths under prefix ("result" for a standard result, "" for a match row) that recognition output can have: the match fields, the enterprise fields, and anything inside a provider block.

func RunBatch

func RunBatch(ctx context.Context, a *app.App, opts app.BatchOptions) (app.BatchSummary, error)

RunBatch recognizes many inputs as a resumable job (spec §5): it enforces --max-files, shows the plan and asks to confirm, offers to resume an unfinished identical job, runs a worker pool, saves each item as it finishes, and streams results. Ctrl-C lets requests in progress finish, saves them, and exits 130 with the resume command.

Types

type CSVRow

type CSVRow struct {
	JobID        string `json:"job_id"`
	Index        int    `json:"index"`
	Input        string `json:"input"`
	Status       string `json:"status"`
	Cached       bool   `json:"cached"`
	Artist       string `json:"artist"`
	Title        string `json:"title"`
	Album        string `json:"album"`
	ReleaseDate  string `json:"release_date"`
	Label        string `json:"label"`
	ISRC         string `json:"isrc"`
	UPC          string `json:"upc"`
	SongLink     string `json:"song_link"`
	Timecode     string `json:"timecode"`
	Score        string `json:"score"`
	StartSeconds string `json:"start_seconds"`
	EndSeconds   string `json:"end_seconds"`
	Error        string `json:"error"`
}

CSVRow is one CSV row: one per standard result, one per enterprise match.

func Rows

func Rows(jobID string, it Item) []CSVRow

Rows converts an item to CSV rows.

func SingleRows

func SingleRows(name string, cached bool, raw json.RawMessage) []CSVRow

SingleRows is the CSV rows of one input recognized on its own: the same columns as a batch, with no job ID.

type DryRunDoc

type DryRunDoc struct {
	DryRun   bool    `json:"dry_run"`
	Input    *string `json:"input"`
	JobID    *string `json:"job_id"`
	Endpoint string  `json:"endpoint"`
	Plan     any     `json:"plan"`
}

DryRunDoc is recognize --dry-run output, the same for one input, a batch, and jobs resume:

{"dry_run":true,"input":"song.mp3"|null,"job_id":"k3x9"|null,
 "endpoint":"standard"|"enterprise","plan":{"files","cached_files",
 "requests","approximate","cost_usd",...}}

input names the file or URL of a single-input run and is null for batches; job_id is the job a batch would resume, null for a single input and for a new batch. Piped, both print this document. With --format jsonl it is one "type":"event" line with "event":"dry_run", so it is never counted as a file's result.

type Item

type Item struct {
	Index  int             `json:"index"`
	Input  media.Input     `json:"input"`
	State  string          `json:"state"`
	Result json.RawMessage `json:"result,omitempty"`
	Err    string          `json:"error,omitempty"`
	// ErrCode is the stable error code (see output.Error); APICode the AudD
	// API error code, when there was one.
	ErrCode string `json:"error_code,omitempty"`
	APICode int    `json:"api_code,omitempty"`
	// SafeRetry marks a failure where nothing reached the API (for example
	// a connection that never opened), so resuming retries it automatically.
	// Other failures may have used a request and are retried only with
	// --retry-failed.
	SafeRetry bool `json:"safe_retry,omitempty"`
	Cached    bool `json:"cached,omitempty"`
	// Requests is the number of requests the item used, when it is known.
	// For an enterprise file of unknown length it is 0, and
	// RequestsReserved is the limit sent with the call (the most it can
	// have used), or RequestsUnknown is set when no limit was sent.
	Requests         int  `json:"requests,omitempty"`
	RequestsReserved int  `json:"requests_reserved,omitempty"`
	RequestsUnknown  bool `json:"requests_unknown,omitempty"`
	// BudgetLimit is set when --max-requests lowered the enterprise limit
	// sent for a file of unknown length: the result covers at most the
	// first BudgetLimit 12-second chunks, so it may be partial.
	BudgetLimit int `json:"budget_limit,omitempty"`
}

Item is one input of a job.

func Results

func Results(s *Store, id string) ([]Item, error)

Results returns a job's items with their results (the explorer's jobs tab reads them); it is Items as a package function.

type Job

type Job struct {
	ID      string            `json:"id"`
	Command []string          `json:"-"` // "recognize" + every input; can be long
	Inputs  string            `json:"inputs"`
	Params  map[string]string `json:"params"`
	Created time.Time         `json:"created"`
	Updated time.Time         `json:"updated"`
	Total   int               `json:"total"`
	Done    int               `json:"done"` // finished items, matched or not
	NoMatch int               `json:"no_match"`
	Failed  int               `json:"failed"`
	Pending int               `json:"pending"`
	// Remaining is what a plain resume runs: pending items plus failures
	// that are safe to retry.
	Remaining int `json:"remaining"`
	Cached    int `json:"cached"`
	// Requests counts requests whose number is known: standard calls, and
	// enterprise calls for files of known length. RequestsReserved is the
	// most that calls for files of unknown length may have used (the limit
	// sent with them), and RequestsUnknownFiles counts such files sent
	// without any limit.
	Requests             int `json:"requests_spent"`
	RequestsReserved     int `json:"requests_reserved"`
	RequestsUnknownFiles int `json:"requests_unknown_files"`
	// BudgetLimitedFiles counts enterprise files of unknown length whose
	// limit --max-requests lowered; their results may cover only part of
	// the file (see Item.BudgetLimit).
	BudgetLimitedFiles int    `json:"budget_limited_files"`
	Status             string `json:"status"`
}

Job is one batch run.

func List

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

List returns every job, newest first.

type Lease

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

Lease is a claim on a running job. A process that stops sending heartbeats for staleAfter (suspended, asleep) can lose its lease to another process; every write through the lease then fails with job_taken_over instead of touching the job.

func (*Lease) Heartbeat

func (l *Lease) Heartbeat() error

Heartbeat records that this process is alive and still holds the job. It returns job_taken_over when another process holds it now.

func (*Lease) Release

func (l *Lease) Release(status string)

Release stores the final status and gives the job up, unless another process has taken it over.

func (*Lease) SaveItem

func (l *Lease) SaveItem(it Item) error

SaveItem writes an item's state and result while this process holds the job. It returns job_taken_over, and writes nothing, when it does not.

type LineError

type LineError struct {
	Code      string `json:"code"`
	APICode   int    `json:"api_code"`
	Message   string `json:"message"`
	Retryable bool   `json:"retryable"`
}

LineError is a failed item's error.

type Params

type Params struct {
	Enterprise bool
	Return     string            // extra metadata (standard endpoint only)
	Limit      *int              // enterprise chunks per file; nil = no limit
	Options    map[string]string // enterprise passthrough: skip, every, skip_first_seconds, use_timecode, accurate_offsets
}

Params are the recognition settings of a job. They are stored with the job, so `audd jobs resume <id>` needs nothing but the ID.

func ParamsFromMap

func ParamsFromMap(m map[string]string) Params

ParamsFromMap is the inverse of Map.

func (Params) Endpoint

func (p Params) Endpoint() string

Endpoint is "standard" or "enterprise".

func (Params) Map

func (p Params) Map() map[string]string

Map is the stored form: endpoint, return, limit ("none" or a number), and "opt.<name>" for each passthrough option.

type Plan

type Plan struct {
	Endpoint           string  `json:"-"`
	Files              int     `json:"files"`
	CachedFiles        int     `json:"cached_files"`
	Requests           int     `json:"requests"`
	Approximate        bool    `json:"approximate"`
	CostUSD            float64 `json:"cost_usd"`
	RemainingAllowance *int    `json:"remaining_allowance,omitempty"`
	UnknownLengthFiles int     `json:"unknown_length_files,omitempty"`
	// TooLargeFiles counts local files over the standard endpoint's 10 MB
	// limit. They are not sent and not counted in Requests.
	TooLargeFiles int `json:"too_large_files,omitempty"`
	// MaxRequests is the --max-requests ceiling when it stops the run
	// before the plan is done (the run spends at most this many).
	MaxRequests     int    `json:"max_requests,omitempty"`
	MaxRequestsName string `json:"-"`
}

Plan is what a batch run is expected to spend. Endpoint is printed beside the plan, not inside it, the same as for a single input's dry run. UnknownLengthFiles counts enterprise inputs of unknown length (URLs) sent without --limit: nothing caps them, so the request count and cost are unknown (null in JSON, with "unbounded": true).

func (Plan) Capped

func (p Plan) Capped() bool

Capped reports whether --max-requests stops the run before the plan is done.

func (Plan) Line

func (p Plan) Line() string

Line is the plan as one sentence, worded the same as a single input's plan (see safety.PlanText).

func (Plan) MarshalJSON

func (p Plan) MarshalJSON() ([]byte, error)

MarshalJSON writes requests and cost_usd as null, with "unbounded": true, when the plan is unbounded.

func (Plan) Unbounded

func (p Plan) Unbounded() bool

Unbounded reports whether nothing caps what the plan can use.

type RecentResult

type RecentResult struct {
	Source string
	At     time.Time // when the job last changed
	Result json.RawMessage
}

RecentResult is a finished job item, for the explorer's Recent tab.

type ResultLine

type ResultLine struct {
	JobID  string          `json:"job_id"`
	Index  int             `json:"index"`
	Input  string          `json:"input"`
	Status string          `json:"status"` // matched, no_match, failed, pending
	Cached bool            `json:"cached"`
	Result json.RawMessage `json:"result"`
	// BudgetLimit is the enterprise limit --max-requests lowered for this
	// file of unknown length: the result covers at most that many
	// 12-second chunks from the start, so it may be partial.
	BudgetLimit int        `json:"budget_limit,omitempty"`
	Error       *LineError `json:"error,omitempty"`
}

ResultLine is one item in JSON/JSONL output (type "result").

func Line

func Line(jobID string, it Item) ResultLine

Line converts an item to its JSON output form.

type Store

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

Store is the jobs database.

func Open

func Open() (*Store, error)

Open opens DataDir()/jobs.db.

func (*Store) Claim

func (s *Store) Claim(id string) (release func(status string), err error)

Claim marks the job as running in this process. It fails with job_running while another live process holds it. release stores the final status and gives the job up.

func (*Store) ClaimLease

func (s *Store) ClaimLease(id string) (*Lease, error)

ClaimLease is Claim, returning the lease the claiming process writes through.

func (*Store) Clean

func (s *Store) Clean(olderThan time.Duration) (int, error)

Clean deletes jobs not updated within olderThan, except running ones, and returns how many it deleted.

func (*Store) Close

func (s *Store) Close() error

Close closes the database.

func (*Store) Create

func (s *Store) Create(cmd []string, inputs []media.Input, params map[string]string) (*Job, error)

Create stores a new job with every input pending.

func (*Store) Delete

func (s *Store) Delete(id string) error

Delete removes one job and its items.

func (*Store) FindResumable

func (s *Store) FindResumable(cmd []string, params map[string]string) (*Job, bool)

FindResumable returns the newest job for the same command and params that still has work left (pending items, or failures that are safe to retry) and is not running in another process.

func (*Store) Get

func (s *Store) Get(id string) (*Job, error)

Get returns one job with its counts.

func (*Store) Items

func (s *Store) Items(id string) ([]Item, error)

Items returns a job's items in input order.

func (*Store) RecentResults

func (s *Store) RecentResults(limit int) ([]RecentResult, error)

RecentResults returns finished items with a result, newest job first.

func (*Store) SaveItem

func (s *Store) SaveItem(id string, it Item) error

SaveItem writes an item's state and result.

Jump to

Keyboard shortcuts

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