-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathAdaptiveUploadController.cs
More file actions
369 lines (318 loc) · 12.1 KB
/
AdaptiveUploadController.cs
File metadata and controls
369 lines (318 loc) · 12.1 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
using System.Reactive.Linq;
using ByteSync.Business.Sessions;
using ByteSync.Common.Business.Communications.Transfers;
using ByteSync.Interfaces.Controls.Communications;
using ByteSync.Interfaces.Services.Sessions;
namespace ByteSync.Services.Communications.Transfers.Uploading;
public class AdaptiveUploadController : IAdaptiveUploadController
{
// Initial configuration
private const int INITIAL_CHUNK_SIZE_BYTES = 500 * 1024; // 500 KB
private const int MIN_CHUNK_SIZE_BYTES = 64 * 1024; // 64 KB
private const int MAX_CHUNK_SIZE_BYTES = 16 * 1024 * 1024; // 16 MB
private const int MIN_PARALLELISM = 2;
private const int MAX_PARALLELISM = 4;
private const double MULTIPLIER_2_X = 2.0;
private const double MULTIPLIER_1_75_X = 1.75;
private const double MULTIPLIER_1_5_X = 1.5;
private const double MULTIPLIER_1_25_X = 1.25;
// Thresholds
private static readonly TimeSpan _upscaleThreshold = TimeSpan.FromSeconds(22);
private static readonly TimeSpan _downscaleThreshold = TimeSpan.FromSeconds(30);
// Chunk size thresholds for parallelism increases
private const int FOUR_MB = 4 * 1024 * 1024;
private const int EIGHT_MB = 8 * 1024 * 1024;
// State
private int _currentChunkSizeBytes;
private int _currentParallelism;
private readonly Queue<TimeSpan> _recentDurations;
private readonly Queue<bool> _recentSuccesses;
private readonly Queue<long> _recentBytes;
private int _successesInWindow;
private int _windowSize;
private readonly ILogger<AdaptiveUploadController> _logger;
private readonly object _syncRoot = new();
public AdaptiveUploadController(ILogger<AdaptiveUploadController> logger, ISessionService sessionService)
{
_logger = logger;
_recentDurations = new Queue<TimeSpan>();
_recentSuccesses = new Queue<bool>();
_recentBytes = new Queue<long>();
ResetState();
sessionService.SessionObservable.Subscribe(_ => { ResetState(); });
sessionService.SessionStatusObservable
.Where(status => status == SessionStatus.Preparation)
.Subscribe(_ => { ResetState(); });
}
public int CurrentChunkSizeBytes
{
get
{
lock (_syncRoot)
{
return _currentChunkSizeBytes;
}
}
}
public int CurrentParallelism
{
get
{
lock (_syncRoot)
{
return _currentParallelism;
}
}
}
public int GetNextChunkSizeBytes()
{
lock (_syncRoot)
{
return _currentChunkSizeBytes;
}
}
public void RecordUploadResult(UploadResult uploadResult)
{
lock (_syncRoot)
{
if (IsClientSideFailure(uploadResult.FailureKind))
{
return;
}
EnqueueSample(uploadResult.Elapsed, uploadResult.IsSuccess, uploadResult.ActualBytes);
if (HandleBandwidthReset(uploadResult.IsSuccess, uploadResult.StatusCode))
{
return;
}
if (_recentDurations.Count < _windowSize)
{
return;
}
var maxElapsed = GetMaxElapsedInWindow();
_logger.LogDebug(
"Adaptive: file {FileId} maxElapsed={MaxElapsedMs} ms, window={Window}, parallelism={Parallelism}, chunkSize={ChunkKb} KB",
uploadResult.FileId ?? "-",
maxElapsed.TotalMilliseconds,
_windowSize,
_currentParallelism,
Math.Round(_currentChunkSizeBytes / 1024d));
if (TryHandleDownscale(maxElapsed, uploadResult.FileId))
{
return;
}
TryHandleUpscale(uploadResult.FileId);
}
}
private void EnqueueSample(TimeSpan elapsed, bool isSuccess, long actualBytes)
{
_recentDurations.Enqueue(elapsed);
_recentSuccesses.Enqueue(isSuccess);
_recentBytes.Enqueue(actualBytes);
if (isSuccess)
{
_successesInWindow += 1;
}
while (_recentDurations.Count > _windowSize)
{
_recentDurations.Dequeue();
if (_recentSuccesses.Count > 0)
{
var removedSuccess = _recentSuccesses.Dequeue();
if (removedSuccess && _successesInWindow > 0)
{
_successesInWindow -= 1;
}
}
if (_recentBytes.Count > 0)
{
_recentBytes.Dequeue();
}
}
}
private static bool IsClientSideFailure(UploadFailureKind failureKind)
{
return failureKind is UploadFailureKind.ClientCancellation or UploadFailureKind.ClientTimeout;
}
private bool HandleBandwidthReset(bool isSuccess, int? statusCode)
{
if (!isSuccess && statusCode != null)
{
if (statusCode == 429 || statusCode == 500 || statusCode == 503 || statusCode == 507)
{
_logger.LogWarning("Adaptive: bandwidth error status {Status}. Resetting chunk size to {InitialKb} KB (was {PrevKb} KB)",
statusCode, INITIAL_CHUNK_SIZE_BYTES / 1024, _currentChunkSizeBytes / 1024);
_currentChunkSizeBytes = Math.Clamp(INITIAL_CHUNK_SIZE_BYTES, MIN_CHUNK_SIZE_BYTES, MAX_CHUNK_SIZE_BYTES);
ResetWindow();
return true;
}
}
return false;
}
private TimeSpan GetMaxElapsedInWindow()
{
var maxElapsed = TimeSpan.Zero;
foreach (var recentDuration in _recentDurations)
{
if (recentDuration > maxElapsed)
{
maxElapsed = recentDuration;
}
}
return maxElapsed;
}
private bool TryHandleDownscale(TimeSpan maxElapsed, string? fileId)
{
if (maxElapsed > _downscaleThreshold)
{
if (_currentParallelism > MIN_PARALLELISM)
{
_logger.LogInformation(
"Adaptive: file {FileId} Downscale. Reducing parallelism {Prev} -> {Next}. Resetting window (window before {WindowBefore})",
fileId ?? "-",
_currentParallelism, _currentParallelism - 1,
_windowSize);
_currentParallelism -= 1;
_windowSize = _currentParallelism;
ResetWindow();
return true;
}
var reduced = (int)Math.Max(MIN_CHUNK_SIZE_BYTES, _currentChunkSizeBytes * 0.75);
if (reduced != _currentChunkSizeBytes)
{
_currentChunkSizeBytes = reduced;
_logger.LogInformation(
"Adaptive: file {FileId} Downscale. maxElapsed={MaxElapsedMs} ms > {ThresholdMs} ms. New chunkSize={ChunkKb} KB",
fileId ?? "-",
maxElapsed.TotalMilliseconds,
_downscaleThreshold.TotalMilliseconds,
Math.Round(_currentChunkSizeBytes / 1024d));
}
ResetWindow();
return true;
}
return false;
}
private void TryHandleUpscale(string? fileId)
{
var recentDurations = _recentDurations.ToArray();
var recentSuccesses = _recentSuccesses.ToArray();
var recentBytes = _recentBytes.ToArray();
var minEligibleBytes = (long)Math.Floor(_currentChunkSizeBytes * 0.9);
var eligibleIndexes = new List<int>();
for (var i = 0; i < recentDurations.Length && i < recentSuccesses.Length && i < recentBytes.Length; i++)
{
var chunkBytes = recentBytes[i];
if (chunkBytes < 0)
{
chunkBytes = _currentChunkSizeBytes;
}
if (chunkBytes >= minEligibleBytes)
{
eligibleIndexes.Add(i);
}
}
if (eligibleIndexes.Count >= _windowSize)
{
var start = eligibleIndexes.Count - _windowSize;
var maxElapsedEligible = TimeSpan.Zero;
var eligibleSuccesses = 0;
for (var k = start; k < eligibleIndexes.Count; k++)
{
var idx = eligibleIndexes[k];
var d = recentDurations[idx];
if (d > maxElapsedEligible)
{
maxElapsedEligible = d;
}
if (recentSuccesses[idx])
{
eligibleSuccesses++;
}
}
if (maxElapsedEligible <= _upscaleThreshold && eligibleSuccesses >= _windowSize)
{
var multiplier = GetUpscaleMultiplier(maxElapsedEligible);
var increased = (int)Math.Round(_currentChunkSizeBytes * multiplier);
_currentChunkSizeBytes = Math.Clamp(increased, MIN_CHUNK_SIZE_BYTES, MAX_CHUNK_SIZE_BYTES);
_logger.LogInformation(
"Adaptive: file {FileId} Upscale. maxElapsed={MaxElapsedMs} ms <= {ThresholdMs} ms. New chunkSize={ChunkKb} KB",
fileId ?? "-",
maxElapsedEligible.TotalMilliseconds,
_upscaleThreshold.TotalMilliseconds,
Math.Round(_currentChunkSizeBytes / 1024d));
UpdateParallelismOnUpscale(fileId);
_currentParallelism = Math.Min(_currentParallelism, MAX_PARALLELISM);
_windowSize = _currentParallelism;
ResetWindow();
}
}
}
private static double GetUpscaleMultiplier(TimeSpan maxElapsedEligible)
{
if (maxElapsedEligible < TimeSpan.FromSeconds(1))
{
return MULTIPLIER_2_X;
}
if (maxElapsedEligible < TimeSpan.FromSeconds(3))
{
return MULTIPLIER_1_75_X;
}
if (maxElapsedEligible < TimeSpan.FromSeconds(10))
{
return MULTIPLIER_1_5_X;
}
return MULTIPLIER_1_25_X;
}
private void UpdateParallelismOnUpscale(string? fileId)
{
if (_currentChunkSizeBytes >= EIGHT_MB)
{
var prev = _currentParallelism;
_currentParallelism = Math.Max(_currentParallelism, 4);
if (_currentParallelism != prev)
{
_logger.LogInformation("Adaptive: file {FileId} Upscale. Increasing parallelism {Prev} -> {Next} due to chunk>=8MB",
fileId ?? "-", prev, _currentParallelism);
}
}
else if (_currentChunkSizeBytes >= FOUR_MB)
{
var prev = _currentParallelism;
_currentParallelism = Math.Max(_currentParallelism, 3);
if (_currentParallelism != prev)
{
_logger.LogInformation("Adaptive: file {FileId} Upscale. Increasing parallelism {Prev} -> {Next} due to chunk>=4MB",
fileId ?? "-", prev, _currentParallelism);
}
}
}
private void ResetWindow()
{
lock (_syncRoot)
{
while (_recentDurations.Count > 0)
{
_recentDurations.Dequeue();
}
while (_recentSuccesses.Count > 0)
{
_recentSuccesses.Dequeue();
}
while (_recentBytes.Count > 0)
{
_recentBytes.Dequeue();
}
_successesInWindow = 0;
}
}
private void ResetState()
{
lock (_syncRoot)
{
_currentChunkSizeBytes = Math.Clamp(INITIAL_CHUNK_SIZE_BYTES, MIN_CHUNK_SIZE_BYTES, MAX_CHUNK_SIZE_BYTES);
_currentParallelism = MIN_PARALLELISM;
_windowSize = _currentParallelism;
}
ResetWindow();
}
}