| | | 1 | | //======================================================================= |
| | | 2 | | // JsonRecordSerializer.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 | | using System; |
| | | 9 | | using System.Collections.Generic; |
| | | 10 | | using System.Diagnostics.CodeAnalysis; |
| | | 11 | | using System.IO; |
| | | 12 | | using System.Text; |
| | | 13 | | using System.Text.Json; |
| | | 14 | | |
| | | 15 | | namespace Chronicler.Serialization; |
| | | 16 | | |
| | | 17 | | /// <summary> |
| | | 18 | | /// Saves recorded state to JSON and restores it into host-created objects. |
| | | 19 | | /// </summary> |
| | | 20 | | /// <remarks>Each call made without a session context creates one with an empty link registry.</remarks> |
| | | 21 | | public static class JsonRecordSerializer |
| | | 22 | | { |
| | 1 | 23 | | private static readonly JsonSerializerOptions _defaultOptions = CreateDefaultOptions(); |
| | | 24 | | |
| | | 25 | | /// <inheritdoc cref="Serialize(IRecordable, ChronicleContext, bool)"/> |
| | | 26 | | public static string Serialize(IRecordable target, bool writeIndented = false) |
| | 6 | 27 | | => Serialize(target, context: null, writeIndented); |
| | | 28 | | |
| | | 29 | | /// <summary> |
| | | 30 | | /// Saves the state declared by a recordable instance. |
| | | 31 | | /// </summary> |
| | | 32 | | /// <param name="target">The source whose schema runs in <see cref="SerializationMode.Saving"/> mode.</param> |
| | | 33 | | /// <param name="context">The session that supplies stable link IDs. Null creates a fresh context.</param> |
| | | 34 | | /// <param name="writeIndented">Whether to indent the output. The default produces compact JSON.</param> |
| | | 35 | | /// <returns>A JSON object keyed by the recorded field names.</returns> |
| | | 36 | | /// <exception cref="ArgumentNullException"><paramref name="target"/> is null.</exception> |
| | | 37 | | /// <exception cref="InvalidOperationException">A non-null recorded link has no stable ID.</exception> |
| | | 38 | | public static string Serialize(IRecordable target, ChronicleContext? context, bool writeIndented = false) |
| | | 39 | | { |
| | 82 | 40 | | if (target == null) |
| | 1 | 41 | | throw new ArgumentNullException(nameof(target)); |
| | | 42 | | |
| | 81 | 43 | | context ??= new ChronicleContext(); |
| | | 44 | | |
| | 81 | 45 | | JsonSerializerOptions options = writeIndented |
| | 81 | 46 | | ? CreateIndentedOptions() |
| | 81 | 47 | | : _defaultOptions; |
| | | 48 | | |
| | 81 | 49 | | var chronicler = new JsonRecordWriter(options, context); |
| | 81 | 50 | | target.RecordData(chronicler); |
| | 79 | 51 | | return chronicler.ToJson(); |
| | | 52 | | } |
| | | 53 | | |
| | | 54 | | /// <inheritdoc cref="Populate(IRecordable, string, ChronicleContext)"/> |
| | | 55 | | public static void Populate(IRecordable target, string json) |
| | 8 | 56 | | => Populate(target, json, context: null); |
| | | 57 | | |
| | | 58 | | /// <summary> |
| | | 59 | | /// Applies a JSON record to an existing instance. |
| | | 60 | | /// </summary> |
| | | 61 | | /// <param name="target">The object to mutate. Initialize owned class instances needed by present deep records.</par |
| | | 62 | | /// <param name="json">The nonblank JSON object containing the recorded fields.</param> |
| | | 63 | | /// <param name="context">The destination session for link resolution. Null creates a fresh context.</param> |
| | | 64 | | /// <remarks> |
| | | 65 | | /// Runs the target schema, then calls <see cref="ChronicleContext.ResolveDeferredLinks"/>. |
| | | 66 | | /// A failure can leave earlier assignments applied. A supplied context retains pending callbacks. |
| | | 67 | | /// </remarks> |
| | | 68 | | /// <exception cref="ArgumentNullException"><paramref name="target"/> is null.</exception> |
| | | 69 | | /// <exception cref="ArgumentException"><paramref name="json"/> is null, empty, or whitespace.</exception> |
| | | 70 | | /// <exception cref="JsonException">The payload is malformed or a recorded value cannot be read as its declared type |
| | | 71 | | /// <exception cref="InvalidOperationException"> |
| | | 72 | | /// A record that is read as an object has another JSON shape, a present deep class lacks an initialized |
| | | 73 | | /// target, or link resolution fails. |
| | | 74 | | /// </exception> |
| | | 75 | | public static void Populate(IRecordable target, string json, ChronicleContext? context) |
| | | 76 | | { |
| | 96 | 77 | | if (target == null) |
| | 1 | 78 | | throw new ArgumentNullException(nameof(target)); |
| | 95 | 79 | | if (string.IsNullOrWhiteSpace(json)) |
| | 3 | 80 | | throw new ArgumentException("Serialized JSON must not be null or empty.", nameof(json)); |
| | | 81 | | |
| | 92 | 82 | | context ??= new ChronicleContext(); |
| | | 83 | | |
| | 92 | 84 | | using var chronicler = new JsonRecordReader(json, _defaultOptions, context); |
| | 92 | 85 | | target.RecordData(chronicler); |
| | 55 | 86 | | context.ResolveDeferredLinks(); |
| | 106 | 87 | | } |
| | | 88 | | |
| | | 89 | | private static JsonSerializerOptions CreateDefaultOptions() |
| | | 90 | | { |
| | 1 | 91 | | return new JsonSerializerOptions() |
| | 1 | 92 | | { |
| | 1 | 93 | | IncludeFields = true |
| | 1 | 94 | | }; |
| | | 95 | | } |
| | | 96 | | |
| | | 97 | | private static JsonSerializerOptions CreateIndentedOptions() |
| | | 98 | | { |
| | 77 | 99 | | return new JsonSerializerOptions(_defaultOptions) |
| | 77 | 100 | | { |
| | 77 | 101 | | WriteIndented = true |
| | 77 | 102 | | }; |
| | | 103 | | } |
| | | 104 | | |
| | | 105 | | private sealed class JsonRecordWriter : IChronicler |
| | | 106 | | { |
| | 204 | 107 | | private readonly OrderedStringMap<string> _entries = new(8, StringComparer.Ordinal); |
| | | 108 | | private readonly JsonSerializerOptions _options; |
| | | 109 | | |
| | 204 | 110 | | public JsonRecordWriter(JsonSerializerOptions options, ChronicleContext context) |
| | | 111 | | { |
| | 204 | 112 | | _options = options; |
| | 204 | 113 | | Context = context; |
| | 204 | 114 | | } |
| | | 115 | | |
| | | 116 | | public ChronicleContext Context { get; } |
| | | 117 | | |
| | 22 | 118 | | public SerializationMode Mode => SerializationMode.Saving; |
| | | 119 | | |
| | | 120 | | public void LookValue<T>(ref T value, string name, T? defaultValue = default) |
| | | 121 | | { |
| | 402 | 122 | | if (value is null || EqualityComparer<T>.Default.Equals(value, defaultValue!)) |
| | 112 | 123 | | return; |
| | | 124 | | |
| | 290 | 125 | | _entries[name] = JsonSerializer.Serialize(value, _options); |
| | 290 | 126 | | } |
| | | 127 | | |
| | | 128 | | public void LookDeep<T>(ref T value, string name) where T : class, IRecordable |
| | | 129 | | { |
| | 12 | 130 | | if (value == null) |
| | | 131 | | { |
| | 1 | 132 | | _entries[name] = "null"; |
| | 1 | 133 | | return; |
| | | 134 | | } |
| | | 135 | | |
| | 11 | 136 | | var nested = new JsonRecordWriter(_options, Context); |
| | 11 | 137 | | value.RecordData(nested); |
| | 11 | 138 | | _entries[name] = nested.ToJson(); |
| | 11 | 139 | | } |
| | | 140 | | |
| | | 141 | | public void LookDeepStruct<T>(ref T value, string name) where T : struct, IRecordable |
| | | 142 | | { |
| | 107 | 143 | | var nested = new JsonRecordWriter(_options, Context); |
| | 107 | 144 | | value.RecordData(nested); |
| | 107 | 145 | | _entries[name] = nested.ToJson(); |
| | 107 | 146 | | } |
| | | 147 | | |
| | | 148 | | public void LookNullableDeep<T>(ref T? value, string name) where T : struct, IRecordable |
| | | 149 | | { |
| | 7 | 150 | | if (!value.HasValue) |
| | 2 | 151 | | return; |
| | | 152 | | |
| | 5 | 153 | | T nestedValue = value.Value; |
| | 5 | 154 | | var nested = new JsonRecordWriter(_options, Context); |
| | 5 | 155 | | nestedValue.RecordData(nested); |
| | 5 | 156 | | _entries[name] = nested.ToJson(); |
| | 5 | 157 | | } |
| | | 158 | | |
| | | 159 | | public void LookLink<T>( |
| | | 160 | | ref T value, |
| | | 161 | | string name, |
| | | 162 | | string? slot = null, |
| | | 163 | | RecordLinkResolveMode resolveMode = RecordLinkResolveMode.Immediate, |
| | | 164 | | Action<T>? assignLoadedValue = null) |
| | | 165 | | { |
| | 15 | 166 | | string? id = null; |
| | 15 | 167 | | if (value is not null |
| | 15 | 168 | | && !Context.Links.TryGetReferenceId(value, out id, slot)) |
| | | 169 | | { |
| | 2 | 170 | | throw new InvalidOperationException( |
| | 2 | 171 | | $"Unable to save link '{name}' of type {typeof(T).Name} because no stable id could be produced{Forma |
| | | 172 | | } |
| | | 173 | | |
| | 13 | 174 | | _entries[name] = JsonSerializer.Serialize(id, _options); |
| | 13 | 175 | | } |
| | | 176 | | |
| | | 177 | | public string ToJson() |
| | | 178 | | { |
| | 202 | 179 | | using var stream = new MemoryStream(); |
| | 202 | 180 | | using (var writer = new Utf8JsonWriter(stream, new JsonWriterOptions() { Indented = _options.WriteIndented } |
| | | 181 | | { |
| | 202 | 182 | | writer.WriteStartObject(); |
| | | 183 | | |
| | 1256 | 184 | | foreach (var entry in _entries) |
| | | 185 | | { |
| | 426 | 186 | | writer.WritePropertyName(entry.Key); |
| | 426 | 187 | | using var document = JsonDocument.Parse(entry.Value); |
| | 426 | 188 | | document.RootElement.WriteTo(writer); |
| | | 189 | | } |
| | | 190 | | |
| | 202 | 191 | | writer.WriteEndObject(); |
| | 202 | 192 | | } |
| | | 193 | | |
| | 202 | 194 | | return Encoding.UTF8.GetString(stream.ToArray()); |
| | 202 | 195 | | } |
| | | 196 | | } |
| | | 197 | | |
| | | 198 | | private sealed class JsonRecordReader : IChronicler, IDisposable |
| | | 199 | | { |
| | | 200 | | private readonly JsonDocument _document; |
| | | 201 | | private readonly JsonElement _root; |
| | | 202 | | private readonly JsonSerializerOptions _options; |
| | | 203 | | |
| | 230 | 204 | | public JsonRecordReader(string json, JsonSerializerOptions options, ChronicleContext context) |
| | | 205 | | { |
| | 230 | 206 | | _document = JsonDocument.Parse(json); |
| | 230 | 207 | | _root = _document.RootElement; |
| | 230 | 208 | | _options = options; |
| | 230 | 209 | | Context = context; |
| | 230 | 210 | | } |
| | | 211 | | |
| | | 212 | | public ChronicleContext Context { get; } |
| | | 213 | | |
| | 34 | 214 | | public SerializationMode Mode => SerializationMode.Loading; |
| | | 215 | | |
| | | 216 | | public void LookValue<T>(ref T value, string name, T? defaultValue = default) |
| | | 217 | | { |
| | 415 | 218 | | if (!_root.TryGetProperty(name, out JsonElement entry)) |
| | | 219 | | { |
| | 158 | 220 | | value = defaultValue!; |
| | 158 | 221 | | return; |
| | | 222 | | } |
| | | 223 | | |
| | 257 | 224 | | if (entry.ValueKind == JsonValueKind.Null) |
| | | 225 | | { |
| | 1 | 226 | | value = defaultValue!; |
| | 1 | 227 | | return; |
| | | 228 | | } |
| | | 229 | | |
| | 256 | 230 | | T? loadedValue = JsonSerializer.Deserialize<T>(entry.GetRawText(), _options); |
| | 256 | 231 | | if (loadedValue is null) |
| | | 232 | | { |
| | 1 | 233 | | value = defaultValue!; |
| | 1 | 234 | | return; |
| | | 235 | | } |
| | | 236 | | |
| | 255 | 237 | | value = loadedValue; |
| | 255 | 238 | | } |
| | | 239 | | |
| | | 240 | | public void LookDeep<T>(ref T value, string name) where T : class, IRecordable |
| | | 241 | | { |
| | 11 | 242 | | if (!_root.TryGetProperty(name, out JsonElement entry) || entry.ValueKind == JsonValueKind.Null) |
| | 2 | 243 | | return; |
| | | 244 | | |
| | 9 | 245 | | if (value == null) |
| | 1 | 246 | | throw new InvalidOperationException( |
| | 1 | 247 | | $"Unable to load '{name}' because {typeof(T).Name} must already be instantiated for a deep chronicle |
| | | 248 | | |
| | 8 | 249 | | using var nested = new JsonRecordReader(entry.GetRawText(), _options, Context); |
| | 8 | 250 | | value.RecordData(nested); |
| | 16 | 251 | | } |
| | | 252 | | |
| | | 253 | | public void LookDeepStruct<T>(ref T value, string name) where T : struct, IRecordable |
| | | 254 | | { |
| | 121 | 255 | | if (!_root.TryGetProperty(name, out JsonElement entry) || entry.ValueKind == JsonValueKind.Null) |
| | | 256 | | { |
| | 11 | 257 | | value = CreateDefaultDeepStruct<T>(); |
| | 10 | 258 | | return; |
| | | 259 | | } |
| | | 260 | | |
| | 110 | 261 | | value = new(); |
| | 110 | 262 | | using var nested = new JsonRecordReader(entry.GetRawText(), _options, Context); |
| | 110 | 263 | | value.RecordData(nested); |
| | 208 | 264 | | } |
| | | 265 | | |
| | | 266 | | public void LookNullableDeep<T>(ref T? value, string name) where T : struct, IRecordable |
| | | 267 | | { |
| | 13 | 268 | | if (!_root.TryGetProperty(name, out JsonElement entry) || entry.ValueKind == JsonValueKind.Null) |
| | | 269 | | { |
| | 4 | 270 | | value = null; |
| | 4 | 271 | | return; |
| | | 272 | | } |
| | | 273 | | |
| | 9 | 274 | | T nestedValue = new(); |
| | 9 | 275 | | using var nested = new JsonRecordReader(entry.GetRawText(), _options, Context); |
| | 9 | 276 | | nestedValue.RecordData(nested); |
| | 3 | 277 | | value = nestedValue; |
| | 6 | 278 | | } |
| | | 279 | | |
| | | 280 | | public void LookLink<T>( |
| | | 281 | | ref T value, |
| | | 282 | | string name, |
| | | 283 | | string? slot = null, |
| | | 284 | | RecordLinkResolveMode resolveMode = RecordLinkResolveMode.Immediate, |
| | | 285 | | Action<T>? assignLoadedValue = null) |
| | | 286 | | { |
| | 15 | 287 | | if (!TryReadLinkId(name, out string? id)) |
| | | 288 | | { |
| | 6 | 289 | | value = default!; |
| | 6 | 290 | | assignLoadedValue?.Invoke(value); |
| | 6 | 291 | | return; |
| | | 292 | | } |
| | | 293 | | |
| | 9 | 294 | | if (resolveMode == RecordLinkResolveMode.Deferred) |
| | | 295 | | { |
| | 5 | 296 | | LoadDeferredLink(ref value, name, id, slot, assignLoadedValue); |
| | 4 | 297 | | return; |
| | | 298 | | } |
| | | 299 | | |
| | 4 | 300 | | LoadImmediateLink(ref value, name, id, slot, assignLoadedValue); |
| | 3 | 301 | | } |
| | | 302 | | |
| | | 303 | | private bool TryReadLinkId(string name, [NotNullWhen(true)] out string? id) |
| | | 304 | | { |
| | 15 | 305 | | if (!_root.TryGetProperty(name, out JsonElement entry) |
| | 15 | 306 | | || entry.ValueKind == JsonValueKind.Null) |
| | | 307 | | { |
| | 6 | 308 | | id = null; |
| | 6 | 309 | | return false; |
| | | 310 | | } |
| | | 311 | | |
| | 9 | 312 | | id = JsonSerializer.Deserialize<string>(entry.GetRawText(), _options); |
| | 9 | 313 | | return id != null; |
| | | 314 | | } |
| | | 315 | | |
| | | 316 | | private void LoadDeferredLink<T>( |
| | | 317 | | ref T value, |
| | | 318 | | string name, |
| | | 319 | | string id, |
| | | 320 | | string? slot, |
| | | 321 | | Action<T>? assignLoadedValue) |
| | | 322 | | { |
| | 5 | 323 | | if (assignLoadedValue == null) |
| | 1 | 324 | | throw new InvalidOperationException( |
| | 1 | 325 | | $"Deferred link '{name}' of type {typeof(T).Name} requires an assignment callback."); |
| | | 326 | | |
| | 4 | 327 | | if (Context.Links.TryResolve(id, out T? deferredValue, slot)) |
| | | 328 | | { |
| | 1 | 329 | | value = deferredValue!; |
| | 1 | 330 | | assignLoadedValue(deferredValue!); |
| | 1 | 331 | | return; |
| | | 332 | | } |
| | | 333 | | |
| | 3 | 334 | | Context.QueueDeferredLink(name, id, slot, assignLoadedValue); |
| | 3 | 335 | | value = default!; |
| | 3 | 336 | | } |
| | | 337 | | |
| | | 338 | | private void LoadImmediateLink<T>( |
| | | 339 | | ref T value, |
| | | 340 | | string name, |
| | | 341 | | string id, |
| | | 342 | | string? slot, |
| | | 343 | | Action<T>? assignLoadedValue) |
| | | 344 | | { |
| | 4 | 345 | | if (!Context.Links.TryResolve(id, out T? resolvedValue, slot)) |
| | 1 | 346 | | throw new InvalidOperationException( |
| | 1 | 347 | | $"Unable to load link '{name}' of type {typeof(T).Name} with id '{id}'{FormatSlot(slot)}."); |
| | | 348 | | |
| | 3 | 349 | | value = resolvedValue!; |
| | 3 | 350 | | assignLoadedValue?.Invoke(resolvedValue!); |
| | 3 | 351 | | } |
| | | 352 | | |
| | | 353 | | public void Dispose() |
| | | 354 | | { |
| | 230 | 355 | | _document.Dispose(); |
| | 230 | 356 | | } |
| | | 357 | | |
| | | 358 | | private T CreateDefaultDeepStruct<T>() where T : struct, IRecordable |
| | | 359 | | { |
| | 11 | 360 | | T defaultValue = new(); |
| | 11 | 361 | | using var nested = new JsonRecordReader("{}", _options, Context); |
| | 11 | 362 | | defaultValue.RecordData(nested); |
| | 10 | 363 | | return defaultValue; |
| | 10 | 364 | | } |
| | | 365 | | } |
| | | 366 | | |
| | | 367 | | private static string FormatSlot(string? slot) |
| | | 368 | | { |
| | 3 | 369 | | return string.IsNullOrEmpty(slot) |
| | 3 | 370 | | ? string.Empty |
| | 3 | 371 | | : $" in slot '{slot}'"; |
| | | 372 | | } |
| | | 373 | | } |