Esempio n. 1
0
        public EventStoreTests()
        {
            inMemoryCrudRepository = Substitute.ForPartsOf <InMemoryCrudRepository>();

            eventStreams = new[]
            {
                new EventStream(Guid.NewGuid()),
                new EventStream(Guid.NewGuid()),
                new EventStream(Guid.NewGuid())
            };
            inMemoryCrudRepository.AttachRange(eventStreams);

            eventSerializer = Substitute.For <IEventSerializer>();

            eventSerializer.SerializeEvent(null)
            .ReturnsForAnyArgs(ci => ("{\"bar\":" + ci.ArgAt <Event1>(0).Foo + "}", new VersionedTypeId("EventName", 5)));
            eventSerializer.DeserializeEvent(Arg.Any <string>(), new VersionedTypeId("EventName", 5))
            .Returns(ci => new Event1((int)JObject.Parse(ci.ArgAt <string>(0))["bar"]));
            eventSerializer.SerializeEventMetadata(null)
            .ReturnsForAnyArgs(ci => JsonConvert.SerializeObject(ci.Arg <IReadOnlyDictionary <string, string> >()
                                                                 .Append(new KeyValuePair <string, string>("fakeSer", "true"))
                                                                 .ToDictionary(x => x.Key, x => x.Value)));
            eventSerializer.DeserializeEventMetadata(null)
            .ReturnsForAnyArgs(ci =>
            {
                var json          = JObject.Parse(ci.Arg <string>());
                json["fakeDeser"] = "true";
                return(new JsonMetadata(json));
            });

            FakeClock.Setup();

            eventStreamRows = new[]
            {
                new EventStreamRow(Guid.NewGuid(), "{\"bar\":1}", "EventName", 5, eventStreams[0].Id, 1, Clock.Current.Now, "{\"doh\":\"1\"}"),
                new EventStreamRow(Guid.NewGuid(), "{\"bar\":2}", "EventName", 5, eventStreams[0].Id, 2, Clock.Current.Now, "{\"doh\":\"2\"}"),
                new EventStreamRow(Guid.NewGuid(), "{\"bar\":3}", "EventName", 5, eventStreams[1].Id, 3, Clock.Current.Now, "{\"doh\":\"3\"}"),
                new EventStreamRow(Guid.NewGuid(), "{\"bar\":4}", "EventName", 5, eventStreams[1].Id, 2, Clock.Current.Now, "{\"doh\":\"4\"}"),
                new EventStreamRow(Guid.NewGuid(), "{\"bar\":5}", "EventName", 5, eventStreams[1].Id, 4, Clock.Current.Now, "{\"doh\":\"5\"}"),
                new EventStreamRow(Guid.NewGuid(), "{\"bar\":6}", "EventName", 5, eventStreams[1].Id, 5, Clock.Current.Now, "{\"doh\":\"6\"}")
            };

            expectedStoreRecords = eventStreamRows.Select((x, i) =>
                                                          new FakeEventStoreRecord()
            {
                Event = eventSerializer.DeserializeEvent(x.EventJson, new VersionedTypeId(x.EventName, x.EventVersion)),
                AdditionalMetadata = new Dictionary <string, string>()
                {
                    { "doh", (i + 1).ToString() }, { "fakeDeser", "true" }
                },
                EventId = eventStreamRows[i].Id,
                StreamSequenceNumber = eventStreamRows[i].StreamSequenceNumber
            })
                                   .ToArray();

            inMemoryCrudRepository.AttachRange(eventStreamRows);

            sut = new EventStore(inMemoryCrudRepository, eventSerializer);
        }
Esempio n. 2
0
        /// <summary>
        /// Processes an incoming message and returns the event output.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <returns>The event.</returns>
        private Event ProcessMessage(InboundMessage message)
        {
            // read envelope
            Envelope envelope = new Envelope(message, _namespace);

            // check for header
            if (!envelope.Headers.ContainsKey(EventHeader.HEADER_NAME))
            {
                throw new InvalidDataException("Invalid event header");
            }

            // read header
            EventHeader header = new EventHeader(Encoding.UTF8.GetString(envelope.Headers[EventHeader.HEADER_NAME] as byte[]));

            // validate version
            if (header.Version != "1.1")
            {
                throw new NotSupportedException("Event version is not supported");
            }

            // find serializer
            IEventSerializer serializer = null;

            if (!EventSerializer.Serializers.TryGetValue(header.Serializer, out serializer))
            {
                throw new NotSupportedException("Event serializer not supported");
            }

            // post
            Event e = serializer.DeserializeEvent(envelope.Body);

            return(e);
        }
Esempio n. 3
0
        public async Task <IEnumerable <Event> > GetAllAsync(StreamId streamId, CancellationToken cancellationToken)
        {
            var events      = new List <Event>();
            var loaded      = false;
            var readAllPage = await _streamStore.ReadStreamForwards(streamId, 0, 100, cancellationToken);

            while (!loaded)
            {
                foreach (var message in readAllPage.Messages)
                {
                    var json = await message.GetJsonData(cancellationToken);

                    var data = (Event)_eventSerializer.DeserializeEvent(message.Type, json);
                    data.ExpectedVersion = message.StreamVersion;
                    events.Add(data);
                }

                if (!readAllPage.IsEnd)
                {
                    readAllPage = await readAllPage.ReadNext(cancellationToken);
                }
                else
                {
                    loaded = true;
                }
            }

            return(events);
        }
Esempio n. 4
0
        private async Task <object> DeserializeJsonEvent(StreamMessage streamMessage,
                                                         CancellationToken cancellationToken)
        {
            var json = await streamMessage.GetJsonData(cancellationToken);

            return(_eventSerializer.DeserializeEvent(streamMessage.Type, json));
        }
        public async Task <IEnumerable <TEvent> > LoadEventsAsync <TEvent>(string streamName)
        {
            // TODO: Handle large streams in  batches
            var eventsSlice = await _connection.ReadStreamEventsForwardAsync(streamName, 0, ClientApiConstants.MaxReadSize, false);

            switch (eventsSlice.Status)
            {
            case SliceReadStatus.Success:
                break;

            case SliceReadStatus.StreamNotFound:
                // TOOO: Better exception
                throw new InvalidOperationException($"Unable to find stream {streamName}");

            case SliceReadStatus.StreamDeleted:
                throw new StreamDeletedException(streamName);

            default:
                throw new ArgumentOutOfRangeException();
            }

            var events = eventsSlice.Events;

            return(events.Select(e => _serializer.DeserializeEvent <TEvent>(e.OriginalEvent.Data, e.OriginalEvent.EventType)));
        }
Esempio n. 6
0
 public IEnumerable <IEvent> ExtractEvents(EventCommit commit)
 {
     foreach (KeyValuePair <string, EventDto> @event in commit.Events)
     {
         @event.Value.Headers.Add(EventHeaderKeys.AggregateId, commit.AggregateId);
         @event.Value.Headers.Add(EventHeaderKeys.CommitId, commit.Ordinal.ToString());
         yield return(serializer.DeserializeEvent(@event.Value.Headers, @event.Value.Body));
     }
 }
Esempio n. 7
0
        public IEvent FromResolvedEvent(ResolvedEvent @event)
        {
            string headerVal  = eventEncoding.GetString(@event.Event.Metadata);
            string contentVal = eventEncoding.GetString(@event.Event.Data);

            IEvent result = serializer.DeserializeEvent(headerVal, contentVal);

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

            result.Headers.Set(EventHeaderKeys.EventNumber, @event.OriginalEventNumber);
            return(result);
        }
Esempio n. 8
0
    StreamEvent ToStreamEvent(ResolvedEvent resolvedEvent)
    {
        var deserialized = _serializer.DeserializeEvent(
            resolvedEvent.Event.Data.ToArray(),
            resolvedEvent.Event.EventType,
            resolvedEvent.Event.ContentType
            );

        return(deserialized switch {
            SuccessfullyDeserialized success => AsStreamEvent(success.Payload),
            FailedToDeserialize failed => throw new SerializationException(
                $"Can't deserialize {resolvedEvent.Event.EventType}: {failed.Error}"
                ),
            _ => throw new Exception("Unknown deserialization result")
        });
Esempio n. 9
0
        public async Task CatchUpAsync()
        {
            var nondispatchedEvents = (await readRepository
                                       .Where <ExternalEventRecord>(x => !x.IsDispatchedToAsyncQueues)
                                       .ToListAsync(readRepository));

            if (nondispatchedEvents.Count > 0)
            {
                var messages = nondispatchedEvents.Select(x =>
                {
                    var @event = eventSerializer.DeserializeEvent(x.EventJson,
                                                                  new VersionedTypeId(x.EventName, x.EventVersion));
                    var metadata = eventSerializer.DeserializeEventMetadata(x.MetadataJson);
                    return(EventMessage.FromEvent(@event, metadata));
                });

                await asyncEventQueueDispatcher.DispatchToQueuesAsync(messages, null, null);
            }
        }
        protected override async Task EventAppeared(ResolvedEvent resolvedEvent, long currentPosition)
        {
            var domainEvent = _eventSerializer.DeserializeEvent(resolvedEvent);

            await _mediator.MediateEvent(domainEvent);
        }
Esempio n. 11
0
 private DomainEvent ConvertEventDataToDomainEvent(ResolvedEvent resolvedEvent)
 {
     return(_eventSerializer.DeserializeEvent(resolvedEvent));
 }