< Summary

Information
Class: Chronicler.Serialization.SerializationPayloadEditor
Assembly: Chronicler
File(s): /home/runner/work/Chronicler/Chronicler/src/Chronicler/Serialization/SerializationPayloadEditor.cs
Line coverage
100%
Covered lines: 60
Uncovered lines: 0
Coverable lines: 60
Total lines: 189
Line coverage: 100%
Branch coverage
100%
Covered branches: 38
Total branches: 38
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%
RemoveJsonProperty(...)100%44100%
SetJsonValue(...)100%44100%
ParseJsonRoot(...)100%44100%
GetJsonParent(...)100%44100%
RemoveMemoryPackEntry(...)100%44100%
SetMemoryPackValue(...)100%44100%
ReadEnvelope(...)100%22100%
RemoveMemoryPackEntry(...)100%66100%
SetMemoryPackValue(...)100%66100%

File(s)

/home/runner/work/Chronicler/Chronicler/src/Chronicler/Serialization/SerializationPayloadEditor.cs

#LineLine coverage
 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
 9using MemoryPack;
 10#endif
 11using System;
 12using System.Text.Json;
 13using System.Text.Json.Nodes;
 14
 15namespace 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>
 26public static class SerializationPayloadEditor
 27{
 28    #region JSON Editing
 29
 130    private static readonly JsonSerializerOptions JsonOptions = new()
 131    {
 132        IncludeFields = true
 133    };
 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    {
 4144        if (path == null || path.Length == 0)
 245            throw new ArgumentException("A JSON property path is required.", nameof(path));
 46
 3947        JsonObject root = ParseJsonRoot(json);
 3848        JsonObject parent = GetJsonParent(root, path);
 3849        parent.Remove(path[^1]);
 3850        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    {
 2464        if (path == null || path.Length == 0)
 265            throw new ArgumentException("A JSON property path is required.", nameof(path));
 66
 2267        JsonObject root = ParseJsonRoot(json);
 2168        JsonObject parent = GetJsonParent(root, path);
 2069        parent[path[^1]] = JsonSerializer.SerializeToNode(value, JsonOptions);
 2070        return root.ToJsonString(JsonOptions);
 71    }
 72
 73    private static JsonObject ParseJsonRoot(string json)
 74    {
 6175        JsonNode rootNode = JsonNode.Parse(json)
 6176            ?? throw new InvalidOperationException("Unable to parse JSON payload.");
 6077        return rootNode as JsonObject
 6078            ?? throw new InvalidOperationException("Expected JSON root object.");
 79    }
 80
 81    private static JsonObject GetJsonParent(JsonObject root, string[] path)
 82    {
 5983        JsonObject current = root;
 20684        for (int i = 0; i < path.Length - 1; i++)
 85        {
 4586            current = current[path[i]] as JsonObject
 4587                ?? throw new InvalidOperationException(
 4588                    $"Expected JSON object at path segment '{path[i]}'.");
 89        }
 90
 5891        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    {
 42109        if (path == null || path.Length == 0)
 2110            throw new ArgumentException("A MemoryPack entry path is required.", nameof(path));
 111
 40112        MemoryPackRecordEnvelope envelope = ReadEnvelope(data);
 40113        RemoveMemoryPackEntry(envelope, path, 0);
 39114        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    {
 24128        if (path == null || path.Length == 0)
 2129            throw new ArgumentException("A MemoryPack entry path is required.", nameof(path));
 130
 22131        MemoryPackRecordEnvelope envelope = ReadEnvelope(data);
 22132        SetMemoryPackValue(envelope, path, 0, MemoryPackSerializer.Serialize(value));
 21133        return MemoryPackSerializer.Serialize(envelope);
 134    }
 135
 136    private static MemoryPackRecordEnvelope ReadEnvelope(byte[] data)
 137    {
 106138        return MemoryPackRecordEnvelope.Deserialize(data)
 106139            ?? new MemoryPackRecordEnvelope();
 140    }
 141
 142    private static void RemoveMemoryPackEntry(MemoryPackRecordEnvelope envelope, string[] path, int depth)
 143    {
 65144        if (depth == path.Length - 1)
 145        {
 39146            envelope.RemoveEntry(path[depth]);
 39147            return;
 148        }
 149
 26150        if (!envelope.TryGetEntry(path[depth], out byte[]? nestedData)
 26151            || nestedData == null)
 152        {
 1153            throw new InvalidOperationException(
 1154                $"Unable to locate MemoryPack entry '{path[depth]}' at depth {depth}.");
 155        }
 156
 25157        MemoryPackRecordEnvelope nestedEnvelope = ReadEnvelope(nestedData);
 25158        RemoveMemoryPackEntry(nestedEnvelope, path, depth + 1);
 25159        envelope.SetEntry(path[depth], MemoryPackSerializer.Serialize(nestedEnvelope));
 25160    }
 161
 162    private static void SetMemoryPackValue(
 163        MemoryPackRecordEnvelope envelope,
 164        string[] path,
 165        int depth,
 166        byte[] serializedValue)
 167    {
 41168        if (depth == path.Length - 1)
 169        {
 21170            envelope.SetEntry(path[depth], serializedValue);
 21171            return;
 172        }
 173
 20174        if (!envelope.TryGetEntry(path[depth], out byte[]? nestedData)
 20175            || nestedData == null)
 176        {
 1177            throw new InvalidOperationException(
 1178                $"Unable to locate MemoryPack entry '{path[depth]}' at depth {depth}.");
 179        }
 180
 19181        MemoryPackRecordEnvelope nestedEnvelope = ReadEnvelope(nestedData);
 19182        SetMemoryPackValue(nestedEnvelope, path, depth + 1, serializedValue);
 19183        envelope.SetEntry(path[depth], MemoryPackSerializer.Serialize(nestedEnvelope));
 19184    }
 185
 186    #endregion
 187
 188#endif
 189}