forked from LykosAI/StabilityMatrix
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrackedDownload.cs
More file actions
473 lines (391 loc) · 15.7 KB
/
TrackedDownload.cs
File metadata and controls
473 lines (391 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
using System.Diagnostics.CodeAnalysis;
using System.Security.Authentication;
using System.Text.Json.Serialization;
using AsyncAwaitBestPractices;
using NLog;
using StabilityMatrix.Core.Helper;
using StabilityMatrix.Core.Models.FileInterfaces;
using StabilityMatrix.Core.Models.Progress;
using StabilityMatrix.Core.Services;
namespace StabilityMatrix.Core.Models;
public class TrackedDownload
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
[JsonIgnore]
private IDownloadService? downloadService;
[JsonIgnore]
private Task? downloadTask;
[JsonIgnore]
private CancellationTokenSource? downloadCancellationTokenSource;
[JsonIgnore]
private CancellationTokenSource? downloadPauseTokenSource;
[JsonIgnore]
private CancellationTokenSource AggregateCancellationTokenSource =>
CancellationTokenSource.CreateLinkedTokenSource(
downloadCancellationTokenSource?.Token ?? CancellationToken.None,
downloadPauseTokenSource?.Token ?? CancellationToken.None
);
public required Guid Id { get; init; }
public required Uri SourceUrl { get; init; }
public Uri? RedirectedUrl { get; init; }
public required DirectoryPath DownloadDirectory { get; init; }
public required string FileName { get; init; }
public required string TempFileName { get; init; }
public string? ExpectedHashSha256 { get; set; }
/// <summary>
/// Whether to auto-extract the archive after download
/// </summary>
public bool AutoExtractArchive { get; set; }
/// <summary>
/// Optional relative path to extract the archive to, if AutoExtractArchive is true
/// </summary>
public string? ExtractRelativePath { get; set; }
[JsonIgnore]
[MemberNotNullWhen(true, nameof(ExpectedHashSha256))]
public bool ValidateHash => ExpectedHashSha256 is not null;
[JsonConverter(typeof(JsonStringEnumConverter<ProgressState>))]
public ProgressState ProgressState { get; set; } = ProgressState.Inactive;
public List<string> ExtraCleanupFileNames { get; init; } = new();
// Used for restoring progress on load
public long DownloadedBytes { get; set; }
public long TotalBytes { get; set; }
/// <summary>
/// Optional context action to be invoked on completion
/// </summary>
public IContextAction? ContextAction { get; set; }
[JsonIgnore]
public Exception? Exception { get; private set; }
private const int MaxRetryAttempts = 3;
private int attempts;
private CancellationTokenSource? retryDelayCancellationTokenSource;
#region Events
public event EventHandler<ProgressReport>? ProgressUpdate;
private void OnProgressUpdate(ProgressReport e)
{
// Update downloaded and total bytes
DownloadedBytes = Convert.ToInt64(e.Current);
TotalBytes = Convert.ToInt64(e.Total);
ProgressUpdate?.Invoke(this, e);
}
public event EventHandler<ProgressState>? ProgressStateChanging;
private void OnProgressStateChanging(ProgressState e)
{
Logger.Debug("Download {Download}: State changing to {State}", FileName, e);
ProgressStateChanging?.Invoke(this, e);
}
public event EventHandler<ProgressState>? ProgressStateChanged;
private void OnProgressStateChanged(ProgressState e)
{
Logger.Debug("Download {Download}: State changed to {State}", FileName, e);
ProgressStateChanged?.Invoke(this, e);
}
#endregion
[MemberNotNull(nameof(downloadService))]
private void EnsureDownloadService()
{
if (downloadService == null)
{
throw new InvalidOperationException("Download service is not set.");
}
}
private void CancelRetryDelay()
{
retryDelayCancellationTokenSource?.Cancel();
retryDelayCancellationTokenSource?.Dispose();
retryDelayCancellationTokenSource = null;
}
private async Task StartDownloadTask(long resumeFromByte, CancellationToken cancellationToken)
{
var progress = new Progress<ProgressReport>(OnProgressUpdate);
DownloadDirectory.Create();
await downloadService!
.ResumeDownloadToFileAsync(
SourceUrl.ToString(),
DownloadDirectory.JoinFile(TempFileName),
resumeFromByte,
progress,
cancellationToken: cancellationToken
)
.ConfigureAwait(false);
// If hash validation is enabled, validate the hash
if (ValidateHash)
{
OnProgressUpdate(new ProgressReport(0, isIndeterminate: true, type: ProgressType.Hashing));
var hash = await FileHash
.GetSha256Async(DownloadDirectory.JoinFile(TempFileName), progress)
.ConfigureAwait(false);
if (hash != ExpectedHashSha256?.ToLowerInvariant())
{
throw new Exception(
$"Hash validation for {FileName} failed, expected {ExpectedHashSha256} but got {hash}"
);
}
}
// Rename the temp file to the final file
var tempFile = DownloadDirectory.JoinFile(TempFileName);
var finalFile = tempFile.Rename(FileName);
// If auto-extract is enabled, extract the archive
if (AutoExtractArchive)
{
OnProgressUpdate(new ProgressReport(0, isIndeterminate: true, type: ProgressType.Extract));
var extractDirectory = string.IsNullOrWhiteSpace(ExtractRelativePath)
? DownloadDirectory
: DownloadDirectory.JoinDir(ExtractRelativePath);
extractDirectory.Create();
await ArchiveHelper
.Extract7Z(finalFile, extractDirectory, new Progress<ProgressReport>(OnProgressUpdate))
.ConfigureAwait(false);
}
}
/// <summary>
/// This is only intended for use by the download service.
/// Please use <see cref="TrackedDownloadService"/>.TryStartDownload instead.
/// </summary>
/// <exception cref="InvalidOperationException"></exception>
internal void Start()
{
if (ProgressState != ProgressState.Inactive && ProgressState != ProgressState.Pending)
{
throw new InvalidOperationException(
$"Download state must be inactive or pending to start, not {ProgressState}"
);
}
// Cancel any pending auto-retry delay (defensive: Start() accepts Inactive state).
CancelRetryDelay();
Logger.Debug("Starting download {Download}", FileName);
EnsureDownloadService();
downloadCancellationTokenSource = new CancellationTokenSource();
downloadPauseTokenSource = new CancellationTokenSource();
downloadTask = StartDownloadTask(0, AggregateCancellationTokenSource.Token)
.ContinueWith(OnDownloadTaskCompleted);
OnProgressStateChanging(ProgressState.Working);
ProgressState = ProgressState.Working;
OnProgressStateChanged(ProgressState);
}
internal void Resume()
{
// Cancel any pending auto-retry delay since we're resuming now.
CancelRetryDelay();
if (ProgressState != ProgressState.Inactive && ProgressState != ProgressState.Paused)
{
Logger.Warn(
"Attempted to resume download {Download} but it is not paused ({State})",
FileName,
ProgressState
);
return;
}
Logger.Debug("Resuming download {Download}", FileName);
// Read the temp file to get the current size
var tempSize = 0L;
var tempFile = DownloadDirectory.JoinFile(TempFileName);
if (tempFile.Exists)
{
tempSize = tempFile.Info.Length;
}
EnsureDownloadService();
downloadCancellationTokenSource = new CancellationTokenSource();
downloadPauseTokenSource = new CancellationTokenSource();
downloadTask = StartDownloadTask(tempSize, AggregateCancellationTokenSource.Token)
.ContinueWith(OnDownloadTaskCompleted);
OnProgressStateChanging(ProgressState.Working);
ProgressState = ProgressState.Working;
OnProgressStateChanged(ProgressState);
}
public void Pause()
{
// Cancel any pending auto-retry delay.
CancelRetryDelay();
if (ProgressState != ProgressState.Working)
{
Logger.Warn(
"Attempted to pause download {Download} but it is not in progress ({State})",
FileName,
ProgressState
);
return;
}
Logger.Debug("Pausing download {Download}", FileName);
downloadPauseTokenSource?.Cancel();
OnProgressStateChanging(ProgressState.Paused);
ProgressState = ProgressState.Paused;
OnProgressStateChanged(ProgressState);
}
public void Cancel()
{
if (ProgressState is not (ProgressState.Working or ProgressState.Inactive))
{
Logger.Warn(
"Attempted to cancel download {Download} but it is not in progress ({State})",
FileName,
ProgressState
);
return;
}
// Cancel any pending auto-retry delay.
CancelRetryDelay();
Logger.Debug("Cancelling download {Download}", FileName);
// Cancel token if it exists
if (downloadCancellationTokenSource is { } token)
{
token.Cancel();
}
// Otherwise handle it manually
else
{
DoCleanup();
OnProgressStateChanging(ProgressState.Cancelled);
ProgressState = ProgressState.Cancelled;
OnProgressStateChanged(ProgressState);
}
}
public void SetPending()
{
OnProgressStateChanging(ProgressState.Pending);
ProgressState = ProgressState.Pending;
OnProgressStateChanged(ProgressState);
}
/// <summary>
/// Deletes the temp file and any extra cleanup files
/// </summary>
private void DoCleanup()
{
try
{
DownloadDirectory.JoinFile(TempFileName).Delete();
}
catch (IOException)
{
Logger.Warn("Failed to delete temp file {TempFile}", TempFileName);
}
foreach (var extraFile in ExtraCleanupFileNames)
{
try
{
DownloadDirectory.JoinFile(extraFile).Delete();
}
catch (IOException)
{
Logger.Warn("Failed to delete extra cleanup file {ExtraFile}", extraFile);
}
}
}
/// <summary>
/// Returns true for transient network/SSL exceptions that are safe to retry (ie: VPN tunnel resets or TLS re-key failures)
/// (IOException, AuthenticationException, or either wrapped in an AggregateException).
/// </summary>
private static bool IsTransientNetworkException(Exception? ex) =>
ex is IOException or AuthenticationException
|| ex?.InnerException is IOException or AuthenticationException
|| ex is AggregateException ae
&& ae.InnerExceptions.Any(e => e is IOException or AuthenticationException);
/// <summary>
/// Invoked by the task's completion callback
/// </summary>
private void OnDownloadTaskCompleted(Task task)
{
// For cancelled, check if it was actually cancelled or paused
if (task.IsCanceled)
{
// If the task was cancelled, set the state to cancelled
if (downloadCancellationTokenSource?.IsCancellationRequested == true)
{
OnProgressStateChanging(ProgressState.Cancelled);
ProgressState = ProgressState.Cancelled;
}
// If the task was not cancelled, set the state to paused
else if (downloadPauseTokenSource?.IsCancellationRequested == true)
{
OnProgressStateChanging(ProgressState.Inactive);
ProgressState = ProgressState.Inactive;
}
else
{
throw new InvalidOperationException(
"Download task was cancelled but neither cancellation token was cancelled."
);
}
}
// For faulted
else if (task.IsFaulted)
{
// Set the exception
Exception = task.Exception;
if (IsTransientNetworkException(Exception) && attempts < MaxRetryAttempts)
{
attempts++;
Logger.Warn(
"Download {Download} failed with {Exception}, retrying ({Attempt})",
FileName,
Exception,
attempts
);
// Exponential backoff: 2 s → 4 s → 8 s, capped at 30 s, ±500 ms jitter.
// Gives the VPN tunnel time to re-key/re-route before reconnecting,
// which prevents the retry from hitting the same torn connection.
var delayMs =
(int)Math.Min(2000 * Math.Pow(2, attempts - 1), 30_000) + Random.Shared.Next(-500, 500);
Logger.Debug(
"Download {Download} retrying in {Delay}ms (attempt {Attempt}/{MaxAttempts})",
FileName,
delayMs,
attempts,
MaxRetryAttempts
);
// Persist Inactive to disk before the delay so a restart during backoff loads it as resumable.
OnProgressStateChanging(ProgressState.Inactive);
ProgressState = ProgressState.Inactive;
OnProgressStateChanged(ProgressState.Inactive);
// Clean up the completed task resources; Resume() will create new ones.
downloadTask = null;
downloadCancellationTokenSource = null;
downloadPauseTokenSource = null;
// Schedule the retry with a cancellation token so Cancel/Pause can abort the delay.
retryDelayCancellationTokenSource?.Dispose();
retryDelayCancellationTokenSource = new CancellationTokenSource();
Task.Delay(Math.Max(delayMs, 0), retryDelayCancellationTokenSource.Token)
.ContinueWith(t =>
{
if (t.IsCompletedSuccessfully)
Resume();
})
.SafeFireAndForget();
return;
}
Logger.Warn(Exception, "Download {Download} failed", FileName);
OnProgressStateChanging(ProgressState.Failed);
ProgressState = ProgressState.Failed;
}
// Otherwise success
else
{
OnProgressStateChanging(ProgressState.Success);
ProgressState = ProgressState.Success;
}
// For failed or cancelled, delete the temp files
if (ProgressState is ProgressState.Failed or ProgressState.Cancelled)
{
DoCleanup();
}
// For pause, just do nothing
OnProgressStateChanged(ProgressState);
// Dispose of the task and cancellation token
downloadTask = null;
downloadCancellationTokenSource = null;
downloadPauseTokenSource = null;
}
/// <summary>
/// Resets the retry counter and silently sets state to Inactive without firing events.
/// Must be called before re-adding to TrackedDownloadService to avoid events
/// firing while the download is absent from the dictionary.
/// </summary>
public void ResetAttempts()
{
attempts = 0;
ProgressState = ProgressState.Inactive;
}
public void SetDownloadService(IDownloadService service)
{
downloadService = service;
}
}