예제 #1
0
        public JobCoordinator(IEventStream eventStream, IRecoverableAction recoverableAction)
        {
            if (eventStream == null) throw new ArgumentNullException("eventStream");

            _eventStream = eventStream;
            _recoverableAction = recoverableAction;
        }
 /// <summary>
 /// 
 /// </summary>
 /// 
 /// <param name="name"></param>
 /// <param name="eventStream"></param>
 /// 
 public void AddEventStream(string name, IEventStream eventStream)
 {
     if (!Registry.Contains(name))
     {
         Registry.Add(name, eventStream);
     }
 }
 private void PlayActions(IEventStream eventStream)
 {
     foreach (var eventStreamAssignAction in this._eventStreamAssignActions)
     {
         eventStreamAssignAction(eventStream);
     }
 }
예제 #4
0
        public Dispatcher(IDependencyResolver dependencyResolver,
            IJobCoordinator jobCoordinator, IErrorHandlingPolicy errorHandlingPolicy,
            IMethodBinder methodBinder,
            IEventStream eventStream,
            IRecoverableAction recoverableAction,
            IStatusChanger statusChanger,
            IContinuationLiveness continuationLiveness,
            IExceptionFilterDispatcher exceptionFilterDispatcher,
            IJobRootValidator jobRootValidator)
        {
            if (jobCoordinator == null) throw new ArgumentNullException("jobCoordinator");
            if (dependencyResolver == null) throw new ArgumentNullException("dependencyResolver");
            if (errorHandlingPolicy == null) throw new ArgumentNullException("errorHandlingPolicy");
            if (methodBinder == null) throw new ArgumentNullException("methodBinder");
            if (eventStream == null) throw new ArgumentNullException("eventStream");
            if (recoverableAction == null) throw new ArgumentNullException("recoverableAction");
            if (statusChanger == null) throw new ArgumentNullException("statusChanger");
            if (continuationLiveness == null) throw new ArgumentNullException("continuationLiveness");
            if (exceptionFilterDispatcher == null) throw new ArgumentNullException("exceptionFilterDispatcher");
            if (jobRootValidator == null) throw new ArgumentNullException("jobRootValidator");

            _jobCoordinator = jobCoordinator;
            _dependencyResolver = dependencyResolver;
            _errorHandlingPolicy = errorHandlingPolicy;
            _methodBinder = methodBinder;
            _eventStream = eventStream;
            _recoverableAction = recoverableAction;
            _statusChanger = statusChanger;
            _continuationLiveness = continuationLiveness;
            _exceptionFilterDispatcher = exceptionFilterDispatcher;
            _jobRootValidator = jobRootValidator;
        }
예제 #5
0
        public JobQueue(IEnumerable<Job> items, 
            int suspendedCount,
            ActivityConfiguration configuration,    
            IEnumerable<ActivityConfiguration> allActivityConfiguration,
            IPersistenceStore persistenceStore,
            IEventStream eventStream,
            IRecoverableAction recoverableAction,
            IJobMutator jobMutator)
        {
            if (items == null) throw new ArgumentNullException("items");
            if (configuration == null) throw new ArgumentNullException("configuration");
            if (allActivityConfiguration == null) throw new ArgumentNullException("allActivityConfiguration");
            if (persistenceStore == null) throw new ArgumentNullException("persistenceStore");
            if (eventStream == null) throw new ArgumentNullException("eventStream");
            if (recoverableAction == null) throw new ArgumentNullException("recoverableAction");
            if (jobMutator == null) throw new ArgumentNullException("JobMutator");

            Configuration = configuration;

            _suspendedCount = suspendedCount;
            _allActivityConfiguration = allActivityConfiguration;
            _persistenceStore = persistenceStore;
            _eventStream = eventStream;
            _recoverableAction = recoverableAction;
            _jobMutator = jobMutator;
            _items = new Queue<Job>(items);
        }
예제 #6
0
 public void Connect(IEventStream stream)
 {
     subscription = stream.Of<IEventPattern<IDevice, ISensed>>().Subscribe(sensed =>
     {
         var type = topicRegistry.Find(sensed.EventArgs.Topic);
         switch (type)
         {
             case TopicType.Boolean:
                 stream.Push(sensed.Sender, Impulse.Create(sensed.EventArgs.Topic, Payload.ToBoolean(sensed.EventArgs.Payload), clock.Now));
                 break;
             case TopicType.Number:
                 stream.Push(sensed.Sender, Impulse.Create(sensed.EventArgs.Topic, Payload.ToNumber(sensed.EventArgs.Payload), clock.Now));
                 break;
             case TopicType.String:
                 stream.Push(sensed.Sender, Impulse.Create(sensed.EventArgs.Topic, Payload.ToString(sensed.EventArgs.Payload), clock.Now));
                 break;
             case TopicType.Void:
                 stream.Push(sensed.Sender, Impulse.Create(sensed.EventArgs.Topic, Unit.Default, clock.Now));
                 break;
             case TopicType.Unknown:
             default:
                 // TODO: throw? Report?
                 break;
         }
     });
 }
 public NEventStoreSessionStream(ConcurrentDictionary<Guid, IEventStream> eventStreamsInSession, IEventStream eventStream)
 {
     this.eventStreamsInSession = eventStreamsInSession;
     this.eventStream = eventStream;
     this.sessionStreamId = Guid.NewGuid();
     this.eventStreamsInSession.Add(this.sessionStreamId, this);
 }
		public TelemetryEventSubscriber (IEventStream events, ITelemetryProvider telemetry)
		{
			this.events = events;
			this.telemetry = telemetry;

			SubscribeTelemetryEvents ();
		}
예제 #9
0
 public Task openStreamAndWrite(IOwinContext ctx)
 {
     this.context = ctx;
     this.stream = ctx.Environment[environmentKey] as IEventStream;
     var task =  this.stream.Open(onClose);
     this.stream.WriteAsync(this.responseBody + "\n");
     return task;
 }
예제 #10
0
        public NEventStore(IStoreSettings<IStoreEvents> settings, IServiceBus serviceBus)
        {
            _settings = settings;
            _serviceBus = serviceBus;

            _store = _settings.GetConnection();
            _eventStream = _store.OpenStream("main");
        }
        public virtual void BuildFromHistory(IEventStream eventStream)
        {
            if (_uncommittedEvents.Count > 0) throw new InvalidOperationException("Cannot apply history when instance has uncommitted changes.");

            foreach (var evnt in eventStream.Events)
                HandleEvent(evnt);

            Revision = eventStream.Revision;
        }
예제 #12
0
        public RecoverableAction(IDependableConfiguration configuration, IEventStream eventStream)
        {
            if (configuration == null) throw new ArgumentNullException("configuration");
            if (eventStream == null) throw new ArgumentNullException("eventStream");

            _configuration = configuration;
            _eventStream = eventStream;
            _timer = new Timer(OnTick);
        }
예제 #13
0
 public void Connect(IEventStream stream)
 {
     subscription = new CompositeDisposable(
         stream.Of<IEventPattern<IDevice, IImpulse<bool>>>()
               .Subscribe(i => state.Set(i.EventArgs.Topic, i.Sender.Id, i.EventArgs.Payload)),
         stream.Of<IEventPattern<IDevice, IImpulse<float>>>()
               .Subscribe(i => state.Set(i.EventArgs.Topic, i.Sender.Id, i.EventArgs.Payload)),
         stream.Of<IEventPattern<IDevice, IImpulse<string>>>()
               .Subscribe(i => state.Set(i.EventArgs.Topic, i.Sender.Id, i.EventArgs.Payload)));
 }
예제 #14
0
 public void Connect(IEventStream stream)
 {
     subscription = new CompositeDisposable(
         stream.Of<ICommand<bool>>().Subscribe(cmd =>
             stream.Push(Command.Create(cmd.Topic, Payload.ToBytes(cmd.Payload), cmd.Timestamp, cmd.TargetDeviceIds))),
         stream.Of<ICommand<float>>().Subscribe(cmd =>
             stream.Push(Command.Create(cmd.Topic, Payload.ToBytes(cmd.Payload), cmd.Timestamp, cmd.TargetDeviceIds))),
         stream.Of<ICommand<string>>().Subscribe(cmd =>
             stream.Push(Command.Create(cmd.Topic, Payload.ToBytes(cmd.Payload), cmd.Timestamp, cmd.TargetDeviceIds))),
         stream.Of<ICommand<Unit>>().Subscribe(cmd =>
             stream.Push(Command.Create(cmd.Topic, new byte[0], cmd.Timestamp, cmd.TargetDeviceIds))));
 }
예제 #15
0
        public JobPump(
            IDispatcher dispatcher,
            IEventStream eventStream,
            IJobQueue queue)
        {
            if(dispatcher == null) throw new ArgumentNullException("dispatcher");
            if(eventStream == null) throw new ArgumentNullException("eventStream");
            if (queue == null) throw new ArgumentNullException("queue");

            _dispatcher = dispatcher;
            _eventStream = eventStream;
            _queue = queue;
            _throttle = queue.Configuration.MaxWorkers == 0 ? int.MaxValue : queue.Configuration.MaxWorkers;            
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="OnePassDataIndexer"/> class.
 /// </summary>
 /// <param name="eventStream">The event stream which contains all the events seen in the training data.</param>
 /// <param name="cutoff">The minimum number of times a predicate must have been observed 
 /// in order to be included in the model.</param>
 /// <param name="sort">if set to <c>true</c> sort the predicates.</param>
 public OnePassDataIndexer(IEventStream eventStream, int cutoff, bool sort)
 {
     Dictionary<string, int> predicateIndex = new Dictionary<string, int>();
     Console.WriteLine("Indexing events using cutoff of {0}", cutoff);
     Console.Write("Computing event counts...");
     LinkedList<Event> events = ComputeEventCounts(eventStream, predicateIndex, cutoff);
     Console.WriteLine("done. {0} events.", events.Count);
     Console.Write("Indexing...");
     List<ComparableEvent> eventsToCompare = Index(events, predicateIndex);
     Console.WriteLine("done.");
     Console.Write("Sorting and merging events...");
     SortAndMerge(eventsToCompare, sort);
     Console.WriteLine("Done indexing");
 }
예제 #17
0
        public void Connect(IEventStream stream)
        {
            subscription = clock.Tick.Subscribe(tick =>
            {
                stream.Push(Impulse.Create(Topics.System.Date, tick, clock.Now));
                stream.Push(Impulse.Create(Topics.System.Day, tick.Day, clock.Now));
                stream.Push(Impulse.Create(Topics.System.Month, tick.Month, clock.Now));
                stream.Push(Impulse.Create(Topics.System.Year, tick.Year, clock.Now));

                stream.Push(Impulse.Create(Topics.System.Time, new TimeSpan(tick.Hour, tick.Minute, tick.Second), clock.Now));
                stream.Push(Impulse.Create(Topics.System.Hour, tick.Hour, clock.Now));
                stream.Push(Impulse.Create(Topics.System.Minute, tick.Minute, clock.Now));
                stream.Push(Impulse.Create(Topics.System.Second, tick.Second, clock.Now));
            });
        }
예제 #18
0
        public JobQueueFactory(
            IPersistenceStore persistenceStore, 
            IDependableConfiguration configuration,
            IEventStream eventStream,
            IRecoverableAction recoverableAction,
            IJobMutator jobMutator)
        {
            if (persistenceStore == null) throw new ArgumentNullException("persistenceStore");
            if (configuration == null) throw new ArgumentNullException("configuration");
            if (eventStream == null) throw new ArgumentNullException("eventStream");
            if (recoverableAction == null) throw new ArgumentNullException("recoverableAction");
            if (jobMutator == null) throw new ArgumentNullException("jobMutator");

            _persistenceStore = persistenceStore;
            _configuration = configuration;
            _eventStream = eventStream;
            _recoverableAction = recoverableAction;
            _jobMutator = jobMutator;
        }
예제 #19
0
        public StatusChanger(IEventStream eventStream,
            IRunningTransition runningTransition,
            IFailedTransition failedTransition,
            IEndTransition endTransition,
            IWaitingForChildrenTransition waitingForChildrenTransition,
            IJobMutator jobMutator)
        {
            if (eventStream == null) throw new ArgumentNullException("eventStream");
            if (runningTransition == null) throw new ArgumentNullException("runningTransition");
            if (failedTransition == null) throw new ArgumentNullException("failedTransition");
            if (endTransition == null) throw new ArgumentNullException("endTransition");
            if (waitingForChildrenTransition == null) throw new ArgumentNullException("waitingForChildrenTransition");
            if (jobMutator == null) throw new ArgumentNullException("jobMutator");

            _runningTransition = runningTransition;
            _failedTransition = failedTransition;
            _endTransition = endTransition;
            _waitingForChildrenTransition = waitingForChildrenTransition;
            _jobMutator = jobMutator;
        }
예제 #20
0
        public FailedJobQueue(
            IDependableConfiguration configuration,
            IPersistenceStore persistenceStore,
            Func<DateTime> now,
            IEventStream eventStream,
            IJobRouter router)
        {
            if (configuration == null) throw new ArgumentNullException("configuration");
            if (persistenceStore == null) throw new ArgumentNullException("persistenceStore");
            if (now == null) throw new ArgumentNullException("now");
            if(eventStream == null) throw new ArgumentNullException("eventStream");
            if(router == null) throw new ArgumentNullException("router");

            _configuration = configuration;
            _persistenceStore = persistenceStore;
            _now = now;
            _eventStream = eventStream;
            _router = router;

            _timer = new Timer(OnTick);
        }
예제 #21
0
파일: StatusBar.cs 프로젝트: kzu/guit
        public StatusBar(IEventStream eventStream, Repository repository)
        {
            this.repository = repository;

            CanFocus    = false;
            Height      = 1;
            ColorScheme = new ColorScheme
            {
                Normal = Terminal.Gui.Attribute.Make(Color.White, Color.Black)
            };

            status = new Label("Ready")
            {
                // Initially, we can only use the Frame of the top view, since Width is null at this point.
                // See LayoutSubviews below
                Width = Application.Top.Frame.Width - ClockText.Length
            };
            clock = new Label(ClockText)
            {
                Width = ClockText.Length,
                X     = Pos.Right(status)
            };

            // To see the width of the clock itself, uncomment the following line
            //clock.ColorScheme = Colors.Error;

            Add(status, clock);

            Application.MainLoop.AddTimeout(TimeSpan.FromSeconds(1), _ =>
            {
                clock.Text = ClockText;
                return(true);
            });

            // Pushing simple strings to the event stream will cause them to update the
            // status message.
            eventStream.Of <Status>().Subscribe(OnStatus);
        }
예제 #22
0
        public JobPump(
            IDispatcher dispatcher,
            IEventStream eventStream,
            IJobQueue queue)
        {
            if (dispatcher == null)
            {
                throw new ArgumentNullException("dispatcher");
            }
            if (eventStream == null)
            {
                throw new ArgumentNullException("eventStream");
            }
            if (queue == null)
            {
                throw new ArgumentNullException("queue");
            }

            _dispatcher  = dispatcher;
            _eventStream = eventStream;
            _queue       = queue;
            _throttle    = queue.Configuration.MaxWorkers == 0 ? int.MaxValue : queue.Configuration.MaxWorkers;
        }
예제 #23
0
 public bool IsEventExecuted <T>(Guid streamId, int streamVersion, Guid eventId) where T : EventBase
 {
     using (IEventStream eventStream = _store.OpenStream(streamId, streamVersion))
     {
         var events = eventStream.CommittedEvents.Where(e =>
         {
             if (e.Body != null)
             {
                 return(e.Body.GetType() == typeof(T));
             }
             return(false);
         }).Select(e => e.Body as T)
                      .OrderBy(e => e.ExecuteAt)
                      .GroupBy(e => e.Id)
                      .Select(e => e.Last()).ToList();
         var @event = @events.FirstOrDefault(e => e.Id == eventId);
         if (@event == null)
         {
             return(true);
         }
         return(@event.ExecuteAt.CompareTo(DateTime.UtcNow) < 0);
     }
 }
        public override async Task <IExecutionResult> ExecuteAsync(
            IExecutionContext executionContext,
            CancellationToken cancellationToken)
        {
            if (executionContext == null)
            {
                throw new ArgumentNullException(nameof(executionContext));
            }

            EventDescription @event = CreateEvent(executionContext);

            IEventStream eventStream = await SubscribeAsync(
                executionContext.Services, @event);

            return(new SubscriptionResult(
                       eventStream,
                       message => executionContext.Clone(
                           new Dictionary <string, object> {
                { typeof(IEventMessage).FullName, message }
            },
                           cancellationToken),
                       ExecuteSubscriptionQueryAsync));
        }
        public static ICommandProcessor GetForCommand <T>(IEventStream stream, T command) where T : ICommand
        {
            var name = command.GetType().Name;

            if (name == nameof(AnimalArrivedCommand))
            {
                return(new AnimalArrivedCommandProcessor(stream, CommandValidatorFactory.Get <AnimalArrivedCommand>()));
            }
            if (name == nameof(AnimalIntoMobCommand))
            {
                return(new AnimalIntoMobCommandProcessor(stream, CommandValidatorFactory.Get <AnimalIntoMobCommand>()));
            }
            if (name == nameof(MobCreatedCommand))
            {
                return(new MobCreatedCommandProcessor(stream, CommandValidatorFactory.Get <MobCreatedCommand>()));
            }
            if (name == nameof(AnimalUpdatedCommand))
            {
                return(new AnimalUpdatedCommandProcessor(stream, CommandValidatorFactory.Get <AnimalUpdatedCommand>()));
            }

            return(null);
        }
예제 #26
0
        private void SubscribeStream(string symbol)
        {
            //if there is already subscribed stream - unsubscribe it and subscribe for new symbol
            _currentTicksStream?.Close();

            _glue.Interop.Subscribe(_ticksEndpoint,
                                    new ClientEventStreamHandler
            {
                // this lambda is invoked when the status of the stream has changed
                EventStreamStatusChanged = (info, status, cookie) => LogMessage($"{info.EventStreamingMethod.Name} to {info.Server} is {status}"),

                // this lambda is invoked when there is data published to the stream
                EventHandler = (info, data, cookie) =>
                               DispatchAction(() =>
                {
                    var isOOB = data.IsCallbackStream;
                    // if isOOB is true the data has been pushed only to this subscriber

                    var subscriptionItem = $"{data.ResultContext.AsString()}";
                    ListViewSubscriptions.Items.Add(subscriptionItem);
                    ListViewSubscriptions.ScrollIntoView(subscriptionItem);
                })
            },
                                    // these are the arguments sent in the subscription request
                                    mib => mib.SetContext(cb => cb.AddValue("reject", false).AddValue("symbol", symbol)),
                                    // additional settings - specify target await timeout
                                    new TargetSettings().WithTargetAwaitTimeout(TimeSpan.FromSeconds(5)),
                                    // stream settings, specifying that we accept 'personal' (out-of-band) stream pushes
                                    new ClientEventStreamSettings {
                AllowCallbacks = true, ReestablishStream = false
            }
                                    )
            .ContinueWith(eventStream =>
            {
                _currentTicksStream = eventStream.Status == TaskStatus.RanToCompletion ? eventStream.Result : null;
            });
        }
예제 #27
0
        public FailedJobQueue(
            IDependableConfiguration configuration,
            IPersistenceStore persistenceStore,
            Func <DateTime> now,
            IEventStream eventStream,
            IJobRouter router)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }
            if (persistenceStore == null)
            {
                throw new ArgumentNullException("persistenceStore");
            }
            if (now == null)
            {
                throw new ArgumentNullException("now");
            }
            if (eventStream == null)
            {
                throw new ArgumentNullException("eventStream");
            }
            if (router == null)
            {
                throw new ArgumentNullException("router");
            }

            _configuration    = configuration;
            _persistenceStore = persistenceStore;
            _now         = now;
            _eventStream = eventStream;
            _router      = router;

            _timer = new Timer(OnTick);
        }
        private async Task <IExecutionResult> ExecuteInternalAsync(
            IExecutionContext executionContext,
            CancellationToken cancellationToken)
        {
            EventDescription eventDescription = CreateEvent(executionContext);

            IEventStream eventStream = await SubscribeAsync(
                executionContext.Services,
                eventDescription)
                                       .ConfigureAwait(false);

            return(new SubscriptionResult(
                       eventStream,
                       msg =>
            {
                IExecutionContext cloned = executionContext.Clone();

                cloned.ContextData[typeof(IEventMessage).FullName] = msg;

                return cloned;
            },
                       ExecuteSubscriptionQueryAsync,
                       executionContext.ServiceScope));
        }
예제 #29
0
        public Task SubscribeOneConsumer_SendMessage_ConsumerReceivesMessage()
        {
            return(TestHelper.TryTest(async() =>
            {
                // arrange
                var cts = new CancellationTokenSource(30000);
                var eventDescription = new EventDescription(
                    Guid.NewGuid().ToString());

                // act
                IEventStream consumer = await _registry.SubscribeAsync(eventDescription);
                var outgoing = new EventMessage(eventDescription, "bar");
                await _sender.SendAsync(outgoing);

                // assert
                IEventMessage incoming = null;
                await foreach (IEventMessage item in consumer.WithCancellation(cts.Token))
                {
                    incoming = item;
                    break;
                }
                Assert.Equal(outgoing.Payload, incoming.Payload);
            }));
        }
        public async Task When_handler_throws_Then_invoke_exception_callback()
        {
            using (IStoreEvents eventStore = Wireup.Init().UsingInMemoryPersistence().Build())
            {
                var projectedEvents = new List <DomainEventMessage <TestEvent> >();
                var handlerModule   = new TestHandlerModule(projectedEvents);

                using (var host = new DurableCommitDispatcher(
                           new EventStoreClient(eventStore.Advanced),
                           new InMemoryCheckpointRepository(),
                           handlerModule.DispatchCommit))
                {
                    await host.Start();

                    Guid           streamId        = Guid.NewGuid();
                    Guid           commitId        = Guid.NewGuid();
                    Task <ICommit> commitProjected = host
                                                     .ProjectedCommits
                                                     .Take(1)
                                                     .ToTask();

                    using (IEventStream stream = eventStore.CreateStream(streamId))
                    {
                        stream.Add(new EventMessage {
                            Body = new TestEventThatThrows()
                        });
                        stream.CommitChanges(commitId);
                    }
                    host.PollNow();

                    Func <Task> act = async() => await commitProjected;

                    act.ShouldThrow <Exception>();
                }
            }
        }
예제 #31
0
        /// <summary>
        /// Reads the events from <paramref name="eventStream"/> into a <see cref="Collections.Generic.LinkedList"/>.
        /// The predicates associated with each event are counted and any which occur at least <paramref name="cutoff"/>
        /// times are added to the <paramref name="predicateIndex"/> dictionary along
        /// with an unique integer index.
        /// </summary>
        /// <param name="eventStream">The event stream.</param>
        /// <param name="predicateIndex">Index of the predicate.</param>
        /// <param name="cutoff">The cutoff.</param>
        /// <returns>A <see cref="Collections.Generic.LinkedList"/> of events.</returns>
        private LinkedList <Event> ComputeEventCounts(IEventStream eventStream, Dictionary <string, int> predicateIndex, int cutoff)
        {
            LinkedList <Event>        events        = new LinkedList <Event>();
            HashSet <string>          predicatesSet = new HashSet <string>();
            IDictionary <string, int> counter       = new Dictionary <string, int>();

            while (eventStream.HasNext())
            {
                Event next = eventStream.Next();
                events.AddLast(next);
                Update(next.Context, predicatesSet, counter, cutoff);
            }
            PredicateCounts = new int[predicatesSet.Count];
            int index = 0;

            HashSet <string> .Enumerator enumerator = predicatesSet.GetEnumerator();
            while (enumerator.MoveNext())
            {
                string predicate = enumerator.Current;
                PredicateCounts[index]    = counter[predicate];
                predicateIndex[predicate] = index;
            }
            return(events);
        }
예제 #32
0
        public void Save(string bucketId, IAggregate aggregate, Guid commitId, Action <IDictionary <string, object> > updateHeaders)
        {
            Dictionary <string, object> headers = PrepareHeaders(aggregate, updateHeaders);

            while (true)
            {
                IEventStream stream           = PrepareStream(bucketId, aggregate, headers);
                int          commitEventCount = stream.CommittedEvents.Count;

                try
                {
                    stream.CommitChanges(commitId);
                    aggregate.ClearUncommittedEvents();
                    return;
                }
                catch (DuplicateCommitException)
                {
                    stream.ClearChanges();
                    return;
                }
                catch (ConcurrencyException e)
                {
                    var conflict = ThrowOnConflict(stream, commitEventCount);
                    stream.ClearChanges();

                    if (conflict)
                    {
                        throw new ConflictingCommandException(e.Message, e);
                    }
                }
                catch (StorageException e)
                {
                    throw new PersistenceException(e.Message, e);
                }
            }
        }
예제 #33
0
        public static void Main(string[] args)
        {
            IApplicationContext springContainer = ContextRegistry.GetContext();

            IStandardStreamingEventBus streamingEventBus = springContainer.GetObject(
                typeof(IStandardStreamingEventBus).FullName)
                                                           as IStandardStreamingEventBus;

            IList <ModernMajorGeneralMessage> streamMessages = new List <ModernMajorGeneralMessage>();

            streamMessages.Add(new ModernMajorGeneralMessage("I am "));
            streamMessages.Add(new ModernMajorGeneralMessage("the very "));
            streamMessages.Add(new ModernMajorGeneralMessage("model of "));
            streamMessages.Add(new ModernMajorGeneralMessage("a Modern "));
            streamMessages.Add(new ModernMajorGeneralMessage("Major-General "));
            streamMessages.Add(new ModernMajorGeneralMessage("I've information "));
            streamMessages.Add(new ModernMajorGeneralMessage("vegetable, animal, "));
            streamMessages.Add(new ModernMajorGeneralMessage("and mineral, "));
            streamMessages.Add(new ModernMajorGeneralMessage("I know the kings of England, "));
            streamMessages.Add(new ModernMajorGeneralMessage("and I quote the fights historical, "));
            streamMessages.Add(new ModernMajorGeneralMessage("From Marathon to Waterloo, "));
            streamMessages.Add(new ModernMajorGeneralMessage("in order categorical; "));


            using (IEventStream stream = streamingEventBus.CreateStream(typeof(ModernMajorGeneralMessage).FullName))
            {
                stream.BatchLimit = 2;

                foreach (ModernMajorGeneralMessage message in streamMessages)
                {
                    stream.Publish(message);
                }
            }

            Environment.Exit(0);
        }
예제 #34
0
 protected override void Because()
 {
     _stream = Store.CreateStream(streamId);
 }
 protected override void Because()
 {
     _stream = Store.CreateStream(streamId);
 }
 /// <summary>
 /// Reads the events from <paramref name="eventStream"/> into a <see cref="Collections.Generic.LinkedList"/>.
 /// The predicates associated with each event are counted and any which occur at least <paramref name="cutoff"/>
 /// times are added to the <paramref name="predicateIndex"/> dictionary along
 /// with an unique integer index.
 /// </summary>
 /// <param name="eventStream">The event stream.</param>
 /// <param name="predicateIndex">Index of the predicate.</param>
 /// <param name="cutoff">The cutoff.</param>
 /// <returns>A <see cref="Collections.Generic.LinkedList"/> of events.</returns>
 private LinkedList<Event> ComputeEventCounts(IEventStream eventStream, Dictionary<string, int> predicateIndex, int cutoff)
 {
     LinkedList<Event> events = new LinkedList<Event>();
     HashSet<string> predicatesSet = new HashSet<string>();
     IDictionary<string, int> counter = new Dictionary<string, int>();
     while (eventStream.HasNext())
     {
         Event next = eventStream.Next();
         events.AddLast(next);
         Update(next.Context, predicatesSet, counter, cutoff);
     }
     PredicateCounts = new int[predicatesSet.Count];
     int index = 0;
     HashSet<string>.Enumerator enumerator = predicatesSet.GetEnumerator();
     while (enumerator.MoveNext())
     {
         string predicate = enumerator.Current;
         PredicateCounts[index] = counter[predicate];
         predicateIndex[predicate] = index;
     }
     return events;
 }
예제 #37
0
        public async Task <long> GetSize <T>(IEventStream stream, string oob) where T : class, IEventSource
        {
            var streamName = _streamGen(typeof(T), StreamTypes.OOB, stream.Bucket, stream.StreamId, stream.Parents);

            return((await Enumerable.Range(1, 10).ToArray().StartEachAsync(5, (vary) => _store.Size($"{streamName}-{oob}.{vary}")).ConfigureAwait(false)).Sum());
        }
예제 #38
0
 public SendMailHandler(IEventStream eventStream)
 {
     this.subscription = eventStream.Of <IEvent <Product, ProductPublishedEvent> >().Subscribe(this.OnProductPublished);
 }
예제 #39
0
 public Place(IEventStream events) : base(events)
 {
 }
예제 #40
0
 public MobCreatedCommandProcessor(IEventStream eventStream,
                                   ICommandValidator <MobCreatedCommand> validator) : base(eventStream, validator)
 {
 }
예제 #41
0
        //protected AggregateRoot(EntityState<TEntity> entityState)
        //{
        //    _entityState = entityState;

        //}
        protected AggregateRoot(IApplicable <TEntity> entity, IEventStream eventStream)
        {
            _entity      = entity;
            _eventStream = eventStream;
        }
예제 #42
0
 protected override async Task Because()
 {
     _stream = await Store.OpenStream(streamId, 0, 0);
 }
예제 #43
0
        /// <summary>
        /// The commit aggregate.
        /// </summary>
        /// <param name="aggregate">
        /// The aggregate.
        /// </param>
        /// <param name="commitId">
        /// The commit id.
        /// </param>
        /// <exception cref="InvalidOperationException">
        /// </exception>
        /// <exception cref="ConcurrencyException">
        /// </exception>
        private void CommitAggregate(Aggregate aggregate, Guid commitId)
        {
            // Aggregate identifier has bucket id concatenated with stream id
            var parts = aggregate.Identifier.Split('#');

            if (parts.Length > 2)
            {
                throw new InvalidOperationException();
            }

            IEventStream stream = null;

            try
            {
                // Open or create the stream for this aggregate
                if (parts.Length == 2)
                {
                    stream = _storeEvents.OpenStream(parts[0], parts[1], 0, int.MaxValue);
                }
                else
                {
                    stream = _storeEvents.OpenStream(parts[0], 0);
                }

                // Concurrency check
                if (stream.StreamRevision != aggregate.ExpectedVersion)
                {
                    throw new ConcurrencyException();
                }

                // Write each event to the underlying stream
                foreach (var eventObject in aggregate.Root.GetChanges())
                {
                    // Create new message
                    var message = new EventMessage {
                        Body = eventObject
                    };

                    /*// If the aggregate is derived from ITenantAggregate
                     * //   then store TenantId in the message headers
                     * //   as this will be used later to determine the servicebus
                     * //   partition to use for enterprise-level routing
                     * var tenantAggregate = aggregate.Root as ITenantAggregate;
                     * if (tenantAggregate != null)
                     * {
                     *  message.Headers.Add("TenantId", tenantAggregate.TenantId);
                     * }*/

                    // Add message to the event store
                    stream.Add(message);
                }

                // Commit the stream
                stream.CommitChanges(commitId);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Dispose();
                    stream = null;
                }
            }
        }
예제 #44
0
 private static CommittedEventStream GetCommittedEventStream(Guid eventSourceId, IEventStream stream)
 {
     var committedEvents = stream.CommittedEvents
         .Select(x => x.Body)
         .Cast<StoredEvent>()
         .Select(x => x.Convert(eventSourceId));
     return new CommittedEventStream(eventSourceId, committedEvents);
 }
예제 #45
0
 protected override void Because()
 {
     _stream = Store.OpenStream(streamId, 0, 0);
 }
예제 #46
0
 protected override void Because()
 {
     _stream = Store.OpenStream(_snapshot, int.MaxValue);
 }
 protected override void Because()
 {
     _stream = Store.OpenStream(_snapshot, int.MaxValue);
 }
예제 #48
0
 public SwitchCommand(MainThread mainThread, IRepository repository, IEventStream eventStream)
 {
     this.mainThread  = mainThread;
     this.repository  = repository;
     this.eventStream = eventStream;
 }
 protected override void Because()
 {
     _stream = Store.OpenStream(streamId, 0, 0);
 }
예제 #50
0
 protected override async Task Because()
 {
     _stream = await Store.OpenStream(_snapshot, int.MaxValue);
 }
예제 #51
0
 public void Connect(IEventStream stream)
 {
     subscription = stream.Of<IDevice, IssuedCommand>().Subscribe(e => store.Save(e.Sender, e.EventArgs));
 }
 internal abstract MatchResult SubBeginProcessMatch(Tracker tracker, IEventStream eventenum, CaptureList capturedList);
예제 #53
0
 public Monitor(IEventStream stream)
 {
     _stream = stream;
     _frequency = 2000;
 }
예제 #54
0
 public EventBus(IEventStream eventStream) => _eventStream = eventStream;
예제 #55
0
        private static CommittedEventStream GetCommittedEventStream(Guid eventSourceId, IEventStream stream)
        {
            var committedEvents = stream.CommittedEvents
                                  .Select(x => x.Body)
                                  .Cast <StoredEvent>()
                                  .Select(x => x.Convert(eventSourceId));

            return(new CommittedEventStream(eventSourceId, committedEvents));
        }
예제 #56
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CreatePostCommand"/> class.
 /// </summary>
 /// <param name="stream">
 /// The stream.
 /// </param>
 /// <param name="service">
 /// The service.
 /// </param>
 /// <param name="validators">
 /// The validators.
 /// </param>
 public CreatePostCommand(IEventStream stream, IPostService service, IProvidePostValidators validators)
 {
     this.stream = stream;
     this.service = service;
     this.validators = validators;
 }
예제 #57
0
	public SendMailHandler(IEventStream eventStream)
	{
		this.subscription = eventStream.Of<IEvent<Product, ProductPublishedEvent>>().Subscribe(this.OnProductPublished);
	}
 protected override void Because()
 {
     _stream = Store.OpenStream(streamId, MinRevision, MaxRevision);
 }
예제 #59
0
        public async Task WriteStream <T>(Guid commitId, IEventStream stream, IDictionary <string, string> commitHeaders) where T : class, IEventSource
        {
            var streamName = _streamGen(typeof(T), StreamTypes.Domain, stream.Bucket, stream.StreamId, stream.Parents);

            Logger.Write(LogLevel.Debug,
                         () =>
                         $"Writing {stream.Uncommitted.Count()} events to stream {stream.StreamId} bucket {stream.Bucket} with commit id {commitId}");

            if (await CheckFrozen <T>(stream.Bucket, stream.StreamId, stream.Parents).ConfigureAwait(false))
            {
                throw new FrozenException();
            }

            Saved.Mark();

            var events = stream.Uncommitted.Select(writable =>
            {
                IMutating mutated = new Mutating(writable.Event, writable.Descriptor.Headers);
                foreach (var mutate in _mutators)
                {
                    Logger.Write(LogLevel.Debug,
                                 () => $"Mutating outgoing event {writable.Event.GetType()} with mutator {mutate.GetType().FullName}");
                    mutated = mutate.MutateOutgoing(mutated);
                }

                // Todo: have some bool that is set true if they modified headers
                if (_mutators.Any())
                {
                    foreach (var header in mutated.Headers)
                    {
                        writable.Descriptor.Headers[header.Key] = header.Value;
                    }
                }
                return((IFullEvent) new WritableEvent
                {
                    Descriptor = writable.Descriptor,
                    Event = mutated.Message,
                    EventId = UnitOfWork.NextEventId(commitId)
                });
            }).ToList();

            var oobs = stream.Oobs.ToDictionary(x => x.Id, x => x);

            foreach (var oob in stream.PendingOobs)
            {
                oobs[oob.Id] = oob;
            }

            var domainEvents = events.Where(x => x.Descriptor.StreamType == StreamTypes.Domain);
            var oobEvents    = events.Where(x => x.Descriptor.StreamType == StreamTypes.OOB);

            if (domainEvents.Any())
            {
                _cache.Evict(streamName);

                Logger.Write(LogLevel.Debug,
                             () => $"Event stream [{stream.StreamId}] in bucket [{stream.Bucket}] committing {domainEvents.Count()} events");
                await _store.WriteEvents(streamName, domainEvents, commitHeaders, expectedVersion : stream.CommitVersion)
                .ConfigureAwait(false);
            }
            if (stream.PendingOobs.Any())
            {
                await _store.WriteMetadata(streamName, custom : new Dictionary <string, string>
                {
                    [OobMetadataKey] = JsonConvert.SerializeObject(oobs.Values)
                }).ConfigureAwait(false);
            }

            if (stream.PendingSnapshot != null)
            {
                Logger.Write(LogLevel.Debug,
                             () => $"Event stream [{stream.StreamId}] in bucket [{stream.Bucket}] committing snapshot");
                await _snapstore.WriteSnapshots <T>(stream.Bucket, stream.StreamId, stream.Parents, stream.StreamVersion, stream.PendingSnapshot, commitHeaders).ConfigureAwait(false);
            }
            if (oobEvents.Any())
            {
                Logger.Write(LogLevel.Debug,
                             () => $"Event stream [{stream.StreamId}] in bucket [{stream.Bucket}] publishing {oobEvents.Count()} out of band events");

                foreach (var group in oobEvents.GroupBy(x => x.Descriptor.Headers[Defaults.OobHeaderKey]))
                {
                    // OOB events of the same stream name don't need to all be written to the same stream
                    // if we parallelize the events into 10 known streams we can take advantage of internal
                    // ES optimizations and ES sharding
                    var vary      = _random.Next(10) + 1;
                    var oobstream = $"{streamName}-{group.Key}.{vary}";


                    var definition = oobs[group.Key];
                    if (definition.Transient ?? false)
                    {
                        await _publisher.Publish <T>(oobstream, group, commitHeaders).ConfigureAwait(false);
                    }
                    else if (definition.DaysToLive.HasValue)
                    {
                        var version = await _store.WriteEvents(oobstream, group, commitHeaders).ConfigureAwait(false);

                        // if new stream, write metadata
                        if (version == (group.Count() - 1))
                        {
                            await _store.WriteMetadata(oobstream, maxAge : TimeSpan.FromDays(definition.DaysToLive.Value)).ConfigureAwait(false);
                        }
                    }
                    else
                    {
                        await _store.WriteEvents(oobstream, group, commitHeaders).ConfigureAwait(false);
                    }
                }
            }
        }
예제 #60
0
 protected override void Because()
 {
     _stream = Store.OpenStream(streamId, MinRevision, MaxRevision);
 }