private void CreateOrAppend(Guid aggregateId, EventStream eventStream, int expectedVersion) { var path = EventStoreFilePath.From(Dir, aggregateId).Value; EnsureRootDirectoryExists(); EnsurePathExists(path); lock (Lock.For(aggregateId)) { var currentVersion = GetCurrentVersion(path); if (currentVersion != expectedVersion) throw new OptimisticConcurrencyException(currentVersion, expectedVersion); using (var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read)) { using (var streamWriter = new StreamWriter(stream)) { foreach (var @event in eventStream) { currentVersion++; streamWriter.WriteLine(new Record(aggregateId, @event, currentVersion).Serialized()); } } } } }
public void Parallel() { using (var options = new StreamOptions()) using (var eventStream = new EventStream(options)) { var tasks = new List<Task>(); for (int i = 0; i < 10; i++) { tasks.Add(Task.Factory.StartNew(() => { for (int j = 0; j < 5; j++) { eventStream.AppendAsync(new RavenJObject { { "counter", i +"-" + j } }).Wait(); } })); } foreach (var task in tasks) { while (task.IsCompleted == false && task.IsFaulted == false) { Thread.Sleep(100); } } Assert.Equal(50, eventStream.EventCount); } }
public void CanRestart() { using (var options = new StreamOptions { Storage = new FileSystemLowLevelStorage("data") }) { using (var eventStream = new EventStream(options)) { for (int i = 0; i < 15; i++) { eventStream.AppendAsync(new RavenJObject { { "counter", i } }).Wait(); } eventStream.FlushMemTableToFiskAsync(Etag.Empty).Wait(); eventStream.FlushingMemTable.Wait(); } using (var eventStream = new EventStream(options)) { Assert.Equal(15, eventStream.EventCount); int x = 0; foreach (var it in eventStream.ReadFrom(Etag.Empty)) { Assert.Equal(x++, it.Value<int>("counter")); } } } }
public void AndGetRightCount_Parallel() { using (var options = new StreamOptions()) using (var eventStream = new EventStream(options)) { var tasks = new List<Task>(); for (int x = 0; x < 3; x++) { for (int i = 0; i < 10; i++) { tasks.Add(Task.Factory.StartNew(() => { for (int j = 0; j < 5; j++) { eventStream.AppendAsync(new RavenJObject { { "counter", i + "-" + j } }).Wait(); } })); } foreach (var task in tasks) { while (task.IsCompleted == false && task.IsFaulted == false) { Thread.Sleep(100); } } eventStream.FlushMemTableToFiskAsync(Etag.Empty).Wait(); eventStream.FlushingMemTable.Wait(); } Assert.Equal(150, eventStream.EventCount); } }
/// <summary> /// Saves a new file to disk containing event eventStream data /// </summary> /// <param name="aggregateRootId">Aggregate root id</param> /// <param name="domainEvents">List of events</param> /// <param name="extension">File extension for the created file</param> public void InsertEvents(Guid aggregateRootId, IEnumerable<DomainEvent> domainEvents, string extension) { var events = domainEvents.ToList(); var firstEvent = events.First(); var lastEvent = events.Last(); var stream = new EventStream { AggregateRootId = aggregateRootId, DateCreated = DateTime.UtcNow, SequenceStart = firstEvent.Sequence, SequenceEnd = lastEvent.Sequence, EventData = events }; var aggregateRootDirectory = Path.Combine(FileUtility.GetEventDirectory(), aggregateRootId.ToString()); if (!Directory.Exists(aggregateRootDirectory)) { Directory.CreateDirectory(aggregateRootDirectory); } var fileName = string.Format("{0}-{1}.{2}", firstEvent.Sequence, lastEvent.Sequence, extension); var eventPath = Path.Combine(aggregateRootDirectory, fileName); var serialized = GetEventStreamText(stream); File.WriteAllText(eventPath, serialized); }
public void WhenHandlerRegistered_ThenCanProcessEntity() { var id = Guid.NewGuid(); var product = new Product(id, "DevStore"); var context = default(IDomainContext); var eventStream = new EventStream(); IDomainEventStore store = new ConsoleEventStore(); // Keep the handlers so they are not GC'ed. var handlers = new object[] { new ConsoleHandler(eventStream), new SendMailHandler(eventStream), }; context = new DomainContext(eventStream, store); context.Save(product); // Save changes and cause publication of pending events // in the newly created domain object. context.SaveChanges(); Console.WriteLine(); // Here some command might pull the product from the // context, and invoke a domain method. var savedProduct = context.Find<Product>(id); product.Publish(1); // Saving again causes persistence of the entity state // as well as publishing the events. context.SaveChanges(); }
public void when_patient_readmitted_then_raises_alert () { var events = new EventStream(); var query = from discharged in events.Of<PatientLeftHospital>() from admitted in events.Of<PatientEnteredHospital>() where admitted.PatientId == discharged.PatientId && (admitted.When - discharged.When).Days < 5 select admitted; var readmitted = new List<int>(); using (var subscription = query.Subscribe (e => readmitted.Add (e.PatientId))) { // Two patients come in. events.Push (new PatientEnteredHospital { PatientId = 1, When = new DateTime (2011, 1, 1) }); events.Push (new PatientEnteredHospital { PatientId = 2, When = new DateTime (2011, 1, 1) }); // Both leave same day. events.Push (new PatientLeftHospital { PatientId = 1, When = new DateTime (2011, 1, 15) }); events.Push (new PatientLeftHospital { PatientId = 2, When = new DateTime (2011, 1, 15) }); // One comes back before 5 days passed. events.Push (new PatientEnteredHospital { PatientId = 1, When = new DateTime (2011, 1, 18) }); // The other comes back after 10 days passed. events.Push (new PatientEnteredHospital { PatientId = 1, When = new DateTime (2011, 1, 25) }); } // We should have an alert for patient 1 who came back before 5 days passed. Assert.Equal (1, readmitted.Count); Assert.Equal (1, readmitted[0]); }
public void SaveEventStream(EventStream eventStream) { if (eventStream.Removed) { Remove(eventStream.Id); return; } if (_eventStreams.ContainsKey(eventStream.Id)) { _eventStreams.Remove(eventStream.Id); } eventStream.AttemptSnapshot(100); _eventStreams.Add(eventStream.Id, new EventStream(eventStream.Id, eventStream.Version, eventStream.EventsAfter(0), eventStream.Snapshot)); if (!eventStream.HasSnapshot) { return; } if (_snapshots.ContainsKey(eventStream.Id)) { _snapshots.Remove(eventStream.Id); } _snapshots.Add(eventStream.Id, eventStream.Snapshot); }
public void Should_be_able_to_handle_concurrency_invariant_check() { var stream = new EventStream(Guid.NewGuid(), 5, new List<Event>(), null); Assert.DoesNotThrow(() => stream.ConcurrencyInvariant(5)); Assert.Throws<EventStreamConcurrencyException>(() => stream.ConcurrencyInvariant(10)); }
public void Append(EventStream stream) { if (stream == null) { return; } try { var aggregateRootType = _aggregateRootTypeProvider.GetAggregateRootType(stream.AggregateRootName); var collectionName = _collectionNameProvider.GetCollectionName(stream.AggregateRootId, aggregateRootType); var collection = GetMongoCollection(collectionName); collection.Insert(ToMongoEventStream(stream)); } catch (Exception ex) { if (ex.Message.Contains("duplicate key error index")) { throw new ConcurrentException(); } else { throw; } } }
public async Task CreateStream_WillCreateStream_WhenStreamIdIsValid() { // arrange var streamId = Fixture.Create<Guid>(); var streamName = Fixture.Create<string>(); var expectedStream = new EventStream { EventStreamId = streamId, EventStreamName = streamName }; // act await _sut .CreateStream(streamId, streamName) .ConfigureAwait(false); // assert var actualStream = await DatabaseHelper .GetLatestStreamCreated() .ConfigureAwait(false); actualStream .ShouldBeEquivalentTo(expectedStream); }
public void NotifyChanges(IEventStore eventStore, EventStream streamOfEvents) { foreach( var notifierType in _notifiers ) { var notifier = _container.Get(notifierType) as IEventStoreChangeNotifier; notifier.Notify(eventStore, streamOfEvents); } }
/// <summary>Append the event stream to the event store. /// </summary> /// <param name="stream"></param> public void Append(EventStream stream) { if (stream == null) return; if (!_eventDict.TryAdd(new EventKey(stream.AggregateRootId, stream.Version), stream)) { throw new ConcurrentException(""); } }
// Register an event stream public void Register(EventStream stream, Action onReleaseStream) { _streams.Add(new StreamContainer { Stream = stream, OnReleaseStream = onReleaseStream }); }
public void when_user_login_fails_too_fast_then_locks_account () { var seconds = TimeSpan.FromSeconds(1).Ticks; var events = new EventStream(); // Here we use the test scheduler to simulate time passing by // because we have a dependency on time because of the Buffer // method. var scheduler = new TestScheduler(); var observable = scheduler.CreateColdObservable( // Two users attempt to log in, 4 times in a row new Recorded<Notification<LoginFailure>>(10 * seconds, Notification.CreateOnNext(new LoginFailure { UserId = 1 })), new Recorded<Notification<LoginFailure>>(10 * seconds, Notification.CreateOnNext(new LoginFailure { UserId = 2 })), new Recorded<Notification<LoginFailure>>(20 * seconds, Notification.CreateOnNext(new LoginFailure { UserId = 1 })), new Recorded<Notification<LoginFailure>>(20 * seconds, Notification.CreateOnNext(new LoginFailure { UserId = 2 })), new Recorded<Notification<LoginFailure>>(30 * seconds, Notification.CreateOnNext(new LoginFailure { UserId = 1 })), new Recorded<Notification<LoginFailure>>(30 * seconds, Notification.CreateOnNext(new LoginFailure { UserId = 2 })), new Recorded<Notification<LoginFailure>>(40 * seconds, Notification.CreateOnNext(new LoginFailure { UserId = 1 })), new Recorded<Notification<LoginFailure>>(40 * seconds, Notification.CreateOnNext(new LoginFailure { UserId = 2 })), // User 2 attempts one more time within the 1' window new Recorded<Notification<LoginFailure>>(45 * seconds, Notification.CreateOnNext(new LoginFailure { UserId = 2 })), // User 1 pulls out the paper where he wrote his pwd ;), so he takes longer new Recorded<Notification<LoginFailure>>(75 * seconds, Notification.CreateOnNext(new LoginFailure { UserId = 1 })) ); // This subscription bridges the scheduler-driven // observable with our event stream, causing us // to publish events as they are "raised" by the // test scheduler. observable.Subscribe (failure => events.Push (failure)); var query = events.Of<LoginFailure>() // Sliding windows 1' long, every 10'' .Buffer(TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(10), scheduler) // From all failure values .SelectMany(failures => failures // Group the failures by user .GroupBy(failure => failure.UserId) // Only grab those failures with more than 5 in the 1' window .Where(group => group.Count() >= 5) // Return the user id that failed to log in .Select(group => group.Key)); var blocked = new List<int>(); using (var subscription = query.Subscribe (userId => blocked.Add (userId))) { // Here we could advance the scheduler half way and test intermediate // state if needed. We go all the way past the end of our login failures. scheduler.AdvanceTo (100 * seconds); } // We should have only user # 2 in the list. Assert.False (blocked.Contains (1)); Assert.True (blocked.Contains (2)); }
/// <summary>Route a available uncommitted event queue for the given event stream message. /// </summary> /// <param name="stream"></param> /// <returns></returns> public IUncommittedEventQueue Route(EventStream stream) { if (_eventQueues == null) { _eventQueues = Configuration.Instance.GetUncommitedEventQueues().ToArray(); } return _eventQueues.Length > 0 ? _eventQueues[(Interlocked.Increment(ref _index) - 1) % _eventQueues.Length] : null; }
List<Guid> GetUniqueCommandContextsFromEvents(EventStream streamOfEvents) { var commandContextsToNotify = new List<Guid>(); foreach (var @event in streamOfEvents) if (!commandContextsToNotify.Contains(@event.CommandContext)) commandContextsToNotify.Add(@event.CommandContext); return commandContextsToNotify; }
/// <summary> /// Returns an EventStream schudeled on the EventBase of the server that generated the connection. /// Don't forget to dispose it! /// </summary> public Stream GetStream() { ThrowIfDisposed(); if (stream == null) stream = new EventStream(eventBase, socket, FileAccess.ReadWrite); return stream; }
public void Save(EventStream eventStream) { if (this.currentSession == null) { throw new NotSupportedException(); } this.currentSession.Save(eventStream); }
public void Process(EventStream eventStream, IEventProcessContext context) { var processingContext = new EventProcessingContext(eventStream, context); var queueIndex = processingContext.EventStream.AggregateRootId.GetHashCode() % WorkerCount; if (queueIndex < 0) { queueIndex = Math.Abs(queueIndex); } _queueList[queueIndex].Add(processingContext); }
public void Should_be_able_to_apply_empty_invariant() { EventStream stream = null; Assert.Throws<EventStreamEmptyException>(() => stream.EmptyInvariant()); stream = new EventStream(new Guid()); Assert.Throws<EventStreamEmptyException>(() => stream.EmptyInvariant()); }
/// <summary>Publish a given committed event stream to all the event handlers. /// </summary> /// <param name="stream"></param> public void Publish(EventStream stream) { var eventQueue = _eventQueueRouter.Route(stream); if (eventQueue == null) { throw new Exception("Could not route event stream to an appropriate committed event queue."); } eventQueue.Enqueue(stream); }
public void Save(EventStream eventStream) { /* if (this.eventStreams.ContainsKey(id)) { this.eventStreams[id] = new EventStream(id, expectedVersion, this.eventStreams[id].Events.Union(events).ToArray()); return; } this.eventStreams.Add(id, new EventStream(id, expectedVersion, events)); */ }
public void when_pushing_subscribed_event_then_calls_subscriber () { var stream = new EventStream(); var called = false; using (var subscription = stream.Of<ConcreteEvent> ().Subscribe (c => called = true)) { stream.Push (new ConcreteEvent ()); } Assert.True (called); }
public void WhenPushingSubscribedEvent_ThenDoesCallsSubscriber() { var stream = new EventStream(); var called = false; using (var subscription = stream.Of<PatientEnteredHospital>().Subscribe(c => called = true)) { stream.Push(new PatientEnteredHospital()); } Assert.True(called); }
public void Sequence() { using (var options = new StreamOptions()) using (var eventStream = new EventStream(options)) { for (int i = 0; i < 5; i++) { eventStream.AppendAsync(new RavenJObject {{"counter", i}}).Wait(); } Assert.Equal(5, eventStream.EventCount); } }
public async Task<EventStream> LoadEventStream(IIdentity id, long skip, int take) { var name = id.ToString(); var records = (await this.appender.ReadRecords(name, skip, take)).ToList(); var stream = new EventStream(); foreach (var tapeRecord in records) { stream.Events.AddRange(this.serializer.DeserializeEvent(tapeRecord.Data)); stream.Version = tapeRecord.Version; } return stream; }
public async Task<EventStream> ReplayAll(int? afterVersion = default(int?), int? maxVersion = default(int?)) { var records = (await this.appender.ReadRecords(afterVersion ?? 0, maxVersion ?? int.MaxValue)).ToList(); var stream = new EventStream(); foreach (var tapeRecord in records) { stream.Events.AddRange(this.serializer.DeserializeEvent(tapeRecord.Data)); stream.Version++; } return stream; }
public EventStream Load(IIdentity id) { Condition.Requires(id, "id").IsNotNull(); NamedDataSet data = AppendOnlyStore.Load(id.Literal); if (data == null) return null; List<IEvent> events = new List<IEvent>(data.Data.Select(d => (IEvent)Serializer.Deserialize(d))); EventStream s = new EventStream(data.Version, events); return s; }
public EventStream LoadEventStream(IIdentity id) { var key = IdentityToKey(id); // TODO: make this lazy somehow? var stream = new EventStream(); foreach (var record in _store.EnumerateMessages(key, 0, int.MaxValue)) { stream.Events.AddRange(record.Items.Cast<IEvent>()); stream.StreamVersion = record.StreamVersion; } return stream; }
protected BatchReleaseProcess(string activityId, EventStream eventStream) : base(activityId, eventStream) { }
/// <summary> /// Constructor that reads parameters from an Akka <see cref="Config"/> section. /// Expects property 'acceptable-heartbeat-pause'. /// </summary> /// <param name="config"></param> /// <param name="ev"></param> public DeadlineFailureDetector(Config config, EventStream ev) : this( config.GetTimeSpan("acceptable-heartbeat-pause"), config.GetTimeSpan("heartbeat-interval")) { }
private Tasker.Conclusion InstallSDPart2(Tasker tasker, Object sync) { var splitStream = new SplitterStream(Program.debugStreams); tasker.SetStatus(Resources.MountingSDCard); if (DialogOptions.MakeBootable) { hakchi.Shell.Execute("sh /tmp/init mount", null, splitStream, splitStream, 0, true); } else { hakchi.Shell.Execute("mkdir -p /data/", null, null, null, 0, true); hakchi.Shell.Execute("mount /dev/mmcblk0p1 /data/", null, null, null, 0, true); } hakchi.Shell.Execute("mkdir -p /data/hakchi/games/", null, null, null, 0, true); if (!DialogOptions.MakeBootable && DialogOptions.StoreSaves) { hakchi.Shell.Execute("mkdir -p /data/hakchi/saves/", null, null, null, 0, true); } if (DialogOptions.CopyType != SDFormatResult.CopyTypes.None) { using (EventStream copyDataProgress = new EventStream()) { var userDataDeviceName = Sunxi.NandInfo.GetNandInfo().GetDataPartition().Device; splitStream.AddStreams(copyDataProgress); copyDataProgress.OnData += (byte[] buffer) => tasker.SetStatus(Encoding.ASCII.GetString(buffer)); tasker.SetStatus(Resources.CopyingNandDataToSDCard); hakchi.Shell.Execute($"mkdir -p /{userDataDeviceName} && mount /dev/{userDataDeviceName} /{userDataDeviceName}", null, null, null, 0, true); if (DialogOptions.CopyType == SDFormatResult.CopyTypes.Everything) { hakchi.Shell.Execute($"rsync -avc /{userDataDeviceName}/ /data/", null, splitStream, splitStream, 0, true); } else { var nandPath = DialogOptions.MakeBootable ? $"/{userDataDeviceName}/clover" : $"/{userDataDeviceName}/clover/profiles/0"; var dataPath = DialogOptions.MakeBootable ? "/data/clover" : "/data/hakchi/saves"; if (hakchi.Shell.Execute($"[ -d {nandPath} ]") == 0) { hakchi.Shell.Execute($"rsync -avc {nandPath} {dataPath}", null, splitStream, splitStream, 0, true); } } hakchi.Shell.Execute($"umount /{userDataDeviceName}/ && rmdir /{userDataDeviceName}/", null, null, null, 0, true); splitStream.RemoveStream(copyDataProgress); copyDataProgress.Dispose(); } } if (DialogOptions.MakeBootable) { tasker.SetStatus(Resources.CopyingHakchiToSDCard); hakchi.Shell.Execute("sh /tmp/init copy", null, splitStream, splitStream, 0, true); tasker.SetStatus(Resources.UnmountingSDCard); hakchi.Shell.Execute("sh /tmp/init unmount", null, splitStream, splitStream, 0, true); } return(Tasker.Conclusion.Success); }
public bool AppliesTo(EventStream stream) { return(stream.Events.Any(x => _aggregations.ContainsKey(x.Data.GetType()))); }
public static async Task <ActivityResponse> SetLeagueEmailAddressCommandLogParametersActivity( [ActivityTrigger] DurableActivityContext context, ILogger log) { ActivityResponse ret = new ActivityResponse() { FunctionName = "SetLeagueEmailAddressCommandHandlerActivity" }; try { CommandRequest <Set_Email_Address_Definition> cmdRequest = context.GetInput <CommandRequest <Set_Email_Address_Definition> >(); if (null != cmdRequest) { if (null != log) { // Unable to get the request details from the orchestration log.LogInformation($"CreateLeagueCommandLogParametersActivity : Logging parameters for command {cmdRequest.CommandUniqueIdentifier} "); } EventStream commandEvents = new EventStream(@"Command", cmdRequest.CommandName, cmdRequest.CommandUniqueIdentifier.ToString()); if (null != commandEvents) { Set_Email_Address_Definition parameters = cmdRequest.GetParameters(); if (null != parameters) { // Set the parameters await commandEvents.AppendEvent(new TheLongRun.Common.Events.Command.ParameterValueSet(nameof(parameters.LeagueName), parameters.LeagueName)); await commandEvents.AppendEvent(new TheLongRun.Common.Events.Command.ParameterValueSet(nameof(parameters.New_Email_Address), parameters.New_Email_Address)); await commandEvents.AppendEvent(new TheLongRun.Common.Events.Command.ParameterValueSet(nameof(parameters.Notes), parameters.Notes)); await commandEvents.AppendEvent(new TheLongRun.Common.Events.Command.ParameterValueSet(nameof(parameters.InstanceIdentifier), parameters.InstanceIdentifier)); ret.Message = $"All parameters to set for {cmdRequest.CommandName} : {cmdRequest.CommandUniqueIdentifier}"; } else { ret.Message = $"No parameters to set for {cmdRequest.CommandName} : {cmdRequest.CommandUniqueIdentifier}"; } } else { ret.Message = $"Unable to get the event stream for {cmdRequest.CommandName} : {cmdRequest.CommandUniqueIdentifier}"; ret.FatalError = true; } } else { ret.FatalError = true; ret.Message = $"Unable to read command request from {context.InstanceId }"; } } catch (Exception ex) { ret.FatalError = true; ret.Message = ex.Message; } return(ret); }
private void update(T state, EventStream stream) { stream.Events.Each(x => x.Apply(state, _aggregator)); }
public AggregateRoot(EventStream stream) { Changes = new List <IEvent>(); Version = stream.Version; ReplayEvents(stream.Events); }
// Deregister an event stream public void Deregister(EventStream stream) { _streams.RemoveAll(s => s.Stream.Equals(stream)); }
/// <summary> /// One argument constructor for DataIndexer which calls the two argument /// constructor assuming no cutoff. /// </summary> /// <param name="eventStream"> An Event[] which contains the a list of all the Events /// seen in the training data. </param> public TwoPassDataIndexer(EventStream eventStream) : this(eventStream, 0) { }
public TwoPassDataIndexer(EventStream eventStream, int cutoff) : this(eventStream, cutoff, true) { }
/// <summary> /// Perform the underlying processing on the specified command /// </summary> /// <param name="commandId"> /// The unique identifier of the command to process /// </param> private static async Task HandleCreateLeagueCommand(string commandId, ILogger log = null) { const string COMMAND_NAME = @"create-league"; Guid commandGuid; // use custom assembly resolve handler using (new AzureFunctionsResolveAssembly()) { if (Guid.TryParse(commandId, out commandGuid)) { #region Logging if (null != log) { log.LogDebug($"Validating command {commandId} in HandleCreateLeagueCommand"); } #endregion // Get the current state of the command... Projection getCommandState = new Projection(@"Command", COMMAND_NAME, commandGuid.ToString(), nameof(Command_Summary_Projection)); if (null != getCommandState) { #region Logging if (null != log) { log.LogDebug($"Projection processor created in HandleCreateLeagueCommand"); } #endregion Command_Summary_Projection cmdProjection = new Command_Summary_Projection(log); await getCommandState.Process(cmdProjection); if ((cmdProjection.CurrentSequenceNumber > 0) || (cmdProjection.ProjectionValuesChanged())) { if (cmdProjection.CurrentState == Command_Summary_Projection.CommandState.Completed) { // No need to process a completed projection #region Logging if (null != log) { log.LogWarning($"Command {commandId} is complete so no need to process in HandleCreateLeagueCommand"); } #endregion return; } if (cmdProjection.CurrentState == Command_Summary_Projection.CommandState.Created) { // No need to process a completed projection #region Logging if (null != log) { log.LogWarning($"Command {commandId} is not yet validated so cannot process in HandleCreateLeagueCommand"); } #endregion return; } if (cmdProjection.CurrentState == Command_Summary_Projection.CommandState.Invalid) { // No need to process a completed projection #region Logging if (null != log) { log.LogWarning($"Command {commandId} is not yet marked as invalid so cannot process in HandleCreateLeagueCommand"); } #endregion return; } if (cmdProjection.CurrentState == Command_Summary_Projection.CommandState.Validated) { string leagueName = string.Empty; // New or previously invalid command can be validated if (cmdProjection.ParameterIsSet(nameof(Create_New_League_Definition.LeagueName))) { // League name may not be blank leagueName = cmdProjection.GetParameter <string>(nameof(Create_New_League_Definition.LeagueName)); } string location = string.Empty; if (cmdProjection.ParameterIsSet(nameof(Create_New_League_Definition.Location))) { location = cmdProjection.GetParameter <string>(nameof(Create_New_League_Definition.Location)); } DateTime dateIncorporated = DateTime.UtcNow; if (cmdProjection.ParameterIsSet(nameof(Create_New_League_Definition.Date_Incorporated))) { dateIncorporated = cmdProjection.GetParameter <DateTime>(nameof(Create_New_League_Definition.Date_Incorporated)); } // Create a new "League Created" event Leagues.League.eventDefinition.Formed formedEvent = new Leagues.League.eventDefinition.Formed(dateIncorporated, location, $"{leagueName} created by command {commandGuid} "); EventStream leagueEvents = new EventStream(@"Leagues", "League", leagueName); if ((null != leagueEvents) && (null != formedEvent)) { await leagueEvents.AppendEvent(formedEvent); } // if there is contact details, add an event for that string emailAddress = string.Empty; if (cmdProjection.ParameterIsSet(nameof(Create_New_League_Definition.Email_Address))) { emailAddress = cmdProjection.GetParameter <string>(nameof(Create_New_League_Definition.Email_Address)); } string twitterHandle = string.Empty; if (cmdProjection.ParameterIsSet(nameof(Create_New_League_Definition.Twitter_Handle))) { twitterHandle = cmdProjection.GetParameter <string>(nameof(Create_New_League_Definition.Twitter_Handle)); } if ((!string.IsNullOrWhiteSpace(emailAddress)) || (!string.IsNullOrWhiteSpace(twitterHandle))) { // Create a new "Contact details changed" event Leagues.League.eventDefinition.Contact_Details_Changed contactDetailsEvent = new Leagues.League.eventDefinition.Contact_Details_Changed(DateTime.UtcNow, twitterHandle, emailAddress); if ((null != leagueEvents) && (null != contactDetailsEvent)) { await leagueEvents.AppendEvent(contactDetailsEvent); } } } } else { // No events were read into the projection so do nothing #region Logging if (null != log) { log.LogWarning($"No command events read for {commandId} in ValidateCreateLeagueCommand"); } #endregion } } } } }
public StreamEntry(EventStream eventStream, EPStatementHandleCallback callback) { EventStream = eventStream; Callback = callback; }
public IScheduler CreateScheduler() { Func <DateTime> now = () => DateTime.Now; var eventStream = new EventStream(_eventSinks, _exceptionLogger, now); var recoverableAction = new RecoverableAction(this, eventStream); var delegatingPersistenceStore = new DelegatingPersistenceStore(_persistenceProvider); var jobMutation = new JobMutator(eventStream, delegatingPersistenceStore); var queueConfiguration = new JobQueueFactory( delegatingPersistenceStore, this, eventStream, recoverableAction, jobMutation).Create(); var router = new JobRouter(queueConfiguration); var methodBinder = new MethodBinder(); var continuationDispatcher = new ContinuationDispatcher(router, jobMutation, delegatingPersistenceStore, recoverableAction); var activityToContinuationConverter = new ActivityToContinuationConverter(now); var runningTransition = new RunningTransition(jobMutation); var failedTransition = new FailedTransition(this, jobMutation, now); var endTransition = new EndTransition(delegatingPersistenceStore, jobMutation, continuationDispatcher); var continuationLiveness = new ContinuationLiveness(delegatingPersistenceStore, continuationDispatcher); var coordinator = new JobCoordinator(eventStream, recoverableAction); var waitingForChildrenTransition = new WaitingForChildrenTransition( delegatingPersistenceStore, continuationDispatcher, activityToContinuationConverter, recoverableAction, jobMutation); var changeState = new StatusChanger(eventStream, runningTransition, failedTransition, endTransition, waitingForChildrenTransition, jobMutation); var failedJobQueue = new FailedJobQueue(this, delegatingPersistenceStore, now, eventStream, router); var errorHandlingPolicy = new ErrorHandlingPolicy(this, coordinator, changeState, failedJobQueue, recoverableAction); var exceptionFilterDispatcher = new ExceptionFilterDispatcher(eventStream); var jobDispatcher = new Dispatcher.Dispatcher(_dependencyResolver, coordinator, errorHandlingPolicy, methodBinder, eventStream, recoverableAction, changeState, continuationLiveness, exceptionFilterDispatcher); var jobPumps = queueConfiguration .ActivitySpecificQueues .Values .Select(q => new JobPump(jobDispatcher, eventStream, q)) .ToList(); jobPumps.Add(new JobPump(jobDispatcher, eventStream, queueConfiguration.Default)); return(new Scheduler( queueConfiguration, this, delegatingPersistenceStore, now, failedJobQueue, recoverableAction, router, activityToContinuationConverter, jobPumps, jobMutation)); }
protected OrderedStreamHandler(IHandleEvent <TEventType> handleOrderCreated) { _handleOrderCreated = handleOrderCreated; _stream = GetStreamInfo(); }
/// <summary> /// Configures the event stream. /// </summary> private void ConfigureEventStream() { _eventStream = new EventStream(_settings.DebugEventStream); _eventStream.StartStdoutLogger(_settings); }
internal EventStreamWrapper(IStorageDriver storage, IEnumerable <IProjection <TEvent> > projections, IProjectionCacheProvider projectionCache, ILogAdapter log = null) { _log = log; Stream = new EventStream <TEvent>(storage, log); _projection = new ReifiedProjectionGroup <TEvent, TState>(projections, projectionCache, log); }
public async Task <int> SaveAsync(EventStream eventStream) { Task <int> saveValueTask = Task.Run <int> (() => { return(Save(eventStream)); }); return(await saveValueTask); }
public LocalActorRefProvider(string systemName, Settings settings, EventStream eventStream) : this(systemName, settings, eventStream, null, null) { //Intentionally left blank }
public View Transform(EventStream stream, Event <Dto> input) { throw new NotImplementedException(); }