-
Notifications
You must be signed in to change notification settings - Fork 78
Add HTTP request compression support (Gzip, Deflate, Brotli) #695
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
vaceslav
wants to merge
4
commits into
meilisearch:main
Choose a base branch
from
vaceslav:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
5f9a92e
Add HTTP request compression support (Gzip, Deflate, Brotli)
vaceslav 919d8ae
Address CodeRabbit review feedback
vaceslav 1e57bc7
Fix critical HttpContent double-read issue and improve validation
vaceslav 3be6c0b
Fix EnableResponseDecompression and add limitation warning
vaceslav File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,221 @@ | ||
| using System; | ||
| using System.IO; | ||
| using System.IO.Compression; | ||
| using System.Net.Http; | ||
| using System.Threading.Tasks; | ||
|
|
||
| namespace Meilisearch.Compression | ||
| { | ||
| /// <summary> | ||
| /// Helper class for compressing HTTP request content. | ||
| /// </summary> | ||
| internal static class CompressionHelper | ||
| { | ||
| /// <summary> | ||
| /// Wraps existing HttpContent with compression if applicable. | ||
| /// </summary> | ||
| /// <param name="content">Original HTTP content.</param> | ||
| /// <param name="options">Compression options.</param> | ||
| /// <returns>Compressed content or original if compression not applicable.</returns> | ||
| internal static async Task<HttpContent> CompressAsync(HttpContent content, CompressionOptions options) | ||
| { | ||
| if (!ShouldCompress(content, options)) | ||
| { | ||
| return content; | ||
| } | ||
|
|
||
| var originalBytes = await content.ReadAsByteArrayAsync().ConfigureAwait(false); | ||
|
|
||
| if (!MeetsSizeThreshold(originalBytes, options)) | ||
| { | ||
| // Content stream was already consumed; reconstruct it with original headers | ||
| var reconstructedContent = new ByteArrayContent(originalBytes); | ||
| foreach (var header in content.Headers) | ||
| { | ||
| reconstructedContent.Headers.TryAddWithoutValidation(header.Key, header.Value); | ||
| } | ||
| return reconstructedContent; | ||
| } | ||
|
|
||
| var compressedBytes = CompressData(originalBytes, options.Algorithm); | ||
| return CreateCompressedContent(compressedBytes, content, options.Algorithm); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Determines whether content should be compressed. | ||
| /// </summary> | ||
| private static bool ShouldCompress(HttpContent content, CompressionOptions options) | ||
| { | ||
| return content != null && options?.Algorithm != CompressionAlgorithm.None; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Checks if the data size meets the minimum threshold for compression. | ||
| /// </summary> | ||
| private static bool MeetsSizeThreshold(byte[] data, CompressionOptions options) | ||
| { | ||
| return data.Length >= options.MinimumSizeBytes; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Compresses data using the specified algorithm. | ||
| /// </summary> | ||
| private static byte[] CompressData(byte[] data, CompressionAlgorithm algorithm) | ||
| { | ||
| switch (algorithm) | ||
| { | ||
| case CompressionAlgorithm.Gzip: | ||
| return CompressWithGzip(data); | ||
|
|
||
| case CompressionAlgorithm.Deflate: | ||
| return CompressWithDeflate(data); | ||
|
|
||
| case CompressionAlgorithm.Brotli: | ||
| return CompressWithBrotli(data); | ||
|
|
||
| default: | ||
| throw new ArgumentException($"Unsupported compression algorithm: {algorithm}", nameof(algorithm)); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Creates new HttpContent with compressed data and appropriate headers. | ||
| /// </summary> | ||
| private static HttpContent CreateCompressedContent(byte[] compressedBytes, HttpContent originalContent, CompressionAlgorithm algorithm) | ||
| { | ||
| var compressedContent = new ByteArrayContent(compressedBytes); | ||
|
|
||
| // Copy headers from original content, excluding Content-Encoding and Content-Length | ||
| // as these will be set explicitly for the compressed content | ||
| foreach (var header in originalContent.Headers) | ||
| { | ||
| if (header.Key != "Content-Encoding" && header.Key != "Content-Length") | ||
| { | ||
| compressedContent.Headers.TryAddWithoutValidation(header.Key, header.Value); | ||
| } | ||
| } | ||
|
|
||
| // Set Content-Encoding header | ||
| var contentEncoding = GetContentEncoding(algorithm); | ||
| compressedContent.Headers.ContentEncoding.Add(contentEncoding); | ||
|
|
||
| // Set Content-Length | ||
| compressedContent.Headers.ContentLength = compressedBytes.Length; | ||
|
|
||
| return compressedContent; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Compresses data using Gzip algorithm. | ||
| /// </summary> | ||
| private static byte[] CompressWithGzip(byte[] data) | ||
| { | ||
| using (var outputStream = new MemoryStream()) | ||
| { | ||
| using (var gzipStream = new GZipStream(outputStream, CompressionLevel.Fastest, leaveOpen: true)) | ||
| { | ||
| gzipStream.Write(data, 0, data.Length); | ||
| gzipStream.Flush(); | ||
| } | ||
| return outputStream.ToArray(); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Compresses data using Deflate algorithm with zlib wrapper. | ||
| /// Meilisearch expects zlib format (RFC 1950), not raw deflate (RFC 1951). | ||
| /// ZLibStream is only available in .NET 6.0+ | ||
| /// </summary> | ||
| private static byte[] CompressWithDeflate(byte[] data) | ||
| { | ||
| #if NET6_0_OR_GREATER | ||
| using (var outputStream = new MemoryStream()) | ||
| { | ||
| using (var zlibStream = new ZLibStream(outputStream, CompressionLevel.Fastest, leaveOpen: true)) | ||
| { | ||
| zlibStream.Write(data, 0, data.Length); | ||
| zlibStream.Flush(); | ||
| } | ||
| return outputStream.ToArray(); | ||
| } | ||
| #else | ||
| throw new NotSupportedException( | ||
| "Deflate compression requires .NET 6.0+ for ZLibStream support. " + | ||
| "Current target framework is .NET Standard 2.0. " + | ||
| "DeflateStream produces raw deflate (RFC 1951), but Meilisearch expects zlib format (RFC 1950). " + | ||
| "Please use Gzip compression instead, or target .NET 6.0+ in your project."); | ||
| #endif | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Compresses data using Brotli algorithm. | ||
| /// Only available in .NET Standard 2.1+ / .NET Core 2.1+ | ||
| /// </summary> | ||
| private static byte[] CompressWithBrotli(byte[] data) | ||
| { | ||
| #if NETSTANDARD2_1_OR_GREATER || NETCOREAPP2_1_OR_GREATER | ||
| using (var outputStream = new MemoryStream()) | ||
| { | ||
| using (var brotliStream = new BrotliStream(outputStream, CompressionLevel.Fastest, leaveOpen: true)) | ||
| { | ||
| brotliStream.Write(data, 0, data.Length); | ||
| brotliStream.Flush(); | ||
| } | ||
| return outputStream.ToArray(); | ||
| } | ||
| #else | ||
| throw new NotSupportedException( | ||
| "Brotli compression requires .NET Standard 2.1+ or .NET Core 2.1+. " + | ||
| "Current target framework is .NET Standard 2.0. " + | ||
| "Please use Gzip or Deflate compression instead."); | ||
| #endif | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Gets the Content-Encoding header value for a given algorithm. | ||
| /// </summary> | ||
| internal static string GetContentEncoding(CompressionAlgorithm algorithm) | ||
| { | ||
| switch (algorithm) | ||
| { | ||
| case CompressionAlgorithm.Gzip: | ||
| return "gzip"; | ||
| case CompressionAlgorithm.Deflate: | ||
| return "deflate"; | ||
| case CompressionAlgorithm.Brotli: | ||
| return "br"; | ||
| default: | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Checks if the compression algorithm is supported in the current runtime. | ||
| /// </summary> | ||
| internal static bool IsAlgorithmSupported(CompressionAlgorithm algorithm) | ||
| { | ||
| switch (algorithm) | ||
| { | ||
| case CompressionAlgorithm.Gzip: | ||
| return true; | ||
|
|
||
| case CompressionAlgorithm.Deflate: | ||
| #if NET6_0_OR_GREATER | ||
| return true; | ||
| #else | ||
| return false; | ||
| #endif | ||
|
|
||
| case CompressionAlgorithm.Brotli: | ||
| #if NETSTANDARD2_1_OR_GREATER || NETCOREAPP2_1_OR_GREATER | ||
| return true; | ||
| #else | ||
| return false; | ||
| #endif | ||
|
|
||
| default: | ||
| return false; | ||
| } | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.