Exemplo n.º 1
0
        private void InitMethods()
        {
            _serverMethods.AddMethod <Auth, Empty>(WapEndPoint.Parse(_baseEp, "auth"), AuthClient);
            _serverMethods.AddMethod <MethodInfo, Empty>(WapEndPoint.Parse(_baseEp, "method.register"),
                                                         RegisterMethod);
            _serverMethods.AddMethod <Deregister, Empty>(WapEndPoint.Parse(_baseEp, "methods.deregister"),
                                                         DeregisterMethod);
            _serverMethods.AddMethod <MethodInfo, Empty>(WapEndPoint.Parse(_baseEp, "method.check"),
                                                         CheckMethod);

            _serverMethods.AddMethod <RegisterEvent, Empty>(WapEndPoint.Parse(_baseEp, "events.publisher.add"),
                                                            AddPublisher);
            _serverMethods.AddMethod <Deregister, Empty>(WapEndPoint.Parse(_baseEp, "events.publisher.remove"),
                                                         RemovePublisher);

            _serverMethods.AddMethod <RegisterEvent, Empty>(WapEndPoint.Parse(_baseEp, "events.subscribe"),
                                                            SubscribeEvent);
            _serverMethods.AddMethod <Deregister, Empty>(WapEndPoint.Parse(_baseEp, "events.unsubscribe"),
                                                         UnsubscribeEvent);

            _serverMethods.AddMethod <Empty, DictionaryData>(WapEndPoint.Parse(_baseEp, "events.list"), GetEvents);
            _serverMethods.AddMethod <Payloads.Generic.String, StringList>(
                WapEndPoint.Parse(_baseEp, "events.getsubscribers"), GetEventSubscribers);
            _serverMethods.AddMethod <Payloads.Generic.String, StringList>(
                WapEndPoint.Parse(_baseEp, "events.getpublishers"), GetEventPublishers);

            _serverMethods.AddMethod <Empty, MethodInfoList>(WapEndPoint.Parse(_baseEp, "methods.list"), GetMethods);
            _serverMethods.AddMethod <Payloads.Generic.String, MethodInfo>(WapEndPoint.Parse(_baseEp, "methods.getinfo"), GetMethodInfo);
        }
Exemplo n.º 2
0
 private async Task <WapMessage> MethodCallHandler(ClientConnection client, ReceivedWapMessage message)
 {
     if (_serverMethods.HasMethod(message.EndPoint))
     {
         try
         {
             return(await _serverMethods.CallMethod(client, WapEndPoint.Parse(message.EndPoint), message));
         }
         catch (Exception ex)
         {
             return(new WapMessage <MethodResult <Empty> >(MessageType.MethodResponse, message.EndPoint, new MethodResult <Empty>()
             {
                 Success = false,
                 Error = ex.Message
             }));
         }
     }
     else if (_clientMethods.ContainsKey(message.EndPoint))
     {
         return(await _clientMethods[message.EndPoint].Client.CallMethod(message));
     }
     else
     {
         return(new WapMessage <MethodResult <Empty> >(MessageType.MethodResponse, message.EndPoint, new MethodResult <Empty>()
         {
             Success = false,
             Error = "Method not found"
         }));
     }
 }
Exemplo n.º 3
0
 protected WapClient(string endPoint, string name)
     : this(string.Empty, 0, endPoint, name)
 {
     ControllerAddress = EnvironmentVariableHelper.Get("WAP_CONTROLLER_ADDRESS", "localhost");
     ControllerPort    = int.Parse(EnvironmentVariableHelper.Get("WAP_CONTROLLER_PORT", "51234"));
     _controllerEp     = WapEndPoint.Parse(EnvironmentVariableHelper.Get("WAP_CONTROLLER_ENDPOINT", ":control"));
 }
Exemplo n.º 4
0
        public bool AddMethod <TParam, TResult>(WapEndPoint ep, Func <ClientConnection, TParam, Task <MethodResult <TResult> > > func)
        {
            if (HasMethod(ep))
            {
                return(false);
            }

            var str = ep.ToString();

            var i = new MethodInfo()
            {
                ParameterPayloadType = typeof(TParam).GetPayloadTypeName(),
                ResultPayloadType    = typeof(TResult).GetPayloadTypeName()
            };

            var f = new Func <ClientConnection, ReceivedWapMessage, Task <WapMessage> >(async(client, message) =>
            {
                WapMessage <TParam> msg = WapMessage <TParam> .FromReceivedMessage(message);

                var result = await func(client, msg.Payload);

                WapMessage <MethodResult <TResult> > res = new WapMessage <MethodResult <TResult> >(MessageType.MethodResponse, message.EndPoint, result);
                return(res);
            });

            _infos.Add(str, i);
            _methods.Add(str, f);

            return(true);
        }
Exemplo n.º 5
0
        public async Task <WapMessage> CallMethod(ClientConnection client, WapEndPoint ep, ReceivedWapMessage msg)
        {
            if (!HasMethod(ep))
            {
                return(null);
            }

            return(await _methods[ep.ToString()](client, msg));
        }
Exemplo n.º 6
0
        protected WapClient(string controllerAddress, int port, string endPoint, string name, string controllerEndpoint = null)
        {
            ControllerAddress = controllerAddress;
            ControllerPort    = port;
            Endpoint          = WapEndPoint.Parse(endPoint);
            Name = name;

            _controllerEp = WapEndPoint.Parse(controllerEndpoint ?? ":control");
        }
Exemplo n.º 7
0
        protected async Task <EventPublisher <TEvent> > CreatePublisher <TEvent>(string endpoint) where TEvent : new()
        {
            WapEndPoint ep = WapEndPoint.Parse(Endpoint, endpoint);

            await CallControlMethod <RegisterEvent, Empty>("events.publisher.add", new RegisterEvent()
            {
                EndPoint    = ep.ToString(),
                PayloadType = typeof(TEvent).GetPayloadTypeName()
            });

            return(new EventPublisher <TEvent>(ep, PublishEventData));
        }
Exemplo n.º 8
0
        private Task <WapMessage> MethodCallHandler(ReceivedWapMessage receivedWapMessage)
        {
            if (!_methods.HasMethod(receivedWapMessage.EndPoint))
            {
                var mres = MethodResult <Empty> .FromError("Method not found in this endpoint!");

                var msg = new WapMessage <MethodResult <Empty> >(MessageType.MethodResponse, receivedWapMessage.EndPoint, mres);
                return(Task.FromResult <WapMessage>(msg));
            }

            return(_methods.CallMethod(WapEndPoint.Parse(receivedWapMessage.EndPoint), receivedWapMessage));
        }
Exemplo n.º 9
0
        public static void Main(string[] args)
        {
            int         port     = 51234;
            LogLevel    logLevel = LogLevel.Verbose;
            WapEndPoint ep       = WapEndPoint.Parse(":control");
            OptionSet   options  = new OptionSet()
            {
                { "p|port=", "Port the server shall listen on", s => port = int.Parse(s) },
                { "l|log=", "The log level (starting from 0) for the console. The higher, the more information is printed.", s => logLevel = (LogLevel)int.Parse(s) },
                { "ep|endpoint=", "The base endpoint for the server.", s => ep = WapEndPoint.Parse(s) }
            };

            try
            {
                options.Parse(args);
            }
            catch (Exception ex)
            {
                Console.WriteLine("An error occured with the parameters. Please check below.");
                Console.WriteLine(ex.ToString());
                options.WriteOptionDescriptions(Console.Out);
                Environment.Exit(-1);
            }

            Log.ConsoleLevel = logLevel;
            var log = Log.Create("Main");

            Console.WriteLine("WapServer (c) 2018 Merlin Steuer");

            log.Info($"Program startup...");

            WapServer srv = new WapServer(port, ep.ToString());

            if (!srv.Start())
            {
                log.Fatal("Server startup failed.");
                Environment.Exit(-2);
            }

            ManualResetEvent ev = new ManualResetEvent(false);

            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                log.Info("Server shutting down...");
                srv.Stop();
                ev.Set();
            };


            ev.WaitOne();
        }
Exemplo n.º 10
0
        private async Task <TResult> CallMethod <TParam, TResult>(WapEndPoint ep, TParam param)
        {
            WapMessage <TParam> msg = new WapMessage <TParam>(MessageType.MethodCall, ep.ToString(), param);
            var rMsg = await _conn.CallMethod(msg);

            WapMessage <MethodResult <TResult> > result = WapMessage <MethodResult <TResult> > .FromReceivedMessage(rMsg);

            if (!result.Payload.Success)
            {
                throw new MethodCallFailedException(result.Payload.Error);
            }

            return(result.Payload.Result);
        }
Exemplo n.º 11
0
        public async Task <MethodCaller <TParam, TResult> > CreateMethodCaller <TParam, TResult>(string endPoint)
        {
            WapEndPoint ep = WapEndPoint.Parse(Endpoint, endPoint);

            // Call raises an exception if the method does not exist or has a different signature
            await CallControlMethod <MethodInfo, Empty>("method.check", new MethodInfo()
            {
                EndPoint          = ep.ToString(),
                ParamPayloadType  = typeof(TParam).GetPayloadTypeName(),
                ResultPayloadType = typeof(TResult).GetPayloadTypeName()
            });

            return(new MethodCaller <TParam, TResult>(CallMethod <TParam, TResult>, ep));
        }
Exemplo n.º 12
0
        private Task <MethodResult <Empty> > AuthClient(ClientConnection clt, Auth auth)
        {
            if (EndpointRegistered(auth.EndPoint))
            {
                _log.Info($"A client wanted to register already occupied endpoint {auth.EndPoint}.");
                return(GetEmptyErrorMessage("Endpoint already authenticated"));
            }

            _log.Debug($"Authenticating {auth.EndPoint} ({auth.Name})");

            clt.EndPoint = WapEndPoint.Parse(auth.EndPoint);
            clt.Name     = auth.Name;

            return(GetEmptySuccessMessage());
        }
Exemplo n.º 13
0
        protected async Task <MethodProvider <TParam, TResult> > RegisterMethod <TParam, TResult>(string endpoint,
                                                                                                  Func <TParam, Task <TResult> > func)
        {
            WapEndPoint ep = WapEndPoint.Parse(Endpoint, endpoint);

            await CallControlMethod <MethodInfo, Empty>("method.register", new MethodInfo()
            {
                EndPoint          = ep.ToString(),
                ParamPayloadType  = typeof(TParam).GetPayloadTypeName(),
                ResultPayloadType = typeof(TResult).GetPayloadTypeName()
            });

            // If no exception occured, method was successfully registered...
            _methods.AddMethod(ep, func);

            return(new MethodProvider <TParam, TResult>(ep, func));
        }
Exemplo n.º 14
0
        protected async Task <EventSubscriber <TEvent> > SubscribeEvent <TEvent>(string endpoint)
        {
            WapEndPoint ep = WapEndPoint.Parse(Endpoint, endpoint);

            await CallControlMethod <RegisterEvent, Empty>("events.subscribe", new RegisterEvent()
            {
                EndPoint    = ep.ToString(),
                PayloadType = typeof(TEvent).GetPayloadTypeName()
            });

            var subscr = new EventSubscriber <TEvent>(ep);
            var hdl    = new Action <ReceivedWapMessage>(msg =>
            {
                WapMessage <TEvent> wm = WapMessage <TEvent> .FromReceivedMessage(msg);
                subscr.PassData(wm.Payload);
            });

            _eventHandlers.Add(subscr, hdl);

            return(subscr);
        }
Exemplo n.º 15
0
        private void ClientStoppedHandler(object sender, Exception exception)
        {
            var clt = (ClientConnection)sender;

            _log.Debug($"Client {clt.EndPoint} exits");

            foreach (string method in clt.Methods)
            {
                _clientMethods.Remove(method);
            }

            foreach (string publishingEvent in clt.PublishingEvents)
            {
                _events[publishingEvent].Publishers.Remove(clt);
            }

            foreach (string subscribedEvent in clt.SubscribedEvents)
            {
                _events[subscribedEvent].Subscribtions.Remove(clt);
            }

            clt.EndPoint = WapEndPoint.Parse(":");
            _clients.Remove(clt);
        }
Exemplo n.º 16
0
 public WapServer(int port, string baseEndpoint)
 {
     Port    = port;
     _baseEp = WapEndPoint.Parse(baseEndpoint);
     InitMethods();
 }
Exemplo n.º 17
0
 protected Task <TResult> CallControlMethod <TParam, TResult>(string command, TParam param)
 {
     return(CallMethod <TParam, TResult>(WapEndPoint.Parse(_controllerEp, command), param));
 }
Exemplo n.º 18
0
 internal EventSubscriber(WapEndPoint endpoint)
 {
     Endpoint = endpoint;
 }
Exemplo n.º 19
0
        public bool HasMethod(WapEndPoint ep)
        {
            var str = ep.ToString();

            return(_methods.ContainsKey(str) && _infos.ContainsKey(str));
        }
Exemplo n.º 20
0
 public bool HasMethod(string endpoint)
 {
     return(HasMethod(WapEndPoint.Parse(endpoint)));
 }
Exemplo n.º 21
0
 internal EventPublisher(WapEndPoint ep, PublishEvent <T> publishDelegate)
 {
     Endpoint   = ep;
     _publisher = publishDelegate;
 }
Exemplo n.º 22
0
 internal MethodProvider(WapEndPoint ep, Func <TParam, Task <TResult> > func)
 {
     Endpoint = ep;
     Func     = func;
 }
Exemplo n.º 23
0
 internal MethodCaller(Func <WapEndPoint, TParam, Task <TResult> > caller, WapEndPoint endPoint)
 {
     _caller  = caller;
     EndPoint = endPoint;
 }