From 27400b66fb43f590adfdc086335def7da2ea2d41 Mon Sep 17 00:00:00 2001 From: Hasitha Aravinda Date: Wed, 4 Nov 2026 14:32:29 +0530 Subject: [PATCH 1/6] feat(cli): list, inspect, signal and end workflows from workflow-cli --- cli/internal/command/command_test.go | 2 + cli/internal/command/namespace.go | 7 +- cli/internal/command/root.go | 9 +- cli/internal/command/taskqueue.go | 85 +++++ cli/internal/command/workflow.go | 390 ++++++++++++++++++++ cli/internal/command/workflow_test.go | 321 ++++++++++++++++ docs/features/workflow-cli.md | 18 +- docs/guides/ARCHITECTURE.md | 2 +- docs/user-guide/manage-with-workflow-cli.md | 43 ++- docs/user-guide/monitor.md | 2 + docs/user-guide/quick-start.md | 7 +- docs/user-guide/reference/workflow-cli.md | 8 + 12 files changed, 874 insertions(+), 20 deletions(-) create mode 100644 cli/internal/command/taskqueue.go create mode 100644 cli/internal/command/workflow.go create mode 100644 cli/internal/command/workflow_test.go diff --git a/cli/internal/command/command_test.go b/cli/internal/command/command_test.go index 68790f0..cbdf759 100644 --- a/cli/internal/command/command_test.go +++ b/cli/internal/command/command_test.go @@ -58,6 +58,7 @@ type fakeEngine struct { notYetSeen int // AddSearchAttributes answers NotFound this many times, as for a namespace not yet cached adminDenied bool health *health.Server + workflows *workflowState } // One type per service: the generated Unimplemented servers share method names. @@ -81,6 +82,7 @@ func newFakeEngine() *fakeEngine { namespaces: map[string]*workflowservice.DescribeNamespaceResponse{}, attributes: map[string]map[string]enumspb.IndexedValueType{}, health: health.NewServer(), + workflows: newWorkflowState(), } f.health.SetServingStatus(healthServices["frontend"], healthpb.HealthCheckResponse_SERVING) f.health.SetServingStatus(healthServices["history"], healthpb.HealthCheckResponse_NOT_SERVING) diff --git a/cli/internal/command/namespace.go b/cli/internal/command/namespace.go index 22b539e..72439ec 100644 --- a/cli/internal/command/namespace.go +++ b/cli/internal/command/namespace.go @@ -20,7 +20,6 @@ import ( "context" "errors" "fmt" - "strings" "time" "github.com/spf13/cobra" @@ -239,9 +238,5 @@ func (c *cli) namespaceUpdateCommand() *cobra.Command { // namespaceState shows NAMESPACE_STATE_REGISTERED as Registered. func namespaceState(info *namespacepb.NamespaceInfo) string { - s := strings.TrimPrefix(info.GetState().String(), "NAMESPACE_STATE_") - if s == "" { - return "" - } - return s[:1] + strings.ToLower(s[1:]) + return enumName(info.GetState().String(), "NAMESPACE_STATE_") } diff --git a/cli/internal/command/root.go b/cli/internal/command/root.go index 5c4b79a..6b2f38c 100644 --- a/cli/internal/command/root.go +++ b/cli/internal/command/root.go @@ -82,9 +82,10 @@ func (e exitError) Error() string { return fmt.Sprintf("exit status %d", int(e)) func (c *cli) root() *cobra.Command { root := &cobra.Command{ - Use: "workflow-cli", - Short: "Operate a WSO2 Workflow Runtime engine", - Long: "workflow-cli manages a Workflow Runtime engine: its cluster, namespaces and search attributes.", + Use: "workflow-cli", + Short: "Operate a WSO2 Workflow Runtime engine", + Long: "workflow-cli manages a Workflow Runtime engine: its cluster, namespaces and search attributes, the\n" + + "workflows integrations run, and the task queues their workers poll.", SilenceUsage: true, SilenceErrors: true, } @@ -103,7 +104,7 @@ func (c *cli) root() *cobra.Command { f.StringVarP(&c.output, "output", "o", outputText, "output format: text or json") f.DurationVar(&c.timeout, "command-timeout", 30*time.Second, "limit for each command") - root.AddCommand(c.versionCommand(), c.operatorCommand(), c.configCommand()) + root.AddCommand(c.versionCommand(), c.operatorCommand(), c.workflowCommand(), c.taskQueueCommand(), c.configCommand()) return root } diff --git a/cli/internal/command/taskqueue.go b/cli/internal/command/taskqueue.go new file mode 100644 index 0000000..ee34378 --- /dev/null +++ b/cli/internal/command/taskqueue.go @@ -0,0 +1,85 @@ +// Copyright (c) 2026, WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package command + +import ( + "fmt" + "strconv" + + "github.com/spf13/cobra" + enumspb "go.temporal.io/api/enums/v1" + taskqueuepb "go.temporal.io/api/taskqueue/v1" + "go.temporal.io/api/workflowservice/v1" + "google.golang.org/protobuf/proto" +) + +func (c *cli) taskQueueCommand() *cobra.Command { + tq := &cobra.Command{Use: "task-queue", Short: "See which workers poll a task queue"} + tq.AddCommand(c.taskQueueDescribeCommand()) + return tq +} + +func (c *cli) taskQueueDescribeCommand() *cobra.Command { + var name string + cmd := &cobra.Command{ + Use: "describe", + Short: "List the workers polling a task queue for workflow and activity tasks", + Long: "Lists the workers that polled --task-queue in the last few minutes. An integration's workers poll the\n" + + "task queue named in its Config.toml; none here means no integration serves those workflows.", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + conn, s, ctx, cancel, err := c.connect(cmd) + if err != nil { + return err + } + defer cancel() + defer func() { _ = conn.Close() }() + client := workflowservice.NewWorkflowServiceClient(conn) + kinds := []struct { + name string + typ enumspb.TaskQueueType + }{{"workflow", enumspb.TASK_QUEUE_TYPE_WORKFLOW}, {"activity", enumspb.TASK_QUEUE_TYPE_ACTIVITY}} + var responses []proto.Message + rows := [][]string{{"TYPE", "WORKER", "LAST POLL", "RATE PER SECOND"}} + for _, k := range kinds { + res, err := client.DescribeTaskQueue(ctx, &workflowservice.DescribeTaskQueueRequest{ + Namespace: s.Namespace, TaskQueue: &taskqueuepb.TaskQueue{Name: name}, TaskQueueType: k.typ, + }) + if err != nil { + return fmt.Errorf("unable to describe task queue %s: %w", name, err) + } + responses = append(responses, res) + for _, p := range res.GetPollers() { + rows = append(rows, []string{k.name, p.GetIdentity(), timestamp(p.GetLastAccessTime()), + strconv.FormatFloat(p.GetRatePerSecond(), 'f', -1, 64)}) + } + } + out := cmd.OutOrStdout() + if c.output == outputJSON { + return writeJSON(out, true, responses...) + } + if len(rows) == 1 { + _, err := fmt.Fprintf(out, "No worker has polled task queue %s recently.\n", name) + return err + } + return table(out, rows) + }, + } + cmd.Flags().StringVarP(&name, "task-queue", "t", "", "the task queue (required)") + _ = cmd.MarkFlagRequired("task-queue") + return cmd +} diff --git a/cli/internal/command/workflow.go b/cli/internal/command/workflow.go new file mode 100644 index 0000000..aca46d4 --- /dev/null +++ b/cli/internal/command/workflow.go @@ -0,0 +1,390 @@ +// Copyright (c) 2026, WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package command + +import ( + "bytes" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "strconv" + "strings" + "time" + + "github.com/spf13/cobra" + commonpb "go.temporal.io/api/common/v1" + historypb "go.temporal.io/api/history/v1" + workflowpb "go.temporal.io/api/workflow/v1" + "go.temporal.io/api/workflowservice/v1" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// execution holds the --workflow-id and --run-id flags of the commands that act on one workflow. +type execution struct { + workflowID, runID string +} + +func (e *execution) flags(cmd *cobra.Command) { + cmd.Flags().StringVarP(&e.workflowID, "workflow-id", "w", "", "the workflow's ID (required)") + cmd.Flags().StringVarP(&e.runID, "run-id", "r", "", "one run of it; the latest run when not set") + _ = cmd.MarkFlagRequired("workflow-id") +} + +func (e execution) proto() *commonpb.WorkflowExecution { + return &commonpb.WorkflowExecution{WorkflowId: e.workflowID, RunId: e.runID} +} + +func (c *cli) workflowCommand() *cobra.Command { + wf := &cobra.Command{Use: "workflow", Short: "List, inspect, signal, cancel and terminate workflows"} + wf.AddCommand(c.workflowListCommand(), c.workflowCountCommand(), c.workflowDescribeCommand(), + c.workflowShowCommand(), c.workflowSignalCommand(), c.workflowCancelCommand(), c.workflowTerminateCommand()) + return wf +} + +func (c *cli) workflowListCommand() *cobra.Command { + var query string + var limit int + cmd := &cobra.Command{ + Use: "list", + Short: "List workflows, newest first", + Long: "Lists the namespace's workflows, filtered by a visibility --query such as\n" + + " 'ExecutionStatus=\"Running\" AND WorkflowKind=\"orders.Order\"'", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + if limit < 0 { + return errors.New("--limit must not be negative") + } + conn, s, ctx, cancel, err := c.connect(cmd) + if err != nil { + return err + } + defer cancel() + defer func() { _ = conn.Close() }() + client := workflowservice.NewWorkflowServiceClient(conn) + var all []*workflowpb.WorkflowExecutionInfo + var token []byte + for limit == 0 || len(all) < limit { + res, err := client.ListWorkflowExecutions(ctx, &workflowservice.ListWorkflowExecutionsRequest{ + Namespace: s.Namespace, Query: query, PageSize: 100, NextPageToken: token, + }) + if err != nil { + return fmt.Errorf("unable to list workflows: %w", err) + } + all = append(all, res.GetExecutions()...) + if token = res.GetNextPageToken(); len(token) == 0 { + break + } + } + if limit > 0 && len(all) > limit { + all = all[:limit] + } + out := cmd.OutOrStdout() + if c.output == outputJSON { + msgs := make([]proto.Message, len(all)) + for i, w := range all { + msgs[i] = w + } + return writeJSON(out, true, msgs...) + } + rows := [][]string{{"STATUS", "WORKFLOW ID", "TYPE", "START TIME"}} + for _, w := range all { + rows = append(rows, []string{enumName(w.GetStatus().String(), "WORKFLOW_EXECUTION_STATUS_"), + w.GetExecution().GetWorkflowId(), w.GetType().GetName(), timestamp(w.GetStartTime())}) + } + return table(out, rows) + }, + } + cmd.Flags().StringVarP(&query, "query", "q", "", "a visibility query") + cmd.Flags().IntVar(&limit, "limit", 100, "the most workflows to show; 0 for all") + return cmd +} + +func (c *cli) workflowCountCommand() *cobra.Command { + var query string + cmd := &cobra.Command{ + Use: "count", + Short: "Count workflows", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + conn, s, ctx, cancel, err := c.connect(cmd) + if err != nil { + return err + } + defer cancel() + defer func() { _ = conn.Close() }() + res, err := workflowservice.NewWorkflowServiceClient(conn).CountWorkflowExecutions(ctx, + &workflowservice.CountWorkflowExecutionsRequest{Namespace: s.Namespace, Query: query}) + if err != nil { + return fmt.Errorf("unable to count workflows: %w", err) + } + if c.output == outputJSON { + return writeJSON(cmd.OutOrStdout(), false, res) + } + _, err = fmt.Fprintf(cmd.OutOrStdout(), "Total: %d\n", res.GetCount()) + return err + }, + } + cmd.Flags().StringVarP(&query, "query", "q", "", "a visibility query") + return cmd +} + +func (c *cli) workflowDescribeCommand() *cobra.Command { + var e execution + cmd := &cobra.Command{ + Use: "describe", + Short: "Show a workflow's status, type, task queue and pending work", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + conn, s, ctx, cancel, err := c.connect(cmd) + if err != nil { + return err + } + defer cancel() + defer func() { _ = conn.Close() }() + res, err := workflowservice.NewWorkflowServiceClient(conn).DescribeWorkflowExecution(ctx, + &workflowservice.DescribeWorkflowExecutionRequest{Namespace: s.Namespace, Execution: e.proto()}) + if err != nil { + return fmt.Errorf("unable to describe workflow %s: %w", e.workflowID, err) + } + out := cmd.OutOrStdout() + if c.output == outputJSON { + return writeJSON(out, false, res) + } + w := res.GetWorkflowExecutionInfo() + return table(out, [][]string{ + {"Workflow ID", w.GetExecution().GetWorkflowId()}, + {"Run ID", w.GetExecution().GetRunId()}, + {"Type", w.GetType().GetName()}, + {"Task queue", w.GetTaskQueue()}, + {"Status", enumName(w.GetStatus().String(), "WORKFLOW_EXECUTION_STATUS_")}, + {"Start time", timestamp(w.GetStartTime())}, + {"Close time", timestamp(w.GetCloseTime())}, + {"History events", strconv.FormatInt(w.GetHistoryLength(), 10)}, + {"Pending activities", strconv.Itoa(len(res.GetPendingActivities()))}, + {"Pending child workflows", strconv.Itoa(len(res.GetPendingChildren()))}, + }) + }, + } + e.flags(cmd) + return cmd +} + +func (c *cli) workflowShowCommand() *cobra.Command { + var e execution + cmd := &cobra.Command{ + Use: "show", + Short: "Show a workflow's event history", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + conn, s, ctx, cancel, err := c.connect(cmd) + if err != nil { + return err + } + defer cancel() + defer func() { _ = conn.Close() }() + client := workflowservice.NewWorkflowServiceClient(conn) + history := &historypb.History{} + var token []byte + for { + res, err := client.GetWorkflowExecutionHistory(ctx, &workflowservice.GetWorkflowExecutionHistoryRequest{ + Namespace: s.Namespace, Execution: e.proto(), NextPageToken: token, + }) + if err != nil { + return fmt.Errorf("unable to read the history of workflow %s: %w", e.workflowID, err) + } + history.Events = append(history.Events, res.GetHistory().GetEvents()...) + if token = res.GetNextPageToken(); len(token) == 0 { + break + } + } + out := cmd.OutOrStdout() + if c.output == outputJSON { + return writeJSON(out, false, history) + } + rows := [][]string{{"ID", "TIME", "TYPE"}} + for _, ev := range history.GetEvents() { + rows = append(rows, []string{strconv.FormatInt(ev.GetEventId(), 10), timestamp(ev.GetEventTime()), + enumName(ev.GetEventType().String(), "EVENT_TYPE_")}) + } + return table(out, rows) + }, + } + e.flags(cmd) + return cmd +} + +func (c *cli) workflowSignalCommand() *cobra.Command { + var e execution + var name string + var inputs []string + cmd := &cobra.Command{ + Use: "signal", + Short: "Send a signal, such as an integration's data event, to a workflow", + Long: "Sends --name with each --input as a JSON argument, for example\n" + + " workflow-cli workflow signal -w order-1 --name approval --input '{\"approved\":true}'", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + payloads, err := jsonPayloads(inputs) + if err != nil { + return err + } + conn, s, ctx, cancel, err := c.connect(cmd) + if err != nil { + return err + } + defer cancel() + defer func() { _ = conn.Close() }() + _, err = workflowservice.NewWorkflowServiceClient(conn).SignalWorkflowExecution(ctx, + &workflowservice.SignalWorkflowExecutionRequest{ + Namespace: s.Namespace, WorkflowExecution: e.proto(), SignalName: name, Input: payloads, + Identity: identity(), RequestId: requestID(), + }) + if err != nil { + return fmt.Errorf("unable to signal workflow %s: %w", e.workflowID, err) + } + _, err = fmt.Fprintf(cmd.OutOrStdout(), "Signal %s sent to workflow %s.\n", name, e.workflowID) + return err + }, + } + e.flags(cmd) + cmd.Flags().StringVar(&name, "name", "", "the signal's name (required)") + cmd.Flags().StringArrayVarP(&inputs, "input", "i", nil, "a JSON argument; repeat for more") + _ = cmd.MarkFlagRequired("name") + return cmd +} + +func (c *cli) workflowCancelCommand() *cobra.Command { + var e execution + var reason string + cmd := &cobra.Command{ + Use: "cancel", + Short: "Ask a workflow to cancel; it can clean up before it closes", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + conn, s, ctx, cancel, err := c.connect(cmd) + if err != nil { + return err + } + defer cancel() + defer func() { _ = conn.Close() }() + _, err = workflowservice.NewWorkflowServiceClient(conn).RequestCancelWorkflowExecution(ctx, + &workflowservice.RequestCancelWorkflowExecutionRequest{ + Namespace: s.Namespace, WorkflowExecution: e.proto(), Reason: reason, + Identity: identity(), RequestId: requestID(), + }) + if err != nil { + return fmt.Errorf("unable to cancel workflow %s: %w", e.workflowID, err) + } + _, err = fmt.Fprintf(cmd.OutOrStdout(), "Cancellation requested for workflow %s.\n", e.workflowID) + return err + }, + } + e.flags(cmd) + cmd.Flags().StringVar(&reason, "reason", "", "why, recorded in its history") + return cmd +} + +func (c *cli) workflowTerminateCommand() *cobra.Command { + var e execution + var reason string + cmd := &cobra.Command{ + Use: "terminate", + Short: "End a workflow at once, without letting it clean up", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + conn, s, ctx, cancel, err := c.connect(cmd) + if err != nil { + return err + } + defer cancel() + defer func() { _ = conn.Close() }() + _, err = workflowservice.NewWorkflowServiceClient(conn).TerminateWorkflowExecution(ctx, + &workflowservice.TerminateWorkflowExecutionRequest{ + Namespace: s.Namespace, WorkflowExecution: e.proto(), Reason: reason, Identity: identity(), + }) + if err != nil { + return fmt.Errorf("unable to terminate workflow %s: %w", e.workflowID, err) + } + _, err = fmt.Fprintf(cmd.OutOrStdout(), "Workflow %s terminated.\n", e.workflowID) + return err + }, + } + e.flags(cmd) + cmd.Flags().StringVar(&reason, "reason", "", "why, recorded in its history") + return cmd +} + +// jsonPayloads encodes each input as a json/plain payload, the encoding ballerina/workflow and the Temporal SDKs read. +func jsonPayloads(inputs []string) (*commonpb.Payloads, error) { + if len(inputs) == 0 { + return nil, nil + } + payloads := &commonpb.Payloads{} + for _, in := range inputs { + var compact bytes.Buffer + if err := json.Compact(&compact, []byte(in)); err != nil { + return nil, fmt.Errorf("--input %q is not JSON; quote a string as '\"text\"'", in) + } + payloads.Payloads = append(payloads.Payloads, &commonpb.Payload{ + Metadata: map[string][]byte{"encoding": []byte("json/plain")}, Data: compact.Bytes(), + }) + } + return payloads, nil +} + +// identity names the caller in a workflow's history, as the Temporal CLI does. +func identity() string { + host, err := os.Hostname() + if err != nil { + host = "unknown" + } + return "workflow-cli@" + host +} + +// requestID makes a repeated call with the same ID a no-op on the engine; each command run is a new request. +func requestID() string { + b := make([]byte, 16) + _, _ = rand.Read(b) + return hex.EncodeToString(b) +} + +func timestamp(t *timestamppb.Timestamp) string { + if t == nil || t.AsTime().IsZero() { + return "" + } + return t.AsTime().UTC().Format(time.RFC3339) +} + +// enumName shows WORKFLOW_EXECUTION_STATUS_RUNNING as Running and EVENT_TYPE_TIMER_STARTED as TimerStarted; the +// Temporal API's enums already print in that form, which is kept as it is. +func enumName(s, prefix string) string { + if !strings.Contains(s, "_") { + return s + } + var b strings.Builder + for _, word := range strings.Split(strings.TrimPrefix(s, prefix), "_") { + if word == "" { + continue + } + b.WriteString(word[:1] + strings.ToLower(word[1:])) + } + return b.String() +} diff --git a/cli/internal/command/workflow_test.go b/cli/internal/command/workflow_test.go new file mode 100644 index 0000000..b9a99c5 --- /dev/null +++ b/cli/internal/command/workflow_test.go @@ -0,0 +1,321 @@ +// Copyright (c) 2026, WSO2 LLC. (http://www.wso2.com). +// +// WSO2 LLC. licenses this file to you under the Apache License, +// Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package command + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "testing" + "time" + + commonpb "go.temporal.io/api/common/v1" + enumspb "go.temporal.io/api/enums/v1" + historypb "go.temporal.io/api/history/v1" + "go.temporal.io/api/serviceerror" + taskqueuepb "go.temporal.io/api/taskqueue/v1" + workflowpb "go.temporal.io/api/workflow/v1" + "go.temporal.io/api/workflowservice/v1" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// workflowState is the fake engine's workflows: their info, history, and the calls made on them. +type workflowState struct { + infos []*workflowpb.WorkflowExecutionInfo + events []*historypb.HistoryEvent + signals []*workflowservice.SignalWorkflowExecutionRequest + cancels []*workflowservice.RequestCancelWorkflowExecutionRequest + ends []*workflowservice.TerminateWorkflowExecutionRequest + queries []string + pollers map[enumspb.TaskQueueType][]*taskqueuepb.PollerInfo +} + +var started = time.Date(2026, 11, 4, 9, 30, 0, 0, time.UTC) + +func newWorkflowState() *workflowState { + w := &workflowState{pollers: map[enumspb.TaskQueueType][]*taskqueuepb.PollerInfo{}} + for i, st := range []enumspb.WorkflowExecutionStatus{enumspb.WORKFLOW_EXECUTION_STATUS_RUNNING, + enumspb.WORKFLOW_EXECUTION_STATUS_COMPLETED, enumspb.WORKFLOW_EXECUTION_STATUS_TERMINATED} { + w.infos = append(w.infos, &workflowpb.WorkflowExecutionInfo{ + Execution: &commonpb.WorkflowExecution{WorkflowId: fmt.Sprintf("order-%d", i+1), RunId: fmt.Sprintf("run-%d", i+1)}, + Type: &commonpb.WorkflowType{Name: "orders.Order"}, Status: st, TaskQueue: "orders", + StartTime: timestamppb.New(started.Add(time.Duration(i) * time.Minute)), HistoryLength: 5, + }) + } + for i, t := range []enumspb.EventType{enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_STARTED, + enumspb.EVENT_TYPE_WORKFLOW_TASK_SCHEDULED, enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_SIGNALED} { + w.events = append(w.events, &historypb.HistoryEvent{EventId: int64(i + 1), EventType: t, + EventTime: timestamppb.New(started.Add(time.Duration(i) * time.Second))}) + } + return w +} + +func (w *workflowState) find(id string) *workflowpb.WorkflowExecutionInfo { + for _, info := range w.infos { + if info.GetExecution().GetWorkflowId() == id { + return info + } + } + return nil +} + +// ListWorkflowExecutions returns two workflows per page and records each query. +func (f workflowFake) ListWorkflowExecutions(ctx context.Context, r *workflowservice.ListWorkflowExecutionsRequest) ( + *workflowservice.ListWorkflowExecutionsResponse, error) { + f.record(ctx) + f.mu.Lock() + defer f.mu.Unlock() + w := f.workflows + w.queries = append(w.queries, r.GetQuery()) + start := 0 + if len(r.GetNextPageToken()) > 0 { + start = int(r.GetNextPageToken()[0]) + } + end := min(start+2, len(w.infos)) + res := &workflowservice.ListWorkflowExecutionsResponse{Executions: w.infos[start:end]} + if end < len(w.infos) { + res.NextPageToken = []byte{byte(end)} + } + return res, nil +} + +func (f workflowFake) CountWorkflowExecutions(ctx context.Context, r *workflowservice.CountWorkflowExecutionsRequest) ( + *workflowservice.CountWorkflowExecutionsResponse, error) { + f.record(ctx) + f.mu.Lock() + defer f.mu.Unlock() + f.workflows.queries = append(f.workflows.queries, r.GetQuery()) + return &workflowservice.CountWorkflowExecutionsResponse{Count: int64(len(f.workflows.infos))}, nil +} + +func (f workflowFake) DescribeWorkflowExecution(ctx context.Context, r *workflowservice.DescribeWorkflowExecutionRequest) ( + *workflowservice.DescribeWorkflowExecutionResponse, error) { + f.record(ctx) + f.mu.Lock() + defer f.mu.Unlock() + info := f.workflows.find(r.GetExecution().GetWorkflowId()) + if info == nil { + return nil, serviceerror.NewNotFound("workflow not found") + } + return &workflowservice.DescribeWorkflowExecutionResponse{WorkflowExecutionInfo: info, + PendingActivities: []*workflowpb.PendingActivityInfo{{ActivityId: "1"}}}, nil +} + +// GetWorkflowExecutionHistory returns one event per page. +func (f workflowFake) GetWorkflowExecutionHistory(ctx context.Context, + r *workflowservice.GetWorkflowExecutionHistoryRequest) (*workflowservice.GetWorkflowExecutionHistoryResponse, error) { + f.record(ctx) + f.mu.Lock() + defer f.mu.Unlock() + if f.workflows.find(r.GetExecution().GetWorkflowId()) == nil { + return nil, serviceerror.NewNotFound("workflow not found") + } + i := 0 + if len(r.GetNextPageToken()) > 0 { + i = int(r.GetNextPageToken()[0]) + } + res := &workflowservice.GetWorkflowExecutionHistoryResponse{ + History: &historypb.History{Events: f.workflows.events[i : i+1]}, + } + if i+1 < len(f.workflows.events) { + res.NextPageToken = []byte{byte(i + 1)} + } + return res, nil +} + +func (f workflowFake) SignalWorkflowExecution(ctx context.Context, r *workflowservice.SignalWorkflowExecutionRequest) ( + *workflowservice.SignalWorkflowExecutionResponse, error) { + f.record(ctx) + f.mu.Lock() + defer f.mu.Unlock() + if f.workflows.find(r.GetWorkflowExecution().GetWorkflowId()) == nil { + return nil, serviceerror.NewNotFound("workflow not found") + } + f.workflows.signals = append(f.workflows.signals, r) + return &workflowservice.SignalWorkflowExecutionResponse{}, nil +} + +func (f workflowFake) RequestCancelWorkflowExecution(ctx context.Context, + r *workflowservice.RequestCancelWorkflowExecutionRequest) (*workflowservice.RequestCancelWorkflowExecutionResponse, + error) { + f.record(ctx) + f.mu.Lock() + defer f.mu.Unlock() + f.workflows.cancels = append(f.workflows.cancels, r) + return &workflowservice.RequestCancelWorkflowExecutionResponse{}, nil +} + +func (f workflowFake) TerminateWorkflowExecution(ctx context.Context, r *workflowservice.TerminateWorkflowExecutionRequest) ( + *workflowservice.TerminateWorkflowExecutionResponse, error) { + f.record(ctx) + f.mu.Lock() + defer f.mu.Unlock() + if info := f.workflows.find(r.GetWorkflowExecution().GetWorkflowId()); info == nil || + info.GetStatus() != enumspb.WORKFLOW_EXECUTION_STATUS_RUNNING { + return nil, serviceerror.NewNotFound("workflow execution already completed") + } + f.workflows.ends = append(f.workflows.ends, r) + return &workflowservice.TerminateWorkflowExecutionResponse{}, nil +} + +func (f workflowFake) DescribeTaskQueue(ctx context.Context, r *workflowservice.DescribeTaskQueueRequest) ( + *workflowservice.DescribeTaskQueueResponse, error) { + f.record(ctx) + f.mu.Lock() + defer f.mu.Unlock() + return &workflowservice.DescribeTaskQueueResponse{Pollers: f.workflows.pollers[r.GetTaskQueueType()]}, nil +} + +func TestWorkflowListAndCount(t *testing.T) { + tc := newTestCLI(t) + out := tc.must("workflow", "list", "-q", `WorkflowKind="orders.Order"`) + for _, want := range []string{"STATUS WORKFLOW ID TYPE START TIME", + "Running order-1 orders.Order 2026-11-04T09:30:00Z", "Completed order-2", + "Terminated order-3"} { + if !strings.Contains(out, want) { + t.Errorf("list lacks %q:\n%s", want, out) + } + } + if q := tc.engine.workflows.queries; q[0] != `WorkflowKind="orders.Order"` || len(q) != 2 { + t.Fatalf("queries = %q, want the query on both pages", q) + } + if out := tc.must("workflow", "list", "--limit", "1"); strings.Contains(out, "order-2") { + t.Fatalf("--limit 1 listed more:\n%s", out) + } + var list []map[string]any + if err := json.Unmarshal([]byte(tc.must("workflow", "list", "-o", "json", "--limit", "0")), &list); err != nil || + len(list) != 3 { + t.Fatalf("json list = %v, %v", list, err) + } + if out := tc.must("workflow", "count"); out != "Total: 3\n" { + t.Fatalf("count = %q", out) + } + if code, _, errOut := tc.run("workflow", "list", "--limit", "-1"); code != 1 || !strings.Contains(errOut, "negative") { + t.Fatalf("negative limit = %d %q", code, errOut) + } +} + +func TestWorkflowDescribeAndShow(t *testing.T) { + tc := newTestCLI(t) + out := tc.must("workflow", "describe", "-w", "order-1") + for _, want := range []string{"Run ID run-1", "Task queue orders", + "Status Running", "Pending activities 1"} { + if !strings.Contains(out, want) { + t.Errorf("describe lacks %q:\n%s", want, out) + } + } + out = tc.must("workflow", "show", "-w", "order-1") + for _, want := range []string{"1 2026-11-04T09:30:00Z WorkflowExecutionStarted", + "3 2026-11-04T09:30:02Z WorkflowExecutionSignaled"} { + if !strings.Contains(out, want) { + t.Errorf("show over three pages lacks %q:\n%s", want, out) + } + } + var history map[string][]any + if err := json.Unmarshal([]byte(tc.must("workflow", "show", "-w", "order-1", "-o", "json")), &history); err != nil || + len(history["events"]) != 3 { + t.Fatalf("json history = %v, %v", history, err) + } + for args, want := range map[string]string{ + "workflow describe -w missing": "unable to describe workflow missing", + "workflow show -w missing": "unable to read the history of workflow missing", + "workflow describe": `required flag(s) "workflow-id" not set`, + } { + if code, _, errOut := tc.run(strings.Fields(args)...); code != 1 || !strings.Contains(errOut, want) { + t.Errorf("%s = %d %q, want %q", args, code, errOut, want) + } + } +} + +func TestWorkflowSignalCancelTerminate(t *testing.T) { + tc := newTestCLI(t) + out := tc.must("workflow", "signal", "-w", "order-1", "--name", "approval", "-i", `{ "approved": true }`, "-i", `"ann"`) + if out != "Signal approval sent to workflow order-1.\n" { + t.Fatalf("signal = %q", out) + } + sig := tc.engine.workflows.signals[0] + if sig.GetSignalName() != "approval" || len(sig.GetInput().GetPayloads()) != 2 || + string(sig.GetInput().GetPayloads()[0].GetData()) != `{"approved":true}` || + string(sig.GetInput().GetPayloads()[0].GetMetadata()["encoding"]) != "json/plain" || + !strings.HasPrefix(sig.GetIdentity(), "workflow-cli@") || len(sig.GetRequestId()) != 32 { + t.Fatalf("signal request = %v", sig) + } + tc.must("workflow", "cancel", "-w", "order-1", "-r", "run-1", "--reason", "customer withdrew") + if c := tc.engine.workflows.cancels[0]; c.GetReason() != "customer withdrew" || + c.GetWorkflowExecution().GetRunId() != "run-1" { + t.Fatalf("cancel request = %v", c) + } + if out := tc.must("workflow", "terminate", "-w", "order-1", "--reason", "stuck"); out != "Workflow order-1 terminated.\n" { + t.Fatalf("terminate = %q", out) + } + if e := tc.engine.workflows.ends[0]; e.GetReason() != "stuck" { + t.Fatalf("terminate request = %v", e) + } + for args, want := range map[string]string{ + "workflow signal -w order-1 --name x -i {oops": "is not JSON", + "workflow signal -w missing --name x": "unable to signal workflow missing", + "workflow signal -w order-1": `required flag(s) "name" not set`, + "workflow terminate -w order-2": "unable to terminate workflow order-2", + } { + if code, _, errOut := tc.run(strings.Fields(args)...); code != 1 || !strings.Contains(errOut, want) { + t.Errorf("%s = %d %q, want %q", args, code, errOut, want) + } + } +} + +func TestTaskQueueDescribe(t *testing.T) { + tc := newTestCLI(t) + if out := tc.must("task-queue", "describe", "-t", "orders"); !strings.Contains(out, "No worker has polled") { + t.Fatalf("empty task queue:\n%s", out) + } + tc.engine.workflows.pollers[enumspb.TASK_QUEUE_TYPE_WORKFLOW] = []*taskqueuepb.PollerInfo{ + {Identity: "orders-1@host", LastAccessTime: timestamppb.New(started), RatePerSecond: 100000}} + tc.engine.workflows.pollers[enumspb.TASK_QUEUE_TYPE_ACTIVITY] = []*taskqueuepb.PollerInfo{ + {Identity: "orders-1@host", LastAccessTime: timestamppb.New(started), RatePerSecond: 2.5}} + out := tc.must("task-queue", "describe", "-t", "orders") + for _, want := range []string{"workflow orders-1@host 2026-11-04T09:30:00Z 100000", + "activity orders-1@host 2026-11-04T09:30:00Z 2.5"} { + if !strings.Contains(out, want) { + t.Errorf("describe lacks %q:\n%s", want, out) + } + } + var res []map[string]any + if err := json.Unmarshal([]byte(tc.must("task-queue", "describe", "-t", "orders", "-o", "json")), &res); err != nil || + len(res) != 2 { + t.Fatalf("json = %v, %v", res, err) + } + if code, _, errOut := tc.run("task-queue", "describe"); code != 1 || !strings.Contains(errOut, "task-queue") { + t.Fatalf("missing task queue = %d %q", code, errOut) + } +} + +func TestEnumName(t *testing.T) { + for in, want := range map[string]string{"EVENT_TYPE_TIMER_STARTED": "TimerStarted", "EVENT_TYPE_": "", + "WORKFLOW_EXECUTION_STATUS_CONTINUED_AS_NEW": "ContinuedAsNew", "ContinuedAsNew": "ContinuedAsNew"} { + prefix := "EVENT_TYPE_" + if strings.HasPrefix(in, "WORKFLOW") { + prefix = "WORKFLOW_EXECUTION_STATUS_" + } + if got := enumName(in, prefix); got != want { + t.Errorf("enumName(%s) = %q, want %q", in, got, want) + } + } + if timestamp(nil) != "" { + t.Error("a missing time is not empty") + } +} diff --git a/docs/features/workflow-cli.md b/docs/features/workflow-cli.md index a79846a..fd5329d 100644 --- a/docs/features/workflow-cli.md +++ b/docs/features/workflow-cli.md @@ -1,11 +1,11 @@ # workflow-cli -Status: in progress · P0 (cluster, namespaces, search attributes, profiles) since 0.1.0 +Status: in progress · P0 (cluster, namespaces, search attributes, profiles) and P1 (workflows, task queues) since 0.1.0 ## What it does `workflow-cli` is the runtime's command line client for operators: it checks the engine's services, lists the nodes -behind each, and manages namespaces and search attributes. Customers who can run only WSO2-supported tools use it +behind each, manages namespaces and search attributes, and lists, inspects, signals, cancels and terminates workflows. Customers who can run only WSO2-supported tools use it instead of the Temporal CLI. Its commands and flags follow the Temporal CLI's, so `temporal operator namespace list` is `workflow-cli operator namespace list`. @@ -44,6 +44,12 @@ Precedence, as in the Temporal CLI: flag, environment variable, profile, default and adds `WorkflowKind` (Keyword), retrying while the new namespace is not yet in the engine's namespace cache (`NotFound`, `Unavailable`). An existing namespace (`AlreadyExists`) is reported and left unchanged, and the attribute is still ensured; the engine skips attributes that exist. +- `workflow list` and `count` take Temporal's visibility query; `list` pages through 100 at a time up to `--limit` + (100; 0 for all). `show` pages through the whole history. `signal` encodes each `--input` as a `json/plain` + payload after checking it is JSON; `signal` and `cancel` send a fresh request ID, and every change carries the + identity `workflow-cli@`, which the workflow's history records. +- `task-queue describe` calls `DescribeTaskQueue` once for workflow and once for activity tasks and lists their + pollers. - A token goes only over TLS, or in plain text to a loopback address; otherwise the command refuses before dialing. - The profile file is written atomically, mode 0600 in a 0700 directory; unknown properties in it are errors. `config get` shows an API key as `(set)`. @@ -52,14 +58,13 @@ Precedence, as in the Temporal CLI: flag, environment variable, profile, default ## Limits -- Only the P0 commands: workflow, task queue, schedule, batch and dead-letter commands come later (P1, P2). +- Workflow start, reset, batch, schedule and dead-letter commands come later (P2). - A token is read once per command; refreshing an expiring one is up to the caller (`apiKeyFile` rewritten by a token helper works). ## Not covered yet -P1: `workflow list|describe|show|signal|cancel|terminate`, `task-queue describe`. P2: `workflow reset`, batch -operations, schedules, dead-letter queues and shards (Temporal's `tdbg`). A token command for the API server, once +P2: `workflow reset`, batch operations, schedules, dead-letter queues and shards (Temporal's `tdbg`). A token command for the API server, once it exists. ## Tests @@ -67,6 +72,7 @@ it exists. | Test | Covers | |---|---| | `cli/internal/command/command_test.go` | Every command against an in-memory fake engine (bufconn): health per service and exit codes, describe with and without the admin API, namespace create (cache retry, idempotence), describe, list over pages, update, search attributes, profile/environment/flag precedence and the bearer header, `config` commands and file mode, error messages | +| `cli/internal/command/workflow_test.go` | `workflow list` over pages with a query and `--limit`, `count`, `describe`, `show` over pages, `signal` payloads, identity and request ID, `cancel` and `terminate` with reasons and run IDs, `task-queue describe` with and without pollers, error messages | | `cli/internal/command/dial_test.go` | Mutual TLS against a real TLS server, refusal without a client certificate or TLS, token refused in plain text off-loopback, CA, client certificate and key file errors | | `cli/internal/clientconfig/clientconfig_test.go` | Profile file parsing, unknown keys, environment variables, TLS on/off rules, writing and deleting properties | -| `tools/internal/enginetest/workflowcli_test.go` | Against the real engine: every P0 command on `start-dev`; on a secured engine, profiles with admin and namespace tokens, refusals, a token never sent in plain text, and the health of each internal port with a node certificate | +| `tools/internal/enginetest/workflowcli_test.go` | Against the real engine: every P0 and P1 command on `start-dev` (workflows started on a task queue no worker polls: listed by `WorkflowKind`, described, signalled, cancelled and terminated, their history shown); on a secured engine, profiles with admin and namespace tokens, refusals, a token never sent in plain text, a namespace token listing only its own namespace, and the health of each internal port with a node certificate | diff --git a/docs/guides/ARCHITECTURE.md b/docs/guides/ARCHITECTURE.md index 624783a..6d4a011 100644 --- a/docs/guides/ARCHITECTURE.md +++ b/docs/guides/ARCHITECTURE.md @@ -13,7 +13,7 @@ portals, packaging and updates. | Engine | Temporal's four services (frontend, history, matching, worker) in our Go binary, `workflow-engine` | Builds and runs | | Engine endpoint | The integrations' one port (7233): gRPC to Temporal's frontend, `/runtime/...` HTTPS to the Manager | Planned | | Launcher | `bin/workflow-runtime`: finds the runtime's home and starts the engine from `conf/runtime.toml`, or in development mode | Starts the engine; supervision and restart planned | -| workflow-cli | `bin/workflow-cli`: the operators' client over the Temporal gRPC API (health, nodes, namespaces, search attributes); its own module, no server code | P0 commands | +| workflow-cli | `bin/workflow-cli`: the operators' client over the Temporal gRPC API (health, nodes, namespaces, search attributes, workflows, task queues); its own module, no server code | P0 and P1 commands | | Manager | Go service: engine administration, the Workflow Management API, SSO sign-in, roles; serves the portals | Planned | | Admin Portal | UI for administrators and operators, at `/admin` | Planned | | User Portal | Business users' human-task inbox, at `/portal` | Planned | diff --git a/docs/user-guide/manage-with-workflow-cli.md b/docs/user-guide/manage-with-workflow-cli.md index 8bdd816..eeb59a4 100644 --- a/docs/user-guide/manage-with-workflow-cli.md +++ b/docs/user-guide/manage-with-workflow-cli.md @@ -1,13 +1,14 @@ --- title: Manage the engine with workflow-cli -description: Check the engine's health, see its nodes, and create namespaces and search attributes with workflow-cli. +description: Check the engine, manage namespaces, and find, inspect and act on workflows with workflow-cli. keywords: [wso2 integrator, workflow runtime, workflow-cli, cli, namespace, search attribute, health check, cluster] --- # Manage the engine with workflow-cli `workflow-cli` is the runtime's command line client. It checks the engine's health, lists the nodes behind each -service, and manages namespaces and their search attributes. It is a client like an integration: it talks only to +service, manages namespaces and their search attributes, and finds, inspects and acts on the workflows integrations +run. It is a client like an integration: it talks only to the engine's frontend (or, for health checks, to one service's port), never to the database. It is in the distribution's `bin/` directory and in the container image. Copy the one file to any machine that can @@ -109,6 +110,44 @@ workflow-cli operator search-attribute list --namespace orders Types are `Keyword`, `Text`, `Int`, `Double`, `Bool`, `Datetime` and `KeywordList`. An attribute that exists already is left as it is. +## Find and inspect workflows + +```bash +workflow-cli workflow list --namespace orders --query 'ExecutionStatus="Running" AND WorkflowKind="orders.Order"' +workflow-cli workflow count --namespace orders --query 'ExecutionStatus="Failed"' +workflow-cli workflow describe --namespace orders --workflow-id order-1042 +workflow-cli workflow show --namespace orders --workflow-id order-1042 +``` + +`list` shows the newest 100 by default (`--limit 0` for all). The query is Temporal's visibility query language: +`WorkflowId`, `WorkflowType`, `ExecutionStatus`, `StartTime`, `CloseTime` and any search attribute, such as the +`WorkflowKind` integrations set. `describe` shows the task queue, status and pending activities; `show` lists the +events of its history, the place to look when a workflow does not move. Add `--run-id` for a run other than the +latest. + +A token with `read` in the namespace is enough for these. + +## Act on a workflow + +```bash +workflow-cli workflow signal -n orders -w order-1042 --name approval --input '{"approved": true}' +workflow-cli workflow cancel -n orders -w order-1042 --reason "customer withdrew" +workflow-cli workflow terminate -n orders -w order-1042 --reason "stuck on a retired version" +``` + +`signal` delivers the event the workflow waits for, each `--input` a JSON argument. `cancel` asks the workflow to +stop and lets it clean up; `terminate` ends it at once, running nothing more. Both record the reason in its +history. These need `write` in the namespace. + +## Check an integration's workers + +```bash +workflow-cli task-queue describe --namespace orders --task-queue orders +``` + +lists the workers that polled the task queue recently, for workflow and for activity tasks. Workflows that stay +`Running` without progress while this lists no worker are waiting for their integration to start. + ## Use it in scripts Every command takes `-o json` for the Temporal API's JSON form, and exits with 1 on any error, the message on diff --git a/docs/user-guide/monitor.md b/docs/user-guide/monitor.md index 62d9240..ce87755 100644 --- a/docs/user-guide/monitor.md +++ b/docs/user-guide/monitor.md @@ -31,6 +31,8 @@ they resolve themselves. After that they are logged as errors again, so a lastin ## Workflows Use the Integration Control Plane (ICP) to see integrations' workflows, their status and history. +`workflow-cli workflow list`, `describe` and `show` do the same from a terminal, with a token that has `read` in the +namespace ([Manage the engine with workflow-cli](manage-with-workflow-cli.md#find-and-inspect-workflows)). ## The engine diff --git a/docs/user-guide/quick-start.md b/docs/user-guide/quick-start.md index 94c223b..c066e8d 100644 --- a/docs/user-guide/quick-start.md +++ b/docs/user-guide/quick-start.md @@ -64,7 +64,12 @@ bin/workflow-cli operator namespace list bin/workflow-cli operator namespace create --namespace orders # another namespace, with WorkflowKind ``` -The Integration Control Plane (ICP) shows the workflows themselves ([Monitor the runtime](monitor.md)). +Once the integration has run, list its workflows and look at one: + +```bash +bin/workflow-cli workflow list +bin/workflow-cli workflow show --workflow-id +``` ## Next steps diff --git a/docs/user-guide/reference/workflow-cli.md b/docs/user-guide/reference/workflow-cli.md index 2c0f383..d3d0b61 100644 --- a/docs/user-guide/reference/workflow-cli.md +++ b/docs/user-guide/reference/workflow-cli.md @@ -18,6 +18,14 @@ keywords: [wso2 integrator, workflow runtime, workflow-cli, reference, flags, pr | `operator namespace update [--retention ] [--description ]` | Changes the retention or the description | | `operator search-attribute create --name --type ...` | Adds search attributes, each `--name` with the `--type` in the same position; existing ones are left unchanged | | `operator search-attribute list` | The namespace's custom and system search attributes | +| `workflow list [--query ] [--limit ]` | Workflows, newest first, with status, ID, type and start time; `--limit` 100 by default, 0 for all | +| `workflow count [--query ]` | How many workflows match | +| `workflow describe -w [-r ]` | A workflow's run, type, task queue, status, times, history length, and pending activities and child workflows | +| `workflow show -w [-r ]` | Its event history: ID, time and type of each event | +| `workflow signal -w --name [-i ]...` | Sends a signal, each `--input` a JSON argument (`json/plain`) | +| `workflow cancel -w [--reason ]` | Requests cancellation; the workflow can clean up | +| `workflow terminate -w [--reason ]` | Ends the workflow at once | +| `task-queue describe -t ` | The workers that polled it recently, for workflow and activity tasks | | `config set --prop --value ` | Sets a property of the profile, creating the profile | | `config get [--prop ]` | Shows the profile (an API key as `(set)`), or one property | | `config delete --prop ` | Removes a property | From 66fac08c9e929b368222f1da5b61b170ade26766 Mon Sep 17 00:00:00 2001 From: Hasitha Aravinda Date: Wed, 4 Nov 2026 14:32:29 +0530 Subject: [PATCH 2/6] test: drive the workflow and task queue commands on real engines --- tools/internal/enginetest/workflowcli_test.go | 40 +++++++++++++++++-- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/tools/internal/enginetest/workflowcli_test.go b/tools/internal/enginetest/workflowcli_test.go index 96c92ec..2d95264 100644 --- a/tools/internal/enginetest/workflowcli_test.go +++ b/tools/internal/enginetest/workflowcli_test.go @@ -76,7 +76,7 @@ func TestWorkflowCLIOnADevEngine(t *testing.T) { binary := engineBinary(t) w := newWorkflowCLI(t) base := freeBase(t) - start(t, binary, base, nil, "start-dev", "--port", strconv.Itoa(base)) + e := start(t, binary, base, nil, "start-dev", "--port", strconv.Itoa(base)) addr := []string{"--address", fmt.Sprintf("127.0.0.1:%d", base)} cli := func(args ...string) string { return w.must(append(args, addr...)...) } @@ -92,6 +92,34 @@ func TestWorkflowCLIOnADevEngine(t *testing.T) { cli("operator", "namespace", "update", "-n", "orders", "--retention", "48h", "--description", "Orders") w.mustContain(cli("operator", "namespace", "list"), "default", "orders", "2d", "Orders") w.mustContain(cli("operator", "namespace", "list", "-o", "json"), `"name": "orders"`) + + // Workflows waiting on a task queue no worker polls, as an integration's are while it is down. + for _, id := range []string{"order-1", "order-2", "order-3"} { + e.must("workflow", "start", "--namespace", "orders", "--type", "Order", "--task-queue", "orders", + "--workflow-id", id, "--search-attribute", `WorkflowKind="orders.Order"`) + } + kind := []string{"workflow", "list", "-n", "orders", "-q", `WorkflowKind="orders.Order"`} + var out string + for deadline := time.Now().Add(30 * time.Second); time.Now().Before(deadline); time.Sleep(time.Second) { + if out = cli(kind...); strings.Count(out, "Running") == 3 { + break + } + } + w.mustContain(out, "order-1", "order-2", "order-3", "Order") + w.mustContain(cli("workflow", "count", "-n", "orders"), "Total: 3") + w.mustContain(cli("workflow", "describe", "-n", "orders", "-w", "order-1"), "Task queue orders", + "Status Running") + cli("workflow", "signal", "-n", "orders", "-w", "order-1", "--name", "approval", "-i", `{"approved":true}`) + w.mustContain(cli("workflow", "show", "-n", "orders", "-w", "order-1"), "WorkflowExecutionStarted", + "WorkflowExecutionSignaled") + cli("workflow", "cancel", "-n", "orders", "-w", "order-2", "--reason", "withdrawn") + w.mustContain(cli("workflow", "show", "-n", "orders", "-w", "order-2"), "WorkflowExecutionCancelRequested") + cli("workflow", "terminate", "-n", "orders", "-w", "order-3", "--reason", "stuck") + w.mustContain(cli("workflow", "describe", "-n", "orders", "-w", "order-3"), "Terminated") + if out, err := w.run(append([]string{"workflow", "terminate", "-n", "orders", "-w", "order-3"}, addr...)...); err == nil { + t.Errorf("a closed workflow was terminated again:\n%s", out) + } + w.mustContain(cli("task-queue", "describe", "-n", "orders", "-t", "orders"), "No worker has polled") } // TestWorkflowCLIOnASecuredEngine reaches a secured engine through a profile, with tokens of different roles, and @@ -128,13 +156,17 @@ func TestWorkflowCLIOnASecuredEngine(t *testing.T) { w.mustContain(w.must("operator", "cluster", "describe", "--profile", "ops"), "internal-frontend", "history", "matching", "worker") w.mustContain(w.must("operator", "namespace", "create", "--profile", "ops", "-n", "orders"), "created") + w.must("operator", "namespace", "create", "--profile", "ops", "-n", "billing") w.mustContain(w.must("operator", "search-attribute", "list", "--profile", "app"), "WorkflowKind") w.mustContain(w.must("operator", "namespace", "describe", "--profile", "app"), "orders") + w.mustContain(w.must("workflow", "count", "--profile", "app"), "Total: 0") + w.mustContain(w.must("task-queue", "describe", "--profile", "app", "-t", "orders"), "No worker has polled") refused := map[string][]string{ - "an app creating a namespace": {"operator", "namespace", "create", "--profile", "app", "-n", "billing"}, - "an app changing retention": {"operator", "namespace", "update", "--profile", "app", "--retention", "1h"}, - "no token": {"operator", "namespace", "list", "--address", fmt.Sprintf("127.0.0.1:%d", se.base), "--tls-ca-path", ca}, + "an app creating a namespace": {"operator", "namespace", "create", "--profile", "app", "-n", "billing"}, + "an app changing retention": {"operator", "namespace", "update", "--profile", "app", "--retention", "1h"}, + "an app listing another namespace": {"workflow", "list", "--profile", "app", "-n", "billing"}, + "no token": {"operator", "namespace", "list", "--address", fmt.Sprintf("127.0.0.1:%d", se.base), "--tls-ca-path", ca}, } for name, args := range refused { if out, err := w.run(args...); err == nil || !strings.Contains(out, "Request unauthorized") { From 092ca07ba881309b78c672be52f87ea2c29957c2 Mon Sep 17 00:00:00 2001 From: Hasitha Aravinda Date: Wed, 4 Nov 2026 15:59:43 +0530 Subject: [PATCH 3/6] test: wait for a new search attribute before tagging workflows --- tools/internal/enginetest/workflowcli_test.go | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/tools/internal/enginetest/workflowcli_test.go b/tools/internal/enginetest/workflowcli_test.go index 2d95264..f291a6d 100644 --- a/tools/internal/enginetest/workflowcli_test.go +++ b/tools/internal/enginetest/workflowcli_test.go @@ -95,8 +95,7 @@ func TestWorkflowCLIOnADevEngine(t *testing.T) { // Workflows waiting on a task queue no worker polls, as an integration's are while it is down. for _, id := range []string{"order-1", "order-2", "order-3"} { - e.must("workflow", "start", "--namespace", "orders", "--type", "Order", "--task-queue", "orders", - "--workflow-id", id, "--search-attribute", `WorkflowKind="orders.Order"`) + e.startTagged("orders", "Order", "orders", id, `WorkflowKind="orders.Order"`) } kind := []string{"workflow", "list", "-n", "orders", "-q", `WorkflowKind="orders.Order"`} var out string @@ -211,3 +210,21 @@ func readFile(t *testing.T, path string) string { } return string(b) } + +// startTagged starts a workflow with a search attribute, retrying while the engine's namespace cache does not yet know +// an attribute just added to the namespace (refreshed every few seconds). +func (e *engine) startTagged(namespace, workflowType, taskQueue, id, attribute string) { + e.t.Helper() + args := []string{"workflow", "start", "--namespace", namespace, "--type", workflowType, "--task-queue", taskQueue, + "--workflow-id", id, "--search-attribute", attribute} + var out string + var err error + for deadline := time.Now().Add(30 * time.Second); time.Now().Before(deadline); time.Sleep(time.Second) { + if out, err = e.temporal(args...); err == nil || !strings.Contains(out, "no mapping defined for search attribute") { + break + } + } + if err != nil { + e.t.Fatalf("temporal %s: %v\n%s", strings.Join(args, " "), err, out) + } +} From 54501adb2c07e276d6d6e5d74d591298d21ba634 Mon Sep 17 00:00:00 2001 From: Hasitha Aravinda Date: Thu, 5 Nov 2026 10:25:59 +0530 Subject: [PATCH 4/6] fix(cli): confirm workflow changes on stderr in json mode --- cli/internal/command/taskqueue.go | 4 ++-- cli/internal/command/workflow.go | 9 +++------ cli/internal/command/workflow_test.go | 16 ++++++++++++++++ docs/features/workflow-cli.md | 4 ++-- docs/user-guide/manage-with-workflow-cli.md | 5 +++-- tools/internal/enginetest/workflowcli_test.go | 12 ++++++++++-- 6 files changed, 36 insertions(+), 14 deletions(-) diff --git a/cli/internal/command/taskqueue.go b/cli/internal/command/taskqueue.go index ee34378..6b505b9 100644 --- a/cli/internal/command/taskqueue.go +++ b/cli/internal/command/taskqueue.go @@ -38,8 +38,8 @@ func (c *cli) taskQueueDescribeCommand() *cobra.Command { cmd := &cobra.Command{ Use: "describe", Short: "List the workers polling a task queue for workflow and activity tasks", - Long: "Lists the workers that polled --task-queue in the last few minutes. An integration's workers poll the\n" + - "task queue named in its Config.toml; none here means no integration serves those workflows.", + Long: "Lists the workers that polled --task-queue in the last five minutes. An integration's workers poll the\n" + + "task queue named in its Config.toml; an empty list means none polled recently, not that none runs.", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { conn, s, ctx, cancel, err := c.connect(cmd) diff --git a/cli/internal/command/workflow.go b/cli/internal/command/workflow.go index aca46d4..a2c70cb 100644 --- a/cli/internal/command/workflow.go +++ b/cli/internal/command/workflow.go @@ -260,8 +260,7 @@ func (c *cli) workflowSignalCommand() *cobra.Command { if err != nil { return fmt.Errorf("unable to signal workflow %s: %w", e.workflowID, err) } - _, err = fmt.Fprintf(cmd.OutOrStdout(), "Signal %s sent to workflow %s.\n", name, e.workflowID) - return err + return c.confirm(cmd, "Signal %s sent to workflow %s.\n", name, e.workflowID) }, } e.flags(cmd) @@ -293,8 +292,7 @@ func (c *cli) workflowCancelCommand() *cobra.Command { if err != nil { return fmt.Errorf("unable to cancel workflow %s: %w", e.workflowID, err) } - _, err = fmt.Fprintf(cmd.OutOrStdout(), "Cancellation requested for workflow %s.\n", e.workflowID) - return err + return c.confirm(cmd, "Cancellation requested for workflow %s.\n", e.workflowID) }, } e.flags(cmd) @@ -323,8 +321,7 @@ func (c *cli) workflowTerminateCommand() *cobra.Command { if err != nil { return fmt.Errorf("unable to terminate workflow %s: %w", e.workflowID, err) } - _, err = fmt.Fprintf(cmd.OutOrStdout(), "Workflow %s terminated.\n", e.workflowID) - return err + return c.confirm(cmd, "Workflow %s terminated.\n", e.workflowID) }, } e.flags(cmd) diff --git a/cli/internal/command/workflow_test.go b/cli/internal/command/workflow_test.go index b9a99c5..2aac0a5 100644 --- a/cli/internal/command/workflow_test.go +++ b/cli/internal/command/workflow_test.go @@ -20,6 +20,7 @@ import ( "context" "encoding/json" "fmt" + "slices" "strings" "testing" "time" @@ -42,6 +43,7 @@ type workflowState struct { cancels []*workflowservice.RequestCancelWorkflowExecutionRequest ends []*workflowservice.TerminateWorkflowExecutionRequest queries []string + runIDs []string pollers map[enumspb.TaskQueueType][]*taskqueuepb.PollerInfo } @@ -108,6 +110,7 @@ func (f workflowFake) DescribeWorkflowExecution(ctx context.Context, r *workflow f.record(ctx) f.mu.Lock() defer f.mu.Unlock() + f.workflows.runIDs = append(f.workflows.runIDs, r.GetExecution().GetRunId()) info := f.workflows.find(r.GetExecution().GetWorkflowId()) if info == nil { return nil, serviceerror.NewNotFound("workflow not found") @@ -122,6 +125,7 @@ func (f workflowFake) GetWorkflowExecutionHistory(ctx context.Context, f.record(ctx) f.mu.Lock() defer f.mu.Unlock() + f.workflows.runIDs = append(f.workflows.runIDs, r.GetExecution().GetRunId()) if f.workflows.find(r.GetExecution().GetWorkflowId()) == nil { return nil, serviceerror.NewNotFound("workflow not found") } @@ -231,6 +235,12 @@ func TestWorkflowDescribeAndShow(t *testing.T) { len(history["events"]) != 3 { t.Fatalf("json history = %v, %v", history, err) } + tc.engine.workflows.runIDs = nil + tc.must("workflow", "describe", "-w", "order-1", "-r", "run-1") + tc.must("workflow", "show", "-w", "order-1", "-r", "run-1") + if got := tc.engine.workflows.runIDs; len(got) < 2 || slices.ContainsFunc(got, func(id string) bool { return id != "run-1" }) { + t.Fatalf("describe and show sent run IDs %q, want run-1 on every call", got) + } for args, want := range map[string]string{ "workflow describe -w missing": "unable to describe workflow missing", "workflow show -w missing": "unable to read the history of workflow missing", @@ -266,6 +276,12 @@ func TestWorkflowSignalCancelTerminate(t *testing.T) { if e := tc.engine.workflows.ends[0]; e.GetReason() != "stuck" { t.Fatalf("terminate request = %v", e) } + for _, args := range [][]string{{"signal", "--name", "approval"}, {"cancel"}, {"terminate"}} { + args = append([]string{"workflow"}, append(args, "-w", "order-1", "-o", "json")...) + if code, out, errOut := tc.run(args...); code != 0 || out != "" || errOut == "" { + t.Errorf("%v: exit %d, stdout %q, stderr %q; want the confirmation on stderr only", args, code, out, errOut) + } + } for args, want := range map[string]string{ "workflow signal -w order-1 --name x -i {oops": "is not JSON", "workflow signal -w missing --name x": "unable to signal workflow missing", diff --git a/docs/features/workflow-cli.md b/docs/features/workflow-cli.md index 77bbe8c..8ee9638 100644 --- a/docs/features/workflow-cli.md +++ b/docs/features/workflow-cli.md @@ -72,7 +72,7 @@ it exists. | Test | Covers | |---|---| | `cli/internal/command/command_test.go` | Every command against an in-memory fake engine (bufconn): health per service and exit codes, describe with and without the admin API, namespace create (cache retry, idempotence), describe, list over pages, update, search attributes, profile/environment/flag precedence and the bearer header, `config` commands and file mode, error messages | -| `cli/internal/command/workflow_test.go` | `workflow list` over pages with a query and `--limit`, `count`, `describe`, `show` over pages, `signal` payloads, identity and request ID, `cancel` and `terminate` with reasons and run IDs, `task-queue describe` with and without pollers, error messages | +| `cli/internal/command/workflow_test.go` | `workflow list` over pages with a query and `--limit`, `count`, `describe`, `show` over pages, `signal` payloads, identity and request ID, `describe` and `show` sending `-r`, `cancel` and `terminate` with reasons and run IDs, confirmations on stderr with `-o json`, `task-queue describe` with and without pollers, error messages | | `cli/internal/command/dial_test.go` | Mutual TLS against a real TLS server, refusal without a client certificate or TLS, token refused in plain text off-loopback, CA, client certificate and key file errors | | `cli/internal/clientconfig/clientconfig_test.go` | Profile file parsing, unknown keys, environment variables, TLS on/off rules, writing and deleting properties, profile names that would nest refused with the file left readable | -| `tools/internal/enginetest/workflowcli_test.go` | Against the real engine: every P0 and P1 command on `start-dev` (workflows started on a task queue no worker polls: listed by `WorkflowKind`, described, signalled, cancelled and terminated, their history shown); on a secured engine, profiles with admin and namespace tokens, refusals, a token never sent in plain text, a namespace token listing only its own namespace, and the health of each internal port with a node certificate | +| `tools/internal/enginetest/workflowcli_test.go` | Against the real engine: every P0 and P1 command on `start-dev` (workflows started on a task queue no worker polls: listed by `WorkflowKind`, described, signalled, cancelled and terminated, their history shown); on a secured engine, profiles with admin and namespace tokens, refusals, a token never sent in plain text, a namespace token listing only its own namespace and counting a workflow started in it, and the health of each internal port with a node certificate | diff --git a/docs/user-guide/manage-with-workflow-cli.md b/docs/user-guide/manage-with-workflow-cli.md index eeb59a4..b67cf71 100644 --- a/docs/user-guide/manage-with-workflow-cli.md +++ b/docs/user-guide/manage-with-workflow-cli.md @@ -145,8 +145,9 @@ history. These need `write` in the namespace. workflow-cli task-queue describe --namespace orders --task-queue orders ``` -lists the workers that polled the task queue recently, for workflow and for activity tasks. Workflows that stay -`Running` without progress while this lists no worker are waiting for their integration to start. +lists the workers that polled the task queue in the last five minutes, for workflow and for activity tasks. Workflows +that stay `Running` without progress while this lists no worker are waiting for an integration to poll: one that +is not running, or one that cannot reach the engine. ## Use it in scripts diff --git a/tools/internal/enginetest/workflowcli_test.go b/tools/internal/enginetest/workflowcli_test.go index f291a6d..b412d5a 100644 --- a/tools/internal/enginetest/workflowcli_test.go +++ b/tools/internal/enginetest/workflowcli_test.go @@ -137,7 +137,7 @@ func TestWorkflowCLIOnASecuredEngine(t *testing.T) { } admin := tokenFile("admin", map[string]any{"sub": "ops", "groups": []any{"workflow-admins"}}) app := tokenFile("app", map[string]any{"sub": "orders-app", "groups": []any{"orders-app"}}) - start(t, binary, se.base, []string{"--tls-ca-path", ca, "--api-key", strings.TrimSpace(readFile(t, admin))}, + eng := start(t, binary, se.base, []string{"--tls-ca-path", ca, "--api-key", strings.TrimSpace(readFile(t, admin))}, "start", "--runtime-config", se.config) for prop, value := range map[string]string{ @@ -158,7 +158,15 @@ func TestWorkflowCLIOnASecuredEngine(t *testing.T) { w.must("operator", "namespace", "create", "--profile", "ops", "-n", "billing") w.mustContain(w.must("operator", "search-attribute", "list", "--profile", "app"), "WorkflowKind") w.mustContain(w.must("operator", "namespace", "describe", "--profile", "app"), "orders") - w.mustContain(w.must("workflow", "count", "--profile", "app"), "Total: 0") + // The app reads a workflow the admin started in its namespace, not only an empty one. + eng.startTagged("orders", "Order", "orders", "secured-1", `WorkflowKind="orders.Order"`) + var count string + for deadline := time.Now().Add(30 * time.Second); time.Now().Before(deadline); time.Sleep(time.Second) { + if count = w.must("workflow", "count", "--profile", "app"); strings.Contains(count, "Total: 1") { + break + } + } + w.mustContain(count, "Total: 1") w.mustContain(w.must("task-queue", "describe", "--profile", "app", "-t", "orders"), "No worker has polled") refused := map[string][]string{ From 906b5d0780953e67f573099e2245cefdc7eb8b07 Mon Sep 17 00:00:00 2001 From: Hasitha Aravinda Date: Sun, 15 Nov 2026 07:41:32 +0530 Subject: [PATCH 5/6] fix(cli): accept engine responses up to 128 MiB gRPC's default 4 MiB receive limit refused valid history pages: Temporal returns up to 256 events per page and allows 2 MiB per event, so workflow show failed with ResourceExhausted. The limit now matches the Temporal Go SDK's 128 MiB, for every call the CLI makes. --- cli/internal/command/dial.go | 7 ++++++- cli/internal/command/workflow_test.go | 13 +++++++++++++ docs/features/workflow-cli.md | 5 +++-- 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/cli/internal/command/dial.go b/cli/internal/command/dial.go index f92f872..4ff429f 100644 --- a/cli/internal/command/dial.go +++ b/cli/internal/command/dial.go @@ -43,6 +43,10 @@ func dial(s clientconfig.Settings) (*grpc.ClientConn, error) { return grpc.NewClient(s.Address, opts...) } +// maxResponseSize matches the Temporal Go SDK: a history page holds up to 256 events of up to 2 MiB each, far above +// gRPC's default 4 MiB. +const maxResponseSize = 128 << 20 + func dialOptions(s clientconfig.Settings) ([]grpc.DialOption, error) { if _, _, err := net.SplitHostPort(s.Address); err != nil { return nil, fmt.Errorf("address %q must be host:port", s.Address) @@ -55,7 +59,8 @@ func dialOptions(s clientconfig.Settings) ([]grpc.DialOption, error) { } transport = credentials.NewTLS(cfg) } - opts := []grpc.DialOption{grpc.WithTransportCredentials(transport)} + opts := []grpc.DialOption{grpc.WithTransportCredentials(transport), + grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(maxResponseSize))} key, err := apiKey(s) if err != nil { diff --git a/cli/internal/command/workflow_test.go b/cli/internal/command/workflow_test.go index 2aac0a5..061c9dd 100644 --- a/cli/internal/command/workflow_test.go +++ b/cli/internal/command/workflow_test.go @@ -252,6 +252,19 @@ func TestWorkflowDescribeAndShow(t *testing.T) { } } +func TestWorkflowShowReadsAHistoryPageOver4MiB(t *testing.T) { + tc := newTestCLI(t) + big := &commonpb.Payload{Data: []byte(strings.Repeat("x", 5<<20))} + tc.engine.workflows.events[2].Attributes = &historypb.HistoryEvent_WorkflowExecutionSignaledEventAttributes{ + WorkflowExecutionSignaledEventAttributes: &historypb.WorkflowExecutionSignaledEventAttributes{ + SignalName: "approval", Input: &commonpb.Payloads{Payloads: []*commonpb.Payload{big}}}} + var history map[string][]any + if err := json.Unmarshal([]byte(tc.must("workflow", "show", "-w", "order-1", "-o", "json")), &history); err != nil || + len(history["events"]) != 3 { + t.Fatalf("json history = %d events, %v", len(history["events"]), err) + } +} + func TestWorkflowSignalCancelTerminate(t *testing.T) { tc := newTestCLI(t) out := tc.must("workflow", "signal", "-w", "order-1", "--name", "approval", "-i", `{ "approved": true }`, "-i", `"ann"`) diff --git a/docs/features/workflow-cli.md b/docs/features/workflow-cli.md index c0d2e19..a47f58e 100644 --- a/docs/features/workflow-cli.md +++ b/docs/features/workflow-cli.md @@ -46,7 +46,8 @@ setting (`clientconfig.ReplaceCredential`): a level that sets either replaces bo (`NotFound`, `Unavailable`). An existing namespace (`AlreadyExists`) is reported and left unchanged, and the attribute is still ensured; the engine skips attributes that exist. - `workflow list` and `count` take Temporal's visibility query; `list` pages through 100 at a time up to `--limit` - (100; 0 for all). `show` pages through the whole history. `signal` encodes each `--input` as a `json/plain` + (100; 0 for all). `show` pages through the whole history; responses up to 128 MiB are accepted, as in the + Temporal Go SDK, since one history page can hold 256 events of up to 2 MiB each. `signal` encodes each `--input` as a `json/plain` payload after checking it is JSON; `signal` and `cancel` send a fresh request ID, and every change carries the identity `workflow-cli@`, which the workflow's history records. - `task-queue describe` calls `DescribeTaskQueue` once for workflow and once for activity tasks and lists their @@ -73,7 +74,7 @@ it exists. | Test | Covers | |---|---| | `cli/internal/command/command_test.go` | Every command against an in-memory fake engine (bufconn): health per service and exit codes, describe with and without the admin API, namespace create (cache retry, idempotence), describe, list over pages, update, search attributes, profile/environment/flag precedence and the bearer header, a token file replacing an earlier level's token, `config` commands and file mode, error messages | -| `cli/internal/command/workflow_test.go` | `workflow list` over pages with a query and `--limit`, `count`, `describe`, `show` over pages, `signal` payloads, identity and request ID, `describe` and `show` sending `-r`, `cancel` and `terminate` with reasons and run IDs, confirmations on stderr with `-o json`, `task-queue describe` with and without pollers, error messages | +| `cli/internal/command/workflow_test.go` | `workflow list` over pages with a query and `--limit`, `count`, `describe`, `show` over pages and with a page over 4 MiB, `signal` payloads, identity and request ID, `describe` and `show` sending `-r`, `cancel` and `terminate` with reasons and run IDs, confirmations on stderr with `-o json`, `task-queue describe` with and without pollers, error messages | | `cli/internal/command/dial_test.go` | Mutual TLS against a real TLS server, refusal without a client certificate or TLS, token refused in plain text off-loopback, CA, client certificate and key file errors | | `cli/internal/clientconfig/clientconfig_test.go` | Profile file parsing, unknown keys, environment variables, TLS on/off rules, writing and deleting properties, profile names that would nest refused with the file left readable | | `tools/internal/enginetest/workflowcli_test.go` | Against the real engine: every P0 and P1 command on `start-dev` (workflows started on a task queue no worker polls: listed by `WorkflowKind`, described, signalled, cancelled and terminated, their history shown); on a secured engine, profiles with admin and namespace tokens, refusals, a token never sent in plain text, a namespace token listing only its own namespace and counting a workflow started in it, and the health of each internal port with a node certificate | From daaa9de7034307d5d12c1b59da9256f885fb8e42 Mon Sep 17 00:00:00 2001 From: Hasitha Aravinda Date: Thu, 19 Nov 2026 11:10:08 +0530 Subject: [PATCH 6/6] fix(cli): ask the engine only for the workflows --limit needs --- cli/internal/command/workflow.go | 7 ++++++- cli/internal/command/workflow_test.go | 13 ++++++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/cli/internal/command/workflow.go b/cli/internal/command/workflow.go index a2c70cb..b4cc742 100644 --- a/cli/internal/command/workflow.go +++ b/cli/internal/command/workflow.go @@ -82,8 +82,13 @@ func (c *cli) workflowListCommand() *cobra.Command { var all []*workflowpb.WorkflowExecutionInfo var token []byte for limit == 0 || len(all) < limit { + // Ask only for the rows still needed, so a small --limit runs a small visibility query. + pageSize := 100 + if limit > 0 { + pageSize = min(pageSize, limit-len(all)) + } res, err := client.ListWorkflowExecutions(ctx, &workflowservice.ListWorkflowExecutionsRequest{ - Namespace: s.Namespace, Query: query, PageSize: 100, NextPageToken: token, + Namespace: s.Namespace, Query: query, PageSize: int32(pageSize), NextPageToken: token, //nolint:gosec // at most 100 }) if err != nil { return fmt.Errorf("unable to list workflows: %w", err) diff --git a/cli/internal/command/workflow_test.go b/cli/internal/command/workflow_test.go index 061c9dd..904bc99 100644 --- a/cli/internal/command/workflow_test.go +++ b/cli/internal/command/workflow_test.go @@ -43,6 +43,7 @@ type workflowState struct { cancels []*workflowservice.RequestCancelWorkflowExecutionRequest ends []*workflowservice.TerminateWorkflowExecutionRequest queries []string + sizes []int32 // the page sizes list requests asked for runIDs []string pollers map[enumspb.TaskQueueType][]*taskqueuepb.PollerInfo } @@ -84,11 +85,12 @@ func (f workflowFake) ListWorkflowExecutions(ctx context.Context, r *workflowser defer f.mu.Unlock() w := f.workflows w.queries = append(w.queries, r.GetQuery()) + w.sizes = append(w.sizes, r.GetPageSize()) start := 0 if len(r.GetNextPageToken()) > 0 { start = int(r.GetNextPageToken()[0]) } - end := min(start+2, len(w.infos)) + end := min(start+2, start+int(r.GetPageSize()), len(w.infos)) res := &workflowservice.ListWorkflowExecutionsResponse{Executions: w.infos[start:end]} if end < len(w.infos) { res.NextPageToken = []byte{byte(end)} @@ -198,9 +200,18 @@ func TestWorkflowListAndCount(t *testing.T) { if q := tc.engine.workflows.queries; q[0] != `WorkflowKind="orders.Order"` || len(q) != 2 { t.Fatalf("queries = %q, want the query on both pages", q) } + tc.engine.workflows.sizes = nil if out := tc.must("workflow", "list", "--limit", "1"); strings.Contains(out, "order-2") { t.Fatalf("--limit 1 listed more:\n%s", out) } + if s := tc.engine.workflows.sizes; !slices.Equal(s, []int32{1}) { + t.Fatalf("--limit 1 asked for pages of %v, want one page of 1", s) + } + tc.engine.workflows.sizes = nil + tc.must("workflow", "list", "--limit", "3") + if s := tc.engine.workflows.sizes; !slices.Equal(s, []int32{3, 1}) { + t.Fatalf("--limit 3 asked for pages of %v, want 3 then the 1 still needed", s) + } var list []map[string]any if err := json.Unmarshal([]byte(tc.must("workflow", "list", "-o", "json", "--limit", "0")), &list); err != nil || len(list) != 3 {