Skip to content

Add gRPC JSON transcoding option to remove enum prefix #62873

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 1 commit into from
Jul 29, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,42 @@ public sealed class GrpcJsonSettings
/// </para>
/// </remarks>
public bool PropertyNameCaseInsensitive { get; set; }

/// <summary>
/// Gets or sets a value indicating whether the enum type name prefix should be removed when reading and writing enum values.
/// The default value is <see langword="false"/>.
/// </summary>
/// <remarks>
/// <para>
/// In Protocol Buffers, enum value names are globally scoped, so they are often prefixed with the enum type name
/// to avoid name collisions. For example, the <c>Status</c> enum might define values like <c>STATUS_UNKNOWN</c>
/// and <c>STATUS_OK</c>.
/// </para>
/// <code>
/// enum Status {
/// STATUS_UNKNOWN = 0;
/// STATUS_OK = 1;
/// }
/// </code>
/// <para>
/// When <see cref="RemoveEnumPrefix"/> is set to <see langword="true"/>:
/// </para>
/// <list type="bullet">
/// <item>
/// <description>The <c>STATUS</c> prefix is removed from enum values. The enum values above will be read and written as <c>UNKNOWN</c> and <c>OK</c> instead of <c>STATUS_UNKNOWN</c> and <c>STATUS_OK</c>.</description>
/// </item>
/// <item>
/// <description>Original prefixed values are used as a fallback when reading JSON. For example, <c>STATUS_OK</c> and <c>OK</c> map to the <c>STATUS_OK</c> enum value.</description>
/// </item>
/// </list>
/// <para>
/// The Protobuf JSON specification requires enum values in JSON to match enum fields exactly.
/// Enabling this option may reduce interoperability, as removing enum prefix might not be supported
/// by other JSON transcoding implementations.
/// </para>
/// <para>
/// For more information, see <see href="https://protobuf.dev/programming-guides/json/"/>.
/// </para>
/// </remarks>
public bool RemoveEnumPrefix { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
using System.Runtime.CompilerServices;
using System.Text.Json;
using Google.Protobuf.Reflection;
using Grpc.Shared;
using Type = System.Type;

namespace Microsoft.AspNetCore.Grpc.JsonTranscoding.Internal.Json;
Expand All @@ -21,18 +20,12 @@ public EnumConverter(JsonContext context) : base(context)
switch (reader.TokenType)
{
case JsonTokenType.String:
var enumDescriptor = (EnumDescriptor?)Context.DescriptorRegistry.FindDescriptorByType(typeToConvert);
if (enumDescriptor == null)
{
throw new InvalidOperationException($"Unable to resolve descriptor for {typeToConvert}.");
}
var enumDescriptor = (EnumDescriptor?)Context.DescriptorRegistry.FindDescriptorByType(typeToConvert)
?? throw new InvalidOperationException($"Unable to resolve descriptor for {typeToConvert}.");

var value = reader.GetString()!;
var valueDescriptor = enumDescriptor.FindValueByName(value);
if (valueDescriptor == null)
{
throw new InvalidOperationException(@$"Error converting value ""{value}"" to enum type {typeToConvert}.");
}
var valueDescriptor = JsonNamingHelpers.GetEnumFieldReadValue(enumDescriptor, value, Context.Settings)
?? throw new InvalidOperationException(@$"Error converting value ""{value}"" to enum type {typeToConvert}.");

return ConvertFromInteger(valueDescriptor.Number);
case JsonTokenType.Number:
Expand All @@ -52,7 +45,10 @@ public override void Write(Utf8JsonWriter writer, TEnum value, JsonSerializerOpt
}
else
{
var name = Legacy.OriginalEnumValueHelper.GetOriginalName(value);
var enumDescriptor = (EnumDescriptor?)Context.DescriptorRegistry.FindDescriptorByType(value.GetType())
?? throw new InvalidOperationException($"Unable to resolve descriptor for {value.GetType()}.");

var name = JsonNamingHelpers.GetEnumFieldWriteName(enumDescriptor, value, Context.Settings);
if (name != null)
{
writer.WriteStringValue(name);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.Concurrent;
using System.Linq;
using System.Reflection;
using Google.Protobuf.Reflection;

namespace Microsoft.AspNetCore.Grpc.JsonTranscoding.Internal.Json;

internal static class JsonNamingHelpers
{
private static readonly ConcurrentDictionary<Type, EnumMapping> _enumMappings = new ConcurrentDictionary<Type, EnumMapping>();

internal static EnumValueDescriptor? GetEnumFieldReadValue(EnumDescriptor enumDescriptor, string value, GrpcJsonSettings settings)
{
string resolvedName;
if (settings.RemoveEnumPrefix)
{
var nameMapping = GetEnumMapping(enumDescriptor);
if (!nameMapping.RemoveEnumPrefixMapping.TryGetValue(value, out var n))
{
return null;
}

resolvedName = n;
}
else
{
resolvedName = value;
}

return enumDescriptor.FindValueByName(resolvedName);
}

internal static string? GetEnumFieldWriteName(EnumDescriptor enumDescriptor, object value, GrpcJsonSettings settings)
{
var enumMapping = GetEnumMapping(enumDescriptor);

// If this returns false, name will be null, which is what we want.
if (!enumMapping.WriteMapping.TryGetValue(value, out var mapping))
{
return null;
}

return settings.RemoveEnumPrefix ? mapping.RemoveEnumPrefixName : mapping.OriginalName;
}

private static EnumMapping GetEnumMapping(EnumDescriptor enumDescriptor)
{
return _enumMappings.GetOrAdd(
enumDescriptor.ClrType,
static (t, descriptor) => GetEnumMapping(descriptor.Name, t),
enumDescriptor);
}

private static EnumMapping GetEnumMapping(string enumName, Type enumType)
{
var nameMappings = enumType.GetTypeInfo().DeclaredFields
.Where(f => f.IsStatic)
.Where(f => f.GetCustomAttributes<OriginalNameAttribute>().FirstOrDefault()?.PreferredAlias ?? true)
.Select(f =>
{
// If the attribute hasn't been applied, fall back to the name of the field.
var fieldName = f.GetCustomAttributes<OriginalNameAttribute>().FirstOrDefault()?.Name ?? f.Name;

return new NameMapping
{
Value = f.GetValue(null)!,
OriginalName = fieldName,
RemoveEnumPrefixName = GetEnumValueName(enumName, fieldName)
};
})
.ToList();

var writeMapping = nameMappings.ToDictionary(m => m.Value, m => m);

// Add original names as fallback when mapping enum values with removed prefixes.
// There are added to the dictionary first so they are overridden by the mappings with removed prefixes.
var removeEnumPrefixMapping = nameMappings.ToDictionary(m => m.OriginalName, m => m.OriginalName);

// Protobuf codegen prevents collision of enum names when the prefix is removed.
// For example, the following enum will fail to build because both fields would resolve to "OK":
//
// enum Status {
// STATUS_OK = 0;
// OK = 1;
// }
//
// Tooling error message:
// ----------------------
// Enum name OK has the same name as STATUS_OK if you ignore case and strip out the enum name prefix (if any).
// (If you are using allow_alias, please assign the same number to each enum value name.)
//
// Just in case it does happen, map to the first value rather than error.
foreach (var item in nameMappings.GroupBy(m => m.RemoveEnumPrefixName).Select(g => KeyValuePair.Create(g.Key, g.First().OriginalName)))
{
removeEnumPrefixMapping[item.Key] = item.Value;
}

return new EnumMapping { WriteMapping = writeMapping, RemoveEnumPrefixMapping = removeEnumPrefixMapping };
}

// Remove the prefix from the specified value. Ignore case and underscores in the comparison.
private static string TryRemovePrefix(string prefix, string value)
{
var normalizedPrefix = prefix.Replace("_", string.Empty, StringComparison.Ordinal).ToLowerInvariant();

var prefixIndex = 0;
var valueIndex = 0;

while (prefixIndex < normalizedPrefix.Length && valueIndex < value.Length)
{
if (value[valueIndex] == '_')
{
valueIndex++;
continue;
}

if (char.ToLowerInvariant(value[valueIndex]) != normalizedPrefix[prefixIndex])
{
return value;
}

prefixIndex++;
valueIndex++;
}

if (prefixIndex < normalizedPrefix.Length)
{
return value;
}

while (valueIndex < value.Length && value[valueIndex] == '_')
{
valueIndex++;
}

return valueIndex == value.Length ? value : value.Substring(valueIndex);
}

private static string GetEnumValueName(string enumName, string valueName)
{
var result = TryRemovePrefix(enumName, valueName);

// Prefix name starting with a digit with an underscore to ensure it is a valid identifier.
return result.Length > 0 && char.IsDigit(result[0])
? $"_{result}"
: result;
}

private sealed class EnumMapping
{
public required Dictionary<object, NameMapping> WriteMapping { get; init; }
public required Dictionary<string, string> RemoveEnumPrefixMapping { get; init; }
}

private sealed class NameMapping
{
public required object Value { get; init; }
public required string OriginalName { get; init; }
public required string RemoveEnumPrefixName { get; init; }
}
Comment on lines +152 to +163

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we make the EnumMapping and NameMapping as record?

private sealed record EnumMapping(
    Dictionary<object, NameMapping> WriteMapping, 
    Dictionary<string, string> RemoveEnumPrefixMapping);

private sealed record NameMapping(
    object Value, 
    string OriginalName, 
    string RemoveEnumPrefixName);

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. But classes work fine here. And records are bloated when doing AOT.

}
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#nullable enable
Microsoft.AspNetCore.Grpc.JsonTranscoding.GrpcJsonSettings.PropertyNameCaseInsensitive.get -> bool
Microsoft.AspNetCore.Grpc.JsonTranscoding.GrpcJsonSettings.PropertyNameCaseInsensitive.set -> void
Microsoft.AspNetCore.Grpc.JsonTranscoding.GrpcJsonSettings.RemoveEnumPrefix.get -> bool
Microsoft.AspNetCore.Grpc.JsonTranscoding.GrpcJsonSettings.RemoveEnumPrefix.set -> void
41 changes: 1 addition & 40 deletions src/Grpc/JsonTranscoding/src/Shared/Legacy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
using System.Text.RegularExpressions;
using Google.Protobuf.Reflection;
using Google.Protobuf.WellKnownTypes;
using Microsoft.AspNetCore.Grpc.JsonTranscoding.Internal.Json;
using Type = System.Type;

namespace Grpc.Shared;
Expand Down Expand Up @@ -365,44 +366,4 @@ internal static bool IsPathValid(string input)
}
return true;
}

// Effectively a cache of mapping from enum values to the original name as specified in the proto file,
// fetched by reflection.
// The need for this is unfortunate, as is its unbounded size, but realistically it shouldn't cause issues.
internal static class OriginalEnumValueHelper
{
private static readonly ConcurrentDictionary<Type, Dictionary<object, string>> _dictionaries
= new ConcurrentDictionary<Type, Dictionary<object, string>>();

internal static string? GetOriginalName(object value)
{
var enumType = value.GetType();
Dictionary<object, string>? nameMapping;
lock (_dictionaries)
{
if (!_dictionaries.TryGetValue(enumType, out nameMapping))
{
nameMapping = GetNameMapping(enumType);
_dictionaries[enumType] = nameMapping;
}
}

// If this returns false, originalName will be null, which is what we want.
nameMapping.TryGetValue(value, out var originalName);
return originalName;
}

private static Dictionary<object, string> GetNameMapping(Type enumType)
{
return enumType.GetTypeInfo().DeclaredFields
.Where(f => f.IsStatic)
.Where(f => f.GetCustomAttributes<OriginalNameAttribute>()
.FirstOrDefault()?.PreferredAlias ?? true)
.ToDictionary(f => f.GetValue(null)!,
f => f.GetCustomAttributes<OriginalNameAttribute>()
.FirstOrDefault()
// If the attribute hasn't been applied, fall back to the name of the field.
?.Name ?? f.Name);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -264,17 +264,52 @@ public void Enum_ReadNumber(int value)
}

[Theory]
[InlineData("FOO")]
[InlineData("BAR")]
[InlineData("NEG")]
public void Enum_ReadString(string value)
[InlineData("FOO", HelloRequest.Types.DataTypes.Types.NestedEnum.Foo)]
[InlineData("BAR", HelloRequest.Types.DataTypes.Types.NestedEnum.Bar)]
[InlineData("NEG", HelloRequest.Types.DataTypes.Types.NestedEnum.Neg)]
public void Enum_ReadString(string value, HelloRequest.Types.DataTypes.Types.NestedEnum expectedValue)
{
var serviceDescriptorRegistry = new DescriptorRegistry();
serviceDescriptorRegistry.RegisterFileDescriptor(JsonTranscodingGreeter.Descriptor.File);

var json = @$"{{ ""singleEnum"": ""{value}"" }}";

AssertReadJson<HelloRequest.Types.DataTypes>(json, descriptorRegistry: serviceDescriptorRegistry);
var result = AssertReadJson<HelloRequest.Types.DataTypes>(json, descriptorRegistry: serviceDescriptorRegistry);
Assert.Equal(expectedValue, result.SingleEnum);
}

[Theory]
[InlineData("UNSPECIFIED", PrefixEnumType.Types.PrefixEnum.Unspecified)]
[InlineData("PREFIX_ENUM_UNSPECIFIED", PrefixEnumType.Types.PrefixEnum.Unspecified)]
[InlineData("FOO", PrefixEnumType.Types.PrefixEnum.Foo)]
[InlineData("PREFIX_ENUM_FOO", PrefixEnumType.Types.PrefixEnum.Foo)]
[InlineData("BAR", PrefixEnumType.Types.PrefixEnum.Bar)]
public void Enum_RemovePrefix_ReadString(string value, PrefixEnumType.Types.PrefixEnum expectedValue)
{
var serviceDescriptorRegistry = new DescriptorRegistry();
serviceDescriptorRegistry.RegisterFileDescriptor(JsonTranscodingGreeter.Descriptor.File);

var json = @$"{{ ""singleEnum"": ""{value}"" }}";

var result = AssertReadJson<PrefixEnumType>(json, descriptorRegistry: serviceDescriptorRegistry, serializeOld: false, settings: new GrpcJsonSettings { RemoveEnumPrefix = true });
Assert.Equal(expectedValue, result.SingleEnum);
}

[Theory]
[InlineData("UNSPECIFIED", CollisionPrefixEnumType.Types.CollisionPrefixEnum.Unspecified)]
[InlineData("COLLISION_PREFIX_ENUM_UNSPECIFIED", CollisionPrefixEnumType.Types.CollisionPrefixEnum.Unspecified)]
[InlineData("FOO", CollisionPrefixEnumType.Types.CollisionPrefixEnum.Foo)]
[InlineData("COLLISION_PREFIX_ENUM_FOO", CollisionPrefixEnumType.Types.CollisionPrefixEnum.CollisionPrefixEnumFoo)] // Match exact rather than fallback.
[InlineData("COLLISION_PREFIX_ENUM_COLLISION_PREFIX_ENUM_FOO", CollisionPrefixEnumType.Types.CollisionPrefixEnum.CollisionPrefixEnumFoo)]
public void Enum_RemovePrefix_Collision_ReadString(string value, CollisionPrefixEnumType.Types.CollisionPrefixEnum expectedValue)
{
var serviceDescriptorRegistry = new DescriptorRegistry();
serviceDescriptorRegistry.RegisterFileDescriptor(JsonTranscodingGreeter.Descriptor.File);

var json = @$"{{ ""singleEnum"": ""{value}"" }}";

var result = AssertReadJson<CollisionPrefixEnumType>(json, descriptorRegistry: serviceDescriptorRegistry, serializeOld: false, settings: new GrpcJsonSettings { RemoveEnumPrefix = true });
Assert.Equal(expectedValue, result.SingleEnum);
}

[Fact]
Expand Down
Loading
Loading