Exemple #1
0
        private async Task RunTransactionAsync(Func <CancellationToken, Task> txnFunc, IClientSessionHandle session, IClientSessionHandle parentSession = default(IClientSessionHandle), Action <Behavior> transactionBehaviorAction = default(Action <Behavior>), CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var transactionBehavior = new Behavior();
                transactionBehaviorAction?.Invoke(transactionBehavior);
                transactionBehavior = transactionBehaviorAction == null ? this.configurationSource.Model.TransactionBehavior : default(Behavior);

                if (parentSession != null)
                {
                    session.AdvanceClusterTime(parentSession.ClusterTime);
                    session.AdvanceOperationTime(parentSession.OperationTime);
                }

                session.StartTransaction(transactionBehavior.ToTransactionOptions());
#if NETFULL
                await txnFunc(cancellationToken).ConfigureAwait(false);

                await commitRetryPolicy.ExecuteAsync((cToken) => CommitAsync(session, cToken), cancellationToken).ConfigureAwait(false);
#else
                await txnFunc(cancellationToken);

                await commitRetryPolicy.ExecuteAsync((cToken) => CommitAsync(session, cToken), cancellationToken);
#endif
            }
            catch (Exception)
            {
#if NETFULL
                await session.AbortTransactionAsync(cancellationToken).ConfigureAwait(false);
#else
                await session.AbortTransactionAsync(cancellationToken);
#endif
                throw;
            }
        }
        /// <summary>
        /// Executed on each HTTP request
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            // Should not happen, but let's stay safe
            if (next is null)
            {
                return;
            }

            _logger.LogDebug($"[Transaction] Starting transaction [ID: {_session.ServerSession.Id}]");
            _session.StartTransaction();

            var executedContext = await next.Invoke();

            if (executedContext.Exception is null)
            {
                _logger.LogDebug($"[Transaction] Commiting transaction [ID: {_session.ServerSession.Id}]");
                await _session.CommitTransactionAsync();
            }
            else
            {
                // If an exception happens anywhere, we just abort the transation
                _logger.LogDebug($"[Transaction] Aborting transaction [ID: {_session.ServerSession.Id}]");
                await _session.AbortTransactionAsync();
            }
        }
Exemple #3
0
 public async Task AbortTransactionAsync()
 {
     if (sessionHandle.IsInTransaction)
     {
         await sessionHandle.AbortTransactionAsync();
     }
 }
        public async Task AbortAsync(CancellationToken cancellation = default)
        {
            await _session.AbortTransactionAsync(cancellation);

            _onCompleted(false);
            _isCompleted = true;
        }
Exemple #5
0
        public async Task AddUserAndAddAudit_Abort_UserNull()
        {
            //arrange
            var user = User.CreateSample();

            IMongoDatabase db = _mongoRsResource.CreateDatabase();
            await db.CreateCollectionAsync("users");

            using (IClientSessionHandle session =
                       await _mongoRsResource.Client.StartSessionAsync())
            {
                var repo = new UserRepositoryWithTransaction(db);
                session.StartTransaction();

                //act
                await repo.AddAsync(user, session);

                await session.AbortTransactionAsync();
            }

            //assert
            User createdUser = await GetUserAsync(db, user.Id);

            createdUser.Should().BeNull();
        }
Exemple #6
0
 public async Task AbortTransactionAsync()
 {
     if (_session != null && _session.IsInTransaction)
     {
         await _session?.AbortTransactionAsync();
     }
 }
Exemple #7
0
 internal Task AbortTransactionAsync()
 {
     if (IsInRunningState())
     {
         return(_transactionSession.AbortTransactionAsync());
     }
     return(Task.CompletedTask);
 }
Exemple #8
0
 public async Task RollbackAsync()
 {
     if (_session != null)
     {
         await _session.AbortTransactionAsync();
     }
     _session = null;
 }
Exemple #9
0
 public Task AbortTransactionAsync(CancellationToken cancellationToken = default(CancellationToken))
 {
     if (DotUseTransaction)
     {
         return(Task.FromResult(0));
     }
     return(session.AbortTransactionAsync(cancellationToken));
 }
        public async void RollBackAsync()
        {
            if (_session == null)
            {
                throw new Exception("Session has been gone somehow!");
            }

            await _session.AbortTransactionAsync();
        }
Exemple #11
0
        public async Task RollbackAsync(CancellationToken cancellationToken)
        {
            await EnsureTransaction();

            if (session.IsInTransaction)
            {
                await session.AbortTransactionAsync(cancellationToken);
            }
        }
Exemple #12
0
        public async Task <IActionResult> DeploySimulator(SimulatorDto simulatorDto)
        {
            logger.LogInformation("Deploying simulator...");
            bool simulatorExists = await this.simulatorFamilyRepository.SimulatorExists(simulatorDto.Identifier, simulatorDto.Version);

            if (simulatorExists)
            {
                return(Conflict($"Simulator(Identifier='{simulatorDto.Identifier}', Version={simulatorDto.Version}, NameLanguageKey='{simulatorDto.NameLanguageKey}' already exists."));
            }

            SimulatorFamily family = new SimulatorFamily
            {
                Identifier      = simulatorDto.SimulatorFamilyIdentifier,
                NameLanguageKey = simulatorDto.SimulatorFamilyNameLanguageKey
            };

            Simulator    simulator = this.mapper.Map <Simulator>(simulatorDto);
            List <Scene> scenes    = this.mapper.Map <IEnumerable <Scene> >(simulatorDto.Sections.SelectMany(x => x.Scenes)).ToList();

            scenes.ForEach(scene => { scene.SimulatorIdentifier = simulatorDto.Identifier; scene.SimulatorVersion = simulatorDto.Version; });

            using (IClientSessionHandle session = await this.clientWrapper.Client.StartSessionAsync(new ClientSessionOptions()))
            {
                try
                {
                    session.StartTransaction();
                    await this.sceneRepository.InsertMany(scenes, session);

                    foreach (var sectionDto in simulatorDto.Sections)
                    {
                        var section = simulator.SceneSections.FirstOrDefault(x => x.Identifier == sectionDto.Identifier);
                        foreach (var sceneOfSection in sectionDto.Scenes)
                        {
                            section.SceneIdentifiers.Add(scenes.FirstOrDefault(x => x.Identifier == sceneOfSection.Identifier).Id);
                        }
                    }

                    await this.simulatorFamilyRepository.UpsertAndAddSimulator(family, simulator, session);

                    await session.CommitTransactionAsync();
                }
                catch (Exception)
                {
                    await session.AbortTransactionAsync();

                    throw;
                }
            }


            logger.LogInformation("Deploying simulator finished");
            return(Ok());
        }
Exemple #13
0
        /// <summary>
        /// Async Insert entity
        /// </summary>
        /// <param name="entity">Entity</param>
        public virtual async Task <T> InsertAsync(T entity)
        {
            StartTransaction();
            try
            {
                await _collection.InsertOneAsync(entity);

                await _session.CommitTransactionAsync();

                return(entity);
            }
            catch (Exception)
            {
                await _session.AbortTransactionAsync();

                throw;
            }
        }
        public async Task <OperationResult> ExecuteAsync(CancellationToken cancellationToken)
        {
            try
            {
                await _session.AbortTransactionAsync(cancellationToken).ConfigureAwait(false);

                return(OperationResult.Empty());
            }
            catch (Exception ex)
            {
                return(OperationResult.FromException(ex));
            }
        }
        public async Task <int> SaveAsync()
        {
            try
            {
                await session.CommitTransactionAsync().ConfigureAwait(false);

                return(actions);
            }
            catch
            {
                await session.AbortTransactionAsync().ConfigureAwait(false);

                return(0);
            }
        }
        private static async Task CommitOrAbortTx(IClientSessionHandle session, AppendResult result)
        {
            if (session != null)
            {
                if (result.HadWrongVersion || string.IsNullOrWhiteSpace(result.CommitId) || result.CurrentVersion <= 0)
                {
                    await session.AbortTransactionAsync();
                }
                else
                {
                    await session.CommitTransactionAsync();
                }

                session.Dispose();
            }
        }
Exemple #17
0
            public async Task <Maybe <string> > Handle(CreateVehicleCommand request, CancellationToken cancellationToken)
            {
                //TODO think about IDs
                var vehicleDTO = request.vehicleDTO;

                vehicleDTO.GeneratePopertyIds();

                var vehicle = vehicleMapper.MapToVehicle(vehicleDTO);

                var existingVehiclesCursor = await sparePartsDbContext.Vehicles.FindAsync(v =>
                                                                                          v.ManufacturerName == vehicle.ManufacturerName &&
                                                                                          v.Model == vehicle.Model &&
                                                                                          v.Generation == vehicle.Generation);

                var existingVehicle = await existingVehiclesCursor.ToListAsync();

                if (existingVehicle.Count > 0)
                {
                    return(existingVehicle.FirstOrDefault().Id.ToString());
                }

                var askForSparePartsEvent = new AskForSparePartsPricesIntegrationEvent(vehicleDTO);

                clientSessionHandle.StartTransaction();

                try
                {
                    await sparePartsDbContext.Vehicles.InsertOneAsync(vehicle);

                    await sparePartsIntegrationEventService.PublishThroughEventBusAsync(askForSparePartsEvent);

                    await clientSessionHandle.CommitTransactionAsync();
                }
                catch (Exception ex)
                {
                    logger.Information($"Can`t write to db vehicle: {vehicle.ToJson()} Exception: {ex.Message}");

                    await clientSessionHandle.AbortTransactionAsync();

                    return(Maybe <string> .None);
                }

                return(vehicle.Id.ToString());
            }
Exemple #18
0
        public async Task ApplyChangesAsync(CancellationToken token = default)
        {
            if (_operations.Count > 0)
            {
                IClientSessionHandle session = null;
                if (_connection.UseTransactions)
                {
                    session = _connection.StartSession();
                    session.StartTransaction();
                }

                try
                {
                    while (_operations.Count > 0)
                    {
                        var item = _operations.Dequeue();
                        await item.ProcessAsync(session, token);
                    }

                    if (session != null)
                    {
                        await session.CommitTransactionAsync(token);

                        session.Dispose();
                    }

                    _operations.Clear();
                }
                catch
                {
                    if (session != null)
                    {
                        await session.AbortTransactionAsync(token);

                        session.Dispose();
                    }

                    throw;
                }
            }
        }
Exemple #19
0
        public async Task Append <TInvariant>(IEnumerable <Envelope> envelopes)
        {
            if (!_session.IsInTransaction)
            {
                _session.StartTransaction();
            }

            try {
                await _events.InsertManyAsync(
                    envelopes.Select(e => e.IdentifiedBy(ObjectId.GenerateNewId().ToString())),
                    new InsertManyOptions {
                    IsOrdered = true,
                }
                    );

                await _session.CommitTransactionAsync();
            } catch (Exception error) {
                await _session.AbortTransactionAsync();

                throw;
            }
        }
Exemple #20
0
        private static async Task <CallbackOutcome <TResult> > ExecuteCallbackAsync <TResult>(IClientSessionHandle clientSession, Func <IClientSessionHandle, CancellationToken, Task <TResult> > callbackAsync, DateTime startTime, IClock clock, CancellationToken cancellationToken)
        {
            try
            {
                var result = await callbackAsync(clientSession, cancellationToken).ConfigureAwait(false);

                return(new CallbackOutcome <TResult> .WithResult(result));
            }
            catch (Exception ex)
            {
                if (IsTransactionInStartingOrInProgressState(clientSession))
                {
                    await clientSession.AbortTransactionAsync(cancellationToken).ConfigureAwait(false);
                }

                if (HasErrorLabel(ex, TransientTransactionErrorLabel) && !HasTimedOut(startTime, clock.UtcNow))
                {
                    return(new CallbackOutcome <TResult> .WithShouldRetryTransaction());
                }

                throw;
            }
        }
 public async System.Threading.Tasks.Task RollBackTransaction()
 {
     await session.AbortTransactionAsync();
 }
    public async Task HandleAsync(string messageId, Func <Task> handler)
    {
        if (!Enabled)
        {
            _logger.LogWarning("Outbox is disabled, incoming messages won't be processed.");
            return;
        }

        if (string.IsNullOrWhiteSpace(messageId))
        {
            throw new ArgumentException("Message id to be processed cannot be empty.", nameof(messageId));
        }

        _logger.LogTrace($"Received a message with id: '{messageId}' to be processed.");
        if (await _inboxRepository.ExistsAsync(m => m.Id == messageId))
        {
            _logger.LogTrace($"Message with id: '{messageId}' was already processed.");
            return;
        }

        IClientSessionHandle session = null;

        if (_transactionsEnabled)
        {
            session = await _sessionFactory.CreateAsync();

            session.StartTransaction();
        }

        try
        {
            _logger.LogTrace($"Processing a message with id: '{messageId}'...");
            await handler();

            await _inboxRepository.AddAsync(new InboxMessage
            {
                Id          = messageId,
                ProcessedAt = DateTime.UtcNow
            });

            if (session is not null)
            {
                await session.CommitTransactionAsync();
            }

            _logger.LogTrace($"Processed a message with id: '{messageId}'.");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"There was an error when processing a message with id: '{messageId}'.");
            if (session is not null)
            {
                await session.AbortTransactionAsync();
            }

            throw;
        }
        finally
        {
            session?.Dispose();
        }
    }
Exemple #23
0
 public async Task AbortAsync(CancellationToken cancellation = default)
 {
     await _session.AbortTransactionAsync(cancellation);
 }
Exemple #24
0
 public async Task AbortTransaction()
 {
     await _session.AbortTransactionAsync();
 }
 public async Task RollbackAsync(CancellationToken cancellationToken = default)
 {
     await Session.AbortTransactionAsync(cancellationToken).ConfigureAwait(false);
 }
Exemple #26
0
 public Task AbortTransactionAsync(CancellationToken cancellationToken)
 => _session.AbortTransactionAsync(cancellationToken);
 public async Task AbortAsync(IClientSessionHandle session)
 {
     await session.AbortTransactionAsync();
 }
 public Task Rollback()
 {
     return(_session.AbortTransactionAsync());
 }
Exemple #29
0
 public void Rollback()
 {
     _transactionSession.AbortTransactionAsync();
     _transactionSession.Dispose();
 }
Exemple #30
0
 public override async Task RollbackAsync(CancellationToken cancellationToken = default)
 {
     await _clientSessionHandle.AbortTransactionAsync();
 }