internal sealed class RdConnectionHostedService()

in src/dotnet/AspireWorker/RdConnection/RdConnectionHostedService.cs [25:82]


internal sealed class RdConnectionHostedService(
    IOptions<ConnectionOptions> connectionOptions,
    RdConnection rdConnection,
    ILogger<RdConnectionHostedService> logger)
    : IHostedService
{
    private readonly LifetimeDefinition _lifetimeDef = new();

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        var rdPort = connectionOptions.Value.RdPort;
        if (!rdPort.HasValue)
        {
            logger.LogWarning("Unable to find RD port environment variable. Skip connecting to Rider.");
            return;
        }

        var scheduler = SingleThreadScheduler.RunOnSeparateThread(
            _lifetimeDef.Lifetime,
            "Aspire Worker Protocol Connection"
        );
        var wire = new SocketWire.Client(
            _lifetimeDef.Lifetime,
            scheduler,
            rdPort.Value
        );
        var protocol = new Protocol(
            "Aspire Worker Protocol",
            new Serializers(),
            new Identities(IdKind.Client),
            scheduler,
            wire,
            _lifetimeDef.Lifetime
        );

        var tcs = new TaskCompletionSource<AspireWorkerModel>(TaskCreationOptions.RunContinuationsAsynchronously);
        scheduler.Queue(() =>
        {
            try
            {
                tcs.SetResult(new AspireWorkerModel(_lifetimeDef.Lifetime, protocol));
            }
            catch (Exception ex)
            {
                tcs.SetException(ex);
            }
        });

        var model = await tcs.Task;
        rdConnection.InitializeWithModelAndScheduler(model, scheduler);
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _lifetimeDef.Dispose();
        return Task.CompletedTask;
    }
}