Initial pipelines server, CLI, TUI, and Go installation
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"pipelines/internal/cli"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"pipelines/internal/stage"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCLIHeadlessRunInspectionCancellationAndRPC(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "cli-runs.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
store.Submit(ctx, "workflow", pipeline.Template([]string{"worker"}, true))
|
||||
handler := Handler(ctx, store)
|
||||
r := handler.(*runHandler).runner
|
||||
r.execute = func(ctx context.Context, _ stage.Definition, input stage.Values) (stage.Result, error) {
|
||||
<-ctx.Done()
|
||||
return stage.Result{}, ctx.Err()
|
||||
}
|
||||
http := httptest.NewServer(handler)
|
||||
defer http.Close()
|
||||
defer func() { cancel(); WaitRuns(handler) }()
|
||||
url := "ws" + strings.TrimPrefix(http.URL, "http") + "/connect"
|
||||
run := func(args ...string) (string, error) {
|
||||
var out bytes.Buffer
|
||||
app := cli.App{Out: &out, Err: &out, In: strings.NewReader(`{"type":"list_templates"}`)}
|
||||
err := app.Run(ctx, append([]string{"--url", url}, args...))
|
||||
return out.String(), err
|
||||
}
|
||||
output, err := run("run", "workflow", "exact task", "--yes", "--json", "--request-key", "same-key")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var response protocol.Message
|
||||
json.Unmarshal([]byte(output), &response)
|
||||
id := response.RunDetail.ID
|
||||
if response.RunDetail.Input["prompt"] != "exact task" || response.RunDetail.AllowTools {
|
||||
t.Fatal("prompt or approval changed", response)
|
||||
}
|
||||
output, err = run("run", "workflow", "exact task", "--yes", "--json", "--request-key", "same-key")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
json.Unmarshal([]byte(output), &response)
|
||||
if response.RunDetail.ID != id {
|
||||
t.Fatal("idempotency lost")
|
||||
}
|
||||
if _, err = run("inspect", "1", "--json"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = run("runs", "--pipeline", "workflow", "--json"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = run("run", "workflow", "exact task", "--yes", "--json", "--request-key", "same-key", "--wait", "--timeout", "100ms"); err == nil || !strings.Contains(err.Error(), "remains active") {
|
||||
t.Fatal("wait timeout canceled or incorrectly succeeded", err)
|
||||
}
|
||||
if _, err = run("cancel", "1", "--json"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
detail, err := store.GetRun(ctx, id)
|
||||
if err != nil || detail.Status != "canceled" {
|
||||
t.Fatal(detail, err)
|
||||
}
|
||||
if output, err = run("rpc", "-"); err != nil || !strings.Contains(output, "templates") {
|
||||
t.Fatal(output, err)
|
||||
}
|
||||
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
|
||||
}
|
||||
output, err = run("run", "workflow", "second task", "--yes", "--json", "--wait", "--timeout", "3s")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
json.Unmarshal([]byte(output), &response)
|
||||
if response.RunDetail.Status != "succeeded" {
|
||||
t.Fatal("wait lost terminal state", output)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"os"
|
||||
"pipelines/internal/protocol"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var notificationTopic = regexp.MustCompile(`^[-_A-Za-z0-9]{1,64}$`)
|
||||
|
||||
func publicNtfyBase(text string) string {
|
||||
u, err := url.Parse(text)
|
||||
if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimRight(u.String(), "/")
|
||||
}
|
||||
|
||||
func notificationEndpoints() []protocol.NotificationEndpoint {
|
||||
u, err := url.Parse(os.Getenv("PIPELINES_NTFY_URL"))
|
||||
if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.RawPath != "" {
|
||||
return nil
|
||||
}
|
||||
topic := strings.TrimPrefix(u.Path, "/")
|
||||
if !notificationTopic.MatchString(topic) {
|
||||
return nil
|
||||
}
|
||||
return []protocol.NotificationEndpoint{{Destination: "system", ServerURL: publicNtfyBase(os.Getenv("PIPELINES_NTFY_PUBLIC_URL")), Topic: topic}}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPublicNotificationSetup(t *testing.T) {
|
||||
t.Setenv("PIPELINES_NTFY_URL", "http://ntfy/pipelines")
|
||||
t.Setenv("PIPELINES_NTFY_TOKEN", "private-token")
|
||||
t.Setenv("PIPELINES_NTFY_PUBLIC_URL", "http://10.0.0.249:8090")
|
||||
found := false
|
||||
for _, endpoint := range notificationEndpoints() {
|
||||
if endpoint.Destination == "system" {
|
||||
found = true
|
||||
if endpoint.ServerURL != "http://10.0.0.249:8090" || endpoint.Topic != "pipelines" {
|
||||
t.Fatal(endpoint)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("missing destination")
|
||||
}
|
||||
for _, value := range []string{"http://user:secret@example.com", "http://example.com?token=secret", "file:///tmp/secret", "http://example.com/topic"} {
|
||||
if publicNtfyBase(value) != "" {
|
||||
t.Fatal("unsafe public URL accepted", value)
|
||||
}
|
||||
}
|
||||
t.Setenv("PIPELINES_NTFY_PUBLIC_URL", "")
|
||||
for _, endpoint := range notificationEndpoints() {
|
||||
if endpoint.ServerURL != "" {
|
||||
t.Fatal("internal URL exposed", endpoint)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"pipelines/internal/protocol"
|
||||
"pipelines/internal/stage"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
func (r *runner) notifyStep(id int64, d *protocol.PipelineDetail, workspace string, policy *protocol.NotificationPolicy, step protocol.RunStep) {
|
||||
if policy == nil {
|
||||
return
|
||||
}
|
||||
event := "success"
|
||||
if step.Status != "completed" || step.Outcome == "error" || step.Target == protocol.FailureEnd {
|
||||
event = "failure"
|
||||
}
|
||||
enabled := false
|
||||
for _, on := range policy.On {
|
||||
if on == event {
|
||||
enabled = true
|
||||
}
|
||||
}
|
||||
if !enabled {
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
summary := fmt.Sprintf("%s · run #%d · stage %s · %s (%s)", d.Name, id, step.Stage, event, step.Outcome)
|
||||
if len(summary) > 1800 {
|
||||
summary = summary[:1800]
|
||||
for !utf8.ValidString(summary) {
|
||||
summary = summary[:len(summary)-1]
|
||||
}
|
||||
}
|
||||
title := fmt.Sprintf("Pipeline stage %s", event)
|
||||
receipts := []protocol.NotificationReceipt{}
|
||||
persist := func() bool {
|
||||
save, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := r.store.SaveNotifications(save, id, step.Sequence, receipts); err != nil {
|
||||
log.Printf("notification audit run=%d step=%d: %v", id, step.Sequence, err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
send := func(filename string, data []byte) {
|
||||
receipts = append(receipts, protocol.NotificationReceipt{Destination: "system", Status: "sending", Filename: filename})
|
||||
if !persist() {
|
||||
return
|
||||
}
|
||||
receipt := &receipts[len(receipts)-1]
|
||||
result, err := stage.PublishNtfy(ctx, "system", title, summary, filename, data)
|
||||
if err != nil {
|
||||
receipt.Status = "failed"
|
||||
receipt.Diagnostic = err.Error()
|
||||
} else {
|
||||
receipt.Status = "sent"
|
||||
receipt.MessageID, _ = result["message_id"].(string)
|
||||
receipt.AttachmentURL, _ = result["attachment_url"].(string)
|
||||
}
|
||||
persist()
|
||||
}
|
||||
reject := func(filename, diagnostic string) {
|
||||
receipts = append(receipts, protocol.NotificationReceipt{Destination: "system", Status: "failed", Filename: filename, Diagnostic: diagnostic})
|
||||
persist()
|
||||
}
|
||||
sentArtifact := false
|
||||
for _, kind := range policy.Artifacts {
|
||||
switch kind {
|
||||
case "markdown":
|
||||
if markdown, ok := step.Output["markdown"].(string); ok && strings.TrimSpace(markdown) != "" {
|
||||
sentArtifact = true
|
||||
send("digest.md", []byte(markdown))
|
||||
}
|
||||
case "files":
|
||||
raw, exists := step.Output["artifacts"]
|
||||
if !exists {
|
||||
continue
|
||||
}
|
||||
var names []string
|
||||
switch files := raw.(type) {
|
||||
case []string:
|
||||
names = files
|
||||
case []any:
|
||||
for _, value := range files {
|
||||
name, ok := value.(string)
|
||||
if !ok {
|
||||
reject("", "output.artifacts must be an array of relative file paths")
|
||||
names = nil
|
||||
break
|
||||
}
|
||||
names = append(names, name)
|
||||
}
|
||||
default:
|
||||
reject("", "output.artifacts must be an array of relative file paths")
|
||||
}
|
||||
if len(names) > 10 {
|
||||
reject("", "at most 10 file artifacts can be notified")
|
||||
continue
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, name := range names {
|
||||
if seen[name] {
|
||||
continue
|
||||
}
|
||||
seen[name] = true
|
||||
data, err := notificationArtifact(workspace, name)
|
||||
if err != nil {
|
||||
reject(name, err.Error())
|
||||
continue
|
||||
}
|
||||
sentArtifact = true
|
||||
send(filepath.Base(name), data)
|
||||
}
|
||||
}
|
||||
}
|
||||
// No produced artifacts still merits an event, especially on failures.
|
||||
if !sentArtifact {
|
||||
send("", nil)
|
||||
}
|
||||
}
|
||||
|
||||
func notificationArtifact(workspace, name string) ([]byte, error) {
|
||||
if name == "" || filepath.IsAbs(name) || filepath.Clean(name) != name || strings.ContainsAny(name, "\\\x00\r\n") {
|
||||
return nil, fmt.Errorf("artifact must be a clean workspace-relative file path")
|
||||
}
|
||||
for _, part := range strings.Split(filepath.ToSlash(name), "/") {
|
||||
lower := strings.ToLower(part)
|
||||
if strings.HasPrefix(part, ".") || lower == "secrets" || lower == "node_modules" || strings.HasSuffix(lower, ".pem") || strings.HasSuffix(lower, ".key") || strings.HasSuffix(lower, ".db") || strings.HasSuffix(lower, ".db-wal") || strings.HasSuffix(lower, ".db-shm") || strings.HasSuffix(lower, ".sqlite") || strings.HasSuffix(lower, ".sqlite3") {
|
||||
return nil, fmt.Errorf("artifact path is protected")
|
||||
}
|
||||
}
|
||||
root, err := filepath.EvalSymlinks(workspace)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("artifact workspace unavailable")
|
||||
}
|
||||
// os.Root prevents symlink traversal outside the workspace; disallow symlinks
|
||||
// altogether so aliases cannot bypass protected path names within it either.
|
||||
current := root
|
||||
for _, part := range strings.Split(name, string(os.PathSeparator)) {
|
||||
current = filepath.Join(current, part)
|
||||
info, err := os.Lstat(current)
|
||||
if err != nil || info.Mode()&os.ModeSymlink != 0 {
|
||||
return nil, fmt.Errorf("artifact is missing or uses a symlink")
|
||||
}
|
||||
}
|
||||
scoped, err := os.OpenRoot(root)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("artifact workspace unavailable")
|
||||
}
|
||||
defer scoped.Close()
|
||||
file, err := scoped.OpenFile(name, os.O_RDONLY|syscall.O_NONBLOCK|syscall.O_NOFOLLOW, 0)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot read artifact")
|
||||
}
|
||||
defer file.Close()
|
||||
info, err := file.Stat()
|
||||
if err != nil || !info.Mode().IsRegular() || info.Size() > 1<<20 {
|
||||
return nil, fmt.Errorf("artifact must be a regular file at most 1 MiB")
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(file, (1<<20)+1))
|
||||
if err != nil || len(data) > 1<<20 {
|
||||
return nil, fmt.Errorf("cannot read artifact within size limit")
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"pipelines/internal/stage"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestStageNotificationEventsAndArtifactAudit(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "notify.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
workspace := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(workspace, "report.txt"), []byte("created file"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var calls atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
count := calls.Add(1)
|
||||
filename, _ := new(mime.WordDecoder).DecodeHeader(r.Header.Get("Filename"))
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
if filename == "report.txt" && string(body) != "created file" {
|
||||
t.Error("wrong file content")
|
||||
}
|
||||
if filename == "digest.md" && string(body) != "# Digest" {
|
||||
t.Error("wrong markdown")
|
||||
}
|
||||
ack := map[string]any{"id": fmt.Sprintf("msg%d", count), "event": "message"}
|
||||
if filename != "" {
|
||||
ack["attachment"] = map[string]string{"name": filename, "url": "https://ntfy.example.com/file/" + filename}
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(ack)
|
||||
}))
|
||||
defer srv.Close()
|
||||
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/pipelines")
|
||||
if _, err := store.Submit(ctx, "notifications", pipeline.Template([]string{"one"}, true)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ := store.List(ctx)
|
||||
d, _ := store.Get(ctx, items[0].ID, 0)
|
||||
r, _ := newRunner(ctx, store)
|
||||
for i, test := range []struct {
|
||||
status, outcome, target, on string
|
||||
attachments bool
|
||||
expected int32
|
||||
}{
|
||||
{"completed", "success", protocol.SuccessEnd, "success", true, 2},
|
||||
{"completed", "blocked", protocol.FailureEnd, "failure", false, 1},
|
||||
{"failed", "error", protocol.FailureEnd, "failure", false, 1},
|
||||
{"completed", "error", protocol.FailureEnd, "success", false, 0},
|
||||
} {
|
||||
id, _, err := store.CreateRun(ctx, d, fmt.Sprintf("case%d", i), workspace, false, nil, map[string]any{"prompt": "task"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.BeginStep(ctx, id, 1, "one", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
step := protocol.RunStep{Sequence: 1, Stage: "one", Status: test.status, Outcome: test.outcome, Target: test.target, Output: map[string]any{}}
|
||||
policy := &protocol.NotificationPolicy{On: []string{test.on}, Destination: "anime"}
|
||||
if test.attachments {
|
||||
policy.Artifacts = []string{"markdown", "files"}
|
||||
step.Output = map[string]any{"markdown": "# Digest", "artifacts": []any{"report.txt"}}
|
||||
}
|
||||
if err := store.FinishStep(ctx, id, step); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := calls.Load()
|
||||
r.notifyStep(id, d, workspace, policy, step)
|
||||
detail, err := store.GetRun(ctx, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls.Load()-before != test.expected || len(detail.Steps[0].Notifications) != int(test.expected) {
|
||||
t.Fatal("event/attachments mismatch", detail, calls.Load()-before)
|
||||
}
|
||||
for _, receipt := range detail.Steps[0].Notifications {
|
||||
if receipt.Status != "sent" || receipt.MessageID == "" {
|
||||
t.Fatal("notification receipt not persisted", receipt)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotificationFailureDoesNotChangeRunRouting(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "routing.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
source := strings.Replace(pipeline.Template([]string{"one"}, true), "# stage one", "# stage one\n```notify\non=success\ndestination=anime\nartifacts=markdown\n```", 1)
|
||||
if _, err := store.Submit(ctx, "test", source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ := store.List(ctx)
|
||||
r, _ := newRunner(ctx, store)
|
||||
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "# Result"}}, nil
|
||||
}
|
||||
t.Setenv("PIPELINES_NTFY_URL", "")
|
||||
run, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "once", Input: map[string]any{"prompt": "task"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
detail, _ := store.GetRun(ctx, run.ID)
|
||||
if detail.Status != "succeeded" || len(detail.Steps[0].Notifications) != 1 || detail.Steps[0].Notifications[0].Status != "failed" {
|
||||
t.Fatal("notification altered routing or lost failure audit", detail)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotificationArtifactPathSafety(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
os.WriteFile(filepath.Join(root, "safe.txt"), []byte("safe"), 0600)
|
||||
os.WriteFile(filepath.Join(root, ".env"), []byte("secret"), 0600)
|
||||
os.Symlink(filepath.Join(root, ".env"), filepath.Join(root, "alias.txt"))
|
||||
outside := filepath.Join(t.TempDir(), "outside.txt")
|
||||
os.WriteFile(outside, []byte("secret"), 0600)
|
||||
os.Symlink(outside, filepath.Join(root, "external.txt"))
|
||||
os.Mkdir(filepath.Join(root, "directory"), 0700)
|
||||
os.WriteFile(filepath.Join(root, "large.bin"), []byte(strings.Repeat("x", (1<<20)+1)), 0600)
|
||||
if err := syscall.Mkfifo(filepath.Join(root, "pipe"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, name := range []string{"../outside.txt", outside, ".env", "alias.txt", "external.txt", "directory", "large.bin", "pipe", "pipelines.db", "secret.key", "secrets/file.txt", "sub/../safe.txt"} {
|
||||
if _, err := notificationArtifact(root, name); err == nil {
|
||||
t.Fatal("unsafe artifact accepted", name)
|
||||
}
|
||||
}
|
||||
if data, err := notificationArtifact(root, "safe.txt"); err != nil || string(data) != "safe" {
|
||||
t.Fatal("safe artifact rejected", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRunnerNtfyDeliveryIsAuditedAndIdempotent(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "ntfy.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
calls := 0
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls++
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
if string(body) != "# Anime\nA report." {
|
||||
t.Error("wrong markdown", string(body))
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"id":"delivery123","event":"message","attachment":{"name":"digest.md","url":"https://ntfy.example.com/file/digest.md"}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
t.Setenv("PIPELINES_NTFY_ANIME_URL", srv.URL+"/anime")
|
||||
source := "# stage notify\n```configs\ntype=ntfy\ndestination=anime\n```\n```edges\nsuccess -> #success\nerror -> #failure\n```\n"
|
||||
if _, err := store.Submit(ctx, "notify", source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ := store.List(ctx)
|
||||
r, _ := newRunner(ctx, store)
|
||||
for i, approved := range []bool{false, true} {
|
||||
key := []string{"notify", "approved-notify"}[i]
|
||||
request := protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: key, AllowTools: approved, Input: map[string]any{"prompt": "notify", "title": "Anime", "summary": "Your digest is ready", "markdown": "# Anime\nA report."}}
|
||||
run, err := r.start(request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
detail, _ := store.GetRun(ctx, run.ID)
|
||||
if detail.Status != "succeeded" || len(detail.Steps) != 1 || detail.Steps[0].Output["delivery"] == nil || detail.Steps[0].SessionID != "" {
|
||||
t.Fatal("native delivery not audited", detail)
|
||||
}
|
||||
if duplicate, err := r.start(request); err != nil || duplicate.ID != run.ID {
|
||||
t.Fatal("repeat not idempotent", err)
|
||||
}
|
||||
}
|
||||
if calls != 2 {
|
||||
t.Fatal("duplicate publication", calls)
|
||||
}
|
||||
t.Setenv("PIPELINES_NTFY_ANIME_URL", "")
|
||||
failed, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "failure", Input: map[string]any{"prompt": "notify", "title": "Anime", "summary": "Ready", "markdown": "# report"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
detail, _ := store.GetRun(ctx, failed.ID)
|
||||
if detail.Status != "failed" || detail.Steps[0].Outcome != "error" {
|
||||
t.Fatal("delivery failure not routed", detail)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"pipelines/internal/stage"
|
||||
)
|
||||
|
||||
func TestRunWebSocketRemainsResponsiveAndAuditable(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "run.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
if _, err := store.Submit(ctx, "ws", pipeline.Template([]string{"one"}, true)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ := store.List(ctx)
|
||||
handler := Handler(ctx, store).(*runHandler)
|
||||
defer func() { cancel(); WaitRuns(handler) }()
|
||||
entered := make(chan struct{})
|
||||
handler.runner.execute = func(ctx context.Context, _ stage.Definition, _ stage.Values) (stage.Result, error) {
|
||||
close(entered)
|
||||
<-ctx.Done()
|
||||
return stage.Result{}, ctx.Err()
|
||||
}
|
||||
srv := httptest.NewServer(handler)
|
||||
defer srv.Close()
|
||||
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.CloseNow()
|
||||
var snapshot protocol.Message
|
||||
if err := wsjson.Read(ctx, conn, &snapshot); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := func(message protocol.Message) protocol.Message {
|
||||
t.Helper()
|
||||
if err := wsjson.Write(ctx, conn, message); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var response protocol.Message
|
||||
if err := wsjson.Read(ctx, conn, &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.ID != message.ID {
|
||||
t.Fatal("response ID mismatch")
|
||||
}
|
||||
return response
|
||||
}
|
||||
invalid := request(protocol.Message{Type: protocol.RunPipeline, ID: "invalid", PipelineID: items[0].ID, RequestKey: "invalid"})
|
||||
if invalid.Type != protocol.Error {
|
||||
t.Fatal("accepted unpinned run")
|
||||
}
|
||||
missingPrompt := request(protocol.Message{Type: protocol.RunPipeline, ID: "missing-prompt", PipelineID: items[0].ID, Version: 1, RequestKey: "missing-prompt"})
|
||||
if missingPrompt.Type != protocol.Error || !strings.Contains(missingPrompt.Error, "user prompt") {
|
||||
t.Fatal("run accepted missing user prompt")
|
||||
}
|
||||
started := request(protocol.Message{Type: protocol.RunPipeline, ID: "start", PipelineID: items[0].ID, Version: 1, RequestKey: "ws-once", Input: map[string]any{"prompt": "test"}})
|
||||
if started.Type != protocol.RunStarted || started.RunDetail == nil {
|
||||
t.Fatal("run not started", started)
|
||||
}
|
||||
<-entered
|
||||
if response := request(protocol.Message{Type: protocol.Ping, ID: "ping"}); response.Type != protocol.Pong {
|
||||
t.Fatal("active run blocked ping")
|
||||
}
|
||||
if response := request(protocol.Message{Type: protocol.ListRuns, ID: "list"}); response.Type != protocol.Runs || len(response.Runs) != 1 {
|
||||
t.Fatal("run list missing")
|
||||
}
|
||||
if response := request(protocol.Message{Type: protocol.CancelRun, ID: "cancel", RunID: started.RunDetail.ID}); response.Type != protocol.Run {
|
||||
t.Fatal("cancel rejected")
|
||||
}
|
||||
handler.runner.wg.Wait()
|
||||
result := request(protocol.Message{Type: protocol.GetRun, ID: "inspect", RunID: started.RunDetail.ID})
|
||||
if result.RunDetail == nil || result.RunDetail.Status != "canceled" || len(result.RunDetail.Steps) != 1 || result.RunDetail.Steps[0].Input["prompt"] != "test" {
|
||||
t.Fatal("missing canceled audit", result)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"pipelines/internal/stage"
|
||||
)
|
||||
|
||||
type runner struct {
|
||||
ctx context.Context
|
||||
store *pipeline.Store
|
||||
mu sync.Mutex
|
||||
active map[int64]context.CancelFunc
|
||||
execute func(context.Context, stage.Definition, stage.Values) (stage.Result, error)
|
||||
wg sync.WaitGroup
|
||||
schedulerWG sync.WaitGroup
|
||||
workspaceRoots []string
|
||||
}
|
||||
|
||||
func newRunner(ctx context.Context, s *pipeline.Store) (*runner, error) {
|
||||
sessions, err := s.ActiveAgentSessions(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, id := range sessions {
|
||||
stop, cancel := context.WithTimeout(ctx, 20*time.Second)
|
||||
err := (stage.OpenCodeClient{}).Interrupt(stop, id)
|
||||
cancel()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot interrupt previously active agent %s: %w", id, err)
|
||||
}
|
||||
}
|
||||
if err := s.RecoverRuns(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &runner{ctx: ctx, store: s, active: map[int64]context.CancelFunc{}}, nil
|
||||
}
|
||||
|
||||
func (r *runner) start(request protocol.Message) (*protocol.RunDetail, error) {
|
||||
if request.Version <= 0 || request.RequestKey == "" || len(request.RequestKey) > 128 {
|
||||
return nil, fmt.Errorf("an explicit version and request key are required")
|
||||
}
|
||||
workspace, err := os.Getwd()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
workspace, err = filepath.EvalSymlinks(workspace)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if request.Workspace != "" {
|
||||
if !filepath.IsAbs(request.Workspace) {
|
||||
return nil, fmt.Errorf("run workspace must be an absolute directory")
|
||||
}
|
||||
selected, err := filepath.EvalSymlinks(request.Workspace)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("run workspace is unavailable")
|
||||
}
|
||||
info, err := os.Stat(selected)
|
||||
if err != nil || !info.IsDir() {
|
||||
return nil, fmt.Errorf("run workspace must be a directory")
|
||||
}
|
||||
allowed := selected == workspace
|
||||
for _, root := range r.workspaceRoots {
|
||||
root, err = filepath.Abs(root)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
root, err = filepath.EvalSymlinks(root)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("configured workspace root is unavailable")
|
||||
}
|
||||
rel, err := filepath.Rel(root, selected)
|
||||
if err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
|
||||
allowed = true
|
||||
}
|
||||
}
|
||||
if !allowed {
|
||||
return nil, fmt.Errorf("run workspace is outside the server's allowed workspace roots")
|
||||
}
|
||||
workspace = selected
|
||||
}
|
||||
if len(request.WritePaths) > 20 {
|
||||
return nil, fmt.Errorf("too many write paths")
|
||||
}
|
||||
for _, path := range request.WritePaths {
|
||||
if filepath.IsAbs(path) || filepath.Clean(path) != path || strings.HasPrefix(path, "..") || strings.ContainsAny(path, "*?\\") || !strings.HasSuffix(path, ".go") {
|
||||
return nil, fmt.Errorf("write paths must be exact project-local Go files")
|
||||
}
|
||||
resolved, err := filepath.EvalSymlinks(filepath.Join(workspace, path))
|
||||
if err != nil || !strings.HasPrefix(resolved, workspace+string(os.PathSeparator)) {
|
||||
return nil, fmt.Errorf("write path must be an existing file within workspace")
|
||||
}
|
||||
}
|
||||
if request.Input == nil {
|
||||
request.Input = map[string]any{}
|
||||
}
|
||||
if prompt, ok := request.Input["prompt"].(string); !ok || strings.TrimSpace(prompt) == "" {
|
||||
return nil, fmt.Errorf("a nonempty user prompt is required in input.prompt")
|
||||
}
|
||||
d, err := r.store.Get(r.ctx, request.PipelineID, request.Version)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := pipeline.Parse(pipeline.ExecutionSource(d.Source)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, s := range d.Graph.Stages {
|
||||
if stage.EffectiveType(s.Type) != stage.ModelType {
|
||||
continue
|
||||
}
|
||||
tools, _, err := stage.ToolNames(pipeline.StageDefinition(s))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, tool := range tools {
|
||||
if (tool == "edit" || tool == "shell") && !request.AllowTools {
|
||||
return nil, fmt.Errorf("stage %s: %s requires explicit manual tool approval", s.Key, tool)
|
||||
}
|
||||
}
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if r.ctx.Err() != nil {
|
||||
return nil, r.ctx.Err()
|
||||
}
|
||||
sessions, err := r.store.ActiveAgentSessions(r.ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(sessions) > 0 && len(r.active) == 0 {
|
||||
return nil, fmt.Errorf("an agent may still be active; restart recovery must interrupt it before new work")
|
||||
}
|
||||
// Idempotent repeats are accepted even while the original run is active.
|
||||
if len(r.active) > 0 {
|
||||
existing, err := r.store.RunByKey(r.ctx, request.RequestKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if existing == 0 {
|
||||
return nil, fmt.Errorf("another run is active; inspect it before starting more work")
|
||||
}
|
||||
}
|
||||
id, created, err := r.store.CreateRun(r.ctx, d, request.RequestKey, workspace, request.AllowTools, request.WritePaths, request.Input)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if created {
|
||||
ctx, cancel := context.WithTimeout(r.ctx, 30*time.Minute)
|
||||
r.active[id] = cancel
|
||||
r.wg.Add(1)
|
||||
go func() {
|
||||
defer r.wg.Done()
|
||||
defer cancel()
|
||||
defer func() { r.mu.Lock(); delete(r.active, id); r.mu.Unlock() }()
|
||||
r.run(ctx, id, d, workspace, request)
|
||||
}()
|
||||
}
|
||||
return r.store.GetRun(r.ctx, id)
|
||||
}
|
||||
|
||||
func (r *runner) cancel(id int64) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
cancel, ok := r.active[id]
|
||||
if !ok {
|
||||
return fmt.Errorf("run is not active")
|
||||
}
|
||||
cancel()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail, workspace string, request protocol.Message) {
|
||||
input := stage.Values(request.Input)
|
||||
key := d.Graph.Stages[0].Key
|
||||
visits := map[string]int{}
|
||||
finish := func(status, outcome, diagnostic string) {
|
||||
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := r.store.FinishRun(c, id, status, outcome, diagnostic, input); err != nil {
|
||||
log.Printf("finish run %d: %v", id, err)
|
||||
}
|
||||
}
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
finish("failed", "error", "stage execution panicked")
|
||||
}
|
||||
}()
|
||||
for sequence := 1; sequence <= 30; sequence++ {
|
||||
if ctx.Err() != nil {
|
||||
finish("canceled", "", ctx.Err().Error())
|
||||
return
|
||||
}
|
||||
visits[key]++
|
||||
if visits[key] > 5 {
|
||||
finish("failed", "error", "stage visit budget exceeded")
|
||||
return
|
||||
}
|
||||
var def stage.Definition
|
||||
found := false
|
||||
for _, s := range d.Graph.Stages {
|
||||
if s.Key == key {
|
||||
def = pipeline.StageDefinition(s)
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
finish("failed", "error", "missing stage")
|
||||
return
|
||||
}
|
||||
if err := r.store.BeginStep(ctx, id, sequence, key, input); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
finish("canceled", "", ctx.Err().Error())
|
||||
return
|
||||
}
|
||||
finish("failed", "error", err.Error())
|
||||
return
|
||||
}
|
||||
var tools []string
|
||||
explicitTools := false
|
||||
var toolErr error
|
||||
if stage.EffectiveType(def.Type) == stage.ModelType {
|
||||
tools, explicitTools, toolErr = stage.ToolNames(def)
|
||||
}
|
||||
if toolErr != nil {
|
||||
finish("failed", "error", toolErr.Error())
|
||||
return
|
||||
}
|
||||
useAgent := stage.EffectiveType(def.Type) == stage.ModelType && (len(tools) > 0 || (request.AllowTools && !explicitTools))
|
||||
client := &stage.AgentClient{OpenCodeClient: stage.OpenCodeClient{Directory: workspace}, WritePaths: request.WritePaths, Tools: tools}
|
||||
client.OnSession = func(session string, active bool) error {
|
||||
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
return r.store.RunSession(c, id, sequence, session, active)
|
||||
}
|
||||
var result stage.Result
|
||||
var err error
|
||||
if r.execute != nil {
|
||||
result, err = r.execute(ctx, def, input)
|
||||
} else if useAgent {
|
||||
result, err = (stage.ModelStage{Client: client}).Run(ctx, def, input)
|
||||
} else if stage.EffectiveType(def.Type) == stage.ModelType {
|
||||
result, err = (stage.ModelStage{Client: stage.OpenCodeClient{Directory: workspace}}).Run(ctx, def, input)
|
||||
} else {
|
||||
result, err = stage.DefaultRegistry().Run(ctx, def, input)
|
||||
}
|
||||
step := protocol.RunStep{Sequence: sequence, Stage: key, Status: "completed", Outcome: result.Outcome, Output: result.Output, Transcript: client.Transcript}
|
||||
if err != nil {
|
||||
step.Status = "failed"
|
||||
step.Diagnostic = err.Error()
|
||||
step.Outcome = "error"
|
||||
step.Output = stage.Values{"error": err.Error(), "stage": key, "input": input}
|
||||
}
|
||||
step.Target = def.Edges[step.Outcome]
|
||||
save, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
persistErr := r.store.FinishStep(save, id, step)
|
||||
cancel()
|
||||
if persistErr != nil {
|
||||
finish("failed", "error", persistErr.Error())
|
||||
return
|
||||
}
|
||||
for _, s := range d.Graph.Stages {
|
||||
if s.Key == key {
|
||||
r.notifyStep(id, d, workspace, s.Notify, step)
|
||||
break
|
||||
}
|
||||
}
|
||||
input = stage.Values(step.Output)
|
||||
if useAgent {
|
||||
sessions, checkErr := r.store.ActiveAgentSessions(context.Background())
|
||||
if checkErr != nil || len(sessions) > 0 {
|
||||
finish("failed", "error", "agent quiescence not confirmed; inspect retained session before further work")
|
||||
return
|
||||
}
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
finish("canceled", "", ctx.Err().Error())
|
||||
return
|
||||
}
|
||||
if step.Target == protocol.SuccessEnd {
|
||||
finish("succeeded", "success", "")
|
||||
return
|
||||
}
|
||||
if step.Target == protocol.FailureEnd {
|
||||
finish("failed", "error", step.Diagnostic)
|
||||
return
|
||||
}
|
||||
if step.Target == "" {
|
||||
finish("failed", "error", "stage returned an undeclared outcome")
|
||||
return
|
||||
}
|
||||
key = step.Target
|
||||
}
|
||||
finish("failed", "error", "total stage budget exceeded")
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"pipelines/internal/stage"
|
||||
)
|
||||
|
||||
func TestRunnerRoutingPersistenceAndIdempotency(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "runs.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
if _, err := store.Submit(ctx, "test", pipeline.Template([]string{"one", "two"}, true)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ := store.List(ctx)
|
||||
r, err := newRunner(ctx, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entered := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
r.execute = func(ctx context.Context, def stage.Definition, input stage.Values) (stage.Result, error) {
|
||||
if def.Key == "one" {
|
||||
if len(input) != 1 || input["prompt"] != "task" {
|
||||
t.Error("entry input must be the user prompt unchanged")
|
||||
}
|
||||
close(entered)
|
||||
<-release
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"handoff": "evidence"}}, nil
|
||||
}
|
||||
if len(input) != 1 || input["handoff"] != "evidence" {
|
||||
t.Error("handoff not propagated")
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"verified": true}}, nil
|
||||
}
|
||||
request := protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "same", Input: map[string]any{"prompt": "task"}}
|
||||
run, err := r.start(request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
<-entered
|
||||
duplicate, err := r.start(request)
|
||||
if err != nil || duplicate.ID != run.ID {
|
||||
t.Fatal("active repeat was not idempotent", err)
|
||||
}
|
||||
other := request
|
||||
other.RequestKey = "other"
|
||||
if _, err := r.start(other); err == nil {
|
||||
t.Fatal("overlapping execution accepted")
|
||||
}
|
||||
close(release)
|
||||
r.wg.Wait()
|
||||
detail, err := store.GetRun(ctx, run.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if detail.Status != "succeeded" || len(detail.Steps) != 2 || detail.Steps[1].Input["handoff"] != "evidence" || detail.Output["verified"] != true {
|
||||
t.Fatalf("invalid persisted run: %+v", detail)
|
||||
}
|
||||
duplicate, err = r.start(request)
|
||||
if err != nil || duplicate.ID != run.ID {
|
||||
t.Fatal("finished repeat not idempotent")
|
||||
}
|
||||
request.RequestKey = "failure"
|
||||
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
|
||||
return stage.Result{}, errors.New("provider failed")
|
||||
}
|
||||
failed, err := r.start(request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
detail, _ = store.GetRun(ctx, failed.ID)
|
||||
if detail.Status != "failed" || detail.Steps[0].Outcome != "error" || detail.Steps[0].Target != protocol.FailureEnd {
|
||||
t.Fatal("execution error did not follow mandatory error edge")
|
||||
}
|
||||
request.RequestKey = "cancel"
|
||||
r.execute = func(ctx context.Context, _ stage.Definition, _ stage.Values) (stage.Result, error) {
|
||||
<-ctx.Done()
|
||||
return stage.Result{}, ctx.Err()
|
||||
}
|
||||
canceled, err := r.start(request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.cancel(canceled.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
detail, _ = store.GetRun(ctx, canceled.ID)
|
||||
if detail.Status != "canceled" {
|
||||
t.Fatal("cancel not persisted")
|
||||
}
|
||||
request.RequestKey = "budget"
|
||||
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{}}, nil
|
||||
}
|
||||
// A new version with a self-loop remains reachable to a terminal via error.
|
||||
source := pipeline.Template([]string{"loop"}, true)
|
||||
source = strings.Replace(source, "success -> #success", "success -> loop", 1)
|
||||
if _, err := store.Submit(ctx, "loop", source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ = store.List(ctx)
|
||||
for _, p := range items {
|
||||
if p.Name == "loop" {
|
||||
request.PipelineID = p.ID
|
||||
}
|
||||
}
|
||||
bounded, err := r.start(request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
detail, _ = store.GetRun(ctx, bounded.ID)
|
||||
if detail.Status != "failed" || len(detail.Steps) != 5 {
|
||||
t.Fatalf("cycle not bounded: %+v", detail)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestScheduleSubmissionOverWebSocket(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "ws.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
handler := Handler(ctx, store)
|
||||
defer func() { cancel(); WaitRuns(handler) }()
|
||||
srv := httptest.NewServer(handler)
|
||||
defer srv.Close()
|
||||
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.CloseNow()
|
||||
var response protocol.Message
|
||||
if err := wsjson.Read(ctx, conn, &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
base := "\n```\n```prompt\ntask\n```\n" + pipeline.Template([]string{"one"}, true)
|
||||
for _, test := range []struct {
|
||||
rule string
|
||||
valid bool
|
||||
}{{"every=15m\ntimes=09:00", false}, {"days=mon", false}, {"every=15m\ndays=mon,fri", true}, {"times=09:00,17:30\ndays=tue,thu", true}} {
|
||||
source := "# settings\n```schedule\n" + test.rule + base
|
||||
request := protocol.Message{Type: protocol.Submit, ID: "submit", Name: "scheduled", Source: source}
|
||||
if err := wsjson.Write(ctx, conn, request); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := wsjson.Read(ctx, conn, &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if test.valid {
|
||||
if response.Type != protocol.Submitted || response.Detail == nil || response.Detail.Graph.Settings == nil {
|
||||
t.Fatal("schedule not accepted/returned", response)
|
||||
}
|
||||
d := response.Detail
|
||||
due, err := store.ScheduleDue(ctx, d, 0, d.Graph.Settings.Schedules[0], time.Now())
|
||||
if err != nil || !due.After(time.Now()) {
|
||||
t.Fatal("schedule not activated", due, err)
|
||||
}
|
||||
} else if response.Type != protocol.Error || !strings.Contains(response.Error, "exactly one") {
|
||||
t.Fatal("XOR not enforced over websocket", response)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (r *runner) scheduleLoop() {
|
||||
defer r.schedulerWG.Done()
|
||||
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 now := <-ticker.C:
|
||||
if err := r.scheduleTick(now, false); err != nil {
|
||||
log.Printf("scheduler: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *runner) scheduleTick(now time.Time, recovery bool) error {
|
||||
items, err := r.store.List(r.ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, item := range items {
|
||||
d, err := r.store.Get(r.ctx, item.ID, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.Graph.Settings == nil {
|
||||
continue
|
||||
}
|
||||
for slot, rule := range d.Graph.Settings.Schedules {
|
||||
due, err := r.store.ScheduleDue(r.ctx, d, slot, rule, now)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if due.After(now) {
|
||||
continue
|
||||
}
|
||||
next, err := pipeline.NextSchedule(rule, now)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if rule.Every != "" {
|
||||
interval, _ := time.ParseDuration(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(rule)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !pipeline.ScheduleDay(rule, due.In(loc)) {
|
||||
status = "skipped_day"
|
||||
}
|
||||
claimed, err := r.store.ClaimSchedule(r.ctx, d, slot, due, next, status)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !claimed || status != "claimed" {
|
||||
continue
|
||||
}
|
||||
request := protocol.Message{PipelineID: d.ID, Version: d.Version, RequestKey: fmt.Sprintf("schedule:%d:%d:%d:%d", d.ID, d.Version, slot, due.UnixNano()), Input: map[string]any{"prompt": d.Graph.Settings.Prompt}}
|
||||
run, err := r.start(request)
|
||||
runID := int64(0)
|
||||
diagnostic := ""
|
||||
status = "started"
|
||||
if err != nil {
|
||||
status = "skipped"
|
||||
diagnostic = err.Error()
|
||||
} else {
|
||||
runID = run.ID
|
||||
}
|
||||
if err := r.store.FinishSchedule(r.ctx, d, slot, due, status, diagnostic, runID); err != nil {
|
||||
return err
|
||||
}
|
||||
log.Printf("schedule pipeline=%d version=%d slot=%d due=%s status=%s run=%d %s", d.ID, d.Version, slot, due.Format(time.RFC3339), status, runID, diagnostic)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/stage"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestScheduledExecutionPersistenceAndSkipping(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
path := filepath.Join(t.TempDir(), "schedule.db")
|
||||
store, err := pipeline.Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { store.Close() }()
|
||||
source := "# settings\n```schedule\nevery=15m\ndays=everyday\n```\n```prompt\nScheduled task\n```\n" + pipeline.Template([]string{"one"}, true)
|
||||
if _, err := store.Submit(ctx, "scheduled", source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ := store.List(ctx)
|
||||
d, _ := store.Get(ctx, items[0].ID, 0)
|
||||
rule := d.Graph.Settings.Schedules[0]
|
||||
now := time.Now()
|
||||
due, err := store.ScheduleDue(ctx, d, 0, rule, now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Reopening must retain the activation/cadence, not reset the timer.
|
||||
store.Close()
|
||||
store, err = pipeline.Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
persisted, err := store.ScheduleDue(ctx, d, 0, rule, now.Add(time.Minute))
|
||||
if err != nil || !persisted.Equal(due) {
|
||||
t.Fatal("timer reset on restart", persisted, due, err)
|
||||
}
|
||||
r, err := newRunner(ctx, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
calls := 0
|
||||
r.execute = func(ctx context.Context, def stage.Definition, input stage.Values) (stage.Result, error) {
|
||||
calls++
|
||||
if input["prompt"] != "Scheduled task" {
|
||||
t.Error("wrong scheduled prompt")
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"done": true}}, nil
|
||||
}
|
||||
if err := r.scheduleTick(due, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
runs, err := store.ListRuns(ctx)
|
||||
if err != nil || len(runs) != 1 || runs[0].Status != "succeeded" || calls != 1 {
|
||||
t.Fatal("scheduled execution", runs, calls, err)
|
||||
}
|
||||
detail, _ := store.GetRun(ctx, runs[0].ID)
|
||||
if detail.AllowTools {
|
||||
t.Fatal("scheduled run granted tools")
|
||||
}
|
||||
if err := r.scheduleTick(due, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls != 1 {
|
||||
t.Fatal("duplicate occurrence")
|
||||
}
|
||||
next, _ := store.ScheduleDue(ctx, d, 0, rule, due)
|
||||
if err := r.scheduleTick(next.Add(time.Hour), true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runs, _ = store.ListRuns(ctx)
|
||||
if len(runs) != 1 {
|
||||
t.Fatal("replayed downtime backlog")
|
||||
}
|
||||
// A new manual-only version disables the old schedule.
|
||||
if _, err := store.Submit(ctx, "scheduled", pipeline.Template([]string{"one"}, true)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next, _ = store.ScheduleDue(ctx, d, 0, rule, due)
|
||||
claimed, err := store.ClaimSchedule(ctx, d, 0, next, next.Add(time.Minute), "claimed")
|
||||
if err != nil || claimed {
|
||||
t.Fatal("obsolete schedule claimed", err)
|
||||
}
|
||||
if err := r.scheduleTick(next, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runs, _ = store.ListRuns(ctx)
|
||||
if len(runs) != 1 {
|
||||
t.Fatal("disabled schedule executed")
|
||||
}
|
||||
}
|
||||
|
||||
// Opt-in wall-clock integration: no clock injection, no external model calls.
|
||||
func TestLiveScheduleLoop(t *testing.T) {
|
||||
if os.Getenv("PIPELINES_LIVE_SCHEDULE_TEST") != "1" {
|
||||
t.Skip("set PIPELINES_LIVE_SCHEDULE_TEST=1 for the one-minute wall-clock check")
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "live.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
r, err := newRunner(ctx, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
executed := make(chan stage.Values, 1)
|
||||
r.execute = func(ctx context.Context, def stage.Definition, input stage.Values) (stage.Result, error) {
|
||||
executed <- input
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"done": true}}, nil
|
||||
}
|
||||
r.schedulerWG.Add(1)
|
||||
go r.scheduleLoop()
|
||||
defer func() { cancel(); r.schedulerWG.Wait(); r.wg.Wait() }()
|
||||
source := "# settings\n```schedule\nevery=1m\n```\n```prompt\nwall-clock task\n```\n" + pipeline.Template([]string{"one"}, true)
|
||||
if _, err := store.Submit(ctx, "live", source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case input := <-executed:
|
||||
if input["prompt"] != "wall-clock task" {
|
||||
t.Fatal("wrong prompt", input)
|
||||
}
|
||||
case <-time.After(75 * time.Second):
|
||||
t.Fatal("wall-clock scheduler did not dispatch")
|
||||
}
|
||||
r.wg.Wait()
|
||||
runs, err := store.ListRuns(ctx)
|
||||
if err != nil || len(runs) != 1 || runs[0].Status != "succeeded" {
|
||||
t.Fatal("scheduled audit missing", runs, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSchedulerSkipsOverlapAndExcludedDays(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "schedule.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
source := "# settings\n```schedule\nevery=15m\n```\n```prompt\ntask\n```\n" + pipeline.Template([]string{"one"}, true)
|
||||
if _, err := store.Submit(ctx, "test", source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ := store.List(ctx)
|
||||
d, _ := store.Get(ctx, items[0].ID, 0)
|
||||
rule := d.Graph.Settings.Schedules[0]
|
||||
due, _ := store.ScheduleDue(ctx, d, 0, rule, time.Now())
|
||||
r, _ := newRunner(ctx, store)
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
r.execute = func(ctx context.Context, def stage.Definition, input stage.Values) (stage.Result, error) {
|
||||
close(entered)
|
||||
<-release
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{}}, nil
|
||||
}
|
||||
if err := r.scheduleTick(due, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
<-entered
|
||||
if err := r.scheduleTick(due.Add(15*time.Minute), false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runs, _ := store.ListRuns(ctx)
|
||||
if len(runs) != 1 {
|
||||
t.Fatal("overlap started")
|
||||
}
|
||||
close(release)
|
||||
r.wg.Wait()
|
||||
// A weekday different from the upcoming due date must exclude that occurrence.
|
||||
days := []string{"sun", "mon", "tue", "wed", "thu", "fri", "sat"}
|
||||
excluded := days[(time.Now().Add(15*time.Minute).In(time.Local).Weekday()+1)%7]
|
||||
source = strings.Replace(source, "every=15m", "every=15m\ndays="+excluded, 1)
|
||||
if _, err := store.Submit(ctx, "test", source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d, _ = store.Get(ctx, d.ID, 0)
|
||||
rule = d.Graph.Settings.Schedules[0]
|
||||
due, _ = store.ScheduleDue(ctx, d, 0, rule, time.Now())
|
||||
if err := r.scheduleTick(due, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runs, _ = store.ListRuns(ctx)
|
||||
if len(runs) != 1 {
|
||||
t.Fatal("excluded day executed")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTemplatesDoNotSeedDatabaseAndCreateOnlyPreservesExisting(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "empty.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
handler := Handler(ctx, store)
|
||||
defer func() { cancel(); WaitRuns(handler) }()
|
||||
srv := httptest.NewServer(handler)
|
||||
defer srv.Close()
|
||||
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.CloseNow()
|
||||
conn.SetReadLimit(8 << 20)
|
||||
var response protocol.Message
|
||||
if err := wsjson.Read(ctx, conn, &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(response.Pipelines) != 0 {
|
||||
t.Fatal("new install seeded pipelines")
|
||||
}
|
||||
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ListTemplates, ID: "templates"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := wsjson.Read(ctx, conn, &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Type != protocol.Templates || len(response.Templates) != 11 {
|
||||
t.Fatal("missing catalog", response.Type, len(response.Templates))
|
||||
}
|
||||
items, err := store.List(ctx)
|
||||
if err != nil || len(items) != 0 {
|
||||
t.Fatal("browsing created pipelines", err)
|
||||
}
|
||||
source := response.Templates[0].Source
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.Submit, ID: "create", Name: "template copy", Source: source, CreateOnly: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := wsjson.Read(ctx, conn, &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if i == 0 && response.Type != protocol.Submitted {
|
||||
t.Fatal("new pipeline failed", response)
|
||||
}
|
||||
if i == 1 && (response.Type != protocol.Error || !strings.Contains(response.Error, "already exists")) {
|
||||
t.Fatal("template overwrote existing pipeline", response)
|
||||
}
|
||||
}
|
||||
items, _ = store.List(ctx)
|
||||
detail, _ := store.Get(ctx, items[0].ID, 0)
|
||||
if detail.Version != 1 || detail.Source != source {
|
||||
t.Fatal("immutable source changed")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"pipelines/internal/stage"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestWebStagesCanRunWithoutMutationApproval(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "web.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
source := strings.Replace(pipeline.Template([]string{"research", "process"}, true), "```tools\n```", "```tools\nwebsearch\nwebfetch\n```", 1)
|
||||
if _, err := store.Submit(ctx, "web", source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ := store.List(ctx)
|
||||
r, _ := newRunner(ctx, store)
|
||||
r.execute = func(ctx context.Context, def stage.Definition, input stage.Values) (stage.Result, error) {
|
||||
tools, explicit, err := stage.ToolNames(def)
|
||||
if err != nil || !explicit {
|
||||
t.Error("missing per-stage policy", err)
|
||||
}
|
||||
if def.Key == "research" && len(tools) != 2 {
|
||||
t.Error("research tools missing")
|
||||
}
|
||||
if def.Key == "process" && len(tools) != 0 {
|
||||
t.Error("processing inherited web access")
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"done": true}}, nil
|
||||
}
|
||||
request := protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "web", Input: map[string]any{"prompt": "task"}}
|
||||
run, err := r.start(request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
detail, _ := store.GetRun(ctx, run.ID)
|
||||
if detail.AllowTools || detail.Status != "succeeded" || len(detail.Steps) != 2 {
|
||||
t.Fatal("web stage required broad approval", detail)
|
||||
}
|
||||
// Scheduling uses the same prompt-only request and accepts declared web tools.
|
||||
scheduled := "# settings\n```schedule\nevery=15m\n```\n```prompt\ntask\n```\n" + source
|
||||
if _, err := store.Submit(ctx, "web", scheduled); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d, _ := store.Get(ctx, items[0].ID, 0)
|
||||
due, _ := store.ScheduleDue(ctx, d, 0, d.Graph.Settings.Schedules[0], time.Now())
|
||||
if err := r.scheduleTick(due, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
runs, _ := store.ListRuns(ctx)
|
||||
if len(runs) != 2 {
|
||||
t.Fatal("scheduled web run not started", runs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMutatingToolsRequireManualApproval(t *testing.T) {
|
||||
for _, tool := range []string{"edit", "shell"} {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "tools.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
source := strings.Replace(pipeline.Template([]string{"one"}, true), "```tools\n```", "```tools\n"+tool+"\n```", 1)
|
||||
if _, err := store.Submit(ctx, "tools", source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ := store.List(ctx)
|
||||
r, _ := newRunner(ctx, store)
|
||||
request := protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "unsafe", Input: map[string]any{"prompt": "task"}}
|
||||
if _, err := r.start(request); err == nil || !strings.Contains(err.Error(), "manual tool approval") {
|
||||
t.Fatal("mutation without approval", tool, err)
|
||||
}
|
||||
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{}}, nil
|
||||
}
|
||||
request.AllowTools = true
|
||||
if _, err := r.start(request); err != nil {
|
||||
t.Fatal("approved run rejected", err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
cancel()
|
||||
store.Close()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
|
||||
"pipelines/examples"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// Handler serves the persistent connection. Canceling ctx stops active clients.
|
||||
func Handler(ctx context.Context, stores ...*pipeline.Store) http.Handler {
|
||||
return handler(ctx, nil, stores...)
|
||||
}
|
||||
|
||||
// HandlerForWorkspaces permits run workspaces only below explicitly configured roots.
|
||||
func HandlerForWorkspaces(ctx context.Context, store *pipeline.Store, roots []string) http.Handler {
|
||||
return handler(ctx, roots, store)
|
||||
}
|
||||
|
||||
func handler(ctx context.Context, roots []string, stores ...*pipeline.Store) http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
var runs *runner
|
||||
var runErr error
|
||||
if len(stores) > 0 {
|
||||
runs, runErr = newRunner(ctx, stores[0])
|
||||
if runErr == nil {
|
||||
runs.workspaceRoots = append([]string(nil), roots...)
|
||||
runs.schedulerWG.Add(1)
|
||||
go runs.scheduleLoop()
|
||||
}
|
||||
}
|
||||
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if runErr != nil {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
_, _ = w.Write([]byte(`{"healthy":false}`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"healthy":true}`))
|
||||
})
|
||||
mux.HandleFunc("GET /connect", func(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := websocket.Accept(w, r, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer conn.CloseNow()
|
||||
conn.SetReadLimit(2 << 20)
|
||||
if len(stores) > 0 {
|
||||
items, err := stores[0].List(ctx)
|
||||
if err != nil {
|
||||
log.Printf("list pipelines: %v", err)
|
||||
return
|
||||
}
|
||||
writeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
err = wsjson.Write(writeCtx, conn, protocol.Message{Type: protocol.PipelineList, Pipelines: items, NotificationEndpoints: notificationEndpoints()})
|
||||
cancel()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
for {
|
||||
var request protocol.Message
|
||||
if err := wsjson.Read(ctx, conn, &request); err != nil {
|
||||
return
|
||||
}
|
||||
log.Printf("command received: client=%s type=%q id=%q pipeline=%d version=%d", r.RemoteAddr, request.Type, request.ID, request.PipelineID, request.Version)
|
||||
response := protocol.Message{Type: protocol.Pong, ID: request.ID}
|
||||
if request.Type == protocol.List || request.Type == protocol.Submit {
|
||||
response.NotificationEndpoints = notificationEndpoints()
|
||||
}
|
||||
if request.Type == protocol.Ping {
|
||||
response.Time = time.Now().UTC().Format(time.RFC3339)
|
||||
} else if request.Type == protocol.ListTemplates {
|
||||
response.Type = protocol.Templates
|
||||
response.Templates = examples.Catalog()
|
||||
} else if request.Type == protocol.Validate {
|
||||
graph, err := pipeline.Parse(request.Source)
|
||||
response.Type = protocol.Validated
|
||||
if err != nil {
|
||||
response.Type = protocol.Error
|
||||
response.Error = err.Error()
|
||||
} else {
|
||||
response.Graph = &graph
|
||||
}
|
||||
} else if request.Type == protocol.Submit && len(stores) > 0 {
|
||||
response.Type = protocol.Submitted
|
||||
response.Name = strings.TrimSpace(request.Name)
|
||||
version, err := stores[0].SubmitChecked(ctx, request.Name, request.Source, request.CreateOnly, request.ExpectedVersion)
|
||||
if err != nil {
|
||||
response.Type = protocol.Error
|
||||
response.Error = err.Error()
|
||||
} else {
|
||||
response.Version = version
|
||||
response.Pipelines, err = stores[0].List(ctx)
|
||||
if err != nil {
|
||||
log.Printf("list pipelines after submission: %v", err)
|
||||
}
|
||||
for _, item := range response.Pipelines {
|
||||
if item.Name == response.Name {
|
||||
response.Detail, err = stores[0].Get(ctx, item.ID, version)
|
||||
if err != nil {
|
||||
log.Printf("load submitted pipeline: %v", err)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if request.Type == protocol.GetPipeline && len(stores) > 0 {
|
||||
response.Type = protocol.Pipeline
|
||||
detail, err := stores[0].Get(ctx, request.PipelineID, request.Version)
|
||||
if err != nil {
|
||||
response.Type = protocol.Error
|
||||
response.Error = err.Error()
|
||||
} else {
|
||||
response.Detail = detail
|
||||
}
|
||||
} else if request.Type == protocol.List && len(stores) > 0 {
|
||||
response.Type = protocol.PipelineList
|
||||
items, err := stores[0].List(ctx)
|
||||
if err != nil {
|
||||
response.Type = protocol.Error
|
||||
response.Error = err.Error()
|
||||
} else {
|
||||
response.Pipelines = items
|
||||
}
|
||||
} else if runs != nil && (request.Type == protocol.RunPipeline || request.Type == protocol.ListRuns || request.Type == protocol.GetRun || request.Type == protocol.CancelRun) {
|
||||
var err error
|
||||
switch request.Type {
|
||||
case protocol.RunPipeline:
|
||||
response.Type = protocol.RunStarted
|
||||
response.RunDetail, err = runs.start(request)
|
||||
case protocol.ListRuns:
|
||||
response.Type = protocol.Runs
|
||||
response.Runs, err = runs.store.ListRuns(ctx)
|
||||
case protocol.GetRun:
|
||||
response.Type = protocol.Run
|
||||
response.RunDetail, err = runs.store.GetRun(ctx, request.RunID)
|
||||
case protocol.CancelRun:
|
||||
response.Type = protocol.Run
|
||||
err = runs.cancel(request.RunID)
|
||||
if err == nil {
|
||||
response.RunDetail, err = runs.store.GetRun(ctx, request.RunID)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
response.Type = protocol.Error
|
||||
response.Error = err.Error()
|
||||
}
|
||||
} else {
|
||||
response.Type = protocol.Error
|
||||
response.Error = "unknown command: " + request.Type
|
||||
if runErr != nil {
|
||||
response.Error = "execution unavailable: " + runErr.Error()
|
||||
}
|
||||
}
|
||||
writeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
err := wsjson.Write(writeCtx, conn, response)
|
||||
cancel()
|
||||
if err != nil {
|
||||
log.Printf("write response: %v", err)
|
||||
return
|
||||
}
|
||||
selectedVersion := response.Version
|
||||
if response.Detail != nil {
|
||||
selectedVersion = response.Detail.Version
|
||||
}
|
||||
log.Printf("response sent: client=%s type=%q id=%q time=%q error=%q version=%d", r.RemoteAddr, response.Type, response.ID, response.Time, response.Error, selectedVersion)
|
||||
}
|
||||
})
|
||||
return &runHandler{Handler: mux, runner: runs}
|
||||
}
|
||||
|
||||
type runHandler struct {
|
||||
http.Handler
|
||||
runner *runner
|
||||
}
|
||||
|
||||
// WaitRuns drains active execution before the database is closed on shutdown.
|
||||
func WaitRuns(handler http.Handler) {
|
||||
if h, ok := handler.(*runHandler); ok && h.runner != nil {
|
||||
h.runner.schedulerWG.Wait()
|
||||
h.runner.wg.Wait()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"log"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
|
||||
"pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
type logBuffer struct {
|
||||
mu sync.Mutex
|
||||
buffer bytes.Buffer
|
||||
}
|
||||
|
||||
func (b *logBuffer) Write(p []byte) (int, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.buffer.Write(p)
|
||||
}
|
||||
|
||||
func (b *logBuffer) String() string {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.buffer.String()
|
||||
}
|
||||
|
||||
func TestPersistentConnection(t *testing.T) {
|
||||
var logs logBuffer
|
||||
previousOutput := log.Writer()
|
||||
log.SetOutput(&logs)
|
||||
defer log.SetOutput(previousOutput)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
srv := httptest.NewServer(Handler(ctx))
|
||||
defer srv.Close()
|
||||
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.CloseNow()
|
||||
for _, request := range []protocol.Message{
|
||||
{Type: protocol.Ping, ID: "1"},
|
||||
{Type: "unknown", ID: "2"},
|
||||
{Type: protocol.Ping, ID: "3"},
|
||||
} {
|
||||
before := time.Now().UTC().Truncate(time.Second)
|
||||
if err := wsjson.Write(ctx, conn, request); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var response protocol.Message
|
||||
if err := wsjson.Read(ctx, conn, &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.ID != request.ID {
|
||||
t.Fatalf("ID = %q, want %q", response.ID, request.ID)
|
||||
}
|
||||
if request.Type != protocol.Ping {
|
||||
if response.Type != protocol.Error || response.Error == "" {
|
||||
t.Fatalf("expected error response, got %+v", response)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if response.Type != protocol.Pong {
|
||||
t.Fatalf("expected pong, got %+v", response)
|
||||
}
|
||||
stamp, err := time.Parse(time.RFC3339, response.Time)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stamp.Before(before) || stamp.After(time.Now().UTC()) || stamp.Nanosecond() != 0 || !strings.HasSuffix(response.Time, "Z") {
|
||||
t.Fatalf("invalid current UTC time to seconds: %q", response.Time)
|
||||
}
|
||||
}
|
||||
for _, expected := range []string{
|
||||
`command received: client=`,
|
||||
`type="ping" id="1"`,
|
||||
`response sent: client=`,
|
||||
`type="pong" id="1" time="`,
|
||||
`type="error" id="2"`,
|
||||
} {
|
||||
if !strings.Contains(logs.String(), expected) {
|
||||
t.Errorf("missing log %q in %s", expected, logs.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"pipelines/internal/pipeline"
|
||||
"pipelines/internal/protocol"
|
||||
"pipelines/internal/stage"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRepositoryWorkspaceAllowlistAndAudit(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "workspace.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
root := t.TempDir()
|
||||
a := filepath.Join(root, "repo-a")
|
||||
b := filepath.Join(root, "repo-b")
|
||||
os.Mkdir(a, 0700)
|
||||
os.Mkdir(b, 0700)
|
||||
outside := t.TempDir()
|
||||
if _, err := store.Submit(ctx, "test", pipeline.Template([]string{"one"}, true)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ := store.List(ctx)
|
||||
r, err := newRunner(ctx, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.workspaceRoots = []string{root}
|
||||
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"done": true}}, nil
|
||||
}
|
||||
for i, path := range []string{a, b} {
|
||||
detail, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: path, Input: map[string]any{"prompt": "task"}, Workspace: path})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
detail, err = store.GetRun(ctx, detail.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expected, _ := filepath.EvalSymlinks(path)
|
||||
if detail.Workspace != expected || detail.Status != "succeeded" {
|
||||
t.Fatal("incorrect workspace audit", i, detail)
|
||||
}
|
||||
}
|
||||
os.Symlink(outside, filepath.Join(root, "escape"))
|
||||
for _, path := range []string{outside, filepath.Join(root, "escape"), "relative/repo"} {
|
||||
if _, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: path, Input: map[string]any{"prompt": "task"}, Workspace: path}); err == nil {
|
||||
t.Fatal("unauthorized workspace accepted", path)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user