Log error if gzip fails during response

This commit is contained in:
Mark McDowall 2014-07-30 21:41:35 -07:00
parent 9ecbf8773e
commit 125e69da6d
1 changed files with 39 additions and 21 deletions

View File

@ -1,13 +1,22 @@
using System.IO; using System;
using System.IO;
using System.IO.Compression; using System.IO.Compression;
using System.Linq; using System.Linq;
using Nancy; using Nancy;
using Nancy.Bootstrapper; using Nancy.Bootstrapper;
using NLog;
namespace NzbDrone.Api.Extensions.Pipelines namespace NzbDrone.Api.Extensions.Pipelines
{ {
public class GzipCompressionPipeline : IRegisterNancyPipeline public class GzipCompressionPipeline : IRegisterNancyPipeline
{ {
private readonly Logger _logger;
public GzipCompressionPipeline(Logger logger)
{
_logger = logger;
}
public void Register(IPipelines pipelines) public void Register(IPipelines pipelines)
{ {
pipelines.AfterRequest.AddItemToEndOfPipeline(c => CompressResponse(c.Request, c.Response)); pipelines.AfterRequest.AddItemToEndOfPipeline(c => CompressResponse(c.Request, c.Response));
@ -15,34 +24,43 @@ namespace NzbDrone.Api.Extensions.Pipelines
private Response CompressResponse(Request request, Response response) private Response CompressResponse(Request request, Response response)
{ {
if (!response.ContentType.Contains("image") try
{
if (!response.ContentType.Contains("image")
&& request.Headers.AcceptEncoding.Any(x => x.Contains("gzip")) && request.Headers.AcceptEncoding.Any(x => x.Contains("gzip"))
&& (!response.Headers.ContainsKey("Content-Encoding") || response.Headers["Content-Encoding"] != "gzip")) && (!response.Headers.ContainsKey("Content-Encoding") || response.Headers["Content-Encoding"] != "gzip"))
{
var data = new MemoryStream();
response.Contents.Invoke(data);
data.Position = 0;
if (data.Length < 1024)
{ {
response.Contents = stream => var data = new MemoryStream();
response.Contents.Invoke(data);
data.Position = 0;
if (data.Length < 1024)
{ {
data.CopyTo(stream); response.Contents = stream =>
stream.Flush(); {
}; data.CopyTo(stream);
} stream.Flush();
else };
{ }
response.Headers["Content-Encoding"] = "gzip"; else
response.Contents = s =>
{ {
var gzip = new GZipStream(s, CompressionMode.Compress, true); response.Headers["Content-Encoding"] = "gzip";
data.CopyTo(gzip); response.Contents = s =>
gzip.Close(); {
}; var gzip = new GZipStream(s, CompressionMode.Compress, true);
data.CopyTo(gzip);
gzip.Close();
};
}
} }
return response;
} }
return response; catch (Exception ex)
{
_logger.ErrorException("Unable to gzip response", ex);
throw;
}
} }
} }
} }