Files
lmxopcua/src/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker/WorkerHost.cs
T
Joseph Doherty bed9620e31 fix(scripting): #1014 host owns the compiled-PE cache; the worker never holds the HMAC key
Review 2026-12-02 K-1 option 4 (#971 follow-up). The ScriptWorker used to read, verify and
WRITE the PE cache with the key it received in Hello, and a verified image is loaded without
re-running the analyzer — so code that escaped inside a worker could sign an entry for any
script's source and persist across restarts and redeploys.

- Hello no longer carries pe_cache_dir / pe_cache_key (fields reserved).
- HostPeCache: the host verifies an entry under its host-only key and ships the image in
  ScriptSource.pe_image; on a miss the worker compiles as before and, only after that compile
  succeeded, the host queues its OWN compile (one background thread, de-duplicated) and writes
  the signed entry. The worker loads a supplied image or compiles; it never opens the directory.
- Images go only to a worker whose Ready.pe_image_abi equals ScriptSandbox.ImageAbi (runtime +
  pinned assembly names); pre-#1014 workers report none and just compile.
- Entry format v2: every worker-written (possibly forged) v1 entry is rejected and refilled.
- Scripting:Worker:PeCacheDir and the directory layout are unchanged.
2026-12-03 15:12:17 -05:00

853 lines
38 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Collections;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO.Pipes;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
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.ScriptWorker;
/// <summary>
/// One worker's whole life (lmxopcua#780, design §3.2): handshake, compile-on-load, a bounded evaluation scheduler
/// on dedicated threads, a hard-deadline watchdog, heartbeats, and log forwarding. The host is authoritative for
/// deadlines (it kills this process); the watchdog is the belt to that brace and fails fast slightly later, so the
/// exit names the key that overran.
/// </summary>
/// <remarks>
/// Anything that means "the host is gone" — pipe end of stream, a protocol fault, the parent pid disappearing —
/// ends the process. The worker never outlives its host (design §3.3).
/// </remarks>
internal sealed class WorkerHost
{
/// <summary>The watchdog fails fast this long after the host's own hard deadline, so the host normally wins.</summary>
private static readonly TimeSpan WatchdogMargin = TimeSpan.FromMilliseconds(500);
/// <summary>The watchdog's longest sleep between passes.</summary>
private static readonly TimeSpan WatchdogPoll = TimeSpan.FromMilliseconds(50);
/// <summary>The host pipe, driven blocking (<see cref="ScriptWorkerFrameCodec.BlockingStream"/>).</summary>
private readonly Stream _pipe;
private readonly string _nonce;
private readonly int _parentPid;
private readonly ConcurrentDictionary<string, LoadedScript> _scripts = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<long, RunningEval> _running = new();
/// <summary>
/// Hand-off to an IDLE evaluation thread: an evaluation is put here only when a thread is known to be waiting
/// for it (<see cref="_idle"/>), so whatever is put here starts at once. Everything else waits in
/// <see cref="_backlog"/> and is reported to the host as deferred (lmxopcua#780 batch submit: per-item deadlines
/// stay exact, see the proto's <c>EvalResults</c>).
/// </summary>
private readonly BlockingCollection<EvalRequest> _queue = new(new ConcurrentQueue<EvalRequest>());
/// <summary>Evaluations that arrived while every evaluation thread was busy, in arrival order. Under <see cref="_schedLock"/>.</summary>
private readonly Queue<EvalRequest> _backlog = new();
private readonly object _schedLock = new();
/// <summary>Evaluation threads committed to taking from <see cref="_queue"/>, minus hand-offs not yet taken. Under <see cref="_schedLock"/>.</summary>
private int _idle;
/// <summary>
/// Loads waiting for a compile thread. Compiles are long, synchronous and CPU-bound, so they run on
/// <see cref="CompileThreads"/> dedicated threads, never on the thread pool: a burst of cold loads (a node start
/// or a deploy with an empty PE cache) used to put one blocking pool item per load in front of the heartbeat
/// timer and the pipe writer, and the host killed the worker for silence (found on windev, lmxopcua#780 §8).
/// </summary>
private readonly BlockingCollection<LoadScripts> _loads = new(new ConcurrentQueue<LoadScripts>());
/// <summary>Default dedicated compile threads: half the processors, at least 1, at most 8.</summary>
internal static int DefaultCompileThreads => Math.Clamp(Environment.ProcessorCount / 2, 1, 8);
/// <summary>
/// Outbound frames (lmxopcua#789): the thread that produces a frame — an evaluation thread with its result, a
/// compile thread with its load result — writes it itself when no write is in progress, instead of handing it to
/// a writer task through a channel (one thread-pool wake-up and spin per result).
/// </summary>
private ScriptWorkerFrameWriter? _writer;
private int _compileThreads = DefaultCompileThreads;
private readonly ForwardingLogSink _logSink;
private readonly ILogger _scriptLogger;
private int _maxFrameBytes = ScriptWorkerFrameCodec.DefaultMaxFrameBytes;
private int _queueCapacity = 4096;
private TimeSpan _hardGrace = TimeSpan.FromSeconds(1);
private TimeSpan _heartbeatInterval = TimeSpan.FromSeconds(1);
/// <summary>
/// lmxopcua#827: this worker runs each evaluation's soft clock from the run's start and reports the crossing
/// (<c>EvalResults.soft_expired_eval_ids</c>); the host asked for it in <c>Hello</c> and we echoed it in
/// <c>Ready</c>. Off (an older host): the host's own clock, started at submit, is the soft deadline.
/// </summary>
private bool _workerSoftClock;
/// <summary>Wakes the watchdog early when a run's soft deadline is sooner than its next planned pass.</summary>
private readonly AutoResetEvent _watchdogWake = new(false);
/// <summary><see cref="Stopwatch.GetTimestamp"/> of the watchdog's next planned pass.</summary>
private long _watchdogNextPass;
private long _seq;
/// <summary>Test seam (<c>Hello.test_stall_reader_on_diag</c>).</summary>
private bool _testStallReaderOnDiag;
public WorkerHost(Stream pipe, string nonce, int parentPid)
{
_pipe = pipe;
_nonce = nonce;
_parentPid = parentPid;
_logSink = new ForwardingLogSink();
_scriptLogger = new LoggerConfiguration().MinimumLevel.Verbose().WriteTo.Sink(_logSink).CreateLogger();
}
public async Task<int> RunAsync()
{
try
{
// Blocking I/O from the first byte (lmxopcua#789): on Unix one async call would turn the socket under the
// pipe non-blocking for good, and every later read would go through the socket engine; on Windows the
// stream waits for its own overlapped I/O, off the completion port.
var hello = ScriptWorkerFrameCodec.Read(_pipe, ScriptWorkerFrameCodec.DefaultMaxFrameBytes);
if (hello is null) return ScriptWorkerEnvironment.ExitPipeClosed;
if (hello.BodyCase != Envelope.BodyOneofCase.Hello)
throw new ScriptWorkerProtocolException($"expected Hello, got {hello.BodyCase}");
Configure(hello.Hello);
// The nonce is echoed, not trusted: the host compares it with the one it put in OUR environment, which
// proves the process on the other end of its pipe is the one it launched.
var ready = Wrap(new Envelope
{
Ready = new Ready
{
Nonce = _nonce,
Pid = Environment.ProcessId,
RuntimeVersion = Environment.Version.ToString(),
WorkerSoftClock = _workerSoftClock,
// lmxopcua#1014: lets the host decide whether its compiled images bind here.
PeImageAbi = ScriptSandbox.ImageAbi,
},
});
ScriptWorkerFrameCodec.Write(_pipe, ready, _maxFrameBytes);
_logSink.Capacity = (int)Math.Max(1, hello.Hello.MaxLogLines == 0 ? 1000 : hello.Hello.MaxLogLines);
_writer = new ScriptWorkerFrameWriter(_pipe, OnWriteFault, _maxFrameBytes, firstSeq: Interlocked.Read(ref _seq),
synchronous: true);
StartBackground(Math.Max(1, (int)hello.Hello.EvalThreads));
var exit = await ReadOnDedicatedThread();
_writer.Complete();
return exit;
}
catch (ScriptWorkerProtocolException ex)
{
await Console.Error.WriteLineAsync($"ScriptWorker: protocol fault: {ex.Message}");
return ScriptWorkerEnvironment.ExitProtocolFault;
}
catch (IOException)
{
return ScriptWorkerEnvironment.ExitPipeClosed;
}
}
private void Configure(Hello hello)
{
if (hello.MaxFrameBytes > 0) _maxFrameBytes = (int)Math.Min(hello.MaxFrameBytes, 64u * 1024 * 1024);
if (hello.QueueCapacity > 0) _queueCapacity = (int)hello.QueueCapacity;
if (hello.HardGraceMs > 0) _hardGrace = TimeSpan.FromMilliseconds(hello.HardGraceMs);
if (hello.HeartbeatIntervalMs > 0) _heartbeatInterval = TimeSpan.FromMilliseconds(hello.HeartbeatIntervalMs);
if (hello.CompileThreads > 0) _compileThreads = (int)Math.Min(hello.CompileThreads, 64);
_workerSoftClock = hello.WorkerSoftClock;
_testStallReaderOnDiag = hello.TestStallReaderOnDiag;
// lmxopcua#1014: no PE-cache key or directory any more — the host verifies, compiles and signs, and sends a
// verified image inside the load (ScriptSource.pe_image). This process runs Designer code; it holds nothing that
// would let that code persist.
}
private void StartBackground(int evalThreads)
{
for (var i = 0; i < evalThreads; i++)
{
new Thread(EvalThreadLoop) { IsBackground = true, Name = $"ScriptWorker.Eval{i}" }.Start();
}
for (var i = 0; i < _compileThreads; i++)
{
new Thread(CompileThreadLoop) { IsBackground = true, Name = $"ScriptWorker.Compile{i}" }.Start();
}
new Thread(WatchdogLoop) { IsBackground = true, Name = "ScriptWorker.Watchdog" }.Start();
_ = Task.Run(HeartbeatLoopAsync);
_ = Task.Run(LogFlushLoopAsync);
if (_parentPid > 0) _ = Task.Run(ParentWatchLoopAsync);
}
/// <summary>The blocking read loop on its own thread (lmxopcua#789); completes with the exit code.</summary>
private Task<int> ReadOnDedicatedThread()
{
var done = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
new Thread(() =>
{
var reader = new ScriptWorkerFrameReader(_pipe, _maxFrameBytes);
while (true)
{
Envelope? frame;
try
{
frame = reader.Read();
}
catch (ScriptWorkerProtocolException ex)
{
Console.Error.WriteLine($"ScriptWorker: protocol fault: {ex.Message}");
done.TrySetResult(ScriptWorkerEnvironment.ExitProtocolFault);
return;
}
catch (Exception ex) when (ex is IOException or ObjectDisposedException or System.Net.Sockets.SocketException)
{
done.TrySetResult(ScriptWorkerEnvironment.ExitPipeClosed);
return;
}
int? exit;
try
{
exit = HandleFrame(frame);
}
catch (Exception ex)
{
// Never an unhandled exception on this thread: the worker ends as a fault the host can attribute.
Console.Error.WriteLine($"ScriptWorker: reader failed: {ex}");
done.TrySetResult(ScriptWorkerEnvironment.ExitProtocolFault);
return;
}
if (exit is { } code)
{
done.TrySetResult(code);
return;
}
}
}) { IsBackground = true, Name = "ScriptWorker.Reader" }.Start();
return done.Task;
}
/// <summary>Acts on one frame from the host.</summary>
/// <param name="frame">The frame; null = end of stream.</param>
/// <returns>The exit code when the worker must end, otherwise null.</returns>
private int? HandleFrame(Envelope? frame)
{
if (frame is null) return ScriptWorkerEnvironment.ExitPipeClosed; // host gone: fatal by design
switch (frame.BodyCase)
{
case Envelope.BodyOneofCase.Load:
// Compile off the reader, so evaluations for already-loaded keys keep flowing during a load, and off
// the thread pool, so the heartbeat and the writer keep flowing during a burst of them.
_loads.Add(frame.Load);
return null;
case Envelope.BodyOneofCase.Unload:
foreach (var key in frame.Unload.Keys)
if (_scripts.TryRemove(key, out var gone)) gone.Dispose();
return null;
case Envelope.BodyOneofCase.Eval:
{
List<ulong>? deferred = null;
foreach (var item in frame.Eval.Items)
if (!Admit(item)) (deferred ??= []).Add(item.EvalId);
// One notice per incoming frame. It can reach the host after the deferred run's own start notice (an
// evaluation thread may pick the run up before this is queued); the host treats the two as unordered.
if (deferred is not null)
{
var notice = new EvalResults();
notice.DeferredEvalIds.AddRange(deferred);
Send(new Envelope { Results = notice });
}
return null;
}
case Envelope.BodyOneofCase.Cancel:
if (_running.TryGetValue((long)frame.Cancel.EvalId, out var toCancel))
{
// Off the reader (lmxopcua#789): Cancel() runs the script's own ctx.CancellationToken callbacks, and a
// callback that blocks would stop this worker reading its pipe — the host's writes would then block.
ThreadPool.UnsafeQueueUserWorkItem(static cts =>
{
try { cts.Cancel(); }
catch (ObjectDisposedException) { /* just finished */ }
catch (Exception ex) { Console.Error.WriteLine($"ScriptWorker: a cancellation callback threw: {ex.Message}"); }
}, toCancel.Cancellation, preferLocal: false);
}
return null;
case Envelope.BodyOneofCase.DiagRequest:
if (_testStallReaderOnDiag) Thread.Sleep(Timeout.Infinite); // test seam: talk but never listen again
Send(new Envelope { DiagReply = Diagnostics() });
return null;
case Envelope.BodyOneofCase.Shutdown:
return 0;
case Envelope.BodyOneofCase.Fault:
Console.Error.WriteLine($"ScriptWorker: host fault: {frame.Fault.Message}");
return ScriptWorkerEnvironment.ExitProtocolFault;
default:
Console.Error.WriteLine($"ScriptWorker: unexpected frame {frame.BodyCase}");
return ScriptWorkerEnvironment.ExitProtocolFault;
}
}
private void CompileThreadLoop()
{
foreach (var load in _loads.GetConsumingEnumerable()) Load(load);
}
private void Load(LoadScripts load)
{
// The host's compile timeout runs from here, not from when it sent the load (lmxopcua#790).
Send(new Envelope { LoadStarted = new LoadStarted { LoadId = load.LoadId } });
var result = new LoadResult { LoadId = load.LoadId };
foreach (var script in load.Scripts)
{
var outcome = new LoadOutcome { Key = script.Key, Ok = true };
try
{
var loaded = LoadedScript.Load(script, out var cache);
outcome.Cache = cache;
if (_scripts.TryRemove(script.Key, out var previous)) previous.Dispose();
_scripts[script.Key] = loaded;
}
catch (CompilationErrorException ex)
{
outcome.Ok = false;
outcome.Error = new ScriptError { Kind = ScriptError.Types.Kind.Compile, Message = ex.Message };
}
catch (ScriptSandboxViolationException ex)
{
outcome.Ok = false;
outcome.Error = new ScriptError { Kind = ScriptError.Types.Kind.Sandbox, Message = ex.Message };
}
catch (Exception ex)
{
outcome.Ok = false;
outcome.Error = new ScriptError { Kind = ScriptError.Types.Kind.Threw, Message = ex.Message };
}
result.Outcomes.Add(outcome);
}
if (ForbiddenAssemblyLoaded() is { } forbidden) DieForbidden(forbidden);
Send(new Envelope { LoadResult = result });
}
/// <summary>
/// Schedules one evaluation: straight to an idle evaluation thread when there is one (it starts now, so the
/// host's clock, started at submit, is right), otherwise into the backlog.
/// </summary>
/// <param name="request">The evaluation.</param>
/// <returns>False when it was deferred to the backlog (the host must stop its clock until it starts).</returns>
private bool Admit(EvalRequest request)
{
lock (_schedLock)
{
if (_backlog.Count + _queue.Count < _queueCapacity)
{
if (_idle > 0 && _backlog.Count == 0)
{
_idle--;
_queue.Add(request);
return true;
}
_backlog.Enqueue(request);
return false;
}
}
// Full: answered at once, outside the lock (a send may write to the pipe on this thread).
SendResult(new EvalResult
{
EvalId = request.EvalId,
Error = new ScriptError { Kind = ScriptError.Types.Kind.Busy, Message = "script worker busy" },
});
return true;
}
private void EvalThreadLoop()
{
EvalResult? finished = null;
while (true)
{
// A thread that just finished a run takes the oldest deferred evaluation, and its start notice rides on
// the finished run's result frame. With nothing deferred it goes idle and waits for a hand-off.
EvalRequest? request = null;
lock (_schedLock)
{
if (finished is not null && _backlog.TryDequeue(out var next)) request = next;
else _idle++;
}
if (finished is not null)
{
var frame = new EvalResults();
frame.Items.Add(finished);
if (request is not null) frame.StartedEvalIds.Add(request.EvalId);
Send(new Envelope { Results = frame });
finished = null;
}
request ??= _queue.Take();
try
{
finished = Evaluate(request);
}
catch (Exception ex)
{
finished = new EvalResult
{
EvalId = request.EvalId,
Error = new ScriptError { Kind = ScriptError.Types.Kind.Threw, Message = ex.Message },
};
}
}
}
private EvalResult Evaluate(EvalRequest request)
{
var result = new EvalResult { EvalId = request.EvalId };
if (!_scripts.TryGetValue(request.Key, out var script))
{
result.Error = new ScriptError { Kind = ScriptError.Types.Kind.NotLoaded, Message = $"script '{request.Key}' is not loaded" };
return result;
}
var inputs = new Dictionary<string, DataValueSnapshot>(request.Inputs.Count, StringComparer.Ordinal);
foreach (var input in request.Inputs)
{
string path;
if (!string.IsNullOrEmpty(input.Path)) path = input.Path;
else if (input.Slot < script.InputPaths.Length) path = script.InputPaths[input.Slot];
else throw new ScriptWorkerProtocolException($"input slot {input.Slot} is not registered for '{request.Key}'");
if (input.Unsupported)
{
result.Error = new ScriptError
{
Kind = ScriptError.Types.Kind.UnsupportedType,
Message = $"input '{path}' has a value of unsupported type {input.UnsupportedType}",
};
return result;
}
inputs[path] = new DataValueSnapshot(
VariantCodec.Decode(input.Value),
input.StatusCode,
input.SourceTsTicks == 0 ? null : new DateTime(input.SourceTsTicks, DateTimeKind.Utc),
input.ServerTsTicks == 0 ? null : new DateTime(input.ServerTsTicks, DateTimeKind.Utc));
}
// ctx.Now follows the HOST clock (design §4.3) but keeps ticking: a fixed instant would never let a script
// that waits on ctx.Now finish.
var offset = request.NowUtcTicks == 0
? TimeSpan.Zero
: new DateTime(request.NowUtcTicks, DateTimeKind.Utc) - DateTime.UtcNow;
Func<DateTime> clock = () => DateTime.UtcNow + offset;
var logger = _scriptLogger.ForContext(ForwardingLogSink.KeyProperty, request.Key);
var soft = TimeSpan.FromMilliseconds(Math.Max(1, request.SoftTimeoutMs));
// Cancelled by the host's Cancel frame at the soft deadline, never by our own clock (see the proto): with the
// worker soft clock (lmxopcua#827) the watchdog only REPORTS the crossing; the host answers its caller, then
// cancels.
using var cts = new CancellationTokenSource();
var grace = request.HardGraceMs > 0 ? TimeSpan.FromMilliseconds(request.HardGraceMs) : _hardGrace;
var started = Stopwatch.GetTimestamp();
var running = new RunningEval(request.EvalId, request.Key, started, soft, grace, cts);
_running[(long)request.EvalId] = running;
// The watchdog plans its next pass at most WatchdogPoll ahead; a budget shorter than that wakes it now, so the
// soft notice is not late by up to a poll interval.
if (_workerSoftClock && running.SoftDue < Interlocked.Read(ref _watchdogNextPass)) _watchdogWake.Set();
var before = GC.GetAllocatedBytesForCurrentThread();
var sw = Stopwatch.StartNew();
try
{
object? value = script.Run(inputs, logger, clock, cts.Token, out var isPredicate);
if (isPredicate)
{
result.Predicate = (bool)value!;
}
else if (VariantCodec.TryEncode(value, out var variant, out var unsupported))
{
result.Value = variant;
}
else
{
result.Error = new ScriptError
{
Kind = ScriptError.Types.Kind.UnsupportedType,
Message = $"script returned a value of unsupported type {unsupported}",
};
}
}
catch (Exception ex)
{
result.Error = new ScriptError { Kind = ScriptError.Types.Kind.Threw, Message = ex.Message };
}
finally
{
_running.TryRemove((long)request.EvalId, out _);
}
result.AllocatedBytes = (ulong)Math.Max(0, GC.GetAllocatedBytesForCurrentThread() - before);
result.RunMicros = (uint)Math.Min(uint.MaxValue, sw.Elapsed.TotalMicroseconds);
return result;
}
/// <summary>
/// The watchdog: reports soft-deadline crossings (worker soft clock, lmxopcua#827) and fails the process fast for
/// a run past its hard deadline that the host has not killed.
/// </summary>
/// <remarks>
/// The hard deadline it enforces is the host's plus <see cref="WatchdogMargin"/>, from the same anchor the host
/// uses: the run's start (T + G) on the host clock, or — with the worker soft clock — the soft notice it sent
/// (G), which is where the host arms its kill. So the host normally wins and the exit names the culprit.
/// </remarks>
private void WatchdogLoop()
{
while (true)
{
var now = Stopwatch.GetTimestamp();
var nextPass = now + Ticks(WatchdogPoll);
List<ulong>? expired = null;
foreach (var (_, run) in _running)
{
if (_workerSoftClock)
{
if (run.SoftReportedAt == 0)
{
if (now >= run.SoftDue)
{
run.SoftReportedAt = now;
(expired ??= []).Add(run.EvalId);
}
else if (run.SoftDue < nextPass)
{
nextPass = run.SoftDue;
}
}
else if (now - run.SoftReportedAt > Ticks(run.Grace + WatchdogMargin))
{
FailFast(run, run.Grace + WatchdogMargin, "its soft deadline");
}
}
else if (now - run.StartedTimestamp > Ticks(run.Soft + run.Grace + WatchdogMargin))
{
FailFast(run, run.Soft + run.Grace + WatchdogMargin, "its start");
}
}
if (expired is not null)
{
var notice = new EvalResults();
notice.SoftExpiredEvalIds.AddRange(expired);
Send(new Envelope { Results = notice });
}
Interlocked.Exchange(ref _watchdogNextPass, nextPass);
var wait = Stopwatch.GetElapsedTime(Stopwatch.GetTimestamp(), nextPass);
if (wait > TimeSpan.Zero) _watchdogWake.WaitOne(wait);
}
static void FailFast(RunningEval run, TimeSpan after, string anchor)
{
// The host should have killed us already; this names the culprit in the exit/dump.
Environment.FailFast($"ScriptWorker: script '{run.Key}' exceeded its hard deadline ({after.TotalMilliseconds:F0} ms after {anchor})");
}
}
private static long Ticks(TimeSpan span) => (long)(span.TotalSeconds * Stopwatch.Frequency);
private async Task HeartbeatLoopAsync()
{
using var timer = new PeriodicTimer(_heartbeatInterval);
while (await timer.WaitForNextTickAsync())
{
Send(new Envelope
{
Heartbeat = new Heartbeat
{
Inflight = (uint)_running.Count,
Queued = (uint)QueuedCount(),
HeapBytes = GC.GetTotalMemory(false),
Gen2Count = (uint)GC.CollectionCount(2),
},
});
}
}
private async Task LogFlushLoopAsync()
{
using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(100));
while (await timer.WaitForNextTickAsync())
{
// #999 / review K-5: cut by BYTES as well as lines — one batch of every buffered line (≤ 1,000 × ~24 KB)
// used to exceed the frame cap, fault the writer and exit the worker.
foreach (var batch in _logSink.Drain(Math.Max(1, _maxFrameBytes - 1024))) Send(new Envelope { Logs = batch });
}
}
private async Task ParentWatchLoopAsync()
{
using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(500));
while (await timer.WaitForNextTickAsync())
{
if (!ParentAlive())
{
await Console.Error.WriteLineAsync("ScriptWorker: parent process is gone; exiting.");
Environment.Exit(ScriptWorkerEnvironment.ExitParentGone);
}
}
}
private bool ParentAlive()
{
try
{
using var parent = Process.GetProcessById(_parentPid);
return !parent.HasExited;
}
catch (ArgumentException)
{
return false;
}
catch (InvalidOperationException)
{
return false;
}
catch (System.ComponentModel.Win32Exception)
{
// Access denied: a worker under Scripting:Worker:Identity runs with a restricted token that may not open the
// host's process. It exists (GetProcessById found it), so it is alive; on Windows the Job Object's
// kill-on-close is what ends the worker with its host, and pipe end-of-stream backs it up.
return true;
}
}
private static void OnWriteFault(Exception ex)
{
// The host is gone (or a frame broke the protocol): fatal by design.
if (ex is ScriptWorkerProtocolException)
{
Console.Error.WriteLine($"ScriptWorker: protocol fault writing a frame: {ex.Message}");
Environment.Exit(ScriptWorkerEnvironment.ExitProtocolFault);
}
Environment.Exit(ScriptWorkerEnvironment.ExitPipeClosed);
}
private int QueuedCount()
{
lock (_schedLock) return _backlog.Count + _queue.Count;
}
private void SendResult(EvalResult result)
{
var results = new EvalResults();
results.Items.Add(result);
Send(new Envelope { Results = results });
}
private void Send(Envelope envelope) => _writer?.TryWrite(envelope);
private Envelope Wrap(Envelope envelope)
{
envelope.ProtocolVersion = ScriptWorkerFrameCodec.ProtocolVersion;
envelope.Seq = (ulong)Interlocked.Increment(ref _seq);
return envelope;
}
private static DiagnosticsReply Diagnostics()
{
var reply = new DiagnosticsReply
{
Pid = Environment.ProcessId,
WorkingDirectory = Environment.CurrentDirectory,
};
reply.LoadedAssemblies.AddRange(AppDomain.CurrentDomain.GetAssemblies()
.Select(a => a.GetName().Name ?? string.Empty)
.Where(n => n.Length > 0));
foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables())
reply.EnvironmentNames.Add((string)entry.Key);
return reply;
}
private static string? ForbiddenAssemblyLoaded()
{
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
var name = assembly.GetName().Name ?? string.Empty;
foreach (var prefix in ScriptWorkerEnvironment.ForbiddenAssemblyPrefixes)
if (name.StartsWith(prefix, StringComparison.Ordinal)) return name;
}
return null;
}
private static void DieForbidden(string assembly)
{
Console.Error.WriteLine($"ScriptWorker: forbidden assembly '{assembly}' is loaded; exiting.");
Environment.Exit(ScriptWorkerEnvironment.ExitForbiddenAssembly);
}
/// <summary>One evaluation on an evaluation thread, as the watchdog sees it.</summary>
private sealed class RunningEval(ulong evalId, string key, long startedTimestamp, TimeSpan soft, TimeSpan grace,
CancellationTokenSource cancellation)
{
public ulong EvalId { get; } = evalId;
public string Key { get; } = key;
/// <summary><see cref="Stopwatch.GetTimestamp"/> when the evaluation thread started the run.</summary>
public long StartedTimestamp { get; } = startedTimestamp;
/// <summary>T.</summary>
public TimeSpan Soft { get; } = soft;
/// <summary>The run's start + T.</summary>
public long SoftDue { get; } = startedTimestamp + Ticks(soft);
public TimeSpan Grace { get; } = grace;
public CancellationTokenSource Cancellation { get; } = cancellation;
/// <summary>When the watchdog reported the soft crossing to the host; 0 = not yet. Watchdog thread only.</summary>
public long SoftReportedAt { get; set; }
}
/// <summary>One loaded script: its compiled evaluator and its input slot order.</summary>
private sealed class LoadedScript : IDisposable
{
private readonly ScriptEvaluator<VirtualTagContext, object?>? _value;
private readonly ScriptEvaluator<AlarmPredicateContext, bool>? _predicate;
private LoadedScript(string[] inputPaths, ScriptEvaluator<VirtualTagContext, object?>? value,
ScriptEvaluator<AlarmPredicateContext, bool>? predicate)
{
InputPaths = inputPaths;
_value = value;
_predicate = predicate;
}
public string[] InputPaths { get; }
/// <summary>
/// Loads a script: from the image the host sent with it when there is one (Roslyn is not entered), otherwise by
/// compiling the source. The image comes from the host's PE cache (lmxopcua#1014): the host verified it under a
/// key this process never holds and emitted it with its own compile pipeline, analyzer included, so it is
/// loaded as the host's own compile would be. One that does not load is reported (<see cref="PeCache.Rejected"/>)
/// and the source compiled; the host evicts the entry.
/// </summary>
public static LoadedScript Load(ScriptSource source, out PeCache how) => source.Kind switch
{
ContextKind.VirtualTag or ContextKind.Calculation => new LoadedScript(
[.. source.InputPaths], Load<VirtualTagContext, object?>(source, out how), null),
ContextKind.AlarmPredicate => new LoadedScript(
[.. source.InputPaths], null, Load<AlarmPredicateContext, bool>(source, out how)),
_ => throw new ScriptWorkerProtocolException($"unknown script kind {source.Kind}"),
};
private static ScriptEvaluator<TContext, TResult> Load<TContext, TResult>(ScriptSource source, out PeCache how)
where TContext : ScriptContext
{
if (!source.PeImage.IsEmpty)
{
try
{
var evaluator = ScriptEvaluator<TContext, TResult>.FromImage(source.PeImage.ToByteArray());
how = PeCache.Hit;
return evaluator;
}
catch (Exception ex) when (ex is BadImageFormatException or InvalidOperationException or TypeLoadException
or MissingMethodException or FileLoadException or FileNotFoundException
or InvalidCastException or ArgumentException)
{
// Verified by the host but unloadable here: a runtime difference the image ABI did not capture.
how = PeCache.Rejected;
return ScriptEvaluator<TContext, TResult>.Compile(source.Source);
}
}
how = PeCache.None;
return ScriptEvaluator<TContext, TResult>.Compile(source.Source);
}
public object? Run(IReadOnlyDictionary<string, DataValueSnapshot> inputs, ILogger logger, Func<DateTime> clock,
CancellationToken ct, out bool isPredicate)
{
if (_predicate is not null)
{
isPredicate = true;
return _predicate.RunAsync(new AlarmPredicateContext(inputs, logger, clock), ct).GetAwaiter().GetResult();
}
isPredicate = false;
// Single-tag mode, as in the host: a cross-tag write is dropped.
return _value!.RunAsync(new VirtualTagContext(inputs, static (_, _) => { }, logger, clock), ct)
.GetAwaiter().GetResult();
}
public void Dispose()
{
_value?.Dispose();
_predicate?.Dispose();
}
}
/// <summary>Buffers <c>ctx.Logger</c> events for the host, bounded, counting what it had to drop.</summary>
private sealed class ForwardingLogSink : ILogEventSink
{
public const string KeyProperty = "ScriptWorkerKey";
private readonly ConcurrentQueue<LogLine> _lines = new();
private int _count;
private int _dropped;
public int Capacity { get; set; } = 1000;
public void Emit(LogEvent logEvent)
{
if (Interlocked.Increment(ref _count) > Capacity)
{
Interlocked.Decrement(ref _count);
Interlocked.Increment(ref _dropped);
return;
}
var key = logEvent.Properties.TryGetValue(KeyProperty, out var k) && k is ScalarValue { Value: string s } ? s : string.Empty;
_lines.Enqueue(new LogLine
{
Key = key,
Level = (uint)logEvent.Level,
Rendered = Truncate(logEvent.RenderMessage(), 8 * 1024),
Exception = Truncate(logEvent.Exception?.ToString() ?? string.Empty, 16 * 1024),
TsTicks = logEvent.Timestamp.UtcTicks,
});
}
/// <summary>
/// Drains every buffered line into batches of at most <paramref name="maxBatchBytes"/> encoded bytes each
/// (#999 / review K-5). A line too large for any batch on its own is counted as dropped.
/// </summary>
public List<LogBatch> Drain(int maxBatchBytes)
{
var batches = new List<LogBatch>();
var dropped = Interlocked.Exchange(ref _dropped, 0);
if (_lines.IsEmpty && dropped == 0) return batches;
var batch = new LogBatch();
var bytes = 0;
while (_lines.TryDequeue(out var line))
{
Interlocked.Decrement(ref _count);
var size = line.CalculateSize();
var lineBytes = 1 + Google.Protobuf.CodedOutputStream.ComputeLengthSize(size) + size;
if (lineBytes > maxBatchBytes - 16)
{
dropped++;
continue;
}
if (bytes + lineBytes > maxBatchBytes - 16)
{
batches.Add(batch);
batch = new LogBatch();
bytes = 0;
}
batch.Lines.Add(line);
bytes += lineBytes;
}
batch.Dropped = (uint)dropped;
batches.Add(batch);
return batches;
}
private static string Truncate(string value, int max) => value.Length <= max ? value : value[..max];
}
}