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