Files
tile-server/src/TileServer.Infrastructure/Downloads/StreamCopy.cs
T
2026-09-21 03:53:15 +03:00

63 lines
1.8 KiB
C#

using System.Diagnostics;
namespace TileServer.Infrastructure.Downloads;
public static class StreamCopy
{
public static async Task<long> CopyWithStallTimeoutAsync(
Stream input,
Stream output,
TimeSpan stallTimeout,
TimeSpan logInterval,
Action<long, long?> onProgress,
long? totalBytes,
CancellationToken ct)
{
var buffer = new byte[1024 * 1024];
long copied = 0;
var firstByteLogged = false;
var lastLog = TimeSpan.Zero;
var clock = Stopwatch.StartNew();
while (true)
{
int read;
using (var stallCts = CancellationTokenSource.CreateLinkedTokenSource(ct))
{
stallCts.CancelAfter(stallTimeout);
try
{
read = await input.ReadAsync(buffer.AsMemory(0, buffer.Length), stallCts.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
throw new TimeoutException(
$"No data received for {stallTimeout.TotalSeconds:0}s after {copied} bytes (stall).");
}
}
if (read == 0)
{
break;
}
await output.WriteAsync(buffer.AsMemory(0, read), ct).ConfigureAwait(false);
copied += read;
if (!firstByteLogged)
{
firstByteLogged = true;
onProgress(copied, totalBytes);
lastLog = clock.Elapsed;
}
else if (clock.Elapsed - lastLog >= logInterval)
{
onProgress(copied, totalBytes);
lastLog = clock.Elapsed;
}
}
return copied;
}
}