-
Notifications
You must be signed in to change notification settings - Fork 152
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
Add NerdbankMessagePackFormatter #1100
Draft
trippwill
wants to merge
8
commits into
microsoft:main
Choose a base branch
from
trippwill:dev/trippwill/nbmp-formatter
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+2,774
−10
Draft
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
e934175
Update package versions and target frameworks
6819e6b
Continue implementing NerdbankMessagePackFormatter.
052592e
Refactor NerdbankMessagePackFormatter for converters
259558a
Add type converter registration methods to interface
e87da44
Enhance serialization context and type shape providers
ca439ea
Enhance NerdbankMessagePackFormatter with new methods
b12c357
Replaced the `IFormatterContextBuilder` interface with a concrete `Fo…
345a39c
Downgrade package versions for compatibility
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 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 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 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 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
104 changes: 104 additions & 0 deletions
104
src/StreamJsonRpc/NerdbankMessagePackFormatter.CommonString.cs
This file contains 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,104 @@ | ||
// Copyright (c) Microsoft Corporation. All rights reserved. | ||
// Licensed under the MIT license. See LICENSE file in the project root for full license information. | ||
|
||
using System.Diagnostics; | ||
using NBMP = Nerdbank.MessagePack; | ||
|
||
namespace StreamJsonRpc; | ||
|
||
public partial class NerdbankMessagePackFormatter | ||
{ | ||
[DebuggerDisplay("{" + nameof(Value) + "}")] | ||
private struct CommonString | ||
{ | ||
internal CommonString(string value) | ||
{ | ||
Requires.Argument(value.Length > 0 && value.Length <= 16, nameof(value), "Length must be >0 and <=16."); | ||
this.Value = value; | ||
ReadOnlyMemory<byte> encodedBytes = MessagePack.Internal.CodeGenHelpers.GetEncodedStringBytes(value); | ||
this.EncodedBytes = encodedBytes; | ||
|
||
ReadOnlySpan<byte> span = this.EncodedBytes.Span.Slice(1); | ||
this.Key = MessagePack.Internal.AutomataKeyGen.GetKey(ref span); // header is 1 byte because string length <= 16 | ||
this.Key2 = span.Length > 0 ? (ulong?)MessagePack.Internal.AutomataKeyGen.GetKey(ref span) : null; | ||
} | ||
|
||
/// <summary> | ||
/// Gets the original string. | ||
/// </summary> | ||
internal string Value { get; } | ||
|
||
/// <summary> | ||
/// Gets the 64-bit integer that represents the string without decoding it. | ||
/// </summary> | ||
private ulong Key { get; } | ||
|
||
/// <summary> | ||
/// Gets the next 64-bit integer that represents the string without decoding it. | ||
/// </summary> | ||
private ulong? Key2 { get; } | ||
|
||
/// <summary> | ||
/// Gets the messagepack header and UTF-8 bytes for this string. | ||
/// </summary> | ||
private ReadOnlyMemory<byte> EncodedBytes { get; } | ||
|
||
/// <summary> | ||
/// Writes out the messagepack binary for this common string, if it matches the given value. | ||
/// </summary> | ||
/// <param name="writer">The writer to use.</param> | ||
/// <param name="value">The value to be written, if it matches this <see cref="CommonString"/>.</param> | ||
/// <returns><see langword="true"/> if <paramref name="value"/> matches this <see cref="Value"/> and it was written; <see langword="false"/> otherwise.</returns> | ||
internal bool TryWrite(ref NBMP::MessagePackWriter writer, string value) | ||
{ | ||
if (value == this.Value) | ||
{ | ||
this.Write(ref writer); | ||
return true; | ||
} | ||
|
||
return false; | ||
} | ||
|
||
internal readonly void Write(ref NBMP::MessagePackWriter writer) => writer.WriteRaw(this.EncodedBytes.Span); | ||
|
||
/// <summary> | ||
/// Checks whether a span of UTF-8 bytes equal this common string. | ||
/// </summary> | ||
/// <param name="utf8String">The UTF-8 string.</param> | ||
/// <returns><see langword="true"/> if the UTF-8 bytes are the encoding of this common string; <see langword="false"/> otherwise.</returns> | ||
internal readonly bool TryRead(ReadOnlySpan<byte> utf8String) | ||
{ | ||
if (utf8String.Length != this.EncodedBytes.Length - 1) | ||
{ | ||
return false; | ||
} | ||
|
||
ulong key1 = MessagePack.Internal.AutomataKeyGen.GetKey(ref utf8String); | ||
if (key1 != this.Key) | ||
{ | ||
return false; | ||
} | ||
|
||
if (utf8String.Length > 0) | ||
{ | ||
if (!this.Key2.HasValue) | ||
{ | ||
return false; | ||
} | ||
|
||
ulong key2 = MessagePack.Internal.AutomataKeyGen.GetKey(ref utf8String); | ||
if (key2 != this.Key2.Value) | ||
{ | ||
return false; | ||
} | ||
} | ||
else if (this.Key2.HasValue) | ||
{ | ||
return false; | ||
} | ||
|
||
return true; | ||
} | ||
} | ||
} |
219 changes: 219 additions & 0 deletions
219
src/StreamJsonRpc/NerdbankMessagePackFormatter.ISerializationContextBuilder.cs
This file contains 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,219 @@ | ||
// Copyright (c) Microsoft Corporation. All rights reserved. | ||
// Licensed under the MIT license. See LICENSE file in the project root for full license information. | ||
|
||
using System.Collections.Immutable; | ||
using System.IO.Pipelines; | ||
using Nerdbank.MessagePack; | ||
using PolyType; | ||
using PolyType.Abstractions; | ||
using StreamJsonRpc.Reflection; | ||
|
||
namespace StreamJsonRpc; | ||
|
||
/// <summary> | ||
/// Serializes JSON-RPC messages using MessagePack (a fast, compact binary format). | ||
/// </summary> | ||
/// <remarks> | ||
/// The MessagePack implementation used here comes from https://github.com/AArnott/Nerdbank.MessagePack. | ||
/// </remarks> | ||
public sealed partial class NerdbankMessagePackFormatter | ||
{ | ||
/// <summary> | ||
/// Provides methods to build a serialization context for the <see cref="NerdbankMessagePackFormatter"/>. | ||
/// </summary> | ||
public class FormatterContextBuilder | ||
{ | ||
private readonly NerdbankMessagePackFormatter formatter; | ||
private readonly FormatterContext baseContext; | ||
|
||
private ImmutableArray<ITypeShapeProvider>.Builder? typeShapeProvidersBuilder = null; | ||
|
||
/// <summary> | ||
/// Initializes a new instance of the <see cref="FormatterContextBuilder"/> class. | ||
/// </summary> | ||
/// <param name="formatter">The formatter to use.</param> | ||
/// <param name="baseContext">The base context to build upon.</param> | ||
internal FormatterContextBuilder(NerdbankMessagePackFormatter formatter, FormatterContext baseContext) | ||
{ | ||
this.formatter = formatter; | ||
this.baseContext = baseContext; | ||
} | ||
|
||
/// <summary> | ||
/// Adds a type shape provider to the context. | ||
/// </summary> | ||
/// <param name="provider">The type shape provider to add.</param> | ||
public void AddTypeShapeProvider(ITypeShapeProvider provider) | ||
{ | ||
this.typeShapeProvidersBuilder ??= ImmutableArray.CreateBuilder<ITypeShapeProvider>(); | ||
this.typeShapeProvidersBuilder.Add(provider); | ||
} | ||
|
||
/// <summary> | ||
/// Registers an async enumerable type with the context. | ||
/// </summary> | ||
/// <typeparam name="TEnumerable">The type of the async enumerable.</typeparam> | ||
/// <typeparam name="TElement">The type of the elements in the async enumerable.</typeparam> | ||
public void RegisterAsyncEnumerableType<TEnumerable, TElement>() | ||
where TEnumerable : IAsyncEnumerable<TElement> | ||
{ | ||
MessagePackConverter<TEnumerable> converter = this.formatter.asyncEnumerableConverterResolver.GetConverter<TEnumerable>(); | ||
this.baseContext.Serializer.RegisterConverter(converter); | ||
} | ||
|
||
/// <summary> | ||
/// Registers a converter with the context. | ||
/// </summary> | ||
/// <typeparam name="T">The type the converter handles.</typeparam> | ||
/// <param name="converter">The converter to register.</param> | ||
public void RegisterConverter<T>(MessagePackConverter<T> converter) | ||
{ | ||
this.baseContext.Serializer.RegisterConverter(converter); | ||
} | ||
|
||
/// <summary> | ||
/// Registers known subtypes for a base type with the context. | ||
/// </summary> | ||
/// <typeparam name="TBase">The base type.</typeparam> | ||
/// <param name="mapping">The mapping of known subtypes.</param> | ||
public void RegisterKnownSubTypes<TBase>(KnownSubTypeMapping<TBase> mapping) | ||
{ | ||
this.baseContext.Serializer.RegisterKnownSubTypes(mapping); | ||
} | ||
|
||
/// <summary> | ||
/// Registers a progress type with the context. | ||
/// </summary> | ||
/// <typeparam name="TProgress">The type of the progress.</typeparam> | ||
/// <typeparam name="TReport">The type of the report.</typeparam> | ||
public void RegisterProgressType<TProgress, TReport>() | ||
where TProgress : IProgress<TReport> | ||
{ | ||
MessagePackConverter<TProgress> converter = this.formatter.progressConverterResolver.GetConverter<TProgress>(); | ||
this.baseContext.Serializer.RegisterConverter(converter); | ||
} | ||
|
||
/// <summary> | ||
/// Registers a duplex pipe type with the context. | ||
/// </summary> | ||
/// <typeparam name="TPipe">The type of the duplex pipe.</typeparam> | ||
public void RegisterDuplexPipeType<TPipe>() | ||
where TPipe : IDuplexPipe | ||
{ | ||
MessagePackConverter<TPipe> converter = this.formatter.pipeConverterResolver.GetConverter<TPipe>(); | ||
this.baseContext.Serializer.RegisterConverter(converter); | ||
} | ||
|
||
/// <summary> | ||
/// Registers a pipe reader type with the context. | ||
/// </summary> | ||
/// <typeparam name="TReader">The type of the pipe reader.</typeparam> | ||
public void RegisterPipeReaderType<TReader>() | ||
where TReader : PipeReader | ||
{ | ||
MessagePackConverter<TReader> converter = this.formatter.pipeConverterResolver.GetConverter<TReader>(); | ||
this.baseContext.Serializer.RegisterConverter(converter); | ||
} | ||
|
||
/// <summary> | ||
/// Registers a pipe writer type with the context. | ||
/// </summary> | ||
/// <typeparam name="TWriter">The type of the pipe writer.</typeparam> | ||
public void RegisterPipeWriterType<TWriter>() | ||
where TWriter : PipeWriter | ||
{ | ||
MessagePackConverter<TWriter> converter = this.formatter.pipeConverterResolver.GetConverter<TWriter>(); | ||
this.baseContext.Serializer.RegisterConverter(converter); | ||
} | ||
|
||
/// <summary> | ||
/// Registers a stream type with the context. | ||
/// </summary> | ||
/// <typeparam name="TStream">The type of the stream.</typeparam> | ||
public void RegisterStreamType<TStream>() | ||
where TStream : Stream | ||
{ | ||
MessagePackConverter<TStream> converter = this.formatter.pipeConverterResolver.GetConverter<TStream>(); | ||
this.baseContext.Serializer.RegisterConverter(converter); | ||
} | ||
|
||
/// <summary> | ||
/// Registers an exception type with the context. | ||
/// </summary> | ||
/// <typeparam name="TException">The type of the exception.</typeparam> | ||
public void RegisterExceptionType<TException>() | ||
where TException : Exception | ||
{ | ||
MessagePackConverter<TException> converter = this.formatter.exceptionResolver.GetConverter<TException>(); | ||
this.baseContext.Serializer.RegisterConverter(converter); | ||
} | ||
|
||
/// <summary> | ||
/// Registers an RPC marshalable type with the context. | ||
/// </summary> | ||
/// <typeparam name="T">The type to register.</typeparam> | ||
public void RegisterRpcMarshalableType<T>() | ||
where T : class | ||
{ | ||
if (MessageFormatterRpcMarshaledContextTracker.TryGetMarshalOptionsForType( | ||
typeof(T), | ||
out JsonRpcProxyOptions? proxyOptions, | ||
out JsonRpcTargetOptions? targetOptions, | ||
out RpcMarshalableAttribute? attribute)) | ||
{ | ||
var converter = (RpcMarshalableConverter<T>)Activator.CreateInstance( | ||
typeof(RpcMarshalableConverter<>).MakeGenericType(typeof(T)), | ||
this.formatter, | ||
proxyOptions, | ||
targetOptions, | ||
attribute)!; | ||
|
||
this.baseContext.Serializer.RegisterConverter(converter); | ||
} | ||
|
||
// TODO: Throw? | ||
} | ||
|
||
/// <summary> | ||
/// Builds the formatter context. | ||
/// </summary> | ||
/// <returns>The built formatter context.</returns> | ||
internal FormatterContext Build() | ||
{ | ||
if (this.typeShapeProvidersBuilder is null || this.typeShapeProvidersBuilder.Count < 1) | ||
{ | ||
return this.baseContext; | ||
} | ||
|
||
ITypeShapeProvider provider = this.typeShapeProvidersBuilder.Count == 1 | ||
? this.typeShapeProvidersBuilder[0] | ||
: new CompositeTypeShapeProvider(this.typeShapeProvidersBuilder.ToImmutable()); | ||
|
||
return new FormatterContext(this.baseContext.Serializer, provider); | ||
} | ||
} | ||
|
||
private class CompositeTypeShapeProvider : ITypeShapeProvider | ||
{ | ||
private readonly ImmutableArray<ITypeShapeProvider> providers; | ||
|
||
internal CompositeTypeShapeProvider(ImmutableArray<ITypeShapeProvider> providers) | ||
{ | ||
this.providers = providers; | ||
} | ||
|
||
public ITypeShape? GetShape(Type type) | ||
{ | ||
foreach (ITypeShapeProvider provider in this.providers) | ||
{ | ||
ITypeShape? shape = provider.GetShape(type); | ||
if (shape is not null) | ||
{ | ||
return shape; | ||
} | ||
} | ||
|
||
return null; | ||
} | ||
} | ||
} |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hopefully we can replace this with the API that fulfills AArnott/Nerdbank.MessagePack#183