Skip to content
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

First pass at Grpc.StatusProto API #2205

Merged
merged 15 commits into from
Jan 4, 2024
Merged
Show file tree
Hide file tree
Changes from 11 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
14 changes: 14 additions & 0 deletions Grpc.DotNet.sln
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Grpc.HealthCheck.Tests", "t
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Grpc.Reflection.Tests", "test\Grpc.Reflection.Tests\Grpc.Reflection.Tests.csproj", "{857C5B4B-E2A8-4ACA-98FB-5E592E2224CC}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Grpc.StatusProto", "src\Grpc.StatusProto\Grpc.StatusProto.csproj", "{C01E4F44-9AB0-4478-A453-C88CCB49A4F1}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Grpc.StatusProto.Tests", "test\Grpc.StatusProto.Tests\Grpc.StatusProto.Tests.csproj", "{E49FA5BF-4D67-4C95-9543-8E9FCEAF3609}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -302,6 +306,14 @@ Global
{857C5B4B-E2A8-4ACA-98FB-5E592E2224CC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{857C5B4B-E2A8-4ACA-98FB-5E592E2224CC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{857C5B4B-E2A8-4ACA-98FB-5E592E2224CC}.Release|Any CPU.Build.0 = Release|Any CPU
{C01E4F44-9AB0-4478-A453-C88CCB49A4F1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C01E4F44-9AB0-4478-A453-C88CCB49A4F1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C01E4F44-9AB0-4478-A453-C88CCB49A4F1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C01E4F44-9AB0-4478-A453-C88CCB49A4F1}.Release|Any CPU.Build.0 = Release|Any CPU
{E49FA5BF-4D67-4C95-9543-8E9FCEAF3609}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E49FA5BF-4D67-4C95-9543-8E9FCEAF3609}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E49FA5BF-4D67-4C95-9543-8E9FCEAF3609}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E49FA5BF-4D67-4C95-9543-8E9FCEAF3609}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -355,6 +367,8 @@ Global
{B4153E7F-5CF3-4DFB-A9D1-5E77A2FB2C48} = {8C62055F-8CD7-4859-9001-634D544DF2AE}
{25544326-C145-4D05-A4C3-AC7D59E17196} = {CECC4AE8-9C4E-4727-939B-517CC2E58D65}
{857C5B4B-E2A8-4ACA-98FB-5E592E2224CC} = {CECC4AE8-9C4E-4727-939B-517CC2E58D65}
{C01E4F44-9AB0-4478-A453-C88CCB49A4F1} = {8C62055F-8CD7-4859-9001-634D544DF2AE}
{E49FA5BF-4D67-4C95-9543-8E9FCEAF3609} = {CECC4AE8-9C4E-4727-939B-517CC2E58D65}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {CD5C2B19-49B4-480A-990C-36D98A719B07}
Expand Down
1 change: 1 addition & 0 deletions build/dependencies.props
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<Project>
<PropertyGroup>
<BenchmarkDotNetPackageVersion>0.13.1</BenchmarkDotNetPackageVersion>
<GoogleApiCommonProtosPackageVersion>2.10.0</GoogleApiCommonProtosPackageVersion>
<GoogleApisAuthPackageVersion>1.46.0</GoogleApisAuthPackageVersion>
<GoogleProtobufPackageVersion>3.23.1</GoogleProtobufPackageVersion>
<GrpcDotNetPackageVersion>2.55.0</GrpcDotNetPackageVersion> <!-- Used by example projects -->
Expand Down
105 changes: 105 additions & 0 deletions src/Grpc.StatusProto/ExceptionExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
// Copyright 2023 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Rpc;
using Grpc.Shared;

namespace Grpc.StatusProto;
Copy link
Member

Choose a reason for hiding this comment

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

I think the namespace of the extension types should change. See #2273 (comment)


/// <summary>
/// Extensions methods for <see cref="System.Exception"/>
/// </summary>
public static class ExceptionExtensions
{
/// <summary>
/// Create a <see cref="Google.Rpc.DebugInfo"/> from an <see cref="System.Exception"/>,
/// populating the Message and StackTrace from the exception.
/// Note: experimental API that can change or be removed without any prior notice.
/// </summary>
/// <remarks>
/// <example>
/// For example:
/// <code>
/// try { /* ... */
/// }
/// catch (Exception e) {
/// Google.Rpc.Status status = new() {
/// Code = (int)StatusCode.Internal,
/// Message = "Internal error",
/// Details = {
/// // populate debugInfo from the exception
/// Any.Pack(e.ToRpcDebugInfo())
/// }
/// };
/// // ...
/// }
/// </code>
/// </example>
/// </remarks>
/// <param name="exception"></param>
/// <param name="innerDepth">Maximum number of inner exceptions to include in the StackTrace. Defaults
/// to not including any inner exceptions</param>
/// <returns>
/// A new <see cref="Google.Rpc.DebugInfo"/> populated from the exception.
/// </returns>
public static DebugInfo ToRpcDebugInfo(this Exception exception, int innerDepth = 0)
tonydnewell marked this conversation as resolved.
Show resolved Hide resolved
{
ArgumentNullThrowHelper.ThrowIfNull(exception);

var debugInfo = new DebugInfo();

var message = exception.Message;
var name = exception.GetType().FullName;

// Populate the Detail from the exception type and message
debugInfo.Detail = message is null ? name : name + ": " + message;

// Populate the StackEntries from the exception StackTrace
if (exception.StackTrace is not null)
{
var sr = new StringReader(exception.StackTrace);
var entry = sr.ReadLine();
while (entry is not null)
{
debugInfo.StackEntries.Add(entry);
entry = sr.ReadLine();
}
}

// Add inner exceptions to the StackEntries
var inner = exception.InnerException;
while (innerDepth > 0 && inner is not null)
{
message = inner.Message;
name = inner.GetType().FullName;
debugInfo.StackEntries.Add("InnerException: " + (message is null ? name : name + ": " + message));

if (inner.StackTrace is not null)
{
var sr = new StringReader(inner.StackTrace);
var entry = sr.ReadLine();
while (entry is not null)
{
debugInfo.StackEntries.Add(entry);
entry = sr.ReadLine();
}
}

inner = inner.InnerException;
--innerDepth;
}

return debugInfo;
}
}
29 changes: 29 additions & 0 deletions src/Grpc.StatusProto/Grpc.StatusProto.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<Description>gRPC C# API for error handling using google/rpc/status.proto</Description>
<PackageTags>gRPC RPC HTTP/2</PackageTags>

<IsGrpcPublishedPackage>true</IsGrpcPublishedPackage>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<TargetFrameworks>net462;netstandard2.0;netstandard2.1</TargetFrameworks>
<PackageReadmeFile>README.md</PackageReadmeFile>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Google.Api.CommonProtos" Version="$(GoogleApiCommonProtosPackageVersion)" />
</ItemGroup>

<ItemGroup>
<None Include="README.md" Pack="true" PackagePath="\" />

<Compile Include="..\Shared\NullableAttributes.cs" Link="Internal\NullableAttributes.cs" />
<Compile Include="..\Shared\CallerArgumentExpressionAttribute.cs" Link="Internal\CallerArgumentExpressionAttribute.cs" />
<Compile Include="..\Shared\ThrowHelpers\ArgumentNullThrowHelper.cs" Link="Internal\ArgumentNullThrowHelper.cs" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Grpc.Core.Api\Grpc.Core.Api.csproj" />
</ItemGroup>

</Project>
83 changes: 83 additions & 0 deletions src/Grpc.StatusProto/MetadataExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
// Copyright 2023 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Protobuf;
using Grpc.Core;
using Grpc.Shared;

namespace Grpc.StatusProto;

/// <summary>
/// Extension methods for the Grpc.Core.Metadata
/// </summary>
public static class MetadataExtensions
{
/// <summary>
/// Name of key in the metadata for the binary encoding of
/// <see cref="Google.Rpc.Status"/>
/// </summary>
public const string StatusDetailsTrailerName = "grpc-status-details-bin";

/// <summary>
/// Get the <see cref="Google.Rpc.Status"/> from the metadata.
/// Note: experimental API that can change or be removed without any prior notice.
/// </summary>
/// <param name="metadata"></param>
/// <param name="throwOnParseError">if true then <see cref="Google.Protobuf.InvalidProtocolBufferException"/>
/// is thrown if the metadata cannot be parsed. Otherwise null is returned on a parsing error.</param>
/// <returns>
/// The found <see cref="Google.Rpc.Status"/> or null if it was
/// not present or could the data could not be parsed.
/// </returns>
public static Google.Rpc.Status? GetRpcStatus(this Metadata metadata, bool throwOnParseError = false)
{
ArgumentNullThrowHelper.ThrowIfNull(metadata);

var entry = metadata.Get(StatusDetailsTrailerName);
if (entry is null)
{
return null;
}
try
{
return Google.Rpc.Status.Parser.ParseFrom(entry.ValueBytes);
}
catch when (!throwOnParseError)
{
// By default if the message is malformed, just report there's no information.
return null;
tonydnewell marked this conversation as resolved.
Show resolved Hide resolved
}
}

/// <summary>
/// Add <see cref="Google.Rpc.Status"/> to the metadata.
/// Any existing status in the metadata will be overwritten.
/// Note: experimental API that can change or be removed without any prior notice.
/// </summary>
/// <param name="metadata"></param>
/// <param name="status">Status to add</param>
public static void SetRpcStatus(this Metadata metadata, Google.Rpc.Status status)
{
ArgumentNullThrowHelper.ThrowIfNull(metadata);
ArgumentNullThrowHelper.ThrowIfNull(status);

var entry = metadata.Get(StatusDetailsTrailerName);
JamesNK marked this conversation as resolved.
Show resolved Hide resolved
while (entry is not null)
{
metadata.Remove(entry);
entry = metadata.Get(StatusDetailsTrailerName);
}
metadata.Add(StatusDetailsTrailerName, status.ToByteArray());
}
}
Loading
Loading