Esempio n. 1
0
        public void restoring_incompatible_snapshot_should_return_false()
        {
            var ticket    = TicketTestFactory.ForTest();
            var persister = (IEventSourcedAggregate)ticket;
            var snapshot  = new SnapshotInfo(ticket.Id, 2, null, 0);
            var restored  = persister.TryRestore(snapshot);

            Assert.False(restored);
        }
Esempio n. 2
0
        protected override SnapshotInfo PreprocessSnapshot(SnapshotInfo snapshotInfo)
        {
            if (snapshotInfo.SnapshotVersion != 1)
            {
                return(null);
            }

            return(snapshotInfo);
        }
Esempio n. 3
0
        void Initialize()
        {
            DateTime startTime = DateTime.Now;

            _at = ActionTree.Read <ActionTree>(ActionTreeFile);
            if (IsVerbose)
            {
                Console.WriteLine("Action tree: {0}", _at.Version.ToString());
            }
            _init             = new InitData(this);
            _playersCount     = _at.PlayersCount;
            _epsilonLog       = new List <EpsilonLogEntry>();
            _snapshotSwitcher = new SnapshotSwitcher(OutputPath, GetSnapshotHeaderFileName(), SnapshotsCount);
            _curSnapshotInfo  = new SnapshotInfo(_snapshotSwitcher.CurrentSnapshotPath, _playersCount);
            IterationCounts   = new int[_playersCount];
            LastBrValues      = new double[_playersCount];
            _ptExt            = new Node[_playersCount][];

            _rng       = new System.Random(RngSeed);
            _mcDealer  = new McDealer(GameDef, _rng);
            _hands     = new int[_playersCount][].Fill(i => new int[_mcDealer.HandSize]);
            _handSizes = GameDef.GetHandSizes();
            _oppGv     = new double[_at.NodesCount];

            bool isNewSnapshot = !_snapshotSwitcher.IsSnapshotAvailable;

            if (isNewSnapshot)
            {
                CreateNewSnapshot();
            }
            //LoadSnapshot();

            CreatePlayerTrees();

            for (int p = 0; p < _playersCount; ++p)
            {
                if (TraceDir != null)
                {
                    Vis.Show(this, p, GetTraceFileName(p, "tree", "init-pt", "gv"));
                }
            }
            if (TraceDir != null)
            {
                VisChanceTree.Show(_init.PlayerCt, GetTraceFileName(0, "pct", "", "gv"));
            }

            PrintInitDone();

            // Clean-up
            _init = null;
            double time = (DateTime.Now - startTime).TotalSeconds;

            if (IsVerbose)
            {
                Console.WriteLine("Initialization done in {0:0.0} s", time);
            }
        }
Esempio n. 4
0
        public void restoring_incompatible_snapshot_should_return_false()
        {
            var ticket       = TicketTestFactory.ForTest();
            var snaphottable = (ISnapshottable)ticket;
            var snapshot     = new SnapshotInfo(ticket.Id, 2, null, null);
            var restored     = snaphottable.TryRestore(snapshot);

            Assert.False(restored);
        }
Esempio n. 5
0
        public async Task snapshot_data_should_be_different_across_write_and_reads()
        {
            var input = new SnapshotInfo("Aggregate_1", 1, new State(), 1);

            await _snapshots.Add("Aggregate_1", input);

            var output = await _snapshots.Get("Aggregate_1", Int32.MaxValue);

            Assert.NotSame(input.Data, output.Data);
        }
        public async Task empty_snapshot_is_not_persisted()
        {
            var nullSnapshot = new SnapshotInfo("empty", 0, null, string.Empty);
            await _snapshots.AddAsync("empty", nullSnapshot);

            var tape = new Recorder();
            await Store.ReadForwardAsync("empty", 0, tape);

            Assert.True(tape.IsEmpty);
        }
        public async Task snapshot_data_should_be_different_across_write_and_reads()
        {
            var input = new SnapshotInfo("Aggregate_1", 1, new State(), string.Empty);

            await _snapshots.AddAsync("Aggregate_1", input);

            var output = await _snapshots.GetAsync("Aggregate_1", Int32.MaxValue);

            Assert.NotSame(input.Payload, output.Payload);
        }
Esempio n. 8
0
        internal StateSnapshot(ReplicatedState state, IntPtr stateHandle)
        {
            State = state;
            var info = new SnapshotInfo();

            handle       = PInvoke_GetSnapshot(stateHandle, ref info);
            Version      = info.Version;
            KeysCount    = info.KeysCount.ToUInt64();
            SubkeysCount = info.SubkeysCount.ToUInt64();
        }
        public async Task snapshots_can_be_deleted()
        {
            var input = new SnapshotInfo("Aggregate_1", 1, new State(), string.Empty);
            await _snapshots.AddAsync("Aggregate_1", input);

            await _snapshots.DeleteAsync("Aggregate_1");

            var tape = new Recorder();
            await Store.ReadForwardAsync("Aggregate_1", 0, tape);

            Assert.True(tape.IsEmpty);
        }
Esempio n. 10
0
        public async Task with_snapshot_but_without_stream_should_throw_stale_aggregate_exception()
        {
            var ticketState = new TicketState();
            var snapshot    = new SnapshotInfo("Ticket_1", 2, ticketState, "1");
            await Snapshots.AddAsync("Ticket_1", snapshot).ConfigureAwait(false);

            var ex = await Assert.ThrowsAsync <StaleSnapshotException>(() =>
                                                                       Repository.GetByIdAsync <Ticket>("Ticket_1")
                                                                       ).ConfigureAwait(false);

            Assert.Equal("Ticket_1", ex.AggregateId);
            Assert.Equal(2, ex.AggregateVersion);
        }
Esempio n. 11
0
        protected AbstractAggregateTest()
        {
            this.Aggregate = _defaultFactory.Create <TAggregate>();
            this.State     = new TState();
            var snapshot = new SnapshotInfo("test", 1, this.State, "1");

            ((ISnaphottable)this.Aggregate).TryRestore(snapshot);

            if (!this.Aggregate.IsInitialized)
            {
                throw new Exception("something went wrong");
            }
        }
Esempio n. 12
0
        public void process_can_apply_changeset()
        {
            Checkout.MessageReceived(new PaymentReceived("Order_1", DateTime.Parse("2017-12-31")));
            var changeset = GetChangeset();

            var cloned   = new CheckoutProcess();
            var snapshot = new SnapshotInfo("test", 1, new CheckoutState(), "1");

            ((ISnaphottable)cloned).TryRestore(snapshot);

            ((IEventSourcedAggregate)cloned).ApplyChanges(changeset);

            Assert.True(cloned.ExposeStateForTest.PaymentReceived);
        }
Esempio n. 13
0
        public void TestXmlSerializer_ISerializable()
        {
            var value = new SnapshotInfo()
            {
                Time = DateTime.Now.ToUniversalTime()
            };

            var xml = XmlSerializer.Serialize(value);

            var roundtrip = (SnapshotInfo)XmlSerializer.Deserialize(xml);

            Assert.IsNotNull(roundtrip);
            Assert.AreEqual <Guid>(value.Id, roundtrip.Id);
            Assert.AreEqual <DateTime>(value.Time, roundtrip.Time);
        }
 /// <summary>
 /// Validate the object.
 /// </summary>
 /// <exception cref="ValidationException">
 /// Thrown if validation fails
 /// </exception>
 public virtual void Validate()
 {
     if (SiteConfig != null)
     {
         SiteConfig.Validate();
     }
     if (CloningInfo != null)
     {
         CloningInfo.Validate();
     }
     if (SnapshotInfo != null)
     {
         SnapshotInfo.Validate();
     }
 }
 /// <summary>
 /// Validate the object.
 /// </summary>
 /// <exception cref="ValidationException">
 /// Thrown if validation fails
 /// </exception>
 public override void Validate()
 {
     if (SiteConfig != null)
     {
         SiteConfig.Validate();
     }
     if (CloningInfo != null)
     {
         CloningInfo.Validate();
     }
     if (SnapshotInfo != null)
     {
         SnapshotInfo.Validate();
     }
 }
Esempio n. 16
0
    private void ParsePackedNativeUnityEngineObject()
    {
        _snapshotInfo = new SnapshotInfo();
        Debug.Log("nativeObjects Length: " + _snapshot.nativeObjects.Length);
        foreach (PackedNativeUnityEngineObject nativeObject in _snapshot.nativeObjects)
        {
            string typeName = _snapshot.nativeTypes[nativeObject.nativeTypeArrayIndex].name;

            _snapshotInfo.AddObjectToType(typeName, nativeObject);
            _snapshotInfo.TotalSize += nativeObject.size;
            _snapshotInfo.TotalObjects++;
        }

        _snapshotInfo.Sort();
    }
Esempio n. 17
0
        public void TestSaveAndGet_ISerializable()
        {
            var testObject = new SnapshotInfo()
            {
                Time = DateTime.Now
            };

            testFile.SaveItem(key, testObject);


            var roundTrip = testFile.GetItem <SnapshotInfo>(key);

            Assert.IsNotNull(roundTrip);
            Assert.AreEqual <Guid>(testObject.Id, roundTrip.Id);
            Assert.AreEqual <DateTime>(testObject.Time, roundTrip.Time.ToLocalTime());
        }
Esempio n. 18
0
        private async Task <SnapshotInfo> LoadSnapshot(string snapshotId, CancellationToken cancellationToken)
        {
            SnapshotInfo si = null;

            if (_upToIndex.HasValue)
            {
                si = await _snapshots.GetAsync(snapshotId, _upToIndex.Value, cancellationToken)
                     .ConfigureAwait(false);
            }
            else
            {
                si = await _snapshots.GetLastAsync(snapshotId, cancellationToken)
                     .ConfigureAwait(false);
            }
            return(si);
        }
Esempio n. 19
0
        public AbstractProcessManagerTest()
        {
            Process = _defaultFactory.Create <TProcess>();
            State   = new TState();

            //restore @ version 1
            var snapshot = new SnapshotInfo("test", 1, State, "1");

            ((ISnaphottable)this.Process).TryRestore(snapshot);

            if (!this.Process.IsInitialized)
#pragma warning disable S112 // General exceptions should never be thrown
            {
                throw new Exception("something went wrong");
            }
#pragma warning restore S112 // General exceptions should never be thrown
        }
Esempio n. 20
0
        protected override SnapshotInfo PreprocessSnapshot(SnapshotInfo snapshotInfo)
        {
            var baseProcessing = base.PreprocessSnapshot(snapshotInfo);

            if (baseProcessing == null)
            {
                return(null);
            }

            //We are trying to restore a snapshot that has not the very same version of itnernal state of this aggregate
            var emptyState = new TState();

            if (snapshotInfo.SchemaVersion != emptyState.VersionSignature)
            {
                return(null);
            }

            JarvisAggregateState state = snapshotInfo.Payload as JarvisAggregateState;

            if (state == null)
            {
                return(null);
            }

            //If we need to restore the aggregate we should restore all the entities
            snapshotRestoredEntities = new List <IEntityRoot>();
            foreach (var entity in CreateChildEntities(snapshotInfo.SourceId))
            {
                JarvisEntityState entityState;
                if (!state.EntityStates.TryGetValue(entity.Id, out entityState))
                {
                    return(null); // one of the entity cannot be restored
                }
                //TODO: Need to change nstore to avoid this.
                var info = new SnapshotInfo(snapshotInfo.SourceId, snapshotInfo.SourceVersion, entityState.Clone(), entityState.VersionSignature);
                if (!entity.TryRestore(info))
                {
                    return(null); //This snapshot is not valid for the entity
                }
                snapshotRestoredEntities.Add(entity);
            }

            //Set restore snapshot and create a new payload with a clone of the state
            RestoreSnapshot = snapshotInfo;
            return(new SnapshotInfo(snapshotInfo.SourceId, snapshotInfo.SourceVersion, state.Clone(), snapshotInfo.SchemaVersion));
        }
Esempio n. 21
0
        public void LoadSnapshot()
        {
            if (IsVerbose)
            {
                Console.WriteLine("Loading snapshot from {0}", _curSnapshotInfo.BaseDir);
            }

            _loadedSnapshotInfo = _curSnapshotInfo;

            using (TextReader tr = new StreamReader(_curSnapshotInfo.HeaderFile))
            {
                string line;
                for (int pos = 0; pos < _playersCount; ++pos)
                {
                    line = tr.ReadLine();
                    IterationCounts[pos] = int.Parse(line);
                }
                line = tr.ReadLine();
            }

            _epsilonLog.Clear();
            if (File.Exists(_curSnapshotInfo.EpsilonLog))
            {
                using (TextReader tr = new StreamReader(_curSnapshotInfo.EpsilonLog))
                {
                    for (;;)
                    {
                        string line;
                        line = tr.ReadLine();
                        if (line == null)
                        {
                            break;
                        }
                        string[] data = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                        _epsilonLog.Add(new EpsilonLogEntry
                        {
                            Epsilon = double.Parse(data[0]),
                            TotalIterationsCount = int.Parse(data[1]),
                        });
                    }
                }
            }
        }
Esempio n. 22
0
        public static T Create <T, TId, TState>(TState initialState, IIdentity identity, Int32 version)
            where T : AggregateRoot <TState, TId>
            where TState : JarvisAggregateState, new()
            where TId : EventStoreIdentity
        {
            if (identity == null)
            {
                throw new ArgumentNullException(nameof(identity));
            }

            var ctor = typeof(T).Constructor(Flags.Default, new Type[] { });

            if (ctor == null)
            {
                throw new MissingMethodException(string.Format("{0} missing default ctor", typeof(T).FullName));
            }

            var aggregate = (T)ctor.CreateInstance();

            //To restore the state from the test we need to pass from the snapshot
            if (version > 0)
            {
                SnapshotInfo snapshot = new SnapshotInfo(
                    identity.ToString(),
                    version,
                    initialState,
                    initialState.VersionSignature);

                aggregate.Init(identity.ToString());
                var restoreResult = ((ISnapshottable)aggregate).TryRestore(snapshot);
                if (!restoreResult)
                {
                    throw new Machine.Specifications.SpecificationException("Unable to restore snapshot into the aggregate under test");
                }
            }
            else if (initialState != null)
            {
                throw new Machine.Specifications.SpecificationException("If you specify a not null initialState version should be greater than zero. Pass null as state if you want to create a new empty aggregate!!");
            }
            aggregate.Init(identity.AsString());
            return(aggregate);
        }
Esempio n. 23
0
        public void TestSnapshotInfoSerialization_Valid()
        {
            var snapshotInfo = new SnapshotInfo();

            snapshotInfo.Time = DateTime.Now.ToUniversalTime();

            var xml = snapshotInfo.Serialize();

            var roundTrip = new SnapshotInfo();

            Assert.IsTrue(roundTrip.Validate(xml));

            roundTrip.Deserialize(xml);


            Assert.IsNotNull(snapshotInfo);
            Assert.IsNotNull(roundTrip);

            Assert.AreEqual <Guid>(snapshotInfo.Id, roundTrip.Id);
            Assert.AreEqual <DateTime>(snapshotInfo.Time, roundTrip.Time);
        }
Esempio n. 24
0
        /// <summary>
        /// See <see cref="IDatabaseServices.DeleteSnapshot(SnapshotInfo)"/>.
        /// </summary>
        public void DeleteSnapshot(SnapshotInfo snapshot)
        {
            ArgumentChecks.AssertNotNull(snapshot, nameof(snapshot));

            try
            {
                snapshot.Database.Connection.DbServer.Services.Snapshots.DeleteSnapshot(
                    snapshot.Name,
                    new DbServerConnectionData(
                        snapshot.Database.Connection.Host,
                        snapshot.Database.Connection.UsesIntegratedSecurity,
                        snapshot.Database.Connection.UserId,
                        snapshot.Database.Connection.Password));
            }
            catch (Exception ex)
            {
                var message = string.Format(CultureInfo.CurrentCulture, Messages.DeleteSnapshotFailed, snapshot);

                throw new SnapshotException(message, ex);
            }
        }
Esempio n. 25
0
        bool ISnapshottable.TryRestore(SnapshotInfo snapshotInfo)
        {
            if (snapshotInfo == null)
            {
                throw new ArgumentNullException(nameof(snapshotInfo));
            }

            var processed = PreprocessSnapshot(snapshotInfo);

            if (processed == null || processed.IsEmpty)
            {
                return(false);
            }

            this.InternalInit(
                processed.SourceId,
                processed.SourceVersion,
                (TState)processed.Payload
                );

            return(true);
        }
Esempio n. 26
0
        /// <summary>
        /// See <see cref="ISnapshotRepository.TryDeleteSnapshot(SnapshotInfo)"/>.
        /// </summary>
        public SuccessResult TryDeleteSnapshot(SnapshotInfo snapshot)
        {
            ArgumentChecks.AssertNotNull(snapshot, nameof(snapshot));

            try
            {
                this._databaseServices.DeleteSnapshot(snapshot);

                // If this snapshot and his friends from the same database were already loaded...
                if (this._snapshotsPerDatabaseDict.ContainsKey(snapshot.Database))
                {
                    // ...we try to reload them.
                    return(this.TryLoadSnapshots(snapshot.Database));
                }

                return(SuccessResult.CreateSuccessful());
            }
            catch (SnapshotException ex)
            {
                return(SuccessResult.CreateFailed($"{ex.Message} ({ex.InnerException.Message})"));
            }
        }
Esempio n. 27
0
        public bool TryRestore(SnapshotInfo snapshotInfo)
        {
            if (snapshotInfo == null)
            {
                throw new ArgumentNullException(nameof(snapshotInfo));
            }

            var processed = PreprocessSnapshot(snapshotInfo);

            if (processed == null || processed.IsEmpty)
            {
                return(false);
            }

            var state = (TState)processed.Payload;

            if (snapshotInfo.SchemaVersion != _state.VersionSignature)
            {
                return(false);
            }

            _state = state;
            return(true);
        }
Esempio n. 28
0
 /// <summary>
 /// Give chance to upcast state or just drop snapshot with empty default state
 /// </summary>
 /// <param name="snapshotInfo"></param>
 /// <returns></returns>
 protected virtual SnapshotInfo PreprocessSnapshot(SnapshotInfo snapshotInfo)
 {
     return(snapshotInfo);
 }
Esempio n. 29
0
        /// <summary>
        /// Delegate for logging core actions.
        /// </summary>
        /// <param name="core">The core the request was made for.</param>
        /// <param name="request">The original request.</param>
        /// <param name="action">The action taken.</param>
        private void RequestProcessed(Core core, CoreRequest request, CoreAction action)
        {
            if (core == _core)
            {
                if (action != null)
                {
                    Auditors?.Invoke(action);

                    if (action.Type != CoreAction.Types.CreateSnapshot &&
                        action.Type != CoreAction.Types.DeleteSnapshot &&
                        action.Type != CoreAction.Types.RevertToSnapshot)
                    {
                        HistoryEvent e = _history.AddCoreAction(action);

                        switch (action.Type)
                        {
                        case CoreRequest.Types.LoadDisc:
                            Status = (action.MediaBuffer.GetBytes() != null) ? "Loaded disc" : "Ejected disc";
                            break;

                        case CoreRequest.Types.LoadTape:
                            Status = (action.MediaBuffer.GetBytes() != null) ? "Loaded tape" : "Ejected tape";
                            break;

                        case CoreRequest.Types.Reset:
                            Status = "Reset";
                            break;
                        }
                    }

                    if (action.Type == CoreAction.Types.RunUntil)
                    {
                        lock (_snapshots)
                        {
                            SnapshotInfo newSnapshot = _snapshots.LastOrDefault();
                            if (newSnapshot != null && action.AudioSamples != null)
                            {
                                newSnapshot.AudioBuffer.Write(action.AudioSamples);
                            }
                        }
                    }
                    else if (action.Type == CoreAction.Types.RevertToSnapshot)
                    {
                        HistoryEvent historyEvent = ((SnapshotInfo)request.UserData).HistoryEvent;
                        if (_history.CurrentEvent != historyEvent)
                        {
                            _history.CurrentEvent = historyEvent;
                        }

                        Display.CopyScreenAsync();
                    }
                    else if (action.Type == CoreAction.Types.CreateSnapshot)
                    {
                        lock (_snapshots)
                        {
                            // Figure out what history event should be set as current if we revert to this snapshot.
                            // If the current event is a RunUntil, it may not be "finalized" yet (i.e. it may still
                            // be updated), so go with its parent.
                            HistoryEvent historyEvent = _history.MostRecentClosedEvent(_history.CurrentEvent);

                            SnapshotInfo newSnapshot = new SnapshotInfo(action.SnapshotId, historyEvent);
                            _snapshots.Add(newSnapshot);

                            while (_snapshots.Count > _snapshotLimit)
                            {
                                SnapshotInfo snapshot = _snapshots[0];
                                _snapshots.RemoveAt(0);
                                _core.PushRequest(CoreRequest.DeleteSnapshot(snapshot.Id));
                            }
                        }
                    }
                }
            }
        }
Esempio n. 30
0
        public async Task <IAggregate> GetByIdAsync(Type aggregateType, string id, CancellationToken cancellationToken)
        {
            if (_trackingAggregates.TryGetValue(id, out IAggregate aggregate))
            {
                return(aggregate);
            }

            aggregate = _factory.Create(aggregateType);
            var persister = (IEventSourcedAggregate)aggregate;

            SnapshotInfo snapshot = null;

            if (_snapshots != null && aggregate is ISnapshottable snapshottable)
            {
                snapshot = await _snapshots.GetLastAsync(id, cancellationToken).ConfigureAwait(false);

                if (snapshot != null)
                {
                    //@@REVIEW: invalidate snapshot on false?
                    snapshottable.TryRestore(snapshot);
                }
            }

            if (!aggregate.IsInitialized)
            {
                aggregate.Init(id);
            }

            _trackingAggregates.Add(id, aggregate);
            var stream = OpenStream(id);

            int readCount    = 0;
            var subscription = new LambdaSubscription(data =>
            {
                readCount++;
                persister.ApplyChanges((Changeset)data.Payload);
                return(Task.FromResult(true));
            });
            var consumer = ConfigureConsumer(subscription, cancellationToken);

            // we use aggregate.Version because snapshot could be rejected
            // Starting point is inclusive, so almost one changeset should be loaded
            // aggregate will ignore because ApplyChanges is idempotent
            await stream.ReadAsync(consumer, aggregate.Version, long.MaxValue, cancellationToken).ConfigureAwait(false);

            //Check lambda subscription for errors.
            if (subscription.Failed)
            {
                throw new RepositoryReadException($"Error reading aggregate {id}", subscription.LastError);
            }

            persister.Loaded();

            // no data from stream, we cannot validate the aggregate
            if (snapshot != null && readCount == 0)
            {
                throw new StaleSnapshotException(snapshot.SourceId, snapshot.SourceVersion);
            }

            return(aggregate);
        }