Beispiel #1
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");
        }
Beispiel #2
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);
        }
Beispiel #3
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");
        }
Beispiel #4
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});
        }
Beispiel #5
0
 /// <summary>
 /// Acquires the actor reference for the given worker type.
 /// </summary>
 /// <param name="system">The reference to actor system</param>
 /// <param name="type">The type</param>
 /// <returns>An actor reference</returns>
 public static ActorRef WorkerOf(this IActorSystem system, string type)
 {
     return(system.ActorOf(ActorPath.From(type, "#")));
 }
Beispiel #6
0
 /// <summary>
 /// Acquires the actor reference for the given actor path string.
 /// </summary>
 /// <param name="system">The reference to actor system</param>
 /// <param name="path">The path string</param>
 /// <returns>An actor reference</returns>
 public static ActorRef ActorOf(this IActorSystem system, string path)
 {
     return(system.ActorOf(ActorPath.Parse(path)));
 }
 public ActorRef ActorOf(ActorPath path)
 {
     return(system.ActorOf(path));
 }
 public static ActorRef FreshActorOf <TActor>(this IActorSystem system) where TActor : Actor
 {
     return(system.ActorOf <TActor>(Guid.NewGuid().ToString()));
 }
Beispiel #9
0
        public static void MapActors(
            this IEndpointRouteBuilder routes,
            IActorSystem system,
            JsonSerializerOptions serializer,
            ActorRouteMapper mapper,
            string prefix = "")
        {
            routes.Map($"{prefix}/{{actor}}/{{id}}/{{message}}", async context =>
            {
                try
                {
                    await ProcessRequest();
                }
                catch (ActorRouteException ex)
                {
                    await RespondNotFound(ex.Message);
                }
                catch (Exception ex)
                {
                    await RespondError(ex.Message);
                }

                async Task ProcessRequest()
                {
                    var actor   = FindActor();
                    var message = FindMessage(actor);

                    var request  = await ReadRequest(message);
                    var response = await Send(actor, request);

                    if (response != null)
                    {
                        await WriteResponse(response);
                    }
                }

                string ActorRouteValue() => context.Request.RouteValues["actor"].ToString();
                string IdRouteValue() => context.Request.RouteValues["id"].ToString();
                string MessageRouteValue() => context.Request.RouteValues["message"].ToString();

                ActorRouteMapping FindActor()
                {
                    var actor = mapper.FindByRoute(ActorRouteValue());
                    return(actor ?? throw new ActorRouteException($"Can't find actor with key: {ActorRouteValue()}"));
                }

                MessageRouteMapping FindMessage(ActorRouteMapping actor)
                {
                    var message = actor.Find(MessageRouteValue());
                    return(message ?? throw new ActorRouteException($"Can't find message '{MessageRouteValue()}' for actor '{ActorRouteValue()}'"));
                }

                async Task RespondNotFound(string error)
                {
                    context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                    await context.Response.WriteAsync(error);
                }

                async Task RespondError(string error)
                {
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    await context.Response.WriteAsync(error);
                }

                async Task <object> Send(ActorRouteMapping route, object message)
                {
                    var actor = system.ActorOf(route.Interface, IdRouteValue());
                    return(await actor.Ask <object>(message));
                }

                async Task <object> ReadRequest(MessageRouteMapping message)
                {
                    if (context.Request.Method == HttpMethod.Get.ToString())
                    {
                        return(Activator.CreateInstance(message.Request));
                    }

                    if (context.Request.Method == HttpMethod.Post.ToString())
                    {
                        return(await Deserialize(context.Request.BodyReader, message.Request, context.RequestAborted));
                    }

                    throw new ActorRouteException("Unsupported http verb: " + context.Request.Method);
                }

                async ValueTask WriteResponse(object result)
                {
                    await Serialize(result, context.Response.BodyWriter);
                }
            });

            async ValueTask <object> Deserialize(PipeReader reader, Type type, CancellationToken cancellationToken)
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    var frame = await reader.ReadAsync(cancellationToken);

                    var buffer = frame.Buffer;

                    var message = JsonSerializer.Deserialize(buffer.FirstSpan, type, serializer);
                    reader.AdvanceTo(buffer.Start, buffer.End);

                    if (frame.IsCompleted)
                    {
                        return(message);
                    }
                }

                return(null);
            }

            async ValueTask Serialize(object obj, PipeWriter writer)
            {
                await JsonSerializer.SerializeAsync(writer.AsStream(), obj, obj.GetType(), serializer);
            }
        }
Beispiel #10
0
 /// <summary>
 /// Acquires the actor reference for the given id and type of the actor.
 /// The type could be either an interface or implementation class.
 /// </summary>
 /// <typeparam name="TActor">The type of the actor</typeparam>
 /// <param name="system">The reference to actor system</param>
 /// <param name="id">The id</param>
 /// <returns>An actor reference</returns>
 public static ActorRef ActorOf<TActor>(this IActorSystem system, string id) where TActor : IActor
 {
     return system.ActorOf(typeof(TActor), id);
 }
Beispiel #11
0
 public ChatClient(IActorSystem system, string user, string room)
 {
     this.user = system.ActorOf <ChatUser>(user);
     this.room = system.StreamOf <SimpleMessageStreamProvider>(room);
 }
Beispiel #12
0
 /// <summary>
 /// Acquires the reference for the given id and type of the actor.
 /// </summary>
 /// <typeparam name="TActor">The type of the actor</typeparam>
 /// <param name="system">The reference to actor system</param>
 /// <param name="id">The id</param>
 /// <returns>An actor reference</returns>
 public static ActorRef ActorOf <TActor>(this IActorSystem system, string id) where TActor : Actor
 {
     return(system.ActorOf(ActorPath.From(typeof(TActor), id)));
 }
Beispiel #13
0
 internal static ActorRef ActorOf(this IActorSystem system, ActorType type, string id)
 {
     return(system.ActorOf(ActorPath.From(type.Code, id)));
 }
Beispiel #14
0
 /// <summary>
 /// Acquires the typed actor reference for the given id and type of the actor.
 /// The type could be either an interface or implementation class.
 /// </summary>
 /// <typeparam name="TActor">The type of the actor</typeparam>
 /// <param name="system">The reference to actor system</param>
 /// <param name="id">The id</param>
 public static ActorRef <TActor> TypedActorOf <TActor>(this IActorSystem system, string id) where TActor : IActor
 {
     return(new ActorRef <TActor>(system.ActorOf(typeof(TActor).ToActorPath(id))));
 }
Beispiel #15
0
 public ChatClient(IActorSystem system, string user, string room)
 {
     this.user = system.ActorOf <ChatUser>(user);
     this.room = system.StreamOf("sms", room);
 }
Beispiel #16
0
 /// <summary>
 /// Acquires the typed actor reference for the given id and type of the worker actor.
 /// The type could be either an interface or implementation class.
 /// </summary>
 /// <typeparam name="TActor">The type of the actor</typeparam>
 /// <param name="system">The reference to actor system</param>
 public static ActorRef <TActor> TypedWorkerOf <TActor>(this IActorSystem system) where TActor : IActor
 {
     return(new ActorRef <TActor>(system.ActorOf(typeof(TActor).ToActorPath("#"))));
 }
Beispiel #17
0
 public ChatClient(IActorSystem system, string user, string room)
 {
     this.user = system.ActorOf<ChatUser>(user);
     this.room = system.StreamOf<SimpleMessageStreamProvider>(room);
 }
        public StreamConsumer Consumer(IActorSystem system)
        {
            var actor = system.ActorOf(ActorType, ActorId);

            return(new StreamConsumer(actor, Filter));
        }
 static IEnumerable <Task> Autorun(IActorSystem system, string type, IEnumerable <string> ids) =>
 ids.Select(id => system.ActorOf(type, id).Autorun());
Beispiel #20
0
 public ChatClient(IActorSystem system, string user, string room)
 {
     this.user = user;
     this.room = system.ActorOf<ChatRoom>(room);
 }
Beispiel #21
0
 ActorRef Reference(IActorSystem system, string id) => system.ActorOf(ActorPath.For(Interface, id));
Beispiel #22
0
 public ChatClient(IActorSystem system, string user, string room)
 {
     this.user = system.ActorOf<ChatUser>(user);
     this.room = system.StreamOf("sms", room);
 }
Beispiel #23
0
 /// <summary>
 /// Acquires the actor reference for the given actor type and id.
 /// </summary>
 /// <param name="system">The reference to actor system</param>
 /// <param name="type">The actor type</param>
 /// <param name="id">The actor id</param>
 /// <returns>An actor reference</returns>
 public static ActorRef ActorOf(this IActorSystem system, string type, string id)
 {
     return(system.ActorOf(ActorPath.From(type, id)));
 }
 public StreamConsumer Consumer(IActorSystem system)
 {
     var actor = system.ActorOf(ActorType, ActorId);
     return new StreamConsumer(actor, Filter);
 }
Beispiel #25
0
 public ChatClient(IActorSystem system, string user, string room)
 {
     this.user = user;
     this.room = system.ActorOf <ChatRoom>(room);
 }