Moving from 1.x to 2.0
Elastic.Transport 2.0 fixes a set of defects in how a request walks its nodes, and tightens a few public types that
should never have been mutable. If you only use ITransport, TransportConfiguration and the node pools, most of this
will not touch you, but the behaviour fixes can change results, so read that section.
MaxRetriesis enforced. A request used to try every node in the pool whateverMaxRetriessaid. A request now makes at mostmin(MaxRetries, nodes - 1) + 1attempts.Request-level settings win.
UserAgent,ForceNode,DisableSniff,EnableHttpCompression,MaxRetriesandDisablePingsset on a single request now override the transport's value. Before, the transport's value won for the first four, and the request's value was ignored for the last two. A transport-levelContentTypeis also honoured.MaxRetryTimeoutis honoured. It was accepted and ignored. It now bounds the whole request including retries, and defaults toRequestTimeoutas documented.Bad credentials on a ping stop the request. A 401 on a ping was rethrown as a recoverable ping failure, so every node was pinged in turn until retries ran out. It now surfaces as
PipelineFailure.BadAuthentication, as documented.Sniffing tries every node. It used to give up after the first node that failed.
Stale-cluster sniffing can fire.
NodePool.LastUpdatestarts at the pool's creation time instead ofnull.Error bodies.
ApiCallDetails.ResponseBodyInBytesholds the body of every non-success response, including HTML from a proxy, even whenSkipDeserializationForStatusCodesapplies. (This was already the behaviour of 1.x; the old 7.x tests asserted otherwise.)Connection pools are keyed on what a handler is built from. Two requests share an HTTP handler (and so a connection pool) exactly when their compression, proxy, DNS refresh, certificates and transport settings are the same. Before, the key was a hash that could collide across different proxy credentials, ignored several of those settings, and included
RequestTimeout, so each distinct per-request timeout opened its own pool.Byte-array bodies are not copied when nothing transforms them (
PostData.Byteswith request compression off).Pooled streams come from
Microsoft.IO.RecyclableMemoryStream.RecyclableMemoryStreamFactoryis unchanged, but its ETW event source is now the package's (Microsoft-IO-RecyclableMemoryStream) and the package depends onSystem.Memorybelow net8.0. The defaultMemoryStreamFactoryis still a plainMemoryStream, on purpose: a pool keeps memory for reuse, which a memory dump of a healthy application then shows, and people read that as a leak. Pooling is opt-in (MemoryStreamFactory = new RecyclableMemoryStreamFactory(blockSize: 16 * 1024)), and worth it for large bodies that are serialized and not compressed: for a 64 KB body that is about 7 KB allocated per request against about 204 KB, with gen 2 collections, for a plain stream. With compression on, the default, the two are about equal.RecyclableMemoryStreamFactoryis now bounded: by default it keeps at most 50 MB idle (RecyclableMemoryStreamFactory.DefaultMaximumFreeBytes), and buffers returned beyond that are left to the garbage collector, so what a memory dump shows as pooled has a ceiling. Before, the pool kept its high-water mark forever. Choose your own withnew RecyclableMemoryStreamFactory(blockSize, maximumFreeBytes). Memory held by streams that are in use is not counted. Pooling pays off from about 4 KB of body upwards and costs below that: building a serialized body, 16 threads at once, a plain stream takes 40 ns at 256 B against 659 ns pooled, and 107 ns at 1 KB against 671 ns, because a short-lived small allocation is cheap and the pool's own overhead is not. At 4 KB the two are level on time and the pool allocates 93% less; at 16 KB the pool is 3.8 times faster and allocates 99% less.
Node.IsResurrectedis read-only. The pool is the only thing that decides a node is due a ping.Nodehealth is exposed throughIsAlive,IsResurrected,DeadUntilandFailedAttemptsas before, but they are now read from one atomic state, so you can no longer observe a half-updated node.RequestPipelineandRequestPipelineFactoryare internal, and so isRequestAttempt. They were never a usable extension point (the factory's constructor was already internal), and nothing in this organisation's repositories referenced them.ITransportConfiguration.PipelineProviderandTransportConfigurationDescriptor.PipelineProvider()are gone with them.Elastic.Transport.VirtualizedCluster:ExposingPipelineFactory<T>is internal. It existed to hand out aRequestPipelinefrom the test-support package, and was the only public way to obtain one; it never registered itself with the transport, so it had no effect on how requests ran.RuleOption<TFirst, TSecond>(VirtualizedCluster) is a C# 15 union, so an absent option isRuleOption<...>?rather thannull. Rules still readFails(Times(2), 503)andFailAlways(new Exception()).Auditis a record.SemVersionandVersionInfoare internal. They were a vendored semver parser and the base of the version objects in the client meta header; nothing in the Elastic .NET repositories derivesVersionInfoor usesSemVersion.ReflectionVersionInfostays public with the same members (Major,Minor,Patch,Prerelease,Metadata,IsPrerelease,ToMetadataHeaderValue(),ToString(),Create<T>(),Create(Type),TransportVersion) but no longer derives fromVersionInfo, becauseelastic-ingest-dotnetexposes one. The constructors ofDefaultMetaHeaderProvider,DefaultMetaHeaderProducerandMetaDataHeaderthat took aVersionInfoare internal; the ones taking aTypeare unchanged.- Fixed before it went internal:
SemVersion.CompareByPrecedenceandCompareTo. Precedence used to end by comparing the pre-release with the other version's build metadata, so two equal pre-release versions compared as different. Precedence now ignores build metadata (semver 2.0), andCompareTouses it only to break a tie, so it is zero exactly whenEqualsis true. SniffingNodePoolno longer overridesCreateView(it held a lock around a lazy iterator, which guarded nothing).netstandard2.1stays a target, with the same public and protected API as in 1.x.Elastic.Transport.VirtualizedCluster:SingleNodeConnection()works,ClientThrows()applies per request, and a sniff rule without a new cluster state no longer throws.
The repository pins the .NET 11 SDK (global.json) and builds the libraries for netstandard2.0, net462, net8.0,
net10.0 and net11.0. C# 15 union types are used internally; a small internal polyfill supplies the two runtime
types below net11.0, so they do not appear in the public API.
StreamResponse, PipeResponse and the Elasticsearch variants used to return an empty Stream.Null body, with a 200 status, when the server answered with another Content-Type than the request's Accept. They now throw a TransportException (PipelineFailure.BadResponse) that names both types, for a successful status code only. An error status (for example an HTML 502 from a proxy) is reported through ApiCallDetails as before, and typed responses such as StringResponse keep reporting a mismatch through ApiCallDetails.HasExpectedContentType.
To take whatever the server sends, set the request's Accept to */*. That skips the content-type check for the request.
Connections send TCP keep-alive probes after 5 minutes of silence, then every second, and drop the connection after 5 unanswered probes. KeepAliveTime and KeepAliveInterval now default to 5 minutes and 1 second on every target (they were 2 seconds each, and only reached .NET Framework). On .NET, the transport connects the socket for SocketsHttpHandler through a ConnectCallback to set them. A deployment that wants other values sets KeepAliveTime and KeepAliveInterval on the transport configuration; the probe count is fixed at 5.
A TransportConfigurationDescriptor (or a subclass built on TransportConfigurationDescriptorBase<T>) can no longer be changed after a transport is created from it. The descriptor methods throw an InvalidOperationException. Before, such a change was half applied: the transport had copied its own settings, while a request with its own configuration read the live values. Finish configuring before you create the transport, or create a copy with new TransportConfigurationDescriptor(configuration) and change that. Two transports can still share one configuration, and the TransportConfiguration record is unaffected: it was already immutable and copies with with.
DynamicResponse, ElasticsearchDynamicResponse, DynamicDictionary and DynamicValue are gone, and with them the Microsoft.CSharp dependency of the package. JsonResponse does the same with System.Text.Json's own DOM, reads the same paths, and needs no runtime binder, so it works with native AOT and trimming without exceptions. See response types.
| Was | Is |
|---|---|
transport.Get<DynamicResponse>(path) |
transport.Get<JsonResponse>(path) |
transport.Get<ElasticsearchDynamicResponse>(path) |
transport.Get<ElasticsearchJsonResponse>(path) |
response.Body.Get<int>("a.b") |
response.Get<int>("a.b") |
response.Body.a.b (the dynamic keyword) |
response.Body["a"]["b"], or response.Get<T>("a.b") |
response.Body.Get<DynamicDictionary>("a") |
response.Get<JsonNode>("a") |
The paths are the ones of DynamicResponse.Get<T>(path) as it read them after #269: [N], _first_, _last_, [first()], [last()], _arbitrary_key_ and \. for a dot in a key. Two things to look for when you move: a path that leads nowhere reads as the default of the type (as it did), and an object or an array reads as a JsonNode, not as a string.
ResponseFactory.CreateAsync, IResponseBuilder.BuildAsync and the BuildAsync of TypedResponseBuilder<TResponse> return a ValueTask<TResponse> instead of a Task<TResponse>. Most response types are built without waiting for anything, and a Task for each of them was an allocation per request (about 220 B on a call through HttpClient). await works as before. A custom response builder or response factory changes its return type: Task.FromResult(x) becomes new ValueTask<T>(x), and an async Task<T> method becomes async ValueTask<T>. A caller that needs a Task calls .AsTask().