Exemple #1
0
        internal void ProcessAck(Message msg)
        {
            Ack ack      = null;
            var ds       = DataStorage.CreateForRead(msg.Body);
            var bitField = ds.ReadInt32();
            var msgType  = ds.ReadInt16();

            lock (_ackPerMsgType) {
                if (_ackPerMsgType.ContainsKey(msgType))
                {
                    ack = _ackPerMsgType[msgType];
                }
            }
            if (ack != null)
            {
                ack.ProcessReceivedAckBitfield(bitField, msg.MessageId, msgType);
            }
        }
        public override int GetHashCode()
        {
            int hash = 1;

            if (Ack != false)
            {
                hash ^= Ack.GetHashCode();
            }
            if (Id.Length != 0)
            {
                hash ^= Id.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
Exemple #3
0
        private string GetAck(HL7RequestInfo requestInfo, string error)
        {
            Ack      ack = new Ack(ConfigurationManager.AppSettings["CommunicationName"], ConfigurationManager.AppSettings["EnvironmentIdentifier"]);
            IMessage result;

            if (error == null)
            {
                result = ack.MakeACK(requestInfo.Message);
            }
            else
            {
                result = ack.MakeACK(requestInfo.Message, AckTypes.AE, error);
            }

            PipeParser parser = new PipeParser();

            return(parser.Encode(result));
        }
        private string GetAck(HL7RequestInfo requestInfo, string error)
        {
            Ack      ack = new Ack("NSService", "Development");
            IMessage result;

            if (error == null)
            {
                result = ack.MakeACK(requestInfo.Message);
            }
            else
            {
                result = ack.MakeACK(requestInfo.Message, AckTypes.AE, error);
            }

            PipeParser parser = new PipeParser();

            return(parser.Encode(result));
        }
Exemple #5
0
        protected async Task ProcessAck(string encryptedToken)
        {
            Ack ack = await base.DecryptAndInstantiateHandshakeToken <Ack>(encryptedToken);

            VerifyHandshakeTokenIDOwnership(ack);

            if (_tokenCryptoService.VerifySignature(ack))
            {
                Ack = ack;
                GenerateAndSendSynAck(ack);
            }
            else
            {
                throw new SignatureDoesntMatchException("The signature was not " +
                                                        "generated by the given " +
                                                        "public Key");
            }
        }
        public static async Task <TReply> DoOperation <TRequest, TReply>(
            this IConnection conn,
            string action,
            TRequest reqBody,
            Ack ack)
            where TRequest : class
            where TReply : class
        {
            if (ack == Ack.Yes)
            {
                var res = await conn.DoOperationAsync(action, reqBody)
                          .ConfigureAwait(false);

                return(res.Match(
                           disconnected: _ =>
                {
                    throw new DisconnectedException();
                },
                           failure: f =>
                {
                    throw f.error;
                },
                           reply: r => r.Match(
                               positive: p =>
                {
                    return p.pdu.Body?.ToObject <TReply>();
                },
                               negative: p =>
                {
                    throw new PduException(p.pdu);
                },
                               unknown: p =>
                {
                    throw new PduException(p.pdu);
                })));
            }
            else
            {
                await conn.DoOperationNoAckAsync(action, reqBody);

                return(null);
            }
        }
Exemple #7
0
 /// <summary>
 /// Оповестить брокер о результате обработки.
 /// </summary>
 /// <param name="acknowledgement">Данные о результате обработки.</param>
 /// <param name="channel">Канал.</param>
 /// <param name="messageContext">Контекст сообщения.</param>
 /// <param name="settings">Настройки очереди.</param>
 public Task HandleAsync <TMessage>(
     Acknowledgement acknowledgement,
     IModel channel,
     MessageContext messageContext,
     SubscriberSettings settings
     ) where TMessage : class, IMessage
 {
     return(acknowledgement switch
     {
         Ack _ => HandleAck(channel, messageContext, settings),
         Reject reject => HandleRejectAsync <TMessage>(reject, channel, messageContext, settings),
         Nack nack => HandleNackAsync <TMessage>(nack, channel, messageContext, settings),
         Retry retry => HandleRetryAsync <TMessage>(retry, channel, messageContext, settings),
         _ => throw new ArgumentOutOfRangeException(
             nameof(acknowledgement),
             typeof(Acknowledgement),
             "Передан неизвестный подтип Acknowledgement."
             )
     });
Exemple #8
0
        public static async Task WriteAsync(Stream stream, byte[] messageHeader, Ack ack,
                                            IpcBufferMessageContext ipcBufferMessageContext, ILogger logger)
        {
            logger.Debug($"[{nameof(IpcMessageConverter)}] Start Write {ipcBufferMessageContext.Summary}");

            VerifyMessageLength(ipcBufferMessageContext.Length);

            var binaryWriter = await WriteHeaderAsync(stream, messageHeader, ack,
                                                      ipcBufferMessageContext.IpcMessageCommandType);

            await binaryWriter.WriteAsync(ipcBufferMessageContext.Length);

            foreach (var ipcBufferMessage in ipcBufferMessageContext.IpcBufferMessageList)
            {
                await stream.WriteAsync(ipcBufferMessage.Buffer, ipcBufferMessage.Start, ipcBufferMessage.Count);
            }

            logger.Debug($"[{nameof(IpcMessageConverter)}] Finished Write {ipcBufferMessageContext.Summary}");
        }
            public async Task <RtmWriteReply> Write <T>(RtmWriteRequest <T> request, Ack ack)
            {
                Log.I("Write to channel, request: '{0}', ack: {1}", request, ack);

                var conn = await _client.GetConnection();

                Log.V("Write to channel executing, request: '{0}'", request);

                if (conn == null)
                {
                    Log.W("Write to channel ignored because connection is null, request: '{0}'", request);
                    return(null);
                }

                var reply = await conn.RtmWrite(request, ack).ConfigureAwait(false);

                Log.V("Write to channel completed, request: '{0}', reply: '{1}'", request, reply);
                return(reply);
            }
Exemple #10
0
        private void Receiver_OnReceive(object sender, ReceiveEventArgs e)
        {
            Command c = CommandHandler.GetCommand(CommandsArray, e.message);

            if (c == null)
            {
                Debug.Log("Unknown command " + e.message, Logger.Level.Error);
            }
            c.Inject(this);

            if (c is Ack)
            {
                bool received = SendOnAckReceived(c as Ack);
                OnAckReceived?.Invoke(this, new CommandEventArgs()
                {
                    command = c
                });
            }
            else
            {
                Ack ack = new Ack(this)
                {
                    message = e.message
                };
                string message = CommandHandler.CommandToString(ack);

                new Sender(null, c.sourceIp, c.sourcePort, message).Send(false); // send ack

                //if(!e.sourceIP.Equals(c.sourceIp) || e.sourcePort != c.sourcePort) {
                //    Debug.Log(string.Format("SourceIP not equals {0}:{1} != {2}:{3}", e.sourceIP, e.sourcePort, c.sourceIp, c.sourcePort), Logger.Level.Error);
                //}

                Debug.Log(string.Format("Command received {0}:{1} | {2}:{3} [{4}] - {5}: {6}", e.sourceIP, e.sourcePort, c.sourceIp, c.sourcePort, c.tag, c.type, e.message), Logger.Level.Command);
                c.ExecuteCommand(); // execute command

                OnCommandReceived?.Invoke(this, new CommandEventArgs()
                {
                    command = c
                });                                                                      // invoke event

                AddContact(c.Source);
            }
        }
Exemple #11
0
        public override AckAndMessage DecodeMessage(ByteString raw, RemoteActorRefProvider provider, Address localAddress)
        {
            var ackAndEnvelope = AckAndEnvelopeContainer.ParseFrom(raw);

            Ack ackOption = null;

            if (ackAndEnvelope.HasAck)
            {
                ackOption = new Ack(new SeqNo((long)ackAndEnvelope.Ack.CumulativeAck), ackAndEnvelope.Ack.NacksList.Select(x => new SeqNo((long)x)));
            }

            Message messageOption = null;

            if (ackAndEnvelope.HasEnvelope)
            {
                var envelopeContainer = ackAndEnvelope.Envelope;
                if (envelopeContainer != null)
                {
                    var     recipient = provider.ResolveActorRefWithLocalAddress(envelopeContainer.Recipient.Path, localAddress);
                    Address recipientAddress;
                    ActorPath.TryParseAddress(envelopeContainer.Recipient.Path, out recipientAddress);
                    var       serializedMessage = envelopeContainer.Message;
                    IActorRef senderOption      = null;
                    if (envelopeContainer.HasSender)
                    {
                        senderOption = provider.ResolveActorRefWithLocalAddress(envelopeContainer.Sender.Path, localAddress);
                    }
                    SeqNo seqOption = null;
                    if (envelopeContainer.HasSeq)
                    {
                        unchecked
                        {
                            seqOption = new SeqNo((long)envelopeContainer.Seq); //proto takes a ulong
                        }
                    }
                    messageOption = new Message(recipient, recipientAddress, serializedMessage, senderOption, seqOption);
                }
            }


            return(new AckAndMessage(ackOption, messageOption));
        }
        public Ack CreateAcknowledgement(string orderRef)
        {
            var ack = new Ack
            {
                OrderReference = orderRef,
                Status         = "accept",
                Time           = (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds,
            };

            Dictionary <string, object> sigDict = new Dictionary <string, object>
            {
                { "orderReference", ack.OrderReference },
                { "status", ack.Status },
                { "time", ack.Time }
            };

            ack.Signature = GetSignature(sigDict, WayForPayConstants.AckSigKeys);

            return(ack);
        }
        public override int GetHashCode()
        {
            unchecked
            {
                int hashCode = Type.GetHashCode();

                hashCode = (hashCode * 397) ^ (Data != null ? Data.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ (Ack != null ? Ack.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ (AckId != null ? AckId.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ (EndPoint != null ? EndPoint.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ (Id != null ? Id.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ (Name != null ? Name.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ (Args != null ? Args.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ (Advice != null ? Advice.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ (Reason != null ? Reason.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ (QueryString != null ? QueryString.GetHashCode() : 0);

                return(hashCode);
            }
        }
Exemple #14
0
        public void JsonSerializer_should_be_able_to_serialize_Ack()
        {
            var serializer = new NewtonSoftJsonSerializer((ExtendedActorSystem)Sys);

            var nacks = new List <SeqNo>();

            for (var i = 100; i < 200; ++i)
            {
                nacks.Add(new SeqNo(i));
            }

            var message         = new Ack(new SeqNo(666), nacks);
            var serializedBytes = serializer.ToBinary(message);
            var deserialized    = (Ack)serializer.FromBinary(serializedBytes, typeof(Ack));

            deserialized.CumulativeAck.RawValue.ShouldBe(666);
            deserialized.Nacks.Count.ShouldBe(100);
            var seqNos = deserialized.Nacks.Select(ack => (int)ack.RawValue);

            seqNos.ShouldOnlyContainInOrder(Enumerable.Range(100, 100).ToArray());
        }
        ///<inheritdoc/>
        public void Publish(string topic, object message, Ack ack = Ack.Master)
        {
            var sw      = Stopwatch.StartNew();
            var payload = JsonConvert.SerializeObject(message);

            var subscribers = _subscriptionAgent.GetSubscribers(topic);

            if (subscribers != null && subscribers.Any())
            {
                foreach (var subscriber in subscribers)
                {
                    _publishingAgent.PublishToSubscriber(subscriber.Name, topic, payload, ack);
                }
            }
            else
            {
                _messagingLogger.Debug($"no subsriptions for {topic}");
                _deadLettersAgent.Publish(topic, payload, ack);
            }
            _messagingLogger.Debug($"{topic} sent in {sw.ElapsedMilliseconds}");
        }
Exemple #16
0
        public void when_email_is_scheduled_is_sent_when_is_due()
        {
            var settings = ReminderSettings.Default
                           .WithPersistenceId("email")
                           .WithTickInterval(TimeSpan.FromMilliseconds(500))
                           .WithSnapshotInterval(5);
            var taskId         = Guid.NewGuid().ToString();
            var probe          = CreateTestProbe("email-sender");
            var scheduler      = (TestScheduler)Sys.Scheduler;
            var emailScheduler = Sys.ActorOf(Props.Create(() => new EmailScheduler(settings)).WithDispatcher(CallingThreadDispatcher.Id), "email");
            var when           = DateTime.UtcNow.AddDays(1);
            var job            = new ScheduleEmail("me", "you", "hi");
            var ack            = new Ack(taskId);
            var schedule       = new Reminder.Schedule(taskId, probe.Ref.Path, job, when, ack);

            emailScheduler.Tell(schedule, probe);
            probe.ExpectMsg <Ack>(x => x.Id == taskId);
            scheduler.AdvanceTo(when);

            probe.ExpectMsg <ScheduleEmail>(x => x.Body == job.Body && x.From == job.From && x.To == job.To);
        }
Exemple #17
0
        public void AckTest()
        {
            Ack    sender   = new Ack();
            Ack    receiver = new Ack();
            var    msg      = new Message(123, Mode.Reliable);
            Random rnd      = new Random();

            List <MessageCounter> sendedMessages   = new List <MessageCounter>();
            List <MessageCounter> recievedMessages = new List <MessageCounter>();

            sender.MessageArrived += (mc, type) =>
            {
                if (!recievedMessages.Contains(mc))
                {
                    recievedMessages.Add(mc);
                }
            };

            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 100; j++)
                {
                    msg.MessageId = (short)rnd.Next(0, 10000);
                    if (!sendedMessages.Contains(msg.MessageId))
                    {
                        sendedMessages.Add(msg.MessageId);
                    }
                    receiver.ReceiveReliable(msg);
                }
                var acks = receiver.GetAcks();
                foreach (var ack in acks)
                {
                    sender.ProcessReceivedAckBitfield(ack.Val2, ack.Val1, 123);
                }
                var rErr1 = recievedMessages.Where(m => !sendedMessages.Contains(m)).ToArray();
                var rErr2 = sendedMessages.Where(m => !recievedMessages.Contains(m)).ToArray();
                Assert.AreEqual(0, rErr1.Length);
                Assert.AreEqual(0, rErr2.Length);
            }
        }
Exemple #18
0
        private IOOperation DebugN1_PublicKey(BiuIoHopArgs arg)
        {
            var peer = arg.Peer;

            try
            {
                RawData raw = new RawData();
                if (!peer.Protocol.GetObjKept <RawData>(ref raw))
                {
                    return(IOOperation.None);
                }

                AshleyHeader header = Ashley.CreateHeader(AshleyVersion.V1_1, NetDebugLogTransmissionManager.ID_N1,
                                                          (ulong)BiuAction.Ack, AshleyFlag.None);

                Ack ack = new Ack()
                {
                    AckAction = (ulong)BiuAction.PublicKey,
                    AckResult = (uint)BiuAckResult.OK
                };

                if (null == peer.SecurityContext)
                {
                    ack.AckResult = (uint)BiuAckResult.Unsupported;
                }
                else if (!peer.SecurityContext.ChangeRemoateKey(raw.Raw.ToArray()))
                {
                    ack.AckResult = (uint)BiuAckResult.Failed;
                }

                peer.Return(ack, header);

                return(IOOperation.Continue);
            }
            catch
            {
                throw;
            }
        }
Exemple #19
0
        public void RegisterAckTask()
        {
            "重复注册相同编号的消息,提示错误".Test(() =>
            {
                var clientName           = "lindexi";
                Ack ack                  = 20;
                var taskCompletionSource = new TaskCompletionSource <bool>();

                var ackTask = new AckTask(clientName, ack, taskCompletionSource, "调试");
                AckManager.RegisterAckTask(ackTask);
                Assert.ThrowsException <ArgumentException>(() => { AckManager.RegisterAckTask(ackTask); });
            });

            "将消息注册,如果没有收到回复,那么注册的任务依然没有完成".Test(() =>
            {
                // 注册的消息可以完成
                var clientName           = "lindexi";
                Ack ack                  = 2;
                var taskCompletionSource = new TaskCompletionSource <bool>();

                var ackTask = new AckTask(clientName, ack, taskCompletionSource, "调试");
                AckManager.RegisterAckTask(ackTask);
                Assert.AreEqual(false, taskCompletionSource.Task.IsCompleted);
            });

            "将消息注册,此时设置收到回复,注册的消息可以完成".Test(() =>
            {
                // 注册的消息可以完成
                var clientName           = "lindexi";
                Ack ack                  = 2;
                var taskCompletionSource = new TaskCompletionSource <bool>();

                var ackTask = new AckTask(clientName, ack, taskCompletionSource, "调试");
                AckManager.RegisterAckTask(ackTask);
                AckManager.OnAckReceived(this, new AckArgs(clientName, ack));
                //Debug.Assert(taskCompletionSource.Task.IsCompleted);
                Assert.AreEqual(true, taskCompletionSource.Task.IsCompleted);
            });
        }
Exemple #20
0
        public void Run()
        {
            try
            {
                var lastStatus = Status;

                if (Status == State.Queued)
                {
                    Process.Invoke(this);
                }
                else if (Status >= State.RevealOK || Status < State.DBlockConfirmed)
                {
                    var ack = new Ack(Chain.FactomD);
                    switch (ack.CheckReveal(Chain.ChainID, EntryHash))
                    {
                    case Ack.Status.DBlockConfirmed:
                        Status = State.DBlockConfirmed;
                        break;

                    case Ack.Status.TransactionACK:
                        Status = State.TransactionACK;
                        break;

                    case Ack.Status.NotConfirmed:
                    case Ack.Status.RequestFailed:
                    case Ack.Status.Unknown:
                        break;
                    }
                }
                else
                {
                    //retry?
                }
            }catch (Exception ex)
            {
                ApiError = new APIError(ex);
                Status   = State.Exception;
            }
        }
Exemple #21
0
        public ISMEV3Result Ack(string messageId)
        {
            var result = new SMEV3Result {
                MessageId = messageId
            };

            try
            {
                var ackMessage = new AckTargetMessage();
                ackMessage.Id       = "SIGNED_BY_CALLER";
                ackMessage.accepted = true;
                ackMessage.Value    = messageId;

                var request  = new Ack(ackMessage, null);
                var smevSign = SerializeWithSign(request, "SIGNED_BY_CALLER");
                request.CallerInformationSystemSignature = smevSign;

                var response = smev.Ack(request);
                result.SoapRequest  = behavior.SoapRequest;
                result.SoapResponse = behavior.SoapResponse;
                result.Status       = SMEV3ResultStatus.OK;
            }
            catch (FaultException e)
            {
                result.SoapRequest  = behavior.SoapRequest;
                result.SoapResponse = behavior.SoapResponse;
                result.Status       = SMEV3ResultStatus.Fail;
                result.ErrorText    = e.Message;
            }
            catch (Exception e)
            {
                result.Status     = SMEV3ResultStatus.Error;
                result.ErrorText  = e.Message;
                result.ErrorText += "\n" + e.StackTrace;
            }

            return(result);
        }
        private static object GenerateEvent(ref JsonReader reader)
        {
            Event  generatedObject;
            JToken obj = JObject.ReadFrom(reader);

            reader = obj.CreateReader();
            if (obj["ok"] != null)
            {
                generatedObject = new Ack();
            }
            else
            {
                switch (obj["type"].ToString())
                {
                case "hello":
                    generatedObject = new Hello();
                    break;

                case "message":
                    generatedObject = new Message();
                    break;

                default:
                    return(new UnknownEvent(obj as JObject));
                }
            }
            foreach (JProperty key in obj.Children())
            {
                var name = key.Name.FromUnderscoreLower();
                var prop = generatedObject.GetType().GetProperties().FirstOrDefault(n => n.Name == name);
                if (prop != null && prop.CanWrite && !string.IsNullOrEmpty(key.Value.ToString()))
                {
                    prop.SetValue(generatedObject, key.Value.ToObject(prop.PropertyType), null);
                }
            }
            return(generatedObject);
        }
        /**
         * Remove the selected tuple and add the remaining locked tuples back to the tuplespace
         */
        private Message ProcessTakeRemove(Message message)
        {
            TakeRemove takeRemove = (TakeRemove)message;

            LockedTuples.TryRemove(takeRemove.TakeRequestSeqNumber, out List <Tuple> lockedTuples);

            // remove the selected tuple specified in the request
            if (lockedTuples != null && takeRemove.SelectedTuple != null)
            {
                lockedTuples.Remove(takeRemove.SelectedTuple);

                // add back the remaining tuples to the tuple space
                foreach (Tuple tuple in lockedTuples)
                {
                    TupleSpace.Write(tuple);
                }
            }

            // Send back an Ack of the remove
            Ack ack = new Ack(EndpointURL, takeRemove);

            SendMessageToRemoteURL(takeRemove.SrcRemoteURL, ack);
            return(ack);
        }
            public async Task <RtmDeleteReply> Delete(string channel, Ack ack)
            {
                var request = new RtmDeleteRequest
                {
                    Channel = channel
                };

                Log.I("Delete from channel, request: '{0}', ack: {1}", request, ack);

                var conn = await _client.GetConnection();

                Log.V("Delete from channel, request: '{0}' executing", request);

                if (conn == null)
                {
                    Log.W("Delete from channel ignored because connection is null, request: '{0}'", request);
                    return(null);
                }

                var reply = await conn.RtmDelete(request, ack).ConfigureAwait(false);

                Log.V("Delete from channel completed, request: '{0}', reply: '{1}'", request, reply);
                return(reply);
            }
Exemple #25
0
        private string GetAck(HL7RequestInfo requestInfo, string error)
        {
            Ack      ack = new Ack(ConfigurationManager.AppSettings["CommunicationName"], ConfigurationManager.AppSettings["EnvironmentIdentifier"]);
            IMessage result;

            if (error == null)
            {
                result = ack.MakeACK(requestInfo.Message);
            }
            else
            {
                if (requestInfo.Message == null)
                {
                    result = ack.MakeErrorACK(requestInfo.versionname, requestInfo.feild10, requestInfo.sendingapp, requestInfo.sendingEnvironment, requestInfo.feild11, requestInfo.feild15, requestInfo.feild16, AckTypes.AE, "");
                }
                else
                {
                    result = ack.MakeACK(requestInfo.Message, AckTypes.AE, error);
                }
            }
            PipeParser parser = new PipeParser();

            return(parser.Encode(result));
        }
Exemple #26
0
 public abstract ByteString ConstructMessage(Address localAddress, IActorRef recipient,
     SerializedMessage serializedMessage, IActorRef senderOption = null, SeqNo seqOption = null, Ack ackOption = null);
Exemple #27
0
 public abstract ByteString ConstructPureAck(Ack ack);
Exemple #28
0
 public abstract ByteString ConstructMessage(Address localAddress, IActorRef recipient,
                                             SerializedMessage serializedMessage, IActorRef senderOption = null, SeqNo seqOption = null, Ack ackOption = null);
Exemple #29
0
 public AckAndMessage(Ack ackOption, Message messageOption)
 {
     MessageOption = messageOption;
     AckOption     = ackOption;
 }
Exemple #30
0
 public AckAndMessage(Ack ackOption, Message messageOption)
 {
     MessageOption = messageOption;
     AckOption = ackOption;
 }
Exemple #31
0
 public override ByteString ConstructPureAck(Ack ack)
 {
     return AckAndEnvelopeContainer.CreateBuilder().SetAck(AckBuilder(ack)).Build().ToByteString();
 }
Exemple #32
0
        public override ByteString ConstructMessage(Address localAddress, IActorRef recipient, SerializedMessage serializedMessage,
            IActorRef senderOption = null, SeqNo seqOption = null, Ack ackOption = null)
        {
            var ackAndEnvelopeBuilder = AckAndEnvelopeContainer.CreateBuilder();
            var envelopeBuilder = RemoteEnvelope.CreateBuilder().SetRecipient(SerializeActorRef(recipient.Path.Address, recipient));
            if (senderOption != null && senderOption.Path != null) { envelopeBuilder = envelopeBuilder.SetSender(SerializeActorRef(localAddress, senderOption)); }
            if (seqOption != null) { envelopeBuilder = envelopeBuilder.SetSeq((ulong)seqOption.RawValue); }
            if (ackOption != null) { ackAndEnvelopeBuilder = ackAndEnvelopeBuilder.SetAck(AckBuilder(ackOption)); }
            envelopeBuilder = envelopeBuilder.SetMessage(serializedMessage);
            ackAndEnvelopeBuilder = ackAndEnvelopeBuilder.SetEnvelope(envelopeBuilder);

            return ackAndEnvelopeBuilder.Build().ToByteString();
        }
Exemple #33
0
        private AcknowledgementInfo.Builder AckBuilder(Ack ack)
        {
            var ackBuilder = AcknowledgementInfo.CreateBuilder();
            ackBuilder = ackBuilder.SetCumulativeAck((ulong)ack.CumulativeAck.RawValue);

            return ack.Nacks.Aggregate(ackBuilder, (current, nack) => current.AddNacks((ulong)nack.RawValue));
        }
Exemple #34
0
        public override AckAndMessage DecodeMessage(ByteString raw, RemoteActorRefProvider provider, Address localAddress)
        {
            var ackAndEnvelope = AckAndEnvelopeContainer.ParseFrom(raw);

            Ack ackOption = null;

            if (ackAndEnvelope.HasAck)
            {
                ackOption = new Ack(new SeqNo((long)ackAndEnvelope.Ack.CumulativeAck), ackAndEnvelope.Ack.NacksList.Select(x => new SeqNo((long)x)));
            }

            Message messageOption = null;

            if (ackAndEnvelope.HasEnvelope)
            {
                var envelopeContainer = ackAndEnvelope.Envelope;
                if (envelopeContainer != null)
                {
                    var recipient = provider.ResolveActorRefWithLocalAddress(envelopeContainer.Recipient.Path, localAddress);
                    Address recipientAddress;
                    ActorPath.TryParseAddress(envelopeContainer.Recipient.Path, out recipientAddress);
                    var serializedMessage = envelopeContainer.Message;
                    IActorRef senderOption = null;
                    if (envelopeContainer.HasSender)
                    {
                        senderOption = provider.ResolveActorRefWithLocalAddress(envelopeContainer.Sender.Path, localAddress);
                    }
                    SeqNo seqOption = null;
                    if (envelopeContainer.HasSeq)
                    {
                        unchecked
                        {
                            seqOption = new SeqNo((long)envelopeContainer.Seq); //proto takes a ulong
                        }
                    }
                    messageOption = new Message(recipient, recipientAddress, serializedMessage, senderOption, seqOption);
                }
            }


            return new AckAndMessage(ackOption, messageOption);
        }
Exemple #35
0
        private bool WriteSend(EndpointManager.Send send)
        {
            try
            {
                if (_handle == null)
                    throw new EndpointException(
                        "Internal error: Endpoint is in state Writing, but no association handle is present.");
                if (_provider.RemoteSettings.LogSend)
                {
                    var msgLog = string.Format("RemoteMessage: {0} to [{1}]<+[{2}] from [{3}]", send.Message,
                        send.Recipient, send.Recipient.Path, send.SenderOption ?? _system.DeadLetters);
                    _log.Debug(msgLog);
                }

                var pdu = _codec.ConstructMessage(send.Recipient.LocalAddressToUse, send.Recipient,
                    SerializeMessage(send.Message), send.SenderOption, send.Seq, _lastAck);

                //todo: RemoteMetrics https://github.com/akka/akka/blob/dc0547dd73b54b5de9c3e0b45a21aa865c5db8e2/akka-remote/src/main/scala/akka/remote/Endpoint.scala#L742

                //todo: max payload size validation

                var ok = _handle.Write(pdu);

                if (ok)
                {
                    _ackDeadline = NewAckDeadline();
                    _lastAck = null;
                    return true;
                }

                return false;
            }
            catch (SerializationException ex)
            {
                _log.Error(ex, "Transient association error (association remains live)");
                return true;
            }
            catch (EndpointException ex)
            {
                PublishAndThrow(ex, LogLevel.ErrorLevel);
            }
            catch (Exception ex)
            {
                PublishAndThrow(new EndpointException("Failed to write message to the transport", ex),
                    LogLevel.ErrorLevel);
            }

            return false;
        }
Exemple #36
0
        public override ByteString ConstructMessage(Address localAddress, IActorRef recipient, SerializedMessage serializedMessage,
                                                    IActorRef senderOption = null, SeqNo seqOption = null, Ack ackOption = null)
        {
            var ackAndEnvelopeBuilder = AckAndEnvelopeContainer.CreateBuilder();
            var envelopeBuilder       = RemoteEnvelope.CreateBuilder().SetRecipient(SerializeActorRef(recipient.Path.Address, recipient));

            if (senderOption != null && senderOption.Path != null)
            {
                envelopeBuilder = envelopeBuilder.SetSender(SerializeActorRef(localAddress, senderOption));
            }
            if (seqOption != null)
            {
                envelopeBuilder = envelopeBuilder.SetSeq((ulong)seqOption.RawValue);
            }
            if (ackOption != null)
            {
                ackAndEnvelopeBuilder = ackAndEnvelopeBuilder.SetAck(AckBuilder(ackOption));
            }
            envelopeBuilder       = envelopeBuilder.SetMessage(serializedMessage);
            ackAndEnvelopeBuilder = ackAndEnvelopeBuilder.SetEnvelope(envelopeBuilder);

            return(ackAndEnvelopeBuilder.Build().ToByteString());
        }
Exemple #37
0
        private void SendAck(IPEndPoint senderEndpoint, Int24 sequenceNumber)
        {
            var ack = new Ack
            {
                sequenceNumber = sequenceNumber,
                count = 1,
                onlyOneSequence = 1
            };

            var data = ack.Encode();

            SendData(data);
        }
Exemple #38
0
        public Person(int num)
        {
            random = new Random(num);
              mNum = num;
              mBrush = mBrushes[num % mBrushes.Length];

              join.Initialize(out GotoFloor);
              join.Initialize(out Stopped);
              join.Initialize(out Arrived);

              join.Initialize(out OnFloor);
              join.Initialize(out InLift);

              join.When(ProcessMessage).And(GotoFloor).Do(delegate(Floor floor)
              {
            UnderViewLock(delegate
            {
              Y = (Program.NUMFLOORS - floor.mNum) * Program.COLUMNHEIGHT;
            });
            OnFloor(floor);
            Ack a = new Ack();
            floor.PersonArrived(Helpers.pair(this, a));
            a.Receive();
            ChooseDir(floor);
              });

              join.When(ProcessMessage).And(OnFloor).And(Arrived).Do(delegate(Floor floor, Pair<Lift, Dir> p)
              {
            Lift lift = p.Fst;
            Dir dir = p.Snd;
            if (dir == mDir) {
              floor.PersonDeparted(this);
              UnderViewLock(delegate
              {
            State = PersonState.Entering;
            X = 0;
            nextX =  (2 + 2 * lift.mNum) * Program.COLUMNWIDTH;
            speed = (int)Math.Round((double)(Program.SPEED * 2 * nextX / (1.0 * Program.STOPTIME * Program.COLUMNHEIGHT)));
              });
              WaitForEndTransition();
              UnderViewLock(delegate
              {
            X = nextX;
            State = PersonState.Travelling;
              });
              Ack ack = new Ack();
              lift.PersonArrived(Helpers.pair(this, ack));
              ack.Receive();
              InLift(lift);
              ChooseFloor(floor, lift);
            }
            else OnFloor(floor);
              });

              join.When(ProcessMessage).And(InLift).And(Arrived).Do(delegate(Lift lift, Pair<Lift, Dir> p) { InLift(lift); });

              join.When(ProcessMessage).And(InLift).And(Stopped).Do(delegate(Lift lift, Floor stop)
              {
            if (stop.mNum == mNext) {

              lift.PersonDeparted(this);
              UnderViewLock(delegate
              {
            State = PersonState.Exiting;
            nextX = 0;
            Y = (Program.NUMFLOORS - stop.mNum) * Program.COLUMNHEIGHT;
              });
              WaitForEndTransition();
              UnderViewLock(delegate {
            X = 0;
            State = PersonState.Waiting;
              });
              OnFloor(stop);
              Thread.Sleep(1000 * random.Next(1, 10));
              Ack ack = new Ack();
              stop.PersonArrived(Helpers.pair(this, ack));
              ack.Receive();
              ChooseDir(stop);
            }
            else InLift(lift);
              });

              XOffSet = (mNum % 16) * 2;
              YOffSet = mNum / 16 * 2;
              X = 0;
              nextX = 0;
        }
Exemple #39
0
        protected override void Unhandled(object message)
        {
            if (message is Terminated)
            {
                var t = message as Terminated;
                if (_reader == null || t.ActorRef.Equals(_reader))
                {
                    PublishAndThrow(new EndpointDisassociatedException("Disassociated"), LogLevel.DebugLevel);
                }
            }
            else if (message is StopReading)
            {
                var stop = message as StopReading;
                if (_reader != null)
                {
                    _reader.Tell(stop, stop.ReplyTo);
                }
                else
                {
                    // initializing, buffer and take care of it later when buffer is sent
                    EnqueueInBuffer(message);
                }
            }
            else if (message is TakeOver)
            {
                var takeover = message as TakeOver;

                // Shutdown old reader
                _handle.Disassociate();
                _handle = takeover.ProtocolHandle;
                takeover.ReplyTo.Tell(new TookOver(Self, _handle));
                Context.Become(Handoff);
            }
            else if (message is FlushAndStop)
            {
                _stopReason = DisassociateInfo.Shutdown;
                Context.Stop(Self);
            }
            else if (message is OutboundAck)
            {
                var ack = message as OutboundAck;
                _lastAck = ack.Ack;
                if (_ackDeadline.IsOverdue)
                    TrySendPureAck();
            }
            else if (message is AckIdleCheckTimer || message is FlushAndStopTimeout || message is BackoffTimer)
            {
                //ignore
            }
            else
            {
                base.Unhandled(message);
            }
        }
Exemple #40
0
        private bool WriteSend(EndpointManager.Send send)
        {
            try
            {
                if (_handle == null)
                    throw new EndpointException(
                        "Internal error: Endpoint is in state Writing, but no association handle is present.");
                if (_provider.RemoteSettings.LogSend)
                {
                    _log.Debug("RemoteMessage: {0} to [{1}]<+[{2}] from [{3}]", send.Message,
                        send.Recipient, send.Recipient.Path, send.SenderOption ?? _system.DeadLetters);
                }

                var pdu = _codec.ConstructMessage(send.Recipient.LocalAddressToUse, send.Recipient,
                    SerializeMessage(send.Message), send.SenderOption, send.Seq, _lastAck);

                _remoteMetrics.LogPayloadBytes(send.Message, pdu.Length);

                if (pdu.Length > Transport.MaximumPayloadBytes)
                {
                    var reason = new OversizedPayloadException(
                        string.Format("Discarding oversized payload sent to {0}: max allowed size {1} bytes, actual size of encoded {2} was {3} bytes.",
                            send.Recipient,
                            Transport.MaximumPayloadBytes,
                            send.Message.GetType(),
                            pdu.Length));
                    _log.Error(reason, "Transient association error (association remains live)");
                    return true;
                }
                else
                {
                    var ok = _handle.Write(pdu);

                    if (ok)
                    {
                        _ackDeadline = NewAckDeadline();
                        _lastAck = null;
                        return true;
                    }
                }
                return false;
            }
            catch (SerializationException ex)
            {
                _log.Error(ex, "Transient association error (association remains live)");
                return true;
            }
            catch (EndpointException ex)
            {
                PublishAndThrow(ex, LogLevel.ErrorLevel);
            }
            catch (Exception ex)
            {
                PublishAndThrow(new EndpointException("Failed to write message to the transport", ex),
                    LogLevel.ErrorLevel);
            }

            return false;
        }
Exemple #41
0
 public override ByteString ConstructPureAck(Ack ack)
 {
     return(AckAndEnvelopeContainer.CreateBuilder().SetAck(AckBuilder(ack)).Build().ToByteString());
 }
Exemple #42
0
 public abstract ByteString ConstructPureAck(Ack ack);
Exemple #43
0
 private void TrySendPureAck()
 {
     if (_handle != null && _lastAck != null)
     {
         if (_handle.Write(_codec.ConstructPureAck(_lastAck)))
         {
             _ackDeadline = NewAckDeadline();
             _lastAck = null;
         }
     }
 }
Exemple #44
0
        public void SendBuffer_and_ReceiveBuffer_must_correctly_cooperate_with_each_other()
        {
            var msgCount = 1000;
            var deliveryProbability = 0.5D;
            var referenceList = Enumerable.Range(0, msgCount).Select(x => Msg(x)).ToList();

            var toSend = referenceList;
            var received = new List<Sequenced>();
            var sndBuf = new AckedSendBuffer<Sequenced>(10);
            var rcvBuf = new AckedReceiveBuffer<Sequenced>();
            var log = new List<string>();
            var lastAck = new Ack(new SeqNo(-1));

            Action<string> dbLog = log.Add;
            Action<int, double> senderSteps = (steps, p) =>
            {
                var resends = new List<Sequenced>(sndBuf.Nacked.Concat(sndBuf.NonAcked).Take(steps));

                var sends = new List<Sequenced>();
                if (steps - resends.Count > 0)
                {
                    var tmp = toSend.Take(steps - resends.Count).ToList();
                    toSend = toSend.Drop(steps - resends.Count).ToList();
                    sends = tmp;
                }

                foreach (var msg in resends.Concat(sends))
                {
                    if (sends.Contains(msg)) sndBuf = sndBuf.Buffer(msg);
                    if (Happened(p))
                    {
                        var del = rcvBuf.Receive(msg).ExtractDeliverable;
                        rcvBuf = del.Buffer;
                        dbLog(string.Format("{0} -- {1} --> {2}", sndBuf, msg, rcvBuf));
                        lastAck = del.Ack;
                        received.AddRange(del.Deliverables);
                        dbLog(string.Format("R: {0}", string.Join(",", received.Select(x => x.ToString()))));
                    }
                    else
                    {
                        dbLog(string.Format("{0} -- {1} --X {2}", sndBuf, msg, rcvBuf));
                    }
                }
            };

            Action<double> receiverStep = (p) =>
            {
                if (Happened(p))
                {
                    sndBuf = sndBuf.Acknowledge(lastAck);
                    dbLog(string.Format("{0} <-- {1} -- {2}", sndBuf, lastAck, rcvBuf));
                }
                else
                {
                    dbLog(string.Format("{0} X-- {1} -- {2}", sndBuf, lastAck, rcvBuf));
                }
            };

            //Dropping phase
            global::System.Diagnostics.Debug.WriteLine("Starting unreliable delivery for {0} messages, with delivery probably P = {1}", msgCount, deliveryProbability);
            var nextSteps = msgCount*2;
            while (nextSteps > 0)
            {
                var s = Geom(0.3, limit: 5);
                senderSteps(s, deliveryProbability);
                receiverStep(deliveryProbability);
                nextSteps--;
            }
            global::System.Diagnostics.Debug.WriteLine("Successfully delivered {0} messages from {1}", received.Count, msgCount);
            global::System.Diagnostics.Debug.WriteLine("Entering reliable phase");

            //Finalizing phase
            for (var i = 1; i <= msgCount; i++)
            {
                senderSteps(1, 1.0);
                receiverStep(1.0);
            }

            if (!received.SequenceEqual(referenceList))
            {
                global::System.Diagnostics.Debug.WriteLine(string.Join(Environment.NewLine, log));
                global::System.Diagnostics.Debug.WriteLine("Received: ");
                global::System.Diagnostics.Debug.WriteLine(string.Join(Environment.NewLine, received.Select(x => x.ToString())));
                Assert.True(false,"Not all messages were received");
            }

            global::System.Diagnostics.Debug.WriteLine("All messages have been successfully delivered");
        }
Exemple #45
0
 public OutboundAck(Ack ack)
 {
     Ack = ack;
 }
Exemple #46
0
 /// <summary>
 ///     Triggered after the application has run.
 /// </summary>
 /// <param name="result">The result from the OpenFin Desktop</param>
 private void afterRun(Ack result)
 {
     htmlApp_.getWindow().show();
 }