public static PostData StreamHandler()

in src/Elastic.Transport/Requests/Body/PostData.Streamable.cs [22:66]


	public static PostData StreamHandler<T>(T state, Action<T, Stream> syncWriter,
		Func<T, Stream, CancellationToken, Task> asyncWriter) =>
		new StreamableData<T>(state, syncWriter, asyncWriter);

	/// <summary>
	/// Represents an instance of <see cref="PostData"/> that can handle <see cref="PostType.StreamHandler"/>.
	/// Allows users full control over how they want to write data to the stream.
	/// </summary>
	/// <typeparam name="T">The data or a state object used during writing, passed to the handlers to avoid boxing</typeparam>
	private class StreamableData<T> : PostData
	{
		private readonly T _state;
		private readonly Action<T, Stream> _syncWriter;
		private readonly Func<T, Stream, CancellationToken, Task> _asyncWriter;

		public StreamableData(T state, Action<T, Stream> syncWriter,
			Func<T, Stream, CancellationToken, Task> asyncWriter)
		{
			_state = state;
			const string message = "PostData.StreamHandler needs to handle both synchronous and async paths";
			_syncWriter = syncWriter ?? throw new ArgumentNullException(nameof(syncWriter), message);
			_asyncWriter = asyncWriter ?? throw new ArgumentNullException(nameof(asyncWriter), message);
			if (_syncWriter == null || _asyncWriter == null)
				throw new ArgumentNullException();
			Type = PostType.StreamHandler;
		}

		public override void Write(Stream writableStream, ITransportConfiguration settings, bool disableDirectStreaming)
		{
			MemoryStream buffer = null;
			var stream = writableStream;
			BufferIfNeeded(settings.MemoryStreamFactory, disableDirectStreaming, ref buffer, ref stream);
			_syncWriter(_state, stream);
			FinishStream(writableStream, buffer, disableDirectStreaming);
		}

		public override async Task WriteAsync(Stream writableStream, ITransportConfiguration settings, bool disableDirectStreaming, CancellationToken cancellationToken)
		{
			MemoryStream buffer = null;
			var stream = writableStream;
			BufferIfNeeded(settings.MemoryStreamFactory, disableDirectStreaming, ref buffer, ref stream);
			await _asyncWriter(_state, stream, cancellationToken).ConfigureAwait(false);
			await FinishStreamAsync(writableStream, buffer, disableDirectStreaming, cancellationToken).ConfigureAwait(false);
		}
	}