using System.Net;
namespace VFXReviewWorker;
///
/// StreamContent that reports bytes sent, so a long upload can show progress.
/// Length is computed from the stream, so the PUT still carries Content-Length
/// (presigned S3 uploads reject chunked bodies).
///
internal sealed class ProgressStreamContent : HttpContent
{
private readonly Stream _source;
private readonly Action? _onProgress;
public ProgressStreamContent(Stream source, Action? onProgress)
{
_source = source;
_onProgress = onProgress;
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context) =>
SerializeToStreamAsync(stream, context, CancellationToken.None);
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext? context, CancellationToken ct)
{
var buffer = new byte[81920];
long sent = 0;
int read;
while ((read = await _source.ReadAsync(buffer, ct)) > 0)
{
await stream.WriteAsync(buffer.AsMemory(0, read), ct);
sent += read;
_onProgress?.Invoke(sent);
}
}
protected override bool TryComputeLength(out long length)
{
length = _source.Length;
return true;
}
}