| | | 1 | | //======================================================================= |
| | | 2 | | // SerializationPayloadEditor.cs |
| | | 3 | | //======================================================================= |
| | | 4 | | // MIT License, Copyright (c) 2024-present David Oravsky (mrdav30) |
| | | 5 | | // See LICENSE file in the project root for full license information. |
| | | 6 | | //======================================================================= |
| | | 7 | | |
| | | 8 | | #if !CHRONICLER_DISABLE_MEMORYPACK |
| | | 9 | | using MemoryPack; |
| | | 10 | | #endif |
| | | 11 | | using System; |
| | | 12 | | using System.Text.Json; |
| | | 13 | | using System.Text.Json.Nodes; |
| | | 14 | | |
| | | 15 | | namespace Chronicler.Serialization; |
| | | 16 | | |
| | | 17 | | /// <summary> |
| | | 18 | | /// Edits JSON properties and MemoryPack entries without populating a recordable object graph. |
| | | 19 | | /// </summary> |
| | | 20 | | /// <remarks> |
| | | 21 | | /// Paths and replacement values must match the recorded schema. Replacement values use the |
| | | 22 | | /// selected transport serializer directly; editing does not invoke <see cref="IRecordable.RecordData"/>. |
| | | 23 | | /// Use the format-specific record serializers to serialize and populate records. |
| | | 24 | | /// A serialized null MemoryPack envelope is treated as an empty record. |
| | | 25 | | /// </remarks> |
| | | 26 | | public static class SerializationPayloadEditor |
| | | 27 | | { |
| | | 28 | | #region JSON Editing |
| | | 29 | | |
| | 1 | 30 | | private static readonly JsonSerializerOptions JsonOptions = new() |
| | 1 | 31 | | { |
| | 1 | 32 | | IncludeFields = true |
| | 1 | 33 | | }; |
| | | 34 | | |
| | | 35 | | /// <summary>Removes a recorded JSON property if it exists.</summary> |
| | | 36 | | /// <param name="json">A payload whose root is a JSON object.</param> |
| | | 37 | | /// <param name="path">Ordered property names from the root to the target. Each intermediate name must identify a ne |
| | | 38 | | /// <returns>The complete edited object serialized as JSON.</returns> |
| | | 39 | | /// <exception cref="ArgumentException"><paramref name="path"/> is null or has no segments.</exception> |
| | | 40 | | /// <exception cref="InvalidOperationException">The root or an intermediate node is missing or is not a JSON object. |
| | | 41 | | /// <exception cref="JsonException">The JSON codec rejects the payload.</exception> |
| | | 42 | | public static string RemoveJsonProperty(string json, params string[] path) |
| | | 43 | | { |
| | 41 | 44 | | if (path == null || path.Length == 0) |
| | 2 | 45 | | throw new ArgumentException("A JSON property path is required.", nameof(path)); |
| | | 46 | | |
| | 39 | 47 | | JsonObject root = ParseJsonRoot(json); |
| | 38 | 48 | | JsonObject parent = GetJsonParent(root, path); |
| | 38 | 49 | | parent.Remove(path[^1]); |
| | 38 | 50 | | return root.ToJsonString(JsonOptions); |
| | | 51 | | } |
| | | 52 | | |
| | | 53 | | /// <summary>Adds or replaces a recorded JSON property.</summary> |
| | | 54 | | /// <typeparam name="T">The declared type used to encode the replacement.</typeparam> |
| | | 55 | | /// <param name="json">A payload whose root is a JSON object.</param> |
| | | 56 | | /// <param name="value">The replacement to encode with the transport's value codec.</param> |
| | | 57 | | /// <param name="path">Ordered property names from the root to the target. Each intermediate name must identify a ne |
| | | 58 | | /// <returns>The complete edited object serialized as JSON.</returns> |
| | | 59 | | /// <exception cref="ArgumentException"><paramref name="path"/> is null or has no segments.</exception> |
| | | 60 | | /// <exception cref="InvalidOperationException">The root or an intermediate node is missing or is not a JSON object. |
| | | 61 | | /// <exception cref="JsonException">The JSON codec rejects the payload or replacement value.</exception> |
| | | 62 | | public static string SetJsonValue<T>(string json, T value, params string[] path) |
| | | 63 | | { |
| | 24 | 64 | | if (path == null || path.Length == 0) |
| | 2 | 65 | | throw new ArgumentException("A JSON property path is required.", nameof(path)); |
| | | 66 | | |
| | 22 | 67 | | JsonObject root = ParseJsonRoot(json); |
| | 21 | 68 | | JsonObject parent = GetJsonParent(root, path); |
| | 20 | 69 | | parent[path[^1]] = JsonSerializer.SerializeToNode(value, JsonOptions); |
| | 20 | 70 | | return root.ToJsonString(JsonOptions); |
| | | 71 | | } |
| | | 72 | | |
| | | 73 | | private static JsonObject ParseJsonRoot(string json) |
| | | 74 | | { |
| | 61 | 75 | | JsonNode rootNode = JsonNode.Parse(json) |
| | 61 | 76 | | ?? throw new InvalidOperationException("Unable to parse JSON payload."); |
| | 60 | 77 | | return rootNode as JsonObject |
| | 60 | 78 | | ?? throw new InvalidOperationException("Expected JSON root object."); |
| | | 79 | | } |
| | | 80 | | |
| | | 81 | | private static JsonObject GetJsonParent(JsonObject root, string[] path) |
| | | 82 | | { |
| | 59 | 83 | | JsonObject current = root; |
| | 206 | 84 | | for (int i = 0; i < path.Length - 1; i++) |
| | | 85 | | { |
| | 45 | 86 | | current = current[path[i]] as JsonObject |
| | 45 | 87 | | ?? throw new InvalidOperationException( |
| | 45 | 88 | | $"Expected JSON object at path segment '{path[i]}'."); |
| | | 89 | | } |
| | | 90 | | |
| | 58 | 91 | | return current; |
| | | 92 | | } |
| | | 93 | | |
| | | 94 | | #endregion |
| | | 95 | | |
| | | 96 | | #if !CHRONICLER_DISABLE_MEMORYPACK |
| | | 97 | | |
| | | 98 | | #region MemoryPack Editing |
| | | 99 | | |
| | | 100 | | /// <summary>Removes a recorded MemoryPack entry if it exists.</summary> |
| | | 101 | | /// <param name="data">The source record bytes. The input buffer is read as-is and remains caller-owned.</param> |
| | | 102 | | /// <param name="path">Ordered entry names from the root to the target. Each intermediate name must identify a neste |
| | | 103 | | /// <returns>The complete edited record in a new caller-owned array.</returns> |
| | | 104 | | /// <exception cref="ArgumentException"><paramref name="path"/> is null or has no segments.</exception> |
| | | 105 | | /// <exception cref="InvalidOperationException">An intermediate entry is missing or null.</exception> |
| | | 106 | | /// <exception cref="MemoryPackSerializationException">The MemoryPack codec rejects the payload.</exception> |
| | | 107 | | public static byte[] RemoveMemoryPackEntry(byte[] data, params string[] path) |
| | | 108 | | { |
| | 42 | 109 | | if (path == null || path.Length == 0) |
| | 2 | 110 | | throw new ArgumentException("A MemoryPack entry path is required.", nameof(path)); |
| | | 111 | | |
| | 40 | 112 | | MemoryPackRecordEnvelope envelope = ReadEnvelope(data); |
| | 40 | 113 | | RemoveMemoryPackEntry(envelope, path, 0); |
| | 39 | 114 | | return MemoryPackSerializer.Serialize(envelope); |
| | | 115 | | } |
| | | 116 | | |
| | | 117 | | /// <summary>Adds or replaces a recorded MemoryPack entry.</summary> |
| | | 118 | | /// <typeparam name="T">The declared type used to encode the replacement.</typeparam> |
| | | 119 | | /// <param name="data">The source record bytes. The input buffer is read as-is and remains caller-owned.</param> |
| | | 120 | | /// <param name="value">The replacement to encode with the transport's value codec.</param> |
| | | 121 | | /// <param name="path">Ordered entry names from the root to the target. Each intermediate name must identify a neste |
| | | 122 | | /// <returns>The complete edited record in a new caller-owned array.</returns> |
| | | 123 | | /// <exception cref="ArgumentException"><paramref name="path"/> is null or has no segments.</exception> |
| | | 124 | | /// <exception cref="InvalidOperationException">An intermediate entry is missing or null.</exception> |
| | | 125 | | /// <exception cref="MemoryPackSerializationException">The MemoryPack codec rejects the payload or replacement value |
| | | 126 | | public static byte[] SetMemoryPackValue<T>(byte[] data, T value, params string[] path) |
| | | 127 | | { |
| | 24 | 128 | | if (path == null || path.Length == 0) |
| | 2 | 129 | | throw new ArgumentException("A MemoryPack entry path is required.", nameof(path)); |
| | | 130 | | |
| | 22 | 131 | | MemoryPackRecordEnvelope envelope = ReadEnvelope(data); |
| | 22 | 132 | | SetMemoryPackValue(envelope, path, 0, MemoryPackSerializer.Serialize(value)); |
| | 21 | 133 | | return MemoryPackSerializer.Serialize(envelope); |
| | | 134 | | } |
| | | 135 | | |
| | | 136 | | private static MemoryPackRecordEnvelope ReadEnvelope(byte[] data) |
| | | 137 | | { |
| | 106 | 138 | | return MemoryPackRecordEnvelope.Deserialize(data) |
| | 106 | 139 | | ?? new MemoryPackRecordEnvelope(); |
| | | 140 | | } |
| | | 141 | | |
| | | 142 | | private static void RemoveMemoryPackEntry(MemoryPackRecordEnvelope envelope, string[] path, int depth) |
| | | 143 | | { |
| | 65 | 144 | | if (depth == path.Length - 1) |
| | | 145 | | { |
| | 39 | 146 | | envelope.RemoveEntry(path[depth]); |
| | 39 | 147 | | return; |
| | | 148 | | } |
| | | 149 | | |
| | 26 | 150 | | if (!envelope.TryGetEntry(path[depth], out byte[]? nestedData) |
| | 26 | 151 | | || nestedData == null) |
| | | 152 | | { |
| | 1 | 153 | | throw new InvalidOperationException( |
| | 1 | 154 | | $"Unable to locate MemoryPack entry '{path[depth]}' at depth {depth}."); |
| | | 155 | | } |
| | | 156 | | |
| | 25 | 157 | | MemoryPackRecordEnvelope nestedEnvelope = ReadEnvelope(nestedData); |
| | 25 | 158 | | RemoveMemoryPackEntry(nestedEnvelope, path, depth + 1); |
| | 25 | 159 | | envelope.SetEntry(path[depth], MemoryPackSerializer.Serialize(nestedEnvelope)); |
| | 25 | 160 | | } |
| | | 161 | | |
| | | 162 | | private static void SetMemoryPackValue( |
| | | 163 | | MemoryPackRecordEnvelope envelope, |
| | | 164 | | string[] path, |
| | | 165 | | int depth, |
| | | 166 | | byte[] serializedValue) |
| | | 167 | | { |
| | 41 | 168 | | if (depth == path.Length - 1) |
| | | 169 | | { |
| | 21 | 170 | | envelope.SetEntry(path[depth], serializedValue); |
| | 21 | 171 | | return; |
| | | 172 | | } |
| | | 173 | | |
| | 20 | 174 | | if (!envelope.TryGetEntry(path[depth], out byte[]? nestedData) |
| | 20 | 175 | | || nestedData == null) |
| | | 176 | | { |
| | 1 | 177 | | throw new InvalidOperationException( |
| | 1 | 178 | | $"Unable to locate MemoryPack entry '{path[depth]}' at depth {depth}."); |
| | | 179 | | } |
| | | 180 | | |
| | 19 | 181 | | MemoryPackRecordEnvelope nestedEnvelope = ReadEnvelope(nestedData); |
| | 19 | 182 | | SetMemoryPackValue(nestedEnvelope, path, depth + 1, serializedValue); |
| | 19 | 183 | | envelope.SetEntry(path[depth], MemoryPackSerializer.Serialize(nestedEnvelope)); |
| | 19 | 184 | | } |
| | | 185 | | |
| | | 186 | | #endregion |
| | | 187 | | |
| | | 188 | | #endif |
| | | 189 | | } |