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
15 changes: 7 additions & 8 deletions src/Qdrant.Client/Grpc/QdrantChannel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,20 +33,19 @@ public override CallInvoker CreateCallInvoker()
if (Disposed)
throw new ObjectDisposedException(nameof(QdrantChannel));

var hasApiKey = _configuration.ApiKey is not null;
var hasHeaders = _configuration.Headers.Count > 0;

if (!hasApiKey && !hasHeaders)
return _channel.CreateCallInvoker();

return _channel.Intercept(metadata =>
{
if (hasApiKey)
metadata.Add("api-key", _configuration.ApiKey!);
if (_configuration.ApiKey is not null)
metadata.Add("api-key", _configuration.ApiKey);

foreach (var header in _configuration.Headers)
metadata.Add(header.Key, header.Value);

var requestHeaders = RequestHeaders.Current;
if (requestHeaders is not null)
foreach (var header in requestHeaders)
metadata.Add(header.Key, header.Value);

return metadata;
});
}
Expand Down
42 changes: 42 additions & 0 deletions src/Qdrant.Client/RequestHeaders.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
namespace Qdrant.Client;

/// <summary>
/// Utilities for attaching per-request headers to gRPC calls.
/// </summary>
public static class RequestHeaders
{
private static readonly AsyncLocal<IReadOnlyDictionary<string, string>?> _headers = new();

internal static IReadOnlyDictionary<string, string>? Current => _headers.Value;

/// <summary>
/// Sets key and value as metadata on requests made within the returned scope.
/// </summary>
public static IDisposable Use(string key, string value) =>
Use(new Dictionary<string, string> { [key] = value });

/// <summary>
/// Sets all entries of headers as metadata on requests made within the returned scope.
/// </summary>
public static IDisposable Use(IDictionary<string, string> headers)
{
var previous = _headers.Value;
var merged = new Dictionary<string, string>();
if (previous is not null)
foreach (var header in previous)
merged[header.Key] = header.Value;
foreach (var header in headers)
merged[header.Key] = header.Value;
_headers.Value = merged;
return new Scope(() => _headers.Value = previous);
}

private sealed class Scope : IDisposable
{
private readonly Action _restore;

internal Scope(Action restore) => _restore = restore;

public void Dispose() => _restore();
}
}
Loading