-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathGeneralUpdateBootstrap.cs
More file actions
452 lines (394 loc) · 20 KB
/
Copy pathGeneralUpdateBootstrap.cs
File metadata and controls
452 lines (394 loc) · 20 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
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.JsonContext;
using GeneralUpdate.Core.Strategy;
using GeneralUpdate.Core.Network;
using GeneralUpdate.Core.Hooks;
using GeneralUpdate.Core.Ipc;
using GeneralUpdate.Core.Download.Reporting;
using GeneralUpdate.Core.Differential;
using GeneralUpdate.Core.Pipeline;
using GeneralUpdate.Differential.Abstractions;
using GeneralUpdate.Differential.Differ;
namespace GeneralUpdate.Core;
/// <summary>
/// Unified update bootstrap — single entry point for Client, Upgrade, and OSS roles.
/// Use <see cref="AppType"/> to select the workflow:
/// <list type="bullet">
/// <item><see cref="AppType.Client"/> — validate versions, download, start upgrade process</item>
/// <item><see cref="AppType.Upgrade"/> — receive ProcessInfo, apply updates, start main app</item>
/// <item><see cref="AppType.OSSClient"/> — OSS client: download version config, start upgrade process</item>
/// <item><see cref="AppType.OSSUpgrade"/> — OSS upgrade: download packages from cloud, start main app</item>
/// </list>
/// </summary>
/// <remarks>
/// For Client mode, use <c>Option(UpdateOptions.AppType, AppType.Client)</c>.
/// </remarks>
public class GeneralUpdateBootstrap : AbstractBootstrap<GeneralUpdateBootstrap, IStrategy>
{
private GlobalConfigInfo _configInfo = new();
private Func<bool>? _customSkipOption;
private Func<UpdateInfoEventArgs, bool>? _updatePrecheck;
private CancellationTokenSource? _cts;
private DiffPipelineBuilder? _diffPipelineBuilder;
public GeneralUpdateBootstrap()
{
InitializeFromEnvironment();
}
/// <summary>Cancel the current update operation.</summary>
public void Cancel()
{
_cts?.Cancel();
GeneralTracer.Info("GeneralUpdateBootstrap: cancellation requested.");
}
// ════════════════════════════════════════════════════════════════
// Launch — AppType dispatch via role strategies
// ════════════════════════════════════════════════════════════════
public override async Task<GeneralUpdateBootstrap> LaunchAsync()
{
var appType = GetOption(UpdateOptions.AppType);
// Silent mode: start background poll and return immediately
if (appType == AppType.Client && GetOption(UpdateOptions.Silent))
{
await LaunchSilentAsync().ConfigureAwait(false);
return this;
}
return appType switch
{
AppType.Client => await LaunchWithStrategy(new ClientUpdateStrategy()),
AppType.Upgrade => await LaunchWithStrategy(new UpgradeUpdateStrategy()),
AppType.OSSClient => await LaunchWithStrategy(new OSSUpdateStrategy(AppType.OSSClient)),
AppType.OSSUpgrade => await LaunchWithStrategy(new OSSUpdateStrategy(AppType.OSSUpgrade)),
_ => await LaunchWithStrategy(new ClientUpdateStrategy())
};
}
private async Task<GeneralUpdateBootstrap> LaunchWithStrategy(IStrategy roleStrategy)
{
_cts = new CancellationTokenSource();
var token = _cts.Token;
try
{
token.ThrowIfCancellationRequested();
ApplyRuntimeOptions();
// Resolve hooks and reporter from extensions
var hooks = ResolveExtension<Hooks.IUpdateHooks>() ?? new Hooks.NoOpUpdateHooks();
var reporter = ResolveExtension<Download.Reporting.IUpdateReporter>() ?? new Download.Reporting.NoOpUpdateReporter();
// Configure client-specific callbacks
if (roleStrategy is ClientUpdateStrategy clientStrat)
{
clientStrat.Hooks = hooks;
clientStrat.Reporter = reporter;
// Resolve DownloadSource from extension registry (Hub, custom, etc.)
var resolvedSource = ResolveExtension<Download.Abstractions.IDownloadSource>();
// Inject SignalR Hub download source if configured
if (resolvedSource == null)
{
var hubConfig = GetOption(UpdateOptions.Hub);
if (hubConfig != null && !string.IsNullOrEmpty(hubConfig.Url))
{
var hubSource = new Download.Sources.HubDownloadSource(
hubConfig.Url, _configInfo.Token, _configInfo.AppSecretKey);
await hubSource.StartAsync().ConfigureAwait(false);
resolvedSource = hubSource;
GeneralTracer.Info("GeneralUpdateBootstrap: HubDownloadSource started from HubConfig.");
}
}
clientStrat.DownloadSource = resolvedSource;
if (_updatePrecheck != null)
clientStrat.UseUpdatePrecheck(_updatePrecheck);
await CallSmallBowlHomeAsync(_configInfo.Bowl).ConfigureAwait(false);
}
else if (roleStrategy is UpgradeUpdateStrategy upgradeStrat)
{
upgradeStrat.Hooks = hooks;
upgradeStrat.Reporter = reporter;
}
else if (roleStrategy is OSSUpdateStrategy ossStrat)
{
ossStrat.Hooks = hooks;
ossStrat.Reporter = reporter;
}
roleStrategy.Create(_configInfo);
var binaryDiffer = ResolveExtension<IBinaryDiffer>();
var dirtyStrategy = ResolveExtension<IDirtyStrategy>();
if (roleStrategy is ClientUpdateStrategy cs2)
{
if (binaryDiffer != null) cs2.SetBinaryDiffer(binaryDiffer);
if (dirtyStrategy != null) cs2.SetDirtyStrategy(dirtyStrategy);
}
else if (roleStrategy is UpgradeUpdateStrategy us2)
{
if (binaryDiffer != null) us2.SetBinaryDiffer(binaryDiffer);
if (dirtyStrategy != null) us2.SetDirtyStrategy(dirtyStrategy);
}
// Build DiffPipeline — user‑configured or default with BsdiffDiffer,
// parallelism=2, and progress reporter wired to AddListenerProgress.
var diffPipeline = BuildDiffPipeline();
if (roleStrategy is ClientUpdateStrategy cs3)
cs3.SetDiffPipeline(diffPipeline);
else if (roleStrategy is UpgradeUpdateStrategy us3)
us3.SetDiffPipeline(diffPipeline);
// Check custom skip condition before executing update
if (_customSkipOption?.Invoke() == true)
{
GeneralTracer.Info("GeneralUpdateBootstrap: update skipped by custom skip option.");
return this;
}
await roleStrategy.ExecuteAsync();
}
catch (Exception ex)
{
GeneralTracer.Error("LaunchWithStrategy failed.", ex);
EventManager.Instance.Dispatch(this, new ExceptionEventArgs(ex, ex.Message));
}
finally
{
// Dispose HubDownloadSource if it was started
if (roleStrategy is ClientUpdateStrategy cs && cs.DownloadSource is IAsyncDisposable ad)
await ad.DisposeAsync();
_cts?.Dispose();
_cts = null;
}
return this;
}
// ════════════════════════════════════════════════════════════════
// Configuration
// ════════════════════════════════════════════════════════════════
public GeneralUpdateBootstrap SetConfig(Configinfo configInfo)
{
configInfo.Validate();
_configInfo = ConfigurationMapper.MapToGlobalConfigInfo(configInfo);
var appType = GetOption(UpdateOptions.AppType);
if (appType != AppType.Upgrade)
{
_configInfo.TempPath = StorageManager.GetTempDirectory("upgrade_temp");
InitBlackList();
}
return this;
}
public GeneralUpdateBootstrap SetCustomSkipOption(Func<bool>? func)
{
_customSkipOption = func;
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>
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.Configinfo);
if (config == null)
throw new InvalidOperationException($"Failed to parse config file: {fullPath}");
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;
}
public GeneralUpdateBootstrap AddListenerUpdatePrecheck(Func<UpdateInfoEventArgs, bool> func)
{
_updatePrecheck = func ?? throw new ArgumentNullException(nameof(func));
return this;
}
// ════════════════════════════════════════════════════════════════
// Helpers
// ════════════════════════════════════════════════════════════════
private void InitializeFromEnvironment()
{
// Read ProcessInfo via AES-encrypted file IPC.
var processInfo = new EncryptedFileProcessInfoProvider().Receive();
if (processInfo == null) return;
_configInfo = new GlobalConfigInfo
{
MainAppName = processInfo.AppName,
InstallPath = processInfo.InstallPath,
ClientVersion = processInfo.CurrentVersion,
LastVersion = processInfo.LastVersion,
UpdateLogUrl = processInfo.UpdateLogUrl,
Encoding = Encoding.GetEncoding(processInfo.CompressEncoding),
Format = processInfo.CompressFormat,
DownloadTimeOut = processInfo.DownloadTimeOut,
AppSecretKey = processInfo.AppSecretKey,
UpdateVersions = processInfo.UpdateVersions,
TempPath = StorageManager.GetTempDirectory("upgrade_temp"),
ReportUrl = processInfo.ReportUrl,
BackupDirectory = processInfo.BackupDirectory,
Scheme = processInfo.Scheme,
Token = processInfo.Token,
DriverDirectory = processInfo.DriverDirectory,
BlackFiles = processInfo.BlackFiles ?? BlackListDefaults.DefaultBlackFiles,
BlackFormats = processInfo.BlackFileFormats ?? BlackListDefaults.DefaultBlackFormats,
SkipDirectorys = processInfo.SkipDirectorys ?? BlackListDefaults.DefaultSkipDirectories
};
StorageManager.BlackListMatcher = DefaultBlackListMatcher.FromConfigInfo(_configInfo);
}
/// <summary>
/// Applies UpdateOptions 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 UpdateOptions — 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(UpdateOptions.Encoding);
_configInfo.Format ??= GetOption(UpdateOptions.Format);
// Normalize legacy "ZIP" default (UpdateOptions) to Format.ZIP (".zip")
// so the pipeline constructs correct paths and CompressProvider matches its switch.
if (_configInfo.Format == "ZIP")
_configInfo.Format = Format.ZIP;
if (_configInfo.DownloadTimeOut <= 0)
_configInfo.DownloadTimeOut = GetOption(UpdateOptions.DownloadTimeout) ?? 60;
// bool? options: use ??= so user-configured false is preserved
_configInfo.PatchEnabled ??= GetOption(UpdateOptions.PatchEnabled);
_configInfo.BackupEnabled ??= GetOption(UpdateOptions.BackupEnabled);
// Always apply from UpdateOptions — no other code sets these before
// ApplyRuntimeOptions() runs. Defaults are functionally reasonable.
_configInfo.MaxConcurrency = GetOption(UpdateOptions.MaxConcurrency);
_configInfo.EnableResume = GetOption(UpdateOptions.EnableResume);
_configInfo.RetryCount = GetOption(UpdateOptions.RetryCount);
_configInfo.RetryInterval = GetOption(UpdateOptions.RetryInterval);
_configInfo.VerifyChecksum = GetOption(UpdateOptions.VerifyChecksum);
_configInfo.DiffMode = GetOption(UpdateOptions.DiffMode);
}
/// <summary>
/// Silent update mode — starts a background poll loop and returns immediately.
/// The orchestrator checks for updates periodically and prepares them.
/// When the host process exits, the prepared update is applied.
/// </summary>
private async Task LaunchSilentAsync()
{
GeneralTracer.Info("GeneralUpdateBootstrap: starting silent update mode.");
var pollMinutes = GetOption(UpdateOptions.SilentPollIntervalMinutes);
var autoInstall = GetOption(UpdateOptions.SilentAutoInstall);
var silentOptions = new Silent.SilentOptions
{
PollInterval = TimeSpan.FromMinutes(pollMinutes),
AutoInstall = autoInstall
};
var hooks = ResolveExtension<Hooks.IUpdateHooks>() ?? new Hooks.NoOpUpdateHooks();
var reporter = ResolveExtension<Download.Reporting.IUpdateReporter>() ?? new Download.Reporting.NoOpUpdateReporter();
var orchestrator = new Silent.SilentPollOrchestrator(_configInfo, silentOptions)
.WithHooks(hooks)
.WithReporter(reporter);
await orchestrator.StartAsync().ConfigureAwait(false);
GeneralTracer.Info("GeneralUpdateBootstrap: silent update mode started, returning to caller.");
}
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 void InitBlackList()
{
// Build blacklist matcher from GlobalConfigInfo and set on StorageManager.
// The matcher combines user config with system defaults.
var effectiveConfig = new BlackListConfig(
_configInfo.BlackFiles?.Count > 0 ? _configInfo.BlackFiles : BlackListDefaults.DefaultBlackFiles,
_configInfo.BlackFormats?.Count > 0 ? _configInfo.BlackFormats : BlackListDefaults.DefaultBlackFormats,
_configInfo.SkipDirectorys?.Count > 0 ? _configInfo.SkipDirectorys : BlackListDefaults.DefaultSkipDirectories
);
StorageManager.BlackListMatcher = new DefaultBlackListMatcher(effectiveConfig);
}
private async Task CallSmallBowlHomeAsync(string processName)
{
if (string.IsNullOrWhiteSpace(processName)) return;
try
{
var processes = Process.GetProcessesByName(processName);
foreach (var process in processes)
{
GeneralTracer.Info($"Shutting down process {process.ProcessName} (ID: {process.Id})");
await GracefulExit.ShutdownAsync(process).ConfigureAwait(false);
}
}
catch (Exception ex)
{
GeneralTracer.Error("CallSmallBowlHomeAsync failed.", ex);
}
}
// ════════════════════════════════════════════════════════════════
// 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;
}
public GeneralUpdateBootstrap AddListenerMultiAllDownloadCompleted(
Action<object, MultiAllDownloadCompletedEventArgs> cb) => AddListener(cb);
public GeneralUpdateBootstrap AddListenerMultiDownloadCompleted(
Action<object, MultiDownloadCompletedEventArgs> cb) => AddListener(cb);
public GeneralUpdateBootstrap AddListenerMultiDownloadError(
Action<object, MultiDownloadErrorEventArgs> cb) => AddListener(cb);
public GeneralUpdateBootstrap AddListenerMultiDownloadStatistics(
Action<object, MultiDownloadStatisticsEventArgs> cb) => AddListener(cb);
public GeneralUpdateBootstrap AddListenerException(
Action<object, ExceptionEventArgs> cb) => AddListener(cb);
public GeneralUpdateBootstrap AddListenerUpdateInfo(
Action<object, UpdateInfoEventArgs> cb) => AddListener(cb);
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;
}
}