Skip to content

Commit 4fca80e

Browse files
Fix CLI startup token race
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent bc89141 commit 4fca80e

3 files changed

Lines changed: 113 additions & 15 deletions

File tree

‎src/UniGetUI.Interface.BackgroundApi/BackgroundApi.cs‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -187,13 +187,23 @@ public async Task Start()
187187
});
188188
});
189189
_host = builder.Build();
190-
await _host.StartAsync();
191190
_transportOptions.Persist(
192191
SessionId,
193192
ApiTokenHolder.Token,
194193
SessionKind,
195194
Environment.ProcessId
196195
);
196+
try
197+
{
198+
await _host.StartAsync();
199+
}
200+
catch
201+
{
202+
BackgroundApiTransportOptions.DeletePersistedMetadata(SessionId);
203+
_host.Dispose();
204+
_host = null;
205+
throw;
206+
}
197207
Logger.Info(
198208
_transportOptions.TransportKind == BackgroundApiTransportKind.NamedPipe
199209
? $"Api running on named pipe {_transportOptions.NamedPipeName}"

‎src/UniGetUI.Interface.BackgroundApi/BackgroundApiClient.cs‎

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -28,16 +28,9 @@ public static BackgroundApiClient CreateForCli(IReadOnlyList<string>? args = nul
2828

2929
if (BackgroundApiTransportOptions.HasExplicitClientOverride(args))
3030
{
31-
var matchingRegistrations = BackgroundApiTransportOptions.LoadPersistedRegistrations()
32-
.Where(candidate => candidate.Matches(requestedOptions))
33-
.ToArray();
34-
var registration = SelectLiveRegistration(
35-
matchingRegistrations
36-
);
37-
3831
return new BackgroundApiClient(
3932
requestedOptions,
40-
registration?.Token ?? matchingRegistrations.FirstOrDefault()?.Token
33+
WaitForExplicitSessionToken(requestedOptions)
4134
);
4235
}
4336

@@ -55,6 +48,32 @@ public static BackgroundApiClient CreateForCli(IReadOnlyList<string>? args = nul
5548
: new BackgroundApiClient(requestedOptions);
5649
}
5750

51+
private static string? WaitForExplicitSessionToken(BackgroundApiTransportOptions requestedOptions)
52+
{
53+
Stopwatch timeout = Stopwatch.StartNew();
54+
55+
while (timeout.Elapsed < TimeSpan.FromSeconds(5))
56+
{
57+
var matchingRegistrations = BackgroundApiTransportOptions.LoadPersistedRegistrations()
58+
.Where(candidate => candidate.Matches(requestedOptions))
59+
.ToArray();
60+
var registration = SelectLiveRegistration(matchingRegistrations);
61+
string? token = registration?.Token
62+
?? matchingRegistrations.FirstOrDefault(candidate =>
63+
!string.IsNullOrWhiteSpace(candidate.Token)
64+
)?.Token;
65+
66+
if (!string.IsNullOrWhiteSpace(token))
67+
{
68+
return token;
69+
}
70+
71+
Thread.Sleep(100);
72+
}
73+
74+
return null;
75+
}
76+
5877
public async Task<BackgroundApiStatus> GetStatusAsync()
5978
{
6079
try
@@ -1479,7 +1498,10 @@ IEnumerable<BackgroundApiEndpointRegistration> candidates
14791498
return candidate;
14801499
}
14811500

1482-
BackgroundApiTransportOptions.DeletePersistedMetadata(candidate.SessionId);
1501+
if (candidate.ProcessId <= 0)
1502+
{
1503+
BackgroundApiTransportOptions.DeletePersistedMetadata(candidate.SessionId);
1504+
}
14831505
}
14841506

14851507
return null;

‎testing/automation/run-cli-e2e.ps1‎

Lines changed: 71 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,26 @@ $cliProject = Join-Path (Join-Path $srcRoot 'UniGetUI.Cli') 'UniGetUI.Cli.csproj
1414
$daemonDll = $env:UNIGETUI_DAEMON_DLL
1515
$cliDll = $env:UNIGETUI_CLI_DLL
1616

17+
function Find-BuiltDll {
18+
param(
19+
[Parameter(Mandatory = $true)]
20+
[string] $ProjectDirectory,
21+
[Parameter(Mandatory = $true)]
22+
[string] $AssemblyName,
23+
[Parameter(Mandatory = $true)]
24+
[string] $BuildConfiguration
25+
)
26+
27+
$outputRoot = Join-Path $ProjectDirectory (Join-Path 'bin' $BuildConfiguration)
28+
if (-not (Test-Path $outputRoot)) {
29+
return $null
30+
}
31+
32+
return Get-ChildItem -Path $outputRoot -Recurse -File -Filter "$AssemblyName.dll" |
33+
Sort-Object FullName |
34+
Select-Object -First 1 -ExpandProperty FullName
35+
}
36+
1737
if (-not (Test-Path $daemonProject)) {
1838
throw "Daemon project not found at $daemonProject"
1939
}
@@ -25,6 +45,14 @@ if (-not (Test-Path $cliProject)) {
2545
$daemonProject = (Resolve-Path $daemonProject).Path
2646
$cliProject = (Resolve-Path $cliProject).Path
2747

48+
if ([string]::IsNullOrWhiteSpace($daemonDll)) {
49+
$daemonDll = Find-BuiltDll -ProjectDirectory (Split-Path $daemonProject -Parent) -AssemblyName 'UniGetUI.Avalonia' -BuildConfiguration $configuration
50+
}
51+
52+
if ([string]::IsNullOrWhiteSpace($cliDll)) {
53+
$cliDll = Find-BuiltDll -ProjectDirectory (Split-Path $cliProject -Parent) -AssemblyName 'UniGetUI.Cli' -BuildConfiguration $configuration
54+
}
55+
2856
if (-not [string]::IsNullOrWhiteSpace($daemonDll)) {
2957
if (-not (Test-Path $daemonDll)) {
3058
throw "Daemon DLL override not found at $daemonDll"
@@ -45,13 +73,35 @@ $daemonRoot = Join-Path ([System.IO.Path]::GetTempPath()) ("unigetui-headless-"
4573
New-Item -ItemType Directory -Path $daemonRoot | Out-Null
4674
$downloadRoot = Join-Path $daemonRoot 'downloads'
4775
New-Item -ItemType Directory -Path $downloadRoot | Out-Null
76+
$localDataRoot = if ($runningOnWindows) {
77+
Join-Path $daemonRoot 'AppData\Local'
78+
}
79+
else {
80+
Join-Path $daemonRoot '.local\share'
81+
}
82+
New-Item -ItemType Directory -Path $localDataRoot -Force | Out-Null
83+
$roamingDataRoot = if ($runningOnWindows) {
84+
Join-Path $daemonRoot 'AppData\Roaming'
85+
}
86+
else {
87+
$null
88+
}
89+
if (-not [string]::IsNullOrWhiteSpace($roamingDataRoot)) {
90+
New-Item -ItemType Directory -Path $roamingDataRoot -Force | Out-Null
91+
}
4892

4993
$env:HOME = $daemonRoot
5094
$env:USERPROFILE = $daemonRoot
5195
$env:DOTNET_CLI_HOME = $daemonRoot
5296
$env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE = '1'
5397
$env:DOTNET_CLI_TELEMETRY_OPTOUT = '1'
5498
$env:UNIGETUI_GITHUB_TOKEN_NAMESPACE = "cli-e2e-$([Guid]::NewGuid().ToString('N'))"
99+
$env:XDG_DATA_HOME = $localDataRoot
100+
101+
if ($runningOnWindows) {
102+
$env:LOCALAPPDATA = $localDataRoot
103+
$env:APPDATA = $roamingDataRoot
104+
}
55105

56106
$transportArgs = @()
57107
$daemonArgs = if ([string]::IsNullOrWhiteSpace($daemonDll)) {
@@ -150,17 +200,28 @@ try {
150200

151201
$deadline = (Get-Date).AddSeconds($TimeoutSeconds)
152202
$lastResponse = $null
203+
$lastError = $null
153204

154205
do {
155-
$lastResponse = Invoke-CliJson -Arguments $Arguments
156-
if (& $Condition $lastResponse) {
157-
return $lastResponse
206+
try {
207+
$lastResponse = Invoke-CliJson -Arguments $Arguments
208+
$lastError = $null
209+
if (& $Condition $lastResponse) {
210+
return $lastResponse
211+
}
212+
}
213+
catch {
214+
$lastError = $_.Exception.Message
158215
}
159216

160217
Start-Sleep -Seconds $DelaySeconds
161218
} while ((Get-Date) -lt $deadline)
162219

163-
throw "$FailureMessage`nLast payload: $($lastResponse | ConvertTo-Json -Depth 8)"
220+
if ($null -ne $lastResponse) {
221+
throw "$FailureMessage`nLast payload: $($lastResponse | ConvertTo-Json -Depth 8)"
222+
}
223+
224+
throw "$FailureMessage`nLast error: $lastError"
164225
}
165226

166227
$deadline = (Get-Date).AddMinutes(2)
@@ -181,7 +242,12 @@ try {
181242
}
182243

183244
Write-Stage 'App lifecycle'
184-
$appState = Invoke-CliJson -Arguments @('get-app-state')
245+
$appState = Wait-ForCliCondition `
246+
-Arguments @('get-app-state') `
247+
-Condition { param($state) $state.app.headless -and -not $state.app.windowAvailable -and -not $state.app.canNavigate -and $state.app.canQuit } `
248+
-FailureMessage 'get-app-state did not stabilize into the expected headless app state' `
249+
-TimeoutSeconds 30 `
250+
-DelaySeconds 2
185251
if (-not $appState.app.headless) {
186252
throw "get-app-state did not report a headless session"
187253
}

0 commit comments

Comments
 (0)