Communication Layer (WP-1–5): - 8 message patterns with correlation IDs, per-pattern timeouts - Central/Site communication actors, transport heartbeat config - Connection failure handling (no central buffering, debug streams killed) Data Connection Layer (WP-6–14, WP-34): - Connection actor with Become/Stash lifecycle (Connecting/Connected/Reconnecting) - OPC UA + LmxProxy adapters behind IDataConnection - Auto-reconnect, bad quality propagation, transparent re-subscribe - Write-back, tag path resolution with retry, health reporting - Protocol extensibility via DataConnectionFactory Site Runtime (WP-15–25, WP-32–33): - ScriptActor/ScriptExecutionActor (triggers, concurrent execution, blocking I/O dispatcher) - AlarmActor/AlarmExecutionActor (ValueMatch/RangeViolation/RateOfChange, in-memory state) - SharedScriptLibrary (inline execution), ScriptRuntimeContext (API) - ScriptCompilationService (Roslyn, forbidden API enforcement, execution timeout) - Recursion limit (default 10), call direction enforcement - SiteStreamManager (per-subscriber bounded buffers, fire-and-forget) - Debug view backend (snapshot + stream), concurrency serialization - Local artifact storage (4 SQLite tables) Health Monitoring (WP-26–28): - SiteHealthCollector (thread-safe counters, connection state) - HealthReportSender (30s interval, monotonic sequence numbers) - CentralHealthAggregator (offline detection 60s, online recovery) Site Event Logging (WP-29–31): - SiteEventLogger (SQLite, 6 event categories, ISO 8601 UTC) - EventLogPurgeService (30-day retention, 1GB cap) - EventLogQueryService (filters, keyword search, keyset pagination) 541 tests pass, zero warnings.
226 lines
7.7 KiB
C#
226 lines
7.7 KiB
C#
using Akka.Actor;
|
|
using Akka.TestKit.Xunit2;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using ScadaLink.Commons.Messages.Instance;
|
|
using ScadaLink.Commons.Types.Flattening;
|
|
using ScadaLink.SiteRuntime.Actors;
|
|
using ScadaLink.SiteRuntime.Persistence;
|
|
using ScadaLink.SiteRuntime.Scripts;
|
|
using System.Text.Json;
|
|
|
|
namespace ScadaLink.SiteRuntime.Tests.Actors;
|
|
|
|
/// <summary>
|
|
/// Tests for InstanceActor: attribute loading, static overrides, and persistence.
|
|
/// </summary>
|
|
public class InstanceActorTests : TestKit, IDisposable
|
|
{
|
|
private readonly SiteStorageService _storage;
|
|
private readonly ScriptCompilationService _compilationService;
|
|
private readonly SharedScriptLibrary _sharedScriptLibrary;
|
|
private readonly SiteRuntimeOptions _options;
|
|
private readonly string _dbFile;
|
|
|
|
public InstanceActorTests()
|
|
{
|
|
_dbFile = Path.Combine(Path.GetTempPath(), $"instance-actor-test-{Guid.NewGuid():N}.db");
|
|
_storage = new SiteStorageService(
|
|
$"Data Source={_dbFile}",
|
|
NullLogger<SiteStorageService>.Instance);
|
|
_storage.InitializeAsync().GetAwaiter().GetResult();
|
|
_compilationService = new ScriptCompilationService(
|
|
NullLogger<ScriptCompilationService>.Instance);
|
|
_sharedScriptLibrary = new SharedScriptLibrary(
|
|
_compilationService, NullLogger<SharedScriptLibrary>.Instance);
|
|
_options = new SiteRuntimeOptions();
|
|
}
|
|
|
|
private IActorRef CreateInstanceActor(string instanceName, FlattenedConfiguration config)
|
|
{
|
|
return ActorOf(Props.Create(() => new InstanceActor(
|
|
instanceName,
|
|
JsonSerializer.Serialize(config),
|
|
_storage,
|
|
_compilationService,
|
|
_sharedScriptLibrary,
|
|
null, // no stream manager in tests
|
|
_options,
|
|
NullLogger<InstanceActor>.Instance)));
|
|
}
|
|
|
|
void IDisposable.Dispose()
|
|
{
|
|
Shutdown();
|
|
try { File.Delete(_dbFile); } catch { /* cleanup */ }
|
|
}
|
|
|
|
[Fact]
|
|
public void InstanceActor_LoadsAttributesFromConfig()
|
|
{
|
|
var config = new FlattenedConfiguration
|
|
{
|
|
InstanceUniqueName = "Pump1",
|
|
Attributes =
|
|
[
|
|
new ResolvedAttribute { CanonicalName = "Temperature", Value = "98.6", DataType = "Double" },
|
|
new ResolvedAttribute { CanonicalName = "Status", Value = "Running", DataType = "String" }
|
|
]
|
|
};
|
|
|
|
var actor = CreateInstanceActor("Pump1", config);
|
|
|
|
// Query for an attribute that exists
|
|
actor.Tell(new GetAttributeRequest(
|
|
"corr-1", "Pump1", "Temperature", DateTimeOffset.UtcNow));
|
|
|
|
var response = ExpectMsg<GetAttributeResponse>();
|
|
Assert.True(response.Found);
|
|
Assert.Equal("98.6", response.Value?.ToString());
|
|
Assert.Equal("corr-1", response.CorrelationId);
|
|
}
|
|
|
|
[Fact]
|
|
public void InstanceActor_GetAttribute_NotFound_ReturnsFalse()
|
|
{
|
|
var config = new FlattenedConfiguration
|
|
{
|
|
InstanceUniqueName = "Pump1",
|
|
Attributes = []
|
|
};
|
|
|
|
var actor = CreateInstanceActor("Pump1", config);
|
|
|
|
actor.Tell(new GetAttributeRequest(
|
|
"corr-2", "Pump1", "NonExistent", DateTimeOffset.UtcNow));
|
|
|
|
var response = ExpectMsg<GetAttributeResponse>();
|
|
Assert.False(response.Found);
|
|
Assert.Null(response.Value);
|
|
}
|
|
|
|
[Fact]
|
|
public void InstanceActor_SetStaticAttribute_UpdatesInMemory()
|
|
{
|
|
var config = new FlattenedConfiguration
|
|
{
|
|
InstanceUniqueName = "Pump1",
|
|
Attributes =
|
|
[
|
|
new ResolvedAttribute { CanonicalName = "Temperature", Value = "98.6", DataType = "Double" }
|
|
]
|
|
};
|
|
|
|
var actor = CreateInstanceActor("Pump1", config);
|
|
|
|
// Set a static attribute -- response comes async via PipeTo
|
|
actor.Tell(new SetStaticAttributeCommand(
|
|
"corr-3", "Pump1", "Temperature", "100.0", DateTimeOffset.UtcNow));
|
|
|
|
var setResponse = ExpectMsg<SetStaticAttributeResponse>(TimeSpan.FromSeconds(5));
|
|
Assert.True(setResponse.Success);
|
|
|
|
// Verify the value changed in memory
|
|
actor.Tell(new GetAttributeRequest(
|
|
"corr-4", "Pump1", "Temperature", DateTimeOffset.UtcNow));
|
|
|
|
var getResponse = ExpectMsg<GetAttributeResponse>();
|
|
Assert.True(getResponse.Found);
|
|
Assert.Equal("100.0", getResponse.Value?.ToString());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task InstanceActor_SetStaticAttribute_PersistsToSQLite()
|
|
{
|
|
var config = new FlattenedConfiguration
|
|
{
|
|
InstanceUniqueName = "PumpPersist1",
|
|
Attributes =
|
|
[
|
|
new ResolvedAttribute { CanonicalName = "Temperature", Value = "98.6", DataType = "Double" }
|
|
]
|
|
};
|
|
|
|
var actor = CreateInstanceActor("PumpPersist1", config);
|
|
|
|
actor.Tell(new SetStaticAttributeCommand(
|
|
"corr-persist", "PumpPersist1", "Temperature", "100.0", DateTimeOffset.UtcNow));
|
|
|
|
ExpectMsg<SetStaticAttributeResponse>(TimeSpan.FromSeconds(5));
|
|
|
|
// Give async persistence time to complete
|
|
await Task.Delay(500);
|
|
|
|
// Verify it persisted to SQLite
|
|
var overrides = await _storage.GetStaticOverridesAsync("PumpPersist1");
|
|
Assert.Single(overrides);
|
|
Assert.Equal("100.0", overrides["Temperature"]);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task InstanceActor_LoadsStaticOverridesFromSQLite()
|
|
{
|
|
// Pre-populate overrides in SQLite
|
|
await _storage.SetStaticOverrideAsync("PumpOverride1", "Temperature", "200.0");
|
|
|
|
var config = new FlattenedConfiguration
|
|
{
|
|
InstanceUniqueName = "PumpOverride1",
|
|
Attributes =
|
|
[
|
|
new ResolvedAttribute { CanonicalName = "Temperature", Value = "98.6", DataType = "Double" }
|
|
]
|
|
};
|
|
|
|
var actor = CreateInstanceActor("PumpOverride1", config);
|
|
|
|
// Wait for the async override loading to complete (PipeTo)
|
|
await Task.Delay(1000);
|
|
|
|
actor.Tell(new GetAttributeRequest(
|
|
"corr-5", "PumpOverride1", "Temperature", DateTimeOffset.UtcNow));
|
|
|
|
var response = ExpectMsg<GetAttributeResponse>();
|
|
Assert.True(response.Found);
|
|
// The override value should take precedence over the config default
|
|
Assert.Equal("200.0", response.Value?.ToString());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task StaticOverride_ResetOnRedeployment()
|
|
{
|
|
// Set up an override
|
|
await _storage.SetStaticOverrideAsync("PumpRedeploy", "Temperature", "200.0");
|
|
|
|
// Verify override exists
|
|
var overrides = await _storage.GetStaticOverridesAsync("PumpRedeploy");
|
|
Assert.Single(overrides);
|
|
|
|
// Clear overrides (simulates what DeploymentManager does on redeployment)
|
|
await _storage.ClearStaticOverridesAsync("PumpRedeploy");
|
|
|
|
overrides = await _storage.GetStaticOverridesAsync("PumpRedeploy");
|
|
Assert.Empty(overrides);
|
|
|
|
// Create actor with fresh config -- should NOT have the override
|
|
var config = new FlattenedConfiguration
|
|
{
|
|
InstanceUniqueName = "PumpRedeploy",
|
|
Attributes =
|
|
[
|
|
new ResolvedAttribute { CanonicalName = "Temperature", Value = "98.6", DataType = "Double" }
|
|
]
|
|
};
|
|
|
|
var actor = CreateInstanceActor("PumpRedeploy", config);
|
|
|
|
await Task.Delay(1000);
|
|
|
|
actor.Tell(new GetAttributeRequest(
|
|
"corr-6", "PumpRedeploy", "Temperature", DateTimeOffset.UtcNow));
|
|
|
|
var response = ExpectMsg<GetAttributeResponse>();
|
|
Assert.Equal("98.6", response.Value?.ToString());
|
|
}
|
|
}
|