Phase 3B: Site I/O & Observability — Communication, DCL, Script/Alarm actors, Health, Event Logging
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.
This commit is contained in:
@@ -0,0 +1,196 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ScadaLink.Commons.Interfaces.Protocol;
|
||||
using ScadaLink.Commons.Types.Enums;
|
||||
|
||||
namespace ScadaLink.DataConnectionLayer.Adapters;
|
||||
|
||||
/// <summary>
|
||||
/// WP-8: LmxProxy adapter implementing IDataConnection.
|
||||
/// Maps IDataConnection to LmxProxy SDK calls.
|
||||
///
|
||||
/// LmxProxy-specific behavior:
|
||||
/// - Session-based connection with 30s keep-alive
|
||||
/// - gRPC streaming for subscriptions
|
||||
/// - SessionId management (required for all operations)
|
||||
/// </summary>
|
||||
public class LmxProxyDataConnection : IDataConnection
|
||||
{
|
||||
private readonly ILmxProxyClientFactory _clientFactory;
|
||||
private readonly ILogger<LmxProxyDataConnection> _logger;
|
||||
private ILmxProxyClient? _client;
|
||||
private string _host = "localhost";
|
||||
private int _port = 5000;
|
||||
private ConnectionHealth _status = ConnectionHealth.Disconnected;
|
||||
private Timer? _keepAliveTimer;
|
||||
|
||||
private readonly Dictionary<string, string> _subscriptionHandles = new();
|
||||
|
||||
public LmxProxyDataConnection(ILmxProxyClientFactory clientFactory, ILogger<LmxProxyDataConnection> logger)
|
||||
{
|
||||
_clientFactory = clientFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public ConnectionHealth Status => _status;
|
||||
|
||||
public async Task ConnectAsync(IDictionary<string, string> connectionDetails, CancellationToken cancellationToken = default)
|
||||
{
|
||||
_host = connectionDetails.TryGetValue("Host", out var host) ? host : "localhost";
|
||||
if (connectionDetails.TryGetValue("Port", out var portStr) && int.TryParse(portStr, out var port))
|
||||
_port = port;
|
||||
|
||||
_status = ConnectionHealth.Connecting;
|
||||
_client = _clientFactory.Create();
|
||||
|
||||
var sessionId = await _client.OpenSessionAsync(_host, _port, cancellationToken);
|
||||
_status = ConnectionHealth.Connected;
|
||||
|
||||
// Start 30s keep-alive timer per design spec
|
||||
_keepAliveTimer = new Timer(
|
||||
async _ => await SendKeepAliveAsync(),
|
||||
null,
|
||||
TimeSpan.FromSeconds(30),
|
||||
TimeSpan.FromSeconds(30));
|
||||
|
||||
_logger.LogInformation("LmxProxy connected to {Host}:{Port}, sessionId={SessionId}", _host, _port, sessionId);
|
||||
}
|
||||
|
||||
public async Task DisconnectAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
_keepAliveTimer?.Dispose();
|
||||
_keepAliveTimer = null;
|
||||
|
||||
if (_client != null)
|
||||
{
|
||||
await _client.CloseSessionAsync(cancellationToken);
|
||||
_status = ConnectionHealth.Disconnected;
|
||||
_logger.LogInformation("LmxProxy disconnected from {Host}:{Port}", _host, _port);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<string> SubscribeAsync(string tagPath, SubscriptionCallback callback, CancellationToken cancellationToken = default)
|
||||
{
|
||||
EnsureConnected();
|
||||
|
||||
var handle = await _client!.SubscribeTagAsync(
|
||||
tagPath,
|
||||
(path, value, timestamp, isGood) =>
|
||||
{
|
||||
var quality = isGood ? QualityCode.Good : QualityCode.Bad;
|
||||
callback(path, new TagValue(value, quality, new DateTimeOffset(timestamp, TimeSpan.Zero)));
|
||||
},
|
||||
cancellationToken);
|
||||
|
||||
_subscriptionHandles[handle] = tagPath;
|
||||
return handle;
|
||||
}
|
||||
|
||||
public async Task UnsubscribeAsync(string subscriptionId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (_client != null)
|
||||
{
|
||||
await _client.UnsubscribeTagAsync(subscriptionId, cancellationToken);
|
||||
_subscriptionHandles.Remove(subscriptionId);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ReadResult> ReadAsync(string tagPath, CancellationToken cancellationToken = default)
|
||||
{
|
||||
EnsureConnected();
|
||||
|
||||
var (value, timestamp, isGood) = await _client!.ReadTagAsync(tagPath, cancellationToken);
|
||||
var quality = isGood ? QualityCode.Good : QualityCode.Bad;
|
||||
|
||||
if (!isGood)
|
||||
return new ReadResult(false, null, "LmxProxy read returned bad quality");
|
||||
|
||||
return new ReadResult(true, new TagValue(value, quality, new DateTimeOffset(timestamp, TimeSpan.Zero)), null);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyDictionary<string, ReadResult>> ReadBatchAsync(IEnumerable<string> tagPaths, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var results = new Dictionary<string, ReadResult>();
|
||||
foreach (var tagPath in tagPaths)
|
||||
{
|
||||
results[tagPath] = await ReadAsync(tagPath, cancellationToken);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
public async Task<WriteResult> WriteAsync(string tagPath, object? value, CancellationToken cancellationToken = default)
|
||||
{
|
||||
EnsureConnected();
|
||||
|
||||
var success = await _client!.WriteTagAsync(tagPath, value, cancellationToken);
|
||||
return success
|
||||
? new WriteResult(true, null)
|
||||
: new WriteResult(false, "LmxProxy write failed");
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyDictionary<string, WriteResult>> WriteBatchAsync(IDictionary<string, object?> values, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var results = new Dictionary<string, WriteResult>();
|
||||
foreach (var (tagPath, value) in values)
|
||||
{
|
||||
results[tagPath] = await WriteAsync(tagPath, value, cancellationToken);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
public async Task<bool> WriteBatchAndWaitAsync(
|
||||
IDictionary<string, object?> values, string flagPath, object? flagValue,
|
||||
string responsePath, object? responseValue, TimeSpan timeout,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var allValues = new Dictionary<string, object?>(values) { [flagPath] = flagValue };
|
||||
var writeResults = await WriteBatchAsync(allValues, cancellationToken);
|
||||
|
||||
if (writeResults.Values.Any(r => !r.Success))
|
||||
return false;
|
||||
|
||||
var deadline = DateTimeOffset.UtcNow + timeout;
|
||||
while (DateTimeOffset.UtcNow < deadline)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var readResult = await ReadAsync(responsePath, cancellationToken);
|
||||
if (readResult.Success && readResult.Value != null && Equals(readResult.Value.Value, responseValue))
|
||||
return true;
|
||||
|
||||
await Task.Delay(100, cancellationToken);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
_keepAliveTimer?.Dispose();
|
||||
_keepAliveTimer = null;
|
||||
|
||||
if (_client != null)
|
||||
{
|
||||
await _client.DisposeAsync();
|
||||
_client = null;
|
||||
}
|
||||
_status = ConnectionHealth.Disconnected;
|
||||
}
|
||||
|
||||
private void EnsureConnected()
|
||||
{
|
||||
if (_client == null || !_client.IsConnected)
|
||||
throw new InvalidOperationException("LmxProxy client is not connected.");
|
||||
}
|
||||
|
||||
private async Task SendKeepAliveAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_client?.IsConnected == true)
|
||||
await _client.SendKeepAliveAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "LmxProxy keep-alive failed for {Host}:{Port}", _host, _port);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user