-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathIO.cs
240 lines (201 loc) · 8.58 KB
/
IO.cs
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
using System;
using System.Buffers;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
// ReSharper disable InconsistentNaming
// ReSharper disable AccessToModifiedClosure
namespace Hi3Helper.Http
{
internal static class IO
{
internal static async Task WriteStreamToFileChunkSessionAsync(
ChunkSession session,
DownloadSpeedLimiter? downloadSpeedLimiter,
int threadSize,
HttpResponseInputStream? networkStream,
bool isNetworkStreamFromExternal,
Stream fileStream,
DownloadProgress downloadProgress,
DownloadProgressDelegate? progressDelegateAsync,
CancellationToken token)
{
long written = 0;
long thisInstanceDownloadLimitBase = downloadSpeedLimiter?.InitialRequestedSpeed ?? -1;
int currentRetry = 0;
Stopwatch currentStopwatch = Stopwatch.StartNew();
double maximumBytesPerSecond;
double bitPerUnit;
CalculateBps();
StartWrite:
byte[] buffer = ArrayPool<byte>.Shared.Rent(16 << 10);
CancellationTokenSource? timeoutToken = null;
CancellationTokenSource? coopToken = null;
int wri = 0;
try
{
if (session.CurrentMetadata != null)
{
session.CurrentMetadata.UpdateChunkRangesCountEvent += CurrentMetadata_UpdateChunkRangesCountEvent;
}
if (downloadSpeedLimiter != null)
{
downloadSpeedLimiter.DownloadSpeedChangedEvent += DownloadClient_DownloadSpeedLimitChanged;
}
if (session.CurrentPositions.End != 0 && session.CurrentPositions.Start >= session.CurrentPositions.End)
{
return;
}
if (!isNetworkStreamFromExternal || (isNetworkStreamFromExternal && currentRetry > 0))
{
networkStream = await CreateStreamFromSessionAsync(session, token);
}
if (isNetworkStreamFromExternal && networkStream == null)
{
throw new NullReferenceException(
"networkStream argument cannot be null when isNetworkStreamFromExternal is set!");
}
if (fileStream.CanSeek && session.CurrentPositions.End + 1 > fileStream.Length)
{
fileStream.SetLength(session.CurrentPositions.Start);
}
if (fileStream.CanSeek)
{
fileStream.Seek(session.CurrentPositions.Start, SeekOrigin.Begin);
}
timeoutToken = new CancellationTokenSource(session.TimeoutAfterInterval);
coopToken = CancellationTokenSource.CreateLinkedTokenSource(timeoutToken.Token, token);
int read;
while ((read = await networkStream!.ReadAsync(buffer, coopToken.Token)) > 0)
{
await fileStream.WriteAsync(buffer, 0, read, coopToken.Token);
written += read;
wri += read;
session.CurrentPositions.AdvanceStartOffset(read);
session.CurrentMetadata?.UpdateLastEndOffset(session.CurrentPositions);
downloadProgress.AdvanceBytesDownloaded(read);
progressDelegateAsync?.Invoke(read, downloadProgress);
timeoutToken.Dispose();
coopToken.Dispose();
timeoutToken = new CancellationTokenSource(session.TimeoutAfterInterval);
coopToken = CancellationTokenSource.CreateLinkedTokenSource(timeoutToken.Token, token);
await ThrottleAsync();
currentRetry = 0;
}
}
catch (TaskCanceledException) when (token.IsCancellationRequested)
{
throw;
}
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
throw;
}
catch (NullReferenceException)
{
throw;
}
catch (Exception)
{
currentRetry++;
if (currentRetry > session.RetryMaxAttempt)
{
throw;
}
await Task.Delay(session.RetryAttemptInterval, token);
goto StartWrite;
}
finally
{
if (networkStream != null)
{
await networkStream.DisposeAsync();
}
ArrayPool<byte>.Shared.Return(buffer);
if (downloadSpeedLimiter != null)
{
downloadSpeedLimiter.DownloadSpeedChangedEvent -= DownloadClient_DownloadSpeedLimitChanged;
}
if (session.CurrentMetadata != null)
{
session.CurrentMetadata.UpdateChunkRangesCountEvent -= CurrentMetadata_UpdateChunkRangesCountEvent;
}
timeoutToken?.Dispose();
coopToken?.Dispose();
}
return;
void CalculateBps()
{
if (thisInstanceDownloadLimitBase <= 0)
thisInstanceDownloadLimitBase = -1;
else
thisInstanceDownloadLimitBase = Math.Max(DownloadClient.MinimumDownloadSpeedLimit, thisInstanceDownloadLimitBase);
double threadNum = Math.Min((double)threadSize, session.CurrentMetadata?.Ranges?.Count ?? 2);
maximumBytesPerSecond = thisInstanceDownloadLimitBase / threadNum;
bitPerUnit = 940 - (threadNum - 2) / (16 - 2) * 400;
}
void DownloadClient_DownloadSpeedLimitChanged(object? sender, long e)
{
thisInstanceDownloadLimitBase = e == 0 ? -1 : e;
CalculateBps();
}
void CurrentMetadata_UpdateChunkRangesCountEvent(object? sender, bool e)
{
CalculateBps();
}
async Task ThrottleAsync()
{
// Make sure the buffer isn't empty.
if (maximumBytesPerSecond <= 0 || written <= 0)
{
return;
}
long elapsedMilliseconds = currentStopwatch.ElapsedMilliseconds;
if (elapsedMilliseconds > 0)
{
// Calculate the current bps.
double bps = written * bitPerUnit / elapsedMilliseconds;
// If the bps are more then the maximum bps, try to throttle.
if (bps > maximumBytesPerSecond)
{
// Calculate the time to sleep.
double wakeElapsed = written * bitPerUnit / maximumBytesPerSecond;
double toSleep = wakeElapsed - elapsedMilliseconds;
if (toSleep > 1)
{
// The time to sleep is more than a millisecond, so sleep.
await Task.Delay(TimeSpan.FromMilliseconds(toSleep), token);
// A sleep has been done, reset.
currentStopwatch.Restart();
written = 0;
}
}
}
}
}
private static async ValueTask<HttpResponseInputStream?> CreateStreamFromSessionAsync(ChunkSession session,
CancellationToken token)
{
// Assign the url and throw if null
Uri? fileUri = session.CurrentMetadata?.Url;
if (fileUri == null)
{
throw new NullReferenceException("Metadata was found to be null and it shouldn't happen!");
}
// Create the network stream instance
HttpResponseInputStream? stream = await HttpResponseInputStream
.CreateStreamAsync(
session.CurrentHttpClient,
fileUri,
session.CurrentPositions.Start,
session.CurrentPositions.End,
session.TimeoutAfterInterval,
session.RetryAttemptInterval,
session.RetryMaxAttempt,
token);
// Return the stream
return stream;
}
}
}