tree: 54217633026c4f65e3b91ef8eda7479d6fe1161d [search]
  1. Benchmarks/
  2. Tests/
  3. Thrift/
  4. Thrift.AspNetCore/
  5. build.cmd
  6. build.sh
  7. buildfuzzers.sh
  8. Directory.Build.props
  9. Makefile.am
  10. README.md
  11. runfuzzer.sh
  12. runtests.cmd
  13. runtests.sh
  14. Thrift.slnx
lib/netstd/README.md

Apache Thrift netstd

Thrift client library for Microsoft .NET Standard

NuGet packages

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.

Build the library

How to build on Windows

  • Get Thrift IDL compiler executable, add to some folder and add path to this folder into PATH variable.
  • Alternatively, build from source by using the cmake target “copy-thrift-compiler”, which places the binary to a suitable place.
  • Open the Thrift.slnx project with Visual Studio and build. or
  • Build with scripts

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.

How to build on Unix/Linux

  • Ensure you have a suitable .NET Core SDK installed, or use the Ubuntu docker image
  • Follow common automake build practice: ./ bootstrap && ./ configure && make

Known issues

  • In trace logging mode you can see some not important internal exceptions

Async calls and the SynchronizationContext

Since 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:

  • A client call that such a thread blocks on, for example with .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.
  • Service handlers and the 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().
  • Your own code that the library calls, such as a custom transport, protocol, stream or processor, may be called on a thread-pool thread once an I/O operation has completed asynchronously. If it awaits anything itself, it should use ConfigureAwait(false) too, otherwise a blocked caller can still hang.

Migration to netstd

... from netcore

If you are migrating your code from netcore library, you will have to:

  • Switch to thrift -gen netstd
  • the following compiler flags are no longer needed or supported: hashcode is now standard, while nullable is no longer supported.
  • the Thrift.Transport and Thrift.Protocol namespaces now use the singular form
  • add using Thrift.Processor; in the server code where appropriate
  • rename all T*ClientTransport to T*Transport
  • rename all TBaseServer occurrences in your code to TServer
  • the SingletonTProcessorFactory is now called TSingletonProcessorFactory
  • and the AsyncBaseServer is now the TSimpleAsyncServer

You 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.

... from csharp

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.

  1. Client and server applications must use at least framework 4.6.1, any version below will not work.
  2. Switch to 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.
  3. Familiarize yourself with the 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).
  4. Consider proper use of cancellationToken parameters. They are optional but may be quite helpful.
  5. As you probably already guessed, there are a few names that have been changed:
  • add using Thrift.Processor; in the server code where appropriate
  • the TServerSocket is now called TServerSocketTransport
  • change IProtocolFactory into ITProtocolFactory
  • if you are looking for TSimpleServer, try TSimpleAsyncServer instead
  • similarly, the TThreadPoolServer is now a TThreadPoolAsyncServer
  • the server's Serve() method does now ServeAsync()
  • In case you are using Thrift server event handlers: the SetEventHandler method now starts with an uppercase letter
  • and you will also have to revise the method names of all TServerEventHandler descendants you have in your code

Isolated clients (overlapping calls)

A 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.

What is shared and what is per call

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.

Multiplexed protocol

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());

Split send and receive

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.

Timeouts and cancellation

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.

Lifetime and ownership

  • The high-level methods create a context, use it for exactly one call and dispose it on success, failure and cancellation. One-way calls release their context after the request has been sent. A call whose token is already cancelled creates no transport view at all.
  • A context created with 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.
  • Each call gets a sequence ID that is unique within the client. A reply whose ID differs from the ID of its call is rejected with a TApplicationException of type BadSequenceId.
  • The client owns the shared transport. Disposing the client disposes the transport and rejects new calls, so keep the client alive until all of its calls have finished.

Fuzzing

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.

Prerequisites

  1. A .NET 11 SDK (same one used for the rest of lib/netstd).

  2. 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.

  3. 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.

A temporary note on DOTNET_ROLL_FORWARD

As 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.

Running the fuzzers

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