taskschedule

package
v0.0.0-...-afcfe8e Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Overview

Package taskschedule manages user-defined task schedules (task_schedule table). The Dispatcher polls for due schedules and submits them to the task manager, using FOR UPDATE SKIP LOCKED to prevent double-firing in multi-instance deployments.

Design note: TaskSchedule does not have an internal domain type.

Other objects (Rack, Component, Task) use three layers: proto, internal domain type, and DB model, with converters in internal/converter/. TaskSchedule is intentionally kept at two layers (proto and DB model) because:

  1. It is a configuration record, not a domain object. It does not flow through business logic across package boundaries — it goes linearly from API to store and back.

  2. The meaningful domain content inside a schedule (the operation and target) is already properly typed as operation.Request / operation.TargetSpec. TaskSchedule itself is just the scheduling envelope around that content.

  3. Every consumer (service, dispatcher, store) already imports dbmodel for dbmodel.TaskSchedule, so an internal type would add a near-identical struct and trivial field-copy converters with no practical decoupling.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ComputeFirstRunAt

func ComputeFirstRunAt(
	specType dbmodel.SpecType,
	spec string,
	timezone string,
) (time.Time, error)

ComputeFirstRunAt returns the first execution time for a new schedule.

func MarshalTemplate

func MarshalTemplate(
	opType taskcommon.TaskType,
	code string,
	info json.RawMessage,
	opts TemplateOptions,
) (json.RawMessage, error)

MarshalTemplate serializes an operation into a TaskTemplate JSON blob suitable for storing in task_schedule.operation_template.

func SummaryFromTemplate

func SummaryFromTemplate(templateJSON json.RawMessage) (opType, description string, err error)

SummaryFromTemplate derives the operation_type and human-readable description that are surfaced on a TaskSchedule response. Both values are derived entirely from the stored operation_template so no live operation object is needed.

opType is a stable SCREAMING_SNAKE_CASE string suitable for client filtering (e.g. "POWER_ON", "BRING_UP"). description is a short English phrase for display (e.g. "Power Off (forced)", "Upgrade Firmware to v2.1.0").

func WrapperFromTemplate

func WrapperFromTemplate(raw json.RawMessage) (operation.Wrapper, error)

WrapperFromTemplate unmarshals an operation_template JSON blob and returns the corresponding operation.Wrapper.

Types

type AfterFireUpdate

type AfterFireUpdate struct {
	// LastRunAt is the wall-clock time at which the schedule fired.
	LastRunAt time.Time
	// NextRunAt is the next scheduled firing time. nil sets next_run_at to NULL,
	// which marks a one-time schedule as fully consumed.
	NextRunAt *time.Time
	// Enabled reflects whether the schedule should remain active after this firing.
	// Set to false for one-time schedules after they fire.
	Enabled bool
}

AfterFireUpdate carries the schedule-level fields written back after a firing. Per-scope last_task_id updates are handled separately via UpdateScopeLastTaskIDs.

type Config

type Config struct {
	Store        Store
	TaskManager  taskmanager.Manager
	TaskStore    taskstore.Store
	PollInterval time.Duration
	FetchBatch   int
}

Config holds the configuration for a Dispatcher.

type Dispatcher

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

Dispatcher polls the task_schedule table and submits due tasks to the task manager.

func NewDispatcher

func NewDispatcher(cfg Config) *Dispatcher

NewDispatcher creates a new Dispatcher.

func (*Dispatcher) FireNow

func (d *Dispatcher) FireNow(
	ctx context.Context,
	id uuid.UUID,
) ([]uuid.UUID, error)

FireNow fires a schedule immediately, used by TriggerTaskSchedule. It submits tasks for all scopes unconditionally (no overlap check — explicit trigger overrides the policy). Returns an error if called on a one-time schedule that has already fired.

Serialization

FireNow uses the same three-phase structure as fire() and acquires a blocking FOR UPDATE lock in Phase 1 (rather than the SKIP LOCKED used by the poller). This serializes:

  • Two concurrent FireNow calls: the second blocks on LockForTrigger until the first's Phase 1 commits, then re-reads the updated row.
  • FireNow racing fire(): if the poller wins the lock first, FireNow blocks until Phase 1 commits; if FireNow wins, the poller's SKIP LOCKED returns nil (row no longer due after applyAfterFire) and skips the schedule.

func (*Dispatcher) Start

func (d *Dispatcher) Start(ctx context.Context) error

Start launches the polling loop. It returns immediately; the loop runs in a background goroutine until Stop is called or ctx is cancelled. Start is idempotent: subsequent calls after the first are no-ops.

func (*Dispatcher) Stop

func (d *Dispatcher) Stop()

Stop halts the polling loop and waits for it to exit. If Start was never called, Stop returns immediately. Stop may be called concurrently; all callers unblock once the loop exits.

type ListOptions

type ListOptions struct {
	// RackIDs, when non-empty, restricts results to schedules whose scope
	// includes at least one of the given racks.
	RackIDs []uuid.UUID
	// EnabledOnly, when true, excludes paused schedules from results.
	EnabledOnly bool
	// Pagination, when non-nil, applies offset/limit to the result set.
	Pagination *dbquery.Pagination
}

ListOptions filters results from List.

type PostgresStore

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

PostgresStore implements Store using PostgreSQL via bun.

func NewPostgresStore

func NewPostgresStore(pg *cdb.Session) *PostgresStore

NewPostgresStore creates a new PostgreSQL-backed task schedule store.

func (*PostgresStore) Create

func (s *PostgresStore) Create(
	ctx context.Context,
	ts *dbmodel.TaskSchedule,
) (uuid.UUID, error)

Create implements Store.

func (*PostgresStore) CreateScopes

func (s *PostgresStore) CreateScopes(
	ctx context.Context,
	scopes []*dbmodel.TaskScheduleScope,
) error

CreateScopes implements Store.

func (*PostgresStore) Delete

func (s *PostgresStore) Delete(ctx context.Context, id uuid.UUID) error

Delete implements Store.

func (*PostgresStore) DeleteScope

func (s *PostgresStore) DeleteScope(
	ctx context.Context,
	scopeID uuid.UUID,
) error

DeleteScope implements Store.

func (*PostgresStore) Disable

func (s *PostgresStore) Disable(ctx context.Context, id uuid.UUID) error

Disable implements Store.

func (*PostgresStore) FetchDue

func (s *PostgresStore) FetchDue(
	ctx context.Context, batchSize int, now time.Time,
) ([]uuid.UUID, error)

FetchDue implements Store.

func (*PostgresStore) Get

Get implements Store.

func (*PostgresStore) GetScope

func (s *PostgresStore) GetScope(
	ctx context.Context,
	scopeID uuid.UUID,
) (*dbmodel.TaskScheduleScope, error)

GetScope implements Store.

func (*PostgresStore) List

func (s *PostgresStore) List(
	ctx context.Context,
	opts ListOptions,
) ([]*dbmodel.TaskSchedule, int32, error)

List implements Store.

func (*PostgresStore) ListScopes

func (s *PostgresStore) ListScopes(
	ctx context.Context,
	scheduleID uuid.UUID,
) ([]*dbmodel.TaskScheduleScope, error)

ListScopes implements Store.

func (*PostgresStore) LockForFire

func (s *PostgresStore) LockForFire(
	ctx context.Context,
	id uuid.UUID,
	now time.Time,
) (*dbmodel.TaskSchedule, error)

LockForFire implements Store.

func (*PostgresStore) LockForTrigger

func (s *PostgresStore) LockForTrigger(
	ctx context.Context,
	id uuid.UUID,
) (*dbmodel.TaskSchedule, error)

LockForTrigger implements Store.

func (*PostgresStore) Resume

func (s *PostgresStore) Resume(
	ctx context.Context, id uuid.UUID, nextRunAt *time.Time,
) (*dbmodel.TaskSchedule, error)

Resume implements Store.

func (*PostgresStore) RunInTransaction

func (s *PostgresStore) RunInTransaction(
	ctx context.Context,
	fn func(ctx context.Context) error,
) error

RunInTransaction implements Store.

func (*PostgresStore) SetEnabled

func (s *PostgresStore) SetEnabled(
	ctx context.Context, id uuid.UUID, enabled bool,
) (*dbmodel.TaskSchedule, error)

SetEnabled implements Store.

func (*PostgresStore) Update

func (s *PostgresStore) Update(
	ctx context.Context,
	id uuid.UUID,
	fields UpdateFields,
) (*dbmodel.TaskSchedule, error)

Update implements Store.

func (*PostgresStore) UpdateAfterFire

func (s *PostgresStore) UpdateAfterFire(
	ctx context.Context,
	id uuid.UUID,
	u AfterFireUpdate,
) error

UpdateAfterFire implements Store.

func (*PostgresStore) UpdateScopeComponentFilter

func (s *PostgresStore) UpdateScopeComponentFilter(
	ctx context.Context,
	scopeID uuid.UUID,
	componentFilter json.RawMessage,
) error

UpdateScopeComponentFilter implements Store.

func (*PostgresStore) UpdateScopeLastTaskIDs

func (s *PostgresStore) UpdateScopeLastTaskIDs(
	ctx context.Context,
	scopeTaskIDs map[uuid.UUID]uuid.UUID,
) error

UpdateScopeLastTaskIDs implements Store.

type Store

type Store interface {
	// Create inserts a new TaskSchedule row and returns the DB-generated ID.
	Create(ctx context.Context, ts *dbmodel.TaskSchedule) (uuid.UUID, error)

	// Get returns the TaskSchedule with the given ID, or an error if not found.
	Get(ctx context.Context, id uuid.UUID) (*dbmodel.TaskSchedule, error)

	// List returns schedules matching opts, along with the total count before
	// pagination is applied (useful for building paginated API responses).
	List(ctx context.Context, opts ListOptions) ([]*dbmodel.TaskSchedule, int32, error)

	// Update applies non-zero fields from UpdateFields to the schedule and
	// returns the updated row.
	Update(ctx context.Context, id uuid.UUID, fields UpdateFields) (*dbmodel.TaskSchedule, error)

	// SetEnabled sets the enabled flag on a schedule and returns the updated row.
	// Use this for pause operations rather than Update to make intent clear.
	SetEnabled(ctx context.Context, id uuid.UUID, enabled bool) (*dbmodel.TaskSchedule, error)

	// Disable terminally deactivates a schedule by setting enabled=false and
	// next_run_at=NULL while preserving last_run_at.
	Disable(ctx context.Context, id uuid.UUID) error

	// Resume sets enabled=true and, for interval/cron schedules, atomically
	// updates next_run_at in the same statement. Pass nil nextRunAt for
	// one-time schedules that were paused before firing (next_run_at unchanged).
	Resume(ctx context.Context, id uuid.UUID, nextRunAt *time.Time) (*dbmodel.TaskSchedule, error)

	// Delete permanently removes the schedule row. Associated scope rows are
	// removed automatically via ON DELETE CASCADE on the FK constraint.
	// Returns an error if no row with the given ID exists.
	Delete(ctx context.Context, id uuid.UUID) error

	// RunInTransaction executes fn within a database transaction. The transaction
	// is propagated through ctx so nested Store calls participate in it automatically.
	// fn must use the ctx it receives, not the outer ctx.
	RunInTransaction(ctx context.Context, fn func(ctx context.Context) error) error

	// FetchDue returns the IDs of up to batchSize enabled schedules whose
	// next_run_at is at or before now, ordered by next_run_at ascending.
	// This is a read-only scan with no row locking; use LockForFire inside a
	// transaction to claim individual rows before firing.
	FetchDue(ctx context.Context, batchSize int, now time.Time) ([]uuid.UUID, error)

	// LockForFire attempts SELECT ... FOR UPDATE SKIP LOCKED on the schedule row.
	// Returns the locked row if it is still enabled and due at now.
	// Returns nil (no error) if the row was already locked by another instance
	// or is no longer due (e.g. another instance already advanced it).
	// Must be called within a RunInTransaction block.
	LockForFire(ctx context.Context, id uuid.UUID, now time.Time) (*dbmodel.TaskSchedule, error)

	// LockForTrigger acquires a blocking SELECT ... FOR UPDATE lock on the row.
	// Unlike LockForFire it does not filter by enabled or next_run_at, and it
	// blocks (no SKIP LOCKED) so concurrent FireNow calls and a racing poller
	// all serialize against the same row lock. Returns an error if the row does
	// not exist.
	// Must be called within a RunInTransaction block.
	LockForTrigger(ctx context.Context, id uuid.UUID) (*dbmodel.TaskSchedule, error)

	// UpdateAfterFire writes back last_run_at, next_run_at, and enabled
	// after a successful firing. next_run_at is set to NULL when AfterFireUpdate.NextRunAt
	// is nil, which marks a one-time schedule as fully consumed.
	// Must be called within a RunInTransaction block.
	UpdateAfterFire(ctx context.Context, id uuid.UUID, u AfterFireUpdate) error

	// CreateScopes bulk-inserts scope rows. The ScheduleID field must be set on
	// each row before calling. A no-op if scopes is empty.
	CreateScopes(ctx context.Context, scopes []*dbmodel.TaskScheduleScope) error

	// ListScopes returns all scope rows for the given schedule, ordered by created_at ascending.
	// Returns an error if no schedule with the given ID exists.
	ListScopes(ctx context.Context, scheduleID uuid.UUID) ([]*dbmodel.TaskScheduleScope, error)

	// GetScope fetches a single scope row by its ID.
	// Returns an error if no row with the given ID exists.
	GetScope(ctx context.Context, scopeID uuid.UUID) (*dbmodel.TaskScheduleScope, error)

	// DeleteScope removes a single scope row by its ID.
	// Returns an error if no row with the given ID exists.
	DeleteScope(ctx context.Context, scopeID uuid.UUID) error

	// UpdateScopeLastTaskIDs sets last_task_id on each scope row in the map.
	// Keyed by scope ID; the value is the task ID produced by the most recent firing.
	// Must be called within a RunInTransaction block.
	UpdateScopeLastTaskIDs(ctx context.Context, scopeTaskIDs map[uuid.UUID]uuid.UUID) error

	// UpdateScopeComponentFilter replaces the component_filter JSONB on a scope row.
	// componentFilter must be nil or a value produced by dbmodel.MarshalComponentFilter;
	// passing arbitrary JSON bypasses the kind/field validation enforced by that function.
	// Pass nil to clear the filter, which causes the dispatcher to target all
	// components in the rack.
	UpdateScopeComponentFilter(ctx context.Context, scopeID uuid.UUID, componentFilter json.RawMessage) error
}

Store is the persistence layer for task schedules and their scopes.

Methods that must run inside a transaction are documented with "Must be called within a RunInTransaction block." Calling them outside a transaction is safe but will use auto-commit semantics.

type TaskTemplate

type TaskTemplate struct {
	Type             taskcommon.TaskType `json:"type"`
	Code             string              `json:"code"`
	Info             json.RawMessage     `json:"information"`
	ConflictStrategy int                 `json:"conflict_strategy,omitempty"`
	QueueTimeoutSecs int64               `json:"queue_timeout_secs,omitempty"`
	RuleID           string              `json:"rule_id,omitempty"`
}

TaskTemplate is the JSON-serialized operation stored in task_schedule.operation_template. It carries the operation type, code, and info needed to reconstruct an operation.Request at fire time. The target is resolved from task_schedule_scope rows at fire time, so it is not stored here.

type TemplateOptions

type TemplateOptions struct {
	// ConflictStrategy is operation.ConflictStrategy stored as its underlying
	// int value. 0 = ConflictStrategyReject (default), 1 = ConflictStrategyQueue.
	ConflictStrategy int
	// QueueTimeoutSecs is operation.Request.QueueTimeout expressed in seconds.
	// Zero means use the server default.
	QueueTimeoutSecs int64
	// RuleID is the override rule UUID as a string. Empty string means no override.
	RuleID string
}

TemplateOptions holds the scheduling-policy fields stored alongside the operation in a TaskTemplate. They are passed in at creation time and restored at fire time to reconstruct the full operation.Request.

func OptionsFromTemplate

func OptionsFromTemplate(raw json.RawMessage) (TemplateOptions, error)

OptionsFromTemplate extracts the scheduling-policy fields from a stored TaskTemplate JSON blob. These are restored at fire time to reconstruct the full operation.Request (conflict strategy, queue timeout, rule override).

type UpdateFields

type UpdateFields struct {
	// Name, when non-empty, replaces the schedule's display name.
	Name string
	// SpecType, when non-empty, replaces the scheduling mechanism (interval/cron/one-time).
	SpecType dbmodel.SpecType
	// Spec, when non-empty, replaces the raw spec string (duration, cron expression, or RFC3339 timestamp).
	Spec string
	// Timezone, when non-empty, replaces the IANA timezone used to interpret cron specs.
	Timezone string
	// OverlapPolicy, when non-empty, replaces how the schedule behaves when the previous run is still active.
	OverlapPolicy dbmodel.OverlapPolicy
	// NextRunAt, when non-nil, replaces the next scheduled firing time.
	// Typically set together with Spec/SpecType when the spec changes.
	NextRunAt *time.Time
}

UpdateFields carries the mutable fields for Update. Only non-zero fields are applied; zero values are left unchanged in the DB.

Jump to

Keyboard shortcuts

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