Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using MktData.Api.Actors.Exchanges;
- using MktData.Api.Models;
- using Proto;
- namespace MktData.Api.Actors;
- // The whole actor instance is recreated on restart. We lose the state e.g. fields will be lost.
- // What if we want to keep the state? We should either use persistence or never let the actor restart, i.e. try/catch to prevent failures.
- //
- // This actor spawns child "classic" local actors supposed to coordinate the virtual actors via PID.
- internal sealed class SubscriptionManager : IActor
- {
- private readonly ILogger<SubscriptionManager> _logger;
- private readonly IServiceProvider _serviceProvider;
- public SubscriptionManager(ILogger<SubscriptionManager> logger, IServiceProvider serviceProvider)
- {
- _logger = logger;
- _serviceProvider = serviceProvider;
- }
- public Task ReceiveAsync(IContext context)
- {
- // We forward the messages to child actors because this is a subscription manager,
- // i.e. it is meant for managing subscriptions for all exchanges.
- switch (context.Message)
- {
- case Started:
- break;
- case SubscriberRequest { Exchange: var exchange, AccountId: var accountId }:
- CreateChild(context, exchange, accountId);
- break;
- case OneOffBackFill { Exchange: var exchange, AccountId: var accountId }:
- ForwardToChild(context, exchange, accountId);
- break;
- case Notification:
- SendToAllChildren(context);
- break;
- case Terminated:
- StopAll(context);
- break;
- }
- return Task.CompletedTask;
- }
- private PID CreateChild(IContext context, string exchange, string accountId)
- {
- var childProps = Props.FromProducer(() =>
- // `ActivatorUtilities.CreateInstance` is used in opposed to `new FtxChildActor(...)`
- // because we partially DI `accountId` and let the IoC framework inject the logger itself.
- ActivatorUtilities.CreateInstance<FtxSubscriptionActor>(_serviceProvider, accountId)
- );
- return context.SpawnNamed(childProps, $"{exchange}:{accountId}");
- }
- private void ForwardToChild(IContext context, string exchange, string accountId)
- {
- var pid = PID.FromAddress(ActorSystem.NoHost, $"subscription-manager/{exchange}:{accountId}");
- context.Forward(pid);
- }
- // Fan-out mechanism
- private void SendToAllChildren(IContext context)
- {
- foreach (var child in context.Children)
- {
- context.Forward(child);
- }
- }
- // Terminates parent and its children
- private void StopAll(IContext context)
- {
- context.Stop(context.Self);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement