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