| | | 1 | | using SwiftCollections; |
| | | 2 | | using System; |
| | | 3 | | using System.Collections.Generic; |
| | | 4 | | using System.IO; |
| | | 5 | | using System.Text; |
| | | 6 | | using System.Text.Json; |
| | | 7 | | |
| | | 8 | | namespace Chronicler; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// Serializes <see cref="IRecordable"/> state graphs to and from JSON through the chronicler API. |
| | | 12 | | /// </summary> |
| | | 13 | | public static class JsonRecordSerializer |
| | | 14 | | { |
| | 1 | 15 | | private static readonly JsonSerializerOptions _defaultOptions = CreateDefaultOptions(); |
| | | 16 | | |
| | | 17 | | /// <summary> |
| | | 18 | | /// Serializes the current state of a recordable instance into JSON. |
| | | 19 | | /// </summary> |
| | | 20 | | public static string Serialize(IRecordable target, bool writeIndented = false) |
| | 4 | 21 | | => Serialize(target, context: null, writeIndented); |
| | | 22 | | |
| | | 23 | | /// <summary> |
| | | 24 | | /// Serializes the current state of a recordable instance into JSON. |
| | | 25 | | /// </summary> |
| | | 26 | | public static string Serialize(IRecordable target, ChronicleContext? context, bool writeIndented = false) |
| | 27 | 27 | | { |
| | 27 | 28 | | if (target == null) |
| | 1 | 29 | | throw new ArgumentNullException(nameof(target)); |
| | | 30 | | |
| | 26 | 31 | | context ??= new ChronicleContext(); |
| | | 32 | | |
| | 26 | 33 | | JsonSerializerOptions options = writeIndented |
| | 26 | 34 | | ? CreateIndentedOptions() |
| | 26 | 35 | | : _defaultOptions; |
| | | 36 | | |
| | 26 | 37 | | var chronicler = new JsonRecordWriter(options, context); |
| | 26 | 38 | | target.RecordData(chronicler); |
| | 25 | 39 | | return chronicler.ToJson(); |
| | 25 | 40 | | } |
| | | 41 | | |
| | | 42 | | /// <summary> |
| | | 43 | | /// Loads JSON state into an existing recordable instance. |
| | | 44 | | /// </summary> |
| | | 45 | | public static void Populate(IRecordable target, string json) |
| | 6 | 46 | | => Populate(target, json, context: null); |
| | | 47 | | |
| | | 48 | | /// <summary> |
| | | 49 | | /// Loads JSON state into an existing recordable instance. |
| | | 50 | | /// </summary> |
| | | 51 | | public static void Populate(IRecordable target, string json, ChronicleContext? context) |
| | 27 | 52 | | { |
| | 27 | 53 | | if (target == null) |
| | 1 | 54 | | throw new ArgumentNullException(nameof(target)); |
| | 26 | 55 | | if (string.IsNullOrWhiteSpace(json)) |
| | 3 | 56 | | throw new ArgumentException("Serialized JSON must not be null or empty.", nameof(json)); |
| | | 57 | | |
| | 23 | 58 | | context ??= new ChronicleContext(); |
| | | 59 | | |
| | 23 | 60 | | using var chronicler = new JsonRecordReader(json, _defaultOptions, context); |
| | 23 | 61 | | target.RecordData(chronicler); |
| | 20 | 62 | | context.ResolveDeferredLinks(); |
| | 36 | 63 | | } |
| | | 64 | | |
| | | 65 | | private static JsonSerializerOptions CreateDefaultOptions() |
| | 1 | 66 | | { |
| | 1 | 67 | | return new JsonSerializerOptions() |
| | 1 | 68 | | { |
| | 1 | 69 | | IncludeFields = true |
| | 1 | 70 | | }; |
| | 1 | 71 | | } |
| | | 72 | | |
| | | 73 | | private static JsonSerializerOptions CreateIndentedOptions() |
| | 23 | 74 | | { |
| | 23 | 75 | | return new JsonSerializerOptions(_defaultOptions) |
| | 23 | 76 | | { |
| | 23 | 77 | | WriteIndented = true |
| | 23 | 78 | | }; |
| | 23 | 79 | | } |
| | | 80 | | |
| | | 81 | | private sealed class JsonRecordWriter : IChronicler |
| | | 82 | | { |
| | 41 | 83 | | private readonly SwiftDictionary<string, string> _entries = new(8, StringComparer.Ordinal); |
| | | 84 | | private readonly JsonSerializerOptions _options; |
| | | 85 | | |
| | 41 | 86 | | public JsonRecordWriter(JsonSerializerOptions options, ChronicleContext context) |
| | 41 | 87 | | { |
| | 41 | 88 | | _options = options; |
| | 41 | 89 | | Context = context ?? throw new ArgumentNullException(nameof(context)); |
| | 41 | 90 | | } |
| | | 91 | | |
| | 27 | 92 | | public ChronicleContext Context { get; } |
| | | 93 | | |
| | 16 | 94 | | public SerializationMode Mode => SerializationMode.Saving; |
| | | 95 | | |
| | | 96 | | public void LookValue<T>(ref T value, string name, T? defaultValue = default) |
| | 43 | 97 | | { |
| | 43 | 98 | | if (value is null || EqualityComparer<T>.Default.Equals(value, defaultValue!)) |
| | 9 | 99 | | return; |
| | | 100 | | |
| | 34 | 101 | | _entries[name] = JsonSerializer.Serialize(value, _options); |
| | 43 | 102 | | } |
| | | 103 | | |
| | | 104 | | public void LookDeep<T>(ref T value, string name) where T : class, IRecordable |
| | 10 | 105 | | { |
| | 10 | 106 | | if (value == null) |
| | 1 | 107 | | { |
| | 1 | 108 | | _entries[name] = "null"; |
| | 1 | 109 | | return; |
| | | 110 | | } |
| | | 111 | | |
| | 9 | 112 | | var nested = new JsonRecordWriter(_options, Context); |
| | 9 | 113 | | value.RecordData(nested); |
| | 9 | 114 | | _entries[name] = nested.ToJson(); |
| | 10 | 115 | | } |
| | | 116 | | |
| | | 117 | | public void LookDeepStruct<T>(ref T value, string name) where T : struct, IRecordable |
| | 4 | 118 | | { |
| | 4 | 119 | | var nested = new JsonRecordWriter(_options, Context); |
| | 4 | 120 | | value.RecordData(nested); |
| | 4 | 121 | | _entries[name] = nested.ToJson(); |
| | 4 | 122 | | } |
| | | 123 | | |
| | | 124 | | public void LookNullableDeep<T>(ref T? value, string name) where T : struct, IRecordable |
| | 4 | 125 | | { |
| | 4 | 126 | | if (!value.HasValue) |
| | 2 | 127 | | return; |
| | | 128 | | |
| | 2 | 129 | | T nestedValue = value.Value; |
| | 2 | 130 | | var nested = new JsonRecordWriter(_options, Context); |
| | 2 | 131 | | nestedValue.RecordData(nested); |
| | 2 | 132 | | _entries[name] = nested.ToJson(); |
| | 4 | 133 | | } |
| | | 134 | | |
| | | 135 | | public void LookLink<T>( |
| | | 136 | | ref T value, |
| | | 137 | | string name, |
| | | 138 | | string? slot = null, |
| | | 139 | | RecordLinkResolveMode resolveMode = RecordLinkResolveMode.Immediate, |
| | | 140 | | Action<T>? assignLoadedValue = null) |
| | 12 | 141 | | { |
| | 12 | 142 | | string? id = null; |
| | 12 | 143 | | if (value is not null |
| | 12 | 144 | | && !Context.Links.TryGetReferenceId(value, out id, slot)) |
| | 1 | 145 | | { |
| | 1 | 146 | | throw new InvalidOperationException( |
| | 1 | 147 | | $"Unable to save link '{name}' of type {typeof(T).Name} because no stable id could be produced{Forma |
| | | 148 | | } |
| | | 149 | | |
| | 11 | 150 | | _entries[name] = JsonSerializer.Serialize(id, _options); |
| | 11 | 151 | | } |
| | | 152 | | |
| | | 153 | | public string ToJson() |
| | 40 | 154 | | { |
| | 40 | 155 | | using var stream = new MemoryStream(); |
| | 40 | 156 | | using (var writer = new Utf8JsonWriter(stream, new JsonWriterOptions() { Indented = _options.WriteIndented } |
| | 40 | 157 | | { |
| | 40 | 158 | | writer.WriteStartObject(); |
| | | 159 | | |
| | 240 | 160 | | foreach (var entry in _entries) |
| | 60 | 161 | | { |
| | 60 | 162 | | writer.WritePropertyName(entry.Key); |
| | 60 | 163 | | using var document = JsonDocument.Parse(entry.Value); |
| | 60 | 164 | | document.RootElement.WriteTo(writer); |
| | 60 | 165 | | } |
| | | 166 | | |
| | 40 | 167 | | writer.WriteEndObject(); |
| | 40 | 168 | | } |
| | | 169 | | |
| | 40 | 170 | | return Encoding.UTF8.GetString(stream.ToArray()); |
| | 40 | 171 | | } |
| | | 172 | | } |
| | | 173 | | |
| | | 174 | | private sealed class JsonRecordReader : IChronicler, IDisposable |
| | | 175 | | { |
| | | 176 | | private readonly JsonDocument _document; |
| | | 177 | | private readonly JsonElement _root; |
| | | 178 | | private readonly JsonSerializerOptions _options; |
| | | 179 | | |
| | 38 | 180 | | public JsonRecordReader(string json, JsonSerializerOptions options, ChronicleContext context) |
| | 38 | 181 | | { |
| | 38 | 182 | | _document = JsonDocument.Parse(json); |
| | 38 | 183 | | _root = _document.RootElement; |
| | 38 | 184 | | _options = options; |
| | 38 | 185 | | Context = context ?? throw new ArgumentNullException(nameof(context)); |
| | 38 | 186 | | } |
| | | 187 | | |
| | 26 | 188 | | public ChronicleContext Context { get; } |
| | | 189 | | |
| | 12 | 190 | | public SerializationMode Mode => SerializationMode.Loading; |
| | | 191 | | |
| | | 192 | | public void LookValue<T>(ref T value, string name, T? defaultValue = default) |
| | 40 | 193 | | { |
| | 40 | 194 | | if (!_root.TryGetProperty(name, out JsonElement entry)) |
| | 20 | 195 | | { |
| | 20 | 196 | | value = defaultValue!; |
| | 20 | 197 | | return; |
| | | 198 | | } |
| | | 199 | | |
| | 20 | 200 | | if (entry.ValueKind == JsonValueKind.Null) |
| | 1 | 201 | | { |
| | 1 | 202 | | value = defaultValue!; |
| | 1 | 203 | | return; |
| | | 204 | | } |
| | | 205 | | |
| | 19 | 206 | | T? loadedValue = JsonSerializer.Deserialize<T>(entry.GetRawText(), _options); |
| | 19 | 207 | | if (loadedValue is null) |
| | 1 | 208 | | { |
| | 1 | 209 | | value = defaultValue!; |
| | 1 | 210 | | return; |
| | | 211 | | } |
| | | 212 | | |
| | 18 | 213 | | value = loadedValue; |
| | 40 | 214 | | } |
| | | 215 | | |
| | | 216 | | public void LookDeep<T>(ref T value, string name) where T : class, IRecordable |
| | 9 | 217 | | { |
| | 9 | 218 | | if (!_root.TryGetProperty(name, out JsonElement entry) || entry.ValueKind == JsonValueKind.Null) |
| | 2 | 219 | | return; |
| | | 220 | | |
| | 7 | 221 | | if (value == null) |
| | 1 | 222 | | throw new InvalidOperationException( |
| | 1 | 223 | | $"Unable to load '{name}' because {typeof(T).Name} must already be instantiated for a deep chronicle |
| | | 224 | | |
| | 6 | 225 | | using var nested = new JsonRecordReader(entry.GetRawText(), _options, Context); |
| | 6 | 226 | | value.RecordData(nested); |
| | 14 | 227 | | } |
| | | 228 | | |
| | | 229 | | public void LookDeepStruct<T>(ref T value, string name) where T : struct, IRecordable |
| | 4 | 230 | | { |
| | 4 | 231 | | value = CreateDefaultDeepStruct<T>(); |
| | | 232 | | |
| | 4 | 233 | | if (!_root.TryGetProperty(name, out JsonElement entry) || entry.ValueKind == JsonValueKind.Null) |
| | 1 | 234 | | return; |
| | | 235 | | |
| | 3 | 236 | | using var nested = new JsonRecordReader(entry.GetRawText(), _options, Context); |
| | 3 | 237 | | value.RecordData(nested); |
| | 7 | 238 | | } |
| | | 239 | | |
| | | 240 | | public void LookNullableDeep<T>(ref T? value, string name) where T : struct, IRecordable |
| | 4 | 241 | | { |
| | 4 | 242 | | if (!_root.TryGetProperty(name, out JsonElement entry) || entry.ValueKind == JsonValueKind.Null) |
| | 3 | 243 | | { |
| | 3 | 244 | | value = null; |
| | 3 | 245 | | return; |
| | | 246 | | } |
| | | 247 | | |
| | 1 | 248 | | T nestedValue = CreateDefaultDeepStruct<T>(); |
| | 1 | 249 | | using var nested = new JsonRecordReader(entry.GetRawText(), _options, Context); |
| | 1 | 250 | | nestedValue.RecordData(nested); |
| | 1 | 251 | | value = nestedValue; |
| | 5 | 252 | | } |
| | | 253 | | |
| | | 254 | | public void LookLink<T>( |
| | | 255 | | ref T value, |
| | | 256 | | string name, |
| | | 257 | | string? slot = null, |
| | | 258 | | RecordLinkResolveMode resolveMode = RecordLinkResolveMode.Immediate, |
| | | 259 | | Action<T>? assignLoadedValue = null) |
| | 10 | 260 | | { |
| | 10 | 261 | | if (!_root.TryGetProperty(name, out JsonElement entry) |
| | 10 | 262 | | || entry.ValueKind == JsonValueKind.Null) |
| | 2 | 263 | | { |
| | 2 | 264 | | value = default!; |
| | 2 | 265 | | return; |
| | | 266 | | } |
| | | 267 | | |
| | 8 | 268 | | string id = JsonSerializer.Deserialize<string>(entry.GetRawText(), _options)!; |
| | | 269 | | |
| | 8 | 270 | | if (resolveMode == RecordLinkResolveMode.Deferred) |
| | 5 | 271 | | { |
| | 5 | 272 | | if (assignLoadedValue == null) |
| | 1 | 273 | | throw new InvalidOperationException( |
| | 1 | 274 | | $"Deferred link '{name}' of type {typeof(T).Name} requires an assignment callback."); |
| | | 275 | | |
| | | 276 | | T? deferredValue; |
| | 4 | 277 | | if (Context.Links.TryResolve(id, out deferredValue, slot)) |
| | 1 | 278 | | { |
| | 1 | 279 | | value = deferredValue!; |
| | 1 | 280 | | assignLoadedValue(deferredValue!); |
| | 1 | 281 | | return; |
| | | 282 | | } |
| | | 283 | | |
| | 3 | 284 | | Context.QueueDeferredLink(name, id, slot, assignLoadedValue); |
| | 3 | 285 | | value = default!; |
| | 3 | 286 | | return; |
| | | 287 | | } |
| | | 288 | | |
| | | 289 | | T? resolvedValue; |
| | 3 | 290 | | if (!Context.Links.TryResolve(id, out resolvedValue, slot)) |
| | 1 | 291 | | { |
| | 1 | 292 | | throw new InvalidOperationException( |
| | 1 | 293 | | $"Unable to load link '{name}' of type {typeof(T).Name} with id '{id}'{FormatSlot(slot)}."); |
| | | 294 | | } |
| | | 295 | | |
| | 2 | 296 | | value = resolvedValue!; |
| | 2 | 297 | | assignLoadedValue?.Invoke(resolvedValue!); |
| | 8 | 298 | | } |
| | | 299 | | |
| | | 300 | | public void Dispose() |
| | 38 | 301 | | { |
| | 38 | 302 | | _document.Dispose(); |
| | 38 | 303 | | } |
| | | 304 | | |
| | | 305 | | private T CreateDefaultDeepStruct<T>() where T : struct, IRecordable |
| | 5 | 306 | | { |
| | 5 | 307 | | T defaultValue = new(); |
| | 5 | 308 | | using var nested = new JsonRecordReader("{}", _options, Context); |
| | 5 | 309 | | defaultValue.RecordData(nested); |
| | 5 | 310 | | return defaultValue; |
| | 5 | 311 | | } |
| | | 312 | | } |
| | | 313 | | |
| | | 314 | | private static string FormatSlot(string? slot) |
| | 2 | 315 | | { |
| | 2 | 316 | | return string.IsNullOrEmpty(slot) |
| | 2 | 317 | | ? string.Empty |
| | 2 | 318 | | : $" in slot '{slot}'"; |
| | 2 | 319 | | } |
| | | 320 | | } |