package webui import ( "context" "encoding/json" "errors" "log/slog" "net/http" "time" "github.com/samcharles93/archie-core/internal/domain/org" "github.com/samcharles93/archie-core/internal/domain/scheduling" "github.com/samcharles93/archie-core/internal/domain/storecontract" ) // ScheduleStore is the State Store's schedule contract as the dashboard uses // it. type ScheduleStore interface { ListSchedules(ctx context.Context) ([]scheduling.Schedule, error) GetSchedule(ctx context.Context, id string) (scheduling.Schedule, error) PutSchedule(ctx context.Context, s scheduling.Schedule) (scheduling.Schedule, error) DeleteSchedule(ctx context.Context, id string) error RequestScheduleRun(ctx context.Context, id string) (scheduling.Run, error) ListScheduleRuns(ctx context.Context, scheduleID string, limit int) ([]scheduling.Run, error) } // scheduleRunsShown is how many runs the runs page lists. const scheduleRunsShown = 100 type scheduleOwnerView struct { Kind scheduling.OwnerKind `json:"kind"` ID string `json:"id,omitempty"` // Name is the owning org's name, resolved here so the dashboard never // stores or invents one. Name string `json:"name,omitempty"` } type scheduleRunView struct { ID int64 `json:"id"` ScheduleID string `json:"schedule_id"` ScheduledFor time.Time `json:"scheduled_for"` Started *time.Time `json:"started,omitempty"` Finished *time.Time `json:"finished,omitempty"` Result scheduling.RunResult `json:"result"` Error string `json:"error,omitempty"` TaskIDs []int64 `json:"task_ids,omitempty"` } type scheduleView struct { ID string `json:"id"` Name string `json:"name"` Owner scheduleOwnerView `json:"owner"` Enabled bool `json:"enabled"` BuiltIn bool `json:"built_in"` Timing scheduling.Timing `json:"timing"` NextRun *time.Time `json:"next_run,omitempty"` LastRun *scheduleRunView `json:"last_run,omitempty"` } // scheduleInput is what the dashboard may set on a schedule. Owner and // built-in are the store's to decide. type scheduleInput struct { Name string `json:"name"` Enabled bool `json:"enabled"` Timing scheduling.Timing `json:"timing"` } func optionalTime(t time.Time) *time.Time { if t.IsZero() { return nil } return &t } func runView(r scheduling.Run) scheduleRunView { return scheduleRunView{ ID: r.ID, ScheduleID: r.ScheduleID, ScheduledFor: r.ScheduledFor, Started: optionalTime(r.Started), Finished: optionalTime(r.Finished), Result: r.Result, Error: r.Error, } } // schedulesAPI owns the /api/schedules routes. They are org-scoped, not // instance-only: the system org sees every schedule, any other org only its // own, and the handlers enforce that ownership. type schedulesAPI struct { schedules ScheduleStore orgs org.API dispatches storecontract.DispatchLedger log *slog.Logger authorize func(http.ResponseWriter, *http.Request) bool } func newSchedulesAPI(s *Server) *schedulesAPI { return &schedulesAPI{schedules: s.Schedules, orgs: s.Orgs, dispatches: s.Dispatches, log: s.Log, authorize: s.authorizeTaskMutation} } func (a *schedulesAPI) register(mux *http.ServeMux) { mux.HandleFunc("GET /api/schedules", a.handleSchedules) mux.HandleFunc("PUT /api/schedules/{id}", a.handleSchedulePut) mux.HandleFunc("DELETE /api/schedules/{id}", a.handleScheduleDelete) mux.HandleFunc("GET /api/schedules/{id}/runs", a.handleScheduleRuns) mux.HandleFunc("POST /api/schedules/{id}/runs", a.handleScheduleRunNow) } func (a *schedulesAPI) ownerView(ctx context.Context, owner scheduling.Owner, names map[org.OrgID]string) scheduleOwnerView { view := scheduleOwnerView{Kind: owner.Kind, ID: owner.ID} id := org.OrgID(owner.ID) if owner.Kind == scheduling.OwnerInstance { id = org.DefaultOrgID } name, ok := names[id] if !ok && a.orgs != nil { if found, err := a.orgs.GetOrg(ctx, id); err == nil { name = found.Name } names[id] = name } view.Name = name return view } func (a *schedulesAPI) scheduleView(ctx context.Context, sched scheduling.Schedule, names map[org.OrgID]string) scheduleView { view := scheduleView{ ID: sched.ID, Name: sched.Name, Owner: a.ownerView(ctx, sched.Owner, names), Enabled: sched.Enabled, BuiltIn: sched.BuiltIn, Timing: sched.Timing, NextRun: optionalTime(sched.NextRun), } if sched.LastRun != nil { last := runView(*sched.LastRun) view.LastRun = &last } return view } func (a *schedulesAPI) scheduleError(ctx context.Context, w http.ResponseWriter, op string, err error) { switch { case errors.Is(err, scheduling.ErrNotFound): http.Error(w, "schedule not found", http.StatusNotFound) case errors.Is(err, scheduling.ErrBuiltIn): http.Error(w, scheduling.ErrBuiltIn.Error(), http.StatusConflict) case errors.Is(err, scheduling.ErrInvalidSpec): http.Error(w, err.Error(), http.StatusBadRequest) default: a.log.ErrorContext(ctx, op, "err", err) http.Error(w, op+" failed", http.StatusInternalServerError) } } func (a *schedulesAPI) schedulesReady(w http.ResponseWriter) bool { if a.schedules == nil { http.Error(w, "schedules unavailable", http.StatusServiceUnavailable) return false } return true } // scheduleScope is the org a schedule request acts in and whether that org is // the system org, which operates the instance. A request without a principal // is an install without the access chain, whose operator is the system org. func scheduleScope(r *http.Request) (org.OrgID, bool) { id := org.OrgFromContext(r.Context()) return id, id == org.DefaultOrgID } // scheduleOwned reports whether the acting org may see and change sched. The // system org operates the instance and may act on every schedule; any other // org only on the schedules it owns, and another org's or the instance's // schedule reads as absent to it. func scheduleOwned(instance bool, orgID org.OrgID, sched scheduling.Schedule) bool { if instance { return true } return sched.Owner.Kind == scheduling.OwnerOrg && sched.Owner.ID == string(orgID) } // ownedSchedule reads the named schedule and reports whether the acting org // owns it, answering not found when it does not exist or belongs elsewhere. func (a *schedulesAPI) ownedSchedule(w http.ResponseWriter, r *http.Request, id string) (scheduling.Schedule, bool) { orgID, instance := scheduleScope(r) sched, err := a.schedules.GetSchedule(r.Context(), id) switch { case errors.Is(err, scheduling.ErrNotFound): http.Error(w, "schedule not found", http.StatusNotFound) return scheduling.Schedule{}, false case err != nil: a.scheduleError(r.Context(), w, "get schedule", err) return scheduling.Schedule{}, false case !scheduleOwned(instance, orgID, sched): http.Error(w, "schedule not found", http.StatusNotFound) return scheduling.Schedule{}, false } return sched, true } func (a *schedulesAPI) handleSchedules(w http.ResponseWriter, r *http.Request) { if !a.schedulesReady(w) { return } list, err := a.schedules.ListSchedules(r.Context()) if err != nil { a.scheduleError(r.Context(), w, "list schedules", err) return } orgID, instance := scheduleScope(r) names := map[org.OrgID]string{} views := make([]scheduleView, 0, len(list)) for _, sched := range list { if !scheduleOwned(instance, orgID, sched) { continue } views = append(views, a.scheduleView(r.Context(), sched, names)) } writeJSON(w, map[string]any{"schedules": views}) } // handleSchedulePut creates the schedule or replaces what the dashboard may // change on it. A new schedule belongs to the instance when the system org // writes it and to the acting org otherwise; an existing schedule must be the // acting org's own. func (a *schedulesAPI) handleSchedulePut(w http.ResponseWriter, r *http.Request) { if !a.authorize(w, r) || !a.schedulesReady(w) { return } var input scheduleInput if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10)).Decode(&input); err != nil { http.Error(w, "invalid schedule", http.StatusBadRequest) return } id := r.PathValue("id") orgID, instance := scheduleScope(r) sched, err := a.schedules.GetSchedule(r.Context(), id) switch { case errors.Is(err, scheduling.ErrNotFound): owner := scheduling.Owner{Kind: scheduling.OwnerInstance} if !instance { owner = scheduling.Owner{Kind: scheduling.OwnerOrg, ID: string(orgID)} } sched = scheduling.Schedule{ID: id, Owner: owner} case err != nil: a.scheduleError(r.Context(), w, "get schedule", err) return case !scheduleOwned(instance, orgID, sched): http.Error(w, "schedule not found", http.StatusNotFound) return } sched.Name, sched.Enabled, sched.Timing = input.Name, input.Enabled, input.Timing saved, err := a.schedules.PutSchedule(r.Context(), sched) if err != nil { a.scheduleError(r.Context(), w, "save schedule", err) return } writeJSON(w, a.scheduleView(r.Context(), saved, map[org.OrgID]string{})) } func (a *schedulesAPI) handleScheduleDelete(w http.ResponseWriter, r *http.Request) { if !a.authorize(w, r) || !a.schedulesReady(w) { return } if _, ok := a.ownedSchedule(w, r, r.PathValue("id")); !ok { return } if err := a.schedules.DeleteSchedule(r.Context(), r.PathValue("id")); err != nil { a.scheduleError(r.Context(), w, "delete schedule", err) return } w.WriteHeader(http.StatusNoContent) } func (a *schedulesAPI) handleScheduleRunNow(w http.ResponseWriter, r *http.Request) { if !a.authorize(w, r) || !a.schedulesReady(w) { return } if _, ok := a.ownedSchedule(w, r, r.PathValue("id")); !ok { return } run, err := a.schedules.RequestScheduleRun(r.Context(), r.PathValue("id")) if err != nil { a.scheduleError(r.Context(), w, "run schedule", err) return } writeJSON(w, runView(run)) } // handleScheduleRuns lists a schedule's runs, each with the tasks its firing // started: the binding dispatches recorded against the run's capture. func (a *schedulesAPI) handleScheduleRuns(w http.ResponseWriter, r *http.Request) { if !a.schedulesReady(w) { return } if _, ok := a.ownedSchedule(w, r, r.PathValue("id")); !ok { return } runs, err := a.schedules.ListScheduleRuns(r.Context(), r.PathValue("id"), scheduleRunsShown) if err != nil { a.scheduleError(r.Context(), w, "list schedule runs", err) return } views := make([]scheduleRunView, 0, len(runs)) for _, run := range runs { view := runView(run) view.TaskIDs = a.runTasks(r.Context(), run.CaptureID) views = append(views, view) } writeJSON(w, map[string]any{"runs": views}) } func (a *schedulesAPI) runTasks(ctx context.Context, captureID string) []int64 { if captureID == "" || a.dispatches == nil { return nil } dispatches, err := a.dispatches.ListDispatches(ctx, storecontract.DispatchFilter{CaptureID: captureID, Limit: 50}) if err != nil { a.log.WarnContext(ctx, "schedule run tasks unavailable", "capture", captureID, "err", err) return nil } var ids []int64 for _, d := range dispatches { if d.TaskID != 0 { ids = append(ids, d.TaskID) } } return ids }