Documentation
¶
Overview ¶
Package store defines Workly's persistence interface.
There are two implementations, postgres and sqlite, and both must pass the conformance suite in storetest. Every method that touches workspace data takes the workspace ID explicitly: there is no way to query across workspaces by accident. The exception is the dispatcher methods, which schedule work for all workspaces and are grouped under Dispatch.
Index ¶
- Constants
- Variables
- type ActivityCount
- type AlertChannel
- type AlertChannelType
- type AlertErrorGroup
- type AlertFailures
- type AlertKind
- type AlertSubject
- type AlertWindow
- type Attempt
- type AttemptResult
- type AutoPause
- type AutoPauseEvent
- type Callback
- type Changes
- type Dispatch
- type FailureGroup
- type FinishOutcome
- type FinishedAttempt
- type FinishedCount
- type Fire
- type Group
- type GroupError
- type GroupFilter
- type GroupStatus
- type GroupSummary
- type Leader
- type MissedPolicy
- type NewGroup
- type NewTask
- type NewWorkflowRun
- type Outcome
- type OverlapPolicy
- type Queue
- type QueueActivity
- type QueueConfig
- type QueueStats
- type QueueStatus
- type Run
- type RunAttemptResult
- type RunCallbackBody
- type RunClaim
- type RunFilter
- type RunState
- type RunSummary
- type RunTrigger
- type Schedule
- type ScheduleConfig
- type ScheduleStatus
- type SkipReason
- type StepStatus
- type Store
- type Sweep
- type Task
- type TaskCallbackBody
- type TaskFilter
- type TaskSort
- type TaskState
- type TaskWorkflowStep
- type Workflow
- type WorkflowConfig
- type WorkflowRun
- type WorkflowRunFilter
- type WorkflowRunStatus
- type WorkflowStep
- type WorkflowStepBody
- type WorkflowStepConfig
- type Workspace
Constants ¶
const ( HeaderWorkflow = "Workly-Workflow" HeaderWorkflowRunID = "Workly-Workflow-Run-Id" HeaderWorkflowStep = "Workly-Workflow-Step" HeaderWorkflowStepID = "Workly-Workflow-Step-Id" // HeaderWorkflowRunAttempt is the run's attempt, 1 until it is retried: // with the step ID, a key for work that a retried step should redo. HeaderWorkflowRunAttempt = "Workly-Workflow-Run-Attempt" )
Headers on a step's task, set when the task is created: they tell the endpoint which step it is serving, and the task which step it delivers.
const CallbackQueue = "_callbacks"
CallbackQueue is the queue every callback is enqueued into. Its name is reserved, so only Workly enqueues into it, and callbacks have no callbacks of their own.
const DefaultWorkflowMaxDuration = 24 * time.Hour
DefaultWorkflowMaxDuration is MaxDuration when it isn't set.
const DurationSampleLimit = 1000
DurationSampleLimit is how many of the latest succeeded, and of the latest failed, tasks QueueActivity's duration percentiles are taken over.
const MaxWorkflowSteps = 100
MaxWorkflowSteps bounds a workflow's size.
const WaitForHeader = "Workly-Wait-For"
WaitForHeader is the response header with which a step's endpoint hands its completion to another resource: "group/<id>".
const WorkflowQueue = "_workflows"
WorkflowQueue is the queue steps go to unless they name one. Its name is reserved, so only Workly enqueues into it.
Variables ¶
var ( // ErrNotFound is returned when a requested record does not exist. ErrNotFound = errors.New("not found") // ErrNotLeader is returned by TryLead when another process holds leadership. ErrNotLeader = errors.New("another dispatcher is leader") // ErrLeaseLost is returned by FinishAttempt (FinishRunAttempt) when the // task (run) is no longer running under the given attempt, e.g. because // the lease reaper already recovered it or its queue (schedule) was // deleted. ErrLeaseLost = errors.New("lease lost") // ErrInvalidState is returned when a task or run can't make the requested // transition, e.g. cancelling a task that already succeeded. ErrInvalidState = errors.New("invalid task or run state for this operation") // ErrInvalidCursor is returned by ListTasks for a cursor it didn't // issue, or issued for another sort. ErrInvalidCursor = errors.New("invalid cursor") // ErrGroupNotFound is returned, in a GroupError, by CreateTask and // CreateTasks for a group that doesn't exist. It wraps ErrNotFound. ErrGroupNotFound = fmt.Errorf("group %w", ErrNotFound) // ErrGroupClosed is returned, in a GroupError, by CreateTask and // CreateTasks for a group that no longer accepts tasks. ErrGroupClosed = errors.New("group is closed") )
var ErrExists = errors.New("already exists")
ErrExists is returned when creating something that already exists, such as an alert channel with the same target.
var ErrWorkflowStepTask = errors.New("task is a workflow step")
ErrWorkflowStepTask is returned by RetryTask for a task that is a workflow step: its run has moved on, so replaying it alone would deliver it outside the workflow.
var StatsCountLimit = 10000
StatsCountLimit caps the counts in QueueStats, so that stats stay cheap on queues with a large backlog. It's a variable only so that tests can lower it instead of creating thousands of tasks.
Functions ¶
This section is empty.
Types ¶
type ActivityCount ¶
ActivityCount is how many tasks of a queue were created in the bucket starting at Start.
type AlertChannel ¶
type AlertChannel struct {
ID string
WorkspaceID workspace.ID
Type AlertChannelType
Target string
CreatedAt time.Time
}
AlertChannel is where a workspace's alerts go. Target is an email address or a Slack incoming webhook URL, validated by the API.
type AlertChannelType ¶
type AlertChannelType string
const ( AlertEmail AlertChannelType = "email" AlertSlack AlertChannelType = "slack" )
type AlertErrorGroup ¶
type AlertFailures ¶
type AlertFailures struct {
AlertSubject
// Since is when the counted failures start.
Since time.Time
Total int
Groups []AlertErrorGroup
}
AlertFailures are a subject's failures since its previous alert (or the window's Since), grouped by error, most common first.
type AlertSubject ¶
AlertSubject is a queue or schedule that alerts are about.
type AlertWindow ¶
type AlertWindow struct {
Now time.Time
// Since is the earliest a failure counts from, for subjects never
// alerted about or alerted about before it.
Since time.Time
// Cooldown is how long a subject waits after an alert before the next.
Cooldown time.Duration
}
AlertWindow selects the failures to alert about (see FailuresToAlert).
type Attempt ¶
type Attempt struct {
ID string
TaskID string
RunID string
Number int
StartedAt time.Time
FinishedAt time.Time
StatusCode *int
Outcome Outcome
Error string
ResponseBody string
ResponseHeaders map[string]string
// RetriedAt is set when a manual retry came between the previous
// attempt and this one: when the retry happened. The store sets it.
RetriedAt *time.Time
}
Attempt is one delivery of a task or a schedule run. Exactly one of TaskID and RunID is set.
type AttemptResult ¶
type AttemptResult struct {
Attempt
// NextState is pending (retry at RunAt), succeeded or failed.
NextState TaskState
RunAt time.Time
}
AttemptResult is an attempt plus the task's resulting state.
type AutoPause ¶ added in v0.5.0
type AutoPause struct {
Since time.Time
// Error is the error of the attempt that paused the queue, or of the
// latest failed probe.
Error string
// Probes counts the probes that failed since it paused.
Probes int
NextProbeAt time.Time
}
AutoPause is the state of a queue that paused itself after failures in a row. It delivers nothing but one probe task at a time, at NextProbeAt; the first success, or resuming by hand, clears it.
type AutoPauseEvent ¶ added in v0.5.0
type AutoPauseEvent struct {
Workspace workspace.ID
Queue string
// Resumed is false when the queue paused, true when it resumed.
Resumed bool
// Since is when the queue paused.
Since time.Time
// Error is the error that paused it (when pausing), or the last one
// before it resumed.
Error string
// Failures is how many failures in a row paused it (when pausing).
Failures int
}
AutoPauseEvent is a queue pausing itself after failures in a row, or resuming after a success, for alerts.
type Callback ¶ added in v0.2.1
Callback is a task enqueued when something completes: a POST saying what completed, as JSON: a TaskCallbackBody, RunCallbackBody or GroupSummary.
type Changes ¶ added in v0.2.0
type Changes interface {
// PublishChanges tells every replica listening, this one included, that
// the workspaces changed.
PublishChanges(ctx context.Context, ws []workspace.ID) error
// ListenChanges calls fn with the workspaces of each notice published
// from the time it is listening (it calls ready then) until ctx is done
// or the connection fails. fn must not block.
ListenChanges(ctx context.Context, ready func(), fn func([]workspace.ID)) error
}
Changes carries change notices between the replicas sharing a database, so each can tell the dashboards it serves that a workspace's queues, tasks, schedules or runs changed. Notices are hints: they say which workspaces changed, not what, and may be lost.
type Dispatch ¶
type Dispatch interface {
// TryLead attempts to become the single dispatcher. It returns
// ErrNotLeader if another process holds leadership.
TryLead(ctx context.Context) (Leader, error)
// DueQueues returns unpaused queues that have pending tasks due at now:
// those not auto-paused, and auto-paused ones whose next probe is due.
DueQueues(ctx context.Context, now time.Time) ([]Queue, error)
// NextRunAt returns the earliest run_at after the given time of any
// pending task, or the next probe time of an auto-paused queue if that
// is earlier.
NextRunAt(ctx context.Context, after time.Time) (t time.Time, ok bool, err error)
// ClaimTasks moves up to limit due tasks of a queue to running, increments
// their attempt count and leases them until now + their timeout + grace.
// It claims nothing if the queue has been paused or auto-paused.
ClaimTasks(ctx context.Context, q Queue, limit int, now time.Time, grace time.Duration) ([]Task, error)
// ClaimProbe claims the oldest due task of an auto-paused queue whose
// probe is due, as ClaimTasks would, and holds off the next probe until
// the task's lease expires, so a probe in flight is never joined by
// another. It claims nothing if the queue isn't auto-paused, is paused by
// hand or its probe isn't due.
ClaimProbe(ctx context.Context, q Queue, now time.Time, grace time.Duration) ([]Task, error)
// AutoPauseQueue auto-pauses a queue that has AutoPauseAfter set and
// isn't auto-paused yet, with its first probe at nextProbe. paused
// reports whether it did.
AutoPauseQueue(ctx context.Context, ws workspace.ID, name, errMsg string, now, nextProbe time.Time) (paused bool, err error)
// ProbeFailed records a failed probe of an auto-paused queue and when to
// send the next one.
ProbeFailed(ctx context.Context, ws workspace.ID, name, errMsg string, nextProbe time.Time) error
// AutoResumeQueue clears a queue's auto-pause after a success. It returns
// the state it cleared, or nil if the queue wasn't auto-paused.
AutoResumeQueue(ctx context.Context, ws workspace.ID, name string) (*AutoPause, error)
// FinishAttempt records an attempt and moves the task to r.NextState,
// or leaves it cancelled if it was cancelled mid-attempt. It returns the
// task's resulting state, or ErrLeaseLost if attempt r.Number is no
// longer in flight, in which case nothing is written.
FinishAttempt(ctx context.Context, ws workspace.ID, r AttemptResult) (TaskState, error)
// FinishAttempts records several attempts in one transaction, each as
// FinishAttempt would, so a busy dispatcher commits once per batch
// rather than once per delivery. Each task may appear at most once.
// outcomes[i] is rs[i]'s; its Err is nil or ErrLeaseLost. If err is
// non-nil, nothing is written.
FinishAttempts(ctx context.Context, rs []FinishedAttempt) (outcomes []FinishOutcome, err error)
// ExpiredLeases returns up to limit tasks with an attempt in flight whose
// lease expired before now, i.e. whose dispatcher crashed or lost its
// database connection mid-delivery.
ExpiredLeases(ctx context.Context, now time.Time, limit int) ([]Task, error)
// AllQueueStats returns every queue's stats across all workspaces, for
// metrics.
AllQueueStats(ctx context.Context, now time.Time) ([]QueueStatus, error)
// DeleteFinishedTasks deletes up to limit succeeded, failed or cancelled
// tasks in the sweep's workspaces that finished before sw.Before, with
// their attempts. It returns how many it deleted.
DeleteFinishedTasks(ctx context.Context, sw Sweep, limit int) (int, error)
// DeleteFinishedGroups deletes up to limit groups in the sweep's
// workspaces that completed before sw.Before. It returns how many it
// deleted.
DeleteFinishedGroups(ctx context.Context, sw Sweep, limit int) (int, error)
// DueSchedules returns unpaused schedules whose next slot is at or
// before now.
DueSchedules(ctx context.Context, now time.Time) ([]Schedule, error)
// FireSchedule creates the run for f.Slot and moves the schedule to
// f.NextRunAt, if the schedule is unpaused and its next slot is still
// f.Due; otherwise it does nothing and returns fired = false. The run is
// skipped if f.SkipReason is set, or if the schedule's overlap policy is
// skip and a run is still pending or running. A slot never gets two
// runs.
FireSchedule(ctx context.Context, f Fire, now time.Time) (run Run, fired bool, err error)
// NextScheduleWork returns the earliest time after the given one when a
// schedule fires or a pending run is due.
NextScheduleWork(ctx context.Context, after time.Time) (t time.Time, ok bool, err error)
// ClaimRuns moves up to limit due runs to running, oldest first,
// increments their attempt count and leases them until now + their
// schedule's timeout + grace.
ClaimRuns(ctx context.Context, limit int, now time.Time, grace time.Duration) ([]RunClaim, error)
// FinishRunAttempt records a run's attempt and moves it to r.NextState,
// as FinishAttempt does for tasks.
FinishRunAttempt(ctx context.Context, ws workspace.ID, r RunAttemptResult) (RunState, error)
// ExpiredRunLeases returns up to limit runs with an attempt in flight
// whose lease expired before now.
ExpiredRunLeases(ctx context.Context, now time.Time, limit int) ([]Run, error)
// DeleteFinishedRuns deletes up to limit runs in the sweep's workspaces
// that finished before sw.Before, with their attempts, except each
// schedule's latest run.
DeleteFinishedRuns(ctx context.Context, sw Sweep, limit int) (int, error)
// AllScheduleStatus returns every schedule's status across all
// workspaces, for metrics.
AllScheduleStatus(ctx context.Context) ([]ScheduleStatus, error)
// AllAlertChannels returns every workspace's alert channels, oldest
// first, for the alerts loop.
AllAlertChannels(ctx context.Context) ([]AlertChannel, error)
// ExpireWorkflowRuns fails up to limit running workflow runs whose
// deadline passed before now, as a failed step would, and returns how
// many.
ExpireWorkflowRuns(ctx context.Context, now time.Time, limit int) (int, error)
// DeleteFinishedWorkflowRuns deletes up to limit workflow runs in the
// sweep's workspaces that finished before sw.Before, with their steps,
// except each workflow's latest run.
DeleteFinishedWorkflowRuns(ctx context.Context, sw Sweep, limit int) (int, error)
}
Dispatch holds the methods used by the dispatcher. Unlike the rest of the Store, they span all workspaces.
type FailureGroup ¶
type FailureGroup struct {
// Outcome is empty for tasks that failed before outcomes were recorded
// on tasks.
Outcome Outcome
StatusCode *int
Error string
Count int
LastFailed time.Time
// LatestTaskID is the group's most recently failed task.
LatestTaskID string
// ResponseBody is the start of the latest task's last response body.
ResponseBody string
}
FailureGroup is a set of failed tasks whose latest attempt ended the same way.
type FinishOutcome ¶
FinishOutcome is what FinishAttempts did with one result.
type FinishedAttempt ¶
type FinishedAttempt struct {
Workspace workspace.ID
AttemptResult
}
FinishedAttempt is an attempt result of a task in workspace Workspace.
type FinishedCount ¶ added in v0.4.0
FinishedCount is how many tasks finished in State (succeeded or failed) in the bucket starting at Start.
type Fire ¶
type Fire struct {
WorkspaceID workspace.ID
Schedule string
// Due is the schedule's NextRunAt as the dispatcher read it. The fire
// only happens if it is unchanged, so a slot can't fire twice.
Due time.Time
// Slot is the slot the run is for.
Slot time.Time
// SkipReason, if set, records the slot as skipped without delivering it.
SkipReason SkipReason
// NextRunAt is the slot after this one.
NextRunAt time.Time
}
Fire fires one slot of a schedule (see Dispatch.FireSchedule).
type Group ¶ added in v0.2.0
type Group struct {
ID string
WorkspaceID workspace.ID
Name string
Status GroupStatus
IdempotencyKey string
Total int
Succeeded int
Failed int
Cancelled int
OnComplete *Callback
// CallbackTaskID is the task enqueued for OnComplete when the group
// completed.
CallbackTaskID string
CreatedAt time.Time
ClosedAt *time.Time
FinishedAt *time.Time
}
Group is a set of tasks tracked together. Its counts cover its tasks' current states while it is open or running, and are frozen once it completes: retrying a task of a completed group doesn't change them.
func (Group) CallbackBody ¶ added in v0.2.0
CallbackBody is the JSON body of g's callback.
type GroupError ¶ added in v0.2.0
GroupError says which group a task couldn't join, and why: Err is ErrGroupNotFound or ErrGroupClosed.
func (*GroupError) Error ¶ added in v0.2.0
func (e *GroupError) Error() string
func (*GroupError) Unwrap ¶ added in v0.2.0
func (e *GroupError) Unwrap() error
type GroupFilter ¶ added in v0.2.0
type GroupFilter struct {
Status GroupStatus
Name string
Cursor string
Limit int
}
GroupFilter selects groups. Zero fields match everything.
type GroupStatus ¶ added in v0.2.0
type GroupStatus string
GroupStatus is where a group is in its lifecycle: open (accepting tasks), running (closed, tasks unfinished), then succeeded or failed for good.
const ( GroupOpen GroupStatus = "open" GroupRunning GroupStatus = "running" GroupSucceeded GroupStatus = "succeeded" GroupFailed GroupStatus = "failed" )
func (GroupStatus) Finished ¶ added in v0.2.0
func (s GroupStatus) Finished() bool
Finished reports whether the group has completed.
type GroupSummary ¶ added in v0.2.0
type GroupSummary struct {
GroupID string `json:"group_id"`
Name string `json:"name,omitempty"`
Status GroupStatus `json:"status"`
Total int `json:"total"`
Succeeded int `json:"succeeded"`
Failed int `json:"failed"`
Cancelled int `json:"cancelled"`
}
GroupSummary is the body of a group's callback.
type Leader ¶
type Leader interface {
// Wake receives a value when a task is enqueued (due now or later), so
// the dispatcher can dispatch it or reset its timer. It is a hint:
// wake-ups coalesce, and the dispatcher also polls.
Wake() <-chan struct{}
// Lost is closed if leadership is lost, e.g. the database connection
// holding it dropped.
Lost() <-chan struct{}
// Release gives up leadership.
Release()
}
Leader is held by the one dispatcher allowed to deliver tasks.
type MissedPolicy ¶
type MissedPolicy string
MissedPolicy decides what happens to slots missed while no dispatcher was running. Either way at most one run is created for them.
const ( // MissedSkip records the most recent missed slot as a skipped run. MissedSkip MissedPolicy = "skip" // MissedCatchUp runs the most recent missed slot. MissedCatchUp MissedPolicy = "catch_up" )
type NewTask ¶
type NewTask struct {
Queue string
Method string
URL string
Headers map[string]string
Body []byte
RunAt time.Time
// MaxAttempts and Timeout override the queue's policy when non-nil.
MaxAttempts *int
Timeout *time.Duration
IdempotencyKey string
// TraceContext is the W3C traceparent captured at enqueue.
TraceContext string
GroupID string
// OnComplete is enqueued each time the task finishes.
OnComplete *Callback
// WorkflowStepID is the workflow step the task delivers, if any.
WorkflowStepID string
}
type NewWorkflowRun ¶ added in v0.4.0
type NewWorkflowRun struct {
Input json.RawMessage
IdempotencyKey string
// ScheduleRunID is the schedule run that started it, if any.
ScheduleRunID string
}
type Outcome ¶
type Outcome string
const ( OutcomeSuccess Outcome = "success" OutcomeHTTPError Outcome = "http_error" OutcomeTimeout Outcome = "timeout" OutcomeNetworkError Outcome = "network_error" // OutcomeLost means the result is unknown: the dispatcher crashed or was // shut down mid-delivery. The endpoint may have processed the request. OutcomeLost Outcome = "lost" )
type OverlapPolicy ¶
type OverlapPolicy string
OverlapPolicy decides what happens to a slot that comes up while the previous run is still pending or running.
const ( // OverlapSkip records the slot as a skipped run. OverlapSkip OverlapPolicy = "skip" // OverlapAllow runs it alongside. OverlapAllow OverlapPolicy = "allow" )
type Queue ¶
type Queue struct {
WorkspaceID workspace.ID
Name string
// Paused is a pause by hand. It wins over AutoPaused: a queue paused by
// hand sends no probes.
Paused bool
// AutoPaused is set while the queue has paused itself (AutoPauseAfter).
AutoPaused *AutoPause
QueueConfig
CreatedAt time.Time
UpdatedAt time.Time
}
type QueueActivity ¶
type QueueActivity struct {
Succeeded int
Failed int
Cancelled int
// P50Duration and P95Duration are percentiles of the latest attempt's
// duration over the succeeded and failed tasks counted: up to the
// DurationSampleLimit of each that finished last. Nil if none recorded
// one.
P50Duration *time.Duration
P95Duration *time.Duration
// DurationSamples is how many durations the percentiles are taken over.
DurationSamples int
}
QueueActivity counts a queue's finished tasks by final state.
type QueueConfig ¶
type QueueConfig struct {
// RatePerSecond limits how many deliveries start per second. 0 means
// unlimited.
RatePerSecond float64
// MaxConcurrency limits how many deliveries are in flight. The API
// always sets it; 0, for no limit, is left to tests.
MaxConcurrency int
MaxAttempts int
MinBackoff time.Duration
MaxBackoff time.Duration
BackoffMultiplier float64
Timeout time.Duration
// RetryOn4xx retries 4xx responses other than 408 and 429, which are
// otherwise treated as permanent failures.
RetryOn4xx bool
// AutoPauseAfter pauses the queue after this many failed attempts in a
// row that say its endpoint is down (see dispatch.CountsTowardAutoPause).
// 0 never does.
AutoPauseAfter int
}
QueueConfig is a queue's delivery policy. Tasks can override MaxAttempts and Timeout.
func DefaultQueueConfig ¶
func DefaultQueueConfig() QueueConfig
type QueueStats ¶
type QueueStats struct {
// Due counts pending tasks whose run_at has passed.
Due int
// Scheduled counts pending tasks due in the future, including ones
// waiting to retry.
Scheduled int
Running int
// Failed counts tasks that failed and are still retained.
Failed int
// OldestDueAt is the earliest run_at of a due task: how long the queue
// has been behind. Nil when nothing is due.
OldestDueAt *time.Time
}
QueueStats describes a queue's current work. Counts stop at StatsCountLimit.
type QueueStatus ¶
type QueueStatus struct {
WorkspaceID workspace.ID
Queue string
Paused bool
AutoPaused bool
QueueStats
}
QueueStatus is a queue's stats with its identity, for metrics.
type Run ¶
type Run struct {
ID string
WorkspaceID workspace.ID
Schedule string
State RunState
Trigger RunTrigger
ScheduledFor time.Time
SkipReason SkipReason
Method string
URL string
Headers map[string]string
Body []byte
// RunAt is when the run is next eligible for delivery.
RunAt time.Time
AttemptCount int
ReplayedAttempts int
LeaseExpiresAt *time.Time
LastStatus *int
LastOutcome Outcome
LastError string
CreatedAt time.Time
UpdatedAt time.Time
FinishedAt *time.Time
LastAttemptAt *time.Time
// StartedAt is when the first delivery attempt started. Replays don't
// reset it.
StartedAt *time.Time
// LastDuration is how long the latest finished attempt took.
LastDuration *time.Duration
RetriedAt *time.Time
// CallbackTaskID is the callback enqueued when the run last finished.
CallbackTaskID string
// WorkflowRunID is the workflow run it started, for a schedule that
// starts a workflow.
WorkflowRunID string
// WorkflowRunStatus is that workflow run's status, filled in by GetRun
// and ListRuns.
WorkflowRunStatus WorkflowRunStatus
// CallbackState is the state of the task in CallbackTaskID, filled in
// by GetRun and ListRuns; empty once retention has removed it.
CallbackState TaskState
}
Run is one firing of a schedule. It snapshots the schedule's request when it is created, and is retried under the schedule's current policy.
func (Run) AttemptsSinceReplay ¶
AttemptsSinceReplay is the number of attempts counted against the schedule's MaxAttempts.
func (Run) CallbackBody ¶ added in v0.3.0
CallbackBody is the JSON body of the callback for r, once r has finished.
type RunAttemptResult ¶
type RunAttemptResult struct {
Attempt
// NextState is pending (retry at RunAt), succeeded or failed.
NextState RunState
RunAt time.Time
}
RunAttemptResult is a run's attempt plus the run's resulting state.
type RunCallbackBody ¶ added in v0.3.0
type RunCallbackBody struct {
RunID string `json:"run_id"`
Schedule string `json:"schedule"`
State RunState `json:"state"`
Trigger RunTrigger `json:"trigger"`
ScheduledFor time.Time `json:"scheduled_for"`
AttemptCount int `json:"attempt_count"`
LastStatus *int `json:"last_status,omitempty"`
LastOutcome Outcome `json:"last_outcome,omitempty"`
LastError string `json:"last_error,omitempty"`
FinishedAt time.Time `json:"finished_at"`
}
RunCallbackBody is the body of a schedule's callback.
type RunFilter ¶
RunFilter selects runs. Zero fields match everything: with Schedule empty, runs of every schedule in the workspace.
type RunSummary ¶
type RunSummary struct {
ID string
State RunState
Trigger RunTrigger
ScheduledFor time.Time
FinishedAt *time.Time
LastStatus *int
LastError string
// WorkflowRunID and WorkflowRunStatus are the workflow run it started,
// for a schedule that starts a workflow.
WorkflowRunID string
WorkflowRunStatus WorkflowRunStatus
}
RunSummary describes a schedule's latest run.
type RunTrigger ¶
type RunTrigger string
const ( TriggerSchedule RunTrigger = "schedule" TriggerManual RunTrigger = "manual" )
type Schedule ¶
type Schedule struct {
WorkspaceID workspace.ID
Name string
ScheduleConfig
Paused bool
// PausedAt is when a paused schedule was paused; nil while it runs.
PausedAt *time.Time
// NextRunAt is the next slot to fire; nil while paused.
NextRunAt *time.Time
// LastRun is the most recent run, if any. Only GetSchedule and
// ListSchedules set it.
LastRun *RunSummary
CreatedAt time.Time
UpdatedAt time.Time
}
type ScheduleConfig ¶
type ScheduleConfig struct {
Cron string
Timezone string
// Workflow, if set, is the workflow each run starts instead of calling
// URL, with Body as the workflow run's input.
Workflow string
Method string
URL string
Headers map[string]string
Body []byte
Timeout time.Duration
MaxAttempts int
MinBackoff time.Duration
MaxBackoff time.Duration
BackoffMultiplier float64
RetryOn4xx bool
Overlap OverlapPolicy
Missed MissedPolicy
// OnComplete is enqueued each time a run finishes, except skipped runs.
OnComplete *Callback
}
ScheduleConfig is a schedule's settings. The cron expression and timezone are validated by the API; the store keeps them as text.
func DefaultScheduleConfig ¶
func DefaultScheduleConfig() ScheduleConfig
DefaultScheduleConfig is the settings a schedule gets for omitted fields. Retries are fewer and shorter than a queue's, so a failing run gives up well before a frequent schedule's next slot.
type ScheduleStatus ¶
type ScheduleStatus struct {
WorkspaceID workspace.ID
Schedule string
Paused bool
// LastSuccessAt is when the latest successful run finished.
LastSuccessAt *time.Time
}
ScheduleStatus is what metrics report per schedule.
type SkipReason ¶
type SkipReason string
const ( SkipOverlap SkipReason = "overlap" SkipMissed SkipReason = "missed" )
type StepStatus ¶ added in v0.4.0
type StepStatus string
StepStatus is where a step is. A pending step has a task; whether it is being delivered or retried is the task's state.
const ( // StepBlocked waits for its dependencies. StepBlocked StepStatus = "blocked" // StepPending has its task enqueued. StepPending StepStatus = "pending" // StepWaiting's request succeeded, and handed completion to WaitFor. StepWaiting StepStatus = "waiting" StepSucceeded StepStatus = "succeeded" StepFailed StepStatus = "failed" // StepSkipped never ran, or was dropped, because the run stopped. StepSkipped StepStatus = "skipped" )
func (StepStatus) Finished ¶ added in v0.4.0
func (s StepStatus) Finished() bool
type Store ¶
type Store interface {
// Ping checks that the database is reachable.
Ping(ctx context.Context) error
// Migrate applies all pending schema migrations. It is safe to call
// concurrently from multiple processes.
Migrate(ctx context.Context) error
// MigrationsPending reports whether any embedded migration has not been applied.
MigrationsPending(ctx context.Context) (bool, error)
Close() error
// EnsureWorkspace creates the workspace if it doesn't exist and returns it.
EnsureWorkspace(ctx context.Context, id workspace.ID, name string) (Workspace, error)
GetWorkspace(ctx context.Context, id workspace.ID) (Workspace, error)
// DeleteWorkspace deletes the workspace with everything in it: queues,
// tasks, groups, schedules, runs, workflows, alert channels and their
// attempts. Attempts in flight finish with ErrLeaseLost. It returns
// ErrNotFound if the workspace doesn't exist.
DeleteWorkspace(ctx context.Context, id workspace.ID) error
// PutQueue creates the queue or replaces its configuration. created
// reports whether it was new.
PutQueue(ctx context.Context, ws workspace.ID, name string, cfg QueueConfig) (q Queue, created bool, err error)
GetQueue(ctx context.Context, ws workspace.ID, name string) (Queue, error)
ListQueues(ctx context.Context, ws workspace.ID) ([]Queue, error)
// DeleteQueue deletes the queue with all its tasks and attempts.
DeleteQueue(ctx context.Context, ws workspace.ID, name string) error
// SetQueuePaused pauses or resumes dispatch from a queue. Resuming also
// clears an auto-pause. PutQueue
// doesn't change whether a queue is paused.
SetQueuePaused(ctx context.Context, ws workspace.ID, name string, paused bool) (Queue, error)
// QueueStats returns the stats of the named queue, or of every queue in
// the workspace if name is empty, keyed by queue name. A missing queue is
// absent from the map.
QueueStats(ctx context.Context, ws workspace.ID, name string, now time.Time) (map[string]QueueStats, error)
// QueueActivity counts the queue's tasks that finished at or after
// since, by final state. Only retained tasks count, and counts stop at
// StatsCountLimit.
QueueActivity(ctx context.Context, ws workspace.ID, queue string, since time.Time) (QueueActivity, error)
// TaskActivity counts the workspace's tasks created at or after since,
// per queue and per bucket of the given size, aligned to the Unix epoch
// (so to UTC hours and days). Empty buckets are left out.
TaskActivity(ctx context.Context, ws workspace.ID, since time.Time, bucket time.Duration) ([]ActivityCount, error)
// FinishedActivity counts the workspace's tasks that succeeded or
// failed at or after since, per final state and per bucket, aligned like
// TaskActivity's. Empty buckets are left out.
FinishedActivity(ctx context.Context, ws workspace.ID, since time.Time, bucket time.Duration) ([]FinishedCount, error)
// QueueFailures groups the queue's failed tasks by how their latest
// attempt ended, most common first, and returns up to limit groups. Only
// the StatsCountLimit most recently failed tasks are grouped.
QueueFailures(ctx context.Context, ws workspace.ID, queue string, limit int) ([]FailureGroup, error)
// CancelPendingTasks cancels the queue's pending tasks (including
// scheduled ones), as CancelTask does, and returns how many. Running
// tasks are unaffected. It returns ErrNotFound if the queue doesn't
// exist.
CancelPendingTasks(ctx context.Context, ws workspace.ID, queue string) (int, error)
// CreateTask enqueues a task. If t.IdempotencyKey matches an existing
// task in the same queue, that task is returned with created = false.
// If the queue doesn't exist it is created with defaults when
// autoCreateQueue is set, and ErrNotFound is returned otherwise. A task
// with a GroupID joins that group, which must be open (ErrGroupNotFound,
// ErrGroupClosed).
CreateTask(ctx context.Context, ws workspace.ID, t NewTask, autoCreateQueue bool) (task Task, created bool, err error)
// CreateTasks enqueues tasks atomically, as CreateTask does one.
CreateTasks(ctx context.Context, ws workspace.ID, ts []NewTask, autoCreateQueue bool) (tasks []Task, created []bool, err error)
GetTask(ctx context.Context, ws workspace.ID, id string) (Task, error)
// ListTasks returns tasks matching the filter, in the filter's order
// (newest first by default). Pass the returned cursor back, with the
// same filter, to get the next page; it is empty on the last page.
ListTasks(ctx context.Context, ws workspace.ID, f TaskFilter) (tasks []Task, cursor string, err error)
// ListAttempts returns a task's attempts, oldest first.
ListAttempts(ctx context.Context, ws workspace.ID, taskID string) ([]Attempt, error)
// CancelTask cancels a pending or running task. A running task's
// current attempt finishes and is recorded, but the task isn't retried.
// Cancelling a cancelled task is a no-op; cancelling a succeeded or
// failed one returns ErrInvalidState.
CancelTask(ctx context.Context, ws workspace.ID, id string) (Task, error)
// RetryTask makes a task due now. A finished task (succeeded, failed or
// cancelled) is replayed with a fresh attempt budget. It returns
// ErrInvalidState while an attempt is in flight.
RetryTask(ctx context.Context, ws workspace.ID, id string) (Task, error)
// RetryFailedTasks replays the failed tasks in the queue, as RetryTask
// does, and returns how many. With lastError set, only tasks whose
// LastError equals it are replayed. It returns ErrNotFound if the queue
// doesn't exist.
RetryFailedTasks(ctx context.Context, ws workspace.ID, queue, lastError string) (int, error)
// CreateGroup creates an open group. If g.IdempotencyKey matches an
// existing group, that group is returned with created = false.
CreateGroup(ctx context.Context, ws workspace.ID, g NewGroup) (group Group, created bool, err error)
GetGroup(ctx context.Context, ws workspace.ID, id string) (Group, error)
// ListGroups returns groups matching the filter, newest first, paged
// like ListRuns.
ListGroups(ctx context.Context, ws workspace.ID, f GroupFilter) (groups []Group, cursor string, err error)
// CloseGroup stops a group from accepting tasks. A group whose tasks
// are all finished (or that has none) completes at once; closing a
// closed group changes nothing.
CloseGroup(ctx context.Context, ws workspace.ID, id string) (Group, error)
// PutSchedule creates the schedule or replaces its settings, and sets
// when it next fires unless it is paused. created reports whether it was
// new.
PutSchedule(ctx context.Context, ws workspace.ID, name string, cfg ScheduleConfig, nextRunAt time.Time) (s Schedule, created bool, err error)
GetSchedule(ctx context.Context, ws workspace.ID, name string) (Schedule, error)
ListSchedules(ctx context.Context, ws workspace.ID) ([]Schedule, error)
// DeleteSchedule deletes the schedule with all its runs and attempts.
DeleteSchedule(ctx context.Context, ws workspace.ID, name string) error
// SetSchedulePaused pauses a schedule, or resumes a paused one from
// nextRunAt. Resuming a schedule that isn't paused changes nothing.
SetSchedulePaused(ctx context.Context, ws workspace.ID, name string, paused bool, nextRunAt time.Time) (Schedule, error)
// TriggerSchedule creates a manual run, due now, whatever the schedule's
// paused state and overlap policy.
TriggerSchedule(ctx context.Context, ws workspace.ID, name string, now time.Time) (Run, error)
// ListRuns returns runs matching the filter, newest first, paged like
// ListTasks.
ListRuns(ctx context.Context, ws workspace.ID, f RunFilter) (runs []Run, cursor string, err error)
GetRun(ctx context.Context, ws workspace.ID, id string) (Run, error)
// ListRunAttempts returns a run's attempts, oldest first.
ListRunAttempts(ctx context.Context, ws workspace.ID, runID string) ([]Attempt, error)
// CancelRun cancels a pending or running run, as CancelTask does a task.
// Cancelling a cancelled run is a no-op; any other state returns
// ErrInvalidState.
CancelRun(ctx context.Context, ws workspace.ID, id string) (Run, error)
// RetryRun makes a run due now. A finished or skipped run is delivered
// again with a fresh attempt budget. It returns ErrInvalidState while an
// attempt is in flight.
RetryRun(ctx context.Context, ws workspace.ID, id string) (Run, error)
// PutWorkflow creates the workflow or replaces its definition. Runs
// already started keep the definition they started with. created
// reports whether it was new.
PutWorkflow(ctx context.Context, ws workspace.ID, name string, cfg WorkflowConfig) (w Workflow, created bool, err error)
GetWorkflow(ctx context.Context, ws workspace.ID, name string) (Workflow, error)
ListWorkflows(ctx context.Context, ws workspace.ID) ([]Workflow, error)
// DeleteWorkflow deletes the definition. Its runs are kept, and those
// still running finish under the definition they started with.
DeleteWorkflow(ctx context.Context, ws workspace.ID, name string) error
// StartWorkflowRun starts a run of the workflow: it enqueues the tasks
// of the steps without dependencies. If r.IdempotencyKey matches an
// existing run of the workflow, that run is returned with created =
// false.
StartWorkflowRun(ctx context.Context, ws workspace.ID, name string, r NewWorkflowRun, now time.Time) (run WorkflowRun, created bool, err error)
// GetWorkflowRun returns a run with its steps and their tasks.
GetWorkflowRun(ctx context.Context, ws workspace.ID, id string) (WorkflowRun, error)
// ListWorkflowRuns returns runs matching the filter, newest first, paged
// like ListRuns. Steps are not set.
ListWorkflowRuns(ctx context.Context, ws workspace.ID, f WorkflowRunFilter) (runs []WorkflowRun, cursor string, err error)
// CancelWorkflowRun stops a running run: steps not yet started are
// skipped and their pending tasks cancelled. Steps being delivered
// finish, and are recorded, but nothing starts after them. Cancelling a
// cancelled run is a no-op; any other finished run returns
// ErrInvalidState.
CancelWorkflowRun(ctx context.Context, ws workspace.ID, id string) (WorkflowRun, error)
// RetryWorkflowRun reopens a failed or cancelled run, under the
// definition it started with: its succeeded steps stay, and the rest
// run again, each step reusing its task with a fresh set of attempts. A
// step that was waiting for a group follows the group: done if it
// succeeded since, waiting again if it is still going. Its attempt goes
// up by one and its deadline starts over. Any other run is
// ErrInvalidState.
RetryWorkflowRun(ctx context.Context, ws workspace.ID, id string, now time.Time) (WorkflowRun, error)
// CreateAlertChannel adds a channel. It returns ErrExists if the
// workspace has one of the same type and target.
CreateAlertChannel(ctx context.Context, ws workspace.ID, typ AlertChannelType, target string) (AlertChannel, error)
GetAlertChannel(ctx context.Context, ws workspace.ID, id string) (AlertChannel, error)
// ListAlertChannels returns the workspace's channels, oldest first.
ListAlertChannels(ctx context.Context, ws workspace.ID) ([]AlertChannel, error)
DeleteAlertChannel(ctx context.Context, ws workspace.ID, id string) error
// FailuresToAlert returns, for each queue and schedule in the workspace
// that is due an alert, its tasks or runs that failed after its last
// alert (or w.Since, whichever is later) and up to w.Now. A subject is
// due once w.Cooldown has passed since its last alert.
FailuresToAlert(ctx context.Context, ws workspace.ID, w AlertWindow) ([]AlertFailures, error)
// MarkAlerted records that the subjects were alerted about at the
// given time.
MarkAlerted(ctx context.Context, ws workspace.ID, subjects []AlertSubject, at time.Time) error
Dispatch
Changes
}
type Sweep ¶ added in v0.4.0
Sweep picks what a retention sweep deletes: rows finished before Before, in Workspace only if it's set, otherwise in every workspace but Except.
type Task ¶
type Task struct {
ID string
WorkspaceID workspace.ID
Queue string
State TaskState
Method string
URL string
Headers map[string]string
Body []byte
// RunAt is when the task is next eligible for dispatch.
RunAt time.Time
AttemptCount int
// ReplayedAttempts is AttemptCount when the task was last replayed. The
// attempt budget (MaxAttempts) counts from there.
ReplayedAttempts int
MaxAttempts *int
Timeout *time.Duration
IdempotencyKey string
TraceContext string
LeaseExpiresAt *time.Time
LastStatus *int
LastOutcome Outcome
LastError string
CreatedAt time.Time
UpdatedAt time.Time
FinishedAt *time.Time
// LastAttemptAt is when the latest attempt finished.
LastAttemptAt *time.Time
// StartedAt is when the first delivery attempt started (when the task
// was first claimed). Replays don't reset it.
StartedAt *time.Time
// LastDuration is how long the latest finished attempt took.
LastDuration *time.Duration
// RetriedAt is when the task was last retried by hand (RetryTask or
// RetryFailedTasks).
RetriedAt *time.Time
// GroupID is the group the task belongs to, if any.
GroupID string
// OnComplete is enqueued each time the task finishes; CallbackTaskID
// is the one enqueued when it last did.
OnComplete *Callback
CallbackTaskID string
// WorkflowStepID is the workflow step the task delivers, if any.
WorkflowStepID string
}
func (Task) AttemptsSinceReplay ¶
AttemptsSinceReplay is the number of attempts counted against MaxAttempts.
func (Task) CallbackBody ¶ added in v0.3.0
CallbackBody is the JSON body of t's callback, once t has finished.
func (Task) EffectiveMaxAttempts ¶
func (t Task) EffectiveMaxAttempts(q QueueConfig) int
EffectiveMaxAttempts applies the queue default.
func (Task) EffectiveTimeout ¶
func (t Task) EffectiveTimeout(q QueueConfig) time.Duration
EffectiveTimeout applies the queue default.
func (Task) WorkflowStep ¶ added in v0.4.0
func (t Task) WorkflowStep() (step TaskWorkflowStep, ok bool)
WorkflowStep is the step the task delivers, read from the headers it was created with; ok is false for a task that isn't a step.
type TaskCallbackBody ¶ added in v0.3.0
type TaskCallbackBody struct {
TaskID string `json:"task_id"`
Queue string `json:"queue"`
State TaskState `json:"state"`
AttemptCount int `json:"attempt_count"`
LastStatus *int `json:"last_status,omitempty"`
LastOutcome Outcome `json:"last_outcome,omitempty"`
LastError string `json:"last_error,omitempty"`
IdempotencyKey string `json:"idempotency_key,omitempty"`
GroupID string `json:"group_id,omitempty"`
FinishedAt time.Time `json:"finished_at"`
}
TaskCallbackBody is the body of a task's callback.
type TaskFilter ¶
type TaskFilter struct {
Queue string
GroupID string
State TaskState
IdempotencyKey string
LastError string
CreatedAfter time.Time
CreatedBefore time.Time
// Sort defaults to SortCreated. Ties are broken by ID, in the same
// direction.
Sort TaskSort
Ascending bool
// Cursor continues a listing with the same filter, sort and direction.
Cursor string
Limit int
}
TaskFilter selects tasks. Zero fields match everything.
type TaskWorkflowStep ¶ added in v0.4.0
type TaskWorkflowStep struct {
ID, Name, Workflow, RunID string
}
TaskWorkflowStep is the workflow step a task delivers.
type Workflow ¶ added in v0.4.0
type Workflow struct {
WorkspaceID workspace.ID
Name string
WorkflowConfig
// Version counts the changes to the definition, from 1.
Version int
// LastRun is the latest run, without its steps, or nil before the first.
LastRun *WorkflowRun
CreatedAt time.Time
UpdatedAt time.Time
}
type WorkflowConfig ¶ added in v0.4.0
type WorkflowConfig struct {
Steps []WorkflowStepConfig `json:"steps"`
// MaxDuration bounds a run: one still running after it fails.
MaxDuration time.Duration `json:"max_duration"`
}
WorkflowConfig is a workflow's definition. The API validates it; the store keeps it as JSON, and each run keeps the one it started with.
func (WorkflowConfig) EffectiveMaxDuration ¶ added in v0.4.0
func (c WorkflowConfig) EffectiveMaxDuration() time.Duration
type WorkflowRun ¶ added in v0.4.0
type WorkflowRun struct {
ID string
WorkspaceID workspace.ID
Workflow string
Version int
Config WorkflowConfig
Input json.RawMessage
Status WorkflowRunStatus
Error string
IdempotencyKey string
ScheduleRunID string
DeadlineAt time.Time
CreatedAt time.Time
FinishedAt *time.Time
// Attempt is 1, plus one for each time the run was retried; RetriedAt
// is when it last was.
Attempt int
RetriedAt *time.Time
// Steps are in definition order. Only GetWorkflowRun sets them.
Steps []WorkflowStep
}
WorkflowRun is one execution of a workflow, under the definition (and version) it started with.
type WorkflowRunFilter ¶ added in v0.4.0
type WorkflowRunFilter struct {
Workflow string
Status WorkflowRunStatus
Cursor string
Limit int
}
WorkflowRunFilter selects runs. Zero fields match everything.
type WorkflowRunStatus ¶ added in v0.4.0
type WorkflowRunStatus string
const ( WorkflowRunning WorkflowRunStatus = "running" WorkflowSucceeded WorkflowRunStatus = "succeeded" WorkflowFailed WorkflowRunStatus = "failed" WorkflowCancelled WorkflowRunStatus = "cancelled" )
func (WorkflowRunStatus) Finished ¶ added in v0.4.0
func (s WorkflowRunStatus) Finished() bool
type WorkflowStep ¶ added in v0.4.0
type WorkflowStep struct {
ID string
RunID string
Name string
DependsOn []string
Status StepStatus
TaskID string
// Task is the step's task, if it has one and it is still retained.
Task *Task
// WaitType and WaitID are the resource a waiting step waits for.
WaitType string
WaitID string
Error string
CreatedAt time.Time
// ReadyAt is when its task was enqueued; HTTPDoneAt when that task
// succeeded; FinishedAt when the step finished.
ReadyAt *time.Time
HTTPDoneAt *time.Time
FinishedAt *time.Time
}
type WorkflowStepBody ¶ added in v0.4.0
type WorkflowStepBody struct {
WorkflowRunID string `json:"workflow_run_id"`
Workflow string `json:"workflow"`
Step string `json:"step"`
StepID string `json:"step_id"`
RunAttempt int `json:"run_attempt"`
Input json.RawMessage `json:"input"`
}
WorkflowStepBody is the body of a step that has none of its own.
type WorkflowStepConfig ¶ added in v0.4.0
type WorkflowStepConfig struct {
Name string `json:"name"`
DependsOn []string `json:"depends_on,omitempty"`
// Queue is the queue the step's task goes to, WorkflowQueue by default.
Queue string `json:"queue"`
Method string `json:"method"`
URL string `json:"url"`
Headers map[string]string `json:"headers,omitempty"`
// Body is the request body. When nil the step is sent the run's
// context instead (a WorkflowStepBody).
Body []byte `json:"body,omitempty"`
// MaxAttempts and Timeout override the queue's policy when non-nil.
MaxAttempts *int `json:"max_attempts,omitempty"`
Timeout *time.Duration `json:"timeout,omitempty"`
}
WorkflowStepConfig is one step: the request its task sends, once all of DependsOn have succeeded.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package migrate applies embedded SQL migrations.
|
Package migrate applies embedded SQL migrations. |
|
Package postgres implements store.Store on PostgreSQL (14+).
|
Package postgres implements store.Store on PostgreSQL (14+). |
|
Package sqlite implements store.Store on SQLite, for `workly dev` and small single-replica self-hosted installs.
|
Package sqlite implements store.Store on SQLite, for `workly dev` and small single-replica self-hosted installs. |
|
Package sqlstore holds the SQL shared by the postgres and sqlite stores.
|
Package sqlstore holds the SQL shared by the postgres and sqlite stores. |
|
Package storetest is the conformance suite every store.Store implementation must pass.
|
Package storetest is the conformance suite every store.Store implementation must pass. |