<commit_before>using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Owin;
using Newtonsoft.Json;
using RElmah.Extensions;

namespace RElmah.Middleware
{
    internal static class Router
    {
        public delegate Task<object> AsyncHttpRequest(IDictionary<string, object> env, IDictionary<string, string> keys, IDictionary<string, string> form);

        public class Route
        {
            class AsyncHttpRequestHandler
            {
                public AsyncHttpRequest Executor { get; private set; }
                public Func<object, int> StatusCodeGenerator { get; private set; }
                public AsyncHttpRequestHandler(AsyncHttpRequest executor, Func<object, int> statusCodeGenerator = null)
                {
                    Executor = executor;
                    StatusCodeGenerator = statusCodeGenerator ?? (_ => (int)HttpStatusCode.OK);
                }

                public static readonly AsyncHttpRequestHandler Null = new AsyncHttpRequestHandler(async (_, __, ___) => await Task.FromResult((object) null));
            }

            private readonly ImmutableDictionary<string, AsyncHttpRequestHandler> _handlers = ImmutableDictionary<string, AsyncHttpRequestHandler>.Empty;

            Route()
            {
            }

            Route(Route r, string verb, AsyncHttpRequest handler, Func<object, int> statusCodeGenerator)
            {
                _handlers  = r._handlers.Add(verb, new AsyncHttpRequestHandler(handler, statusCodeGenerator));
            }

            public static Route Empty
            {
                get { return new Route(); }
            }

            private Route Handle(string verb, AsyncHttpRequest handler, Func<object, int> statusCodeGenerator = null)
            {
                return new Route(this, verb, handler, statusCodeGenerator);
            }

            public Route Get(AsyncHttpRequest handler, Func<object, int> statusCodeGenerator = null)
            {
                return Handle("GET",
                    handler,
                    statusCodeGenerator ?? (r => 
                        r == null
                        ? (int)HttpStatusCode.NotFound
                        : (int)HttpStatusCode.OK));
            }
            public Route Delete(AsyncHttpRequest handler, Func<object, int> statusCodeGenerator = null)
            {
                return Handle("DELETE", 
                    handler,
                    statusCodeGenerator ?? (r =>
                        r == null
                        ? (int)HttpStatusCode.NoContent
                        : (int)HttpStatusCode.OK));
            }

            public Route Put(AsyncHttpRequest handler, Func<object, int> statusCodeGenerator = null)
            {
                return Handle("PUT",
                    handler,
                    statusCodeGenerator ?? (r =>
                        r == null
                        ? (int)HttpStatusCode.NoContent
                        : (int)HttpStatusCode.OK));
            }
            
            public Route Post(AsyncHttpRequest handler, Func<object, int> statusCodeGenerator = null)
            {
                return Handle("POST",
                    handler,
                    statusCodeGenerator ?? (r =>
                        r == null
                        ? (int)HttpStatusCode.NoContent
                        : (int)HttpStatusCode.Created));
            }

            public async Task Invoke(IDictionary<string, object> environment, IDictionary<string, string> keys)
            {
                var completed = new TaskCompletionSource<bool>();

                try
                {          
                    var request  = new OwinRequest(environment);

                    var handler  = _handlers.GetValueOrDefault(request.Method, AsyncHttpRequestHandler.Null);

                    keys         = keys.ToDictionary(k => k.Key, v => WebUtility.UrlDecode(v.Value));

                    await ExecuteAsync(environment, keys, request, handler).ConfigureAwait(false);

                    completed.TrySetResult(true);
                }
                catch (Exception ex)
                {
                    completed.TrySetException(ex);

                    throw;
                }
            }

            static readonly IDictionary<string, string[]> EmptyForm = new Dictionary<string, string[]>();

            private async Task ExecuteAsync(
                IDictionary<string, object> environment, 
                IDictionary<string, string> keys, OwinRequest request,
                AsyncHttpRequestHandler handler)
            {
                var rs = new OwinResponse(environment);

                var rf = (Func<Task<object>>)(async () => handler.Executor(
                    environment,
                    keys,
                    from w in request.HasForm()
                                ? (IEnumerable<KeyValuePair<string, string[]>>)(await request.ReadFormAsync().ConfigureAwait(false))
                                : EmptyForm
                    select w != null ? w[0] : null));

                var r = await rf().ConfigureAwait(false);

                await rs.WriteAsync(JsonConvert.SerializeObject(r)).ConfigureAwait(false);

                rs.StatusCode = handler.StatusCodeGenerator != null
                                ? handler.StatusCodeGenerator(r)
                                : (int)HttpStatusCode.OK;

            }
        }<commit_msg>Readability<commit_after>using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Owin;
using Newtonsoft.Json;
using RElmah.Extensions;

namespace RElmah.Middleware
{
    internal static class Router
    {
        public delegate Task<object> AsyncHttpRequest(IDictionary<string, object> env, IDictionary<string, string> keys, IDictionary<string, string> form);

        public class Route
        {
            class AsyncHttpRequestHandler
            {
                public AsyncHttpRequest Executor { get; private set; }
                public Func<object, int> StatusCodeGenerator { get; private set; }
                public AsyncHttpRequestHandler(AsyncHttpRequest executor, Func<object, int> statusCodeGenerator = null)
                {
                    Executor = executor;
                    StatusCodeGenerator = statusCodeGenerator ?? (_ => (int)HttpStatusCode.OK);
                }

                public static readonly AsyncHttpRequestHandler Null = new AsyncHttpRequestHandler(async (_, __, ___) => await Task.FromResult((object) null));
            }

            private readonly ImmutableDictionary<string, AsyncHttpRequestHandler> _handlers = ImmutableDictionary<string, AsyncHttpRequestHandler>.Empty;

            Route()
            {
            }

            Route(Route r, string verb, AsyncHttpRequest handler, Func<object, int> statusCodeGenerator)
            {
                _handlers  = r._handlers.Add(verb, new AsyncHttpRequestHandler(handler, statusCodeGenerator));
            }

            public static Route Empty
            {
                get { return new Route(); }
            }

            private Route Handle(string verb, AsyncHttpRequest handler, Func<object, int> statusCodeGenerator = null)
            {
                return new Route(this, verb, handler, statusCodeGenerator);
            }

            public Route Get(AsyncHttpRequest handler, Func<object, int> statusCodeGenerator = null)
            {
                return Handle("GET",
                    handler,
                    statusCodeGenerator ?? (r => 
                        r == null
                        ? (int)HttpStatusCode.NotFound
                        : (int)HttpStatusCode.OK));
            }
            public Route Delete(AsyncHttpRequest handler, Func<object, int> statusCodeGenerator = null)
            {
                return Handle("DELETE", 
                    handler,
                    statusCodeGenerator ?? (r =>
                        r == null
                        ? (int)HttpStatusCode.NoContent
                        : (int)HttpStatusCode.OK));
            }

            public Route Put(AsyncHttpRequest handler, Func<object, int> statusCodeGenerator = null)
            {
                return Handle("PUT",
                    handler,
                    statusCodeGenerator ?? (r =>
                        r == null
                        ? (int)HttpStatusCode.NoContent
                        : (int)HttpStatusCode.OK));
            }
            
            public Route Post(AsyncHttpRequest handler, Func<object, int> statusCodeGenerator = null)
            {
                return Handle("POST",
                    handler,
                    statusCodeGenerator ?? (r =>
                        r == null
                        ? (int)HttpStatusCode.NoContent
                        : (int)HttpStatusCode.Created));
            }

            public async Task Invoke(IDictionary<string, object> environment, IDictionary<string, string> keys)
            {
                var completed = new TaskCompletionSource<bool>();

                try
                {          
                    var request  = new OwinRequest(environment);

                    var handler  = _handlers.GetValueOrDefault(request.Method, AsyncHttpRequestHandler.Null);

                    keys         = keys.ToDictionary(k => k.Key, v => WebUtility.UrlDecode(v.Value));

                    await ExecuteAsync(environment, keys, request, handler).ConfigureAwait(false);

                    completed.TrySetResult(true);
                }
                catch (Exception ex)
                {
                    completed.TrySetException(ex);

                    throw;
                }
            }

            static readonly IDictionary<string, string[]> EmptyForm = new Dictionary<string, string[]>();

            private async Task ExecuteAsync(
                IDictionary<string, object> environment, 
                IDictionary<string, string> keys, OwinRequest request,
                AsyncHttpRequestHandler handler)
            {
                var response = new OwinResponse(environment);

                var executor = (Func<Task<object>>)(async () => handler.Executor(
                    environment,
                    keys,
                    from w in request.HasForm()
                              ? (IEnumerable<KeyValuePair<string, string[]>>)(await request.ReadFormAsync().ConfigureAwait(false))
                              : EmptyForm
                    select w != null ? w[0] : null));

                var result = await executor().ConfigureAwait(false);

                await response.WriteAsync(JsonConvert.SerializeObject(result)).ConfigureAwait(false);

                response.StatusCode = handler.StatusCodeGenerator != null
                                    ? handler.StatusCodeGenerator(result)
                                    : (int)HttpStatusCode.OK;
            }
        }
{'fraction_non_alphanumeric': 0.08108108108108109, 'fraction_numerical': 0.0001755001755001755, 'mean_word_length': 1.5405706642888988, 'pattern_counts': {'":': 0, '<': 53, '<?xml version=': 0, '>': 71, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1772455', 'n_tokens_mistral': 2629, 'n_tokens_neox': 2480, 'n_words': 576}