using System.Collections.Concurrent;
using Serilog;
using ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol;
using ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol.V1;
using ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms;
using ZB.MOM.WW.OtOpcUa.Core.VirtualTags;
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess;
///
/// The host's side of the compiled-PE cache (lmxopcua#780 design §7), which since lmxopcua#1014 is the ONLY side:
/// the host verifies entries under a key only it holds and ships a verified image to the worker inside the load, and
/// it fills the cache with its OWN compile — a worker never writes an entry and never sees the key.
///
///
///
/// Why (review 2026-12-02 K-1, option 4). The worker used to read, verify and write the cache itself with
/// the key it received in Hello, and a verified image is loaded without re-running the analyzer. Code
/// that escaped inside a worker could therefore sign an entry for ANY script's source and have it loaded by every
/// later worker, across restarts and redeploys. A worker is the component that runs Designer-authored code, so it
/// must hold nothing that lets it persist.
///
///
/// Fill. After a worker reports a successful compile of a source the cache did not have, the host queues
/// its own compile of the same source on one background thread (below-normal priority, de-duplicated) and writes
/// the signed entry. Filling only after the worker's compile succeeded keeps a source that crashes Roslyn inside
/// the worker, where the isolation machinery contains it — the host never compiles a source first. A host compile
/// is the same pipeline the in-process runner and the deploy gate use (analyzer included); its image is never
/// loaded in the host.
///
///
/// Compatibility. The host compiles against its own runtime, so it ships images only to a worker whose
/// Ready.pe_image_abi equals ; any other worker (including a pre-#1014
/// one, which reports none) compiles every script, as with no cache.
///
///
internal sealed class HostPeCache : IDisposable
{
/// A fill backlog above this is dropped (best effort: a dropped fill costs a recompile at the next start).
internal const int MaxQueuedFills = 10_000;
private readonly ScriptPeCacheStore _store;
private readonly ILogger _log;
private readonly ConcurrentDictionary _queued = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary _abiWarned = new(StringComparer.Ordinal);
private readonly BlockingCollection _fills = new(new ConcurrentQueue());
private readonly object _idleGate = new();
private TaskCompletionSource _idle = NewCompleted();
private int _outstanding;
private Thread? _thread;
private int _failureLogged;
private volatile bool _disposed;
/// Creates the host cache over .
/// The store, opened with the node's key.
/// Host diagnostics.
public HostPeCache(ScriptPeCacheStore store, ILogger log)
{
_store = store ?? throw new ArgumentNullException(nameof(store));
_log = log ?? throw new ArgumentNullException(nameof(log));
}
/// The cache directory.
public string Directory => _store.Directory;
/// Whether a worker reporting may be sent this host's images.
/// The worker's Ready.pe_image_abi.
/// True when it equals .
public bool IsCompatible(string? workerImageAbi)
=> string.Equals(workerImageAbi, ScriptSandbox.ImageAbi, StringComparison.Ordinal);
/// Logs, once per distinct value, that a worker is not served images because its ABI differs.
/// The worker's shard.
/// What it reported.
public void NoteIncompatible(string shard, string? workerImageAbi)
{
if (!_abiWarned.TryAdd(workerImageAbi ?? string.Empty, 0)) return;
_log.Warning(
"ScriptWorker {Shard} reports image ABI {WorkerAbi}, not the host's {HostAbi}: the PE cache is not used for it and it compiles every script",
shard, string.IsNullOrEmpty(workerImageAbi) ? "(none — a pre-#1014 worker)" : workerImageAbi, ScriptSandbox.ImageAbi);
}
/// Reads and verifies the entry for one source. A rejected entry has been deleted.
/// The context kind.
/// The source.
/// The verified image on a hit.
/// Hit, miss or rejected.
public PeCacheLookup Lookup(ContextKind kind, string source, out byte[]? image)
{
image = null;
try
{
return _store.TryRead(EntryId(kind, source), out image);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Best effort: an unreadable entry is a miss (the fill will try to replace it).
return PeCacheLookup.Miss;
}
}
/// Deletes the entry for one source (its image did not load in a worker).
/// The context kind.
/// The source.
public void Evict(ContextKind kind, string source)
{
try { File.Delete(_store.EntryPath(EntryId(kind, source))); }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { }
}
///
/// Queues the host's own compile of into the cache. Call only after a worker compiled
/// it successfully. Duplicates of a queued fill are ignored; past the fill is dropped.
///
/// The context kind.
/// The source.
public void QueueFill(ContextKind kind, string source)
{
if (_disposed || kind is not (ContextKind.VirtualTag or ContextKind.Calculation or ContextKind.AlarmPredicate)) return;
var id = EntryId(kind, source);
if (_queued.Count >= MaxQueuedFills || !_queued.TryAdd(id, 0)) return;
lock (_idleGate)
{
if (_outstanding++ == 0) _idle = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
if (_thread is null)
{
_thread = new Thread(FillLoop) { IsBackground = true, Name = "ScriptPeCache.Fill", Priority = ThreadPriority.BelowNormal };
_thread.Start();
}
}
bool added;
try { added = _fills.TryAdd(new Fill(id, kind, source)); }
catch (InvalidOperationException) { added = false; } // disposed meanwhile
if (!added) Done(id);
}
/// Completes when no fill is queued or running (tests; a fill is best effort and never awaited in production).
/// The idle task.
public Task WhenIdleAsync()
{
lock (_idleGate) return _idle.Task;
}
///
public void Dispose()
{
if (_disposed) return;
_disposed = true;
try { _fills.CompleteAdding(); } catch (ObjectDisposedException) { }
}
private void FillLoop()
{
foreach (var fill in _fills.GetConsumingEnumerable())
{
try
{
if (!_disposed) RunFill(fill);
}
finally
{
Done(fill.Id);
}
}
}
private void RunFill(Fill fill)
{
// Another shard's load of the same source may have filled it already; a present entry that does not verify is
// deleted by the read and refilled here.
if (_store.TryRead(fill.Id, out _) == PeCacheLookup.Hit) return;
try
{
var image = fill.Kind == ContextKind.AlarmPredicate
? ScriptEvaluator.CompileToImage(fill.Source)
: ScriptEvaluator.CompileToImage(fill.Source);
if (!_store.TryWrite(fill.Id, image) && Interlocked.Exchange(ref _failureLogged, 1) == 0)
_log.Warning("Script PE cache {Directory}: an entry could not be written; ScriptWorkers will recompile those scripts on each start",
_store.Directory);
}
catch (Exception ex)
{
// The worker compiled this source, so a host compile that fails is an environment difference (or a defect):
// never fatal — the worker keeps compiling it, as with no cache.
if (Interlocked.Exchange(ref _failureLogged, 1) == 0)
_log.Warning(ex, "Script PE cache {Directory}: the host could not compile a script a worker compiled; it will not be cached",
_store.Directory);
}
}
private void Done(string id)
{
_queued.TryRemove(id, out _);
lock (_idleGate)
{
if (--_outstanding == 0) _idle.TrySetResult();
}
}
/// The entry id for one source: the HOST's compile fingerprint for the kind's context, the kind, the source.
internal static string EntryId(ContextKind kind, string source)
{
var fingerprint = kind == ContextKind.AlarmPredicate
? ScriptEvaluator.CacheFingerprint
: ScriptEvaluator.CacheFingerprint;
return ScriptPeCacheStore.EntryId(fingerprint, (int)kind, source);
}
private static TaskCompletionSource NewCompleted()
{
var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
tcs.TrySetResult();
return tcs;
}
private sealed record Fill(string Id, ContextKind Kind, string Source);
}