示例#1
0
        public async Task <JimuRemoteCallResultData> SendAsync(JimuRemoteCallData data)
        {
            try
            {
                _logger.Debug($"prepare sending: {data.ServiceId}");
                var transportMsg = new JimuTransportMsg(data);
                var callbackTask = RegisterResultCallbackAsync(transportMsg.Id);
                try
                {
                    await DoSendAsync(transportMsg);

                    _logger.Debug($"succed to send: {data.ServiceId}, msg: {transportMsg.Id}");
                    return(await callbackTask);
                }
                catch (Exception ex)
                {
                    _logger.Error($"error occur when connecting with server, serviceid: {data.ServiceId}", ex);
                    throw;
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"failed to send: {data.ServiceId}", ex);
                throw new TransportException(ex.Message, ex);
            }
        }
示例#2
0
        private IByteBuffer GetByteBuffer(JimuTransportMsg message)
        {
            var data   = JimuHelper.Serialize <byte[]>(message);
            var buffer = Unpooled.Buffer(data.Length, data.Length);

            return(buffer.WriteBytes(data));
        }
示例#3
0
        protected override async Task DoSendAsync(JimuTransportMsg msg)
        {
            var invokeMessage = msg.GetContent <JimuRemoteCallData>();
            var uri           = $"http://{_address.CreateEndPoint()}/{invokeMessage.Descriptor.RoutePath}";

            //if (invokeMessage.Descriptor.HttpMethod() == "get" || invokeMessage.Descriptor.HttpMethod() == null)
            //{
            foreach (var para in invokeMessage.Parameters)
            {
                uri.SetQueryParam(para.Key, para.Value);
            }
            //var ret = await uri.SendJsonAsync(HttpMethod.Get, msg);
            //var str = await ret.Content.ReadAsStringAsync();
            var result = await uri.SendJsonAsync(HttpMethod.Get, msg).ReceiveJson <JimuTransportMsg>();

            //result = await uri.GetJsonAsync<RemoteInvokeResultMessage>();

            //return new RemoteInvokeResultMessage { Result = result, ResultType = result.GetType().ToString() };
            //}
            //else if (invokeMessage.Descriptor.HttpMethod() == "post")
            //{
            //    switch (invokeMessage.Descriptor.HttpContentType())
            //    {
            //        case "application/json":
            //        case null:
            //            result = await uri.PostJsonAsync(invokeMessage.Parameters).ReceiveJson<TransportMessage>();
            //            break;
            //        case "application/x-www-form-urlencoded":
            //            result = await uri.PostUrlEncodedAsync(invokeMessage.Parameters).ReceiveJson<TransportMessage>();
            //            break;
            //        case "text/plain":
            //            StringBuilder paraSb = new StringBuilder();
            //            foreach (var para in invokeMessage.Parameters)
            //            {
            //                paraSb.Append($"{para.Key}={para.Value}&");
            //            }
            //            result = await uri.PostStringAsync(paraSb.Length > 0 ? paraSb.ToString().TrimEnd('&') : "").ReceiveJson<TransportMessage>();
            //            break;
            //        case "multipart/form-data":
            //            var ret = await uri.PostMultipartAsync((bc) =>
            //            {
            //                foreach (var para in invokeMessage.Parameters)
            //                {
            //                    if (para.Value.GetType().IsAssignableFrom(typeof(HttpContent)))
            //                    {
            //                        bc.Add((HttpContent)para.Value);
            //                    }
            //                    //bc.Add(para.Key, (HttpContent)para.Value);
            //                }
            //            });
            //            result = TransportMessage.Create(msg.Id, new RemoteInvokeResultMessage { Result = ret });
            //            break;
            //        default:
            //            result = TransportMessage.Create(msg.Id, new RemoteInvokeResultMessage { ErrorCode = "501", ErrorMsg = "not support media type" });
            //            break;
            //    }
            //}
            //result = new RemoteInvokeResultMessage { ErrorCode = "501", ErrorMsg = "not support media type" };
            await _clientListener.Received(result);
        }
示例#4
0
        private async Task OnReceived(IChannelHandlerContext channel, JimuTransportMsg message)
        {
            _logger.Debug($"begin handling msg: {message.Id}");
            //TaskCompletionSource<TransportMessage> task;
            if (message.ContentType == typeof(JimuRemoteCallData).FullName)
            {
                IResponse response    = new DotNettyResponse(channel, _logger);
                var       thisContext = new ServiceInvokerContext(message, _serviceEntryContainer, response, _logger, _serviceInvokeAddress);
                Guid      operationId = Guid.Empty;

                var lastInvoke = new RequestDel(async context =>
                {
                    JimuRemoteCallResultData resultMessage = new JimuRemoteCallResultData();
                    if (context.ServiceEntry == null)
                    {
                        resultMessage.ExceptionMessage = $"can not find service {context.RemoteInvokeMessage.ServiceId}";
                        _jimuApm.WriteServiceInvokeAfter(operationId, thisContext, resultMessage);
                        await response.WriteAsync(message.Id, resultMessage);
                    }
                    else if (context.ServiceEntry.Descriptor.WaitExecution)
                    {
                        await LocalServiceExecuteAsync(context.ServiceEntry, context.RemoteInvokeMessage, resultMessage);
                        _jimuApm.WriteServiceInvokeAfter(operationId, thisContext, resultMessage);
                        await response.WriteAsync(message.Id, resultMessage);
                    }
                    else
                    {
                        await response.WriteAsync(message.Id, resultMessage);
                        await Task.Factory.StartNew(async() =>
                        {
                            await LocalServiceExecuteAsync(context.ServiceEntry, context.RemoteInvokeMessage, resultMessage);
                            _jimuApm.WriteServiceInvokeAfter(operationId, thisContext, resultMessage);
                        });
                    }
                });

                foreach (var middleware in _middlewares)
                {
                    lastInvoke = middleware(lastInvoke);
                }
                try
                {
                    _jimuApm.WriteServiceInvokeBefore(thisContext);
                    await lastInvoke(thisContext);
                }
                catch (Exception ex)
                {
                    JimuRemoteCallResultData resultMessage = new JimuRemoteCallResultData();
                    resultMessage.ErrorCode        = "500";
                    resultMessage.ExceptionMessage = ex.ToStackTraceString();
                    _logger.Error("throw exception when excuting local service: \r\n " + JimuHelper.Serialize <string>(message), ex);
                    await response.WriteAsync(message.Id, resultMessage);
                }
            }
            else
            {
                _logger.Debug($"msg: {message.Id}, message type is not an  JimuRemoteCallData.");
            }
        }
示例#5
0
 /// <summary>
 ///     how to handle server response
 /// </summary>
 /// <param name="message"></param>
 /// <returns></returns>
 public async Task Received(JimuTransportMsg message)
 {
     if (OnReceived == null)
     {
         return;
     }
     await OnReceived(message);
 }
示例#6
0
 public async Task Received(IClientSender sender, JimuTransportMsg message)
 {
     if (OnReceived == null)
     {
         return;
     }
     await OnReceived(sender, message);
 }
示例#7
0
        private Task ListenerOnReceived(JimuTransportMsg message)
        {
            _logger.Debug($"receive response of msg: {message.Id}");
            if (!_resultCallbackDic.TryGetValue(message.Id, out var task))
            {
                return(Task.CompletedTask);
            }

            if (message.ContentType != typeof(JimuRemoteCallResultData).FullName)
            {
                return(Task.CompletedTask);
            }
            task.SetResult(message);
            return(Task.CompletedTask);
        }
示例#8
0
        public async Task Invoke(HttpContext context)
        {
            using (var sr = new StreamReader(context.Request.Body))
            {
                var body = sr.ReadToEnd();
                _logger.Debug($"received msg is: {body}");
                _message = (JimuTransportMsg)_typeConvert.Convert(body, typeof(JimuTransportMsg));
            }

            _logger.Debug($"begin handling msg: {_message.Id}");
            IResponse response    = new HttpResponse(context.Response, _serializer, _logger);
            var       thisContext = new RemoteCallerContext(_message, _serviceEntryContainer, response, _logger);
            var       lastInvoke  = new RequestDel(async ctx =>
            {
                JimuRemoteCallResultData resultMessage = new JimuRemoteCallResultData();

                if (ctx.ServiceEntry == null)
                {
                    resultMessage.ExceptionMessage = $"can not find service {ctx.RemoteInvokeMessage.ServiceId}";
                    await response.WriteAsync(_message.Id, resultMessage);
                }
                else if (ctx.ServiceEntry.Descriptor.WaitExecution)
                {
                    await LocalServiceExecuteAsync(ctx.ServiceEntry, ctx.RemoteInvokeMessage, resultMessage);
                    await response.WriteAsync(_message.Id, resultMessage);
                }
                else
                {
                    await response.WriteAsync(_message.Id, resultMessage);
                    await Task.Factory.StartNew(async() =>
                    {
                        await LocalServiceExecuteAsync(ctx.ServiceEntry, ctx.RemoteInvokeMessage, resultMessage);
                    });
                }
            });


            foreach (var middleware in _middlewares)
            {
                lastInvoke = middleware(lastInvoke);
            }

            await lastInvoke(thisContext);

            //await _next(context);
        }
示例#9
0
        private async Task OnReceived(IChannelHandlerContext channel, JimuTransportMsg message)
        {
            _logger.Debug($"begin handling msg: {message.Id}");
            //TaskCompletionSource<TransportMessage> task;
            if (message.ContentType == typeof(JimuRemoteCallData).FullName)
            {
                IResponse response    = new DotNettyResponse(channel, _serializer, _logger);
                var       thisContext = new RemoteCallerContext(message, _serviceEntryContainer, response, _logger);

                var lastInvoke = new RequestDel(async context =>
                {
                    JimuRemoteCallResultData resultMessage = new JimuRemoteCallResultData();
                    if (context.ServiceEntry == null)
                    {
                        resultMessage.ExceptionMessage = $"can not find service {context.RemoteInvokeMessage.ServiceId}";
                        await response.WriteAsync(message.Id, resultMessage);
                    }
                    else if (context.ServiceEntry.Descriptor.WaitExecution)
                    {
                        await LocalServiceExecuteAsync(context.ServiceEntry, context.RemoteInvokeMessage, resultMessage);
                        await response.WriteAsync(message.Id, resultMessage);
                    }
                    else
                    {
                        await response.WriteAsync(message.Id, resultMessage);
                        await Task.Factory.StartNew(async() =>
                        {
                            await LocalServiceExecuteAsync(context.ServiceEntry, context.RemoteInvokeMessage, resultMessage);
                        });
                    }
                });

                foreach (var middleware in _middlewares)
                {
                    lastInvoke = middleware(lastInvoke);
                }
                await lastInvoke(thisContext);
            }
            else
            {
                _logger.Debug($"msg: {message.Id}, message type is not an  JimuRemoteCallData.");
            }
        }
示例#10
0
        public RemoteCallerContext(JimuTransportMsg transportMessage, IServiceEntryContainer serviceEntryContainer,
                                   IResponse response, ILogger logger)
        {
            Response         = response;
            TransportMessage = transportMessage;
            try
            {
                RemoteInvokeMessage = transportMessage.GetContent <JimuRemoteCallData>();
            }
            catch (Exception ex)
            {
                logger.Error("failed to convert transportmsg.content to  JimuRemoteCallerData.", ex);
                return;
            }

            ServiceEntry = serviceEntryContainer.GetServiceEntry()
                           .FirstOrDefault(x => x.Descriptor.Id == RemoteInvokeMessage.ServiceId);
            if (ServiceEntry == null)
            {
                logger.Error($"not found service: {RemoteInvokeMessage.ServiceId}", new EntryPointNotFoundException($"{RemoteInvokeMessage.ServiceId}"));
            }
        }
示例#11
0
 protected override async Task DoSendAsync(JimuTransportMsg message)
 {
     var buffer = GetByteBuffer(message);
     await _channel.WriteAndFlushAsync(buffer);
 }
示例#12
0
 /// <summary>
 ///     send msg to server
 /// </summary>
 /// <param name="msg"></param>
 /// <returns></returns>
 protected abstract Task DoSendAsync(JimuTransportMsg msg);
示例#13
0
 public async Task SendAsync(JimuTransportMsg message)
 {
     var buffer = GetByteBuffer(message);
     await _channel.WriteAndFlushAsync(buffer);
 }