< Summary

Information
Class: Chronicler.Serialization.JsonRecordSerializer
Assembly: Chronicler
File(s): /home/runner/work/Chronicler/Chronicler/src/Chronicler/Serialization/Json/JsonRecordSerializer.cs
Line coverage
100%
Covered lines: 158
Uncovered lines: 0
Coverable lines: 158
Total lines: 373
Line coverage: 100%
Branch coverage
100%
Covered branches: 66
Total branches: 66
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
Serialize(...)100%11100%
Serialize(...)100%66100%
Populate(...)100%11100%
Populate(...)100%66100%
CreateDefaultOptions()100%11100%
CreateIndentedOptions()100%11100%
.ctor(...)100%11100%
get_Mode()100%11100%
LookValue(...)100%44100%
LookDeep(...)100%22100%
LookDeepStruct(...)100%11100%
LookNullableDeep(...)100%22100%
LookLink(...)100%44100%
ToJson()100%22100%
.ctor(...)100%11100%
get_Mode()100%11100%
LookValue(...)100%66100%
LookDeep(...)100%66100%
LookDeepStruct(...)100%44100%
LookNullableDeep(...)100%44100%
LookLink(...)100%66100%
TryReadLinkId(...)100%44100%
LoadDeferredLink(...)100%44100%
LoadImmediateLink(...)100%44100%
Dispose()100%11100%
CreateDefaultDeepStruct()100%11100%
FormatSlot(...)100%22100%

File(s)

/home/runner/work/Chronicler/Chronicler/src/Chronicler/Serialization/Json/JsonRecordSerializer.cs

#LineLine coverage
 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
 8using System;
 9using System.Collections.Generic;
 10using System.Diagnostics.CodeAnalysis;
 11using System.IO;
 12using System.Text;
 13using System.Text.Json;
 14
 15namespace 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>
 21public static class JsonRecordSerializer
 22{
 123    private static readonly JsonSerializerOptions _defaultOptions = CreateDefaultOptions();
 24
 25    /// <inheritdoc cref="Serialize(IRecordable, ChronicleContext, bool)"/>
 26    public static string Serialize(IRecordable target, bool writeIndented = false)
 627        => 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    {
 8240        if (target == null)
 141            throw new ArgumentNullException(nameof(target));
 42
 8143        context ??= new ChronicleContext();
 44
 8145        JsonSerializerOptions options = writeIndented
 8146            ? CreateIndentedOptions()
 8147            : _defaultOptions;
 48
 8149        var chronicler = new JsonRecordWriter(options, context);
 8150        target.RecordData(chronicler);
 7951        return chronicler.ToJson();
 52    }
 53
 54    /// <inheritdoc cref="Populate(IRecordable, string, ChronicleContext)"/>
 55    public static void Populate(IRecordable target, string json)
 856        => 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    {
 9677        if (target == null)
 178            throw new ArgumentNullException(nameof(target));
 9579        if (string.IsNullOrWhiteSpace(json))
 380            throw new ArgumentException("Serialized JSON must not be null or empty.", nameof(json));
 81
 9282        context ??= new ChronicleContext();
 83
 9284        using var chronicler = new JsonRecordReader(json, _defaultOptions, context);
 9285        target.RecordData(chronicler);
 5586        context.ResolveDeferredLinks();
 10687    }
 88
 89    private static JsonSerializerOptions CreateDefaultOptions()
 90    {
 191        return new JsonSerializerOptions()
 192        {
 193            IncludeFields = true
 194        };
 95    }
 96
 97    private static JsonSerializerOptions CreateIndentedOptions()
 98    {
 7799        return new JsonSerializerOptions(_defaultOptions)
 77100        {
 77101            WriteIndented = true
 77102        };
 103    }
 104
 105    private sealed class JsonRecordWriter : IChronicler
 106    {
 204107        private readonly OrderedStringMap<string> _entries = new(8, StringComparer.Ordinal);
 108        private readonly JsonSerializerOptions _options;
 109
 204110        public JsonRecordWriter(JsonSerializerOptions options, ChronicleContext context)
 111        {
 204112            _options = options;
 204113            Context = context;
 204114        }
 115
 116        public ChronicleContext Context { get; }
 117
 22118        public SerializationMode Mode => SerializationMode.Saving;
 119
 120        public void LookValue<T>(ref T value, string name, T? defaultValue = default)
 121        {
 402122            if (value is null || EqualityComparer<T>.Default.Equals(value, defaultValue!))
 112123                return;
 124
 290125            _entries[name] = JsonSerializer.Serialize(value, _options);
 290126        }
 127
 128        public void LookDeep<T>(ref T value, string name) where T : class, IRecordable
 129        {
 12130            if (value == null)
 131            {
 1132                _entries[name] = "null";
 1133                return;
 134            }
 135
 11136            var nested = new JsonRecordWriter(_options, Context);
 11137            value.RecordData(nested);
 11138            _entries[name] = nested.ToJson();
 11139        }
 140
 141        public void LookDeepStruct<T>(ref T value, string name) where T : struct, IRecordable
 142        {
 107143            var nested = new JsonRecordWriter(_options, Context);
 107144            value.RecordData(nested);
 107145            _entries[name] = nested.ToJson();
 107146        }
 147
 148        public void LookNullableDeep<T>(ref T? value, string name) where T : struct, IRecordable
 149        {
 7150            if (!value.HasValue)
 2151                return;
 152
 5153            T nestedValue = value.Value;
 5154            var nested = new JsonRecordWriter(_options, Context);
 5155            nestedValue.RecordData(nested);
 5156            _entries[name] = nested.ToJson();
 5157        }
 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        {
 15166            string? id = null;
 15167            if (value is not null
 15168                && !Context.Links.TryGetReferenceId(value, out id, slot))
 169            {
 2170                throw new InvalidOperationException(
 2171                    $"Unable to save link '{name}' of type {typeof(T).Name} because no stable id could be produced{Forma
 172            }
 173
 13174            _entries[name] = JsonSerializer.Serialize(id, _options);
 13175        }
 176
 177        public string ToJson()
 178        {
 202179            using var stream = new MemoryStream();
 202180            using (var writer = new Utf8JsonWriter(stream, new JsonWriterOptions() { Indented = _options.WriteIndented }
 181            {
 202182                writer.WriteStartObject();
 183
 1256184                foreach (var entry in _entries)
 185                {
 426186                    writer.WritePropertyName(entry.Key);
 426187                    using var document = JsonDocument.Parse(entry.Value);
 426188                    document.RootElement.WriteTo(writer);
 189                }
 190
 202191                writer.WriteEndObject();
 202192            }
 193
 202194            return Encoding.UTF8.GetString(stream.ToArray());
 202195        }
 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
 230204        public JsonRecordReader(string json, JsonSerializerOptions options, ChronicleContext context)
 205        {
 230206            _document = JsonDocument.Parse(json);
 230207            _root = _document.RootElement;
 230208            _options = options;
 230209            Context = context;
 230210        }
 211
 212        public ChronicleContext Context { get; }
 213
 34214        public SerializationMode Mode => SerializationMode.Loading;
 215
 216        public void LookValue<T>(ref T value, string name, T? defaultValue = default)
 217        {
 415218            if (!_root.TryGetProperty(name, out JsonElement entry))
 219            {
 158220                value = defaultValue!;
 158221                return;
 222            }
 223
 257224            if (entry.ValueKind == JsonValueKind.Null)
 225            {
 1226                value = defaultValue!;
 1227                return;
 228            }
 229
 256230            T? loadedValue = JsonSerializer.Deserialize<T>(entry.GetRawText(), _options);
 256231            if (loadedValue is null)
 232            {
 1233                value = defaultValue!;
 1234                return;
 235            }
 236
 255237            value = loadedValue;
 255238        }
 239
 240        public void LookDeep<T>(ref T value, string name) where T : class, IRecordable
 241        {
 11242            if (!_root.TryGetProperty(name, out JsonElement entry) || entry.ValueKind == JsonValueKind.Null)
 2243                return;
 244
 9245            if (value == null)
 1246                throw new InvalidOperationException(
 1247                    $"Unable to load '{name}' because {typeof(T).Name} must already be instantiated for a deep chronicle
 248
 8249            using var nested = new JsonRecordReader(entry.GetRawText(), _options, Context);
 8250            value.RecordData(nested);
 16251        }
 252
 253        public void LookDeepStruct<T>(ref T value, string name) where T : struct, IRecordable
 254        {
 121255            if (!_root.TryGetProperty(name, out JsonElement entry) || entry.ValueKind == JsonValueKind.Null)
 256            {
 11257                value = CreateDefaultDeepStruct<T>();
 10258                return;
 259            }
 260
 110261            value = new();
 110262            using var nested = new JsonRecordReader(entry.GetRawText(), _options, Context);
 110263            value.RecordData(nested);
 208264        }
 265
 266        public void LookNullableDeep<T>(ref T? value, string name) where T : struct, IRecordable
 267        {
 13268            if (!_root.TryGetProperty(name, out JsonElement entry) || entry.ValueKind == JsonValueKind.Null)
 269            {
 4270                value = null;
 4271                return;
 272            }
 273
 9274            T nestedValue = new();
 9275            using var nested = new JsonRecordReader(entry.GetRawText(), _options, Context);
 9276            nestedValue.RecordData(nested);
 3277            value = nestedValue;
 6278        }
 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        {
 15287            if (!TryReadLinkId(name, out string? id))
 288            {
 6289                value = default!;
 6290                assignLoadedValue?.Invoke(value);
 6291                return;
 292            }
 293
 9294            if (resolveMode == RecordLinkResolveMode.Deferred)
 295            {
 5296                LoadDeferredLink(ref value, name, id, slot, assignLoadedValue);
 4297                return;
 298            }
 299
 4300            LoadImmediateLink(ref value, name, id, slot, assignLoadedValue);
 3301        }
 302
 303        private bool TryReadLinkId(string name, [NotNullWhen(true)] out string? id)
 304        {
 15305            if (!_root.TryGetProperty(name, out JsonElement entry)
 15306                || entry.ValueKind == JsonValueKind.Null)
 307            {
 6308                id = null;
 6309                return false;
 310            }
 311
 9312            id = JsonSerializer.Deserialize<string>(entry.GetRawText(), _options);
 9313            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        {
 5323            if (assignLoadedValue == null)
 1324                throw new InvalidOperationException(
 1325                    $"Deferred link '{name}' of type {typeof(T).Name} requires an assignment callback.");
 326
 4327            if (Context.Links.TryResolve(id, out T? deferredValue, slot))
 328            {
 1329                value = deferredValue!;
 1330                assignLoadedValue(deferredValue!);
 1331                return;
 332            }
 333
 3334            Context.QueueDeferredLink(name, id, slot, assignLoadedValue);
 3335            value = default!;
 3336        }
 337
 338        private void LoadImmediateLink<T>(
 339            ref T value,
 340            string name,
 341            string id,
 342            string? slot,
 343            Action<T>? assignLoadedValue)
 344        {
 4345            if (!Context.Links.TryResolve(id, out T? resolvedValue, slot))
 1346                throw new InvalidOperationException(
 1347                    $"Unable to load link '{name}' of type {typeof(T).Name} with id '{id}'{FormatSlot(slot)}.");
 348
 3349            value = resolvedValue!;
 3350            assignLoadedValue?.Invoke(resolvedValue!);
 3351        }
 352
 353        public void Dispose()
 354        {
 230355            _document.Dispose();
 230356        }
 357
 358        private T CreateDefaultDeepStruct<T>() where T : struct, IRecordable
 359        {
 11360            T defaultValue = new();
 11361            using var nested = new JsonRecordReader("{}", _options, Context);
 11362            defaultValue.RecordData(nested);
 10363            return defaultValue;
 10364        }
 365    }
 366
 367    private static string FormatSlot(string? slot)
 368    {
 3369        return string.IsNullOrEmpty(slot)
 3370            ? string.Empty
 3371            : $" in slot '{slot}'";
 372    }
 373}