fc7dbb0ac0
Server: drop ntfy publishing (stage hooks, run outbox, chat attention, chat tool notify, auto-switch and schedule notices), the chat push outbox (its table is dropped at startup), ntfy status/endpoints and PIPELINES_NTFY_*. The app_notifications stream, subscribe/clear and kinds are unchanged. Notification settings keep run_finished/chat_needs_you/chat_reply_finished; ntfy_enabled is accepted and ignored and its stored row is never read. Stage type=ntfy is rejected: "ntfy stages were removed; notifications go to the Pipelines apps — use the stage notify hook". The notify hook remains. Installer: no ntfy build, accounts, config or supervisor child; manifest gets top-level "mode" (legacy ntfy.mode still read). Reinstall retires an old ntfy (safe PID-file stop, deletes binary, config, data dir, token, log, with a note in logs/install.log); uninstall cleans leftovers. App: ntfy settings section replaced by "Notification events"; texts updated. Docs: docs/ntfy.md folded into docs/notifications.md; install, docker, cli, author skill references updated; security review M1 marked resolved. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
215 lines
8.0 KiB
Go
215 lines
8.0 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"time"
|
|
|
|
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
|
"git.a-wan.net/alan/pipelines/internal/protocol"
|
|
)
|
|
|
|
func (r *runner) scheduleLoop() {
|
|
defer r.schedulerWG.Done()
|
|
// Admissions run beside the loop; shutdown waits for the ones it started.
|
|
defer r.scheduleAdmissions.Wait()
|
|
if err := r.scheduleTick(time.Now(), true); err != nil {
|
|
log.Printf("scheduler startup: %v", err)
|
|
}
|
|
ticker := time.NewTicker(time.Second)
|
|
defer ticker.Stop()
|
|
for {
|
|
select {
|
|
case <-r.ctx.Done():
|
|
return
|
|
case <-r.store.Done():
|
|
return
|
|
case <-ticker.C:
|
|
// Lateness is measured against the time of the claim, not the
|
|
// (possibly delayed) tick.
|
|
if err := r.scheduleTick(time.Now(), false); err != nil {
|
|
log.Printf("scheduler: %v", err)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// scheduleTick claims every enabled schedule due at now. A schedule that
|
|
// cannot be read or claimed is logged and skipped, never stopping the others.
|
|
// A claimed run is admitted on its own goroutine (scheduleAdmissions): run
|
|
// admission can take up to a minute (git worktree creation), and an inline
|
|
// start would make the next due schedule look missed by the time it is seen.
|
|
func (r *runner) scheduleTick(now time.Time, recovery bool) error {
|
|
items, err := r.store.ListSchedules(r.ctx, 0)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, item := range items {
|
|
if !item.Enabled {
|
|
continue
|
|
}
|
|
if err := r.claimSchedule(item, now, recovery); err != nil {
|
|
log.Printf("schedule id=%d pipeline=%d: %v", item.ID, item.PipelineID, err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (r *runner) claimSchedule(item protocol.SavedSchedule, now time.Time, recovery bool) error {
|
|
due, err := time.Parse(time.RFC3339Nano, item.NextDue)
|
|
if err != nil {
|
|
return fmt.Errorf("next due %q: %w", item.NextDue, err)
|
|
}
|
|
if due.After(now) {
|
|
return nil
|
|
}
|
|
next, err := pipeline.NextSchedule(item.Rule, now)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if item.Rule.Every != "" {
|
|
interval, err := time.ParseDuration(item.Rule.Every)
|
|
if err != nil || interval <= 0 {
|
|
return fmt.Errorf("interval %q is invalid", item.Rule.Every)
|
|
}
|
|
next = due.Add((now.Sub(due)/interval + 1) * interval)
|
|
}
|
|
status := "claimed"
|
|
if recovery || now.Sub(due) > 5*time.Second {
|
|
status = "skipped_missed"
|
|
}
|
|
loc, err := pipeline.ScheduleLocation(item.Rule)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !pipeline.ScheduleDay(item.Rule, due.In(loc)) {
|
|
status = "skipped_day"
|
|
}
|
|
claimed, err := r.store.ClaimSavedSchedule(r.ctx, item, due, next, status)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if claimed && status == "skipped_missed" {
|
|
name := scheduleLabel(item)
|
|
go r.scheduleNotice(item, due, "skipped", "Scheduled run skipped: "+name, fmt.Sprintf("%s was due at %s while the server was not running, so that run was skipped.", name, due.Local().Format("15:04 on 2 Jan")), "")
|
|
}
|
|
if !claimed || status != "claimed" {
|
|
return nil
|
|
}
|
|
r.scheduleAdmissions.Add(1)
|
|
go func() {
|
|
defer r.scheduleAdmissions.Done()
|
|
r.admitScheduled(item, due)
|
|
}()
|
|
return nil
|
|
}
|
|
|
|
// scheduleBusyRetry is how often, and for how long after its due time, a
|
|
// scheduled admission whose workspace another run holds is tried again
|
|
// (the limit counts from the first attempt).
|
|
// PIPELINES_SCHEDULE_BUSY_RETRY_EVERY and PIPELINES_SCHEDULE_BUSY_RETRY_FOR
|
|
// (Go durations; FOR=0 disables waiting) override the defaults.
|
|
var scheduleBusyRetry = func() (every, limit time.Duration) {
|
|
every, limit = 5*time.Minute, 2*time.Hour
|
|
if value, err := time.ParseDuration(os.Getenv("PIPELINES_SCHEDULE_BUSY_RETRY_EVERY")); err == nil && value > 0 {
|
|
every = value
|
|
}
|
|
if value, err := time.ParseDuration(os.Getenv("PIPELINES_SCHEDULE_BUSY_RETRY_FOR")); err == nil && value >= 0 {
|
|
limit = value
|
|
}
|
|
return every, limit
|
|
}
|
|
|
|
// scheduleNoticePriority is the notification stream's "low" priority.
|
|
const scheduleNoticePriority = 2
|
|
|
|
// admitScheduled starts one claimed schedule's run and records the outcome in
|
|
// the schedule's history. A workspace another run holds delays the admission
|
|
// instead of skipping it: it is tried again every few minutes for a bounded
|
|
// time, recorded as "delayed" meanwhile. The operator is told, at low
|
|
// priority, when a scheduled run is delayed and when one is skipped.
|
|
func (r *runner) admitScheduled(item protocol.SavedSchedule, due time.Time) {
|
|
request := protocol.Message{PipelineID: item.PipelineID, Version: item.Version, RequestKey: fmt.Sprintf("saved-schedule:%d:%d", item.ID, due.UnixNano()), Input: item.Input, Workspace: item.Workspace, WritePaths: item.WritePaths, AllowTools: item.AllowTools, Model: item.Model, StageModels: item.StageModels, NotifyMode: item.NotifyMode, Title: item.Title, OutputFormat: item.OutputFormat}
|
|
every, limit := scheduleBusyRetry()
|
|
started := time.Now()
|
|
deadline := started.Add(limit)
|
|
name := scheduleLabel(item)
|
|
diagnostic := ""
|
|
status := "started"
|
|
var runID int64
|
|
for attempt := 1; ; attempt++ {
|
|
run, err := r.startWithSchedule(request, &pipeline.ScheduleAdmission{ID: item.ID, Revision: item.Revision, Due: due, Name: item.Name})
|
|
if err == nil {
|
|
status, diagnostic = "started", ""
|
|
if run != nil {
|
|
runID = run.ID
|
|
}
|
|
if attempt > 1 {
|
|
diagnostic = fmt.Sprintf("started after waiting %s for a busy workspace", time.Since(started).Round(time.Second))
|
|
}
|
|
break
|
|
}
|
|
status, diagnostic = "skipped", err.Error()
|
|
var busy *workspaceBusyError
|
|
if !errors.As(err, &busy) {
|
|
break
|
|
}
|
|
if time.Now().Add(every).After(deadline) {
|
|
if attempt > 1 {
|
|
diagnostic = fmt.Sprintf("gave up after waiting %s for a busy workspace: %s", time.Since(started).Round(time.Second), diagnostic)
|
|
}
|
|
break
|
|
}
|
|
if attempt == 1 {
|
|
r.scheduleNotice(item, due, "delayed", "Scheduled run delayed: "+name,
|
|
fmt.Sprintf("%s is waiting for run #%d to free its workspace; it is tried again every %s until %s.", name, busy.runID, every, deadline.Local().Format("15:04")), runAttentionClick(busy.runID))
|
|
}
|
|
delayed := fmt.Sprintf("waiting for a busy workspace (attempt %d; retrying every %s until %s): %s", attempt, every, deadline.UTC().Format(time.RFC3339), err.Error())
|
|
if err := r.store.FinishSavedSchedule(r.ctx, item.ID, due, "delayed", delayed); err != nil {
|
|
log.Printf("schedule id=%d record delay: %v", item.ID, err)
|
|
}
|
|
log.Printf("schedule id=%d pipeline=%d due=%s delayed: %s", item.ID, item.PipelineID, due.Format(time.RFC3339), delayed)
|
|
timer := time.NewTimer(every)
|
|
select {
|
|
case <-timer.C:
|
|
continue
|
|
case <-r.ctx.Done():
|
|
timer.Stop()
|
|
diagnostic = "the server stopped while this run waited for a busy workspace: " + diagnostic
|
|
}
|
|
break
|
|
}
|
|
save, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 10*time.Second)
|
|
if err := r.store.FinishSavedSchedule(save, item.ID, due, status, diagnostic); err != nil {
|
|
log.Printf("schedule id=%d record admission: %v", item.ID, err)
|
|
}
|
|
cancel()
|
|
if status == "skipped" {
|
|
r.scheduleNotice(item, due, "skipped", "Scheduled run skipped: "+name, name+" did not start: "+diagnostic, "")
|
|
}
|
|
log.Printf("schedule id=%d pipeline=%d version=%d due=%s status=%s run=%d %s", item.ID, item.PipelineID, item.Version, due.Format(time.RFC3339), status, runID, diagnostic)
|
|
}
|
|
|
|
// scheduleLabel names a schedule in a notice.
|
|
func scheduleLabel(item protocol.SavedSchedule) string {
|
|
if name := singleLine(item.Name); name != "" {
|
|
return truncateUTF8(name, 120)
|
|
}
|
|
return fmt.Sprintf("Schedule %d", item.ID)
|
|
}
|
|
|
|
// scheduleNotice tells the operator, at low priority, through the app
|
|
// notification stream, that a scheduled run was
|
|
// delayed or skipped.
|
|
func (r *runner) scheduleNotice(item protocol.SavedSchedule, due time.Time, event, title, message, click string) {
|
|
ctx, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 30*time.Second)
|
|
defer cancel()
|
|
title, message = truncateUTF8(singleLine(title), 256), truncateUTF8(singleLine(message), 2000)
|
|
r.notes.record(ctx, pipeline.AppNotificationRecord{AppNotification: protocol.AppNotification{
|
|
ID: fmt.Sprintf("schedule:%d:%d:%s", item.ID, due.UnixNano(), event), Kind: protocol.NotificationSchedule,
|
|
Title: title, Message: message, Click: click, Priority: scheduleNoticePriority, Tags: []string{}, Group: fmt.Sprintf("schedule:%d", item.ID)}})
|
|
}
|