Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/pr-validation.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
35 changes: 34 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 ./...)
```
Expand Down
271 changes: 271 additions & 0 deletions durabletasktest/host.go
Original file line number Diff line number Diff line change
@@ -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(
Comment thread
andystaples marked this conversation as resolved.
Resolved
"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()
}
Loading