-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathGeneralUpdateBootstrap.cs
More file actions
673 lines (608 loc) · 30.7 KB
/
Copy pathGeneralUpdateBootstrap.cs
File metadata and controls
673 lines (608 loc) · 30.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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using GeneralUpdate.Core.FileSystem;
using GeneralUpdate.Core.Download;
using GeneralUpdate.Core.Event;
using GeneralUpdate.Core.Configuration;
using GeneralUpdate.Core.Strategy;
using GeneralUpdate.Core.Ipc;
using GeneralUpdate.Core.Differential;
using GeneralUpdate.Core.Pipeline;
using GeneralUpdate.Core.Network;
using GeneralUpdate.Differential.Differ;
namespace GeneralUpdate.Core;
/// <summary>
/// Unified update entry point for all application update scenarios.
/// Configure the update via fluent methods, then call <see cref="LaunchAsync"/> to execute.
/// </summary>
/// <remarks>
/// <para><b>Core flow:</b></para>
/// <para>
/// 1. <b>Configuration</b> — <see cref="SetConfig(UpdateRequest)"/> loads parameters (versions, paths, URLs).<br/>
/// 2. <b>Extension resolution</b> — <see cref="LaunchWithStrategy"/> resolves all registered
/// extension points (strategy, hooks, download components, network policies) and injects
/// them into the role strategy.<br/>
/// 3. <b>Role dispatch</b> — <see cref="AppType"/> selects the role strategy:<br/>
/// • <see cref="AppType.Client"/> — validates against server, downloads packages,
/// applies upgrade packages in-place, serializes client packages to IPC, and launches
/// the upgrade process.<br/>
/// • <see cref="AppType.Upgrade"/> — reads IPC data, applies client packages via the
/// OS pipeline, then starts the main application.<br/>
/// • <see cref="AppType.OssClient"/>/<see cref="AppType.OssUpgrade"/> — Oss-based
/// workflow for cloud storage (AliYun, AWS S3, MinIO).<br/>
/// 4. <b>Platform resolution</b> — <see cref="ClientStrategy.ResolveOsStrategy"/>
/// detects the OS and creates <c>WindowsStrategy</c>, <c>LinuxStrategy</c>, or
/// <c>MacStrategy</c> unless overridden via <c>Strategy<T>()</c>.<br/>
/// 5. <b>Pipeline execution</b> — the OS strategy runs <c>HashMiddleware → CompressMiddleware
/// → PatchMiddleware</c> for each update version.<br/>
/// 6. <b>App launch</b> — the OS strategy starts the updated main application.
/// </para>
/// <para><b>Silent mode:</b> when <c>Option(Option.Silent, true)</c> is set on
/// <see cref="AppType.Client"/>, launches a background poll loop via
/// <see cref="Silent.SilentPollOrchestrator"/> and returns immediately. Updates are
/// prepared on process exit.</para>
/// <para><b>Extension points:</b> <see cref="AbstractBootstrap{TBootstrap, TStrategy}"/>
/// provides fluent methods for injecting custom implementations of hooks, download
/// components, network policies, and OS strategy.</para>
/// </remarks>
/// <example>
/// <para><b>Standard flow (Client):</b></para>
/// <code>
/// var result = await new GeneralUpdateBootstrap()
/// .SetSource("https://api.example.com", "my-key")
/// .SetOption(Option.AppType, AppType.Client)
/// .Hooks<MyCustomHooks>()
/// .LaunchAsync();
/// </code>
/// <para><b>OSS flow (Object Storage Service):</b></para>
/// <code>
/// // OssClient — only secrets in code; identity from generalupdate.manifest.json
/// var result = await new GeneralUpdateBootstrap()
/// .SetSource("https://oss.example.com/versions.json", "my-key")
/// .SetOption(Option.AppType, AppType.OssClient)
/// .Hooks<MyCustomHooks>()
/// .LaunchAsync();
///
/// // OssUpgrade — running from a subdirectory; pass installPath to locate
/// // generalupdate.manifest.json in the parent directory
/// var installPath = Path.GetFullPath(Path.Combine(baseDir, ".."));
/// var result = await new GeneralUpdateBootstrap()
/// .SetSource("https://oss.example.com/versions.json", "my-key",
/// installPath: installPath)
/// .SetOption(Option.AppType, AppType.OssUpgrade)
/// .Hooks<MyCustomHooks>()
/// .LaunchAsync();
/// </code>
/// </example>
public class GeneralUpdateBootstrap : AbstractBootstrap<GeneralUpdateBootstrap, IStrategy>
{
private UpdateContext _configInfo = new();
private Func<UpdateInfoEventArgs, bool>? _updatePrecheck;
private CancellationTokenSource? _cts;
private DiffPipelineBuilder? _diffPipelineBuilder;
private Silent.SilentPollOrchestrator? _silentOrchestrator;
private List<string> _syncedCustomHeaders = new();
/// <summary>
/// When silent mode is active, provides access to the background polling orchestrator.
/// Returns <c>null</c> in non-silent modes or before <see cref="LaunchAsync"/> is called.
/// </summary>
public Silent.SilentPollOrchestrator? SilentOrchestrator => _silentOrchestrator;
public GeneralUpdateBootstrap()
{
InitializeFromEnvironment();
}
/// <summary>Cancel the current update operation.</summary>
/// <remarks>
/// Signals the internal <see cref="CancellationTokenSource"/> to request cancellation
/// of the ongoing update workflow. After calling this method, the running strategy
/// (e.g., <see cref="ClientStrategy"/>) will observe the cancellation
/// token and terminate the current operation at the next safe checkpoint.
/// A cancellation message is also written to the trace log.
/// </remarks>
public void Cancel()
{
_cts?.Cancel();
GeneralTracer.Info("GeneralUpdateBootstrap: cancellation requested.");
}
/// <summary>
/// Dispatches the update workflow based on <see cref="AppType"/>.
/// <see cref="AppType.Client"/> with silent mode returns immediately after starting a
/// background poll; all other modes run synchronously.
/// </summary>
/// <returns>This bootstrap instance for chaining.</returns>
public override async Task<GeneralUpdateBootstrap> LaunchAsync()
{
var appType = GetOption(Option.AppType);
_configInfo.AppType = appType;
// Silent mode: start background poll and return immediately
if (appType == AppType.Client && GetOption(Option.Silent))
{
await LaunchSilentAsync().ConfigureAwait(false);
return this;
}
return appType switch
{
AppType.Client => await LaunchWithStrategy(new ClientStrategy()),
AppType.Upgrade => await LaunchWithStrategy(new UpdateStrategy()),
AppType.OssClient => await LaunchWithStrategy(new OssStrategy(AppType.OssClient)),
AppType.OssUpgrade => await LaunchWithStrategy(new OssStrategy(AppType.OssUpgrade)),
_ => await LaunchWithStrategy(new ClientStrategy())
};
}
private async Task<GeneralUpdateBootstrap> LaunchWithStrategy(IStrategy roleStrategy)
{
_cts = new CancellationTokenSource();
var token = _cts.Token;
try
{
token.ThrowIfCancellationRequested();
ApplyRuntimeOptions();
// ── Network-level extensions (global, applied before any HTTP call) ──
var sslPolicy = ResolveExtension<Security.ISslValidationPolicy>();
if (sslPolicy != null)
{
Network.HttpClientProvider.SetSslValidationPolicy(sslPolicy);
}
var authProvider = ResolveExtension<Security.IHttpAuthProvider>();
if (authProvider != null) Network.VersionService.SetDefaultAuthProvider(authProvider);
ConfigureStrategy(roleStrategy);
roleStrategy.Create(_configInfo);
await roleStrategy.ExecuteAsync();
}
catch (Exception ex)
{
GeneralTracer.Error("LaunchWithStrategy failed.", ex);
EventManager.Instance.Dispatch(this, new ExceptionEventArgs(ex, ex.Message));
}
finally
{
_cts?.Dispose();
_cts = null;
}
return this;
}
/// <summary>
/// Applies the primary configuration object. Validates required fields, maps to
/// the internal <see cref="UpdateContext"/>, and initialises the blacklist
/// matcher for file exclusion during update operations.
/// </summary>
/// <param name="configInfo">User-facing configuration. All required fields must
/// be set explicitly — no auto-discovery is performed. Use
/// <see cref="SetSource"/> for the zero-config path.</param>
/// <returns>This bootstrap instance for chaining.</returns>
public GeneralUpdateBootstrap SetConfig(UpdateRequest configInfo)
{
configInfo.Validate();
_configInfo = ConfigurationMapper.MapToUpdateContext(configInfo);
// Sync custom headers to the global HTTP client so they are applied
// to every request (Verification + Report) without manual extra setup.
// First clear stale headers from a previous SetConfig call, then apply
// the current ones — avoids leaking headers between bootstrap instances.
var oldHeaders = _syncedCustomHeaders;
_syncedCustomHeaders = new List<string>();
foreach (var key in oldHeaders)
HttpClientProvider.ExtraHeaders.TryRemove(key, out _);
if (_configInfo.CustomHeaders is { Count: > 0 })
{
foreach (var kv in _configInfo.CustomHeaders)
{
HttpClientProvider.ExtraHeaders[kv.Key] = kv.Value;
_syncedCustomHeaders.Add(kv.Key);
}
}
var appType = GetOption(Option.AppType);
if (appType != AppType.Upgrade)
{
// Cleanup temp directories from previous runs (older than 24h) to
// prevent disk accumulation from silent-mode polling or crashes.
StorageManager.CleanupOldTempDirectories();
_configInfo.TempPath = StorageManager.GetTempDirectory("upgrade_temp");
InitBlackPolicy();
}
return this;
}
/// <summary>
/// Load configuration from a local JSON file.
/// </summary>
/// <param name="filePath">
/// Config file path.
/// If just a filename (no directory separator), resolves relative to the current directory.
/// Relative or absolute paths are used as-is.
/// </param>
/// <returns>This bootstrap instance for chaining.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="filePath"/> is <c>null</c> or whitespace.</exception>
/// <exception cref="FileNotFoundException">Thrown when the specified file does not exist.</exception>
/// <exception cref="InvalidOperationException">Thrown when the JSON file cannot be deserialised into a valid <see cref="UpdateRequest"/>.</exception>
/// <remarks>
/// Reads the file content as UTF-8 JSON, deserialises it into a <see cref="UpdateRequest"/>
/// using the source-generated JSON serialisation context (<see cref="JsonContext.HttpParameterJsonContext"/>),
/// then delegates to <see cref="SetConfig(UpdateRequest)"/> for validation and mapping.
/// </remarks>
public GeneralUpdateBootstrap SetConfig(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
throw new ArgumentNullException(nameof(filePath));
// Resolve filename-only paths to current directory
var hasPathChar = filePath.Contains(Path.DirectorySeparatorChar)
|| filePath.Contains(Path.AltDirectorySeparatorChar);
var fullPath = hasPathChar
? Path.GetFullPath(filePath)
: Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filePath);
if (!File.Exists(fullPath))
throw new FileNotFoundException($"Config file not found: {fullPath}");
var json = File.ReadAllText(fullPath);
var config = JsonSerializer.Deserialize(json, JsonContext.HttpParameterJsonContext.Default.UpdateRequest);
if (config == null)
throw new InvalidOperationException($"Failed to parse config file: {fullPath}");
return SetConfig(config);
}
/// <summary>
/// Zero-config entry-point: supply only secrets. Provides sensible identity defaults
/// that pass <see cref="UpdateRequest.Validate"/>; the real identity metadata is
/// discovered later by <see cref="ClientStrategy"/> or <see cref="OssStrategy"/>
/// from <c>generalupdate.manifest.json</c>. Works with all <see cref="AppType"/>
/// modes (<c>Client</c>, <c>Upgrade</c>, <c>OssClient</c>, <c>OssUpgrade</c>).
/// </summary>
/// <param name="updateUrl">The remote endpoint for update validation or version config retrieval.</param>
/// <param name="appSecretKey">The application secret key used for authentication.</param>
/// <param name="reportUrl">Optional URL for reporting update status back to the server.</param>
/// <param name="scheme">Optional URL scheme override (e.g. <c>"https"</c>).</param>
/// <param name="token">Optional authentication token for API requests.</param>
/// <param name="authScheme">Explicitly selects the HTTP authentication method. Defaults to <see cref="Security.AuthScheme.Hmac"/>.</param>
/// <param name="basicUsername">Optional username for HTTP Basic Authentication.</param>
/// <param name="basicPassword">Optional password for HTTP Basic Authentication.</param>
/// <param name="installPath">
/// Optional override for the installation root directory. When <c>null</c>,
/// defaults to <see cref="AppDomain.CurrentDomain.BaseDirectory"/>. Set this when
/// the current process runs from a subdirectory (e.g. the OSS upgrade process in
/// <c>update/</c>) and <c>generalupdate.manifest.json</c> lives in the parent.
/// </param>
/// <returns>This bootstrap instance for chaining.</returns>
public GeneralUpdateBootstrap SetSource(
string updateUrl,
string appSecretKey,
string? reportUrl = null,
string? scheme = null,
string? token = null,
Security.AuthScheme authScheme = Security.AuthScheme.Hmac,
string? basicUsername = null,
string? basicPassword = null,
string? installPath = null)
{
var config = new UpdateRequest
{
UpdateUrl = updateUrl,
AppSecretKey = appSecretKey,
Token = token,
Scheme = scheme,
AuthScheme = authScheme,
BasicUsername = basicUsername,
BasicPassword = basicPassword,
ReportUrl = reportUrl
};
if (installPath != null)
config.InstallPath = installPath;
return SetConfig(config);
}
/// <summary>
/// Configure the <see cref="DiffPipeline"/> via a fluent builder action.
/// If not called, a default pipeline is built with <see cref="BsdiffDiffer"/>,
/// <see cref="DefaultDirtyMatcher"/>, <see cref="DefaultCleanMatcher"/>,
/// and max parallelism of 2.
/// </summary>
public GeneralUpdateBootstrap UseDiffPipeline(Action<DiffPipelineBuilder>? configure)
{
var builder = new DiffPipelineBuilder();
configure?.Invoke(builder);
_diffPipelineBuilder = builder;
return this;
}
/// <summary>
/// Registers a pre-check callback that is invoked after update information is retrieved
/// but before downloads begin. The callback can inspect the metadata and decide whether
/// to proceed with or abort the update.
/// </summary>
/// <param name="func">A predicate that receives <see cref="UpdateInfoEventArgs"/>
/// and returns <c>true</c> to continue or <c>false</c> to abort the update.</param>
/// <returns>This bootstrap instance for chaining.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="func"/> is <c>null</c>.</exception>
/// <remarks>
/// The pre-check function is called during the client update strategy's standard workflow,
/// immediately after version comparison and before any packages are downloaded.
/// This allows conditional update logic, such as skipping updates under certain
/// network conditions or user preferences.
/// </remarks>
public GeneralUpdateBootstrap AddListenerUpdatePrecheck(Func<UpdateInfoEventArgs, bool> func)
{
_updatePrecheck = func ?? throw new ArgumentNullException(nameof(func));
return this;
}
// ════════════════════════════════════════════════════════════════
// Helpers
// ════════════════════════════════════════════════════════════════
private void InitializeFromEnvironment()
{
// Read ProcessContract via AES-encrypted file IPC.
// The Upgrade process is only ever launched by the Client — no IPC means
// there is nothing to do. The Client's manifest.json flows through IPC,
// so the Upgrade never needs to load one directly.
ProcessContract? processInfo;
try
{
processInfo = new EncryptedFileProcessContractProvider().Receive();
}
catch (Exception ex)
{
// Corrupted / unreadable IPC file (e.g. leftover from a crashed
// previous run, or parallel test execution) — treat as "no IPC data".
GeneralTracer.Warn($"Failed to read IPC process contract: {ex.Message}");
return;
}
if (processInfo == null) return;
try
{
var encoding = !string.IsNullOrEmpty(processInfo.CompressEncoding)
? Encoding.GetEncoding(processInfo.CompressEncoding)
: Encoding.UTF8;
_configInfo = new UpdateContext
{
MainAppName = processInfo.AppName,
InstallPath = processInfo.InstallPath,
ClientVersion = processInfo.CurrentVersion,
LastVersion = processInfo.LastVersion,
UpdateLogUrl = processInfo.UpdateLogUrl,
Encoding = encoding,
Format = ParseFormat(processInfo.CompressFormat),
DownloadTimeOut = processInfo.DownloadTimeOut,
AppSecretKey = processInfo.AppSecretKey,
UpdateVersions = processInfo.UpdateVersions,
TempPath = processInfo.TempPath,
ReportUrl = processInfo.ReportUrl,
BackupDirectory = processInfo.BackupDirectory,
Scheme = processInfo.Scheme,
Token = processInfo.Token,
AuthScheme = processInfo.AuthScheme,
BasicUsername = processInfo.BasicUsername,
BasicPassword = processInfo.BasicPassword,
DriverDirectory = processInfo.DriverDirectory,
UpdatePath = processInfo.UpdatePath,
LaunchClientAfterUpdate = processInfo.LaunchClientAfterUpdate,
ReportType = processInfo.ReportType,
Files = processInfo.Files ?? BlackDefaults.DefaultFiles,
Formats = processInfo.Formats ?? BlackDefaults.DefaultFormats,
Directories = processInfo.Directories ?? BlackDefaults.DefaultDirectories
};
StorageManager.BlackMatcher = BlackMatcher.FromConfigInfo(_configInfo);
}
catch (Exception ex)
{
// Corrupted / incompatible IPC data (e.g. from a mismatched version
// of the sender, or stale test data) — treat as "no IPC data".
GeneralTracer.Warn($"Failed to map IPC process contract: {ex.Message}");
}
}
/// <summary>
/// Applies Option to _configInfo.
/// Uses ??= only for values that InitializeFromEnvironment() may have already
/// populated on the Upgrade path (Encoding, Format, DownloadTimeOut).
/// All other options are always applied from Option — their defaults
/// are already functionally reasonable (e.g. MaxConcurrency=3, RetryCount=3).
/// </summary>
private void ApplyRuntimeOptions()
{
// Preserve Upgrade path values set by InitializeFromEnvironment()
_configInfo.Encoding ??= GetOption(Option.Encoding);
_configInfo.Format = GetOption(Option.Format);
if (_configInfo.DownloadTimeOut <= 0)
_configInfo.DownloadTimeOut = GetOption(Option.DownloadTimeout) ?? 60;
// bool? options: use ??= so user-configured false is preserved
_configInfo.PatchEnabled ??= GetOption(Option.PatchEnabled);
_configInfo.BackupEnabled ??= GetOption(Option.BackupEnabled);
// Always apply from Option — no other code sets these before
// ApplyRuntimeOptions() runs. Defaults are functionally reasonable.
_configInfo.MaxConcurrency = GetOption(Option.MaxConcurrency);
_configInfo.EnableResume = GetOption(Option.EnableResume);
_configInfo.RetryCount = GetOption(Option.RetryCount);
_configInfo.RetryInterval = GetOption(Option.RetryInterval);
_configInfo.VerifyChecksum = GetOption(Option.VerifyChecksum);
_configInfo.DiffMode = GetOption(Option.DiffMode);
}
/// <summary>
/// Silent update mode — starts a background poll loop and returns immediately.
/// Uses the same fully-configured <see cref="ClientStrategy"/> as the standard flow;
/// the orchestrator only adds polling and deferred-upgrade-on-exit on top.
/// </summary>
private async Task<GeneralUpdateBootstrap> LaunchSilentAsync()
{
GeneralTracer.Info("GeneralUpdateBootstrap: starting silent update mode.");
ApplyRuntimeOptions();
// Network-level extensions (global, applied before any HTTP call)
var sslPolicy = ResolveExtension<Security.ISslValidationPolicy>();
if (sslPolicy != null)
{
Network.HttpClientProvider.SetSslValidationPolicy(sslPolicy);
}
var authProvider = ResolveExtension<Security.IHttpAuthProvider>();
if (authProvider != null) Network.VersionService.SetDefaultAuthProvider(authProvider);
var strategy = new ClientStrategy();
ConfigureStrategy(strategy);
strategy.LaunchAfterPrepare = false;
var pollMinutes = GetOption(Option.SilentPollIntervalMinutes);
var launchClient = GetOption(Option.LaunchClientAfterUpdate);
var silentOptions = new Silent.SilentOptions
{
PollInterval = TimeSpan.FromMinutes(pollMinutes),
LaunchClientAfterUpdate = launchClient
};
var orchestrator = new Silent.SilentPollOrchestrator(strategy, _configInfo, silentOptions);
_silentOrchestrator = orchestrator;
await orchestrator.StartAsync().ConfigureAwait(false);
GeneralTracer.Info("GeneralUpdateBootstrap: silent update mode started, returning to caller.");
return this;
}
/// <summary>
/// Applies all registered extensions (hooks, reporter, download components,
/// DiffPipeline, custom OS strategy) to a role strategy. Shared by the standard
/// and silent boot paths so they are always configured identically.
/// </summary>
private void ConfigureStrategy(IStrategy roleStrategy)
{
var hooks = ResolveExtension<Hooks.IUpdateHooks>() ?? new Hooks.NoOpUpdateHooks();
roleStrategy.Hooks = hooks;
var reporter = ResolveExtension<Download.Reporting.IUpdateReporter>() ??
new Download.Reporting.HttpUpdateReporter();
if (reporter is Download.Reporting.HttpUpdateReporter httpReporter)
httpReporter.ReportUrl = _configInfo.ReportUrl;
roleStrategy.Reporter = reporter;
var diffPipeline = BuildDiffPipeline();
// Download components
var downloadOrchestrator = ResolveExtension<Download.Abstractions.IDownloadOrchestrator>();
var downloadPolicy = ResolveExtension<Download.Abstractions.IDownloadPolicy>();
var downloadExecutor = ResolveExtension<Download.Abstractions.IDownloadExecutor>();
Func<string?, Download.Abstractions.IDownloadPipeline>? downloadPipelineFactory = null;
var downloadPipeline = ResolveExtension<Download.Abstractions.IDownloadPipeline>();
if (downloadPipeline != null)
downloadPipelineFactory = _ => downloadPipeline;
switch (roleStrategy)
{
case ClientStrategy cs:
cs.DownloadSource = ResolveExtension<Download.Abstractions.IDownloadSource>();
cs.SetDiffPipeline(diffPipeline);
if (downloadOrchestrator != null) cs.SetOrchestrator(downloadOrchestrator);
if (downloadPolicy != null) cs.SetDownloadPolicy(downloadPolicy);
if (downloadExecutor != null) cs.SetDownloadExecutor(downloadExecutor);
if (downloadPipelineFactory != null) cs.SetDownloadPipelineFactory(downloadPipelineFactory);
if (_updatePrecheck != null) cs.UseUpdatePrecheck(_updatePrecheck);
break;
case UpdateStrategy us:
us.SetDiffPipeline(diffPipeline);
us.SetReportType(_configInfo.ReportType);
break;
}
// Custom OS-level strategy (registered via Strategy<T>())
var customOsStrategy = ResolveExtension<IStrategy>();
if (customOsStrategy != null)
{
switch (roleStrategy)
{
case ClientStrategy cs: cs.SetOsStrategy(customOsStrategy); break;
case UpdateStrategy us: us.SetOsStrategy(customOsStrategy); break;
}
}
}
private DiffPipeline BuildDiffPipeline()
{
if (_diffPipelineBuilder != null)
return _diffPipelineBuilder.Build();
return new DiffPipelineBuilder()
.UseDiffer(new BsdiffDiffer())
.UseCleanMatcher(new DefaultCleanMatcher())
.UseDirtyMatcher(new DefaultDirtyMatcher())
.WithParallelism(2)
.WithProgress(new DiffProgressReporter(this))
.Build();
}
private static Format ParseFormat(string? compressFormat)
{
if (string.IsNullOrWhiteSpace(compressFormat)) return Format.Zip;
return compressFormat switch
{
".zip" => Format.Zip,
_ => Format.Zip
};
}
private void InitBlackPolicy()
{
StorageManager.BlackMatcher = new BlackMatcher(
BlackDefaults.CreatePolicyWithDefaults(
_configInfo.Files,
_configInfo.Formats,
_configInfo.Directories
));
}
// ════════════════════════════════════════════════════════════════
// Strategy & Events
// ════════════════════════════════════════════════════════════════
private GeneralUpdateBootstrap AddListener<TArgs>(Action<object, TArgs> action) where TArgs : EventArgs
{
if (action is null) throw new ArgumentNullException(nameof(action));
EventManager.Instance.AddListener(action);
return this;
}
/// <summary>
/// Registers a callback for the multi-all-download-completed event, raised when all
/// update files across all versions have been downloaded.
/// </summary>
/// <param name="cb">The callback to invoke.</param>
/// <returns>This bootstrap instance for chaining.</returns>
public GeneralUpdateBootstrap AddListenerMultiAllDownloadCompleted(
Action<object, MultiAllDownloadCompletedEventArgs> cb) => AddListener(cb);
/// <summary>
/// Registers a callback for the multi-download-completed event, raised when a single
/// version's set of files has finished downloading.
/// </summary>
/// <param name="cb">The callback to invoke.</param>
/// <returns>This bootstrap instance for chaining.</returns>
public GeneralUpdateBootstrap AddListenerMultiDownloadCompleted(
Action<object, MultiDownloadCompletedEventArgs> cb) => AddListener(cb);
/// <summary>
/// Registers a callback for the multi-download-error event, raised when an error
/// occurs during batch download.
/// </summary>
/// <param name="cb">The callback to invoke.</param>
/// <returns>This bootstrap instance for chaining.</returns>
public GeneralUpdateBootstrap AddListenerMultiDownloadError(
Action<object, MultiDownloadErrorEventArgs> cb) => AddListener(cb);
/// <summary>
/// Registers a callback for download statistics events, providing real-time throughput
/// and progress information during batch downloads.
/// </summary>
/// <param name="cb">The callback to invoke.</param>
/// <returns>This bootstrap instance for chaining.</returns>
public GeneralUpdateBootstrap AddListenerMultiDownloadStatistics(
Action<object, MultiDownloadStatisticsEventArgs> cb) => AddListener(cb);
/// <summary>
/// Registers a callback for exception events raised during the update workflow.
/// </summary>
/// <param name="cb">The callback to invoke.</param>
/// <returns>This bootstrap instance for chaining.</returns>
public GeneralUpdateBootstrap AddListenerException(
Action<object, ExceptionEventArgs> cb) => AddListener(cb);
/// <summary>
/// Registers a callback for update-information events, providing version metadata
/// retrieved from the server.
/// </summary>
/// <param name="cb">The callback to invoke.</param>
/// <returns>This bootstrap instance for chaining.</returns>
public GeneralUpdateBootstrap AddListenerUpdateInfo(
Action<object, UpdateInfoEventArgs> cb) => AddListener(cb);
/// <summary>
/// Registers a callback for general progress events during the update process.
/// </summary>
/// <param name="cb">The callback to invoke.</param>
/// <returns>This bootstrap instance for chaining.</returns>
public GeneralUpdateBootstrap AddListenerProgress(
Action<object, ProgressEventArgs> cb) => AddListener(cb);
/// <summary>
/// Batch-register an event listener implementing <see cref="IUpdateEventListener"/>.
/// All 7 event handlers are registered at once.
/// </summary>
public GeneralUpdateBootstrap AddEventListener<TListener>() where TListener : IUpdateEventListener, new()
{
var listener = new TListener();
AddListener<MultiAllDownloadCompletedEventArgs>((s, e) => listener.OnAllDownloadCompleted(e));
AddListener<MultiDownloadCompletedEventArgs>((s, e) => listener.OnDownloadCompleted(e));
AddListener<MultiDownloadErrorEventArgs>((s, e) => listener.OnDownloadError(e));
AddListener<MultiDownloadStatisticsEventArgs>((s, e) => listener.OnDownloadStatistics(e));
AddListener<UpdateInfoEventArgs>((s, e) => listener.OnUpdateInfo(e));
AddListener<ExceptionEventArgs>((s, e) => listener.OnException(e));
AddListener<ProgressEventArgs>((s, e) => listener.OnProgress(e));
return this;
}
}