Beispiel #1
0
        public void MiddlewareShouldBeCalledOnDispatch()
        {
            var count = 0;

            // This middleware just simply increase count variable
            // whenever Dispatch is count
            MiddlewareDelegate <int> countingMiddleware = _ => {
                return(dispatcher => action => {
                    ++count;
                    dispatcher.Invoke(action);
                    return action;
                });
            };

            var store = new SimpleStore(0, countingMiddleware);

            store.Dispatch(new CountAction());
            Assert.AreEqual(1, count);

            store.Dispatch(new AddAction()
            {
                amount = 5
            });
            Assert.AreEqual(2, count);

            store.Dispatch(new CountAction());
            Assert.AreEqual(3, count);
        }
Beispiel #2
0
        public void StoreShouldUseMiddlewareModifiedAction()
        {
            // This is an evil middleware that basically replace all actions
            // to CountAction instead.
            MiddlewareDelegate <int> replaceAllActionToCountMiddleware = _ => {
                return(dispatcher => action => {
                    var newAction = new CountAction();
                    dispatcher.Invoke(newAction);
                    return newAction;
                });
            };

            var store = new SimpleStore(0, replaceAllActionToCountMiddleware);

            Assert.AreEqual(0, store.GetState());

            store.Dispatch(new CountAction());
            Assert.AreEqual(1, store.GetState());

            store.Dispatch(new AddAction()
            {
                amount = 5
            });
            Assert.AreEqual(2, store.GetState());

            // Even on actions that normally not recognized
            store.Dispatch(new UnrecognizedAction());
            Assert.AreEqual(3, store.GetState());
        }
Beispiel #3
0
        private async Task Dispatch(IMessageContext context, MiddlewareDelegate next)
        {
            try
            {
                var batchContext = new BatchConsumeMessageContext(
                    context.WorkerId,
                    context.GroupId,
                    context.Consumer,
                    this.batch.ToList());

                await next(batchContext).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                this.logHandler.Error(
                    "Error executing a message batch",
                    ex,
                    new
                {
                    context.Topic,
                    context.GroupId,
                    context.WorkerId
                });
            }
            finally
            {
                foreach (var messageContext in this.batch)
                {
                    messageContext.Consumer.StoreOffset();
                }

                this.dispatchTask = null;
                this.batch.Clear();
            }
        }
Beispiel #4
0
        public async Task Invoke(IMessageContext context, MiddlewareDelegate next)
        {
            var cancellationToken = context.Consumer.WorkerStopped;

            context.Consumer.ShouldStoreOffset = false;

            do
            {
                cancellationToken.ThrowIfCancellationRequested();

                try
                {
                    await next(context);

                    context.Consumer.ShouldStoreOffset = true;

                    return;
                }
                catch (OperationCanceledException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    this.SafeErrorHandler("Error processing message.", ex, context);

                    // Wait before next attempt.
                    await Task.Delay(this.retryDelay, cancellationToken);
                }
            }while (true);
        }
        private async Task Dispatch(IMessageContext context, MiddlewareDelegate next)
        {
            var localBatch = Interlocked.Exchange(ref this.batch, new(this.batchSize));

            try
            {
                var batchContext = new BatchConsumeMessageContext(context.ConsumerContext, localBatch);

                await next(batchContext).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                this.logHandler.Error(
                    "Error executing a message batch",
                    ex,
                    new
                {
                    context.ConsumerContext.Topic,
                    context.ConsumerContext.GroupId,
                    context.ConsumerContext.WorkerId,
                });
            }
            finally
            {
                foreach (var messageContext in localBatch)
                {
                    messageContext.ConsumerContext.StoreOffset();
                }
            }
        }
Beispiel #6
0
        public XSLTransformContentMiddleWare(
            MiddlewareDelegate <CFTFileContext> next,
            ILogger <XSLTransformContentMiddleWare> logger,
            XSLTransformContentOptions options)
            : base(next, logger)
        {
            try
            {
                options.ValidationParams();
            }
            catch (Exception e)
            {
                throw new CFTConfigurationException("Ошибка при конфигурации модуля XSLT преобразования.", e);
            }

            _transform = new XslCompiledTransform();
            try
            {
                _transform.Load(options.XSLTPath);
            }
            catch (Exception e)
            {
                throw new CFTConfigurationException("Что-то пошло не так во время загрузки XSLT файла.", e);
            }
            _options = options;
        }
Beispiel #7
0
 public LogMiddlewareBase(
     MiddlewareDelegate <CFTFileContext> next,
     ILogger logger)
 {
     _next   = next ?? throw new ArgumentNullException(nameof(next));
     _logger = logger ?? throw new ArgumentNullException(nameof(logger));
 }
        public ValidateByXSDMiddleWare(
            MiddlewareDelegate <CFTFileContext> next,
            ILogger <ValidateByXSDMiddleWare> logger,
            IValidateByXSDOptions options)
            : base(next, logger)
        {
            try
            {
                options.ValidationParams();

                try
                {
                    _schemas.Add(options.TargetNamespace, options.XSDPath);
                }
                catch (Exception e)
                {
                    throw new XSDFileFormatException(options.XSDPath, e);
                }
            }
            catch (Exception e)
            {
                throw new XSDModuleConfigurationException(e);
            }

            _option = options;
        }
Beispiel #9
0
        /// <summary>
        /// Deserializes the message using the passed serialized
        /// </summary>
        /// <param name="context">The <see cref="IMessageContext"/> containing the message and metadata</param>
        /// <param name="next">A delegate to the next middleware</param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException">Throw if message is not byte[]</exception>
        public async Task Invoke(IMessageContext context, MiddlewareDelegate next)
        {
            var messageType = this.typeResolver.OnConsume(context);

            if (messageType is null)
            {
                return;
            }

            if (context.Message.Value is null)
            {
                await next(context).ConfigureAwait(false);

                return;
            }

            if (context.Message.Value is not byte[] rawData)
            {
                throw new InvalidOperationException(
                          $"{nameof(context.Message)} must be a byte array to be deserialized and it is '{context.Message.GetType().FullName}'");
            }

            using var stream = new MemoryStream(rawData);

            var data = await this.serializer
                       .DeserializeAsync(
                stream,
                messageType,
                SerializerContext.Empty)
                       .ConfigureAwait(false);

            await next(context.SetMessage(context.Message.Key, data)).ConfigureAwait(false);
        }
Beispiel #10
0
        public LogMiddleware(
            MiddlewareDelegate <CFTFileContext> next,
            ILogger <LogMiddleware> logger,
            string startMessage,
            string endSuccessMessage,
            string endErrorMessage)
        {
            if (string.IsNullOrEmpty(startMessage))
            {
                throw new ArgumentNullException(nameof(startMessage));
            }
            if (string.IsNullOrEmpty(endSuccessMessage))
            {
                throw new ArgumentNullException(nameof(endSuccessMessage));
            }
            if (string.IsNullOrEmpty(endErrorMessage))
            {
                throw new ArgumentNullException(nameof(endErrorMessage));
            }

            _next              = next ?? throw new ArgumentNullException(nameof(next));
            _logger            = logger ?? throw new ArgumentNullException(nameof(logger));
            _startMessage      = startMessage;
            _endSuccessMessage = endSuccessMessage;
            _endErrorMessage   = endErrorMessage;
        }
        private static MiddlewareDelegate <TContext> CreateMiddleware <TContext>(MiddlewareDelegate <TContext> next, MiddlewareBranch <TContext>[] branches) where TContext : Context
        {
            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            if (branches == null)
            {
                throw new ArgumentNullException(nameof(branches));
            }

            return(BranchMiddleware);

            async Task BranchMiddleware(TContext context)
            {
                bool goNext = true;

                foreach (var branch in branches)
                {
                    if (branch.IsApplicable(context))
                    {
                        await branch.Branch(context);

                        goNext = false;
                        break;
                    }
                }

                if (goNext)
                {
                    await next(context); // continue after all routes failed
                }
            };
        }
Beispiel #12
0
        public async Task Invoke(IMessageContext context, MiddlewareDelegate next)
        {
            var handlers = this.configuration
                           .HandlerMapping
                           .GetHandlersTypes(context.Message.Value.GetType());

            if (!handlers.Any())
            {
                this.configuration.OnNoHandlerFound(context);
            }
            else
            {
                await Task.WhenAll(
                    handlers
                    .Select(
                        handler =>
                        HandlerExecutor
                        .GetExecutor(context.Message.Value.GetType())
                        .Execute(
                            this.dependencyResolver.Resolve(handler),
                            context,
                            context.Message.Value)))
                .ConfigureAwait(false);
            }

            await next(context).ConfigureAwait(false);
        }
Beispiel #13
0
        public async Task AddAsync(IMessageContext context, MiddlewareDelegate next)
        {
            await this.semaphore.WaitAsync().ConfigureAwait(false);

            try
            {
                this.batch.Add(context);

                if (this.batch.Count < this.batch.Capacity)
                {
                    this.dispatchTask ??= this.ScheduleDispatch(context, next);
                    return;
                }

                this.cancelScheduleTokenSource.Cancel();
            }
            finally
            {
                this.semaphore.Release();
            }

            // stores the Task in a local variable to avoid NullReferenceException in case the schedule Task ends before the await below
            var localTask = this.dispatchTask;

            if (localTask != null)
            {
                await localTask.Unwrap().ConfigureAwait(false);
            }
        }
 /// <summary>
 /// Creates a new instance of <see cref="MapWhenExceptionMiddleware"/>.
 /// </summary>
 /// <param name="next">The delegate representing the next middleware in the request pipeline.</param>
 /// <param name="options">The middleware options.</param>
 public MapWhenExceptionMiddleware(
     MiddlewareDelegate <TContext> next,
     MapWhenExceptionOptions <TContext> options)
 {
     _next    = next ?? throw new ArgumentNullException(nameof(next));
     _options = options ?? throw new ArgumentNullException(nameof(options));
 }
Beispiel #15
0
 public async Task ReceiveAsync(HubConnectionContext context, MiddlewareDelegate next)
 {
     using (var stream = new CryptoStream(context.Stream, new FromBase64Transform(), CryptoStreamMode.Read))
     {
         await next(new HubConnectionContext(
                        context.Connection,
                        stream));
     }
 }
        /// <summary>
        /// Adds a middleware delegate to the store's dispatch pipeline.
        /// </summary>
        /// <param name="middleware">The middleware delegate.</param>
        /// <returns>The <see cref="IStoreBuilder{TState}"/> instance.</returns>
        public IStoreBuilder <TState> UseMiddleware(MiddlewareDelegate <TState> middleware)
        {
            if (middleware == null)
            {
                throw new ArgumentNullException(nameof(middleware));
            }

            _middlewares.Add(middleware);
            return(this);
        }
        /// <summary>
        /// Serializes message based on message type resolver strategy
        /// </summary>
        /// <param name="context">The <see cref="IMessageContext"/> containing the message and metadata</param>
        /// <param name="next">A delegate to call next middleware</param>
        /// <returns></returns>
        public Task Invoke(IMessageContext context, MiddlewareDelegate next)
        {
            this.typeResolver.OnProduce(context);

            var data = this.serializer.Serialize(context.Message);

            context.TransformMessage(data);

            return(next(context));
        }
Beispiel #18
0
        public Task Invoke(IMessageContext context, MiddlewareDelegate next)
        {
            var workerBatch = this.batches.GetOrAdd(
                context.WorkerId,
                _ => this.workerBatchFactory.Create(this.batchSize, this.batchTimeout, this.logHandler));

            context.Consumer.ShouldStoreOffset = false;

            return(workerBatch.AddAsync(context, next));
        }
Beispiel #19
0
 public async Task SendAsync(ConnectionContext context, MiddlewareDelegate next)
 {
     using (var reader = new StreamReader(context.Stream))
     {
         var data = Encoding.UTF8.GetBytes(await reader.ReadToEndAsync());
         using (var txStream = new MemoryStream(Encoding.UTF8.GetBytes(Convert.ToBase64String(data))))
         {
             await next(new ConnectionContext(context.Connection, txStream));
         }
     }
 }
Beispiel #20
0
 public async Task ReceiveAsync(ConnectionContext context, MiddlewareDelegate next)
 {
     using (var reader = new StreamReader(context.Stream))
     {
         var data = Convert.FromBase64String(await reader.ReadToEndAsync());
         using (var stream = new MemoryStream(data))
         {
             await next(new ConnectionContext(context.Connection, stream));
         }
     }
 }
Beispiel #21
0
        public async Task SendAsync(Stream stream)
        {
            var context  = new ConnectionContext(Connection, stream);
            var iterator = Middleware.GetEnumerator();
            MiddlewareDelegate delegator = BuildMiddlewareDelegate(iterator, InternalSendAsync);

            await delegator
            .Invoke(context)
            .ContinueWith(task => iterator.Dispose())
            .ConfigureAwait(false);
        }
 public BackupInputFileMiddleware(
     MiddlewareDelegate <CFTFileContext> next,
     ILogger <BackupInputFileMiddleware> logger,
     string backupPath)
     : base(next, logger)
 {
     if (string.IsNullOrWhiteSpace(backupPath))
     {
         throw new ArgumentException("Не указан каталог для бэкапа.");
     }
     _backupPath = backupPath;
 }
        /// <inheritdoc />
        public Task Invoke(IMessageContext context, MiddlewareDelegate next)
        {
            if (!(context.Message.Value is byte[] rawData))
            {
                throw new InvalidOperationException(
                          $"{nameof(context.Message.Value)} must be a byte array to be decompressed and it is '{context.Message.Value.GetType().FullName}'");
            }

            var data = this.compressor.Decompress(rawData);

            return(next(context.SetMessage(context.Message.Key, data)));
        }
Beispiel #24
0
        public Task Invoke(IMessageContext context, MiddlewareDelegate next)
        {
            var batch = context.GetMessagesBatch();

            var text = string.Join(
                '\n',
                batch.Select(ctx => ((SampleBatchMessage)ctx.Message.Value).Text));

            Console.WriteLine(text);

            return(Task.CompletedTask);
        }
        public async Task Invoke(IMessageContext context, MiddlewareDelegate next)
        {
            try
            {
                await next(context);
            }
            catch
            {
                // Muttley, do something!

                throw;
            }
        }
        public MiddlewareDelegate <TContext> Build()
        {
            _factories.Reverse();

            MiddlewareDelegate <TContext> current = TerminalMiddleware; // safeguard

            foreach (var middlewareFactory in _factories)
            {
                current = middlewareFactory(current);
            }

            return(current);
        }
Beispiel #27
0
        //{
        //    return new MiddlewareBuilder<TContext>(this);
        //}

        public MiddlewareDelegate <TContext> Build(MiddlewareDelegate <TContext> defaultDelegate)
        {
            MiddlewareDelegate <TContext> app = defaultDelegate ?? (context =>
            {
                return(Task.CompletedTask);
            });

            foreach (var component in _components.Reverse())
            {
                app = component(app);
            }

            return(app);
        }
        public async Task ProcessAllAsync(MiddlewareDelegate <CFTFileContext> applicationFlow)
        {
            try
            {
                _logger.LogInformation("Начинаем обработку файлов в каталоге.");
                await _component.ProcessAllAsync(applicationFlow);

                _logger.LogInformation("Файлы обработаны.");
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Ошибка обработки файлов.");
                throw;
            }
        }
        public void DefaultEndpointBuilder_Build_WithMiddlwareDelegate()
        {
            // arange
            MiddlewareDelegate <Context> x = (context) => Task.CompletedTask;

            var endpoint = new DefaultEndpointBuilder <Context>(null)
                           // act
                           .WithMiddlewareDelegate(x)
                           .Build();

            // assert
            Assert.NotNull(endpoint.MiddlewareDelegate);
            Assert.Same(x, endpoint.MiddlewareDelegate);
            Assert.Null(endpoint.DisplayName);
            Assert.Empty(endpoint.Metadata);
        }
Beispiel #30
0
        /// <summary>
        /// Inserts the <see cref="MiddlewareDelegate"/> as the last node in the collection.
        /// </summary>
        /// <param name="array">The <see cref="MiddlewareDelegate"/> array of filters.</param>
        /// <param name="filter">The <see cref="MiddlewareDelegate"/> to insert.</param>
        public static MiddlewareDelegate[] Append(this MiddlewareDelegate[] array, MiddlewareDelegate filter)
        {
            if (array == null)
            {
                return(new MiddlewareDelegate[] { filter });
            }

            MiddlewareDelegate[] result = new MiddlewareDelegate[array.Length + 1];
            for (int i = 0; i < array.Length; i++)
            {
                result[i] = array[i];
            }

            result[array.Length] = filter;
            return(result);
        }