Example #1
0
        private async Task<IEnumerable<IEvent>> Insert(IStream stream, int version, IEnumerable<IEvent> events, bool doInsert)
        {
            var store = GetStore(stream);
            var origVersion = version;
            var currentBranch = _manager.ActiveBranch;
            var liveStream = await _streamLocator.FindBranched(stream, currentBranch);

            IList<IEvent> laterEvents = new List<IEvent>();

            if (liveStream != null)
                laterEvents = await store.ReadStream<IEvent>(liveStream, version).ToList();
            else
                stream = stream.Branch(currentBranch, ExpectedVersion.EmptyStream);

            if (laterEvents.Count == 0)
            {
                if (doInsert)
                    return await Append(stream, version, events);

                if (stream.Version != version - 1)
                    throw new InvalidOperationException("Stream version is inconsistent");
                return new List<IEvent>();
            }

            var enumerable = events.ToList();
            Time time;
            if (version > 0)
                time = (await store.ReadStream<IEvent>(stream, version - 1, 1).SingleAsync()).Timestamp;
            else
                time = enumerable.First().Timestamp;

            var tempStreamId = $"{stream.Timeline}-{stream.Id}-{version}";
            var branch = await _manager.Branch(tempStreamId, time);

            var newStream = await _streamLocator.FindBranched(stream, branch.Id);
            if (newStream == null)
                throw new InvalidOperationException($"Stream {tempStreamId}:{stream.Type}:{stream.Id} not found!");

            var invalidEvents = (await Append(newStream, version, enumerable.Concat(laterEvents))).ToList();
            
            await _manager.Branch(currentBranch);
            if (doInsert && !invalidEvents.Any())
            {
                await TrimStream(liveStream, origVersion - 1);
                await _manager.Merge(tempStreamId);
            }
            
            await _manager.DeleteBranch(tempStreamId);
            return invalidEvents;
        }
Example #2
0
        /// <inheritdoc />
        public async Task DeleteStream(IStream stream)
        {
            await DeleteStreamStore(stream);

            _streams.OnNext(stream.Branch(stream.Timeline, ExpectedVersion.NoStream));
        }