| | 1 | | // Copyright (c) ZeroC, Inc. |
| | 2 | |
|
| | 3 | | using IceRpc.Features; |
| | 4 | | using System.Buffers; |
| | 5 | | using ZeroC.Slice; |
| | 6 | |
|
| | 7 | | namespace IceRpc.RequestContext; |
| | 8 | |
|
| | 9 | | /// <summary>Represents a middleware that decodes request context fields into request context features.</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 RequestContextMiddleware : IDispatcher |
| | 14 | | { |
| | 15 | | private readonly IDispatcher _next; |
| | 16 | |
|
| | 17 | | /// <summary>Constructs a request context middleware.</summary> |
| | 18 | | /// <param name="next">The next dispatcher in the dispatch pipeline.</param> |
| 18 | 19 | | public RequestContextMiddleware(IDispatcher next) => _next = next; |
| | 20 | |
|
| | 21 | | /// <inheritdoc/> |
| | 22 | | public ValueTask<OutgoingResponse> DispatchAsync(IncomingRequest request, CancellationToken cancellationToken) |
| 85 | 23 | | { |
| | 24 | | // Decode Context from Fields and set corresponding feature. |
| 85 | 25 | | if (request.Fields.TryGetValue(RequestFieldKey.Context, out ReadOnlySequence<byte> value)) |
| 13 | 26 | | { |
| 13 | 27 | | var decoder = new SliceDecoder( |
| 13 | 28 | | value, |
| 13 | 29 | | request.Protocol == Protocol.Ice ? SliceEncoding.Slice1 : SliceEncoding.Slice2); |
| | 30 | |
|
| 13 | 31 | | Dictionary<string, string> context = decoder.DecodeDictionary( |
| 13 | 32 | | size => new Dictionary<string, string>(size), |
| 13 | 33 | | keyDecodeFunc: (ref SliceDecoder decoder) => decoder.DecodeString(), |
| 26 | 34 | | valueDecodeFunc: (ref SliceDecoder decoder) => decoder.DecodeString()); |
| 13 | 35 | | if (context.Count > 0) |
| 13 | 36 | | { |
| 13 | 37 | | request.Features = request.Features.With<IRequestContextFeature>(new RequestContextFeature(context)); |
| 13 | 38 | | } |
| 13 | 39 | | } |
| 85 | 40 | | return _next.DispatchAsync(request, cancellationToken); |
| 85 | 41 | | } |
| | 42 | | } |