コード例 #1
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));
    }
コード例 #2
0
ファイル: ProjectionStates.cs プロジェクト: dolittle/Runtime
    /// <inheritdoc/>
    public async Task <bool> TryReplace(ProjectionId projection, ScopeId scope, ProjectionKey key, ProjectionState state, CancellationToken token)
    {
        try
        {
            var collection = await _projections.GetStates(scope, projection, token).ConfigureAwait(false);

            var filter           = CreateKeyFilter(key);
            var updateDefinition = Builders <Projection>
                                   .Update
                                   .Set(_ => _.Content, BsonDocument.Parse(state.Value))
                                   .Set(_ => _.ContentRaw, state.Value);

            var updateResult = await collection.UpdateOneAsync(
                filter,
                updateDefinition,
                new UpdateOptions { IsUpsert = true },
                token).ConfigureAwait(false);

            return(updateResult.IsAcknowledged);
        }
        catch (MongoWaitQueueFullException)
        {
            return(false);
        }
    }
コード例 #3
0
ファイル: EmbeddingStore.cs プロジェクト: dolittle/Runtime
    /// <inheritdoc/>
    public async Task <Try <EmbeddingCurrentState> > TryGet(EmbeddingId embedding, ProjectionKey key, CancellationToken token)
    {
        _logger.GettingOneEmbedding(embedding, key);

        var state = await _embeddingStates.TryGet(embedding, key, token);

        var result = state switch
        {
            { Success : true, Result : { IsRemoved : true } } => await TryGetInitialState(
コード例 #4
0
ファイル: ProjectionKeys.cs プロジェクト: dolittle/Runtime
 static bool StaticIsKey(ProjectEventKeySelectorType type, ProjectionKey staticKey, out ProjectionKey key)
 {
     key = null;
     if (type != ProjectEventKeySelectorType.Static)
     {
         return(false);
     }
     key = staticKey;
     return(true);
 }
コード例 #5
0
        public Task SaveProjectionAsync(ISerializedProjection projection)
        {
            var key = new ProjectionKey(projection.ProjectionId, projection.Category);

            if (!_uncommitedProjections.ContainsKey(key))
            {
                _uncommitedProjections.Add(key, null);
            }

            _uncommitedProjections[key] = projection.Projection;

            return(Task.CompletedTask);
        }
コード例 #6
0
ファイル: ProjectionStates.cs プロジェクト: dolittle/Runtime
    /// <inheritdoc/>
    public async Task <bool> TryRemove(ProjectionId projection, ScopeId scope, ProjectionKey key, CancellationToken token)
    {
        try
        {
            var collection = await _projections.GetStates(scope, projection, token).ConfigureAwait(false);

            var deleteResult = await collection.DeleteOneAsync(CreateKeyFilter(key), token).ConfigureAwait(false);

            return(deleteResult.IsAcknowledged);
        }
        catch (MongoWaitQueueFullException)
        {
            return(false);
        }
    }
コード例 #7
0
 async Task <Try <CommittedAggregateEvents> > TryGetUnprocessedEvents(ProjectionKey key, AggregateRootVersion aggregateRootVersion, CancellationToken cancellationToken)
 {
     try
     {
         return(await _committedEvents.FetchForAggregateAfter(
                    key.Value,
                    _embedding.Value,
                    aggregateRootVersion,
                    cancellationToken).ConfigureAwait(false));
     }
     catch (Exception ex)
     {
         return(ex);
     }
 }
コード例 #8
0
    public async Task <bool> TryRemove(ProjectionDefinition projection, ProjectionKey key, CancellationToken token)
    {
        Log.RemovingProjectionState(_logger, projection.Projection, projection.Scope, key);
        _metrics.IncrementTotalRemoveAttempts();
        foreach (var store in ApplicableCopyStores(projection))
        {
            if (!await store.TryRemove(projection, key, token).ConfigureAwait(false))
            {
                Log.FailedToRemoveProjectionStateInCopyStore(_logger, projection.Projection, projection.Scope, key);
                _metrics.IncrementTotalFailedCopyStoreRemovals();
                return(false);
            }
            _metrics.IncrementTotalCopyStoreRemovals();
        }

        return(await _projectionStore.TryRemove(projection.Projection, projection.Scope, key, token));
    }
コード例 #9
0
    /// <inheritdoc />
    public async Task <bool> TryRemove(ProjectionDefinition projection, ProjectionKey key, CancellationToken token)
    {
        ThrowIfShouldNotPersistFor(projection);

        try
        {
            var collection = GetCollectionFor(projection);
            var filter     = GetFilterFor(key);

            var deleteResult = await collection.DeleteOneAsync(filter, token).ConfigureAwait(false);

            return(deleteResult.IsAcknowledged);
        }
        catch (MongoWaitQueueFullException)
        {
            return(false);
        }
    }
コード例 #10
0
    /// <inheritdoc />
    public async Task <bool> TryReplace(ProjectionDefinition projection, ProjectionKey key, ProjectionState state, CancellationToken token)
    {
        ThrowIfShouldNotPersistFor(projection);

        try
        {
            var document = _converter.Convert(state, projection.Copies.MongoDB.Conversions);
            AddKeyTo(document, key);

            var collection = GetCollectionFor(projection);
            var filter     = GetFilterFor(key);

            var replaceResult = await collection.ReplaceOneAsync(filter, document, new ReplaceOptions { IsUpsert = true }, token).ConfigureAwait(false);

            return(replaceResult.IsAcknowledged);
        }
        catch (MongoWaitQueueFullException)
        {
            return(false);
        }
    }
コード例 #11
0
 /// <inheritdoc/>
 public async Task <Try <bool> > TryReplace(
     EmbeddingId embedding,
     ProjectionKey key,
     EmbeddingState state,
     CancellationToken token)
 {
     try
     {
         return(await OnEmbedding(
                    embedding,
                    async collection =>
         {
             var updateDefinition = Builders <Embedding>
                                    .Update
                                    .Set(_ => _.Content, state.State.Value)
                                    .Set(_ => _.Version, state.Version.Value)
                                    .Set(_ => _.IsRemoved, state.IsRemoved);
             var updateResult = await collection
                                .UpdateOneAsync(
                 CreateKeyFilter(key),
                 updateDefinition,
                 new UpdateOptions {
                 IsUpsert = true
             },
                 token)
                                .ConfigureAwait(false);
             return updateResult.IsAcknowledged;
         },
                    token).ConfigureAwait(false));
     }
     catch (MongoWaitQueueFullException)
     {
         return(false);
     }
     catch (Exception ex)
     {
         return(ex);
     }
 }
コード例 #12
0
 /// <inheritdoc/>
 public async Task <Try <bool> > TryMarkAsRemove(
     EmbeddingId embedding,
     ProjectionKey key,
     AggregateRootVersion version,
     CancellationToken token)
 {
     try
     {
         return(await OnEmbedding(
                    embedding,
                    async collection =>
         {
             var markDefinition = Builders <Embedding>
                                  .Update
                                  .Set(_ => _.IsRemoved, true)
                                  .Set(_ => _.Version, version.Value);
             var markResult = await collection
                              .UpdateOneAsync(
                 CreateKeyFilter(key),
                 markDefinition,
                 new UpdateOptions {
                 IsUpsert = true
             },
                 token)
                              .ConfigureAwait(false);
             return markResult.IsAcknowledged;
         },
                    token).ConfigureAwait(false));
     }
     catch (MongoWaitQueueFullException)
     {
         return(false);
     }
     catch (Exception ex)
     {
         return(ex);
     }
 }
コード例 #13
0
    /// <inheritdoc/>
    public async Task <Try <EmbeddingState> > TryGet(
        EmbeddingId embeddingId,
        ProjectionKey key,
        CancellationToken token)
    {
        try
        {
            var embedding = await OnEmbedding(
                embeddingId,
                async collection => await collection
                .Find(CreateKeyFilter(key))
                .SingleOrDefaultAsync(token)
                .ConfigureAwait(false),
                token).ConfigureAwait(false);

            return(embedding == default
                ? Try <EmbeddingState> .Failed(new EmbeddingStateDoesNotExist(embeddingId, key))
                : new EmbeddingState(embedding.Content, embedding.Version, embedding.IsRemoved));
        }
        catch (Exception ex)
        {
            return(ex);
        }
    }
コード例 #14
0
 /// <summary>
 /// Initializes an instance of the <see cref="FailedToRemoveEmbedding" /> class.
 /// </summary>
 /// <param name="embedding">The embedding identifier.</param>
 /// <param name="key">The projection key</param>
 /// <param name="version">The aggregate root version.</param>
 public FailedToRemoveEmbedding(EmbeddingId embedding, ProjectionKey key, AggregateRootVersion version)
     : base($"Failed to remove embedding with id {embedding.Value}, key {key.Value} and aggregate root version {version.Value}")
 {
 }
コード例 #15
0
 /// <summary>
 /// Initializes an instance of the <see cref="EmbeddingStateDoesNotExist" /> class.
 /// </summary>
 /// <param name="embedding">The embedding id.</param>
 /// <param name="key">The key to the embedding.</param>
 public EmbeddingStateDoesNotExist(EmbeddingId embedding, ProjectionKey key)
     : base($"An embedding state for embedding {embedding.Value} with key {key.Value} does not exist")
 {
 }
コード例 #16
0
ファイル: LoggerExtensions.cs プロジェクト: dolittle/Runtime
 internal static void GettingOneProjection(this ILogger logger, ProjectionId projection, ScopeId scope, ProjectionKey key)
 => _gettingOneProjection(logger, projection, scope, key, null);
コード例 #17
0
 /// <inheritdoc/>
 public Task <Try <ProjectionCurrentState> > TryGetOne(ProjectionId projection, ScopeId scope, ProjectionKey key, ExecutionContext context, CancellationToken token)
 => _executionContextCreator
 .TryCreateUsing(context)
 .Then(_ => _getProjectionStoreFor(_.Tenant))
 .Then(_ => _.TryGet(projection, scope, key, token));
コード例 #18
0
ファイル: ProjectionKeys.cs プロジェクト: dolittle/Runtime
 static bool EventSourceIsKey(ProjectEventKeySelectorType type, EventSourceId eventSource, out ProjectionKey key)
 {
     key = null;
     if (type != ProjectEventKeySelectorType.EventSourceId)
     {
         return(false);
     }
     key = eventSource.Value;
     return(true);
 }
コード例 #19
0
ファイル: ProjectionKeys.cs プロジェクト: dolittle/Runtime
 static bool PartitionIsKey(ProjectEventKeySelectorType type, PartitionId partition, out ProjectionKey key)
 {
     key = null;
     if (type != ProjectEventKeySelectorType.PartitionId)
     {
         return(false);
     }
     key = partition.Value;
     return(true);
 }
コード例 #20
0
ファイル: ProjectionKeys.cs プロジェクト: dolittle/Runtime
 bool TryGetKey(ProjectionEventSelector eventSelector, CommittedEvent @event, PartitionId partition, out ProjectionKey key)
 => PartitionIsKey(eventSelector.KeySelectorType, partition, out key) ||
 EventSourceIsKey(eventSelector.KeySelectorType, @event.EventSource, out key) ||
 PropertyIsKey(eventSelector.KeySelectorType, @event.Content, eventSelector.KeySelectorExpression, out key) ||
 StaticIsKey(eventSelector.KeySelectorType, eventSelector.StaticKey, out key) ||
 OccurredIsKey(eventSelector.KeySelectorType, eventSelector.OccurredFormat, @event.Occurred, out key);
コード例 #21
0
 static void AddKeyTo(BsonDocument document, ProjectionKey key)
 => document.Set(ProjectionDocumentKeyProperty, key.Value);
コード例 #22
0
 FilterDefinition <Embedding> CreateKeyFilter(ProjectionKey key) =>
 Builders <Embedding> .Filter.Eq(_ => _.Key, key.Value);
コード例 #23
0
ファイル: ProjectionStates.cs プロジェクト: dolittle/Runtime
    /// <inheritdoc/>
    public async Task <Try <ProjectionState> > TryGet(ProjectionId projection, ScopeId scope, ProjectionKey key, CancellationToken token)
    {
        try
        {
            var collection = await _projections.GetStates(scope, projection, token).ConfigureAwait(false);

            var projectionState = await collection
                                  .Find(CreateKeyFilter(key))
                                  .Project(_ => _.ContentRaw)
                                  .SingleOrDefaultAsync(token)
                                  .ConfigureAwait(false);

            return(string.IsNullOrEmpty(projectionState)
                ? Try <ProjectionState> .Failed(new ProjectionStateDoesNotExist(projection, key, scope))
                : new ProjectionState(projectionState));
        }
        catch (Exception ex)
        {
            return(ex);
        }
    }
コード例 #24
0
ファイル: ProjectionKeys.cs プロジェクト: dolittle/Runtime
 bool PropertyIsKey(ProjectEventKeySelectorType type, string eventContent, KeySelectorExpression keySelectorExpression, out ProjectionKey key)
 {
     key = null;
     return(type == ProjectEventKeySelectorType.Property && _keyPropertyExtractor.TryExtract(eventContent, keySelectorExpression, out key));
 }
コード例 #25
0
 /// <summary>
 /// Initializes an instance of the <see cref="ProjectionStateDoesNotExist" /> class.
 /// </summary>
 /// <param name="projection">The projection id.</param>
 /// <param name="key">The projection key.</param>
 /// <param name="scope">The scope id.</param>
 public ProjectionStateDoesNotExist(ProjectionId projection, ProjectionKey key, ScopeId scope)
     : base($"A projection state for projection {projection.Value} with key {key.Value} in scope {scope.Value} does not exist")
 {
 }
コード例 #26
0
ファイル: ProjectionKeys.cs プロジェクト: dolittle/Runtime
    public bool TryGetFor(ProjectionDefinition projectionDefinition, CommittedEvent @event, PartitionId partition, out ProjectionKey key)
    {
        key = null;
        var eventSelector = projectionDefinition.Events.FirstOrDefault(_ => _.EventType == @event.Type.Id);

        return(eventSelector != null && TryGetKey(eventSelector, @event, partition, out key));
    }
コード例 #27
0
 static FilterDefinition <BsonDocument> GetFilterFor(ProjectionKey key)
 => Builders <BsonDocument> .Filter.Eq(ProjectionDocumentKeyProperty, key.Value);
コード例 #28
0
ファイル: ProjectionKeys.cs プロジェクト: dolittle/Runtime
 bool OccurredIsKey(ProjectEventKeySelectorType type, OccurredFormat occurredFormat, DateTimeOffset eventOccurred, out ProjectionKey key)
 {
     key = null;
     if (type != ProjectEventKeySelectorType.EventOccurred)
     {
         return(false);
     }
     try
     {
         key = eventOccurred.ToString(occurredFormat, CultureInfo.InvariantCulture);
         return(true);
     }
     catch (Exception ex)
     {
         Log.FailedToGetProjectionKeyFromOccurredKeySelector(_logger, ex, occurredFormat);
         key = null;
         return(false);
     }
 }
コード例 #29
0
        private static BaseballPlayer FindAndRemovePlayer(Dictionary <ProjectionKey, BaseballPlayer> existingDictionary, ProjectionKey key)
        {
            if (!existingDictionary.ContainsKey(key))
            {
                return(null);
            }
            var existingPlayer = existingDictionary[key];

            existingDictionary.Remove(key);
            return(existingPlayer);
        }
コード例 #30
0
ファイル: ProjectionStates.cs プロジェクト: dolittle/Runtime
 FilterDefinition <Projection> CreateKeyFilter(ProjectionKey key) => Builders <Projection> .Filter.Eq(_ => _.Key, key.Value);