AutoForge/src/AutoForge.Application/Features/Vehicles/Diagnostics/DiagnosticSessionService.cs

519 lines
20 KiB
C#

using System.Runtime.ExceptionServices;
using AutoForge.Application.ExecutionTargets;
using AutoForge.Application.Features.Vehicles.Profiles;
using AutoForge.Core.ExecutionTargets;
using AutoForge.Core.Simulation;
using AutoForge.Core.Vehicles;
using AutoForge.Diagnostics;
using Microsoft.Extensions.DependencyInjection;
namespace AutoForge.Application.Features.Vehicles.Diagnostics;
public enum DiagnosticSessionFailure
{
ProviderNotRegistered,
UnsupportedTargetKind,
DefinitionNotFound,
InvalidDefinition,
SessionConflict,
DynamicsCapabilityUnavailable
}
public sealed class DiagnosticSessionException(
DiagnosticSessionFailure failure,
string message,
Exception? innerException = null) : Exception(message, innerException)
{
public DiagnosticSessionFailure Failure { get; } = failure;
}
public sealed class DiagnosticClearVerificationResult
{
internal DiagnosticClearVerificationResult(
DiagnosticOperationResult<TroubleCodeClearResult> acknowledgement,
DiagnosticOperationResult<TroubleCodeReadResult>? readback,
bool isVerified,
string? verificationError)
{
Acknowledgement = acknowledgement;
Readback = readback;
IsVerified = isVerified;
VerificationError = verificationError;
}
public DiagnosticOperationResult<TroubleCodeClearResult> Acknowledgement { get; }
public DiagnosticOperationResult<TroubleCodeReadResult>? Readback { get; }
public bool IsVerified { get; }
public string? VerificationError { get; }
}
public interface IDiagnosticSessionService
{
IReadOnlyList<DiagnosticProviderDescriptor> Providers { get; }
Task<DiagnosticSession> OpenAsync(
string profileIdentifier,
int profileRevision,
string providerIdentifier,
ExecutionTargetKind targetKind,
CancellationToken cancellationToken = default);
Task<DiagnosticSession> OpenDynamicsAsync(
string profileIdentifier,
int profileRevision,
string providerIdentifier,
ExecutionTargetKind targetKind,
DynamicsConfiguration configuration,
CancellationToken cancellationToken = default);
Task<DiagnosticSession> ResetAsync(DiagnosticSession session, CancellationToken cancellationToken = default);
}
public sealed class DiagnosticSession(
VehicleProfile profile,
DiagnosticSessionIdentity identity,
IDiagnosticProtocolClient protocol,
IDiagnosticTransport transport,
CancellationTokenSource lifetime,
DynamicsConfiguration? dynamicsConfiguration = null,
IDynamicsControl? dynamicsControl = null) : IAsyncDisposable
{
private int _closed;
private readonly object _lifetimeGate = new();
private readonly List<IAsyncDisposable> _lifetimeResources = [];
private Task? _disposeTask;
public VehicleProfile Profile { get; } = profile;
public DiagnosticSessionIdentity Identity { get; } = identity;
public DynamicsConfiguration? DynamicsConfiguration { get; } = dynamicsConfiguration;
public IDynamicsControl? DynamicsControl { get; } = dynamicsControl;
public IReadOnlyList<DiagnosticEndpoint> ExpectedEndpoints => protocol.ExpectedEndpoints;
public DiagnosticTraceSnapshot Trace => protocol.Trace;
public bool IsClosed => Volatile.Read(ref _closed) != 0;
public int ObservationProtocolVersion =>
(protocol as IDiagnosticOperationObservationSource)?.ProtocolVersion
?? throw new InvalidOperationException("This diagnostic session does not expose validated operation observations.");
public string? ObservationDispatchError =>
(protocol as IDiagnosticOperationObservationSource)?.ObservationDispatchError;
public IDisposable SubscribeObservations(Action<DiagnosticOperationObservation> observer) =>
(protocol as IDiagnosticOperationObservationSource)?.Subscribe(observer)
?? throw new InvalidOperationException("This diagnostic session does not expose validated operation observations.");
public void RegisterLifetimeResource(IAsyncDisposable resource)
{
ArgumentNullException.ThrowIfNull(resource);
lock (_lifetimeGate)
{
ObjectDisposedException.ThrowIf(IsClosed, this);
_lifetimeResources.Add(resource);
}
}
internal void UnregisterLifetimeResource(IAsyncDisposable resource)
{
ArgumentNullException.ThrowIfNull(resource);
lock (_lifetimeGate)
{
_lifetimeResources.Remove(resource);
}
}
public Task<DiscoveryResult> DiscoverAsync(CancellationToken cancellationToken = default) =>
InvokeAsync(protocol.DiscoverAsync, cancellationToken);
public Task<DiagnosticOperationResult<ModuleIdentityResult>> ReadIdentityAsync(
DiagnosticEndpoint endpoint,
CancellationToken cancellationToken = default) =>
InvokeAsync(token => protocol.ReadIdentityAsync(endpoint, token), cancellationToken);
public Task<DiagnosticOperationResult<TroubleCodeReadResult>> ReadTroubleCodesAsync(
DiagnosticEndpoint endpoint,
CancellationToken cancellationToken = default) =>
InvokeAsync(token => protocol.ReadTroubleCodesAsync(endpoint, token), cancellationToken);
public Task<DiagnosticOperationResult<TroubleCodeClearResult>> ClearTroubleCodesAsync(
DiagnosticEndpoint endpoint,
CancellationToken cancellationToken = default) =>
InvokeAsync(token => protocol.ClearTroubleCodesAsync(endpoint, token), cancellationToken);
public Task<DiagnosticClearVerificationResult> ClearTroubleCodesAndVerifyAsync(
DiagnosticEndpoint endpoint,
CancellationToken cancellationToken = default) =>
InvokeAsync(async token =>
{
var acknowledgement = await protocol.ClearTroubleCodesAsync(endpoint, token).ConfigureAwait(false);
if (!acknowledgement.IsSuccess)
{
return new DiagnosticClearVerificationResult(
acknowledgement,
null,
false,
$"Virtual clear was not acknowledged ({acknowledgement.Outcome}): {acknowledgement.Error}");
}
var readback = await protocol.ReadTroubleCodesAsync(endpoint, token).ConfigureAwait(false);
if (!readback.IsSuccess)
{
return new DiagnosticClearVerificationResult(
acknowledgement,
readback,
false,
$"Virtual clear was acknowledged, but fresh readback could not verify the state ({readback.Outcome}): {readback.Error}");
}
if (readback.Value!.Codes.Count != 0)
{
return new DiagnosticClearVerificationResult(
acknowledgement,
readback,
false,
$"Virtual clear was acknowledged, but fresh readback still contains {readback.Value.Codes.Count} DTC(s).");
}
return new DiagnosticClearVerificationResult(acknowledgement, readback, true, null);
}, cancellationToken);
public Task<DiagnosticOperationResult<SignalSnapshot>> ReadSignalsAsync(
DiagnosticEndpoint endpoint,
CancellationToken cancellationToken = default) =>
InvokeAsync(token => protocol.ReadSignalsAsync(endpoint, token), cancellationToken);
public ValueTask DisposeAsync()
{
IAsyncDisposable[] resources;
TaskCompletionSource disposalCompletion;
Task disposalTask;
lock (_lifetimeGate)
{
if (_disposeTask is not null)
{
return new ValueTask(_disposeTask);
}
Interlocked.Exchange(ref _closed, 1);
resources = _lifetimeResources.ToArray();
_lifetimeResources.Clear();
disposalCompletion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
disposalTask = _disposeTask = disposalCompletion.Task;
}
_ = CompleteDisposalAsync(resources, disposalCompletion);
return new ValueTask(disposalTask);
}
private async Task CompleteDisposalAsync(
IReadOnlyList<IAsyncDisposable> resources,
TaskCompletionSource disposalCompletion)
{
try
{
await DisposeResourcesAsync(resources).ConfigureAwait(false);
disposalCompletion.TrySetResult();
}
catch (Exception exception)
{
disposalCompletion.TrySetException(exception);
}
}
private async Task DisposeResourcesAsync(IReadOnlyList<IAsyncDisposable> resources)
{
List<Exception>? failures = null;
try
{
lifetime.Cancel();
}
catch (Exception exception)
{
(failures ??= []).Add(exception);
}
foreach (var resource in resources)
{
try
{
await resource.DisposeAsync().ConfigureAwait(false);
}
catch (Exception exception)
{
(failures ??= []).Add(exception);
}
}
if (DynamicsControl is not null)
{
try
{
await DynamicsControl.DisposeAsync().ConfigureAwait(false);
}
catch (Exception exception)
{
(failures ??= []).Add(exception);
}
}
try
{
await transport.DisposeAsync().ConfigureAwait(false);
}
catch (Exception exception)
{
(failures ??= []).Add(exception);
}
finally
{
lifetime.Dispose();
}
if (failures is { Count: 1 })
{
ExceptionDispatchInfo.Capture(failures[0]).Throw();
}
if (failures is { Count: > 1 })
{
throw new AggregateException("One or more diagnostic session resources failed during cleanup.", failures);
}
}
private async Task<T> InvokeAsync<T>(Func<CancellationToken, Task<T>> operation, CancellationToken cancellationToken)
{
if (IsClosed)
{
return await operation(new CancellationToken(canceled: true)).ConfigureAwait(false);
}
if (!cancellationToken.CanBeCanceled)
{
return await operation(lifetime.Token).ConfigureAwait(false);
}
using var linked = CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token, cancellationToken);
return await operation(linked.Token).ConfigureAwait(false);
}
}
public sealed class DiagnosticSessionService : IDiagnosticSessionService
{
private readonly IVehicleProfileService _profiles;
private readonly IExecutionTargetResolver _targets;
private readonly IReadOnlyList<IDiagnosticTransportFactory> _factories;
private readonly Func<IDiagnosticLogicalClock> _logicalClockFactory;
private long _sessionSequence;
private long _runSequence;
public DiagnosticSessionService(
IVehicleProfileService profiles,
IExecutionTargetResolver targets,
IEnumerable<IDiagnosticTransportFactory> factories,
Func<IDiagnosticLogicalClock> logicalClockFactory)
{
_profiles = profiles;
_targets = targets;
_factories = Array.AsReadOnly(factories.ToArray());
_logicalClockFactory = logicalClockFactory ?? throw new ArgumentNullException(nameof(logicalClockFactory));
Providers = Array.AsReadOnly(_factories.Select(factory => factory.Descriptor).ToArray());
}
public IReadOnlyList<DiagnosticProviderDescriptor> Providers { get; }
public Task<DiagnosticSession> OpenAsync(
string profileIdentifier,
int profileRevision,
string providerIdentifier,
ExecutionTargetKind targetKind,
CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var profile = _profiles.Select(profileIdentifier, profileRevision);
var target = _targets.Resolve(new ExecutionTargetDescriptor(providerIdentifier, targetKind));
if (target.Kind != ExecutionTargetKind.Simulation)
{
throw new DiagnosticSessionException(
DiagnosticSessionFailure.UnsupportedTargetKind,
$"{target.Kind} operational sessions are unavailable; no provider substitution is performed.");
}
var factory = _factories.FirstOrDefault(item =>
StringComparer.OrdinalIgnoreCase.Equals(item.Descriptor.Target.ProviderIdentifier, target.ProviderIdentifier));
if (factory is null)
{
throw new DiagnosticSessionException(
DiagnosticSessionFailure.ProviderNotRegistered,
$"No diagnostic transport is registered for provider '{target.ProviderIdentifier}'.");
}
if (factory is IDynamicsDiagnosticTransportFactory)
{
throw new DiagnosticSessionException(
DiagnosticSessionFailure.DynamicsCapabilityUnavailable,
$"Provider '{target.ProviderIdentifier}' requires an explicit dynamics configuration; use the dynamics session workflow instead of opening a static session.");
}
var sequence = Interlocked.Increment(ref _sessionSequence);
var identity = new DiagnosticSessionIdentity(
$"diagnostic-session-{sequence:D6}",
profile.ProfileIdentifier,
profile.Revision,
profile.Vehicle.VehicleIdentifier,
target);
var logicalClock = _logicalClockFactory()
?? throw new InvalidOperationException("The logical clock factory returned null.");
IDiagnosticTransport transport;
try
{
transport = factory.OpenTransport(profile, identity);
}
catch (DiagnosticProviderException exception)
{
throw new DiagnosticSessionException(
exception.Failure switch
{
DiagnosticProviderFailure.ConfigurationNotFound => DiagnosticSessionFailure.DefinitionNotFound,
DiagnosticProviderFailure.SessionConflict => DiagnosticSessionFailure.SessionConflict,
_ => throw new ArgumentOutOfRangeException(nameof(exception), "The provider returned an undefined failure.")
},
exception.Message,
exception);
}
catch (ArgumentException exception)
{
throw new DiagnosticSessionException(
DiagnosticSessionFailure.InvalidDefinition,
exception.Message,
exception);
}
var lifetime = new CancellationTokenSource();
var protocol = new SyntheticDiagnosticProtocolClient(
profile,
identity,
transport,
logicalClock);
return Task.FromResult(new DiagnosticSession(profile, identity, protocol, transport, lifetime));
}
public Task<DiagnosticSession> OpenDynamicsAsync(
string profileIdentifier,
int profileRevision,
string providerIdentifier,
ExecutionTargetKind targetKind,
DynamicsConfiguration configuration,
CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
ArgumentNullException.ThrowIfNull(configuration);
var profile = _profiles.Select(profileIdentifier, profileRevision);
configuration.ValidateAgainst(profile);
var target = _targets.Resolve(new ExecutionTargetDescriptor(providerIdentifier, targetKind));
if (target.Kind != ExecutionTargetKind.Simulation)
{
throw new DiagnosticSessionException(
DiagnosticSessionFailure.UnsupportedTargetKind,
$"{target.Kind} operational sessions are unavailable; no provider substitution is performed.");
}
var factory = _factories.FirstOrDefault(item =>
StringComparer.OrdinalIgnoreCase.Equals(item.Descriptor.Target.ProviderIdentifier, target.ProviderIdentifier));
if (factory is not IDynamicsDiagnosticTransportFactory dynamicsFactory)
{
throw new DiagnosticSessionException(
DiagnosticSessionFailure.DynamicsCapabilityUnavailable,
$"Provider '{target.ProviderIdentifier}' does not offer dynamics control; no static or other-target fallback is performed.");
}
var sessionSequence = Interlocked.Increment(ref _sessionSequence);
var runSequence = Interlocked.Increment(ref _runSequence);
var identity = new DiagnosticSessionIdentity(
$"diagnostic-session-{sessionSequence:D6}",
profile.ProfileIdentifier,
profile.Revision,
profile.Vehicle.VehicleIdentifier,
target,
configuration.ConfigurationIdentifier,
$"dynamics-run-{runSequence:D6}");
var binding = dynamicsFactory.OpenDynamicsTransport(profile, identity, configuration);
var transport = binding.Transport ?? throw new InvalidOperationException("Dynamics provider returned a null transport.");
var control = binding.Control ?? throw new InvalidOperationException("Dynamics provider returned a null control capability.");
var protocol = new SyntheticDiagnosticProtocolClient(
profile,
identity,
transport,
_logicalClockFactory()
?? throw new InvalidOperationException("The logical clock factory returned null."),
protocolVersion: 2,
dynamicsConfiguration: configuration);
return Task.FromResult(new DiagnosticSession(
profile,
identity,
protocol,
transport,
new CancellationTokenSource(),
configuration,
control));
}
public async Task<DiagnosticSession> ResetAsync(
DiagnosticSession session,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(session);
var identity = session.Identity;
if (session.DynamicsConfiguration is { } configuration)
{
await session.DisposeAsync().ConfigureAwait(false);
return await OpenDynamicsAsync(
identity.ProfileIdentifier,
identity.ProfileRevision,
identity.Target.ProviderIdentifier,
identity.Target.Kind,
configuration,
cancellationToken).ConfigureAwait(false);
}
await session.DisposeAsync().ConfigureAwait(false);
return await OpenAsync(
identity.ProfileIdentifier,
identity.ProfileRevision,
identity.Target.ProviderIdentifier,
identity.Target.Kind,
cancellationToken).ConfigureAwait(false);
}
}
public static class DiagnosticSessionServiceCollectionExtensions
{
public static IServiceCollection AddAutoForgeDiagnostics(
this IServiceCollection services,
IEnumerable<IDiagnosticTransportFactory> factories,
Func<IDiagnosticLogicalClock>? logicalClockFactory = null)
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(factories);
if (services.Any(service => service.ServiceType == typeof(IDiagnosticSessionService)))
{
throw new InvalidOperationException("Diagnostic session services are already registered.");
}
var providerFactories = factories.ToArray();
if (providerFactories.Any(factory => factory is null))
{
throw new ArgumentException("Diagnostic provider factories cannot contain null values.", nameof(factories));
}
services.AddAutoForgeTargetSelection(providerFactories.Select(factory => factory.Descriptor.Target));
foreach (var factory in providerFactories)
{
services.AddSingleton(typeof(IDiagnosticTransportFactory), factory);
services.AddSingleton(factory.GetType(), factory);
}
services.AddSingleton<IDiagnosticSessionService>(provider =>
new DiagnosticSessionService(
provider.GetRequiredService<IVehicleProfileService>(),
provider.GetRequiredService<IExecutionTargetResolver>(),
provider.GetServices<IDiagnosticTransportFactory>(),
logicalClockFactory ?? (() => new DiagnosticLogicalClock())));
return services;
}
}