Thrift client library for Microsoft .NET Standard
The library ships as two packages so that non-web projects no longer pull in the ASP.NET Core stack:
ApacheThrift – the core library (protocols, transports, processors and the TSimpleAsyncServer/TThreadPoolAsyncServer servers). It only depends on Microsoft.Extensions.Logging.Abstractions and has no ASP.NET Core dependency.ApacheThrift.AspNetCore – the ASP.NET Core HTTP server middleware (THttpServerTransport, namespace Thrift.Transport.Server). Reference this package in addition to ApacheThrift only when you host Thrift over ASP.NET Core. Existing code keeps compiling unchanged once the package reference is added.The test projects under Tests/Thrift.Compile.Tests generate their code with the compiler they find first, so rebuild the compiler after changing a generator. An outdated binary produces code that no longer matches the library and fails with confusing compile errors.
./ bootstrap && ./ configure && makeSince 0.26.0, every await in the library and in the code generated by thrift -gen netstd uses ConfigureAwait(false), so none of them resumes on the SynchronizationContext of the caller (THRIFT-6538). This matters on threads that have one, such as a WinForms, WPF, WinUI or MAUI UI thread, or a request thread of classic ASP.NET:
.Result, .Wait() or GetAwaiter().GetResult(), no longer hangs. Awaiting the call is still the better choice, because blocking keeps the thread busy until the call returns.CreateContextAsync, ProcessContextAsync and DeleteContextAsync callbacks of a server event handler run on the thread pool, also when ServeAsync() is started on such a thread. Up to 0.25.0, TSimpleAsyncServer ran them on the SynchronizationContext of the thread that started ServeAsync(). A handler that updates the UI has to marshal that update itself, for example with Control.Invoke, Dispatcher.Invoke or a SynchronizationContext it has captured. PreServeAsync is still called on the thread that starts ServeAsync().ConfigureAwait(false) too, otherwise a blocked caller can still hang.If you are migrating your code from netcore library, you will have to:
thrift -gen netstdhashcode is now standard, while nullable is no longer supported.Thrift.Transport and Thrift.Protocol namespaces now use the singular formusing Thrift.Processor; in the server code where appropriateT*ClientTransport to T*TransportTBaseServer occurrences in your code to TServerSingletonTProcessorFactory is now called TSingletonProcessorFactoryAsyncBaseServer is now the TSimpleAsyncServerYou may wonder why we changed so many names. The naming scheme has been revised for two reasons: First, we want to get back the established, well-known naming consistency across the Thrift libraries which the netcore library did not fully respect. Second, by achieving that first objective, we get the additional benefit of making migration at least a bit easier for C# projects.
Because of the different environment requirements, migration from C# takes slightly more efforts. While the code changes related to Thrift itself are moderate, you may need to upgrade certain dependencies, components or even modules to more recent versions.
thrift -gen netstd. The following compiler flags are no longer needed or supported: hashcode and async are now standard, while nullable is no longer supported.async/await model, if you have not already done so. As netstd does not support ISync anymore, async is mandatory. The synchronous model is simply no longer available (that‘s also the reason why we don’t need the async flag anymore).cancellationToken parameters. They are optional but may be quite helpful.using Thrift.Processor; in the server code where appropriateTServerSocket is now called TServerSocketTransportIProtocolFactory into ITProtocolFactoryTSimpleServer, try TSimpleAsyncServer insteadTThreadPoolServer is now a TThreadPoolAsyncServerServe() method does now ServeAsync()SetEventHandler method now starts with an uppercase letterTServerEventHandler descendants you have in your codeA generated client normally shares one protocol, and with it one transport, between all of its calls. That is fine for sequential use, but asynchronous calls that overlap can corrupt each other's request and response data. For transports that can keep request and response state per call, the generator offers an opt-in isolated option:
thrift -gen netstd:isolated my.thrift
The default output is unchanged. With isolated, the generated Client keeps its constructors that take protocols and gains a constructor that takes a call-isolated transport and a protocol factory. The constructor you choose decides how the client behaves:
// shared protocols, exactly as without the option (socketTransport: any TTransport, for example a TSocketTransport) var legacy = new MyService.Client(new TBinaryProtocol(socketTransport)); // per-call transport view and protocol for every call var transport = new THttpTransport(new Uri("http://localhost:9090/thrift"), new TConfiguration()); using var client = new MyService.Client(transport, new TBinaryProtocol.Factory()); // these calls may overlap var a = client.add(1, 2); var b = client.add(3, 4); await Task.WhenAll(a, b);
When a service extends another service, the base service needs the isolated option as well, because the client of the derived service builds on the client of the base service. Generate the included IDL files together with -r, or regenerate the base service separately with the option. A client generated with isolated over a base client that was generated without it does not compile.
Call-isolated transports implement ICallIsolatedTransport: THttpTransport and TMemoryBufferTransport, plus TIsolatedBufferedTransport and TIsolatedFramedTransport, which wrap another call-isolated transport. The isolated layers only accept an ICallIsolatedTransport, so stream-based transports cannot be combined with them. Stream transports share ordered input and are not suitable for overlapping calls. A transport whose call views need asynchronous setup implements IAsyncCallIsolatedTransport; the client then creates each view asynchronously.
client.IsCallIsolated tells which mode a client is in. A client built with a call-isolated transport has no shared protocols, so its InputProtocol and OutputProtocol properties throw.
The legacy TBufferedTransport and TFramedTransport are not call-isolated. Wrapping a THttpTransport in one of them and passing the result to the call-isolated constructor does not compile, and that is intended: it is not silently ignored. Use TIsolatedBufferedTransport or TIsolatedFramedTransport instead.
Shared by all calls of a client: the transport object and its configuration (for THttpTransport that is the HttpClient, its headers, ContentType, ConnectTimeout and PerCallTimeout), the protocol factory and the counter that hands out sequence IDs.
Created for every call and released with it: the transport view with its request buffer and its response, the protocol, the sequence ID, and the cancellation token and timeout of the call.
The constructor takes a protocol factory, and the factory decides what each call's protocol looks like. To address a service on a multiplexed server, return a TMultiplexedProtocol from the factory:
class MultiplexedFactory : TProtocolFactory { public override TProtocol GetProtocol(TTransport trans) => new TMultiplexedProtocol(new TBinaryProtocol(trans), "MyService"); } using var client = new MyService.Client(transport, new MultiplexedFactory());
Besides the high-level methods, the client exposes send_<name> and recv_<name>. Without a context they use the shared protocols, as before. For an isolated client there is a second overload of each that takes the TCallContext of the call, so replies can be received in any order:
using var first = client.CreateCallContext(); using var second = client.CreateCallContext(); await client.send_add(first, 1, 2); await client.send_add(second, 3, 4); var r2 = await client.recv_add(second); var r1 = await client.recv_add(first);
The overloads that take a context have no CancellationToken parameter: the call's cancellation token and timeout are those of its context.
Two timeouts can apply to a call. A transport can declare a default for all of its calls, for example THttpTransport.PerCallTimeout, and one call can be given a tighter one of its own. Both are linked with the cancellation token you pass, and the shortest bound wins. A per-call timeout cannot loosen the transport's.
var transport = new THttpTransport(new Uri("http://localhost:9090/thrift"), new TConfiguration()) { PerCallTimeout = TimeSpan.FromSeconds(60), ConnectTimeout = 60000, // milliseconds, see below }; using var client = new MyService.Client(transport, new TBinaryProtocol.Factory()); // this call is bounded by 5 seconds instead of 60 using var context = client.CreateCallContext(TimeSpan.FromSeconds(5)); await client.send_add(context, 1, 2); var sum = await client.recv_add(context);
The clock of a call runs from the creation of its context until the context is disposed, so for split calls it covers the time between send and receive. A call that exceeds its timeout fails with a TTransportException of type TimedOut. A call that the caller cancelled fails as cancelled instead, so the two can be told apart. Neither affects any other call.
A third limit applies to every request that THttpTransport sends: the timeout of its HttpClient, which you set with ConnectTimeout (30 seconds by default). It is not the timeout of the call, so a PerCallTimeout that is longer does not extend it. If you need calls to run longer than 30 seconds, raise ConnectTimeout as well, as in the example above. When this limit elapses, the request fails with a TTransportException of type TimedOut, like the other timeouts, and not as a cancellation by the caller. The message text of such an exception differs between .NET and .NET Framework.
CreateCallContext() is owned by the caller. Dispose it once its reply has been received, or when the call is abandoned. Disposing a context releases only that call's transport view.TApplicationException of type BadSequenceId.We use SharpFuzz (and its libfuzzer variant) to fuzz the Thrift protocol parsers. This is not integrated with oss-fuzz, so all fuzzing must be run locally. Supported platform: Linux only.
make check compiles the 12 fuzzer variants without SharpFuzz IL instrumentation, so changes that break the fuzzer build will fail CI. Full, instrumented builds suitable for actually running a fuzzer remain opt-in: run make build-fuzzers (or ./buildfuzzers.sh), which additionally requires the SharpFuzz.CommandLine global tool and the libfuzzer-dotnet native driver as described below.
A .NET 11 SDK (same one used for the rest of lib/netstd).
The SharpFuzz IL-rewriter CLI, installed as a .NET global tool:
dotnet tool install --global SharpFuzz.CommandLine export PATH="$PATH:$HOME/.dotnet/tools"
Add the PATH export to your shell rc if you want it to persist.
The native libfuzzer-dotnet driver binary. Grab a prebuilt release from the Metalnem/libfuzzer-dotnet releases page (or build it from source). Place it in a directory of your choice and point SHARPFUZZ_DIR at that directory:
export SHARPFUZZ_DIR=/path/to/libfuzzer-dotnet-dir
buildfuzzers.sh and runfuzzer.sh expect to find $SHARPFUZZ_DIR/libfuzzer-dotnet.
DOTNET_ROLL_FORWARDAs of SharpFuzz.CommandLine 2.2.0, the global tool's runtimeconfig.json pins the tool to .NET 9, which prevents it from running under a .NET 11-only host. Both buildfuzzers.sh and runfuzzer.sh therefore export DOTNET_ROLL_FORWARD=Major at the top of the script as a workaround. Upstream fix: SharpFuzz PR #72 (merged, pending release as SharpFuzz 2.3.0). Once that release ships, remove the DOTNET_ROLL_FORWARD exports from both shell drivers and update the SharpFuzz package pin in Tests/Thrift.FuzzTests/Thrift.FuzzTests.csproj.
Build all twelve fuzzer assemblies (3 protocols x 2 fuzzer types x 2 engines) and instrument them with SharpFuzz:
./buildfuzzers.sh
Run one fuzzer:
./runfuzzer.sh <fuzzer-name> <engine> [extra-fuzzer-args...]
Where <fuzzer-name> is one of binary, compact, json, binary-roundtrip, compact-roundtrip, json-roundtrip, and <engine> is libfuzzer or afl. Any additional arguments are passed through to the underlying fuzzer engine, e.g.:
./runfuzzer.sh binary libfuzzer -runs=10000