Ejemplo n.º 1
0
        public void TestCorrelationCoreAddOperationAndVerify_RNG_Remove()
        {
            CorrelationContext cc = new CorrelationContext(1337);

            long op1 = cc.AddOperation();
            long op2 = cc.AddOperation();
            long op3 = cc.AddOperation();
            long op4 = cc.AddOperation();

            Assert.AreEqual(5, cc.CurrentOperationPosition.Position);

            long removed = cc.RemoveOperation();

            Assert.AreEqual(op4, removed);

            Assert.AreEqual(4, cc.CurrentOperationPosition.Position);

            string correlationContext = cc.Get();

            string[] parts = correlationContext.Split('|');

            // Assert.AreEqual(Convert.ToBase64String(BitConverter.GetBytes(RootValue)), parts[0]); always random
            Assert.AreEqual(Convert.ToBase64String(BitConverter.GetBytes(op1)), parts[1]);
            Assert.AreEqual(Convert.ToBase64String(BitConverter.GetBytes(op2)), parts[2]);
            Assert.AreEqual(Convert.ToBase64String(BitConverter.GetBytes(op3)), parts[3]);
        }
Ejemplo n.º 2
0
        static bool ProcessMessage(QueueMessage message, int?invisibilityTimeout = null)
        {
            var  messageProcessed = false;
            Guid contextId        = message.CorrelationId.HasValue ? message.CorrelationId.Value : Guid.Empty;

            using (var ctx = new CorrelationContext(contextId))
            {
                switch (message.MessageType)
                {
                case MessageTypes.BeginReplicate:
                    messageProcessed = DoReplicateJob(message, invisibilityTimeout);
                    break;

                case MessageTypes.ReplicateProgress:
                    messageProcessed = DoReplicateProgressJob(message, invisibilityTimeout);
                    break;

                case MessageTypes.DeleteReplica:
                    messageProcessed = DoDeleteReplicaJob(message, invisibilityTimeout);
                    break;

                case MessageTypes.Unknown:
                default:
                    DashTrace.TraceWarning("Unable to process unknown message type from async queue [{0}]. Payload: {1}",
                                           message.MessageType,
                                           message.ToString());
                    // Let this message bounce around for a bit - there may be a different version running
                    // on another instance that knows about this message. It will be automatically discarded
                    // after exceeding the deque limit.
                    messageProcessed = false;
                    break;
                }
            }
            return(messageProcessed);
        }
Ejemplo n.º 3
0
        private Message CreateMessage(string data, EventProperties properties, DateTime?scheduledEnqueueTimeUtc = null)
        {
            Guard.Against(() => properties.EventType == null, () => new ArgumentException("EventType is a required argument"));
            Guard.Against(() => properties.Topic == null, () => new ArgumentException("Topic is a required argument"));
            Guard.Against(() => properties.RoutingKey == null, () => new ArgumentException("RoutingKey is a required argument"));

            properties.MessageId = properties.MessageId ?? Guid.NewGuid().ToString();
            // if the correlationId is not set, set one from the current context
            if (string.IsNullOrEmpty(properties.CorrelationId))
            {
                properties.CorrelationId = CorrelationContext.GetCorrelationId(true);
            }

            var message = new Message(data)
            {
                Header = new Header {
                    Durable = (Settings.Durable == 2)
                },
                ApplicationProperties = new ApplicationProperties(),
                MessageAnnotations    = new MessageAnnotations(),
                Properties            = new Properties {
                    MessageId     = properties.MessageId,
                    GroupId       = properties.EventType,
                    CorrelationId = properties.CorrelationId
                }
            };

            message.ApplicationProperties[Constants.MESSAGE_TYPE_KEY] = properties.EventType;
            if (scheduledEnqueueTimeUtc.HasValue)
            {
                message.MessageAnnotations[new Symbol(Constants.SCHEDULED_ENQUEUE_TIME_UTC)] = scheduledEnqueueTimeUtc;
            }
            return(message);
        }
        public async Task Forward_PropagateAsPredefined_ExpectPredefinedHeader(CorrelationContext correlationContext)
        {
            // arrange
            var incomingHeader      = HttpHeaders.RequestId;
            var outgoindHeader      = "X-MyRequest-Id";
            var propagationSettings = PropagationSettings.PropagateAs(outgoindHeader);

            _correlationContextAccessor
            .Setup(a => a.CorrelationContext)
            .Returns(correlationContext);

            void AssertRequest(HttpRequestMessage r)
            {
                Assert.True(r.Headers.Contains(outgoindHeader));
                Assert.Contains(TestCorrelationId.Value, r.Headers.GetValues(outgoindHeader));
            }

            var handler = CreateMessageHandler(propagationSettings, _correlationContextAccessor, AssertRequest);

            // act & assert (via test delegating handler)
            var client = new HttpClient(handler);

            _ = await client
                .GetAsync("https://www.example.com/")
                .ConfigureAwait(false);
        }
Ejemplo n.º 5
0
        public async Task <object> PostAsync([FromBody] Order order)
        {
            List <OrderItem> ItemsNotSatisfie = new List <OrderItem>();

            foreach (var item in order.Items)
            {
                ItemStockDTO itemStockDTO = await _stockItemServices.GetItemStockAsync(_tenant.TenantId, item.ItemId);

                if (itemStockDTO.Quantity < item.Quantity)
                {
                    ItemsNotSatisfie.Add(item);
                }
            }

            if (ItemsNotSatisfie.Count > 0)
            {
                return(BadRequest("Some items exceed the stock"));
            }
            var @updateStockCommand = new UpdateStockEvent(order.Items.ToList());

            //  _busClient.PublishAsync(updateStockCommand, GetContext<UpdateStockEvent>(), "tenant1");

            var gui = Guid.NewGuid();

            _ = _busClient.PublishAsync(@updateStockCommand, CorrelationContext.Create <UpdateStockEvent>(gui, gui, gui, "origen", gui.ToString(), "", "", ""), _tenant.TenantId);

            _orderRepository.Add(order);
            _orderRepository.SaveChanges();
            return(Ok(""));
        }
Ejemplo n.º 6
0
        public async Task StopAsync()
        {
            try
            {
                CorrelationContext.SetCorrelationId(mainThreadCorrelationId.ToString());

                Log.Information("Stopping {ServiceName} {version}", GetType().Name, GetVersion());

                await StopServiceBusesAsync();
                await StopStartablesAsync();

                StopApplication();

                applicationContainer?.GracefulDispose();
                applicationContainer = null;
                webApp?.Dispose();
                webApp   = null;
                settings = null;
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Unhandled exception while stopping {ServiceName}", GetType().Name);
                throw;
            }
        }
Ejemplo n.º 7
0
        private async Task Invoke(HttpContext httpContext, CorrelationContext correlationContext)
        {
            // emit correlation ID back to caller in response headers
            if (_options.Emit.Settings != HeaderPropagation.NoPropagation)
            {
                httpContext.Response.OnStarting(() => _emitter.Emit(httpContext, correlationContext));
            }

            var correlationId = correlationContext.CorrelationId;

            // assign correlation ID to ASP.NET `TraceIdentifier` property
            // (causes correlation ID to appear in trace logs instead of generated trace ID)
            if (_options.ReplaceTraceIdentifier && !correlationId.IsEmpty)
            {
                _logger.ReplacingTraceIdentifier(httpContext.TraceIdentifier);
                httpContext.TraceIdentifier = correlationId;
            }

            // create logging scope or await next middleware right away
            // (state is shared via scope provider with other logger instances)
            if (_options.LoggingScope.IncludeScope && !correlationId.IsEmpty)
            {
                await InvokeWithLoggingScope(httpContext, _options.LoggingScope.CorrelationKey, correlationId);
            }
            else
            {
                await _next.Invoke(httpContext);
            }
        }
Ejemplo n.º 8
0
        public async Task HandleAsync(CreateRole command, CorrelationContext context)
        {
            using (var connection = _strongHoldDataBase.Get())
            {
                const string sql = @"
                    INSERT INTO [dbo].[Role]
                               ([id], [parentId], [name], [description], [roleContextId], [created], [createdBy], [modified], [modifiedBy])
                         VALUES
                               (@id, @parentId, @name, @description, @roleContextId, @created, @createdBy, @modified, @modifiedBy)";

                await connection.ExecuteAsync(sql, new
                {
                    id            = command.Id,
                    parentId      = command.ParentId.IfEmptyThenEmptyId(),
                    name          = command.Name,
                    description   = command.Description,
                    roleContextId = command.RoleContextId.IfEmptyThenEmptyId(),
                    created       = DateTime.UtcNow.GetUxTime(),
                    createdBy     = context.UserId,
                    modified      = DateTime.UtcNow.GetUxTime(),
                    modifiedBy    = context.UserId
                });
            }

            _logger.LogInformation($"Creating role {command.Id} - {command.Name}");
            await _busPublisher.PublishAsync(new RoleCreated { Id = command.Id, Name = command.Name }, context);
        }
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            HttpContext ctx = _httpContextAccessor.HttpContext;

            if (ctx == null)
            {
                return;
            }

            var httpContextCache = ctx.Items[cacheKey];

            if (httpContextCache == null)
            {
                CorrelationContext correlationContext = _correlationContextAccessor.CorrelationContext;
                if (correlationContext == null)
                {
                    return;
                }

                httpContextCache    = correlationContext.CorrelationId;
                ctx.Items[cacheKey] = httpContextCache;
            }

            logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty(propertyName, httpContextCache, true));
        }
Ejemplo n.º 10
0
        public void FillsCorrelationContextWithApplicationContextIfHeaderNotRequiredAndNotProvided()
        {
            //Arrange
            var loggerMock         = new Moq.Mock <ILogger <CorrelationMiddleware> >();
            var applicationContext = new ApplicationContext("appId", "appName");

            var middleware = new CorrelationMiddleware(next: async(innerHttpContext) => { await innerHttpContext.Response.WriteAsync("test response body"); }, logger: loggerMock.Object, applicationContext: applicationContext);
            var options    = Options.Create <CorrelationOptions>(new CorrelationOptions()
            {
                CorrelationHeaderRequired = false
            });
            var correlationContext = new CorrelationContext(options);
            var httpContext        = new DefaultHttpContext();

            var serviceProvider = new Moq.Mock <IServiceProvider>();

            serviceProvider.Setup((x) => x.GetService(typeof(ICorrelationContext))).Returns(correlationContext);

            httpContext.RequestServices = serviceProvider.Object;

            //Act
            middleware.Invoke(httpContext, options);

            //Assert
            Assert.Equal("appId", correlationContext.SourceId);
        }
        public void SetValuesFirstTime()
        {
            var options      = new CorrelationOptions();
            var context      = new CorrelationContext(Options.Create(options));
            var id           = Guid.NewGuid().ToString();
            var sourceId     = Guid.NewGuid().ToString();
            var sourceName   = "appName";
            var instanceId   = Guid.NewGuid().ToString();
            var instanceName = "appName-instanceName";
            var userId       = "userId";
            var ipAddress    = "194.25.76.122";

            var result = context.TrySetValues(id, sourceId, sourceName, instanceId, instanceName, userId, ipAddress);

            Assert.True(result);
            Assert.Equal(id, context.Id);
            Assert.Equal(sourceId, context.SourceId);
            Assert.Equal(sourceName, context.SourceName);
            Assert.Equal(instanceId, context.InstanceId);
            Assert.Equal(instanceName, context.InstanceName);
            Assert.Equal(userId, context.UserId);
            Assert.Equal(ipAddress, context.IpAddress);

            byte[]  data         = Convert.FromBase64String(context.DgpHeader);
            string  json         = Encoding.UTF8.GetString(data);
            dynamic parsedHeader = JObject.Parse(json);

            Assert.Equal(id, (string)parsedHeader.id);
            Assert.Equal(sourceId, (string)parsedHeader.sourceId);
            Assert.Equal(sourceName, (string)parsedHeader.sourceName);
            Assert.Equal(instanceId, (string)parsedHeader.instanceId);
            Assert.Equal(instanceName, (string)parsedHeader.instanceName);
            Assert.Equal(userId, (string)parsedHeader.userId);
            Assert.Equal(ipAddress, (string)parsedHeader.ipAddress);
        }
Ejemplo n.º 12
0
        protected override async Task ExecuteIntervalAsync()
        {
            var correlationId = CorrelationContext.GetCorrelationId();

            // run something async in async method
            await Task.Run(() => logger.LogInformation($"CorrelationId: {correlationId}")).ConfigureAwait(false);
        }
        public async Task Invoke_ValidInput_AddsAllTheAttributesToLoggerContext()
        {
            // arrange
            var autoMocker     = new AutoMocker();
            var sut            = autoMocker.CreateInstance <RequestLoggerContextMiddleware>();
            var logger         = new Mock <ILogger <RequestLoggerContextMiddleware> >();
            var httpContext    = new Mock <HttpContext>();
            var connectionInfo = new Mock <ConnectionInfo>();

            httpContext.Setup(s => s.Connection).Returns(connectionInfo.Object);
            var request = Mock.Of <HttpRequest>();

            request.Path = new PathString("/test");
            httpContext.Setup(s => s.Request).Returns(request);
            connectionInfo.Setup(s => s.RemoteIpAddress).Returns(new System.Net.IPAddress(34));
            var correlationContextAccessor = new Mock <ICorrelationContextAccessor>();
            var correlationId      = Guid.NewGuid().ToString();
            var correlationContext = new CorrelationContext(correlationId, "test header");

            correlationContextAccessor.Setup(s => s.CorrelationContext).Returns(correlationContext);
            var configuration = autoMocker.GetMock <IConfiguration>();

            configuration.Setup(s => s.GetSection(It.IsAny <string>())).Returns(Mock.Of <IConfigurationSection>());

            // act
            await sut.Invoke(httpContext.Object, logger.Object, correlationContextAccessor.Object, configuration.Object);

            // assert
            logger.VerifyDebug($"Executing {nameof(RequestLoggerContextMiddleware)} ...");
            logger.VerifyDebug($"Executed {nameof(RequestLoggerContextMiddleware)}");
        }
Ejemplo n.º 14
0
        public async Task ShouldSetCorrelationId()
        {
            var correlationId = Guid.NewGuid().ToString();

            CorrelationContext.SetCorrelationId(Guid.NewGuid().ToString());

            var intValue = int.MaxValue;
            await publisher.PublishAsync(new TestEvent()
            {
                IntValue = intValue
            }, correlationId).ConfigureAwait(false);

            await Task.Delay(2000).ConfigureAwait(false);

            Assert.False(broker.HasItems);
            var messages = broker.GetAcceptedMessagesByType <TestEvent>();

            Assert.NotNull(messages);
            Assert.Equal(intValue, messages.First().IntValue);

            // test the filter
            messages = broker.GetAcceptedMessagesByType <TestEvent>(x => x.IntValue == intValue);
            Assert.NotNull(messages);
            Assert.Equal(intValue, messages.First().IntValue);
        }
        public void AddsCorrelationHeaderWithContext()
        {
            var client             = new HttpClient();
            var options            = new CorrelationOptions();
            var correlationContext = new CorrelationContext(Utilities.Options.Create(options));

            var id           = Guid.NewGuid().ToString();
            var sourceId     = Guid.NewGuid().ToString();
            var sourceName   = "testSource";
            var instanceId   = Guid.NewGuid().ToString();
            var instanceName = "testSource-instanceName";
            var userId       = "userId";
            var ipAddress    = "194.25.76.122";

            correlationContext.TrySetValues(id, sourceId, sourceName, instanceId, instanceName, userId, ipAddress);

            client.SetCorrelationValues(CreateServiceProvider(correlationContext, options));

            var result = client.DefaultRequestHeaders.Single(h => h.Key == CorrelationHeaders.HeaderKey);

            Assert.NotEqual(default(KeyValuePair <string, IEnumerable <string> >), result);
            byte[] data = Convert.FromBase64String(result.Value.Single());
            string json = Encoding.UTF8.GetString(data);

            dynamic parsedHeader  = JObject.Parse(json);
            string  correlationId = (string)parsedHeader.id;

            Assert.Equal(id, (string)parsedHeader.id);
            Assert.Equal(sourceId, (string)parsedHeader.sourceId);
            Assert.Equal(sourceName, (string)parsedHeader.sourceName);
            Assert.Equal(instanceId, (string)parsedHeader.instanceId);
            Assert.Equal(instanceName, (string)parsedHeader.instanceName);
            Assert.Equal(userId, (string)parsedHeader.userId);
            Assert.Equal(ipAddress, (string)parsedHeader.ipAddress);
        }
Ejemplo n.º 16
0
        public async Task <IActionResult> Deposit(
            [FromBody] DepositRequest request,
            CancellationToken token)
        {
            var query = new DepositCommand(
                request.AccountNumber,
                request.Amount,
                CorrelationContext.Get());
            var response = await _mediator
                           .Send(
                query,
                token);

            if (!response
                .ValidationResult
                .IsValid)
            {
                var errors = string.Empty;
                response
                .ValidationResult
                .Errors
                .ToList()
                .ForEach(e => { errors += $"{e}//r//n"; });
                return(BadRequest(errors));
            }

            return(Ok(new DepositView(
                          response.Balance)));
        }
Ejemplo n.º 17
0
        public void SetPropertiesFromDgpHeaderReturnsCorrelationContext()
        {
            var context = new CorrelationContext
            {
                Id           = Guid.NewGuid().ToString(),
                SourceId     = Guid.NewGuid().ToString(),
                SourceName   = "appName",
                InstanceId   = Guid.NewGuid().ToString(),
                InstanceName = "appName-instanceName",
                UserId       = "userId",
                IpAddress    = "194.25.76.122"
            };

            context.SetDgpHeader();
            var logger           = new Moq.Mock <ILogger <CorrelationContextFormatter> >().Object;
            var contextFormatter = new CorrelationContextFormatter(logger);

            var result = contextFormatter.ValidateAndSetPropertiesFromDgpHeader(context.DgpHeader);

            Assert.Equal(result.Id, context.Id);
            Assert.Equal(result.SourceId, context.SourceId);
            Assert.Equal(result.SourceName, context.SourceName);
            Assert.Equal(result.InstanceId, context.InstanceId);
            Assert.Equal(result.InstanceName, context.InstanceName);
            Assert.Equal(result.UserId, context.UserId);
            Assert.Equal(result.IpAddress, context.IpAddress);
        }
        public async Task Invoke(HttpContext httpContex)
        {
            var value = httpContex.Request.Headers.TryGetValue(CorrelationContext.CorrelationIdName, out var correlationIds) ? correlationIds.Single() : null;

            CorrelationContext.SetCorrelationId(value);

            await next(httpContex);
        }
Ejemplo n.º 19
0
        public async Task <ActionResult> CreatePersonReportsByLocation(CreatePersonReportsByLocationCommand command)
        {
            var context = CorrelationContext.Create(Guid.NewGuid(), command.PersonId);

            await BusPublisher.SendAsync(command, context);

            return(Accepted(context));
        }
Ejemplo n.º 20
0
        public override Task Invoke(IOwinContext context)
        {
            var value = context.Request.Headers.TryGetValue(CorrelationContext.CorrelationIdName, out var correlationIds) ? correlationIds.Single() : null;

            CorrelationContext.SetCorrelationId(value);

            return(Next.Invoke(context));
        }
Ejemplo n.º 21
0
        public void RequestIdValid()
        {
            var tId = Guid.NewGuid().ToString();
            var rId = Guid.NewGuid().ToString();
            var ctx = new CorrelationContext(tId, rId);

            Assert.Equal(rId, ctx.RequestId);
        }
Ejemplo n.º 22
0
        public async Task HandleAsync(SynchronizationAcceptedEvent @event, ISagaContext sagaContext)
        {
            logger.LogInformation($"{nameof(@event)} ({sagaContext.CorrelationId}) {this.GetType()}");

            await busPublisher.SendAsync(
                new MergeSynchronizationDataCommand(),
                CorrelationContext.Create(sagaContext.CorrelationId));
        }
        public async Task <IActionResult> Post([FromBody] CreateReservation command)
        {
            var context = new CorrelationContext(Guid.NewGuid(), command.UserId, "reservations",
                                                 _tracer.ActiveSpan.Context.ToString());
            await _busPublisher.SendAsync(command, context);

            return(Accepted($"reservations/{context.Id}"));
        }
Ejemplo n.º 24
0
        protected CorrelationContext GetContext <T>(Guid?resourceId = null, string resource = "") where T : ICommand
        {
            if (!string.IsNullOrWhiteSpace(resource))
            {
                resource = $"{resource}/{resourceId}";
            }

            return(CorrelationContext.Create <T>(Guid.NewGuid(), Guid.NewGuid(), resourceId ?? Guid.Empty, Request.Path.ToString(), Culture, resource));
        }
Ejemplo n.º 25
0
        protected ICorrelationContext GetContext <T>(Guid?resourceId = null, string resource = "") where T : ICommand
        {
            if (!string.IsNullOrWhiteSpace(resource))
            {
                resource = $"{resource}/{resourceId}";
            }

            return(CorrelationContext.Create <T>(Guid.NewGuid(), UserId, resourceId ?? Guid.Empty));
        }
Ejemplo n.º 26
0
        private void SetHeaderKeysFromOptions()
        {
            var options = new CorrelationOptions();

            var context = new CorrelationContext(Options.Create(options));

            Assert.Equal(options.IdHeaderKey, context.IdHeaderKey);
            Assert.Equal(options.SourceHeaderKey, context.SourceHeaderKey);
        }
        public async Task HandleAsync(CreaterUserCommand command, CorrelationContext correlationContext)
        {
            var usercom = new Users {
                FirstName = command.first_name, LastName = command.last_name, Username = command.username
            };


            repo.Save(usercom);
        }
Ejemplo n.º 28
0
        public void you_can_run_a_func_which_returns_something_with_it()
        {
            var context = new CorrelationContext();

            var result = context.Run(() => 1);

            Assert.True(result == 1,
                        $"Expected result to have the value 1 (because it was returned) but was <{result}>");
        }
Ejemplo n.º 29
0
        public void CorrelationIdValid()
        {
            var tId = Guid.NewGuid().ToString();
            var ctx = new CorrelationContext(tId);

            Assert.Equal(tId, ctx.CorrelationId);
            Assert.Null(ctx.RequestId);
            Assert.Equal(2, ctx.Count);
        }
Ejemplo n.º 30
0
        public void ChildContextNull()
        {
            var ctx = new CorrelationContext(Guid.NewGuid().ToString());

            var request  = new HttpRequestMessage();
            var childCtx = ctx.GetChildRequestContext(request.GetChildRequestId());

            Assert.Equal(2, childCtx.Count);
        }