Skip to content

Commit 4fd96dd

Browse files
authored
Merge pull request #174 from Astn/aus-1015-preview3
AUS-1015: Release 2.0.0-preview.3: strong-named assemblies and the error-handler change
2 parents abbd40e + e10aec6 commit 4fd96dd

14 files changed

Lines changed: 252 additions & 56 deletions

‎AustinHarris.JsonRpc.AspNetCore/AustinHarris.JsonRpc.AspNetCore.csproj‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66
<Product>Json-Rpc.Net ASP.NET Core host</Product>
77
<Description>ASP.NET Core hosting for AustinHarris.JsonRpc. Adds HTTP endpoints and raw Kestrel connections over TCP, Unix sockets and named pipes, with dependency injection.</Description>
88
<VersionPrefix>2.0.0</VersionPrefix>
9-
<VersionSuffix>preview.2</VersionSuffix>
10-
<PackageReleaseNotes>2.0.0-preview.2, released with the core package. What is new: https://astn.github.io/JSON-RPC.NET/changelog.html. Upgrading from 1.x: https://astn.github.io/JSON-RPC.NET/upgrading.html</PackageReleaseNotes>
9+
<VersionSuffix>preview.3</VersionSuffix>
10+
<PackageReleaseNotes>2.0.0-preview.3, released with the core package: strong-named assemblies and the error-handler change. What is new: https://astn.github.io/JSON-RPC.NET/changelog.html. Upgrading from 1.x: https://astn.github.io/JSON-RPC.NET/upgrading.html</PackageReleaseNotes>
1111
<Copyright>Austin Harris</Copyright>
1212
<PackageProjectUrl>https://astn.github.io/JSON-RPC.NET/aspnetcore.html</PackageProjectUrl>
1313
<RepositoryUrl>https://github.com/Astn/JSON-RPC.NET</RepositoryUrl>
@@ -26,6 +26,11 @@
2626
<EmbedUntrackedSources>true</EmbedUntrackedSources>
2727
<PackageIcon>icon.png</PackageIcon>
2828
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
29+
<!-- Strong-named with the key checked in at the repository root: one key for the four packages and the
30+
friend assemblies, unchanged between releases, so a signed caller can reference the packages and
31+
.NET Framework can load them. -->
32+
<SignAssembly>true</SignAssembly>
33+
<AssemblyOriginatorKeyFile>$(MSBuildThisFileDirectory)..\AustinHarris.JsonRpc.snk</AssemblyOriginatorKeyFile>
2934
<RootNamespace>AustinHarris.JsonRpc.AspNetCore</RootNamespace>
3035
</PropertyGroup>
3136

‎AustinHarris.JsonRpc.Newtonsoft/AustinHarris.JsonRpc.Newtonsoft.csproj‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66
<Product>Json-Rpc.Net Json.NET serializer</Product>
77
<Description>Json.NET serializer for AustinHarris.JsonRpc. Uses JsonSerializerSettings for converters, contract resolvers and lenient JSON input.</Description>
88
<VersionPrefix>2.0.0</VersionPrefix>
9-
<VersionSuffix>preview.2</VersionSuffix>
10-
<PackageReleaseNotes>2.0.0-preview.2, released with the core package. What is new: https://astn.github.io/JSON-RPC.NET/changelog.html. Upgrading from 1.x: https://astn.github.io/JSON-RPC.NET/upgrading.html</PackageReleaseNotes>
9+
<VersionSuffix>preview.3</VersionSuffix>
10+
<PackageReleaseNotes>2.0.0-preview.3, released with the core package: strong-named assemblies and the error-handler change. What is new: https://astn.github.io/JSON-RPC.NET/changelog.html. Upgrading from 1.x: https://astn.github.io/JSON-RPC.NET/upgrading.html</PackageReleaseNotes>
1111
<Copyright>Austin Harris</Copyright>
1212
<PackageProjectUrl>https://astn.github.io/JSON-RPC.NET/newtonsoft.html</PackageProjectUrl>
1313
<RepositoryUrl>https://github.com/Astn/JSON-RPC.NET</RepositoryUrl>
@@ -26,6 +26,11 @@
2626
<EmbedUntrackedSources>true</EmbedUntrackedSources>
2727
<PackageIcon>icon.png</PackageIcon>
2828
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
29+
<!-- Strong-named with the key checked in at the repository root: one key for the four packages and the
30+
friend assemblies, unchanged between releases, so a signed caller can reference the packages and
31+
.NET Framework can load them. -->
32+
<SignAssembly>true</SignAssembly>
33+
<AssemblyOriginatorKeyFile>$(MSBuildThisFileDirectory)..\AustinHarris.JsonRpc.snk</AssemblyOriginatorKeyFile>
2934
<RootNamespace>AustinHarris.JsonRpc.Newtonsoft</RootNamespace>
3035
</PropertyGroup>
3136

‎AustinHarris.JsonRpc.SystemTextJson/AustinHarris.JsonRpc.SystemTextJson.csproj‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66
<Product>Json-Rpc.Net System.Text.Json serializer</Product>
77
<Description>System.Text.Json serializer for AustinHarris.JsonRpc. Reads UTF-8 parameters and writes results directly to the response buffer, configured with JsonSerializerOptions.</Description>
88
<VersionPrefix>2.0.0</VersionPrefix>
9-
<VersionSuffix>preview.2</VersionSuffix>
10-
<PackageReleaseNotes>2.0.0-preview.2, released with the core package. What is new: https://astn.github.io/JSON-RPC.NET/changelog.html. Upgrading from 1.x: https://astn.github.io/JSON-RPC.NET/upgrading.html</PackageReleaseNotes>
9+
<VersionSuffix>preview.3</VersionSuffix>
10+
<PackageReleaseNotes>2.0.0-preview.3, released with the core package: strong-named assemblies and the error-handler change. What is new: https://astn.github.io/JSON-RPC.NET/changelog.html. Upgrading from 1.x: https://astn.github.io/JSON-RPC.NET/upgrading.html</PackageReleaseNotes>
1111
<Copyright>Austin Harris</Copyright>
1212
<PackageProjectUrl>https://astn.github.io/JSON-RPC.NET/systemtextjson.html</PackageProjectUrl>
1313
<RepositoryUrl>https://github.com/Astn/JSON-RPC.NET</RepositoryUrl>
@@ -25,6 +25,11 @@
2525
<EmbedUntrackedSources>true</EmbedUntrackedSources>
2626
<PackageIcon>icon.png</PackageIcon>
2727
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
28+
<!-- Strong-named with the key checked in at the repository root: one key for the four packages and the
29+
friend assemblies, unchanged between releases, so a signed caller can reference the packages and
30+
.NET Framework can load them. -->
31+
<SignAssembly>true</SignAssembly>
32+
<AssemblyOriginatorKeyFile>$(MSBuildThisFileDirectory)..\AustinHarris.JsonRpc.snk</AssemblyOriginatorKeyFile>
2833
<RootNamespace>AustinHarris.JsonRpc.SystemTextJson</RootNamespace>
2934
</PropertyGroup>
3035

‎AustinHarris.JsonRpc.snk‎

1.14 KB
Binary file not shown.

‎AustinHarris.JsonRpcTestN/AustinHarris.JsonRpcTestN.csproj‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44
<Copyright>Austin Harris</Copyright>
55
<TargetFrameworks>net8.0;net10.0</TargetFrameworks>
66
<IsPackable>false</IsPackable>
7+
<!-- Friend of the signed core assembly (InternalsVisibleTo), so signed with the same key. -->
8+
<SignAssembly>true</SignAssembly>
9+
<AssemblyOriginatorKeyFile>$(MSBuildThisFileDirectory)..\\AustinHarris.JsonRpc.snk</AssemblyOriginatorKeyFile>
710
</PropertyGroup>
811

912
<ItemGroup>

‎AustinHarris.JsonRpcTestN/DispatchHardeningTests.cs‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -385,14 +385,17 @@ public void ExceptionDetails_AreSentWhenEnabled(string name)
385385
{
386386
Config.IncludeExceptionDetails = true;
387387
var response = Parse(Run("{\"method\":\"throwsInner\",\"id\":1}", null, serializer));
388+
// the exception the method threw, with its whole cause chain: the library does not substitute the cause
388389
var data = (JObject)response["error"]["data"];
389-
Assert.AreEqual("System.ArgumentException", (string)data["ClassName"]);
390-
Assert.AreEqual("inner message", (string)data["Message"]);
390+
Assert.AreEqual("System.InvalidOperationException", (string)data["ClassName"]);
391+
Assert.AreEqual("outer message", (string)data["Message"]);
391392
StringAssert.Contains("ThrowsInner", (string)data["StackTraceString"]);
392-
Assert.AreEqual(new ArgumentException().HResult, (int)data["HResult"]);
393-
Assert.AreEqual("innermost message", (string)data["InnerException"]["Message"]);
394-
Assert.AreEqual("System.Exception", (string)data["InnerException"]["ClassName"]);
393+
Assert.AreEqual(new InvalidOperationException().HResult, (int)data["HResult"]);
394+
Assert.AreEqual("System.ArgumentException", (string)data["InnerException"]["ClassName"]);
395+
Assert.AreEqual("inner message", (string)data["InnerException"]["Message"]);
395396
StringAssert.Contains("ThrowsInner", (string)data["InnerException"]["StackTraceString"]);
397+
Assert.AreEqual("System.Exception", (string)data["InnerException"]["InnerException"]["ClassName"]);
398+
Assert.AreEqual("innermost message", (string)data["InnerException"]["InnerException"]["Message"]);
396399

397400
response = Parse(Run("{\"method\":\"throws\",\"id\":1}", null, serializer));
398401
data = (JObject)response["error"]["data"];
Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
using System;
2+
using System.Buffers;
3+
using System.IO;
4+
using System.Reflection;
5+
using System.Text;
6+
using System.Threading.Tasks;
7+
using AustinHarris.JsonRpc;
8+
using Newtonsoft.Json.Linq;
9+
using NUnit.Framework;
10+
11+
namespace AustinHarris.JsonRpcTestN
12+
{
13+
/// <summary>
14+
/// What an error handler receives in <c>error.data</c> when a method throws: the exception the method threw,
15+
/// with its own cause still attached. Only the wrappers the invocation machinery adds are stripped, a
16+
/// <see cref="TargetInvocationException"/> and an <see cref="AggregateException"/> holding one exception; an
17+
/// inner exception is never substituted for the outer one, and an inner <see cref="JsonRpcException"/> is not
18+
/// promoted. The same rule on the synchronous and the asynchronous path.
19+
/// </summary>
20+
[TestFixture]
21+
public sealed class ErrorHandlerExceptionTests
22+
{
23+
private string _session;
24+
private Exception _seen;
25+
26+
[SetUp]
27+
public void SetUp()
28+
{
29+
_session = "error-handler-" + Guid.NewGuid().ToString("N");
30+
_seen = null;
31+
Handler.GetSessionHandler(_session).SetErrorHandler((request, error) => { _seen = error.data as Exception; return error; });
32+
}
33+
34+
[TearDown]
35+
public void TearDown() => Handler.DestroySession(_session);
36+
37+
private static string Request(string method, string id = "1") => "{\"jsonrpc\":\"2.0\",\"method\":\"" + method + "\"" + (id == null ? "" : ",\"id\":" + id) + "}";
38+
39+
private string Sync(string json)
40+
{
41+
var output = new ArrayBufferWriter<byte>();
42+
JsonRpcProcessor.Process(_session, Encoding.UTF8.GetBytes(json).AsSpan(), output);
43+
return Encoding.UTF8.GetString(output.WrittenSpan);
44+
}
45+
46+
private Task<string> Async(string json) => JsonRpcProcessor.ProcessAsync(_session, json);
47+
48+
private static JObject Error(string json, int code)
49+
{
50+
var response = JObject.Parse(json);
51+
Assert.IsNotNull(response["error"], json);
52+
Assert.AreEqual(code, (int)response["error"]["code"], json);
53+
return response;
54+
}
55+
56+
/// <summary>
57+
/// Binds <paramref name="thrower"/> as a synchronous method, a Task method that has already suspended, and a
58+
/// ValueTask method that faults synchronously; "hooked" runs the synchronous method with a pre-process handler
59+
/// installed, which takes the hook path through the request objects.
60+
/// </summary>
61+
private void Bind(Func<Exception> thrower)
62+
{
63+
ServiceBinder.BindMethod(_session, "sync", new Func<int>(() => throw thrower()));
64+
ServiceBinder.BindMethod(_session, "hooked", new Func<int>(() => throw thrower()));
65+
ServiceBinder.BindMethod(_session, "async", new Func<Task<int>>(async () => { await Task.Yield(); throw thrower(); }));
66+
ServiceBinder.BindMethod(_session, "valueTask", new Func<ValueTask<int>>(() => new ValueTask<int>(Task.FromException<int>(thrower()))));
67+
}
68+
69+
private async Task<string> Run(string path, string id = "1")
70+
{
71+
if (path == "hooked")
72+
{
73+
Config.SetPreProcessHandler(_session, (request, context) => null);
74+
return Sync(Request(path, id));
75+
}
76+
return path == "sync" ? Sync(Request(path, id)) : await Async(Request(path, id));
77+
}
78+
79+
[TestCase("sync")] [TestCase("hooked")] [TestCase("async")] [TestCase("valueTask")]
80+
public async Task ThrownException_ReachesTheHandler_WithItsCause(string path)
81+
{
82+
Bind(() => new InvalidOperationException("outer", new IOException("cause")));
83+
string response = await Run(path);
84+
var error = Error(response, -32603);
85+
Assert.AreEqual(JTokenType.Null, error["error"]["data"].Type, "redacted on the wire by default");
86+
Assert.IsInstanceOf<InvalidOperationException>(_seen, "the handler gets the exception that was thrown, not its cause");
87+
Assert.AreEqual("outer", _seen.Message);
88+
Assert.IsInstanceOf<IOException>(_seen.InnerException, "with its cause still attached");
89+
}
90+
91+
[TestCase("sync")] [TestCase("hooked")] [TestCase("async")] [TestCase("valueTask")]
92+
public async Task InnerJsonRpcException_IsNotPromoted(string path)
93+
{
94+
Bind(() => new InvalidOperationException("outer", new JsonRpcException(-32040, "authored inside", "data")));
95+
string response = await Run(path);
96+
Error(response, -32603);
97+
Assert.IsInstanceOf<InvalidOperationException>(_seen);
98+
Assert.AreEqual("outer", _seen.Message);
99+
}
100+
101+
[TestCase("sync")] [TestCase("hooked")] [TestCase("async")] [TestCase("valueTask")]
102+
public async Task AuthoredException_IsPassedAsThrown(string path)
103+
{
104+
Bind(() => new JsonRpcException(-32040, "authored", "ticket 42"));
105+
string response = await Run(path);
106+
var error = Error(response, -32040);
107+
Assert.AreEqual("authored", (string)error["error"]["message"]);
108+
Assert.AreEqual("ticket 42", (string)error["error"]["data"]);
109+
}
110+
111+
[TestCase("sync")] [TestCase("hooked")] [TestCase("async")] [TestCase("valueTask")]
112+
public async Task TargetInvocationWrapper_IsStripped(string path)
113+
{
114+
Bind(() => new TargetInvocationException(new JsonRpcException(-32040, "authored", null)));
115+
Error(await Run(path), -32040);
116+
}
117+
118+
[TestCase("sync", false)] [TestCase("sync", true)] [TestCase("hooked", false)] [TestCase("hooked", true)]
119+
[TestCase("async", false)] [TestCase("async", true)] [TestCase("valueTask", false)] [TestCase("valueTask", true)]
120+
public async Task Aggregate_OnlyASingleInner_IsStripped(string path, bool several)
121+
{
122+
var authored = new JsonRpcException(-32040, "authored", null);
123+
Bind(() => several ? new AggregateException(authored, new Exception("second")) : new AggregateException(authored));
124+
Error(await Run(path), several ? -32603 : -32040);
125+
if (several) Assert.IsInstanceOf<AggregateException>(_seen, "an aggregate of several failures is passed whole");
126+
}
127+
128+
[TestCase("sync")] [TestCase("hooked")] [TestCase("async")] [TestCase("valueTask")]
129+
public async Task Notification_StillReachesTheHandler(string path)
130+
{
131+
Bind(() => new InvalidOperationException("outer", new IOException("cause")));
132+
Assert.AreEqual("", await Run(path, id: null), "a notification produces no response");
133+
Assert.IsInstanceOf<InvalidOperationException>(_seen, "but the handler still sees what was thrown");
134+
Assert.IsInstanceOf<IOException>(_seen.InnerException);
135+
}
136+
137+
[TestCase("sync")] [TestCase("async")]
138+
public async Task ConversionFailure_StaysInvalidParams(string path)
139+
{
140+
ServiceBinder.BindMethod(_session, "sync", new Func<int, int>(n => n));
141+
ServiceBinder.BindMethod(_session, "async", new Func<int, Task<int>>(async n => { await Task.Yield(); return n; }));
142+
string json = "{\"jsonrpc\":\"2.0\",\"method\":\"" + path + "\",\"params\":[\"many\"],\"id\":1}";
143+
string response = path == "sync" ? Sync(json) : await Async(json);
144+
var error = Error(response, -32602);
145+
Assert.AreEqual("conversion", (string)error["error"]["data"]["reason"], response);
146+
}
147+
148+
[TestCase("sync")] [TestCase("hooked")] [TestCase("async")] [TestCase("valueTask")]
149+
public async Task WithDetailsOn_TheWireCarriesTheOuterExceptionAndItsCause(string path)
150+
{
151+
Bind(() => new InvalidOperationException("outer", new IOException("cause")));
152+
Config.IncludeExceptionDetails = true;
153+
try
154+
{
155+
string response = await Run(path);
156+
var data = (JObject)Error(response, -32603)["error"]["data"];
157+
Assert.AreEqual("outer", (string)data["Message"], response);
158+
Assert.AreEqual("cause", (string)data["InnerException"]["Message"], response);
159+
}
160+
finally
161+
{
162+
Config.IncludeExceptionDetails = false;
163+
}
164+
}
165+
}
166+
}

‎CHANGELOG.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ the package pages on NuGet link here.
88
Versions follow [Semantic Versioning](https://semver.org/) for the public API and the documented wire
99
behaviour: a breaking change to either means a new major version.
1010

11-
## 2.0.0 (in preview: `2.0.0-preview.2`)
11+
## 2.0.0 (in preview: `2.0.0-preview.3`)
1212

1313
### Added
1414

@@ -33,6 +33,8 @@ behaviour: a breaking change to either means a new major version.
3333

3434
### Changed
3535

36+
- The four assemblies are strong-named (preview.3). One key, `AustinHarris.JsonRpc.snk` at the repository root, signs the packages and the friend assemblies, and stays the same from here on: changing a strong-name key changes the assembly identity. Public key token `e6819c02cf4aec44`. A signed caller can now reference the packages without CS8002, and .NET Framework loads them from a signed assembly.
37+
- An error handler receives the exception the method threw (preview.3). Previously the library replaced an exception that had an `InnerException` with that inner exception, and promoted an inner `JsonRpcException` to the response, so a handler saw the cause instead of the error and an authored outer error lost its message. Now only the wrappers the invocation machinery adds are stripped, a `TargetInvocationException` and a single-inner `AggregateException`, on the synchronous and asynchronous paths alike; everything else, inner exception included, reaches the handler as thrown.
3638
- `RpcMethod.FromMethod` is `RpcMethod.FromMethodInfo`; `RpcInterfaceMethod.Method` is `RpcInterfaceMethod.MethodInfo`. A `MethodInfo` is always spelled out; "method" means the JSON-RPC method.
3739
- The session parameter is spelled `sessionId` on every overload (`BindService`, `Handler.RegisterInstance` and the `JsonRpcService` constructor used `sessionID`).
3840
- `Handler.RegisterFuction` and `UnRegisterFunction` are obsolete; use `ServiceBinder.BindMethod` and `UnbindMethod` (which throw on a duplicate name instead of replacing it).

0 commit comments

Comments
 (0)