using System.Diagnostics; namespace TileServer.Infrastructure.Downloads; public static class StreamCopy { public static async Task CopyWithStallTimeoutAsync( Stream input, Stream output, TimeSpan stallTimeout, TimeSpan logInterval, Action 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; } }