Merge: archive and unarchive pipelines

# Conflicts:
#	internal/cli/commands.go
#	internal/pipeline/store.go
This commit is contained in:
2026-11-04 23:39:02 +00:00
30 changed files with 1206 additions and 78 deletions
+140
View File
@@ -0,0 +1,140 @@
package pipeline
import (
"context"
"database/sql"
"fmt"
"strconv"
"strings"
"time"
)
// Archiving retires a pipeline from everyday lists without deleting anything:
// its versions, runs, artifacts and search history stay as they are, and its
// name stays reserved. Only the pipelines row carries the archived_at stamp.
func (s *Store) initArchive() error {
return s.addColumnIfMissing("pipelines", "archived_at", "TEXT")
}
// ArchivedError reports that a name or ID belongs to an archived pipeline.
type ArchivedError struct{ Name string }
func (e *ArchivedError) Error() string {
return fmt.Sprintf("pipeline %q is archived; unarchive it first (pipelines unarchive %s)", e.Name, quoteArg(e.Name))
}
func quoteArg(name string) string {
if strings.ContainsAny(name, " \t'\"\\$`") {
return "'" + strings.ReplaceAll(name, "'", `'\''`) + "'"
}
return name
}
// ResolvePipelineID finds a pipeline by exact name first, then by numeric ID,
// archived or not, matching the CLI's name-over-ID rule.
func (s *Store) ResolvePipelineID(ctx context.Context, id int64, name string) (int64, error) {
name = strings.TrimSpace(name)
if name != "" {
var found int64
err := s.db.QueryRowContext(ctx, `SELECT id FROM pipelines WHERE name=?`, name).Scan(&found)
if err == nil {
return found, nil
}
if err != sql.ErrNoRows {
return 0, err
}
if id == 0 {
id, _ = strconv.ParseInt(name, 10, 64)
}
if id <= 0 {
return 0, fmt.Errorf("pipeline %q not found", name)
}
}
if id <= 0 {
return 0, fmt.Errorf("a pipeline name or ID is required")
}
var found int64
err := s.db.QueryRowContext(ctx, `SELECT id FROM pipelines WHERE id=?`, id).Scan(&found)
if err == sql.ErrNoRows {
return 0, fmt.Errorf("pipeline not found")
}
return found, err
}
// SetArchived archives or unarchives one pipeline. A positive expectedVersion
// refuses the change when a newer version was published meanwhile. Archiving
// is refused while an enabled schedule still points at the pipeline, naming
// the schedules, so nothing silently stops firing; repeating a request that is
// already in effect is a no-op.
func (s *Store) SetArchived(ctx context.Context, id int64, archived bool, expectedVersion int, now time.Time) error {
if expectedVersion < 0 {
return fmt.Errorf("expected version must be nonnegative")
}
s.mu.Lock()
defer s.mu.Unlock()
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
var name string
var stamp sql.NullString
var latest int
err = tx.QueryRowContext(ctx, `SELECT p.name,p.archived_at,COALESCE((SELECT MAX(version) FROM pipeline_versions WHERE pipeline_id=p.id),0) FROM pipelines p WHERE p.id=?`, id).Scan(&name, &stamp, &latest)
if err == sql.ErrNoRows {
return fmt.Errorf("pipeline not found")
}
if err != nil {
return err
}
if expectedVersion > 0 && latest != expectedVersion {
return fmt.Errorf("pipeline %q changed: expected latest version %d, found %d; reload first", name, expectedVersion, latest)
}
if stamp.Valid == archived {
return tx.Commit()
}
if !archived {
if _, err = tx.ExecContext(ctx, `UPDATE pipelines SET archived_at=NULL WHERE id=?`, id); err != nil {
return err
}
return tx.Commit()
}
rows, err := tx.QueryContext(ctx, savedScheduleSelect+` WHERE pipeline_id=? AND deleted=0 AND enabled=1 ORDER BY id`, id)
if err != nil {
return err
}
var enabled []string
for rows.Next() {
item, err := scanSavedSchedule(rows)
if err != nil {
rows.Close()
return err
}
enabled = append(enabled, fmt.Sprintf("%q (#%d)", item.Name, item.ID))
}
err = rows.Err()
rows.Close()
if err != nil {
return err
}
if len(enabled) > 0 {
return fmt.Errorf("pipeline %q has enabled schedule(s) %s; pause or repoint them before archiving", name, strings.Join(enabled, ", "))
}
if _, err = tx.ExecContext(ctx, `UPDATE pipelines SET archived_at=? WHERE id=?`, now.UTC().Format(time.RFC3339), id); err != nil {
return err
}
return tx.Commit()
}
// archivedName reports whether the pipeline row is archived inside a
// transaction, so a submission or schedule edit cannot race an archive.
func archivedName(ctx context.Context, tx *sql.Tx, query string, arg any) (string, bool, error) {
var name string
var stamp sql.NullString
err := tx.QueryRowContext(ctx, `SELECT name,archived_at FROM pipelines WHERE `+query, arg).Scan(&name, &stamp)
if err == sql.ErrNoRows {
return "", false, nil
}
return name, stamp.Valid, err
}
+117
View File
@@ -0,0 +1,117 @@
package pipeline
import (
"context"
"database/sql"
"errors"
"path/filepath"
"strings"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
_ "modernc.org/sqlite"
)
func TestArchiveHidesReservesAndGuardsSchedules(t *testing.T) {
ctx := context.Background()
s, err := Open(filepath.Join(t.TempDir(), "archive.db"))
if err != nil {
t.Fatal(err)
}
defer s.Close()
if _, err := s.Submit(ctx, "old", Template([]string{"one"}, true)); err != nil {
t.Fatal(err)
}
if _, err := s.Submit(ctx, "keep", Template([]string{"one"}, true)); err != nil {
t.Fatal(err)
}
id, err := s.ResolvePipelineID(ctx, 0, "old")
if err != nil {
t.Fatal(err)
}
if byID, err := s.ResolvePipelineID(ctx, 0, "1"); err != nil || byID != id {
t.Fatal("numeric name did not resolve as an ID", byID, err)
}
spec := protocol.SavedSchedule{Name: "nightly", PipelineID: id, Version: 1, Enabled: true, Workspace: t.TempDir(), Input: map[string]any{"prompt": "go"}, Rule: protocol.Schedule{Every: "1h"}}
saved, err := s.SaveSchedule(ctx, spec, time.Now())
if err != nil {
t.Fatal(err)
}
err = s.SetArchived(ctx, id, true, 0, time.Now())
if err == nil || !strings.Contains(err.Error(), `"nightly"`) || !strings.Contains(err.Error(), "pause") {
t.Fatal("archive with an enabled schedule was not refused by name", err)
}
paused := *saved
paused.Enabled = false
if _, err = s.SaveSchedule(ctx, paused, time.Now()); err != nil {
t.Fatal(err)
}
if err = s.SetArchived(ctx, id, true, 7, time.Now()); err == nil || !strings.Contains(err.Error(), "expected latest version 7") {
t.Fatal("stale expected version accepted", err)
}
if err = s.SetArchived(ctx, id, true, 1, time.Now()); err != nil {
t.Fatal(err)
}
if err = s.SetArchived(ctx, id, true, 0, time.Now()); err != nil {
t.Fatal("repeated archive must be a no-op", err)
}
active, _ := s.List(ctx)
if len(active) != 1 || active[0].Name != "keep" {
t.Fatal("archived pipeline listed by default", active)
}
all, _ := s.ListPipelines(ctx, true)
if len(all) != 2 || all[1].Name != "old" || all[1].ArchivedAt == "" || all[0].ArchivedAt != "" {
t.Fatal("include_archived did not mark the archived pipeline", all)
}
detail, err := s.Get(ctx, id, 1)
if err != nil || detail.ArchivedAt == "" || detail.Source == "" {
t.Fatal("archived detail lost history", detail, err)
}
var archived *ArchivedError
if _, err = s.Submit(ctx, "old", Template([]string{"one", "two"}, true), true); !errors.As(err, &archived) || !strings.Contains(err.Error(), "unarchive") {
t.Fatal("create-only reuse of an archived name not refused", err)
}
if _, err = s.Submit(ctx, "old", Template([]string{"one", "two"}, true)); !errors.As(err, &archived) {
t.Fatal("new version of an archived pipeline accepted", err)
}
enabled := paused
enabled.Revision++
enabled.Enabled = true
if _, err = s.SaveSchedule(ctx, enabled, time.Now()); !errors.As(err, &archived) {
t.Fatal("enabled schedule saved for an archived pipeline", err)
}
if err = s.SetArchived(ctx, id, false, 1, time.Now()); err != nil {
t.Fatal(err)
}
if active, _ = s.List(ctx); len(active) != 2 {
t.Fatal("unarchived pipeline still hidden", active)
}
if v, err := s.Submit(ctx, "old", Template([]string{"one", "two"}, true)); err != nil || v != 2 {
t.Fatal("unarchived pipeline cannot publish", v, err)
}
}
func TestArchiveColumnMigratesExistingDatabase(t *testing.T) {
path := filepath.Join(t.TempDir(), "legacy.db")
db, err := sql.Open("sqlite", path)
if err != nil {
t.Fatal(err)
}
if _, err = db.Exec(`CREATE TABLE pipelines (id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP);
INSERT INTO pipelines(name) VALUES ('legacy');`); err != nil {
t.Fatal(err)
}
db.Close()
for range 2 {
s, err := Open(path)
if err != nil {
t.Fatal(err)
}
var stamp sql.NullString
if err = s.db.QueryRow(`SELECT archived_at FROM pipelines WHERE name='legacy'`).Scan(&stamp); err != nil || stamp.Valid {
t.Fatal("legacy pipeline not migrated as active", stamp, err)
}
s.Close()
}
}
+9
View File
@@ -267,6 +267,15 @@ func (s *Store) SaveSchedule(ctx context.Context, spec protocol.SavedSchedule, n
return nil, err
}
defer tx.Rollback()
// An archived pipeline cannot gain an enabled schedule; a paused one may
// still be saved so the operator can repoint or tidy it.
if spec.Enabled {
if name, archived, err := archivedName(ctx, tx, "id=?", spec.PipelineID); err != nil {
return nil, err
} else if archived {
return nil, &ArchivedError{Name: name}
}
}
if spec.ID == 0 && requestKey != "" {
var id int64
var oldHash string
+26 -5
View File
@@ -61,6 +61,10 @@ CREATE TABLE IF NOT EXISTS submissions (id INTEGER PRIMARY KEY, name TEXT NOT NU
return nil, err
}
s := &Store{db: db, dir: filepath.Dir(path), path: path, done: make(chan struct{}), created: existing == 0}
if err := s.initArchive(); err != nil {
db.Close()
return nil, err
}
if err := s.initRuns(); err != nil {
db.Close()
return nil, err
@@ -173,8 +177,15 @@ func OpenMaintenance(path string) (*Store, error) {
// adjacent server state such as stage artifacts.
func (s *Store) Directory() string { return s.dir }
// List returns the active (unarchived) pipelines.
func (s *Store) List(ctx context.Context) ([]protocol.PipelineSummary, error) {
rows, err := s.db.QueryContext(ctx, `SELECT p.id, p.name, v.version,
return s.ListPipelines(ctx, false)
}
// ListPipelines returns the latest version of every pipeline; archived ones
// are included, marked by ArchivedAt, only when includeArchived is set.
func (s *Store) ListPipelines(ctx context.Context, includeArchived bool) ([]protocol.PipelineSummary, error) {
rows, err := s.db.QueryContext(ctx, `SELECT p.id, p.name, v.version, COALESCE(p.archived_at, ''),
json_array_length(v.graph_json, '$.stages'),
strftime('%Y-%m-%dT%H:%M:%SZ', p.created_at), strftime('%Y-%m-%dT%H:%M:%SZ', v.created_at),
v.graph_json,
@@ -182,7 +193,8 @@ v.graph_json,
(SELECT COUNT(*) FROM saved_schedules WHERE pipeline_id=p.id AND deleted=0 AND enabled=1)
FROM pipelines p JOIN pipeline_versions v ON v.pipeline_id=p.id
WHERE v.version=(SELECT MAX(version) FROM pipeline_versions WHERE pipeline_id=p.id)
ORDER BY p.name, p.id`)
AND (? OR p.archived_at IS NULL)
ORDER BY p.name, p.id`, includeArchived)
if err != nil {
return nil, err
}
@@ -191,7 +203,7 @@ ORDER BY p.name, p.id`)
for rows.Next() {
var item protocol.PipelineSummary
var graphJSON string
if err := rows.Scan(&item.ID, &item.Name, &item.Version, &item.Stages, &item.CreatedAt, &item.UpdatedAt, &graphJSON, &item.ScheduleCount, &item.EnabledScheduleCount); err != nil {
if err := rows.Scan(&item.ID, &item.Name, &item.Version, &item.ArchivedAt, &item.Stages, &item.CreatedAt, &item.UpdatedAt, &graphJSON, &item.ScheduleCount, &item.EnabledScheduleCount); err != nil {
return nil, err
}
var shape protocol.Graph
@@ -231,10 +243,10 @@ func (s *Store) Get(ctx context.Context, id int64, version int) (*protocol.Pipel
defer tx.Rollback()
detail := &protocol.PipelineDetail{}
err = tx.QueryRowContext(ctx, `SELECT p.id,p.name,strftime('%Y-%m-%dT%H:%M:%SZ',p.created_at),
v.version,strftime('%Y-%m-%dT%H:%M:%SZ',v.created_at)
v.version,strftime('%Y-%m-%dT%H:%M:%SZ',v.created_at),COALESCE(p.archived_at,'')
FROM pipelines p JOIN pipeline_versions v ON v.pipeline_id=p.id
WHERE p.id=? ORDER BY v.version DESC LIMIT 1`, id).
Scan(&detail.ID, &detail.Name, &detail.CreatedAt, &detail.LatestVersion, &detail.UpdatedAt)
Scan(&detail.ID, &detail.Name, &detail.CreatedAt, &detail.LatestVersion, &detail.UpdatedAt, &detail.ArchivedAt)
if err == sql.ErrNoRows {
return nil, fmt.Errorf("pipeline not found")
}
@@ -337,6 +349,15 @@ func (s *Store) submit(ctx context.Context, name, source string, createOnly bool
var version int
var versionID any
hash := fmt.Sprintf("%x", sha256.Sum256([]byte(source)))
if validation == nil {
// An archived name stays reserved: neither a fresh pipeline nor a new
// version may take it until the operator unarchives it.
if _, archived, err := archivedName(ctx, tx, "name=?", name); err != nil {
return 0, err
} else if archived {
validation = &ArchivedError{Name: name}
}
}
if validation == nil {
_, err = tx.ExecContext(ctx, "INSERT INTO pipelines(name) VALUES (?) ON CONFLICT(name) DO NOTHING", name)
if err != nil {