| | | 1 | | namespace AsyncResponse; |
| | | 2 | | |
| | | 3 | | /// <summary> |
| | | 4 | | /// Raw broker/webhook response payload that can be materialized into the active waiter's payload |
| | | 5 | | /// type without first allocating an intermediate JsonElement. |
| | | 6 | | /// </summary> |
| | | 7 | | internal sealed class RawJsonResponse |
| | | 8 | | { |
| | | 9 | | private readonly string _json; |
| | | 10 | | |
| | | 11 | | // One instance is shared across every subscriber of a correlation id, and fan-out dispatch can |
| | | 12 | | // materialize payloads from multiple threads. TYPED payloads are deliberately NOT memoized: |
| | | 13 | | // handing one mutable payload instance to multiple same-type waiters would alias user state |
| | | 14 | | // across concurrently-running predicates and handlers — every durable channel deserializes a |
| | | 15 | | // private instance per waiter, and the in-memory raw path must match (wire parity, same rule |
| | | 16 | | // as the typed path's MaterializeAs). The untyped memo below stays: it materializes an |
| | | 17 | | // immutable JsonElement, so sharing it is safe; _gate guards its torn-publication hazard. |
| | 301 | 18 | | private readonly object _gate = new(); |
| | | 19 | | private object? _untypedPayload; |
| | | 20 | | private bool _hasUntypedPayload; |
| | | 21 | | |
| | | 22 | | /// <summary>Runs the RawJsonResponse operation.</summary> |
| | 301 | 23 | | public RawJsonResponse(string json) |
| | | 24 | | { |
| | 301 | 25 | | JsonSafety.ThrowIfClearlyNotJson(json); |
| | 301 | 26 | | _json = json; |
| | 301 | 27 | | } |
| | | 28 | | |
| | 2 | 29 | | public string Json => _json; |
| | | 30 | | |
| | | 31 | | /// <summary>Runs the DeserializeUntyped operation.</summary> |
| | | 32 | | public object? DeserializeUntyped() |
| | | 33 | | { |
| | 2926 | 34 | | lock (_gate) |
| | | 35 | | { |
| | 2926 | 36 | | if (_hasUntypedPayload) |
| | 2702 | 37 | | return _untypedPayload; |
| | | 38 | | |
| | 224 | 39 | | _untypedPayload = JsonSafety.SafeDeserialize<object?>(_json); |
| | 224 | 40 | | _hasUntypedPayload = true; |
| | 224 | 41 | | return _untypedPayload; |
| | | 42 | | } |
| | 2926 | 43 | | } |
| | | 44 | | |
| | | 45 | | /// <summary>Runs the Deserialize operation.</summary> |
| | 5631 | 46 | | public T? Deserialize<T>() => (T?)Deserialize(typeof(T)); |
| | | 47 | | |
| | | 48 | | /// <summary>Materializes a private payload instance per call — see the aliasing note above.</summary> |
| | | 49 | | public object? Deserialize(Type payloadType) |
| | 5633 | 50 | | => JsonSafety.SafeDeserialize(_json, payloadType); |
| | | 51 | | } |