-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPackageState.cs
432 lines (358 loc) · 15.1 KB
/
PackageState.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
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
using System.Collections.Immutable;
using System.Text;
using Dalamud.Interface.Textures.TextureWraps;
using Heliosphere.Model;
using Heliosphere.Util;
using Newtonsoft.Json;
using Semver;
namespace Heliosphere;
internal class PackageState : IDisposable {
private Plugin Plugin { get; }
private string? PenumbraPath => this.Plugin.Penumbra.GetModDirectory();
private Guard<Dictionary<Guid, InstalledPackage>> InstalledInternal { get; } = new([]);
private Guard<Dictionary<Guid, InstalledPackage>> ExternalInternal { get; } = new([]);
private SemaphoreSlim UpdateMutex { get; } = new(1, 1);
internal int DirectoriesToScan = -1;
internal int CurrentDirectory;
private int _updateNum;
internal IReadOnlyDictionary<Guid, InstalledPackage> Installed {
get {
using var guard = this.InstalledInternal.Wait();
return guard.Data.ToImmutableDictionary(
entry => entry.Key,
entry => entry.Value
);
}
}
internal IReadOnlyDictionary<Guid, InstalledPackage> InstalledNoBlock {
get {
using var guard = this.InstalledInternal.Wait(0);
if (guard == null) {
return ImmutableDictionary<Guid, InstalledPackage>.Empty;
}
return guard.Data.ToImmutableDictionary(
entry => entry.Key,
entry => entry.Value
);
}
}
/// <summary>
/// <para>
/// Returns an immutable Dictionary of "external" Heliosphere mods.
/// </para>
/// <para>
/// External mods are mods installed via means other than the plugin.
/// Specifically, these are mods that are in directories not starting with
/// <c>"hs-"</c> and that contain a heliosphere.json file.
/// </para>
/// </summary>
internal IReadOnlyDictionary<Guid, InstalledPackage> External {
get {
using var guard = this.ExternalInternal.Wait();
return guard.Data.ToImmutableDictionary(
entry => entry.Key,
entry => entry.Value
);
}
}
/// <summary>
/// Same as <see cref="External"/> but returns an empty Dictionary if
/// accessing the data would have blocked.
/// </summary>
internal IReadOnlyDictionary<Guid, InstalledPackage> ExternalNoBlock {
get {
using var guard = this.ExternalInternal.Wait(0);
if (guard == null) {
return ImmutableDictionary<Guid, InstalledPackage>.Empty;
}
return guard.Data.ToImmutableDictionary(
entry => entry.Key,
entry => entry.Value
);
}
}
internal PackageState(Plugin plugin) {
this.Plugin = plugin;
}
public void Dispose() {
this.UpdateMutex.Dispose();
this.InstalledInternal.Dispose();
}
internal async Task<IReadOnlyDictionary<Guid, InstalledPackage>> GetInstalled(CancellationToken token = default) {
using var guard = await this.InstalledInternal.WaitAsync(token);
return guard.Data.ToImmutableDictionary(
entry => entry.Key,
entry => entry.Value
);
}
internal async Task UpdatePackages(CancellationToken token = default) {
using var span = SentryHelper.StartTransaction("PackageState", "UpdatePackages");
// get the current update number. if this changes by the time this task
// gets a lock on the update mutex, the update that this task was queued
// for is already complete
var updateNum = Interlocked.CompareExchange(ref this._updateNum, 0, 0);
// first wait until all downloads are completed
var timesDelayed = 0;
while (true) {
bool anyRunning;
using (var downloads = await this.Plugin.Downloads.WaitAsync(token)) {
anyRunning = downloads.Data.Any(task => !task.State.IsDone());
}
if (anyRunning) {
timesDelayed += 1;
await Task.Delay(TimeSpan.FromSeconds(1), token);
} else {
break;
}
}
span.Inner.SetExtra("timesDelayed", timesDelayed);
// get a lock on the update guard so no other updates can continue
using var updateGuard = await SemaphoreGuard.WaitAsync(this.UpdateMutex, token);
// get a lock on the downloads so that no one can add any until the update is complete
using var downloadGuard = await this.Plugin.Downloads.WaitAsync(token);
// check if this task is redundant
if (updateNum != Interlocked.CompareExchange(ref this._updateNum, 0, 0)) {
span.Inner.SetExtra("wasRedundant", true);
return;
}
span.Inner.SetExtra("wasRedundant", false);
int numPreviouslyInstalled;
using (var guard = await this.InstalledInternal.WaitAsync(token)) {
numPreviouslyInstalled = guard.Data.Count;
// dispose and remove existing packages
foreach (var (_, package) in guard.Data) {
package.Dispose();
}
guard.Data.Clear();
}
using (var externalGuard = await this.ExternalInternal.WaitAsync(token)) {
externalGuard.Data.Clear();
}
if (this.PenumbraPath is not { } penumbraPath) {
return;
}
var dirs = Directory.EnumerateDirectories(penumbraPath)
.Select(Path.GetFileName)
.Where(dir => !string.IsNullOrEmpty(dir))
.Cast<string>()
.ToList();
Interlocked.Exchange(ref this.CurrentDirectory, 0);
Interlocked.Exchange(ref this.DirectoriesToScan, dirs.Count);
await Parallel.ForEachAsync(
dirs,
new ParallelOptions {
CancellationToken = token,
},
async (dir, token) => {
Interlocked.Increment(ref this.CurrentDirectory);
if (dir.StartsWith("hs-")) {
try {
await this.LoadPackage(dir, penumbraPath, token);
} catch (Exception ex) {
ErrorHelper.Handle(ex, "Could not load package");
}
} else {
try {
await this.LoadExternalPackage(dir, penumbraPath, token);
} catch (Exception ex) {
ErrorHelper.Handle(ex, "Could not load external package");
}
}
}
);
Interlocked.Exchange(ref this.DirectoriesToScan, -1);
Interlocked.Add(ref this._updateNum, 1);
}
private static async Task<HeliosphereMeta?> LoadMeta(string penumbraPath, string directory, CancellationToken token = default) {
var metaPath = Path.Join(penumbraPath, directory, "heliosphere.json");
try {
return await HeliosphereMeta.Load(metaPath, token);
} catch (Exception ex) when (ex is FileNotFoundException or DirectoryNotFoundException) {
return null;
} catch (Exception ex) {
// downgrading these to a warning - most of the time it just doesn't
// matter, and I can't be fucked handling every bad meta json out
// there to prevent sentry being mad
Plugin.Log.Warning(ex, "Could not load heliosphere.json");
return null;
}
}
private static InstalledPackage CreateInstalledPackage(
string penumbraPath,
string directory,
HeliosphereMeta meta,
Guard<Dictionary<Guid, InstalledPackage>>.Handle guard
) {
InstalledPackage package;
if (guard.Data.TryGetValue(meta.Id, out var existing)) {
package = existing;
existing.InternalVariants.Add(meta);
} else {
var coverPath = Path.Join(penumbraPath, directory, "cover.jpg");
package = new InstalledPackage(
meta.Id,
meta.Name,
meta.Author,
[meta],
coverPath
);
}
return package;
}
private async Task LoadExternalPackage(string directory, string penumbraPath, CancellationToken token = default) {
var meta = await LoadMeta(penumbraPath, directory, token);
if (meta == null) {
return;
}
using var guard = await this.ExternalInternal.WaitAsync(token);
var package = CreateInstalledPackage(penumbraPath, directory, meta, guard);
guard.Data[meta.Id] = package;
}
private async Task LoadPackage(string directory, string penumbraPath, CancellationToken token = default) {
// always attempt to load the hs meta file
var meta = await LoadMeta(penumbraPath, directory, token);
if (meta == null) {
return;
}
if (SemVersion.TryParse(directory.Split('-')[^2], SemVersionStyles.Strict, out _)) {
// second-to-last part should be a uuid in the new scheme, so this
// is the old naming scheme
directory = await this.MigrateOldDirectory(meta, penumbraPath, directory, token);
}
if (HeliosphereMeta.ParseDirectory(directory) is not { } info) {
return;
}
if (meta.Id != info.PackageId || meta.VariantId != info.VariantId) {
return;
}
// always make sure path is correct
await this.RenameDirectory(meta, penumbraPath, directory, token);
using var guard = await this.InstalledInternal.WaitAsync(token);
var package = CreateInstalledPackage(penumbraPath, directory, meta, guard);
guard.Data[meta.Id] = package;
}
internal async Task RenameDirectory(HeliosphereMeta meta, string penumbraPath, string directory, CancellationToken token = default) {
var correctName = meta.ModDirectoryName();
if (directory == correctName) {
return;
}
Plugin.Log.Info($"Fixing incorrect folder name for {directory}");
var oldPath = Path.Join(penumbraPath, directory);
var newPath = Path.Join(penumbraPath, correctName);
if (Directory.Exists(newPath)) {
throw new ModAlreadyExistsException(oldPath, newPath);
}
Plugin.Log.Debug($" {oldPath} -> {newPath}");
Directory.Move(oldPath, newPath);
if (!await PathHelper.WaitToExist(newPath)) {
throw new DirectoryNotFoundException($"Directory '{newPath}' could not be found after waiting");
}
await this.Plugin.Framework.RunOnFrameworkThread(() => {
var oldPath = this.Plugin.Penumbra.GetModPath(directory);
this.Plugin.Penumbra.DeleteMod(directory);
this.Plugin.Penumbra.AddMod(correctName);
this.Plugin.Penumbra.CopyModSettings(directory, correctName);
if (oldPath != null) {
this.Plugin.Penumbra.SetModPath(correctName, oldPath);
}
});
}
private async Task<string> MigrateOldDirectory(HeliosphereMeta meta, string penumbraPath, string directory, CancellationToken token = default) {
Plugin.Log.Debug($"Migrating old folder name layout for {directory}");
var variant = await Plugin.GraphQl.GetVariant.ExecuteAsync(meta.VersionId, token);
if (variant.Data?.GetVersion == null) {
throw new Exception($"no variant for version id {meta.VersionId}");
}
meta.Variant = variant.Data.GetVersion.Variant.Name;
meta.VariantId = variant.Data.GetVersion.Variant.Id;
var newName = meta.ModDirectoryName();
var oldPath = Path.Join(penumbraPath, directory);
var newPath = Path.Join(penumbraPath, newName);
Plugin.Log.Debug($" {oldPath} -> {newPath}");
Directory.Move(oldPath, newPath);
await this.Plugin.Framework.RunOnFrameworkThread(() => {
this.Plugin.Penumbra.AddMod(newName);
this.Plugin.Penumbra.ReloadMod(directory);
});
Plugin.Log.Debug(" writing new meta");
var json = JsonConvert.SerializeObject(meta, Formatting.Indented);
var path = Path.Join(penumbraPath, newName, "heliosphere.json");
await using var file = FileHelper.Create(path);
await file.WriteAsync(Encoding.UTF8.GetBytes(json), token);
return newName;
}
}
internal class ModAlreadyExistsException : Exception {
private string OldPath { get; }
private string NewPath { get; }
public override string Message => $"Could not move old mod to new path because new path already exists ({this.OldPath} -> {this.NewPath})";
internal ModAlreadyExistsException(string oldPath, string newPath) {
this.OldPath = oldPath;
this.NewPath = newPath;
}
}
internal class InstalledPackage : IDisposable {
internal Guid Id { get; }
internal string Name { get; }
internal string Author { get; }
internal string CoverImagePath { get; }
private bool _loading;
internal IDalamudTextureWrap? CoverImage {
get {
if (this._loading) {
return null;
}
if (Plugin.Instance.CoverImages.TryGet(this.CoverImagePath, out var img)) {
return img;
}
this._loading = true;
Task.Run(async () => {
try {
await this.AttemptLoad();
} finally {
this._loading = false;
}
});
return null;
}
}
internal List<HeliosphereMeta> InternalVariants { get; }
internal IReadOnlyList<HeliosphereMeta> Variants => this.InternalVariants.ToImmutableList();
internal InstalledPackage(Guid id, string name, string author, List<HeliosphereMeta> variants, string coverImagePath) {
this.Id = id;
this.Name = name;
this.Author = author;
this.CoverImagePath = coverImagePath;
this.InternalVariants = variants;
}
public void Dispose() {
// no-op
}
public override int GetHashCode() {
return this.Id.GetHashCode();
}
public override bool Equals(object? obj) {
return obj is InstalledPackage pkg && pkg.Id == this.Id;
}
private async Task AttemptLoad(CancellationToken token = default) {
using var guard = await SemaphoreGuard.WaitAsync(Plugin.ImageLoadSemaphore, token);
try {
var img = await Plugin.Resilience.ExecuteAsync(async token => await this.AttemptLoadSingle(token), token);
Plugin.Instance.CoverImages.AddOrUpdate(this.CoverImagePath, img);
} catch {
Plugin.Instance.CoverImages.AddOrUpdate(this.CoverImagePath, null);
throw;
}
}
private async Task<IDalamudTextureWrap?> AttemptLoadSingle(CancellationToken token = default) {
byte[] bytes;
try {
bytes = await FileHelper.ReadAllBytesAsync(this.CoverImagePath, token);
} catch (Exception ex) when (ex is FileNotFoundException or DirectoryNotFoundException) {
return null;
}
var wrap = await ImageHelper.LoadImageAsync(Plugin.Instance.TextureProvider, bytes, token)
?? throw new Exception("image was null");
return wrap;
}
}