private IByteBuffer GetByteBuffer(JimuTransportMsg message) { var data = JimuHelper.Serialize <byte[]>(message); var buffer = Unpooled.Buffer(data.Length, data.Length); return(buffer.WriteBytes(data)); }
public async Task SetRoutesAsync(List <JimuServiceRoute> routes) { OnBeforeSetRoutes?.Invoke(routes); //var existingRoutes = await GetRoutes(routes.Select(x => GetKey(x.ServiceDescriptor.Id))); _routes = routes.ToList(); var routeDescriptors = new List <JimuServiceRouteDesc>(routes.Count()); foreach (var route in routes) { routeDescriptors.Add(new JimuServiceRouteDesc { ServiceDescriptor = route.ServiceDescriptor, AddressDescriptors = route.Address?.Select(x => new JimuAddressDesc { //Type = $"{x.GetType().FullName}, {x.GetType().Assembly.GetName()}", Value = JimuHelper.Serialize <string>(x) }) }); } //await SetRoutesAsync(routeDescriptors); var nodeData = JimuHelper.Serialize <byte[]>(routeDescriptors); foreach (var key in GetKey()) { var keyValuePair = new KVPair(key) { Value = nodeData }; await _consul.KV.Put(keyValuePair); } }
public Task WriteAsync(string messageId, JimuRemoteCallResultData resultMessage) { _logger.Debug($"finish handling msg: {messageId}"); var data = JimuHelper.Serialize <string>(new JimuTransportMsg(messageId, resultMessage)); //_httpResponse. return(_httpResponse.WriteAsync(data)); }
public JimuServiceDesc Parse(MethodInfo methodInfo) { JimuServiceDesc desc = new JimuServiceDesc(); var descriptorAttributes = methodInfo.GetCustomAttributes <JimuServiceDescAttribute>(); foreach (var attr in descriptorAttributes) { attr.Apply(desc); } if (string.IsNullOrEmpty(desc.Comment)) { var xml = GetXmlComment(methodInfo.DeclaringType); var key = XmlCommentsMemberNameHelper.GetMemberNameForMethod(methodInfo); if (xml != null && xml.TryGetValue(key, out var node)) { var summaryNode = node.SelectSingleNode("summary"); if (summaryNode != null) { desc.Comment = summaryNode.Value.Trim(); } } } desc.ReturnDesc = GetReturnDesc(methodInfo); if (string.IsNullOrEmpty(desc.HttpMethod)) { desc.HttpMethod = GetHttpMethod(methodInfo); } desc.Parameters = JimuHelper.Serialize <string>(GetParameters(methodInfo)); if (string.IsNullOrEmpty(desc.Id)) { desc.Id = JimuHelper.GenerateServiceId(methodInfo); } var type = methodInfo.DeclaringType; var routeTemplate = type.GetCustomAttribute <JimuAttribute>(); if (routeTemplate != null) { if (string.IsNullOrEmpty(desc.RoutePath)) { var setPath = string.IsNullOrEmpty(desc.Rest) ? methodInfo.Name : desc.Rest; desc.ServiceClassPath = JimuServiceRoute.ParseClassPath(routeTemplate.GetTemplate(type), type.Name, type.IsInterface); desc.RoutePath = JimuServiceRoute.ParseRoutePath(desc.HttpMethod, desc.ServiceClassPath, setPath, methodInfo.GetParameters().Select(x => x.Name).ToArray(), type.IsInterface); } } desc.Service = methodInfo.DeclaringType.FullName; desc.ServiceComment = GetServiceComment(methodInfo); return(desc); }
private string GetReturnDesc(MethodInfo methodInfo) { JimuServiceReturnDesc desc = new JimuServiceReturnDesc(); var jimuReturnComment = methodInfo.GetCustomAttribute <JimuReturnCommentAttribute>(); if (jimuReturnComment != null) { desc.Comment = jimuReturnComment.Comment; desc.ReturnFormat = jimuReturnComment.Format; } if (string.IsNullOrEmpty(desc.Comment)) { var xml = GetXmlComment(methodInfo.DeclaringType); var key = XmlCommentsMemberNameHelper.GetMemberNameForMethod(methodInfo); if (xml != null && xml.TryGetValue(key, out var node)) { var returnNode = node.SelectSingleNode("returns"); desc.Comment = returnNode?.Value.Trim(); } } List <Type> customTypes = new List <Type>(); if (methodInfo.ReturnType.ToString().IndexOf("System.Threading.Tasks.Task", StringComparison.Ordinal) == 0 && methodInfo.ReturnType.IsGenericType) { //desc.ReturnType = methodInfo.ReturnType.ToString(); desc.ReturnType = string.Join(",", methodInfo.ReturnType.GenericTypeArguments.Select(x => x.FullName)); customTypes = (from type in methodInfo.ReturnType.GenericTypeArguments from childType in type.GenericTypeArguments select childType).ToList(); } else if (methodInfo.ReturnType.IsGenericType) //if (methodInfo.ReturnType.IsGenericType) { //desc.ReturnType = string.Join(",", methodInfo.ReturnType.GenericTypeArguments.Select(x => x.FullName)); desc.ReturnType = methodInfo.ReturnType.ToString(); customTypes = methodInfo.ReturnType.GenericTypeArguments.ToList(); } else { desc.ReturnType = methodInfo.ReturnType.ToString(); customTypes = new List <Type> { methodInfo.ReturnType }; } // if not specify the return format in method attribute, we auto generate it. if (string.IsNullOrEmpty(desc.ReturnFormat)) { desc.ReturnFormat = GetReturnFormat(customTypes); } return(JimuHelper.Serialize <string>(desc)); }
private string GetReturnDesc(MethodInfo methodInfo) { JimuServiceReturnDesc desc = new JimuServiceReturnDesc(); var jimuReturnComment = methodInfo.GetCustomAttribute <JimuReturnCommentAttribute>(); if (jimuReturnComment != null) { desc.Comment = jimuReturnComment.Comment; desc.ReturnFormat = jimuReturnComment.Default; } if (string.IsNullOrEmpty(desc.Comment)) { var xml = GetXmlComment(methodInfo.DeclaringType); var key = XmlCommentsMemberNameHelper.GetMemberNameForMethod(methodInfo); if (xml != null && xml.TryGetValue(key, out var node)) { var returnNode = node.SelectSingleNode("returns"); desc.Comment = returnNode?.Value.Trim(); } } Type returnType = methodInfo.ReturnType; if (methodInfo.ReturnType.ToString().IndexOf("System.Threading.Tasks.Task", StringComparison.Ordinal) == 0) { if (methodInfo.ReturnType.GenericTypeArguments.Any()) { returnType = methodInfo.ReturnType.GenericTypeArguments[0]; } else { returnType = typeof(void); } } desc.ReturnType = returnType.ToString(); if (returnType.IsGenericType && returnType.ToString().StartsWith("System.")) { returnType = returnType.GenericTypeArguments[0]; } else if (returnType.IsArray) { var arrayBaseType = returnType.Assembly.ExportedTypes.FirstOrDefault(x => x.FullName == returnType.FullName.TrimEnd('[', ']')); returnType = arrayBaseType; } if (returnType != null) { desc.Properties = GetProperties(returnType); } return(JimuHelper.Serialize <string>(desc)); }
public async Task WriteAsync(string messageId, JimuRemoteCallResultData resultMessage) { try { _logger.Debug($"finish handling msg: {messageId}"); var data = JimuHelper.Serialize <byte[]>(new JimuTransportMsg(messageId, resultMessage)); var buffer = Unpooled.Buffer(data.Length, data.Length); buffer.WriteBytes(data); await _channel.WriteAndFlushAsync(buffer); } catch (Exception ex) { _logger.Error("throw exception when response msg: " + messageId, ex); } }
public async Task WriteAsync(string messageId, JimuRemoteCallResultData resultMessage) { try { _logger.Debug($"finish handling msg: {messageId}"); var data = JimuHelper.Serialize <byte[]>(new JimuTransportMsg(messageId, resultMessage)); if (data.Length < 102400) { _logger.Debug($"resp msg is: {Encoding.UTF8.GetString(data)}"); } else { _logger.Debug($"resp msg is (bigger than 100k, we don't show it)"); } var buffer = Unpooled.Buffer(data.Length, data.Length); buffer.WriteBytes(data); await _channel.WriteAndFlushAsync(buffer); } catch (Exception ex) { _logger.Error("throw exception when response msg: " + messageId, ex); } }
public override void DoInit(IContainer container) { if (_options != null) { var logger = container.Resolve <ILogger>(); logger.Info($"[config]use jose.jwt for Auth"); //while (!container.IsRegistered<IServer>() || !container.IsRegistered<IServiceDiscovery>()) //{ // Thread.Sleep(200); //} var server = container.Resolve <IServer>(); server.UseMiddleware <JwtAuthorizationMiddleware>(_options, container); if (string.IsNullOrEmpty(_options.TokenEndpointPath)) { return; } var discovery = container.Resolve <IServiceDiscovery>(); var addr = new JimuAddress(_options.ServiceInvokeIp, Convert.ToInt32(_options.ServiceInvokePort), _options.Protocol); var tokenRoute = new JimuServiceRoute { Address = new List <JimuAddress> { addr }, ServiceDescriptor = new JimuServiceDesc { Id = _options.GetServiceId(), Service = "Token", RoutePath = JimuServiceRoute.ParseRoutePath("", "", _options.TokenEndpointPath, new[] { "username", "password" }, false), Parameters = JimuHelper.Serialize <string>(new List <JimuServiceParameterDesc> { new JimuServiceParameterDesc { Comment = "username", Format = "System.String", Name = "username", Type = "object" }, new JimuServiceParameterDesc { Comment = "password", Format = "System.String", Name = "password", Type = "object" }, }), ReturnDesc = JimuHelper.Serialize <string>(new JimuServiceReturnDesc { Comment = "Token", ReturnType = "object", ReturnFormat = "{\"access_token\":\"System.String | token\", \"expired_in\":\"System.Int32 | expired timestamp which is the number of seconds between 1970-01-01 and expired datetime\"}" }) } }; //discovery.ClearServiceAsync(tokenRoute.First().ServiceDescriptor.Id).Wait(); ////discovery.SetRoutesAsync(tokenRoute); //discovery.AddRouteAsync(tokenRoute).Wait(); discovery.OnBeforeSetRoutes += (routes) => { routes.Add(tokenRoute); }; } base.DoInit(container); }
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."); } }
public override void DoInit(IContainer container) { if (_options != null) { var loggerFactory = container.Resolve <ILoggerFactory>(); var logger = loggerFactory.Create(this.GetType()); logger.Info($"[config]use jose.jwt for Auth"); //while (!container.IsRegistered<IRemoteServiceCaller>() || !container.IsRegistered<IClientServiceDiscovery>()) //{ // Thread.Sleep(100); //} var caller = container.Resolve <IRemoteServiceCaller>(); caller.UseMiddleware <JwtAuthorizationMiddleware>(_options); if (string.IsNullOrEmpty(_options.TokenEndpointPath)) { return; } var discovery = container.Resolve <IClientServiceDiscovery>(); var addr = new JimuAddress(_options.ServiceInvokeIp, Convert.ToInt32(_options.ServiceInvokePort), _options.Protocol); var tokenRoute = new List <JimuServiceRoute> { new JimuServiceRoute { Address = new List <JimuAddress> { addr }, ServiceDescriptor = new JimuServiceDesc { Id = _options.GetServiceId(), Service = "Token", HttpMethod = "POST", AllowAnonymous = true, ServiceClassPath = "", RoutePath = JimuServiceRoute.ParseRoutePath("POST", "", _options.TokenEndpointPath, new[] { "username", "password", "grant_type" }, false), Parameters = JimuHelper.Serialize <string>(new List <JimuServiceParameterDesc> { new JimuServiceParameterDesc { Comment = "username", Name = "username", Type = "System.String" }, new JimuServiceParameterDesc { Comment = "password", Name = "password", Type = "System.String" }, new JimuServiceParameterDesc { Comment = "grant_type", Default = "password", Name = "grant_type", Type = "System.String" }, }), ReturnDesc = JimuHelper.Serialize <string>(new JimuServiceReturnDesc { Comment = "Token", ReturnType = "object", Properties = new List <JimuServiceParameterDesc> { new JimuServiceParameterDesc { Comment = "token", Name = "access_token", Type = "System.String" }, new JimuServiceParameterDesc { Comment = "expired timestamp which is the number of seconds between 1970-01-01 and expired datetime", Name = "expired_in", Type = "System.Int32" } } }) } } }; discovery.AddRoutesGetter(() => { return(Task.FromResult(tokenRoute)); }); } base.DoInit(container); }
public override void DoInit(IContainer container) { if (_options != null) { var logger = container.Resolve <ILogger>(); logger.Info($"[config]use jose.jwt for Auth"); while (!container.IsRegistered <IRemoteServiceCaller>() || !container.IsRegistered <IClientServiceDiscovery>()) { Thread.Sleep(100); } var caller = container.Resolve <IRemoteServiceCaller>(); caller.UseMiddleware <JwtAuthorizationMiddleware>(_options); if (string.IsNullOrEmpty(_options.TokenEndpointPath)) { return; } var discovery = container.Resolve <IClientServiceDiscovery>(); var addr = new JimuAddress(_options.ServerIp, _options.ServerPort, _options.Protocol); var tokenRoute = new List <JimuServiceRoute> { new JimuServiceRoute { Address = new List <JimuAddress> { addr }, ServiceDescriptor = new JimuServiceDesc { Id = _options.GetServiceId(), RoutePath = JimuServiceRoute.ParseRoutePath("", "", _options.TokenEndpointPath, new[] { "username", "password" }, false), Parameters = JimuHelper.Serialize <string>(new List <JimuServiceParameterDesc> { new JimuServiceParameterDesc { Comment = "username", Format = "System.String", Name = "username", Type = "object" }, new JimuServiceParameterDesc { Comment = "password", Format = "System.String", Name = "password", Type = "object" }, }), ReturnDesc = JimuHelper.Serialize <string>(new JimuServiceReturnDesc { Comment = "Token", ReturnType = "object", ReturnFormat = "{\"access_token\":\"System.String | token\", \"expired_in\":\"System.Int32 | expired timestamp which is the number of seconds between 1970-01-01 and expired datetime\"}" }) } } }; discovery.AddRoutesGetter(() => { return(Task.FromResult(tokenRoute)); }); } base.DoInit(container); }