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
- Variables
- func CheckFields(out *output.Printer) error
- func Describe(it Item) string
- func EnterpriseJSON(matches []audd.EnterpriseMatch) json.RawMessage
- func ErrorFor(err error) *output.Error
- func HumanLine(w io.Writer, st output.Styles, it Item)
- func ItemStatus(it Item) string
- func PrintDryRun(out *output.Printer, input, jobID, endpoint string, plan any, ...) error
- func RecognizeSDK(ctx context.Context, a *app.App, in media.Input, p Params) (json.RawMessage, error)
- func RequestsUsed(spent, reserved, unknown int) string
- func ResultFields(prefix string) []string
- func RunBatch(ctx context.Context, a *app.App, opts app.BatchOptions) (app.BatchSummary, error)
- type CSVRow
- type DryRunDoc
- type Item
- type Job
- type Lease
- type LineError
- type Params
- type Plan
- type RecentResult
- type ResultLine
- type Store
- func (s *Store) Claim(id string) (release func(status string), err error)
- func (s *Store) ClaimLease(id string) (*Lease, error)
- func (s *Store) Clean(olderThan time.Duration) (int, error)
- func (s *Store) Close() error
- func (s *Store) Create(cmd []string, inputs []media.Input, params map[string]string) (*Job, error)
- func (s *Store) Delete(id string) error
- func (s *Store) FindResumable(cmd []string, params map[string]string) (*Job, bool)
- func (s *Store) Get(id string) (*Job, error)
- func (s *Store) Items(id string) ([]Item, error)
- func (s *Store) RecentResults(limit int) ([]RecentResult, error)
- func (s *Store) SaveItem(id string, it Item) error
Constants ¶
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.
const ( StatePending = "pending" StateDone = "done" // recognized, or no match (Result is null or []) StateFailed = "failed" )
Item states.
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.
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.
const ErrCodeTakenOver = "job_taken_over"
ErrCodeTakenOver is the error code when another process took a job over.
const ExitInterrupted = 130
ExitInterrupted is the exit code after Ctrl-C (128 + SIGINT).
Variables ¶
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.
var EnterpriseFields = []string{"start_offset", "end_offset", "start_seconds", "end_seconds"}
EnterpriseFields are the fields an enterprise match has besides MatchFields.
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.
var ProviderBlocks = []string{"apple_music", "spotify", "deezer", "musicbrainz"}
ProviderBlocks are the optional metadata blocks --return adds.
Functions ¶
func CheckFields ¶
CheckFields checks --fields for the result lines of a batch before anything is sent.
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 ¶
ErrorFor maps a recognition error to the CLI's error (exit code, stable code, and hint).
func ItemStatus ¶
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 ¶
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 ¶
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 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.
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.
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 ¶
Heartbeat records that this process is alive and still holds the job. It returns job_taken_over when another process holds it now.
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 ¶
ParamsFromMap is the inverse of Map.
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) Line ¶
Line is the plan as one sentence, worded the same as a single input's plan (see safety.PlanText).
func (Plan) MarshalJSON ¶
MarshalJSON writes requests and cost_usd as null, with "unbounded": true, when the plan is unbounded.
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 (*Store) Claim ¶
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 ¶
ClaimLease is Claim, returning the lease the claiming process writes through.
func (*Store) Clean ¶
Clean deletes jobs not updated within olderThan, except running ones, and returns how many it deleted.
func (*Store) FindResumable ¶
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) RecentResults ¶
func (s *Store) RecentResults(limit int) ([]RecentResult, error)
RecentResults returns finished items with a result, newest job first.