| | | 1 | | using System.Text.Json; |
| | | 2 | | using System.Text.Json.Nodes; |
| | | 3 | | using System.Text.Json.Serialization.Metadata; |
| | | 4 | | |
| | | 5 | | namespace AsyncResponse; |
| | | 6 | | |
| | | 7 | | internal static class FlowStateJson |
| | | 8 | | { |
| | | 9 | | // FlowState is a library wire type: its metadata is source-generated |
| | | 10 | | // (AsyncResponseJsonContext), and the ledger omits nulls exactly as before. |
| | | 11 | | private static JsonTypeInfo<FlowState> TypeInfo |
| | 3 | 12 | | => AsyncResponseJson.GetTypeInfo<FlowState>(AsyncResponseJson.IgnoreNullWrites); |
| | | 13 | | |
| | 3 | 14 | | public static string Serialize(FlowState state) => JsonSerializer.Serialize(state, TypeInfo); |
| | | 15 | | |
| | | 16 | | public static FlowState? Deserialize(string json) |
| | | 17 | | { |
| | | 18 | | try |
| | | 19 | | { |
| | 3 | 20 | | var state = JsonSerializer.Deserialize(json, TypeInfo); |
| | 3 | 21 | | return state is not null && FlowStateSchema.IsReadable(state.SchemaVersion) ? state : null; |
| | | 22 | | } |
| | 2 | 23 | | catch (JsonException) |
| | | 24 | | { |
| | 2 | 25 | | return null; |
| | | 26 | | } |
| | 3 | 27 | | } |
| | | 28 | | |
| | | 29 | | public static bool JsonEquivalent(string? left, string right) |
| | | 30 | | { |
| | 3 | 31 | | if (string.Equals(left, right, StringComparison.Ordinal)) |
| | 3 | 32 | | return true; |
| | 3 | 33 | | if (left is null) |
| | 2 | 34 | | return false; |
| | | 35 | | |
| | | 36 | | try |
| | | 37 | | { |
| | 3 | 38 | | return JsonNode.DeepEquals(JsonNode.Parse(left), JsonNode.Parse(right)); |
| | | 39 | | } |
| | 2 | 40 | | catch (JsonException) |
| | | 41 | | { |
| | 2 | 42 | | return false; |
| | | 43 | | } |
| | 3 | 44 | | } |
| | | 45 | | |
| | | 46 | | /// <summary> |
| | | 47 | | /// Serializes a child <see cref="FlowState"/> for memoization as a parent step result, without |
| | | 48 | | /// the captured ambient <see cref="FlowState.Context"/>: it is propagation machinery (it can |
| | | 49 | | /// carry principal/tenant values) that the parent never needs, and dropping it keeps nested |
| | | 50 | | /// child snapshots from compounding ledger size. |
| | | 51 | | /// </summary> |
| | | 52 | | public static string SerializeSnapshot(FlowState state) |
| | | 53 | | { |
| | 2 | 54 | | var context = state.Context; |
| | 2 | 55 | | state.Context = null; |
| | | 56 | | try |
| | | 57 | | { |
| | 2 | 58 | | return Serialize(state); |
| | | 59 | | } |
| | | 60 | | finally |
| | | 61 | | { |
| | 2 | 62 | | state.Context = context; |
| | 2 | 63 | | } |
| | 2 | 64 | | } |
| | | 65 | | } |