Exemple #1
0
        public async Task <Response> Shutdown(Request request)
        {
            if (_serverState == ServerState.Online)
            {
                lock (_shutdownMonitor)
                {
                    if (_serverState == ServerState.Online)
                    {
                        _serverState = ServerState.Offline;
                    }
                }
            }

            int timeout;

            try
            {
                bool timeoutIsNumber = int.TryParse(request.Headers["timeout"], out timeout);

                if (!timeoutIsNumber)
                {
                    return(ResponseFactory.InvalidRequestResponse("Invalid timeout format."));
                }

                if (timeout <= 0)
                {
                    return(ResponseFactory.TimeoutResponse());
                }
            }
            catch (Exception)
            {
                return(ResponseFactory.InvalidRequestResponse("Invalid timeout format."));
            }

            _cancellationTokenSource.Cancel();

            Response response;

            try
            {
                await Task.Delay(timeout, _shutdownCompletionSource.Token);

                response = ResponseFactory.TimeoutResponse("The server is shutting down, waiting time expired.");
            }
            catch (OperationCanceledException)
            {
                response = ResponseFactory.SuccessResponse("Server shutdown successful.");
            }

            return(response);
        }
Exemple #2
0
        private async Task <Response> Receive(Request request)
        {
            bool pathExists = _queues.TryGetValue(request.Path, out var queue);

            if (!pathExists)
            {
                return(ResponseFactory.InvalidRequestResponse("The given path does not exist."));
            }

            int timeout;

            try
            {
                bool timeoutIsNumber = int.TryParse(request.Headers["timeout"], out timeout);

                if (!timeoutIsNumber)
                {
                    return(ResponseFactory.InvalidRequestResponse("Invalid timeout format."));
                }

                if (timeout <= 0)
                {
                    return(ResponseFactory.TimeoutResponse());
                }
            }
            catch (Exception)
            {
                return(ResponseFactory.InvalidRequestResponse("Invalid timeout format."));
            }

            JObject payload;

            try
            {
                payload = await queue.Dequeue(TimeSpan.FromMilliseconds(timeout), _cancellationTokenSource);
            }
            catch (TimeoutException)
            {
                return(ResponseFactory.TimeoutResponse());
            }

            return(ResponseFactory.SuccessResponse(payload));
        }