/
TransportAdapters.cs
626 lines (558 loc) · 20.7 KB
/
TransportAdapters.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
//-----------------------------------------------------------------------
// <copyright file="TransportAdapters.cs" company="Akka.NET Project">
// Copyright (C) 2009-2023 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2023 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Akka.Actor;
using Akka.Actor.Internal;
using Akka.Event;
namespace Akka.Remote.Transport
{
/// <summary>
/// Interface for producing adapters that can wrap an underlying transport and augment it with additional behavior.
/// </summary>
public interface ITransportAdapterProvider
{
/// <summary>
/// Create a transport adapter that wraps the underlying transport
/// </summary>
/// <param name="wrappedTransport">The transport that will be wrapped.</param>
/// <param name="system">The actor system to which this transport belongs.</param>
/// <returns>A transport wrapped with the new adapter.</returns>
Transport Create(Transport wrappedTransport, ExtendedActorSystem system);
}
/// <summary>
/// INTERNAL API
/// </summary>
internal sealed class TransportAdaptersExtension : ExtensionIdProvider<TransportAdapters>
{
/// <inheritdoc cref="ExtensionIdProvider{T}"/>
public override TransportAdapters CreateExtension(ExtendedActorSystem system)
{
return new TransportAdapters((ActorSystemImpl)system);
}
#region Static methods
/// <summary>
/// TBD
/// </summary>
/// <param name="system">TBD</param>
/// <returns>TBD</returns>
public static TransportAdapters For(ActorSystem system)
{
return system.WithExtension<TransportAdapters, TransportAdaptersExtension>();
}
#endregion
}
/// <summary>
/// INTERNAL API
///
/// Extension that allows us to look up transport adapters based upon the settings provided inside <see cref="RemoteSettings"/>
/// </summary>
internal sealed class TransportAdapters : IExtension
{
/// <summary>
/// TBD
/// </summary>
/// <param name="system">TBD</param>
public TransportAdapters(ExtendedActorSystem system)
{
System = system;
Settings = ((IRemoteActorRefProvider)system.Provider).RemoteSettings;
}
/// <summary>
/// The ActorSystem
/// </summary>
public ActorSystem System { get; private set; }
/// <summary>
/// The Akka.Remote settings
/// </summary>
private readonly RemoteSettings Settings;
private Dictionary<string, ITransportAdapterProvider> _adaptersTable;
private Dictionary<string, ITransportAdapterProvider> AdaptersTable()
{
if (_adaptersTable != null) return _adaptersTable;
_adaptersTable = new Dictionary<string, ITransportAdapterProvider>();
foreach (var adapter in Settings.Adapters)
{
try
{
var adapterTypeName = Type.GetType(adapter.Value);
// ReSharper disable once AssignNullToNotNullAttribute
var newAdapter = (ITransportAdapterProvider)Activator.CreateInstance(adapterTypeName);
_adaptersTable.Add(adapter.Key, newAdapter);
}
catch (Exception ex)
{
throw new ArgumentException($"Cannot initiate transport adapter {adapter.Value}", ex);
}
}
return _adaptersTable;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="name">TBD</param>
/// <exception cref="ArgumentException">TBD</exception>
/// <returns>TBD</returns>
public ITransportAdapterProvider GetAdapterProvider(string name)
{
if (AdaptersTable().TryGetValue(name, out var provider))
return provider;
throw new ArgumentException($"There is no registered transport adapter provider with name {name}");
}
}
/// <summary>
/// Used to augment the protocol scheme of transports when enabled.
/// </summary>
public class SchemeAugmenter
{
/// <summary>
/// Creates a new <see cref="SchemeAugmenter"/> instance.
/// </summary>
/// <param name="addedSchemeIdentifier">The new identifier that will be added to the front of the pipeline.</param>
public SchemeAugmenter(string addedSchemeIdentifier)
{
AddedSchemeIdentifier = addedSchemeIdentifier;
}
/// <summary>
/// The scheme that will be added to the front of the protocol.
/// I.E. if using a TLS augmentor, the this field might read "ssl"
/// and the full scheme of addresses generated using this transport
/// might read "akka.tcp.ssl", the latter part being added by this augmenter.
/// </summary>
public readonly string AddedSchemeIdentifier;
/// <summary>
/// TBD
/// </summary>
/// <param name="originalScheme">TBD</param>
/// <returns>TBD</returns>
public string AugmentScheme(string originalScheme)
{
return string.Format("{0}.{1}", AddedSchemeIdentifier, originalScheme);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="address">TBD</param>
/// <returns>TBD</returns>
public Address AugmentScheme(Address address)
{
var protocol = AugmentScheme(address.Protocol);
return address.WithProtocol(protocol);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="scheme">TBD</param>
/// <returns>TBD</returns>
public string RemoveScheme(string scheme)
{
if (scheme.StartsWith(string.Format("{0}.", AddedSchemeIdentifier)))
return scheme.Remove(0, AddedSchemeIdentifier.Length + 1);
return scheme;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="address">TBD</param>
/// <returns>TBD</returns>
public Address RemoveScheme(Address address)
{
var protocol = RemoveScheme(address.Protocol);
return address.WithProtocol(protocol);
}
}
/// <summary>
/// An adapter that wraps a transport and provides interception capabilities
/// </summary>
public abstract class AbstractTransportAdapter : Transport
{
/// <summary>
/// TBD
/// </summary>
/// <param name="wrappedTransport">TBD</param>
protected AbstractTransportAdapter(Transport wrappedTransport)
{
WrappedTransport = wrappedTransport;
}
/// <summary>
/// TBD
/// </summary>
protected Transport WrappedTransport;
/// <summary>
/// TBD
/// </summary>
protected abstract SchemeAugmenter SchemeAugmenter { get; }
/// <summary>
/// TBD
/// </summary>
public override string SchemeIdentifier
{
get
{
return SchemeAugmenter.AugmentScheme(WrappedTransport.SchemeIdentifier);
}
}
/// <summary>
/// TBD
/// </summary>
public override long MaximumPayloadBytes
{
get
{
return WrappedTransport.MaximumPayloadBytes;
}
}
/// <summary>
/// TBD
/// </summary>
/// <param name="listenAddress">TBD</param>
/// <param name="listenerTask">TBD</param>
/// <returns>TBD</returns>
protected abstract Task<IAssociationEventListener> InterceptListen(Address listenAddress,
Task<IAssociationEventListener> listenerTask);
/// <summary>
/// TBD
/// </summary>
/// <param name="remoteAddress">TBD</param>
/// <param name="statusPromise">TBD</param>
protected abstract void InterceptAssociate(Address remoteAddress,
TaskCompletionSource<AssociationHandle> statusPromise);
/// <summary>
/// TBD
/// </summary>
/// <param name="remote">TBD</param>
/// <returns>TBD</returns>
public override bool IsResponsibleFor(Address remote)
{
return WrappedTransport.IsResponsibleFor(remote);
}
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override Task<(Address, TaskCompletionSource<IAssociationEventListener>)> Listen()
{
var upstreamListenerPromise = new TaskCompletionSource<IAssociationEventListener>();
return WrappedTransport.Listen().ContinueWith(async listenerTask =>
{
var listenAddress = listenerTask.Result.Item1;
var listenerPromise = listenerTask.Result.Item2;
listenerPromise.TrySetResult(await InterceptListen(listenAddress, upstreamListenerPromise.Task).ConfigureAwait(false));
return (SchemeAugmenter.AugmentScheme(listenAddress), upstreamListenerPromise);
}, TaskContinuationOptions.ExecuteSynchronously).Unwrap();
}
/// <summary>
/// TBD
/// </summary>
/// <param name="remoteAddress">TBD</param>
/// <returns>TBD</returns>
public override Task<AssociationHandle> Associate(Address remoteAddress)
{
var statusPromise = new TaskCompletionSource<AssociationHandle>();
InterceptAssociate(SchemeAugmenter.RemoveScheme(remoteAddress), statusPromise);
return statusPromise.Task;
}
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override Task<bool> Shutdown()
{
return WrappedTransport.Shutdown();
}
}
/// <summary>
/// TBD
/// </summary>
public abstract class AbstractTransportAdapterHandle : AssociationHandle
{
/// <summary>
/// TBD
/// </summary>
/// <param name="wrappedHandle">TBD</param>
/// <param name="addedSchemeIdentifier">TBD</param>
protected AbstractTransportAdapterHandle(AssociationHandle wrappedHandle, string addedSchemeIdentifier)
: this(wrappedHandle.LocalAddress, wrappedHandle.RemoteAddress, wrappedHandle, addedSchemeIdentifier) { }
/// <summary>
/// TBD
/// </summary>
/// <param name="originalLocalAddress">TBD</param>
/// <param name="originalRemoteAddress">TBD</param>
/// <param name="wrappedHandle">TBD</param>
/// <param name="addedSchemeIdentifier">TBD</param>
protected AbstractTransportAdapterHandle(Address originalLocalAddress, Address originalRemoteAddress, AssociationHandle wrappedHandle, string addedSchemeIdentifier) : base(originalLocalAddress, originalRemoteAddress)
{
WrappedHandle = wrappedHandle;
OriginalRemoteAddress = originalRemoteAddress;
OriginalLocalAddress = originalLocalAddress;
SchemeAugmenter = new SchemeAugmenter(addedSchemeIdentifier);
RemoteAddress = SchemeAugmenter.AugmentScheme(OriginalRemoteAddress);
LocalAddress = SchemeAugmenter.AugmentScheme(OriginalLocalAddress);
}
/// <summary>
/// TBD
/// </summary>
public Address OriginalLocalAddress { get; private set; }
/// <summary>
/// TBD
/// </summary>
public Address OriginalRemoteAddress { get; private set; }
/// <summary>
/// TBD
/// </summary>
public AssociationHandle WrappedHandle { get; private set; }
/// <summary>
/// TBD
/// </summary>
protected SchemeAugmenter SchemeAugmenter { get; private set; }
/// <summary>
/// TBD
/// </summary>
/// <param name="other">TBD</param>
/// <returns>TBD</returns>
protected bool Equals(AbstractTransportAdapterHandle other)
{
return Equals(OriginalLocalAddress, other.OriginalLocalAddress) && Equals(OriginalRemoteAddress, other.OriginalRemoteAddress) && Equals(WrappedHandle, other.WrappedHandle);
}
/// <inheritdoc/>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((AbstractTransportAdapterHandle)obj);
}
/// <inheritdoc/>
public override int GetHashCode()
{
unchecked
{
var hashCode = base.GetHashCode() + (OriginalLocalAddress != null ? OriginalLocalAddress.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (OriginalRemoteAddress != null ? OriginalRemoteAddress.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (WrappedHandle != null ? WrappedHandle.GetHashCode() : 0);
return hashCode;
}
}
}
/// <summary>
/// Marker interface for all transport operations
/// </summary>
public abstract class TransportOperation : INoSerializationVerificationNeeded
{
/// <summary>
/// TBD
/// </summary>
public static readonly TimeSpan AskTimeout = TimeSpan.FromSeconds(5);
}
/// <summary>
/// TBD
/// </summary>
public sealed class ListenerRegistered : TransportOperation
{
/// <summary>
/// TBD
/// </summary>
/// <param name="listener">TBD</param>
public ListenerRegistered(IAssociationEventListener listener)
{
Listener = listener;
}
/// <summary>
/// TBD
/// </summary>
public IAssociationEventListener Listener { get; private set; }
}
/// <summary>
/// TBD
/// </summary>
public sealed class AssociateUnderlying : TransportOperation
{
/// <summary>
/// TBD
/// </summary>
/// <param name="remoteAddress">TBD</param>
/// <param name="statusPromise">TBD</param>
public AssociateUnderlying(Address remoteAddress, TaskCompletionSource<AssociationHandle> statusPromise)
{
RemoteAddress = remoteAddress;
StatusPromise = statusPromise;
}
/// <summary>
/// TBD
/// </summary>
public Address RemoteAddress { get; private set; }
/// <summary>
/// TBD
/// </summary>
public TaskCompletionSource<AssociationHandle> StatusPromise { get; private set; }
}
/// <summary>
/// TBD
/// </summary>
public sealed class ListenUnderlying : TransportOperation
{
/// <summary>
/// TBD
/// </summary>
/// <param name="listenAddress">TBD</param>
/// <param name="upstreamListener">TBD</param>
public ListenUnderlying(Address listenAddress, Task<IAssociationEventListener> upstreamListener)
{
UpstreamListener = upstreamListener;
ListenAddress = listenAddress;
}
/// <summary>
/// TBD
/// </summary>
public Address ListenAddress { get; private set; }
/// <summary>
/// TBD
/// </summary>
public Task<IAssociationEventListener> UpstreamListener { get; private set; }
}
/// <summary>
/// TBD
/// </summary>
public sealed class DisassociateUnderlying : TransportOperation, IDeadLetterSuppression
{
/// <summary>
/// TBD
/// </summary>
/// <param name="info">TBD</param>
public DisassociateUnderlying(DisassociateInfo info = DisassociateInfo.Unknown)
{
Info = info;
}
/// <summary>
/// TBD
/// </summary>
public DisassociateInfo Info { get; private set; }
}
/// <summary>
/// Actor-based transport adapter
/// </summary>
public abstract class ActorTransportAdapter : AbstractTransportAdapter
{
/// <summary>
/// TBD
/// </summary>
/// <param name="wrappedTransport">TBD</param>
/// <param name="system">TBD</param>
protected ActorTransportAdapter(Transport wrappedTransport, ActorSystem system) : base(wrappedTransport)
{
System = system;
}
/// <summary>
/// TBD
/// </summary>
protected abstract string ManagerName { get; }
/// <summary>
/// TBD
/// </summary>
protected abstract Props ManagerProps { get; }
/// <summary>
/// TBD
/// </summary>
public static readonly TimeSpan AskTimeout = TimeSpan.FromSeconds(5);
/// <summary>
/// TBD
/// </summary>
protected volatile IActorRef manager;
private Task<IActorRef> RegisterManager()
{
return System.ActorSelection("/system/transports").Ask<IActorRef>(new RegisterTransportActor(ManagerProps, ManagerName));
}
/// <inheritdoc/>
protected override Task<IAssociationEventListener> InterceptListen(Address listenAddress, Task<IAssociationEventListener> listenerTask)
{
return RegisterManager().ContinueWith(mgrTask =>
{
manager = mgrTask.Result;
manager.Tell(new ListenUnderlying(listenAddress, listenerTask));
return (IAssociationEventListener)new ActorAssociationEventListener(manager);
}, TaskContinuationOptions.ExecuteSynchronously);
}
/// <inheritdoc/>
protected override void InterceptAssociate(Address remoteAddress, TaskCompletionSource<AssociationHandle> statusPromise)
{
manager.Tell(new AssociateUnderlying(remoteAddress, statusPromise));
}
/// <inheritdoc/>
public override Task<bool> Shutdown()
{
var stopTask = manager.GracefulStop((RARP.For(System).Provider).RemoteSettings.FlushWait);
var transportStopTask = WrappedTransport.Shutdown();
return Task.WhenAll(stopTask, transportStopTask).ContinueWith(x => x.IsCompleted && !(x.IsFaulted || x.IsCanceled), TaskContinuationOptions.ExecuteSynchronously);
}
}
/// <summary>
/// TBD
/// </summary>
public abstract class ActorTransportAdapterManager : UntypedActor
{
/// <summary>
/// Lightweight Stash implementation
/// </summary>
protected Queue<object> DelayedEvents = new();
/// <summary>
/// TBD
/// </summary>
protected IAssociationEventListener AssociationListener;
/// <summary>
/// TBD
/// </summary>
protected Address LocalAddress;
/// <summary>
/// TBD
/// </summary>
protected long UniqueId = 0L;
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
protected long NextId()
{
return Interlocked.Increment(ref UniqueId);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="message">TBD</param>
protected override void OnReceive(object message)
{
switch (message)
{
case ListenUnderlying listen:
LocalAddress = listen.ListenAddress;
var capturedSelf = Self;
listen.UpstreamListener.ContinueWith(
listenerRegistered => capturedSelf.Tell(new ListenerRegistered(listenerRegistered.Result)),
TaskContinuationOptions.ExecuteSynchronously);
break;
case ListenerRegistered listener:
AssociationListener = listener.Listener;
foreach (var dEvent in DelayedEvents)
{
Self.Tell(dEvent, ActorRefs.NoSender);
}
DelayedEvents = new Queue<object>();
Context.Become(Ready);
break;
default:
DelayedEvents.Enqueue(message);
break;
}
}
/// <summary>
/// Method to be implemented for child classes - processes messages once the transport is ready to send / receive
/// </summary>
/// <param name="message">TBD</param>
protected abstract void Ready(object message);
}
}