diff --git a/docs/requirements/Component-InboundAPI.md b/docs/requirements/Component-InboundAPI.md index 5585bd03..a8f76882 100644 --- a/docs/requirements/Component-InboundAPI.md +++ b/docs/requirements/Component-InboundAPI.md @@ -69,7 +69,7 @@ Each API method definition includes: - **Return Value Definition**: Structure of the response, with: - Field names and (extended-system) data types. Supports returning **lists of objects** and arbitrarily nested structures. - **Implementation Script**: C# script that executes when the method is called. Stored **inline** in the method definition. Follows standard C# authoring patterns but has no template inheritance — it is a standalone script tied to this method. -- **Timeout**: Configurable per method. Defines the maximum time the method is allowed to execute (including any routed calls to sites) before returning a timeout error to the caller. +- **Timeout**: Configurable per method. Defines the maximum time the method is allowed to execute (including any routed calls to sites) before returning a timeout error to the caller. The script is started on the thread pool (not inline on the request thread), so the timeout also bounds the synchronous prefix of the script — CPU work or a blocking call before its first `await` — and a script that overruns is abandoned and counted exactly like one that blocks later (review INB-1). - **TraceAllCalls** (Flow Debugger, 2026-09-05): when set, every call to this method runs its routed site scripts with the trace flag on, so their `ScriptRun` / `AttributeWrite` / `AttributeWait` audit rows (`AuditChannel.ScriptTrace`) are recorded for Replay. Default off — adds 7–10 audit rows per call (3 of them trace-only; a cached DB write and a notification account for the upper end), so it is meant for low-volume integration methods. Set from the method form's *Trace all calls* checkbox or `api-method create|update --trace-all-calls`. > **Authoring note — idempotent methods for at-least-once callers**: some external callers retry diff --git a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/InboundScriptExecutor.cs b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/InboundScriptExecutor.cs index 17a2e45a..80c26de8 100644 --- a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/InboundScriptExecutor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/InboundScriptExecutor.cs @@ -625,7 +625,15 @@ public class InboundScriptExecutor _scriptHandlers[method.Name] = cached; // last-write-wins; concurrent first-callers race benignly } - handlerTask = cached.Handler(context); + // Start the handler OFF the request thread (INB-1). Script.RunAsync runs the script + // synchronously up to its first incomplete await, so invoking the handler inline would + // hold the request thread with no deadline for any script that does CPU work or a + // blocking call before its first await (TimeoutSeconds and client disconnect both + // ignored, no TIMEOUT, abandoned-execution count stuck at 0). Running it on the pool + // lets WaitAsync bound the WHOLE run; a non-cooperative script is then abandoned and + // counted exactly like one that blocks after an await. + var handler = cached.Handler; + handlerTask = Task.Run(() => handler(context), cts.Token); var result = await handlerTask.WaitAsync(cts.Token); var resultJson = result != null diff --git a/tests/ZB.MOM.WW.ScadaBridge.InboundAPI.Tests/InboundScriptExecutorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.InboundAPI.Tests/InboundScriptExecutorTests.cs index 0d8a701c..27d22c0f 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.InboundAPI.Tests/InboundScriptExecutorTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.InboundAPI.Tests/InboundScriptExecutorTests.cs @@ -1106,6 +1106,40 @@ public class InboundScriptExecutorTests Assert.Equal(0, _executor.AbandonedExecutionCount); // ...and DECREMENTED } + /// + /// INB-1: a script that blocks BEFORE its first await (CPU loop, .Result on a helper) used to + /// run inline on the request thread, so the method timeout could not fire until it returned. The + /// request must come back with TIMEOUT at the deadline and the orphan must be counted. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task ScriptBlockingBeforeFirstAwait_StillTimesOutAtTheDeadline() + { + var release = new ManualResetEventSlim(); + _executor.RegisterHandler("spin", _ => + { + release.Wait(TimeSpan.FromSeconds(30)); // synchronous block: no await has happened yet + return Task.FromResult(1); + }); + var method = new ApiMethod("spin", "unused") { Id = 10, TimeoutSeconds = 1 }; + + var started = System.Diagnostics.Stopwatch.StartNew(); + var execution = _executor.ExecuteAsync( + method, new Dictionary(), _route, TimeSpan.FromMilliseconds(200)); + var finished = await Task.WhenAny(execution, Task.Delay(TimeSpan.FromSeconds(10))); + + Assert.Same(execution, finished); // pre-fix: the call itself never returned until released + var result = await execution; + Assert.False(result.Success); + Assert.Equal("TIMEOUT", result.ErrorCode); + Assert.True(started.Elapsed < TimeSpan.FromSeconds(5), $"took {started.Elapsed}"); + Assert.Equal(1, _executor.AbandonedExecutionCount); + + release.Set(); // the orphan finishes; its continuation cleans up + await Task.Delay(300); + Assert.Equal(0, _executor.AbandonedExecutionCount); + } + // --- Flow Debugger step logs (design 2026-09-09 D4/D5/D7): the Log global --- /// Verifies that a traced run emits one ScriptLog row on the trace sink.