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;
///
/// 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.
///
///
/// 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).
///
internal sealed class WorkerHost
{
/// The watchdog fails fast this long after the host's own hard deadline, so the host normally wins.
private static readonly TimeSpan WatchdogMargin = TimeSpan.FromMilliseconds(500);
/// The watchdog's longest sleep between passes.
private static readonly TimeSpan WatchdogPoll = TimeSpan.FromMilliseconds(50);
/// The host pipe, driven blocking ().
private readonly Stream _pipe;
private readonly string _nonce;
private readonly int _parentPid;
private readonly ConcurrentDictionary _scripts = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary _running = new();
///
/// Hand-off to an IDLE evaluation thread: an evaluation is put here only when a thread is known to be waiting
/// for it (), so whatever is put here starts at once. Everything else waits in
/// and is reported to the host as deferred (lmxopcua#780 batch submit: per-item deadlines
/// stay exact, see the proto's EvalResults).
///
private readonly BlockingCollection _queue = new(new ConcurrentQueue());
/// Evaluations that arrived while every evaluation thread was busy, in arrival order. Under .
private readonly Queue _backlog = new();
private readonly object _schedLock = new();
/// Evaluation threads committed to taking from , minus hand-offs not yet taken. Under .
private int _idle;
///
/// Loads waiting for a compile thread. Compiles are long, synchronous and CPU-bound, so they run on
/// 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).
///
private readonly BlockingCollection _loads = new(new ConcurrentQueue());
/// Default dedicated compile threads: half the processors, at least 1, at most 8.
internal static int DefaultCompileThreads => Math.Clamp(Environment.ProcessorCount / 2, 1, 8);
///
/// 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).
///
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);
private ScriptPeCacheStore? _peCache;
///
/// lmxopcua#827: this worker runs each evaluation's soft clock from the run's start and reports the crossing
/// (EvalResults.soft_expired_eval_ids); the host asked for it in Hello and we echoed it in
/// Ready. Off (an older host): the host's own clock, started at submit, is the soft deadline.
///
private bool _workerSoftClock;
/// Wakes the watchdog early when a run's soft deadline is sooner than its next planned pass.
private readonly AutoResetEvent _watchdogWake = new(false);
/// of the watchdog's next planned pass.
private long _watchdogNextPass;
private long _seq;
/// Test seam (Hello.test_stall_reader_on_diag).
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 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,
},
});
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;
if (!string.IsNullOrEmpty(hello.PeCacheDir) && hello.PeCacheKey.Length == ScriptPeCacheStore.KeyLength)
{
// Design §7: the host owns the key; it reaches us only here, never through the environment or a file.
_peCache = new ScriptPeCacheStore(hello.PeCacheDir, hello.PeCacheKey.ToByteArray());
}
}
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);
}
/// The blocking read loop on its own thread (lmxopcua#789); completes with the exit code.
private Task ReadOnDedicatedThread()
{
var done = new TaskCompletionSource(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;
}
/// Acts on one frame from the host.
/// The frame; null = end of stream.
/// The exit code when the worker must end, otherwise null.
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? 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, _peCache, 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 });
}
///
/// 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.
///
/// The evaluation.
/// False when it was deferred to the backlog (the host must stop its clock until it starts).
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(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 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;
}
///
/// 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.
///
///
/// The hard deadline it enforces is the host's plus , 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.
///
private void WatchdogLoop()
{
while (true)
{
var now = Stopwatch.GetTimestamp();
var nextPass = now + Ticks(WatchdogPoll);
List? 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);
}
/// One evaluation on an evaluation thread, as the watchdog sees it.
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;
/// when the evaluation thread started the run.
public long StartedTimestamp { get; } = startedTimestamp;
/// T.
public TimeSpan Soft { get; } = soft;
/// The run's start + T.
public long SoftDue { get; } = startedTimestamp + Ticks(soft);
public TimeSpan Grace { get; } = grace;
public CancellationTokenSource Cancellation { get; } = cancellation;
/// When the watchdog reported the soft crossing to the host; 0 = not yet. Watchdog thread only.
public long SoftReportedAt { get; set; }
}
/// One loaded script: its compiled evaluator and its input slot order.
private sealed class LoadedScript : IDisposable
{
private readonly ScriptEvaluator? _value;
private readonly ScriptEvaluator? _predicate;
private LoadedScript(string[] inputPaths, ScriptEvaluator? value,
ScriptEvaluator? predicate)
{
InputPaths = inputPaths;
_value = value;
_predicate = predicate;
}
public string[] InputPaths { get; }
///
/// Loads a script: from a verified PE cache entry when there is one (Roslyn is not entered), otherwise by
/// compiling it and writing the entry (design §7). A compile error is never cached — the host's negative
/// cache covers that — and an entry that fails verification is deleted by the store and recompiled.
///
public static LoadedScript Load(ScriptSource source, ScriptPeCacheStore? cache, out PeCache how) => source.Kind switch
{
ContextKind.VirtualTag or ContextKind.Calculation => new LoadedScript(
[.. source.InputPaths], Load(source, cache, out how), null),
ContextKind.AlarmPredicate => new LoadedScript(
[.. source.InputPaths], null, Load(source, cache, out how)),
_ => throw new ScriptWorkerProtocolException($"unknown script kind {source.Kind}"),
};
private static ScriptEvaluator Load(ScriptSource source, ScriptPeCacheStore? cache,
out PeCache how) where TContext : ScriptContext
{
if (cache is null)
{
how = PeCache.None;
return ScriptEvaluator.Compile(source.Source);
}
var id = ScriptPeCacheStore.EntryId(ScriptEvaluator.CacheFingerprint, (int)source.Kind, source.Source);
var lookup = cache.TryRead(id, out var image);
if (lookup == PeCacheLookup.Hit)
{
try
{
how = PeCache.Hit;
return ScriptEvaluator.FromImage(image!);
}
catch (Exception ex) when (ex is BadImageFormatException or InvalidOperationException or TypeLoadException or MissingMethodException)
{
// Authenticated but unloadable: only possible across a runtime change the fingerprint missed.
try { File.Delete(cache.EntryPath(id)); } catch (IOException) { }
lookup = PeCacheLookup.Rejected;
}
}
var compiled = ScriptEvaluator.CompileToImage(source.Source);
cache.TryWrite(id, compiled);
how = lookup == PeCacheLookup.Rejected ? PeCache.Rejected : PeCache.Miss;
return ScriptEvaluator.FromImage(compiled);
}
public object? Run(IReadOnlyDictionary inputs, ILogger logger, Func 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();
}
}
/// Buffers ctx.Logger events for the host, bounded, counting what it had to drop.
private sealed class ForwardingLogSink : ILogEventSink
{
public const string KeyProperty = "ScriptWorkerKey";
private readonly ConcurrentQueue _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,
});
}
///
/// Drains every buffered line into batches of at most encoded bytes each
/// (#999 / review K-5). A line too large for any batch on its own is counted as dropped.
///
public List Drain(int maxBatchBytes)
{
var batches = new List();
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];
}
}