Пример #1
0
 static StreamSubscriptionMatch[] Match(IActorSystem system, string stream, IEnumerable <StreamSubscriptionSpecification> specifications)
 {
     return(specifications
            .Select(s => s.Match(system, stream))
            .Where(m => m != StreamSubscriptionMatch.None)
            .ToArray());
 }
Пример #2
0
 internal ActorRuntime(IActorSystem system, IActorHost host)
 {
     System     = system;
     Timers     = new TimerService(host);
     Reminders  = new ReminderService(host);
     Activation = new ActivationService(host);
 }
        public static StreamConsumer[] Match(IActorSystem system, StreamIdentity stream)
        {
            var specifications = DictionaryExtensions.Find(configuration, stream.Provider)
                                 ?? Enumerable.Empty <StreamSubscriptionSpecification>();

            return(Match(system, stream.Id, specifications));
        }
 public ChatClientNetChannel(IActorSystem<IRoomActor> rooms, ICallbacksGatewayNode callbacksNode, INetNode node,  
     ITransportChannel transportChannel, IMessageSerializer serializer, ICoreEvents logger, INetNodeConfig config, IBufferPool bufferPool) 
     : base(node, transportChannel, serializer, logger, config, bufferPool)
 {
     _rooms = rooms;
     _callbacksNode = callbacksNode;
 }
Пример #5
0
        static async Task Run(IActorSystem system)
        {
            var item = system.TypedActorOf <InventoryItem>("12345");

            await item.Tell(new Create("XBOX1"));

            await Print(item);

            await item.Tell(new CheckIn(10));

            await Print(item);

            await item.Tell(new CheckOut(5));

            await Print(item);

            await item.Tell(new Rename("XBOX360"));

            await Print(item);

            await item.Tell(new Deactivate());

            await Print(item);

            var inventory = system.TypedActorOf <Inventory>("#");

            var items = await inventory.Ask(new GetInventoryItems());

            Console.WriteLine($"\n# of items in inventory: {items.Length}");
            Array.ForEach(items, Print);

            var total = await inventory.Ask(new GetInventoryItemsTotal());

            Console.WriteLine($"\nTotal of all items inventory: {total}");
        }
Пример #6
0
        public static void Main()
        {
            Console.WriteLine("Booting cluster might take some time ...\n");

            var config = new ClusterConfiguration().LoadFromEmbeddedResource <Program>("Server.xml");

            Orleankka = ActorSystem.Configure()
                        .Cluster()
                        .From(config)
                        .Register(Assembly.GetExecutingAssembly())
                        .Serializer <NativeSerializer>()
                        .Done();

            HostConfiguration hostConfigs = new HostConfiguration()
            {
                UrlReservations = new UrlReservations()
                {
                    CreateAutomatically = true
                }
            };

            Uri address = new Uri("http://localhost:1234");

            using (var host = new NancyHost(address, new DefaultNancyBootstrapper(), hostConfigs))
            {
                host.Start();
                Console.WriteLine($"API is now accessible via {address}");
            }

            Console.WriteLine("\nPress any key to terminate ...");
            Console.ReadKey(true);

            Orleankka.Dispose();
            Environment.Exit(0);
        }
Пример #7
0
            protected override Task Run(IActorSystem system, Properties properties)
            {
                var client = CloudStorageAccount.Parse(properties.StorageAccount).CreateCloudTableClient();

                Table = client.GetTableReference(properties.TableName);
                return(TaskDone.Done);
            }
Пример #8
0
 /// <summary>
 /// CTOR
 /// Registers the actor into <paramref name="actorSystem"/> using given <paramref name="name"/>
 /// Enables the message processing of the actor and sets the <see cref="ReceiveTarget"/> to <see cref="Receive"/> method
 /// </summary>
 /// <param name="actorSystem">Actor system</param>
 /// <param name="name">Actor name</param>
 protected Actor(IActorSystem actorSystem, string name)
 {
     ActorSystem   = actorSystem;
     ReceiveTarget = Receive;
     Self          = actorSystem.RegisterActor(this, name);
     CanReceive    = true;
 }
Пример #9
0
        static async Task Run(IActorSystem system)
        {
            var e0 = system.ActorOf <Employee>("E0");
            var e1 = system.ActorOf <Employee>("E1");
            var e2 = system.ActorOf <Employee>("E2");
            var e3 = system.ActorOf <Employee>("E3");
            var e4 = system.ActorOf <Employee>("E4");

            var m0 = system.ActorOf <Manager>("M0");
            var m1 = system.ActorOf <Manager>("M1");

            await m0.Tell(new AddDirectReport { Employee = e0 });

            await m0.Tell(new AddDirectReport { Employee = e1 });

            await m0.Tell(new AddDirectReport { Employee = e2 });

            await m1.Tell(new AddDirectReport { Employee = e3 });

            await m1.Tell(new AddDirectReport { Employee = e4 });

            await e1.Tell(new Promote { NewLevel = 80 });

            await e4.Tell(new Promote { NewLevel = 80 });
        }
Пример #10
0
        static async Task Run(IActorSystem system)
        {
            var item = system.TypedActorOf<InventoryItem>("12345");

            await item.Tell(new Create("XBOX1"));
            await Print(item);

            await item.Tell(new CheckIn(10));
            await Print(item);

            await item.Tell(new CheckOut(5));
            await Print(item);

            await item.Tell(new Rename("XBOX360"));
            await Print(item);

            await item.Tell(new Deactivate());
            await Print(item);

            var inventory = system.TypedActorOf<Inventory>("#");

            var items = await inventory.Ask(new GetInventoryItems());
            Console.WriteLine($"\n# of items in inventory: {items.Length}");
            Array.ForEach(items, Print);

            var total = await inventory.Ask(new GetInventoryItemsTotal());
            Console.WriteLine($"\nTotal of all items inventory: {total}");
        }
Пример #11
0
 internal ActorRuntime(IActorSystem system, ActorEndpoint endpoint)
 {
     System     = system;
     Timers     = new TimerService(endpoint);
     Reminders  = new ReminderService(endpoint);
     Activation = new ActivationService(endpoint);
 }
Пример #12
0
 public ChatClientNetChannel(IActorSystem <IRoomActor> rooms, ICallbacksGatewayNode callbacksNode, INetNode node,
                             ITransportChannel transportChannel, IMessageSerializer serializer, ICoreEvents logger, INetNodeConfig config, IBufferPool bufferPool)
     : base(node, transportChannel, serializer, logger, config, bufferPool)
 {
     _rooms         = rooms;
     _callbacksNode = callbacksNode;
 }
Пример #13
0
        internal Actor(
            Option <ICluster> cluster,
            ActorItem parent,
            ProcessName name,
            Func <S, T, S> actor,
            Func <IActor, S> setup,
            Func <S, ProcessId, S> term,
            State <StrategyContext, Unit> strategy,
            ProcessFlags flags,
            ProcessSystemConfig settings,
            IActorSystem sys
            )
        {
            setupFn = setup ?? throw new ArgumentNullException(nameof(setup));
            actorFn = actor ?? throw new ArgumentNullException(nameof(actor));

            this.sys     = sys;
            Id           = parent.Actor.Id[name];
            this.cluster = cluster;
            this.flags   = flags == ProcessFlags.Default
                ? settings.GetProcessFlags(Id)
                : flags;

            termFn = term;

            Parent   = parent;
            Name     = name;
            Strategy = strategy;
            SetupRemoteSubscriptions(cluster, flags);
        }
Пример #14
0
 void EnsureSystem(ISerializerContext context)
 {
     if (system == null)
     {
         system = context.ServiceProvider.GetRequiredService <IActorSystem>();
     }
 }
Пример #15
0
        static async Task Run(IActorSystem system)
        {
            var lightbulb = system.ActorOf <ILightbulb>("eco");

            async Task Request(object message)
            {
                var response = await lightbulb.Ask <object>(message);

                if (response is string)
                {
                    WriteLine(response);
                }
            }

            await Request(new PressSwitch());
            await Request(new Touch());
            await Request(new PressSwitch());
            await Request(new Touch());

            await Request(new HitWithHammer());
            await Request(new PressSwitch());
            await Request(new Touch());

            await Request(new Fix());
            await Request(new Touch());

            // on
            await Request(new PressSwitch());

            await Task.Delay(5000);

            await Request(new Deactivate());

            await Request(new Touch());
        }
Пример #16
0
 internal ActorRuntime(IActorSystem system, ActorGrain grain)
 {
     System     = system;
     Timers     = new TimerService(grain);
     Reminders  = new ReminderService(grain);
     Activation = new ActivationService(grain);
 }
Пример #17
0
 internal void Initialize(string id, IActorSystem system, ActorEndpoint endpoint, ActorPrototype prototype)
 {
     Id       = id;
     System   = system;
     Endpoint = endpoint;
     _        = prototype;
 }
Пример #18
0
        public ActorSystemBootstrap(IActorSystem system, Option <ICluster> cluster, ProcessId rootId, IActor rootProcess, IActorInbox rootInbox, ProcessName rootProcessName, ActorSystemConfig config, ProcessSystemConfig settings, SessionSync sync)
        {
            System = system;
            Sync   = sync;

            var parent = new ActorItem(new NullProcess(system.Name), new NullInbox(), ProcessFlags.Default);

            rootProcess = new Actor <ActorSystemBootstrap, Unit>(
                cluster,
                parent,
                rootProcessName,
                SystemInbox,
                _ => this,
                null,
                Process.DefaultStrategy,
                ProcessFlags.Default,
                settings,
                system
                );

            root            = new ActorItem(rootProcess, rootInbox, rootProcess.Flags);
            Config          = config;
            Settings        = settings;
            Cluster         = cluster;
            RootProcess     = rootProcess;
            RootInbox       = rootInbox;
            RootProcessName = rootProcessName;
        }
Пример #19
0
 internal ActorRuntime(IActorSystem system, ActorEndpoint endpoint)
 {
     System      = system;
     Timers      = new TimerService(endpoint);
     Reminders   = new ReminderService(endpoint);
     Activation  = new ActivationService(endpoint);
 }
Пример #20
0
 internal void Initialize(string id, IActorSystem system, ActorEndpoint endpoint, ActorPrototype prototype)
 {
     Id = id;
     System = system;
     Endpoint = endpoint;
     Proto = prototype;
 }
Пример #21
0
        public static StreamSubscriptionMatch[] Match(IActorSystem system, StreamIdentity stream)
        {
            var specifications = configuration.Find(stream.Provider)
                                 ?? Enumerable.Empty <StreamSubscriptionSpecification>();

            return(Match(system, stream.Id, specifications));
        }
Пример #22
0
        protected Actor(string id, IActorSystem system)
        {
            Requires.NotNull(system, "system");
            Requires.NotNullOrWhitespace(id, "id");

            Id = id;
            System = system;
        }
Пример #23
0
        PersistentStreamProviderMatcher(IServiceProvider services, string[] providers)
        {
            system        = services.GetRequiredService <IActorSystem>();
            subscriptions = services.GetRequiredService <StreamSubscriptionSpecificationRegistry>();

            this.services  = services;
            this.providers = providers;
        }
Пример #24
0
        static async Task Run(IActorSystem system)
        {
            var a = system.ActorOf<DIActor>("A-123");
            var b = system.ActorOf<DIActor>("B-456");

            await a.Tell("Hello");
            await b.Tell("Bueno");
        }
Пример #25
0
        protected Actor(string id, IActorSystem system)
        {
            Requires.NotNull(system, "system");
            Requires.NotNullOrWhitespace(id, "id");

            Id     = id;
            System = system;
        }
 static StreamConsumer[] Match(IActorSystem system, string stream, IEnumerable <StreamSubscriptionSpecification> specifications)
 {
     return(specifications
            .Select(s => s.Match(stream))
            .Where(m => !m.Equals(StreamSubscriptionMatch.None))
            .Select(m => m.Consumer(system))
            .ToArray());
 }
Пример #27
0
        static async Task Run(IActorSystem system)
        {
            var a = system.ActorOf <DIActor>("A-123");
            var b = system.ActorOf <DIActor>("B-456");

            await a.Tell("Hello");

            await b.Tell("Bueno");
        }
Пример #28
0
 /// <summary>
 /// CTOR
 /// </summary>
 /// <param name="actorSystem">Actor system</param>
 /// <param name="responseType">Expected type of the response</param>
 /// <param name="waitHandle">Wait handle used to signal that the response has arrived </param>
 public SyncActor(IActorSystem actorSystem, Type responseType, AutoResetEvent waitHandle)
 {
     ActorSystem   = actorSystem;
     ReceiveTarget = Receive;
     ReceiveTarget = Receive;
     Self          = actorSystem.RegisterActor(this, $"SyncActor{Guid.NewGuid()}");
     CanReceive    = true;
     ResponseType  = responseType;
     WaitHandle    = waitHandle;
 }
Пример #29
0
            public Task Run(IActorSystem system, object properties)
            {
                HubGateway.system = system;

                ip = GetSiloIpAddress((ClusterActorSystem)system);
                Trace.TraceError(ip.ToString());

                var hub = GetLocalHub();

                return(hub.Tell(new Hub.Init()));
            }
Пример #30
0
            protected override async Task Run(IActorSystem system, IDictionary <string, string> properties)
            {
                if (done)
                {
                    throw new InvalidOperationException("Already done");
                }

                TopicStorage = await Demo.TopicStorage.Init(properties["account"]);

                done = true;
            }
        public SimpleMessageStreamProviderMatcher(IServiceProvider services, string name)
        {
            system = services.GetRequiredService <IActorSystem>();

            var registry = services.GetRequiredService <StreamSubscriptionSpecificationRegistry>();

            specifications = registry.Find(name);

            provider = SimpleMessageStreamProvider.Create(services, name);
            Name     = name;
        }
Пример #32
0
        /// <summary>
        /// CTOR
        /// Creates the mailbox (queue) for the actor
        /// </summary>
        /// <param name="actor">Actor</param>
        /// <param name="name">Name of the actor</param>
        /// <param name="actorSystem">Actor system</param>
        internal ActorRefInternal(IActor actor, string name, IActorSystem actorSystem)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException(nameof(name));
            }

            Actor            = actor ?? throw new ArgumentNullException(nameof(actor));
            this.actorSystem = actorSystem;
            Name             = name;
            Queue            = new ManagedMessageQueue();
        }
Пример #33
0
 public Topic(
     string id,
     IActorSystem system,
     ITimerService timers,
     IReminderService reminders,
     ITopicStorage storage)
     : base(id, system)
 {
     this.timers    = timers;
     this.reminders = reminders;
     this.storage   = storage;
 }
Пример #34
0
 public Api(
     string id,
     IActorSystem system,
     ITimerService timers,
     IObserverCollection observers,
     IApiWorker worker)
     : base(id, system)
 {
     this.timers    = timers;
     this.observers = observers;
     this.worker    = () => worker;
 }
Пример #35
0
 public Topic(
     string id, 
     IActorSystem system, 
     ITimerService timers, 
     IReminderService reminders, 
     ITopicStorage storage)
     : base(id, system)
 {
     this.timers = timers;
     this.reminders = reminders;
     this.storage = storage;
 }
Пример #36
0
        public override void Dispose()
        {
            if (host == null)
                return;

            host.StopOrleansSilo();
            host.UnInitializeOrleansSilo();
            host.Dispose();
            host = null;

            configurator.Dispose();
            current = null;
        }
Пример #37
0
        public override void Dispose()
        {
            if (host == null)
            {
                return;
            }

            host.StopOrleansSilo();
            host.UnInitializeOrleansSilo();
            host.Dispose();
            host = null;

            configurator.Dispose();
            current = null;
        }
        internal StreamSubscriptionMatch Match(IActorSystem system, string stream)
        {
            var target = matcher(stream);

            if (target == null)
            {
                return(StreamSubscriptionMatch.None);
            }

            var receiver = selector == null
                ? (Func <object, Task>)Reference(system, target).Tell
                : (x => Reference(system, selector(x)).Tell(x));

            return(new StreamSubscriptionMatch(target, receiver, filter));
        }
Пример #39
0
        static async Task Run(IActorSystem system)
        {
            var item = system.ActorOf<InventoryItem>("12345");

            await item.Tell(new CreateInventoryItem("XBOX1"));
            await Print(item);

            await item.Tell(new CheckInInventoryItem(10));
            await Print(item);

            await item.Tell(new CheckOutInventoryItem(5));
            await Print(item);

            await item.Tell(new RenameInventoryItem("XBOX360"));
            await Print(item);

            await item.Tell(new DeactivateInventoryItem());
            await Print(item);
        }
Пример #40
0
        static async Task Run(IActorSystem system)
        {
            var item = system.TypedActorOf<InventoryItem>("12345");

            await item.Call(x => x.Create("XBOX1"));
            await Print(item);

            await item.Call(x => x.CheckIn(10));
            await Print(item);

            await item.Call(x => x.CheckOut(5));
            await Print(item);

            await item.Call(x => x.Rename("XBOX360"));
            await Print(item);

            await item.Call(x => x.Deactivate());
            await Print(item);
        }
Пример #41
0
        static async Task Run(IActorSystem system)
        {
            var e0 = system.TypedActorOf<Employee>("E0");
            var e1 = system.TypedActorOf<Employee>("E1");
            var e2 = system.TypedActorOf<Employee>("E2");
            var e3 = system.TypedActorOf<Employee>("E3");
            var e4 = system.TypedActorOf<Employee>("E4");

            var m0 = system.TypedActorOf<Manager>("M0");
            var m1 = system.TypedActorOf<Manager>("M1");

            await m0.Tell(new AddDirectReport {Employee = e0});
            await m0.Tell(new AddDirectReport {Employee = e1});
            await m0.Tell(new AddDirectReport {Employee = e2});

            await m1.Tell(new AddDirectReport {Employee = e3});
            await m1.Tell(new AddDirectReport {Employee = e4});

            await e1.Tell(new Promote {NewLevel = 80});
            await e4.Tell(new Promote {NewLevel = 80});
        }
Пример #42
0
        static async Task Run(IActorSystem system)
        {
            var rwx = system.ActorOf<ReaderWriterLock>("rw-x");
            await rwx.Ask<int>(new Read()); // warm-up

            var writes = new List<Task>
            {
                rwx.Tell(new Write {Value = 1, Delay = TimeSpan.FromMilliseconds(1400)}),
                rwx.Tell(new Write {Value = 2, Delay = TimeSpan.FromMilliseconds(600)}),
            };

            var cts = new CancellationTokenSource();
            var reads = new List<int>();

            Console.Write("\nReads: ");
            var indicator = ConsolePosition.Current();

            Task.Run(async () =>
            {
                while (!cts.Token.IsCancellationRequested)
                {
                    reads.Add(await rwx.Ask(new Read()));
                    indicator.Write(reads.Count);
                }
            },
            cts.Token).Ignore();

            await Task.WhenAll(writes);
            cts.Cancel();

            Debug.Assert(reads.Count > writes.Count * 100,
                "Should actually serve reads in parallel, while there are slow sequential writes in flight");

            Debug.Assert(reads.OrderBy(x => x).SequenceEqual(reads),
                "All readers should see consistently incrementing sequence, despite that 2nd write is faster. Writes are queued");

            Debug.Assert(reads.Distinct().SequenceEqual(new[] {1, 2}),
                "Should see all changes of the write sequence");
        }
Пример #43
0
        private static async Task RunChatClient(IActorSystem system)
        {
            const string room = "Orleankka";

            Console.WriteLine("Enter your user name...");
            var userName = Console.ReadLine();
            
            var client = new ChatClient(system, userName, room);
            await client.Join();

            while (true)
            {
                var message = Console.ReadLine();

                if (message == "quit")
                {
                    await client.Leave();
                    break;
                }

                await client.Say(message);
            }
        }
Пример #44
0
        public static void Main(string[] args)
        {
            resume = args.Length == 1 && args[0] == "resume";

            Console.WriteLine("Make sure you've started Azure storage emulator using \".\\Nake.bat run\"!");
            Console.WriteLine("Running example. Booting cluster might take some time ...\n");

            var account = CloudStorageAccount.DevelopmentStorageAccount;
            SetupTable(account);

            system = ActorSystem.Configure()
                .Playground()
                .Register(Assembly.GetExecutingAssembly())
                .Serializer<NativeSerializer>()
                .Run<SS.Bootstrap>(new SS.Properties
                {
                    StorageAccount = account.ToString(true),
                    TableName = "ssexample"
                })
                .Done();

            try
            {
                (resume ? Resume() : Run()).Wait();
            }
            catch (AggregateException e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(e.InnerException.Message);
            }

            Console.WriteLine("\nPress any key to terminate ...");
            Console.ReadKey(true);

            system.Dispose();
            Environment.Exit(0);
        }
Пример #45
0
 internal ClusterActorSystem(IDisposable configurator, ClusterConfiguration configuration)
 {
     current = this;
     this.configurator = configurator;
     host = new SiloHost(Dns.GetHostName(), configuration);
 }
            public override StreamSubscriptionMatch Match(IActorSystem system, string stream)
            {
                var match = matcher.Match(stream);

                if (!match.Success)
                    return StreamSubscriptionMatch.None;

                var id = generator.Replace(target, m =>
                {
                    var placeholder = m.Value.Substring(1, m.Value.Length - 2);
                    return match.Groups[placeholder].Value;
                });

                return new StreamSubscriptionMatch(x => receiver(system, id)(x), filter);
            }
Пример #47
0
 public void SetUp()
 {
     system = TestActorSystem.Instance;
 }
 public abstract StreamSubscriptionMatch Match(IActorSystem system, string stream);
 public override StreamSubscriptionMatch Match(IActorSystem system, string stream)
 {
     return stream == source 
             ? new StreamSubscriptionMatch(x => receiver(system, target)(x), filter) 
             : StreamSubscriptionMatch.None;
 }
 public MouseActorsBackendClientNetChannel(IActorSystem<ITestActor> actorSystem, INetNode node, ITransportChannel transportChannel, IMessageSerializer serializer, 
     ICoreEvents logger, INetNodeConfig config, IBufferPool bufferPool)
     : base(node, transportChannel, serializer, logger, config, bufferPool)
 {
     _actorSystem = actorSystem;
 }
 void IActor.Init(IActorSystem system, ActorRef actorRef)
 {
     MySystem = system;
     ActorRef = actorRef;
     OnInitialise();
 }
 public StreamConsumer Consumer(IActorSystem system)
 {
     var actor = system.ActorOf(ActorType, ActorId);
     return new StreamConsumer(actor, Filter);
 }
Пример #53
0
 public Client(IActorSystem system, Observer observer)
 {
     this.system = system;
     this.observer = observer;
 }
Пример #54
0
 public ChatClient(IActorSystem system, string user, string room)
 {
     this.user = system.ActorOf<ChatUser>(user);
     this.room = system.StreamOf("sms", room);
 }
Пример #55
0
 public State(Map<ProcessName, ClusterNode> members, IActorSystem system)
 {
     Members = members.Filter(node => node != null);
     System = system;
 }
Пример #56
0
 public ClientActorSystem(IDisposable configurator)
 {
     current = this;
     this.configurator = configurator;
 }
Пример #57
0
 public ChatClient(IActorSystem system, string user, string room)
 {
     this.user = user;
     this.room = system.ActorOf<ChatRoom>(room);
 }
Пример #58
0
 internal EmbeddedActorSystem(AppDomain domain, IActorSystem client, IActorSystem cluster)
 {
     this.domain = domain;
     this.client = client;
     this.cluster = cluster;
 }
Пример #59
0
 /// <summary>
 /// Root Process setup
 /// </summary>
 public static State Setup(IActorSystem system) =>
     Heartbeat(State.Empty(system), system.Cluster);
Пример #60
0
 public override void Dispose()
 {
     GrainClient.Uninitialize();
     configurator.Dispose();
     current = null;
 }