Example #1
0
 public Bus(
     BusOptions options,
     ILogger <Bus> logger,
     IStorageApiWrapper storageApiWrapper,
     ILifetimeScope lifetimeScope,
     IClock clock)
 {
     _busOptions              = options;
     _logger                  = logger;
     _storageApiWrapper       = storageApiWrapper;
     _lifetimeScope           = lifetimeScope;
     _clock                   = clock;
     MessageHandlerCollection = new MessageHandlerCollection(_clock);
     BusId = RandomIdHelper.GetId();
 }
Example #2
0
 public static async Task SendResponse <TResponse>(this IBus dispatcher, Task <TResponse> responseTask,
                                                   BusMessage requestMessage)
     where TResponse : IResponse
 {
     var resp            = await responseTask;
     var parentId        = requestMessage.MessageId;
     var requestTypeName = typeof(TResponse).Name;
     var channelMessage  = new BusMessage
     {
         MessageId       = RandomIdHelper.GetId(),
         MessageType     = requestTypeName,
         PayloadJson     = JsonSerializer.Serialize((object)resp !),
         ParentMessageId = parentId
     };
     await dispatcher.SendMessage(channelMessage);
 }
Example #3
0
    public static async Task <TResponse> SendRequest <TRequest, TResponse>(this IBus dispatcher,
                                                                           TRequest request)
        where TRequest : IRequest
        where TResponse : IResponse
    {
        var requestTypeName  = typeof(TRequest).Name;
        var responseTypeName = typeof(TResponse).Name;

        var channelMessage = new BusMessage
        {
            MessageId   = RandomIdHelper.GetId(),
            MessageType = requestTypeName,
            PayloadJson = JsonSerializer.Serialize((object)request)
        };
        var tcs = new TaskCompletionSource <TResponse>();

        dispatcher.RegisterHandler(responseTypeName, (scope, responseMessage) =>
        {
            if (responseMessage.ParentMessageId == channelMessage.MessageId)
            {
                var payloadJson = responseMessage.PayloadJson;
                if (string.IsNullOrEmpty(payloadJson))
                {
                    return(false);
                }

                var result = (TResponse)JsonSerializer.Deserialize(payloadJson, typeof(TResponse)) !;
                tcs.TrySetResult(result);
                return(true);
            }

            return(false);
        }, channelMessage.MessageId);
        await dispatcher.SendMessage(channelMessage);

        var delay      = Task.Delay(TimeSpan.FromSeconds(Bus.DefaultExpiredDuration));
        var resultTask = await Task.WhenAny(delay, tcs.Task);

        if (resultTask == delay)
        {
            tcs.TrySetException(new TimeoutException());
        }

        return(tcs.Task.Result);
    }