| | | 1 | | namespace NexusLabs.Needlr.AgentFramework.Workflows.Sequential; |
| | | 2 | | |
| | | 3 | | /// <summary> |
| | | 4 | | /// Tries a primary executor and, on failure, falls back to a secondary executor. |
| | | 5 | | /// User cancellation is never swallowed. |
| | | 6 | | /// </summary> |
| | | 7 | | /// <param name="primary">The preferred executor to try first.</param> |
| | | 8 | | /// <param name="fallback">The executor to use if the primary throws.</param> |
| | | 9 | | /// <param name="shouldFallback"> |
| | | 10 | | /// Optional predicate controlling which exceptions trigger fallback. When <see langword="null"/> |
| | | 11 | | /// (the default), any non-cancellation exception triggers fallback. When provided, only exceptions |
| | | 12 | | /// where the predicate returns <see langword="true"/> trigger fallback; others propagate. |
| | | 13 | | /// </param> |
| | | 14 | | /// <example> |
| | | 15 | | /// <code> |
| | | 16 | | /// // Default — falls back on any failure |
| | | 17 | | /// var executor = new FallbackExecutor(primaryExecutor, fallbackExecutor); |
| | | 18 | | /// |
| | | 19 | | /// // Narrow — only fall back on timeouts |
| | | 20 | | /// var executor = new FallbackExecutor(primaryExecutor, fallbackExecutor, |
| | | 21 | | /// shouldFallback: ex => ex is TaskCanceledException or HttpRequestException); |
| | | 22 | | /// </code> |
| | | 23 | | /// </example> |
| | | 24 | | [DoNotAutoRegister] |
| | 10 | 25 | | public sealed class FallbackExecutor( |
| | 10 | 26 | | IStageExecutor primary, |
| | 10 | 27 | | IStageExecutor fallback, |
| | 10 | 28 | | Func<Exception, bool>? shouldFallback = null) : IStageExecutor |
| | | 29 | | { |
| | | 30 | | /// <inheritdoc /> |
| | | 31 | | public async Task<StageExecutionResult> ExecuteAsync( |
| | | 32 | | StageExecutionContext context, |
| | | 33 | | CancellationToken cancellationToken) |
| | | 34 | | { |
| | | 35 | | try |
| | | 36 | | { |
| | 7 | 37 | | return await primary.ExecuteAsync(context, cancellationToken); |
| | | 38 | | } |
| | 2 | 39 | | catch (OperationCanceledException) when (context.CallerCancellationToken.IsCancellationRequested) |
| | | 40 | | { |
| | 1 | 41 | | throw; |
| | | 42 | | } |
| | 4 | 43 | | catch (Exception ex) when (shouldFallback is null || shouldFallback(ex)) |
| | | 44 | | { |
| | 3 | 45 | | return await fallback.ExecuteAsync(context, cancellationToken); |
| | | 46 | | } |
| | 5 | 47 | | } |
| | | 48 | | } |