-
Notifications
You must be signed in to change notification settings - Fork 41
Nexus cancellation sample #124
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
64 changes: 64 additions & 0 deletions
64
src/NexusCancellation/Caller/HelloCallerWorkflow.workflow.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| namespace TemporalioSamples.NexusCancellation.Caller; | ||
|
|
||
| using Microsoft.Extensions.Logging; | ||
| using Temporalio.Exceptions; | ||
| using Temporalio.Workflows; | ||
|
|
||
| [Workflow] | ||
| public class HelloCallerWorkflow | ||
| { | ||
| private static readonly IHelloService.HelloLanguage[] Languages = | ||
| [IHelloService.HelloLanguage.En, IHelloService.HelloLanguage.Fr, IHelloService.HelloLanguage.De, | ||
| IHelloService.HelloLanguage.Es, IHelloService.HelloLanguage.Tr]; | ||
|
|
||
| [WorkflowRun] | ||
| public async Task<string> RunAsync(string name) | ||
| { | ||
| using var cts = CancellationTokenSource.CreateLinkedTokenSource(Workflow.CancellationToken); | ||
| var client = Workflow.CreateNexusClient<IHelloService>(IHelloService.EndpointName); | ||
|
|
||
| // Concurrently execute an operation per language. | ||
| var tasks = Languages.Select(lang => | ||
| client.ExecuteNexusOperationAsync( | ||
| svc => svc.SayHello(new IHelloService.HelloInput(name, lang)), | ||
| new NexusOperationOptions | ||
| { | ||
| // We set the CancellationType to WaitCancellationRequested, which means the caller waits | ||
| // for the request to be received by the handler before proceeding with the cancellation. | ||
| // | ||
| // The default CancellationType is WaitCancellationCompleted, where the caller would wait | ||
| // until the operation is completed. | ||
| CancellationType = NexusOperationCancellationType.WaitCancellationRequested, | ||
| CancellationToken = cts.Token, | ||
| })).ToList(); | ||
|
|
||
| var firstTask = await Workflow.WhenAnyAsync(tasks); | ||
|
|
||
| Workflow.Logger.LogInformation("First operation completed, cancelling remaining operations"); | ||
|
|
||
| // Now that the first operation has won the race, we are going to cancel the other operations. | ||
| #pragma warning disable CA1849, VSTHRD103 // CancelAsync() is non-deterministic in workflows. | ||
| cts.Cancel(); | ||
| #pragma warning restore CA1849, VSTHRD103 | ||
|
|
||
| // Wait for all tasks to resolve. Once the workflow completes, the server will stop trying to cancel any of | ||
| // the operations that have not yet received cancellation, letting them run to completion. We are using the | ||
| // CancellationType of WaitCancellationRequested so these tasks will return as soon as the operation has received | ||
| // the cancellation request. | ||
| foreach (var task in tasks) | ||
| { | ||
| try | ||
| { | ||
| await task; | ||
| } | ||
| // Only throw an error if an operation errored out not due to cancellation. | ||
| catch (Exception ex) when (TemporalException.IsCanceledException(ex)) | ||
| { | ||
| Workflow.Logger.LogInformation("Operation was cancelled"); | ||
| } | ||
| } | ||
|
|
||
| var result = await firstTask; | ||
| return result?.Message ?? throw new ApplicationFailureException("No successful result"); | ||
| } | ||
| } | ||
52 changes: 52 additions & 0 deletions
52
src/NexusCancellation/Handler/HelloHandlerWorkflow.workflow.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| namespace TemporalioSamples.NexusCancellation.Handler; | ||
|
|
||
| using Microsoft.Extensions.Logging; | ||
| using Temporalio.Exceptions; | ||
| using Temporalio.Workflows; | ||
|
|
||
| [Workflow] | ||
| public class HelloHandlerWorkflow | ||
| { | ||
| [WorkflowRun] | ||
| public async Task<IHelloService.HelloOutput> RunAsync(IHelloService.HelloInput input) | ||
| { | ||
| Workflow.Logger.LogInformation( | ||
| "HelloHandlerWorkflow started for {Name} in {Language}", | ||
| input.Name, | ||
| input.Language); | ||
|
|
||
| // Sleep for a random duration to simulate some work | ||
| var duration = TimeSpan.FromSeconds(Workflow.Random.Next(5)); | ||
|
|
||
| try | ||
| { | ||
| await Workflow.DelayAsync(duration); | ||
| } | ||
| catch (Exception ex) when (TemporalException.IsCanceledException(ex)) | ||
| { | ||
| // Simulate cleanup work after cancellation is requested. | ||
| // Use CancellationToken.None to create a "disconnected" context. | ||
| var cleanupDuration = TimeSpan.FromSeconds(Workflow.Random.Next(5)); | ||
| await Workflow.DelayAsync(cleanupDuration, CancellationToken.None); | ||
|
|
||
| Workflow.Logger.LogInformation( | ||
| "HelloHandlerWorkflow for {Name} in {Language} was cancelled after {Duration} of work, performed {CleanupDuration} of cleanup", | ||
| input.Name, | ||
| input.Language, | ||
| duration, | ||
| cleanupDuration); | ||
| throw; // Re-throw the cancellation after cleanup | ||
| } | ||
|
|
||
| return input.Language switch | ||
| { | ||
| IHelloService.HelloLanguage.En => new($"Hello {input.Name} 👋"), | ||
| IHelloService.HelloLanguage.Fr => new($"Bonjour {input.Name} 👋"), | ||
| IHelloService.HelloLanguage.De => new($"Hallo {input.Name} 👋"), | ||
| IHelloService.HelloLanguage.Es => new($"¡Hola! {input.Name} 👋"), | ||
| IHelloService.HelloLanguage.Tr => new($"Merhaba {input.Name} 👋"), | ||
| _ => throw new ApplicationFailureException( | ||
| $"Unsupported language: {input.Language}", errorType: "UNSUPPORTED_LANGUAGE"), | ||
| }; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| namespace TemporalioSamples.NexusCancellation.Handler; | ||
|
|
||
| using NexusRpc.Handlers; | ||
| using Temporalio.Nexus; | ||
|
|
||
| [NexusServiceHandler(typeof(IHelloService))] | ||
| public class HelloService | ||
| { | ||
| [NexusOperationHandler] | ||
| public IOperationHandler<IHelloService.HelloInput, IHelloService.HelloOutput> SayHello() => | ||
| // This Nexus service operation is backed by a workflow run | ||
| WorkflowRunOperationHandler.FromHandleFactory( | ||
| (WorkflowRunOperationContext context, IHelloService.HelloInput input) => | ||
| context.StartWorkflowAsync( | ||
| (HelloHandlerWorkflow wf) => wf.RunAsync(input), | ||
| // Workflow IDs should typically be business meaningful IDs and are used to | ||
| // dedupe workflow starts. For this example, we're using the request ID | ||
| // allocated by Temporal when the caller workflow schedules the operation, | ||
| // this ID is guaranteed to be stable across retries of this operation. | ||
| new() { Id = context.HandlerContext.RequestId })); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| namespace TemporalioSamples.NexusCancellation; | ||
|
|
||
| using NexusRpc; | ||
|
|
||
| [NexusService] | ||
| public interface IHelloService | ||
| { | ||
| static readonly string EndpointName = "nexus-cancellation-endpoint"; | ||
|
|
||
| [NexusOperation] | ||
| HelloOutput SayHello(HelloInput input); | ||
|
|
||
| public record HelloInput(string Name, HelloLanguage Language); | ||
|
|
||
| public record HelloOutput(string Message); | ||
|
|
||
| public enum HelloLanguage | ||
| { | ||
| En, | ||
| Fr, | ||
| De, | ||
| Es, | ||
| Tr, | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| using Microsoft.Extensions.Logging; | ||
| using Temporalio.Client; | ||
| using Temporalio.Common.EnvConfig; | ||
| using Temporalio.Worker; | ||
| using TemporalioSamples.NexusCancellation.Caller; | ||
| using TemporalioSamples.NexusCancellation.Handler; | ||
|
|
||
| using var loggerFactory = LoggerFactory.Create(builder => | ||
| builder. | ||
| AddSimpleConsole(options => options.TimestampFormat = "[HH:mm:ss] "). | ||
| SetMinimumLevel(LogLevel.Information)); | ||
| var logger = loggerFactory.CreateLogger<Program>(); | ||
|
|
||
| // Cancellation token cancelled on ctrl+c | ||
| using var tokenSource = new CancellationTokenSource(); | ||
| Console.CancelKeyPress += (_, eventArgs) => | ||
| { | ||
| tokenSource.Cancel(); | ||
| eventArgs.Cancel = true; | ||
| }; | ||
|
|
||
| Task<TemporalClient> ConnectClientAsync(string temporalNamespace) | ||
| { | ||
| var connectOptions = ClientEnvConfig.LoadClientConnectOptions(); | ||
| connectOptions.TargetHost ??= "localhost:7233"; | ||
| connectOptions.Namespace = temporalNamespace; | ||
| connectOptions.LoggerFactory = loggerFactory; | ||
| return TemporalClient.ConnectAsync(connectOptions); | ||
| } | ||
|
|
||
| async Task RunHandlerWorkerAsync() | ||
| { | ||
| // Run worker until cancelled | ||
| logger.LogInformation("Running handler worker"); | ||
| using var worker = new TemporalWorker( | ||
| await ConnectClientAsync("nexus-cancellation-handler-namespace"), | ||
| new TemporalWorkerOptions(taskQueue: "nexus-cancellation-handler-sample"). | ||
| AddNexusService(new HelloService()). | ||
| AddWorkflow<HelloHandlerWorkflow>()); | ||
| try | ||
| { | ||
| await worker.ExecuteAsync(tokenSource.Token); | ||
| } | ||
| catch (OperationCanceledException) | ||
| { | ||
| logger.LogInformation("Handler worker cancelled"); | ||
| } | ||
| } | ||
|
|
||
| async Task RunCallerWorkerAsync() | ||
| { | ||
| // Run worker until cancelled | ||
| logger.LogInformation("Running caller worker"); | ||
| using var worker = new TemporalWorker( | ||
| await ConnectClientAsync("nexus-cancellation-caller-namespace"), | ||
| new TemporalWorkerOptions(taskQueue: "nexus-cancellation-caller-sample") | ||
| .AddWorkflow<HelloCallerWorkflow>()); | ||
| try | ||
| { | ||
| await worker.ExecuteAsync(tokenSource.Token); | ||
| } | ||
| catch (OperationCanceledException) | ||
| { | ||
| logger.LogInformation("Caller worker cancelled"); | ||
| } | ||
| } | ||
|
|
||
| async Task ExecuteCallerWorkflowAsync() | ||
| { | ||
| logger.LogInformation("Executing caller hello workflow"); | ||
|
|
||
| var client = await ConnectClientAsync("nexus-cancellation-caller-namespace"); | ||
|
|
||
| var result = await client.ExecuteWorkflowAsync( | ||
| (HelloCallerWorkflow wf) => wf.RunAsync("Temporal"), | ||
| new(id: "nexus-cancellation-hello-id", taskQueue: "nexus-cancellation-caller-sample")); | ||
| logger.LogInformation("Workflow result: {Result}", result); | ||
| } | ||
|
|
||
| switch (args.ElementAtOrDefault(0)) | ||
| { | ||
| case "handler-worker": | ||
| await RunHandlerWorkerAsync(); | ||
| break; | ||
| case "caller-worker": | ||
| await RunCallerWorkerAsync(); | ||
| break; | ||
| case "caller-workflow": | ||
| await ExecuteCallerWorkflowAsync(); | ||
| break; | ||
| default: | ||
| throw new ArgumentException( | ||
| "Must pass 'handler-worker', 'caller-worker', or 'caller-workflow' as the single argument"); | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
May deserve the similar comments here (and elsewhere) similar to the Go and Java samples
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Added comments that follow the other samples.