84b405ff5f
The compile cache was a `static` class, so its entry table and its Hits/Count
counters were one process-global blob every test class in the SiteRuntime
assembly wrote into. Row 91 last wave neutered the resulting flakes (per-test
GUID keys + one-sided counter bounds), but the shared mutable state itself
remained: any test calling Clear() evicted entries other parallel classes had
just inserted, and a Clear() from a class outside the serialized collection
would degrade the others to recompiles and re-open the row-91 flake class.
PREMISE CORRECTION: the register speculated production clears "per-instance or
per-deployment script entries" and offered ClearKeys(prefix) as the natural fit.
There are NO production callers of Clear() at all — grep of src/ finds only
GetOrAdd (ScriptCompilationService.CompileCore). Clear() existed solely so
tests could reset the global. A key-scoped API would therefore have been new
production surface built for nobody, so the instance-scoped seam is the fix and
Clear() is deleted outright rather than migrated.
- SiteScriptCompileCache: `internal static class` -> `internal sealed class`;
Cache/EvictionLock/_hits/_accessSequence become instance fields. LRU batch
eviction, the double-checked sweep and the ConcurrentDictionary.ToArray()
snapshot are byte-for-byte the same policy. Clear() removed.
- ScriptCompilationService owns one cache. Public ctor (the DI path) builds its
own; a new internal ctor takes one for tests. Production N4 sharing is
unchanged and now rests on the DI SINGLETON registration — the one service
instance is threaded to DeployCompileValidator and to every Instance Actor —
so that lifetime is load-bearing and is pinned by a new registration test.
- Tests: all three Clear() callers migrated off it. Each test now owns its cache,
which lets the assertions get STRONGER — the row-91 workarounds are retired:
Hits/Count are exact again (no >= baseline bounds), the per-test GUID key
token is gone, and ForeignEntrySlack (512 entries of allowance on the bound)
drops to the racing-thread count in the concurrency test. New test
SeparateCaches_DoNotShareEntriesOrCounters pins the scoping directly: filling
one cache past MaxEntries leaves another's entry, hit count and identity
intact. DeploymentWarmThenGateTests additionally asserts Count == 1 now that
its counter is private.
- The [Collection("SiteScriptCompileCache")] serialization from row 91 is
RELAXED (removed from all three classes) — they no longer touch any shared
state, so there is nothing left to serialize.
- Docs: Component-SiteRuntime.md gains the ownership/singleton note and drops
the Clear() reference; DeploymentManagerActor / DeployCompileValidator /
ServiceCollectionExtensions comments corrected to say where the cache lives.
Build: 0 warnings. SiteRuntime.Tests 643/643, three consecutive full-parallel
runs. AuditLog.Tests correlation classes (other ScriptCompilationService
consumers) green.
122 lines
5.7 KiB
C#
122 lines
5.7 KiB
C#
using System.Text.Json;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Types.Flattening;
|
|
using ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts;
|
|
|
|
namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Deployment;
|
|
|
|
/// <summary>
|
|
/// Pure, thread-safe deploy-time gate: given a flattened-configuration JSON, it
|
|
/// compiles every script, every alarm on-trigger script, and every Expression
|
|
/// trigger just as <see cref="Actors.InstanceActor.CreateChildActors"/> does at
|
|
/// runtime — but WITHOUT touching any actor state. It returns the collected
|
|
/// compile errors so the Deployment Manager can reject a deployment whose scripts
|
|
/// do not compile on the site (design spec: site-side compile failure rejects the
|
|
/// deployment; no partial state is applied).
|
|
///
|
|
/// Because it holds no actor state and only calls <see cref="ScriptCompilationService"/>
|
|
/// (whose only state is a thread-safe compile cache), it is pure and thread-safe; the
|
|
/// Deployment Manager nevertheless invokes it <em>synchronously on the singleton's actor
|
|
/// thread</em> as a pure prefix step, preserving mailbox-FIFO deploy ordering (see
|
|
/// <see cref="Actors.DeploymentManagerActor.HandleDeploy"/>). Compiles of unchanged
|
|
/// script bodies are deduped by that cache, which is shared across the whole site because
|
|
/// the compilation service is a DI singleton.
|
|
/// </summary>
|
|
public sealed class DeployCompileValidator
|
|
{
|
|
private readonly ScriptCompilationService _compilationService;
|
|
|
|
/// <summary>Initializes a new instance of the <see cref="DeployCompileValidator"/>.</summary>
|
|
/// <param name="compilationService">The same compilation service the Instance Actor uses at runtime.</param>
|
|
public DeployCompileValidator(ScriptCompilationService compilationService)
|
|
=> _compilationService = compilationService;
|
|
|
|
/// <summary>
|
|
/// Validates every compilable artifact in the flattened configuration.
|
|
/// Returns an empty list when the whole configuration compiles; otherwise
|
|
/// one human-readable error per failing artifact. Malformed JSON is itself a
|
|
/// single error (this also fronts the poison-config case for startup load).
|
|
/// </summary>
|
|
/// <param name="configJson">The flattened-configuration JSON to validate.</param>
|
|
/// <returns>A list of compile-error messages; empty if the configuration is clean.</returns>
|
|
public IReadOnlyList<string> Validate(string configJson)
|
|
{
|
|
FlattenedConfiguration? config;
|
|
try
|
|
{
|
|
config = JsonSerializer.Deserialize<FlattenedConfiguration>(configJson);
|
|
}
|
|
catch (JsonException ex)
|
|
{
|
|
return [$"Configuration JSON failed to deserialize: {ex.Message}"];
|
|
}
|
|
|
|
if (config == null)
|
|
return ["Configuration JSON failed to deserialize: result was null."];
|
|
|
|
var errors = new List<string>();
|
|
|
|
// Scripts: full execution-path compile against ScriptGlobals.
|
|
foreach (var script in config.Scripts)
|
|
{
|
|
var result = _compilationService.Compile(script.CanonicalName, script.Code);
|
|
if (!result.IsSuccess)
|
|
errors.Add($"Script '{script.CanonicalName}': {string.Join("; ", result.Errors)}");
|
|
|
|
// Expression-triggered scripts also compile their trigger expression.
|
|
AddTriggerExpressionError(errors, script.TriggerType, script.TriggerConfiguration,
|
|
$"script-trigger-{script.CanonicalName}");
|
|
}
|
|
|
|
// Alarms: on-trigger script reference must resolve + compile, and any
|
|
// Expression trigger must compile — mirrors InstanceActor.CreateChildActors.
|
|
foreach (var alarm in config.Alarms)
|
|
{
|
|
if (!string.IsNullOrEmpty(alarm.OnTriggerScriptCanonicalName))
|
|
{
|
|
var triggerScriptDef = config.Scripts
|
|
.FirstOrDefault(s => s.CanonicalName == alarm.OnTriggerScriptCanonicalName);
|
|
if (triggerScriptDef == null)
|
|
{
|
|
errors.Add($"Alarm '{alarm.CanonicalName}': on-trigger script " +
|
|
$"'{alarm.OnTriggerScriptCanonicalName}' is not defined.");
|
|
}
|
|
else
|
|
{
|
|
var result = _compilationService.Compile(
|
|
$"alarm-trigger-{alarm.CanonicalName}", triggerScriptDef.Code);
|
|
if (!result.IsSuccess)
|
|
errors.Add($"Alarm '{alarm.CanonicalName}' on-trigger script " +
|
|
$"'{alarm.OnTriggerScriptCanonicalName}': {string.Join("; ", result.Errors)}");
|
|
}
|
|
}
|
|
|
|
AddTriggerExpressionError(errors, alarm.TriggerType, alarm.TriggerConfiguration,
|
|
$"alarm-trigger-expr-{alarm.CanonicalName}");
|
|
}
|
|
|
|
return errors;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Compiles the boolean trigger expression for an Expression-triggered script
|
|
/// or alarm and records any failure. No-op for non-Expression triggers or a
|
|
/// blank/malformed expression config — mirroring
|
|
/// <c>InstanceActor.CompileTriggerExpression</c>, where those cases yield an
|
|
/// inert trigger rather than a deployment error.
|
|
/// </summary>
|
|
private void AddTriggerExpressionError(
|
|
List<string> errors, string? triggerType, string? triggerConfigJson, string compileName)
|
|
{
|
|
if (!string.Equals(triggerType, "Expression", StringComparison.OrdinalIgnoreCase))
|
|
return;
|
|
|
|
var expression = TriggerExpressionGlobals.ExtractExpression(triggerConfigJson);
|
|
if (expression == null)
|
|
return;
|
|
|
|
var result = _compilationService.CompileTriggerExpression(compileName, expression);
|
|
if (!result.IsSuccess)
|
|
errors.Add($"Trigger expression '{compileName}': {string.Join("; ", result.Errors)}");
|
|
}
|
|
}
|