package pipeline import ( "context" "git.a-wan.net/alan/pipelines/internal/protocol" "time" ) func (s *Store) initSchedules() error { _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS schedule_state ( pipeline_id INTEGER NOT NULL REFERENCES pipelines(id), version INTEGER NOT NULL, slot INTEGER NOT NULL, next_due TEXT NOT NULL, PRIMARY KEY(pipeline_id,version,slot)); CREATE TABLE IF NOT EXISTS schedule_events ( id INTEGER PRIMARY KEY, pipeline_id INTEGER NOT NULL, version INTEGER NOT NULL, slot INTEGER NOT NULL, due TEXT NOT NULL, status TEXT NOT NULL, diagnostic TEXT NOT NULL DEFAULT '', run_id INTEGER, UNIQUE(pipeline_id,version,slot,due));`) return err } func (s *Store) ScheduleDue(ctx context.Context, d *protocol.PipelineDetail, slot int, rule protocol.Schedule, now time.Time) (time.Time, error) { next, err := NextSchedule(rule, now) if err != nil { return time.Time{}, err } _, err = s.db.ExecContext(ctx, `INSERT INTO schedule_state(pipeline_id,version,slot,next_due) VALUES(?,?,?,?) ON CONFLICT DO NOTHING`, d.ID, d.Version, slot, next.UTC().Format(time.RFC3339Nano)) if err != nil { return time.Time{}, err } var text string err = s.db.QueryRowContext(ctx, `SELECT next_due FROM schedule_state WHERE pipeline_id=? AND version=? AND slot=?`, d.ID, d.Version, slot).Scan(&text) if err != nil { return time.Time{}, err } return time.Parse(time.RFC3339Nano, text) } // Claim and advance before dispatch. A crash cannot replay the occurrence. // The latest-version check prevents an observed old schedule from starting after // it was replaced or removed by a newer submission. func (s *Store) ClaimSchedule(ctx context.Context, d *protocol.PipelineDetail, slot int, due, next time.Time, status string) (bool, error) { tx, err := s.db.BeginTx(ctx, nil) if err != nil { return false, err } defer tx.Rollback() result, err := tx.ExecContext(ctx, `UPDATE schedule_state SET next_due=? WHERE pipeline_id=? AND version=? AND slot=? AND next_due=? AND version=(SELECT MAX(version) FROM pipeline_versions WHERE pipeline_id=?)`, next.UTC().Format(time.RFC3339Nano), d.ID, d.Version, slot, due.UTC().Format(time.RFC3339Nano), d.ID) if err != nil { return false, err } n, err := result.RowsAffected() if err != nil || n == 0 { return false, err } _, err = tx.ExecContext(ctx, `INSERT INTO schedule_events(pipeline_id,version,slot,due,status) VALUES(?,?,?,?,?)`, d.ID, d.Version, slot, due.UTC().Format(time.RFC3339Nano), status) if err != nil { return false, err } return true, tx.Commit() } func (s *Store) FinishSchedule(ctx context.Context, d *protocol.PipelineDetail, slot int, due time.Time, status, diagnostic string, runID int64) error { _, err := s.db.ExecContext(ctx, `UPDATE schedule_events SET status=?,diagnostic=?,run_id=? WHERE pipeline_id=? AND version=? AND slot=? AND due=?`, status, diagnostic, runID, d.ID, d.Version, slot, due.UTC().Format(time.RFC3339Nano)) return err }