| | 1 | | // Copyright (c) ZeroC, Inc. |
| | 2 | |
|
| | 3 | | using IceRpc.Features; |
| | 4 | | using ZeroC.Slice; |
| | 5 | |
|
| | 6 | | namespace IceRpc.RequestContext; |
| | 7 | |
|
| | 8 | | /// <summary>Represents an interceptor that encodes request context features into request context fields.</summary> |
| | 9 | | /// <remarks>Both the ice protocol and the icerpc protocol can transmit request context fields with requests; while |
| | 10 | | /// icerpc can transmit all request fields, ice can only transmit request context fields and idempotent fields. |
| | 11 | | /// </remarks> |
| | 12 | | public class RequestContextInterceptor : IInvoker |
| | 13 | | { |
| | 14 | | private readonly IInvoker _next; |
| | 15 | |
|
| | 16 | | /// <summary>Constructs a request context interceptor.</summary> |
| | 17 | | /// <param name="next">The next invoker in the invocation pipeline.</param> |
| 12 | 18 | | public RequestContextInterceptor(IInvoker next) => _next = next; |
| | 19 | |
|
| | 20 | | /// <inheritdoc/> |
| | 21 | | public Task<IncomingResponse> InvokeAsync(OutgoingRequest request, CancellationToken cancellationToken) |
| 86 | 22 | | { |
| 86 | 23 | | if (request.Features.Get<IRequestContextFeature>()?.Value is IDictionary<string, string> context) |
| 14 | 24 | | { |
| 14 | 25 | | if (context.Count == 0) |
| 1 | 26 | | { |
| | 27 | | // make sure it's not set. |
| 1 | 28 | | request.Fields = request.Fields.Without(RequestFieldKey.Context); |
| 1 | 29 | | } |
| | 30 | | else |
| 13 | 31 | | { |
| 13 | 32 | | request.Fields = request.Fields.With( |
| 13 | 33 | | RequestFieldKey.Context, |
| 13 | 34 | | context, |
| 13 | 35 | | (ref SliceEncoder encoder, IDictionary<string, string> dictionary) => encoder.EncodeDictionary( |
| 13 | 36 | | dictionary, |
| 13 | 37 | | (ref SliceEncoder encoder, string value) => encoder.EncodeString(value), |
| 26 | 38 | | (ref SliceEncoder encoder, string value) => encoder.EncodeString(value)), |
| 13 | 39 | | request.Protocol == Protocol.Ice ? SliceEncoding.Slice1 : SliceEncoding.Slice2); |
| 13 | 40 | | } |
| 14 | 41 | | } |
| 86 | 42 | | return _next.InvokeAsync(request, cancellationToken); |
| 86 | 43 | | } |
| | 44 | | } |