public void IfSeveralActorsRegisteredToHandleTheMessage_TheAreFoundInRoundRobinManner() { var messageIdentifier = MessageIdentifier.Create <SimpleMessage>(); var registrations = EnumerableExtensions.Produce(Randomizer.Int32(6, 16), () => new InternalRouteRegistration { ReceiverIdentifier = ReceiverIdentities.CreateForActor(), DestinationSocket = new LocalSocket <IMessage>(), MessageContracts = new[] { new MessageContract { Message = messageIdentifier } } }); registrations.ForEach(r => internalRoutingTable.AddMessageRoute(r)); // foreach (var registration in registrations) { var socket = internalRoutingTable.FindRoutes(new InternalRouteLookupRequest { Message = messageIdentifier }) .First(); var localSocket = registration.DestinationSocket; // Assert.AreEqual(localSocket, socket); } }
public void AddMessageRoute_AddsActorRoute() { var actor = ReceiverIdentities.CreateForActor(); var localSocket = new LocalSocket <IMessage>(); var messageIdentifier = MessageIdentifier.Create <SimpleMessage>(); var registration = new InternalRouteRegistration { ReceiverIdentifier = actor, DestinationSocket = localSocket, MessageContracts = new[] { new MessageContract { Message = messageIdentifier } } }; // internalRoutingTable.AddMessageRoute(registration); // var lookupRequest = new InternalRouteLookupRequest { ReceiverIdentity = actor, Message = messageIdentifier }; var socket = internalRoutingTable.FindRoutes(lookupRequest).First(); Assert.AreEqual(localSocket, socket); }
public void FindRoutesByActorReceiverIdentifier_ReturnsActorHostSocket() { var messageIdentifier = MessageIdentifier.Create <SimpleMessage>(); var registrations = EnumerableExtensions.Produce(Randomizer.Int32(3, 6), () => new InternalRouteRegistration { ReceiverIdentifier = ReceiverIdentities.CreateForActor(), DestinationSocket = new LocalSocket <IMessage>(), MessageContracts = new[] { new MessageContract { Message = messageIdentifier } } }); registrations.ForEach(r => internalRoutingTable.AddMessageRoute(r)); var lookupRoute = registrations.First(); var actor = lookupRoute.ReceiverIdentifier; var localSocket = lookupRoute.DestinationSocket; // var socket = internalRoutingTable.FindRoutes(new InternalRouteLookupRequest { Message = messageIdentifier, ReceiverIdentity = actor }) .First(); // Assert.AreEqual(localSocket, socket); }
public void AddMessageRoute_AddsLocalOrExternalActorRoute(bool keepLocal) { var actor = ReceiverIdentities.CreateForActor(); var localSocket = new LocalSocket <IMessage>(); var messageIdentifier = MessageIdentifier.Create <SimpleMessage>(); var registration = new InternalRouteRegistration { ReceiverIdentifier = actor, DestinationSocket = localSocket, MessageContracts = new[] { new MessageContract { Message = messageIdentifier, KeepRegistrationLocal = keepLocal } } }; // internalRoutingTable.AddMessageRoute(registration); // var route = internalRoutingTable.GetAllRoutes().Actors.First().Actors.First(); Assert.AreEqual(keepLocal, route.LocalRegistration); Assert.IsTrue(Unsafe.ArraysEqual(actor.Identity, route.Identity)); }
/// <summary> /// Listens for incoming messages on the <see cref="NetworkStream" />. /// Fires a <see cref="MessageReceived" /> event when a new <see cref="IMessage" /> has been received. /// </summary> /// <param name="clientUserId">The Id of the user the NetworkStream is linked to.</param> /// <param name="tcpClient">The stream between the Client and the Server.</param> public void ReceiveMessages(int clientUserId, TcpClient tcpClient) { using (NetworkStream networkStream = tcpClient.GetStream()) { try { while (true) { MessageIdentifier messageIdentifier = MessageIdentifierSerialiser.DeserialiseMessageIdentifier(networkStream); IMessageSerialiser serialiser = SerialiserFactory.GetSerialiser(messageIdentifier); IMessage message = serialiser.Deserialise(networkStream); OnMessageReceived(new MessageEventArgs(message)); } } catch (IOException) { Log.Info("Detected client disconnection, notifying Server of ClientDisconnection."); IMessage message = new ClientDisconnection(clientUserId); OnMessageReceived(new MessageEventArgs(message)); } } }
public static CallbackPoint Create <T1, T2, T3>(byte[] partition = null) where T1 : IIdentifier, new() where T2 : IIdentifier, new() where T3 : IIdentifier, new() => new CallbackPoint(MessageIdentifier.Create <T1>(partition), MessageIdentifier.Create <T2>(partition), MessageIdentifier.Create <T3>(partition));
public void AssignActor_SendsRegisterationMessage() { var partition = Guid.NewGuid().ToByteArray(); var messageIdentifier = MessageIdentifier.Create <SimpleMessage>(partition); try { StartActorHost(actorHost); actorHost.AssignActor(new ConfigurableActor(new[] { new MessageHandlerDefinition { Handler = _ => null, Message = new MessageDefinition(messageIdentifier.Identity, messageIdentifier.Version, partition) } })); AsyncOp.Sleep(); Func <InternalRouteRegistration, bool> registrationRequest = (reg) => reg.MessageContracts.Any(id => Unsafe.ArraysEqual(id.Message.Identity, messageIdentifier.Identity) && Unsafe.ArraysEqual(id.Message.Partition, messageIdentifier.Partition) && id.Message.Version == messageIdentifier.Version); internalRegistrationSender.Verify(m => m.Send(It.Is <InternalRouteRegistration>(reg => registrationRequest(reg))), Times.Once); } finally { actorHost.Stop(); } }
public void IfSameMessageRouteRequestedMultipleTimes_MessageForThatRouteIsSentOnlyOnce() { var receiverIdentifier = ReceiverIdentities.CreateForActor(); var messageIdentifier = MessageIdentifier.Create <SimpleMessage>(); // for (var i = 0; i < Randomizer.Int32(5, 15); i++) { routeDiscovery.RequestRouteDiscovery(new MessageRoute { Message = messageIdentifier, Receiver = receiverIdentifier }); } routeDiscovery.Start(); AsyncOp.Sleep(); routeDiscovery.Stop(); // Func <IMessage, bool> isDiscoveryMessage = msg => { var payload = msg.GetPayload <DiscoverMessageRouteMessage>(); Assert.IsNull(payload.ReceiverIdentity); Assert.IsTrue(Unsafe.ArraysEqual(payload.MessageContract.Identity, messageIdentifier.Identity)); Assert.IsTrue(Unsafe.ArraysEqual(payload.MessageContract.Partition, messageIdentifier.Partition)); Assert.AreEqual(payload.MessageContract.Version, messageIdentifier.Version); Assert.IsTrue(Unsafe.ArraysEqual(payload.RequestorNodeIdentity, scaleOutAddress.Identity)); Assert.AreEqual(payload.RequestorUri, scaleOutAddress.Uri.ToSocketAddress()); return(true); }; autoDiscoverySender.Verify(m => m.EnqueueMessage(It.Is <IMessage>(msg => isDiscoveryMessage(msg))), Times.Once); }
public void Message_HasIdentitySet() { var message = Message.CreateFlowStartMessage(new SimpleMessage()); Assert.IsNotNull(message.Identity); Assert.IsTrue(message.Equals(MessageIdentifier.Create <SimpleMessage>())); }
public void TestRouteIsRemoved_BySocketIdentifier() { var logger = new Mock<ILogger>(); var externalRoutingTable = new ExternalRoutingTable(logger.Object); var messageHandlerIdentifier1 = new MessageIdentifier(Message.CurrentVersion, SimpleMessage.MessageIdentity); var messageHandlerIdentifier2 = new MessageIdentifier(Message.CurrentVersion, AsyncMessage.MessageIdentity); var socketIdentifier1 = new SocketIdentifier(Guid.NewGuid().ToByteArray()); var socketIdentifier2 = new SocketIdentifier(Guid.NewGuid().ToByteArray()); var uri1 = new Uri("tcp://127.0.0.1:40"); var uri2 = new Uri("tcp://127.0.0.2:40"); var node1 = new Node(uri1, socketIdentifier1.Identity); var node2 = new Node(uri2, socketIdentifier2.Identity); externalRoutingTable.AddMessageRoute(messageHandlerIdentifier1, socketIdentifier1, uri1); externalRoutingTable.AddMessageRoute(messageHandlerIdentifier2, socketIdentifier1, uri1); externalRoutingTable.AddMessageRoute(messageHandlerIdentifier1, socketIdentifier2, uri2); Assert.AreEqual(node1, externalRoutingTable.FindRoute(messageHandlerIdentifier1)); externalRoutingTable.RemoveNodeRoute(socketIdentifier1); Assert.AreEqual(node2, externalRoutingTable.FindRoute(messageHandlerIdentifier1)); Assert.AreEqual(node2, externalRoutingTable.FindRoute(messageHandlerIdentifier1)); Assert.IsNull(externalRoutingTable.FindRoute(messageHandlerIdentifier2)); }
public override Task <StartResponse> Start(StartRequest request, ServerCallContext context) { mutex = new Mutex(); latencies = new List <long>(); received_messages = new List <MessageIdentifier>(); try { client = SimpleSubscriber.CreateAsync( new SubscriptionName(request.Project, request.PubsubOptions.Subscription) ).Result; Console.WriteLine("Client created successfully."); } catch (Exception e) { Console.WriteLine("Error starting client: " + e.ToString()); } client.StartAsync((msg, ct) => { long now = CurrentTimeMillis(); var identifier = new MessageIdentifier(); mutex.WaitOne(); latencies.Add(now - long.Parse(msg.Attributes["sendTime"])); identifier.PublisherClientId = long.Parse(msg.Attributes["clientId"]); identifier.SequenceNumber = int.Parse(msg.Attributes["sequenceNumber"]); received_messages.Add(identifier); mutex.ReleaseMutex(); return(Task.FromResult(SimpleSubscriber.Reply.Ack)); }); return(Task.FromResult(new StartResponse())); }
public void RegisterOwnGlobalRoutes_RegisteresOnlyGlobalyRegisteredActors() { var actors = EnumerableExtensions.Produce(Randomizer.Int32(5, 15), i => new ReceiverIdentifierRegistration(ReceiverIdentities.CreateForActor(), i % 2 == 0)); var messageIdentifier = MessageIdentifier.Create <SimpleMessage>(); var internalRoutes = new InternalRouting { Actors = new[] { new MessageActorRoute { Message = messageIdentifier, Actors = actors } }, MessageHubs = Enumerable.Empty <MessageHubRoute>() }; internalRoutingTable.Setup(m => m.GetAllRoutes()).Returns(internalRoutes); var globalActors = internalRoutes.Actors .SelectMany(r => r.Actors.Where(a => !a.LocalRegistration)) .Select(a => new ReceiverIdentifier(a.Identity)); // registrar.RegisterOwnGlobalRoutes(domain); // Func <IEnumerable <MessageRoute>, bool> isGlobalMessageRoute = mrs => { Assert.IsTrue(mrs.All(mr => mr.Message == messageIdentifier)); CollectionAssert.AreEquivalent(globalActors, mrs.Select(mr => mr.Receiver)); return(true); }; clusterMonitor.Verify(m => m.RegisterSelf(It.Is <IEnumerable <MessageRoute> >(mrs => isGlobalMessageRoute(mrs)), domain), Times.Once); }
public void WhenClusterMonitorStarts_ClusterRoutesAreRequested() { Func <Barrier, bool> setBarrier = (b) => { b.SignalAndWait(); return(true); }; autoDiscoveryListener.Setup(m => m.StartBlockingListenMessages(It.IsAny <Action>(), It.IsAny <CancellationToken>(), It.Is <Barrier>(b => setBarrier(b)))); autoDiscoverySender.Setup(m => m.StartBlockingSendMessages(It.IsAny <CancellationToken>(), It.Is <Barrier>(b => setBarrier(b)))); // clusterMonitor.Start(); // Func <Message, bool> isRequestClusterRoutesMessage = (msg) => { if (msg.Equals(MessageIdentifier.Create <RequestClusterMessageRoutesMessage>())) { var payload = msg.GetPayload <RequestClusterMessageRoutesMessage>(); Assert.IsTrue(Unsafe.ArraysEqual(scaleOutAddress.Identity, payload.RequestorNodeIdentity)); Assert.AreEqual(scaleOutAddress.Uri.ToSocketAddress(), payload.RequestorUri); return(true); } return(false); }; autoDiscoverySender.Verify(m => m.EnqueueMessage(It.Is <IMessage>(msg => isRequestClusterRoutesMessage(msg.As <Message>()))), Times.Once); }
public void WhenCusterMonitorStops_UnregisterNodeMessageIsSent() { Func <Barrier, bool> setBarrier = (b) => { b.SignalAndWait(); return(true); }; autoDiscoveryListener.Setup(m => m.StartBlockingListenMessages(It.IsAny <Action>(), It.IsAny <CancellationToken>(), It.Is <Barrier>(b => setBarrier(b)))); autoDiscoverySender.Setup(m => m.StartBlockingSendMessages(It.IsAny <CancellationToken>(), It.Is <Barrier>(b => setBarrier(b)))); // clusterMonitor.Start(); AsyncOp.Sleep(); clusterMonitor.Stop(); // Func <IMessage, bool> isUnregistrationMessage = msg => { if (msg.Equals(MessageIdentifier.Create <UnregisterNodeMessage>())) { var payload = msg.GetPayload <UnregisterNodeMessage>(); Assert.IsTrue(Unsafe.ArraysEqual(scaleOutAddress.Identity, payload.ReceiverNodeIdentity)); Assert.AreEqual(scaleOutAddress.Uri.ToSocketAddress(), payload.Uri); return(true); } return(false); }; autoDiscoverySender.Verify(m => m.EnqueueMessage(It.Is <IMessage>(msg => isUnregistrationMessage(msg))), Times.Once); }
public Task SaveMessageContextAsync(long chatId, long messageId, MessageContext context) { var id = new MessageIdentifier(chatId, messageId); _contexts[id] = context; return(Task.CompletedTask); }
public void IfSecurityExceptionThrownForOneMessageRoute_OthersAreStillSent() { var messageHub = ReceiverIdentities.CreateForMessageHub(); var allowedDomains = EnumerableExtensions.Produce(Randomizer.Int32(2, 5), () => Guid.NewGuid().ToString()); securityProvider.Setup(m => m.GetAllowedDomains()).Returns(allowedDomains); securityProvider.Setup(m => m.GetDomain(It.IsAny <byte[]>())).Throws <SecurityException>(); // routeDiscovery.RequestRouteDiscovery(new MessageRoute { Receiver = messageHub }); routeDiscovery.RequestRouteDiscovery(new MessageRoute { Receiver = ReceiverIdentities.CreateForActor(), Message = MessageIdentifier.Create <SimpleMessage>() }); routeDiscovery.Start(); AsyncOp.Sleep(); routeDiscovery.Stop(); // Func <IMessage, bool> isDiscoveryMessage = msg => { var payload = msg.GetPayload <DiscoverMessageRouteMessage>(); CollectionAssert.Contains(allowedDomains, msg.Domain); Assert.IsTrue(Unsafe.ArraysEqual(messageHub.Identity, payload.ReceiverIdentity)); Assert.IsNull(payload.MessageContract); Assert.IsTrue(Unsafe.ArraysEqual(payload.RequestorNodeIdentity, scaleOutAddress.Identity)); Assert.AreEqual(payload.RequestorUri, scaleOutAddress.Uri.ToSocketAddress()); return(true); }; autoDiscoverySender.Verify(m => m.EnqueueMessage(It.Is <IMessage>(msg => isDiscoveryMessage(msg))), Times.Exactly(allowedDomains.Count())); logger.Verify(m => m.Error(It.Is <object>(exc => exc is SecurityException)), Times.Once); }
public void RemoveMessageRouteForNode_RemovesAllActorRegistrationsForThisMessageForThisNode() { var nodeIdentity = Guid.NewGuid().ToByteArray(); var messageIdentifier = MessageIdentifier.Create <SimpleMessage>(); var routeRegistrations = EnumerableExtensions.Produce(Randomizer.Int32(3, 10), () => CreateActorRouteRegistration(messageIdentifier, ReceiverIdentities.CreateForActor(), nodeIdentity)); routeRegistrations.ForEach(r => externalRoutingTable.AddMessageRoute(r)); // var res = externalRoutingTable.RemoveMessageRoute(new ExternalRouteRemoval { Route = new MessageRoute { Message = messageIdentifier }, NodeIdentifier = nodeIdentity }); // Assert.AreEqual(PeerConnectionAction.Disconnect, res.ConnectionAction); var externalRouteLookupRequest = new ExternalRouteLookupRequest { ReceiverNodeIdentity = new ReceiverIdentifier(nodeIdentity) }; CollectionAssert.IsEmpty(externalRoutingTable.FindRoutes(externalRouteLookupRequest)); }
private void IfNodeIdentifierIsNotProvidedOrNotFound_PeerRemovalResultIsNotFound(byte[] removeNodeIdentity) { var nodeIdentity = Guid.NewGuid().ToByteArray(); var messageIdentifier = MessageIdentifier.Create <SimpleMessage>(); var routeRegistration = CreateActorRouteRegistration(messageIdentifier, ReceiverIdentities.CreateForActor(), nodeIdentity); externalRoutingTable.AddMessageRoute(routeRegistration); // var res = externalRoutingTable.RemoveMessageRoute(new ExternalRouteRemoval { Route = new MessageRoute { Message = messageIdentifier }, NodeIdentifier = removeNodeIdentity }); // Assert.AreEqual(PeerConnectionAction.NotFound, res.ConnectionAction); var externalRouteLookupRequest = new ExternalRouteLookupRequest { ReceiverNodeIdentity = new ReceiverIdentifier(nodeIdentity) }; CollectionAssert.IsNotEmpty(externalRoutingTable.FindRoutes(externalRouteLookupRequest)); }
public void RemoveNodeRoute_RemovesAllNodeRoutes() { var nodeIdentity = Guid.NewGuid().ToByteArray(); var routeRegistrations = EnumerableExtensions.Produce(Randomizer.Int32(3, 10), () => { var messageIdentifier = new MessageIdentifier(Guid.NewGuid().ToByteArray(), Randomizer.UInt16(), Guid.NewGuid().ToByteArray()); return(CreateActorRouteRegistration(messageIdentifier, ReceiverIdentities.CreateForActor(), nodeIdentity)); }); routeRegistrations.ForEach(r => externalRoutingTable.AddMessageRoute(r)); // externalRoutingTable.RemoveNodeRoute(new ReceiverIdentifier(nodeIdentity)); // var externalRouteLookupRequest = new ExternalRouteLookupRequest { ReceiverNodeIdentity = new ReceiverIdentifier(nodeIdentity) }; CollectionAssert.IsEmpty(externalRoutingTable.FindRoutes(externalRouteLookupRequest)); }
public static IMessage FromStream(BinaryReader reader) { IMessage result = null; //skim off first int. Note that this makes IMessage's From* and To* methods asymmetric. I don't //really like that but for now it's good enough. MessageIdentifier id = (MessageIdentifier)IPAddress.NetworkToHostOrder(reader.ReadInt32()); switch (id) { case MessageIdentifier.FileChanged: result = new FileChangedMessage(reader); break; case MessageIdentifier.FileRequest: result = new FileRequestMessage(reader); break; case MessageIdentifier.FileData: result = new FileDataMessage(); break; case MessageIdentifier.Verification: result = new VerificationMessage(reader); break; case MessageIdentifier.Null: default: result = new NullMessage(reader); break; } return(result); }
private static void CreateLeaseProviderInstances(IEnumerable <string> instances, IMessageHub messageHub, byte[] partition) { if (instances.Any()) { var results = new List <CreateLeaseProviderInstanceResponseMessage>(); foreach (var instance in instances) { var message = Message.CreateFlowStartMessage(new CreateLeaseProviderInstanceRequestMessage { Instance = instance, Partition = partition }); //message.TraceOptions = MessageTraceOptions.Routing; var callback = new CallbackPoint(MessageIdentifier.Create <CreateLeaseProviderInstanceResponseMessage>(partition)); using (var promise = messageHub.Send(message, callback)) { results.Add(promise.GetResponse().Result.GetPayload <CreateLeaseProviderInstanceResponseMessage>()); } } var activationWaitTime = results.Max(r => r.ActivationWaitTime); Console.WriteLine($"Waiting {activationWaitTime.TotalSeconds} sec before LeaseProvider Instances are active..."); if (activationWaitTime > TimeSpan.Zero) { Thread.Sleep(activationWaitTime); } } }
public void PopCallBackHandlerForSpecificCallbackKey_RemovesAllOtherHandlersForThisCallbackKey() { var promise = new Promise(Randomizer.Int64()); var simpleMessageIdentifier = MessageIdentifier.Create <SimpleMessage>(); var messageHandlerIdentifiers = new[] { simpleMessageIdentifier, MessageIdentifier.Create <ExceptionMessage>() }; callbackHandlerStack.Push(promise, messageHandlerIdentifiers); // var handler = callbackHandlerStack.Pop(new CallbackHandlerKey { Identity = simpleMessageIdentifier.Identity, Version = simpleMessageIdentifier.Version, Partition = simpleMessageIdentifier.Partition, CallbackKey = promise.CallbackKey.Value }); Assert.NotNull(handler); handler = callbackHandlerStack.Pop(new CallbackHandlerKey { Identity = KinoMessages.Exception.Identity, Version = KinoMessages.Exception.Version, CallbackKey = promise.CallbackKey.Value }); Assert.Null(handler); }
public void RegisterSelf_SendsOneRegistrationMessageForSpecifiedDomainButNotMessageDomain() { var actorIdentifier = ReceiverIdentities.CreateForActor(); var registrations = new[] { new MessageRoute { Message = MessageIdentifier.Create <SimpleMessage>(), Receiver = actorIdentifier }, new MessageRoute { Message = MessageIdentifier.Create <ExceptionMessage>(), Receiver = actorIdentifier } }; var simpleMessageDomain = Guid.NewGuid().ToString(); var exceptionMessageDomain = Guid.NewGuid().ToString(); var allowedDomains = new[] { exceptionMessageDomain, simpleMessageDomain, Guid.NewGuid().ToString() }; securityProvider.Setup(m => m.GetDomain(MessageIdentifier.Create <SimpleMessage>().Identity)).Returns(simpleMessageDomain); securityProvider.Setup(m => m.GetDomain(MessageIdentifier.Create <ExceptionMessage>().Identity)).Returns(exceptionMessageDomain); securityProvider.Setup(m => m.GetAllowedDomains()).Returns(allowedDomains); // clusterMonitor.RegisterSelf(registrations, domain); // autoDiscoverySender.Verify(m => m.EnqueueMessage(It.Is <IMessage>(msg => msg.Domain == domain)), Times.Once); }
private string GetExtraDataText(IExtraData ev, MessageIdentifier messageIdentifier) { switch (messageIdentifier) { case MessageIdentifier.BlackcallIncoming: case MessageIdentifier.AccelerationEvent: case MessageIdentifier.DesaccelerationEvent: case MessageIdentifier.BateryInfo: //return String.Format(" - {0}", ((Event)ev).SensorsDataString); return(ev.Data.Count > 1 ? String.Format(" - {0}", ev.Data[1]) : String.Empty); case MessageIdentifier.Picture: var cantidad = ev.Data.Count > 1 ? Convert.ToInt32(ev.Data[1]) : 0; var id = ev.Data.Count > 2 ? Convert.ToInt32(ev.Data[2]) : 0; return(GetPictureText(cantidad, id)); case MessageIdentifier.TemperatureInfo: case MessageIdentifier.TemperatureDisconected: case MessageIdentifier.TemperaturePowerDisconected: case MessageIdentifier.TemperaturePowerReconected: case MessageIdentifier.TemperatureThawingButtonPressed: case MessageIdentifier.TemperatureThawingButtonUnpressed: case MessageIdentifier.CheckpointReached: return(String.Format(" - {0:000.00}", ev.GetData() / (float)100.0)); } return(String.Empty); }
public void CallbackTriggeresForEveryMessageInCallbackPoint() { var callbackReceiverIdentity = Guid.NewGuid().ToByteArray(); var callbackReceiverNodeIdentity = Guid.NewGuid().ToByteArray(); var callbackMessageIdentifier = new[] { MessageIdentifier.Create <SimpleMessage>(), MessageIdentifier.Create <AsyncExceptionMessage>(), MessageIdentifier.Create <AsyncMessage>() }; var messages = new[] { Message.Create(new SimpleMessage()), Message.Create(new AsyncExceptionMessage()), Message.Create(new AsyncMessage()), }; foreach (var message in messages.OfType <Message>()) { message.RegisterCallbackPoint(callbackReceiverNodeIdentity, callbackReceiverIdentity, callbackMessageIdentifier, Randomizer.Int32()); CollectionAssert.AreEqual(callbackReceiverIdentity, message.CallbackReceiverIdentity); } }
public void CallbackReceiverIdentities_AreCopiedFromIncomingMessageProcessedSync() { try { actorHost.AssignActor(new EchoActor()); var messageIn = Message.CreateFlowStartMessage(new SimpleMessage()).As <Message>(); var callbackReceiver = Guid.NewGuid().ToByteArray(); var callbackReceiverNode = Guid.NewGuid().ToByteArray(); messageIn.RegisterCallbackPoint(callbackReceiverNode, callbackReceiver, MessageIdentifier.Create <SimpleMessage>(), Randomizer.Int32()); receivingSocket.SetupMessageReceived(messageIn); // StartActorHost(actorHost); // Func <Message, bool> assertCallbackPropertiesCopied = messageOut => messageIn.CallbackPoint.SequenceEqual(messageOut.CallbackPoint) && Unsafe.ArraysEqual(messageIn.CallbackReceiverIdentity, messageOut.CallbackReceiverIdentity) && Unsafe.ArraysEqual(messageIn.CallbackReceiverNodeIdentity, messageOut.CallbackReceiverNodeIdentity); localRouterSocket.WaitUntilMessageSent(assertCallbackPropertiesCopied); } finally { actorHost.Stop(); } }
public void WhenDuplicatedKeyExceptionThrown_NonOfTheActorHandlersIsAdded() { var actorHandlersMap = new ActorHandlerMap(); var simpleMessageActor = new ConfigurableActor(new[] { new MessageHandlerDefinition { Handler = null, Message = MessageDefinition.Create <SimpleMessage>() } }); var exceptionMessageActor = new ConfigurableActor(new[] { new MessageHandlerDefinition { Handler = null, Message = MessageDefinition.Create <ExceptionMessage>() }, new MessageHandlerDefinition { Handler = null, Message = MessageDefinition.Create <SimpleMessage>() } }); actorHandlersMap.Add(simpleMessageActor); actorHandlersMap.Get(MessageIdentifier.Create <SimpleMessage>()); Assert.Throws <DuplicatedKeyException>(() => { actorHandlersMap.Add(exceptionMessageActor); }); actorHandlersMap.Get(MessageIdentifier.Create <SimpleMessage>()); Assert.Throws <KeyNotFoundException>(() => actorHandlersMap.Get(MessageIdentifier.Create <ExceptionMessage>())); }
public void RegisteringCallbackPoint_SetsCallbackIdentityAndCallbackReceiverIdentity() { var message = Message.CreateFlowStartMessage(new SimpleMessage()).As <Message>(); var callbackReceiverIdentity = Guid.NewGuid().ToByteArray(); var callbackReceiverNodeIdentity = Guid.NewGuid().ToByteArray(); var callbackMessageIdentifier = new MessageIdentifier(Guid.NewGuid().ToByteArray(), Randomizer.UInt16(), Guid.NewGuid().ToByteArray()); var callbackKey = Randomizer.Int32(); message.RegisterCallbackPoint(callbackReceiverNodeIdentity, callbackReceiverIdentity, callbackMessageIdentifier, callbackKey); var multipart = new MultipartMessage(message); message = Message.FromMultipartMessage(multipart); CollectionAssert.Contains(message.CallbackPoint, callbackMessageIdentifier); CollectionAssert.AreEqual(callbackReceiverIdentity, message.CallbackReceiverIdentity); CollectionAssert.AreEqual(callbackReceiverNodeIdentity, message.CallbackReceiverNodeIdentity); CollectionAssert.IsEmpty(message.ReceiverIdentity); }
public void ActorHandlersMap_CanAddTwoActorsHandlingSameMessageTypeInDifferentPartitions() { var actorHandlersMap = new ActorHandlerMap(); var partition = Guid.NewGuid().ToByteArray(); var actorWithoutPartition = new ConfigurableActor(new[] { new MessageHandlerDefinition { Handler = null, Message = MessageDefinition.Create <SimpleMessage>() } }); var actorWithPartition = new ConfigurableActor(new[] { new MessageHandlerDefinition { Handler = null, Message = MessageDefinition.Create <SimpleMessage>(partition) } }); actorHandlersMap.Add(actorWithoutPartition); actorHandlersMap.Add(actorWithPartition); actorHandlersMap.Get(MessageIdentifier.Create(typeof(SimpleMessage), partition)); actorHandlersMap.Get(MessageIdentifier.Create(typeof(SimpleMessage))); }
public void IfCallbackIsRegistered_SyncExceptionMessageIsDeliveredToCallbackReceiver() { try { actorHost.AssignActor(new ExceptionActor()); var messageIn = Message.CreateFlowStartMessage(new SimpleMessage()).As <Message>(); var callbackReceiver = Guid.NewGuid().ToByteArray(); var callbackReceiverNode = Guid.NewGuid().ToByteArray(); var callbackPoints = new[] { MessageIdentifier.Create <SimpleMessage>(), KinoMessages.Exception }; messageIn.RegisterCallbackPoint(callbackReceiverNode, callbackReceiver, callbackPoints, Randomizer.Int32()); receivingSocket.SetupMessageReceived(messageIn); // StartActorHost(actorHost); // Func <Message, bool> assertCallbackPropertiesCopied = messageOut => messageOut.Equals(KinoMessages.Exception) && messageIn.CallbackPoint.SequenceEqual(messageOut.CallbackPoint) && Unsafe.ArraysEqual(messageIn.CallbackReceiverIdentity, messageOut.CallbackReceiverIdentity) && Unsafe.ArraysEqual(messageIn.CallbackReceiverNodeIdentity, messageOut.CallbackReceiverNodeIdentity); localRouterSocket.WaitUntilMessageSent(assertCallbackPropertiesCopied); } finally { actorHost.Stop(); } }
private static IMessage FactoryEventWithoutPosition(int id, ulong mid, MessageIdentifier mi, String datastring) { var res = mi.FactoryEvent(id, mid, null, ((GPSPoint)null).GetDate(), null, null); res.SensorsDataString = datastring; return(res); }
public void TestIfNoRouteRegisteredForSpecificMessage_ExternalRoutingTableReturnsNull() { var logger = new Mock<ILogger>(); var externalRoutingTable = new ExternalRoutingTable(logger.Object); var messageHandlerIdentifier = new MessageIdentifier(Message.CurrentVersion, AsyncMessage.MessageIdentity); externalRoutingTable.AddMessageRoute(messageHandlerIdentifier, new SocketIdentifier(Guid.NewGuid().ToByteArray()), new Uri("tcp://127.0.0.1:40")); Assert.IsNull(externalRoutingTable.FindRoute(new MessageIdentifier(Message.CurrentVersion, SimpleMessage.MessageIdentity))); }
public MessageHandler Get(MessageIdentifier identifier) { MessageHandler value; if (messageHandlers.TryGetValue(identifier, out value)) { return value; } throw new KeyNotFoundException(identifier.ToString()); }
public IPromise Pop(CallbackHandlerKey callbackIdentifier) { IPromise promise = null; IDictionary<MessageIdentifier, IPromise> messageHandlers; if(handlers.TryRemove(new CorrelationId(callbackIdentifier.Correlation), out messageHandlers)) { var massageHandlerId = new MessageIdentifier(callbackIdentifier.Version, callbackIdentifier.Identity); messageHandlers.TryGetValue(massageHandlerId, out promise); } return promise; }
public void TestTwoMessageHandlerIdentifiers_AreComparedByVersionIdentity() { var firstIdentifier = new MessageIdentifier(Message.CurrentVersion, SimpleMessage.MessageIdentity); var secondIdentifier = new MessageIdentifier(Message.CurrentVersion, SimpleMessage.MessageIdentity); Assert.AreEqual(firstIdentifier, secondIdentifier); Assert.IsTrue(firstIdentifier.Equals((object) secondIdentifier)); var thirdIdentifier = new MessageIdentifier(Guid.NewGuid().ToByteArray(), SimpleMessage.MessageIdentity); Assert.AreNotEqual(firstIdentifier, thirdIdentifier); Assert.IsFalse(firstIdentifier.Equals((object) thirdIdentifier)); }
/// <summary> /// Build a message based on an identifier and a data array. /// </summary> /// <param name="message"></param> /// <param name="data"></param> /// <returns></returns> public byte[] BuildMessage(MessageIdentifier message, byte[] data, bool encryp) { byte[] combinedMessage; if (data == null) combinedMessage = new byte[1]; else { //Encrypt the data if needed byte[] finalData = encryp ? encryption.Encrypt(data) : data; combinedMessage = new byte[finalData.Length + 1]; finalData.CopyTo(combinedMessage, 1); } combinedMessage[0] = (byte)message; return combinedMessage; }
public void TestTwoExternalRegistrationsForSameMessage_AreReturnedInRoundRobinWay() { var logger = new Mock<ILogger>(); var externalRoutingTable = new ExternalRoutingTable(logger.Object); var messageHandlerIdentifier = new MessageIdentifier(Message.CurrentVersion, SimpleMessage.MessageIdentity); var socketIdentifier1 = new SocketIdentifier(Guid.NewGuid().ToByteArray()); var socketIdentifier2 = new SocketIdentifier(Guid.NewGuid().ToByteArray()); var uri1 = new Uri("tcp://127.0.0.1:40"); var uri2 = new Uri("tcp://127.0.0.2:40"); var node1 = new Node(uri1, socketIdentifier1.Identity); var node2 = new Node(uri2, socketIdentifier2.Identity); externalRoutingTable.AddMessageRoute(messageHandlerIdentifier, socketIdentifier1, uri1); externalRoutingTable.AddMessageRoute(messageHandlerIdentifier, socketIdentifier2, uri2); Assert.AreEqual(node1, externalRoutingTable.FindRoute(messageHandlerIdentifier)); Assert.AreEqual(node2, externalRoutingTable.FindRoute(messageHandlerIdentifier)); Assert.AreEqual(node1, externalRoutingTable.FindRoute(messageHandlerIdentifier)); }
public void TestRemoveMessageRoute_RemovesOnlyProvidedMessageIdentifiers() { var logger = new Mock<ILogger>(); var externalRoutingTable = new ExternalRoutingTable(logger.Object); var messageHandlerIdentifier1 = new MessageIdentifier(Message.CurrentVersion, SimpleMessage.MessageIdentity); var messageHandlerIdentifier2 = new MessageIdentifier(Message.CurrentVersion, AsyncMessage.MessageIdentity); var messageHandlerIdentifier3 = new MessageIdentifier(Message.CurrentVersion, AsyncExceptionMessage.MessageIdentity); var socketIdentifier = new SocketIdentifier(Guid.NewGuid().ToByteArray()); var uri = new Uri("tcp://127.0.0.1:40"); var node = new Node(uri, socketIdentifier.Identity); externalRoutingTable.AddMessageRoute(messageHandlerIdentifier1, socketIdentifier, uri); externalRoutingTable.AddMessageRoute(messageHandlerIdentifier2, socketIdentifier, uri); externalRoutingTable.AddMessageRoute(messageHandlerIdentifier3, socketIdentifier, uri); Assert.AreEqual(node, externalRoutingTable.FindRoute(messageHandlerIdentifier3)); externalRoutingTable.RemoveMessageRoute(new[] {messageHandlerIdentifier2, messageHandlerIdentifier3}, socketIdentifier); Assert.AreEqual(node, externalRoutingTable.FindRoute(messageHandlerIdentifier1)); Assert.IsNull(externalRoutingTable.FindRoute(messageHandlerIdentifier2)); Assert.IsNull(externalRoutingTable.FindRoute(messageHandlerIdentifier3)); }
private bool DiscoverMessageRoute(IMessage message) { var shouldHandle = IsDiscoverMessageRouteRequest(message); if (shouldHandle) { var messageContract = message.GetPayload<DiscoverMessageRouteMessage>().MessageContract; var messageIdentifier = new MessageIdentifier(messageContract.Version, messageContract.Identity); if (internalRoutingTable.CanRouteMessage(messageIdentifier)) { clusterMonitor.RegisterSelf(new [] { messageIdentifier}); } } return shouldHandle; }
private void ProcessRequests(CancellationToken token, Barrier gateway) { using (var localSocket = CreateRoutableSocket()) { localSocketIdentityPromise.SetResult(localSocket.GetIdentity()); gateway.SignalAndWait(token); while (!token.IsCancellationRequested) { try { var message = (Message) localSocket.ReceiveMessage(token); if (message != null) { try { var actorIdentifier = new MessageIdentifier(message.Version, message.Identity); var handler = actorHandlerMap.Get(actorIdentifier); if (handler != null) { var task = handler(message); HandleTaskResult(token, task, message, localSocket); } else { messageTracer.HandlerNotFound(message); } } catch (Exception err) { //TODO: Add more context to exception about which Actor failed CallbackException(localSocket, err, message); logger.Error(err); } } } catch (Exception err) { logger.Error(err); } } } }
public void TestHandlerForReceiverIdentifier_HasHighestPriority() { var internalRoutingTable = new Mock<IInternalRoutingTable>(); var router = new MessageRouter(socketFactory.Object, internalRoutingTable.Object, new ExternalRoutingTable(logger), routerConfiguration, clusterMonitor.Object, messageTracer.Object, logger); try { StartMessageRouter(router); var message = (Message) SendMessageOverMessageHub(); var callbackSocketIdentity = message.CallbackReceiverIdentity; var callbackIdentifier = new MessageIdentifier(Message.CurrentVersion, callbackSocketIdentity); internalRoutingTable.Setup(m => m.FindRoute(It.Is<MessageIdentifier>(mhi => mhi.Equals(callbackIdentifier)))) .Returns(new SocketIdentifier(callbackSocketIdentity)); messageRouterSocketFactory.GetRouterSocket().DeliverMessage(message); Thread.Sleep(AsyncOp); internalRoutingTable.Verify(m => m.FindRoute(It.Is<MessageIdentifier>(mhi => mhi.Equals(callbackIdentifier))), Times.Once()); } finally { router.Stop(); } }
public void TestMessageIsRouted_BasedOnHandlerIdentities() { var actorSocketIdentity = new SocketIdentifier(Guid.NewGuid().ToString().GetBytes()); var actorIdentifier = new MessageIdentifier(Message.CurrentVersion, SimpleMessage.MessageIdentity); var messageHandlerStack = new Mock<IInternalRoutingTable>(); messageHandlerStack.Setup(m => m.FindRoute(It.Is<MessageIdentifier>(mhi => mhi.Equals(actorIdentifier)))) .Returns(actorSocketIdentity); var router = new MessageRouter(socketFactory.Object, messageHandlerStack.Object, new ExternalRoutingTable(logger), routerConfiguration, clusterMonitor.Object, messageTracer.Object, logger); try { StartMessageRouter(router); var message = Message.Create(new SimpleMessage(), SimpleMessage.MessageIdentity); messageRouterSocketFactory.GetRouterSocket().DeliverMessage(message); Thread.Sleep(AsyncOpCompletionDelay); messageHandlerStack.Verify(m => m.FindRoute(It.Is<MessageIdentifier>(mhi => mhi.Equals(actorIdentifier))), Times.Once()); } finally { router.Stop(); } }
public void TestIfUnhandledMessageReceivedFromOtherNode_RouterUnregistersSelfAndRequestsDiscovery() { var router = new MessageRouter(socketFactory.Object, new InternalRoutingTable(), new ExternalRoutingTable(logger), routerConfiguration, clusterMonitor.Object, messageTracer.Object, logger); try { StartMessageRouter(router); var messageIdentifier = new MessageIdentifier(Message.CurrentVersion, SimpleMessage.MessageIdentity); var message = (Message) Message.Create(new SimpleMessage(), SimpleMessage.MessageIdentity); message.PushRouterAddress(new SocketEndpoint(new Uri("tcp://127.1.1.1:9000"), SocketIdentifier.CreateIdentity())); messageRouterSocketFactory.GetRouterSocket().DeliverMessage(message); Thread.Sleep(AsyncOp); clusterMonitor.Verify(m => m.UnregisterSelf(It.Is<IEnumerable<MessageIdentifier>>(ids => ids.First().Equals(messageIdentifier))), Times.Once()); clusterMonitor.Verify(m => m.DiscoverMessageRoute(It.Is<MessageIdentifier>(id => id.Equals(messageIdentifier))), Times.Once()); } finally { router.Stop(); } }
public void TestIfUnhandledMessageReceivedFromLocalActor_RouterRequestsDiscovery() { var router = new MessageRouter(socketFactory.Object, new InternalRoutingTable(), new ExternalRoutingTable(logger), routerConfiguration, clusterMonitor.Object, messageTracer.Object, logger); try { StartMessageRouter(router); var messageIdentifier = new MessageIdentifier(Message.CurrentVersion, SimpleMessage.MessageIdentity); var message = Message.Create(new SimpleMessage(), SimpleMessage.MessageIdentity); messageRouterSocketFactory.GetRouterSocket().DeliverMessage(message); Thread.Sleep(AsyncOp); clusterMonitor.Verify(m => m.UnregisterSelf(It.IsAny<IEnumerable<MessageIdentifier>>()), Times.Never()); clusterMonitor.Verify(m => m.DiscoverMessageRoute(It.Is<MessageIdentifier>(id => id.Equals(messageIdentifier))), Times.Once()); } finally { router.Stop(); } }
public void TestIfMessageRouterCanHandleMessage_SelfRegisterIsCalled() { var internalRoutingTable = new InternalRoutingTable(); var router = new MessageRouter(socketFactory.Object, internalRoutingTable, new ExternalRoutingTable(logger), routerConfiguration, clusterMonitor.Object, messageTracer.Object, logger); try { StartMessageRouter(router); var messageIdentifier = new MessageIdentifier(Message.CurrentVersion, SimpleMessage.MessageIdentity); internalRoutingTable.AddMessageRoute(messageIdentifier, SocketIdentifier.Create()); var message = Message.Create(new DiscoverMessageRouteMessage { MessageContract = new MessageContract { Version = messageIdentifier.Version, Identity = messageIdentifier.Identity } }, DiscoverMessageRouteMessage.MessageIdentity); messageRouterSocketFactory.GetRouterSocket().DeliverMessage(message); Thread.Sleep(AsyncOp); Assert.IsTrue(internalRoutingTable.CanRouteMessage(messageIdentifier)); clusterMonitor.Verify(m => m.RegisterSelf(It.Is<IEnumerable<MessageIdentifier>>(ids => ids.First().Equals(messageIdentifier))), Times.Once()); } finally { router.Stop(); } }
private bool ProcessUnhandledMessage(Message message, MessageIdentifier messageIdentifier) { clusterMonitor.DiscoverMessageRoute(messageIdentifier); if (MessageCameFromOtherNode(message)) { clusterMonitor.UnregisterSelf(new[] {messageIdentifier}); if (message.Distribution == DistributionPattern.Broadcast) { logger.Warn("Broadcast message: " + $"{nameof(message.Version)}:{message.Version.GetString()} " + $"{nameof(message.Identity)}:{message.Identity.GetString()} " + "didn't find any local handler and was not forwarded."); } } else { logger.Warn("Handler not found: " + $"{nameof(messageIdentifier.Version)}:{messageIdentifier.Version.GetString()} " + $"{nameof(messageIdentifier.Identity)}:{messageIdentifier.Identity.GetString()}"); } return true; }
private IEnumerable<MessageIdentifier> UpdateLocalRoutingTable(RegisterInternalMessageRouteMessage payload, SocketIdentifier socketIdentifier) { var handlers = new List<MessageIdentifier>(); foreach (var registration in payload.MessageContracts) { try { var messageIdentifier = new MessageIdentifier(registration.Version, registration.Identity); internalRoutingTable.AddMessageRoute(messageIdentifier, socketIdentifier); handlers.Add(messageIdentifier); } catch (Exception err) { logger.Error(err); } } return handlers; }
public void DiscoverMessageRoute(MessageIdentifier messageIdentifier) { }
private bool HandleMessageLocally(MessageIdentifier messageIdentifier, Message message, ISocket localSocket) { var handlers = ((message.Distribution == DistributionPattern.Unicast) ? new[] {internalRoutingTable.FindRoute(messageIdentifier)} : internalRoutingTable.FindAllRoutes(messageIdentifier)) .Where(h => h != null) .ToList(); foreach (var handler in handlers) { message.SetSocketIdentity(handler.Identity); try { localSocket.SendMessage(message); messageTracer.RoutedToLocalActor(message); } catch (HostUnreachableException err) { var removedHandlerIdentifiers = internalRoutingTable.RemoveActorHostRoute(handler); if (removedHandlerIdentifiers.Any()) { clusterMonitor.UnregisterSelf(removedHandlerIdentifiers); } logger.Error(err); } } return handlers.Any(); }
private bool RegisterExternalRoutes(IMessage message, ISocket scaleOutBackend) { var shouldHandle = IsExternalRouteRegistration(message); if (shouldHandle) { var payload = message.GetPayload<RegisterExternalMessageRouteMessage>(); var handlerSocketIdentifier = new SocketIdentifier(payload.SocketIdentity); var uri = new Uri(payload.Uri); foreach (var registration in payload.MessageContracts) { try { var messageHandlerIdentifier = new MessageIdentifier(registration.Version, registration.Identity); externalRoutingTable.AddMessageRoute(messageHandlerIdentifier, handlerSocketIdentifier, uri); scaleOutBackend.Connect(uri); } catch (Exception err) { logger.Error(err); } } } return shouldHandle; }
private bool ForwardMessageAway(MessageIdentifier messageIdentifier, Message message, ISocket scaleOutBackend) { var handlers = ((message.Distribution == DistributionPattern.Unicast) ? new[] {externalRoutingTable.FindRoute(messageIdentifier)} : (MessageCameFromLocalActor(message) ? externalRoutingTable.FindAllRoutes(messageIdentifier) : Enumerable.Empty<Node>())) .Where(h => h != null) .ToList(); foreach (var handler in handlers) { try { message.SetSocketIdentity(handler.SocketIdentity); message.PushRouterAddress(routerConfiguration.ScaleOutAddress); scaleOutBackend.SendMessage(message); messageTracer.ForwardedToOtherNode(message); } catch (HostUnreachableException err) { externalRoutingTable.RemoveNodeRoute(new SocketIdentifier(handler.SocketIdentity)); scaleOutBackend.Disconnect(handler.Uri); logger.Error(err); } } return handlers.Any(); }
public void DiscoverMessageRoute(MessageIdentifier messageIdentifier) { var message = Message.Create(new DiscoverMessageRouteMessage { RequestorSocketIdentity = routerConfiguration.ScaleOutAddress.Identity, RequestorUri = routerConfiguration.ScaleOutAddress.Uri.ToSocketAddress(), MessageContract = new MessageContract { Version = messageIdentifier.Version, Identity = messageIdentifier.Identity } }, DiscoverMessageRouteMessage.MessageIdentity); outgoingMessages.Add(message); }