-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathOSSUpdateStrategy.cs
More file actions
347 lines (305 loc) · 14.5 KB
/
Copy pathOSSUpdateStrategy.cs
File metadata and controls
347 lines (305 loc) · 14.5 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using GeneralUpdate.Core.Compress;
using GeneralUpdate.Core.Configuration;
using GeneralUpdate.Core.Download.Abstractions;
using GeneralUpdate.Core.Download.Models;
using GeneralUpdate.Core.Download.Orchestrators;
namespace GeneralUpdate.Core.Strategy;
/// <summary>
/// OSS (Object Storage Service) update strategy — client/upgrade split via AppType.
/// <list type="bullet">
/// <item><see cref="AppType.OSSClient"/> — downloads version config, checks for updates,
/// starts the upgrade process, and exits.</item>
/// <item><see cref="AppType.OSSUpgrade"/> — reads version config, downloads packages from OSS,
/// decompresses them, starts the main app, and exits.</item>
/// </list>
/// </summary>
public class OSSUpdateStrategy : IStrategy
{
private readonly AppType _role;
private GlobalConfigInfo? _configInfo;
private readonly string _appPath = AppDomain.CurrentDomain.BaseDirectory;
private const int DefaultTimeOut = 60;
public OSSUpdateStrategy(AppType role = AppType.OSSClient)
{
_role = role;
}
public Hooks.IUpdateHooks Hooks { get; set; } = new Hooks.NoOpUpdateHooks();
public Download.Reporting.IUpdateReporter Reporter { get; set; } = new Download.Reporting.NoOpUpdateReporter();
public IDownloadSource? DownloadSource { get; set; }
public IDownloadOrchestrator? DownloadOrchestrator { get; set; }
public void Create(GlobalConfigInfo parameter)
{
_configInfo = parameter ?? throw new ArgumentNullException(nameof(parameter));
}
public async Task ExecuteAsync()
{
if (_configInfo == null)
throw new InvalidOperationException("OSSUpdateStrategy not configured. Call Create() first.");
// Dispatch by role — no env-var detection needed.
if (_role == AppType.OSSUpgrade)
{
await ExecuteUpgradeAsync();
return;
}
await ExecuteClientAsync();
}
// ════════════════════════════════════════════════════════════════
// Client side: check version, start upgrade process
// ════════════════════════════════════════════════════════════════
private async Task ExecuteClientAsync()
{
GeneralTracer.Debug("OSSUpdateStrategy (client): checking for updates.");
var versionFileName = $"{_configInfo!.MainAppName ?? _configInfo.AppName}_versions.json";
var versionsFilePath = Path.Combine(_appPath, versionFileName);
if (!string.IsNullOrEmpty(_configInfo.UpdateUrl))
{
await DownloadVersionConfig(_configInfo.UpdateUrl, versionsFilePath).ConfigureAwait(false);
}
if (!File.Exists(versionsFilePath))
{
GeneralTracer.Info("OSSUpdateStrategy: version config download failed, aborting.");
return;
}
var versions = JsonSerializer.Deserialize(
File.ReadAllText(versionsFilePath),
JsonContext.VersionOSSJsonContext.Default.ListVersionOSS);
if (versions == null || versions.Count == 0)
{
GeneralTracer.Info("OSSUpdateStrategy: no versions found, aborting.");
return;
}
versions = versions.OrderByDescending(x => x.PubTime).ToList();
var latest = versions.First();
if (!IsOssUpgrade(_configInfo.ClientVersion, latest.Version))
{
GeneralTracer.Info("OSSUpdateStrategy: no upgrade needed.");
return;
}
// Use user-configured AppName or default upgrade exe
var upgradeAppName = !string.IsNullOrWhiteSpace(_configInfo.AppName) && _configInfo.AppName != "Update.exe"
? _configInfo.AppName
: "GeneralUpdate.Upgrade.exe";
var appPath = Path.Combine(_appPath, upgradeAppName);
if (!File.Exists(appPath))
throw new FileNotFoundException($"Upgrade application not found: {upgradeAppName}");
Process.Start(appPath);
await GracefulExit.CurrentProcessAsync().ConfigureAwait(false);
}
// ════════════════════════════════════════════════════════════════
// Upgrade side: download packages, decompress, start main app
// ════════════════════════════════════════════════════════════════
private async Task ExecuteUpgradeAsync()
{
var ctx = BuildUpdateContext();
try
{
var versionFileName = $"{_configInfo!.MainAppName ?? _configInfo.AppName}_versions.json";
var jsonPath = Path.Combine(_appPath, versionFileName);
if (!File.Exists(jsonPath) && DownloadSource == null)
throw new FileNotFoundException($"Version config not found: {jsonPath}");
// Hooks: allow cancellation before download
if (!await SafeOnBeforeUpdateAsync(ctx).ConfigureAwait(false))
{
GeneralTracer.Info("OSSUpdateStrategy (upgrade): cancelled by hook.");
return;
}
await SafeReportUpdateStartedAsync(ctx).ConfigureAwait(false);
// Build download assets from version config or injected source
List<DownloadAsset> assets;
if (DownloadSource != null)
{
assets = (await DownloadSource.ListAsync().ConfigureAwait(false)).ToList();
}
else
{
var versions = JsonSerializer.Deserialize(
File.ReadAllText(jsonPath),
JsonContext.VersionOSSJsonContext.Default.ListVersionOSS);
if (versions == null || versions.Count == 0)
throw new InvalidOperationException("No versions found in OSS configuration.");
assets = versions.OrderBy(v => v.PubTime)
.Where(v => new Version(v.Version ?? "0.0.0") > new Version(_configInfo.ClientVersion))
.Select(v =>
{
if (string.IsNullOrWhiteSpace(v.Url))
throw new InvalidOperationException(
$"OSS version '{v.PacketName ?? v.Version}' has no download URL.");
var zipName = $"{v.PacketName ?? v.Version}zip";
if (!zipName.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
zipName += ".zip";
return new DownloadAsset(
Name: zipName, Url: v.Url, Size: 0,
SHA256: v.Hash, Version: v.Version ?? "0.0.0");
}).ToList();
}
if (assets.Count == 0)
throw new InvalidOperationException("No assets to download.");
GeneralTracer.Debug($"OSSUpdateStrategy (upgrade): downloading {assets.Count} asset(s).");
await DownloadAssetsAsync(assets).ConfigureAwait(false);
GeneralTracer.Debug("OSSUpdateStrategy (upgrade): decompressing.");
DecompressAssets(assets);
await SafeOnDownloadCompletedAsync(ctx).ConfigureAwait(false);
await SafeOnAfterUpdateAsync(ctx).ConfigureAwait(false);
await SafeReportUpdateAppliedAsync(ctx).ConfigureAwait(false);
await SafeOnBeforeStartAppAsync(ctx).ConfigureAwait(false);
GeneralTracer.Debug("OSSUpdateStrategy (upgrade): launching main app.");
await StartAppAsync();
}
catch (Exception ex)
{
await SafeOnUpdateErrorAsync(ctx, ex).ConfigureAwait(false);
await SafeReportUpdateFailedAsync(ctx, ex).ConfigureAwait(false);
GeneralTracer.Error("OSSUpdateStrategy.ExecuteUpgradeAsync failed.", ex);
GeneralUpdate.Core.Event.EventManager.Instance.Dispatch(this, new GeneralUpdate.Core.Event.ExceptionEventArgs(ex, ex.Message));
}
finally
{
await GracefulExit.CurrentProcessAsync().ConfigureAwait(false);
}
}
public Task StartAppAsync()
{
var appName = _configInfo?.MainAppName ?? _configInfo?.AppName;
if (string.IsNullOrEmpty(appName)) return Task.CompletedTask;
var appPath = Path.Combine(_appPath, appName);
if (!File.Exists(appPath))
throw new FileNotFoundException($"Application not found: {appPath}");
Process.Start(appPath);
GeneralTracer.Debug("OSSUpdateStrategy: main application started.");
return Task.CompletedTask;
}
#region Helpers
private static async Task DownloadVersionConfig(string url, string path)
{
if (File.Exists(path))
{
File.SetAttributes(path, FileAttributes.Normal);
File.Delete(path);
}
using var httpClient = GeneralUpdate.Core.Network.HttpClientProvider.Shared;
var bytes = await httpClient.GetByteArrayAsync(url).ConfigureAwait(false);
File.WriteAllBytes(path, bytes);
}
private static bool IsOssUpgrade(string clientVersion, string serverVersion)
{
if (string.IsNullOrWhiteSpace(clientVersion) || string.IsNullOrWhiteSpace(serverVersion))
return false;
return Version.TryParse(clientVersion, out var cv)
&& Version.TryParse(serverVersion, out var sv)
&& cv < sv;
}
private async Task DownloadAssetsAsync(List<DownloadAsset> assets)
{
var plan = new DownloadPlan(assets, false);
if (DownloadOrchestrator != null)
{
await DownloadOrchestrator.ExecuteAsync(plan, _appPath).ConfigureAwait(false);
}
else
{
using var httpClient = new HttpClient
{
Timeout = TimeSpan.FromSeconds(_configInfo?.DownloadTimeOut > 0 ? _configInfo!.DownloadTimeOut : DefaultTimeOut)
};
var orchestrator = new DefaultDownloadOrchestrator(httpClient);
await orchestrator.ExecuteAsync(plan, _appPath).ConfigureAwait(false);
}
}
private void DecompressAssets(List<DownloadAsset> assets)
{
var encoding = Encoding.GetEncoding(_configInfo?.Encoding?.CodePage ?? Encoding.UTF8.CodePage);
foreach (var asset in assets)
{
var zipFilePath = Path.Combine(_appPath, $"{asset.Name}{Format.ZIP}");
CompressProvider.Decompress(Format.ZIP, zipFilePath, _appPath, encoding);
if (!File.Exists(zipFilePath)) continue;
File.SetAttributes(zipFilePath, FileAttributes.Normal);
File.Delete(zipFilePath);
}
}
private Hooks.UpdateContext BuildUpdateContext()
{
return new Hooks.UpdateContext(
_configInfo?.AppName ?? "unknown",
_configInfo?.InstallPath ?? _appPath,
_configInfo?.ClientVersion ?? "0.0.0",
_configInfo?.LastVersion,
AppType.OSSUpgrade
);
}
private async Task<bool> SafeOnBeforeUpdateAsync(Hooks.UpdateContext ctx)
{
try { return await Hooks.OnBeforeUpdateAsync(ctx).ConfigureAwait(false); }
catch (Exception ex) { GeneralTracer.Warn($"OnBeforeUpdateAsync hook failed: {ex.Message}"); return true; }
}
private async Task SafeOnBeforeStartAppAsync(Hooks.UpdateContext ctx)
{
try { await Hooks.OnBeforeStartAppAsync(ctx).ConfigureAwait(false); }
catch (Exception ex) { GeneralTracer.Warn($"OnBeforeStartAppAsync hook failed: {ex.Message}"); }
}
private async Task SafeOnUpdateErrorAsync(Hooks.UpdateContext ctx, Exception error)
{
try { await Hooks.OnUpdateErrorAsync(ctx, error).ConfigureAwait(false); }
catch (Exception ex) { GeneralTracer.Warn($"OnUpdateErrorAsync hook failed: {ex.Message}"); }
}
private async Task SafeOnAfterUpdateAsync(Hooks.UpdateContext ctx)
{
try { await Hooks.OnAfterUpdateAsync(ctx).ConfigureAwait(false); }
catch (Exception ex) { GeneralTracer.Warn($"OnAfterUpdateAsync hook failed: {ex.Message}"); }
}
private async Task SafeOnDownloadCompletedAsync(Hooks.UpdateContext ctx)
{
try
{
var downloadCtx = new Hooks.DownloadContext(
_configInfo?.MainAppName ?? _configInfo?.AppName ?? "unknown",
_configInfo?.LastVersion ?? "", 0, TimeSpan.Zero, _appPath, true);
await Hooks.OnDownloadCompletedAsync(downloadCtx).ConfigureAwait(false);
}
catch (Exception ex) { GeneralTracer.Warn($"OnDownloadCompletedAsync hook failed: {ex.Message}"); }
}
private async Task SafeReportUpdateStartedAsync(Hooks.UpdateContext ctx)
{
try
{
await Reporter.ReportAsync(new Download.Reporting.UpdateReport(
ctx.AppName, ctx.CurrentVersion, ctx.TargetVersion,
Download.Reporting.UpdateEvent.UpdateStarted, ctx.AppType, DateTimeOffset.UtcNow
)).ConfigureAwait(false);
}
catch (Exception ex) { GeneralTracer.Warn($"Report UpdateStarted failed: {ex.Message}"); }
}
private async Task SafeReportUpdateAppliedAsync(Hooks.UpdateContext ctx)
{
try
{
await Reporter.ReportAsync(new Download.Reporting.UpdateReport(
ctx.AppName, ctx.CurrentVersion, ctx.TargetVersion,
Download.Reporting.UpdateEvent.UpdateApplied, ctx.AppType, DateTimeOffset.UtcNow
)).ConfigureAwait(false);
}
catch (Exception ex) { GeneralTracer.Warn($"Report UpdateApplied failed: {ex.Message}"); }
}
private async Task SafeReportUpdateFailedAsync(Hooks.UpdateContext ctx, Exception error)
{
try
{
await Reporter.ReportAsync(new Download.Reporting.UpdateReport(
ctx.AppName, ctx.CurrentVersion, ctx.TargetVersion,
Download.Reporting.UpdateEvent.UpdateFailed, ctx.AppType, DateTimeOffset.UtcNow,
ErrorMessage: error.Message
)).ConfigureAwait(false);
}
catch (Exception ex) { GeneralTracer.Warn($"Report UpdateFailed failed: {ex.Message}"); }
}
#endregion
}