Esempio n. 1
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity <AccountEntity>()
            .HasMany(b => b.Transactions)
            .WithOne(e => e.From);

            modelBuilder.Entity <AccountEntity>()
            .HasData(
                new AccountEntity
            {
                Id        = new Guid("E74EA75C-EF51-40E1-BD83-086805F32060"),
                Balance   = 0,
                IBAN      = "MOCKACCOUNT1",
                OwenerId  = "SYSTEM",
                CreatedAt = SystemDateTime.UtcNow()
            },
                new AccountEntity
            {
                Id        = new Guid("5ccc827f-63e3-4bcc-9826-487088444106"),
                Balance   = 0,
                IBAN      = "MOCKACCOUNT2",
                OwenerId  = "SYSTEM",
                CreatedAt = SystemDateTime.UtcNow()
            }
                );

            modelBuilder.Entity <TransactionEntity>()
            .HasOne(b => b.From)
            .WithMany(x => x.Transactions)
            .HasForeignKey(x => x.FromId);

            //modelBuilder.ApplyConfiguration(new ManufacturerConfiguration());
            //modelBuilder.ApplyConfiguration(new VehicleModelConfiguration());
        }
Esempio n. 2
0
        public async Task UpdateTransactionAsync(Account account, AccountTransaction accountTransaction)
        {
            using (var dbContextTransaction = _dataDbContext.Database.BeginTransaction())
            {
                var entity   = _dataDbContext.Accounts.Single(x => string.Equals(x.IBAN, account.AccountName));
                var entityTo =
                    _dataDbContext.Accounts.SingleOrDefault(x => string.Equals(x.IBAN, accountTransaction.AccountName));

                entity.Balance   = account.Balance;
                entity.UpdatedAt = SystemDateTime.UtcNow();

                var transaction = new TransactionEntity
                {
                    FromId    = entity.Id,
                    Amount    = accountTransaction.Amount,
                    CreateAt  = entity.UpdatedAt,
                    Type      = accountTransaction.Type,
                    Status    = OperationStatus.Ok,
                    AccountTo = accountTransaction.AccountName
                };

                if (entityTo == null)
                {
                    transaction.Status = OperationStatus.AccountNotFound;
                }

                _dataDbContext.Transactions.Add(transaction);
                await _dataDbContext.SaveChangesAsync();

                dbContextTransaction.Commit();
            }
        }
Esempio n. 3
0
        public async Task CollectFeeAsync(Account account, decimal fee)
        {
            using (var dbContextTransaction = _dataDbContext.Database.BeginTransaction())
            {
                var entity = _dataDbContext.Accounts.Single(x => string.Equals(x.IBAN, account.AccountName));

                entity.Balance   = account.Balance;
                entity.UpdatedAt = SystemDateTime.UtcNow();

                var transaction = new TransactionEntity
                {
                    FromId    = entity.Id,
                    Amount    = fee,
                    CreateAt  = entity.UpdatedAt,
                    Type      = TransactionType.Withdraw,
                    Status    = OperationStatus.Ok,
                    AccountTo = "SYSTEM"
                };

                _dataDbContext.Transactions.Add(transaction);
                await _dataDbContext.SaveChangesAsync();

                dbContextTransaction.Commit();
            }
        }
Esempio n. 4
0
        public PilotDto GetPilot(string name, int allianceId, int corpId, decimal securityStatus = 0)
        {
            var query = _reportingRepository.QueryFor <IPilotByNameQuery>(c => c.Name = name);
            var dto   = query.Execute();

            if (dto == null)
            {
                var sequence = _reportingRepository.GetNextSequenceFor <PilotDto>();
                var uid      = SystemIdGenerator.Next();

                _bus.Send(new CreatePilot(uid, sequence, name, allianceId, corpId, securityStatus, 0));

                dto = new PilotDto {
                    AllianceId    = allianceId,
                    CorporationId = corpId,
                    ExternalId    = 0,
                    Id            = uid,
                    Name          = name,
                    Timestamp     = SystemDateTime.Now(),
                    Sequence      = sequence
                };
            }
            else
            {
                if (dto.CorporationId != corpId)
                {
                    dto.CorporationId = corpId;
                    _bus.Send(new ChangePilotsCorporation(dto.Id, corpId));
                }
            }

            return(dto);
        }
 public void should_return_utc_timestamps()
 {
     using (SystemDateTime.PauseTime())
     {
         new UniqueTimestampProvider().NextUtcTimestamp().ShouldApproximateDateTime(SystemDateTime.UtcNow);
     }
 }
            public void should_send_MessageProcessingFailed_if_unable_to_deserialize_message()
            {
                SetupPeersHandlingMessage <MessageProcessingFailed>(_peerUp);

                _bus.Start();

                var command = new FakeCommand(123);

                _messageSerializer.AddSerializationExceptionFor(command.TypeId(), "Serialization error");

                using (SystemDateTime.PauseTime())
                    using (MessageId.PauseIdGeneration())
                    {
                        var transportMessage = command.ToTransportMessage();

                        var messageProcessingFailedBytes = new MessageProcessingFailed(null, null, null, DateTime.UtcNow, null).ToTransportMessage().Content;
                        _messageSerializer.AddSerializationFuncFor <MessageProcessingFailed>(x =>
                        {
                            x.FailingMessage.ShouldEqual(transportMessage);
                            x.ExceptionUtcTime.ShouldEqual(SystemDateTime.UtcNow);
                            x.ExceptionMessage.ShouldContain("Unable to deserialize message");
                            return(messageProcessingFailedBytes);
                        });

                        _transport.RaiseMessageReceived(transportMessage);

                        var processingFailedTransportMessage = new TransportMessage(MessageUtil.TypeId <MessageProcessingFailed>(), messageProcessingFailedBytes, _self);
                        _transport.ExpectExactly(new TransportMessageSent(processingFailedTransportMessage, _peerUp));
                    }
            }
        public void Register_ForCitizenWithEmptyVatId_AssignedVatIdContainsDigitsOnly()
        {
            var citizen = CitizenBuilder.NewWoman().WithDate(SystemDateTime.Now()).Build();
            registry.Register(citizen);

            StringAssert.Matches(citizen.VatId, new Regex("^[0-9]+$"));
        }
        public void should_raise_PingMissed_before_a_peer_is_marked_as_timed_out()
        {
            SetupPeerRepository(_persistentAlivePeer, _transientAlivePeer0);
            SetupPeerResponse(_transientAlivePeer0.PeerId, true, true);
            SetupPeerResponse(_persistentAlivePeer.PeerId, false, false);

            using (SystemDateTime.PauseTime())
            {
                var missedPings = new List <PeerEvent>();
                _detector.PingTimeout += (peer, timestamp) => missedPings.Add(new PeerEvent(peer, timestamp));

                var startTime = SystemDateTime.UtcNow;
                _detector.DetectDeadPeers();

                SystemDateTime.Set(startTime.Add(_pingInterval - 1.Second()));
                _detector.DetectDeadPeers();
                missedPings.Count.ShouldEqual(0);

                SystemDateTime.Set(startTime.Add(_pingInterval + 1.Second()));
                _detector.DetectDeadPeers();
                missedPings.Count.ShouldEqual(1);
                missedPings.First().PeerId.ShouldEqual(_persistentAlivePeer.PeerId);

                SystemDateTime.Set(startTime.Add(_pingInterval + _pingInterval + 1.Second()));
                _detector.DetectDeadPeers();
                missedPings.Count.ShouldEqual(2);
                missedPings.All(evt => evt.PeerId == _persistentAlivePeer.PeerId).ShouldBeTrue();
            }
        }
        public void should_timeout_if_any_debug_service_does_not_respond_in_time()
        {
            SetupPeerRepository(_debugPersistentAlivePeer, _debugTransientAlivePeer);
            SetupPeerResponse(_debugPersistentAlivePeer.PeerId, false, false);
            SetupPeerResponse(_debugTransientAlivePeer.PeerId, false, false);

            using (SystemDateTime.PauseTime())
            {
                var startTime             = SystemDateTime.UtcNow;
                var firstPingTimestampUtc = startTime;

                _detector.DetectDeadPeers();
                _bus.ExpectExactly(new PingPeerCommand(), new PingPeerCommand());
                _bus.ClearMessages();

                SystemDateTime.Set(startTime.AddSeconds(_debugPeerTimeout - 1));
                _detector.DetectDeadPeers();
                _bus.ExpectExactly(new PingPeerCommand(), new PingPeerCommand());
                _bus.ClearMessages();

                SystemDateTime.Set(startTime.AddSeconds(_debugPeerTimeout + 1));
                _detector.DetectDeadPeers();
                _bus.ExpectExactly(
                    new UnregisterPeerCommand(_debugTransientAlivePeer.Peer, firstPingTimestampUtc),
                    new UnregisterPeerCommand(_debugPersistentAlivePeer.Peer, firstPingTimestampUtc)
                    );
            }
        }
Esempio n. 10
0
        public void should_not_decommission_directory_peer()
        {
            SetupPeerRepository(_directoryPeer, _transientAlivePeer0);
            SetupPeerResponse(_transientAlivePeer0.PeerId, false, false);
            SetupPeerResponse(_directoryPeer.PeerId, false, false);

            using (SystemDateTime.PauseTime())
            {
                var startTime             = SystemDateTime.UtcNow;
                var firstPingTimestampUtc = startTime;

                _detector.DetectDeadPeers();
                _bus.ExpectExactly(new PingPeerCommand());
                _bus.ClearMessages();

                SystemDateTime.Set(startTime.AddSeconds(_transientPeerTimeout - 1));
                _detector.DetectDeadPeers();
                _bus.ExpectExactly(new PingPeerCommand());
                _bus.ClearMessages();

                SystemDateTime.Set(startTime.AddSeconds(_transientPeerTimeout + 1));
                _detector.DetectDeadPeers();
                _bus.ExpectExactly(new UnregisterPeerCommand(_transientAlivePeer0.Peer, firstPingTimestampUtc));
            }
        }
Esempio n. 11
0
        public void should_not_decommission_the_persistence()
        {
            SetupPeerRepository(_persistencePeer);
            SetupPeerResponse(_persistencePeer.PeerId, false, false);

            using (SystemDateTime.PauseTime())
            {
                var startTime = SystemDateTime.UtcNow;

                var persistenceDownDetectedCount = 0;
                _detector.PersistenceDownDetected += () => persistenceDownDetectedCount++;

                _detector.DetectDeadPeers();
                _bus.ExpectExactly(new PingPeerCommand());

                SystemDateTime.Set(startTime.AddSeconds(_transientPeerTimeout - 1));
                _detector.DetectDeadPeers();
                _bus.ExpectExactly(new PingPeerCommand(), new PingPeerCommand());

                SystemDateTime.Set(startTime.AddSeconds(_transientPeerTimeout + 1));
                _detector.DetectDeadPeers();

                _bus.ExpectExactly(new PingPeerCommand(), new PingPeerCommand());
                persistenceDownDetectedCount.ShouldEqual(1);
            }
        }
Esempio n. 12
0
        public void should_timeout_if_a_persistent_service_does_not_respond_in_time()
        {
            SetupPeerRepository(_persistentAlivePeer, _transientAlivePeer0);
            SetupPeerResponse(_transientAlivePeer0.PeerId, true, true);
            SetupPeerResponse(_persistentAlivePeer.PeerId, false, false);

            using (SystemDateTime.PauseTime())
            {
                var startTime             = SystemDateTime.UtcNow;
                var firstPingTimestampUtc = startTime;

                _detector.DetectDeadPeers();
                _bus.ExpectExactly(new PingPeerCommand(), new PingPeerCommand());
                _bus.ClearMessages();

                SystemDateTime.Set(startTime.AddSeconds(_transientPeerTimeout - 1));
                _detector.DetectDeadPeers();
                _bus.ExpectExactly(new PingPeerCommand(), new PingPeerCommand());
                _bus.ClearMessages();

                var retryTimestamp = startTime.AddSeconds(_persistentPeerTimeout - 1);
                SystemDateTime.Set(retryTimestamp);
                _detector.DetectDeadPeers();
                _bus.ExpectExactly(new PingPeerCommand(), new PingPeerCommand());
                _bus.ClearMessages();

                SystemDateTime.Set(startTime.AddSeconds(_persistentPeerTimeout + 1));
                _detector.DetectDeadPeers();
                _bus.ExpectExactly(new MarkPeerAsNotRespondingCommand(_persistentAlivePeer.Peer.Id, firstPingTimestampUtc));
            }
        }
Esempio n. 13
0
        public void should_mark_as_not_responding_if_a_transient_peer_in_the_whitelist_does_not_respond_in_time(string peerNotToDecommission)
        {
            _peersNotToDecommission = new[] { peerNotToDecommission };
            SetupPeerRepository(_transientAlivePeer0);
            SetupPeerResponse(_transientAlivePeer0.PeerId, false, false);

            using (SystemDateTime.PauseTime())
            {
                var startTime             = SystemDateTime.UtcNow;
                var firstPingTimestampUtc = startTime;

                _detector.DetectDeadPeers();
                _bus.ExpectExactly(new PingPeerCommand());
                _bus.ClearMessages();

                SystemDateTime.Set(startTime.AddSeconds(_transientPeerTimeout - 1));
                _detector.DetectDeadPeers();
                _bus.ExpectExactly(new PingPeerCommand());
                _bus.ClearMessages();

                SystemDateTime.Set(startTime.AddSeconds(_transientPeerTimeout + 1));
                _detector.DetectDeadPeers();
                _bus.ExpectExactly(new MarkPeerAsNotRespondingCommand(_transientAlivePeer0.Peer.Id, firstPingTimestampUtc));
            }
        }
Esempio n. 14
0
        public void should_not_timeout_if_a_persistent_service_responds_to_the_second_ping()
        {
            SetupPeerRepository(_persistentAlivePeer, _transientAlivePeer0);
            SetupPeerResponse(_transientAlivePeer0.PeerId, true, true);
            SetupPeerResponse(_persistentAlivePeer.PeerId, false, true);

            using (SystemDateTime.PauseTime())
            {
                var startTime = SystemDateTime.UtcNow;

                _detector.DetectDeadPeers();
                _bus.ExpectExactly(new PingPeerCommand(), new PingPeerCommand());
                _bus.ClearMessages();

                SystemDateTime.Set(startTime.AddSeconds(_transientPeerTimeout - 1));
                _detector.DetectDeadPeers();
                _bus.ExpectExactly(new PingPeerCommand(), new PingPeerCommand());
                _bus.ClearMessages();

                SystemDateTime.Set(startTime.AddSeconds(_persistentPeerTimeout - 1));
                _detector.DetectDeadPeers();
                _bus.ExpectExactly(new PingPeerCommand(), new PingPeerCommand());
                _bus.ClearMessages();

                SystemDateTime.Set(startTime.AddSeconds(_persistentPeerTimeout + 1));
                _detector.DetectDeadPeers();
                _bus.ExpectNothing();;
            }
        }
        void SetCurrentTime()
        {
            SystemDateTime testDateTimeValue = new SystemDateTime();

            Proxies.Onvif.DateTime dateTime = new Proxies.Onvif.DateTime();

            dateTime.Date = new Date();
            dateTime.Time = new Time();

            System.DateTime nowUtc = System.DateTime.Now.ToUniversalTime();

            dateTime.Time.Hour   = nowUtc.Hour;
            dateTime.Time.Minute = nowUtc.Minute;
            dateTime.Time.Second = nowUtc.Second;

            dateTime.Date.Day   = nowUtc.Day;
            dateTime.Date.Month = nowUtc.Month;
            dateTime.Date.Year  = nowUtc.Year;

            testDateTimeValue.DateTimeType    = SetDateTimeType.Manual;
            testDateTimeValue.DaylightSavings = false;
            testDateTimeValue.UTCDateTime     = dateTime;

            SetSystemDateAndTime(testDateTimeValue, "Synchronize time");
        }
Esempio n. 16
0
        /// <inheritdoc />
        public void Register(ICitizen citizen)
        {
            if (string.IsNullOrWhiteSpace(citizen.VatId))
            {
                int    dayNumber  = (citizen.BirthDate - startDate).Days;
                string dateString = dayNumber.ToString("D5");

                var oneDayBorned = register.Where(v => v.Key.StartsWith(dateString) && v.Key.Length == 10)
                                   .Select(v => v.Key.Substring(5, 4));

                var genderSequenceNumbers = oneDayBorned.Where(v => GenderCondition(v, citizen.Gender))
                                            .Select(v => int.Parse(v)).ToList();

                int currentNumber = genderSequenceNumbers.Any() ? genderSequenceNumbers.Max() : -1;

                int    nextSequenceNumber   = GetNextAllowed(currentNumber, citizen.Gender);
                string stringSequenceNumber = nextSequenceNumber.ToString("D4");

                int controlNumber = GetControlNumber(dateString, stringSequenceNumber);

                citizen.VatId = dateString + stringSequenceNumber + controlNumber;
            }

            if (!register.ContainsKey(citizen.VatId))
            {
                citizen.RegistrationDate = SystemDateTime.Now();
                register.Add(citizen.VatId, citizen.Clone() as ICitizen);
            }
            else
            {
                throw new InvalidOperationException();
            }
        }
Esempio n. 17
0
        public async Task should_remove_peer_subscriptions_for_a_type_if_there_are_no_binding_keys()
        {
            using (SystemDateTime.PauseTime())
            {
                var subscriptionsForTypes = new[]
                {
                    new SubscriptionsForType(MessageUtil.GetTypeId(typeof(int))),
                    new SubscriptionsForType(MessageUtil.GetTypeId(typeof(double)), BindingKey.Empty)
                };
                await _peerDirectory.RegisterAsync(_bus, _self, Enumerable.Empty <Subscription>());

                _bus.ClearMessages();
                SubscriptionsForType[] addedSubscriptions    = null;
                MessageTypeId[]        removedMessageTypeIds = null;
                _repositoryMock.Setup(repo => repo.AddDynamicSubscriptionsForTypes(_self.Id, SystemDateTime.UtcNow, It.IsAny <SubscriptionsForType[]>()))
                .Callback((PeerId peerId, DateTime timestampUtc, SubscriptionsForType[] subs) => addedSubscriptions = subs);
                _repositoryMock.Setup(repo => repo.RemoveDynamicSubscriptionsForTypes(_self.Id, SystemDateTime.UtcNow, It.IsAny <MessageTypeId[]>()))
                .Callback((PeerId peerId, DateTime timestampUtc, MessageTypeId[] ids) => removedMessageTypeIds = ids);

                await _peerDirectory.UpdateSubscriptionsAsync(_bus, subscriptionsForTypes);

                var addedSubscription = addedSubscriptions.ExpectedSingle();
                addedSubscription.ShouldHaveSamePropertiesAs(new SubscriptionsForType(MessageUtil.GetTypeId(typeof(double)), BindingKey.Empty));
                var removedMessageTypeId = removedMessageTypeIds.ExpectedSingle();
                removedMessageTypeId.ShouldHaveSamePropertiesAs(MessageUtil.GetTypeId(typeof(int)));
                _bus.ExpectExactly(new PeerSubscriptionsForTypesUpdated(_self.Id, SystemDateTime.UtcNow, subscriptionsForTypes));
            }
        }
Esempio n. 18
0
        void SynchronizeTime(SystemDateTime initialSettings = null)
        {
            var dateTime = new Proxies.Onvif.DateTime {
                Date = new Date(), Time = new Time()
            };

            System.DateTime nowUtc = System.DateTime.UtcNow;

            dateTime.Time.Hour   = nowUtc.Hour;
            dateTime.Time.Minute = nowUtc.Minute;
            dateTime.Time.Second = nowUtc.Second;

            dateTime.Date.Day   = nowUtc.Day;
            dateTime.Date.Month = nowUtc.Month;
            dateTime.Date.Year  = nowUtc.Year;

            //If initial settings were not retrieved then use DaylightSavings = false and DateTimeType = SetDateTimeType.Manual
            if (null == initialSettings)
            {
                initialSettings = new SystemDateTime()
                {
                    DaylightSavings = false,
                    DateTimeType    = SetDateTimeType.Manual
                };
            }

            initialSettings.LocalDateTime = null;
            initialSettings.UTCDateTime   = dateTime;

            SetSystemDateAndTime(initialSettings, "Synchronize time");
        }
        public void Register_ForCitizenWithEmptyVatId_AssignsVatId()
        {
            var citizen = CitizenBuilder.NewWoman().WithDate(SystemDateTime.Now()).Build();
            registry.Register(citizen);

            Assert.IsFalse(String.IsNullOrWhiteSpace(citizen.VatId));
        }
        public void GivenAMongoMessageDataRepository_WhenPuttingMessageDataWithExpiration()
        {
            var db = new MongoClient().GetDatabase("messagedatastoretests");

            _bucket = new GridFSBucket(db);

            _now = DateTime.UtcNow;
            SystemDateTime.Set(_now);

            var fixture = new Fixture();

            var resolver = new Mock <IMongoMessageUriResolver>();

            resolver.Setup(x => x.Resolve(It.IsAny <ObjectId>()))
            .Callback((ObjectId id) => _id = id);

            var nameCreator = new Mock <IFileNameCreator>();

            nameCreator.Setup(x => x.CreateFileName())
            .Returns(fixture.Create <string>());

            var sut = new MongoMessageDataRepository(resolver.Object, _bucket, nameCreator.Object);

            _expectedTtl = TimeSpan.FromHours(1);

            using (var stream = new MemoryStream(fixture.Create <byte[]>()))
            {
                sut.Put(stream, _expectedTtl).GetAwaiter().GetResult();
            }
        }
        public void Constructor_WithNeedlessWhiteSpacesInName_CorrectsName()
        {
            var citizen = new Citizen(" Roger  ", " Pierce  ", SystemDateTime.Now(), Gender.Male);

            Assert.AreEqual("Roger", citizen.FirstName);
            Assert.AreEqual("Pierce", citizen.LastName);
        }
        public void Constructor_WithInvalidNameCasing_CorrectsNameToLowerCaseWithCapital()
        {
            var citizen = new Citizen("RoGer", "pIERCE", SystemDateTime.Now(), Gender.Male);

            Assert.AreEqual("Roger", citizen.FirstName);
            Assert.AreEqual("Pierce", citizen.LastName);
        }
Esempio n. 23
0
 protected void SetSystemDateAndTime(SystemDateTime dateTime)
 {
     RunStep(() => { Client.SetSystemDateAndTime(dateTime.DateTimeType,
                                                 dateTime.DaylightSavings,
                                                 dateTime.TimeZone,
                                                 dateTime.UTCDateTime); }, "Set system date and time");
 }
        public void should_not_ack_message_with_other_peer_id()
        {
            _batchSize = 100;
            _delay     = 2.Seconds();

            var signal           = new ManualResetEventSlim();
            var persistedEntries = new List <MatcherEntry>();

            _storeBatchFunc = entries =>
            {
                persistedEntries.AddRange(entries);
                signal.Set();
            };

            using (SystemDateTime.PauseTime())
            {
                _matcher.Start();

                var messageId = MessageId.NextId();
                _matcher.EnqueueMessage(_peerId, messageId, new MessageTypeId("X"), new byte[0]);
                _matcher.EnqueueMessage(_otherPeerId, messageId, new MessageTypeId("X"), new byte[0]);
                _matcher.EnqueueAck(_otherPeerId, messageId);

                SystemDateTime.Set(utcNow: SystemDateTime.UtcNow.Add(_delay.Value));

                var persistCalled = signal.Wait(1.Second());
                persistCalled.ShouldBeTrue();

                var persistedEntry = persistedEntries.ExpectedSingle();
                persistedEntry.PeerId.ShouldEqual(_peerId);
            }
        }
Esempio n. 25
0
        public async Task should_persist_messages_in_order()
        {
            var firstPeer  = new PeerId("Abc.Testing.Target");
            var secondPeer = new PeerId("Abc.Testing.OtherTarget");

            _peerStateRepository.Add(new PeerState(firstPeer, 0, SystemDateTime.UtcNow.Date.Ticks));
            _peerStateRepository.Add(new PeerState(secondPeer, 0, SystemDateTime.UtcNow.Date.Ticks));

            using (MessageId.PauseIdGeneration())
                using (SystemDateTime.PauseTime())
                {
                    var expectedTransportMessages = Enumerable.Range(1, 100).Select(CreateTestTransportMessage).ToList();
                    var messages = expectedTransportMessages.SelectMany(x =>
                    {
                        var transportMessageBytes = Serialization.Serializer.Serialize(x).ToArray();
                        return(new[]
                        {
                            MatcherEntry.Message(firstPeer, x.Id, x.MessageTypeId, transportMessageBytes),
                            MatcherEntry.Message(secondPeer, x.Id, x.MessageTypeId, transportMessageBytes),
                        });
                    })
                                   .ToList();

                    await _storage.Write(messages);

                    _peerStateRepository[firstPeer].NonAckedMessageCount.ShouldEqual(100);
                    _peerStateRepository[secondPeer].NonAckedMessageCount.ShouldEqual(100);

                    var readerForFirstPeer = (CqlMessageReader)_storage.CreateMessageReader(firstPeer);
                    readerForFirstPeer.GetUnackedMessages().ToList().ShouldEqualDeeply(expectedTransportMessages);

                    var readerForSecondPeer = (CqlMessageReader)_storage.CreateMessageReader(secondPeer);
                    readerForSecondPeer.GetUnackedMessages().ToList().ShouldEqualDeeply(expectedTransportMessages);
                }
        }
        public void should_save_entries_with_different_timestamps_in_different_batches()
        {
            var persistedEntries = new List <MatcherEntry>();

            _storeBatchFunc = entries => persistedEntries.AddRange(entries);

            _delay     = 5.Seconds();
            _batchSize = 10;

            using (SystemDateTime.PauseTime())
            {
                // messages for batch 1
                _matcher.EnqueueMessage(_peerId, MessageId.NextId(), new MessageTypeId("Abc.X"), new byte[0]);
                _matcher.EnqueueMessage(_peerId, MessageId.NextId(), new MessageTypeId("Abc.X"), new byte[0]);
                SystemDateTime.Set(utcNow: SystemDateTime.UtcNow.Add(4.Seconds()));

                // message for batch 2
                _matcher.EnqueueMessage(_peerId, MessageId.NextId(), new MessageTypeId("Abc.X"), new byte[0]);
                SystemDateTime.Set(utcNow: SystemDateTime.UtcNow.Add(3.Seconds()));

                _matcher.Start();

                Wait.Until(() => persistedEntries.Count == 2, 500.Milliseconds());

                SystemDateTime.Set(utcNow: SystemDateTime.UtcNow.Add(2.Seconds()));

                Wait.Until(() => persistedEntries.Count == 3, 500.Milliseconds());
            }
        }
        public void should_persist_message_and_ack(int batchSize)
        {
            var persistedEntries = new List <MatcherEntry>();

            _storeBatchFunc = persistedEntries.AddRange;
            _batchSize      = batchSize;

            using (SystemDateTime.PauseTime())
            {
                _matcher.Start();

                var messageId = MessageId.NextId();
                _matcher.EnqueueMessage(_peerId, messageId, new MessageTypeId("Abc.X"), new byte[0]);

                var signal = new AutoResetEvent(false);
                _matcher.EnqueueWaitHandle(signal);
                signal.WaitOne(50000).ShouldBeTrue();

                _matcher.EnqueueAck(_peerId, messageId);

                _matcher.EnqueueWaitHandle(signal);
                signal.WaitOne(50000).ShouldBeTrue();

                persistedEntries.Count.ShouldEqual(2);
            }
        }
Esempio n. 28
0
        public async Task should_write_message_entry_fields_to_cassandra()
        {
            using (SystemDateTime.PauseTime())
            {
                var messageBytes = new byte[512];
                new Random().NextBytes(messageBytes);
                var messageId = MessageId.NextId();
                var peerId    = "Abc.Peer.0";

                await _storage.Write(new List <MatcherEntry> {
                    MatcherEntry.Message(new PeerId(peerId), messageId, MessageTypeId.PersistenceStopping, messageBytes)
                });

                var retrievedMessage = DataContext.PersistentMessages.Execute().ExpectedSingle();
                retrievedMessage.TransportMessage.ShouldBeEquivalentTo(messageBytes, true);
                retrievedMessage.BucketId.ShouldEqual(GetBucketIdFromMessageId(messageId));
                retrievedMessage.IsAcked.ShouldBeFalse();
                retrievedMessage.PeerId.ShouldEqual(peerId);
                retrievedMessage.UniqueTimestampInTicks.ShouldEqual(messageId.GetDateTime().Ticks);
                var writeTimeRow = DataContext.Session.Execute("SELECT WRITETIME(\"IsAcked\") FROM \"PersistentMessage\";").ExpectedSingle();
                writeTimeRow.GetValue <long>(0).ShouldEqual(ToUnixMicroSeconds(messageId.GetDateTime()));

                var peerState = DataContext.PeerStates.Execute().ExpectedSingle();
                peerState.NonAckedMessageCount.ShouldEqual(1);
                peerState.PeerId.ShouldEqual(peerId);
                peerState.OldestNonAckedMessageTimestamp.ShouldEqual(messageId.GetDateTime().Ticks - PeerState.MessagesTimeToLive.Ticks);
            }
        }
 protected void SetSystemDateAndTime(SystemDateTime dateTime, string stepName)
 {
     RunStep(() => { Client.SetSystemDateAndTime(dateTime.DateTimeType,
                                                 dateTime.DaylightSavings,
                                                 dateTime.TimeZone,
                                                 dateTime.UTCDateTime); }, stepName);
     DoRequestDelay();
 }
        public void SystemDateTime_ReturnsCurrentDateTime()
        {
            // Arrange
            var sdt = new SystemDateTime();

            // Assert
            Assert.Equal(DateTime.Now.ToString(CultureInfo.InvariantCulture), sdt.Now.ToString(CultureInfo.InvariantCulture));
        }