Repository navigation
Conversation
…ine of code Resolves Pathoschild#135
This fixes a few edge cases: - downloads finishing without a guaranteed 100% progress update; - progress reporting invalid percentages (e.g. 250%) if the server provides an incorrect Content-Length; - progress never reported if the server provides no Content-Length; - a DivideByZeroException if the server provides a zero Content-Length.
This applies our pre-existing fixes like Pathoschild#126 to the new code.
We reported progress on every chunk read, but that could lead to a large number of callbacks when downloading a large file over a fast connection (e.g. thousands per second). The progress reports are now throttled to one per 250ms at most.
|
This looks good overall; thanks for the PR! There's one edge case I'm not sure how we should handle: when used with |
| lastTickReported = tick; // workaround: `Environment.TickCount` eventually wraps around, which would stop any further progress updates | ||
|
|
||
| // notify progress tracker | ||
| if (contentLength > 0 && tick >= lastTickReported + throttleMilliseconds) |
There was a problem hiding this comment.
Rather than throttling progress to once per arbitrary period of 250 ticks, go back to the previous logic and convert percentDownloaded and lastReportedProgress variables to int. The line if (percentDownloaded > lastReportedProgress) will ensure we report progress at most once per percent for a total maximum of 100 progress reports per download. That would keep the logic simple AND prevent overwhelming.
There was a problem hiding this comment.
Something like this:
// stream file to disk
int lastReportedProgress = 0;
int bytesRead;
long totalBytesRead = 0L;
byte[] buffer = new byte[bufferSize];
while ((bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) > 0)
{
// stream next chunk
await fileStream.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
totalBytesRead += bytesRead;
// notify progress tracker
if (contentLength > 0)
{
// Math.Min is used to avoid reporting more than 100%
int percentDownloaded = Math.Min((int)((totalBytesRead / (contentLength * 1d)) * 100), 100);
// report progress if percentage has increased since the last report (to avoid flooding the progress reporter with updates)
if (percentDownloaded > lastReportedProgress)
{
progress?.Report(percentDownloaded);
lastReportedProgress = percentDownloaded;
}
}
}
// send final progress update
if (lastReportedProgress < 100)
progress?.Report(100);There was a problem hiding this comment.
One more thing: if you accept my suggestion, you can also change the progress reporter to:
IProgress<int>? progress = nullThere was a problem hiding this comment.
That would be elegant, but it'd cause the opposite problem: downloading a large file over a slow connection could go a long time between progress updates, so a stalled download would be indistinguishable from a slow one. With time throttling, slow and fast connections both get regular updates. The throttle could maybe be configurable though.
Do you mean like a HTTP500 server error? If that's what you mean, the default error filter will catch it and it won't get downloaded as a file (unless the developer has deliberately removed the error filter from the pipeline, in which case I don't know exactly how it will behave. To be honest, I have never tried dispatching a HTTP request without an error filter). |
43e6f7e to
e7af4f7
Compare
Yep. For example, if you do this in the integration test right now: using IClient client = this
.ConstructClient("https://proof.ovh.net/")
.SetOptions(ignoreHttpErrors: true);
await client.DownloadFileAsync("files/error-404.txt", saveToPath);
Console.WriteLine(File.ReadAllText(saveToPath));The downloaded file will having this content: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="noindex">
<title>404 — Not found</title>
…The IResponse response = await client.GetAsync("files/error-404.txt");
if (response.IsSuccessStatusCode)
await response.AsFileDownload(saveToPath, progress);
else
throw new Exception($"File API unavailable: HTTP {response.Status} {await response.AsString()}");As an extra benefit, that would let you download any request as a file: await client
.PostAsync("api/download", request)
.WithBearerAuthentication(signature)
.AsFileDownload(saveToPath, progress); |
|
Oh I see: you turn off error handling. I don't think moving the extension to the Maybe ignoring Http errors is simply not compatible with this new extension method and maybe we should force http errors to be handled. Like so: // fetch response
IResponse response = await client
.GetAsync(resource)
.WithOptions(completeWhen: HttpCompletionOption.ResponseHeadersRead, ignoreHttpErrors: false)
.WithCancellationToken(cancellationToken)
.AsResponse()
.ConfigureAwait(false); |
Download a resource, save it locally and report progress as data is being downloaded.
Resolves #135