Exemplo n.º 1
0
        protected async Task <Message> RecvUnsafeAsync(CancellationToken?token = null)
        {
            if (token == null)
            {
                token = CancellationToken.None;
            }
            List <byte> data = new List <byte>();

            while (true)
            {
                int    bufferSize = 1024 * 64;
                byte[] buffer     = new byte[bufferSize];
                var    result     = await socket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

                byte[] recv = new byte[result.Count];
                Array.Copy(buffer, recv, result.Count);
                data.AddRange(recv);
                if (result.EndOfMessage)
                {
                    break;
                }
            }

            UTF8Encoding encoder = new UTF8Encoding();
            Message      res     = JsonKit.DeserializeObject <Message>(encoder.GetString(data.ToArray()));

            if (AfterRecv != null)
            {
                AfterRecv(res);
            }
            return(res);
        }
Exemplo n.º 2
0
        private bool checkParams(Message req, Message res, MethodInfo method, object[] args, object[] invokeArgs)
        {
            ParameterInfo[] pinfo = method.GetParameters();
            int             count = 0;

            foreach (ParameterInfo info in pinfo)
            {
                if (typeof(Message).IsAssignableFrom(info.ParameterType))
                {
                    continue;
                }
                count++;
            }
            if (count != args.Length)
            {
                reply(res, 400, string.Format("Request(Url={0}, Method={1}, Params={2}) Bad Format", req.Url, method.Name, JsonKit.SerializeObject(args)));
                return(false);
            }
            int j = 0;

            for (int i = 0; i < pinfo.Length; i++)
            {
                if (typeof(Message).IsAssignableFrom(pinfo[i].ParameterType))
                {
                    invokeArgs[i] = req;
                    continue;
                }
                invokeArgs[i] = JsonKit.Convert(args[j++], pinfo[i].ParameterType);
            }

            return(true);
        }
Exemplo n.º 3
0
        public async Task <object> InvokeAsync(Type type, Message req, int timeoutMillis = 10000)
        {
            Message res = await base.InvokeAsync(req, timeoutMillis);

            object data = parseResult(res);

            return(JsonKit.Convert(data, type));
        }
Exemplo n.º 4
0
        public async Task <T> InvokeAsync <T>(Message req, int timeoutMillis = 10000)
        {
            Message res = await base.InvokeAsync(req, timeoutMillis);

            object data = parseResult(res);

            return((T)JsonKit.Convert(data, typeof(T)));
        }
Exemplo n.º 5
0
        public dynamic Request(Type realReturnType, Message request)
        {
            dynamic resp = rpcClient.InvokeAsync(realReturnType, request).Result;

            if (realReturnType == typeof(void))
            {
                return(null);
            }

            if (realReturnType != resp.GetType() && !typeof(Task).IsAssignableFrom(realReturnType))
            {
                return(JsonKit.Convert(resp, realReturnType));
            }
            return(resp);
        }
Exemplo n.º 6
0
        public MqClient(string address) : base(address)
        {
            this.heartbeatMessage = new Message();
            this.heartbeatMessage.Headers[Protocol.CMD] = Protocol.PING;

            OnMessage += async(msg) => {
                string mq      = (string)msg.Headers[Protocol.MQ];
                string channel = (string)msg.Headers[Protocol.CHANNEL];
                if (mq == null || channel == null)
                {
                    logger.Warn("Missing mq or channel in response: " + JsonKit.SerializeObject(msg));
                    return;
                }
                MqHandler mqHandler = null;
                foreach (var e in this.handlers)
                {
                    if (e.Mq == mq && e.Channel == channel)
                    {
                        mqHandler = e;
                        break;
                    }
                }
                if (mqHandler == null)
                {
                    logger.Warn(string.Format("Missing handler for mq={}, channel={}", mq, channel));
                    return;
                }
                mqHandler.Handler(msg);

                string windowStr = (string)msg.Headers[Protocol.WINDOW];
                int?   window    = null;
                if (windowStr != null)
                {
                    window = int.Parse(windowStr);
                }
                if (window != null && window <= mqHandler.Window / 2)
                {
                    var sub = new Message();
                    sub.Headers[Protocol.CMD]     = Protocol.SUB;
                    sub.Headers[Protocol.MQ]      = mq;
                    sub.Headers[Protocol.CHANNEL] = channel;
                    sub.Headers[Protocol.ACK]     = false;
                    sub.Headers[Protocol.WINDOW]  = mqHandler.Window.ToString();

                    await this.SendAsync(sub);
                }
            };
        }
Exemplo n.º 7
0
 protected async Task SendUnsafeAsync(Message req, Action <Message> beforeSend = null, CancellationToken?token = null)
 {
     if (token == null)
     {
         token = CancellationToken.None;
     }
     if (beforeSend == null)
     {
         beforeSend = BeforeSend;
     }
     if (beforeSend != null)
     {
         beforeSend(req);
     }
     if (AuthEnabled)
     {
         Auth.Sign(ApiKey, SecretKey, req);
     }
     string       msg     = JsonKit.SerializeObject(req);
     UTF8Encoding encoder = new UTF8Encoding();
     await socket.SendAsync(new ArraySegment <byte>(encoder.GetBytes(msg)),
                            WebSocketMessageType.Text, true, token.Value);
 }
Exemplo n.º 8
0
        public void Start()
        {
            if (Mq == null)
            {
                throw new MissingFieldException("missing mq field");
            }
            if (Channel == null)
            {
                Channel = Mq;
            }

            processor.MountDoc();

            MqClient client = new MqClient(MqServerAddress);

            if (AuthEnabled)
            {
                client.AuthEnabled = AuthEnabled;
                client.ApiKey      = ApiKey;
                client.SecretKey   = SecretKey;
            }

            client.OnOpen += async(cli) =>
            {
                Message msg = new Message();
                msg.Headers[Protocol.CMD]     = Protocol.CREATE;
                msg.Headers[Protocol.MQ]      = Mq;
                msg.Headers[Protocol.MQ_TYPE] = MqType;
                msg.Headers[Protocol.CHANNEL] = Channel;

                var res = await client.InvokeAsync(msg);

                logger.Info(JsonKit.SerializeObject(res));

                msg = new Message();
                msg.Headers[Protocol.CMD]     = Protocol.SUB;
                msg.Headers[Protocol.MQ]      = Mq;
                msg.Headers[Protocol.CHANNEL] = Channel;

                res = await client.InvokeAsync(msg);

                logger.Info(JsonKit.SerializeObject(res));

                msg = new Message();
                msg.Headers[Protocol.CMD] = Protocol.BIND;
                msg.Headers[Protocol.MQ]  = Mq;
                msg.Body = processor.UrlEntryList(Mq);

                res = await client.InvokeAsync(msg);

                logger.Info(JsonKit.SerializeObject(res));
            };

            client.AddMqHandler(Mq, Channel, async(request) =>
            {
                string prefix = processor.UrlPrefix;
                string url    = request.Url;
                if (url != null && url.StartsWith(prefix))
                {
                    url         = url.Substring(prefix.Length);
                    request.Url = PathKit.Join(url);
                }

                string id        = (string)request.Headers[Protocol.ID];
                string source    = (string)request.Headers[Protocol.SOURCE];
                Message response = new Message();
                try
                {
                    await processor.ProcessAsync(request, response);
                }
                catch (Exception e)
                {
                    while (e.InnerException != null)
                    {
                        e = e.InnerException;
                    }
                    response.Status = 500;
                    response.Headers["content-type"] = "text/plain; charset=utf8;";
                    response.Body = e.Message;
                }

                response.Headers[Protocol.CMD]    = Protocol.ROUTE;
                response.Headers[Protocol.ID]     = id;
                response.Headers[Protocol.TARGET] = source;

                await client.SendAsync(response);
            });

            client.ConnectAsync().Wait();
        }
Exemplo n.º 9
0
        public async Task ProcessAsync(Message request, Message response)
        {
            response.Status = 200;
            if (request.Url == null)
            {
                reply(response, 400, "Missing url in request");
                return;
            }
            string         url        = request.Url;
            int            length     = 0;
            MethodInstance target     = null;
            string         targetPath = null;

            foreach (var e in this.UrlPath2Method)
            {
                string path = e.Key;
                if (url.StartsWith(path))
                {
                    if (path.Length > length)
                    {
                        target     = e.Value;
                        targetPath = path;
                        length     = path.Length;
                    }
                }
            }
            if (target == null)
            {
                reply(response, 404, string.Format("Url={0} Not Found", url));
                return;
            }
            object[] args = new object[0];
            if (request.Body != null)
            {
                args = JsonKit.Convert <object[]>(request.Body);
            }
            else
            {
                args = parseParam(url.Substring(targetPath.Length));
            }

            ParameterInfo[] pinfo      = target.Method.GetParameters();
            object[]        invokeArgs = new object[pinfo.Length];
            bool            ok         = checkParams(request, response, target.Method, args, invokeArgs);

            if (!ok)
            {
                return;
            }

            dynamic invoked = target.Method.Invoke(target.Instance, invokeArgs);

            if (invoked != null && typeof(Task).IsAssignableFrom(invoked.GetType()))
            {
                if (target.Method.ReturnType.GenericTypeArguments.Length > 0)
                {
                    invoked = await invoked;
                }
            }

            if (invoked is Message)
            {
                response.Replace((Message)invoked);
            }
            else
            {
                response.Body = invoked;
                response.Headers["content-type"] = "application/json; charset=utf8;";
            }
        }