-
Notifications
You must be signed in to change notification settings - Fork 3
Tolerate unknown IChange $type via PeekThenConcreteChangeConverter #80
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
8277851
Add AGENTS.md and gitignore local agent skill files.
hahn-kev 1e7c02f
Add OpaqueChange and drop JsonPolymorphic from IChange.
hahn-kev 2d008f7
Wire PeekThenConcreteChangeConverter for unknown $type tolerance.
hahn-kev 1503b33
Build change discriminator map fully before publishing field.
hahn-kev 77f7110
Revert "Add AGENTS.md and gitignore local agent skill files."
hahn-kev 1b398e8
use name of instead of hard coding the string name
hahn-kev 5f0a869
Refine unknown change handling and initialization.
hahn-kev File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| using System.Text.Json; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using SIL.Harmony.Changes; | ||
| using SIL.Harmony.Sample; | ||
| using SIL.Harmony.Sample.Changes; | ||
|
|
||
| namespace SIL.Harmony.Tests; | ||
|
|
||
| public class ChangeConverterTests | ||
| { | ||
| private static JsonSerializerOptions SampleOptions() => | ||
| new ServiceCollection() | ||
| .AddCrdtDataSample(":memory:") | ||
| .BuildServiceProvider() | ||
| .GetRequiredService<JsonSerializerOptions>(); | ||
|
|
||
| [Fact] | ||
| public void Happy_path_deserializes_to_concrete_change() | ||
| { | ||
| var options = SampleOptions(); | ||
| var entityId = Guid.Parse("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"); | ||
| IChange change = new SetWordTextChange(entityId, "hello"); | ||
|
|
||
| var json = JsonSerializer.Serialize(change, options); | ||
| var roundTripped = JsonSerializer.Deserialize<IChange>(json, options); | ||
|
|
||
| roundTripped.Should().BeOfType<SetWordTextChange>() | ||
| .Which.Text.Should().Be("hello"); | ||
| roundTripped!.EntityId.Should().Be(entityId); | ||
| json.Should().StartWith("{\"$type\":\"SetWordTextChange\""); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void Unknown_type_deserializes_to_OpaqueChange() | ||
| { | ||
| var options = SampleOptions(); | ||
| var json = """ | ||
| {"$type":"SetWordPriorityChange","EntityId":"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee","Priority":7} | ||
| """; | ||
|
|
||
| var change = JsonSerializer.Deserialize<IChange>(json, options); | ||
|
|
||
| var opaque = change.Should().BeOfType<OpaqueChange>().Subject; | ||
| opaque.TypeName.Should().Be("SetWordPriorityChange"); | ||
| opaque.RawJson.GetProperty("Priority").GetInt32().Should().Be(7); | ||
| opaque.SupportsNewEntity().Should().BeFalse(); | ||
| opaque.SupportsApplyChange().Should().BeFalse(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void OpaqueChange_round_trips_original_discriminator() | ||
| { | ||
| var options = SampleOptions(); | ||
| var json = """ | ||
| {"$type":"SetWordPriorityChange","EntityId":"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee","Priority":7} | ||
| """; | ||
|
|
||
| var change = JsonSerializer.Deserialize<IChange>(json, options)!; | ||
| var rewritten = JsonSerializer.Serialize(change, options); | ||
|
|
||
| rewritten.Should().Contain("\"$type\":\"SetWordPriorityChange\""); | ||
| rewritten.Should().Contain("\"Priority\":7"); | ||
| rewritten.Should().NotContain("OpaqueChange"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void Mixed_commit_round_trips_known_and_opaque_changes() | ||
| { | ||
| var options = SampleOptions(); | ||
| var entityId = Guid.Parse("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"); | ||
| var commit = new Commit | ||
| { | ||
| ClientId = Guid.NewGuid(), | ||
| HybridDateTime = new HybridDateTime(DateTimeOffset.UtcNow, 0), | ||
| }; | ||
| commit.ChangeEntities.Add(new ChangeEntity<IChange> | ||
| { | ||
| Index = 0, | ||
| CommitId = commit.Id, | ||
| EntityId = entityId, | ||
| Change = new SetWordTextChange(entityId, "hello") | ||
| }); | ||
|
|
||
| var json = JsonSerializer.Serialize(commit, options); | ||
| // Inject an unknown change as if from a newer client. | ||
| json = json.Replace( | ||
| "\"ChangeEntities\":[", | ||
| """ | ||
| "ChangeEntities":[{"Index":1,"CommitId":"00000000-0000-0000-0000-000000000000","EntityId":"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee","Change":{"$type":"SetWordPriorityChange","Priority":3}}, | ||
| """); | ||
|
|
||
| var roundTripped = JsonSerializer.Deserialize<Commit>(json, options)!; | ||
| roundTripped.ChangeEntities.Should().HaveCount(2); | ||
| roundTripped.ChangeEntities.Select(c => c.Change.GetType()) | ||
| .Should().BeEquivalentTo([typeof(OpaqueChange), typeof(SetWordTextChange)]); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void Requires_type_as_first_property() | ||
| { | ||
| var options = SampleOptions(); | ||
| var json = """ | ||
| {"Text":"hello","EntityId":"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee","$type":"SetWordTextChange"} | ||
| """; | ||
|
|
||
| var act = () => JsonSerializer.Deserialize<IChange>(json, options); | ||
| act.Should().Throw<JsonException>().WithMessage("*first property*"); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| using System.Text.Json; | ||
|
|
||
| namespace SIL.Harmony.Changes; | ||
|
|
||
| /// <summary> | ||
| /// An <see cref="IChange"/> whose <c>$type</c> was not registered on this client. | ||
| /// Preserves the original JSON so it can round-trip and be applied once the type is known. | ||
| /// </summary> | ||
| public sealed class OpaqueChange : IChange | ||
| { | ||
| public required string TypeName { get; init; } | ||
| public required JsonElement RawJson { get; init; } | ||
|
|
||
| public Guid EntityId { get; set; } | ||
|
|
||
| public Type EntityType => | ||
| throw new NotSupportedException($"Opaque change '{TypeName}' has no known entity type."); | ||
|
|
||
| public ValueTask ApplyChange(IObjectBase entity, IChangeContext context) => default; | ||
|
|
||
| public ValueTask<IObjectBase> NewEntity(Commit commit, IChangeContext context) => | ||
| throw new NotSupportedException( | ||
| $"Opaque change '{TypeName}' cannot create entities on this client. CommitId: {commit.Id}, EntityId: {EntityId}"); | ||
|
|
||
| public bool SupportsApplyChange() => false; | ||
| public bool SupportsNewEntity() => false; | ||
| } |
122 changes: 122 additions & 0 deletions
122
src/SIL.Harmony/Changes/PeekThenConcreteChangeConverter.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,122 @@ | ||
| using System.Text; | ||
| using System.Text.Json; | ||
| using System.Text.Json.Serialization; | ||
| using System.Text.Json.Serialization.Metadata; | ||
|
|
||
| namespace SIL.Harmony.Changes; | ||
|
|
||
| /// <summary> | ||
| /// Owns <see cref="IChange"/> discrimination. Requires <c>$type</c> as the first JSON property | ||
| /// (matching synthetic write order from <see cref="CrdtConfig"/>). | ||
| /// Known discriminators deserialize via cached concrete <see cref="JsonTypeInfo"/>; | ||
| /// unknown → <see cref="OpaqueChange"/> preserving the raw payload. | ||
| /// </summary> | ||
| internal sealed class PeekThenConcreteChangeConverter : JsonConverter<IChange> | ||
| { | ||
| private readonly KnownType[] _known; | ||
| private readonly byte[] _discriminatorPropertyUtf8; | ||
|
|
||
| public PeekThenConcreteChangeConverter(IReadOnlyDictionary<string, Type> known) | ||
| { | ||
| _discriminatorPropertyUtf8 = Encoding.UTF8.GetBytes(CrdtConstants.ChangeDiscriminatorProperty); | ||
| _known = known.Select(kv => new KnownType(Encoding.UTF8.GetBytes(kv.Key), kv.Value)).ToArray(); | ||
| } | ||
|
|
||
| public override IChange Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | ||
| { | ||
| if (reader.TokenType != JsonTokenType.StartObject) | ||
| throw new JsonException("Expected StartObject"); | ||
|
|
||
| // Checkpoint: restore for full-object deserialize / opaque capture after peeking $type. | ||
| var checkpoint = reader; | ||
|
|
||
| if (!reader.Read() || reader.TokenType != JsonTokenType.PropertyName) | ||
| throw new JsonException("Expected property name"); | ||
|
|
||
| if (!reader.ValueTextEquals(_discriminatorPropertyUtf8)) | ||
| throw new JsonException( | ||
| $"IChange requires \"{CrdtConstants.ChangeDiscriminatorProperty}\" as the first property"); | ||
|
|
||
| if (!reader.Read() || reader.TokenType != JsonTokenType.String) | ||
| throw new JsonException($"Expected string {CrdtConstants.ChangeDiscriminatorProperty} discriminator"); | ||
|
|
||
| if (!TryFindKnown(ref reader, out var knownIndex, out var unknownTypeName)) | ||
| { | ||
| reader = checkpoint; | ||
| return ReadOpaque(ref reader, unknownTypeName!); | ||
| } | ||
|
|
||
| ref var known = ref _known[knownIndex]; | ||
| var typeInfo = known.EnsureTypeInfo(options); | ||
|
|
||
| // Real change types use parameterized constructors / get-only props — let STJ materialize. | ||
| reader = checkpoint; | ||
| return (IChange)(JsonSerializer.Deserialize(ref reader, typeInfo) | ||
| ?? throw new JsonException($"null {known.ClrType.Name}")); | ||
| } | ||
|
|
||
| public override void Write(Utf8JsonWriter writer, IChange value, JsonSerializerOptions options) | ||
| { | ||
| if (value is OpaqueChange opaque) | ||
| { | ||
| opaque.RawJson.WriteTo(writer); | ||
| return; | ||
| } | ||
|
|
||
| // Concrete runtime type: synthetic $type comes from JsonTypeInfo modifier. | ||
| JsonSerializer.Serialize(writer, value, value.GetType(), options); | ||
| } | ||
|
|
||
| private static OpaqueChange ReadOpaque(ref Utf8JsonReader reader, string typeName) | ||
| { | ||
| using var doc = JsonDocument.ParseValue(ref reader); | ||
| var element = doc.RootElement.Clone(); | ||
| return new OpaqueChange | ||
| { | ||
| TypeName = typeName, | ||
| EntityId = element.TryGetProperty(nameof(IChange.EntityId), out var id) && id.ValueKind == JsonValueKind.String | ||
| ? id.GetGuid() | ||
| : default, | ||
| RawJson = element | ||
| }; | ||
| } | ||
|
|
||
| private bool TryFindKnown(ref Utf8JsonReader reader, out int index, out string? unknownTypeName) | ||
| { | ||
| for (var i = 0; i < _known.Length; i++) | ||
| { | ||
| if (reader.ValueTextEquals(_known[i].Utf8Discriminator)) | ||
| { | ||
| index = i; | ||
| unknownTypeName = null; | ||
| return true; | ||
| } | ||
| } | ||
|
|
||
| index = -1; | ||
| unknownTypeName = reader.GetString(); | ||
| return false; | ||
| } | ||
|
|
||
| private struct KnownType | ||
| { | ||
| public KnownType(byte[] utf8Discriminator, Type clrType) | ||
| { | ||
| Utf8Discriminator = utf8Discriminator; | ||
| ClrType = clrType; | ||
| } | ||
|
|
||
| public byte[] Utf8Discriminator { get; } | ||
| public Type ClrType { get; } | ||
| private JsonTypeInfo? _typeInfo; | ||
|
|
||
| public JsonTypeInfo EnsureTypeInfo(JsonSerializerOptions options) | ||
| { | ||
| if (_typeInfo is not null && ReferenceEquals(_typeInfo.Options, options)) | ||
| return _typeInfo; | ||
|
|
||
| _typeInfo = options.GetTypeInfo(ClrType); | ||
| return _typeInfo; | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.