|
| 1 | +namespace ModularPipelines.Helpers; |
| 2 | + |
| 3 | +/// <summary> |
| 4 | +/// Reusable utility for executing tasks with timeout support that can return |
| 5 | +/// control immediately when timeout elapses. |
| 6 | +/// </summary> |
| 7 | +/// <remarks> |
| 8 | +/// This implementation is inspired by the TUnit testing framework's TimeoutHelper. |
| 9 | +/// </remarks> |
| 10 | +internal static class TimeoutHelper |
| 11 | +{ |
| 12 | + /// <summary> |
| 13 | + /// Grace period to allow tasks to handle cancellation before throwing |
| 14 | + /// timeout exception. |
| 15 | + /// </summary> |
| 16 | + private static readonly TimeSpan GracePeriod = TimeSpan.FromSeconds(1); |
| 17 | + |
| 18 | + /// <summary> |
| 19 | + /// Executes a task with an optional timeout. If the timeout elapses before |
| 20 | + /// the task completes, control is returned to the caller immediately with a |
| 21 | + /// TimeoutException. |
| 22 | + /// </summary> |
| 23 | + public static async Task ExecuteWithTimeoutAsync( |
| 24 | + Func<CancellationToken, Task> taskFactory, |
| 25 | + TimeSpan? timeout, |
| 26 | + CancellationToken cancellationToken, |
| 27 | + string? timeoutMessage = null) |
| 28 | + { |
| 29 | + await ExecuteWithTimeoutAsync( |
| 30 | + async ct => |
| 31 | + { |
| 32 | + await taskFactory(ct).ConfigureAwait(false); |
| 33 | + return true; |
| 34 | + }, |
| 35 | + timeout, |
| 36 | + cancellationToken, |
| 37 | + timeoutMessage).ConfigureAwait(false); |
| 38 | + } |
| 39 | + |
| 40 | + /// <summary> |
| 41 | + /// Executes a task with an optional timeout and returns a result. If the |
| 42 | + /// timeout elapses before the task completes, control is returned to the |
| 43 | + /// caller immediately with a TimeoutException. |
| 44 | + /// </summary> |
| 45 | + public static async Task<T> ExecuteWithTimeoutAsync<T>( |
| 46 | + Func<CancellationToken, Task<T>> taskFactory, |
| 47 | + TimeSpan? timeout, |
| 48 | + CancellationToken cancellationToken, |
| 49 | + string? timeoutMessage = null) |
| 50 | + { |
| 51 | + // Fast path: no timeout specified |
| 52 | + if (!timeout.HasValue || timeout.Value == TimeSpan.Zero) |
| 53 | + { |
| 54 | + var task = taskFactory(cancellationToken); |
| 55 | + |
| 56 | + // If the token can't be cancelled, just await directly (avoid allocations) |
| 57 | + if (!cancellationToken.CanBeCanceled) |
| 58 | + { |
| 59 | + return await task.ConfigureAwait(false); |
| 60 | + } |
| 61 | + |
| 62 | + // Race against cancellation - TrySetCanceled makes the TCS throw |
| 63 | + // OperationCanceledException when awaited |
| 64 | + var tcs = new TaskCompletionSource<T>( |
| 65 | + TaskCreationOptions.RunContinuationsAsynchronously); |
| 66 | + using var reg = cancellationToken.Register( |
| 67 | + static state => ((TaskCompletionSource<T>)state!).TrySetCanceled(), |
| 68 | + tcs); |
| 69 | + |
| 70 | + // await await: first gets winning task, then awaits it |
| 71 | + // (propagates result or exception) |
| 72 | + return await await Task.WhenAny(task, tcs.Task) |
| 73 | + .ConfigureAwait(false); |
| 74 | + } |
| 75 | + |
| 76 | + // Timeout path: create linked token so task can observe both timeout |
| 77 | + // and external cancellation. |
| 78 | + using var timeoutCts = CancellationTokenSource |
| 79 | + .CreateLinkedTokenSource(cancellationToken); |
| 80 | + |
| 81 | + // Set up cancellation detection BEFORE scheduling timeout to avoid race |
| 82 | + // condition where timeout fires before registration completes |
| 83 | + // (with very small timeouts) |
| 84 | + var cancelledTcs = new TaskCompletionSource<T>( |
| 85 | + TaskCreationOptions.RunContinuationsAsynchronously); |
| 86 | + using var registration = timeoutCts.Token.Register( |
| 87 | + static state => ((TaskCompletionSource<T>)state!) |
| 88 | + .TrySetCanceled(), |
| 89 | + cancelledTcs); |
| 90 | + |
| 91 | + // Now schedule the timeout - registration is guaranteed to catch it |
| 92 | + timeoutCts.CancelAfter(timeout.Value); |
| 93 | + |
| 94 | + var executionTask = taskFactory(timeoutCts.Token); |
| 95 | + |
| 96 | + var winner = await Task.WhenAny(executionTask, cancelledTcs.Task) |
| 97 | + .ConfigureAwait(false); |
| 98 | + |
| 99 | + if (winner == cancelledTcs.Task) |
| 100 | + { |
| 101 | + // Determine if it was external cancellation or timeout |
| 102 | + if (cancellationToken.IsCancellationRequested) |
| 103 | + { |
| 104 | + throw new OperationCanceledException(cancellationToken); |
| 105 | + } |
| 106 | + |
| 107 | + // Timeout occurred - give the execution task a brief grace period |
| 108 | + // to clean up |
| 109 | + try |
| 110 | + { |
| 111 | + await executionTask.WaitAsync(GracePeriod, CancellationToken.None).ConfigureAwait(false); |
| 112 | + } |
| 113 | + catch |
| 114 | + { |
| 115 | + // Ignore all exceptions - task was cancelled, we're just giving |
| 116 | + // it time to clean up |
| 117 | + } |
| 118 | + |
| 119 | + // Even if task completed during grace period, timeout already elapsed |
| 120 | + // so we throw |
| 121 | + throw new TimeoutException( |
| 122 | + timeoutMessage ?? $"Operation timed out after {timeout.Value}"); |
| 123 | + } |
| 124 | + |
| 125 | + return await executionTask.ConfigureAwait(false); |
| 126 | + } |
| 127 | +} |
0 commit comments