|
| 1 | +module BwdServer.Compression |
| 2 | + |
| 3 | +open FSharp.Control.Tasks |
| 4 | +open System.Threading.Tasks |
| 5 | + |
| 6 | +open System |
| 7 | +open Microsoft.AspNetCore |
| 8 | +open Microsoft.AspNetCore.Builder |
| 9 | +open Microsoft.AspNetCore.Hosting |
| 10 | +open Microsoft.AspNetCore.Http |
| 11 | +open Microsoft.AspNetCore.Http.Extensions |
| 12 | +open Microsoft.AspNetCore.Http.Abstractions |
| 13 | +open Microsoft.Extensions.Logging |
| 14 | +open Microsoft.Extensions.Hosting |
| 15 | +open Microsoft.Extensions.DependencyInjection |
| 16 | +open Microsoft.AspNetCore.ResponseCompression |
| 17 | +open Microsoft.Extensions.DependencyInjection.Extensions |
| 18 | + |
| 19 | +type CustomCompressionProvider(services, options) = |
| 20 | + inherit ResponseCompressionProvider(services, options) |
| 21 | + override this.ShouldCompressResponse(ctx : HttpContext) : bool = |
| 22 | + // Compress responses unless they're too small |
| 23 | + let default_ = base.ShouldCompressResponse ctx |
| 24 | + let tooSmall = |
| 25 | + // This was the setting we had in the ocaml nginx |
| 26 | + if ctx.Response.ContentLength.HasValue then |
| 27 | + ctx.Response.ContentLength.Value < 1024 |
| 28 | + else |
| 29 | + false |
| 30 | + default_ && not tooSmall |
| 31 | + |
| 32 | +let configureServices (services : IServiceCollection) : IServiceCollection = |
| 33 | + let configureOptions (options : ResponseCompressionOptions) : unit = |
| 34 | + // CLEANUP: This is set to the same values as we used in nginx for the ocaml |
| 35 | + // bwdserver. By default, .net also had a few others: text/javascript, |
| 36 | + // application/xml, text/xml, text/json, application/wasm. They aren't that |
| 37 | + // interesting to us right now. |
| 38 | + options.MimeTypes <- |
| 39 | + [ "text/html" |
| 40 | + "text/plain" |
| 41 | + "text/css" |
| 42 | + "application/javascript" |
| 43 | + "application/json" ] |
| 44 | + services.Configure(configureOptions) |> ignore<IServiceCollection> |
| 45 | + services.TryAddSingleton<IResponseCompressionProvider, CustomCompressionProvider>() |
| 46 | + services |
| 47 | + |
| 48 | +let addToApp (app : IApplicationBuilder) : IApplicationBuilder = |
| 49 | + // FSTODO do we need to do anything to use our custom provider with the default middleware? |
| 50 | + // https://github.com/dotnet/aspnetcore/tree/c85baf8db0c72ae8e68643029d514b2e737c9fae/src/Middleware/ResponseCompression/src |
| 51 | + app.UseResponseCompression() |
0 commit comments