Repository navigation
Expand file tree
/
Copy pathScriptReloadHost.cs
More file actions
1037 lines (984 loc) · 41.7 KB
/
Copy pathScriptReloadHost.cs
File metadata and controls
1037 lines (984 loc) · 41.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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Inno.Core.Diagnostics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using Inno.Assets;
using Inno.Assets.Pipeline;
using Inno.Plugins.Authoring;
using Inno.Extensibility.Modules;
using Inno.Extensibility.Reload;
using Inno.Extensibility.Types;
using Inno.Core.Settings;
using Inno.Scripting.Compiler;
namespace Inno.Scripting.Reload;
/// <summary>
/// Watches, compiles, and atomically activates one project's C# script assemblies.
/// </summary>
public sealed class ScriptReloadHost : IDisposable
{
private const float C_COMPILATION_PROGRESS_SHARE = 0.8f;
private const float C_STAGING_PROGRESS = 0.86f;
private const float C_MIGRATION_PROGRESS = 0.94f;
private const float C_UNLOAD_VERIFICATION_PROGRESS = 0.97f;
private readonly object m_sync = new();
private readonly AssetPipeline m_assets;
private readonly ScriptCompiler m_compiler;
private readonly ModuleHost m_modules;
private readonly ScriptReloadOptions m_options;
private readonly PluginEnvironment m_plugins;
private readonly ProjectSettingsStore m_settings;
private readonly IScriptReloadCoordinator m_reloads;
private readonly Func<ScriptModuleDeployment, IModuleSource> m_moduleSourceFactory;
private readonly SemaphoreSlim m_compileGate = new(1, 1);
private readonly CancellationTokenSource m_lifetimeCancellation = new();
private readonly TaskCompletionSource<Exception?> m_disposalCompleted = new(
TaskCreationOptions.RunContinuationsAsynchronously);
private readonly CancellationToken m_lifetimeToken;
private CancellationTokenSource? m_activeCompilationCancellation;
private ScriptCompilationResult? m_activeCompilation;
private PendingReload? m_pendingCompilation;
private ScriptCompilationResult? m_lastCompilation;
private readonly Dictionary<string, AssemblyModuleHandle> m_pluginModules = new(StringComparer.Ordinal);
private AssemblyModuleHandle? m_runtimeScriptModule;
private AssemblyModuleHandle? m_editorScriptModule;
private string? m_activeCompilationDirectory;
private readonly Dictionary<string, string> m_activeModuleFingerprints = new(StringComparer.Ordinal);
private ScriptReloadProgress m_progress = new(0, 0f, "Waiting for script changes.", false);
private long m_progressOperation;
private long m_activeProgressOperation;
private long m_retiringProgressOperation;
private bool m_acceptCompilerProgress;
private long m_lastCompileRequestTimestamp;
private long m_compilationStartedTimestamp;
private TimeSpan m_lastCompilationElapsed;
private ScriptReloadRequest m_requestedReload;
private bool m_initialCompileRequested;
private bool m_publishingGeneration;
private int m_disposeStarted;
private int m_isCompiling;
private volatile bool m_disposed;
/// <summary>
/// Creates a reload host for one compiler and runtime module owner.
/// </summary>
/// <param name="options">
/// The automatic compilation, debounce, and long-running warning policy.
/// </param>
/// <param name="compiler">
/// The compiler that produces immutable candidate script generations.
/// </param>
/// <param name="assets">
/// The authoring asset pipeline that supplies committed source artifacts.
/// </param>
/// <param name="plugins">
/// The Plugin environment that owns active and candidate source generations.
/// </param>
/// <param name="modules">
/// The module host that atomically activates compiled assemblies.
/// </param>
/// <param name="settings">
/// The project settings store rebuilt with each committed Plugin generation.
/// </param>
/// <param name="reloads">
/// The host-owned coordinator that commits dependent state together with script generations.
/// </param>
/// <param name="moduleSourceFactory">
/// The composition-owned factory that chooses the loading policy for each immutable script module.
/// It must return a fresh source without activating or publishing the module.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when any required dependency is null.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when the configured debounce duration is negative.
/// </exception>
public ScriptReloadHost(
ScriptReloadOptions options,
ScriptCompiler compiler,
AssetPipeline assets,
PluginEnvironment plugins,
ModuleHost modules,
ProjectSettingsStore settings,
IScriptReloadCoordinator reloads,
Func<ScriptModuleDeployment, IModuleSource> moduleSourceFactory
) {
ArgumentNullException.ThrowIfNull(options);
ArgumentNullException.ThrowIfNull(compiler);
ArgumentNullException.ThrowIfNull(assets);
ArgumentNullException.ThrowIfNull(plugins);
ArgumentNullException.ThrowIfNull(modules);
ArgumentNullException.ThrowIfNull(settings);
ArgumentNullException.ThrowIfNull(reloads);
ArgumentNullException.ThrowIfNull(moduleSourceFactory);
if (options.debounceMilliseconds < 0)
throw new ArgumentOutOfRangeException(nameof(options), "Debounce duration cannot be negative.");
if (options.compilationWarningTimeout <= TimeSpan.Zero &&
options.compilationWarningTimeout != Timeout.InfiniteTimeSpan)
{
throw new ArgumentOutOfRangeException(
nameof(options),
"Compilation warning timeout must be positive or infinite.");
}
if (options.unloadCollectionInterval < TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(options), "Unload collection interval cannot be negative.");
if (options.unloadRetentionTimeout <= TimeSpan.Zero &&
options.unloadRetentionTimeout != Timeout.InfiniteTimeSpan)
{
throw new ArgumentOutOfRangeException(
nameof(options),
"Unload retention timeout must be positive or infinite.");
}
m_assets = assets;
m_compiler = compiler;
m_plugins = plugins;
m_modules = modules;
m_settings = settings;
m_reloads = reloads;
m_moduleSourceFactory = moduleSourceFactory;
m_options = new ScriptReloadOptions
{
autoCompile = options.autoCompile,
debounceMilliseconds = options.debounceMilliseconds,
compilationWarningTimeout = options.compilationWarningTimeout,
unloadCollectionInterval = options.unloadCollectionInterval,
unloadRetentionTimeout = options.unloadRetentionTimeout
};
m_modules.generations.Configure(new AssemblyUnloadBarrierOptions
{
collectionInterval = options.unloadCollectionInterval,
retentionTimeout = options.unloadRetentionTimeout
});
m_lifetimeToken = m_lifetimeCancellation.Token;
}
/// <summary>
/// Gets whether a compilation currently owns the compiler gate.
/// </summary>
public bool isCompiling => Volatile.Read(ref m_isCompiling) != 0;
/// <summary>
/// Gets whether source or plugin changes are waiting to be compiled.
/// </summary>
public bool isCompilationPending
{
get
{
lock (m_sync)
return m_requestedReload != ScriptReloadRequest.None;
}
}
/// <summary>
/// Gets one atomically published operation, fraction, stage and cancellation snapshot.
/// </summary>
public ScriptReloadProgress progress => Volatile.Read(ref m_progress);
/// <summary>
/// Gets the elapsed duration of the active or most recently completed compilation.
/// </summary>
public TimeSpan compilationElapsed
{
get
{
long started = Volatile.Read(ref m_compilationStartedTimestamp);
return isCompiling && started != 0
? TimeSpan.FromMilliseconds(Math.Max(0, Environment.TickCount64 - started))
: m_lastCompilationElapsed;
}
}
/// <summary>
/// Gets whether the active compilation exceeded the configured warning duration.
/// </summary>
public bool isCompilationTakingLong
=> isCompiling &&
m_options.compilationWarningTimeout != Timeout.InfiniteTimeSpan &&
compilationElapsed >= m_options.compilationWarningTimeout;
/// <summary>
/// Gets the most recently completed compilation.
/// </summary>
public ScriptCompilationResult? lastCompilation
{
get
{
lock (m_sync)
return m_lastCompilation;
}
}
/// <summary>
/// Gets whether retired collectible assembly generations are still being verified for unload.
/// </summary>
public bool isUnloadVerificationPending
{
get
{
lock (m_sync)
return m_modules.generations.state == GenerationState.AwaitingCollection;
}
}
/// <summary>
/// Gets whether a retired generation exceeded the retention threshold and permanently stopped this host.
/// </summary>
public bool isFaulted
{
get
{
lock (m_sync)
return m_modules.generations.state == GenerationState.Faulted;
}
}
/// <summary>
/// Subscribes to committed asset changes and queues a cache-aware initial compilation request.
/// </summary>
public void Start()
{
ObjectDisposedException.ThrowIf(m_disposed, this);
if (!m_assets.isInitialized)
throw new InvalidOperationException("ScriptReloadHost requires AssetPipeline to be initialized first.");
m_assets.Update();
m_assets.Changed -= OnAssetDatabaseChanged;
m_assets.Changed += OnAssetDatabaseChanged;
m_assets.SourceMountsChanged -= OnSourceMountsChanged;
m_assets.SourceMountsChanged += OnSourceMountsChanged;
m_plugins.ActivationCandidateChanged -= OnPluginActivationCandidateChanged;
m_plugins.ActivationCandidateChanged += OnPluginActivationCandidateChanged;
if (m_options.autoCompile)
{
lock (m_sync)
{
bool hasActiveScripting = m_modules.isInitialized &&
m_modules.modules.Any(static module => module.domain == AssemblyDomain.InnoScripting);
m_requestedReload = m_plugins.hasPendingActivation
? ScriptReloadRequest.ReloadPlugins
: hasActiveScripting
? ScriptReloadRequest.Recompile
: ScriptReloadRequest.ReloadScripting;
m_initialCompileRequested = true;
m_lastCompileRequestTimestamp = Environment.TickCount64;
Volatile.Write(ref m_progress, new ScriptReloadProgress(++m_progressOperation, 0f,
"Initial scripting cache probe queued.", false));
}
}
}
/// <summary>
/// Requests cancellation of the active compilation without changing the active script generation.
/// </summary>
/// <returns>
/// <see langword="true"/> when an active compilation received the request.
/// </returns>
/// <exception cref="ObjectDisposedException">
/// Thrown after the manager has been disposed.
/// </exception>
/// <param name="operationId">
/// The observed request; a stale cancellation is rejected.
/// </param>
public bool CancelCompilation(long operationId)
{
ObjectDisposedException.ThrowIf(m_disposed, this);
CancellationTokenSource? cancellation;
lock (m_sync)
{
if (operationId != m_progress.operationId || operationId != m_activeProgressOperation)
return false;
cancellation = m_activeCompilationCancellation;
if (cancellation is not null)
SetCompilationProgress(m_progress.fraction, "Canceling script compilation...", operationId, cancellationRequested: true);
}
if (cancellation is null)
return false;
try
{
cancellation.Cancel();
}
catch (ObjectDisposedException)
{
return false;
}
return true;
}
/// <summary>
/// Queues incremental recompilation of changed script assemblies.
/// </summary>
/// <exception cref="ObjectDisposedException">
/// Thrown after the manager has been disposed.
/// </exception>
public void RecompileScripting()
{
QueueReload(ScriptReloadRequest.Recompile);
}
/// <summary>
/// Queues a complete rebuild of both scripting load contexts while retaining the plugin generation.
/// Valid cached artifacts are reused.
/// </summary>
/// <exception cref="ObjectDisposedException">
/// Thrown after the manager has been disposed.
/// </exception>
public void ReloadScripting() => QueueReload(ScriptReloadRequest.ReloadScripting);
/// <summary>
/// Queues replacement of the unified plugin generation and both dependent scripting generations.
/// Valid script artifacts are reused when plugin reference fingerprints are unchanged.
/// </summary>
/// <exception cref="ObjectDisposedException">
/// Thrown after the manager has been disposed.
/// </exception>
public void ReloadPlugins() => QueueReload(ScriptReloadRequest.ReloadPlugins);
/// <summary>
/// Starts a pending compilation after the configured quiet period has elapsed.
/// </summary>
/// <remarks>
/// The initial automatic request is immediately ready and does not observe the debounce duration.
/// </remarks>
/// <param name="compilation">
/// The started compilation task, or <see langword="null"/> when none was ready.
/// </param>
/// <returns>
/// <see langword="true"/> when a pending compilation was started.
/// </returns>
public bool TryCompilePending(out Task<ScriptCompilationResult>? compilation)
{
ObjectDisposedException.ThrowIf(m_disposed, this);
if (!m_modules.generations.TryAcquireChange("start pending script compilation", out IDisposable? admission))
{
compilation = null;
return false;
}
admission!.Dispose();
ScriptReloadRequest request;
long operation;
lock (m_sync)
{
ThrowIfFaultedLocked();
if (m_modules.generations.state == GenerationState.AwaitingCollection)
{
compilation = null;
return false;
}
long elapsed = Environment.TickCount64 - m_lastCompileRequestTimestamp;
if (m_requestedReload == ScriptReloadRequest.None ||
isCompiling ||
!m_initialCompileRequested && elapsed < m_options.debounceMilliseconds)
{
compilation = null;
return false;
}
request = m_requestedReload;
operation = m_progress.operationId;
m_requestedReload = ScriptReloadRequest.None;
m_initialCompileRequested = false;
}
if (m_assets.isInitialized)
m_assets.Update();
PluginUnavailabilityPlan? unavailability = request == ScriptReloadRequest.ReloadPlugins
? CapturePluginUnavailabilityPlan()
: null;
compilation = CompileAsync(request, unavailability, operation).AsTask();
return true;
}
private async ValueTask<ScriptCompilationResult> CompileAsync(
ScriptReloadRequest request,
PluginUnavailabilityPlan? unavailability,
long operation,
CancellationToken cancellationToken = default
) {
ObjectDisposedException.ThrowIf(m_disposed, this);
using CancellationTokenSource linkedCancellation = CancellationTokenSource.CreateLinkedTokenSource(
cancellationToken,
m_lifetimeToken);
CancellationToken effectiveCancellation = linkedCancellation.Token;
await m_compileGate.WaitAsync(effectiveCancellation).ConfigureAwait(false);
try
{
effectiveCancellation.ThrowIfCancellationRequested();
ObjectDisposedException.ThrowIf(m_disposed, this);
Volatile.Write(ref m_isCompiling, 1);
Volatile.Write(ref m_compilationStartedTimestamp, Environment.TickCount64);
lock (m_sync)
{
m_activeCompilationCancellation = linkedCancellation;
m_activeProgressOperation = operation;
m_acceptCompilerProgress = true;
}
SetCompilationProgress(0f, "Preparing script compilation...", operation, canCancel: true);
ScriptCompilationResult result;
try
{
result = await m_compiler
.CompileAuthoringGenerationAsync(
new ScriptProgressObserver((
progress,
status
) => SetCompilationProgress(
progress * C_COMPILATION_PROGRESS_SHARE,
progress >= 1f ? "Compilation finished; waiting for generation activation and state recovery." : status,
operation, isCompilerUpdate: true)),
effectiveCancellation)
.ConfigureAwait(false);
}
catch (OperationCanceledException) when (effectiveCancellation.IsCancellationRequested)
{
throw;
}
catch (Exception exception)
{
result = ScriptCompilationResult.Failure(
new ScriptDiagnostic(
"INNO0001",
DiagnosticSeverity.Error,
exception.ToString(),
filePath: null,
line: 0,
column: 0));
}
lock (m_sync)
{
if (!m_disposed)
{
m_acceptCompilerProgress = false;
m_lastCompilation = result;
if (m_requestedReload != ScriptReloadRequest.None)
{
if (request > m_requestedReload)
m_requestedReload = request;
m_pendingCompilation = null;
}
else if (result.success || unavailability is not null)
{
m_pendingCompilation = new PendingReload(
result,
request,
operation,
result.success ? null : unavailability);
}
SetCompilationProgress(
result.success || unavailability is not null ? C_COMPILATION_PROGRESS_SHARE : progress.fraction,
m_requestedReload != ScriptReloadRequest.None
? "Compilation superseded by a queued reload request."
: result.success
? "Script compilation completed; waiting for generation activation and state recovery."
: unavailability is not null
? "Compilation failed after a Plugin availability change; the unavailable " +
"generation is ready to activate."
: "Script compilation failed.", operation);
}
}
return result;
}
finally
{
long started = Interlocked.Exchange(ref m_compilationStartedTimestamp, 0);
if (started != 0)
{
m_lastCompilationElapsed = TimeSpan.FromMilliseconds(
Math.Max(0, Environment.TickCount64 - started));
}
lock (m_sync)
{
if (ReferenceEquals(m_activeCompilationCancellation, linkedCancellation))
{
m_activeCompilationCancellation = null;
m_acceptCompilerProgress = false;
}
}
Volatile.Write(ref m_isCompiling, 0);
m_compileGate.Release();
}
}
/// <summary>
/// Applies the latest compiled generation, or commits a Plugin-unavailability generation when changed
/// Plugin code cannot produce a replacement, at a caller-controlled main-thread safe point.
/// </summary>
/// <returns>
/// <see langword="true"/> when modules were replaced or retired; otherwise, <see langword="false"/>.
/// </returns>
/// <exception cref="ObjectDisposedException">
/// Thrown after the manager has been disposed.
/// </exception>
public bool ApplyPendingReload()
{
ObjectDisposedException.ThrowIf(m_disposed, this);
PendingReload? pending;
lock (m_sync)
{
ThrowIfFaultedLocked();
if (m_modules.generations.state == GenerationState.AwaitingCollection)
throw new InvalidOperationException("A new script generation cannot activate before the previous unload barrier completes.");
pending = m_pendingCompilation;
if (pending is not null && m_requestedReload != ScriptReloadRequest.None)
{
if (pending.request > m_requestedReload)
m_requestedReload = pending.request;
m_pendingCompilation = null;
pending = null;
}
}
if (pending is null)
return false;
ReloadPlan plan = SelectReloadPlan(pending);
if (plan.requests.Count == 0 && plan.removedModuleNames.Count == 0)
{
m_plugins.ApplyPendingChange();
CompletePendingReload(pending);
m_reloads.RefreshDiagnostics();
SetCompilationProgress(1f, "No scripting changes detected.", pending.operationId);
return false;
}
SetCompilationProgress(C_STAGING_PROGRESS, "Staging script reload candidates...", pending.operationId);
using AssemblyReloadSession reload = m_modules.BeginReload(
plan.requests.Select(m_moduleSourceFactory).ToArray(),
plan.removedModuleNames);
SetCompilationProgress(C_MIGRATION_PROGRESS, "Restoring active editor state...", pending.operationId);
IAssemblyUnloadProbe unload = PublishGeneration(reload);
m_modules.generations.TrackRetirement(unload);
m_retiringProgressOperation = pending.operationId;
m_activeCompilationDirectory = pending.unavailability is null
? pending.compilation.outputDirectory
: null;
_ = m_compiler.CollectArtifacts(m_activeCompilationDirectory is null
? Array.Empty<string?>()
: [m_activeCompilationDirectory]);
RefreshModuleHandles();
UpdateActiveFingerprints(plan);
string completedStatus = pending.unavailability is null
? "Script reload completed."
: "Plugin availability change committed. Unavailable scene types are preserved as Missing until their " +
"Stable IDs return.";
SetCompilationProgress(
!isUnloadVerificationPending ? 1f : C_UNLOAD_VERIFICATION_PROGRESS,
!isUnloadVerificationPending
? completedStatus
: completedStatus + " Verifying retired assembly unload...", pending.operationId);
m_reloads.RefreshDiagnostics();
CompletePendingReload(pending);
return true;
}
/// <summary>
/// Generates standard SDK-style game/editor projects and a solution for IDE tooling.
/// </summary>
/// <exception cref="ObjectDisposedException">
/// Thrown after the manager has been disposed.
/// </exception>
public void GenerateProjectFiles()
{
ObjectDisposedException.ThrowIf(m_disposed, this);
if (m_assets.isInitialized)
{
m_assets.Update();
m_assets.Rescan();
}
m_compiler.GenerateProjectFiles();
}
/// <summary>
/// Cancels and waits for active compilation work, stops Asset Database observation, and unloads
/// the active script module.
/// </summary>
public void Dispose()
{
if (Interlocked.Exchange(ref m_disposeStarted, 1) != 0)
{
Exception? previousFailure = m_disposalCompleted.Task.GetAwaiter().GetResult();
if (previousFailure is not null)
ExceptionDispatchInfo.Capture(previousFailure).Throw();
return;
}
Exception? disposalFailure = null;
try
{
m_disposed = true;
m_lifetimeCancellation.Cancel();
m_compileGate.Wait();
try
{
if (m_assets.isInitialized)
{
m_assets.Changed -= OnAssetDatabaseChanged;
m_assets.SourceMountsChanged -= OnSourceMountsChanged;
}
m_plugins.ActivationCandidateChanged -= OnPluginActivationCandidateChanged;
lock (m_sync)
{
m_requestedReload = ScriptReloadRequest.None;
m_initialCompileRequested = false;
m_pendingCompilation = null;
}
if (m_modules.isInitialized)
{
// Shutdown is a new module publication and must not overlap a previous GC barrier.
m_modules.generations.Wait();
AssemblyModuleHandle[] modules =
[
.. new[] { m_editorScriptModule, m_runtimeScriptModule }
.OfType<AssemblyModuleHandle>(),
.. m_pluginModules.Values
];
if (modules.Length > 0)
_ = m_modules.Unload(modules);
m_pluginModules.Clear();
m_runtimeScriptModule = null;
m_editorScriptModule = null;
if (modules.Length > 0 && m_assets.isInitialized)
m_assets.Rescan();
}
m_activeCompilationDirectory = null;
m_activeCompilation = null;
}
finally
{
m_compileGate.Release();
m_lifetimeCancellation.Dispose();
}
GC.SuppressFinalize(this);
}
catch (Exception exception)
{
disposalFailure = exception;
throw;
}
finally
{
m_disposalCompleted.TrySetResult(disposalFailure);
}
}
/// <summary>
/// Advances cooperative unload verification for retired script generations.
/// </summary>
/// <param name="failure">
/// Receives the retention failure after all verification attempts, otherwise <see langword="null"/>.
/// </param>
/// <returns>
/// <see langword="true"/> when no additional verification frame is required.
/// </returns>
public bool AdvanceUnloadVerification(out Exception? failure)
{
failure = m_modules.generations.failure;
if (failure is not null)
{
SetCompilationProgress(progress.fraction, "Generation retirement failed. Restart the host before Play, Build, Export or reload.");
return true;
}
try
{
if (!m_modules.generations.Advance())
{
SetCompilationProgress(C_UNLOAD_VERIFICATION_PROGRESS, "Verifying retired generation unload...", m_retiringProgressOperation);
return false;
}
SetCompilationProgress(1f, "Generation publication and retired assembly unload completed.", m_retiringProgressOperation);
return true;
}
catch (Exception exception)
{
failure = exception;
SetCompilationProgress(progress.fraction, "Generation retirement failed. Restart the host before Play, Build, Export or reload.");
return true;
}
}
private void OnAssetDatabaseChanged(AssetChangeSet changeSet)
{
if (m_disposed || !m_options.autoCompile)
return;
for (int i = 0; i < changeSet.changes.Count; i++)
{
AssetChange change = changeSet.changes[i];
string path = change.assetPath.ToString();
string previousPath = change.previousAssetPath?.ToString() ?? string.Empty;
if (!IsScriptInput(path) && !IsScriptInput(previousPath))
continue;
QueueReload(IsPluginInput(path) || IsPluginInput(previousPath)
? ScriptReloadRequest.ReloadPlugins
: ScriptReloadRequest.Recompile);
return;
}
}
private void OnSourceMountsChanged()
{
if (m_disposed || !m_options.autoCompile || m_publishingGeneration)
return;
if (m_plugins.hasPendingActivation)
return;
QueueReload(ScriptReloadRequest.ReloadPlugins);
}
private IAssemblyUnloadProbe PublishGeneration(AssemblyReloadSession reload)
{
// Catalog republication belongs to this candidate, not to a new source edit. Only this
// synchronous notification is suppressed; actual source edits and explicit requests stay queued.
m_publishingGeneration = true;
try
{
return m_reloads.Execute(reload, m_plugins.CreateReloadChange());
}
finally
{
m_publishingGeneration = false;
}
}
private void OnPluginActivationCandidateChanged()
{
if (m_disposed || !m_options.autoCompile)
return;
QueueReload(ScriptReloadRequest.ReloadPlugins);
}
private void SetCompilationProgress(
float fraction,
string stage,
long? operationId = null,
bool cancellationRequested = false,
bool isCompilerUpdate = false,
bool canCancel = false
) {
lock (m_sync)
{
ScriptReloadProgress current = m_progress;
if (m_disposed || (operationId is long expected && expected != current.operationId))
return;
if (isCompilerUpdate && (!m_acceptCompilerProgress || current.cancellationRequested))
return;
Volatile.Write(ref m_progress, new ScriptReloadProgress(current.operationId,
Math.Clamp(fraction, 0f, 1f), stage, current.cancellationRequested || cancellationRequested,
m_activeCompilationCancellation is not null && m_activeProgressOperation == current.operationId &&
(canCancel || isCompilerUpdate) && !current.cancellationRequested && !cancellationRequested));
}
}
private void QueueReload(ScriptReloadRequest request)
{
ObjectDisposedException.ThrowIf(m_disposed, this);
lock (m_sync)
{
ThrowIfFaultedLocked();
if (request > m_requestedReload)
m_requestedReload = request;
m_lastCompileRequestTimestamp = Environment.TickCount64;
Volatile.Write(ref m_progress, new ScriptReloadProgress(++m_progressOperation, 0f, m_requestedReload switch
{
ScriptReloadRequest.ReloadPlugins => "Plugin and scripting reload queued.",
ScriptReloadRequest.ReloadScripting => "Full scripting reload queued.",
_ => "Scripting recompile queued."
}, false));
}
}
private ReloadPlan SelectReloadPlan(PendingReload pending)
{
if (pending.unavailability is not null)
{
return new ReloadPlan(
Array.Empty<ScriptModuleDeployment>(),
pending.unavailability.removedModuleNames);
}
IReadOnlyList<ScriptModuleDeployment> requests = pending.compilation.moduleDeployments;
string[] candidatePlugins = requests
.Where(static request => request.domain == AssemblyDomain.InnoPlugin)
.Select(static request => request.moduleName)
.ToArray();
string[] removedPlugins = pending.request == ScriptReloadRequest.ReloadPlugins
? m_pluginModules.Keys.Except(candidatePlugins, StringComparer.Ordinal).ToArray()
: [];
if (m_runtimeScriptModule is null || m_editorScriptModule is null ||
candidatePlugins.Any(plugin => !m_pluginModules.ContainsKey(plugin)))
{
return new ReloadPlan(requests, removedPlugins);
}
if (pending.request == ScriptReloadRequest.ReloadPlugins)
return new ReloadPlan(requests, removedPlugins);
if (pending.request == ScriptReloadRequest.ReloadScripting)
{
return new ReloadPlan(
requests.Where(static request => request.domain == AssemblyDomain.InnoScripting).ToArray(),
[]);
}
if (string.Equals(
pending.compilation.outputDirectory,
m_activeCompilationDirectory,
StringComparison.OrdinalIgnoreCase))
{
return new ReloadPlan([], []);
}
var compiled = pending.compilation.compiledAssemblyNames.ToHashSet(StringComparer.OrdinalIgnoreCase);
var selected = requests
.Where(request => GetOwnedAssemblyNames(request).Any(compiled.Contains) ||
!m_activeModuleFingerprints.TryGetValue(
request.moduleName,
out string? activeFingerprint) ||
!string.Equals(
ComputeRequestFingerprint(request),
activeFingerprint,
StringComparison.Ordinal))
.Select(static request => request.moduleName)
.ToHashSet(StringComparer.Ordinal);
if (selected.Any(name => requests.Any(request =>
request.domain == AssemblyDomain.InnoPlugin &&
string.Equals(request.moduleName, name, StringComparison.Ordinal))))
{
bool changed;
do
{
changed = false;
foreach (ScriptModuleDeployment request in requests.Where(static request =>
request.domain == AssemblyDomain.InnoPlugin))
{
if (!selected.Contains(request.moduleName) && request.upstreamModuleNames.Any(selected.Contains))
changed |= selected.Add(request.moduleName);
}
}
while (changed);
selected.UnionWith(requests
.Where(static request => request.domain == AssemblyDomain.InnoScripting)
.Select(static request => request.moduleName));
}
// Closed generic editor extensions over project runtime types can create CLR loader
// allocator dependencies in both directions even though assembly references are one-way.
// Project scripts therefore retire as one authoring generation, preserving scene state
// through the same candidate transaction used for runtime-source changes.
if (requests.Any(request => request.domain == AssemblyDomain.InnoScripting &&
selected.Contains(request.moduleName)))
{
selected.UnionWith(requests
.Where(static request => request.domain == AssemblyDomain.InnoScripting)
.Select(static request => request.moduleName));
}
return new ReloadPlan(
requests.Where(request => selected.Contains(request.moduleName)).ToArray(),
[]);
}
private void RefreshModuleHandles()
{
IReadOnlyList<AssemblyModuleInfo> modules = m_modules.modules;
m_pluginModules.Clear();
foreach (AssemblyModuleInfo module in modules.Where(static module =>
module.domain == AssemblyDomain.InnoPlugin &&
module.moduleName.StartsWith("Plugin.", StringComparison.Ordinal)))
{
m_pluginModules.Add(module.moduleName, module.handle);
}
m_runtimeScriptModule = modules.SingleOrDefault(static module =>
module.moduleName == "RuntimeScripts")?.handle;
m_editorScriptModule = modules.SingleOrDefault(static module =>
module.moduleName == "EditorScripts")?.handle;
}
private void UpdateActiveFingerprints(ReloadPlan plan)
{
foreach (string removed in plan.removedModuleNames)
m_activeModuleFingerprints.Remove(removed);
foreach (ScriptModuleDeployment request in plan.requests)
m_activeModuleFingerprints[request.moduleName] = ComputeRequestFingerprint(request);
}
private static IEnumerable<string> GetOwnedAssemblyNames(ScriptModuleDeployment request)
=> new[] { request.mainAssemblyPath }
.Concat(request.preloadAssemblyPaths)
.Select(static path => System.Reflection.AssemblyName.GetAssemblyName(path).Name ?? string.Empty);
private static string ComputeRequestFingerprint(ScriptModuleDeployment request)
{
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
foreach (string path in new[] { request.mainAssemblyPath }
.Concat(request.preloadAssemblyPaths)
.OrderBy(static value => value, StringComparer.OrdinalIgnoreCase))
{
byte[] name = System.Text.Encoding.UTF8.GetBytes(System.IO.Path.GetFileName(path));
hash.AppendData(name);
hash.AppendData(System.IO.File.ReadAllBytes(path));
}
return Convert.ToHexString(hash.GetHashAndReset());
}
private void CompletePendingReload(PendingReload applied)
{
lock (m_sync)
{
m_activeCompilation = applied.unavailability is null
? applied.compilation
: null;
if (ReferenceEquals(m_pendingCompilation, applied))
m_pendingCompilation = null;
}
}
private PluginUnavailabilityPlan? CapturePluginUnavailabilityPlan()
{
if (!m_plugins.hasPendingActivation || m_pluginModules.Count == 0)
return null;
Dictionary<string, string> candidatePluginHashes = m_plugins.compilationPlugins
.Where(static plugin => plugin.containsCode)
.ToDictionary(
static plugin => plugin.manifest.pluginId,
static plugin => plugin.contentHash,
StringComparer.Ordinal);
var removedModuleNames = m_plugins.activePlugins
.Where(static plugin => plugin.containsCode)
.Where(plugin => !candidatePluginHashes.TryGetValue(
plugin.manifest.pluginId,
out string? candidateHash) ||
!string.Equals(
plugin.contentHash,
candidateHash,
StringComparison.Ordinal))
.Select(static plugin => "Plugin." + plugin.manifest.pluginId)
.Where(m_pluginModules.ContainsKey)
.ToHashSet(StringComparer.Ordinal);
if (removedModuleNames.Count == 0)
return null;
AssemblyModuleInfo[] activeModules = m_modules.modules.ToArray();
bool changed;
do
{
changed = false;
foreach (AssemblyModuleInfo module in activeModules)
{
if (removedModuleNames.Contains(module.moduleName) ||
!module.upstreamModuleNames.Any(removedModuleNames.Contains))
{
continue;
}
changed |= removedModuleNames.Add(module.moduleName);
}
}
while (changed);
return new PluginUnavailabilityPlan(
removedModuleNames
.OrderBy(static moduleName => moduleName, StringComparer.Ordinal)
.ToArray());
}
private static bool IsScriptInput(string path)
=> path.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) ||
path.EndsWith(".iasmdef", StringComparison.OrdinalIgnoreCase);
private static bool IsPluginInput(string path)
{
if (string.IsNullOrWhiteSpace(path) || !IsScriptInput(path))
return false;
try
{
return AssetPath.Parse(path).source != AssetSourceId.project;
}
catch (ArgumentException)
{
return false;
}
}
private void ThrowIfFaultedLocked()
{
if (m_modules.generations.state == GenerationState.Faulted)