Ejemplo n.º 1
0
        /// <summary>
        /// Initializes the ModuleClient and sets up the callback to receive
        /// messages containing temperature information
        /// </summary>
        static async Task Init()
        {
            MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);

            ITransportSettings[] settings = { mqttSetting };

            // Open a connection to the Edge runtime
            ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);

            await ioTHubModuleClient.OpenAsync();

            Console.WriteLine("IoT Hub module client initialized.");

            var connectionString = Environment.GetEnvironmentVariable("STORAGE_CONNECTION_STRING");
            var containerName    = Environment.GetEnvironmentVariable("RESULT_CONTAINER_NAME");
            var storageAccount   = CloudStorageAccount.Parse(connectionString);
            var cloudBlobClient  = storageAccount.CreateCloudBlobClient();

            cloudBlobContainer = cloudBlobClient.GetContainerReference(containerName);
            await cloudBlobContainer.CreateIfNotExistsAsync();

            http = new HttpRouter(new string[] { "http://+:80/" });
            http.Register("/caption", SetCaption);
            http.Register("/video/start", StartRecording);
            http.Register("/video/end", EndRecording);
            http.Register("/photo", TakePhoto);
            http.Start();

            await Task.CompletedTask;
        }
        public async Task MatchNamePortAndSetHostAddress()
        {
            var resolver = new HttpRouteResolver();


            var path = "api/values/0";


            var headMatcher = new HttpSetMethodMatcher(HttpMethod.Get);

            headMatcher.Chain(new SetAddressListMatcher(Srv02HostNamePort),
                              new HostAddressMatcher(Srv01HostNamePort, StringMatchType.UriHostandPortMatch));


            await resolver.AddMatcherAsync(headMatcher, 0);

            var router = new HttpRouter(resolver);

            var results = await router.RouteAsync(string.Concat(srv01Address, path));


            var responseMessage = await results.ResultAsAsync <HttpResponseMessage>();

            var responseString = await responseMessage.Content.ReadAsStringAsync();

            // server returns the address
            // in the response

            Assert.AreEqual(string.Concat(srv02Address, path), responseString);
        }
        /// <summary>
        /// Creates a DefaultHttpSysService instance with the specified host and port.
        /// </summary>
        /// <param name="isSecured">NOT_SUPPORTED_YET</param>
        /// <param name="host">host</param>
        /// <param name="port">port</param>
        public DefaultHttpSysService(bool isSecured, string host, int port)
        {
            _inputPipe  = new BlockingCollection <HttpContext>();
            _outputPipe = new BlockingCollection <HttpContext>();

            _httpInboundAdapter  = new HttpSysInboundAdapter();
            _httpOutboundAdapter = new HttpSysOutboundAdapter();
            _httpRouter          = new HttpRouter(this);
            _httpProcessors      = new Dictionary <string, IHttpProcessor>();

            //set names
            _httpInboundAdapter.Name  = "TxHTTP_Inbound_Adapter";
            _httpOutboundAdapter.Name = "TxHTTP_Outbound_Adapter";
            _httpRouter.Name          = "TxHTTP_Router";

            //HttpInboundAdapter ----<TaggedContext>----> HttpRouter
            _httpInboundAdapter.OutputPipe = _inputPipe;
            _httpRouter.InputPipe          = _inputPipe;

            //---<HttpContext>---> HttpOutboundAdapter
            _httpOutboundAdapter.InputPipe = _outputPipe;

            _routingEngine = new RoutingEngine();
            AddController(new HttpInternalController(), INTERNAL_PROCESSING_GROUP);

            //create ServiceConfiguration
            _serviceConfiguration           = new ServiceConfiguration();
            _serviceConfiguration.IsSecured = isSecured;
            _serviceConfiguration.Host      = host;
            _serviceConfiguration.Port      = port;
        }
Ejemplo n.º 4
0
        public async Task doHttpPutWithQueryString()
        {
            var resolver = new HttpRouteResolver();

            var path      = "api/models/";
            var sentModel = Model.getRandomModel();



            var headMatcher = new HttpSetMethodMatcher(HttpMethod.Put);

            headMatcher.Chain(new SetAddressListMatcher(Srv02HostNamePort),
                              new HttpAddSetHeaderMatcher("Content-Type", "application/json"),
                              new HostAddressMatcher(Srv01HostNamePort, StringMatchType.UriHostandPortMatch));


            await resolver.AddMatcherAsync(headMatcher, 0);


            var router  = new HttpRouter(resolver);
            var results = await router.RouteAsync(string.Concat(srv01Address, path, "?ModelId=", sentModel.ModelId), sentModel.asJsonStream());


            var responseMessage = await results.ResultAsAsync <HttpResponseMessage>();

            var responseString = await responseMessage.Content.ReadAsStringAsync();

            var modelReturn = JsonConvert.DeserializeObject <ModelControllerResponseContent>(responseString);


            Assert.AreEqual(sentModel.ModelId, modelReturn.Models[0].ModelId);
            Assert.AreEqual(string.Concat(srv02Address, path, "?ModelId=", sentModel.ModelId), modelReturn.RequestUri);
        }
Ejemplo n.º 5
0
        public async Task BasicWiring()
        {
            var resolver = new HttpRouteResolver();


            /*
             * route from bing to microsoft
             *
             */
            var headMatcher = new HttpSetMethodMatcher(HttpMethod.Get);

            headMatcher.Chain(new SetAddressListMatcher("www.microsoft.com"),
                              new HostAddressMatcher("www.bing.com", StringMatchType.UriHostandPortMatch));


            await resolver.AddMatcherAsync(headMatcher, 0);


            var router  = new HttpRouter(resolver);
            var results = await router.RouteAsync("http://www.bing.com");


            var responseMessage = await results.ResultAsAsync <HttpResponseMessage>();

            Trace.WriteLine(await responseMessage.Content.ReadAsStringAsync());
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MosaicRoutesApi"/> class
        /// using Configuration object
        /// </summary>
        /// <param name="configuration">An instance of Configuration</param>
        /// <returns></returns>
        internal MosaicRoutesApi(HttpRouter http, Configuration configuration = null)
        {
            if (configuration == null) // use the default one in Configuration
            {
                Configuration = Configuration.Default;
            }
            else
            {
                Configuration = configuration;
            }

            if (http.Url == null)
            {
                throw new NullReferenceException("Url cannot be null");
            }
            Configuration.ApiClient = new ApiClient(http.Url);

            ExceptionFactory = Configuration.DefaultExceptionFactory;

            // ensure API client has configuration ready
            if (Configuration.ApiClient.Configuration == null)
            {
                Configuration.ApiClient.Configuration = Configuration;
            }
        }
        public async Task MatchOnContextUsingCustomValuePredicate()
        {
            var resolver = new HttpRouteResolver();



            var path        = "api/values/0";
            var customKey   = "MyCustomContextKey";
            var customValue = "MyCustomValue";

            // this pluming is to extract which host are we going to use to route


            var headMatcher = new HttpSetMethodMatcher(HttpMethod.Get);

            // whenever our custom predicate return true we will route the traffic to server 2
            headMatcher.Chain(new SetAddressListMatcher(Srv02HostNamePort),
                              new ContextCustomValueMatcher(customKey, (k, v) =>
            {
                var ar = v as string[];
                if (null == ar)
                {
                    return(false);
                }

                if (ar.Length == 3)
                {
                    return(true);
                }

                return(false);
            }));


            await resolver.AddMatcherAsync(headMatcher, 0);

            var router = new HttpRouter(resolver);



            var context = new Dictionary <string, object>();

            // context contains a custom value that is a string array
            context.Add(customKey, new string[] { customValue, customValue, customValue });


            var results = await router.RouteAsync(string.Concat(srv01Address, path), context);


            var responseMessage = await results.ResultAsAsync <HttpResponseMessage>();

            var responseString = await responseMessage.Content.ReadAsStringAsync();

            // server returns the address
            // in the response

            Assert.AreEqual(string.Concat(srv02Address, path), responseString);
        }
Ejemplo n.º 8
0
        public static void Main(string[] args)
        {
            Configuration = new Configuration();
            if (!File.Exists("config.json"))
            {
                File.WriteAllText("config.json", JsonConvert.SerializeObject(Configuration, Formatting.Indented));
                Console.WriteLine("Empty config.json file created. Populate it and restart.");
                return;
            }
            JsonConvert.PopulateObject(File.ReadAllText("config.json"), Configuration);
            File.WriteAllText("config.json", JsonConvert.SerializeObject(Configuration, Formatting.Indented));

            if (Configuration.Irc.Enabled)
            {
                IrcBot = new IrcBot();
            }
            var httpd  = new HttpServer();
            var router = new HttpRouter();

            httpd.LogRequests = Configuration.LogRequests;
            httpd.Request     = router.Route;

            var staticContent = new StaticContentHandler(Configuration.MusicPath);

            router.AddRoute(new StaticContentRoute(staticContent));
            var staticResources = new StaticContentHandler(Path.Combine(".", "Static"));

            router.AddRoute(new StaticContentRoute(staticResources));

            var mvc = new MvcRouter();

            mvc.RegisterController(new IndexController());
            mvc.AddRoute("Default", "{action}", new { controller = "Index", action = "Index" });
            router.AddRoute(mvc);

            router.AddRoute(new RegexRoute("/download/(?<path>.*)", (context, request, response) =>
            {
                response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", Path.GetFileName(context["path"])));
                staticContent.Serve(context["path"], request, response);
            }));

            MusicRunner.Start();
            httpd.Start(new IPEndPoint(IPAddress.Parse(Configuration.EndPoint), Configuration.Port));
            if (Configuration.Irc.Enabled)
            {
                IrcBot.Start();
            }

            Console.WriteLine("Type 'quit' to exit, or 'help' for help.");
            string command = null;

            while (command != "quit")
            {
                command = Console.ReadLine();
                HandleCommand(command);
            }
        }
Ejemplo n.º 9
0
        public async Task FastestRoute()
        {
            var resolver = new HttpRouteResolver();



            /*
             *  anything point to http://localhost:9001
             *  will be routed as fastest route to
             *  http://locahost:9002 or http://locahost:9003
             *
             *  With HttpGet + Same path
             *
             */



            var path         = "api/randomdelay/0";
            var trytimes     = 5;
            var firstMatcher = new HttpSetMethodMatcher(HttpMethod.Get);

            firstMatcher.Chain(new SetAddressListMatcher(new string[] { Srv01HostNamePort, Srv02HostNamePort, Srv03HostNamePort }, false, ContextRoutingType.FastestRoute),
                               new HostAddressMatcher(Srv01HostNamePort, StringMatchType.UriHostandPortMatch));


            await resolver.AddMatcherAsync(firstMatcher, 0);


            var router        = new HttpRouter(resolver);
            var resultsList   = new List <HttpRoutingResult>(trytimes);
            var responsesList = new HashSet <string>();

            // call as many as try times
            for (var i = 1; i <= trytimes; i++)
            {
                resultsList.Add(await router.RouteAsync(string.Concat(srv01Address, path)));
            }

            foreach (var result in resultsList)
            {
                var responseMessage = await result.ResultAsAsync <HttpResponseMessage>();

                var responseString = await responseMessage.Content.ReadAsStringAsync();

                responsesList.Add(responseString);
            }



            // server returns the address
            // in the response
            // any count > 1 means that router is routing to more than one end point
            Assert.AreEqual(true, responsesList.Count > 1);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Initializes the ModuleClient and sets up the callback to receive
        /// messages containing temperature information
        /// </summary>
        static async Task Init()
        {
            MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);

            ITransportSettings[] settings = { mqttSetting };

            // Open a connection to the Edge runtime
            ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);

            await ioTHubModuleClient.OpenAsync();

            WriteLog("IoT Hub module client initialized.");

            var connectionString = Environment.GetEnvironmentVariable("STORAGE_CONNECTION_STRING");
            var containerName    = Environment.GetEnvironmentVariable("RESULT_CONTAINER_NAME");
            var storageAccount   = CloudStorageAccount.Parse(connectionString);
            var cloudBlobClient  = storageAccount.CreateCloudBlobClient();

            cloudBlobContainer = cloudBlobClient.GetContainerReference(containerName);
            await cloudBlobContainer.CreateIfNotExistsAsync();

            // XXX 環境変数に
            videoInputStream = new VideoInputStream(0);
            videoInputStream.Start();

            var rtmpUri = Environment.GetEnvironmentVariable("RTMP_URI");

            // XXX Size
            videoLiveStream = new FfmpegRtmpVideoOutputStream(rtmpUri, fps, new Size(320, 240));
            videoLiveStream.Start();

            caption = new CaptionRequest {
                Caption = ""
            };
            captionFont = new System.Drawing.Font("noto", 15f);
            smallFont   = new System.Drawing.Font("noto", 10f);

            frameTimer          = new System.Timers.Timer(1.0 / fps);
            frameTimer.Elapsed += UpdateFrame;
            frameTimer.Start();

            http = new HttpRouter(new string[] { "http://+:80/" });
            http.Register("/caption", SetCaption);
            http.Register("/video/start", StartRecording);
            http.Register("/video/end", EndRecording);
            http.Register("/photo", TakePhoto);
            http.Register("/photo_with_caption", TakePhotoWithCaption);
            http.Start();

            await Task.CompletedTask;
        }
Ejemplo n.º 11
0
        public async Task AggregateMultipleEndPoints()
        {
            var resolver = new HttpRouteResolver();


            /*
             *  anything point to http://localhost:9001
             *  will be routed as  be aggregated from multiple backend endpoints
             *
             *  With HttpGet + Same path
             *
             */



            var path  = "api/randomdelay/0";
            var Hosts = 3;



            var firstMatcher = new HttpSetMethodMatcher(HttpMethod.Get);

            firstMatcher.Chain(new SetAddressListMatcher(new string[] { Srv01HostNamePort, Srv02HostNamePort, Srv03HostNamePort }, false, ContextRoutingType.ScatterGather),
                               new HostAddressMatcher(Srv01HostNamePort, StringMatchType.UriHostandPortMatch));


            await resolver.AddMatcherAsync(firstMatcher, 0);


            var router = new HttpRouter(resolver);

            var resultsList   = new List <HttpRoutingResult>(Hosts);
            var responsesList = new HashSet <string>();

            // call as many as try times
            var allResults = await router.RouteAsync(string.Concat(srv01Address, path));

            foreach (var result in await allResults.ResultAsAsync <List <HttpResponseMessage> >())
            {
                var responseString = await result.Content.ReadAsStringAsync();

                responsesList.Add(responseString);
            }

            Assert.IsTrue(responsesList.Count == 3); // all hosts in the system
        }
        public async Task RetryThenRoute()
        {
            var resolver = new HttpRouteResolver();



            /*
             *  Attempt to an address (that will fail), then retry after 10 ms, if still failing
             *  it will route to a different server.
             */



            var path = "api/values/0";


            var headMatcher = new HttpSetMethodMatcher(HttpMethod.Get);

            headMatcher.Chain(new SetAddressListMatcher("fail"), // point to an address that does not exist (i really hope that you have a machine on your network named "fail")
                              new HostAddressMatcher(Srv01HostNamePort, StringMatchType.UriHostandPortMatch));


            await resolver.AddMatcherAsync(headMatcher, 0);


            var router = new HttpRouter(resolver);

            var headStrategy = new RetryAfterStrategy(10);

            // chain
            headStrategy.ThenRouteToHost(Srv02HostNamePort);

            router.DefaultContextExecuteStrategy = headStrategy;

            var results = await router.RouteAsync(string.Concat(srv01Address, path));


            var responseMessage = await results.ResultAsAsync <HttpResponseMessage>();

            var responseString = await responseMessage.Content.ReadAsStringAsync();

            // server returns the address
            // in the response

            Assert.AreEqual(string.Concat(srv02Address, path), responseString);
        }
        public async Task MatchUsingCustomPredicate()
        {
            var resolver = new HttpRouteResolver();



            var path = "api/values/0";



            var headMatcher = new HttpSetMethodMatcher(HttpMethod.Get);

            // whenever our custom predicate return true we will route the traffic to server 2

            headMatcher.Chain(new SetAddressListMatcher(Srv02HostNamePort),
                              new PredicateMatcher((routingctx, address, ctx, body) =>
            {
                return(true);
            }));


            await resolver.AddMatcherAsync(headMatcher, 0);

            var router = new HttpRouter(resolver);



            var context = new Dictionary <string, object>();
            // context contains a custom value that is a string array



            var results = await router.RouteAsync(string.Concat(srv01Address, path), context);


            var responseMessage = await results.ResultAsAsync <HttpResponseMessage>();

            var responseString = await responseMessage.Content.ReadAsStringAsync();

            // server returns the address
            // in the response

            Assert.AreEqual(string.Concat(srv02Address, path), responseString);
        }
Ejemplo n.º 14
0
        public static IHttpService UseHttp2(this IConnectionService @this, Action <Http2Options, HttpRouter> handler)
        {
            if (@this == null)
            {
                throw new ArgumentNullException(nameof(@this));
            }
            if (handler == null)
            {
                throw new ArgumentNullException(nameof(handler));
            }

            var optionsValue = new Http2Options();
            var router       = new HttpRouter();

            handler.Invoke(optionsValue, router);
            if (optionsValue.Certificate == null)
            {
                throw new ArgumentNullException(nameof(optionsValue.Certificate));
            }
            var http1 = new HttpService(
                optionsValue.Http1KeepAliveTimeout,
                optionsValue.Http1ReceiveTimeout,
                optionsValue.Http1SendTimeout,
                optionsValue.Http1MaxHeaderSize
                );

            http1.Handler = router;
            var http2 = new Http2Service(
                optionsValue.KeepAliveTimeout,
                optionsValue.ReceiveTimeout,
                optionsValue.SendTimeout,
                optionsValue.MaxConcurrentStreams,
                optionsValue.InitialWindowSize,
                optionsValue.MaxHeaderListSize,
                optionsValue.MaxSettings
                );

            http2.Handler = router;
            var service = new Service(http1, http2, optionsValue.Certificate, optionsValue.HandShakeTimeout);

            @this.Handler = service;
            return(service);
        }
        public async Task MatchOnContextContainsKeyWithStringValue()
        {
            var resolver = new HttpRouteResolver();



            var path        = "api/values/0";
            var customKey   = "MyCustomContextKey";
            var customValue = "MyCustomValue";



            var headMatcher = new HttpSetMethodMatcher(HttpMethod.Get);

            headMatcher.Chain(new SetAddressListMatcher(Srv02HostNamePort),
                              new ContextValueStringMatcher(customKey, customValue, StringMatchType.Exact));


            await resolver.AddMatcherAsync(headMatcher, 0);

            var router = new HttpRouter(resolver);



            var context = new Dictionary <string, object>();

            context.Add(customKey, customValue);


            var results = await router.RouteAsync(string.Concat(srv01Address, path), context);


            var responseMessage = await results.ResultAsAsync <HttpResponseMessage>();

            var responseString = await responseMessage.Content.ReadAsStringAsync();

            // server returns the address
            // in the response

            Assert.AreEqual(string.Concat(srv02Address, path), responseString);
        }
        public async Task RemoveHeader()
        {
            var resolver = new HttpRouteResolver();



            var path              = "api/Headers/0";
            var customHeaderName  = "customHeader";
            var customHeaderValue = "customHeaderValue";


            var headMatcher = new HttpSetMethodMatcher(HttpMethod.Get);

            headMatcher.Chain(new SetAddressListMatcher(Srv02HostNamePort),
                              new HttpRemoveHeaderMatcher(customHeaderName),
                              new HttpAddSetHeaderMatcher(customHeaderName, customHeaderValue),
                              new HostAddressMatcher(Srv01HostNamePort, StringMatchType.UriHostandPortMatch));


            await resolver.AddMatcherAsync(headMatcher, 0);


            var router = new HttpRouter(resolver);



            var results = await router.RouteAsync(string.Concat(srv01Address, path));


            var responseMessage = await results.ResultAsAsync <HttpResponseMessage>();

            var responseString = await responseMessage.Content.ReadAsStringAsync();


            var dict = JsonConvert.DeserializeObject <Dictionary <string, IEnumerable <string> > >(responseString);


            // server returns the headers in the response

            Assert.AreEqual(false, dict.ContainsKey(customHeaderName));
        }
        public async Task MatchOnIIFMatcher()
        {
            var resolver = new HttpRouteResolver();



            var path      = "api/values/0";
            var customKey = "MyCustomContextKey";


            var headMatcher = new HttpSetMethodMatcher(HttpMethod.Get);

            // Whenever a context contains a key we will route all the traffic to server02
            headMatcher.Chain(

                new IIFMatcher(
                    new ContextContainsKeyMatcher(customKey, StringMatchType.Exact),
                    new SetAddressListMatcher(Srv02HostNamePort),
                    new SetAddressListMatcher(Srv03HostNamePort)
                    )
                );


            await resolver.AddMatcherAsync(headMatcher, 0);

            var router = new HttpRouter(resolver);



            var results = await router.RouteAsync(string.Concat(srv01Address, path));


            var responseMessage = await results.ResultAsAsync <HttpResponseMessage>();

            var responseString = await responseMessage.Content.ReadAsStringAsync();

            // server returns the address
            // in the response

            Assert.AreEqual(string.Concat(srv03Address, path), responseString);
        }
        public async Task MatchUsingOrMatcher()
        {
            var resolver = new HttpRouteResolver();



            var path = "api/values/0";

            // if true || False then set address to serve2 and method to get
            var headMatcher = new HttpSetMethodMatcher(HttpMethod.Get);


            headMatcher.Chain(new SetAddressListMatcher(Srv02HostNamePort),
                              new OrMatcher(
                                  new FalseMatcher(),
                                  new TrueMatcher()
                                  )
                              );


            await resolver.AddMatcherAsync(headMatcher, 0);


            var router = new HttpRouter(resolver);



            var results = await router.RouteAsync(string.Concat(srv01Address, path));


            var responseMessage = await results.ResultAsAsync <HttpResponseMessage>();

            var responseString = await responseMessage.Content.ReadAsStringAsync();

            // server returns the address
            // in the response

            Assert.AreEqual(string.Concat(srv02Address, path), responseString);
        }
        public async Task MatchUsingAndMatcher()
        {
            var resolver = new HttpRouteResolver();


            var path = "api/values/0";

            // if host name = srv1's name and port srv1's port then set the address to server 2 and http method to get.
            var headMatcher = new HttpSetMethodMatcher(HttpMethod.Get);


            headMatcher.Chain(new SetAddressListMatcher(Srv02HostNamePort),
                              new AndMatcher(
                                  new HostAddressMatcher(srv01Uri.Port.ToString(), StringMatchType.UriHostPortMatch),
                                  new HostAddressMatcher(srv01Uri.Host, StringMatchType.UriHostNameMatch)
                                  )
                              );


            await resolver.AddMatcherAsync(headMatcher, 0);


            var router = new HttpRouter(resolver);



            var results = await router.RouteAsync(string.Concat(srv01Address, path));


            var responseMessage = await results.ResultAsAsync <HttpResponseMessage>();

            var responseString = await responseMessage.Content.ReadAsStringAsync();

            // server returns the address
            // in the response

            Assert.AreEqual(string.Concat(srv02Address, path), responseString);
        }
        public async Task BasicTelemetry()
        {
            var resolver = new HttpRouteResolver();



            var path = "api/values/0";
            // this pluming is to extract which host are we going to use to route


            var headMatcher = new HttpSetMethodMatcher(HttpMethod.Get);

            headMatcher.Chain(new SetAddressListMatcher(Srv02HostNamePort),
                              new HostAddressMatcher(Srv01HostNamePort, StringMatchType.UriHostandPortMatch));


            await resolver.AddMatcherAsync(headMatcher, 0);


            var router = new HttpRouter(resolver);



            var results = await router.RouteAsync(string.Concat(srv01Address, path));


            var responseMessage = await results.ResultAsAsync <HttpResponseMessage>();

            var responseString = await responseMessage.Content.ReadAsStringAsync();

            // server returns the address
            // in the response

            Assert.AreEqual(string.Concat(srv02Address, path), responseString);
            Assert.IsTrue(router.TotalExecutedLastMin > 0);
            Assert.IsTrue(router.TotalResolvedLastMin > 0);
        }
Ejemplo n.º 21
0
        public async Task OverrideSchemeAndPath()
        {
            var resolver = new HttpRouteResolver();



            var path = "api/values/0";

            /*
             *  route to server 2 override the scheme to http & path to a static path
             */


            var headMatcher = new HttpSetMethodMatcher(HttpMethod.Get);

            headMatcher.Chain(new SetAddressListMatcher(Srv02HostNamePort),
                              new HttpOverridePathMatcher("/api/values/0"),
                              new HttpOverrideSchemeMatcher("http"),
                              new HostAddressMatcher(Srv01HostNamePort, StringMatchType.UriHostandPortMatch));


            await resolver.AddMatcherAsync(headMatcher, 0);

            var router = new HttpRouter(resolver);

            var results = await router.RouteAsync(string.Concat("xxx://", Srv01HostNamePort)); // bad scehme & no path

            var responseMessage = await results.ResultAsAsync <HttpResponseMessage>();

            var responseString = await responseMessage.Content.ReadAsStringAsync();

            // server returns the address
            // in the response

            Assert.AreEqual(string.Concat(srv02Address, path), responseString);
        }
Ejemplo n.º 22
0
        private async Task <HttpRouter> GetRouter()
        {
            /*
             * factory create a instance of SocketSession for incoming connection.
             * in this test we will create a router attached it to the factory (which is injected in every socket session)
             *
             */

            // prepare the router
            var resolver = new HttpRouteResolver();


            // routing logic

            //-> If context contains GetModels (route to backend(s), fastest route, add scheme, add path, ignore body, set HttpMethod to Get)


            var getModelsMatchers = new HttpSetMethodMatcher(HttpMethod.Get);

            getModelsMatchers.Chain(new IgnoreSourceBodyStreamMatcher(),                                                                                                             // ignore whatever message body provided by the socket.
                                    new SetAddressListMatcher(new string[] { RouterTestSuit.Srv01HostNamePort, RouterTestSuit.Srv02HostNamePort, RouterTestSuit.Srv03HostNamePort }, // address list
                                                              true,                                                                                                                  // clear whatever there
                                                              ContextRoutingType.FastestRoute),                                                                                      // fastest
                                    new HttpOverridePathMatcher("/api/models/"),                                                                                                     // add path
                                    new HttpOverrideSchemeMatcher("http"),                                                                                                           // add scheme
                                    new ContextValueStringMatcher("Message.Type", "GetModels"));



            //-> If context contains AddModels
            var addModelsMatcher = new HttpSetMethodMatcher(HttpMethod.Post);

            addModelsMatcher.Chain(
                new SetAddressListMatcher(RouterTestSuit.Srv01HostNamePort),     // set address to Server1
                new HttpAddSetHeaderMatcher("Content-Type", "application/json"), // my socket puts everything as json
                new HttpOverridePathMatcher("/api/models/"),                     // add path
                new HttpOverrideSchemeMatcher("http"),                           // add scheme
                new ContextValueStringMatcher("Message.Type", "AddModels")
                );



            // There are multiple ways i can do use the above matchers

            /* method 1) use Or matcher
             *  var orMatcher = new OrMatcher(getModelsMatchers, addModelsMatcher);
             *  await resolver.AddMatcherAsync(orMatcher, 0);
             */

            /* method 2) use AnyMatcher
             *  var anyMatcher = new AnyMatcher(getModelsMatchers, addModelsMatcher);
             *  await resolver.AddMatcherAsync(anyMatcher, 0);
             */

            // method 3) use the  new ContextValueStringMatcher("Message.Type", "AddModels") in an IIF matcher (remember to remove them from Add/Get matcher variables above).


            // or just create differet matchers in resolvers. the advantages, if each tree wants to cache and have state on thier
            // they will do that without conficlts (check how load balanacer is used in HttpRoutingContext).

            await resolver.AddMatcherAsync(getModelsMatchers, 0);

            await resolver.AddMatcherAsync(addModelsMatcher, 1);

            var router = new HttpRouter(resolver);

            return(router);
        }
Ejemplo n.º 23
0
        public async Task SimpleLoadBalance()
        {
            var resolver = new HttpRouteResolver();



            /*
             *  anything point to http://localhost:9001
             *  will be routed R/R balanced to
             *  http://locahost:9001
             *  http://locahost:9002
             *  http://locahost:9003
             *
             *  With HttpGet + Same path
             */



            var path     = "/api/values/0";
            var trytimes = 3;



            var firstMatcher = new HttpSetMethodMatcher(HttpMethod.Get);

            firstMatcher.Chain(new SetAddressListMatcher(new string[] { Srv01HostNamePort, Srv02HostNamePort, Srv03HostNamePort }, false, ContextRoutingType.RoundRobin),
                               new HostAddressMatcher(Srv01HostNamePort, StringMatchType.UriHostandPortMatch));


            await resolver.AddMatcherAsync(firstMatcher, 0);


            var router = new HttpRouter(resolver);



            var resultsList   = new List <HttpRoutingResult>(trytimes);
            var responsesList = new HashSet <string>();

            // call as many as try times
            for (var i = 1; i <= trytimes; i++)
            {
                resultsList.Add(await router.RouteAsync(string.Concat(srv01Address, path)));
            }

            foreach (var result in resultsList)
            {
                var responseMessage = await result.ResultAsAsync <HttpResponseMessage>();

                var responseString = await responseMessage.Content.ReadAsStringAsync();

                responsesList.Add(responseString);
            }


            // response list should contain
            // http <server1> + path
            // http <server2> + path
            // http <server3> + path



            var expectedList = new List <string>()
            {
                string.Concat("http://", Srv01HostNamePort, path),
                string.Concat("http://", Srv02HostNamePort, path),
                string.Concat("http://", Srv03HostNamePort, path)
            };

            foreach (var response in responsesList)
            {
                if (expectedList.Contains(response))
                {
                    expectedList.Remove(response);
                }
            }

            Assert.IsTrue(expectedList.Count == 0); // all hosts in the system
        }
Ejemplo n.º 24
0
        public async Task LongLoadBalance()
        {
            var resolver = new HttpRouteResolver();


            /*
             *  anything point to http://localhost:9001
             *  will be routed R/R balanced to
             *  http://locahost:9001
             *  http://locahost:9002
             *  http://locahost:9003
             *
             *  With HttpGet + Same path
             */



            var path     = "/api/values/0";
            var trytimes = 9;
            // this pluming is to extract which host are we going to use to route



            var firstMatcher = new HttpSetMethodMatcher(HttpMethod.Get);

            firstMatcher.Chain(new SetAddressListMatcher(new string[] { Srv01HostNamePort, Srv02HostNamePort, Srv03HostNamePort }, false, ContextRoutingType.RoundRobin),
                               new HostAddressMatcher(Srv01HostNamePort, StringMatchType.UriHostandPortMatch));


            await resolver.AddMatcherAsync(firstMatcher, 0);


            var router = new HttpRouter(resolver);



            var resultsList   = new List <HttpRoutingResult>(trytimes);
            var responsesList = new Dictionary <string, int>();

            // call as many as try times
            for (var i = 1; i <= trytimes; i++)
            {
                resultsList.Add(await router.RouteAsync(string.Concat(srv01Address, path)));
            }

            foreach (var result in resultsList)
            {
                var responseMessage = await result.ResultAsAsync <HttpResponseMessage>();

                var responseString = await responseMessage.Content.ReadAsStringAsync();

                if (!responsesList.ContainsKey(responseString))
                {
                    responsesList.Add(responseString, 1);
                }
                else
                {
                    responsesList[responseString] = ++responsesList[responseString];
                }
            }

            var bSucess = true;

            // validate that each is called exactly 3 times
            foreach (var key in responsesList.Keys)
            {
                if (responsesList[key] != 3)
                {
                    bSucess = false;
                    break;
                }
            }



            Assert.IsTrue(bSucess); // all hosts in the system
        }
Ejemplo n.º 25
0
 public Routes(HttpRouter router)
 {
     this.router = router;
 }
Ejemplo n.º 26
0
 public WSocketSessionFactory(HttpRouter router)
 {
     Router = router;
 }
Ejemplo n.º 27
0
        public static void Run()
        {
            var router = new HttpRouter();

            //var getTree= router.GetTree;
            //var postTree = router.PostTree;
            //var headTree = router.HeadTree;
            //var putTree = router.PutTree;
            //var deleteTree = router.DeleteTree;

            router.MapGet("/get/index", (req, resp) => Console.WriteLine("/get/index"));
            //不支持参数约束,前缀,后缀 繁琐而且用处不大
            //Not support parameter constraints,prefix,suffix tedious and useless
            router.MapGet("/get/{param1}/{param2}", (req, resp) => Console.WriteLine("/get/{param1}/{param2}"));
            router.MapGet("/get/{*catchAll}", (req, resp) => Console.WriteLine("/get/{*catchAll}"));
            Console.WriteLine("MapGet");
            foreach (var item in router.GetTree)
            {
                Console.WriteLine(item.Key);
            }

            //MapAttribute
            var compiler = new HandlerCompiler();//See HandlerCompilerSample

            //compiler.Register()
            router.MapAttribute(new[] { typeof(TestService) }, compiler);
            //customize
            router.MapAttribute(new[] { typeof(TestService) }, compiler,
                                (method, typeHandlers, methodHandlers, handler) =>
            {
                var handlers = new List <IHttpHandler>();
                handlers.Add(HttpHandler.CreateModule((req, handler) =>
                {
                    Console.WriteLine("Before typeHandlers");
                    return(handler.HandleAsync(req));
                }));
                handlers.AddRange(typeHandlers);
                handlers.Add(HttpHandler.CreateModule((req, handler) =>
                {
                    Console.WriteLine("Before methodHandlers");
                    return(handler.HandleAsync(req));
                }));
                handlers.AddRange(methodHandlers);
                handlers.Add(handler);
                return(HttpHandler.CreatePipeline(handlers));
            });
            //router.MapAttribute(compiler);
            //router.MapAttribute(handlerDelegate)
            Console.WriteLine();
            Console.WriteLine("MapAttribute");
            foreach (var item in router.GetTree)
            {
                Console.WriteLine(item.Key);
            }


            Directory.CreateDirectory("Static");
            File.WriteAllText("Static/testFile.txt", "this is file content.BY 张贺", new UTF8Encoding(false));
            File.WriteAllText("Static/testHtml1.html", "<h1>testHtml1<h1>", new UTF8Encoding(false));
            File.WriteAllText("Static/testHtml2.html", "<h2>testHtml2<h2>", new UTF8Encoding(false));
            //MapFile
            router.MapFile("/testFile1", "Static/testFile.txt", 86400);//CacheControl
            router.MapFile("/testFile2", "Static/testFile.txt", "text/html; charset=utf-8", 86400);
            //MapFiles
            router.MapFiles("/static1/{*path}", "Static", 86400);
            var customMimeTypes = new MimeTypes();

            //var customMimeTypes = new MimeTypes(MimeTypes.Default);
            customMimeTypes.Add(".html", "text/html; charset=utf-8");
            router.MapFiles("/static2/{*customName}", "Static", customMimeTypes, 86400, "customName");
            //router.MapFiles("/static2/{*customName}", "Static", MimeTypes.Default, TimeSpan.FromDays(1), "customName");


            //MapSlash
            //尾部/
            router.GetTree.MapSlash();
            //router.MapSlash();
            Console.WriteLine();
            Console.WriteLine("MapSlash");
            foreach (var item in router.GetTree)
            {
                Console.WriteLine(item.Key);
            }

            //动态路由
            //Dynamic change router
            //CopyOnWrite(Safe)
            var newGetTree = new HttpRouter.Tree();

            newGetTree.Map("/new/index", HttpHandler.Create((req, resp) => { Console.WriteLine("/new/index"); }));
            newGetTree.Map("/new/{param1}/{param2}", HttpHandler.Create((req, resp) => { Console.WriteLine("/new/{param1}/{param2}"); }));
            newGetTree.Map("/new/{*catchAll}", HttpHandler.Create((req, resp) => { Console.WriteLine("/new/{*catchAll}"); }));
            newGetTree.MapSlash();
            newGetTree.MapTree(router.GetTree);
            router.GetTree = newGetTree;
            Console.WriteLine();
            Console.WriteLine("NewGetTree");
            foreach (var item in router.GetTree)
            {
                Console.WriteLine(item.Key);
            }

            //Match
            Console.WriteLine();
            Console.WriteLine("Match");
            var params1 = new PathParams();
            var h1      = router.GetTree.Match("/attribute/index", params1);

            Console.WriteLine(params1.Count);
            var params2 = new PathParams();
            var h2      = router.GetTree.Match("/attribute/p1/x/y", params2);

            Console.WriteLine(params2.Count);
            var params3 = new PathParams();
            var h3      = router.GetTree.Match("/attribute/catchAll/x/y/z//", params3);

            Console.WriteLine(params3.Count);

            //HandleAsync
            Console.WriteLine();
            Console.WriteLine("HandleAsync");
            var req1 = new HttpRequest("/attribute/index")
            {
                Method = HttpMethod.Get
            };
            var resp1 = router.HandleAsync(req1).Result;
            var req2  = new HttpRequest("/attribute/p1/x/y")
            {
                Method = HttpMethod.Get
            };
            var resp2 = router.HandleAsync(req2).Result;
            var req3  = new HttpRequest("/attribute/catchAll/x/y/z//")
            {
                Method = HttpMethod.Get
            };
            var resp3 = router.HandleAsync(req3).Result;

            var req4 = new HttpRequest("/testFile1")
            {
                Method = HttpMethod.Get
            };
            var resp4 = router.HandleAsync(req4).Result;

            Console.WriteLine(resp4.Content.ReadStringAsync().Result);
            var req5 = new HttpRequest("/testFile2")
            {
                Method = HttpMethod.Head
            };
            var resp5 = router.HandleAsync(req5).Result;

            Console.WriteLine(resp5.Content.ReadStringAsync().Result);
            var req6 = new HttpRequest("/static1/testHtml1.html")
            {
                Method = HttpMethod.Get
            };
            var resp6 = router.HandleAsync(req6).Result;

            Console.WriteLine(resp6.Content.ReadStringAsync().Result);
            var req7 = new HttpRequest("/static2/testHtml2.html")
            {
                Method = HttpMethod.Get
            };
            var resp7 = router.HandleAsync(req7).Result;

            Console.WriteLine(resp7.Content.ReadStringAsync().Result);


            //------------------------------------------------------------------------
            //router chain(HttpRouter is IHttpHandler)
            var router1 = new HttpRouter();
            var router2 = new HttpRouter();//var tree1 = new HttpRouter.Tree();

            router2.MapGet("/{*path}", (req, resp) => {
                Console.WriteLine(nameof(router2));
                Console.WriteLine(req.PathParams().GetValue <string>("path"));
            });
            router1.GetTree.Map("/Images/{*img}", router2);
            router1.GetTree.Map("/Js/{*js}", HttpHandler.Create(
                                    (req) => {
                Console.WriteLine("Js");
                return(router2.HandleAsync(req));
            }));

            Console.WriteLine();
            var req8 = new HttpRequest("/Images/123456.png")
            {
                Method = HttpMethod.Get
            };
            var resp8 = router1.HandleAsync(req8).Result;
            var req9  = new HttpRequest("/Js/jq.js")
            {
                Method = HttpMethod.Get
            };
            var resp9 = router1.HandleAsync(req9).Result;

            //------------------------------------------------------------------------
            //special
            // /path1/{param1} Match /path1/  (if not Map /path1/)
            var router3 = new HttpRouter();

            router3.MapGet("/", (req, resp) => { Console.WriteLine("/"); });
            router3.MapGet("/{param1}", (req, resp) => { Console.WriteLine("/{param1}"); });
            var req10 = new HttpRequest("/")
            {
                Method = HttpMethod.Get
            };
            var resp10 = router3.HandleAsync(req10).Result;

            var router4 = new HttpRouter();

            //router4.MapGet("/", (req, resp) => { Console.WriteLine("/"); });
            router4.MapGet("/{param1}", (req, resp) => { Console.WriteLine("/{param1}"); });
            var req11 = new HttpRequest("/")
            {
                Method = HttpMethod.Get
            };
            var resp11 = router4.HandleAsync(req11).Result;

            // multiple /
            var router5 = new HttpRouter();

            router5.MapGet("////", (req, resp) => { Console.WriteLine("////"); });
            var req12 = new HttpRequest("////")
            {
                Method = HttpMethod.Get
            };
            var resp12 = router5.HandleAsync(req12).Result;

            router5.MapGet("/Path1/{param1}/{param2}/", (req, resp) => { Console.WriteLine("/Path1/{param1}/{param2}/"); });
            //OR /Path1/{param1}/{param2}/{param3}
            var req13 = new HttpRequest("/Path1///")
            {
                Method = HttpMethod.Get
            };
            var resp13 = router5.HandleAsync(req13).Result;
        }