Exemple #1
0
        public async Task <bool> AddLogEntryAsync(byte[] data, string entityName = "default", int timeoutMs = 20000)
        {
            if (System.Threading.Interlocked.Read(ref disposed) == 1)
            {
                return(false);
            }

            RaftNode rn = null;

            if (this.raftNodes.TryGetValue(entityName, out rn))
            {
                //Generating externalId
                var msgId    = AsyncResponseHandler.GetMessageId();
                var msgIdStr = msgId.ToBytesString();
                var resp     = new ResponseCrate();
                resp.TimeoutsMs = timeoutMs; //enable for amre
                                             //resp.TimeoutsMs = Int32.MaxValue; //using timeout of the wait handle (not the timer), enable for mre

                //resp.Init_MRE();
                resp.Init_AMRE();

                AsyncResponseHandler.df[msgIdStr] = resp;

                var aler = rn.AddLogEntry(data, msgId);

                switch (aler.AddResult)
                {
                case AddLogEntryResult.eAddLogEntryResult.LOG_ENTRY_IS_CACHED:
                case AddLogEntryResult.eAddLogEntryResult.NODE_NOT_A_LEADER:

                    //async waiting
                    await resp.amre.WaitAsync();        //enable for amre

                    resp.Dispose_MRE();

                    if (AsyncResponseHandler.df.TryRemove(msgIdStr, out resp))
                    {
                        if (resp.IsRespOk)
                        {
                            return(true);
                        }
                    }

                    break;

                default:
                    //case AddLogEntryResult.eAddLogEntryResult.ERROR_OCCURED:
                    //case AddLogEntryResult.eAddLogEntryResult.NO_LEADER_YET:

                    resp.Dispose_MRE();
                    AsyncResponseHandler.df.TryRemove(msgIdStr, out resp);

                    return(false);
                }
            }

            //return new AddLogEntryResult { AddResult = AddLogEntryResult.eAddLogEntryResult.NODE_NOT_FOUND_BY_NAME };
            //return new Tuple<bool, byte[]>(false, null);
            return(false);
        }
Exemple #2
0
        /// <summary>
        /// Registers the controller.
        /// </summary>
        /// <param name="controllerType">Type of the controller.</param>
        /// <param name="controllerFactory">The controller factory method.</param>
        public void RegisterController(Type controllerType, Func <object> controllerFactory)
        {
            var protoDelegate      = new ResponseHandler((server, context) => true);
            var protoAsyncDelegate = new AsyncResponseHandler((server, context) => Task.FromResult(true));

            var methods = controllerType
                          .GetMethods(BindingFlags.Instance | BindingFlags.Public)
#if NET452
                          .Where(
                m => (m.ReturnType == protoDelegate.Method.ReturnType ||
                      m.ReturnType == protoAsyncDelegate.Method.ReturnType) &&
                m.GetParameters()
                .Select(pi => pi.ParameterType)
                .Take(2)
                .SequenceEqual(protoDelegate.Method.GetParameters()
#else
                          .Where(
                m => (m.ReturnType == protoDelegate.GetMethodInfo().ReturnType ||
                      m.ReturnType == protoAsyncDelegate.GetMethodInfo().ReturnType) &&
                      m.GetParameters()
                      .Select(pi => pi.ParameterType)
                      .Take(2)
                      .SequenceEqual(protoDelegate.GetMethodInfo().GetParameters()
#endif
                               .Select(pi => pi.ParameterType)));

            foreach (var method in methods)
            {
                var attribute =
                    method.GetCustomAttributes(typeof(WebApiHandlerAttribute), true).FirstOrDefault() as
                    WebApiHandlerAttribute;
                if (attribute == null)
                {
                    continue;
                }

                foreach (var path in attribute.Paths)
                {
                    if (_delegateMap.ContainsKey(path) == false)
                    {
                        _delegateMap.Add(path, new Dictionary <HttpVerbs, Tuple <Func <object>, MethodInfo> >()); // add
                    }

                    var delegatePair = new Tuple <Func <object>, MethodInfo>(controllerFactory, method);

                    if (_delegateMap[path].ContainsKey(attribute.Verb))
                    {
                        _delegateMap[path][attribute.Verb] = delegatePair; // update
                    }
                    else
                    {
                        _delegateMap[path].Add(attribute.Verb, delegatePair); // add
                    }
                }
            }

            _controllerTypes.Add(controllerType);
        }
Exemple #3
0
        private void OnAsyncResponse(ResponseMessage response)
        {
            AsyncResponseHandler async_response = (AsyncResponseHandler)this.handlers [response.GetType()];

            if (async_response != null)
            {
                async_response(response);
            }
        }
Exemple #4
0
        public void RegisterAsyncResponseHandler(Type t, AsyncResponseHandler handler)
        {
            if (!t.IsSubclassOf(typeof(ResponseMessage)))
            {
                throw new ArgumentException("Type must be a subclass of ResponsePayload");
            }

            this.handlers [t] = handler;
        }
Exemple #5
0
        /// <summary>
        /// Registers the controller.
        /// </summary>
        /// <param name="controllerType">Type of the controller.</param>
        /// <param name="controllerFactory">The controller factory method.</param>
        public void RegisterController(Type controllerType, Func <IHttpContext, object> controllerFactory)
        {
            if (_controllerTypes.Contains(controllerType))
            {
                throw new ArgumentException("Controller types must be unique within the module");
            }

            var protoDelegate      = new ResponseHandler(() => true);
            var protoAsyncDelegate = new AsyncResponseHandler(() => Task.FromResult(true));
            var methods            = controllerType.GetMethods(BindingFlags.Instance | BindingFlags.Public)
                                     .Where(m => m.ReturnType == protoDelegate.GetMethodInfo().ReturnType ||
                                            m.ReturnType == protoAsyncDelegate.GetMethodInfo().ReturnType);

            foreach (var method in methods)
            {
                var attribute = method.GetCustomAttributes(typeof(WebApiHandlerAttribute), true).FirstOrDefault() as WebApiHandlerAttribute;
                if (attribute == null)
                {
                    continue;
                }

                foreach (var path in attribute.Paths)
                {
                    if (_delegateMap.ContainsKey(path) == false)
                    {
                        _delegateMap.Add(path, new Dictionary <HttpVerbs, MethodCacheInstance>()); // add
                    }

                    var delegatePair = new MethodCacheInstance(controllerFactory, new MethodCache(method));

                    if (_delegateMap[path].ContainsKey(attribute.Verb))
                    {
                        _delegateMap[path][attribute.Verb] = delegatePair; // update
                    }
                    else
                    {
                        _delegateMap[path].Add(attribute.Verb, delegatePair); // add
                    }
                }
            }

            _controllerTypes.Add(controllerType);
        }
Exemple #6
0
        /// <summary>
        /// called by external service
        /// </summary>
        /// <param name="data"></param>
        /// <param name="entityName"></param>
        /// <param name="timeoutMs"></param>
        /// <returns></returns>

        public async Task <object> AddLogEntryRequestAsync(byte[] data, string entityName = "default", int timeoutMs = 20000)
        {
            if (System.Threading.Interlocked.Read(ref disposed) == 1)
            {
                return(false);
            }

            RaftStateMachine rn = this.raftNode;;

            {
                //Generating externalId
                var msgId    = AsyncResponseHandler.GetMessageId();
                var msgIdStr = msgId.ToBytesString();
                var resp     = new ResponseCrate();
                resp.TimeoutsMs = timeoutMs; //enable for amre
                resp.Init_AMRE();
                AsyncResponseHandler.df[msgIdStr] = resp;
                var aler = rn.logHandler.ProcessAddLogRequest(data, msgId);
                switch (aler.AddResult)
                {
                case AddLogEntryResult.eAddLogEntryResult.LOG_ENTRY_IS_CACHED:
                case AddLogEntryResult.eAddLogEntryResult.NODE_NOT_A_LEADER:
                    //async waiting
                    resp.amre.Wait();        //enable for amre
                    resp.Dispose_MRE();
                    if (AsyncResponseHandler.df.TryRemove(msgIdStr, out resp))
                    {
                        if (resp.IsRespOk)
                        {
                            return(resp.ReturnValue);
                        }
                    }
                    break;

                default:
                    resp.Dispose_MRE();
                    AsyncResponseHandler.df.TryRemove(msgIdStr, out resp);
                    return(resp.ReturnValue);
                }
            }
            return(null);
        }
        public async Task SimpleTest()
        {
            var asyncResponseHandler = new AsyncResponseHandler <string>(
                httpContext => httpContext.Request.Headers["r-key"],
                new NUnitJsonLogger());

            IWebHostBuilder builder = new WebHostBuilder()
                                      .UseKestrel()
                                      .ConfigureServices(services => services.AddMvc())
                                      .UseUrls(_baseUrl.Replace("localhost", "*"))
                                      .Configure(
                app =>
            {
                app.UseMvc(
                    routes => { routes.MapPost("test/url", asyncResponseHandler.RequestHandler); });
            });

            using (IWebHost host = builder.Build())
            {
                host.Start();
                Url           url      = new Url(_baseUrl).AppendPathSegment("test/url");
                Task <string> sendTask = url.WithHeader("r-key", "t1").PostStringAsync("test").ReceiveString();

                Task responseTask = asyncResponseHandler.WaitAndHandleAsyncResponse(
                    "t1",
                    async(key, httpContext) =>
                {
                    httpContext.Response.StatusCode  = 200;
                    httpContext.Response.ContentType = "text/plain";
                    await httpContext.Response.WriteAsync("Hello!");
                },
                    TimeSpan.FromSeconds(30));
                string result = await sendTask;
                TestContext.WriteLine(result);
                await responseTask;
            }
        }
Exemple #8
0
		public void RegisterAsyncResponseHandler (Type t, AsyncResponseHandler handler)
		{
			if (!t.IsSubclassOf (typeof (ResponseMessage)))
				throw new ArgumentException ("Type must be a subclass of ResponsePayload");

			this.handlers [t] = handler;
		}