Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,42 @@ public OperationDocumentHash ComputeHash(ReadOnlySpan<byte> document)
#endif
}

public OperationDocumentHash ComputeHash(ReadOnlySequence<byte> document)
{
if (document.IsSingleSegment)
{
#if NETSTANDARD2_0
return ComputeHash(document.First.Span);
#else
return ComputeHash(document.FirstSpan);
#endif
}

#if NETSTANDARD2_0
var length = checked((int)document.Length);
var rented = ArrayPool<byte>.Shared.Rent(length);

try
{
document.CopyTo(rented);
return ComputeHash(rented.AsSpan(0, length));
}
finally
{
ArrayPool<byte>.Shared.Return(rented);
}
Comment on lines +53 to +65
Copy link

Copilot AI Feb 18, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On NETSTANDARD2_0, the multi-segment ComputeHash(ReadOnlySequence<byte>) path rents/copies the sequence into rented, but then calls ComputeHash(rented.AsSpan(...)), which in turn rents and copies again in the span overload (because the span overload always copies into an ArrayPool buffer on NETSTANDARD2_0). This causes a double rent+copy for multi-segment sequences. Consider computing the hash directly from the first rented buffer by calling the ComputeHash(byte[] document, int length) abstraction and formatting it, to avoid the extra allocation/copy.

Copilot uses AI. Check for mistakes.
#else
var hash = ComputeHash(document, Format);
return new OperationDocumentHash(hash, Name, Format);
#endif
}

#if NETSTANDARD2_0
protected abstract byte[] ComputeHash(byte[] document, int length);
#else
protected abstract string ComputeHash(ReadOnlySpan<byte> document, HashFormat format);

protected abstract string ComputeHash(ReadOnlySequence<byte> document, HashFormat format);
#endif

protected static string FormatHash(ReadOnlySpan<byte> hash, HashFormat format)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using System.Buffers;

namespace HotChocolate.Language;

/// <summary>
Expand All @@ -21,4 +23,11 @@ public interface IDocumentHashProvider
/// <param name="document">The GraphQL operation document.</param>
/// <returns>The hash of the GraphQL operation document.</returns>
OperationDocumentHash ComputeHash(ReadOnlySpan<byte> document);

/// <summary>
/// Computes the hash of a GraphQL operation document.
/// </summary>
/// <param name="document">The GraphQL operation document.</param>
/// <returns>The hash of the GraphQL operation document.</returns>
OperationDocumentHash ComputeHash(ReadOnlySequence<byte> document);
Comment on lines 25 to +32
Copy link

Copilot AI Feb 18, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adding a new member to the public IDocumentHashProvider interface is a breaking change for any external consumers that implement this interface. If backwards compatibility is required, consider introducing a new interface (e.g., IDocumentHashProvider2) or providing sequence hashing via an extension/helper that falls back to the span overload for single-segment sequences.

Copilot uses AI. Check for mistakes.
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#if NET8_0_OR_GREATER
using System.Buffers;
using System.Runtime.CompilerServices;
#endif
using System.Security.Cryptography;
Expand Down Expand Up @@ -38,5 +39,26 @@ protected override string ComputeHash(ReadOnlySpan<byte> document, HashFormat fo

return FormatHash(hashSpan, format);
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override string ComputeHash(ReadOnlySequence<byte> document, HashFormat format)
{
using var incrementalHash = IncrementalHash.CreateHash(HashAlgorithmName.MD5);

foreach (var segment in document)
{
incrementalHash.AppendData(segment.Span);
}

Span<byte> hashBytes = stackalloc byte[16];
incrementalHash.TryGetHashAndReset(hashBytes, out var written);

if (written < 16)
{
hashBytes = hashBytes[..written];
}

return FormatHash(hashBytes, format);
}
#endif
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#if NET8_0_OR_GREATER
using System.Buffers;
using System.Runtime.CompilerServices;
#endif
using System.Security.Cryptography;
Expand Down Expand Up @@ -40,5 +41,26 @@ protected override string ComputeHash(ReadOnlySpan<byte> document, HashFormat fo

return FormatHash(hashSpan, format);
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override string ComputeHash(ReadOnlySequence<byte> document, HashFormat format)
{
using var incrementalHash = IncrementalHash.CreateHash(HashAlgorithmName.SHA1);

foreach (var segment in document)
{
incrementalHash.AppendData(segment.Span);
}

Span<byte> hashBytes = stackalloc byte[20];
incrementalHash.TryGetHashAndReset(hashBytes, out var written);

if (written < 20)
{
hashBytes = hashBytes[..written];
}

return FormatHash(hashBytes, format);
}
#endif
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#if NET8_0_OR_GREATER
using System.Buffers;
using System.Runtime.CompilerServices;
#endif
using System.Security.Cryptography;
Expand Down Expand Up @@ -42,5 +43,26 @@ protected override string ComputeHash(ReadOnlySpan<byte> document, HashFormat fo

return FormatHash(hashSpan, format);
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override string ComputeHash(ReadOnlySequence<byte> document, HashFormat format)
{
using var incrementalHash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);

foreach (var segment in document)
{
incrementalHash.AppendData(segment.Span);
}

Span<byte> hashBytes = stackalloc byte[32];
incrementalHash.TryGetHashAndReset(hashBytes, out var written);

if (written < 32)
{
hashBytes = hashBytes[..written];
}

return FormatHash(hashBytes, format);
}
#endif
}
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,8 @@ private readonly GraphQLRequest ParseRequest(ref Utf8JsonReader reader, Operatio
ErrorHandlingMode? errorHandlingMode = null;
JsonDocument? variables = null;
JsonDocument? extensions = null;
ReadOnlySpan<byte> documentBody = default;
ReadOnlySequence<byte> documentSequence = default;
ReadOnlySpan<byte> documentSpan = default;
var isDocumentEscaped = false;

while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)
Expand All @@ -183,7 +184,15 @@ private readonly GraphQLRequest ParseRequest(ref Utf8JsonReader reader, Operatio
if (reader.TokenType == JsonTokenType.String)
{
isDocumentEscaped = reader.ValueIsEscaped;
documentBody = reader.ValueSpan;

if (reader.HasValueSequence)
{
documentSequence = reader.ValueSequence;
}
else
{
documentSpan = reader.ValueSpan;
}
}
else if (reader.TokenType == JsonTokenType.Null)
{
Expand Down Expand Up @@ -312,7 +321,7 @@ private readonly GraphQLRequest ParseRequest(ref Utf8JsonReader reader, Operatio
}

// Handle persisted queries via extensions
if (documentBody.IsEmpty
if (documentSpan.IsEmpty
&& documentId.IsEmpty
&& _useCache
&& extensions is not null
Expand All @@ -323,10 +332,19 @@ private readonly GraphQLRequest ParseRequest(ref Utf8JsonReader reader, Operatio
}

// Parse the GraphQL document if provided
if (!documentBody.IsEmpty)
if (!documentSpan.IsEmpty)
{
ParseDocument(
documentBody,
documentSpan,
isDocumentEscaped,
ref document,
ref documentHash,
ref documentId);
}
else if (!documentSequence.IsEmpty)
{
ParseDocument(
documentSequence,
isDocumentEscaped,
ref document,
ref documentHash,
Expand Down Expand Up @@ -406,6 +424,62 @@ private readonly void ParseDocument(
}
}

private readonly void ParseDocument(
ReadOnlySequence<byte> documentBody,
bool isEscaped,
ref DocumentNode? document,
ref OperationDocumentHash documentHash,
ref OperationDocumentId documentId)
{
// When we need to unescape, escape sequences can span segment boundaries,
// so we must work with contiguous memory. Delegate to the span-based overload
// which already handles unescaping.
if (isEscaped)
{
var length = checked((int)documentBody.Length);
var rented = s_bytePool.Rent(length);

try
{
documentBody.CopyTo(rented);
ParseDocument(rented.AsSpan(0, length), isEscaped, ref document, ref documentHash, ref documentId);
}
Comment on lines +437 to +446
Copy link

Copilot AI Feb 18, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the ReadOnlySequence<byte> overload, the escaped path rents a buffer to make the sequence contiguous and then calls the span overload with isEscaped: true, which causes the span overload to rent another buffer for unescaping. This doubles peak memory and copies for large escaped documents. Consider unescaping directly from the contiguous buffer (e.g., call the span overload with isEscaped: false after unescaping yourself) or refactor so the unescape buffer can be reused instead of renting twice.

Copilot uses AI. Check for mistakes.
finally
{
s_bytePool.Return(rented);
}

return;
}

if (_useCache)
{
if (documentId.HasValue && _cache!.TryGetDocument(documentId.Value, out var cachedDocument))
{
document = cachedDocument.Body;
documentHash = cachedDocument.Hash;
}
else if (documentBody.Length > 0)
{
var hash = _hashProvider!.ComputeHash(documentBody);
documentHash = hash;

document = _cache!.TryGetDocument(hash.Value, out cachedDocument)
? cachedDocument.Body
: Utf8GraphQLParser.Parse(documentBody, _options);

if (documentId.IsEmpty)
{
documentId = new OperationDocumentId(hash.Value);
}
}
}
else
{
document = Utf8GraphQLParser.Parse(documentBody, _options);
}
}

private readonly bool TryExtractHash(JsonDocument? extensions, out string hash)
=> TryExtractHashInternal(extensions, _hashProvider, out hash);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using System.Buffers;

namespace HotChocolate.Language;

public class MD5DocumentHashProviderTests
Expand Down Expand Up @@ -29,4 +31,60 @@ public void HashAsHex()
.Add(hash.Value)
.MatchInline("900150983cd24fb0d6963f7d28e17f72");
}

[Fact]
public void HashSequenceSingleSegmentAsBase64()
{
var content = new ReadOnlySequence<byte>("abc"u8.ToArray());
var hashProvider = new MD5DocumentHashProvider(HashFormat.Base64);

var hash = hashProvider.ComputeHash(content);

Snapshot
.Create()
.Add(hash.Value)
.MatchInline("kAFQmDzST7DWlj99KOF_cg");
}

[Fact]
public void HashSequenceMultiSegmentAsBase64()
{
var content = SequenceHelper.CreateMultiSegment("abc"u8.ToArray());
var hashProvider = new MD5DocumentHashProvider(HashFormat.Base64);

var hash = hashProvider.ComputeHash(content);

Snapshot
.Create()
.Add(hash.Value)
.MatchInline("kAFQmDzST7DWlj99KOF_cg");
}

[Fact]
public void HashSequenceSingleSegmentAsHex()
{
var content = new ReadOnlySequence<byte>("abc"u8.ToArray());
var hashProvider = new MD5DocumentHashProvider(HashFormat.Hex);

var hash = hashProvider.ComputeHash(content);

Snapshot
.Create()
.Add(hash.Value)
.MatchInline("900150983cd24fb0d6963f7d28e17f72");
}

[Fact]
public void HashSequenceMultiSegmentAsHex()
{
var content = SequenceHelper.CreateMultiSegment("abc"u8.ToArray());
var hashProvider = new MD5DocumentHashProvider(HashFormat.Hex);

var hash = hashProvider.ComputeHash(content);

Snapshot
.Create()
.Add(hash.Value)
.MatchInline("900150983cd24fb0d6963f7d28e17f72");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using System.Buffers;

namespace HotChocolate.Language;

internal static class SequenceHelper
{
public static ReadOnlySequence<byte> CreateMultiSegment(byte[] data)
{
if (data.Length < 2)
{
return new ReadOnlySequence<byte>(data);
}

var mid = data.Length / 2;
var first = new MemorySegment(data.AsMemory(0, mid));
var last = first.Append(data.AsMemory(mid));

return new ReadOnlySequence<byte>(first, 0, last, last.Memory.Length);
}

private sealed class MemorySegment : ReadOnlySequenceSegment<byte>
{
public MemorySegment(ReadOnlyMemory<byte> memory)
{
Memory = memory;
}

public MemorySegment Append(ReadOnlyMemory<byte> memory)
{
var segment = new MemorySegment(memory)
{
RunningIndex = RunningIndex + Memory.Length
};
Next = segment;
return segment;
}
}
}
Loading
Loading