feat(siteruntime): thread ParentExecutionId into the routed script's ScriptRuntimeContext

This commit is contained in:
Joseph Doherty
2026-05-21 17:35:49 -04:00
parent dc2c73b07d
commit 6af2607a50
8 changed files with 288 additions and 25 deletions

View File

@@ -3,6 +3,7 @@ using Akka.TestKit.Xunit2;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using ScadaLink.Commons.Messages.Deployment;
using ScadaLink.Commons.Messages.InboundApi;
using ScadaLink.Commons.Messages.Lifecycle;
using ScadaLink.Commons.Types.Enums;
using ScadaLink.Commons.Types.Flattening;
@@ -68,6 +69,28 @@ public class DeploymentManagerActorTests : TestKit, IDisposable
return JsonSerializer.Serialize(config);
}
/// <summary>
/// Builds a config carrying a single callable (no-trigger) script that
/// returns a constant — enough for an inbound <see cref="RouteToCallRequest"/>
/// to be routed end-to-end through the Instance/Script/ScriptExecution actors.
/// </summary>
private static string MakeConfigWithScriptJson(string instanceName, string scriptName)
{
var config = new FlattenedConfiguration
{
InstanceUniqueName = instanceName,
Attributes =
[
new ResolvedAttribute { CanonicalName = "TestAttr", Value = "42", DataType = "Int32" }
],
Scripts =
[
new ResolvedScript { CanonicalName = scriptName, Code = "return 7;" }
]
};
return JsonSerializer.Serialize(config);
}
[Fact]
public async Task DeploymentManager_CreatesInstanceActors_FromStoredConfigs()
{
@@ -240,4 +263,57 @@ public class DeploymentManagerActorTests : TestKit, IDisposable
var response = ExpectMsg<DeploymentStatusResponse>(TimeSpan.FromSeconds(5));
Assert.Equal(DeploymentStatus.Success, response.Status);
}
// ── Audit Log #23 (ParentExecutionId, Task 4): inbound-API routing ──
[Fact]
public async Task RouteInboundApiCall_WithParentExecutionId_RoutesToScriptSuccessfully()
{
// A RouteToCallRequest carrying a ParentExecutionId (the inbound
// request's ExecutionId) must be mapped to a ScriptCallRequest and
// routed end-to-end through the Instance/Script/ScriptExecution actors.
// The additive ParentExecutionId field must not break that routing.
var actor = CreateDeploymentManager();
await Task.Delay(500); // empty startup
actor.Tell(new DeployInstanceCommand(
"dep-route", "RoutedPump", "sha256:route",
MakeConfigWithScriptJson("RoutedPump", "DoWork"), "admin", DateTimeOffset.UtcNow));
ExpectMsg<DeploymentStatusResponse>(TimeSpan.FromSeconds(5));
await Task.Delay(1000); // let the InstanceActor + ScriptActor spin up
var parentExecutionId = Guid.NewGuid();
actor.Tell(new RouteToCallRequest(
"route-corr-1", "RoutedPump", "DoWork",
Parameters: null, DateTimeOffset.UtcNow, ParentExecutionId: parentExecutionId));
var response = ExpectMsg<RouteToCallResponse>(TimeSpan.FromSeconds(10));
Assert.Equal("route-corr-1", response.CorrelationId);
Assert.True(response.Success, $"Routed call failed: {response.ErrorMessage}");
Assert.Equal(7, Convert.ToInt32(response.ReturnValue));
}
[Fact]
public async Task RouteInboundApiCall_WithoutParentExecutionId_StillRoutes()
{
// A routed call with no ParentExecutionId (e.g. the Central UI sandbox)
// is the additive-default path — it must route exactly as before.
var actor = CreateDeploymentManager();
await Task.Delay(500);
actor.Tell(new DeployInstanceCommand(
"dep-route2", "RoutedPump2", "sha256:route2",
MakeConfigWithScriptJson("RoutedPump2", "DoWork"), "admin", DateTimeOffset.UtcNow));
ExpectMsg<DeploymentStatusResponse>(TimeSpan.FromSeconds(5));
await Task.Delay(1000);
// No ParentExecutionId argument — exercises the additive `= null` default.
actor.Tell(new RouteToCallRequest(
"route-corr-2", "RoutedPump2", "DoWork",
Parameters: null, DateTimeOffset.UtcNow));
var response = ExpectMsg<RouteToCallResponse>(TimeSpan.FromSeconds(10));
Assert.Equal("route-corr-2", response.CorrelationId);
Assert.True(response.Success, $"Routed call failed: {response.ErrorMessage}");
}
}

View File

@@ -62,7 +62,8 @@ public class ExecutionCorrelationContextTests
IExternalSystemClient? externalSystemClient,
IDatabaseGateway? databaseGateway,
IAuditWriter? auditWriter,
Guid? executionId = null)
Guid? executionId = null,
Guid? parentExecutionId = null)
{
var compilationService = new ScriptCompilationService(
NullLogger<ScriptCompilationService>.Instance);
@@ -87,7 +88,24 @@ public class ExecutionCorrelationContextTests
auditWriter: auditWriter,
operationTrackingStore: null,
cachedForwarder: null,
executionId: executionId);
executionId: executionId,
parentExecutionId: parentExecutionId);
}
/// <summary>
/// Reads a private <see cref="Guid"/>/<see cref="Nullable{Guid}"/> field off a
/// <see cref="ScriptRuntimeContext"/>. The ParentExecutionId plumbing (Audit
/// Log #23, Task 4) only stores the value on the context — no emitter stamps
/// it onto an audit row yet (that is Task 5) — so the field is inspected
/// directly rather than through an emitted row.
/// </summary>
private static object? ReadPrivateField(ScriptRuntimeContext context, string fieldName)
{
var field = typeof(ScriptRuntimeContext).GetField(
fieldName,
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
Assert.NotNull(field);
return field!.GetValue(context);
}
/// <summary>
@@ -183,4 +201,54 @@ public class ExecutionCorrelationContextTests
Assert.Null(apiRow.CorrelationId);
Assert.Null(dbRow.CorrelationId);
}
[Fact]
public void ParentExecutionIdSupplied_StoredVerbatim_AndOwnExecutionIdIsFreshAndDistinct()
{
// Audit Log #23 (ParentExecutionId, Task 4): an inbound-API-routed call
// supplies the spawning execution's ExecutionId as the routed script's
// ParentExecutionId. The context must store that value verbatim AND
// still mint its OWN fresh ExecutionId — the routed script is a new
// execution, it does not inherit the parent's id.
var parentExecutionId = Guid.NewGuid();
var context = CreateContext(
externalSystemClient: null,
databaseGateway: null,
auditWriter: null,
// executionId omitted — the ctor's `?? Guid.NewGuid()` fallback runs.
parentExecutionId: parentExecutionId);
var storedParent = ReadPrivateField(context, "_parentExecutionId");
var ownExecutionId = ReadPrivateField(context, "_executionId");
// The parent id is carried through untouched.
Assert.Equal(parentExecutionId, storedParent);
// The routed script's own ExecutionId is freshly generated, non-empty,
// and NOT the parent id — they are separate correlation values.
Assert.NotNull(ownExecutionId);
var ownId = Assert.IsType<Guid>(ownExecutionId);
Assert.NotEqual(Guid.Empty, ownId);
Assert.NotEqual(parentExecutionId, ownId);
}
[Fact]
public void NoParentExecutionIdSupplied_NonRoutedRun_ParentStaysNull()
{
// A normal (tag-change / timer) script run is not inbound-API-routed —
// no ParentExecutionId is supplied, so _parentExecutionId stays null
// while the run still gets its own fresh ExecutionId.
var context = CreateContext(
externalSystemClient: null,
databaseGateway: null,
auditWriter: null);
var storedParent = ReadPrivateField(context, "_parentExecutionId");
var ownExecutionId = ReadPrivateField(context, "_executionId");
Assert.Null(storedParent);
var ownId = Assert.IsType<Guid>(ownExecutionId);
Assert.NotEqual(Guid.Empty, ownId);
}
}