-
Notifications
You must be signed in to change notification settings - Fork 2
/
SophonAsset.Update.cs
328 lines (302 loc) · 15.7 KB
/
SophonAsset.Update.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
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
using Hi3Helper.Sophon.Helper;
using Hi3Helper.Sophon.Structs;
using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
#if !NET6_0_OR_GREATER
using System.Threading.Tasks.Dataflow;
#endif
// ReSharper disable InvalidXmlDocComment
// ReSharper disable PossibleNullReferenceException
// ReSharper disable AccessToDisposedClosure
// ReSharper disable IdentifierTypo
// ReSharper disable ConvertIfStatementToSwitchStatement
namespace Hi3Helper.Sophon
{
public partial class SophonAsset
{
/// <summary>
/// Perform an update process to an existing or new file and run each chunk download sequentially.
/// </summary>
/// <param name="client">
/// The <see cref="HttpClient" /> to be used for downloading process.<br />Ensure that the maximum connection for the
/// <see cref="HttpClient" /> has been set to at least (Number of Threads/CPU core * 25%) or == Number of Threads/CPU
/// core
/// </param>
/// <param name="oldInputDir">
/// The directory of the old input file.
/// </param>
/// <param name="newOutputDir">
/// The directory of the new output file to be written.
/// </param>
/// <param name="chunkDir">
/// The directory of the staged chunk.
/// </param>
/// <param name="removeChunkAfterApply">
/// Remove chunk file after applying update
/// </param>
/// <param name="writeInfoDelegate">
/// <inheritdoc cref="DelegateWriteStreamInfo" />
/// </param>
/// <param name="downloadInfoDelegate">
/// <inheritdoc cref="DelegateWriteDownloadInfo" />
/// </param>
/// <param name="downloadCompleteDelegate">
/// <inheritdoc cref="DelegateDownloadAssetComplete" />
/// </param>
/// <param name="token">
/// Cancellation token for handling cancellation while the routine is running.
/// </param>
public async
#if NET6_0_OR_GREATER
ValueTask
#else
Task
#endif
WriteUpdateAsync(HttpClient client,
string oldInputDir,
string newOutputDir,
string chunkDir,
bool removeChunkAfterApply = false,
DelegateWriteStreamInfo writeInfoDelegate = null,
DelegateWriteDownloadInfo downloadInfoDelegate = null,
DelegateDownloadAssetComplete downloadCompleteDelegate = null,
CancellationToken token = default)
{
const string tempExt = "_tempUpdate";
this.EnsureOrThrowChunksState();
this.EnsureOrThrowOutputDirectoryExistence(oldInputDir);
this.EnsureOrThrowOutputDirectoryExistence(newOutputDir);
this.EnsureOrThrowOutputDirectoryExistence(chunkDir);
string outputOldPath = Path.Combine(oldInputDir, AssetName);
string outputNewPath = Path.Combine(newOutputDir, AssetName);
string outputNewTempPath = outputNewPath + tempExt;
string outputNewDir = Path.GetDirectoryName(outputNewPath);
if (!Directory.Exists(outputNewDir) && outputNewDir != null)
{
Directory.CreateDirectory(outputNewDir);
}
FileInfo outputOldFileInfo = new FileInfo(outputOldPath);
FileInfo outputNewFileInfo = new FileInfo(outputNewPath);
FileInfo outputNewTempFileInfo = new FileInfo(outputNewTempPath);
foreach (SophonChunk chunk in Chunks)
{
await InnerWriteUpdateAsync(client, chunkDir, writeInfoDelegate, downloadInfoDelegate, DownloadSpeedLimiter, outputOldFileInfo,
outputNewTempFileInfo, chunk, removeChunkAfterApply, token);
}
if (outputNewTempFileInfo.FullName != outputNewFileInfo.FullName)
{
#if NET6_0_OR_GREATER
outputNewTempFileInfo.MoveTo(outputNewFileInfo.FullName, true);
#else
outputNewFileInfo.Delete();
outputNewTempFileInfo.MoveTo(outputNewFileInfo.FullName);
#endif
}
this.PushLogInfo($"Asset: {AssetName} | (Hash: {AssetHash} -> {AssetSize} bytes) has been completely downloaded!");
downloadCompleteDelegate?.Invoke(this);
}
/// <summary>
/// Perform an update process to an existing or new file and run each chunk download in parallel instead of
/// sequentially.
/// </summary>
/// <param name="client">
/// The <see cref="HttpClient" /> to be used for downloading process.<br />Ensure that the maximum connection for the
/// <see cref="HttpClient" /> has been set to at least (Number of Threads/CPU core * 25%) or == Number of Threads/CPU
/// core
/// </param>
/// <param name="oldInputDir">
/// The directory of the old input file.
/// </param>
/// <param name="newOutputDir">
/// The directory of the new output file to be written.
/// </param>
/// <param name="chunkDir">
/// The directory of the staged chunk.
/// </param>
/// <param name="removeChunkAfterApply">
/// Remove chunk file after applying update
/// </param>
/// <param name="parallelOptions">
/// Parallelization settings to be used for downloading chunks and data hashing.
/// Remember that while using this method, the <seealso cref="CancellationToken" /> needs to be passed with
/// <c>CancellationToken</c> property.<br />
/// If it's being set to <c>null</c>, a default setting will be used as below:
/// <code>
/// CancellationToken = <paramref name="token" />,
/// MaxDegreeOfParallelism = [Number of CPU threads/cores available]
/// </code>
/// </param>
/// <param name="writeInfoDelegate">
/// <inheritdoc cref="DelegateWriteStreamInfo" />
/// </param>
/// <param name="downloadInfoDelegate">
/// <inheritdoc cref="DelegateWriteDownloadInfo" />
/// </param>
/// <param name="downloadCompleteDelegate">
/// <inheritdoc cref="DelegateDownloadAssetComplete" />
/// </param>
public async
#if NET6_0_OR_GREATER
ValueTask
#else
Task
#endif
WriteUpdateAsync(HttpClient client,
string oldInputDir,
string newOutputDir,
string chunkDir,
bool removeChunkAfterApply = false,
ParallelOptions parallelOptions = null,
DelegateWriteStreamInfo writeInfoDelegate = null,
DelegateWriteDownloadInfo downloadInfoDelegate = null,
DelegateDownloadAssetComplete downloadCompleteDelegate = null)
{
const string tempExt = "_tempUpdate";
this.EnsureOrThrowChunksState();
this.EnsureOrThrowOutputDirectoryExistence(oldInputDir);
this.EnsureOrThrowOutputDirectoryExistence(newOutputDir);
this.EnsureOrThrowOutputDirectoryExistence(chunkDir);
string outputOldPath = Path.Combine(oldInputDir, AssetName);
string outputNewPath = Path.Combine(newOutputDir, AssetName);
string outputNewTempPath = outputNewPath + tempExt;
string outputNewDir = Path.GetDirectoryName(outputNewPath);
if (!Directory.Exists(outputNewDir) && outputNewDir != null)
{
Directory.CreateDirectory(outputNewDir);
}
if (parallelOptions == null)
{
int maxChunksTask = Math.Min(8, Environment.ProcessorCount);
parallelOptions = new ParallelOptions
{
CancellationToken = default,
MaxDegreeOfParallelism = maxChunksTask
};
}
FileInfo outputOldFileInfo = new FileInfo(outputOldPath);
FileInfo outputNewFileInfo = new FileInfo(outputNewPath);
FileInfo outputNewTempFileInfo = new FileInfo(outputNewTempPath);
if (outputNewFileInfo.Exists && outputNewFileInfo.Length == AssetSize)
{
outputNewTempFileInfo = outputNewFileInfo;
}
#if !NET6_0_OR_GREATER
using (CancellationTokenSource actionToken = new CancellationTokenSource())
{
using (CancellationTokenSource linkedToken = CancellationTokenSource
.CreateLinkedTokenSource(actionToken.Token, parallelOptions.CancellationToken))
{
ActionBlock<SophonChunk> actionBlock = new ActionBlock<SophonChunk>(
async chunk =>
{
await InnerWriteUpdateAsync(client, chunkDir, writeInfoDelegate, downloadInfoDelegate, outputOldFileInfo,
outputNewTempFileInfo, chunk, linkedToken.Token);
},
new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = parallelOptions.MaxDegreeOfParallelism,
CancellationToken = linkedToken.Token
});
foreach (SophonChunk chunk in Chunks)
{
await actionBlock.SendAsync(chunk, linkedToken.Token);
}
actionBlock.Complete();
await actionBlock.Completion;
}
}
#else
await Parallel.ForEachAsync(Chunks, parallelOptions,
async (chunk, threadToken) =>
{
await InnerWriteUpdateAsync(client, chunkDir, writeInfoDelegate, downloadInfoDelegate,
DownloadSpeedLimiter, outputOldFileInfo, outputNewTempFileInfo,
chunk, removeChunkAfterApply,
threadToken);
});
#endif
if (outputNewTempFileInfo.FullName != outputNewFileInfo.FullName)
{
#if NET6_0_OR_GREATER
outputNewTempFileInfo.MoveTo(outputNewFileInfo.FullName, true);
#else
outputNewFileInfo.Delete();
outputNewTempFileInfo.MoveTo(outputNewFileInfo.FullName);
#endif
}
this.PushLogInfo($"Asset: {AssetName} | (Hash: {AssetHash} -> {AssetSize} bytes) has been completely downloaded!");
downloadCompleteDelegate?.Invoke(this);
}
private async Task InnerWriteUpdateAsync(HttpClient client,
string chunkDir,
DelegateWriteStreamInfo writeInfoDelegate,
DelegateWriteDownloadInfo downloadInfoDelegate,
SophonDownloadSpeedLimiter downloadSpeedLimiter,
FileInfo outputOldFileInfo,
FileInfo outputNewFileInfo,
SophonChunk chunk,
bool removeChunkAfterApply,
CancellationToken token)
{
Stream inputStream = null;
Stream outputStream = null;
SourceStreamType streamType = SourceStreamType.Internet;
try
{
bool isUseOldFile = chunk.ChunkOldOffset != -1 &&
outputOldFileInfo.Exists &&
outputOldFileInfo.Length >= chunk.ChunkOldOffset + chunk.ChunkSizeDecompressed;
if (isUseOldFile)
{
inputStream = outputOldFileInfo.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
streamType = SourceStreamType.OldReference;
this.PushLogDebug($"Using old file as reference at offset: 0x{chunk.ChunkOldOffset:x8} -> 0x{chunk.ChunkSizeDecompressed:x8} for: {AssetName}");
}
else
{
string cachedChunkName = chunk.GetChunkStagingFilenameHash(this);
string cachedChunkPath = Path.Combine(chunkDir, cachedChunkName);
string cachedChunkFileCheckedPath = cachedChunkPath + ".verified";
FileInfo cachedChunkInfo = new FileInfo(cachedChunkPath);
if (cachedChunkInfo.Exists && cachedChunkInfo.Length != chunk.ChunkSize)
{
cachedChunkInfo.Delete();
this.PushLogDebug($"Cached/preloaded chunk has invalid size for: {AssetName}. Expecting: 0x{chunk.ChunkSize:x8} but get: 0x{cachedChunkInfo.Length:x8} instead. Fallback to download it instead!");
}
else if (cachedChunkInfo.Exists)
{
inputStream = new FileStream(cachedChunkInfo.FullName, FileMode.Open, FileAccess.Read,
FileShare.Read, 4 << 10, removeChunkAfterApply ?
FileOptions.DeleteOnClose : FileOptions.None);
streamType = SourceStreamType.CachedLocal;
if (File.Exists(cachedChunkFileCheckedPath))
File.Delete(cachedChunkFileCheckedPath);
this.PushLogDebug($"Using cached/preloaded chunk as reference at offset: 0x{chunk.ChunkOffset:x8} -> 0x{chunk.ChunkSizeDecompressed:x8} for: {AssetName}");
}
}
outputStream = outputNewFileInfo.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
await PerformWriteStreamThreadAsync(client, inputStream, streamType, outputStream, chunk, token,
writeInfoDelegate, downloadInfoDelegate, downloadSpeedLimiter);
}
finally
{
#if NET6_0_OR_GREATER
if (inputStream != null)
{
await inputStream.DisposeAsync();
}
if (outputStream != null)
{
await outputStream.DisposeAsync();
}
#else
inputStream?.Dispose();
outputStream?.Dispose();
#endif
}
}
}
}