|
| 1 | +namespace Qdrant.Client; |
| 2 | + |
| 3 | +/// <summary> |
| 4 | +/// Utilities for attaching per-request headers to gRPC calls. |
| 5 | +/// </summary> |
| 6 | +public static class RequestHeaders |
| 7 | +{ |
| 8 | + private static readonly AsyncLocal<IReadOnlyDictionary<string, string>?> _headers = new(); |
| 9 | + |
| 10 | + internal static IReadOnlyDictionary<string, string>? Current => _headers.Value; |
| 11 | + |
| 12 | + /// <summary> |
| 13 | + /// Sets key and value as metadata on requests made within the returned scope. |
| 14 | + /// </summary> |
| 15 | + public static IDisposable Use(string key, string value) => |
| 16 | + Use(new Dictionary<string, string> { [key] = value }); |
| 17 | + |
| 18 | + /// <summary> |
| 19 | + /// Sets all entries of headers as metadata on requests made within the returned scope. |
| 20 | + /// </summary> |
| 21 | + public static IDisposable Use(IDictionary<string, string> headers) |
| 22 | + { |
| 23 | + var previous = _headers.Value; |
| 24 | + var merged = new Dictionary<string, string>(); |
| 25 | + if (previous is not null) |
| 26 | + foreach (var header in previous) |
| 27 | + merged[header.Key] = header.Value; |
| 28 | + foreach (var header in headers) |
| 29 | + merged[header.Key] = header.Value; |
| 30 | + _headers.Value = merged; |
| 31 | + return new Scope(() => _headers.Value = previous); |
| 32 | + } |
| 33 | + |
| 34 | + private sealed class Scope : IDisposable |
| 35 | + { |
| 36 | + private readonly Action _restore; |
| 37 | + |
| 38 | + internal Scope(Action restore) => _restore = restore; |
| 39 | + |
| 40 | + public void Dispose() => _restore(); |
| 41 | + } |
| 42 | +} |
0 commit comments