350 lines
15 KiB
C#
350 lines
15 KiB
C#
using System.Collections.Concurrent;
|
|
using System.Collections.ObjectModel;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Nodes;
|
|
using AutoForge.Core.ExecutionTargets;
|
|
using AutoForge.Core.Vehicles;
|
|
using AutoForge.Diagnostics;
|
|
|
|
namespace AutoForge.Simulation;
|
|
|
|
public sealed class SimulatedDiagnosticTransportFactory : IDiagnosticTransportFactory
|
|
{
|
|
public const string ProviderIdentifier = "autoforge.simulation.synthetic";
|
|
private readonly Dictionary<ProfileRevisionKey, SimulationDefinition> _definitions;
|
|
private readonly ConcurrentDictionary<string, SimulatedDiagnosticTransport> _activeTransports =
|
|
new(StringComparer.Ordinal);
|
|
|
|
public SimulatedDiagnosticTransportFactory(IEnumerable<SimulationDefinition> definitions)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(definitions);
|
|
var source = definitions.ToArray();
|
|
_definitions = new Dictionary<ProfileRevisionKey, SimulationDefinition>(ProfileRevisionKeyComparer.Instance);
|
|
foreach (var definition in source)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(definition);
|
|
if (!_definitions.TryAdd(new ProfileRevisionKey(definition.ProfileIdentifier, definition.ProfileRevision), definition))
|
|
{
|
|
throw new ArgumentException("Simulation definitions contain a duplicate profile revision.", nameof(definitions));
|
|
}
|
|
}
|
|
|
|
Descriptor = new DiagnosticProviderDescriptor(
|
|
new ExecutionTargetDescriptor(ProviderIdentifier, ExecutionTargetKind.Simulation),
|
|
"Synthetic virtual-module provider");
|
|
}
|
|
|
|
public DiagnosticProviderDescriptor Descriptor { get; }
|
|
|
|
public IDiagnosticTransport OpenTransport(VehicleProfile profile, DiagnosticSessionIdentity identity)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(profile);
|
|
ArgumentNullException.ThrowIfNull(identity);
|
|
if (!Same(profile.ProfileIdentifier, identity.ProfileIdentifier) ||
|
|
profile.Revision != identity.ProfileRevision ||
|
|
!Same(profile.Vehicle.VehicleIdentifier, identity.VehicleIdentifier))
|
|
{
|
|
throw new ArgumentException("Session identity does not bind to the supplied immutable profile.", nameof(identity));
|
|
}
|
|
|
|
if (identity.Target.Kind != ExecutionTargetKind.Simulation ||
|
|
!Same(identity.Target.ProviderIdentifier, Descriptor.Target.ProviderIdentifier))
|
|
{
|
|
throw new ArgumentException("The synthetic provider accepts only its explicitly registered Simulation target.", nameof(identity));
|
|
}
|
|
|
|
if (!_definitions.TryGetValue(new ProfileRevisionKey(profile.ProfileIdentifier, profile.Revision), out var definition))
|
|
{
|
|
throw new DiagnosticProviderException(
|
|
DiagnosticProviderFailure.ConfigurationNotFound,
|
|
$"No synthetic simulation definition exists for profile '{profile.ProfileIdentifier}' revision {profile.Revision}.");
|
|
}
|
|
|
|
definition.ValidateAgainst(profile);
|
|
var transport = new SimulatedDiagnosticTransport(
|
|
definition,
|
|
identity,
|
|
onClosed: closed => _activeTransports.TryRemove(closed.SessionIdentifier, out _));
|
|
if (!_activeTransports.TryAdd(identity.SessionIdentifier, transport))
|
|
{
|
|
throw new DiagnosticProviderException(
|
|
DiagnosticProviderFailure.SessionConflict,
|
|
$"Session '{identity.SessionIdentifier}' already has a simulated transport.");
|
|
}
|
|
|
|
return transport;
|
|
}
|
|
|
|
internal IReadOnlyList<string> ReadVirtualDtcStateForTest(string sessionIdentifier, string moduleIdentifier)
|
|
{
|
|
if (!_activeTransports.TryGetValue(sessionIdentifier, out var transport))
|
|
{
|
|
throw new InvalidOperationException("The test oracle can inspect only an active simulated session.");
|
|
}
|
|
|
|
return transport.ReadDtcStateForTest(moduleIdentifier);
|
|
}
|
|
|
|
internal Task WaitForPendingRequestForTestAsync(string sessionIdentifier)
|
|
{
|
|
if (!_activeTransports.TryGetValue(sessionIdentifier, out var transport))
|
|
{
|
|
throw new InvalidOperationException("The test oracle can inspect only an active simulated session.");
|
|
}
|
|
|
|
return transport.WaitForPendingRequestForTestAsync();
|
|
}
|
|
|
|
private readonly record struct ProfileRevisionKey(string ProfileIdentifier, int Revision);
|
|
|
|
private sealed class ProfileRevisionKeyComparer : IEqualityComparer<ProfileRevisionKey>
|
|
{
|
|
public static ProfileRevisionKeyComparer Instance { get; } = new();
|
|
public bool Equals(ProfileRevisionKey x, ProfileRevisionKey y) =>
|
|
x.Revision == y.Revision && Same(x.ProfileIdentifier, y.ProfileIdentifier);
|
|
public int GetHashCode(ProfileRevisionKey value) =>
|
|
HashCode.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(value.ProfileIdentifier), value.Revision);
|
|
}
|
|
|
|
private static bool Same(string left, string right) =>
|
|
StringComparer.OrdinalIgnoreCase.Equals(left, right);
|
|
|
|
}
|
|
|
|
internal sealed class SimulatedDiagnosticTransport : IDiagnosticTransport
|
|
{
|
|
private readonly SimulationDefinition _definition;
|
|
private readonly DiagnosticSessionIdentity _identity;
|
|
private readonly CancellationTokenSource _closed = new();
|
|
private readonly Action<DiagnosticSessionIdentity> _onClosed;
|
|
private readonly Dictionary<string, VirtualModuleState> _states;
|
|
private readonly TaskCompletionSource _pendingRequestStarted = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
private int _isClosed;
|
|
|
|
public SimulatedDiagnosticTransport(
|
|
SimulationDefinition definition,
|
|
DiagnosticSessionIdentity identity,
|
|
Action<DiagnosticSessionIdentity> onClosed)
|
|
{
|
|
_definition = definition;
|
|
_identity = identity;
|
|
_onClosed = onClosed;
|
|
_states = definition.Modules.ToDictionary(
|
|
module => module.ModuleIdentifier,
|
|
module => new VirtualModuleState(module),
|
|
StringComparer.OrdinalIgnoreCase);
|
|
ExpectedEndpoints = Array.AsReadOnly(definition.Modules
|
|
.Select(module => new DiagnosticEndpoint(module.ModuleIdentifier, module.Address))
|
|
.ToArray());
|
|
}
|
|
|
|
public IReadOnlyList<DiagnosticEndpoint> ExpectedEndpoints { get; }
|
|
|
|
public async ValueTask<TransportReply> SendAsync(ReadOnlyMemory<byte> requestPayload, CancellationToken cancellationToken)
|
|
{
|
|
if (Volatile.Read(ref _isClosed) != 0)
|
|
{
|
|
return new TransportReply(TransportOutcome.Cancelled, ReadOnlyMemory<byte>.Empty, 0, "Session transport is closed.");
|
|
}
|
|
|
|
if (!SyntheticProtocolV1.TryDecodeRequest(requestPayload, out var request) || request is null)
|
|
{
|
|
return new TransportReply(TransportOutcome.NoResponse, ReadOnlyMemory<byte>.Empty, 0, "Request frame was malformed.");
|
|
}
|
|
|
|
if (request.Version != 1)
|
|
{
|
|
return new TransportReply(
|
|
TransportOutcome.Response,
|
|
SyntheticProtocolV1.EncodeNegativeResponse(request, "UNSUPPORTED_VERSION", "Synthetic protocol version 1 is required."),
|
|
0);
|
|
}
|
|
|
|
if (!Same(request.SessionIdentifier, _identity.SessionIdentifier) ||
|
|
!Same(request.ProfileIdentifier, _identity.ProfileIdentifier) ||
|
|
!Same(request.ConfigurationIdentifier, _identity.ConfigurationIdentifier) ||
|
|
request.ProfileRevision != _identity.ProfileRevision)
|
|
{
|
|
return new TransportReply(
|
|
TransportOutcome.Response,
|
|
SyntheticProtocolV1.EncodeNegativeResponse(request, "SESSION_MISMATCH", "Request session/profile identity is not bound to this transport."),
|
|
0);
|
|
}
|
|
|
|
var module = _definition.Modules.FirstOrDefault(candidate => Same(candidate.Address, request.TargetAddress));
|
|
if (module is null)
|
|
{
|
|
return new TransportReply(
|
|
TransportOutcome.Response,
|
|
SyntheticProtocolV1.EncodeNegativeResponse(request, "UNKNOWN_ADDRESS", "No virtual endpoint is configured at this address."),
|
|
0);
|
|
}
|
|
|
|
var fault = module.Faults.TryGetValue(request.Service, out var configuredFault)
|
|
? configuredFault
|
|
: SimulatedFault.None;
|
|
if (fault == SimulatedFault.NoResponse)
|
|
{
|
|
return new TransportReply(TransportOutcome.NoResponse, ReadOnlyMemory<byte>.Empty, 0, "Configured endpoint did not respond.");
|
|
}
|
|
|
|
if (fault == SimulatedFault.HoldUntilCancelled)
|
|
{
|
|
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _closed.Token);
|
|
_pendingRequestStarted.TrySetResult();
|
|
try
|
|
{
|
|
await Task.Delay(Timeout.InfiniteTimeSpan, linked.Token).ConfigureAwait(false);
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
return new TransportReply(TransportOutcome.Cancelled, ReadOnlyMemory<byte>.Empty, 0, "Pending virtual request was cancelled or its session closed.");
|
|
}
|
|
}
|
|
|
|
if (Volatile.Read(ref _isClosed) != 0 || cancellationToken.IsCancellationRequested)
|
|
{
|
|
return new TransportReply(TransportOutcome.Cancelled, ReadOnlyMemory<byte>.Empty, 0, "Session transport is closed or request cancelled.");
|
|
}
|
|
|
|
if (module.ResponseLatencyTicks > request.TimeoutTicks)
|
|
{
|
|
return new TransportReply(
|
|
TransportOutcome.Timeout,
|
|
ReadOnlyMemory<byte>.Empty,
|
|
request.TimeoutTicks,
|
|
$"Virtual response latency {module.ResponseLatencyTicks} exceeded deadline {request.TimeoutTicks}.");
|
|
}
|
|
|
|
if (fault == SimulatedFault.MalformedResponse)
|
|
{
|
|
return new TransportReply(TransportOutcome.Response, "{malformed"u8.ToArray(), module.ResponseLatencyTicks);
|
|
}
|
|
|
|
var response = CreateResponse(request, module);
|
|
if (fault == SimulatedFault.WrongCorrelation)
|
|
{
|
|
var corrupted = JsonNode.Parse(response)!.AsObject();
|
|
corrupted["correlationIdentifier"] = "unexpected-correlation";
|
|
response = JsonSerializer.SerializeToUtf8Bytes(corrupted);
|
|
}
|
|
else if (fault == SimulatedFault.WrongIdentity && request.Service == DiagnosticServices.ReadIdentity)
|
|
{
|
|
var corrupted = JsonNode.Parse(response)!.AsObject();
|
|
corrupted["data"]!["moduleIdentifier"] = "module.unexpected";
|
|
response = JsonSerializer.SerializeToUtf8Bytes(corrupted);
|
|
}
|
|
|
|
return new TransportReply(TransportOutcome.Response, response, module.ResponseLatencyTicks);
|
|
}
|
|
|
|
internal IReadOnlyList<string> ReadDtcStateForTest(string moduleIdentifier)
|
|
{
|
|
if (!_states.TryGetValue(moduleIdentifier, out var state))
|
|
{
|
|
throw new KeyNotFoundException($"Virtual module '{moduleIdentifier}' is not configured.");
|
|
}
|
|
|
|
lock (state.Gate)
|
|
{
|
|
return Array.AsReadOnly(state.TroubleCodes.Select(code => code.Code).ToArray());
|
|
}
|
|
}
|
|
|
|
internal Task WaitForPendingRequestForTestAsync() => _pendingRequestStarted.Task;
|
|
|
|
public ValueTask DisposeAsync()
|
|
{
|
|
if (Interlocked.Exchange(ref _isClosed, 1) == 0)
|
|
{
|
|
_closed.Cancel();
|
|
_onClosed(_identity);
|
|
_closed.Dispose();
|
|
}
|
|
|
|
return ValueTask.CompletedTask;
|
|
}
|
|
|
|
private byte[] CreateResponse(SyntheticDiagnosticRequest request, VirtualModuleDefinition module)
|
|
{
|
|
if (!module.ImplementedServices.Contains(request.Service, StringComparer.Ordinal))
|
|
{
|
|
return SyntheticProtocolV1.EncodeNegativeResponse(
|
|
request,
|
|
"UNSUPPORTED_SERVICE",
|
|
$"Service '{request.Service}' is not implemented by this virtual endpoint.");
|
|
}
|
|
|
|
var state = _states[module.ModuleIdentifier];
|
|
object data = request.Service switch
|
|
{
|
|
DiagnosticServices.Probe => new
|
|
{
|
|
moduleIdentifier = module.ModuleIdentifier,
|
|
implementedServices = module.ImplementedServices
|
|
},
|
|
DiagnosticServices.ReadIdentity => new
|
|
{
|
|
moduleIdentifier = module.ModuleIdentifier,
|
|
role = module.Identity.Role,
|
|
name = module.Identity.Name,
|
|
hardwareIdentifier = module.Identity.HardwareIdentifier,
|
|
softwareIdentifier = module.Identity.SoftwareIdentifier,
|
|
firmwareIdentifier = module.Identity.FirmwareIdentifier,
|
|
calibrationIdentifier = module.Identity.CalibrationIdentifier
|
|
},
|
|
DiagnosticServices.ReadTroubleCodes => ReadDtcData(module, state),
|
|
DiagnosticServices.ClearTroubleCodes => ClearDtcData(module, state),
|
|
DiagnosticServices.ReadSignals => new
|
|
{
|
|
moduleIdentifier = module.ModuleIdentifier,
|
|
logicalTimeTicks = request.LogicalTimeTicks,
|
|
origin = "SYNTHETIC_STATIC",
|
|
signals = module.Signals.Select(signal => new
|
|
{
|
|
signalIdentifier = signal.SignalIdentifier,
|
|
value = signal.Value,
|
|
unit = signal.Unit,
|
|
quality = signal.Quality.ToString()
|
|
}).ToArray()
|
|
},
|
|
_ => null!
|
|
};
|
|
|
|
return data is null
|
|
? SyntheticProtocolV1.EncodeNegativeResponse(request, "UNSUPPORTED_SERVICE", $"Service '{request.Service}' is not implemented.")
|
|
: SyntheticProtocolV1.EncodePositiveResponse(request, data);
|
|
}
|
|
|
|
private static object ReadDtcData(VirtualModuleDefinition module, VirtualModuleState state)
|
|
{
|
|
lock (state.Gate)
|
|
{
|
|
return new
|
|
{
|
|
moduleIdentifier = module.ModuleIdentifier,
|
|
codes = state.TroubleCodes.Select(code => new { code = code.Code, description = code.Description }).ToArray()
|
|
};
|
|
}
|
|
}
|
|
|
|
private static object ClearDtcData(VirtualModuleDefinition module, VirtualModuleState state)
|
|
{
|
|
lock (state.Gate)
|
|
{
|
|
var count = state.TroubleCodes.Count;
|
|
state.TroubleCodes.Clear();
|
|
return new { moduleIdentifier = module.ModuleIdentifier, clearedCount = count };
|
|
}
|
|
}
|
|
|
|
private static bool Same(string left, string right) =>
|
|
StringComparer.OrdinalIgnoreCase.Equals(left, right);
|
|
|
|
private sealed class VirtualModuleState(VirtualModuleDefinition definition)
|
|
{
|
|
public object Gate { get; } = new();
|
|
public List<VirtualTroubleCodeDefinition> TroubleCodes { get; } = definition.InitialTroubleCodes.ToList();
|
|
}
|
|
}
|