| | | 1 | | using CounterpointCollective.Dataflow.Internal; |
| | | 2 | | using CounterpointCollective.Utilities; |
| | | 3 | | using System.Threading.Tasks.Dataflow; |
| | | 4 | | |
| | | 5 | | namespace CounterpointCollective.Dataflow |
| | | 6 | | { |
| | | 7 | | /// <summary> |
| | | 8 | | /// A dataflow block that lets you construct and wire up an entire pipeline |
| | | 9 | | /// *before* the actual underlying block is available. |
| | | 10 | | /// |
| | | 11 | | /// <para> |
| | | 12 | | /// Use <b>DeferredBlock</b> when the real <see cref="IPropagatorBlock{I,O}"/> |
| | | 13 | | /// requires asynchronous setup before it can be created (e.g. initializing a |
| | | 14 | | /// database connection, loading configuration, performing I/O, warming caches, |
| | | 15 | | /// etc.). |
| | | 16 | | /// </para> |
| | | 17 | | /// |
| | | 18 | | /// <para> |
| | | 19 | | /// With this block you can: |
| | | 20 | | /// </para> |
| | | 21 | | /// <list type="bullet"> |
| | | 22 | | /// <item><description> |
| | | 23 | | /// Set up all <see cref="LinkTo"/> connections immediately. |
| | | 24 | | /// These links are recorded and only activated once the inner block is created. |
| | | 25 | | /// </description></item> |
| | | 26 | | /// <item><description> |
| | | 27 | | /// Start building the rest of your pipeline without having to await the |
| | | 28 | | /// initialization task. |
| | | 29 | | /// </description></item> |
| | | 30 | | /// <item><description> |
| | | 31 | | /// Accept incoming messages during the initialization phase; they are stored |
| | | 32 | | /// and offered to the inner block once it is ready. |
| | | 33 | | /// </description></item> |
| | | 34 | | /// <item><description> |
| | | 35 | | /// Request completion or fault at any time; the request is applied either |
| | | 36 | | /// immediately (if the inner block already exists) or propagated correctly |
| | | 37 | | /// once initialization finishes. |
| | | 38 | | /// </description></item> |
| | | 39 | | /// </list> |
| | | 40 | | /// |
| | | 41 | | /// <para> |
| | | 42 | | /// As soon as the asynchronous factory produces the real block: |
| | | 43 | | /// </para> |
| | | 44 | | /// <list type="bullet"> |
| | | 45 | | /// <item><description> |
| | | 46 | | /// Pending links are created. |
| | | 47 | | /// </description></item> |
| | | 48 | | /// <item><description> |
| | | 49 | | /// Postponed messages are forwarded. |
| | | 50 | | /// </description></item> |
| | | 51 | | /// <item><description> |
| | | 52 | | /// Any previously requested completion or fault is propagated. |
| | | 53 | | /// </description></item> |
| | | 54 | | /// </list> |
| | | 55 | | /// |
| | | 56 | | /// <para> |
| | | 57 | | /// After the inner block has been created, <b>DeferredBlock</b> behaves exactly as |
| | | 58 | | /// a transparent wrapper around it. |
| | | 59 | | /// </para> |
| | | 60 | | /// </summary> |
| | | 61 | | public class DeferredBlock<I, O> : IPropagatorBlock<I, O> |
| | | 62 | | { |
| | 26 | 63 | | private object Lock { get; } = new(); |
| | | 64 | | private readonly TaskCompletionSource _completionRequest; |
| | | 65 | | private readonly PostponedMessages<DeferredBlock<I, O>, I> _postponedMessages; |
| | 5 | 66 | | private readonly Dictionary<ISourceBlock<I>, I> _postponedValues = []; |
| | | 67 | | |
| | 12 | 68 | | private record Link(ITargetBlock<O> Target, DataflowLinkOptions Options) |
| | | 69 | | { |
| | 1 | 70 | | public IDisposable? RealLink { get; set; } |
| | | 71 | | } |
| | | 72 | | |
| | 5 | 73 | | private readonly List<Link> _pendingLinks = []; |
| | | 74 | | |
| | | 75 | | |
| | | 76 | | private volatile IPropagatorBlock<I, O>? inner; |
| | | 77 | | |
| | | 78 | | public DeferredBlock(Task<IPropagatorBlock<I, O>> factory, CancellationToken cancellationToken = default) |
| | 10 | 79 | | : this(_ => factory, cancellationToken) |
| | | 80 | | { |
| | 5 | 81 | | } |
| | | 82 | | |
| | 5 | 83 | | public DeferredBlock(Func<CancellationToken, Task<IPropagatorBlock<I, O>>> factory, CancellationToken cancellati |
| | | 84 | | { |
| | 5 | 85 | | _postponedMessages = new(this); |
| | | 86 | | |
| | 5 | 87 | | var tcs = new TaskCompletionSource(); |
| | 5 | 88 | | Completion = tcs.Task; |
| | | 89 | | |
| | | 90 | | #pragma warning disable CA2000 // Dispose objects before losing scope |
| | 5 | 91 | | var ctsCancelFactory = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); |
| | | 92 | | #pragma warning restore CA2000 // Dispose objects before losing scope |
| | | 93 | | |
| | 5 | 94 | | Task.Run(async () => |
| | 5 | 95 | | { |
| | 5 | 96 | | var factoryTask = await Task.WhenAny(factory(ctsCancelFactory.Token)); |
| | 5 | 97 | | if (factoryTask.IsFaulted) |
| | 5 | 98 | | { |
| | 1 | 99 | | tcs.SetException(factoryTask.Exception); |
| | 5 | 100 | | } |
| | 4 | 101 | | else if (factoryTask.IsCanceled) |
| | 5 | 102 | | { |
| | 2 | 103 | | if (cancellationToken.IsCancellationRequested) |
| | 5 | 104 | | { |
| | 5 | 105 | | //user requested cancellation |
| | 1 | 106 | | tcs.SetCanceled(); |
| | 5 | 107 | | } else |
| | 5 | 108 | | { |
| | 5 | 109 | | //Completion requested before factory finished. |
| | 1 | 110 | | tcs.SetResult(); |
| | 5 | 111 | | } |
| | 5 | 112 | | } |
| | 5 | 113 | | else //Factory done. |
| | 5 | 114 | | { |
| | 2 | 115 | | var block = await factoryTask; |
| | 2 | 116 | | lock (Lock) |
| | 5 | 117 | | { |
| | 5 | 118 | | //Create all pending links |
| | 6 | 119 | | foreach (var l in _pendingLinks) |
| | 5 | 120 | | { |
| | 1 | 121 | | l.RealLink = block.LinkTo(l.Target, l.Options); |
| | 5 | 122 | | } |
| | 2 | 123 | | _pendingLinks.Clear(); |
| | 5 | 124 | | //Offer the postponed messages |
| | 4 | 125 | | while (_postponedMessages.TryDequeuePostponed(out var p)) |
| | 5 | 126 | | { |
| | 2 | 127 | | var res = block.OfferMessage(p.MessageHeader, _postponedValues[p.SourceBlock], p.SourceBlock |
| | 2 | 128 | | if (res == DataflowMessageStatus.DecliningPermanently) |
| | 5 | 129 | | { |
| | 5 | 130 | | break; //Block already completed, stop offering. |
| | 5 | 131 | | } |
| | 5 | 132 | | } |
| | 2 | 133 | | _postponedValues.Clear(); |
| | 2 | 134 | | inner = block; |
| | 2 | 135 | | } |
| | 2 | 136 | | await block.Completion.PropagateCompletionAsync(tcs); |
| | 5 | 137 | | } |
| | 5 | 138 | | ctsCancelFactory.Dispose(); |
| | 10 | 139 | | }, CancellationToken.None); |
| | | 140 | | |
| | 5 | 141 | | _completionRequest = new TaskCompletionSource(); |
| | 5 | 142 | | _completionRequest.Task.ContinueWith(t => |
| | 5 | 143 | | { |
| | 2 | 144 | | lock(Lock) |
| | 5 | 145 | | { |
| | 2 | 146 | | if (inner == null) |
| | 5 | 147 | | { |
| | 5 | 148 | | //Completion requested before factory finished. |
| | 5 | 149 | | //Try to stop the factory task |
| | 0 | 150 | | ctsCancelFactory.Cancel(); |
| | 5 | 151 | | //Propagate completion to the targets of the links with PropagateCompletion. |
| | 0 | 152 | | foreach (var l in _pendingLinks.Where(l => l.Options.PropagateCompletion)) |
| | 5 | 153 | | { |
| | 0 | 154 | | _completionRequest.Task.PropagateCompletion(l.Target); |
| | 5 | 155 | | } |
| | 0 | 156 | | _pendingLinks.Clear(); |
| | 0 | 157 | | _postponedValues.Clear(); |
| | 5 | 158 | | } else |
| | 5 | 159 | | { |
| | 5 | 160 | | //Otherwise complete the block. |
| | 2 | 161 | | _completionRequest.Task.PropagateCompletion(inner); |
| | 5 | 162 | | } |
| | 2 | 163 | | } |
| | 7 | 164 | | }, CancellationToken.None); |
| | | 165 | | |
| | 5 | 166 | | Completion.ContinueWith(t => |
| | 5 | 167 | | { |
| | 5 | 168 | | lock (Lock) |
| | 5 | 169 | | { |
| | 5 | 170 | | if (inner == null) |
| | 5 | 171 | | { |
| | 3 | 172 | | _postponedMessages.Clear(); |
| | 3 | 173 | | _postponedValues.Clear(); |
| | 5 | 174 | | //If we completed before the inner block was created, complete the targets of the links with Pro |
| | 15 | 175 | | foreach (var l in _pendingLinks.Where(l => l.Options.PropagateCompletion)) |
| | 5 | 176 | | { |
| | 3 | 177 | | t.PropagateCompletion(l.Target); |
| | 5 | 178 | | } |
| | 3 | 179 | | _pendingLinks.Clear(); |
| | 5 | 180 | | } |
| | 5 | 181 | | } |
| | 10 | 182 | | }, CancellationToken.None); |
| | 5 | 183 | | } |
| | | 184 | | |
| | | 185 | | /// <exclude/> |
| | 17 | 186 | | public Task Completion { get; } |
| | | 187 | | |
| | | 188 | | /// <exclude/> |
| | | 189 | | public void Complete() |
| | | 190 | | { |
| | 2 | 191 | | lock (Lock) |
| | | 192 | | { |
| | 2 | 193 | | _completionRequest.TrySetResult(); |
| | 2 | 194 | | } |
| | 2 | 195 | | } |
| | | 196 | | |
| | | 197 | | /// <exclude/> |
| | | 198 | | public void Fault(Exception exception) |
| | | 199 | | { |
| | 0 | 200 | | lock (Lock) |
| | | 201 | | { |
| | 0 | 202 | | _completionRequest.TrySetException(exception); |
| | 0 | 203 | | } |
| | 0 | 204 | | } |
| | | 205 | | |
| | | 206 | | /// <exclude/> |
| | | 207 | | public DataflowMessageStatus OfferMessage(DataflowMessageHeader messageHeader, I messageValue, ISourceBlock<I>? |
| | | 208 | | { |
| | 23 | 209 | | if (inner == null) |
| | | 210 | | { |
| | 5 | 211 | | lock(Lock) |
| | | 212 | | { |
| | 5 | 213 | | if (inner != null) |
| | | 214 | | { |
| | 0 | 215 | | return inner.OfferMessage(messageHeader, messageValue, source, consumeToAccept); |
| | 5 | 216 | | } else if (source == null) |
| | | 217 | | { |
| | 0 | 218 | | return DataflowMessageStatus.Declined; |
| | 5 | 219 | | } else if (_completionRequest.Task.IsCompleted) |
| | | 220 | | { |
| | 0 | 221 | | return DataflowMessageStatus.DecliningPermanently; |
| | | 222 | | } else |
| | | 223 | | { |
| | 5 | 224 | | _postponedMessages.Postpone(source, messageHeader); |
| | 5 | 225 | | _postponedValues[source] = messageValue; |
| | 5 | 226 | | return DataflowMessageStatus.Postponed; |
| | | 227 | | } |
| | | 228 | | } |
| | | 229 | | } else |
| | | 230 | | { |
| | 18 | 231 | | return inner.OfferMessage(messageHeader, messageValue, source, consumeToAccept); |
| | | 232 | | } |
| | 5 | 233 | | } |
| | | 234 | | |
| | | 235 | | /// <exclude/> |
| | | 236 | | public IDisposable LinkTo(ITargetBlock<O> target, DataflowLinkOptions linkOptions) |
| | | 237 | | { |
| | 5 | 238 | | if (inner == null) |
| | | 239 | | { |
| | 5 | 240 | | lock(Lock) |
| | | 241 | | { |
| | 5 | 242 | | if (inner == null) |
| | | 243 | | { |
| | 4 | 244 | | var link = new Link(target, linkOptions); |
| | 4 | 245 | | _pendingLinks.Add(link); |
| | 4 | 246 | | return new ActionDisposable(() => |
| | 4 | 247 | | { |
| | 0 | 248 | | lock (Lock) |
| | 4 | 249 | | { |
| | 0 | 250 | | _pendingLinks.Remove(link); |
| | 0 | 251 | | link.RealLink?.Dispose(); |
| | 0 | 252 | | link.RealLink = null; |
| | 0 | 253 | | } |
| | 4 | 254 | | }); |
| | | 255 | | } |
| | | 256 | | else |
| | | 257 | | { |
| | 1 | 258 | | return inner.LinkTo(target, linkOptions); |
| | | 259 | | } |
| | | 260 | | } |
| | | 261 | | } else |
| | | 262 | | { |
| | 0 | 263 | | return inner.LinkTo(target, linkOptions); |
| | | 264 | | } |
| | 5 | 265 | | } |
| | | 266 | | |
| | | 267 | | /// <exclude/> |
| | | 268 | | public O? ConsumeMessage(DataflowMessageHeader messageHeader, ITargetBlock<O> target, out bool messageConsumed) |
| | | 269 | | { |
| | 0 | 270 | | if (inner == null) |
| | | 271 | | { |
| | 0 | 272 | | lock (Lock) |
| | | 273 | | { |
| | 0 | 274 | | if (inner == null) |
| | | 275 | | { |
| | 0 | 276 | | messageConsumed = false; |
| | 0 | 277 | | return default!; |
| | | 278 | | } |
| | | 279 | | else |
| | | 280 | | { |
| | 0 | 281 | | return inner.ConsumeMessage(messageHeader, target, out messageConsumed); |
| | | 282 | | } |
| | | 283 | | } |
| | | 284 | | } |
| | | 285 | | else |
| | | 286 | | { |
| | 0 | 287 | | return inner.ConsumeMessage(messageHeader, target, out messageConsumed); |
| | | 288 | | } |
| | 0 | 289 | | } |
| | | 290 | | |
| | | 291 | | /// <exclude/> |
| | | 292 | | public void ReleaseReservation(DataflowMessageHeader messageHeader, ITargetBlock<O> target) |
| | | 293 | | { |
| | 0 | 294 | | if (inner == null) |
| | | 295 | | { |
| | 0 | 296 | | lock (Lock) |
| | | 297 | | { |
| | 0 | 298 | | inner?.ReleaseReservation(messageHeader, target); |
| | 0 | 299 | | } |
| | | 300 | | } |
| | | 301 | | else |
| | | 302 | | { |
| | 0 | 303 | | inner.ReleaseReservation(messageHeader, target); |
| | | 304 | | } |
| | 0 | 305 | | } |
| | | 306 | | |
| | | 307 | | /// <exclude/> |
| | | 308 | | public bool ReserveMessage(DataflowMessageHeader messageHeader, ITargetBlock<O> target) |
| | | 309 | | { |
| | 0 | 310 | | if (inner == null) |
| | | 311 | | { |
| | 0 | 312 | | lock(Lock) |
| | | 313 | | { |
| | 0 | 314 | | return inner?.ReserveMessage(messageHeader, target) ?? false; |
| | | 315 | | } |
| | | 316 | | } else |
| | | 317 | | { |
| | 0 | 318 | | return inner.ReserveMessage(messageHeader, target); |
| | | 319 | | } |
| | 0 | 320 | | } |
| | | 321 | | } |
| | | 322 | | } |