<commit_before>﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Owin;
using Nancy;
using Nancy.Bootstrapper;
using Nancy.IO;
using System.IO;

namespace Gate.Adapters.Nancy
{
    using AppFunc = Func<IDictionary<string, object>, Task>;

    public static class NancyAdapter
    {
        public static IAppBuilder RunNancy(this IAppBuilder builder)
        {
            return builder.UseFunc<AppFunc>(_ => App());
        }

        public static IAppBuilder RunNancy(this IAppBuilder builder, INancyBootstrapper bootstrapper)
        {
            return builder.UseFunc<AppFunc>(_ => App(bootstrapper));
        }

        public static AppFunc App()
        {
            return App(NancyBootstrapperLocator.Bootstrapper);
        }

        public static AppFunc App(INancyBootstrapper bootstrapper)
        {
            bootstrapper.Initialise();
            var engine = bootstrapper.GetEngine();
            return env =>
            {
                var owinRequestMethod = Get<string>(env, OwinConstants.RequestMethod);
                var owinRequestScheme = Get<string>(env, OwinConstants.RequestScheme);
                var owinRequestHeaders = Get<IDictionary<string, string[]>>(env, OwinConstants.RequestHeaders);
                var owinRequestPathBase = Get<string>(env, OwinConstants.RequestPathBase);
                var owinRequestPath = Get<string>(env, OwinConstants.RequestPath);
                var owinRequestQueryString = Get<string>(env, OwinConstants.RequestQueryString);
                var owinRequestBody = Get<Stream>(env, OwinConstants.RequestBody);
                var serverClientIp = Get<string>(env, OwinConstants.RemoteIpAddress);
                var callCompleted = Get<Task>(env, OwinConstants.CallCancelled);

                var owinResponseHeaders = Get<IDictionary<string, string[]>>(env, OwinConstants.ResponseHeaders);
                var owinResponseBody = Get<Stream>(env, OwinConstants.ResponseBody);

                var url = new Url
                {
                    Scheme = owinRequestScheme,
                    HostName = GetHeader(owinRequestHeaders, "Host"),
                    Port = null,
                    BasePath = owinRequestPathBase,
                    Path = owinRequestPath,
                    Query = owinRequestQueryString,
                };

                var body = new RequestStream(owinRequestBody, ExpectedLength(owinRequestHeaders), false);

                var nancyRequest = new Request(
                    owinRequestMethod,
                    url,
                    body,
                    owinRequestHeaders.ToDictionary(kv => kv.Key, kv => (IEnumerable<string>)kv.Value, StringComparer.OrdinalIgnoreCase),
                    serverClientIp);

                var tcs = new TaskCompletionSource<object>();
                engine.HandleRequest(
                    nancyRequest,
                    context =>
                    {
                        callCompleted.Finally(context.Dispose);

                        var nancyResponse = context.Response;
                        foreach (var header in nancyResponse.Headers)
                        {
                            owinResponseHeaders.Add(header.Key, new string[] { header.Value });
                        }

                        if (!string.IsNullOrWhiteSpace(nancyResponse.ContentType))
                        {
                            owinResponseHeaders["Content-Type"] = new[] { nancyResponse.ContentType };
                        }
                        if (nancyResponse.Cookies != null && nancyResponse.Cookies.Count != 0)
                        {
                            owinResponseHeaders["Set-Cookie"] = nancyResponse.Cookies.Select(cookie => cookie.ToString()).ToArray();
                        }

                        env[OwinConstants.ResponseStatusCode] = (int)nancyResponse.StatusCode;
                        nancyResponse.Contents(owinResponseBody);
                        tcs.TrySetResult(null);
                    },
                    tcs.SetException);
                return tcs.Task;
            };<commit_msg>Fixing bug calling Nancy context.Dispose<commit_after>﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Owin;
using Nancy;
using Nancy.Bootstrapper;
using Nancy.IO;
using System.IO;

namespace Gate.Adapters.Nancy
{
    using AppFunc = Func<IDictionary<string, object>, Task>;

    public static class NancyAdapter
    {
        public static IAppBuilder RunNancy(this IAppBuilder builder)
        {
            return builder.UseFunc<AppFunc>(_ => App());
        }

        public static IAppBuilder RunNancy(this IAppBuilder builder, INancyBootstrapper bootstrapper)
        {
            return builder.UseFunc<AppFunc>(_ => App(bootstrapper));
        }

        public static AppFunc App()
        {
            return App(NancyBootstrapperLocator.Bootstrapper);
        }

        public static AppFunc App(INancyBootstrapper bootstrapper)
        {
            bootstrapper.Initialise();
            var engine = bootstrapper.GetEngine();
            return env =>
            {
                var owinRequestMethod = Get<string>(env, OwinConstants.RequestMethod);
                var owinRequestScheme = Get<string>(env, OwinConstants.RequestScheme);
                var owinRequestHeaders = Get<IDictionary<string, string[]>>(env, OwinConstants.RequestHeaders);
                var owinRequestPathBase = Get<string>(env, OwinConstants.RequestPathBase);
                var owinRequestPath = Get<string>(env, OwinConstants.RequestPath);
                var owinRequestQueryString = Get<string>(env, OwinConstants.RequestQueryString);
                var owinRequestBody = Get<Stream>(env, OwinConstants.RequestBody);
                var serverClientIp = Get<string>(env, OwinConstants.RemoteIpAddress);

                var owinResponseHeaders = Get<IDictionary<string, string[]>>(env, OwinConstants.ResponseHeaders);
                var owinResponseBody = Get<Stream>(env, OwinConstants.ResponseBody);

                var url = new Url
                {
                    Scheme = owinRequestScheme,
                    HostName = GetHeader(owinRequestHeaders, "Host"),
                    Port = null,
                    BasePath = owinRequestPathBase,
                    Path = owinRequestPath,
                    Query = owinRequestQueryString,
                };

                var body = new RequestStream(owinRequestBody, ExpectedLength(owinRequestHeaders), false);

                var nancyRequest = new Request(
                    owinRequestMethod,
                    url,
                    body,
                    owinRequestHeaders.ToDictionary(kv => kv.Key, kv => (IEnumerable<string>)kv.Value, StringComparer.OrdinalIgnoreCase),
                    serverClientIp);

                var tcs = new TaskCompletionSource<object>();
                engine.HandleRequest(
                    nancyRequest,
                    context =>
                    {
                        var nancyResponse = context.Response;
                        foreach (var header in nancyResponse.Headers)
                        {
                            owinResponseHeaders.Add(header.Key, new string[] { header.Value });
                        }

                        if (!string.IsNullOrWhiteSpace(nancyResponse.ContentType))
                        {
                            owinResponseHeaders["Content-Type"] = new[] { nancyResponse.ContentType };
                        }
                        if (nancyResponse.Cookies != null && nancyResponse.Cookies.Count != 0)
                        {
                            owinResponseHeaders["Set-Cookie"] = nancyResponse.Cookies.Select(cookie => cookie.ToString()).ToArray();
                        }

                        env[OwinConstants.ResponseStatusCode] = (int)nancyResponse.StatusCode;
                        nancyResponse.Contents(owinResponseBody);
                        context.Dispose();
                        tcs.TrySetResult(null);
                    },
                    tcs.SetException);
                return tcs.Task;
            };
{'fraction_non_alphanumeric': 0.08339307048984468, 'fraction_numerical': 0.00023894862604540023, 'mean_word_length': 1.6942388155777277, 'pattern_counts': {'":': 0, '<': 40, '<?xml version=': 0, '>': 54, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4325616', 'n_tokens_mistral': 2056, 'n_tokens_neox': 1935, 'n_words': 382}