Files
archie/internal/infrastructure/staterpc/schedules.go
T
sam cc5789eb5f feat(scheduling): schedules and runs in the State Store with grid timing and run history
Schedules leave the schedules control-plane resource for State Store tables
behind a ScheduleService contract. A run is claimed per schedule slot, missed
slots fire once, the next run stays on the schedule's grid, cron is read in the
schedule-settings time zone, and failed runs are recorded and advance. Three
failures in a row raise a schedule.failing alert. A fired run records a
schedule-fired capture. Run history is pruned by age and count.

Removes the chat and spawn-task runners, the dangerous-payload guard and the
old schedules settings page.
2026-10-26 00:49:24 +11:00

339 lines
12 KiB
Go

// Schedules: the schedule and schedule-run RPCs. Task grants never reach
// them; the dashboard gates each call before it is made.
package staterpc
import (
"context"
"errors"
"time"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
"github.com/samcharles93/archie-core/internal/domain/scheduling"
)
var errSchedulesUnavailable = status.Error(codes.Unavailable, "schedule store unavailable")
type scheduleServer struct {
pb.UnimplementedScheduleServiceServer
*server
}
func scheduleStatus(err error) error {
switch {
case errors.Is(err, scheduling.ErrInvalidSpec):
return status.Error(codes.InvalidArgument, err.Error())
case errors.Is(err, scheduling.ErrNotFound):
return status.Error(codes.NotFound, scheduling.ErrNotFound.Error())
case errors.Is(err, scheduling.ErrBuiltIn):
return status.Error(codes.FailedPrecondition, scheduling.ErrBuiltIn.Error())
default:
return mapError(err)
}
}
func scheduleError(err error) error {
st, ok := status.FromError(err)
if !ok {
return err
}
switch st.Code() {
case codes.InvalidArgument:
return errors.Join(scheduling.ErrInvalidSpec, errors.New(st.Message()))
case codes.NotFound:
return scheduling.ErrNotFound
case codes.FailedPrecondition:
return scheduling.ErrBuiltIn
default:
return unmapError(err)
}
}
// location is the zone cron is read in, from the instance's settings.
func (s *scheduleServer) location(ctx context.Context) (*time.Location, error) {
if s.deps.ScheduleSettings == nil {
return time.UTC, nil
}
settings, err := s.deps.ScheduleSettings(ctx)
if err != nil {
s.deps.Log.WarnContext(ctx, "schedule settings unreadable", "err", err)
return nil, status.Error(codes.Unavailable, "schedule settings unreadable")
}
return settings.Location, nil
}
func (s *scheduleServer) ListSchedules(ctx context.Context, _ *pb.ListSchedulesRequest) (*pb.ListSchedulesResponse, error) {
if s.deps.Schedules == nil {
return nil, errSchedulesUnavailable
}
list, err := s.deps.Schedules.ListSchedules(ctx)
if err != nil {
return nil, s.logErr("ListSchedules", err)
}
return &pb.ListSchedulesResponse{Schedules: mapValues(list, scheduleProto)}, nil
}
func (s *scheduleServer) GetSchedule(ctx context.Context, r *pb.GetScheduleRequest) (*pb.GetScheduleResponse, error) {
if s.deps.Schedules == nil {
return nil, errSchedulesUnavailable
}
got, err := s.deps.Schedules.GetSchedule(ctx, r.GetId())
if err != nil {
return nil, scheduleStatus(err)
}
return &pb.GetScheduleResponse{Schedule: scheduleProto(got)}, nil
}
func (s *scheduleServer) PutSchedule(ctx context.Context, r *pb.PutScheduleRequest) (*pb.PutScheduleResponse, error) {
if s.deps.Schedules == nil {
return nil, errSchedulesUnavailable
}
loc, err := s.location(ctx)
if err != nil {
return nil, err
}
stored, err := s.deps.Schedules.PutSchedule(ctx, scheduleValue(r.GetSchedule()), loc)
if err != nil {
return nil, scheduleStatus(err)
}
return &pb.PutScheduleResponse{Schedule: scheduleProto(stored)}, nil
}
func (s *scheduleServer) DeleteSchedule(ctx context.Context, r *pb.DeleteScheduleRequest) (*pb.DeleteScheduleResponse, error) {
if s.deps.Schedules == nil {
return nil, errSchedulesUnavailable
}
if err := s.deps.Schedules.DeleteSchedule(ctx, r.GetId()); err != nil {
return nil, scheduleStatus(err)
}
return &pb.DeleteScheduleResponse{}, nil
}
func (s *scheduleServer) EnsureBuiltinSchedules(ctx context.Context, r *pb.EnsureBuiltinSchedulesRequest) (*pb.EnsureBuiltinSchedulesResponse, error) {
if s.deps.Schedules == nil {
return nil, errSchedulesUnavailable
}
loc, err := s.location(ctx)
if err != nil {
return nil, err
}
builtins := mapValues(r.GetBuiltins(), func(b *pb.BuiltinSchedule) scheduling.Builtin {
return scheduling.Builtin{ID: b.GetId(), Name: b.GetName(), Interval: time.Duration(b.GetIntervalSeconds()) * time.Second}
})
if err := s.deps.Schedules.EnsureBuiltins(ctx, builtins, loc); err != nil {
return nil, s.logErr("EnsureBuiltinSchedules", err)
}
return &pb.EnsureBuiltinSchedulesResponse{}, nil
}
func (s *scheduleServer) ClaimDueRuns(ctx context.Context, r *pb.ClaimDueRunsRequest) (*pb.ClaimDueRunsResponse, error) {
if s.deps.ScheduleRuns == nil {
return nil, errSchedulesUnavailable
}
loc, err := s.location(ctx)
if err != nil {
return nil, err
}
claims, err := s.deps.ScheduleRuns.ClaimDue(ctx, timeValue(r.GetNow()), time.Duration(r.GetStaleSeconds())*time.Second, loc)
if err != nil {
return nil, s.logErr("ClaimDueRuns", err)
}
return &pb.ClaimDueRunsResponse{Claims: mapValues(claims, func(c scheduling.Claim) *pb.ScheduleClaim {
return &pb.ScheduleClaim{Run: scheduleRunProto(c.Run), Name: c.Name, BuiltIn: c.BuiltIn}
})}, nil
}
func (s *scheduleServer) RequestScheduleRun(ctx context.Context, r *pb.RequestScheduleRunRequest) (*pb.RequestScheduleRunResponse, error) {
if s.deps.ScheduleRuns == nil {
return nil, errSchedulesUnavailable
}
run, err := s.deps.ScheduleRuns.RequestRun(ctx, r.GetId(), time.Now())
if err != nil {
return nil, scheduleStatus(err)
}
return &pb.RequestScheduleRunResponse{Run: scheduleRunProto(run)}, nil
}
func (s *scheduleServer) FinishScheduleRun(ctx context.Context, r *pb.FinishScheduleRunRequest) (*pb.FinishScheduleRunResponse, error) {
if s.deps.ScheduleRuns == nil {
return nil, errSchedulesUnavailable
}
switch scheduling.RunResult(r.GetResult()) {
case scheduling.RunSucceeded, scheduling.RunFailed, scheduling.RunSkipped:
default:
return nil, status.Errorf(codes.InvalidArgument, "result %q is not a finished result", r.GetResult())
}
streak, err := s.deps.ScheduleRuns.FinishRun(ctx, r.GetRunId(), scheduling.RunResult(r.GetResult()), r.GetError(), time.Now())
if err != nil {
return nil, scheduleStatus(err)
}
return &pb.FinishScheduleRunResponse{FailureStreak: int64(streak)}, nil
}
func (s *scheduleServer) SetScheduleRunCapture(ctx context.Context, r *pb.SetScheduleRunCaptureRequest) (*pb.SetScheduleRunCaptureResponse, error) {
if s.deps.ScheduleRuns == nil {
return nil, errSchedulesUnavailable
}
if err := s.deps.ScheduleRuns.SetRunCapture(ctx, r.GetRunId(), r.GetCaptureId()); err != nil {
return nil, scheduleStatus(err)
}
return &pb.SetScheduleRunCaptureResponse{}, nil
}
func (s *scheduleServer) ListScheduleRuns(ctx context.Context, r *pb.ListScheduleRunsRequest) (*pb.ListScheduleRunsResponse, error) {
if s.deps.Schedules == nil {
return nil, errSchedulesUnavailable
}
runs, err := s.deps.Schedules.ListRuns(ctx, r.GetScheduleId(), int(r.GetLimit()))
if err != nil {
return nil, s.logErr("ListScheduleRuns", err)
}
return &pb.ListScheduleRunsResponse{Runs: mapValues(runs, scheduleRunProto)}, nil
}
func scheduleProto(s scheduling.Schedule) *pb.Schedule {
out := &pb.Schedule{
Id: s.ID, Name: s.Name,
Owner: &pb.ScheduleOwner{Kind: string(s.Owner.Kind), Id: s.Owner.ID},
Enabled: s.Enabled, BuiltIn: s.BuiltIn,
Timing: &pb.ScheduleTiming{
Kind: s.Timing.Kind, IntervalSeconds: int64(s.Timing.Interval.Std() / time.Second),
Cron: s.Timing.Cron, Start: timestamp(s.Timing.Start),
},
NextRun: timestamp(s.NextRun), Created: timestamp(s.Created), Updated: timestamp(s.Updated),
}
if s.Timing.At != nil {
out.Timing.At = timestamp(*s.Timing.At)
}
if s.LastRun != nil {
out.LastRun = scheduleRunProto(*s.LastRun)
}
return out
}
func scheduleValue(p *pb.Schedule) scheduling.Schedule {
t := p.GetTiming()
s := scheduling.Schedule{
ID: p.GetId(), Name: p.GetName(),
Owner: scheduling.Owner{Kind: scheduling.OwnerKind(p.GetOwner().GetKind()), ID: p.GetOwner().GetId()},
Enabled: p.GetEnabled(), BuiltIn: p.GetBuiltIn(),
Timing: scheduling.Timing{
Kind: t.GetKind(), Interval: scheduling.Duration(time.Duration(t.GetIntervalSeconds()) * time.Second),
Cron: t.GetCron(), Start: timeValue(t.GetStart()),
},
NextRun: timeValue(p.GetNextRun()), Created: timeValue(p.GetCreated()), Updated: timeValue(p.GetUpdated()),
}
if t.GetAt() != nil {
at := timeValue(t.GetAt())
s.Timing.At = &at
}
if p.GetLastRun() != nil {
run := scheduleRunValue(p.GetLastRun())
s.LastRun = &run
}
return s
}
func scheduleRunProto(r scheduling.Run) *pb.ScheduleRun {
return &pb.ScheduleRun{
Id: r.ID, ScheduleId: r.ScheduleID, ScheduledFor: timestamp(r.ScheduledFor),
Started: timestamp(r.Started), Finished: timestamp(r.Finished),
Result: string(r.Result), Error: r.Error, CaptureId: r.CaptureID,
}
}
func scheduleRunValue(p *pb.ScheduleRun) scheduling.Run {
return scheduling.Run{
ID: p.GetId(), ScheduleID: p.GetScheduleId(), ScheduledFor: timeValue(p.GetScheduledFor()),
Started: timeValue(p.GetStarted()), Finished: timeValue(p.GetFinished()),
Result: scheduling.RunResult(p.GetResult()), Error: p.GetError(), CaptureID: p.GetCaptureId(),
}
}
// ListSchedules lists every schedule with its latest run.
func (c *Client) ListSchedules(ctx context.Context) ([]scheduling.Schedule, error) {
r, err := c.schedule.ListSchedules(ctx, &pb.ListSchedulesRequest{})
if err != nil {
return nil, scheduleError(err)
}
return mapValues(r.GetSchedules(), scheduleValue), nil
}
func (c *Client) GetSchedule(ctx context.Context, id string) (scheduling.Schedule, error) {
r, err := c.schedule.GetSchedule(ctx, &pb.GetScheduleRequest{Id: id})
if err != nil {
return scheduling.Schedule{}, scheduleError(err)
}
return scheduleValue(r.GetSchedule()), nil
}
func (c *Client) PutSchedule(ctx context.Context, s scheduling.Schedule) (scheduling.Schedule, error) {
r, err := c.schedule.PutSchedule(ctx, &pb.PutScheduleRequest{Schedule: scheduleProto(s)})
if err != nil {
return scheduling.Schedule{}, scheduleError(err)
}
return scheduleValue(r.GetSchedule()), nil
}
func (c *Client) DeleteSchedule(ctx context.Context, id string) error {
_, err := c.schedule.DeleteSchedule(ctx, &pb.DeleteScheduleRequest{Id: id})
return scheduleError(err)
}
// EnsureBuiltinSchedules inserts each missing built-in schedule and leaves
// existing ones as the operator set them.
func (c *Client) EnsureBuiltinSchedules(ctx context.Context, builtins []scheduling.Builtin) error {
_, err := c.schedule.EnsureBuiltinSchedules(ctx, &pb.EnsureBuiltinSchedulesRequest{
Builtins: mapValues(builtins, func(b scheduling.Builtin) *pb.BuiltinSchedule {
return &pb.BuiltinSchedule{Id: b.ID, Name: b.Name, IntervalSeconds: int64(b.Interval / time.Second)}
}),
})
return scheduleError(err)
}
// ClaimDueRuns claims the runs due at now; see scheduling.Store.ClaimDue.
func (c *Client) ClaimDueRuns(ctx context.Context, now time.Time, stale time.Duration) ([]scheduling.Claim, error) {
r, err := c.schedule.ClaimDueRuns(ctx, &pb.ClaimDueRunsRequest{Now: timestamp(now), StaleSeconds: int64(stale / time.Second)})
if err != nil {
return nil, scheduleError(err)
}
return mapValues(r.GetClaims(), func(p *pb.ScheduleClaim) scheduling.Claim {
return scheduling.Claim{Run: scheduleRunValue(p.GetRun()), Name: p.GetName(), BuiltIn: p.GetBuiltIn()}
}), nil
}
// RequestScheduleRun queues a run of id now.
func (c *Client) RequestScheduleRun(ctx context.Context, id string) (scheduling.Run, error) {
r, err := c.schedule.RequestScheduleRun(ctx, &pb.RequestScheduleRunRequest{Id: id})
if err != nil {
return scheduling.Run{}, scheduleError(err)
}
return scheduleRunValue(r.GetRun()), nil
}
// FinishScheduleRun records a run's result and returns the schedule's
// failure streak.
func (c *Client) FinishScheduleRun(ctx context.Context, runID int64, result scheduling.RunResult, errText string) (int, error) {
r, err := c.schedule.FinishScheduleRun(ctx, &pb.FinishScheduleRunRequest{RunId: runID, Result: string(result), Error: errText})
if err != nil {
return 0, scheduleError(err)
}
return int(r.GetFailureStreak()), nil
}
// SetScheduleRunCapture records the schedule-fired capture a run recorded.
func (c *Client) SetScheduleRunCapture(ctx context.Context, runID int64, captureID string) error {
_, err := c.schedule.SetScheduleRunCapture(ctx, &pb.SetScheduleRunCaptureRequest{RunId: runID, CaptureId: captureID})
return scheduleError(err)
}
func (c *Client) ListScheduleRuns(ctx context.Context, scheduleID string, limit int) ([]scheduling.Run, error) {
r, err := c.schedule.ListScheduleRuns(ctx, &pb.ListScheduleRunsRequest{ScheduleId: scheduleID, Limit: int32(limit)})
if err != nil {
return nil, scheduleError(err)
}
return mapValues(r.GetRuns(), scheduleRunValue), nil
}