AutoForge/src/AutoForge.Diagnostics/ProviderContracts.cs

606 lines
21 KiB
C#

using System.Collections.ObjectModel;
using System.Text.Json;
using System.Text.RegularExpressions;
using AutoForge.Core.ExecutionTargets;
using AutoForge.Core.Simulation;
using AutoForge.Core.Vehicles;
namespace AutoForge.Diagnostics;
public sealed class DiagnosticProviderDescriptor
{
public DiagnosticProviderDescriptor(ExecutionTargetDescriptor target, string displayName)
{
Target = target ?? throw new ArgumentNullException(nameof(target));
ArgumentException.ThrowIfNullOrWhiteSpace(displayName);
DisplayName = displayName;
}
public ExecutionTargetDescriptor Target { get; }
public string DisplayName { get; }
}
public sealed class DiagnosticSessionIdentity
{
public DiagnosticSessionIdentity(
string sessionIdentifier,
string profileIdentifier,
int profileRevision,
string vehicleIdentifier,
ExecutionTargetDescriptor target,
string? dynamicsConfigurationIdentifier = null,
string? dynamicsRunIdentifier = null)
{
SessionIdentifier = Require(sessionIdentifier, nameof(sessionIdentifier));
ProfileIdentifier = Require(profileIdentifier, nameof(profileIdentifier));
if (profileRevision <= 0)
{
throw new ArgumentOutOfRangeException(nameof(profileRevision));
}
ProfileRevision = profileRevision;
VehicleIdentifier = Require(vehicleIdentifier, nameof(vehicleIdentifier));
Target = target ?? throw new ArgumentNullException(nameof(target));
if ((dynamicsConfigurationIdentifier is null) != (dynamicsRunIdentifier is null))
{
throw new ArgumentException("Dynamics configuration and run identities must either both be present or both be absent.");
}
DynamicsConfigurationIdentifier = dynamicsConfigurationIdentifier is null
? null
: Require(dynamicsConfigurationIdentifier, nameof(dynamicsConfigurationIdentifier));
DynamicsRunIdentifier = dynamicsRunIdentifier is null
? null
: Require(dynamicsRunIdentifier, nameof(dynamicsRunIdentifier));
ConfigurationIdentifier = DynamicsConfigurationIdentifier is null
? $"profile:{ProfileIdentifier}@revision:{ProfileRevision}"
: $"profile:{ProfileIdentifier}@revision:{ProfileRevision};dynamics:{DynamicsConfigurationIdentifier}";
}
public string SessionIdentifier { get; }
public string ProfileIdentifier { get; }
public int ProfileRevision { get; }
public string ConfigurationIdentifier { get; }
public string VehicleIdentifier { get; }
public ExecutionTargetDescriptor Target { get; }
public string? DynamicsConfigurationIdentifier { get; }
public string? DynamicsRunIdentifier { get; }
private static string Require(string value, string parameterName)
{
ArgumentException.ThrowIfNullOrWhiteSpace(value, parameterName);
if (!StringComparer.Ordinal.Equals(value, value.Trim()))
{
throw new ArgumentException("Values must not contain surrounding whitespace.", parameterName);
}
return value;
}
}
public sealed class DiagnosticEndpoint
{
private static readonly Regex AddressPattern = new(@"\A[0-9A-Fa-f]{1,4}\z", RegexOptions.CultureInvariant | RegexOptions.Compiled);
public DiagnosticEndpoint(string moduleIdentifier, string address)
{
ArgumentException.ThrowIfNullOrWhiteSpace(moduleIdentifier);
if (!StringComparer.Ordinal.Equals(moduleIdentifier, moduleIdentifier.Trim()))
{
throw new ArgumentException("Module identifiers must not contain surrounding whitespace.", nameof(moduleIdentifier));
}
ArgumentException.ThrowIfNullOrWhiteSpace(address);
if (!StringComparer.Ordinal.Equals(address, address.Trim()))
{
throw new ArgumentException("Endpoint addresses must not contain surrounding whitespace.", nameof(address));
}
if (!AddressPattern.IsMatch(address))
{
throw new ArgumentException("Synthetic protocol addresses must be one to four hexadecimal digits.", nameof(address));
}
ModuleIdentifier = moduleIdentifier;
Address = address;
}
public string ModuleIdentifier { get; }
public string Address { get; }
}
public interface IDiagnosticTransportFactory
{
DiagnosticProviderDescriptor Descriptor { get; }
IDiagnosticTransport OpenTransport(VehicleProfile profile, DiagnosticSessionIdentity identity);
}
public interface IDynamicsControl : IAsyncDisposable
{
DynamicsRunStatus Status { get; }
double PacingFactor { get; }
Task<DynamicsRunStatus> StartAsync(CancellationToken cancellationToken = default);
Task<DynamicsRunStatus> PauseAsync(CancellationToken cancellationToken = default);
Task<DynamicsRunStatus> ResumeAsync(CancellationToken cancellationToken = default);
Task<DynamicsRunStatus> StopAsync(CancellationToken cancellationToken = default);
Task<DynamicsRunStatus> ResetAsync(CancellationToken cancellationToken = default);
Task<DynamicsRunStatus> StepAsync(int stepCount = 1, CancellationToken cancellationToken = default);
Task<DynamicsRunStatus> SetPacingFactorAsync(double factor, CancellationToken cancellationToken = default);
Task<DynamicsRunStatus> RunScenarioAsync(CancellationToken cancellationToken = default);
}
public sealed record DynamicsSessionBinding(IDiagnosticTransport Transport, IDynamicsControl Control);
public interface IDynamicsDiagnosticTransportFactory : IDiagnosticTransportFactory
{
DynamicsSessionBinding OpenDynamicsTransport(
VehicleProfile profile,
DiagnosticSessionIdentity identity,
DynamicsConfiguration configuration);
}
public enum DiagnosticProviderFailure
{
ConfigurationNotFound,
SessionConflict
}
public sealed class DiagnosticProviderException(
DiagnosticProviderFailure failure,
string message,
Exception? innerException = null) : Exception(message, innerException)
{
public DiagnosticProviderFailure Failure { get; } = failure;
}
public interface IDiagnosticTransport : IAsyncDisposable
{
IReadOnlyList<DiagnosticEndpoint> ExpectedEndpoints { get; }
ValueTask<TransportReply> SendAsync(ReadOnlyMemory<byte> request, CancellationToken cancellationToken);
}
public enum TransportOutcome
{
Response,
NoResponse,
Timeout,
Cancelled
}
public sealed class TransportReply
{
private readonly byte[]? _payload;
public TransportReply(TransportOutcome outcome, ReadOnlyMemory<byte> payload, long elapsedTicks, string? detail = null)
{
if (!Enum.IsDefined(outcome))
{
throw new ArgumentOutOfRangeException(nameof(outcome));
}
if (elapsedTicks < 0)
{
throw new ArgumentOutOfRangeException(nameof(elapsedTicks));
}
if (outcome != TransportOutcome.Response && !payload.IsEmpty)
{
throw new ArgumentException("A non-response outcome cannot contain a response payload.", nameof(payload));
}
Outcome = outcome;
_payload = payload.IsEmpty ? null : payload.ToArray();
ElapsedTicks = elapsedTicks;
Detail = detail;
}
public TransportOutcome Outcome { get; }
public ReadOnlyMemory<byte> Payload => _payload ?? ReadOnlyMemory<byte>.Empty;
public long ElapsedTicks { get; }
public string? Detail { get; }
}
public enum DiagnosticOutcome
{
PositiveResponse,
NegativeResponse,
NoResponse,
Timeout,
Cancelled,
ProtocolError
}
public sealed class DiagnosticOperationResult<T>
{
private DiagnosticOperationResult(
DiagnosticOutcome outcome,
T? value,
string? failureCode,
string? error)
{
Outcome = outcome;
Value = value;
FailureCode = failureCode;
Error = error;
}
public DiagnosticOutcome Outcome { get; }
public T? Value { get; }
public string? FailureCode { get; }
public string? Error { get; }
public bool IsSuccess => Outcome == DiagnosticOutcome.PositiveResponse;
public static DiagnosticOperationResult<T> Success(T value) =>
new(DiagnosticOutcome.PositiveResponse, value ?? throw new ArgumentNullException(nameof(value)), null, null);
public static DiagnosticOperationResult<T> Failure(DiagnosticOutcome outcome, string code, string message)
{
if (outcome == DiagnosticOutcome.PositiveResponse)
{
throw new ArgumentOutOfRangeException(nameof(outcome));
}
return new DiagnosticOperationResult<T>(outcome, default, code, message);
}
}
public sealed record ModuleIdentityResult(
string ModuleIdentifier,
string Address,
string Role,
string Name,
string? HardwareIdentifier,
string? SoftwareIdentifier,
string? FirmwareIdentifier,
string? CalibrationIdentifier);
public sealed class DiagnosticProbeResult
{
public DiagnosticProbeResult(string moduleIdentifier, IEnumerable<string> implementedServices)
{
ArgumentException.ThrowIfNullOrWhiteSpace(moduleIdentifier);
ArgumentNullException.ThrowIfNull(implementedServices);
ModuleIdentifier = moduleIdentifier;
ImplementedServices = Array.AsReadOnly(implementedServices.ToArray());
}
public string ModuleIdentifier { get; }
public IReadOnlyList<string> ImplementedServices { get; }
}
public enum DiagnosticIdentityStatus
{
NotAttempted,
Verified,
Unavailable
}
public sealed class DiscoveryEntry
{
public DiscoveryEntry(
DiagnosticEndpoint endpoint,
DiagnosticOperationResult<DiagnosticProbeResult> probe,
DiagnosticOperationResult<ModuleIdentityResult>? identityResult,
string? identityNotAttemptedReason = null)
{
Endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
Probe = probe ?? throw new ArgumentNullException(nameof(probe));
if (probe.IsSuccess != (probe.Value is not null))
{
throw new ArgumentException("Probe result value must match its success outcome.", nameof(probe));
}
if (!probe.IsSuccess && identityResult is not null)
{
throw new ArgumentException("Identity cannot be attempted when the probe did not succeed.", nameof(identityResult));
}
if (identityResult is not null && !probe.Value!.ImplementedServices.Contains(
DiagnosticServices.ReadIdentity,
StringComparer.Ordinal))
{
throw new ArgumentException("Identity cannot be attempted when the probe did not advertise the service.", nameof(identityResult));
}
if (identityResult is not null &&
identityResult.IsSuccess != (identityResult.Value is not null))
{
throw new ArgumentException("Identity result value must match its success outcome.", nameof(identityResult));
}
if (identityResult is null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(identityNotAttemptedReason);
}
if (identityResult is not null && identityNotAttemptedReason is not null)
{
throw new ArgumentException("An identity attempt cannot also have a not-attempted reason.", nameof(identityNotAttemptedReason));
}
if (!Enum.IsDefined(probe.Outcome) ||
identityResult is not null && !Enum.IsDefined(identityResult.Outcome))
{
throw new ArgumentOutOfRangeException(nameof(probe), "Discovery phases must use defined diagnostic outcomes.");
}
Probe = probe;
IdentityResult = identityResult;
IdentityNotAttemptedReason = identityNotAttemptedReason;
}
public DiagnosticEndpoint Endpoint { get; }
public DiagnosticOperationResult<DiagnosticProbeResult> Probe { get; }
public DiagnosticOutcome ProbeOutcome => Probe.Outcome;
public string? ProbeError => Probe.Error;
public bool ProbeSucceeded => Probe.IsSuccess;
public IReadOnlyList<string> ImplementedServices => Probe.Value?.ImplementedServices ?? Array.Empty<string>();
public DiagnosticOperationResult<ModuleIdentityResult>? IdentityResult { get; }
public ModuleIdentityResult? Identity => IdentityResult?.Value;
public DiagnosticIdentityStatus IdentityStatus => IdentityResult switch
{
null => DiagnosticIdentityStatus.NotAttempted,
{ IsSuccess: true } => DiagnosticIdentityStatus.Verified,
_ => DiagnosticIdentityStatus.Unavailable
};
public DiagnosticOutcome? IdentityOutcome => IdentityResult?.Outcome;
public string? IdentityError => IdentityResult?.Error ?? IdentityNotAttemptedReason;
public string? IdentityNotAttemptedReason { get; }
}
public sealed class DiscoveryResult
{
public DiscoveryResult(IEnumerable<DiscoveryEntry> endpoints)
{
ArgumentNullException.ThrowIfNull(endpoints);
Endpoints = Array.AsReadOnly(endpoints.ToArray());
}
public IReadOnlyList<DiscoveryEntry> Endpoints { get; }
public IReadOnlyList<DiscoveryEntry> ValidatedProbes =>
Array.AsReadOnly(Endpoints.Where(endpoint => endpoint.ProbeSucceeded).ToArray());
public IReadOnlyList<ModuleIdentityResult> IdentifiedModules =>
Array.AsReadOnly(Endpoints.Where(endpoint => endpoint.Identity is not null).Select(endpoint => endpoint.Identity!).ToArray());
public int ExpectedEndpointCount => Endpoints.Count;
public int ValidatedProbeCount => ValidatedProbes.Count;
public int IdentifiedModuleCount => IdentifiedModules.Count;
}
public sealed record DiagnosticTroubleCode(string Code, string Description, string SourceModuleIdentifier);
public sealed class TroubleCodeReadResult
{
public TroubleCodeReadResult(string moduleIdentifier, IEnumerable<DiagnosticTroubleCode> codes)
{
ModuleIdentifier = moduleIdentifier;
Codes = Array.AsReadOnly(codes.ToArray());
}
public string ModuleIdentifier { get; }
public IReadOnlyList<DiagnosticTroubleCode> Codes { get; }
}
public sealed record TroubleCodeClearResult(string ModuleIdentifier, int ClearedCount);
public enum SignalQuality
{
Good,
Uncertain,
Unknown
}
public sealed record DiagnosticSignal(
string SignalIdentifier,
string ModuleIdentifier,
JsonElement Value,
string Unit,
SignalQuality Quality,
long LogicalTimeTicks,
string Origin,
long? ModelStepIndex = null,
double? ModelTimeSeconds = null,
string? ModelConfigurationIdentifier = null,
string? ModelRunIdentifier = null);
public sealed class SignalSnapshot
{
public SignalSnapshot(
string moduleIdentifier,
IEnumerable<DiagnosticSignal> signals,
long? modelStepIndex = null,
double? modelTimeSeconds = null,
string? modelConfigurationIdentifier = null,
string? modelRunIdentifier = null)
{
ModuleIdentifier = moduleIdentifier;
Signals = Array.AsReadOnly(signals.ToArray());
ModelStepIndex = modelStepIndex;
ModelTimeSeconds = modelTimeSeconds;
ModelConfigurationIdentifier = modelConfigurationIdentifier;
ModelRunIdentifier = modelRunIdentifier;
}
public string ModuleIdentifier { get; }
public IReadOnlyList<DiagnosticSignal> Signals { get; }
public long? ModelStepIndex { get; }
public double? ModelTimeSeconds { get; }
public string? ModelConfigurationIdentifier { get; }
public string? ModelRunIdentifier { get; }
}
public sealed class DiagnosticTraceEntry
{
private readonly byte[] _requestPayload;
private readonly byte[]? _responsePayload;
public DiagnosticTraceEntry(
DiagnosticSessionIdentity session,
string moduleIdentifier,
string address,
string correlationIdentifier,
string service,
long startLogicalTicks,
long endLogicalTicks,
ReadOnlyMemory<byte> requestPayload,
ReadOnlyMemory<byte> responsePayload,
DiagnosticOutcome outcome,
string? decodedSummary,
string? error)
{
Session = session;
ModuleIdentifier = moduleIdentifier;
Address = address;
CorrelationIdentifier = correlationIdentifier;
Service = service;
StartLogicalTicks = startLogicalTicks;
EndLogicalTicks = endLogicalTicks;
_requestPayload = requestPayload.ToArray();
_responsePayload = responsePayload.IsEmpty ? null : responsePayload.ToArray();
Outcome = outcome;
DecodedSummary = decodedSummary;
Error = error;
}
public DiagnosticSessionIdentity Session { get; }
public string ModuleIdentifier { get; }
public string Address { get; }
public string CorrelationIdentifier { get; }
public string Service { get; }
public long StartLogicalTicks { get; }
public long EndLogicalTicks { get; }
public ReadOnlyMemory<byte> RequestPayload => _requestPayload.ToArray();
public ReadOnlyMemory<byte>? ResponsePayload =>
_responsePayload is null
? (ReadOnlyMemory<byte>?)null
: new ReadOnlyMemory<byte>(_responsePayload.ToArray());
public DiagnosticOutcome Outcome { get; }
public string? DecodedSummary { get; }
public string? Error { get; }
}
public sealed class DiagnosticTraceSnapshot
{
public DiagnosticTraceSnapshot(IEnumerable<DiagnosticTraceEntry> entries, long droppedRecordCount)
{
Entries = new ReadOnlyCollection<DiagnosticTraceEntry>(entries.ToArray());
DroppedRecordCount = droppedRecordCount;
}
public IReadOnlyList<DiagnosticTraceEntry> Entries { get; }
public long DroppedRecordCount { get; }
}
public sealed class DiagnosticOperationObservation
{
public DiagnosticOperationObservation(
DiagnosticTraceEntry trace,
SignalSnapshot? signalSnapshot)
{
Trace = trace ?? throw new ArgumentNullException(nameof(trace));
SignalSnapshot = signalSnapshot is null
? null
: new SignalSnapshot(
signalSnapshot.ModuleIdentifier,
signalSnapshot.Signals.Select(signal => signal with { Value = signal.Value.Clone() }),
signalSnapshot.ModelStepIndex,
signalSnapshot.ModelTimeSeconds,
signalSnapshot.ModelConfigurationIdentifier,
signalSnapshot.ModelRunIdentifier);
}
public DiagnosticTraceEntry Trace { get; }
public SignalSnapshot? SignalSnapshot { get; }
}
public interface IDiagnosticOperationObservationSource
{
int ProtocolVersion { get; }
string? ObservationDispatchError { get; }
IDisposable Subscribe(Action<DiagnosticOperationObservation> observer);
}
public sealed class DiagnosticTraceBuffer
{
private readonly object _gate = new();
private readonly Queue<DiagnosticTraceEntry> _entries = new();
public DiagnosticTraceBuffer(int capacity)
{
if (capacity <= 0)
{
throw new ArgumentOutOfRangeException(nameof(capacity));
}
Capacity = capacity;
}
public int Capacity { get; }
public long DroppedRecordCount { get; private set; }
public void Add(DiagnosticTraceEntry entry)
{
ArgumentNullException.ThrowIfNull(entry);
lock (_gate)
{
if (_entries.Count == Capacity)
{
_entries.Dequeue();
DroppedRecordCount++;
}
_entries.Enqueue(entry);
}
}
public DiagnosticTraceSnapshot Snapshot()
{
lock (_gate)
{
return new DiagnosticTraceSnapshot(_entries, DroppedRecordCount);
}
}
}
public interface IDiagnosticLogicalClock
{
long Ticks { get; }
void AdvanceBy(long ticks);
}
public sealed class DiagnosticLogicalClock : IDiagnosticLogicalClock
{
private long _ticks;
public long Ticks => Interlocked.Read(ref _ticks);
public void AdvanceBy(long ticks)
{
if (ticks < 0)
{
throw new ArgumentOutOfRangeException(nameof(ticks));
}
Interlocked.Add(ref _ticks, ticks);
}
}
public static class DiagnosticServices
{
public const string Probe = "probe";
public const string ReadIdentity = "read.identity";
public const string ReadTroubleCodes = "read.dtcs";
public const string ClearTroubleCodes = "clear.dtcs";
public const string ReadSignals = "read.signals";
}
public interface IDiagnosticProtocolClient
{
DiagnosticSessionIdentity Session { get; }
IReadOnlyList<DiagnosticEndpoint> ExpectedEndpoints { get; }
DiagnosticTraceSnapshot Trace { get; }
Task<DiscoveryResult> DiscoverAsync(CancellationToken cancellationToken = default);
Task<DiagnosticOperationResult<ModuleIdentityResult>> ReadIdentityAsync(DiagnosticEndpoint endpoint, CancellationToken cancellationToken = default);
Task<DiagnosticOperationResult<TroubleCodeReadResult>> ReadTroubleCodesAsync(DiagnosticEndpoint endpoint, CancellationToken cancellationToken = default);
Task<DiagnosticOperationResult<TroubleCodeClearResult>> ClearTroubleCodesAsync(DiagnosticEndpoint endpoint, CancellationToken cancellationToken = default);
Task<DiagnosticOperationResult<SignalSnapshot>> ReadSignalsAsync(DiagnosticEndpoint endpoint, CancellationToken cancellationToken = default);
}