-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathScriptCatalog.cs
More file actions
558 lines (483 loc) · 18.5 KB
/
Copy pathScriptCatalog.cs
File metadata and controls
558 lines (483 loc) · 18.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
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
using LabApi.Features.Console;
using SER.Code.FlagSystem;
using SER.Code.FlagSystem.Flags;
using SER.Code.Helpers;
using SER.Code.Helpers.ResultSystem;
using SER.Code.ScriptSystem;
using SER.Code.ScriptSystem.Structures;
namespace SER.Code.FileSystem;
public static class ScriptCatalog
{
private readonly record struct ScriptFile(string Content, DateTime LastWriteTimeUtc, long Length);
private readonly record struct FileStamp(DateTime LastWriteTimeUtc, long Length);
public readonly record struct RequestedRefreshResult(bool FileFound, RefreshSummary Summary);
public readonly record struct AcceptedScriptInfo(
string FileName,
string Path,
int Sections,
int FlagBindings);
public readonly record struct FailedScriptInfo(
string FileName,
string Path,
string Error,
bool PreviousVersionActive);
public readonly record struct RefreshSummary(int Reloaded, int Unloaded, int Failed)
{
public static RefreshSummary operator +(RefreshSummary first, RefreshSummary second) => new(
first.Reloaded + second.Reloaded,
first.Unloaded + second.Unloaded,
first.Failed + second.Failed);
}
private sealed record Snapshot(
string Path,
string FileName,
string RawContent,
DateTime LastWriteTimeUtc,
long Length,
ScriptSection[] Sections,
Dictionary<ScriptName, List<Flag>> Flags);
private static readonly Dictionary<string, Snapshot> SnapshotsByPath =
new(StringComparer.OrdinalIgnoreCase);
private static readonly Dictionary<string, Snapshot> SnapshotsByFileName =
new(StringComparer.OrdinalIgnoreCase);
private static readonly Dictionary<string, FileStamp> FailedFileStamps =
new(StringComparer.OrdinalIgnoreCase);
private static readonly Dictionary<string, FailedScriptInfo> FailedScriptsByPath =
new(StringComparer.OrdinalIgnoreCase);
private static bool _initialized;
private static bool _isRefreshing;
public static RefreshSummary Initialize()
{
if (!_initialized)
{
_initialized = true;
return RefreshAll(true);
}
foreach (string path in SnapshotsByPath.Keys.ToArray())
{
RestoreSnapshotBinding(path);
}
return default;
}
public static RefreshSummary RefreshAll(bool force)
{
if (_isRefreshing)
{
return default;
}
_isRefreshing = true;
try
{
if (!Directory.Exists(FileSystem.MainDirPath))
{
Directory.CreateDirectory(FileSystem.MainDirPath);
}
try
{
FileSystem.UpdateScriptPathCollection();
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
Log.Error($"Failed to scan the SER script directory: {exception.Message}");
return new RefreshSummary(0, 0, 1);
}
var paths = FileSystem.RegisteredScriptPaths.ToHashSet(StringComparer.OrdinalIgnoreCase);
RefreshSummary summary = default;
foreach (var removedFailure in FailedFileStamps.Keys.Where(path => !paths.Contains(path)).ToArray())
{
FailedFileStamps.Remove(removedFailure);
FailedScriptsByPath.Remove(removedFailure);
}
foreach (var removedFailure in FailedScriptsByPath.Keys.Where(path => !paths.Contains(path)).ToArray())
{
FailedScriptsByPath.Remove(removedFailure);
}
foreach (var removedPath in SnapshotsByPath.Keys.Where(path => !paths.Contains(path)).ToArray())
{
if (RemoveSnapshot(removedPath) is { } removedName)
{
Logger.Debug($"SER script '{removedName}' was unloaded.");
summary += new RefreshSummary(0, 1, 0);
}
}
foreach (var path in paths)
{
summary += RefreshPath(path, force);
}
return summary;
}
finally
{
_isRefreshing = false;
}
}
public static RequestedRefreshResult RefreshRequested(ScriptName requestedName)
{
if (_isRefreshing)
{
return default;
}
if (!Directory.Exists(FileSystem.MainDirPath))
{
Directory.CreateDirectory(FileSystem.MainDirPath);
}
try
{
FileSystem.UpdateScriptPathCollection();
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
Log.Error($"Failed to scan the SER script directory: {exception.Message}");
return new RequestedRefreshResult(false, new RefreshSummary(0, 0, 1));
}
FileSystem.ParseSectionSelector(requestedName, out var fileName, out _);
var path = FileSystem.RegisteredScriptPaths.FirstOrDefault(candidate =>
string.Equals(
Path.GetFileNameWithoutExtension(candidate),
fileName,
StringComparison.OrdinalIgnoreCase));
if (path is null)
{
return default;
}
_isRefreshing = true;
try
{
return new RequestedRefreshResult(true, RefreshPath(path, false));
}
finally
{
_isRefreshing = false;
}
}
public static AcceptedScriptInfo[] GetAcceptedScripts() => SnapshotsByPath.Values
.OrderBy(snapshot => snapshot.FileName, StringComparer.OrdinalIgnoreCase)
.Select(snapshot => new AcceptedScriptInfo(
snapshot.FileName,
snapshot.Path,
snapshot.Sections.Length,
snapshot.Flags.Sum(pair => pair.Value.Count)))
.ToArray();
public static FailedScriptInfo[] GetFailedScripts() => FailedScriptsByPath.Values
.OrderBy(failure => failure.FileName, StringComparer.OrdinalIgnoreCase)
.ToArray();
public static FailedScriptInfo? GetFailure(ScriptName requestedName)
{
FileSystem.ParseSectionSelector(requestedName, out var fileName, out _);
foreach (var failure in FailedScriptsByPath.Values)
{
if (string.Equals(failure.FileName, fileName, StringComparison.OrdinalIgnoreCase))
{
return failure;
}
}
return null;
}
public static TryGet<ScriptSection> GetSection(ScriptName requestedName)
{
FileSystem.ParseSectionSelector(requestedName, out var fileName, out var requestedSection);
if (!SnapshotsByFileName.TryGetValue(fileName, out var snapshot))
{
return $"Script '{requestedName}' is not registered.";
}
if (requestedSection is { } sectionNumber)
{
if (snapshot.Sections.Length <= 1)
{
return $"Script '{fileName}' is not split into multiple sections.";
}
var section = snapshot.Sections.FirstOrDefault(candidate => candidate.Number == sectionNumber);
return section is not null
? section
: $"Script '{fileName}' does not contain section {sectionNumber}.";
}
if (snapshot.Sections.Length > 1)
{
return $"Script '{fileName}' contains {snapshot.Sections.Length} sections. " +
$"Select one using '{fileName}:1' through '{fileName}:{snapshot.Sections.Length}'.";
}
return snapshot.Sections[0];
}
public static TryGet<string> GetPath(ScriptName requestedName)
{
FileSystem.ParseSectionSelector(requestedName, out var fileName, out _);
return SnapshotsByFileName.TryGetValue(fileName, out var snapshot)
? TryGet<string>.Success(snapshot.Path)
: TryGet<string>.Error($"Script '{requestedName}' is not registered.");
}
public static void Shutdown()
{
foreach (var snapshot in SnapshotsByPath.Values)
{
UnbindSnapshot(snapshot);
}
SnapshotsByPath.Clear();
SnapshotsByFileName.Clear();
FailedFileStamps.Clear();
FailedScriptsByPath.Clear();
_initialized = false;
}
private static RefreshSummary RefreshPath(string path, bool force)
{
if (!force && TryGetFileStamp(path, out var unchangedWriteTime, out var unchangedLength))
{
if (FailedFileStamps.TryGetValue(path, out var failedStamp)
&& failedStamp.LastWriteTimeUtc == unchangedWriteTime
&& failedStamp.Length == unchangedLength)
{
return default;
}
if (SnapshotsByPath.TryGetValue(path, out var unchangedSnapshot)
&& unchangedSnapshot.LastWriteTimeUtc == unchangedWriteTime
&& unchangedSnapshot.Length == unchangedLength)
{
return default;
}
}
if (ReadStableScriptFile(path).HasErrored(out var readError, out var scriptFile))
{
var fileName = Path.GetFileNameWithoutExtension(path);
Log.CompileError(fileName, readError);
FailedScriptsByPath[path] = new FailedScriptInfo(
fileName,
path,
readError,
SnapshotsByPath.ContainsKey(path));
RestoreSnapshotBinding(path);
return new RefreshSummary(0, 0, 1);
}
var content = scriptFile.Content;
var lastWriteTimeUtc = scriptFile.LastWriteTimeUtc;
var length = scriptFile.Length;
if (!force
&& SnapshotsByPath.TryGetValue(path, out var currentSnapshot)
&& currentSnapshot.RawContent == content)
{
var refreshedSnapshot = currentSnapshot with
{
LastWriteTimeUtc = lastWriteTimeUtc,
Length = length
};
SnapshotsByPath[path] = refreshedSnapshot;
SnapshotsByFileName[refreshedSnapshot.FileName] = refreshedSnapshot;
FailedFileStamps.Remove(path);
FailedScriptsByPath.Remove(path);
return default;
}
if (PrepareSnapshot(path, content, lastWriteTimeUtc, length)
.HasErrored(out var error, out var candidate))
{
var fileName = Path.GetFileNameWithoutExtension(path);
FailedFileStamps[path] = new FileStamp(lastWriteTimeUtc, length);
FailedScriptsByPath[path] = new FailedScriptInfo(
fileName,
path,
error,
SnapshotsByPath.ContainsKey(path));
Log.CompileError(fileName, error);
if (SnapshotsByPath.ContainsKey(path))
{
RestoreSnapshotBinding(path);
Logger.Warn($"SER kept the last known-good version of script '{fileName}' active.");
}
return new RefreshSummary(0, 0, 1);
}
if (CommitSnapshot(candidate).HasErrored(out error))
{
FailedFileStamps[path] = new FileStamp(lastWriteTimeUtc, length);
FailedScriptsByPath[path] = new FailedScriptInfo(
candidate.FileName,
path,
error,
SnapshotsByPath.ContainsKey(path));
Log.CompileError(candidate.FileName, error);
Logger.Warn($"SER kept the last known-good version of script '{candidate.FileName}' active.");
return new RefreshSummary(0, 0, 1);
}
FailedFileStamps.Remove(path);
FailedScriptsByPath.Remove(path);
Logger.Debug(
$"reloaded script '{candidate.FileName}'" +
(
candidate.Sections.Length > 1
? $" ({candidate.Sections.Length} section{(candidate.Sections.Length == 1 ? string.Empty : "s")})."
: string.Empty
)
);
return new RefreshSummary(1, 0, 0);
}
private static TryGet<Snapshot> PrepareSnapshot(
string path,
string content,
DateTime lastWriteTimeUtc,
long length)
{
var fileName = Path.GetFileNameWithoutExtension(path);
if (ScriptSection.Split(fileName, content, path).HasErrored(out var splitError, out var sections))
{
return splitError;
}
Dictionary<ScriptName, List<Flag>> preparedFlags = [];
foreach (var section in sections)
{
var script = Script.CreateByVerifiedSection(section, ServerConsoleExecutor.Instance);
if (script.Compile().HasErrored(out var compileError))
{
return $"Section '{section.Name}' failed to compile: {compileError}";
}
if (script.GetFlagLines().HasErrored(out var flagLineError, out var flagLines))
{
return $"Section '{section.Name}' has invalid flags: {flagLineError}";
}
if (ScriptFlagHandler.PrepareScript(flagLines, section.Name)
.HasErrored(out var flagError, out var flags))
{
return $"Section '{section.Name}' has invalid flags: {flagError}";
}
preparedFlags[section.Name] = flags;
}
return new Snapshot(path, fileName, content, lastWriteTimeUtc, length, sections, preparedFlags);
}
private static Result CommitSnapshot(Snapshot candidate)
{
SnapshotsByPath.TryGetValue(candidate.Path, out var previous);
if (previous is not null)
{
UnbindSnapshot(previous);
}
List<ScriptName> boundSections = [];
foreach (var section in candidate.Sections)
{
var flags = candidate.Flags[section.Name];
if (flags.Count == 0)
{
continue;
}
if (ScriptFlagHandler.BindScript(section.Name, flags).HasErrored(out var bindError))
{
boundSections.ForEach(ScriptFlagHandler.UnregisterScript);
if (previous is not null && RebindSnapshot(previous).HasErrored(out var rollbackError))
{
Log.Error($"Failed to restore script '{previous.FileName}' after reload failure: {rollbackError}");
}
return $"Section '{section.Name}' failed to register: {bindError}";
}
boundSections.Add(section.Name);
}
SnapshotsByPath[candidate.Path] = candidate;
RebuildFileNameIndex();
return true;
}
private static Result RebindSnapshot(Snapshot snapshot)
{
List<ScriptName> reboundSections = [];
foreach (var section in snapshot.Sections)
{
var flags = snapshot.Flags[section.Name];
if (flags.Count > 0 && ScriptFlagHandler.BindScript(section.Name, flags).HasErrored(out var error))
{
reboundSections.ForEach(ScriptFlagHandler.UnregisterScript);
return error;
}
if (flags.Count > 0)
{
reboundSections.Add(section.Name);
}
}
return true;
}
private static void RestoreSnapshotBinding(string path)
{
if (!SnapshotsByPath.TryGetValue(path, out var snapshot)
|| snapshot.Flags.All(pair => pair.Value.Count == 0 || ScriptFlagHandler.ScriptsFlags.ContainsKey(pair.Key)))
{
return;
}
// Map initialization clears live bindings. Rebind the accepted in-memory snapshot
// without rereading a file that may have changed since the last explicit reload.
UnbindSnapshot(snapshot);
if (RebindSnapshot(snapshot).HasErrored(out var error))
{
Log.Error($"Failed to restore the last known-good version of script '{snapshot.FileName}': {error}");
}
}
private static void UnbindSnapshot(Snapshot snapshot)
{
foreach (var section in snapshot.Sections)
{
ScriptFlagHandler.UnregisterScript(section.Name);
}
}
private static string? RemoveSnapshot(string path)
{
FailedFileStamps.Remove(path);
FailedScriptsByPath.Remove(path);
if (!SnapshotsByPath.TryGetValue(path, out var snapshot))
{
return null;
}
UnbindSnapshot(snapshot);
SnapshotsByPath.Remove(path);
RebuildFileNameIndex();
return snapshot.FileName;
}
private static void RebuildFileNameIndex()
{
SnapshotsByFileName.Clear();
foreach (var snapshot in SnapshotsByPath.Values)
{
SnapshotsByFileName[snapshot.FileName] = snapshot;
}
}
private static bool TryGetFileStamp(string path, out DateTime lastWriteTimeUtc, out long length)
{
try
{
var info = new FileInfo(path);
info.Refresh();
if (!info.Exists)
{
lastWriteTimeUtc = default;
length = default;
return false;
}
lastWriteTimeUtc = info.LastWriteTimeUtc;
length = info.Length;
return true;
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
lastWriteTimeUtc = default;
length = default;
return false;
}
}
private static TryGet<ScriptFile> ReadStableScriptFile(string path)
{
for (var attempt = 0; attempt < 3; attempt++)
{
if (!TryGetFileStamp(path, out var writeTimeBeforeRead, out var lengthBeforeRead))
{
return "Failed to inspect the script before reading it.";
}
string content;
try
{
content = File.ReadAllText(path);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
return $"Failed to read script: {exception.Message}";
}
if (!TryGetFileStamp(path, out var writeTimeAfterRead, out var lengthAfterRead))
{
return "Failed to inspect the script after reading it.";
}
if (writeTimeBeforeRead == writeTimeAfterRead && lengthBeforeRead == lengthAfterRead)
{
return new ScriptFile(content, writeTimeAfterRead, lengthAfterRead);
}
}
return "The script kept changing while SER tried to read it; it will be retried on the next refresh.";
}
}