Record and serve per-stage artifacts

Every agent stage now writes into a per-run/step artifacts directory under
the data dir (<data>/artifacts/<run>/<step>), passed to Pi as
PIPELINES_ARTIFACTS_DIR, exposed on the OpenCode client env seam, and stated
in the agent prompt boilerplate so agents save images, screenshots, reports
and logs there.

After each step the server scans that directory with a bounded, symlink- and
traversal-safe inventory (os.OpenRoot + Lstat + O_NOFOLLOW) recording name,
size_bytes, content type (extension then 512-byte sniff fallback) and URL,
enforcing max files, per-file bytes and total bytes while counting skipped
and truncated entries. A missing, unreadable or oversized directory yields
only a best-effort diagnostic and never changes the step outcome.

The list is carried on protocol.RunStep as Artifacts []StageArtifact plus
skipped/truncated counters (omitempty, backwards compatible), persisted in a
new step_artifacts table keyed (run_id, sequence) alongside the
notifications/file-changes tables and loaded by GetRun.

GET /artifacts/{run}/{step}/{name} on the existing handler serves the bytes
with http.ServeContent, so Content-Type, Content-Length, HEAD and Range
(206/416) come from the stdlib; unknown runs/steps, absolute paths,
traversal, symlink escapes and non-regular files are refused.

The TUI lists each selected step's artifacts (name + human size) in the
retained-evidence section and adds an artifacts summary in the style of the
file-changes summary. Adds docs/stage-artifacts.md linked from README and an
artifacts subsection to the packaged operations skill reference.

Tests cover the scan records and caps, missing/oversized directories,
HTTP HEAD/Range/traversal/symlink/unknown refusals and protocol round-trips.
This commit is contained in:
2026-10-15 17:51:18 +01:00
parent 370eaaed1f
commit 0f5a188c6a
19 changed files with 905 additions and 49 deletions
+225
View File
@@ -0,0 +1,225 @@
package server
import (
"errors"
"io"
"io/fs"
"log"
"mime"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"syscall"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// Artifact capture is deliberately small and best-effort. A stage's artifacts
// directory is evidence, never a gate: every scan error is swallowed and never
// changes the step's outcome.
const (
maxArtifactFiles = 200
maxArtifactFileBytes = 8 << 20
maxArtifactTotalBytes = 64 << 20
artifactSniffBytes = 512
)
// scanArtifacts returns a bounded inventory of one step's artifacts directory.
// The directory path is supplied by the caller because it was created next to
// the step; runID and sequence name the served URL. A missing, unreadable,
// symlinked or oversized directory yields no entries and a zero count.
func (r *runner) scanArtifacts(runID int64, sequence int, directory string) ([]protocol.StageArtifact, int, int) {
if directory == "" || r.artifactsRoot == "" {
return nil, 0, 0
}
root, err := os.OpenRoot(r.artifactsRoot)
if err != nil {
log.Printf("stage artifacts root unavailable: %v", err)
return nil, 0, 0
}
defer root.Close()
rel := path.Join(strconv.FormatInt(runID, 10), strconv.Itoa(sequence))
if !containedDirectory(root, rel) {
return nil, 0, 0
}
files := []protocol.StageArtifact{}
skipped, truncated := 0, 0
used := int64(0)
walkErr := fs.WalkDir(root.FS(), rel, func(name string, entry fs.DirEntry, walkErr error) error {
if walkErr != nil {
// A single unreadable entry must not abort the whole inventory.
return nil
}
if name == rel || entry.IsDir() {
return nil
}
if entry.Type()&fs.ModeSymlink != 0 || !entry.Type().IsRegular() {
skipped++
return nil
}
info, infoErr := entry.Info()
if infoErr != nil || !info.Mode().IsRegular() {
skipped++
return nil
}
if len(files) >= maxArtifactFiles {
skipped++
return fs.SkipAll
}
if info.Size() > maxArtifactFileBytes {
skipped++
return nil
}
if used+info.Size() > maxArtifactTotalBytes {
truncated++
return fs.SkipAll
}
artifactName := strings.TrimPrefix(name, rel+"/")
full := path.Join(rel, artifactName)
contentType := mime.TypeByExtension(filepath.Ext(artifactName))
if contentType == "" {
contentType = sniffArtifact(root, full)
if contentType == "" {
skipped++
return nil
}
}
used += info.Size()
files = append(files, protocol.StageArtifact{
Name: artifactName,
SizeBytes: info.Size(),
ContentType: contentType,
URL: artifactURL(runID, sequence, artifactName),
})
return nil
})
if walkErr != nil {
log.Printf("stage artifacts inventory run=%d step=%d: %v", runID, sequence, walkErr)
return nil, 0, 0
}
if len(files) == 0 {
files = nil
}
return files, skipped, truncated
}
// containedDirectory reports whether rel names a real directory below root with
// no symlink in any component.
func containedDirectory(root *os.Root, rel string) bool {
if rel == "" || !fs.ValidPath(rel) || rel == "." {
return false
}
parts := strings.Split(rel, "/")
for i := range parts {
info, err := root.Lstat(strings.Join(parts[:i+1], "/"))
if err != nil || info.Mode()&os.ModeSymlink != 0 {
return false
}
if i == len(parts)-1 {
return info.IsDir()
}
}
return false
}
// sniffArtifact opens one regular file without following a final symlink and
// returns the detected content type from at most the first 512 bytes.
func sniffArtifact(root *os.Root, rel string) string {
file, err := root.OpenFile(rel, os.O_RDONLY|syscall.O_NOFOLLOW, 0)
if err != nil {
return ""
}
defer file.Close()
buffer := make([]byte, artifactSniffBytes)
n, err := io.ReadFull(file, buffer)
if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) {
return ""
}
return http.DetectContentType(buffer[:n])
}
// artifactURL builds the server-relative URL for one artifact, escaping each
// path segment so a name cannot forge path structure.
func artifactURL(runID int64, sequence int, name string) string {
parts := strings.Split(name, "/")
for i, part := range parts {
parts[i] = url.PathEscape(part)
}
return "/artifacts/" + strconv.FormatInt(runID, 10) + "/" + strconv.Itoa(sequence) + "/" + strings.Join(parts, "/")
}
// serveArtifact serves one recorded step artifact. It refuses unknown runs or
// steps and any name that is absolute, non-local, symlinked in any component or
// not a regular file, so nothing outside <artifactsRoot>/<run>/<step> is served.
// http.ServeContent supplies Content-Type (extension then sniff), Content-Length,
// HEAD and Range handling from the opened *os.File.
func (r *runner) serveArtifact(w http.ResponseWriter, req *http.Request) {
name := req.PathValue("name")
runID, runErr := strconv.ParseInt(req.PathValue("run"), 10, 64)
sequence, stepErr := strconv.Atoi(req.PathValue("step"))
if runErr != nil || stepErr != nil || runID <= 0 || sequence <= 0 {
http.NotFound(w, req)
return
}
if name == "" || name == "." || !fs.ValidPath(name) || path.IsAbs(name) {
http.NotFound(w, req)
return
}
detail, err := r.store.GetRun(req.Context(), runID)
if err != nil {
http.NotFound(w, req)
return
}
known := false
for _, step := range detail.Steps {
if step.Sequence == sequence {
known = true
break
}
}
if !known {
http.NotFound(w, req)
return
}
root, err := os.OpenRoot(r.artifactsRoot)
if err != nil {
http.NotFound(w, req)
return
}
defer root.Close()
rel := path.Join(strconv.FormatInt(runID, 10), strconv.Itoa(sequence))
if !containedDirectory(root, rel) {
http.NotFound(w, req)
return
}
full := path.Join(rel, name)
parts := strings.Split(full, "/")
for i := range parts {
info, lerr := root.Lstat(strings.Join(parts[:i+1], "/"))
if lerr != nil || info.Mode()&os.ModeSymlink != 0 {
http.NotFound(w, req)
return
}
}
info, err := root.Lstat(full)
if err != nil || !info.Mode().IsRegular() {
http.NotFound(w, req)
return
}
file, err := root.OpenFile(full, os.O_RDONLY|syscall.O_NOFOLLOW, 0)
if err != nil {
http.NotFound(w, req)
return
}
defer file.Close()
opened, err := file.Stat()
if err != nil || !opened.Mode().IsRegular() {
http.NotFound(w, req)
return
}
http.ServeContent(w, req, path.Base(name), opened.ModTime(), file)
}
+278
View File
@@ -0,0 +1,278 @@
package server
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
func artifactNamed(files []protocol.StageArtifact, name string) (protocol.StageArtifact, bool) {
for _, file := range files {
if file.Name == name {
return file, true
}
}
return protocol.StageArtifact{}, false
}
func TestArtifactsScanRecordsSizesTypesAndSkips(t *testing.T) {
root := t.TempDir()
stepDir := filepath.Join(root, "4", "2")
if err := os.MkdirAll(filepath.Join(stepDir, "reports"), 0700); err != nil {
t.Fatal(err)
}
png := []byte("\x89PNG\r\n\x1a\n...png bytes...")
if err := os.WriteFile(filepath.Join(stepDir, "shot.png"), png, 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(stepDir, "notes"), []byte("hello artifacts"), 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(stepDir, "reports", "out.txt"), []byte("report"), 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(stepDir, "big.bin"), make([]byte, maxArtifactFileBytes+1), 0600); err != nil {
t.Fatal(err)
}
if err := os.Symlink(filepath.Join(stepDir, "shot.png"), filepath.Join(stepDir, "alias.png")); err != nil {
t.Fatal(err)
}
r := &runner{artifactsRoot: root}
files, skipped, truncated := r.scanArtifacts(4, 2, stepDir)
if truncated != 0 {
t.Fatalf("unexpected truncation: %d", truncated)
}
if skipped < 2 {
t.Fatalf("oversized file and symlink must be skipped: %d", skipped)
}
shot, ok := artifactNamed(files, "shot.png")
if !ok || shot.SizeBytes != int64(len(png)) || shot.ContentType != "image/png" || shot.URL != "/artifacts/4/2/shot.png" {
t.Fatalf("png artifact wrong: %+v", shot)
}
notes, ok := artifactNamed(files, "notes")
if !ok || !strings.HasPrefix(notes.ContentType, "text/plain") {
t.Fatalf("extensionless artifact not sniffed: %+v", notes)
}
if nested, ok := artifactNamed(files, "reports/out.txt"); !ok || nested.SizeBytes != int64(len("report")) {
t.Fatalf("nested artifact missing: %+v", files)
}
if _, ok := artifactNamed(files, "alias.png"); ok {
t.Fatal("symlink must not be recorded")
}
if _, ok := artifactNamed(files, "big.bin"); ok {
t.Fatal("oversized artifact must not be recorded")
}
}
func TestArtifactsScanBoundsFileCount(t *testing.T) {
root := t.TempDir()
stepDir := filepath.Join(root, "1", "1")
if err := os.MkdirAll(stepDir, 0700); err != nil {
t.Fatal(err)
}
for i := 0; i < maxArtifactFiles+5; i++ {
name := filepath.Join(stepDir, fmt.Sprintf("f%04d", i))
if err := os.WriteFile(name, []byte("x"), 0600); err != nil {
t.Fatal(err)
}
}
r := &runner{artifactsRoot: root}
files, skipped, _ := r.scanArtifacts(1, 1, stepDir)
if len(files) != maxArtifactFiles {
t.Fatalf("file cap not enforced: %d", len(files))
}
if skipped == 0 {
t.Fatal("over-cap files were not counted as skipped")
}
}
func TestArtifactsScanMissingDirectoryIsEmpty(t *testing.T) {
r := &runner{artifactsRoot: t.TempDir()}
files, skipped, truncated := r.scanArtifacts(1, 1, filepath.Join(t.TempDir(), "absent"))
if len(files) != 0 || skipped != 0 || truncated != 0 {
t.Fatalf("missing directory must be empty: %+v %d %d", files, skipped, truncated)
}
}
// runWithArtifact executes one real run whose stage writes a file into the
// runner-provided artifacts directory. It returns the live handler and the
// recorded step so tests can serve the artifact over the real HTTP endpoint.
func runWithArtifact(t *testing.T) (*runHandler, protocol.RunStep) {
t.Helper()
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
store, err := pipeline.Open(filepath.Join(t.TempDir(), "artifacts.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { store.Close() })
if _, err := store.Submit(ctx, "artifacts", pipeline.Template([]string{"one"}, true)); err != nil {
t.Fatal(err)
}
items, err := store.List(ctx)
if err != nil {
t.Fatal(err)
}
handler := Handler(ctx, store).(*runHandler)
t.Cleanup(func() { cancel(); WaitRuns(handler) })
handler.runner.artifactsRoot = t.TempDir()
handler.runner.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
if def.ArtifactsDir == "" {
t.Error("runner did not provide an artifacts directory")
return stage.Result{Outcome: "success"}, nil
}
if err := os.WriteFile(filepath.Join(def.ArtifactsDir, "report.txt"), []byte("artifact bytes"), 0600); err != nil {
return stage.Result{}, err
}
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
}
dir := t.TempDir()
run, err := handler.runner.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "artifact", Workspace: dir, Input: map[string]any{"prompt": "task"}})
if err != nil {
t.Fatal(err)
}
handler.runner.wg.Wait()
detail, err := store.GetRun(ctx, run.ID)
if err != nil {
t.Fatal(err)
}
if detail.Status != "succeeded" || len(detail.Steps) != 1 {
t.Fatalf("unexpected run: %+v", detail)
}
step := detail.Steps[0]
if len(step.Artifacts) != 1 {
t.Fatalf("artifact not retained: %+v", step.Artifacts)
}
artifact := step.Artifacts[0]
if artifact.Name != "report.txt" || artifact.SizeBytes != int64(len("artifact bytes")) ||
!strings.HasPrefix(artifact.ContentType, "text/plain") || artifact.URL == "" {
t.Fatalf("recorded artifact wrong: %+v", artifact)
}
return handler, step
}
func TestArtifactHTTPGetHeadRangeAndRefusals(t *testing.T) {
handler, step := runWithArtifact(t)
srv := httptest.NewServer(handler)
defer srv.Close()
base := srv.URL + step.Artifacts[0].URL
payload := []byte("artifact bytes")
resp, err := http.Get(base)
if err != nil {
t.Fatal(err)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != http.StatusOK || !bytes.Equal(body, payload) {
t.Fatalf("GET wrong: %d %q", resp.StatusCode, body)
}
if ct := resp.Header.Get("Content-Type"); !strings.HasPrefix(ct, "text/plain") {
t.Fatalf("GET content type wrong: %q", ct)
}
if cl := resp.Header.Get("Content-Length"); cl != fmt.Sprint(len(payload)) {
t.Fatalf("GET content length wrong: %q", cl)
}
head, err := http.Head(base)
if err != nil {
t.Fatal(err)
}
headBody, _ := io.ReadAll(head.Body)
head.Body.Close()
if head.StatusCode != http.StatusOK || len(headBody) != 0 {
t.Fatalf("HEAD wrong: %d %q", head.StatusCode, headBody)
}
if head.Header.Get("Content-Length") != fmt.Sprint(len(payload)) {
t.Fatalf("HEAD lost content length: %q", head.Header.Get("Content-Length"))
}
rangeReq, _ := http.NewRequest(http.MethodGet, base, nil)
rangeReq.Header.Set("Range", "bytes=0-3")
rangeResp, err := http.DefaultClient.Do(rangeReq)
if err != nil {
t.Fatal(err)
}
rangeBody, _ := io.ReadAll(rangeResp.Body)
rangeResp.Body.Close()
if rangeResp.StatusCode != http.StatusPartialContent || !bytes.Equal(rangeBody, payload[:4]) {
t.Fatalf("Range wrong: %d %q", rangeResp.StatusCode, rangeBody)
}
if got := rangeResp.Header.Get("Content-Range"); got != fmt.Sprintf("bytes 0-3/%d", len(payload)) {
t.Fatalf("Content-Range wrong: %q", got)
}
unsatReq, _ := http.NewRequest(http.MethodGet, base, nil)
unsatReq.Header.Set("Range", "bytes=9999-10000")
unsatResp, err := http.DefaultClient.Do(unsatReq)
if err != nil {
t.Fatal(err)
}
unsatResp.Body.Close()
if unsatResp.StatusCode != http.StatusRequestedRangeNotSatisfiable {
t.Fatalf("unsatisfiable Range wrong: %d", unsatResp.StatusCode)
}
// Unknown run and unknown step must not serve bytes.
for _, path := range []string{"/artifacts/999999/1/report.txt", fmt.Sprintf("/artifacts/%d/99/report.txt", runIDFromURL(step.Artifacts[0].URL))} {
resp, err := http.Get(srv.URL + path)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusNotFound {
t.Fatalf("%s expected 404, got %d", path, resp.StatusCode)
}
}
}
func runIDFromURL(url string) int64 {
var id int64
fmt.Sscanf(url, "/artifacts/%d/", &id)
return id
}
func TestArtifactHTTPRefusesEscapes(t *testing.T) {
handler, step := runWithArtifact(t)
runID := runIDFromURL(step.Artifacts[0].URL)
root := handler.runner.artifactsRoot
// A symlink inside the step directory must never be followed.
stepDir := filepath.Join(root, fmt.Sprint(runID), "1")
secret := filepath.Join(t.TempDir(), "secret.txt")
if err := os.WriteFile(secret, []byte("secret"), 0600); err != nil {
t.Fatal(err)
}
if err := os.Symlink(secret, filepath.Join(stepDir, "escape.txt")); err != nil {
t.Fatal(err)
}
srv := httptest.NewServer(handler)
defer srv.Close()
for _, path := range []string{
fmt.Sprintf("/artifacts/%d/1/escape.txt", runID),
fmt.Sprintf("/artifacts/%d/1/%%2e%%2e/%%2e%%2e/secret.txt", runID),
fmt.Sprintf("/artifacts/%d/1/%%2Fetc%%2Fpasswd", runID),
} {
resp, err := http.Get(srv.URL + path)
if err != nil {
t.Fatal(err)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode == http.StatusOK || bytes.Contains(body, []byte("secret")) {
t.Fatalf("%s served forbidden bytes: %d %q", path, resp.StatusCode, body)
}
}
}
+29 -12
View File
@@ -8,6 +8,7 @@ import (
"maps"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
@@ -28,13 +29,14 @@ type activeRun struct {
}
type runner struct {
ctx context.Context
store *pipeline.Store
mu sync.Mutex
active map[int64]activeRun
execute func(context.Context, stage.Definition, stage.Values) (stage.Result, error)
wg sync.WaitGroup
schedulerWG sync.WaitGroup
ctx context.Context
store *pipeline.Store
artifactsRoot string
mu sync.Mutex
active map[int64]activeRun
execute func(context.Context, stage.Definition, stage.Values) (stage.Result, error)
wg sync.WaitGroup
schedulerWG sync.WaitGroup
}
func newRunner(ctx context.Context, s *pipeline.Store) (*runner, error) {
@@ -58,7 +60,8 @@ func newRunner(ctx context.Context, s *pipeline.Store) (*runner, error) {
if err := s.RecoverRuns(ctx); err != nil {
return nil, err
}
return &runner{ctx: ctx, store: s, active: map[int64]activeRun{}}, nil
root := filepath.Join(s.Directory(), "artifacts")
return &runner{ctx: ctx, store: s, artifactsRoot: root, active: map[int64]activeRun{}}, nil
}
func (r *runner) start(request protocol.Message, retryOf ...int64) (*protocol.RunDetail, error) {
@@ -357,8 +360,21 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail,
return
}
useAgent := stage.EffectiveType(def.Type) == stage.ModelType && (len(tools) > 0 || !explicitTools)
// Every agent visit gets a per-run/step directory for the files it
// produces. Creation is best-effort: an unusable directory must never
// fail the run, and it is only attempted for model stages.
artifactsDir := ""
if stage.EffectiveType(def.Type) == stage.ModelType {
candidate := filepath.Join(r.artifactsRoot, strconv.FormatInt(id, 10), strconv.Itoa(sequence))
if mkErr := os.MkdirAll(candidate, 0700); mkErr != nil {
log.Printf("stage artifacts directory run=%d step=%d: %v", id, sequence, mkErr)
} else {
artifactsDir = candidate
def.ArtifactsDir = candidate
}
}
operations := &stage.OperationLog{}
client := &stage.AgentClient{OpenCodeClient: stage.OpenCodeClient{Directory: workspace, Operations: operations}, WritePaths: request.WritePaths, Tools: tools}
client := &stage.AgentClient{OpenCodeClient: stage.OpenCodeClient{Directory: workspace, Operations: operations, ArtifactsDir: artifactsDir}, WritePaths: request.WritePaths, Tools: tools}
client.OnSession = func(session string, active bool) error {
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
@@ -409,7 +425,7 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail,
err = fmt.Errorf("Pi is not configured on execution server")
return
}
piClient = &stage.PiClient{Executable: profile.Executable, Directory: workspace, Tools: tools, WritePaths: request.WritePaths}
piClient = &stage.PiClient{Executable: profile.Executable, Directory: workspace, Tools: tools, WritePaths: request.WritePaths, ArtifactsDir: artifactsDir}
piClient.OnOwnership = func(session, reference string, active bool) error {
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
@@ -422,7 +438,7 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail,
result, err = (stage.ModelStage{Client: client}).Run(stageCtx, def, input)
stageSession = client.SessionID
} else if stage.EffectiveType(def.Type) == stage.ModelType {
plain := &stage.OpenCodeClient{Directory: workspace, Operations: operations}
plain := &stage.OpenCodeClient{Directory: workspace, Operations: operations, ArtifactsDir: artifactsDir}
plain.OnGenerationSession = func(session, backend, reference string, active bool) error {
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
@@ -446,7 +462,8 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail,
changes.Status = "partial"
changes.Diagnostic = "Agent cleanup was not confirmed; files may still be changing."
}
step := protocol.RunStep{Sequence: sequence, Stage: key, Status: "completed", Outcome: result.Outcome, Output: result.Output, Transcript: operations.Transcript(client.Transcript), SessionID: stageSession, FileChanges: changes}
artifacts, artifactsSkipped, artifactsTruncated := r.scanArtifacts(id, sequence, artifactsDir)
step := protocol.RunStep{Sequence: sequence, Stage: key, Status: "completed", Outcome: result.Outcome, Output: result.Output, Transcript: operations.Transcript(client.Transcript), SessionID: stageSession, FileChanges: changes, Artifacts: artifacts, ArtifactsSkipped: artifactsSkipped, ArtifactsTruncated: artifactsTruncated}
if budget := budgets[key]; budget != nil {
step.Transcript = stage.BudgetTranscript(step.Transcript, budget, modelConfig.Timeout, modelConfig.Retries)
}
+25 -1
View File
@@ -16,8 +16,22 @@ import (
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// Handler serves the persistent connection. Canceling ctx stops active clients.
// Options configures the HTTP handler.
type Options struct {
// ArtifactsRoot overrides where stage artifacts live. Empty uses the store's
// directory (the database's parent), matching the data-directory default.
ArtifactsRoot string
}
// Handler serves the persistent connection with default options. Canceling ctx
// stops active clients.
func Handler(ctx context.Context, stores ...*pipeline.Store) http.Handler {
return HandlerWithOptions(ctx, Options{}, stores...)
}
// HandlerWithOptions serves the persistent connection and the stage-artifact
// endpoint. Canceling ctx stops active clients.
func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipeline.Store) http.Handler {
build := buildinfo.Current()
started := time.Now()
mux := http.NewServeMux()
@@ -25,11 +39,21 @@ func Handler(ctx context.Context, stores ...*pipeline.Store) http.Handler {
var runErr error
if len(stores) > 0 {
runs, runErr = newRunner(ctx, stores[0])
if runErr == nil && options.ArtifactsRoot != "" {
runs.artifactsRoot = options.ArtifactsRoot
}
if runErr == nil {
runs.schedulerWG.Add(1)
go runs.scheduleLoop()
}
}
mux.HandleFunc("GET /artifacts/{run}/{step}/{name...}", func(w http.ResponseWriter, r *http.Request) {
if runs == nil {
http.NotFound(w, r)
return
}
runs.serveArtifact(w, r)
})
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if runErr != nil {