From def1bf6514ba4fb1a07134e39880c39e138a9165 Mon Sep 17 00:00:00 2001 From: Moshe Immerman Date: Tue, 27 Oct 2026 11:22:08 +0200 Subject: [PATCH] feat: support cancellable and authorized report tasks --- entity/command.go | 10 ++-- entity/delete_flags_spec_test.go | 2 +- entity/entity_action_error_spec_test.go | 2 +- entity/entity_cli.go | 10 ++-- entity/primary_action.go | 2 +- entity/render.go | 7 ++- entity_aliases.go | 6 ++- format.go | 7 +-- format_sinks_ginkgo_test.go | 37 ++++++++++++++ formatters/format_spec_ginkgo_test.go | 7 +++ formatters/manager_context.go | 13 +++-- formatters/manager_options_test.go | 15 ++++++ formatters/options.go | 9 +++- task/api.go | 18 ++++++- task/authorization_ginkgo_test.go | 65 +++++++++++++++++++++++++ task/source.go | 54 ++++++++++++++++++++ task/sse.go | 10 ++-- 17 files changed, 243 insertions(+), 31 deletions(-) create mode 100644 task/authorization_ginkgo_test.go diff --git a/entity/command.go b/entity/command.go index d813988d..b10ff72b 100644 --- a/entity/command.go +++ b/entity/command.go @@ -391,20 +391,20 @@ func addNamedCommand[T any, R any]( }) if err != nil { if result != nil { - err = errors.Join(err, RenderResult(result)) + err = errors.Join(err, RenderResult(ctx, result)) } - return renderCommandError(name, err) + return renderCommandError(ctx, name, err) } - return RenderResult(result) + return RenderResult(ctx, result) } return cmd } -func renderCommandError(name string, err error) error { +func renderCommandError(ctx context.Context, name string, err error) error { if rich, ok := renderableError(err); ok { - if renderErr := RenderResult(rich); renderErr != nil { + if renderErr := RenderResult(ctx, rich); renderErr != nil { return renderErr } } else { diff --git a/entity/delete_flags_spec_test.go b/entity/delete_flags_spec_test.go index ec0fd7b5..f6019d28 100644 --- a/entity/delete_flags_spec_test.go +++ b/entity/delete_flags_spec_test.go @@ -36,7 +36,7 @@ var _ = Describe("entity delete with flags", func() { BeforeEach(func() { rendered = nil originalRender := RenderResult - RenderResult = func(value any) error { + RenderResult = func(_ context.Context, value any) error { rendered = append(rendered, value) return nil } diff --git a/entity/entity_action_error_spec_test.go b/entity/entity_action_error_spec_test.go index 6db517b6..ccbb802e 100644 --- a/entity/entity_action_error_spec_test.go +++ b/entity/entity_action_error_spec_test.go @@ -30,7 +30,7 @@ var _ = Describe("entity action errors", func() { var rendered any originalRender := RenderResult - RenderResult = func(value any) error { + RenderResult = func(_ context.Context, value any) error { rendered = value return nil } diff --git a/entity/entity_cli.go b/entity/entity_cli.go index 6ab1226f..b832bd2f 100644 --- a/entity/entity_cli.go +++ b/entity/entity_cli.go @@ -315,7 +315,7 @@ func generateListCommand(parent *cobra.Command, entity EntityInfo, op EntityOper if err != nil { return err } - return RenderResult(result) + return RenderResult(c.Context(), result) }, } @@ -403,10 +403,10 @@ func generateIDCommand(parent *cobra.Command, spec idCommand) { } result, err := runEntityOp(c, op, flagMap, args) if err != nil { - return renderCommandError(verb, err) + return renderCommandError(c.Context(), verb, err) } if result != nil { - return RenderResult(result) + return RenderResult(c.Context(), result) } return nil }, @@ -515,7 +515,7 @@ func generateBodyCommand(parent *cobra.Command, verb, short string, op EntityOpe return err } if result != nil { - return RenderResult(result) + return RenderResult(c.Context(), result) } return nil }, @@ -585,7 +585,7 @@ func generateBulkActionCommand(parent *cobra.Command, ba BulkActionInfo) { return err } if result != nil { - return RenderResult(result) + return RenderResult(c.Context(), result) } return nil }, diff --git a/entity/primary_action.go b/entity/primary_action.go index e69133b8..f75642b0 100644 --- a/entity/primary_action.go +++ b/entity/primary_action.go @@ -42,7 +42,7 @@ func generatePrimaryAction(entityCmd *cobra.Command, action ActionInfo) { return err } if result != nil { - return RenderResult(result) + return RenderResult(c.Context(), result) } return nil } diff --git a/entity/render.go b/entity/render.go index 38cc8a46..23cf7517 100644 --- a/entity/render.go +++ b/entity/render.go @@ -1,6 +1,9 @@ package entity -import "fmt" +import ( + "context" + "fmt" +) // ParseArgs parses HTTPie-style positional arguments (key=value, key:=json, …) // into a body map for create/update commands. Root clicky wires it in init() to @@ -19,7 +22,7 @@ var ParseArgs = func(args []string) (map[string]any, error) { // It is a package-level hook rather than a direct dependency so the entity // package stays free of the root clicky package (which owns the global flag // state) — preserving the one-way entity → clicky-subpackages dependency. -var RenderResult = func(o any) error { return nil } +var RenderResult = func(ctx context.Context, o any) error { return nil } // PreflightOutput validates CLI output options before a generated operation runs. var PreflightOutput = func() error { return nil } diff --git a/entity_aliases.go b/entity_aliases.go index a50a9620..26f8744a 100644 --- a/entity_aliases.go +++ b/entity_aliases.go @@ -17,11 +17,13 @@ import ( func init() { entity.PreflightOutput = Flags.ParseFormatSpec - entity.RenderResult = func(o any) error { + entity.RenderResult = func(ctx context.Context, o any) error { if err := Flags.ParseFormatSpec(); err != nil { return err } - return PrintAndWriteSinks(o, Flags.FormatOptions) + options := Flags.FormatOptions + options.Context = ctx + return PrintAndWriteSinks(o, options) } entity.ParseArgs = ParseArgumentsAsMap } diff --git a/format.go b/format.go index 5950588b..a415e517 100644 --- a/format.go +++ b/format.go @@ -153,7 +153,8 @@ func MustPrint(o any, opts ...FormatOptions) { // Terminate the output. Without this the shell prompt lands on the last // rendered line, and line-oriented consumers of a redirect drop it. - if result != "" && !strings.HasSuffix(result, "\n") { + options := formatters.MergeOptions(append([]FormatOptions{defaultOpts}, opts...)...) + if result != "" && !strings.HasSuffix(result, "\n") && !formatters.IsBinaryFormat(options.ResolveFormat()) { result += "\n" } fmt.Print(result) @@ -171,7 +172,7 @@ func MustPrintStderr(o any, opts ...FormatOptions) { if err != nil { panic(err) } - if result != "" && !strings.HasSuffix(result, "\n") { + if result != "" && !strings.HasSuffix(result, "\n") && !formatters.IsBinaryFormat(options.ResolveFormat()) { result += "\n" } fmt.Fprint(os.Stderr, result) @@ -235,7 +236,7 @@ func printFormat(o any, opts FormatOptions) error { if err != nil { return err } - if output != "" && !strings.HasSuffix(output, "\n") && opts.Format != "excel" && opts.Format != "pdf" { + if output != "" && !strings.HasSuffix(output, "\n") && !formatters.IsBinaryFormat(opts.ResolveFormat()) { output += "\n" } _, err = fmt.Fprint(os.Stdout, output) diff --git a/format_sinks_ginkgo_test.go b/format_sinks_ginkgo_test.go index b9331e80..2c3480bf 100644 --- a/format_sinks_ginkgo_test.go +++ b/format_sinks_ginkgo_test.go @@ -1,6 +1,7 @@ package clicky import ( + "context" "errors" "io" "os" @@ -9,6 +10,7 @@ import ( "github.com/flanksource/clicky/formatters" "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" + "github.com/spf13/cobra" ) type sinkViews struct{} @@ -46,6 +48,41 @@ func (sinkViews) FormatView(opts FormatOptions) (any, error) { } var _ = ginkgo.Describe("format sinks", func() { + ginkgo.It("passes a generated command context to its formatter", func() { + type contextKey struct{} + var received context.Context + formatters.RegisterFormatter("context-report", func(_ any, opts formatters.FormatOptions) (string, error) { + received = opts.Context + return "", nil + }) + defer formatters.UnregisterFormatter("context-report") + previous := Flags.FormatOptions + defer func() { Flags.FormatOptions = previous }() + Flags.FormatOptions = FormatOptions{Format: "context-report"} + parent := &cobra.Command{Use: "root"} + command := AddNamedCommandWithContext("report", parent, struct{}{}, func(context.Context, struct{}) (string, error) { return "report", nil }) + ctx, cancel := context.WithCancel(context.WithValue(context.Background(), contextKey{}, "command")) + cancel() + command.SetContext(ctx) + Expect(command.RunE(command, nil)).To(Succeed()) + Expect(received.Value(contextKey{})).To(Equal("command")) + Expect(received.Err()).To(MatchError(context.Canceled)) + }) + ginkgo.It("writes a registered binary formatter to stdout without changing its bytes", func() { + formatters.RegisterFormatter("binary-report", func(any, formatters.FormatOptions) (string, error) { + return "%PDF-binary", nil + }, formatters.WithContentType("application/pdf")) + defer formatters.UnregisterFormatter("binary-report") + output, err := os.CreateTemp(ginkgo.GinkgoT().TempDir(), "stdout") + Expect(err).NotTo(HaveOccurred()) + original := os.Stdout + os.Stdout = output + defer func() { os.Stdout = original; _ = output.Close() }() + Expect(printFormat("report", FormatOptions{Format: "binary-report"})).To(Succeed()) + contents, err := os.ReadFile(output.Name()) + Expect(err).NotTo(HaveOccurred()) + Expect(string(contents)).To(Equal("%PDF-binary")) + }) ginkgo.It("uses an independent view for every format", func() { dir := ginkgo.GinkgoT().TempDir() jsonPath := filepath.Join(dir, "rows.json") diff --git a/formatters/format_spec_ginkgo_test.go b/formatters/format_spec_ginkgo_test.go index afdf3472..13c20a00 100644 --- a/formatters/format_spec_ginkgo_test.go +++ b/formatters/format_spec_ginkgo_test.go @@ -8,6 +8,13 @@ import ( ) var _ = Describe("format specification preflight", func() { + It("accepts registered custom formats for stdout and file sinks", func() { + RegisterFormatter("report-format", func(any, FormatOptions) (string, error) { return "report", nil }) + defer UnregisterFormatter("report-format") + opts := FormatOptions{Format: "report-format,report-format=report.html"} + Expect(opts.ParseFormatSpec()).To(Succeed()) + Expect(opts.Sinks).To(Equal([]FormatSink{{Format: "report-format"}, {Format: "report-format", File: "report.html"}})) + }) It("leaves no partial sinks after a bad entry", func() { opts := FormatOptions{Format: "json=rows.json,unknown"} Expect(opts.ParseFormatSpec()).To(MatchError(ContainSubstring("unknown format"))) diff --git a/formatters/manager_context.go b/formatters/manager_context.go index 9101b9fa..293efcbe 100644 --- a/formatters/manager_context.go +++ b/formatters/manager_context.go @@ -15,6 +15,9 @@ import ( // forwarded to registered format callbacks. func (f *FormatManager) FormatWithContext(ctx any, options FormatOptions, data ...any) (string, error) { defer rpchttp.Track(callerContext(ctx), "format")() + if ctx != nil || options.Context == nil { + options.Context = callerContext(ctx) + } options.NoColor = options.NoColor || f.noColor before := collapseFormatInput(data...) before = f.applyBeforeFormatCallbacks(ctx, options, before) @@ -23,7 +26,7 @@ func (f *FormatManager) FormatWithContext(ctx any, options FormatOptions, data . return "", err } output = f.applyAfterFormatCallbacks(ctx, options, before, output) - if options.NoColor && !isBinaryFormat(options.ResolveFormat()) { + if options.NoColor && !IsBinaryFormat(options.ResolveFormat()) { output = ansi.Strip(output) } return output, nil @@ -32,6 +35,9 @@ func (f *FormatManager) FormatWithContext(ctx any, options FormatOptions, data . // FormatWithSchemaContext handles schema-aware formatting while forwarding ctx // to registered format callbacks. func (f *FormatManager) FormatWithSchemaContext(ctx any, prettyData *api.PrettyData, options FormatOptions) (string, error) { + if ctx != nil || options.Context == nil { + options.Context = callerContext(ctx) + } options.NoColor = options.NoColor || f.noColor before := any(prettyData) before = f.applyBeforeFormatCallbacks(ctx, options, before) @@ -86,13 +92,14 @@ func (f *FormatManager) FormatWithSchemaContext(ctx any, prettyData *api.PrettyD return "", err } output = f.applyAfterFormatCallbacks(ctx, options, before, output) - if options.NoColor && !isBinaryFormat(format) { + if options.NoColor && !IsBinaryFormat(format) { output = ansi.Strip(output) } return output, nil } -func isBinaryFormat(format string) bool { +// IsBinaryFormat reports whether a built-in or registered format emits binary data. +func IsBinaryFormat(format string) bool { switch canonicalFormat(strings.ToLower(format)) { case "pdf", "html-pdf", "excel": return true diff --git a/formatters/manager_options_test.go b/formatters/manager_options_test.go index f928840b..355bcaf2 100644 --- a/formatters/manager_options_test.go +++ b/formatters/manager_options_test.go @@ -1,12 +1,27 @@ package formatters import ( + "context" "github.com/flanksource/clicky/api" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" + "net/http/httptest" ) var _ = Describe("Non-terminal format manager", func() { + It("passes the request context to custom formatters", func() { + type key struct{} + ctx, cancel := context.WithCancel(context.WithValue(context.Background(), key{}, "request")) + request := httptest.NewRequest("GET", "/", nil).WithContext(ctx) + RegisterFormatter("context-test", func(_ any, opts FormatOptions) (string, error) { + Expect(opts.Context.Value(key{})).To(Equal("request")) + cancel() + return "", opts.Context.Err() + }) + DeferCleanup(UnregisterFormatter, "context-test") + _, err := NewFormatManager().FormatWithContext(request, FormatOptions{Format: "context-test"}, "example") + Expect(err).To(MatchError(context.Canceled)) + }) DescribeTable("preserves binary bytes with NoColor on both formatting paths", func(format string) { const binary = "binary\x00\xff\x1b[31mpayload\x1b[0m" diff --git a/formatters/options.go b/formatters/options.go index b1d81eb6..460e66f7 100644 --- a/formatters/options.go +++ b/formatters/options.go @@ -1,6 +1,7 @@ package formatters import ( + "context" "flag" "fmt" "os" @@ -65,6 +66,7 @@ type FormatSink struct { // FormatOptions contains options for formatting operations type FormatOptions struct { + Context context.Context `json:"-" yaml:"-"` Format string `json:"format,omitempty"` NoColor bool `json:"no_color,omitempty"` Output string `json:"output,omitempty"` @@ -168,7 +170,9 @@ func (o *FormatOptions) ParseFormatSpec() error { return fmt.Errorf("invalid --format entry %q: empty format name", part) } if !knownFormats[name] { - return fmt.Errorf("invalid --format entry %q: unknown format %q", part, name) + if _, registered := GetCustomFormatter(name); !registered { + return fmt.Errorf("invalid --format entry %q: unknown format %q", part, name) + } } if hasFile && file == "" { return fmt.Errorf("invalid --format entry %q: empty file path after '='", part) @@ -226,6 +230,9 @@ func (o FormatOptions) SkipTree() bool { func MergeOptions(opts ...FormatOptions) FormatOptions { merged := FormatOptions{} for _, opt := range opts { + if opt.Context != nil { + merged.Context = opt.Context + } if opt.Format != "" { merged.Format = opt.Format } diff --git a/task/api.go b/task/api.go index 5e14e6ba..d9313198 100644 --- a/task/api.go +++ b/task/api.go @@ -55,6 +55,7 @@ func RunsHandlerWithSource(source RunSource) http.Handler { } runs = mergeRunMetas(runs, external) } + runs = visibleRuns(r.Context(), source, runs) if runs == nil { runs = []RunMeta{} } @@ -87,6 +88,7 @@ func RunHandlerWithSource(source RunSource) http.Handler { return } } + snapshots = visibleSnapshots(r.Context(), source, snapshots) if len(snapshots) == 0 { http.Error(w, "run not found", http.StatusNotFound) return @@ -110,6 +112,10 @@ func RunControlHandlerWithSource(source RunSource) http.Handler { return } id := r.PathValue("id") + if !authorizedRun(r.Context(), source, id) { + http.Error(w, "run not found", http.StatusNotFound) + return + } var err error if groupByID(id) != nil { err = ControlRun(r.Context(), id, action) @@ -140,6 +146,10 @@ func TaskControlHandlerWithSource(source RunSource) http.Handler { return } runID := r.PathValue("id") + if !authorizedRun(r.Context(), source, runID) { + http.Error(w, "run not found", http.StatusNotFound) + return + } taskID := r.PathValue("taskID") var err error if groupByID(runID) != nil { @@ -180,8 +190,12 @@ func writeControlError(w http.ResponseWriter, err error) { // TaskStdinHandler writes live stdin to a task. Input is deliberately not // included in any snapshot or persisted run record. -func TaskStdinHandler() http.Handler { +func TaskStdinHandler(source RunSource) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !authorizedRun(r.Context(), source, r.PathValue("id")) { + http.Error(w, "run not found", http.StatusNotFound) + return + } var request struct { Data string `json:"data"` } @@ -234,7 +248,7 @@ func RegisterHandlersWithSource(router *route.Router, prefix string, source RunS route.Meta{Entity: "task", Verb: "control", IDParam: "id"}) router.Raw("POST "+prefix+"/tasks/{id}/tasks/{taskID}/control", TaskControlHandlerWithSource(source), route.Meta{Entity: "task", Verb: "control-task", IDParam: "taskID"}) - router.Raw("POST "+prefix+"/tasks/{id}/tasks/{taskID}/stdin", TaskStdinHandler(), + router.Raw("POST "+prefix+"/tasks/{id}/tasks/{taskID}/stdin", TaskStdinHandler(source), route.Meta{Entity: "task", Verb: "stdin", IDParam: "taskID"}) router.Raw("GET "+prefix+"/tasks/{id}", RunHandlerWithSource(source), route.Meta{Entity: "task", Verb: "get", ReadOnly: true, IDParam: "id"}) diff --git a/task/authorization_ginkgo_test.go b/task/authorization_ginkgo_test.go new file mode 100644 index 00000000..c07f1b43 --- /dev/null +++ b/task/authorization_ginkgo_test.go @@ -0,0 +1,65 @@ +package task_test + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "time" + + "github.com/flanksource/clicky/route" + "github.com/flanksource/clicky/task" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" +) + +type ownerSource struct{} + +func (ownerSource) Runs(context.Context, task.RunFilter) ([]task.RunMeta, error) { return nil, nil } +func (ownerSource) Snapshot(context.Context, string) ([]task.TaskSnapshot, error) { return nil, nil } +func (ownerSource) Control(context.Context, string, task.ControlAction) error { return nil } +func (ownerSource) AuthorizeRun(_ context.Context, run task.RunMeta) bool { + return run.Owner == "alice" +} + +var _ = Describe("task run authorization", func() { + It("hides another owner's live run from listings, snapshots and controls", func() { + owned := task.StartManagedRun("owned task", task.WithOwner("alice")) + other := task.StartManagedRun("private task", task.WithOwner("bob")) + DeferCleanup(func() { owned.Finish(task.StatusSuccess, nil); other.Finish(task.StatusSuccess, nil) }) + mux := http.NewServeMux() + task.RegisterHandlersWithSource(route.NewRouter(mux), "/api/v1", ownerSource{}) + listing := httptest.NewRecorder() + mux.ServeHTTP(listing, httptest.NewRequest(http.MethodGet, "/api/v1/tasks", nil)) + Expect(listing.Body.String()).To(ContainSubstring(owned.ID())) + Expect(listing.Body.String()).NotTo(ContainSubstring(other.ID())) + detail := httptest.NewRecorder() + mux.ServeHTTP(detail, httptest.NewRequest(http.MethodGet, "/api/v1/tasks/"+other.ID(), nil)) + Expect(detail.Code).To(Equal(http.StatusNotFound)) + control := httptest.NewRecorder() + mux.ServeHTTP(control, httptest.NewRequest(http.MethodPost, "/api/v1/tasks/"+other.ID()+"/control", strings.NewReader(`{"action":"stop"}`))) + Expect(control.Code).To(Equal(http.StatusNotFound)) + Expect(other.Task().Status()).To(Equal(task.StatusRunning)) + }) + + It("does not stream snapshots or output from another owner's run", func() { + owned := task.StartManagedRun("owned stream", task.WithOwner("alice")) + other := task.StartManagedRun("private stream", task.WithOwner("bob")) + other.SetOutputProvider(func() task.OutputSnapshot { return task.OutputSnapshot{Stdout: "private output"} }) + DeferCleanup(func() { owned.Finish(task.StatusSuccess, nil); other.Finish(task.StatusSuccess, nil) }) + server := httptest.NewServer(task.SSEHandlerWithSource(ownerSource{})) + DeferCleanup(server.Close) + ctx, cancel := context.WithTimeout(context.Background(), 700*time.Millisecond) + defer cancel() + request, err := http.NewRequestWithContext(ctx, http.MethodGet, server.URL, nil) + Expect(err).NotTo(HaveOccurred()) + response, err := http.DefaultClient.Do(request) + Expect(err).NotTo(HaveOccurred()) + defer response.Body.Close() + data, _ := io.ReadAll(response.Body) + Expect(string(data)).To(ContainSubstring(owned.ID())) + Expect(string(data)).NotTo(ContainSubstring(other.ID())) + Expect(string(data)).NotTo(ContainSubstring("private output")) + }) +}) diff --git a/task/source.go b/task/source.go index dda52004..53b4aa88 100644 --- a/task/source.go +++ b/task/source.go @@ -15,6 +15,60 @@ type RunSource interface { Control(context.Context, string, ControlAction) error } +// RunAuthorizer filters both live and externally stored runs for a caller. +type RunAuthorizer interface { + AuthorizeRun(context.Context, RunMeta) bool +} + +func visibleRuns(ctx context.Context, source RunSource, runs []RunMeta) []RunMeta { + authorizer, ok := source.(RunAuthorizer) + if !ok { + return runs + } + visible := make([]RunMeta, 0, len(runs)) + for _, run := range runs { + if authorizer.AuthorizeRun(ctx, run) { + visible = append(visible, run) + } + } + return visible +} + +func visibleSnapshots(ctx context.Context, source RunSource, snapshots []TaskSnapshot) []TaskSnapshot { + authorizer, ok := source.(RunAuthorizer) + if !ok { + return snapshots + } + allowed := make(map[string]bool) + for _, snapshot := range snapshots { + if snapshot.Type == "group" { + allowed[snapshot.GroupID] = authorizer.AuthorizeRun(ctx, RunMetaFromSnapshot(snapshot)) + } + } + visible := make([]TaskSnapshot, 0, len(snapshots)) + for _, snapshot := range snapshots { + if allowed[snapshot.GroupID] { + visible = append(visible, snapshot) + } + } + return visible +} + +func authorizedRun(ctx context.Context, source RunSource, id string) bool { + if _, ok := source.(RunAuthorizer); !ok { + return true + } + snapshots := SnapshotByID(id) + if len(snapshots) == 0 && source != nil { + var err error + snapshots, err = source.Snapshot(ctx, id) + if err != nil { + return false + } + } + return len(visibleSnapshots(ctx, source, snapshots)) != 0 +} + // TaskControlSource is implemented by run sources that can route lifecycle // controls to child tasks owned outside this process. type TaskControlSource interface { diff --git a/task/sse.go b/task/sse.go index 9a1cdf48..be282c0e 100644 --- a/task/sse.go +++ b/task/sse.go @@ -73,7 +73,7 @@ func SSEHandlerWithSource(source RunSource, taskIDs ...string) http.Handler { case <-r.Context().Done(): return case <-ticker.C: - snapshots := snapshotsWithSource(r.Context(), source, finished, ids...) + snapshots := visibleSnapshots(r.Context(), source, snapshotsWithSource(r.Context(), source, finished, ids...)) allDone := true anyEmitted := false @@ -205,7 +205,7 @@ func emitOutputDelta( // re-emits when the listing changes, and pings in between (sse.Snapshot). A // failure to list runs ends the stream with an "event: error" frame. func RunsSSEHandler(supplement func(RunFilter) []RunMeta) http.Handler { - return runsSSEHandler(func(_ context.Context, filter RunFilter) ([]RunMeta, error) { + return runsSSEHandler(nil, func(_ context.Context, filter RunFilter) ([]RunMeta, error) { if supplement == nil { return nil, nil } @@ -215,7 +215,7 @@ func RunsSSEHandler(supplement func(RunFilter) []RunMeta) http.Handler { // RunsSSEHandlerWithSource streams both in-memory and externally-owned runs. func RunsSSEHandlerWithSource(source RunSource) http.Handler { - return runsSSEHandler(func(ctx context.Context, filter RunFilter) ([]RunMeta, error) { + return runsSSEHandler(source, func(ctx context.Context, filter RunFilter) ([]RunMeta, error) { if source == nil { return nil, nil } @@ -223,7 +223,7 @@ func RunsSSEHandlerWithSource(source RunSource) http.Handler { }) } -func runsSSEHandler(loadExternal func(context.Context, RunFilter) ([]RunMeta, error)) http.Handler { +func runsSSEHandler(source RunSource, loadExternal func(context.Context, RunFilter) ([]RunMeta, error)) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { filter := runFilterFromQuery(r) err := sse.ServeSnapshot(w, r, sse.SnapshotOptions{ @@ -233,7 +233,7 @@ func runsSSEHandler(loadExternal func(context.Context, RunFilter) ([]RunMeta, er if err != nil { return nil, fmt.Errorf("list external task runs: %w", err) } - return mergeRunMetas(RunsRaw(filter), external), nil + return visibleRuns(ctx, source, mergeRunMetas(RunsRaw(filter), external)), nil }, // Listing updates are cheaper and less urgent than per-task progress, // so poll on a slower tick than SSEHandler.