Skip to content
Merged
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
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 typed orchestration-local `task.NewChannel[T]` with buffered and unbuffered send/receive operations, cancellation-aware error forms, and `OnSend`/`OnReceive` cases for durable `Select`. Rendezvous selection commits both endpoints without performing losing operations. Channel waits yield to the existing scheduler and replay reconstructs their state. Channel-only waits with no pending durable work or external event receiver fail with `task.ErrOrchestrationDeadlock`; detection is conservative and channels do not support close. Added `ctx.IsCanceled()` to inspect applied durable scope cancellation.
- 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
74 changes: 74 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,80 @@ Obey these rules when you write a retry handler:

Full sample: [samples/retries](./samples/retries).

### Selectable coroutine channels

Use `task.NewChannel[T](ctx, capacity)` to pass values between `ctx.Go` branches
inside one orchestration. Capacity zero requires a sender/receiver rendezvous;
positive capacity provides a bounded FIFO buffer. This is separate from
`task.NewEventChannel`, which receives events raised by clients or other
orchestrations.

```go
results := task.NewChannel[int](ctx, 0)
ctx.Go(func(branch *task.OrchestrationContext) {
var value int
if err := branch.CallActivity("Calculate").Await(&value); err != nil {
panic(err)
}
results.Send(branch, value)
})
value := results.Receive(ctx)
```

`Send` and `Receive` are the durable equivalents of Go's `ch <- value` and
`value := <-ch`. `SendErr` and `ReceiveErr` return `task.ErrTaskCanceled` if the
waiting scope is canceled before the operation commits; the convenience forms
panic on cancellation. A committed exchange is not undone by later
cancellation. Values are passed by assignment without serialization, like Go
channels; do not mutate shared values concurrently or make replay-unsafe values
in orchestration code.

Use the existing selector to wait for channel operations alongside durable
tasks and external events:

```go
ctx.Select(
task.OnReceive(results, func(value int) { /* process value */ }),
task.OnEvent(task.NewEventChannel[string](ctx, "Stop"), func(string) {
/* request cancellation of branch operations */
}),
task.OnTask(timer, func(task.Task) { /* handle timeout */ }),
)
```

`task.OnSend(channel, value, handler)` is the send equivalent. Only the winning
case sends or consumes a value. For an unbuffered exchange, both selections
commit their channel cases before either callback runs. Each callback executes
in its own selecting coroutine. Task and external event readiness is ordered
by history; channel readiness is ordered deterministically by the SDK scheduler.
Argument order breaks ties, but does not give a stop event priority over an
earlier ready result. A repeated case within one `Select` is treated as its
first occurrence and registered only once; cases can also be reused by later calls.

Channel waits yield to the SDK, allowing other branches to schedule activities.
When all branches are waiting and available history is exhausted, the execution
unloads and its durable actions are dispatched. Replay reconstructs branches,
buffers, and exchanges; channels do not keep goroutines alive between turns.
Never use native Go channels or native `select` inside an orchestrator.

If channel operations are waiting with no runnable coroutine, pending durable
task, or external event wait, the SDK fails the orchestration with
`task.ErrOrchestrationDeadlock` rather than leaving an unrecoverable local
cycle silently stuck. Detection is conservative: pending durable work prevents
this diagnosis even if application logic will still be unable to progress.
It cannot detect arbitrary application loops that never yield. Channels have
no close operation; use known result counts, explicit completion messages, or
cancellation to finish receivers.

`ctx.IsCanceled()` inspects applied cancellation of the durable scope, not the
host Go context. Cancellation requested by a `WithCancel` cancel function is
applied at the next scheduler boundary. Canceling a scope releases its pending
channel operations without closing the shared channel or canceling other
scopes. It does not guarantee an already-dispatched activity stops remotely.
Join uncanceled coroutine wrappers when cleanup must finish before returning.

Full sample: [samples/coroutines](./samples/coroutines).

### Deferred work and cooperative cleanup

A root or child coroutine's defers can schedule and await durable work during
Expand Down
8 changes: 5 additions & 3 deletions cmd/orchestratorvet/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,11 @@ creation, send, receive, range, and close, and `select` statements. The check
keys on the package that declares a method, so an embedded `sync.Mutex` is
recognized through the embedding type.

Not reported: `ctx.Go`, `ctx.NewWaitGroup`, `ctx.Select` with `task.OnTask` or
`task.OnEvent`, `task.NewEventChannel`, and `ctx.WaitForSingleEvent`. These are
scheduled by the deterministic orchestration scheduler.
Not reported: `ctx.Go`, `ctx.NewWaitGroup`, `ctx.Select` with `task.OnTask`,
`task.OnEvent`, `task.OnSend`, or `task.OnReceive`, `task.NewChannel`,
`task.NewEventChannel`, and `ctx.WaitForSingleEvent`. SDK channel operations
are also safe: they yield through the deterministic orchestration scheduler,
not native Go channel synchronization.

### External I/O

Expand Down
12 changes: 10 additions & 2 deletions samples/coroutines/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@

- Starts bounded orchestration coroutines with `ctx.Go`.
- Coordinates coroutine completion with `ctx.NewWaitGroup`.
- Uses `Select` on a typed event channel and a durable timer from a child
cancellation scope.
- Sends activity results through an unbuffered `task.NewChannel`.
- Uses `Select` to receive branch results alongside a typed external event
channel and a durable timer from a child cancellation scope.
- Cancels the losing timer when the approval event wins.
- Cancels branch operations and joins their uncanceled wrappers on failure.
- Validates the returned doubled values and selected event outcome.

## Prerequisites
Expand Down Expand Up @@ -34,6 +36,12 @@ it prints:
SAMPLE_OK coroutines
```

Channel operations yield to the SDK scheduler, not Go's native channel
scheduler. Once all branches are waiting and available history is exhausted,
the worker unloads the entire execution and dispatches its pending activities.
Replay recreates the branches and their channel exchanges; no goroutine remains
alive waiting for an activity on another worker.

## Cleanup

The sample terminates if needed and recursively purges only its generated
Expand Down
61 changes: 49 additions & 12 deletions samples/coroutines/coroutines.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ type coroutineOutput struct {
Sum int `json:"sum"`
}

type coroutineResult struct {
index int
value int
err error
}

func main() {
if err := run(); err != nil {
log.Fatal(err)
Expand Down Expand Up @@ -107,35 +113,66 @@ func CoroutineFanInOrchestrator(ctx *task.OrchestrationContext) (any, error) {
}

doubled := make([]int, len(input.Values))
results := task.NewChannel[coroutineResult](ctx, 0)
workCtx, cancelWork := ctx.WithCancel()
waitGroup := ctx.NewWaitGroup()
waitGroup.Add(len(input.Values))
for i, value := range input.Values {
i, value := i, value
ctx.Go(func(ctx *task.OrchestrationContext) {
ctx.Go(func(*task.OrchestrationContext) {
defer waitGroup.Done()
var result int
if err := ctx.CallActivity("DoubleValue", task.WithActivityInput(value)).Await(&result); err != nil {
err := workCtx.CallActivity("DoubleValue", task.WithActivityInput(value)).Await(&result)
if errors.Is(err, task.ErrTaskCanceled) {
return
}
if err := results.SendErr(workCtx, coroutineResult{index: i, value: result, err: err}); err != nil &&
!errors.Is(err, task.ErrTaskCanceled) {
panic(err)
}
doubled[i] = result
})
}

timerCtx, cancelTimer := ctx.WithCancel()
timer := timerCtx.CreateTimer(input.ApprovalWindow)
approvals := task.NewEventChannel[string](ctx, "Approval")
selected := "timeout"
ctx.Select(
task.OnEvent(approvals, func(value string) {
selected = "event:" + value
cancelTimer()
}),
task.OnTask(timer, func(task.Task) {
selected = "timeout"
}),
)
decisionMade := false
received := 0
var failure error
for (received < len(input.Values) || !decisionMade) && failure == nil {
var cases []task.SelectCase
if received < len(input.Values) {
cases = append(cases, task.OnReceive(results, func(result coroutineResult) {
failure = result.err
doubled[result.index] = result.value
received++
}))
}
if !decisionMade {
cases = append(cases,
task.OnEvent(approvals, func(value string) {
selected = "event:" + value
decisionMade = true
cancelTimer()
}),
task.OnTask(timer, func(task.Task) {
selected = "timeout"
decisionMade = true
}),
)
}
ctx.Select(cases...)
}

if failure != nil {
cancelWork()
cancelTimer()
}
waitGroup.Wait(ctx)
if failure != nil {
return nil, failure
}
sum := 0
for _, value := range doubled {
sum += value
Expand Down
8 changes: 8 additions & 0 deletions task/cancel.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
package task

// IsCanceled reports applied cancellation of this orchestration scope.
// WithCancel's cancel function queues cancellation for the next scheduler
// boundary, so IsCanceled need not become true immediately after calling it.
func (ctx *OrchestrationContext) IsCanceled() bool {
ctx.effectContext()
return ctx.scope.isCanceled()
}

type cancellationScope struct {
parent *cancellationScope
parentIndex int
Expand Down
Loading