diff --git a/go.mod b/go.mod index 0fba24bd3..826ecae1a 100644 --- a/go.mod +++ b/go.mod @@ -10,17 +10,17 @@ require ( github.com/fatih/color v1.19.0 github.com/google/uuid v1.6.0 github.com/mattn/go-isatty v0.0.23 - github.com/nexus-rpc/sdk-go v0.7.0 + github.com/nexus-rpc/sdk-go v0.8.0 github.com/olekukonko/tablewriter v0.0.5 github.com/spf13/cobra v1.10.2 github.com/spf13/pflag v1.0.10 github.com/stretchr/testify v1.12.1 github.com/temporalio/cli/cliext v0.0.0 github.com/temporalio/ui-server/v2 v2.56.4 - go.temporal.io/api v1.64.1-0.20261030195137-01272cbd37c9 - go.temporal.io/sdk v1.49.0 + go.temporal.io/api v1.64.4 + go.temporal.io/sdk v1.52.1-0.20261202231524-20e9cbc2994f go.temporal.io/sdk/contrib/envconfig v1.1.0 - go.temporal.io/server v1.33.0-166.3 + go.temporal.io/server v1.33.0-168.3 golang.org/x/exp v0.0.0-20260611194520-c48552f49976 golang.org/x/mod v0.41.0 golang.org/x/term v0.47.0 diff --git a/go.sum b/go.sum index 97ffb93a4..13dc24398 100644 --- a/go.sum +++ b/go.sum @@ -338,8 +338,8 @@ github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOF github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= github.com/nexus-rpc/nexus-proto-annotations v0.1.0 h1:2fELd+9sqUtNu6Fg//pw8YFsxOvp8vZ8hfP0nHhNI80= github.com/nexus-rpc/nexus-proto-annotations v0.1.0/go.mod h1:n3UjF1bPCW8llR8tHvbxJ+27yPWrhpo8w/Yg1IOuY0Y= -github.com/nexus-rpc/sdk-go v0.7.0 h1:38NrfY5rLnZAiMMs2ZfCKI/CSDzdfJG+27iAgfA8bUI= -github.com/nexus-rpc/sdk-go v0.7.0/go.mod h1:FHdPfVQwRuJFZFTF0Y2GOAxCrbIBNrcPna9slkGKPYk= +github.com/nexus-rpc/sdk-go v0.8.0 h1:xQbsF3KHlCwbIt7fMkAk6gx2iE/NYsg9pHRTZgq95VQ= +github.com/nexus-rpc/sdk-go v0.8.0/go.mod h1:FHdPfVQwRuJFZFTF0Y2GOAxCrbIBNrcPna9slkGKPYk= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= @@ -479,18 +479,18 @@ go.opentelemetry.io/otel/trace v1.45.0 h1:l/mP6Uv7oNO7/TblbhpbgMidxhq1uO/rPsikOy go.opentelemetry.io/otel/trace v1.45.0/go.mod h1:qoJJA2xNMnxRrdISU/kLtfUH2wNeQbiv+jhs/CxI8bc= go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk= go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E= -go.temporal.io/api v1.64.1-0.20261030195137-01272cbd37c9 h1:ZJb+HC/3UhzBBnvzKhGOVNf6WSDpNPBDn94vhEBfZVo= -go.temporal.io/api v1.64.1-0.20261030195137-01272cbd37c9/go.mod h1:acM0I9WPuYg8W3Pd9jOZvEgi7mRUttUQ4+e7fowKVnM= +go.temporal.io/api v1.64.4 h1:SHiPMuT9j/txHwk9QAsFE4/KNMcXtgD9z9f5L4ERBLU= +go.temporal.io/api v1.64.4/go.mod h1:acM0I9WPuYg8W3Pd9jOZvEgi7mRUttUQ4+e7fowKVnM= go.temporal.io/auto-scaled-workers v0.0.0-20261030203857-75274b664c29 h1:wr2yPeTpZAvovJ1tQviQFfcZQRuqvdhU1T+6yvZ23S0= go.temporal.io/auto-scaled-workers v0.0.0-20261030203857-75274b664c29/go.mod h1:Wcxj1DAGbC/tQwcfX8VjGhVKM9+/idGDQIvYx/gf13Y= -go.temporal.io/sdk v1.49.0 h1:CtGI0BUe/SCo3eoqTwuWWtXKueii9GBVus7KrKKH1Vo= -go.temporal.io/sdk v1.49.0/go.mod h1:xP0FulN5JJSfisESUP60LlWsrKz2tLSStGjVdk8r5cc= +go.temporal.io/sdk v1.52.1-0.20261202231524-20e9cbc2994f h1:Ze3hiwLZiFF4ifH0btrOV7UI63TFJHA2fH9+hyDzA+k= +go.temporal.io/sdk v1.52.1-0.20261202231524-20e9cbc2994f/go.mod h1:H0KRRzQ/L5EZwtVOIsOyqq16Gm/1meYGJhzwBCZ+lkk= go.temporal.io/sdk/contrib/envconfig v1.1.0 h1:9HGsyrZytjdcZeWJwQlczqYulMhmHS2PRcarcFRjMRE= go.temporal.io/sdk/contrib/envconfig v1.1.0/go.mod h1:th96Zl21YH2mHEe3uZ5Dw0KwZFSF4I2oSwTcUxGA19Y= -go.temporal.io/server v1.33.0-166.3 h1:y3tLzHag7F6Pv5EieBUJk2+RlTkUhKT1TaC7k5k2HcQ= -go.temporal.io/server v1.33.0-166.3/go.mod h1:SP/bukdhfHYhAlaz7oghgdNZvJtEaBmPjzvSbvkS2jk= -go.temporal.io/testx v0.0.0-20261029001555-ddcb0739798d h1:SK9slpVz38T0H1ldMpsh/GFWrVTZw7gWC3i2An0rviI= -go.temporal.io/testx v0.0.0-20261029001555-ddcb0739798d/go.mod h1:nL3IFIKnioDnUxNaqKLyzR2tZUK6THrXsaQuVjNYVX8= +go.temporal.io/server v1.33.0-168.3 h1:CSzVO6eM/qgd3jbLLh6IKBXe05DIWcv3RPeHViLfOIc= +go.temporal.io/server v1.33.0-168.3/go.mod h1:VZr6mUoqAe1bPiJeINuggEOZgqUfR3o7059vGuvEsh4= +go.temporal.io/testx v0.0.0-20261112171501-c4cea589f218 h1:ZUWWvMMda6gW5w+w2CjbZpM18wdXUQ3kM0bB5jADu0A= +go.temporal.io/testx v0.0.0-20261112171501-c4cea589f218/go.mod h1:nL3IFIKnioDnUxNaqKLyzR2tZUK6THrXsaQuVjNYVX8= go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= diff --git a/internal/devserver/server.go b/internal/devserver/server.go index 5da778138..01d812820 100644 --- a/internal/devserver/server.go +++ b/internal/devserver/server.go @@ -85,6 +85,7 @@ type StartOptions struct { SqlitePragmas map[string]string FrontendHTTPPort int EnableGlobalNamespace bool + EnableTimeSkipping bool DynamicConfigValues map[string]any SearchAttributes map[string]enums.IndexedValueType LogConfig func([]byte) @@ -254,6 +255,9 @@ func (s *StartOptions) buildServerOptions() ([]temporal.ServerOption, *slog.Leve for k, v := range s.DynamicConfigValues { dynConf[dynamicconfig.MakeKey(k)] = v } + if s.EnableTimeSkipping { + applyTimeSkippingDynamicConfig(dynConf) + } opts = append(opts, temporal.WithDynamicConfigClient(dynConf)) // gRPC interceptors if set diff --git a/internal/devserver/server_test.go b/internal/devserver/server_test.go new file mode 100644 index 000000000..e0fd5f7f5 --- /dev/null +++ b/internal/devserver/server_test.go @@ -0,0 +1,103 @@ +package devserver + +import ( + "testing" + + "github.com/stretchr/testify/require" + "go.temporal.io/server/common/dynamicconfig" + "go.temporal.io/server/common/log" +) + +func timeSkippingConfigForTest(values map[string]any, enabled bool) dynamicconfig.StaticClient { + config := make(dynamicconfig.StaticClient) + for key, value := range values { + config[dynamicconfig.MakeKey(key)] = value + } + if enabled { + applyTimeSkippingDynamicConfig(config) + } + return config +} + +func TestDevServerTimeSkippingDynamicConfigPrecedence(t *testing.T) { + type wantConfig struct { + workflow, schedule, creation, routing bool + rollout, maxSkip int + } + serverDefaults := wantConfig{routing: true, maxSkip: 200} + allEnabled := wantConfig{workflow: true, schedule: true, creation: true, routing: true, rollout: 100, maxSkip: 200} + + for _, tc := range []struct { + name string + enabled bool + explicit map[string]any + want wantConfig + }{ + {name: "flag off uses server defaults", want: serverDefaults}, + {name: "flag on without explicit config", enabled: true, want: allEnabled}, + { + name: "explicit global config overrides all time-skipping defaults", + enabled: true, + explicit: map[string]any{ + dynamicconfig.WorkflowTimeSkippingEnabled.Key().String(): false, + dynamicconfig.CHASMSchedulerTimeSkippingEnabled.Key().String(): false, + dynamicconfig.EnableCHASMSchedulerCreation.Key().String(): false, + dynamicconfig.CHASMSchedulerCreationRolloutPercent.Key().String(): 0, + dynamicconfig.EnableCHASMSchedulerRouting.Key().String(): false, + }, + want: wantConfig{maxSkip: 200}, + }, + { + name: "partial global override preserves other defaults", + enabled: true, + explicit: map[string]any{ + dynamicconfig.CHASMSchedulerTimeSkippingEnabled.Key().String(): false, + }, + want: wantConfig{workflow: true, creation: true, routing: true, rollout: 100, maxSkip: 200}, + }, + { + name: "explicit global max skip overrides server default", + enabled: true, + explicit: map[string]any{ + dynamicconfig.TimeSkippingMaxSkipPerSession.Key().String(): 50, + }, + want: wantConfig{workflow: true, schedule: true, creation: true, routing: true, rollout: 100, maxSkip: 50}, + }, + { + name: "flag off preserves explicit global config", + explicit: map[string]any{ + dynamicconfig.WorkflowTimeSkippingEnabled.Key().String(): true, + }, + want: wantConfig{workflow: true, routing: true, maxSkip: 200}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + raw := timeSkippingConfigForTest(tc.explicit, tc.enabled) + for key, value := range tc.explicit { + require.Equal(t, value, raw[dynamicconfig.MakeKey(key)], "explicit key %s was replaced", key) + } + for key, fallback := range timeSkippingDynamicConfigDefaults { + if _, explicit := tc.explicit[key.String()]; explicit { + continue + } + if tc.enabled { + require.Equal(t, fallback, raw[key], "key %s", key) + } else { + _, present := raw[key] + require.False(t, present, "unexpected override for %s", key) + } + } + config := dynamicconfig.NewCollection(raw, log.NewNoopLogger()) + for _, namespace := range []string{"timeskipping-test", "another-namespace"} { + t.Run(namespace, func(t *testing.T) { + require.Equal(t, tc.want.workflow, dynamicconfig.WorkflowTimeSkippingEnabled.Get(config)(namespace)) + require.Equal(t, tc.want.schedule, dynamicconfig.CHASMSchedulerTimeSkippingEnabled.Get(config)(namespace)) + require.Equal(t, tc.want.creation, dynamicconfig.EnableCHASMSchedulerCreation.Get(config)(namespace)) + require.Equal(t, tc.want.rollout, dynamicconfig.CHASMSchedulerCreationRolloutPercent.Get(config)(namespace)) + require.Equal(t, tc.want.routing, dynamicconfig.EnableCHASMSchedulerRouting.Get(config)(namespace)) + require.Equal(t, tc.want.maxSkip, dynamicconfig.TimeSkippingMaxSkipPerSession.Get(config)(namespace)) + }) + } + }) + } +} diff --git a/internal/devserver/time_skipping_config.go b/internal/devserver/time_skipping_config.go new file mode 100644 index 000000000..cc48f542e --- /dev/null +++ b/internal/devserver/time_skipping_config.go @@ -0,0 +1,20 @@ +package devserver + +import "go.temporal.io/server/common/dynamicconfig" + +var timeSkippingDynamicConfigDefaults = map[dynamicconfig.Key]any{ + dynamicconfig.WorkflowTimeSkippingEnabled.Key(): true, + dynamicconfig.CHASMSchedulerTimeSkippingEnabled.Key(): true, + dynamicconfig.EnableCHASMSchedulerCreation.Key(): true, + dynamicconfig.CHASMSchedulerCreationRolloutPercent.Key(): 100, + dynamicconfig.EnableCHASMSchedulerRouting.Key(): true, +} + +func applyTimeSkippingDynamicConfig(dynConf dynamicconfig.StaticClient) { + for key, fallback := range timeSkippingDynamicConfigDefaults { + // Explicit dynamic config values take precedence over these defaults. + if _, exists := dynConf[key]; !exists { + dynConf[key] = fallback + } + } +} diff --git a/internal/temporalcli/commands.gen.go b/internal/temporalcli/commands.gen.go index 7e314c50b..452b4277e 100644 --- a/internal/temporalcli/commands.gen.go +++ b/internal/temporalcli/commands.gen.go @@ -38,6 +38,16 @@ func (v *ScheduleIdOptions) BuildFlags(f *pflag.FlagSet) { _ = cobra.MarkFlagRequired(f, "schedule-id") } +type MaxSkipPerSessionOptions struct { + MaxSkipPerSession int + FlagSet *pflag.FlagSet +} + +func (v *MaxSkipPerSessionOptions) BuildFlags(f *pflag.FlagSet) { + v.FlagSet = f + f.IntVar(&v.MaxSkipPerSession, "max-skip-per-session", 0, "Limit the number of time skips in a single time-skipping session. A session starts when time skipping is enabled and ends when it is automatically disabled. Updating the time-skipping configuration resets the session. Omit to use the server default, which is 200 and can be configured through the `system.timeSkippingMaxSkipPerSession` dynamic config. Usually leave this unset unless a previous test reached the limit and time skipping turned off automatically; then set a higher value. If specified, must be between 1 and 10000. Use `temporal schedule describe` or `temporal workflow describe` to check `MaxSessionSkipCount`, `CurrentSessionSkipCount`, and `EffectiveEnabled` in the time-skipping status.") +} + type ScheduleConfigurationOptions struct { Calendar []string CatchupWindow cliext.FlagDuration @@ -2588,6 +2598,7 @@ func NewTemporalScheduleCommand(cctx *CommandContext, parent *TemporalCommand) * s.Command.AddCommand(&NewTemporalScheduleDescribeCommand(cctx, &s).Command) s.Command.AddCommand(&NewTemporalScheduleListCommand(cctx, &s).Command) s.Command.AddCommand(&NewTemporalScheduleListMatchingTimesCommand(cctx, &s).Command) + s.Command.AddCommand(&NewTemporalScheduleTimeSkippingCommand(cctx, &s).Command) s.Command.AddCommand(&NewTemporalScheduleToggleCommand(cctx, &s).Command) s.Command.AddCommand(&NewTemporalScheduleTriggerCommand(cctx, &s).Command) s.Command.AddCommand(&NewTemporalScheduleUpdateCommand(cctx, &s).Command) @@ -2789,6 +2800,118 @@ func NewTemporalScheduleListMatchingTimesCommand(cctx *CommandContext, parent *T return &s } +type TemporalScheduleTimeSkippingCommand struct { + Parent *TemporalScheduleCommand + Command cobra.Command +} + +func NewTemporalScheduleTimeSkippingCommand(cctx *CommandContext, parent *TemporalScheduleCommand) *TemporalScheduleTimeSkippingCommand { + var s TemporalScheduleTimeSkippingCommand + s.Parent = parent + s.Command.Use = "time-skipping" + s.Command.Short = "Manage Schedule time skipping (Experimental)" + s.Command.Long = "Manage Schedule time skipping, where a schedule's virtual clock fast-forwards when idle.\nUse time skipping in testing environments to efficiently evaluate the behavior of a schedule.\n\nNote: This is an experimental feature and may change in the future." + s.Command.Args = cobra.NoArgs + s.Command.AddCommand(&NewTemporalScheduleTimeSkippingDisableCommand(cctx, &s).Command) + s.Command.AddCommand(&NewTemporalScheduleTimeSkippingEnableCommand(cctx, &s).Command) + s.Command.AddCommand(&NewTemporalScheduleTimeSkippingPollCommand(cctx, &s).Command) + return &s +} + +type TemporalScheduleTimeSkippingDisableCommand struct { + Parent *TemporalScheduleTimeSkippingCommand + Command cobra.Command + ScheduleIdOptions +} + +func NewTemporalScheduleTimeSkippingDisableCommand(cctx *CommandContext, parent *TemporalScheduleTimeSkippingCommand) *TemporalScheduleTimeSkippingDisableCommand { + var s TemporalScheduleTimeSkippingDisableCommand + s.Parent = parent + s.Command.DisableFlagsInUseLine = true + s.Command.Use = "disable [flags]" + s.Command.Short = "Disable Schedule time skipping (Experimental)" + if hasHighlighting { + s.Command.Long = "Disable time skipping for a Schedule:\n\n\x1b[1mtemporal schedule time-skipping disable \\\n --namespace YourNamespace \\\n --schedule-id YourScheduleId\x1b[0m\n\nNo other time-skipping flags are needed." + } else { + s.Command.Long = "Disable time skipping for a Schedule:\n\n```\ntemporal schedule time-skipping disable \\\n --namespace YourNamespace \\\n --schedule-id YourScheduleId\n```\n\nNo other time-skipping flags are needed." + } + s.Command.Args = cobra.NoArgs + s.ScheduleIdOptions.BuildFlags(s.Command.Flags()) + s.Command.Run = func(c *cobra.Command, args []string) { + if err := s.run(cctx, args); err != nil { + cctx.Options.Fail(err) + } + } + return &s +} + +type TemporalScheduleTimeSkippingEnableCommand struct { + Parent *TemporalScheduleTimeSkippingCommand + Command cobra.Command + ScheduleIdOptions + MaxSkipPerSessionOptions + FastForwardDuration cliext.FlagDuration + FastForwardId string + DisablePropagation bool +} + +func NewTemporalScheduleTimeSkippingEnableCommand(cctx *CommandContext, parent *TemporalScheduleTimeSkippingCommand) *TemporalScheduleTimeSkippingEnableCommand { + var s TemporalScheduleTimeSkippingEnableCommand + s.Parent = parent + s.Command.DisableFlagsInUseLine = true + s.Command.Use = "enable [flags]" + s.Command.Short = "Enable Schedule time skipping (Experimental)" + if hasHighlighting { + s.Command.Long = "Enable time skipping for a Schedule:\n\n\x1b[1mtemporal schedule time-skipping enable \\\n --namespace YourNamespace \\\n --schedule-id YourScheduleId \\\n --fast-forward-duration 5h\x1b[0m\n\nOnce enabled, the Schedule advances its virtual clock during inactivity,\nallowing scheduled Workflows to start without waiting for wall-clock time." + } else { + s.Command.Long = "Enable time skipping for a Schedule:\n\n```\ntemporal schedule time-skipping enable \\\n --namespace YourNamespace \\\n --schedule-id YourScheduleId \\\n --fast-forward-duration 5h\n```\n\nOnce enabled, the Schedule advances its virtual clock during inactivity,\nallowing scheduled Workflows to start without waiting for wall-clock time." + } + s.Command.Args = cobra.NoArgs + s.FastForwardDuration = 0 + s.Command.Flags().Var(&s.FastForwardDuration, "fast-forward-duration", "Fast-forward the Schedule's virtual time by this duration. Must be greater than zero. Required.") + _ = cobra.MarkFlagRequired(s.Command.Flags(), "fast-forward-duration") + s.Command.Flags().StringVar(&s.FastForwardId, "fast-forward-id", "", "Identify this fast-forward in Schedule status. Generated if omitted. Not an idempotency key.") + s.Command.Flags().BoolVar(&s.DisablePropagation, "disable-propagation", false, "Defaults to false. Omit this flag or set it to false to propagate the time-skipping enabled state to Workflows started by this Schedule. Set it to true, or specify it without a value, to disable propagation. Fast-forward targets are never propagated. Virtual time is propagated regardless of this flag.") + s.ScheduleIdOptions.BuildFlags(s.Command.Flags()) + s.MaxSkipPerSessionOptions.BuildFlags(s.Command.Flags()) + s.Command.Run = func(c *cobra.Command, args []string) { + if err := s.run(cctx, args); err != nil { + cctx.Options.Fail(err) + } + } + return &s +} + +type TemporalScheduleTimeSkippingPollCommand struct { + Parent *TemporalScheduleTimeSkippingCommand + Command cobra.Command + ScheduleIdOptions + FastForwardId string +} + +func NewTemporalScheduleTimeSkippingPollCommand(cctx *CommandContext, parent *TemporalScheduleTimeSkippingCommand) *TemporalScheduleTimeSkippingPollCommand { + var s TemporalScheduleTimeSkippingPollCommand + s.Parent = parent + s.Command.DisableFlagsInUseLine = true + s.Command.Use = "poll [flags]" + s.Command.Short = "Poll a Schedule fast-forward (Experimental)" + if hasHighlighting { + s.Command.Long = "Poll Schedule time-skipping status for a specific fast-forward setting:\n\n\x1b[1mtemporal schedule time-skipping poll \\\n --namespace YourNamespace \\\n --schedule-id YourScheduleId \\\n --fast-forward-id YourFastForwardId\x1b[0m\n\nUse the global \x1b[1m--command-timeout\x1b[0m flag to limit how long the poll waits.\nA failed fast-forward or poll timeout returns a nonzero exit status." + } else { + s.Command.Long = "Poll Schedule time-skipping status for a specific fast-forward setting:\n\n```\ntemporal schedule time-skipping poll \\\n --namespace YourNamespace \\\n --schedule-id YourScheduleId \\\n --fast-forward-id YourFastForwardId\n```\n\nUse the global `--command-timeout` flag to limit how long the poll waits.\nA failed fast-forward or poll timeout returns a nonzero exit status." + } + s.Command.Args = cobra.NoArgs + s.Command.Flags().StringVar(&s.FastForwardId, "fast-forward-id", "", "ID of the fast-forward to poll. Required.") + _ = cobra.MarkFlagRequired(s.Command.Flags(), "fast-forward-id") + s.ScheduleIdOptions.BuildFlags(s.Command.Flags()) + s.Command.Run = func(c *cobra.Command, args []string) { + if err := s.run(cctx, args); err != nil { + cctx.Options.Fail(err) + } + } + return &s +} + type TemporalScheduleToggleCommand struct { Parent *TemporalScheduleCommand Command cobra.Command @@ -2919,6 +3042,7 @@ type TemporalServerStartDevCommand struct { MetricsPort int UiPort int Headless bool + EnableTimeSkipping bool Ip string UiIp string UiPublicPath string @@ -2950,6 +3074,7 @@ func NewTemporalServerStartDevCommand(cctx *CommandContext, parent *TemporalServ s.Command.Flags().IntVar(&s.MetricsPort, "metrics-port", 0, "Port for the '/metrics' HTTP endpoint. Defaults to a random free port.") s.Command.Flags().IntVar(&s.UiPort, "ui-port", 0, "Port for the Web UI. Defaults to '--port' value + 1000.") s.Command.Flags().BoolVar(&s.Headless, "headless", false, "Disable the Web UI.") + s.Command.Flags().BoolVar(&s.EnableTimeSkipping, "enable-time-skipping", false, "Enable Workflow and CHASM Schedule time skipping in all Namespaces for this dev server run. Also enable CHASM Schedule creation and routing. Explicit dynamic config values take precedence.") s.Command.Flags().StringVar(&s.Ip, "ip", "localhost", "IP address bound to the front-end Service.") s.Command.Flags().StringVar(&s.UiIp, "ui-ip", "", "IP address bound to the Web UI. Defaults to same as '--ip' value.") s.Command.Flags().StringVar(&s.UiPublicPath, "ui-public-path", "", "The public base path for the Web UI. Defaults to `/`.") @@ -4746,6 +4871,7 @@ func NewTemporalWorkflowCommand(cctx *CommandContext, parent *TemporalCommand) * s.Command.AddCommand(&NewTemporalWorkflowStartCommand(cctx, &s).Command) s.Command.AddCommand(&NewTemporalWorkflowStartUpdateWithStartCommand(cctx, &s).Command) s.Command.AddCommand(&NewTemporalWorkflowTerminateCommand(cctx, &s).Command) + s.Command.AddCommand(&NewTemporalWorkflowTimeSkippingCommand(cctx, &s).Command) s.Command.AddCommand(&NewTemporalWorkflowTraceCommand(cctx, &s).Command) s.Command.AddCommand(&NewTemporalWorkflowUnpauseCommand(cctx, &s).Command) s.Command.AddCommand(&NewTemporalWorkflowUpdateCommand(cctx, &s).Command) @@ -5480,6 +5606,118 @@ func NewTemporalWorkflowTerminateCommand(cctx *CommandContext, parent *TemporalW return &s } +type TemporalWorkflowTimeSkippingCommand struct { + Parent *TemporalWorkflowCommand + Command cobra.Command +} + +func NewTemporalWorkflowTimeSkippingCommand(cctx *CommandContext, parent *TemporalWorkflowCommand) *TemporalWorkflowTimeSkippingCommand { + var s TemporalWorkflowTimeSkippingCommand + s.Parent = parent + s.Command.Use = "time-skipping" + s.Command.Short = "Manage Workflow time skipping (Experimental)" + s.Command.Long = "Manage Workflow time skipping, where a workflow skips time when idle.\nUse time skipping in testing environments to efficiently evaluate \nthe behavior of a workflow with extended periods of inactivity.\n\nNote: This is an experimental feature and may change in the future." + s.Command.Args = cobra.NoArgs + s.Command.AddCommand(&NewTemporalWorkflowTimeSkippingDisableCommand(cctx, &s).Command) + s.Command.AddCommand(&NewTemporalWorkflowTimeSkippingEnableCommand(cctx, &s).Command) + s.Command.AddCommand(&NewTemporalWorkflowTimeSkippingPollCommand(cctx, &s).Command) + return &s +} + +type TemporalWorkflowTimeSkippingDisableCommand struct { + Parent *TemporalWorkflowTimeSkippingCommand + Command cobra.Command + WorkflowReferenceOptions +} + +func NewTemporalWorkflowTimeSkippingDisableCommand(cctx *CommandContext, parent *TemporalWorkflowTimeSkippingCommand) *TemporalWorkflowTimeSkippingDisableCommand { + var s TemporalWorkflowTimeSkippingDisableCommand + s.Parent = parent + s.Command.DisableFlagsInUseLine = true + s.Command.Use = "disable [flags]" + s.Command.Short = "Disable Workflow time skipping (Experimental)" + if hasHighlighting { + s.Command.Long = "Disable time skipping for a Workflow Execution:\n\n\x1b[1mtemporal workflow time-skipping disable \\\n --namespace YourNamespace \\\n --workflow-id YourWorkflowId\x1b[0m\n\nNo other time-skipping flags are needed." + } else { + s.Command.Long = "Disable time skipping for a Workflow Execution:\n\n```\ntemporal workflow time-skipping disable \\\n --namespace YourNamespace \\\n --workflow-id YourWorkflowId\n```\n\nNo other time-skipping flags are needed." + } + s.Command.Args = cobra.NoArgs + s.WorkflowReferenceOptions.BuildFlags(s.Command.Flags()) + s.Command.Run = func(c *cobra.Command, args []string) { + if err := s.run(cctx, args); err != nil { + cctx.Options.Fail(err) + } + } + return &s +} + +type TemporalWorkflowTimeSkippingEnableCommand struct { + Parent *TemporalWorkflowTimeSkippingCommand + Command cobra.Command + WorkflowReferenceOptions + MaxSkipPerSessionOptions + FastForwardDuration cliext.FlagDuration + FastForwardId string + DisablePropagation bool +} + +func NewTemporalWorkflowTimeSkippingEnableCommand(cctx *CommandContext, parent *TemporalWorkflowTimeSkippingCommand) *TemporalWorkflowTimeSkippingEnableCommand { + var s TemporalWorkflowTimeSkippingEnableCommand + s.Parent = parent + s.Command.DisableFlagsInUseLine = true + s.Command.Use = "enable [flags]" + s.Command.Short = "Enable Workflow time skipping (Experimental)" + if hasHighlighting { + s.Command.Long = "Enable time skipping for a Workflow Execution:\n\n\x1b[1mtemporal workflow time-skipping enable \\\n --namespace YourNamespace \\\n --workflow-id YourWorkflowId\x1b[0m\nOnce enabled, the workflow execution skips time during inactivity, \nexpediting the completion of timers, retry waits, and start delays." + } else { + s.Command.Long = "Enable time skipping for a Workflow Execution:\n\n```\ntemporal workflow time-skipping enable \\\n --namespace YourNamespace \\\n --workflow-id YourWorkflowId\n```\nOnce enabled, the workflow execution skips time during inactivity, \nexpediting the completion of timers, retry waits, and start delays." + } + s.Command.Args = cobra.NoArgs + s.FastForwardDuration = 0 + s.Command.Flags().Var(&s.FastForwardDuration, "fast-forward-duration", "Fast-forward the Workflow Execution's virtual time by this duration. Must be greater than zero.") + s.Command.Flags().StringVar(&s.FastForwardId, "fast-forward-id", "", "Identify this fast-forward in Workflow status and when polling for completion. Generated if omitted. Not an idempotency key. Requires --fast-forward-duration.") + s.Command.Flags().BoolVar(&s.DisablePropagation, "disable-propagation", false, "Defaults to false. Omit this flag or set it to false to propagate the time-skipping enabled state to child Workflows started by this Workflow. Set it to true, or specify it without a value, to disable propagation. Fast-forward targets are never propagated. Virtual time is propagated regardless of this flag.") + s.WorkflowReferenceOptions.BuildFlags(s.Command.Flags()) + s.MaxSkipPerSessionOptions.BuildFlags(s.Command.Flags()) + s.Command.Run = func(c *cobra.Command, args []string) { + if err := s.run(cctx, args); err != nil { + cctx.Options.Fail(err) + } + } + return &s +} + +type TemporalWorkflowTimeSkippingPollCommand struct { + Parent *TemporalWorkflowTimeSkippingCommand + Command cobra.Command + WorkflowId string + FastForwardId string +} + +func NewTemporalWorkflowTimeSkippingPollCommand(cctx *CommandContext, parent *TemporalWorkflowTimeSkippingCommand) *TemporalWorkflowTimeSkippingPollCommand { + var s TemporalWorkflowTimeSkippingPollCommand + s.Parent = parent + s.Command.DisableFlagsInUseLine = true + s.Command.Use = "poll [flags]" + s.Command.Short = "Poll a Workflow fast-forward (Experimental)" + if hasHighlighting { + s.Command.Long = "Poll Workflow time-skipping status for a specific fast-forward setting:\n\n\x1b[1mtemporal workflow time-skipping poll \\\n --namespace YourNamespace \\\n --workflow-id YourWorkflowId \\\n --fast-forward-id YourFastForwardId\x1b[0m\n\nUse the global \x1b[1m--command-timeout\x1b[0m flag to limit how long the poll waits.\nA failed fast-forward or poll timeout returns a nonzero exit status." + } else { + s.Command.Long = "Poll Workflow time-skipping status for a specific fast-forward setting:\n\n```\ntemporal workflow time-skipping poll \\\n --namespace YourNamespace \\\n --workflow-id YourWorkflowId \\\n --fast-forward-id YourFastForwardId\n```\n\nUse the global `--command-timeout` flag to limit how long the poll waits.\nA failed fast-forward or poll timeout returns a nonzero exit status." + } + s.Command.Args = cobra.NoArgs + s.Command.Flags().StringVarP(&s.WorkflowId, "workflow-id", "w", "", "Workflow ID. Required.") + _ = cobra.MarkFlagRequired(s.Command.Flags(), "workflow-id") + s.Command.Flags().StringVar(&s.FastForwardId, "fast-forward-id", "", "ID of the fast-forward to poll. Required.") + _ = cobra.MarkFlagRequired(s.Command.Flags(), "fast-forward-id") + s.Command.Run = func(c *cobra.Command, args []string) { + if err := s.run(cctx, args); err != nil { + cctx.Options.Fail(err) + } + } + return &s +} + type TemporalWorkflowTraceCommand struct { Parent *TemporalWorkflowCommand Command cobra.Command diff --git a/internal/temporalcli/commands.schedule.go b/internal/temporalcli/commands.schedule.go index 3a18271bd..f2105572a 100644 --- a/internal/temporalcli/commands.schedule.go +++ b/internal/temporalcli/commands.schedule.go @@ -18,6 +18,7 @@ import ( schedpb "go.temporal.io/api/schedule/v1" "go.temporal.io/api/workflowservice/v1" "go.temporal.io/sdk/client" + "go.temporal.io/sdk/timeskipping" ) type printableSchedule struct { @@ -43,10 +44,11 @@ type printableSchedule struct { // Info NextRunTime time.Time LastRunTime time.Time - RunningWorkflows []string // describe only - CreatedAt time.Time `cli:",cardOmitEmpty"` // describe only - LastUpdateAt time.Time `cli:",cardOmitEmpty"` // describe only - ActionCounts *actionCounts `cli:",cardOmitEmpty"` // describe only + RunningWorkflows []string // describe only + CreatedAt time.Time `cli:",cardOmitEmpty"` // describe only + LastUpdateAt time.Time `cli:",cardOmitEmpty"` // describe only + ActionCounts *actionCounts `cli:",cardOmitEmpty"` // describe only + TimeSkippingInfo *printableTimeSkippingInfo `cli:",cardOmitEmpty"` // describe only // SearchAttributes, Memo SearchAttributes *commonpb.SearchAttributes `cli:",cardOmitEmpty"` Memo *commonpb.Memo `cli:",cardOmitEmpty"` @@ -104,7 +106,7 @@ func describeResultToPrintable(id string, desc *client.ScheduleDescription) *pri MissedCatchupWindow: desc.Info.NumActionsMissedCatchupWindow, SkippedOverlap: desc.Info.NumActionsSkippedOverlap, } - + out.TimeSkippingInfo = clientTimeSkippingToPrintable(desc.Info.TimeSkippingInfo) return out } @@ -424,6 +426,7 @@ func (c *TemporalScheduleListCommand) run(cctx *CommandContext, args []string) e "CreatedAt", "LastUpdateAt", "ActionCounts", + "TimeSkippingInfo", }, Table: &printer.TableOptions{}, } @@ -558,6 +561,84 @@ func (c *TemporalScheduleUpdateCommand) run(cctx *CommandContext, args []string) }) } +func patchScheduleTimeSkipping(cctx *CommandContext, parent *TemporalScheduleCommand, scheduleID string, config *client.TimeSkippingConfig) error { + if config == nil { + return errors.New("time-skipping configuration is required") + } + cl, err := dialClient(cctx, &parent.ClientOptions) + if err != nil { + return err + } + defer cl.Close() + err = timeskipping.SetScheduleTimeSkippingConfig(cctx, cl.ScheduleClient().GetHandle(cctx, scheduleID), timeskipping.ScheduleSetTimeSkippingConfigOptions{Config: config}) + if err != nil { + return err + } + if cctx.JSONOutput { + return printTimeSkippingUpdateJSON(cctx, config) + } + printScheduleTimeSkippingResult(cctx, "updated", scheduleID, config) + return nil +} + +func (c *TemporalScheduleTimeSkippingDisableCommand) run(cctx *CommandContext, args []string) error { + return patchScheduleTimeSkipping(cctx, c.Parent.Parent, c.ScheduleId, &client.TimeSkippingConfig{Enabled: false}) +} + +func (c *TemporalScheduleTimeSkippingEnableCommand) run(cctx *CommandContext, args []string) error { + if c.Command.Flags().Changed("max-skip-per-session") && c.MaxSkipPerSession <= 0 { + return errors.New("--max-skip-per-session must be greater than zero") + } + config, err := timeSkippingConfig(c.FastForwardDuration.Duration(), true, c.FastForwardId, c.DisablePropagation, c.MaxSkipPerSession) + if err != nil { + return err + } + return patchScheduleTimeSkipping(cctx, c.Parent.Parent, c.ScheduleId, config) +} + +func (c *TemporalScheduleTimeSkippingPollCommand) run(cctx *CommandContext, args []string) error { + cl, err := dialClient(cctx, &c.Parent.Parent.ClientOptions) + if err != nil { + return err + } + defer cl.Close() + handle := cl.ScheduleClient().GetHandle(cctx, c.ScheduleId) + + res, err := timeskipping.PollScheduleFastForward(cctx, handle, + timeskipping.SchedulePollFastForwardOptions{FastForwardID: c.FastForwardId}) + if err != nil { + return err + } + if !res.Completed { + return fmt.Errorf("fast-forward failed: %s", res.FailedReason) + } + return printTimeSkippingPollCompleted(cctx) +} + +func printScheduleTimeSkippingResult( + cctx *CommandContext, + action string, + scheduleID string, + config *client.TimeSkippingConfig, +) { + if config == nil || cctx.JSONOutput { + return + } + cctx.Printer.Printlnf("Schedule %s: %s", action, scheduleID) + if config.Enabled { + cctx.Printer.Println("Time skipping: enabled") + } else { + cctx.Printer.Println("Time skipping: disabled") + } + if config.MaxSessionSkipCount > 0 { + cctx.Printer.Printlnf("Maximum skips per session: %d", config.MaxSessionSkipCount) + } + if ff := config.FastForwardConfig; ff != nil { + cctx.Printer.Printlnf("Fast-forward duration: %s", formatDuration(ff.Duration)) + cctx.Printer.Printlnf("Fast-forward ID: %s", ff.ID) + } +} + func formatCalendarSpec(spec client.ScheduleCalendarSpec) *schedpb.CalendarSpec { processField := func(ranges []client.ScheduleRange) string { var out []string diff --git a/internal/temporalcli/commands.schedule_test.go b/internal/temporalcli/commands.schedule_test.go index d3bf978d9..17eaa42a6 100644 --- a/internal/temporalcli/commands.schedule_test.go +++ b/internal/temporalcli/commands.schedule_test.go @@ -10,13 +10,21 @@ import ( "math/rand" "regexp" "strings" + "testing" "time" + "github.com/google/uuid" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/temporalio/cli/internal/temporalcli" "go.temporal.io/api/enums/v1" "go.temporal.io/api/operatorservice/v1" + "go.temporal.io/api/serviceerror" + "go.temporal.io/api/workflowservice/v1" + "go.temporal.io/sdk/client" "go.temporal.io/sdk/workflow" + "google.golang.org/grpc/codes" + "google.golang.org/protobuf/encoding/protojson" ) func (s *SharedServerSuite) createSchedule(args ...string) (schedId, schedWfId string, res *CommandResult) { @@ -59,6 +67,262 @@ func (s *SharedServerSuite) TestSchedule_Create() { s.NoError(res.Err) } +func (s *SharedServerSuite) TestSchedule_TimeSkippingEnable() { + s.useTimeSkippingServer() + schedID, _, res := s.createSchedule("--interval", "10d", "--paused") + s.NoError(res.Err) + res = s.Execute( + "schedule", "time-skipping", "enable", + "--address", s.Address(), + "--schedule-id", schedID, + "--fast-forward-duration", "5h", + "--fast-forward-id", "YourFastForwardId", + "--disable-propagation", + "--max-skip-per-session", "17", + ) + s.NoError(res.Err) + s.Contains(res.Stdout.String(), "Time skipping: enabled") + s.Contains(res.Stdout.String(), "Fast-forward duration: 5h 0m 0s") + s.Contains(res.Stdout.String(), "Fast-forward ID: YourFastForwardId") + s.NotContains(res.Stdout.String(), "Check status") + s.NotContains(res.Stdout.String(), "temporal schedule describe") + s.Contains(res.Stdout.String(), "Maximum skips per session: 17") + res = s.Execute( + "schedule", "describe", + "--address", s.Address(), + "--schedule-id", schedID, + ) + s.NoError(res.Err) + s.Contains(res.Stdout.String(), `"DisablePropagation":true`) +} + +func (s *SharedServerSuite) TestSchedule_TimeSkippingEnableRequiresDuration() { + s.useTimeSkippingServer() + schedID, _, res := s.createSchedule("--interval", "10d", "--paused") + require.NoError(s.T(), res.Err) + + res = s.Execute( + "schedule", "time-skipping", "enable", + "--address", s.Address(), + "--schedule-id", schedID, + ) + s.EqualError(res.Err, `required flag(s) "fast-forward-duration" not set`) + s.Contains(res.Stderr.String(), `Error: required flag(s) "fast-forward-duration" not set`) + s.NotContains(res.Stdout.String(), "Schedule updated:") +} + +func (s *SharedServerSuite) TestSchedule_TimeSkippingEnableGeneratesFastForwardID() { + s.useTimeSkippingServer() + schedID, _, res := s.createSchedule("--interval", "10d", "--paused") + require.NoError(s.T(), res.Err) + + res = s.Execute( + "schedule", "time-skipping", "enable", + "--address", s.Address(), + "--schedule-id", schedID, + "--fast-forward-duration", "5h", + ) + require.NoError(s.T(), res.Err) + match := regexp.MustCompile(`(?m)^Fast-forward ID: (\S+)$`).FindStringSubmatch(res.Stdout.String()) + require.Len(s.T(), match, 2) + fastForwardID := match[1] + _, err := uuid.Parse(fastForwardID) + require.NoError(s.T(), err) + s.NotContains(res.Stdout.String(), "Poll fast-forward:") + s.NotContains(res.Stdout.String(), "Disable time skipping:") + s.NotContains(res.Stdout.String(), "temporal schedule ") + + res = s.Execute( + "schedule", "describe", + "--address", s.Address(), + "--schedule-id", schedID, + ) + require.NoError(s.T(), res.Err) + s.Contains(res.Stdout.String(), `"Id":"`+fastForwardID+`"`) + + // The generated ID is usable in a poll command. + res = s.Execute( + "schedule", "time-skipping", "poll", + "--address", s.Address(), + "--schedule-id", schedID, + "--fast-forward-id", fastForwardID, + "--command-timeout", "200ms", + ) + s.Error(res.Err) + s.Empty(res.Stdout.String()) +} + +func (s *SharedServerSuite) TestSchedule_TimeSkippingPollTimeout() { + s.useTimeSkippingServer() + schedID, _, res := s.createSchedule("--interval", "10d", "--paused") + require.NoError(s.T(), res.Err) + res = s.Execute( + "schedule", "time-skipping", "enable", + "--address", s.Address(), + "--schedule-id", schedID, + "--fast-forward-duration", "5h", + "--fast-forward-id", "YourFastForwardId", + ) + require.NoError(s.T(), res.Err) + + checkPending := func() { + res := s.Execute("schedule", "describe", "--address", s.Address(), + "--schedule-id", schedID, "--output", "json") + require.NoError(s.T(), res.Err) + var description workflowservice.DescribeScheduleResponse + require.NoError(s.T(), protojson.Unmarshal(res.Stdout.Bytes(), &description)) + info := description.GetInfo().GetTimeSkippingInfo() + require.NotNil(s.T(), info.GetFastForwardInfo()) + s.Equal("YourFastForwardId", info.GetFastForwardInfo().GetFastForwardId()) + s.True(info.GetEffectiveConfig().GetEnabled()) + s.False(info.GetFastForwardInfo().GetHasCompleted()) + } + checkPending() + + ctx, cancel := context.WithTimeout(s.Context, 10*time.Second) + defer cancel() + started := time.Now() + res = s.ExecuteWithContext(ctx, "schedule", "time-skipping", "poll", "--address", s.Address(), + "--schedule-id", schedID, "--fast-forward-id", "YourFastForwardId", "--command-timeout", "200ms") + // Accept both context and service deadline errors without relying on their wrapping. + s.Equal(codes.DeadlineExceeded, serviceerror.ToStatus(res.Err).Code()) + s.Empty(res.Stdout.String()) + s.GreaterOrEqual(time.Since(started), 100*time.Millisecond) + s.Less(time.Since(started), 5*time.Second) + s.NoError(ctx.Err(), "the outer test deadline must not cause the poll timeout") + checkPending() +} + +func (s *SharedServerSuite) TestSchedule_TimeSkippingMinimalLifecycle() { + s.useTimeSkippingServer() + schedID, _, res := s.createSchedule("--interval", "10d") + s.NoError(res.Err) + res = s.Execute( + "schedule", "time-skipping", "enable", + "--address", s.Address(), + "--schedule-id", schedID, + "--fast-forward-duration", "5h", + ) + s.NoError(res.Err) + s.Contains(res.Stdout.String(), "Time skipping: enabled") + match := regexp.MustCompile(`(?m)^Fast-forward ID: (\S+)$`).FindStringSubmatch(res.Stdout.String()) + s.Len(match, 2) + fastForwardID := match[1] + _, err := uuid.Parse(fastForwardID) + s.NoError(err) + + res = s.Execute( + "schedule", "time-skipping", "poll", + "--address", s.Address(), + "--schedule-id", schedID, + "--fast-forward-id", fastForwardID, + ) + s.NoError(res.Err) + s.Equal("completed", strings.TrimSpace(res.Stdout.String())) + + res = s.Execute("schedule", "describe", "--address", s.Address(), "--schedule-id", schedID) + s.NoError(res.Err) + s.Contains(res.Stdout.String(), "TimeSkippingInfo") + s.Contains(res.Stdout.String(), `"Id":"`+fastForwardID+`"`) + s.Contains(res.Stdout.String(), `"HasCompleted":true`) + s.Contains(res.Stdout.String(), `"DisablePropagation":false`) + + for _, output := range []string{"json", "jsonl"} { + res = s.Execute("schedule", "describe", "--address", s.Address(), "--schedule-id", schedID, "--output", output) + s.NoError(res.Err) + var description workflowservice.DescribeScheduleResponse + s.NoError(protojson.Unmarshal(res.Stdout.Bytes(), &description)) + s.Equal("DevWorkflow", description.GetSchedule().GetAction().GetStartWorkflow().GetWorkflowType().GetName()) + info := description.GetInfo().GetTimeSkippingInfo() + s.NotNil(info) + s.Equal(fastForwardID, info.GetFastForwardInfo().GetFastForwardId()) + s.True(info.GetFastForwardInfo().GetHasCompleted()) + s.False(info.GetEffectiveConfig().GetDisablePropagation()) + if output == "jsonl" { + s.Len(strings.Split(strings.TrimSpace(res.Stdout.String()), "\n"), 1) + } + } + + res = s.Execute("schedule", "time-skipping", "disable", "--address", s.Address(), "--schedule-id", schedID) + s.NoError(res.Err) + s.Contains(res.Stdout.String(), "Time skipping: disabled") + res = s.Execute("schedule", "describe", "--address", s.Address(), "--schedule-id", schedID) + s.NoError(res.Err) + s.Contains(res.Stdout.String(), `"EffectiveEnabled":false`) +} + +func (s *SharedServerSuite) TestSchedule_TimeSkippingPollFailed() { + s.useTimeSkippingServer() + for _, change := range []string{"not enabled", "disabled", "replaced"} { + s.T().Run(change, func(t *testing.T) { + schedID, _, res := s.createSchedule("--interval", "10d", "--paused") + require.NoError(t, res.Err) + if change != "not enabled" { + res = s.Execute( + "schedule", "time-skipping", "enable", + "--address", s.Address(), + "--schedule-id", schedID, + "--fast-forward-duration", "5h", + "--fast-forward-id", "OriginalFastForwardId", + ) + require.NoError(t, res.Err) + } + switch change { + case "disabled": + res = s.Execute( + "schedule", "time-skipping", "disable", + "--address", s.Address(), + "--schedule-id", schedID, + ) + require.NoError(t, res.Err) + case "replaced": + res = s.Execute( + "schedule", "time-skipping", "enable", + "--address", s.Address(), + "--schedule-id", schedID, + "--fast-forward-duration", "5h", + "--fast-forward-id", "ReplacementFastForwardId", + ) + require.NoError(t, res.Err) + } + res = s.Execute( + "schedule", "time-skipping", "poll", + "--address", s.Address(), + "--schedule-id", schedID, + "--fast-forward-id", "OriginalFastForwardId", + ) + require.ErrorContains(t, res.Err, "fast-forward failed:") + require.Regexp(t, `^fast-forward failed: \S`, res.Err.Error()) + require.Empty(t, res.Stdout.String()) + }) + } +} + +func (s *SharedServerSuite) TestSchedule_TimeSkippingPollCanceled() { + s.useTimeSkippingServer() + schedID, _, res := s.createSchedule("--interval", "10d", "--paused") + s.NoError(res.Err) + res = s.Execute( + "schedule", "time-skipping", "enable", + "--address", s.Address(), + "--schedule-id", schedID, + "--fast-forward-duration", "5h", + "--fast-forward-id", "YourFastForwardId", + ) + s.NoError(res.Err) + + ctx, cancel := context.WithCancel(s.Context) + cancel() + res = s.ExecuteWithContext(ctx, + "schedule", "time-skipping", "poll", + "--address", s.Address(), + "--schedule-id", schedID, + "--fast-forward-id", "YourFastForwardId", + ) + s.ErrorContains(res.Err, "canceled") + s.Empty(res.Stdout.String()) +} + func (s *SharedServerSuite) TestSchedule_Delete() { schedId, _, res := s.createSchedule("--interval", "10d") s.NoError(res.Err) @@ -511,6 +775,69 @@ func (s *SharedServerSuite) TestSchedule_Update() { }, 10*time.Second, 100*time.Millisecond) } +func (s *SharedServerSuite) TestSchedule_TimeSkippingDisable() { + s.useTimeSkippingServer() + schedID, _, res := s.createSchedule("--interval", "10d", "--paused") + s.NoError(res.Err) + + res = s.Execute( + "schedule", "time-skipping", "enable", + "--address", s.Address(), + "--schedule-id", schedID, + "--fast-forward-duration", "6h", + ) + s.NoError(res.Err) + s.Contains(res.Stdout.String(), "Time skipping: enabled") + s.Contains(res.Stdout.String(), "Fast-forward ID:") + + res = s.Execute( + "schedule", "describe", + "--address", s.Address(), + "--schedule-id", schedID, + ) + s.NoError(res.Err) + s.Contains(res.Stdout.String(), "TimeSkippingInfo") + s.Contains(res.Stdout.String(), `"EffectiveEnabled":true`) + s.Contains(res.Stdout.String(), `"FastForwardInfo":`) + + res = s.Execute( + "schedule", "time-skipping", "disable", + "--address", s.Address(), + "--schedule-id", schedID, + ) + s.NoError(res.Err) + s.Contains(res.Stdout.String(), "Time skipping: disabled") + + res = s.Execute( + "schedule", "describe", + "--address", s.Address(), + "--schedule-id", schedID, + "--output", "json", + ) + s.NoError(res.Err) + var description struct { + Schedule struct { + Action struct { + StartWorkflow struct { + WorkflowType struct { + Name string `json:"name"` + } `json:"workflowType"` + } `json:"startWorkflow"` + } `json:"action"` + } `json:"schedule"` + Info struct { + TimeSkippingInfo struct { + EffectiveConfig struct { + Enabled bool `json:"enabled"` + } `json:"effectiveConfig"` + } `json:"timeSkippingInfo"` + } `json:"info"` + } + s.NoError(json.Unmarshal(res.Stdout.Bytes(), &description)) + s.Equal("DevWorkflow", description.Schedule.Action.StartWorkflow.WorkflowType.Name) + s.False(description.Info.TimeSkippingInfo.EffectiveConfig.Enabled) +} + func (s *SharedServerSuite) TestSchedule_Memo_Update() { schedId, schedWfId, res := s.createSchedule("--memo", "bar=1") s.NoError(res.Err) @@ -606,3 +933,112 @@ func (s *SharedServerSuite) TestSchedule_ListMatchingTimes_NotFound() { ) s.Error(res.Err) } + +func (s *SharedServerSuite) TestSchedule_TimeSkippingPropagatesWithSkipOverlap() { + s.useTimeSkippingServer() + + // The first action is at the next future UTC hour; the fast-forward target + // falls between its third and fourth actions. + firstAction := time.Now().UTC().Truncate(time.Hour).Add(2 * time.Hour) + scheduleID, _, res := s.createSchedule( + "--interval", "1h", + "--start-time", firstAction.Add(-time.Second).Format(time.RFC3339Nano), + "--overlap-policy", "Skip", + ) + s.NoError(res.Err) + + duration := time.Until(firstAction.Add(2*time.Hour + time.Minute)) + res = s.Execute( + "schedule", "time-skipping", "enable", + "--address", s.Address(), + "--schedule-id", scheduleID, + "--fast-forward-duration", duration.String(), + "--fast-forward-id", "ThreeActionsWithPropagation", + "--disable-propagation=false", + ) + s.NoError(res.Err) + + res = s.Execute( + "schedule", "time-skipping", "poll", + "--address", s.Address(), + "--schedule-id", scheduleID, + "--fast-forward-id", "ThreeActionsWithPropagation", + ) + s.NoError(res.Err) + s.Contains(res.Stdout.String(), "completed") + + var description *client.ScheduleDescription + s.EventuallyWithT(func(t *assert.CollectT) { + var err error + description, err = s.Client.ScheduleClient().GetHandle(s.Context, scheduleID).Describe(s.Context) + assert.NoError(t, err) + if err != nil { + return + } + assert.Equal(t, 3, description.Info.NumActions) + assert.Len(t, description.Info.RecentActions, 3) + assert.Equal(t, 0, description.Info.NumActionsSkippedOverlap) + }, 10*time.Second, 100*time.Millisecond) + s.NotNil(description.Schedule.Policy) + s.Equal(enums.SCHEDULE_OVERLAP_POLICY_SKIP, description.Schedule.Policy.Overlap) + s.NotNil(description.Info.TimeSkippingInfo) + s.NotNil(description.Info.TimeSkippingInfo.EffectiveConfig) + s.False(description.Info.TimeSkippingInfo.EffectiveConfig.DisablePropagation) + + workflowIDs := make(map[string]struct{}, 3) + for i, action := range description.Info.RecentActions { + scheduledTime := firstAction.Add(time.Duration(i) * time.Hour) + s.WithinDuration(scheduledTime, action.ScheduleTime, time.Second) + s.NotNil(action.StartWorkflowResult) + workflowID := action.StartWorkflowResult.WorkflowID + _, seen := workflowIDs[workflowID] + s.False(seen, "schedule action reused Workflow ID %q", workflowID) + workflowIDs[workflowID] = struct{}{} + runID := action.StartWorkflowResult.FirstExecutionRunID + workflowDescription, err := s.Client.DescribeWorkflowExecution(s.Context, workflowID, runID) + s.NoError(err) + s.NotNil(workflowDescription.GetWorkflowExecutionInfo().GetStartTime()) + s.WithinDuration(scheduledTime, workflowDescription.GetWorkflowExecutionInfo().GetStartTime().AsTime(), 5*time.Second) + s.NotNil(workflowDescription.GetWorkflowExtendedInfo().GetTimeSkippingInfo()) + s.True(workflowDescription.GetWorkflowExtendedInfo().GetTimeSkippingInfo().GetEffectiveConfig().GetEnabled()) + } +} + +func (s *SharedServerSuite) TestSchedule_TimeSkippingUpdateJSON() { + s.useTimeSkippingServer() + for _, output := range []string{"json", "jsonl"} { + s.T().Run(output, func(t *testing.T) { + schedID, _, res := s.createSchedule("--interval", "10d", "--paused") + require.NoError(t, res.Err) + res = s.Execute("schedule", "time-skipping", "enable", "--address", s.Address(), + "--schedule-id", schedID, "--fast-forward-duration", "5h", "--output", output) + require.NoError(t, res.Err) + var result struct { + Enabled bool `json:"enabled"` + FastForwardID string `json:"fastForwardId"` + } + require.NoError(t, json.Unmarshal(res.Stdout.Bytes(), &result)) + require.True(t, result.Enabled) + _, err := uuid.Parse(result.FastForwardID) + require.NoError(t, err) + if output == "jsonl" { + require.Len(t, strings.Split(strings.TrimSpace(res.Stdout.String()), "\n"), 1) + } + res = s.Execute("schedule", "describe", "--address", s.Address(), "--schedule-id", schedID, "--output", "json") + require.NoError(t, res.Err) + var description workflowservice.DescribeScheduleResponse + require.NoError(t, protojson.Unmarshal(res.Stdout.Bytes(), &description)) + require.Equal(t, result.FastForwardID, description.GetInfo().GetTimeSkippingInfo().GetFastForwardInfo().GetFastForwardId()) + + res = s.Execute("schedule", "time-skipping", "disable", "--address", s.Address(), + "--schedule-id", schedID, "--output", output) + require.NoError(t, res.Err) + require.JSONEq(t, `{"enabled":false}`, res.Stdout.String()) + + res = s.Execute("schedule", "time-skipping", "enable", "--address", s.Address(), + "--schedule-id", schedID+"-missing", "--fast-forward-duration", "5h", "--output", output) + require.Error(t, res.Err) + require.Empty(t, res.Stdout.String()) + }) + } +} diff --git a/internal/temporalcli/commands.server.go b/internal/temporalcli/commands.server.go index ad335d6cf..2fc5a98f1 100644 --- a/internal/temporalcli/commands.server.go +++ b/internal/temporalcli/commands.server.go @@ -49,6 +49,7 @@ func (t *TemporalServerStartDevCommand) run(cctx *CommandContext, args []string) MasterClusterName: "active", CurrentClusterName: "active", InitialFailoverVersion: 1, + EnableTimeSkipping: t.EnableTimeSkipping, } // Set the log level value of the server to the overall log level given to the // CLI. But if it is "never" we have to do a special value, and if it was diff --git a/internal/temporalcli/commands.time_skipping_test.go b/internal/temporalcli/commands.time_skipping_test.go new file mode 100644 index 000000000..ed9e7b68c --- /dev/null +++ b/internal/temporalcli/commands.time_skipping_test.go @@ -0,0 +1,196 @@ +package temporalcli_test + +import ( + "bytes" + "context" + "os" + "os/exec" + "slices" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/stretchr/testify/require" + "github.com/temporalio/cli/internal/temporalcli" + "go.temporal.io/sdk/client" + "go.temporal.io/sdk/workflow" +) + +// Validate user input through the public CLI without contacting a server. +func TestTimeSkippingInvalidFlags(t *testing.T) { + execute := func(t *testing.T, args ...string) *CommandResult { + t.Helper() + res := &CommandResult{} + options := temporalcli.CommandOptions{ + IOStreams: temporalcli.IOStreams{Stdout: &res.Stdout, Stderr: &res.Stderr}, + Fail: func(err error) { res.Err = err }, + } + options.DeprecatedEnvConfig.DisableEnvConfig = true + options.DeprecatedEnvConfig.EnvConfigName = "default" + cctx, cancel, err := temporalcli.NewCommandContext(context.Background(), options) + require.NoError(t, err) + defer cancel() + cmd := temporalcli.NewTemporalCommand(cctx) + cmd.Command.SetArgs(args) + cmd.Command.SetOut(&res.Stdout) + cmd.Command.SetErr(&res.Stderr) + if err := cmd.Command.ExecuteContext(cctx); err != nil { + res.Err = err + } + return res + } + for _, noun := range []string{"workflow", "schedule"} { + t.Run(noun, func(t *testing.T) { + idFlag := "--" + noun + "-id" + for _, verb := range []string{"enable", "disable", "poll"} { + t.Run(verb+" missing execution ID", func(t *testing.T) { + args := []string{noun, "time-skipping", verb} + if verb == "enable" { + args = append(args, "--fast-forward-duration", "5h") + } + if verb == "poll" { + args = append(args, "--fast-forward-id", "YourFastForwardId") + } + res := execute(t, args...) + require.EqualError(t, res.Err, `required flag(s) "`+noun+`-id" not set`) + }) + } + type invalidFlagsCase struct { + name, verb string + flags []string + want string + } + cases := []invalidFlagsCase{ + {"missing poll ID", "poll", nil, `required flag(s) "fast-forward-id" not set`}, + {"zero duration", "enable", []string{"--fast-forward-duration", "0s"}, "--fast-forward-duration must be greater than zero"}, + {"negative duration", "enable", []string{"--fast-forward-duration", "-1h"}, "--fast-forward-duration must be greater than zero"}, + {"malformed duration", "enable", []string{"--fast-forward-duration", "invalid"}, "invalid argument"}, + {"zero skip limit", "enable", []string{"--fast-forward-duration", "5h", "--max-skip-per-session", "0"}, "--max-skip-per-session must be greater than zero"}, + {"negative skip limit", "enable", []string{"--fast-forward-duration", "5h", "--max-skip-per-session", "-1"}, "--max-skip-per-session must be greater than zero"}, + {"skip limit too large", "enable", []string{"--fast-forward-duration", "5h", "--max-skip-per-session", "10001"}, "--max-skip-per-session must be between 1 and 10000"}, + {"malformed skip limit", "enable", []string{"--fast-forward-duration", "5h", "--max-skip-per-session", "abc"}, "invalid argument"}, + {"malformed propagation", "enable", []string{"--fast-forward-duration", "5h", "--disable-propagation=abc"}, "invalid argument"}, + {"unsupported disable setting", "disable", []string{"--disable-propagation"}, "unknown flag: --disable-propagation"}, + } + if noun == "workflow" { + cases = append(cases, invalidFlagsCase{ + "poll with run ID", "poll", []string{"--fast-forward-id", "YourFastForwardId", "--run-id", "YourRunId"}, "unknown flag: --run-id"}) + cases = append(cases, invalidFlagsCase{ + "ID without duration", "enable", []string{"--fast-forward-id", "YourFastForwardId"}, "--fast-forward-id requires --fast-forward-duration"}) + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + args := append([]string{noun, "time-skipping", tc.verb, idFlag, "YourExecutionId"}, tc.flags...) + res := execute(t, args...) + require.ErrorContains(t, res.Err, tc.want) + require.NotContains(t, res.Stdout.String(), "Time skipping: enabled") + }) + } + }) + } +} + +// Run the CLI in a child process so its default Fail handler can call os.Exit. +// The regular command harness replaces that handler and only captures an error. +func TestTimeSkippingCLIProcess(t *testing.T) { + if os.Getenv("TEMPORAL_CLI_TIME_SKIPPING_TEST_PROCESS") != "1" { + return + } + separator := slices.Index(os.Args, "--") + if separator < 0 { + t.Fatal("missing CLI arguments") + } + options := temporalcli.CommandOptions{Args: os.Args[separator+1:]} + options.DeprecatedEnvConfig.DisableEnvConfig = true + options.DeprecatedEnvConfig.EnvConfigName = "default" + temporalcli.Execute(context.Background(), options) + os.Exit(0) +} + +func (s *SharedServerSuite) TestTimeSkipping_PollExitStatus() { + s.useTimeSkippingServer() + s.Worker().OnDevWorkflow(func(ctx workflow.Context, input any) (any, error) { + return nil, workflow.Sleep(ctx, 10*time.Hour) + }) + for _, noun := range []string{"workflow", "schedule"} { + for _, outcome := range []string{"completed", "failed", "timeout"} { + s.T().Run(noun+" "+outcome, func(t *testing.T) { + var id string + if noun == "workflow" { + taskQueue := s.Worker().Options.TaskQueue + if outcome != "completed" { + // Keep fast-forward pending without an active worker. + taskQueue = uuid.NewString() + } + run, err := s.Client.ExecuteWorkflow(s.Context, + client.StartWorkflowOptions{TaskQueue: taskQueue}, DevWorkflow, nil) + require.NoError(t, err) + id = run.GetID() + defer func() { _ = s.Client.CancelWorkflow(s.Context, id, "") }() + } else { + args := []string{"--interval", "10d"} + if outcome != "completed" { + args = append(args, "--paused") + } + var res *CommandResult + id, _, res = s.createSchedule(args...) + require.NoError(t, res.Err) + } + idFlag := "--" + noun + "-id" + res := s.Execute(noun, "time-skipping", "enable", "--address", s.Address(), + idFlag, id, "--fast-forward-duration", "5h", "--fast-forward-id", "ExitStatusTest") + require.NoError(t, res.Err) + if outcome == "failed" { + res = s.Execute(noun, "time-skipping", "disable", "--address", s.Address(), idFlag, id) + require.NoError(t, res.Err) + } + timeout := "15s" + if outcome == "timeout" { + timeout = "200ms" + } + for _, format := range []string{"text", "json", "jsonl"} { + ctx, cancel := context.WithTimeout(s.Context, 20*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestTimeSkippingCLIProcess$", "--", + noun, "time-skipping", "poll", "--address", s.Address(), "--namespace", s.Namespace(), + idFlag, id, "--fast-forward-id", "ExitStatusTest", "--command-timeout", timeout) + if format != "text" { + cmd.Args = append(cmd.Args, "--output", format) + } + cmd.Env = append(os.Environ(), "TEMPORAL_CLI_TIME_SKIPPING_TEST_PROCESS=1") + var stdout, stderr bytes.Buffer + cmd.Stdout, cmd.Stderr = &stdout, &stderr + started := time.Now() + err := cmd.Run() + if outcome == "completed" { + require.NoError(t, err, "stderr: %s", stderr.String()) + if format == "text" { + require.Equal(t, "completed", strings.TrimSpace(stdout.String())) + } else { + require.JSONEq(t, `{"completed":true}`, stdout.String()) + if format == "jsonl" { + require.Len(t, strings.Split(strings.TrimSpace(stdout.String()), "\n"), 1) + } + } + require.Empty(t, stderr.String()) + continue + } + var exitErr *exec.ExitError + require.ErrorAs(t, err, &exitErr) + require.Equal(t, 1, exitErr.ExitCode(), "stderr: %s", stderr.String()) + require.Empty(t, stdout.String()) + if outcome == "failed" { + require.Regexp(t, `Error: fast-forward failed: \S`, stderr.String()) + } else { + // RPC cancellation may arrive before the global deadline handler. + require.Regexp(t, `^Error: \S`, stderr.String()) + require.NotContains(t, stderr.String(), "fast-forward failed:") + require.GreaterOrEqual(t, time.Since(started), 100*time.Millisecond) + require.Less(t, time.Since(started), 5*time.Second) + } + } + }) + } + } +} diff --git a/internal/temporalcli/commands.workflow_test.go b/internal/temporalcli/commands.workflow_test.go index d1d728853..2f16ade14 100644 --- a/internal/temporalcli/commands.workflow_test.go +++ b/internal/temporalcli/commands.workflow_test.go @@ -9,6 +9,7 @@ import ( "strconv" "strings" "sync" + "testing" "time" "github.com/google/uuid" @@ -22,6 +23,7 @@ import ( "go.temporal.io/sdk/worker" "go.temporal.io/sdk/workflow" "google.golang.org/grpc" + "google.golang.org/protobuf/encoding/protojson" ) func (s *SharedServerSuite) TestWorkflow_Signal_SingleWorkflowSuccess() { @@ -57,6 +59,71 @@ func (s *SharedServerSuite) TestWorkflow_Signal_SingleWorkflowSuccess() { s.Equal(map[string]any{"foo": "bar"}, actual) } +func (s *SharedServerSuite) TestWorkflow_TimeSkippingEnablePollDisable() { + s.useTimeSkippingServer() + s.Worker().OnDevWorkflow(func(ctx workflow.Context, a any) (any, error) { + if err := workflow.Sleep(ctx, 10*time.Hour); err != nil { + return nil, err + } + return nil, nil + }) + run, err := s.Client.ExecuteWorkflow( + s.Context, + client.StartWorkflowOptions{TaskQueue: s.Worker().Options.TaskQueue}, + DevWorkflow, + "ignored", + ) + s.NoError(err) + + res := s.Execute( + "workflow", "time-skipping", "enable", + "--address", s.Address(), + "--workflow-id", run.GetID(), + "--run-id", run.GetRunID(), + "--fast-forward-duration", "5h", + "--fast-forward-id", "WorkflowPollId", + "--disable-propagation", + "--max-skip-per-session", "17", + ) + s.NoError(res.Err) + s.Contains(res.Stdout.String(), "Fast-forward ID: WorkflowPollId") + s.NotContains(res.Stdout.String(), "Check status") + s.NotContains(res.Stdout.String(), "temporal workflow describe") + s.NotContains(res.Stdout.String(), "Poll fast-forward:") + s.NotContains(res.Stdout.String(), "temporal workflow ") + + res = s.Execute( + "workflow", "time-skipping", "poll", + "--address", s.Address(), + "--workflow-id", run.GetID(), + "--fast-forward-id", "WorkflowPollId", + ) + s.NoError(res.Err) + s.Contains(res.Stdout.String(), "completed") + + res = s.Execute( + "workflow", "describe", + "--address", s.Address(), + "--workflow-id", run.GetID(), + ) + s.NoError(res.Err) + s.Contains(res.Stdout.String(), "Time Skipping:") + s.ContainsOnSameLine(res.Stdout.String(), "DisablePropagation", "true") + + res = s.Execute( + "workflow", "time-skipping", "disable", + "--address", s.Address(), + "--workflow-id", run.GetID(), + "--run-id", run.GetRunID(), + ) + s.NoError(res.Err) + s.Contains(res.Stdout.String(), "Time skipping: disabled") + s.NotContains(res.Stdout.String(), "Check status") + s.NotContains(res.Stdout.String(), "temporal workflow describe") + s.NotContains(res.Stdout.String(), "Poll fast-forward:") + s.NoError(s.Client.CancelWorkflow(s.Context, run.GetID(), run.GetRunID())) +} + func (s *SharedServerSuite) TestWorkflow_Signal_MultipleInputsWithComplexMetadata() { // Start a random workflow run, err := s.Client.ExecuteWorkflow( @@ -1627,3 +1694,217 @@ func (s *SharedServerSuite) testWorkflowMetadata(json bool) { s.Error(res.Err) s.Contains(res.Err.Error(), "query was rejected, workflow has status: Completed") } + +func (s *SharedServerSuite) TestWorkflow_TimeSkippingMinimalLifecycle() { + s.useTimeSkippingServer() + s.Worker().OnDevWorkflow(func(ctx workflow.Context, input any) (any, error) { + return nil, workflow.Sleep(ctx, 10*time.Hour) + }) + run, err := s.Client.ExecuteWorkflow(s.Context, + client.StartWorkflowOptions{TaskQueue: s.Worker().Options.TaskQueue}, DevWorkflow, nil) + s.NoError(err) + defer func() { _ = s.Client.CancelWorkflow(s.Context, run.GetID(), "") }() + + res := s.Execute("workflow", "time-skipping", "enable", "--address", s.Address(), + "--workflow-id", run.GetID(), "--fast-forward-duration", "5h") + s.NoError(res.Err) + s.Contains(res.Stdout.String(), "Time skipping: enabled") + match := regexp.MustCompile(`(?m)^Fast-forward ID: (\S+)$`).FindStringSubmatch(res.Stdout.String()) + s.Len(match, 2) + fastForwardID := match[1] + _, err = uuid.Parse(fastForwardID) + s.NoError(err) + s.NotContains(res.Stdout.String(), "Poll fast-forward:") + s.NotContains(res.Stdout.String(), "temporal workflow ") + + res = s.Execute("workflow", "time-skipping", "poll", "--address", s.Address(), + "--workflow-id", run.GetID(), "--fast-forward-id", fastForwardID) + s.NoError(res.Err) + s.Equal("completed", strings.TrimSpace(res.Stdout.String())) + + res = s.Execute("workflow", "describe", "--address", s.Address(), "--workflow-id", run.GetID()) + s.NoError(res.Err) + s.Contains(res.Stdout.String(), "Time Skipping:") + s.Contains(res.Stdout.String(), fastForwardID) + s.ContainsOnSameLine(res.Stdout.String(), "DisablePropagation", "false") + s.ContainsOnSameLine(res.Stdout.String(), "HasCompleted", "true") + + for _, output := range []string{"json", "jsonl"} { + res = s.Execute("workflow", "describe", "--address", s.Address(), "--workflow-id", run.GetID(), "--output", output) + s.NoError(res.Err) + var description workflowservice.DescribeWorkflowExecutionResponse + s.NoError(protojson.Unmarshal(res.Stdout.Bytes(), &description)) + s.Equal(run.GetID(), description.GetWorkflowExecutionInfo().GetExecution().GetWorkflowId()) + s.Equal("DevWorkflow", description.GetWorkflowExecutionInfo().GetType().GetName()) + info := description.GetWorkflowExtendedInfo().GetTimeSkippingInfo() + s.NotNil(info) + s.Equal(fastForwardID, info.GetFastForwardInfo().GetFastForwardId()) + s.True(info.GetFastForwardInfo().GetHasCompleted()) + s.False(info.GetEffectiveConfig().GetDisablePropagation()) + if output == "jsonl" { + s.Len(strings.Split(strings.TrimSpace(res.Stdout.String()), "\n"), 1) + } + } + + res = s.Execute("workflow", "time-skipping", "disable", "--address", s.Address(), "--workflow-id", run.GetID()) + s.NoError(res.Err) + s.Contains(res.Stdout.String(), "Time skipping: disabled") + res = s.Execute("workflow", "describe", "--address", s.Address(), "--workflow-id", run.GetID()) + s.NoError(res.Err) + s.ContainsOnSameLine(res.Stdout.String(), "EffectiveEnabled", "false") +} + +func (s *SharedServerSuite) TestWorkflow_TimeSkippingEnableWithoutFastForward() { + s.useTimeSkippingServer() + s.Worker().OnDevWorkflow(func(ctx workflow.Context, input any) (any, error) { + workflow.GetSignalChannel(ctx, "finish").Receive(ctx, nil) + return nil, nil + }) + run, err := s.Client.ExecuteWorkflow(s.Context, + client.StartWorkflowOptions{TaskQueue: s.Worker().Options.TaskQueue}, DevWorkflow, nil) + s.NoError(err) + defer func() { _ = s.Client.CancelWorkflow(s.Context, run.GetID(), "") }() + + res := s.Execute("workflow", "time-skipping", "enable", "--address", s.Address(), "--workflow-id", run.GetID()) + s.NoError(res.Err) + s.Contains(res.Stdout.String(), "Time skipping: enabled") + s.NotContains(res.Stdout.String(), "Fast-forward ID:") + s.NotContains(res.Stdout.String(), "Poll fast-forward:") + res = s.Execute("workflow", "describe", "--address", s.Address(), "--workflow-id", run.GetID()) + s.NoError(res.Err) + s.ContainsOnSameLine(res.Stdout.String(), "EffectiveEnabled", "true") + s.ContainsOnSameLine(res.Stdout.String(), "DisablePropagation", "false") + res = s.Execute("workflow", "time-skipping", "disable", "--address", s.Address(), "--workflow-id", run.GetID()) + s.NoError(res.Err) + res = s.Execute("workflow", "describe", "--address", s.Address(), "--workflow-id", run.GetID()) + s.NoError(res.Err) + s.ContainsOnSameLine(res.Stdout.String(), "EffectiveEnabled", "false") +} + +func (s *SharedServerSuite) TestWorkflow_TimeSkippingUpdateJSON() { + s.useTimeSkippingServer() + s.Worker().OnDevWorkflow(func(ctx workflow.Context, input any) (any, error) { + return nil, workflow.Sleep(ctx, 10*time.Hour) + }) + for _, output := range []string{"json", "jsonl"} { + s.T().Run(output, func(t *testing.T) { + run, err := s.Client.ExecuteWorkflow(s.Context, + client.StartWorkflowOptions{TaskQueue: s.Worker().Options.TaskQueue}, DevWorkflow, nil) + require.NoError(t, err) + defer func() { _ = s.Client.CancelWorkflow(s.Context, run.GetID(), "") }() + res := s.Execute("workflow", "time-skipping", "enable", "--address", s.Address(), + "--workflow-id", run.GetID(), "--fast-forward-duration", "5h", "--output", output) + require.NoError(t, res.Err) + var result struct { + Enabled bool `json:"enabled"` + FastForwardID string `json:"fastForwardId"` + } + require.NoError(t, json.Unmarshal(res.Stdout.Bytes(), &result)) + require.True(t, result.Enabled) + _, err = uuid.Parse(result.FastForwardID) + require.NoError(t, err) + if output == "jsonl" { + require.Len(t, strings.Split(strings.TrimSpace(res.Stdout.String()), "\n"), 1) + } + res = s.Execute("workflow", "describe", "--address", s.Address(), "--workflow-id", run.GetID(), "--output", "json") + require.NoError(t, res.Err) + var description workflowservice.DescribeWorkflowExecutionResponse + require.NoError(t, protojson.Unmarshal(res.Stdout.Bytes(), &description)) + require.Equal(t, result.FastForwardID, description.GetWorkflowExtendedInfo().GetTimeSkippingInfo().GetFastForwardInfo().GetFastForwardId()) + + res = s.Execute("workflow", "time-skipping", "disable", "--address", s.Address(), + "--workflow-id", run.GetID(), "--output", output) + require.NoError(t, res.Err) + require.JSONEq(t, `{"enabled":false}`, res.Stdout.String()) + + res = s.Execute("workflow", "time-skipping", "enable", "--address", s.Address(), + "--workflow-id", run.GetID()+"-missing", "--fast-forward-duration", "5h", "--output", output) + require.Error(t, res.Err) + require.Empty(t, res.Stdout.String()) + }) + } +} + +func (s *SharedServerSuite) TestWorkflow_TimeSkippingPollTimeoutAndRetry() { + s.useTimeSkippingServer() + taskQueue := uuid.NewString() + // Leave the Workflow Task unprocessed so fast-forward remains pending. + run, err := s.Client.ExecuteWorkflow(s.Context, + client.StartWorkflowOptions{TaskQueue: taskQueue}, "TimeSkippingPollWorkflow") + s.NoError(err) + defer func() { _ = s.Client.CancelWorkflow(s.Context, run.GetID(), "") }() + + res := s.Execute("workflow", "time-skipping", "enable", "--address", s.Address(), + "--workflow-id", run.GetID(), "--fast-forward-duration", "5h", "--fast-forward-id", "YourFastForwardId") + s.NoError(res.Err) + args := []string{"workflow", "time-skipping", "poll", "--address", s.Address(), + "--workflow-id", run.GetID(), "--fast-forward-id", "YourFastForwardId"} + + for _, tc := range []struct { + timeout string + minimum time.Duration + }{ + {timeout: "200ms", minimum: 100 * time.Millisecond}, + {timeout: "500ms", minimum: 400 * time.Millisecond}, + } { + s.T().Run("command timeout "+tc.timeout, func(t *testing.T) { + ctx, cancel := context.WithTimeout(s.Context, 10*time.Second) + defer cancel() + started := time.Now() + res := s.ExecuteWithContext(ctx, append(args, "--command-timeout", tc.timeout)...) + // Expiration can surface as either a context or an RPC error. + require.Error(t, res.Err) + require.Empty(t, res.Stdout.String()) + require.GreaterOrEqual(t, time.Since(started), tc.minimum) + require.Less(t, time.Since(started), 5*time.Second) + }) + } + + canceled, stop := context.WithCancel(s.Context) + stop() + res = s.ExecuteWithContext(canceled, args...) + s.ErrorContains(res.Err, "canceled") + s.Empty(res.Stdout.String()) + + // Caller timeouts did not stop the original fast-forward. Let it progress. + w := worker.New(s.Client, taskQueue, worker.Options{}) + w.RegisterWorkflowWithOptions(func(ctx workflow.Context) error { + return workflow.Sleep(ctx, 10*time.Hour) + }, workflow.RegisterOptions{Name: "TimeSkippingPollWorkflow"}) + s.NoError(w.Start()) + defer w.Stop() + ctx, cancel := context.WithTimeout(s.Context, 10*time.Second) + defer cancel() + res = s.ExecuteWithContext(ctx, args...) + s.NoError(res.Err) + s.Equal("completed", strings.TrimSpace(res.Stdout.String())) +} + +func (s *SharedServerSuite) TestWorkflow_TimeSkippingPollFailed() { + s.useTimeSkippingServer() + for _, change := range []string{"disabled", "replaced"} { + s.T().Run(change, func(t *testing.T) { + // Without a worker, the original fast-forward remains pending. + run, err := s.Client.ExecuteWorkflow(s.Context, + client.StartWorkflowOptions{TaskQueue: uuid.NewString()}, "TimeSkippingPollWorkflow") + require.NoError(t, err) + defer func() { _ = s.Client.CancelWorkflow(s.Context, run.GetID(), "") }() + res := s.Execute("workflow", "time-skipping", "enable", "--address", s.Address(), + "--workflow-id", run.GetID(), "--fast-forward-duration", "5h", "--fast-forward-id", "OriginalFastForwardId") + require.NoError(t, res.Err) + if change == "disabled" { + res = s.Execute("workflow", "time-skipping", "disable", "--address", s.Address(), + "--workflow-id", run.GetID()) + } else { + res = s.Execute("workflow", "time-skipping", "enable", "--address", s.Address(), + "--workflow-id", run.GetID(), "--fast-forward-duration", "5h", "--fast-forward-id", "ReplacementFastForwardId") + } + require.NoError(t, res.Err) + res = s.Execute("workflow", "time-skipping", "poll", "--address", s.Address(), + "--workflow-id", run.GetID(), "--fast-forward-id", "OriginalFastForwardId", "--command-timeout", "5s") + require.ErrorContains(t, res.Err, "fast-forward failed:") + require.Regexp(t, `^fast-forward failed: \S`, res.Err.Error()) + require.Empty(t, res.Stdout.String()) + }) + } +} diff --git a/internal/temporalcli/commands.workflow_time_skipping.go b/internal/temporalcli/commands.workflow_time_skipping.go new file mode 100644 index 000000000..689126d7d --- /dev/null +++ b/internal/temporalcli/commands.workflow_time_skipping.go @@ -0,0 +1,77 @@ +package temporalcli + +import ( + "errors" + "fmt" + + "go.temporal.io/sdk/client" + "go.temporal.io/sdk/timeskipping" +) + +func (c *TemporalWorkflowTimeSkippingEnableCommand) run(cctx *CommandContext, args []string) error { + if c.Command.Flags().Changed("max-skip-per-session") && c.MaxSkipPerSession <= 0 { + return errors.New("--max-skip-per-session must be greater than zero") + } + config, err := timeSkippingConfig(c.FastForwardDuration.Duration(), c.Command.Flags().Changed("fast-forward-duration"), c.FastForwardId, c.DisablePropagation, c.MaxSkipPerSession) + if err != nil { + return err + } + return updateWorkflowOptionsForTimeSkipping(cctx, c.Parent.Parent, c.WorkflowId, c.RunId, config) +} + +func (c *TemporalWorkflowTimeSkippingDisableCommand) run(cctx *CommandContext, args []string) error { + return updateWorkflowOptionsForTimeSkipping(cctx, c.Parent.Parent, c.WorkflowId, c.RunId, &client.TimeSkippingConfig{Enabled: false}) +} + +func updateWorkflowOptionsForTimeSkipping(cctx *CommandContext, parent *TemporalWorkflowCommand, workflowID, runID string, config *client.TimeSkippingConfig) error { + if config == nil { + return errors.New("time-skipping configuration is required") + } + cl, err := dialClient(cctx, &parent.ClientOptions) + if err != nil { + return err + } + defer cl.Close() + _, err = cl.UpdateWorkflowExecutionOptions(cctx, client.UpdateWorkflowExecutionOptionsRequest{ + WorkflowId: workflowID, + RunId: runID, + WorkflowExecutionOptionsChanges: client.WorkflowExecutionOptionsChanges{ + TimeSkippingConfig: &client.TimeSkippingConfigChange{Value: config}, + }, + }) + if err != nil { + return err + } + if cctx.JSONOutput { + return printTimeSkippingUpdateJSON(cctx, config) + } + cctx.Printer.Printlnf("Workflow time skipping updated: %s", workflowID) + if config.Enabled { + cctx.Printer.Println("Time skipping: enabled") + } else { + cctx.Printer.Println("Time skipping: disabled") + } + if ff := config.FastForwardConfig; ff != nil { + cctx.Printer.Printlnf("Fast-forward ID: %s", ff.ID) + } + return nil +} + +func (c *TemporalWorkflowTimeSkippingPollCommand) run(cctx *CommandContext, args []string) error { + cl, err := dialClient(cctx, &c.Parent.Parent.ClientOptions) + if err != nil { + return err + } + defer cl.Close() + // The SDK retries server poll timeouts until the command context ends. + res, err := timeskipping.PollWorkflowFastForward(cctx, cl, cl.GetWorkflow(cctx, c.WorkflowId, ""), timeskipping.PollWorkflowFastForwardOptions{ + FastForwardID: c.FastForwardId, + }) + if err != nil { + return err + } + if !res.Completed { + return fmt.Errorf("fast-forward failed: %s", res.FailedReason) + } + return printTimeSkippingPollCompleted(cctx) +} diff --git a/internal/temporalcli/commands.workflow_view.go b/internal/temporalcli/commands.workflow_view.go index fdd3747d9..0695a2882 100644 --- a/internal/temporalcli/commands.workflow_view.go +++ b/internal/temporalcli/commands.workflow_view.go @@ -141,6 +141,11 @@ func (c *TemporalWorkflowDescribeCommand) run(cctx *CommandContext, args []strin RootWorkflowId: info.GetRootExecution().GetWorkflowId(), RootRunId: info.GetRootExecution().GetRunId(), }, printer.StructuredOptions{}) + if tsi := resp.GetWorkflowExtendedInfo().GetTimeSkippingInfo(); tsi != nil { + cctx.Printer.Println() + cctx.Printer.Println(color.MagentaString("Time Skipping:")) + _ = cctx.Printer.PrintStructured(timeSkippingToPrintable(tsi), printer.StructuredOptions{}) + } if priority := info.GetPriority(); priority != nil && (priority.GetPriorityKey() != 0 || priority.GetFairnessKey() != "" || priority.GetFairnessWeight() != 0) { diff --git a/internal/temporalcli/commands.yaml b/internal/temporalcli/commands.yaml index c177f4ee7..db3ad0e75 100644 --- a/internal/temporalcli/commands.yaml +++ b/internal/temporalcli/commands.yaml @@ -3740,6 +3740,85 @@ commands: - schedule-id - overlap-policy + - name: temporal schedule time-skipping + summary: Manage Schedule time skipping (Experimental) + description: | + Manage Schedule time skipping, where a schedule's virtual clock fast-forwards when idle. + Use time skipping in testing environments to efficiently evaluate the behavior of a schedule. + + Note: This is an experimental feature and may change in the future. + + - name: temporal schedule time-skipping enable + summary: Enable Schedule time skipping (Experimental) + description: | + Enable time skipping for a Schedule: + + ``` + temporal schedule time-skipping enable \ + --namespace YourNamespace \ + --schedule-id YourScheduleId \ + --fast-forward-duration 5h + ``` + + Once enabled, the Schedule advances its virtual clock during inactivity, + allowing scheduled Workflows to start without waiting for wall-clock time. + option-sets: + - schedule-id + - max-skip-per-session + options: + - name: fast-forward-duration + type: duration + required: true + description: Fast-forward the Schedule's virtual time by this duration. Must be greater than zero. + - name: fast-forward-id + type: string + description: Identify this fast-forward in Schedule status. Generated if omitted. Not an idempotency key. + - name: disable-propagation + type: bool + description: | + Defaults to false. Omit this flag or set it to false to propagate the + time-skipping enabled state to Workflows started by this Schedule. + Set it to true, or specify it without a value, to disable propagation. + Fast-forward targets are never propagated. Virtual time is propagated + regardless of this flag. + + - name: temporal schedule time-skipping disable + summary: Disable Schedule time skipping (Experimental) + description: | + Disable time skipping for a Schedule: + + ``` + temporal schedule time-skipping disable \ + --namespace YourNamespace \ + --schedule-id YourScheduleId + ``` + + No other time-skipping flags are needed. + option-sets: + - schedule-id + + - name: temporal schedule time-skipping poll + summary: Poll a Schedule fast-forward (Experimental) + description: | + Poll Schedule time-skipping status for a specific fast-forward setting: + + ``` + temporal schedule time-skipping poll \ + --namespace YourNamespace \ + --schedule-id YourScheduleId \ + --fast-forward-id YourFastForwardId + ``` + + Use the global `--command-timeout` flag to limit how long the poll waits. + A failed fast-forward or poll timeout returns a nonzero exit status. + option-sets: + - schedule-id + options: + - name: fast-forward-id + type: string + required: true + description: ID of the fast-forward to poll. + - name: temporal schedule update summary: Update Schedule details description: | @@ -3908,6 +3987,12 @@ commands: - name: headless type: bool description: Disable the Web UI. + - name: enable-time-skipping + type: bool + description: | + Enable Workflow and CHASM Schedule time skipping in all Namespaces for + this dev server run. Also enable CHASM Schedule creation and routing. + Explicit dynamic config values take precedence. - name: ip type: string description: IP address bound to the front-end Service. @@ -4953,6 +5038,87 @@ commands: type: bool description: Print properties without changing their format. + - name: temporal workflow time-skipping + summary: Manage Workflow time skipping (Experimental) + description: | + Manage Workflow time skipping, where a workflow skips time when idle. + Use time skipping in testing environments to efficiently evaluate + the behavior of a workflow with extended periods of inactivity. + + Note: This is an experimental feature and may change in the future. + + - name: temporal workflow time-skipping enable + summary: Enable Workflow time skipping (Experimental) + description: | + Enable time skipping for a Workflow Execution: + + ``` + temporal workflow time-skipping enable \ + --namespace YourNamespace \ + --workflow-id YourWorkflowId + ``` + Once enabled, the workflow execution skips time during inactivity, + expediting the completion of timers, retry waits, and start delays. + + option-sets: + - workflow-reference + - max-skip-per-session + options: + - name: fast-forward-duration + type: duration + description: Fast-forward the Workflow Execution's virtual time by this duration. Must be greater than zero. + - name: fast-forward-id + type: string + description: Identify this fast-forward in Workflow status and when polling for completion. Generated if omitted. Not an idempotency key. Requires --fast-forward-duration. + - name: disable-propagation + type: bool + description: | + Defaults to false. Omit this flag or set it to false to propagate the + time-skipping enabled state to child Workflows started by this Workflow. + Set it to true, or specify it without a value, to disable propagation. + Fast-forward targets are never propagated. Virtual time is propagated + regardless of this flag. + + - name: temporal workflow time-skipping disable + summary: Disable Workflow time skipping (Experimental) + description: | + Disable time skipping for a Workflow Execution: + + ``` + temporal workflow time-skipping disable \ + --namespace YourNamespace \ + --workflow-id YourWorkflowId + ``` + + No other time-skipping flags are needed. + option-sets: + - workflow-reference + + - name: temporal workflow time-skipping poll + summary: Poll a Workflow fast-forward (Experimental) + description: | + Poll Workflow time-skipping status for a specific fast-forward setting: + + ``` + temporal workflow time-skipping poll \ + --namespace YourNamespace \ + --workflow-id YourWorkflowId \ + --fast-forward-id YourFastForwardId + ``` + + Use the global `--command-timeout` flag to limit how long the poll waits. + A failed fast-forward or poll timeout returns a nonzero exit status. + options: + - name: workflow-id + type: string + short: w + description: Workflow ID. + required: true + - name: fast-forward-id + type: string + required: true + description: ID of the fast-forward to poll. + - name: temporal workflow execute summary: Start new Workflow Execution description: | @@ -5817,6 +5983,24 @@ option-sets: required: true short: s + - name: max-skip-per-session + options: + - name: max-skip-per-session + type: int + description: | + Limit the number of time skips in a single time-skipping session. + A session starts when time skipping is enabled and ends when it is + automatically disabled. Updating the time-skipping configuration + resets the session. Omit to use the server default, which is 200 and + can be configured through the `system.timeSkippingMaxSkipPerSession` + dynamic config. Usually leave this unset unless a previous test + reached the limit and time skipping turned off automatically; then + set a higher value. If specified, must be between 1 and 10000. Use + `temporal schedule describe` or + `temporal workflow describe` to check `MaxSessionSkipCount`, + `CurrentSessionSkipCount`, and `EffectiveEnabled` in the time-skipping + status. + - name: schedule-configuration options: - name: calendar diff --git a/internal/temporalcli/commands_test.go b/internal/temporalcli/commands_test.go index f66885df0..dce5e3e8d 100644 --- a/internal/temporalcli/commands_test.go +++ b/internal/temporalcli/commands_test.go @@ -276,6 +276,19 @@ func (s *SharedServerSuite) TearDownSuite() { s.Stop() } +// Use a separate server so CHASM Schedule creation does not change the behavior +// expected by existing Schedule tests in the shared server suite. +func (s *SharedServerSuite) useTimeSkippingServer() { + sharedServer := s.DevServer + s.DevServer = StartDevServer(s.T(), DevServerOptions{ + StartOptions: devserver.StartOptions{EnableTimeSkipping: true}, + }) + s.T().Cleanup(func() { + s.DevServer.Stop() + s.DevServer = sharedServer + }) +} + func (s *SharedServerSuite) Stop() { s.DevServer.Stop() } diff --git a/internal/temporalcli/timeskipping.go b/internal/temporalcli/timeskipping.go new file mode 100644 index 000000000..7de39fe21 --- /dev/null +++ b/internal/temporalcli/timeskipping.go @@ -0,0 +1,137 @@ +package temporalcli + +import ( + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "github.com/temporalio/cli/internal/printer" + commonpb "go.temporal.io/api/common/v1" + "go.temporal.io/sdk/client" +) + +const maxUserSetSkipPerSession = 10_000 + +func timeSkippingConfig(duration time.Duration, hasDuration bool, fastForwardID string, disablePropagation bool, maxSkips int) (*client.TimeSkippingConfig, error) { + if hasDuration && duration <= 0 { + return nil, errors.New("--fast-forward-duration must be greater than zero") + } + if !hasDuration && fastForwardID != "" { + return nil, errors.New("--fast-forward-id requires --fast-forward-duration") + } + if maxSkips < 0 || maxSkips > maxUserSetSkipPerSession { + return nil, fmt.Errorf("--max-skip-per-session must be between 1 and %d", maxUserSetSkipPerSession) + } + config := &client.TimeSkippingConfig{ + Enabled: true, + DisablePropagation: disablePropagation, + MaxSessionSkipCount: int32(maxSkips), + } + if hasDuration { + if fastForwardID == "" { + fastForwardID = uuid.NewString() + } + config.FastForwardConfig = &client.FastForwardConfig{ID: fastForwardID, Duration: duration} + } + return config, nil +} + +type timeSkippingUpdateResult struct { + Enabled bool `json:"enabled"` + FastForwardID string `json:"fastForwardId,omitempty"` +} + +func printTimeSkippingUpdateJSON(cctx *CommandContext, config *client.TimeSkippingConfig) error { + if config == nil { + return errors.New("time-skipping configuration is required") + } + result := timeSkippingUpdateResult{Enabled: config.Enabled} + if ff := config.FastForwardConfig; ff != nil { + result.FastForwardID = ff.ID + } + return cctx.Printer.PrintStructured(result, printer.StructuredOptions{}) +} + +func printTimeSkippingPollCompleted(cctx *CommandContext) error { + if cctx.JSONOutput { + return cctx.Printer.PrintStructured(struct { + Completed bool `json:"completed"` + }{Completed: true}, printer.StructuredOptions{}) + } + cctx.Printer.Println("completed") + return nil +} + +type printableTimeSkippingInfo struct { + EffectiveEnabled bool + DisablePropagation bool + MaxSessionSkipCount int32 + CurrentSessionSkipCount int32 + CurrentTime time.Time `cli:",cardOmitEmpty"` + FastForwardInfo *printableTimeSkippingFastForwardInfo `cli:",cardOmitEmpty"` +} + +type printableTimeSkippingFastForwardInfo struct { + Id string + Duration string + TargetTime time.Time `cli:",cardOmitEmpty"` + HasCompleted bool +} + +// timeSkippingToPrintable renders the raw proto form, which is what +// DescribeWorkflowExecution still returns. +func timeSkippingToPrintable(info *commonpb.TimeSkippingInfo) *printableTimeSkippingInfo { + if info == nil { + return nil + } + + out := &printableTimeSkippingInfo{ + EffectiveEnabled: info.GetEffectiveConfig().GetEnabled(), + DisablePropagation: info.GetEffectiveConfig().GetDisablePropagation(), + MaxSessionSkipCount: info.GetEffectiveConfig().GetMaxSessionSkipCount(), + CurrentSessionSkipCount: info.GetCurrentSessionSkipCount(), + } + if currentTime := info.GetCurrentTime(); currentTime != nil { + out.CurrentTime = currentTime.AsTime() + } + if ff := info.GetFastForwardInfo(); ff != nil { + out.FastForwardInfo = &printableTimeSkippingFastForwardInfo{ + Id: ff.GetFastForwardId(), + Duration: formatDuration(ff.GetFastForwardDuration().AsDuration()), + HasCompleted: ff.GetHasCompleted(), + } + if targetTime := ff.GetTargetTime(); targetTime != nil { + out.FastForwardInfo.TargetTime = targetTime.AsTime() + } + } + return out +} + +// clientTimeSkippingToPrintable renders the SDK's typed form, which is what +// ScheduleHandle.Describe returns. The SDK has already done the proto decoding, +// so there are no timestamp nil checks to repeat here. +func clientTimeSkippingToPrintable(info *client.TimeSkippingInfo) *printableTimeSkippingInfo { + if info == nil { + return nil + } + + out := &printableTimeSkippingInfo{ + CurrentTime: info.CurrentTime, + CurrentSessionSkipCount: info.CurrentSessionSkipCount, + } + if cfg := info.EffectiveConfig; cfg != nil { + out.EffectiveEnabled = cfg.Enabled + out.DisablePropagation = cfg.DisablePropagation + out.MaxSessionSkipCount = cfg.MaxSessionSkipCount + } + if ff := info.FastForwardInfo; ff != nil { + out.FastForwardInfo = &printableTimeSkippingFastForwardInfo{ + Id: ff.ID, + Duration: formatDuration(ff.Duration), + TargetTime: ff.TargetTime, + HasCompleted: ff.HasCompleted, + } + } + return out +} diff --git a/internal/temporalcli/timeskipping_test.go b/internal/temporalcli/timeskipping_test.go new file mode 100644 index 000000000..186a5c3f1 --- /dev/null +++ b/internal/temporalcli/timeskipping_test.go @@ -0,0 +1,286 @@ +package temporalcli + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/stretchr/testify/require" + "github.com/temporalio/cli/internal/printer" + commonpb "go.temporal.io/api/common/v1" + "go.temporal.io/sdk/client" + "google.golang.org/protobuf/types/known/durationpb" + "google.golang.org/protobuf/types/known/timestamppb" +) + +func TestPatchTimeSkippingNilConfig(t *testing.T) { + for _, tc := range []struct { + name string + patch func() error + }{ + { + name: "schedule", + patch: func() error { + return patchScheduleTimeSkipping(nil, nil, "YourScheduleId", nil) + }, + }, + { + name: "workflow", + patch: func() error { + return updateWorkflowOptionsForTimeSkipping(nil, nil, "YourWorkflowId", "", nil) + }, + }, + } { + t.Run(tc.name, func(t *testing.T) { + require.EqualError(t, tc.patch(), "time-skipping configuration is required") + }) + } +} + +func TestTimeSkippingConfig(t *testing.T) { + for _, tc := range []struct { + name string + duration time.Duration + hasDuration bool + fastForwardID string + disablePropagation bool + maxSkips int + wantErr string + }{ + {name: "no fast-forward uses defaults"}, + {name: "minimum user skip limit", maxSkips: 1}, + {name: "maximum user skip limit", maxSkips: 10_000}, + {name: "fast-forward with explicit ID", duration: 5 * time.Hour, hasDuration: true, fastForwardID: "YourFastForwardId", disablePropagation: true, maxSkips: 17}, + {name: "fast-forward generates ID", duration: time.Hour, hasDuration: true}, + {name: "fast-forward with maximum user skip limit", duration: time.Hour, hasDuration: true, maxSkips: 10_000}, + {name: "zero duration", hasDuration: true, wantErr: "--fast-forward-duration must be greater than zero"}, + {name: "negative duration", duration: -time.Second, hasDuration: true, wantErr: "--fast-forward-duration must be greater than zero"}, + {name: "ID without duration", fastForwardID: "YourFastForwardId", wantErr: "--fast-forward-id requires --fast-forward-duration"}, + {name: "negative skip limit", maxSkips: -1, wantErr: "--max-skip-per-session must be between 1 and 10000"}, + {name: "skip limit too large", maxSkips: 10_001, wantErr: "--max-skip-per-session must be between 1 and 10000"}, + {name: "fast-forward with skip limit too large", duration: time.Hour, hasDuration: true, maxSkips: 10_001, wantErr: "--max-skip-per-session must be between 1 and 10000"}, + } { + t.Run(tc.name, func(t *testing.T) { + config, err := timeSkippingConfig(tc.duration, tc.hasDuration, tc.fastForwardID, tc.disablePropagation, tc.maxSkips) + if tc.wantErr != "" { + require.EqualError(t, err, tc.wantErr) + require.Nil(t, config) + return + } + require.NoError(t, err) + require.True(t, config.Enabled) + require.Equal(t, tc.disablePropagation, config.DisablePropagation) + require.Equal(t, int32(tc.maxSkips), config.MaxSessionSkipCount) + if !tc.hasDuration { + require.Nil(t, config.FastForwardConfig) + return + } + require.NotNil(t, config.FastForwardConfig) + require.Equal(t, tc.duration, config.FastForwardConfig.Duration) + if tc.fastForwardID == "" { + require.NotEmpty(t, config.FastForwardConfig.ID) + } else { + require.Equal(t, tc.fastForwardID, config.FastForwardConfig.ID) + } + }) + } +} + +func TestTimeSkippingToPrintable(t *testing.T) { + targetTime := time.Date(2026, time.September, 27, 12, 0, 0, 0, time.UTC) + config := &commonpb.TimeSkippingConfig{ + Enabled: true, + DisablePropagation: true, + MaxSessionSkipCount: 200, + FastForwardConfig: &commonpb.FastForwardConfig{ + Id: "ff-id", + Duration: durationpb.New(5 * time.Hour), + }, + } + info := &commonpb.TimeSkippingInfo{ + CurrentTime: timestamppb.New(targetTime.Add(-time.Hour)), + EffectiveConfig: config, + CurrentSessionSkipCount: 4, + FastForwardInfo: &commonpb.TimeSkippingFastForwardInfo{ + FastForwardDuration: durationpb.New(5 * time.Hour), + FastForwardId: "ff-id", + TargetTime: timestamppb.New(targetTime), + HasCompleted: true, + }, + } + + printable := timeSkippingToPrintable(info) + require.True(t, printable.EffectiveEnabled) + require.True(t, printable.DisablePropagation) + require.Equal(t, int32(200), printable.MaxSessionSkipCount) + require.Equal(t, int32(4), printable.CurrentSessionSkipCount) + require.Equal(t, "ff-id", printable.FastForwardInfo.Id) + require.Equal(t, "5h 0m 0s", printable.FastForwardInfo.Duration) + require.Equal(t, targetTime, printable.FastForwardInfo.TargetTime) + require.True(t, printable.FastForwardInfo.HasCompleted) + + config.DisablePropagation = false + require.False(t, timeSkippingToPrintable(info).DisablePropagation) +} + +func TestTimeSkippingToPrintableNilValues(t *testing.T) { + t.Run("nil info", func(t *testing.T) { + require.Nil(t, timeSkippingToPrintable(nil)) + }) + + t.Run("empty info", func(t *testing.T) { + require.Equal(t, &printableTimeSkippingInfo{}, timeSkippingToPrintable(&commonpb.TimeSkippingInfo{})) + }) + + currentTime := time.Date(2026, time.October, 27, 12, 0, 0, 0, time.UTC) + targetTime := currentTime.Add(5 * time.Hour) + // Exercise every combination of the optional config, current time, + // fast-forward info, duration, and target time. Nested fields cannot be + // present when their parent fast-forward info is nil. + for mask := 0; mask < 32; mask++ { + hasConfig := mask&1 != 0 + hasCurrentTime := mask&2 != 0 + hasFastForward := mask&4 != 0 + hasDuration := mask&8 != 0 + hasTargetTime := mask&16 != 0 + if !hasFastForward && (hasDuration || hasTargetTime) { + continue + } + name := fmt.Sprintf("config=%t/current_time=%t/fast_forward=%t/duration=%t/target_time=%t", + hasConfig, hasCurrentTime, hasFastForward, hasDuration, hasTargetTime) + t.Run(name, func(t *testing.T) { + info := &commonpb.TimeSkippingInfo{CurrentSessionSkipCount: 4} + want := &printableTimeSkippingInfo{CurrentSessionSkipCount: 4} + if hasConfig { + info.EffectiveConfig = &commonpb.TimeSkippingConfig{ + Enabled: true, DisablePropagation: true, MaxSessionSkipCount: 200, + } + want.EffectiveEnabled = true + want.DisablePropagation = true + want.MaxSessionSkipCount = 200 + } + if hasCurrentTime { + info.CurrentTime = timestamppb.New(currentTime) + want.CurrentTime = currentTime + } + if hasFastForward { + info.FastForwardInfo = &commonpb.TimeSkippingFastForwardInfo{ + FastForwardId: "ff-id", HasCompleted: true, + } + want.FastForwardInfo = &printableTimeSkippingFastForwardInfo{ + Id: "ff-id", HasCompleted: true, Duration: "0s", + } + if hasDuration { + info.FastForwardInfo.FastForwardDuration = durationpb.New(5 * time.Hour) + want.FastForwardInfo.Duration = "5h 0m 0s" + } + if hasTargetTime { + info.FastForwardInfo.TargetTime = timestamppb.New(targetTime) + want.FastForwardInfo.TargetTime = targetTime + } + } + require.Equal(t, want, timeSkippingToPrintable(info)) + }) + } +} + +func TestPrintTimeSkippingUpdateJSON(t *testing.T) { + for _, format := range []string{"json", "jsonl"} { + t.Run(format, func(t *testing.T) { + for _, tc := range []struct { + name string + enabled bool + forward bool + id string + }{ + {name: "enabled with generated fast-forward ID", enabled: true, forward: true}, + {name: "enabled with explicit fast-forward ID", enabled: true, forward: true, id: "YourFastForwardId"}, + {name: "enabled without fast-forward", enabled: true}, + {name: "disabled"}, + } { + t.Run(tc.name, func(t *testing.T) { + config := &client.TimeSkippingConfig{Enabled: false} + if tc.enabled { + var err error + config, err = timeSkippingConfig(time.Hour, tc.forward, tc.id, false, 0) + require.NoError(t, err) + } + var output bytes.Buffer + cctx := &CommandContext{JSONOutput: true} + cctx.Printer = &printer.Printer{Output: &output, JSON: true} + if format == "json" { + cctx.Printer.JSONIndent = " " + } + require.NoError(t, printTimeSkippingUpdateJSON(cctx, config)) + var result map[string]any + require.NoError(t, json.Unmarshal(output.Bytes(), &result)) + want := map[string]any{"enabled": tc.enabled} + if tc.forward { + id, ok := result["fastForwardId"].(string) + require.True(t, ok) + require.Equal(t, config.FastForwardConfig.ID, id) + if tc.id == "" { + _, err := uuid.Parse(id) + require.NoError(t, err) + } else { + require.Equal(t, tc.id, id) + } + want["fastForwardId"] = id + } + require.Equal(t, want, result) + if format == "jsonl" { + require.Len(t, strings.Split(strings.TrimSpace(output.String()), "\n"), 1) + } + }) + } + }) + } + t.Run("nil config", func(t *testing.T) { + require.EqualError(t, printTimeSkippingUpdateJSON(nil, nil), "time-skipping configuration is required") + }) + t.Run("output error is returned", func(t *testing.T) { + wantErr := errors.New("write failed") + cctx := &CommandContext{JSONOutput: true, Printer: &printer.Printer{ + JSON: true, Output: timeSkippingResultErrorWriter{err: wantErr}, + }} + require.ErrorIs(t, printTimeSkippingUpdateJSON(cctx, &client.TimeSkippingConfig{}), wantErr) + }) +} + +type timeSkippingResultErrorWriter struct{ err error } + +func (w timeSkippingResultErrorWriter) Write([]byte) (int, error) { return 0, w.err } + +func TestPrintTimeSkippingPollCompleted(t *testing.T) { + for _, format := range []string{"text", "json", "jsonl"} { + t.Run(format, func(t *testing.T) { + var output bytes.Buffer + cctx := &CommandContext{JSONOutput: format != "text"} + cctx.Printer = &printer.Printer{Output: &output, JSON: cctx.JSONOutput} + if format == "json" { + cctx.Printer.JSONIndent = " " + } + require.NoError(t, printTimeSkippingPollCompleted(cctx)) + if format == "text" { + require.Equal(t, "completed\n", output.String()) + } else { + require.JSONEq(t, `{"completed":true}`, output.String()) + if format == "jsonl" { + require.Len(t, strings.Split(strings.TrimSpace(output.String()), "\n"), 1) + } + } + }) + } + t.Run("output error is returned", func(t *testing.T) { + wantErr := errors.New("write failed") + cctx := &CommandContext{JSONOutput: true, Printer: &printer.Printer{ + JSON: true, Output: timeSkippingResultErrorWriter{err: wantErr}, + }} + require.ErrorIs(t, printTimeSkippingPollCompleted(cctx), wantErr) + }) +}