diff --git a/.github/workflows/pr-validation.yml b/.github/workflows/pr-validation.yml index 9319133f..84a69aa0 100644 --- a/.github/workflows/pr-validation.yml +++ b/.github/workflows/pr-validation.yml @@ -36,7 +36,7 @@ jobs: test-kind: coverage test-command: >- go test ./... -count=1 -timeout=20m - -coverpkg=./api,./task,./client,./durabletaskscheduler,./exporthistory,./payload,./internal/contextprop,./internal/failure,./internal/grpcerrors,./internal/helpers,./internal/historyconv,./internal/largepayload,./internal/tagcodec + -coverpkg=./api,./task,./client,./durabletaskscheduler,./durabletasktest,./exporthistory,./payload,./internal/contextprop,./internal/failure,./internal/grpcerrors,./internal/helpers,./internal/historyconv,./internal/inmemory,./internal/largepayload,./internal/tagcodec - go-version: '1.27.x' test-kind: race test-command: go test -race ./... -count=1 -timeout=30m diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f2011d3..7f234169 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- Added the `durabletasktest` package, which runs orchestrations and activities in a test process against an in-memory Durable Task service over an in-memory gRPC transport. It supports activities, sub-orchestrations, real-time timers, external events, continue-as-new, suspend/resume, terminate, restart, queries, purge, and history. Durable entities and rewind are not supported. Like DTS, the service limits requests and completions to 4 MiB; an activity completion over 4 MiB fails once with the non-retriable error type `ActivityResponseTooLarge`. - Added required completion-transport isolation to gRPC workers: one intake and three dedicated completion/abandon connections by default, with a configurable 1–8 completion budget and bounded generation-safe retirement. `WithWorkerCompletionConnections(0)` is invalid. Borrowed workers and client listeners require separate caller-owned channels via `WithWorkerCompletionTransports`; owning factories must return distinct connections and non-nil closers for every invocation. - Added `ResourceId` connection-string support for every DTS authentication mode and optional `AuthorityHost` configuration for SDK-created DefaultAzure, WorkloadIdentity, Environment, and InteractiveBrowser credentials. Caller-supplied credentials own their authority; managed identity and developer-tool cloud configuration remain separate. - Added a flat catalogue of directly runnable DTS samples with outcome assertions, owned-resource cleanup, and process-level E2E validation selected by sample name using Go's `-run` flag. diff --git a/README.md b/README.md index cdbf9c23..3db4f7cf 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,7 @@ Use these features for large systems or for special conditions. | Distributed tracing | Emit OpenTelemetry spans from your process. DTS emits the durable spans. | | Replay-hazard analysis | Find nondeterministic orchestrator code with `cmd/orchestratorvet`. | | History export (preview) | Copy terminal orchestration histories to Azure Blob Storage. | +| In-process testing | Run orchestrations in a test with an in-memory service and `durabletasktest`. | ## Quick start @@ -637,6 +638,38 @@ Each exported object is an opaque gzip file. The name ends with `.jsonl.gz`. The For more information, read the [export history guide](./exporthistory/README.md). See also the [sample](./samples/exporthistory). +## Testing orchestrations + +The `durabletasktest` package runs your orchestrations and activities in your test process. It starts an in-memory Durable Task service, a worker for your registry, and a connected client. The parts talk over an in-memory gRPC transport, so the test needs no emulator, network port, or Azure resource. The worker, executor, and client are the same code that runs against DTS. + +```go +func TestGreeting(t *testing.T) { + registry := task.NewTaskRegistry() + registry.AddOrchestratorN("Greeting", greeting) + registry.AddActivityN("SayHello", func(ctx task.ActivityContext) (any, error) { + return "Hello, test!", nil // Stub the real activity. + }) + + host := durabletasktest.New(t, registry) // Closed when the test ends. + id, err := host.Client().ScheduleNewOrchestration(t.Context(), "Greeting") + require.NoError(t, err) + metadata, err := host.Client().WaitForOrchestrationCompletion(t.Context(), id) + require.NoError(t, err) + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, metadata.RuntimeStatus) +} +``` + +To isolate an orchestration from its dependencies, register stub activities and sub-orchestrators in the test registry. You can use the client to raise events, suspend, resume, terminate, restart, query, and purge instances, and read history. + +The in-memory service has these limits: + +- Timers use the Go runtime clock. `testing/synctest` + can advance timers without waiting in real time while the test goroutines are + blocked. The `durabletasktest` tests include a 24-hour timer example. +- Durable entities and rewind aren't supported. Entity client calls and `RewindInstance` return `api.ErrFeatureNotSupported`. An orchestration that calls, signals, or locks an entity fails. The service has no task hub name, so a query filtered by `TaskHubNames` also returns `api.ErrFeatureNotSupported`. +- State is kept in memory only. It is discarded when the host closes. +- Requests and worker completions are limited to 4 MiB, as in DTS. Larger client requests fail with `ResourceExhausted`. An activity whose completion is larger fails once with the non-retriable error type `ActivityResponseTooLarge` instead of running again. + ## Development ### Clone the repository @@ -671,7 +704,7 @@ The package tests are beside the code that they exercise. The `./tests` director Run the full suite with these commands: ```bash -go test ./... -count=1 -coverpkg=./api,./task,./client,./durabletaskscheduler,./exporthistory,./payload,./internal/contextprop,./internal/failure,./internal/grpcerrors,./internal/helpers,./internal/historyconv,./internal/largepayload,./internal/tagcodec +go test ./... -count=1 -coverpkg=./api,./task,./client,./durabletaskscheduler,./durabletasktest,./exporthistory,./payload,./internal/contextprop,./internal/failure,./internal/grpcerrors,./internal/helpers,./internal/historyconv,./internal/inmemory,./internal/largepayload,./internal/tagcodec (cd cmd/orchestratorvet && go test ./...) (cd samples/distributedtracing && go test ./...) ``` diff --git a/durabletasktest/host.go b/durabletasktest/host.go new file mode 100644 index 00000000..231db350 --- /dev/null +++ b/durabletasktest/host.go @@ -0,0 +1,271 @@ +// Package durabletasktest runs orchestrations and activities in process for tests. +// +// A [Host] starts an in-memory Durable Task service, a worker for the +// orchestrators and activities in a [task.TaskRegistry], and a client +// connected to the same service. Communication uses an in-memory gRPC +// transport, so no network ports or external services are required. +// +// registry := task.NewTaskRegistry() +// registry.AddOrchestratorN("Greeting", greeting) +// registry.AddActivityN("SayHello", sayHello) +// +// host := durabletasktest.New(t, registry) +// id, err := host.Client().ScheduleNewOrchestration(ctx, "Greeting") +// ... +// metadata, err := host.Client().WaitForOrchestrationCompletion(ctx, id) +// +// Orchestrations run through the same worker, executor, and client code paths +// that production workers use. To isolate an orchestrator from external +// dependencies, register stub activities in the test's registry. +// +// Timers use the Go runtime clock. Tests can use testing/synctest to +// advance timers without waiting in real time. +// Durable entities and orchestration rewind are not supported: entity client +// operations and rewind fail with [api.ErrFeatureNotSupported], and an +// orchestration that calls, signals, or locks an entity fails. +package durabletasktest + +import ( + "context" + "errors" + "fmt" + "io" + "log/slog" + "net" + "sync" + "testing" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/test/bufconn" + + "github.com/microsoft/durabletask-go/api" + "github.com/microsoft/durabletask-go/client" + "github.com/microsoft/durabletask-go/internal/inmemory" + "github.com/microsoft/durabletask-go/task" +) + +const bufferSize = 64 << 10 + +const defaultCloseTimeout = 5 * time.Second + +// maxReceiveMessageSize matches the default receive limit of DTS connections. +// Like them, the host's connections set no send limit. +const maxReceiveMessageSize = 64 << 20 + +// Option configures a [Host]. +type Option func(*options) + +type options struct { + logger api.Logger + workerOptions []client.TaskHubGrpcWorkerOption + clientOptions []client.TaskHubGrpcClientOption +} + +// WithLogger sets the logger used by the worker and client. By default, the +// host discards log output. +func WithLogger(logger api.Logger) Option { + return func(o *options) { o.logger = logger } +} + +// WithWorkerOptions adds options for the host's worker, such as a data +// converter or versioning settings. +func WithWorkerOptions(opts ...client.TaskHubGrpcWorkerOption) Option { + return func(o *options) { o.workerOptions = append(o.workerOptions, opts...) } +} + +// WithClientOptions adds options for the host's client, such as a data converter. +func WithClientOptions(opts ...client.TaskHubGrpcClientOption) Option { + return func(o *options) { o.clientOptions = append(o.clientOptions, opts...) } +} + +// Host is an in-process Durable Task service with a running worker and a client. +type Host struct { + backend *inmemory.Server + server *grpc.Server + listener *bufconn.Listener + clientConn *grpc.ClientConn + client *client.TaskHubGrpcClient + worker *client.TaskHubGrpcWorker +} + +// New starts a [Host] for a test and closes it when the test and its subtests finish. +// It stops the test with [testing.TB.Fatal] if the host can't start. +func New(tb testing.TB, registry *task.TaskRegistry, opts ...Option) *Host { + tb.Helper() + host, err := NewHost(tb.Context(), registry, opts...) + if err != nil { + tb.Fatalf("failed to start durable task test host: %v", err) + } + tb.Cleanup(func() { + ctx, cancel := context.WithTimeout(context.Background(), defaultCloseTimeout) + defer cancel() + if err := host.Close(ctx); err != nil { + tb.Errorf("failed to close durable task test host: %v", err) + } + }) + return host +} + +// NewHost starts an in-memory service and a worker for the registry. Call +// [Host.Close] to stop it. ctx bounds startup only. +func NewHost(ctx context.Context, registry *task.TaskRegistry, opts ...Option) (*Host, error) { + if registry == nil { + return nil, errors.New("task registry is required") + } + if ctx == nil { + ctx = context.Background() + } + if err := ctx.Err(); err != nil { + return nil, err + } + o := options{logger: api.NewSlogLogger(slog.New(slog.DiscardHandler))} + for _, configure := range opts { + configure(&o) + } + + h := &Host{ + backend: inmemory.NewServer(), + server: grpc.NewServer(inmemory.ServerOptions()...), + listener: bufconn.Listen(bufferSize), + } + h.backend.Register(h.server) + go func() { _ = h.server.Serve(h.listener) }() + + var err error + h.clientConn, err = h.dial() + if err != nil { + h.stop() + return nil, err + } + h.client = client.NewTaskHubGrpcClient(h.clientConn, o.logger, o.clientOptions...) + + factory := func(context.Context) (grpc.ClientConnInterface, io.Closer, error) { + conn, err := h.dial() + if err != nil { + return nil, nil, err + } + return conn, conn, nil + } + h.worker, err = client.NewTaskHubGrpcWorkerWithConnectionFactory(factory, registry, o.logger, o.workerOptions...) + if err != nil { + h.stop() + return nil, fmt.Errorf("failed to create worker: %w", err) + } + startupCtx, finishStartup := newStartupContext(ctx) + startErr := h.worker.Start(startupCtx) + startupErr := finishStartup() + if startErr != nil { + h.stop() + if startupErr != nil { + startErr = startupErr + } + return nil, fmt.Errorf("failed to start worker: %w", startErr) + } + if startupErr != nil { + closeCtx, cancel := context.WithTimeout(context.Background(), defaultCloseTimeout) + defer cancel() + _ = h.worker.Shutdown(closeCtx) + h.stop() + return nil, fmt.Errorf("failed to start worker: %w", startupErr) + } + return h, nil +} + +type startupContext struct { + context.Context + done chan struct{} + + mu sync.Mutex + err error + starting bool +} + +func newStartupContext(parent context.Context) (*startupContext, func() error) { + ctx := &startupContext{ + Context: context.WithoutCancel(parent), + done: make(chan struct{}), + starting: true, + } + stopParentCancel := context.AfterFunc(parent, func() { + ctx.mu.Lock() + defer ctx.mu.Unlock() + if ctx.starting { + ctx.cancelLocked(parent.Err()) + } + }) + finish := func() error { + ctx.mu.Lock() + defer ctx.mu.Unlock() + stopParentCancel() + if err := parent.Err(); err != nil { + ctx.cancelLocked(err) + } + ctx.starting = false + return ctx.err + } + return ctx, finish +} + +func (c *startupContext) Deadline() (time.Time, bool) { + return time.Time{}, false +} + +func (c *startupContext) Done() <-chan struct{} { + return c.done +} + +func (c *startupContext) Err() error { + c.mu.Lock() + defer c.mu.Unlock() + return c.err +} + +func (c *startupContext) cancelLocked(err error) { + if c.err != nil { + return + } + if err == nil { + err = context.Canceled + } + c.err = err + close(c.done) +} + +func (h *Host) dial() (*grpc.ClientConn, error) { + conn, err := grpc.NewClient( + "passthrough:///durabletasktest", + grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { + return h.listener.DialContext(ctx) + }), + grpc.WithTransportCredentials(insecure.NewCredentials()), + grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(maxReceiveMessageSize)), + ) + if err != nil { + return nil, fmt.Errorf("failed to create in-memory connection: %w", err) + } + return conn, nil +} + +// Client returns a client connected to the host's in-memory service. +func (h *Host) Client() *client.TaskHubGrpcClient { + return h.client +} + +// Close stops the worker and the in-memory service. All orchestration state is discarded. +// If ctx ends before in-flight work items finish, they are canceled. +func (h *Host) Close(ctx context.Context) error { + err := h.worker.Shutdown(ctx) + h.stop() + return err +} + +func (h *Host) stop() { + h.backend.Close() + if h.clientConn != nil { + _ = h.clientConn.Close() + } + h.server.Stop() + _ = h.listener.Close() +} diff --git a/durabletasktest/host_test.go b/durabletasktest/host_test.go new file mode 100644 index 00000000..98f9f183 --- /dev/null +++ b/durabletasktest/host_test.go @@ -0,0 +1,602 @@ +package durabletasktest_test + +import ( + "context" + "errors" + "fmt" + "strings" + "sync/atomic" + "testing" + "testing/synctest" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/microsoft/durabletask-go/api" + "github.com/microsoft/durabletask-go/client" + "github.com/microsoft/durabletask-go/durabletasktest" + "github.com/microsoft/durabletask-go/task" +) + +func testContext(t *testing.T) context.Context { + t.Helper() + ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second) + t.Cleanup(cancel) + return ctx +} + +func run(t *testing.T, host *durabletasktest.Host, name string, opts ...api.NewOrchestrationOptions) *api.OrchestrationMetadata { + t.Helper() + ctx := testContext(t) + id, err := host.Client().ScheduleNewOrchestration(ctx, name, opts...) + require.NoError(t, err) + metadata, err := host.Client().WaitForOrchestrationCompletion(ctx, id) + require.NoError(t, err) + return metadata +} + +func TestActivitySequence(t *testing.T) { + r := task.NewTaskRegistry() + require.NoError(t, r.AddActivityN("Hello", func(ctx task.ActivityContext) (any, error) { + var name string + if err := ctx.GetInput(&name); err != nil { + return nil, err + } + return "Hello, " + name + "!", nil + })) + require.NoError(t, r.AddOrchestratorN("Sequence", func(ctx *task.OrchestrationContext) (any, error) { + var results []string + for _, city := range []string{"Tokyo", "London", "Seattle"} { + var result string + if err := ctx.CallActivity("Hello", task.WithActivityInput(city)).Await(&result); err != nil { + return nil, err + } + results = append(results, result) + } + return results, nil + })) + host := durabletasktest.New(t, r) + + metadata := run(t, host, "Sequence") + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, metadata.RuntimeStatus) + var output []string + require.NoError(t, metadata.ReadOutput(&output)) + assert.Equal(t, []string{"Hello, Tokyo!", "Hello, London!", "Hello, Seattle!"}, output) + + history, err := host.Client().GetOrchestrationHistory(testContext(t), metadata.InstanceID, api.HistoryQuery{}) + require.NoError(t, err) + assert.Equal(t, metadata.ExecutionID, history.ExecutionID) + scheduled := 0 + for _, event := range history.Events { + if event.Type == api.HistoryEventTaskScheduled { + scheduled++ + } + } + assert.Equal(t, 3, scheduled) + assert.Equal(t, api.HistoryEventExecutionCompleted, history.Events[len(history.Events)-1].Type) +} + +func TestFanOutFanIn(t *testing.T) { + r := task.NewTaskRegistry() + require.NoError(t, r.AddActivityN("Square", func(ctx task.ActivityContext) (any, error) { + var n int + if err := ctx.GetInput(&n); err != nil { + return nil, err + } + return n * n, nil + })) + require.NoError(t, r.AddOrchestratorN("FanOut", func(ctx *task.OrchestrationContext) (any, error) { + tasks := make([]task.Task, 10) + for i := range tasks { + tasks[i] = ctx.CallActivity("Square", task.WithActivityInput(i)) + } + sum := 0 + for _, t := range tasks { + var n int + if err := t.Await(&n); err != nil { + return nil, err + } + sum += n + } + return sum, nil + })) + host := durabletasktest.New(t, r) + + metadata := run(t, host, "FanOut") + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, metadata.RuntimeStatus) + var sum int + require.NoError(t, metadata.ReadOutput(&sum)) + assert.Equal(t, 285, sum) +} + +func TestActivityFailureFailsOrchestration(t *testing.T) { + r := task.NewTaskRegistry() + require.NoError(t, r.AddActivityN("Fail", func(task.ActivityContext) (any, error) { + return nil, errors.New("boom") + })) + require.NoError(t, r.AddOrchestratorN("CallsFail", func(ctx *task.OrchestrationContext) (any, error) { + return nil, ctx.CallActivity("Fail").Await(nil) + })) + host := durabletasktest.New(t, r) + + metadata := run(t, host, "CallsFail") + require.Equal(t, api.RUNTIME_STATUS_FAILED, metadata.RuntimeStatus) + require.NotNil(t, metadata.FailureDetails) + assert.Contains(t, metadata.FailureDetails.ErrorMessage, "boom") +} + +func TestActivityConcurrencyDoesNotBlockOrchestrationDispatch(t *testing.T) { + clientCh := make(chan *client.TaskHubGrpcClient, 1) + r := task.NewTaskRegistry() + require.NoError(t, r.AddActivityN("WaitForOrchestration", func(ctx task.ActivityContext) (any, error) { + c := <-clientCh + id, err := c.ScheduleNewOrchestration(ctx.Context(), "Notify") + if err != nil { + return nil, err + } + _, err = c.WaitForOrchestrationCompletion(ctx.Context(), id) + return nil, err + })) + require.NoError(t, r.AddActivityN("Other", func(task.ActivityContext) (any, error) { + return nil, nil + })) + require.NoError(t, r.AddOrchestratorN("FanOut", func(ctx *task.OrchestrationContext) (any, error) { + wait := ctx.CallActivity("WaitForOrchestration") + other := ctx.CallActivity("Other") + if err := wait.Await(nil); err != nil { + return nil, err + } + return nil, other.Await(nil) + })) + require.NoError(t, r.AddOrchestratorN("Notify", func(*task.OrchestrationContext) (any, error) { + return "notified", nil + })) + host := durabletasktest.New(t, r, + durabletasktest.WithWorkerOptions(client.WithMaxConcurrentActivityWorkItems(1)), + ) + clientCh <- host.Client() + + metadata := run(t, host, "FanOut") + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, metadata.RuntimeStatus) +} + +func TestLargeReplayHistory(t *testing.T) { + r := task.NewTaskRegistry() + require.NoError(t, r.AddActivityN("Echo", func(ctx task.ActivityContext) (any, error) { + var input string + if err := ctx.GetInput(&input); err != nil { + return nil, err + } + return input, nil + })) + require.NoError(t, r.AddOrchestratorN("EchoHistory", func(ctx *task.OrchestrationContext) (any, error) { + var input string + if err := ctx.GetInput(&input); err != nil { + return nil, err + } + for range 8 { + var result string + if err := ctx.CallActivity("Echo", task.WithActivityInput(input)).Await(&result); err != nil { + return nil, err + } + input = result + } + return len(input), nil + })) + host := durabletasktest.New(t, r) + + metadata := run(t, host, "EchoHistory", api.WithInput(strings.Repeat("x", 384<<10))) + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, metadata.RuntimeStatus) + var length int + require.NoError(t, metadata.ReadOutput(&length)) + assert.Equal(t, 384<<10, length) +} + +func TestEventsLargerThanOneMessageAreDeliveredAcrossTurns(t *testing.T) { + r := task.NewTaskRegistry() + require.NoError(t, r.AddOrchestratorN("TwoEvents", func(ctx *task.OrchestrationContext) (any, error) { + total := 0 + for _, name := range []string{"A", "B"} { + var payload string + if err := ctx.WaitForSingleEvent(name, time.Minute).Await(&payload); err != nil { + return nil, err + } + total += len(payload) + } + return total, nil + })) + host := durabletasktest.New(t, r) + ctx := testContext(t) + + // Raise both events before the scheduled start so they are pending together + // and exceed the 4 MiB message limit as a single turn. + id, err := host.Client().ScheduleNewOrchestration(ctx, "TwoEvents", api.WithStartTime(time.Now().Add(500*time.Millisecond))) + require.NoError(t, err) + payload := strings.Repeat("x", 3<<20) + require.NoError(t, host.Client().RaiseEvent(ctx, id, "A", api.WithEventPayload(payload))) + require.NoError(t, host.Client().RaiseEvent(ctx, id, "B", api.WithEventPayload(payload))) + metadata, err := host.Client().WaitForOrchestrationCompletion(ctx, id) + require.NoError(t, err) + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, metadata.RuntimeStatus) + var total int + require.NoError(t, metadata.ReadOutput(&total)) + assert.Equal(t, 2*len(payload), total) +} + +func TestOversizedActivityResultFailsOnce(t *testing.T) { + var executions atomic.Int32 + r := task.NewTaskRegistry() + require.NoError(t, r.AddActivityN("Big", func(task.ActivityContext) (any, error) { + executions.Add(1) + return strings.Repeat("x", 5<<20), nil + })) + require.NoError(t, r.AddOrchestratorN("CallsBig", func(ctx *task.OrchestrationContext) (any, error) { + err := ctx.CallActivity("Big").Await(nil) + var failed *task.TaskFailedError + if !errors.As(err, &failed) { + return nil, fmt.Errorf("expected a task failure, got %w", err) + } + return failed.FailureDetails, nil + })) + host := durabletasktest.New(t, r) + + metadata := run(t, host, "CallsBig") + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, metadata.RuntimeStatus) + var failure api.FailureDetails + require.NoError(t, metadata.ReadOutput(&failure)) + assert.Equal(t, api.ErrorType("ActivityResponseTooLarge"), failure.ErrorType) + assert.Contains(t, failure.ErrorMessage, "4194304-byte") + assert.True(t, failure.NonRetriable()) + assert.Equal(t, int32(1), executions.Load()) +} + +func TestRequestsOverMessageLimitAreRejected(t *testing.T) { + host := durabletasktest.New(t, task.NewTaskRegistry()) + + _, err := host.Client().ScheduleNewOrchestration(testContext(t), "Any", + api.WithInput(strings.Repeat("x", 5<<20))) + assert.Equal(t, codes.ResourceExhausted, status.Code(err)) +} + +func TestNewHostPreservesStartupContextAndDetachesAfterStart(t *testing.T) { + r := task.NewTaskRegistry() + require.NoError(t, r.AddOrchestratorN("Complete", func(*task.OrchestrationContext) (any, error) { + return "done", nil + })) + + canceled, cancel := context.WithCancel(context.Background()) + cancel() + _, err := durabletasktest.NewHost(canceled, r) + require.ErrorIs(t, err, context.Canceled) + + expired, cancelExpired := context.WithDeadline(context.Background(), time.Now().Add(-time.Second)) + defer cancelExpired() + _, err = durabletasktest.NewHost(expired, r) + require.ErrorIs(t, err, context.DeadlineExceeded) + + startup, cancelStartup := context.WithCancel(context.Background()) + host, err := durabletasktest.NewHost(startup, r) + require.NoError(t, err) + cancelStartup() + t.Cleanup(func() { + closeCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + require.NoError(t, host.Close(closeCtx)) + }) + + metadata := run(t, host, "Complete") + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, metadata.RuntimeStatus) +} + +func TestCloseCancelsStuckActivity(t *testing.T) { + started := make(chan struct{}) + stopped := make(chan struct{}) + r := task.NewTaskRegistry() + require.NoError(t, r.AddActivityN("WaitForCancellation", func(ctx task.ActivityContext) (any, error) { + close(started) + <-ctx.Context().Done() + close(stopped) + return nil, ctx.Context().Err() + })) + require.NoError(t, r.AddOrchestratorN("Wait", func(ctx *task.OrchestrationContext) (any, error) { + return nil, ctx.CallActivity("WaitForCancellation").Await(nil) + })) + host, err := durabletasktest.NewHost(context.Background(), r) + require.NoError(t, err) + _, err = host.Client().ScheduleNewOrchestration(testContext(t), "Wait") + require.NoError(t, err) + <-started + + closeCtx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + require.ErrorIs(t, host.Close(closeCtx), context.DeadlineExceeded) + select { + case <-stopped: + case <-time.After(time.Second): + t.Fatal("activity was not canceled during host shutdown") + } +} + +func TestSynctestAdvancesDurableTimers(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + r := task.NewTaskRegistry() + require.NoError(t, r.AddOrchestratorN("LongTimer", func(ctx *task.OrchestrationContext) (any, error) { + if err := ctx.CreateTimer(24 * time.Hour).Await(nil); err != nil { + return nil, err + } + return "done", nil + })) + host := durabletasktest.New(t, r) + id, err := host.Client().ScheduleNewOrchestration(context.Background(), "LongTimer") + require.NoError(t, err) + metadata, err := host.Client().WaitForOrchestrationCompletion(context.Background(), id) + require.NoError(t, err) + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, metadata.RuntimeStatus) + }) +} + +func TestSubOrchestrations(t *testing.T) { + r := task.NewTaskRegistry() + require.NoError(t, r.AddOrchestratorN("Child", func(ctx *task.OrchestrationContext) (any, error) { + var n int + if err := ctx.GetInput(&n); err != nil { + return nil, err + } + if n < 0 { + return nil, errors.New("negative input") + } + return n * 2, nil + })) + require.NoError(t, r.AddOrchestratorN("Parent", func(ctx *task.OrchestrationContext) (any, error) { + var input int + if err := ctx.GetInput(&input); err != nil { + return nil, err + } + var result int + err := ctx.CallSubOrchestrator("Child", + task.WithSubOrchestratorInput(input), + task.WithSubOrchestrationInstanceID(string(ctx.ID)+"-child"), + ).Await(&result) + return result, err + })) + host := durabletasktest.New(t, r) + + metadata := run(t, host, "Parent", api.WithInput(21)) + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, metadata.RuntimeStatus) + var result int + require.NoError(t, metadata.ReadOutput(&result)) + assert.Equal(t, 42, result) + child, err := host.Client().FetchOrchestrationMetadata(testContext(t), metadata.InstanceID+"-child") + require.NoError(t, err) + assert.Equal(t, metadata.InstanceID, child.ParentInstanceID) + + metadata = run(t, host, "Parent", api.WithInput(-1)) + require.Equal(t, api.RUNTIME_STATUS_FAILED, metadata.RuntimeStatus) + assert.Contains(t, metadata.FailureDetails.ErrorMessage, "negative input") +} + +func TestTimersAndExternalEvents(t *testing.T) { + r := task.NewTaskRegistry() + require.NoError(t, r.AddOrchestratorN("Approval", func(ctx *task.OrchestrationContext) (any, error) { + if err := ctx.CreateTimer(10 * time.Millisecond).Await(nil); err != nil { + return nil, err + } + var approver string + if err := ctx.WaitForSingleEvent("Approve", 5*time.Second).Await(&approver); err != nil { + return nil, err + } + return approver, nil + })) + require.NoError(t, r.AddOrchestratorN("TimesOut", func(ctx *task.OrchestrationContext) (any, error) { + err := ctx.WaitForSingleEvent("Never", 10*time.Millisecond).Await(nil) + return errors.Is(err, task.ErrTaskCanceled), nil + })) + host := durabletasktest.New(t, r) + ctx := testContext(t) + + id, err := host.Client().ScheduleNewOrchestration(ctx, "Approval") + require.NoError(t, err) + require.NoError(t, host.Client().RaiseEvent(ctx, id, "Approve", api.WithEventPayload("alice"))) + metadata, err := host.Client().WaitForOrchestrationCompletion(ctx, id) + require.NoError(t, err) + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, metadata.RuntimeStatus) + var approver string + require.NoError(t, metadata.ReadOutput(&approver)) + assert.Equal(t, "alice", approver) + + metadata = run(t, host, "TimesOut") + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, metadata.RuntimeStatus) + var timedOut bool + require.NoError(t, metadata.ReadOutput(&timedOut)) + assert.True(t, timedOut) +} + +func TestSendEventBetweenOrchestrations(t *testing.T) { + r := task.NewTaskRegistry() + require.NoError(t, r.AddOrchestratorN("Receiver", func(ctx *task.OrchestrationContext) (any, error) { + var message string + err := ctx.WaitForSingleEvent("Message", 5*time.Second).Await(&message) + return message, err + })) + require.NoError(t, r.AddOrchestratorN("Sender", func(ctx *task.OrchestrationContext) (any, error) { + var target string + if err := ctx.GetInput(&target); err != nil { + return nil, err + } + return nil, ctx.SendEvent(api.InstanceID(target), "Message", "ping") + })) + host := durabletasktest.New(t, r) + ctx := testContext(t) + + receiver, err := host.Client().ScheduleNewOrchestration(ctx, "Receiver") + require.NoError(t, err) + _, err = host.Client().WaitForOrchestrationStart(ctx, receiver) + require.NoError(t, err) + run(t, host, "Sender", api.WithInput(string(receiver))) + metadata, err := host.Client().WaitForOrchestrationCompletion(ctx, receiver) + require.NoError(t, err) + var message string + require.NoError(t, metadata.ReadOutput(&message)) + assert.Equal(t, "ping", message) +} + +func TestContinueAsNew(t *testing.T) { + r := task.NewTaskRegistry() + require.NoError(t, r.AddOrchestratorN("Counter", func(ctx *task.OrchestrationContext) (any, error) { + var n int + if err := ctx.GetInput(&n); err != nil { + return nil, err + } + if n < 5 { + ctx.ContinueAsNew(n + 1) + return nil, nil + } + return n, nil + })) + host := durabletasktest.New(t, r) + + metadata := run(t, host, "Counter", api.WithInput(0)) + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, metadata.RuntimeStatus) + var n int + require.NoError(t, metadata.ReadOutput(&n)) + assert.Equal(t, 5, n) + + history, err := host.Client().GetOrchestrationHistory(testContext(t), metadata.InstanceID, api.HistoryQuery{}) + require.NoError(t, err) + started := 0 + for _, event := range history.Events { + if event.Type == api.HistoryEventExecutionStarted { + started++ + } + } + assert.Equal(t, 1, started, "history should contain only the final execution") + assert.Equal(t, metadata.ExecutionID, history.ExecutionID) +} + +func TestTerminateSuspendAndResume(t *testing.T) { + r := task.NewTaskRegistry() + require.NoError(t, r.AddOrchestratorN("Waiter", func(ctx *task.OrchestrationContext) (any, error) { + var value string + err := ctx.WaitForSingleEvent("Go", time.Minute).Await(&value) + return value, err + })) + require.NoError(t, r.AddOrchestratorN("WaitingParent", func(ctx *task.OrchestrationContext) (any, error) { + return nil, ctx.CallSubOrchestrator("Waiter", + task.WithSubOrchestrationInstanceID(string(ctx.ID)+"-child")).Await(nil) + })) + host := durabletasktest.New(t, r) + ctx := testContext(t) + c := host.Client() + + id, err := c.ScheduleNewOrchestration(ctx, "Waiter") + require.NoError(t, err) + _, err = c.WaitForOrchestrationStart(ctx, id) + require.NoError(t, err) + require.NoError(t, c.SuspendOrchestration(ctx, id, "pause")) + metadata, err := c.FetchOrchestrationMetadata(ctx, id) + require.NoError(t, err) + assert.Equal(t, api.RUNTIME_STATUS_SUSPENDED, metadata.RuntimeStatus) + assert.ErrorIs(t, c.PurgeOrchestrationState(ctx, id), api.ErrNotCompleted) + require.NoError(t, c.RaiseEvent(ctx, id, "Go", api.WithEventPayload("done"))) + require.NoError(t, c.ResumeOrchestration(ctx, id, "continue")) + metadata, err = c.WaitForOrchestrationCompletion(ctx, id) + require.NoError(t, err) + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, metadata.RuntimeStatus) + assert.ErrorIs(t, c.SuspendOrchestration(ctx, id, "too late"), api.ErrInvalidState) + + parent, err := c.ScheduleNewOrchestration(ctx, "WaitingParent") + require.NoError(t, err) + child := parent + "-child" + require.Eventually(t, func() bool { + m, err := c.FetchOrchestrationMetadata(ctx, child) + return err == nil && m.RuntimeStatus == api.RUNTIME_STATUS_RUNNING + }, 10*time.Second, 10*time.Millisecond) + require.NoError(t, c.TerminateOrchestration(ctx, parent, api.WithOutput("stopped"), api.WithRecursiveTerminate(true))) + for _, instance := range []api.InstanceID{parent, child} { + metadata, err := c.WaitForOrchestrationCompletion(ctx, instance) + require.NoError(t, err) + assert.Equal(t, api.RUNTIME_STATUS_TERMINATED, metadata.RuntimeStatus, instance) + } +} + +func TestInstanceManagement(t *testing.T) { + r := task.NewTaskRegistry() + require.NoError(t, r.AddOrchestratorN("Echo", func(ctx *task.OrchestrationContext) (any, error) { + var input string + err := ctx.GetInput(&input) + return input, err + })) + host := durabletasktest.New(t, r) + ctx := testContext(t) + c := host.Client() + + for i := range 3 { + run(t, host, "Echo", api.WithInstanceID(api.InstanceID(fmt.Sprintf("echo-%d", i))), api.WithInput("hi")) + } + + _, err := c.ScheduleNewOrchestration(ctx, "Echo", api.WithInstanceID("echo-0")) + assert.ErrorIs(t, err, api.ErrDuplicateInstance) + _, err = c.FetchOrchestrationMetadata(ctx, "missing") + assert.ErrorIs(t, err, api.ErrInstanceNotFound) + + page, err := c.QueryInstances(ctx, api.OrchestrationQuery{InstanceIDPrefix: "echo-", PageSize: 2, FetchInputsAndOutputs: true}) + require.NoError(t, err) + require.Len(t, page.Orchestrations, 2) + assert.Equal(t, `"hi"`, page.Orchestrations[0].SerializedOutput) + require.NotEmpty(t, page.ContinuationToken) + page, err = c.QueryInstances(ctx, api.OrchestrationQuery{InstanceIDPrefix: "echo-", PageSize: 2, ContinuationToken: page.ContinuationToken}) + require.NoError(t, err) + require.Len(t, page.Orchestrations, 1) + assert.Empty(t, page.ContinuationToken) + + ids, err := c.ListInstanceIDs(ctx, api.InstanceIDQuery{RuntimeStatus: []api.OrchestrationStatus{api.RUNTIME_STATUS_COMPLETED}}) + require.NoError(t, err) + assert.ElementsMatch(t, []api.InstanceID{"echo-0", "echo-1", "echo-2"}, ids.InstanceIDs) + + restarted, err := c.RestartInstance(ctx, "echo-0", api.WithRestartNewInstanceID(true)) + require.NoError(t, err) + assert.NotEqual(t, api.InstanceID("echo-0"), restarted) + metadata, err := c.WaitForOrchestrationCompletion(ctx, restarted) + require.NoError(t, err) + assert.Equal(t, `"hi"`, metadata.SerializedOutput) + + require.NoError(t, c.PurgeOrchestrationState(ctx, "echo-0")) + assert.ErrorIs(t, c.PurgeOrchestrationState(ctx, "echo-0"), api.ErrInstanceNotFound) + result, err := c.PurgeInstances(ctx, api.PurgeInstancesRequest{InstanceIDs: []api.InstanceID{"echo-1", "echo-2"}}) + require.NoError(t, err) + assert.Equal(t, 2, result.DeletedInstanceCount) + result, err = c.PurgeInstances(ctx, api.PurgeInstancesRequest{Filter: &api.PurgeInstanceFilter{ + RuntimeStatus: []api.OrchestrationStatus{api.RUNTIME_STATUS_COMPLETED}, + }}) + require.NoError(t, err) + assert.Equal(t, 1, result.DeletedInstanceCount) + assert.True(t, result.IsComplete) +} + +func TestUnsupportedFeatures(t *testing.T) { + r := task.NewTaskRegistry() + require.NoError(t, r.AddOrchestratorN("CallsEntity", func(ctx *task.OrchestrationContext) (any, error) { + return nil, ctx.CallEntity(api.NewEntityID("counter", "a"), "add").Await(nil) + })) + host := durabletasktest.New(t, r) + ctx := testContext(t) + + metadata := run(t, host, "CallsEntity") + require.Equal(t, api.RUNTIME_STATUS_FAILED, metadata.RuntimeStatus) + require.NotNil(t, metadata.FailureDetails) + assert.Contains(t, metadata.FailureDetails.ErrorMessage, "not supported") + + err := host.Client().SignalEntity(ctx, api.NewEntityID("counter", "a"), "add") + assert.ErrorIs(t, err, api.ErrFeatureNotSupported) + assert.ErrorIs(t, host.Client().RewindInstance(ctx, metadata.InstanceID), api.ErrFeatureNotSupported) +} + +func TestQueryByTaskHubNameIsNotSupported(t *testing.T) { + host := durabletasktest.New(t, task.NewTaskRegistry()) + + _, err := host.Client().QueryInstances(testContext(t), api.OrchestrationQuery{TaskHubNames: []string{"hub"}}) + assert.ErrorIs(t, err, api.ErrFeatureNotSupported) +} diff --git a/internal/inmemory/limits.go b/internal/inmemory/limits.go new file mode 100644 index 00000000..53b1062d --- /dev/null +++ b/internal/inmemory/limits.go @@ -0,0 +1,66 @@ +package inmemory + +import ( + "context" + "fmt" + "math" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" + + "github.com/microsoft/durabletask-go/internal/protos" +) + +// maxMessageSize is the Durable Task Scheduler's 4 MiB gRPC receive limit, +// which the service enforces on requests itself. +const maxMessageSize = 4 << 20 + +// errorTypeActivityResponseTooLarge identifies an activity whose completion +// exceeded maxMessageSize. +const errorTypeActivityResponseTooLarge = "ActivityResponseTooLarge" + +// selfLimitedMethods check their request size themselves. They fail the work +// item instead of rejecting the call, because a worker abandons a work item +// whose completion is rejected and the service would dispatch it again forever. +var selfLimitedMethods = map[string]bool{ + protos.TaskHubSidecarService_CompleteActivityTask_FullMethodName: true, +} + +// ServerOptions returns the gRPC server options for the service. The transport +// accepts large messages so that oversized completions reach the service, which +// enforces the 4 MiB request limit itself. +func ServerOptions() []grpc.ServerOption { + return []grpc.ServerOption{ + grpc.MaxRecvMsgSize(math.MaxInt32), + grpc.UnaryInterceptor(limitRequestSize), + } +} + +func limitRequestSize(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { + if msg, ok := req.(proto.Message); ok && !selfLimitedMethods[info.FullMethod] { + if size := proto.Size(msg); size > maxMessageSize { + return nil, status.Errorf(codes.ResourceExhausted, + "grpc: received message larger than max (%d vs. %d)", size, maxMessageSize) + } + } + return handler(ctx, req) +} + +// oversizedCompletionFailure returns a non-retriable failure with the given +// error type when a worker's completion exceeds maxMessageSize, or nil when it +// fits. kind describes the completion in the failure message. +func oversizedCompletionFailure(errorType, kind string, completion proto.Message) *protos.TaskFailureDetails { + size := proto.Size(completion) + if size <= maxMessageSize { + return nil + } + return &protos.TaskFailureDetails{ + ErrorType: errorType, + ErrorMessage: fmt.Sprintf( + "the %d-byte %s exceeds the %d-byte gRPC message limit of the Durable Task service", + size, kind, maxMessageSize), + IsNonRetriable: true, + } +} diff --git a/internal/inmemory/query.go b/internal/inmemory/query.go new file mode 100644 index 00000000..2293c8a2 --- /dev/null +++ b/internal/inmemory/query.go @@ -0,0 +1,229 @@ +package inmemory + +import ( + "cmp" + "context" + "encoding/base64" + "slices" + "strconv" + "strings" + "time" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/timestamppb" + "google.golang.org/protobuf/types/known/wrapperspb" + + "github.com/microsoft/durabletask-go/internal/grpcerrors" + "github.com/microsoft/durabletask-go/internal/protos" +) + +// QueryInstances returns instances that match a query, ordered by creation time. +func (s *Server) QueryInstances(_ context.Context, req *protos.QueryInstancesRequest) (*protos.QueryInstancesResponse, error) { + query := req.GetQuery() + if len(query.GetTaskHubNames()) > 0 { + // The in-memory service has no task hub identity, so it can't scope a query to one. + return nil, grpcerrors.New(codes.Unimplemented, + "filtering queries by task hub name is not supported by the in-memory test backend", + grpcerrors.ReasonFeatureUnsupported) + } + var cursorTime time.Time + var cursorID string + if token := query.GetContinuationToken().GetValue(); token != "" { + var err error + cursorTime, cursorID, err = decodeInstanceCursor(token) + if err != nil { + return nil, status.Errorf(codes.InvalidArgument, "invalid continuation token %q", token) + } + } + pageSize := int(query.GetMaxInstanceCount()) + if pageSize <= 0 { + pageSize = defaultQueryPageSize + } + + s.mu.Lock() + defer s.mu.Unlock() + var matches []*instance + for _, inst := range s.instances { + if len(query.GetRuntimeStatus()) > 0 && !slices.Contains(query.GetRuntimeStatus(), inst.status) { + continue + } + if !inRange(inst.createdAt, query.GetCreatedTimeFrom(), query.GetCreatedTimeTo()) { + continue + } + if prefix := query.GetInstanceIdPrefix().GetValue(); prefix != "" && !strings.HasPrefix(inst.id, prefix) { + continue + } + matches = append(matches, inst) + } + slices.SortFunc(matches, func(a, b *instance) int { + return cmp.Or(a.createdAt.Compare(b.createdAt), cmp.Compare(a.id, b.id)) + }) + + resp := &protos.QueryInstancesResponse{} + start := 0 + if cursorID != "" { + start = slices.IndexFunc(matches, func(inst *instance) bool { + return cmp.Or(inst.createdAt.Compare(cursorTime), cmp.Compare(inst.id, cursorID)) > 0 + }) + if start < 0 { + start = len(matches) + } + } + end := min(start+pageSize, len(matches)) + for _, inst := range matches[start:end] { + resp.OrchestrationState = append(resp.OrchestrationState, inst.state(query.GetFetchInputsAndOutputs())) + } + if end < len(matches) { + last := matches[end-1] + resp.ContinuationToken = wrapperspb.String(encodeInstanceCursor(last.createdAt, last.id)) + } + return resp, nil +} + +func encodeInstanceCursor(createdAt time.Time, instanceID string) string { + id := base64.RawURLEncoding.EncodeToString([]byte(instanceID)) + return strconv.FormatInt(createdAt.UnixNano(), 10) + ":" + id +} + +func decodeInstanceCursor(token string) (time.Time, string, error) { + timestamp, encodedID, ok := strings.Cut(token, ":") + if !ok { + return time.Time{}, "", status.Error(codes.InvalidArgument, "missing cursor separator") + } + nanos, err := strconv.ParseInt(timestamp, 10, 64) + if err != nil { + return time.Time{}, "", err + } + id, err := base64.RawURLEncoding.DecodeString(encodedID) + if err != nil || len(id) == 0 { + return time.Time{}, "", status.Error(codes.InvalidArgument, "invalid cursor instance ID") + } + return time.Unix(0, nanos), string(id), nil +} + +// ListInstanceIds returns IDs of terminal instances, ordered by completion time. +func (s *Server) ListInstanceIds(_ context.Context, req *protos.ListInstanceIdsRequest) (*protos.ListInstanceIdsResponse, error) { + pageSize := int(req.GetPageSize()) + if pageSize <= 0 { + pageSize = defaultQueryPageSize + } + var cursorTime time.Time + var cursorID string + if token := req.GetLastInstanceKey().GetValue(); token != "" { + var err error + cursorTime, cursorID, err = decodeInstanceCursor(token) + if err != nil { + return nil, status.Errorf(codes.InvalidArgument, "invalid continuation token %q", token) + } + } + + s.mu.Lock() + defer s.mu.Unlock() + var matches []*instance + for _, inst := range s.instances { + if !isTerminal(inst.status) { + continue + } + if len(req.GetRuntimeStatus()) > 0 && !slices.Contains(req.GetRuntimeStatus(), inst.status) { + continue + } + if !inRange(inst.completedAt, req.GetCompletedTimeFrom(), req.GetCompletedTimeTo()) { + continue + } + matches = append(matches, inst) + } + slices.SortFunc(matches, func(a, b *instance) int { + return cmp.Or(a.completedAt.Compare(b.completedAt), cmp.Compare(a.id, b.id)) + }) + + start := 0 + if cursorID != "" { + start = slices.IndexFunc(matches, func(inst *instance) bool { + return cmp.Or(inst.completedAt.Compare(cursorTime), cmp.Compare(inst.id, cursorID)) > 0 + }) + if start < 0 { + start = len(matches) + } + } + resp := &protos.ListInstanceIdsResponse{} + end := min(start+pageSize, len(matches)) + for _, inst := range matches[start:end] { + resp.InstanceIds = append(resp.InstanceIds, inst.id) + } + if end < len(matches) { + last := matches[end-1] + resp.LastInstanceKey = wrapperspb.String(encodeInstanceCursor(last.completedAt, last.id)) + } + return resp, nil +} + +// PurgeInstances deletes terminal instances and, optionally, their sub-orchestrations. +func (s *Server) PurgeInstances(_ context.Context, req *protos.PurgeInstancesRequest) (*protos.PurgeInstancesResponse, error) { + s.mu.Lock() + defer s.mu.Unlock() + deleted := 0 + switch r := req.GetRequest().(type) { + case *protos.PurgeInstancesRequest_InstanceId: + inst, ok := s.instances[r.InstanceId] + if ok && !isTerminal(inst.status) { + return nil, notCompletedError(inst.id) + } + if ok { + deleted = s.purgeLocked(inst, req.GetRecursive()) + } + case *protos.PurgeInstancesRequest_InstanceBatch: + for _, id := range r.InstanceBatch.GetInstanceIds() { + if inst, ok := s.instances[id]; ok && isTerminal(inst.status) { + deleted += s.purgeLocked(inst, req.GetRecursive()) + } + } + case *protos.PurgeInstancesRequest_PurgeInstanceFilter: + filter := r.PurgeInstanceFilter + var matches []*instance + for _, inst := range s.instances { + if !isTerminal(inst.status) || + (len(filter.GetRuntimeStatus()) > 0 && !slices.Contains(filter.GetRuntimeStatus(), inst.status)) || + !inRange(inst.createdAt, filter.GetCreatedTimeFrom(), filter.GetCreatedTimeTo()) { + continue + } + matches = append(matches, inst) + } + for _, inst := range matches { + if s.instances[inst.id] == inst { + deleted += s.purgeLocked(inst, req.GetRecursive()) + } + } + default: + return nil, status.Error(codes.InvalidArgument, "a purge request must specify an instance ID, batch, or filter") + } + if deleted > 0 { + s.notifyLocked() + } + return &protos.PurgeInstancesResponse{DeletedInstanceCount: int32(deleted), IsComplete: wrapperspb.Bool(true)}, nil +} + +func (s *Server) purgeLocked(inst *instance, recursive bool) int { + inst.stopTimers() + delete(s.instances, inst.id) + deleted := 1 + if recursive { + for _, childID := range inst.children { + if child, ok := s.instances[childID]; ok && isTerminal(child.status) && + child.parent.GetOrchestrationInstance().GetInstanceId() == inst.id { + deleted += s.purgeLocked(child, true) + } + } + } + return deleted +} + +func inRange(t time.Time, from, to *timestamppb.Timestamp) bool { + if from != nil && t.Before(from.AsTime()) { + return false + } + if to != nil && t.After(to.AsTime()) { + return false + } + return true +} diff --git a/internal/inmemory/query_test.go b/internal/inmemory/query_test.go new file mode 100644 index 00000000..855f42e0 --- /dev/null +++ b/internal/inmemory/query_test.go @@ -0,0 +1,95 @@ +package inmemory + +import ( + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/microsoft/durabletask-go/internal/protos" +) + +func TestQueryInstancesContinuesAfterLastResultChanges(t *testing.T) { + for _, change := range []string{"purge", "restart"} { + t.Run(change, func(t *testing.T) { + s, createdAt := queryTestServer() + defer s.Close() + + first, err := s.QueryInstances(t.Context(), &protos.QueryInstancesRequest{ + Query: &protos.InstanceQuery{MaxInstanceCount: 1}, + }) + require.NoError(t, err) + require.Len(t, first.GetOrchestrationState(), 1) + require.Equal(t, "a", first.GetOrchestrationState()[0].GetInstanceId()) + + switch change { + case "purge": + _, err = s.PurgeInstances(t.Context(), &protos.PurgeInstancesRequest{ + Request: &protos.PurgeInstancesRequest_InstanceId{InstanceId: "a"}, + }) + require.NoError(t, err) + case "restart": + s.mu.Lock() + s.instances["a"].createdAt = createdAt.Add(4 * time.Second) + s.mu.Unlock() + } + + second, err := s.QueryInstances(t.Context(), &protos.QueryInstancesRequest{ + Query: &protos.InstanceQuery{ + MaxInstanceCount: 1, + ContinuationToken: first.GetContinuationToken(), + }, + }) + require.NoError(t, err) + require.Len(t, second.GetOrchestrationState(), 1) + require.Equal(t, "b", second.GetOrchestrationState()[0].GetInstanceId()) + }) + } +} + +func TestListInstanceIDsContinuesAfterLastResultChanges(t *testing.T) { + for _, change := range []string{"purge", "restart"} { + t.Run(change, func(t *testing.T) { + s, createdAt := queryTestServer() + defer s.Close() + + first, err := s.ListInstanceIds(t.Context(), &protos.ListInstanceIdsRequest{PageSize: 1}) + require.NoError(t, err) + require.Equal(t, []string{"a"}, first.GetInstanceIds()) + + switch change { + case "purge": + _, err = s.PurgeInstances(t.Context(), &protos.PurgeInstancesRequest{ + Request: &protos.PurgeInstancesRequest_InstanceId{InstanceId: "a"}, + }) + require.NoError(t, err) + case "restart": + s.mu.Lock() + s.instances["a"].completedAt = createdAt.Add(4 * time.Second) + s.mu.Unlock() + } + + second, err := s.ListInstanceIds(t.Context(), &protos.ListInstanceIdsRequest{ + PageSize: 1, + LastInstanceKey: first.GetLastInstanceKey(), + }) + require.NoError(t, err) + require.Equal(t, []string{"b"}, second.GetInstanceIds()) + }) + } +} + +func queryTestServer() (*Server, time.Time) { + s := NewServer() + base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + for i, id := range []string{"a", "b", "c"} { + when := base.Add(time.Duration(i) * time.Second) + s.instances[id] = &instance{ + id: id, + status: protos.OrchestrationStatus_ORCHESTRATION_STATUS_COMPLETED, + createdAt: when, + completedAt: when, + } + } + return s, base +} diff --git a/internal/inmemory/server.go b/internal/inmemory/server.go new file mode 100644 index 00000000..855a56b4 --- /dev/null +++ b/internal/inmemory/server.go @@ -0,0 +1,532 @@ +// Package inmemory implements an in-memory Durable Task sidecar service for tests. +// +// The service keeps all orchestration state in process memory and serves the +// same gRPC protocol as the Durable Task Scheduler, so the regular client and +// worker can run against it. Timers fire in real time. Entities and rewind are +// not supported. +package inmemory + +import ( + "context" + "fmt" + "slices" + "sync" + "time" + + "github.com/google/uuid" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/emptypb" + "google.golang.org/protobuf/types/known/timestamppb" + "google.golang.org/protobuf/types/known/wrapperspb" + + "github.com/microsoft/durabletask-go/api" + "github.com/microsoft/durabletask-go/internal/grpcerrors" + "github.com/microsoft/durabletask-go/internal/helpers" + "github.com/microsoft/durabletask-go/internal/protos" +) + +const ( + defaultHealthPingInterval = 30 * time.Second + defaultQueryPageSize = 100 + maxOrchestrationWorkItemSize = 4 << 20 + maxHistoryChunkSize = 4 << 20 +) + +// Server is an in-memory implementation of the TaskHubSidecarService. +type Server struct { + protos.UnimplementedTaskHubSidecarServiceServer + + healthPingInterval time.Duration + + mu sync.Mutex + instances map[string]*instance + orchQueue []*instance + actQueue []*activityItem + orchLeases map[string]*orchestrationLease + actLeases map[string]*activityLease + changed chan struct{} + closed bool + nextStreamID uint64 +} + +type instance struct { + id string + name string + version *wrapperspb.StringValue + status protos.OrchestrationStatus + input *wrapperspb.StringValue + output *wrapperspb.StringValue + customStatus *wrapperspb.StringValue + failure *protos.TaskFailureDetails + tags map[string]string + parent *protos.ParentInstanceInfo + traceContext *protos.TraceContext + createdAt time.Time + updatedAt time.Time + completedAt time.Time + scheduledStart *timestamppb.Timestamp + executionID string + + history []*protos.HistoryEvent + pending []*protos.HistoryEvent + + // started is set once the first orchestration turn commits. Suspension + // changes status but not whether the instance has started. + started bool + leased bool + queued bool + children []string + timers []*time.Timer +} + +type activityItem struct { + inst *instance + executionID string + request *protos.ActivityRequest +} + +type orchestrationLease struct { + inst *instance + events []*protos.HistoryEvent + streamID uint64 +} + +type activityLease struct { + item *activityItem + streamID uint64 +} + +// NewServer creates an empty in-memory service. +func NewServer() *Server { + return &Server{ + healthPingInterval: defaultHealthPingInterval, + instances: make(map[string]*instance), + orchLeases: make(map[string]*orchestrationLease), + actLeases: make(map[string]*activityLease), + changed: make(chan struct{}), + } +} + +// Register registers the service with a gRPC server. +func (s *Server) Register(registrar grpc.ServiceRegistrar) { + protos.RegisterTaskHubSidecarServiceServer(registrar, s) +} + +// Close stops timers and ends all open work item streams and waiters. +func (s *Server) Close() { + s.mu.Lock() + defer s.mu.Unlock() + if s.closed { + return + } + s.closed = true + for _, inst := range s.instances { + inst.stopTimers() + } + s.notifyLocked() +} + +func (s *Server) notifyLocked() { + close(s.changed) + s.changed = make(chan struct{}) +} + +func isTerminal(status protos.OrchestrationStatus) bool { + switch status { + case protos.OrchestrationStatus_ORCHESTRATION_STATUS_COMPLETED, + protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, + protos.OrchestrationStatus_ORCHESTRATION_STATUS_TERMINATED, + protos.OrchestrationStatus_ORCHESTRATION_STATUS_CANCELED: + return true + default: + return false + } +} + +func newID() string { + if u, err := uuid.NewV7(); err == nil { + return u.String() + } + return uuid.NewString() +} + +func (inst *instance) stopTimers() { + for _, t := range inst.timers { + t.Stop() + } + inst.timers = nil +} + +func (inst *instance) state(includePayloads bool) *protos.OrchestrationState { + state := &protos.OrchestrationState{ + InstanceId: inst.id, + Name: inst.name, + Version: inst.version, + OrchestrationStatus: inst.status, + ScheduledStartTimestamp: inst.scheduledStart, + CreatedTimestamp: timestamppb.New(inst.createdAt), + LastUpdatedTimestamp: timestamppb.New(inst.updatedAt), + CustomStatus: inst.customStatus, + FailureDetails: inst.failure, + ExecutionId: wrapperspb.String(inst.executionID), + Tags: inst.tags, + } + if includePayloads { + state.Input = inst.input + state.Output = inst.output + } + if !inst.completedAt.IsZero() { + state.CompletedTimestamp = timestamppb.New(inst.completedAt) + } + if parentID := inst.parent.GetOrchestrationInstance().GetInstanceId(); parentID != "" { + state.ParentInstanceId = wrapperspb.String(parentID) + } + return state +} + +// newInstanceLocked creates a pending instance, replacing any existing instance +// with the same ID, and queues its first work item. +func (s *Server) newInstanceLocked( + id, name string, + version, input *wrapperspb.StringValue, + tags map[string]string, + parent *protos.ParentInstanceInfo, + traceContext *protos.TraceContext, + scheduledStart *timestamppb.Timestamp, +) *instance { + now := time.Now() + inst := &instance{ + id: id, + name: name, + version: version, + status: protos.OrchestrationStatus_ORCHESTRATION_STATUS_PENDING, + input: input, + tags: tags, + parent: parent, + traceContext: traceContext, + createdAt: now, + updatedAt: now, + scheduledStart: scheduledStart, + } + if old, ok := s.instances[id]; ok { + old.stopTimers() + } + s.instances[id] = inst + inst.pending = []*protos.HistoryEvent{inst.newExecutionStartedEvent()} + if scheduledStart != nil && scheduledStart.AsTime().After(now) { + s.startTimerLocked(inst, scheduledStart.AsTime(), func() { s.enqueueLocked(inst) }) + } else { + s.enqueueLocked(inst) + } + s.notifyLocked() + return inst +} + +// newExecutionStartedEvent assigns a new execution ID and returns its start event. +func (inst *instance) newExecutionStartedEvent() *protos.HistoryEvent { + event := helpers.NewExecutionStartedEvent( + inst.name, inst.id, inst.input, inst.parent, inst.traceContext, inst.scheduledStart, inst.version) + started := event.GetExecutionStarted() + started.Tags = inst.tags + inst.executionID = started.GetOrchestrationInstance().GetExecutionId().GetValue() + return event +} + +// startTimerLocked runs fn under the server lock at the given time, unless the +// instance has been replaced or purged, its execution has changed, or the +// server has been closed. +func (s *Server) startTimerLocked(inst *instance, at time.Time, fn func()) { + executionID := inst.executionID + timer := time.AfterFunc(time.Until(at), func() { + s.mu.Lock() + defer s.mu.Unlock() + if s.closed || s.instances[inst.id] != inst || inst.executionID != executionID { + return + } + fn() + s.notifyLocked() + }) + inst.timers = append(inst.timers, timer) +} + +func (s *Server) enqueueLocked(inst *instance) { + if inst.queued || inst.leased || len(inst.pending) == 0 || s.instances[inst.id] != inst { + return + } + if inst.scheduledStart != nil && len(inst.history) == 0 && inst.scheduledStart.AsTime().After(time.Now()) { + return + } + inst.queued = true + s.orchQueue = append(s.orchQueue, inst) + s.notifyLocked() +} + +// deliverLocked adds a new event to an active instance's inbox. +func (s *Server) deliverLocked(inst *instance, event *protos.HistoryEvent) { + if isTerminal(inst.status) { + return + } + inst.pending = append(inst.pending, event) + inst.updatedAt = time.Now() + s.enqueueLocked(inst) +} + +// Hello implements the service handshake. +func (s *Server) Hello(context.Context, *emptypb.Empty) (*emptypb.Empty, error) { + return &emptypb.Empty{}, nil +} + +// StartInstance creates a new orchestration instance. +func (s *Server) StartInstance(_ context.Context, req *protos.CreateInstanceRequest) (*protos.CreateInstanceResponse, error) { + if req.GetName() == "" { + return nil, status.Error(codes.InvalidArgument, "orchestration name is required") + } + id := req.GetInstanceId() + if id == "" { + id = newID() + } + s.mu.Lock() + defer s.mu.Unlock() + if existing, ok := s.instances[id]; ok { + replaceable := req.GetOrchestrationIdReusePolicy().GetReplaceableStatus() + if !slices.Contains(replaceable, existing.status) { + return nil, status.Errorf(codes.AlreadyExists, "orchestration instance %q already exists", id) + } + } + s.newInstanceLocked(id, req.GetName(), req.GetVersion(), req.GetInput(), req.GetTags(), + nil, req.GetParentTraceContext(), req.GetScheduledStartTimestamp()) + return &protos.CreateInstanceResponse{InstanceId: id}, nil +} + +// GetInstance returns an instance's current state. +func (s *Server) GetInstance(_ context.Context, req *protos.GetInstanceRequest) (*protos.GetInstanceResponse, error) { + s.mu.Lock() + defer s.mu.Unlock() + return s.getInstanceLocked(req), nil +} + +func (s *Server) getInstanceLocked(req *protos.GetInstanceRequest) *protos.GetInstanceResponse { + inst, ok := s.instances[req.GetInstanceId()] + if !ok { + return &protos.GetInstanceResponse{Exists: false} + } + return &protos.GetInstanceResponse{Exists: true, OrchestrationState: inst.state(req.GetGetInputsAndOutputs())} +} + +// WaitForInstanceStart blocks until the instance starts running or ends. +func (s *Server) WaitForInstanceStart(ctx context.Context, req *protos.GetInstanceRequest) (*protos.GetInstanceResponse, error) { + return s.waitForInstance(ctx, req, func(inst *instance) bool { + return inst.started || isTerminal(inst.status) + }) +} + +// WaitForInstanceCompletion blocks until the instance reaches a terminal state. +func (s *Server) WaitForInstanceCompletion(ctx context.Context, req *protos.GetInstanceRequest) (*protos.GetInstanceResponse, error) { + return s.waitForInstance(ctx, req, func(inst *instance) bool { + return isTerminal(inst.status) + }) +} + +func (s *Server) waitForInstance( + ctx context.Context, + req *protos.GetInstanceRequest, + done func(*instance) bool, +) (*protos.GetInstanceResponse, error) { + for { + s.mu.Lock() + inst, ok := s.instances[req.GetInstanceId()] + if !ok || done(inst) { + resp := s.getInstanceLocked(req) + s.mu.Unlock() + return resp, nil + } + changed, closed := s.changed, s.closed + s.mu.Unlock() + if closed { + return nil, status.Error(codes.Unavailable, "in-memory service is closed") + } + select { + case <-ctx.Done(): + return nil, status.FromContextError(ctx.Err()).Err() + case <-changed: + } + } +} + +// RaiseEvent delivers an external event to an instance. +func (s *Server) RaiseEvent(_ context.Context, req *protos.RaiseEventRequest) (*protos.RaiseEventResponse, error) { + s.mu.Lock() + defer s.mu.Unlock() + inst, err := s.lookupLocked(req.GetInstanceId()) + if err != nil { + return nil, err + } + s.deliverLocked(inst, helpers.NewEventRaisedEvent(req.GetName(), req.GetInput())) + return &protos.RaiseEventResponse{}, nil +} + +// TerminateInstance terminates an instance and, optionally, its sub-orchestrations. +func (s *Server) TerminateInstance(_ context.Context, req *protos.TerminateRequest) (*protos.TerminateResponse, error) { + s.mu.Lock() + defer s.mu.Unlock() + inst, err := s.lookupLocked(req.GetInstanceId()) + if err != nil { + return nil, err + } + s.terminateLocked(inst, req.GetOutput(), req.GetRecursive()) + return &protos.TerminateResponse{}, nil +} + +func (s *Server) terminateLocked(inst *instance, reason *wrapperspb.StringValue, recursive bool) { + if isTerminal(inst.status) { + return + } + if recursive { + for _, childID := range inst.children { + if child, ok := s.instances[childID]; ok && + child.parent.GetOrchestrationInstance().GetInstanceId() == inst.id { + s.terminateLocked(child, reason, true) + } + } + } + terminated := helpers.NewExecutionTerminatedEvent(reason, recursive) + if len(inst.history) == 0 && !inst.leased && len(inst.pending) > 0 { + // The orchestrator never ran, so complete the termination without a worker. + inst.history = append(inst.history, inst.pending[0], terminated) + s.completeLocked(inst, protos.OrchestrationStatus_ORCHESTRATION_STATUS_TERMINATED, reason, nil) + return + } + s.deliverLocked(inst, terminated) +} + +// recursiveTermination returns a recursive termination that the instance has +// received but whose turn hasn't ended the instance yet, if any. +func (inst *instance) recursiveTermination() *protos.ExecutionTerminatedEvent { + for _, events := range [][]*protos.HistoryEvent{inst.history, inst.pending} { + for _, event := range events { + if terminated := event.GetExecutionTerminated(); terminated.GetRecurse() { + return terminated + } + } + } + return nil +} + +// SuspendInstance suspends a running instance. +func (s *Server) SuspendInstance(_ context.Context, req *protos.SuspendRequest) (*protos.SuspendResponse, error) { + s.mu.Lock() + defer s.mu.Unlock() + inst, err := s.lookupLocked(req.GetInstanceId()) + if err != nil { + return nil, err + } + if isTerminal(inst.status) { + return nil, grpcerrors.New(codes.FailedPrecondition, fmt.Sprintf("orchestration instance %q has already completed", inst.id), grpcerrors.ReasonInvalidState) + } + if inst.status != protos.OrchestrationStatus_ORCHESTRATION_STATUS_SUSPENDED { + inst.status = protos.OrchestrationStatus_ORCHESTRATION_STATUS_SUSPENDED + s.deliverLocked(inst, helpers.NewSuspendOrchestrationEvent(req.GetReason().GetValue())) + s.notifyLocked() + } + return &protos.SuspendResponse{}, nil +} + +// ResumeInstance resumes a suspended instance. +func (s *Server) ResumeInstance(_ context.Context, req *protos.ResumeRequest) (*protos.ResumeResponse, error) { + s.mu.Lock() + defer s.mu.Unlock() + inst, err := s.lookupLocked(req.GetInstanceId()) + if err != nil { + return nil, err + } + if isTerminal(inst.status) { + return nil, grpcerrors.New(codes.FailedPrecondition, fmt.Sprintf("orchestration instance %q has already completed", inst.id), grpcerrors.ReasonInvalidState) + } + if inst.status == protos.OrchestrationStatus_ORCHESTRATION_STATUS_SUSPENDED { + inst.status = protos.OrchestrationStatus_ORCHESTRATION_STATUS_PENDING + if inst.started { + inst.status = protos.OrchestrationStatus_ORCHESTRATION_STATUS_RUNNING + } + s.deliverLocked(inst, helpers.NewResumeOrchestrationEvent(req.GetReason().GetValue())) + s.notifyLocked() + } + return &protos.ResumeResponse{}, nil +} + +// RestartInstance starts a terminal instance again with its original input. +func (s *Server) RestartInstance(_ context.Context, req *protos.RestartInstanceRequest) (*protos.RestartInstanceResponse, error) { + s.mu.Lock() + defer s.mu.Unlock() + inst, err := s.lookupLocked(req.GetInstanceId()) + if err != nil { + return nil, err + } + if !isTerminal(inst.status) { + return nil, notCompletedError(inst.id) + } + id := inst.id + if req.GetRestartWithNewInstanceId() { + id = newID() + } + s.newInstanceLocked(id, inst.name, inst.version, inst.input, inst.tags, nil, inst.traceContext, nil) + return &protos.RestartInstanceResponse{InstanceId: id}, nil +} + +func (s *Server) lookupLocked(id string) (*instance, error) { + inst, ok := s.instances[id] + if !ok { + return nil, status.Errorf(codes.NotFound, "orchestration instance %q not found", id) + } + return inst, nil +} + +// StreamInstanceHistory streams an instance's committed history. +func (s *Server) StreamInstanceHistory( + req *protos.StreamInstanceHistoryRequest, + stream grpc.ServerStreamingServer[protos.HistoryChunk], +) error { + s.mu.Lock() + inst, ok := s.instances[req.GetInstanceId()] + if !ok || (req.GetExecutionId() != nil && req.GetExecutionId().GetValue() != inst.executionID) { + s.mu.Unlock() + return status.Errorf(codes.NotFound, "orchestration instance %q not found", req.GetInstanceId()) + } + history := slices.Clone(inst.history) + s.mu.Unlock() + + chunk := &protos.HistoryChunk{} + chunkSize := 0 + for _, event := range history { + eventSize := proto.Size(event) + encodedSize := protowire.SizeTag(1) + protowire.SizeBytes(eventSize) + if encodedSize > maxHistoryChunkSize { + return status.Errorf(codes.ResourceExhausted, "history event exceeds the %d-byte stream chunk limit", maxHistoryChunkSize) + } + if len(chunk.Events) > 0 && chunkSize+encodedSize > maxHistoryChunkSize { + if err := stream.Send(chunk); err != nil { + return err + } + chunk = &protos.HistoryChunk{} + chunkSize = 0 + } + chunk.Events = append(chunk.Events, event) + chunkSize += encodedSize + } + if len(chunk.Events) > 0 { + return stream.Send(chunk) + } + return nil +} + +func failureDetails(errorType, format string, args ...any) *protos.TaskFailureDetails { + return &protos.TaskFailureDetails{ErrorType: errorType, ErrorMessage: fmt.Sprintf(format, args...)} +} + +// notCompletedError maps to api.ErrNotCompleted in the client. +func notCompletedError(id string) error { + return grpcerrors.New(codes.FailedPrecondition, fmt.Sprintf("%s: instance %q", api.ErrNotCompleted, id), grpcerrors.ReasonNotCompleted) +} diff --git a/internal/inmemory/server_test.go b/internal/inmemory/server_test.go new file mode 100644 index 00000000..ca66d5e2 --- /dev/null +++ b/internal/inmemory/server_test.go @@ -0,0 +1,54 @@ +package inmemory + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/timestamppb" + + "github.com/microsoft/durabletask-go/internal/protos" +) + +func TestSuspendAndResumeBeforeScheduledStart(t *testing.T) { + s := NewServer() + defer s.Close() + ctx := t.Context() + + _, err := s.StartInstance(ctx, &protos.CreateInstanceRequest{ + InstanceId: "id", + Name: "orchestrator", + ScheduledStartTimestamp: timestamppb.New(time.Now().Add(time.Hour)), + }) + require.NoError(t, err) + getReq := &protos.GetInstanceRequest{InstanceId: "id"} + waitForStart := func() error { + waitCtx, cancel := context.WithTimeout(ctx, 20*time.Millisecond) + defer cancel() + _, err := s.WaitForInstanceStart(waitCtx, getReq) + return err + } + + _, err = s.SuspendInstance(ctx, &protos.SuspendRequest{InstanceId: "id"}) + require.NoError(t, err) + assert.Equal(t, codes.DeadlineExceeded, status.Code(waitForStart()), "a suspended instance has not started") + + _, err = s.ResumeInstance(ctx, &protos.ResumeRequest{InstanceId: "id"}) + require.NoError(t, err) + resp, err := s.GetInstance(ctx, getReq) + require.NoError(t, err) + assert.Equal(t, protos.OrchestrationStatus_ORCHESTRATION_STATUS_PENDING, resp.GetOrchestrationState().GetOrchestrationStatus()) + assert.Equal(t, codes.DeadlineExceeded, status.Code(waitForStart())) + + _, err = s.SuspendInstance(ctx, &protos.SuspendRequest{InstanceId: "id"}) + require.NoError(t, err) + _, err = s.TerminateInstance(ctx, &protos.TerminateRequest{InstanceId: "id"}) + require.NoError(t, err) + resp, err = s.WaitForInstanceStart(ctx, getReq) + require.NoError(t, err) + assert.Equal(t, protos.OrchestrationStatus_ORCHESTRATION_STATUS_TERMINATED, resp.GetOrchestrationState().GetOrchestrationStatus()) +} diff --git a/internal/inmemory/work.go b/internal/inmemory/work.go new file mode 100644 index 00000000..9dfa6a69 --- /dev/null +++ b/internal/inmemory/work.go @@ -0,0 +1,622 @@ +package inmemory + +import ( + "context" + "fmt" + "slices" + "strings" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/timestamppb" + "google.golang.org/protobuf/types/known/wrapperspb" + + "github.com/microsoft/durabletask-go/internal/helpers" + "github.com/microsoft/durabletask-go/internal/protos" +) + +// GetWorkItems streams orchestration and activity work items to a worker. +// Work items that are still in flight when the stream ends are returned to the queue. +func (s *Server) GetWorkItems(req *protos.GetWorkItemsRequest, stream grpc.ServerStreamingServer[protos.WorkItem]) error { + ctx := stream.Context() + s.mu.Lock() + s.nextStreamID++ + streamID := s.nextStreamID + s.mu.Unlock() + defer s.releaseStream(streamID) + + filters := req.GetWorkItemFilters() + limits := workItemLimits{ + orchestrations: req.GetMaxConcurrentOrchestrationWorkItems(), + activities: req.GetMaxConcurrentActivityWorkItems(), + } + ping := time.NewTicker(s.healthPingInterval) + defer ping.Stop() + for { + s.mu.Lock() + if s.closed { + s.mu.Unlock() + return status.Error(codes.Unavailable, "in-memory service is closed") + } + item := s.nextWorkItemLocked(filters, streamID, limits) + changed := s.changed + s.mu.Unlock() + + if item != nil { + if err := stream.Send(item); err != nil { + return err + } + continue + } + select { + case <-ctx.Done(): + return nil + case <-ping.C: + if err := stream.Send(&protos.WorkItem{Request: &protos.WorkItem_HealthPing{HealthPing: &protos.HealthPing{}}}); err != nil { + return err + } + case <-changed: + } + } +} + +type workItemLimits struct { + orchestrations int32 + activities int32 +} + +func (s *Server) nextWorkItemLocked( + filters *protos.WorkItemFilters, + streamID uint64, + limits workItemLimits, +) *protos.WorkItem { + if streamHasCapacity(limits.orchestrations, countOrchestrationLeases(s.orchLeases, streamID)) { + for i, inst := range s.orchQueue { + if !matchesOrchestrationFilter(filters, inst) { + continue + } + s.orchQueue = slices.Delete(s.orchQueue, i, i+1) + inst.queued = false + if s.instances[inst.id] != inst || inst.leased || len(inst.pending) == 0 { + // A stale queue entry; look again from the start. + return s.nextWorkItemLocked(filters, streamID, limits) + } + if item := s.leaseOrchestrationLocked(inst, streamID); item != nil { + return item + } + return s.nextWorkItemLocked(filters, streamID, limits) + } + } + if streamHasCapacity(limits.activities, countActivityLeases(s.actLeases, streamID)) { + for i, item := range s.actQueue { + if !matchesActivityFilter(filters, item.request) { + continue + } + s.actQueue = slices.Delete(s.actQueue, i, i+1) + token := newID() + s.actLeases[token] = &activityLease{item: item, streamID: streamID} + return &protos.WorkItem{ + Request: &protos.WorkItem_ActivityRequest{ActivityRequest: item.request}, + CompletionToken: token, + } + } + } + return nil +} + +func streamHasCapacity(limit int32, inFlight int) bool { + return limit <= 0 || inFlight < int(limit) +} + +func countOrchestrationLeases(leases map[string]*orchestrationLease, streamID uint64) int { + count := 0 + for _, lease := range leases { + if lease.streamID == streamID { + count++ + } + } + return count +} + +func countActivityLeases(leases map[string]*activityLease, streamID uint64) int { + count := 0 + for _, lease := range leases { + if lease.streamID == streamID { + count++ + } + } + return count +} + +// leaseOrchestrationLocked leases an instance's pending events as a work item +// that fits in one gRPC message. History that doesn't fit is streamed, and new +// events that don't fit stay pending for later turns. If the first new event +// can't fit on its own, the instance fails and nil is returned. +func (s *Server) leaseOrchestrationLocked(inst *instance, streamID uint64) *protos.WorkItem { + events := inst.pending + prepended := 0 + if events[0].GetOrchestratorStarted() == nil { + events = append([]*protos.HistoryEvent{helpers.NewOrchestratorStartedEvent()}, events...) + prepended = 1 + } + token := newID() + request := &protos.OrchestratorRequest{ + InstanceId: inst.id, + ExecutionId: wrapperspb.String(inst.executionID), + PastEvents: slices.Clone(inst.history), + NewEvents: events, + } + item := &protos.WorkItem{ + Request: &protos.WorkItem_OrchestratorRequest{OrchestratorRequest: request}, + CompletionToken: token, + } + if len(request.PastEvents) > 0 && proto.Size(item) > maxOrchestrationWorkItemSize { + request.PastEvents = nil + request.RequiresHistoryStreaming = true + } + if proto.Size(item) > maxOrchestrationWorkItemSize { + n := fittingNewEventCount(item, events) + // The batch must hold the OrchestratorStarted marker and at least one event. + if n < 2 { + s.completeLocked(inst, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, nil, &protos.TaskFailureDetails{ + ErrorType: "OrchestrationWorkItemTooLarge", + ErrorMessage: fmt.Sprintf( + "a %d-byte history event can't be delivered within the %d-byte gRPC message limit of the in-memory test backend", + proto.Size(events[1]), maxOrchestrationWorkItemSize), + IsNonRetriable: true, + }) + return nil + } + events = slices.Clip(events[:n]) + request.NewEvents = events + } + inst.pending = slices.Clone(inst.pending[len(events)-prepended:]) + inst.leased = true + s.orchLeases[token] = &orchestrationLease{inst: inst, events: events, streamID: streamID} + return item +} + +// fittingNewEventCount returns how many leading events fit in the work item's +// new events without exceeding the message limit. +func fittingNewEventCount(item *protos.WorkItem, events []*protos.HistoryEvent) int { + request := item.GetOrchestratorRequest() + request.NewEvents = nil + size := proto.Size(item) + n := 0 + for _, event := range events { + // newEvents is field 4 of OrchestratorRequest. + size += protowire.SizeTag(4) + protowire.SizeBytes(proto.Size(event)) + if size > maxOrchestrationWorkItemSize { + break + } + n++ + } + // Nested length prefixes also grow, so confirm the estimate. + for ; n > 0; n-- { + request.NewEvents = events[:n] + if proto.Size(item) <= maxOrchestrationWorkItemSize { + break + } + } + return n +} + +func matchesOrchestrationFilter(filters *protos.WorkItemFilters, inst *instance) bool { + if filters == nil || len(filters.GetOrchestrations()) == 0 { + return true + } + if slices.ContainsFunc(filters.GetOrchestrations(), func(filter *protos.OrchestrationFilter) bool { + return strings.EqualFold(filter.GetName(), helpers.RejectAllWorkItemFilterName) + }) { + return false + } + for _, f := range filters.GetOrchestrations() { + if !strings.EqualFold(f.GetName(), inst.name) { + continue + } + if len(f.GetVersions()) == 0 || slices.ContainsFunc(f.GetVersions(), func(version string) bool { + return strings.EqualFold(version, inst.version.GetValue()) + }) { + return true + } + } + return false +} + +func matchesActivityFilter(filters *protos.WorkItemFilters, req *protos.ActivityRequest) bool { + if filters == nil || len(filters.GetActivities()) == 0 { + return true + } + if slices.ContainsFunc(filters.GetActivities(), func(filter *protos.ActivityFilter) bool { + return strings.EqualFold(filter.GetName(), helpers.RejectAllWorkItemFilterName) + }) { + return false + } + for _, f := range filters.GetActivities() { + if !strings.EqualFold(f.GetName(), req.GetName()) { + continue + } + if len(f.GetVersions()) == 0 || slices.ContainsFunc(f.GetVersions(), func(version string) bool { + return strings.EqualFold(version, req.GetVersion().GetValue()) + }) { + return true + } + } + return false +} + +// releaseStream returns the work items leased by a closed stream to the queue. +func (s *Server) releaseStream(streamID uint64) { + s.mu.Lock() + defer s.mu.Unlock() + for token, lease := range s.orchLeases { + if lease.streamID == streamID { + s.abandonOrchestrationLocked(token, lease) + } + } + for token, lease := range s.actLeases { + if lease.streamID == streamID { + delete(s.actLeases, token) + s.actQueue = append(s.actQueue, lease.item) + } + } + s.notifyLocked() +} + +func (s *Server) abandonOrchestrationLocked(token string, lease *orchestrationLease) { + delete(s.orchLeases, token) + inst := lease.inst + inst.leased = false + if s.instances[inst.id] != inst || isTerminal(inst.status) { + s.notifyLocked() + return + } + inst.pending = append(lease.events, inst.pending...) + s.enqueueLocked(inst) + s.notifyLocked() +} + +// AbandonTaskOrchestratorWorkItem returns an orchestration work item to the queue. +func (s *Server) AbandonTaskOrchestratorWorkItem( + _ context.Context, + req *protos.AbandonOrchestrationTaskRequest, +) (*protos.AbandonOrchestrationTaskResponse, error) { + s.mu.Lock() + defer s.mu.Unlock() + lease, ok := s.orchLeases[req.GetCompletionToken()] + if !ok { + return nil, status.Error(codes.NotFound, "orchestration work item not found") + } + s.abandonOrchestrationLocked(req.GetCompletionToken(), lease) + return &protos.AbandonOrchestrationTaskResponse{}, nil +} + +// AbandonTaskActivityWorkItem returns an activity work item to the queue. +func (s *Server) AbandonTaskActivityWorkItem( + _ context.Context, + req *protos.AbandonActivityTaskRequest, +) (*protos.AbandonActivityTaskResponse, error) { + s.mu.Lock() + defer s.mu.Unlock() + lease, ok := s.actLeases[req.GetCompletionToken()] + if !ok { + return nil, status.Error(codes.NotFound, "activity work item not found") + } + delete(s.actLeases, req.GetCompletionToken()) + s.actQueue = append(s.actQueue, lease.item) + s.notifyLocked() + return &protos.AbandonActivityTaskResponse{}, nil +} + +// CompleteActivityTask records an activity result in its orchestration's inbox. +func (s *Server) CompleteActivityTask(_ context.Context, resp *protos.ActivityResponse) (*protos.CompleteTaskResponse, error) { + s.mu.Lock() + defer s.mu.Unlock() + lease, ok := s.actLeases[resp.GetCompletionToken()] + if !ok { + return nil, status.Error(codes.NotFound, "activity work item not found") + } + delete(s.actLeases, resp.GetCompletionToken()) + item := lease.item + inst := item.inst + if s.instances[inst.id] != inst || inst.executionID != item.executionID { + s.notifyLocked() + return &protos.CompleteTaskResponse{}, nil + } + taskID := item.request.GetTaskId() + if failure := oversizedCompletionFailure(errorTypeActivityResponseTooLarge, "activity response", resp); failure != nil { + // Fail the task rather than store a result over the receive limit. + s.deliverLocked(inst, helpers.NewTaskFailedEvent(taskID, failure)) + } else if resp.GetFailureDetails() != nil { + s.deliverLocked(inst, helpers.NewTaskFailedEvent(taskID, resp.GetFailureDetails())) + } else { + s.deliverLocked(inst, helpers.NewTaskCompletedEvent(taskID, resp.GetResult())) + } + s.notifyLocked() + return &protos.CompleteTaskResponse{}, nil +} + +// CompleteOrchestratorTask commits an orchestration turn and applies its actions. +func (s *Server) CompleteOrchestratorTask(_ context.Context, resp *protos.OrchestratorResponse) (*protos.CompleteTaskResponse, error) { + s.mu.Lock() + defer s.mu.Unlock() + token := resp.GetCompletionToken() + lease, ok := s.orchLeases[token] + if !ok { + return nil, status.Error(codes.NotFound, "orchestration work item not found") + } + inst := lease.inst + if resp.GetRequiresHistory() { + s.abandonOrchestrationLocked(token, lease) + return &protos.CompleteTaskResponse{}, nil + } + delete(s.orchLeases, token) + inst.leased = false + if s.instances[inst.id] != inst || isTerminal(inst.status) { + s.notifyLocked() + return &protos.CompleteTaskResponse{}, nil + } + + processed := lease.events + if n := resp.GetNumEventsProcessed(); n != nil && int(n.GetValue()) < len(processed) { + // NumEventsProcessed counts work events, not control markers in the + // response. Keep control markers between consumed events in the prefix. + split := processedEventPrefixLength(processed, int(n.GetValue())) + inst.pending = append(slices.Clone(processed[split:]), inst.pending...) + processed = processed[:split] + } + inst.history = append(inst.history, processed...) + inst.started = true + if inst.status == protos.OrchestrationStatus_ORCHESTRATION_STATUS_PENDING { + inst.status = protos.OrchestrationStatus_ORCHESTRATION_STATUS_RUNNING + } + inst.customStatus = resp.GetCustomStatus() + inst.updatedAt = time.Now() + + s.applyActionsLocked(inst, resp.GetActions()) + s.enqueueLocked(inst) + s.notifyLocked() + return &protos.CompleteTaskResponse{}, nil +} + +func processedEventPrefixLength(events []*protos.HistoryEvent, processedCount int) int { + processed := 0 + for i, event := range events { + if !countsTowardTurnBudget(event) { + continue + } + if processed == processedCount { + return i + } + processed++ + } + return len(events) +} + +func countsTowardTurnBudget(event *protos.HistoryEvent) bool { + return event.GetOrchestratorStarted() == nil && + event.GetOrchestratorCompleted() == nil && + event.GetGenericEvent() == nil && + event.GetExecutionRewound() == nil && + event.GetExecutionTerminated() == nil && + event.GetExecutionSuspended() == nil && + event.GetExecutionResumed() == nil +} + +func (s *Server) applyActionsLocked(inst *instance, actions []*protos.OrchestratorAction) { + for _, action := range actions { + switch action.GetOrchestratorActionType().(type) { + case *protos.OrchestratorAction_ScheduleTask, + *protos.OrchestratorAction_CreateTimer, + *protos.OrchestratorAction_CreateSubOrchestration, + *protos.OrchestratorAction_SendEvent, + *protos.OrchestratorAction_TerminateOrchestration, + *protos.OrchestratorAction_CompleteOrchestration: + case *protos.OrchestratorAction_SendEntityMessage: + s.failUnsupportedLocked(inst, "durable entities are not supported by the in-memory test backend") + return + default: + s.failUnsupportedLocked(inst, "orchestrator action %T is not supported by the in-memory test backend", + action.GetOrchestratorActionType()) + return + } + } + + var complete *protos.CompleteOrchestrationAction + for _, action := range actions { + id := action.GetId() + switch a := action.GetOrchestratorActionType().(type) { + case *protos.OrchestratorAction_ScheduleTask: + task := a.ScheduleTask + event := helpers.NewTaskScheduledEvent(id, task.GetName(), task.GetVersion(), task.GetInput(), task.GetParentTraceContext()) + event.GetTaskScheduled().Tags = task.GetTags() + inst.history = append(inst.history, event) + s.actQueue = append(s.actQueue, &activityItem{ + inst: inst, + executionID: inst.executionID, + request: &protos.ActivityRequest{ + Name: task.GetName(), + Version: task.GetVersion(), + Input: task.GetInput(), + OrchestrationInstance: &protos.OrchestrationInstance{ + InstanceId: inst.id, + ExecutionId: wrapperspb.String(inst.executionID), + }, + TaskId: id, + ParentTraceContext: task.GetParentTraceContext(), + Tags: task.GetTags(), + }, + }) + case *protos.OrchestratorAction_CreateTimer: + fireAt := a.CreateTimer.GetFireAt() + inst.history = append(inst.history, helpers.NewTimerCreatedEvent(id, fireAt)) + s.startTimerLocked(inst, fireAt.AsTime(), func() { + s.deliverLocked(inst, helpers.NewTimerFiredEvent(id, fireAt, nil)) + }) + case *protos.OrchestratorAction_CreateSubOrchestration: + s.createSubOrchestrationLocked(inst, id, a.CreateSubOrchestration) + case *protos.OrchestratorAction_SendEvent: + send := a.SendEvent + targetID := send.GetInstance().GetInstanceId() + inst.history = append(inst.history, helpers.NewSendEventEvent(id, targetID, send.GetName(), send.GetData())) + if target, ok := s.instances[targetID]; ok { + s.deliverLocked(target, helpers.NewEventRaisedEvent(send.GetName(), send.GetData())) + } + case *protos.OrchestratorAction_TerminateOrchestration: + terminate := a.TerminateOrchestration + if target, ok := s.instances[terminate.GetInstanceId()]; ok { + s.terminateLocked(target, terminate.GetReason(), terminate.GetRecurse()) + } + case *protos.OrchestratorAction_CompleteOrchestration: + complete = a.CompleteOrchestration + } + } + inst.history = append(inst.history, &protos.HistoryEvent{ + EventId: -1, + Timestamp: timestamppb.Now(), + EventType: &protos.HistoryEvent_OrchestratorCompleted{OrchestratorCompleted: &protos.OrchestratorCompletedEvent{}}, + }) + + if complete == nil { + return + } + if complete.GetOrchestrationStatus() == protos.OrchestrationStatus_ORCHESTRATION_STATUS_CONTINUED_AS_NEW { + s.continueAsNewLocked(inst, complete) + return + } + s.completeLocked(inst, complete.GetOrchestrationStatus(), complete.GetResult(), complete.GetFailureDetails()) +} + +func (s *Server) createSubOrchestrationLocked(parent *instance, taskID int32, action *protos.CreateSubOrchestrationAction) { + childID := action.GetInstanceId() + created := helpers.NewSubOrchestrationCreatedEvent( + taskID, action.GetName(), action.GetVersion(), action.GetInput(), childID, action.GetParentTraceContext()) + created.GetSubOrchestrationInstanceCreated().Tags = action.GetTags() + parent.history = append(parent.history, created) + + if existing, ok := s.instances[childID]; ok && !isTerminal(existing.status) { + s.deliverLocked(parent, &protos.HistoryEvent{ + EventId: -1, + Timestamp: timestamppb.Now(), + EventType: &protos.HistoryEvent_SubOrchestrationInstanceFailed{ + SubOrchestrationInstanceFailed: &protos.SubOrchestrationInstanceFailedEvent{ + TaskScheduledId: taskID, + FailureDetails: failureDetails("OrchestrationAlreadyExists", + "orchestration instance %q already exists", childID), + }, + }, + }) + return + } + parentInfo := helpers.NewParentInfo(taskID, parent.name, parent.id) + parentInfo.Version = parent.version + parentInfo.OrchestrationInstance.ExecutionId = wrapperspb.String(parent.executionID) + child := s.newInstanceLocked(childID, action.GetName(), action.GetVersion(), action.GetInput(), action.GetTags(), + parentInfo, action.GetParentTraceContext(), nil) + if !slices.Contains(parent.children, childID) { + parent.children = append(parent.children, childID) + } + if terminated := parent.recursiveTermination(); terminated != nil { + // The parent was terminated recursively while this turn was in flight, + // after its existing children were terminated. + s.terminateLocked(child, terminated.GetInput(), true) + } +} + +func (s *Server) continueAsNewLocked(inst *instance, complete *protos.CompleteOrchestrationAction) { + inst.stopTimers() + inst.history = nil + inst.input = complete.GetResult() + if complete.GetNewVersion() != nil { + inst.version = complete.GetNewVersion() + } + if complete.GetTags() != nil { + inst.tags = complete.GetTags() + } + inst.output = nil + inst.failure = nil + pending := []*protos.HistoryEvent{inst.newExecutionStartedEvent()} + pending = append(pending, complete.GetCarryoverEvents()...) + // Results for the previous execution's tasks would be matched to the new + // execution's task IDs, so only events addressed to the instance carry over. + for _, event := range inst.pending { + switch event.GetEventType().(type) { + case *protos.HistoryEvent_EventRaised, + *protos.HistoryEvent_ExecutionSuspended, + *protos.HistoryEvent_ExecutionResumed, + *protos.HistoryEvent_ExecutionTerminated: + pending = append(pending, event) + } + } + inst.pending = pending +} + +func (s *Server) failUnsupportedLocked(inst *instance, format string, args ...any) { + failure := failureDetails("NotSupported", format, args...) + failure.IsNonRetriable = true + inst.history = append(inst.history, &protos.HistoryEvent{ + EventId: -1, + Timestamp: timestamppb.Now(), + EventType: &protos.HistoryEvent_OrchestratorCompleted{OrchestratorCompleted: &protos.OrchestratorCompletedEvent{}}, + }) + s.completeLocked(inst, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, nil, failure) +} + +// completeLocked moves an instance to a terminal state and notifies its parent. +func (s *Server) completeLocked( + inst *instance, + runtimeStatus protos.OrchestrationStatus, + output *wrapperspb.StringValue, + failure *protos.TaskFailureDetails, +) { + now := time.Now() + inst.stopTimers() + inst.status = runtimeStatus + inst.output = output + inst.failure = failure + inst.completedAt = now + inst.updatedAt = now + inst.pending = nil + inst.history = append(inst.history, &protos.HistoryEvent{ + EventId: -1, + Timestamp: timestamppb.New(now), + EventType: &protos.HistoryEvent_ExecutionCompleted{ExecutionCompleted: &protos.ExecutionCompletedEvent{ + OrchestrationStatus: runtimeStatus, + Result: output, + FailureDetails: failure, + }}, + }) + s.notifyLocked() + + parentRef := inst.parent.GetOrchestrationInstance() + parent, ok := s.instances[parentRef.GetInstanceId()] + if !ok || parent.executionID != parentRef.GetExecutionId().GetValue() { + return + } + taskID := inst.parent.GetTaskScheduledId() + event := &protos.HistoryEvent{EventId: -1, Timestamp: timestamppb.New(now)} + if runtimeStatus == protos.OrchestrationStatus_ORCHESTRATION_STATUS_COMPLETED { + event.EventType = &protos.HistoryEvent_SubOrchestrationInstanceCompleted{ + SubOrchestrationInstanceCompleted: &protos.SubOrchestrationInstanceCompletedEvent{ + TaskScheduledId: taskID, + Result: output, + }, + } + } else { + if failure == nil { + failure = failureDetails("OrchestrationTerminated", + "sub-orchestration %q ended with status %s", inst.id, helpers.ToRuntimeStatusString(runtimeStatus)) + } + event.EventType = &protos.HistoryEvent_SubOrchestrationInstanceFailed{ + SubOrchestrationInstanceFailed: &protos.SubOrchestrationInstanceFailedEvent{ + TaskScheduledId: taskID, + FailureDetails: failure, + }, + } + } + s.deliverLocked(parent, event) +} diff --git a/internal/inmemory/work_test.go b/internal/inmemory/work_test.go new file mode 100644 index 00000000..ccfd7033 --- /dev/null +++ b/internal/inmemory/work_test.go @@ -0,0 +1,288 @@ +package inmemory + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/wrapperspb" + + "github.com/microsoft/durabletask-go/internal/helpers" + "github.com/microsoft/durabletask-go/internal/protos" +) + +type testWorkItemStream struct { + grpc.ServerStream + ctx context.Context + items chan *protos.WorkItem +} + +func (s *testWorkItemStream) Context() context.Context { return s.ctx } + +func (s *testWorkItemStream) Send(item *protos.WorkItem) error { + select { + case s.items <- item: + return nil + case <-s.ctx.Done(): + return s.ctx.Err() + } +} + +// openTestStream serves GetWorkItems on a test stream. The returned function +// closes the stream and waits until its leases are released. +func openTestStream(t *testing.T, s *Server) (*testWorkItemStream, func()) { + t.Helper() + ctx, cancel := context.WithCancel(t.Context()) + stream := &testWorkItemStream{ctx: ctx, items: make(chan *protos.WorkItem)} + done := make(chan struct{}) + go func() { + defer close(done) + _ = s.GetWorkItems(&protos.GetWorkItemsRequest{}, stream) + }() + closeStream := func() { + cancel() + <-done + } + t.Cleanup(closeStream) + return stream, closeStream +} + +func (s *testWorkItemStream) receive(t *testing.T) *protos.WorkItem { + t.Helper() + select { + case item := <-s.items: + return item + case <-time.After(10 * time.Second): + require.FailNow(t, "timed out waiting for a work item") + return nil + } +} + +func TestClosedStreamLeasesAreRedeliveredAndOldTokensRejected(t *testing.T) { + s := NewServer() + defer s.Close() + ctx := t.Context() + + _, err := s.StartInstance(ctx, &protos.CreateInstanceRequest{InstanceId: "id", Name: "orchestrator"}) + require.NoError(t, err) + first, closeFirst := openTestStream(t, s) + start := first.receive(t) + require.NotNil(t, start.GetOrchestratorRequest()) + _, err = s.CompleteOrchestratorTask(ctx, &protos.OrchestratorResponse{ + CompletionToken: start.GetCompletionToken(), + Actions: []*protos.OrchestratorAction{{ + Id: 0, + OrchestratorActionType: &protos.OrchestratorAction_ScheduleTask{ + ScheduleTask: &protos.ScheduleTaskAction{Name: "activity"}, + }, + }}, + }) + require.NoError(t, err) + oldActivity := first.receive(t) + require.NotNil(t, oldActivity.GetActivityRequest()) + _, err = s.RaiseEvent(ctx, &protos.RaiseEventRequest{InstanceId: "id", Name: "A"}) + require.NoError(t, err) + oldOrchestration := first.receive(t) + require.NotNil(t, oldOrchestration.GetOrchestratorRequest()) + // B arrives while A's turn is leased. + _, err = s.RaiseEvent(ctx, &protos.RaiseEventRequest{InstanceId: "id", Name: "B"}) + require.NoError(t, err) + + closeFirst() + second, _ := openTestStream(t, s) + var orchestration, activity *protos.WorkItem + for orchestration == nil || activity == nil { + item := second.receive(t) + if item.GetOrchestratorRequest() != nil { + orchestration = item + } else { + activity = item + } + } + + var raised []string + for _, event := range orchestration.GetOrchestratorRequest().GetNewEvents() { + if e := event.GetEventRaised(); e != nil { + raised = append(raised, e.GetName()) + } + } + assert.Equal(t, []string{"A", "B"}, raised) + assert.Equal(t, "activity", activity.GetActivityRequest().GetName()) + assert.NotEqual(t, oldOrchestration.GetCompletionToken(), orchestration.GetCompletionToken()) + assert.NotEqual(t, oldActivity.GetCompletionToken(), activity.GetCompletionToken()) + + _, err = s.CompleteOrchestratorTask(ctx, &protos.OrchestratorResponse{CompletionToken: oldOrchestration.GetCompletionToken()}) + assert.Equal(t, codes.NotFound, status.Code(err)) + _, err = s.CompleteActivityTask(ctx, &protos.ActivityResponse{CompletionToken: oldActivity.GetCompletionToken()}) + assert.Equal(t, codes.NotFound, status.Code(err)) + _, err = s.CompleteOrchestratorTask(ctx, &protos.OrchestratorResponse{CompletionToken: orchestration.GetCompletionToken()}) + require.NoError(t, err) + _, err = s.CompleteActivityTask(ctx, &protos.ActivityResponse{CompletionToken: activity.GetCompletionToken()}) + require.NoError(t, err) +} + +func TestContinueAsNewDropsPreviousExecutionResults(t *testing.T) { + s := NewServer() + defer s.Close() + inst := &instance{id: "id", name: "orchestrator", executionID: "old"} + raised := helpers.NewEventRaisedEvent("event", nil) + inst.pending = []*protos.HistoryEvent{ + helpers.NewTaskCompletedEvent(0, nil), + raised, + helpers.NewTimerFiredEvent(1, nil, nil), + } + carryover := helpers.NewEventRaisedEvent("carryover", nil) + + s.continueAsNewLocked(inst, &protos.CompleteOrchestrationAction{CarryoverEvents: []*protos.HistoryEvent{carryover}}) + + require.Len(t, inst.pending, 3) + assert.NotNil(t, inst.pending[0].GetExecutionStarted()) + assert.NotEqual(t, "old", inst.executionID) + assert.Same(t, carryover, inst.pending[1]) + assert.Same(t, raised, inst.pending[2]) +} + +func TestCompleteOrchestratorTaskSplitsByProcessedEvents(t *testing.T) { + s := NewServer() + defer s.Close() + + inst := &instance{ + id: "id", + executionID: "execution", + status: protos.OrchestrationStatus_ORCHESTRATION_STATUS_RUNNING, + leased: true, + } + started := &protos.HistoryEvent{ + EventType: &protos.HistoryEvent_ExecutionStarted{ExecutionStarted: &protos.ExecutionStartedEvent{}}, + } + suspended := helpers.NewSuspendOrchestrationEvent("pause") + pending := helpers.NewTimerFiredEvent(1, nil, nil) + s.instances[inst.id] = inst + s.orchLeases["token"] = &orchestrationLease{ + inst: inst, + events: []*protos.HistoryEvent{ + helpers.NewOrchestratorStartedEvent(), + started, + suspended, + pending, + }, + } + + _, err := s.CompleteOrchestratorTask(t.Context(), &protos.OrchestratorResponse{ + CompletionToken: "token", + NumEventsProcessed: wrapperspb.Int32(1), + }) + require.NoError(t, err) + require.Len(t, inst.history, 4) + assert.Same(t, started, inst.history[1]) + assert.Same(t, suspended, inst.history[2]) + require.Len(t, inst.pending, 1) + assert.Same(t, pending, inst.pending[0]) +} + +func TestRecursiveTerminationDoesNotTerminateReusedChildID(t *testing.T) { + s := NewServer() + defer s.Close() + + parent := &instance{ + id: "parent", + status: protos.OrchestrationStatus_ORCHESTRATION_STATUS_RUNNING, + children: []string{"child"}, + history: []*protos.HistoryEvent{{}}, + } + replacement := &instance{ + id: "child", + status: protos.OrchestrationStatus_ORCHESTRATION_STATUS_RUNNING, + } + s.instances[parent.id] = parent + s.instances[replacement.id] = replacement + + s.mu.Lock() + s.terminateLocked(parent, nil, true) + s.mu.Unlock() + + assert.Equal(t, protos.OrchestrationStatus_ORCHESTRATION_STATUS_RUNNING, replacement.status) +} + +func TestRecursiveTerminationDuringTurnTerminatesNewChildren(t *testing.T) { + s := NewServer() + defer s.Close() + ctx := t.Context() + + _, err := s.StartInstance(ctx, &protos.CreateInstanceRequest{InstanceId: "parent", Name: "orchestrator"}) + require.NoError(t, err) + s.mu.Lock() + item := s.nextWorkItemLocked(nil, 1, workItemLimits{}) + s.mu.Unlock() + require.NotNil(t, item.GetOrchestratorRequest()) + + _, err = s.TerminateInstance(ctx, &protos.TerminateRequest{InstanceId: "parent", Recursive: true}) + require.NoError(t, err) + _, err = s.CompleteOrchestratorTask(ctx, &protos.OrchestratorResponse{ + CompletionToken: item.GetCompletionToken(), + Actions: []*protos.OrchestratorAction{{ + Id: 0, + OrchestratorActionType: &protos.OrchestratorAction_CreateSubOrchestration{ + CreateSubOrchestration: &protos.CreateSubOrchestrationAction{InstanceId: "child", Name: "orchestrator"}, + }, + }}, + }) + require.NoError(t, err) + + resp, err := s.GetInstance(ctx, &protos.GetInstanceRequest{InstanceId: "child"}) + require.NoError(t, err) + require.True(t, resp.GetExists()) + assert.Equal(t, protos.OrchestrationStatus_ORCHESTRATION_STATUS_TERMINATED, resp.GetOrchestrationState().GetOrchestrationStatus()) +} + +func TestWorkItemTooLargeForOneMessageFailsInstance(t *testing.T) { + s := NewServer() + defer s.Close() + + inst := &instance{ + id: "id", + executionID: "execution", + status: protos.OrchestrationStatus_ORCHESTRATION_STATUS_RUNNING, + pending: []*protos.HistoryEvent{ + helpers.NewEventRaisedEvent("big", wrapperspb.String(strings.Repeat("x", maxOrchestrationWorkItemSize))), + }, + } + s.instances[inst.id] = inst + + s.mu.Lock() + item := s.leaseOrchestrationLocked(inst, 1) + s.mu.Unlock() + + assert.Nil(t, item) + assert.Empty(t, s.orchLeases) + assert.Equal(t, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, inst.status) + require.NotNil(t, inst.failure) + assert.Equal(t, "OrchestrationWorkItemTooLarge", inst.failure.GetErrorType()) +} + +func TestWorkItemFiltersMatchWorkerSemantics(t *testing.T) { + inst := &instance{name: "MyOrchestrator", version: wrapperspb.String("V1")} + activity := &protos.ActivityRequest{Name: "MyActivity", Version: wrapperspb.String("V1")} + + require.True(t, matchesOrchestrationFilter(&protos.WorkItemFilters{ + Activities: []*protos.ActivityFilter{{Name: "unrelated"}}, + }, inst), "an empty orchestration filter must not filter out orchestrations") + require.True(t, matchesActivityFilter(&protos.WorkItemFilters{ + Orchestrations: []*protos.OrchestrationFilter{{Name: "unrelated"}}, + }, activity), "an empty activity filter must not filter out activities") + require.True(t, matchesOrchestrationFilter(&protos.WorkItemFilters{ + Orchestrations: []*protos.OrchestrationFilter{{Name: "myorchestrator", Versions: []string{"v1"}}}, + }, inst), "orchestration names and versions should match case-insensitively") + require.True(t, matchesActivityFilter(&protos.WorkItemFilters{ + Activities: []*protos.ActivityFilter{{Name: "myactivity", Versions: []string{"v1"}}}, + }, activity), "activity names and versions should match case-insensitively") + require.False(t, matchesOrchestrationFilter(&protos.WorkItemFilters{ + Orchestrations: []*protos.OrchestrationFilter{{Name: helpers.RejectAllWorkItemFilterName}}, + }, inst), "the reject-all sentinel must remain honored") +}