Exemplo n.º 1
0
 /// <summary>
 /// Initializes a new instance of <see cref="EventHandler"/>.
 /// </summary>
 /// <param name="streamProcessors">The <see cref="IStreamProcessors" />.</param>
 /// <param name="filterValidationForAllTenants">The <see cref="IValidateFilterForAllTenants" /> for validating the filter definition.</param>
 /// <param name="streamDefinitions">The<see cref="IStreamDefinitions" />.</param>
 /// <param name="arguments">Connecting arguments.</param>
 /// <param name="filterProcessorForTenant"></param>
 /// <param name="eventProcessorForTenant">The event processor.</param>
 /// <param name="acceptRegistration">Accepts the event handler registration.</param>
 /// <param name="rejectRegistration">Rejects the event handler registration.</param>
 /// <param name="logger">Logger for logging.</param>
 /// <param name="executionContext">The execution context for the event handler.</param>
 /// <param name="cancellationToken">Cancellation token that can cancel the hierarchy.</param>
 public EventHandler(
     IStreamProcessors streamProcessors,
     IValidateFilterForAllTenants filterValidationForAllTenants,
     IStreamDefinitions streamDefinitions,
     EventHandlerRegistrationArguments arguments,
     Func <TenantId, IFilterProcessor <TypeFilterWithEventSourcePartitionDefinition> > filterProcessorForTenant,
     Func <TenantId, IEventProcessor> eventProcessorForTenant,
     Func <CancellationToken, Task> acceptRegistration,
     Func <Failure, CancellationToken, Task> rejectRegistration,
     ILogger logger,
     ExecutionContext executionContext,
     CancellationToken cancellationToken)
 {
     _logger                   = logger;
     _streamProcessors         = streamProcessors;
     _filterValidator          = filterValidationForAllTenants;
     _streamDefinitions        = streamDefinitions;
     _arguments                = arguments;
     _filterProcessorForTenant = filterProcessorForTenant;
     _executionContext         = executionContext;
     _eventProcessorForTenant  = eventProcessorForTenant;
     _acceptRegistration       = acceptRegistration;
     _rejectRegistration       = rejectRegistration;
     _cancellationTokenSource  = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
 }
Exemplo n.º 2
0
    /// <inheritdoc/>
    public async Task <Try> TryUpdateAll(ExecutionContext executionContext, CancellationToken cancellationToken)
    {
        _logger.UpdatingAllEmbeddingStates(_embedding);
        var keys = await _embeddingStore.TryGetKeys(_embedding, cancellationToken).ConfigureAwait(false);

        if (!keys.Success)
        {
            return(keys);
        }

        var result = Try.Succeeded();

        foreach (var key in keys.Result)
        {
            _logger.UpdatingEmbeddingStateFor(_embedding, key);
            var updateResult = await TryUpdateEmbedding(key, executionContext, cancellationToken).ConfigureAwait(false);

            if (!updateResult.Success)
            {
                _logger.FailedUpdatingEmbeddingStateFor(_embedding, key, updateResult.Exception);
                result = result.Success ? updateResult : result;
            }
        }

        return(result);
    }
Exemplo n.º 3
0
    async Task <IProcessingResult> Process(HandleEventRequest request, ExecutionContext executionContext, CancellationToken cancellationToken)
    {
        var response = await _dispatcher.Call(request, executionContext, cancellationToken).ConfigureAwait(false);

        return(response switch
        {
            { Failure : null } => new SuccessfulProcessing(),
Exemplo n.º 4
0
    async Task <Try> TryUpdateEmbedding(ProjectionKey key, ExecutionContext executionContext, CancellationToken cancellationToken)
    {
        var currentState = await _embeddingStore.TryGet(_embedding, key, cancellationToken).ConfigureAwait(false);

        if (!currentState.Success)
        {
            return(currentState);
        }
        var unprocessedEvents = await TryGetUnprocessedEvents(key, currentState.Result.Version, cancellationToken).ConfigureAwait(false);

        if (!unprocessedEvents.Success)
        {
            return(Try.Failed(unprocessedEvents.Exception));
        }
        if (!unprocessedEvents.Result.Any())
        {
            return(Try.Succeeded());
        }

        var projectedState = await _projectManyEvents.TryProject(currentState, unprocessedEvents, executionContext, cancellationToken).ConfigureAwait(false);

        if (projectedState.Success || projectedState.IsPartialResult)
        {
            var updateState = await TryUpdateOrDeleteState(projectedState.Result, cancellationToken).ConfigureAwait(false);

            if (updateState.Success && projectedState.IsPartialResult)
            {
                return(projectedState.Exception);
            }

            return(updateState);
        }

        return(Try.Failed(projectedState.Exception));
    }
Exemplo n.º 5
0
    Try <StreamProcessor> TryRegisterStreamProcessor <TFilterDefinition>(
        ScopeId scopeId,
        TFilterDefinition filterDefinition,
        Func <TenantId, IFilterProcessor <TFilterDefinition> > getFilterProcessor,
        ExecutionContext executionContext,
        CancellationToken cancellationToken)
        where TFilterDefinition : IFilterDefinition
    {
        _logger.RegisteringStreamProcessorForFilter(filterDefinition.TargetStream, filterDefinition.SourceStream);
        try
        {
            return(_streamProcessors.TryCreateAndRegister(
                       scopeId,
                       filterDefinition.TargetStream.Value,
                       new EventLogStreamDefinition(),
                       getFilterProcessor,
                       executionContext,
                       cancellationToken));
        }
        catch (Exception ex)
        {
            if (!cancellationToken.IsCancellationRequested)
            {
                _logger.ErrorWhileRegisteringStreamProcessorForFilter(ex, filterDefinition.TargetStream, filterDefinition.SourceStream);
            }

            return(ex);
        }
    }
Exemplo n.º 6
0
    /// <inheritdoc />
    protected override void Setup(IServiceProvider services)
    {
        _eventStore       = services.GetRequiredService <IEventStore>();
        _executionContext = Runtime.CreateExecutionContextFor(ConfiguredTenants.First());

        var events = new List <UncommittedEvent>();

        for (var n = 0; n < EventsToCommit; n++)
        {
            events.Add(new UncommittedEvent(
                           new EventSourceId("8453f4d4-861a-4042-a4e3-c1abf1c8eadd"),
                           new Artifact(new ArtifactId(Guid.Parse("752f88c9-70f0-4ffe-82b6-a69dcc96672e")), ArtifactGeneration.First),
                           false,
                           "{ \"hello\": \"world\" }"));
        }
        _eventsToCommit = new UncommittedEvents(events);

        if (PreExistingEvents < 1)
        {
            return;
        }

        var preExistingEvents = new List <UncommittedEvent>();

        for (var n = 0; n < PreExistingEvents; n++)
        {
            preExistingEvents.Add(new UncommittedEvent(
                                      new EventSourceId("8453f4d4-861a-4042-a4e3-c1abf1c8eadd"),
                                      new Artifact(new ArtifactId(Guid.Parse("752f88c9-70f0-4ffe-82b6-a69dcc96672e")), ArtifactGeneration.First),
                                      false,
                                      "{ \"hello\": \"world\" }"));
        }

        _eventStore.Commit(new UncommittedEvents(preExistingEvents), _executionContext).GetAwaiter().GetResult();
    }
Exemplo n.º 7
0
    async Task <IFilterResult> Filter(FilterEventRequest request, ExecutionContext executionContext, CancellationToken cancellationToken)
    {
        var response = await _dispatcher.Call(request, executionContext, cancellationToken).ConfigureAwait(false);

        return(response switch
        {
            { Failure : null } => new SuccessfulFiltering(response.IsIncluded, response.PartitionId),
Exemplo n.º 8
0
 static void should_have_same_execution_context(ExecutionContext execution_context, Dolittle.Runtime.Events.Store.MongoDB.Events.ExecutionContext stored_execution_context)
 {
     stored_execution_context.Correlation.ShouldEqual(execution_context.CorrelationId.Value);
     stored_execution_context.Environment.ShouldEqual(execution_context.Environment.Value);
     stored_execution_context.Microservice.ShouldEqual(execution_context.Microservice.Value);
     stored_execution_context.Tenant.ShouldEqual(execution_context.Tenant.Value);
     should_have_the_same_version(execution_context.Version, stored_execution_context.Version);
     should_have_the_same_claims(execution_context.Claims, stored_execution_context.Claims);
 }
Exemplo n.º 9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EventHorizonConnection" /> class.
 /// </summary>
 /// <param name="executionContext">The <see cref="ExecutionContext"/>.</param>
 /// <param name="reverseCallClient">The reverse call client.</param>
 /// <param name="metrics">The system for collecting metrics.</param>
 /// <param name="logger">The logger.</param>
 public EventHorizonConnection(
     ExecutionContext executionContext,
     IReverseCallClient <ConsumerSubscriptionRequest, Contracts.SubscriptionResponse, ConsumerRequest, ConsumerResponse> reverseCallClient,
     IMetricsCollector metrics,
     ILogger logger)
 {
     _executionContext  = executionContext;
     _reverseCallClient = reverseCallClient;
     _metrics           = metrics;
     _logger            = logger;
 }
Exemplo n.º 10
0
 Task <Try <ExecutionContext> > CreateExecutionContextOrReject <TClientMessage, TConnectRequest, TResponse>(
     IReverseCallDispatcher <TClientMessage, FilterRuntimeToClientMessage, TConnectRequest, FilterRegistrationResponse, FilterEventRequest, TResponse> dispatcher,
     ExecutionContext requestExecutionContext,
     CancellationToken cancellationToken)
     where TClientMessage : IMessage, new()
     where TConnectRequest : class
     where TResponse : class
 => _executionContextCreator
 .TryCreateUsing(requestExecutionContext)
 .Catch(async exception =>
 {
     _logger.ExecutionContextIsNotValid(exception);
     var failure = new Failure(FiltersFailures.CannotRegisterFilterOnNonWriteableStream, $"Execution context is invalid: {exception.Message}");
     await WriteFailedRegistrationResponse(dispatcher, failure, cancellationToken).ConfigureAwait(false);
 });
Exemplo n.º 11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ScopedStreamProcessor"/> class.
 /// </summary>
 /// <param name="tenantId">The <see cref="TenantId"/>.</param>
 /// <param name="streamProcessorId">The <see cref="IStreamProcessorId" />.</param>
 /// <param name="sourceStreamDefinition">The source stream <see cref="IStreamDefinition" />.</param>
 /// <param name="initialState">The <see cref="StreamProcessorState" />.</param>
 /// <param name="processor">An <see cref="IEventProcessor" /> to process the event.</param>
 /// <param name="streamProcessorStates">The <see cref="IResilientStreamProcessorStateRepository" />.</param>
 /// <param name="eventsFromStreamsFetcher">The<see cref="ICanFetchEventsFromStream" />.</param>
 /// <param name="executionContext">The <see cref="ExecutionContext"/> of the stream processor.</param>
 /// <param name="eventFetcherPolicies">The policies to use while fetching events.</param>
 /// <param name="eventWatcher">The <see cref="IStreamEventWatcher" /> to wait for events to be available in stream.</param>
 /// <param name="timeToRetryGetter">The <see cref="ICanGetTimeToRetryFor{T}" /> <see cref="StreamProcessorState" />.</param>
 /// <param name="logger">An <see cref="ILogger" /> to log messages.</param>
 public ScopedStreamProcessor(
     TenantId tenantId,
     IStreamProcessorId streamProcessorId,
     IStreamDefinition sourceStreamDefinition,
     StreamProcessorState initialState,
     IEventProcessor processor,
     IResilientStreamProcessorStateRepository streamProcessorStates,
     ICanFetchEventsFromStream eventsFromStreamsFetcher,
     ExecutionContext executionContext,
     IEventFetcherPolicies eventFetcherPolicies,
     IStreamEventWatcher eventWatcher,
     ICanGetTimeToRetryFor <StreamProcessorState> timeToRetryGetter,
     ILogger logger)
     : base(tenantId, streamProcessorId, sourceStreamDefinition, initialState, processor, eventsFromStreamsFetcher, executionContext, eventFetcherPolicies, eventWatcher, logger)
 {
     _streamProcessorStates = streamProcessorStates;
     _timeToRetryGetter     = timeToRetryGetter;
 }
    /// <inheritdoc />
    public async Task <AbstractScopedStreamProcessor> Create(
        IStreamDefinition streamDefinition,
        IStreamProcessorId streamProcessorId,
        IEventProcessor eventProcessor,
        ExecutionContext executionContext,
        CancellationToken cancellationToken)
    {
        var processorState = await GetOrCreateStreamProcessorState(
            streamProcessorId,
            streamDefinition.Partitioned
            ?Partitioned.StreamProcessorState.New
            : StreamProcessorState.New,
            cancellationToken)
                             .ConfigureAwait(false);

        AbstractScopedStreamProcessor streamProcessor;

        if (streamDefinition.Partitioned)
        {
            if (processorState is not Partitioned.StreamProcessorState partitionedProcessorState)
            {
                throw new ExpectedPartitionedStreamProcessorState(streamProcessorId);
            }

            var eventFetcher = await _eventFetchers.GetPartitionedFetcherFor(eventProcessor.Scope, streamDefinition, cancellationToken).ConfigureAwait(false);

            streamProcessor = _createPartitionedStreamProcessor(streamDefinition, streamProcessorId, eventFetcher, eventProcessor, partitionedProcessorState, executionContext);
        }
        else
        {
            if (processorState is not StreamProcessorState unpartitionedProcessorState)
            {
                throw new ExpectedUnpartitionedStreamProcessorState(streamProcessorId);
            }

            var eventFetcher = await _eventFetchers.GetFetcherFor(eventProcessor.Scope, streamDefinition, cancellationToken).ConfigureAwait(false);

            streamProcessor = _createUnpartitionedStreamProcessor(streamDefinition, streamProcessorId, eventFetcher, eventProcessor, unpartitionedProcessorState, executionContext);
        }

        NotifyStream(streamProcessorId.ScopeId, streamDefinition, processorState.Position);

        return(streamProcessor);
    }
Exemplo n.º 13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ScopedStreamProcessor"/> class.
 /// </summary>
 /// <param name="tenantId">The <see cref="TenantId"/>.</param>
 /// <param name="streamProcessorId">The <see cref="IStreamProcessorId" />.</param>
 /// <param name="sourceStreamDefinition">The source stream <see cref="StreamDefinition" />.</param>
 /// <param name="initialState">The <see cref="StreamProcessorState" />.</param>
 /// <param name="processor">An <see cref="IEventProcessor" /> to process the event.</param>
 /// <param name="streamProcessorStates">The <see cref="IResilientStreamProcessorStateRepository" />.</param>
 /// <param name="eventsFromStreamsFetcher">The<see cref="ICanFetchEventsFromStream" />.</param>
 /// <param name="executionContext">The <see cref="ExecutionContext"/> of the stream processor.</param>
 /// <param name="failingPartitionsFactory">The factory to use to create the <see cref="IFailingPartitions" />.</param>
 /// <param name="eventFetcherPolicies">The policies to use while fetching events.</param>
 /// <param name="streamWatcher">The <see cref="IStreamEventWatcher" />.</param>
 /// <param name="timeToRetryGetter">The <see cref="ICanGetTimeToRetryFor{T}" /> <see cref="StreamProcessorState" />.</param>
 /// <param name="logger">An <see cref="ILogger" /> to log messages.</param>
 public ScopedStreamProcessor(
     TenantId tenantId,
     IStreamProcessorId streamProcessorId,
     IStreamDefinition sourceStreamDefinition,
     StreamProcessorState initialState,
     IEventProcessor processor,
     IResilientStreamProcessorStateRepository streamProcessorStates,
     ICanFetchEventsFromPartitionedStream eventsFromStreamsFetcher,
     ExecutionContext executionContext,
     Func <IEventProcessor, ICanFetchEventsFromPartitionedStream, Func <StreamEvent, ExecutionContext>, IFailingPartitions> failingPartitionsFactory,
     IEventFetcherPolicies eventFetcherPolicies,
     IStreamEventWatcher streamWatcher,
     ICanGetTimeToRetryFor <StreamProcessorState> timeToRetryGetter,
     ILogger logger)
     : base(tenantId, streamProcessorId, sourceStreamDefinition, initialState, processor, eventsFromStreamsFetcher, executionContext, eventFetcherPolicies, streamWatcher, logger)
 {
     _streamProcessorStates = streamProcessorStates;
     _failingPartitions     = failingPartitionsFactory(processor, eventsFromStreamsFetcher, GetExecutionContextForEvent);
     _timeToRetryGetter     = timeToRetryGetter;
 }
Exemplo n.º 14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StreamProcessor"/> class.
 /// </summary>
 /// <param name="subscriptionId">The identifier of the subscription the stream processor will receive events for.</param>
 /// <param name="executionContext">The <see cref="ExecutionContext"/>.</param>
 /// <param name="eventProcessor">The event processor that writes the received events to a scoped event log.</param>
 /// <param name="eventsFetcher">The event fetcher that receives fetches events over an event horizon connection.</param>
 /// <param name="streamProcessorStates">The repository to use for getting the subscription state.</param>
 /// <param name="eventsFetcherPolicy">The policy around fetching events.</param>
 /// <param name="metrics">The system for collecting metrics.</param>
 /// <param name="loggerFactory">The factory for creating loggers.</param>
 public StreamProcessor(
     SubscriptionId subscriptionId,
     ExecutionContext executionContext,
     IEventProcessor eventProcessor,
     EventsFromEventHorizonFetcher eventsFetcher,
     IResilientStreamProcessorStateRepository streamProcessorStates,
     IEventFetcherPolicies eventsFetcherPolicy,
     IMetricsCollector metrics,
     ILoggerFactory loggerFactory)
 {
     _identifier            = subscriptionId;
     _executionContext      = executionContext;
     _eventProcessor        = eventProcessor;
     _streamProcessorStates = streamProcessorStates;
     _eventsFetcher         = eventsFetcher;
     _eventsFetcherPolicy   = eventsFetcherPolicy;
     _metrics       = metrics;
     _loggerFactory = loggerFactory;
     _logger        = loggerFactory.CreateLogger <StreamProcessor>();
 }
    async Task <Try <EmbeddingCurrentState> > TryProjectNewState(
        EmbeddingCurrentState current,
        Try <UncommittedEvents> newTransitionEvents,
        IEnumerable <ProjectionState> previousStates,
        ExecutionContext executionContext,
        CancellationToken cancellationToken)
    {
        var intermediateState = await _projector.TryProject(current, newTransitionEvents.Result, executionContext, cancellationToken).ConfigureAwait(false);

        if (!intermediateState.Success)
        {
            return(intermediateState.IsPartialResult
                ? new CouldNotProjectAllEvents(_embeddingId, intermediateState.Exception)
                : new FailedProjectingEvents(_embeddingId, intermediateState.Exception));
        }

        var loopDetected = _loopDetector.TryCheckForProjectionStateLoop(intermediateState.Result.State, previousStates);

        return(loopDetected switch
        {
            { Success : false } => loopDetected.Exception,
Exemplo n.º 16
0
    public static void should_be_the_correct_response(
        this CommitAggregateEventsResponse response,
        UncommittedAggregateEvents uncommitted_events,
        ExecutionContext execution_context,
        EventLogSequenceNumber start_sequence_number      = null,
        AggregateRootVersion start_aggregate_root_version = null)
    {
        var committedEvents = response.Events.ToCommittedEvents();

        committedEvents.Count.ShouldEqual(uncommitted_events.Count);
        if (uncommitted_events.Count == 0)
        {
            return;
        }

        committedEvents.AggregateRoot.ShouldEqual(uncommitted_events.AggregateRoot.Id);
        committedEvents.EventSource.ShouldEqual(uncommitted_events.EventSource);

        for (var i = 0; i < committedEvents.Count; i++)
        {
            var committedEvent   = committedEvents[i];
            var uncommittedEvent = uncommitted_events[i];

            if (start_sequence_number != null)
            {
                committedEvent.EventLogSequenceNumber.ShouldEqual(new EventLogSequenceNumber(start_sequence_number + (ulong)i));
            }
            if (start_aggregate_root_version != null)
            {
                committedEvent.AggregateRootVersion.ShouldEqual(new AggregateRootVersion(start_aggregate_root_version + (ulong)i));
            }

            committedEvent.AggregateRoot.ShouldEqual(uncommitted_events.AggregateRoot);
            committedEvent.ExecutionContext.ShouldEqual(execution_context);
            committedEvent.Content.ShouldEqual(uncommittedEvent.Content);
            committedEvent.Public.ShouldEqual(uncommittedEvent.Public);
            committedEvent.Type.ShouldEqual(uncommittedEvent.Type);
            committedEvent.EventSource.ShouldEqual(uncommittedEvent.EventSource);
        }
    }
Exemplo n.º 17
0
    /// <inheritdoc />
    protected override void Setup(IServiceProvider services)
    {
        _eventStore       = services.GetRequiredService <IEventStore>();
        _executionContext = Runtime.CreateExecutionContextFor(ConfiguredTenants.First());

        var events = new List <UncommittedEvent>();

        for (var n = 0; n < EventsToCommit; n++)
        {
            events.Add(new UncommittedEvent(
                           new EventSourceId("46c4de33-9a60-4465-97ab-a2a7f5b7e6a3"),
                           new Artifact(new ArtifactId(Guid.Parse("08db4b0a-3724-444f-9968-ada44922fb78")), ArtifactGeneration.First),
                           false,
                           "{ \"hello\": \"world\" }"));
        }

        _eventsToCommit = new UncommittedAggregateEvents(
            new EventSourceId("46c4de33-9a60-4465-97ab-a2a7f5b7e6a3"),
            new Artifact(new ArtifactId(Guid.Parse("1ad7a5dc-12e9-493a-ba10-714c88be4da7")), ArtifactGeneration.First),
            AggregateRootVersion.Initial,
            events);
    }
Exemplo n.º 18
0
    public static void should_be_the_correct_responses(this CommitAggregateEventsResponse[] responses, UncommittedAggregateEvents[] uncommitted_events, ExecutionContext execution_context, bool random_commit_order = false)
    {
        var startEventLogSequenceNumber = EventLogSequenceNumber.Initial;

        for (var i = 0; i < responses.Length; i++)
        {
            var response = responses[i];
            var events   = uncommitted_events[i];
            response.should_be_the_correct_response(events, execution_context, random_commit_order ? response.Events?.Events?.First().EventLogSequenceNumber : startEventLogSequenceNumber);
            startEventLogSequenceNumber += (ulong)events.Count;
        }
    }
 /// <inheritdoc/>
 public Task <Try <UncommittedAggregateEvents> > TryDelete(EmbeddingCurrentState current, ExecutionContext executionContext, CancellationToken cancellationToken)
 => DoWork(
     current,
     newCurrent => Try <bool> .Do(() => newCurrent.Type is EmbeddingCurrentStateType.Deleted),
     (newCurrent, token) => _embedding.TryDelete(newCurrent, executionContext, token),
     executionContext,
     cancellationToken);
Exemplo n.º 20
0
    /// <inheritdoc/>
    public override Task <IFilterResult> Filter(CommittedEvent @event, PartitionId partitionId, EventProcessorId eventProcessorId, string failureReason, uint retryCount, ExecutionContext executionContext, CancellationToken cancellationToken)
    {
        if ([email protected])
        {
            return(Task.FromResult <IFilterResult>(new SuccessfulFiltering(false, PartitionId.None)));
        }
        var request = new FilterEventRequest
        {
            Event   = @event.ToProtobuf(),
            ScopeId = Scope.ToProtobuf(),
            RetryProcessingState = new RetryProcessingState {
                FailureReason = failureReason, RetryCount = retryCount
            }
        };

        return(Filter(request, executionContext, cancellationToken));
    }
Exemplo n.º 21
0
    public static async Task <CommitEventsResponse> Commit(this IEventStore eventStore, UncommittedEvents events, Dolittle.Runtime.Execution.ExecutionContext executionContext)
    {
        var request = new CommitEventsRequest {
            CallContext = new CallRequestContext {
                ExecutionContext = executionContext.ToProtobuf()
            }
        };

        request.Events.AddRange(events.Select(_ => new UncommittedEventContract
        {
            Content       = _.Content,
            Public        = _.Public,
            EventType     = _.Type.ToProtobuf(),
            EventSourceId = _.EventSource
        }));
        var response = await eventStore.CommitEvents(request, CancellationToken.None).ConfigureAwait(false);

        return(response);
    }
Exemplo n.º 22
0
    /// <inheritdoc/>
    public override Task <IFilterResult> Filter(CommittedEvent @event, PartitionId partitionId, EventProcessorId eventProcessorId, ExecutionContext executionContext, CancellationToken cancellationToken)
    {
        var request = new FilterEventRequest
        {
            Event   = @event.ToProtobuf(),
            ScopeId = Scope.ToProtobuf()
        };

        return(Filter(request, executionContext, cancellationToken));
    }
Exemplo n.º 23
0
    /// <inheritdoc/>
    public async Task <IProcessingResult> Process(CommittedEvent @event, PartitionId partitionId, string failureReason, uint retryCount, ExecutionContext executionContext, CancellationToken cancellationToken)
    {
        _logger.FilteringEventAgain(Identifier, Scope, @event.Type.Id, partitionId, retryCount, failureReason);
        var result = await Filter(@event, partitionId, Identifier, failureReason, retryCount, executionContext, cancellationToken).ConfigureAwait(false);

        return(await HandleResult(result, @event, partitionId, cancellationToken).ConfigureAwait(false));
    }
Exemplo n.º 24
0
 /// <inheritdoc/>
 public abstract Task <IFilterResult> Filter(CommittedEvent @event, PartitionId partitionId, EventProcessorId eventProcessorId, ExecutionContext executionContext, CancellationToken cancellationToken);
    async Task <Try <UncommittedAggregateEvents> > DoWork(
        EmbeddingCurrentState current,
        Func <EmbeddingCurrentState, Try <bool> > isDesiredState,
        Func <EmbeddingCurrentState, CancellationToken, Task <Try <UncommittedEvents> > > getTransitionEvents,
        ExecutionContext executionContext,
        CancellationToken cancellationToken)
    {
        try
        {
            _logger.CalculatingStateTransitionEvents(_embeddingId, current.Key, current.Version);
            var allTransitionEvents = new List <UncommittedEvents>();
            var previousStates      = new List <ProjectionState>
            {
                current.State
            };

            while (true)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    _logger.CalculatingStateTransitionEventsCancelled(_embeddingId, current.Key, current.Version);
                    return(new CalculateStateTransitionEventsCancelled(_embeddingId));
                }
                var getEventsToCommit = TryCheckIfDesiredState(current, allTransitionEvents, isDesiredState, out var eventsToCommit);
                if (!getEventsToCommit.Success || getEventsToCommit.Result)
                {
                    if (getEventsToCommit.Exception != default)
                    {
                        _logger.CalculatingStateTransitionEventsFailedCheckingIfDesiredState(
                            _embeddingId,
                            current.Key,
                            current.Version,
                            getEventsToCommit.Exception);
                        return(getEventsToCommit.Exception);
                    }
                    return(eventsToCommit);
                }
                var addNewTransitionEvents = await TryGetAndAddNewTransitionEventsInto(
                    allTransitionEvents,
                    current,
                    getTransitionEvents,
                    cancellationToken).ConfigureAwait(false);

                if (!addNewTransitionEvents.Success)
                {
                    _logger.CalculatingStateTransitionEventsFailedGettingNextTransitionEvents(
                        _embeddingId,
                        current.Key,
                        current.Version,
                        addNewTransitionEvents.Exception);
                    return(addNewTransitionEvents.Exception);
                }

                var projectIntermediateState = await TryProjectNewState(current, addNewTransitionEvents, previousStates, executionContext, cancellationToken).ConfigureAwait(false);

                if (!projectIntermediateState.Success)
                {
                    _logger.CalculatingStateTransitionEventsFailedProjectingNewState(
                        _embeddingId,
                        current.Key,
                        current.Version,
                        addNewTransitionEvents.Exception);
                    return(projectIntermediateState.Exception);
                }

                previousStates.Add(projectIntermediateState.Result.State);
                current = projectIntermediateState;
            }
        }
        catch (Exception ex)
        {
            return(ex);
        }
    }
Exemplo n.º 26
0
    public static async Task <CommitAggregateEventsResponse> Commit(this IEventStore eventStore, UncommittedAggregateEvents events, Dolittle.Runtime.Execution.ExecutionContext executionContext)
    {
        var response = await eventStore.CommitAggregateEvents(events.ToCommitRequest(executionContext), CancellationToken.None);

        return(response);
    }
Exemplo n.º 27
0
    /// <inheritdoc/>
    public override Task <IFilterResult> Filter(CommittedEvent @event, PartitionId partitionId, EventProcessorId eventProcessorId, ExecutionContext executionContext, CancellationToken cancellationToken)
    {
        if ([email protected])
        {
            return(Task.FromResult <IFilterResult>(new SuccessfulFiltering(false, PartitionId.None)));
        }
        var request = new FilterEventRequest
        {
            Event   = @event.ToProtobuf(),
            ScopeId = Scope.ToProtobuf()
        };

        return(Filter(request, executionContext, cancellationToken));
    }
Exemplo n.º 28
0
    public static async Task <FetchForAggregateResponse> FetchForAggregate(this IEventStore eventStore, ArtifactId aggregateRootId, EventSourceId eventSourceId, Dolittle.Runtime.Execution.ExecutionContext executionContext)
    {
        var response = await eventStore.FetchAggregateEvents(new FetchForAggregateRequest
        {
            CallContext = new CallRequestContext
            {
                ExecutionContext = executionContext.ToProtobuf()
            },
            Aggregate = new Aggregate {
                AggregateRootId = aggregateRootId.ToProtobuf(), EventSourceId = eventSourceId
            }
        }, CancellationToken.None);

        return(response);
    }
Exemplo n.º 29
0
 /// <inheritdoc/>
 public abstract Task <IFilterResult> Filter(CommittedEvent @event, PartitionId partitionId, EventProcessorId eventProcessorId, string failureReason, uint retryCount, ExecutionContext executionContext, CancellationToken cancellationToken);
 /// <inheritdoc/>
 public Task <Try <UncommittedAggregateEvents> > TryConverge(EmbeddingCurrentState current, ProjectionState desired, ExecutionContext executionContext, CancellationToken cancellationToken)
 => DoWork(
     current,
     newCurrent => _stateComparer.TryCheckEquality(newCurrent.State, desired),
     (newCurrent, token) => _embedding.TryCompare(newCurrent, desired, executionContext, token),
     executionContext,
     cancellationToken);