mirror of
https://github.com/wwiinnddyy/LanMountainDesktop.git
synced 2026-06-23 01:44:26 +08:00
Compare commits
21 Commits
v0.8.5.2
...
3f927c41c8
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3f927c41c8 | ||
|
|
44725d7ff3 | ||
|
|
e623aef350 | ||
|
|
63d5165860 | ||
|
|
6d513096d3 | ||
|
|
f487a32149 | ||
|
|
a553f2f7aa | ||
|
|
f03b74ff32 | ||
|
|
bc1520a5d8 | ||
|
|
46341edbea | ||
|
|
f421f574e1 | ||
|
|
8ea8c684a9 | ||
|
|
b411d91b35 | ||
|
|
a2f0af9031 | ||
|
|
5861d73964 | ||
|
|
64975d5752 | ||
|
|
8c58b1c43e | ||
|
|
e82c5d41fd | ||
|
|
8447910fee | ||
|
|
81e0081721 | ||
|
|
fb21bcd8ec |
715
.github/workflows/release.yml
vendored
715
.github/workflows/release.yml
vendored
@@ -317,96 +317,19 @@ jobs:
|
||||
Write-Host "Installer size: $([Math]::Round($installerFile.Length / 1MB, 2)) MB"
|
||||
shell: pwsh
|
||||
|
||||
- name: Build Signed FileMap Update Package
|
||||
if: matrix.self_contained == true
|
||||
run: |
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
$version = "${{ needs.prepare.outputs.version }}"
|
||||
$arch = "${{ matrix.arch }}"
|
||||
$platform = "windows-$arch"
|
||||
$publishDir = "publish/windows-$arch"
|
||||
$appDir = "app-$version"
|
||||
$currentAppPath = Join-Path $publishDir $appDir
|
||||
$outputDir = Join-Path "delta-output" $platform
|
||||
$generateScript = "scripts/Generate-DeltaPackage.ps1"
|
||||
$signScript = "scripts/Sign-FileMap.ps1"
|
||||
|
||||
if (-not (Test-Path $currentAppPath)) {
|
||||
Write-Error "Expected app directory not found: $currentAppPath"
|
||||
exit 1
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Path $outputDir -Force | Out-Null
|
||||
& $generateScript `
|
||||
-PreviousVersion "0.0.0" `
|
||||
-CurrentVersion $version `
|
||||
-PreviousDir $currentAppPath `
|
||||
-CurrentDir $currentAppPath `
|
||||
-OutputDir $outputDir
|
||||
|
||||
$privateKeyPem = @'
|
||||
${{ secrets.PDC_SIGNING_KEY }}
|
||||
'@.Trim()
|
||||
if ([string]::IsNullOrWhiteSpace($privateKeyPem)) {
|
||||
$privateKeyPem = @'
|
||||
${{ secrets.UPDATE_PRIVATE_KEY_PEM }}
|
||||
'@.Trim()
|
||||
}
|
||||
if ([string]::IsNullOrWhiteSpace($privateKeyPem)) {
|
||||
Write-Error "Missing required secret: PDC_SIGNING_KEY or UPDATE_PRIVATE_KEY_PEM"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$privateKeyPem = $privateKeyPem -replace '\\n', "`n"
|
||||
$tempDir = Join-Path $env:RUNNER_TEMP "update-signing"
|
||||
New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
|
||||
|
||||
$privateKeyPath = Join-Path $tempDir "private-key.pem"
|
||||
$publicKeyPath = Join-Path $tempDir "public-key.pem"
|
||||
|
||||
Set-Content -Path $privateKeyPath -Value $privateKeyPem -NoNewline
|
||||
$rsa = [System.Security.Cryptography.RSA]::Create()
|
||||
$rsa.ImportFromPem($privateKeyPem)
|
||||
$derivedPublicKey = $rsa.ExportRSAPublicKeyPem()
|
||||
Set-Content -Path $publicKeyPath -Value $derivedPublicKey -NoNewline
|
||||
|
||||
$repoPublicKeyPath = "LanMountainDesktop.Launcher/Assets/public-key.pem"
|
||||
$repoPublicKeyPem = Get-Content -Path $repoPublicKeyPath -Raw
|
||||
$repoRsa = [System.Security.Cryptography.RSA]::Create()
|
||||
$repoRsa.ImportFromPem($repoPublicKeyPem)
|
||||
$repoSpki = [Convert]::ToBase64String($repoRsa.ExportSubjectPublicKeyInfo())
|
||||
$derivedSpki = [Convert]::ToBase64String($rsa.ExportSubjectPublicKeyInfo())
|
||||
if ($repoSpki -ne $derivedSpki) {
|
||||
Write-Error "Configured signing private key does not match $repoPublicKeyPath. Keep keypair consistent before publishing."
|
||||
exit 1
|
||||
}
|
||||
|
||||
& $signScript `
|
||||
-FilesJsonPath (Join-Path $outputDir "files.json") `
|
||||
-PrivateKeyPath $privateKeyPath `
|
||||
-OutputPath (Join-Path $outputDir "files.json.sig")
|
||||
|
||||
Copy-Item (Join-Path $outputDir "files.json") (Join-Path $outputDir "files-$platform.json") -Force
|
||||
Copy-Item (Join-Path $outputDir "files.json.sig") (Join-Path $outputDir "files-$platform.json.sig") -Force
|
||||
Copy-Item (Join-Path $outputDir "update.zip") (Join-Path $outputDir "update-$platform.zip") -Force
|
||||
shell: pwsh
|
||||
|
||||
- name: Upload Signed FileMap Update Package
|
||||
if: matrix.self_contained == true
|
||||
- name: Upload App Payload
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: release-update-windows-${{ matrix.arch }}
|
||||
name: app-payload-windows-${{ matrix.arch }}
|
||||
path: |
|
||||
delta-output/windows-${{ matrix.arch }}/files-windows-${{ matrix.arch }}.json
|
||||
delta-output/windows-${{ matrix.arch }}/files-windows-${{ matrix.arch }}.json.sig
|
||||
delta-output/windows-${{ matrix.arch }}/update-windows-${{ matrix.arch }}.zip
|
||||
publish/windows-${{ matrix.arch }}/**
|
||||
if-no-files-found: error
|
||||
retention-days: 90
|
||||
retention-days: 30
|
||||
|
||||
- name: Upload Installer
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: release-windows-${{ matrix.arch }}${{ matrix.suffix }}
|
||||
name: installer-windows-${{ matrix.arch }}
|
||||
path: build-installer/*.exe
|
||||
if-no-files-found: error
|
||||
retention-days: 30
|
||||
@@ -608,94 +531,19 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Build Signed FileMap Update Package
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
$version = "${{ needs.prepare.outputs.version }}"
|
||||
$platform = "linux-x64"
|
||||
$publishDir = "publish/linux-x64"
|
||||
$appDir = "app-$version"
|
||||
$currentAppPath = Join-Path $publishDir $appDir
|
||||
$outputDir = Join-Path "delta-output" $platform
|
||||
$generateScript = "scripts/Generate-DeltaPackage.ps1"
|
||||
$signScript = "scripts/Sign-FileMap.ps1"
|
||||
|
||||
if (-not (Test-Path $currentAppPath)) {
|
||||
Write-Error "Expected app directory not found: $currentAppPath"
|
||||
exit 1
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Path $outputDir -Force | Out-Null
|
||||
& $generateScript `
|
||||
-PreviousVersion "0.0.0" `
|
||||
-CurrentVersion $version `
|
||||
-PreviousDir $currentAppPath `
|
||||
-CurrentDir $currentAppPath `
|
||||
-OutputDir $outputDir
|
||||
|
||||
$privateKeyPem = @'
|
||||
${{ secrets.PDC_SIGNING_KEY }}
|
||||
'@.Trim()
|
||||
if ([string]::IsNullOrWhiteSpace($privateKeyPem)) {
|
||||
$privateKeyPem = @'
|
||||
${{ secrets.UPDATE_PRIVATE_KEY_PEM }}
|
||||
'@.Trim()
|
||||
}
|
||||
if ([string]::IsNullOrWhiteSpace($privateKeyPem)) {
|
||||
Write-Error "Missing required secret: PDC_SIGNING_KEY or UPDATE_PRIVATE_KEY_PEM"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$privateKeyPem = $privateKeyPem -replace '\\n', "`n"
|
||||
$tempDir = Join-Path $env:RUNNER_TEMP "update-signing"
|
||||
New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
|
||||
|
||||
$privateKeyPath = Join-Path $tempDir "private-key.pem"
|
||||
$publicKeyPath = Join-Path $tempDir "public-key.pem"
|
||||
|
||||
Set-Content -Path $privateKeyPath -Value $privateKeyPem -NoNewline
|
||||
$rsa = [System.Security.Cryptography.RSA]::Create()
|
||||
$rsa.ImportFromPem($privateKeyPem)
|
||||
$derivedPublicKey = $rsa.ExportRSAPublicKeyPem()
|
||||
Set-Content -Path $publicKeyPath -Value $derivedPublicKey -NoNewline
|
||||
|
||||
$repoPublicKeyPath = "LanMountainDesktop.Launcher/Assets/public-key.pem"
|
||||
$repoPublicKeyPem = Get-Content -Path $repoPublicKeyPath -Raw
|
||||
$repoRsa = [System.Security.Cryptography.RSA]::Create()
|
||||
$repoRsa.ImportFromPem($repoPublicKeyPem)
|
||||
$repoSpki = [Convert]::ToBase64String($repoRsa.ExportSubjectPublicKeyInfo())
|
||||
$derivedSpki = [Convert]::ToBase64String($rsa.ExportSubjectPublicKeyInfo())
|
||||
if ($repoSpki -ne $derivedSpki) {
|
||||
Write-Error "Configured signing private key does not match $repoPublicKeyPath. Keep keypair consistent before publishing."
|
||||
exit 1
|
||||
}
|
||||
|
||||
& $signScript `
|
||||
-FilesJsonPath (Join-Path $outputDir "files.json") `
|
||||
-PrivateKeyPath $privateKeyPath `
|
||||
-OutputPath (Join-Path $outputDir "files.json.sig")
|
||||
|
||||
Copy-Item (Join-Path $outputDir "files.json") (Join-Path $outputDir "files-$platform.json") -Force
|
||||
Copy-Item (Join-Path $outputDir "files.json.sig") (Join-Path $outputDir "files-$platform.json.sig") -Force
|
||||
Copy-Item (Join-Path $outputDir "update.zip") (Join-Path $outputDir "update-$platform.zip") -Force
|
||||
|
||||
- name: Upload Signed FileMap Update Package
|
||||
- name: Upload App Payload
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: release-update-linux-x64
|
||||
name: app-payload-linux-x64
|
||||
path: |
|
||||
delta-output/linux-x64/files-linux-x64.json
|
||||
delta-output/linux-x64/files-linux-x64.json.sig
|
||||
delta-output/linux-x64/update-linux-x64.zip
|
||||
publish/linux-x64/**
|
||||
if-no-files-found: error
|
||||
retention-days: 90
|
||||
retention-days: 30
|
||||
|
||||
- name: Upload
|
||||
- name: Upload Installer
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: release-linux
|
||||
name: installer-linux-x64
|
||||
path: "*.deb"
|
||||
if-no-files-found: error
|
||||
retention-days: 30
|
||||
@@ -859,23 +707,508 @@ jobs:
|
||||
- name: Upload
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: release-macos-${{ matrix.arch }}
|
||||
name: installer-macos-${{ matrix.arch }}
|
||||
path: "*.dmg"
|
||||
if-no-files-found: error
|
||||
retention-days: 30
|
||||
|
||||
github-release:
|
||||
publish-pdc:
|
||||
needs: [ prepare, build-windows, build-linux, build-macos ]
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
VERSION: ${{ needs.prepare.outputs.version }}
|
||||
PRIMARY_VERSION: ${{ needs.prepare.outputs.version }}
|
||||
PDCC_primaryVersion: ${{ needs.prepare.outputs.version }}
|
||||
PDCC_version: ${{ needs.prepare.outputs.version }}
|
||||
PDC_CLIENT_VERSION: ${{ vars.PDC_CLIENT_VERSION || '1.0.1.0' }}
|
||||
S3_ENDPOINT: ${{ vars.S3_ENDPOINT }}
|
||||
S3_BUCKET: ${{ vars.S3_BUCKET }}
|
||||
S3_REGION: ${{ vars.S3_REGION }}
|
||||
PDC_ENDPOINT: ${{ vars.PDC_ENDPOINT }}
|
||||
PDC_TOKEN: ${{ secrets.PDC_TOKEN }}
|
||||
PDC_SIGNING_KEY: ${{ secrets.PDC_SIGNING_KEY }}
|
||||
PDC_SIGNING_KEY_PS: ${{ secrets.PDC_SIGNING_KEY_PS }}
|
||||
UPDATE_PRIVATE_KEY_PEM: ${{ secrets.UPDATE_PRIVATE_KEY_PEM }}
|
||||
S3_ACCESS_KEY: ${{ secrets.S3_ACCESS_KEY }}
|
||||
S3_SECRET_KEY: ${{ secrets.S3_SECRET_KEY }}
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.S3_ACCESS_KEY }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.S3_SECRET_KEY }}
|
||||
AWS_DEFAULT_REGION: ${{ vars.S3_REGION }}
|
||||
AWS_REGION: ${{ vars.S3_REGION }}
|
||||
AWS_EC2_METADATA_DISABLED: "true"
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
submodules: recursive
|
||||
ref: ${{ needs.prepare.outputs.checkout_ref }}
|
||||
|
||||
- name: Download payload artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: payload-artifacts
|
||||
pattern: app-payload-*
|
||||
|
||||
- name: Download installer artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: installer-artifacts
|
||||
pattern: installer-*
|
||||
|
||||
- name: Prepare PDC environment
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
function Resolve-PgpPrivateKey([string]$value) {
|
||||
if ([string]::IsNullOrWhiteSpace($value)) {
|
||||
return $null
|
||||
}
|
||||
|
||||
$trimmed = $value.Trim()
|
||||
if ($trimmed -match '-----BEGIN PGP PRIVATE KEY BLOCK-----') {
|
||||
return $trimmed
|
||||
}
|
||||
|
||||
try {
|
||||
$decoded = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($trimmed)).Trim()
|
||||
if ($decoded -match '-----BEGIN PGP PRIVATE KEY BLOCK-----') {
|
||||
return $decoded
|
||||
}
|
||||
}
|
||||
catch {
|
||||
}
|
||||
|
||||
return $trimmed
|
||||
}
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($env:S3_ENDPOINT) -or
|
||||
[string]::IsNullOrWhiteSpace($env:S3_BUCKET)) {
|
||||
throw "Missing required S3 variables."
|
||||
}
|
||||
|
||||
$resolvedSigningKey = Resolve-PgpPrivateKey $env:PDC_SIGNING_KEY
|
||||
if ([string]::IsNullOrWhiteSpace($resolvedSigningKey)) {
|
||||
$resolvedSigningKey = Resolve-PgpPrivateKey $env:UPDATE_PRIVATE_KEY_PEM
|
||||
}
|
||||
if ([string]::IsNullOrWhiteSpace($resolvedSigningKey)) {
|
||||
throw "Missing PDC_SIGNING_KEY (PGP private key)."
|
||||
}
|
||||
if ($resolvedSigningKey -notmatch '-----BEGIN PGP PRIVATE KEY BLOCK-----') {
|
||||
throw "PDC signing key format is invalid. Please provide armored OpenPGP private key in PDC_SIGNING_KEY."
|
||||
}
|
||||
Add-Content -Path $env:GITHUB_ENV -Value "PDC_SIGNING_KEY<<EOF`n$resolvedSigningKey`nEOF"
|
||||
|
||||
$workRoot = Join-Path $PWD "pdc-work"
|
||||
if (Test-Path $workRoot) {
|
||||
Remove-Item -LiteralPath $workRoot -Recurse -Force
|
||||
}
|
||||
New-Item -ItemType Directory -Path $workRoot -Force | Out-Null
|
||||
|
||||
$template = Get-Content -Path "phainon.yml" -Raw
|
||||
$resolved = $template `
|
||||
-replace '__FILE_REPO_ROOT__', "$($env:S3_ENDPOINT.TrimEnd('/'))/$($env:S3_BUCKET)/lanmountain/update/repo/" `
|
||||
-replace '__ARCHIVE_ROOT__', "$($env:S3_ENDPOINT.TrimEnd('/'))/$($env:S3_BUCKET)/lanmountain/update/archive"
|
||||
|
||||
Set-Content -Path (Join-Path $workRoot "phainon.resolved.yml") -Value $resolved -NoNewline
|
||||
|
||||
python3 -m pip install --user --upgrade awscli
|
||||
Add-Content -Path $env:GITHUB_PATH -Value "$HOME/.local/bin"
|
||||
|
||||
- name: Verify S3 credentials and endpoint
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
function Invoke-AwsChecked([string[]]$Arguments) {
|
||||
& aws @Arguments
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "aws command failed: aws $($Arguments -join ' ')"
|
||||
}
|
||||
}
|
||||
|
||||
$probeDir = Join-Path $PWD "pdc-work"
|
||||
New-Item -ItemType Directory -Path $probeDir -Force | Out-Null
|
||||
|
||||
$probeFile = Join-Path $probeDir "s3-probe.txt"
|
||||
Set-Content -Path $probeFile -Value "lanmountain pdc probe $(Get-Date -Format o)" -NoNewline
|
||||
|
||||
$probeKey = "lanmountain/update/probe/$($env:GITHUB_RUN_ID)-$($env:GITHUB_RUN_ATTEMPT).txt"
|
||||
Invoke-AwsChecked @("--endpoint-url", "$env:S3_ENDPOINT", "--region", "$env:S3_REGION", "s3", "cp", $probeFile, "s3://$env:S3_BUCKET/$probeKey", "--only-show-errors")
|
||||
Invoke-AwsChecked @("--endpoint-url", "$env:S3_ENDPOINT", "--region", "$env:S3_REGION", "s3", "rm", "s3://$env:S3_BUCKET/$probeKey", "--only-show-errors")
|
||||
Write-Host "S3 probe succeeded."
|
||||
|
||||
- name: Bootstrap PDC Endpoint and Token
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
$endpoint = $env:PDC_ENDPOINT
|
||||
if ([string]::IsNullOrWhiteSpace($endpoint)) {
|
||||
$endpoint = "http://127.0.0.1:18765"
|
||||
}
|
||||
|
||||
$token = $env:PDC_TOKEN
|
||||
if ([string]::IsNullOrWhiteSpace($token)) {
|
||||
$token = "lmd-pdc-local-token"
|
||||
}
|
||||
|
||||
Add-Content -Path $env:GITHUB_ENV -Value "PDC_ENDPOINT=$endpoint"
|
||||
Add-Content -Path $env:GITHUB_ENV -Value "PDC_TOKEN=$token"
|
||||
Write-Host "Using PDC endpoint: $endpoint"
|
||||
|
||||
- name: Start Local PDC Mock (Fallback)
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($env:PDC_ENDPOINT)) {
|
||||
throw "PDC_ENDPOINT is empty after bootstrap."
|
||||
}
|
||||
|
||||
$uri = [Uri]$env:PDC_ENDPOINT
|
||||
$isLocalHost = $uri.Host -eq "127.0.0.1" -or $uri.Host -eq "localhost"
|
||||
if (-not $isLocalHost) {
|
||||
Write-Host "Using external PDC endpoint: $($env:PDC_ENDPOINT)"
|
||||
exit 0
|
||||
}
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($env:PDC_TOKEN)) {
|
||||
throw "PDC_TOKEN is empty after bootstrap."
|
||||
}
|
||||
|
||||
$port = if ($uri.Port -gt 0) { $uri.Port } else { 18765 }
|
||||
$dataDir = Join-Path $PWD "pdc-output/mock-pdc"
|
||||
$workDir = Join-Path $PWD "pdc-work"
|
||||
$logPath = Join-Path $workDir "pdc-mock.out.log"
|
||||
$errLogPath = Join-Path $workDir "pdc-mock.err.log"
|
||||
|
||||
New-Item -ItemType Directory -Path $workDir -Force | Out-Null
|
||||
New-Item -ItemType Directory -Path $dataDir -Force | Out-Null
|
||||
if (Test-Path $logPath) {
|
||||
Remove-Item -LiteralPath $logPath -Force
|
||||
}
|
||||
if (Test-Path $errLogPath) {
|
||||
Remove-Item -LiteralPath $errLogPath -Force
|
||||
}
|
||||
|
||||
$args = @(
|
||||
"scripts/pdc-mock-server.py",
|
||||
"--host", "127.0.0.1",
|
||||
"--port", $port.ToString(),
|
||||
"--token", $env:PDC_TOKEN,
|
||||
"--data-dir", $dataDir
|
||||
)
|
||||
$process = Start-Process -FilePath "python3" -ArgumentList $args -PassThru -RedirectStandardOutput $logPath -RedirectStandardError $errLogPath
|
||||
if (-not $process) {
|
||||
throw "Failed to launch PDC mock server."
|
||||
}
|
||||
|
||||
$healthUrl = "http://127.0.0.1:$port/healthz"
|
||||
$ready = $false
|
||||
for ($i = 0; $i -lt 20; $i++) {
|
||||
Start-Sleep -Seconds 1
|
||||
try {
|
||||
$response = Invoke-WebRequest -Uri $healthUrl -Method Get -TimeoutSec 2
|
||||
if ($response.StatusCode -eq 200) {
|
||||
$ready = $true
|
||||
break
|
||||
}
|
||||
}
|
||||
catch {
|
||||
}
|
||||
}
|
||||
|
||||
if (-not $ready) {
|
||||
if (Test-Path $logPath) {
|
||||
Write-Host "===== pdc-mock stdout ====="
|
||||
Get-Content -LiteralPath $logPath -ErrorAction SilentlyContinue | Write-Host
|
||||
}
|
||||
if (Test-Path $errLogPath) {
|
||||
Write-Host "===== pdc-mock stderr ====="
|
||||
Get-Content -LiteralPath $errLogPath -ErrorAction SilentlyContinue | Write-Host
|
||||
}
|
||||
throw "PDC mock server did not become ready in time. See $logPath and $errLogPath."
|
||||
}
|
||||
|
||||
Write-Host "Local PDC mock is running at http://127.0.0.1:$port"
|
||||
|
||||
- name: Install PDCC
|
||||
shell: pwsh
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
./scripts/Install-Pdcc.ps1 -Repository "ClassIsland/PhainonDistributionCenter" -Version "$env:PDC_CLIENT_VERSION" -OutputDir "./pdcc"
|
||||
|
||||
- name: Publish with PDCC
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = "Stop"
|
||||
# Map CI vars to the naming convention expected by PDCC tooling.
|
||||
$env:S3_Endpoint = $env:S3_ENDPOINT
|
||||
$env:S3_Bucket = $env:S3_BUCKET
|
||||
$env:S3_Region = $env:S3_REGION
|
||||
$env:PDC_Endpoint = $env:PDC_ENDPOINT
|
||||
$env:PDC_Token = $env:PDC_TOKEN
|
||||
$env:S3_AccessKey = $env:S3_ACCESS_KEY
|
||||
$env:S3_SecretKey = $env:S3_SECRET_KEY
|
||||
$signingKeyPs = $env:PDC_SIGNING_KEY_PS
|
||||
if ([string]::IsNullOrWhiteSpace($signingKeyPs)) {
|
||||
# Keep a non-empty value so PDCC required-env check passes on Linux runners.
|
||||
$signingKeyPs = " "
|
||||
}
|
||||
$env:PDC_SigningKeyPs = $signingKeyPs
|
||||
# Map config variables with exact names required by phainon placeholders.
|
||||
$env:PDCC_version = $env:VERSION
|
||||
$env:PDCC_primaryVersion = $env:PRIMARY_VERSION
|
||||
$signingKey = $env:PDC_SIGNING_KEY
|
||||
if ([string]::IsNullOrWhiteSpace($signingKey)) {
|
||||
$signingKey = $env:UPDATE_PRIVATE_KEY_PEM
|
||||
}
|
||||
if ([string]::IsNullOrWhiteSpace($signingKey)) {
|
||||
throw "Missing PDC signing key: PDC_SIGNING_KEY or UPDATE_PRIVATE_KEY_PEM."
|
||||
}
|
||||
if ($signingKey -notmatch '-----BEGIN PGP PRIVATE KEY BLOCK-----') {
|
||||
throw "PDC signing key is not an armored OpenPGP private key."
|
||||
}
|
||||
$env:PDC_SigningKey = $signingKey
|
||||
|
||||
$workDir = Join-Path $PWD "pdc-work"
|
||||
$stageRoot = Join-Path $PWD "pdc-stage"
|
||||
$payloadRoot = Join-Path $PWD "payload-artifacts"
|
||||
$installerRoot = Join-Path $PWD "installer-artifacts"
|
||||
$outRoot = Join-Path $PWD "pdc-output"
|
||||
$publishRoot = Join-Path $outRoot "published"
|
||||
$client = Join-Path $PWD "pdcc/PhainonDistributionCenter.Client"
|
||||
$config = Join-Path $workDir "phainon.resolved.yml"
|
||||
|
||||
New-Item -ItemType Directory -Path $workDir -Force | Out-Null
|
||||
if (-not (Test-Path -LiteralPath $config)) {
|
||||
throw "Resolved PDCC config was not found: $config"
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath $client)) {
|
||||
throw "PDCC client was not found: $client"
|
||||
}
|
||||
|
||||
if (Test-Path $stageRoot) {
|
||||
Remove-Item -LiteralPath $stageRoot -Recurse -Force
|
||||
}
|
||||
if (Test-Path $outRoot) {
|
||||
Remove-Item -LiteralPath $outRoot -Recurse -Force
|
||||
}
|
||||
New-Item -ItemType Directory -Path $stageRoot -Force | Out-Null
|
||||
New-Item -ItemType Directory -Path $outRoot -Force | Out-Null
|
||||
New-Item -ItemType Directory -Path $publishRoot -Force | Out-Null
|
||||
|
||||
$payloadArtifacts = Get-ChildItem -LiteralPath $payloadRoot -Directory
|
||||
if (-not $payloadArtifacts) {
|
||||
throw "No payload artifacts were downloaded."
|
||||
}
|
||||
|
||||
$installerArtifacts = Get-ChildItem -LiteralPath $installerRoot -Directory
|
||||
if (-not $installerArtifacts) {
|
||||
throw "No installer artifacts were downloaded."
|
||||
}
|
||||
|
||||
foreach ($installerArtifact in $installerArtifacts) {
|
||||
$stagedInstallerDir = Join-Path $stageRoot "installers/$($installerArtifact.Name)"
|
||||
./scripts/Prepare-PdccOut.ps1 -SourceDir $installerArtifact.FullName -OutputDir $stagedInstallerDir
|
||||
}
|
||||
|
||||
foreach ($payloadArtifact in $payloadArtifacts) {
|
||||
$platformKey = $payloadArtifact.Name -replace '^app-payload-', ''
|
||||
$stagedPayloadDir = Join-Path $stageRoot "payloads/$platformKey"
|
||||
./scripts/Prepare-PdccOut.ps1 -SourceDir $payloadArtifact.FullName -OutputDir $stagedPayloadDir
|
||||
|
||||
$parts = $platformKey.Split('-', 2)
|
||||
if ($parts.Count -lt 2) {
|
||||
throw "Invalid platform key format: $platformKey"
|
||||
}
|
||||
$os = $parts[0]
|
||||
$arch = $parts[1]
|
||||
$packageName = "LanMountainDesktop_app_${os}_${arch}_release_folder.zip"
|
||||
$packagePath = Join-Path $publishRoot $packageName
|
||||
|
||||
Write-Host "Preparing PDCC subchannel package for $platformKey..."
|
||||
& $client $config GenerateFileMap $stagedPayloadDir
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "PDCC GenerateFileMap failed for $platformKey."
|
||||
}
|
||||
|
||||
if (Test-Path $packagePath) {
|
||||
Remove-Item -LiteralPath $packagePath -Force
|
||||
}
|
||||
Compress-Archive -Path (Join-Path $stagedPayloadDir '*') -DestinationPath $packagePath -Force
|
||||
$packageSizeMb = [Math]::Round((Get-Item -LiteralPath $packagePath).Length / 1MB, 2)
|
||||
Write-Host "Prepared package: $packageName ($packageSizeMb MB)"
|
||||
}
|
||||
|
||||
$subchannelPackages = Get-ChildItem -LiteralPath $publishRoot -File -Filter "LanMountainDesktop_app_*_release_folder.zip"
|
||||
if (-not $subchannelPackages) {
|
||||
throw "No PDCC subchannel packages were prepared."
|
||||
}
|
||||
|
||||
Write-Host "Publishing $($subchannelPackages.Count) subchannels in a single PDCC Publish run..."
|
||||
$subchannelPackages | Sort-Object Name | ForEach-Object { Write-Host " - $($_.Name)" }
|
||||
|
||||
$publishStdOut = Join-Path $workDir "pdcc-publish.stdout.log"
|
||||
$publishStdErr = Join-Path $workDir "pdcc-publish.stderr.log"
|
||||
if (Test-Path $publishStdOut) {
|
||||
Remove-Item -LiteralPath $publishStdOut -Force
|
||||
}
|
||||
if (Test-Path $publishStdErr) {
|
||||
Remove-Item -LiteralPath $publishStdErr -Force
|
||||
}
|
||||
|
||||
function Write-NewLogLines([string]$path, [ref]$lineCount, [string]$prefix) {
|
||||
if (-not (Test-Path -LiteralPath $path)) {
|
||||
return
|
||||
}
|
||||
|
||||
$lines = Get-Content -LiteralPath $path -ErrorAction SilentlyContinue
|
||||
if ($null -eq $lines) {
|
||||
return
|
||||
}
|
||||
|
||||
if ($lines -is [string]) {
|
||||
$lines = @($lines)
|
||||
}
|
||||
|
||||
if ($lines.Count -le $lineCount.Value) {
|
||||
return
|
||||
}
|
||||
|
||||
for ($i = $lineCount.Value; $i -lt $lines.Count; $i++) {
|
||||
Write-Host "[$prefix] $($lines[$i])"
|
||||
}
|
||||
|
||||
$lineCount.Value = $lines.Count
|
||||
}
|
||||
|
||||
$publishArgs = @(
|
||||
$config,
|
||||
"Publish",
|
||||
$env:PRIMARY_VERSION,
|
||||
$env:VERSION,
|
||||
$publishRoot
|
||||
)
|
||||
$publishTimeoutMinutes = 20
|
||||
if (-not [string]::IsNullOrWhiteSpace($env:PDC_PUBLISH_TIMEOUT_MINUTES)) {
|
||||
$parsedTimeout = 0
|
||||
if ([int]::TryParse($env:PDC_PUBLISH_TIMEOUT_MINUTES, [ref]$parsedTimeout) -and $parsedTimeout -gt 0) {
|
||||
$publishTimeoutMinutes = $parsedTimeout
|
||||
}
|
||||
}
|
||||
|
||||
$publishProcess = Start-Process `
|
||||
-FilePath $client `
|
||||
-ArgumentList $publishArgs `
|
||||
-WorkingDirectory $publishRoot `
|
||||
-RedirectStandardOutput $publishStdOut `
|
||||
-RedirectStandardError $publishStdErr `
|
||||
-PassThru
|
||||
if (-not $publishProcess) {
|
||||
throw "Failed to start PDCC Publish process."
|
||||
}
|
||||
|
||||
Write-Host "PDCC Publish process started. PID=$($publishProcess.Id), timeout=${publishTimeoutMinutes}m"
|
||||
$publishStart = Get-Date
|
||||
$stdoutLineCount = 0
|
||||
$stderrLineCount = 0
|
||||
|
||||
while (-not $publishProcess.HasExited) {
|
||||
Start-Sleep -Seconds 15
|
||||
$publishProcess.Refresh()
|
||||
Write-NewLogLines -path $publishStdOut -lineCount ([ref]$stdoutLineCount) -prefix "pdcc"
|
||||
Write-NewLogLines -path $publishStdErr -lineCount ([ref]$stderrLineCount) -prefix "pdcc-err"
|
||||
|
||||
$elapsed = (Get-Date) - $publishStart
|
||||
Write-Host ("PDCC Publish heartbeat: elapsed={0:mm\\:ss}, pid={1}" -f $elapsed, $publishProcess.Id)
|
||||
|
||||
if ($elapsed.TotalMinutes -ge $publishTimeoutMinutes) {
|
||||
Stop-Process -Id $publishProcess.Id -Force -ErrorAction SilentlyContinue
|
||||
throw "PDCC Publish exceeded timeout of ${publishTimeoutMinutes} minutes."
|
||||
}
|
||||
}
|
||||
|
||||
Write-NewLogLines -path $publishStdOut -lineCount ([ref]$stdoutLineCount) -prefix "pdcc"
|
||||
Write-NewLogLines -path $publishStdErr -lineCount ([ref]$stderrLineCount) -prefix "pdcc-err"
|
||||
|
||||
if ($publishProcess.ExitCode -ne 0) {
|
||||
throw "PDCC Publish failed with exit code $($publishProcess.ExitCode)."
|
||||
}
|
||||
|
||||
if (Test-Path (Join-Path $stageRoot "installers")) {
|
||||
& aws --endpoint-url "$env:S3_ENDPOINT" --region "$env:S3_REGION" s3 sync (Join-Path $stageRoot "installers") "s3://$env:S3_BUCKET/lanmountain/update/installers/" --only-show-errors
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "aws s3 sync failed for installer mirror upload."
|
||||
}
|
||||
}
|
||||
|
||||
- name: Upload PDC Assets
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: pdc-assets
|
||||
path: |
|
||||
pdc-output/published/**
|
||||
if-no-files-found: error
|
||||
retention-days: 90
|
||||
|
||||
- name: Dump PDC Diagnostics
|
||||
if: failure()
|
||||
shell: pwsh
|
||||
run: |
|
||||
if (Test-Path "pdc-work/pdc-mock.out.log") {
|
||||
Write-Host "===== pdc-mock stdout ====="
|
||||
Get-Content "pdc-work/pdc-mock.out.log" -ErrorAction SilentlyContinue | Write-Host
|
||||
}
|
||||
|
||||
if (Test-Path "pdc-work/pdc-mock.err.log") {
|
||||
Write-Host "===== pdc-mock stderr ====="
|
||||
Get-Content "pdc-work/pdc-mock.err.log" -ErrorAction SilentlyContinue | Write-Host
|
||||
}
|
||||
|
||||
if (Test-Path "pdc-output/mock-pdc") {
|
||||
Write-Host "===== pdc-mock captured payloads ====="
|
||||
Get-ChildItem "pdc-output/mock-pdc" -Recurse -File | ForEach-Object {
|
||||
Write-Host "--- $($_.FullName) ---"
|
||||
Get-Content $_.FullName -ErrorAction SilentlyContinue | Write-Host
|
||||
}
|
||||
}
|
||||
|
||||
- name: Upload PDC Diagnostics Artifact
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: pdc-diagnostics
|
||||
path: |
|
||||
pdc-work/pdc-mock*.log
|
||||
pdc-work/pdcc-publish*.log
|
||||
pdc-output/mock-pdc/**
|
||||
if-no-files-found: ignore
|
||||
retention-days: 30
|
||||
|
||||
github-release:
|
||||
needs: [ prepare, build-windows, build-linux, build-macos, publish-pdc ]
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
steps:
|
||||
- name: Download artifacts
|
||||
- name: Download installer artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: artifacts
|
||||
pattern: release-*
|
||||
path: artifacts/installers
|
||||
pattern: installer-*
|
||||
|
||||
- name: Download PDC artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: artifacts/pdc
|
||||
pattern: pdc-assets
|
||||
|
||||
- name: List artifacts structure
|
||||
run: |
|
||||
@@ -892,10 +1225,8 @@ jobs:
|
||||
run: |
|
||||
echo "Organizing artifacts..."
|
||||
mkdir -p release-files
|
||||
# Copy installers and packages
|
||||
find artifacts -type f \( -name "*.exe" -o -name "*.deb" -o -name "*.dmg" \) -exec cp -v {} release-files/ \;
|
||||
# Copy signed file-map incremental update assets
|
||||
find artifacts -type f \( -name "files-*.json" -o -name "files-*.json.sig" -o -name "update-*.zip" \) -exec cp -v {} release-files/ \;
|
||||
find artifacts/installers -type f \( -name "*.exe" -o -name "*.deb" -o -name "*.dmg" \) -exec cp -v {} release-files/ \;
|
||||
find artifacts/pdc -type f \( -name "files-*.json" -o -name "files-*.json.sig" -o -name "update-*.zip" \) -exec cp -v {} release-files/ \;
|
||||
echo ""
|
||||
echo "Files ready for release:"
|
||||
ls -lh release-files/ || echo "No files found in release-files"
|
||||
@@ -908,44 +1239,6 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Upload Incremental Assets to S3 (optional)
|
||||
if: ${{ vars.S3_ENDPOINT != '' && vars.S3_BUCKET != '' }}
|
||||
env:
|
||||
S3_ENDPOINT: ${{ vars.S3_ENDPOINT }}
|
||||
S3_BUCKET: ${{ vars.S3_BUCKET }}
|
||||
S3_REGION: ${{ vars.S3_REGION != '' && vars.S3_REGION || 'cn-nb1' }}
|
||||
S3_ACCESS_KEY: ${{ secrets.S3_ACCESS_KEY }}
|
||||
S3_SECRET_KEY: ${{ secrets.S3_SECRET_KEY }}
|
||||
S3_OBJECT_PREFIX: lanmountain/distribution-v1
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
if [ -z "${S3_ACCESS_KEY:-}" ] || [ -z "${S3_SECRET_KEY:-}" ]; then
|
||||
echo "S3 credentials are not configured. Skipping optional S3 upload step."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
python3 -m pip install --upgrade awscli
|
||||
|
||||
mkdir -p release-update-assets
|
||||
find release-files -type f \( -name "files-*.json" -o -name "files-*.json.sig" -o -name "update-*.zip" \) -exec cp -v {} release-update-assets/ \;
|
||||
|
||||
asset_count=$(find release-update-assets -type f | wc -l)
|
||||
if [ "$asset_count" -eq 0 ]; then
|
||||
echo "Error: no incremental update assets found for S3 upload."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
export AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY"
|
||||
export AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY"
|
||||
export AWS_DEFAULT_REGION="$S3_REGION"
|
||||
|
||||
version_prefix="${S3_OBJECT_PREFIX}/${{ needs.prepare.outputs.version }}/"
|
||||
latest_prefix="${S3_OBJECT_PREFIX}/latest/"
|
||||
|
||||
aws --endpoint-url "$S3_ENDPOINT" s3 sync release-update-assets "s3://${S3_BUCKET}/${version_prefix}" --only-show-errors
|
||||
aws --endpoint-url "$S3_ENDPOINT" s3 sync release-update-assets "s3://${S3_BUCKET}/${latest_prefix}" --delete --only-show-errors
|
||||
|
||||
- name: Create Release
|
||||
uses: ncipollo/release-action@v1
|
||||
with:
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
# Checklist
|
||||
|
||||
- [x] `release.yml` produces signed FileMap incremental assets for Windows x64/x86 and Linux x64.
|
||||
- [x] `release.yml` no longer depends on `vpk`/VeloPack packaging.
|
||||
- [x] Launcher update engine applies only signed FileMap payload path.
|
||||
- [x] Host update workflow no longer expects `releases.win.json`/`*.nupkg`.
|
||||
- [x] Update source setting includes `pdc` and preserves GitHub fallback behavior.
|
||||
- [ ] `release.yml` includes PDCC publish flow and does not invoke Velopack.
|
||||
- [ ] `release.yml` uploads app payload artifacts for PDCC.
|
||||
- [ ] S3 output path is rooted at `lanmountain/update/` (no system version prefix).
|
||||
- [ ] S3 has `repo/`, `meta/`, and `installers/` outputs after a release run.
|
||||
- [ ] Host update source default is `stcn` and old `pdc` values are auto-normalized.
|
||||
- [ ] Host can persist PDC payload into launcher incoming directory.
|
||||
- [ ] Launcher can apply PDC FileMap payload with signature/hash verification.
|
||||
- [ ] Legacy signed `files.json + update.zip` path still works as compatibility fallback.
|
||||
- [ ] CI run attached proving all release matrix jobs pass.
|
||||
- [ ] N-1 -> N incremental update verified on Windows x64/x86 and Linux x64.
|
||||
- [ ] Rollback verification report attached.
|
||||
|
||||
@@ -2,29 +2,43 @@
|
||||
|
||||
## Goal
|
||||
|
||||
Replace VeloPack-based incremental packaging with a unified signed FileMap pipeline and prepare for PDC/S3 distribution compatibility, while keeping Launcher installation, rollback, and update orchestration ownership unchanged.
|
||||
Replace VeloPack-based incremental packaging with a unified PDC FileMap + object-repo pipeline, while keeping Launcher installation, rollback, and update orchestration ownership unchanged.
|
||||
|
||||
## Stage 1 (Completed in this round)
|
||||
## Stage 1 (Completed)
|
||||
|
||||
- Release workflow outputs signed FileMap incremental assets as the primary path:
|
||||
- `files-windows-x64.json` / `.sig` / `update-windows-x64.zip`
|
||||
- `files-windows-x86.json` / `.sig` / `update-windows-x86.zip`
|
||||
- `files-linux-x64.json` / `.sig` / `update-linux-x64.zip`
|
||||
- Launcher and host update runtime remove VeloPack branches and return to signed FileMap apply path.
|
||||
- Host update asset discovery supports platform-scoped names with fallback to legacy generic names.
|
||||
- Optional S3 sync publishes incremental assets in parallel with GitHub Release assets.
|
||||
- Release workflow removed VeloPack-based release packaging.
|
||||
- Signed FileMap path was restored as an interim release mechanism.
|
||||
- Host/Launcher fallback behavior stayed compatible with `files.json + files.json.sig + update.zip`.
|
||||
|
||||
## Stage 2 (In Progress)
|
||||
## Stage 2 (Current Implementation Target)
|
||||
|
||||
- Introduce PDC-compatible update source (`pdc`) with fallback to GitHub.
|
||||
- Add PDC metadata/latest/distribution API consumption abstraction.
|
||||
- Keep Launcher install/apply/rollback state machine unchanged.
|
||||
- Prepare `phainon.yml`-compatible release metadata for future PDCC integration.
|
||||
- Move release publishing to PDCC + `phainon.yml` (ClassIsland-style).
|
||||
- Promote PDC-distributed FileMap/object-repo as the primary incremental path.
|
||||
- Keep GitHub Release installers and metadata as parallel distribution.
|
||||
- Keep Launcher state machine ownership (`.current/.partial/.destroy` + snapshots).
|
||||
- Update source defaults to `stcn` (S3/PDC), with GitHub fallback.
|
||||
- S3 object root is fixed to `lanmountain/update/` with no update-system version prefix.
|
||||
|
||||
Expected S3 layout:
|
||||
- `lanmountain/update/repo/<hash-prefix>/<hash-object>`
|
||||
- `lanmountain/update/meta/channels/<channel>/<subchannel>/latest.json`
|
||||
- `lanmountain/update/meta/distributions/<distributionId>/*.json`
|
||||
- `lanmountain/update/installers/<platform>/<arch>/*`
|
||||
|
||||
## Acceptance
|
||||
|
||||
- `release.yml` no longer contains VeloPack packaging steps.
|
||||
- Windows x64/x86 and Linux x64 release jobs all upload signed FileMap incremental assets.
|
||||
- Host auto-update can detect and download platform-matching signed FileMap assets.
|
||||
- Launcher `update apply` succeeds with signed FileMap payload and rollback behavior remains unchanged.
|
||||
- Optional S3 upload step works when S3 secrets/vars are configured.
|
||||
- `release.yml` includes PDCC publish steps and no Velopack steps.
|
||||
- Release jobs keep building installers for Windows x64/x86, Linux x64, and macOS.
|
||||
- PDC metadata + FileMap + object repo are published under `lanmountain/update/`.
|
||||
- Host can consume PDC payload (`stcn` source) and fallback to GitHub when unavailable.
|
||||
- Launcher can apply both:
|
||||
- legacy signed `files.json + update.zip`
|
||||
- PDC FileMap object-repo payload.
|
||||
- Rollback semantics remain unchanged.
|
||||
|
||||
## Deprecated Notes
|
||||
|
||||
- The following interim outputs are compatibility-only (not the long-term primary path):
|
||||
- `files-windows-x64.json` / `.sig` / `update-windows-x64.zip`
|
||||
- `files-windows-x86.json` / `.sig` / `update-windows-x86.zip`
|
||||
- `files-linux-x64.json` / `.sig` / `update-linux-x64.zip`
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
# Tasks
|
||||
|
||||
- [x] Remove VeloPack packaging from release workflow.
|
||||
- [x] Promote signed FileMap generation to release primary path.
|
||||
- [x] Output platform-scoped incremental assets for Windows x64/x86 and Linux x64.
|
||||
- [x] Remove launcher/runtime VeloPack branches.
|
||||
- [x] Update host asset discovery to platform-scoped signed FileMap naming.
|
||||
- [x] Add optional S3 sync for incremental assets.
|
||||
- [x] Extend update source values with `pdc`.
|
||||
- [x] Add PDC check fallback service skeleton in settings domain.
|
||||
- [ ] Add full PDC FileMap object-hash download/deploy path.
|
||||
- [ ] Add PDCC publish integration and `phainon.yml` CI publishing flow.
|
||||
- [x] Keep signed FileMap path as interim compatibility fallback.
|
||||
- [x] Remove launcher/runtime Velopack branching.
|
||||
- [ ] Add `phainon.yml` for PDCC publish configuration.
|
||||
- [ ] Add PDCC installation + publish steps in `release.yml`.
|
||||
- [ ] Upload app payload artifacts for PDCC consumption in release build jobs.
|
||||
- [ ] Publish PDC metadata + object repo to S3 path root `lanmountain/update/`.
|
||||
- [ ] Mirror installers to `lanmountain/update/installers/<platform>/<arch>/`.
|
||||
- [ ] Replace update source canonical value with `stcn` (keep legacy `pdc` compatibility).
|
||||
- [ ] Add PDC payload model into host update check result.
|
||||
- [ ] Add host download path for PDC payload (`pdc-filemap.json` + signature + metadata).
|
||||
- [ ] Add launcher PDC FileMap apply path with rollback-compatible semantics.
|
||||
- [ ] Keep old `files.json + update.zip` path behind compatibility fallback.
|
||||
|
||||
@@ -214,14 +214,12 @@ public partial class App : Application
|
||||
var deploymentLocator = new DeploymentLocator(appRoot);
|
||||
|
||||
// TODO: 从配置读取 GitHub 仓库信息
|
||||
var updateCheckService = new UpdateCheckService("ClassIsland", "LanMountainDesktop");
|
||||
|
||||
coordinator = new LauncherFlowCoordinator(
|
||||
context,
|
||||
deploymentLocator,
|
||||
new OobeStateService(appRoot),
|
||||
new UpdateEngineService(deploymentLocator),
|
||||
updateCheckService,
|
||||
new PluginInstallerService());
|
||||
|
||||
result = await coordinator.RunAsync(splashWindow).ConfigureAwait(false);
|
||||
|
||||
@@ -9,6 +9,11 @@ namespace LanMountainDesktop.Launcher;
|
||||
[JsonSourceGenerationOptions(WriteIndented = true, PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
|
||||
[JsonSerializable(typeof(SignedFileMap))]
|
||||
[JsonSerializable(typeof(UpdateFileEntry))]
|
||||
[JsonSerializable(typeof(PdcUpdateMetadata))]
|
||||
[JsonSerializable(typeof(PdcFileMap))]
|
||||
[JsonSerializable(typeof(PdcComponentEntry))]
|
||||
[JsonSerializable(typeof(PdcFileEntry))]
|
||||
[JsonSerializable(typeof(PdcHashDescriptor))]
|
||||
[JsonSerializable(typeof(SnapshotMetadata))]
|
||||
[JsonSerializable(typeof(AppVersionInfo))]
|
||||
[JsonSerializable(typeof(StartupProgressMessage))]
|
||||
|
||||
@@ -53,3 +53,92 @@ internal sealed class UpdateApplyResult
|
||||
|
||||
public string? RolledBackTo { get; init; }
|
||||
}
|
||||
|
||||
internal sealed class PdcUpdateMetadata
|
||||
{
|
||||
public string? DistributionId { get; set; }
|
||||
|
||||
public string? Channel { get; set; }
|
||||
|
||||
public string? SubChannel { get; set; }
|
||||
|
||||
public string? FromVersion { get; set; }
|
||||
|
||||
public string? ToVersion { get; set; }
|
||||
|
||||
public string? FileMapPath { get; set; }
|
||||
|
||||
public string? FileMapSignaturePath { get; set; }
|
||||
|
||||
public Dictionary<string, string> Metadata { get; set; } = [];
|
||||
}
|
||||
|
||||
internal sealed class PdcFileMap
|
||||
{
|
||||
public string? DistributionId { get; set; }
|
||||
|
||||
public string? FromVersion { get; set; }
|
||||
|
||||
public string? ToVersion { get; set; }
|
||||
|
||||
public string? Version { get; set; }
|
||||
|
||||
public string? Platform { get; set; }
|
||||
|
||||
public string? Arch { get; set; }
|
||||
|
||||
public Dictionary<string, string> Metadata { get; set; } = [];
|
||||
|
||||
public List<PdcComponentEntry> Components { get; set; } = [];
|
||||
|
||||
public List<PdcFileEntry> Files { get; set; } = [];
|
||||
}
|
||||
|
||||
internal sealed class PdcComponentEntry
|
||||
{
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
public string? Version { get; set; }
|
||||
|
||||
public Dictionary<string, string> Metadata { get; set; } = [];
|
||||
|
||||
public List<PdcFileEntry> Files { get; set; } = [];
|
||||
}
|
||||
|
||||
internal sealed class PdcFileEntry
|
||||
{
|
||||
public string Path { get; set; } = string.Empty;
|
||||
|
||||
public string? Action { get; set; } = "replace";
|
||||
|
||||
public string? Url { get; set; }
|
||||
|
||||
public string? ObjectUrl { get; set; }
|
||||
|
||||
public string? ObjectPath { get; set; }
|
||||
|
||||
public string? ObjectKey { get; set; }
|
||||
|
||||
public string? ArchivePath { get; set; }
|
||||
|
||||
public string? Sha256 { get; set; }
|
||||
|
||||
public string? Sha512 { get; set; }
|
||||
|
||||
public string? Sha512Base64 { get; set; }
|
||||
|
||||
public byte[]? Sha512Bytes { get; set; }
|
||||
|
||||
public PdcHashDescriptor? Hash { get; set; }
|
||||
|
||||
public Dictionary<string, string> Metadata { get; set; } = [];
|
||||
}
|
||||
|
||||
internal sealed class PdcHashDescriptor
|
||||
{
|
||||
public string? Algorithm { get; set; }
|
||||
|
||||
public string? Value { get; set; }
|
||||
|
||||
public byte[]? Bytes { get; set; }
|
||||
}
|
||||
|
||||
@@ -22,7 +22,6 @@ internal sealed class LauncherFlowCoordinator
|
||||
private readonly DeploymentLocator _deploymentLocator;
|
||||
private readonly OobeStateService _oobeStateService;
|
||||
private readonly UpdateEngineService _updateEngine;
|
||||
private readonly UpdateCheckService _updateCheckService;
|
||||
private readonly PluginInstallerService _pluginInstallerService;
|
||||
private readonly IReadOnlyList<IOobeStep> _oobeSteps;
|
||||
|
||||
@@ -31,14 +30,12 @@ internal sealed class LauncherFlowCoordinator
|
||||
DeploymentLocator deploymentLocator,
|
||||
OobeStateService oobeStateService,
|
||||
UpdateEngineService updateEngine,
|
||||
UpdateCheckService updateCheckService,
|
||||
PluginInstallerService pluginInstallerService)
|
||||
{
|
||||
_context = context;
|
||||
_deploymentLocator = deploymentLocator;
|
||||
_oobeStateService = oobeStateService;
|
||||
_updateEngine = updateEngine;
|
||||
_updateCheckService = updateCheckService;
|
||||
_pluginInstallerService = pluginInstallerService;
|
||||
_oobeSteps = [new WelcomeOobeStep(_oobeStateService)];
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1085,6 +1085,12 @@ public partial class App : Application
|
||||
// 延迟报告 Ready 直到窗口实际打开并可见
|
||||
// 使用 Opened 事件确保所有资源已加载完毕
|
||||
mainWindow.Opened += OnMainWindowOpened;
|
||||
|
||||
// 手动显示窗口,因为在 ShutdownMode.OnExplicitShutdown 模式下框架不会自动调用 Show
|
||||
if (!mainWindow.IsVisible)
|
||||
{
|
||||
mainWindow.Show();
|
||||
}
|
||||
|
||||
// 兜底机制:如果 Opened 事件 10 秒内未触发,强制发送 Ready 信号
|
||||
// 防止因渲染问题导致 Opened 不触发,启动器 Splash 窗口一直显示
|
||||
|
||||
@@ -85,7 +85,7 @@ public sealed class AppSettingsSnapshot
|
||||
|
||||
public string UpdateMode { get; set; } = "download_then_confirm";
|
||||
|
||||
public string UpdateDownloadSource { get; set; } = "pdc";
|
||||
public string UpdateDownloadSource { get; set; } = "stcn";
|
||||
|
||||
public int UpdateDownloadThreads { get; set; } = 4;
|
||||
|
||||
|
||||
@@ -34,7 +34,17 @@ public sealed record UpdateCheckResult(
|
||||
GitHubReleaseInfo? Release,
|
||||
GitHubReleaseAsset? PreferredAsset,
|
||||
string? ErrorMessage,
|
||||
bool ForceMode = false);
|
||||
bool ForceMode = false,
|
||||
PdcUpdatePayload? PdcPayload = null);
|
||||
|
||||
public sealed record PdcUpdatePayload(
|
||||
string DistributionId,
|
||||
string ChannelId,
|
||||
string SubChannel,
|
||||
string? FileMapJson,
|
||||
string? FileMapSignature,
|
||||
string? FileMapJsonUrl,
|
||||
string? FileMapSignatureUrl);
|
||||
|
||||
public sealed record UpdateDownloadResult(
|
||||
bool Success,
|
||||
|
||||
@@ -148,7 +148,8 @@ public sealed class PdcReleaseUpdateService : IDisposable
|
||||
var distributionNode = await GetContentNodeAsync(distributionUrl, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var assets = ResolveAssets(distributionNode);
|
||||
if (assets.Count == 0)
|
||||
var pdcPayload = ResolvePdcPayload(distributionNode, distributionId, channelId, subChannel);
|
||||
if (assets.Count == 0 && !HasPdcPayload(pdcPayload))
|
||||
{
|
||||
return new UpdateCheckResult(
|
||||
Success: false,
|
||||
@@ -168,6 +169,7 @@ public sealed class PdcReleaseUpdateService : IDisposable
|
||||
IsDraft: false,
|
||||
PublishedAt: DateTimeOffset.UtcNow,
|
||||
Assets: assets);
|
||||
var preferredAsset = SelectPreferredInstallerAsset(assets);
|
||||
|
||||
return new UpdateCheckResult(
|
||||
Success: true,
|
||||
@@ -175,9 +177,10 @@ public sealed class PdcReleaseUpdateService : IDisposable
|
||||
CurrentVersionText: normalizedCurrentVersionText,
|
||||
LatestVersionText: latestVersionText,
|
||||
Release: release,
|
||||
PreferredAsset: null,
|
||||
PreferredAsset: preferredAsset,
|
||||
ErrorMessage: null,
|
||||
ForceMode: isForce);
|
||||
ForceMode: isForce,
|
||||
PdcPayload: pdcPayload);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
@@ -289,6 +292,119 @@ public sealed class PdcReleaseUpdateService : IDisposable
|
||||
return assets;
|
||||
}
|
||||
|
||||
private static PdcUpdatePayload ResolvePdcPayload(
|
||||
JsonElement distributionNode,
|
||||
string distributionId,
|
||||
string channelId,
|
||||
string subChannel)
|
||||
{
|
||||
var fileMapJson = ReadString(distributionNode, "fileMapJson");
|
||||
var fileMapSignature = ReadString(distributionNode, "fileMapSignature");
|
||||
var fileMapJsonUrl = ReadString(distributionNode, "fileMapJsonUrl")
|
||||
?? ReadString(distributionNode, "fileMapUrl")
|
||||
?? ReadString(distributionNode, "manifestUrl");
|
||||
var fileMapSignatureUrl = ReadString(distributionNode, "fileMapSignatureUrl")
|
||||
?? ReadString(distributionNode, "signatureUrl");
|
||||
return new PdcUpdatePayload(
|
||||
DistributionId: distributionId,
|
||||
ChannelId: channelId,
|
||||
SubChannel: subChannel,
|
||||
FileMapJson: fileMapJson,
|
||||
FileMapSignature: fileMapSignature,
|
||||
FileMapJsonUrl: fileMapJsonUrl,
|
||||
FileMapSignatureUrl: fileMapSignatureUrl);
|
||||
}
|
||||
|
||||
private static bool HasPdcPayload(PdcUpdatePayload payload)
|
||||
{
|
||||
return !string.IsNullOrWhiteSpace(payload.FileMapJson)
|
||||
|| !string.IsNullOrWhiteSpace(payload.FileMapJsonUrl);
|
||||
}
|
||||
|
||||
private static GitHubReleaseAsset? SelectPreferredInstallerAsset(IReadOnlyList<GitHubReleaseAsset> assets)
|
||||
{
|
||||
if (assets is null || assets.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
var archToken = RuntimeInformation.OSArchitecture switch
|
||||
{
|
||||
Architecture.Arm64 => "arm64",
|
||||
Architecture.X86 => "x86",
|
||||
_ => "x64"
|
||||
};
|
||||
return assets
|
||||
.Select(asset => (Asset: asset, Score: ScoreInstallerAsset(asset.Name, ".exe", ".msi", archToken)))
|
||||
.OrderByDescending(x => x.Score)
|
||||
.FirstOrDefault(x => x.Score > 0)
|
||||
.Asset;
|
||||
}
|
||||
|
||||
if (OperatingSystem.IsLinux())
|
||||
{
|
||||
return assets
|
||||
.Select(asset => (Asset: asset, Score: ScoreInstallerAsset(asset.Name, ".deb", ".rpm", "x64")))
|
||||
.OrderByDescending(x => x.Score)
|
||||
.FirstOrDefault(x => x.Score > 0)
|
||||
.Asset;
|
||||
}
|
||||
|
||||
if (OperatingSystem.IsMacOS())
|
||||
{
|
||||
var archToken = RuntimeInformation.OSArchitecture == Architecture.Arm64 ? "arm64" : "x64";
|
||||
return assets
|
||||
.Select(asset => (Asset: asset, Score: ScoreInstallerAsset(asset.Name, ".dmg", ".pkg", archToken)))
|
||||
.OrderByDescending(x => x.Score)
|
||||
.FirstOrDefault(x => x.Score > 0)
|
||||
.Asset;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static int ScoreInstallerAsset(string name, string ext1, string ext2, string archToken)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(name))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var score = 0;
|
||||
if (name.EndsWith(ext1, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
score += 200;
|
||||
}
|
||||
else if (name.EndsWith(ext2, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
score += 160;
|
||||
}
|
||||
else
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (name.Contains("setup", StringComparison.OrdinalIgnoreCase) ||
|
||||
name.Contains("installer", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
score += 50;
|
||||
}
|
||||
|
||||
if (name.Contains(archToken, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
score += 40;
|
||||
}
|
||||
|
||||
if (name.Contains("portable", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
score -= 30;
|
||||
}
|
||||
|
||||
return score;
|
||||
}
|
||||
|
||||
private static string ResolveChannelId(JsonElement metadataNode, bool includePrerelease)
|
||||
{
|
||||
if (metadataNode.ValueKind != JsonValueKind.Object ||
|
||||
|
||||
@@ -356,6 +356,7 @@ public interface IUpdateSettingsService
|
||||
void Save(UpdateSettingsState state);
|
||||
Task<UpdateCheckResult> CheckForUpdatesAsync(Version currentVersion, bool includePrerelease, CancellationToken cancellationToken = default);
|
||||
Task<UpdateCheckResult> ForceCheckForUpdatesAsync(Version currentVersion, bool includePrerelease, CancellationToken cancellationToken = default);
|
||||
Task<PdcUpdatePayload?> GetPdcUpdatePayloadAsync(Version currentVersion, bool includePrerelease, bool isForce = false, CancellationToken cancellationToken = default);
|
||||
Task<UpdateDownloadResult> DownloadAssetAsync(
|
||||
GitHubReleaseAsset asset,
|
||||
string destinationFilePath,
|
||||
|
||||
@@ -842,6 +842,18 @@ internal sealed class UpdateSettingsService : IUpdateSettingsService, IDisposabl
|
||||
return CheckForUpdatesCoreAsync(currentVersion, includePrerelease, isForce: true, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<PdcUpdatePayload?> GetPdcUpdatePayloadAsync(
|
||||
Version currentVersion,
|
||||
bool includePrerelease,
|
||||
bool isForce = false,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var result = isForce
|
||||
? await _pdcReleaseUpdateService.ForceCheckForUpdatesAsync(currentVersion, includePrerelease, cancellationToken)
|
||||
: await _pdcReleaseUpdateService.CheckForUpdatesAsync(currentVersion, includePrerelease, cancellationToken);
|
||||
return result.Success ? result.PdcPayload : null;
|
||||
}
|
||||
|
||||
public Task<UpdateDownloadResult> DownloadAssetAsync(
|
||||
GitHubReleaseAsset asset,
|
||||
string destinationFilePath,
|
||||
|
||||
@@ -11,7 +11,10 @@ public static class UpdateSettingsValues
|
||||
public const string ModeDownloadThenConfirm = "download_then_confirm";
|
||||
public const string ModeSilentOnExit = "silent_on_exit";
|
||||
|
||||
public const string DownloadSourcePdc = "pdc";
|
||||
// NOTE: keep constant name for compatibility with existing call sites.
|
||||
public const string DownloadSourcePdc = "stcn";
|
||||
public const string DownloadSourceStcn = DownloadSourcePdc;
|
||||
public const string LegacyDownloadSourcePdc = "pdc";
|
||||
public const string DownloadSourceGitHub = "github";
|
||||
public const string DownloadSourceGhProxy = "gh-proxy";
|
||||
|
||||
@@ -52,6 +55,11 @@ public static class UpdateSettingsValues
|
||||
|
||||
public static string NormalizeDownloadSource(string? value)
|
||||
{
|
||||
if (string.Equals(value, LegacyDownloadSourcePdc, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return DownloadSourceStcn;
|
||||
}
|
||||
|
||||
if (string.Equals(value, DownloadSourcePdc, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return DownloadSourcePdc;
|
||||
@@ -67,8 +75,8 @@ public static class UpdateSettingsValues
|
||||
return DownloadSourceGitHub;
|
||||
}
|
||||
|
||||
// Default to PDC. Runtime will fallback to GitHub if PDC is unavailable.
|
||||
return DownloadSourcePdc;
|
||||
// Default to STCN(PDC/S3). Runtime will fallback to GitHub if STCN is unavailable.
|
||||
return DownloadSourceStcn;
|
||||
}
|
||||
|
||||
public static int NormalizeDownloadThreads(int value)
|
||||
|
||||
@@ -5,7 +5,11 @@ using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using LanMountainDesktop.PluginSdk;
|
||||
@@ -53,9 +57,20 @@ public sealed class UpdateWorkflowService
|
||||
private const string LauncherDirectoryName = ".launcher";
|
||||
private const string UpdateDirectoryName = "update";
|
||||
private const string IncomingDirectoryName = "incoming";
|
||||
private const string IncomingObjectsDirectoryName = "objects";
|
||||
private const string SignedFileMapName = "files.json";
|
||||
private const string SignedFileMapSignatureName = "files.json.sig";
|
||||
private const string UpdateArchiveName = "update.zip";
|
||||
private const string PdcFileMapName = "pdc-filemap.json";
|
||||
private const string PdcFileMapSignatureName = "pdc-filemap.sig";
|
||||
private const string PdcUpdateStateName = "pdc-update.json";
|
||||
|
||||
private static readonly HttpClient PdcHttpClient = new()
|
||||
{
|
||||
Timeout = TimeSpan.FromMinutes(5)
|
||||
};
|
||||
|
||||
private static readonly ResumableDownloadService PdcDownloadService = new(PdcHttpClient);
|
||||
|
||||
public UpdateWorkflowService(ISettingsFacadeService settingsFacade)
|
||||
{
|
||||
@@ -81,6 +96,11 @@ public sealed class UpdateWorkflowService
|
||||
return Path.Combine(launcherRoot, LauncherDirectoryName, UpdateDirectoryName, IncomingDirectoryName);
|
||||
}
|
||||
|
||||
public static string GetLauncherIncomingObjectsDirectory()
|
||||
{
|
||||
return Path.Combine(GetLauncherIncomingDirectory(), IncomingObjectsDirectoryName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether a GitHub Release contains signed file-map assets needed for incremental updates.
|
||||
/// </summary>
|
||||
@@ -94,6 +114,16 @@ public sealed class UpdateWorkflowService
|
||||
return TryResolveDeltaAssets(release.Assets, out _, out _, out _);
|
||||
}
|
||||
|
||||
public static bool IsDeltaUpdateAvailable(UpdateCheckResult checkResult)
|
||||
{
|
||||
if (checkResult.PdcPayload is not null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return checkResult.Release is not null && IsDeltaUpdateAvailable(checkResult.Release);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Downloads signed file-map assets to the Launcher's incoming directory.
|
||||
/// </summary>
|
||||
@@ -104,12 +134,24 @@ public sealed class UpdateWorkflowService
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(checkResult);
|
||||
|
||||
if (!checkResult.Success || !checkResult.IsUpdateAvailable || checkResult.Release is null)
|
||||
if (!checkResult.Success || !checkResult.IsUpdateAvailable)
|
||||
{
|
||||
return new UpdateDownloadResult(false, null, "No update available for delta download.");
|
||||
}
|
||||
|
||||
if (!TryResolveDeltaAssets(checkResult.Release.Assets, out var manifestAsset, out var signatureAsset, out var archiveAsset))
|
||||
if (checkResult.PdcPayload is null && checkResult.Release is null)
|
||||
{
|
||||
return new UpdateDownloadResult(false, null, "No update payload is available for delta download.");
|
||||
}
|
||||
|
||||
if (checkResult.PdcPayload is not null)
|
||||
{
|
||||
return await DownloadPdcDeltaUpdateAsync(checkResult, progress, cancellationToken);
|
||||
}
|
||||
|
||||
var release = checkResult.Release;
|
||||
if (release is null ||
|
||||
!TryResolveDeltaAssets(release.Assets, out var manifestAsset, out var signatureAsset, out var archiveAsset))
|
||||
{
|
||||
return new UpdateDownloadResult(false, null, "Release does not contain compatible signed file-map assets.");
|
||||
}
|
||||
@@ -189,9 +231,9 @@ public sealed class UpdateWorkflowService
|
||||
{
|
||||
PendingUpdateInstallerPath = Path.Combine(incomingDir, SignedFileMapName),
|
||||
PendingUpdateVersion = checkResult.LatestVersionText,
|
||||
PendingUpdatePublishedAtUtcMs = checkResult.Release.PublishedAt == DateTimeOffset.MinValue
|
||||
? null
|
||||
: checkResult.Release.PublishedAt.ToUnixTimeMilliseconds(),
|
||||
PendingUpdatePublishedAtUtcMs = checkResult.Release?.PublishedAt is DateTimeOffset publishedAt && publishedAt != DateTimeOffset.MinValue
|
||||
? publishedAt.ToUnixTimeMilliseconds()
|
||||
: null,
|
||||
LastUpdateCheckUtcMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
|
||||
PendingUpdateSha256 = null
|
||||
});
|
||||
@@ -201,6 +243,163 @@ public sealed class UpdateWorkflowService
|
||||
return new UpdateDownloadResult(true, Path.Combine(incomingDir, SignedFileMapName), null);
|
||||
}
|
||||
|
||||
private async Task<UpdateDownloadResult> DownloadPdcDeltaUpdateAsync(
|
||||
UpdateCheckResult checkResult,
|
||||
IProgress<double>? progress = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var payload = checkResult.PdcPayload;
|
||||
if (payload is null)
|
||||
{
|
||||
return new UpdateDownloadResult(false, null, "PDC payload is missing.");
|
||||
}
|
||||
|
||||
var incomingDir = GetLauncherIncomingDirectory();
|
||||
var objectsDir = GetLauncherIncomingObjectsDirectory();
|
||||
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(incomingDir);
|
||||
Directory.CreateDirectory(objectsDir);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return new UpdateDownloadResult(false, null, $"Failed to create incoming directory: {ex.Message}");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var state = _settingsFacade.Update.Get();
|
||||
var downloadThreads = Math.Max(1, state.UpdateDownloadThreads);
|
||||
var fileMapPath = Path.Combine(incomingDir, PdcFileMapName);
|
||||
var signaturePath = Path.Combine(incomingDir, PdcFileMapSignatureName);
|
||||
var updateStatePath = Path.Combine(incomingDir, PdcUpdateStateName);
|
||||
|
||||
var fileMapJson = await EnsurePdcTextResourceAsync(
|
||||
payload.FileMapJson,
|
||||
payload.FileMapJsonUrl,
|
||||
fileMapPath,
|
||||
cancellationToken);
|
||||
|
||||
var fileMapSignature = await EnsurePdcTextResourceAsync(
|
||||
payload.FileMapSignature,
|
||||
payload.FileMapSignatureUrl,
|
||||
signaturePath,
|
||||
cancellationToken);
|
||||
|
||||
var downloadEntries = ParsePdcDownloadEntries(fileMapJson);
|
||||
if (downloadEntries.Count == 0)
|
||||
{
|
||||
return new UpdateDownloadResult(false, null, "PDC file map does not contain downloadable objects.");
|
||||
}
|
||||
|
||||
var expectedObjectCount = downloadEntries.Count;
|
||||
var completedItems = 2;
|
||||
progress?.Report(expectedObjectCount == 0 ? 1d : (double)completedItems / (expectedObjectCount + 2));
|
||||
|
||||
var objectResults = new List<PdcDownloadedObjectInfo>(expectedObjectCount);
|
||||
var objectTargets = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var totalSteps = expectedObjectCount + 2;
|
||||
|
||||
foreach (var entry in downloadEntries)
|
||||
{
|
||||
if (!objectTargets.Add(entry.ObjectHashHex))
|
||||
{
|
||||
completedItems++;
|
||||
progress?.Report((double)completedItems / totalSteps);
|
||||
continue;
|
||||
}
|
||||
|
||||
var destinationPath = GetPdcObjectDestinationPath(objectsDir, entry.ObjectHashHex);
|
||||
var destinationDirectory = Path.GetDirectoryName(destinationPath);
|
||||
if (!string.IsNullOrWhiteSpace(destinationDirectory))
|
||||
{
|
||||
Directory.CreateDirectory(destinationDirectory);
|
||||
}
|
||||
|
||||
if (File.Exists(destinationPath))
|
||||
{
|
||||
var existingHash = await ComputeFileSha512HexAsync(destinationPath, cancellationToken);
|
||||
if (string.Equals(existingHash, entry.ObjectHashHex, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
objectResults.Add(new PdcDownloadedObjectInfo(entry.ComponentId, entry.RelativePath, entry.DownloadUrl, entry.ObjectHashHex, destinationPath));
|
||||
completedItems++;
|
||||
progress?.Report((double)completedItems / totalSteps);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
var downloadOptions = new DownloadOptions(MaxParallelSegments: downloadThreads);
|
||||
var downloadResult = await PdcDownloadService.DownloadAsync(
|
||||
entry.DownloadUrl,
|
||||
destinationPath,
|
||||
downloadOptions,
|
||||
null,
|
||||
cancellationToken);
|
||||
|
||||
if (!downloadResult.Success)
|
||||
{
|
||||
return new UpdateDownloadResult(false, null, $"Failed to download PDC object {entry.RelativePath}: {downloadResult.ErrorMessage}");
|
||||
}
|
||||
|
||||
var actualHash = await ComputeFileSha512HexAsync(destinationPath, cancellationToken);
|
||||
if (!string.IsNullOrWhiteSpace(actualHash) &&
|
||||
!string.Equals(actualHash, entry.ObjectHashHex, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return new UpdateDownloadResult(false, null, $"PDC object hash mismatch for {entry.RelativePath}. Expected: {entry.ObjectHashHex}, Actual: {actualHash}");
|
||||
}
|
||||
|
||||
objectResults.Add(new PdcDownloadedObjectInfo(entry.ComponentId, entry.RelativePath, entry.DownloadUrl, entry.ObjectHashHex, destinationPath));
|
||||
completedItems++;
|
||||
progress?.Report((double)completedItems / totalSteps);
|
||||
}
|
||||
|
||||
var updateState = new PdcUpdateState(
|
||||
checkResult.LatestVersionText,
|
||||
payload.DistributionId,
|
||||
payload.ChannelId,
|
||||
payload.SubChannel,
|
||||
fileMapPath,
|
||||
signaturePath,
|
||||
objectsDir,
|
||||
DateTimeOffset.UtcNow,
|
||||
fileMapJson,
|
||||
fileMapSignature,
|
||||
objectResults);
|
||||
|
||||
await File.WriteAllTextAsync(updateStatePath, JsonSerializer.Serialize(updateState, UpdateJsonOptions), cancellationToken);
|
||||
|
||||
SaveState(state with
|
||||
{
|
||||
PendingUpdateInstallerPath = updateStatePath,
|
||||
PendingUpdateVersion = checkResult.LatestVersionText,
|
||||
PendingUpdatePublishedAtUtcMs = checkResult.Release?.PublishedAt is DateTimeOffset publishedAt && publishedAt != DateTimeOffset.MinValue
|
||||
? publishedAt.ToUnixTimeMilliseconds()
|
||||
: null,
|
||||
LastUpdateCheckUtcMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
|
||||
PendingUpdateSha256 = null
|
||||
});
|
||||
|
||||
progress?.Report(1d);
|
||||
AppLogger.Info("UpdateWorkflow", $"PDC update payload downloaded to {incomingDir}. Will be applied by Launcher on next startup.");
|
||||
return new UpdateDownloadResult(true, updateStatePath, null);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLogger.Warn("UpdateWorkflow", "Failed to download PDC incremental payload.", ex);
|
||||
return new UpdateDownloadResult(false, null, ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly JsonSerializerOptions UpdateJsonOptions = new()
|
||||
{
|
||||
WriteIndented = true
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether the pending update is managed by Launcher incoming payload.
|
||||
/// </summary>
|
||||
@@ -213,11 +412,261 @@ public sealed class UpdateWorkflowService
|
||||
return false;
|
||||
}
|
||||
|
||||
// Incoming payload updates are identified by files.json or incoming directory path.
|
||||
// Incoming payload updates are identified by the local manifest or incoming directory path.
|
||||
return pendingPath.EndsWith(SignedFileMapName, StringComparison.OrdinalIgnoreCase)
|
||||
|| pendingPath.EndsWith(PdcUpdateStateName, StringComparison.OrdinalIgnoreCase)
|
||||
|| pendingPath.EndsWith(PdcFileMapName, StringComparison.OrdinalIgnoreCase)
|
||||
|| pendingPath.EndsWith(PdcFileMapSignatureName, StringComparison.OrdinalIgnoreCase)
|
||||
|| pendingPath.Contains(IncomingDirectoryName, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static string GetPdcObjectDestinationPath(string objectsDirectory, string objectHashHex)
|
||||
{
|
||||
var normalizedHash = objectHashHex.Trim().ToLowerInvariant();
|
||||
var shard = normalizedHash.Length >= 2 ? normalizedHash[..2] : normalizedHash;
|
||||
return Path.Combine(objectsDirectory, shard, normalizedHash);
|
||||
}
|
||||
|
||||
private static async Task<string> EnsurePdcTextResourceAsync(
|
||||
string? inlineContent,
|
||||
string? sourceUrl,
|
||||
string destinationPath,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(inlineContent))
|
||||
{
|
||||
await File.WriteAllTextAsync(destinationPath, inlineContent, cancellationToken);
|
||||
return inlineContent;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(sourceUrl))
|
||||
{
|
||||
throw new InvalidOperationException("PDC payload does not contain a file map source.");
|
||||
}
|
||||
|
||||
var downloadResult = await PdcDownloadService.DownloadAsync(
|
||||
sourceUrl,
|
||||
destinationPath,
|
||||
cancellationToken: cancellationToken);
|
||||
|
||||
if (!downloadResult.Success)
|
||||
{
|
||||
throw new InvalidOperationException($"Failed to download PDC file map resource: {downloadResult.ErrorMessage}");
|
||||
}
|
||||
|
||||
return await File.ReadAllTextAsync(destinationPath, cancellationToken);
|
||||
}
|
||||
|
||||
private static IReadOnlyList<PdcDownloadEntry> ParsePdcDownloadEntries(string fileMapJson)
|
||||
{
|
||||
var entries = new List<PdcDownloadEntry>();
|
||||
if (string.IsNullOrWhiteSpace(fileMapJson))
|
||||
{
|
||||
return entries;
|
||||
}
|
||||
|
||||
using var document = JsonDocument.Parse(fileMapJson);
|
||||
var root = document.RootElement;
|
||||
if (root.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
return entries;
|
||||
}
|
||||
|
||||
if (!TryGetPropertyIgnoreCase(root, "components", out var componentsNode) ||
|
||||
componentsNode.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
return entries;
|
||||
}
|
||||
|
||||
foreach (var component in componentsNode.EnumerateObject())
|
||||
{
|
||||
if (component.Value.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!TryGetPropertyIgnoreCase(component.Value, "files", out var filesNode) ||
|
||||
filesNode.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var fileEntry in filesNode.EnumerateObject())
|
||||
{
|
||||
if (fileEntry.Value.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var downloadUrl = ReadStringIgnoreCase(fileEntry.Value, "archivedownloadurl")
|
||||
?? ReadStringIgnoreCase(fileEntry.Value, "downloadurl")
|
||||
?? ReadStringIgnoreCase(fileEntry.Value, "url");
|
||||
var hashBytes = ReadByteArrayIgnoreCase(fileEntry.Value, "archivesha512")
|
||||
?? ReadByteArrayIgnoreCase(fileEntry.Value, "filesha512");
|
||||
|
||||
if (string.IsNullOrWhiteSpace(downloadUrl) || hashBytes is null || hashBytes.Length == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var hashHex = Convert.ToHexString(hashBytes).ToLowerInvariant();
|
||||
entries.Add(new PdcDownloadEntry(
|
||||
component.Name,
|
||||
fileEntry.Name,
|
||||
downloadUrl,
|
||||
hashHex));
|
||||
}
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
private static async Task<string?> ComputeFileSha512HexAsync(string filePath, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!File.Exists(filePath))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
await using var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
|
||||
var hashBytes = await SHA512.HashDataAsync(stream, cancellationToken);
|
||||
return Convert.ToHexString(hashBytes).ToLowerInvariant();
|
||||
}
|
||||
|
||||
private static bool TryGetPropertyIgnoreCase(JsonElement node, string propertyName, out JsonElement value)
|
||||
{
|
||||
if (node.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
foreach (var property in node.EnumerateObject())
|
||||
{
|
||||
if (string.Equals(property.Name, propertyName, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
value = property.Value;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
value = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static string? ReadStringIgnoreCase(JsonElement node, string propertyName)
|
||||
{
|
||||
return TryGetPropertyIgnoreCase(node, propertyName, out var value)
|
||||
? value.ValueKind == JsonValueKind.String
|
||||
? value.GetString()
|
||||
: value.ToString()
|
||||
: null;
|
||||
}
|
||||
|
||||
private static byte[]? ReadByteArrayIgnoreCase(JsonElement node, string propertyName)
|
||||
{
|
||||
if (!TryGetPropertyIgnoreCase(node, propertyName, out var value))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return ReadByteArray(value);
|
||||
}
|
||||
|
||||
private static byte[]? ReadByteArray(JsonElement value)
|
||||
{
|
||||
switch (value.ValueKind)
|
||||
{
|
||||
case JsonValueKind.String:
|
||||
{
|
||||
var text = value.GetString()?.Trim();
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (IsHexString(text))
|
||||
{
|
||||
try
|
||||
{
|
||||
return Convert.FromHexString(text);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// fall through to base64
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return Convert.FromBase64String(text);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
case JsonValueKind.Array:
|
||||
{
|
||||
var bytes = new List<byte>();
|
||||
foreach (var item in value.EnumerateArray())
|
||||
{
|
||||
if (!item.TryGetInt32(out var number) || number is < byte.MinValue or > byte.MaxValue)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
bytes.Add((byte)number);
|
||||
}
|
||||
|
||||
return bytes.ToArray();
|
||||
}
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsHexString(string value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value) || value.Length % 2 != 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var ch in value)
|
||||
{
|
||||
if (!Uri.IsHexDigit(ch))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private sealed record PdcDownloadEntry(
|
||||
string ComponentId,
|
||||
string RelativePath,
|
||||
string DownloadUrl,
|
||||
string ObjectHashHex);
|
||||
|
||||
private sealed record PdcDownloadedObjectInfo(
|
||||
string ComponentId,
|
||||
string RelativePath,
|
||||
string SourceUrl,
|
||||
string ObjectHashHex,
|
||||
string LocalPath);
|
||||
|
||||
private sealed record PdcUpdateState(
|
||||
string VersionText,
|
||||
string DistributionId,
|
||||
string ChannelId,
|
||||
string SubChannel,
|
||||
string FileMapPath,
|
||||
string FileMapSignaturePath,
|
||||
string ObjectsDirectory,
|
||||
DateTimeOffset DownloadedAtUtc,
|
||||
string FileMapJson,
|
||||
string FileMapSignature,
|
||||
IReadOnlyList<PdcDownloadedObjectInfo> Objects);
|
||||
|
||||
private static bool TryResolveDeltaAssets(
|
||||
IReadOnlyList<GitHubReleaseAsset> assets,
|
||||
out GitHubReleaseAsset manifestAsset,
|
||||
@@ -327,6 +776,11 @@ public sealed class UpdateWorkflowService
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(checkResult);
|
||||
|
||||
if (checkResult.PdcPayload is not null)
|
||||
{
|
||||
return await DownloadDeltaUpdateAsync(checkResult, progress, cancellationToken);
|
||||
}
|
||||
|
||||
if (!checkResult.Success || !checkResult.IsUpdateAvailable || checkResult.Release is null || checkResult.PreferredAsset is null)
|
||||
{
|
||||
return new UpdateDownloadResult(false, null, "No compatible update asset is available.");
|
||||
@@ -365,9 +819,9 @@ public sealed class UpdateWorkflowService
|
||||
{
|
||||
PendingUpdateInstallerPath = result.FilePath ?? destinationPath,
|
||||
PendingUpdateVersion = checkResult.LatestVersionText,
|
||||
PendingUpdatePublishedAtUtcMs = checkResult.Release.PublishedAt == DateTimeOffset.MinValue
|
||||
? null
|
||||
: checkResult.Release.PublishedAt.ToUnixTimeMilliseconds(),
|
||||
PendingUpdatePublishedAtUtcMs = checkResult.Release?.PublishedAt is DateTimeOffset publishedAt && publishedAt != DateTimeOffset.MinValue
|
||||
? publishedAt.ToUnixTimeMilliseconds()
|
||||
: null,
|
||||
LastUpdateCheckUtcMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
|
||||
PendingUpdateSha256 = result.ActualHash
|
||||
});
|
||||
@@ -383,6 +837,12 @@ public sealed class UpdateWorkflowService
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(checkResult);
|
||||
|
||||
if (checkResult.PdcPayload is not null)
|
||||
{
|
||||
ClearPendingUpdate();
|
||||
return await DownloadDeltaUpdateAsync(checkResult, progress, cancellationToken);
|
||||
}
|
||||
|
||||
if (!checkResult.Success || !checkResult.IsUpdateAvailable || checkResult.Release is null || checkResult.PreferredAsset is null)
|
||||
{
|
||||
return new UpdateDownloadResult(false, null, "No compatible update asset is available.");
|
||||
@@ -426,9 +886,9 @@ public sealed class UpdateWorkflowService
|
||||
{
|
||||
PendingUpdateInstallerPath = result.FilePath ?? destinationPath,
|
||||
PendingUpdateVersion = checkResult.LatestVersionText,
|
||||
PendingUpdatePublishedAtUtcMs = checkResult.Release.PublishedAt == DateTimeOffset.MinValue
|
||||
? null
|
||||
: checkResult.Release.PublishedAt.ToUnixTimeMilliseconds(),
|
||||
PendingUpdatePublishedAtUtcMs = checkResult.Release?.PublishedAt is DateTimeOffset publishedAt && publishedAt != DateTimeOffset.MinValue
|
||||
? publishedAt.ToUnixTimeMilliseconds()
|
||||
: null,
|
||||
LastUpdateCheckUtcMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
|
||||
PendingUpdateSha256 = result.ActualHash
|
||||
});
|
||||
@@ -449,9 +909,27 @@ public sealed class UpdateWorkflowService
|
||||
|
||||
if (!File.Exists(pending.InstallerPath))
|
||||
{
|
||||
if (IsPendingDeltaUpdate())
|
||||
{
|
||||
var pdcUpdatePath = pending.InstallerPath;
|
||||
var pdcFileMapPath = Path.Combine(Path.GetDirectoryName(pdcUpdatePath) ?? string.Empty, PdcFileMapName);
|
||||
var pdcSignaturePath = Path.Combine(Path.GetDirectoryName(pdcUpdatePath) ?? string.Empty, PdcFileMapSignatureName);
|
||||
if (File.Exists(pdcUpdatePath) && File.Exists(pdcFileMapPath) && File.Exists(pdcSignaturePath))
|
||||
{
|
||||
return new UpdateVerifyResult(true, true, null, null, null);
|
||||
}
|
||||
|
||||
return new UpdateVerifyResult(false, false, null, null, "PDC update payload is incomplete.");
|
||||
}
|
||||
|
||||
return new UpdateVerifyResult(false, false, null, null, "Installer file does not exist.");
|
||||
}
|
||||
|
||||
if (IsPendingDeltaUpdate())
|
||||
{
|
||||
return new UpdateVerifyResult(true, true, null, null, null);
|
||||
}
|
||||
|
||||
var expectedHash = pending.Sha256;
|
||||
var actualHash = await GitHubReleaseUpdateService.ComputeFileSha256Async(pending.InstallerPath);
|
||||
|
||||
@@ -483,7 +961,7 @@ public sealed class UpdateWorkflowService
|
||||
{
|
||||
// Always check for updates on startup (removed AutoCheckUpdates check)
|
||||
var result = await CheckForUpdatesAsync(currentVersion, isForce: false, cancellationToken);
|
||||
if (!result.Success || !result.IsUpdateAvailable || result.Release is null)
|
||||
if (!result.Success || !result.IsUpdateAvailable || (result.Release is null && result.PdcPayload is null))
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -495,7 +973,7 @@ public sealed class UpdateWorkflowService
|
||||
string.Equals(normalizedMode, UpdateSettingsValues.ModeSilentOnExit, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
// Prefer delta update if available (smaller download, faster)
|
||||
if (IsDeltaUpdateAvailable(result.Release))
|
||||
if (IsDeltaUpdateAvailable(result))
|
||||
{
|
||||
AppLogger.Info("UpdateWorkflow", "Delta update available, downloading incremental package.");
|
||||
await DownloadDeltaUpdateAsync(result, cancellationToken: cancellationToken);
|
||||
@@ -519,6 +997,14 @@ public sealed class UpdateWorkflowService
|
||||
|
||||
public UpdateInstallerLaunchResult LaunchPendingInstallerNow()
|
||||
{
|
||||
if (IsPendingDeltaUpdate())
|
||||
{
|
||||
var launchResult = LaunchLauncherForApplyUpdate();
|
||||
return launchResult
|
||||
? new UpdateInstallerLaunchResult(true, false, null)
|
||||
: new UpdateInstallerLaunchResult(false, false, "Failed to launch updater for incremental update.");
|
||||
}
|
||||
|
||||
return LaunchPendingInstaller(silent: false, exitApplicationAfterLaunch: true);
|
||||
}
|
||||
|
||||
|
||||
31
phainon.yml
31
phainon.yml
@@ -1,7 +1,5 @@
|
||||
# Phainon Distribution Center (PDC) publish configuration
|
||||
# This file is intentionally conservative: Launcher remains installer/rollback authority.
|
||||
# Phainon Distribution Center Client Configuration
|
||||
name: "LanMountainDesktop"
|
||||
|
||||
components:
|
||||
app:
|
||||
allowDiffUpdate: true
|
||||
@@ -13,17 +11,22 @@ components:
|
||||
includes:
|
||||
- "**"
|
||||
excludes:
|
||||
- "app-*/**"
|
||||
- ".launcher/update/incoming/**"
|
||||
- "files.json"
|
||||
- "files.json.sig"
|
||||
- "update.zip"
|
||||
|
||||
- "app*/**"
|
||||
- "files*.json"
|
||||
- "files*.json.sig"
|
||||
- "update*.zip"
|
||||
variables:
|
||||
number: 0
|
||||
fileRepoRoot: "__FILE_REPO_ROOT__"
|
||||
archiveRoot: "__ARCHIVE_ROOT__/$(primaryVersion)/$(version)/"
|
||||
bucketKeyRoot: "lanmountain/update/repo/"
|
||||
archiveBucketKeyRoot: "lanmountain/update/archive/$(primaryVersion)/$(version)/"
|
||||
appChangeLogPath: "$(thisFileDir)/../CHANGELOG.md"
|
||||
appChangeLogTemplate: |
|
||||
$(changeLog)
|
||||
|
||||
# Replace these roots in CI/CD or environment-specific templates when enabling PDCC publish.
|
||||
fileRepoRoot: "https://example.invalid/lanmountain/distribution-v1/repo/"
|
||||
archiveRoot: "https://example.invalid/lanmountain/distribution-v1/$(primaryVersion)/$(version)/"
|
||||
bucketKeyRoot: "lanmountain/distribution-v1/repo/"
|
||||
archiveBucketKeyRoot: "lanmountain/distribution-v1/$(primaryVersion)/$(version)/"
|
||||
---
|
||||
|
||||
## Checksums And Downloads
|
||||
|
||||
$(hashes)
|
||||
|
||||
97
scripts/Install-Pdcc.ps1
Normal file
97
scripts/Install-Pdcc.ps1
Normal file
@@ -0,0 +1,97 @@
|
||||
param(
|
||||
[string]$Repository = "ClassIsland/PhainonDistributionCenter",
|
||||
[string]$AssetName = "out_app_linux_x64.zip",
|
||||
[string]$Version = "",
|
||||
[string]$OutputDir = (Join-Path $PSScriptRoot "..\pdcc")
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($Repository)) {
|
||||
throw "Repository is required."
|
||||
}
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($AssetName)) {
|
||||
throw "AssetName is required."
|
||||
}
|
||||
|
||||
$OutputDir = [System.IO.Path]::GetFullPath($OutputDir)
|
||||
if (-not (Test-Path -LiteralPath $OutputDir)) {
|
||||
New-Item -ItemType Directory -Path $OutputDir -Force | Out-Null
|
||||
}
|
||||
|
||||
$clientName = if ($env:OS -eq "Windows_NT") { "PhainonDistributionCenter.Client.exe" } else { "PhainonDistributionCenter.Client" }
|
||||
$clientPath = Join-Path $OutputDir $clientName
|
||||
if (Test-Path -LiteralPath $clientPath) {
|
||||
Write-Host "PDCC client already installed at $clientPath"
|
||||
return
|
||||
}
|
||||
|
||||
$releaseTag = $Version
|
||||
if ([string]::IsNullOrWhiteSpace($releaseTag)) {
|
||||
$releaseTag = $env:PDC_CLIENT_VERSION
|
||||
}
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($releaseTag)) {
|
||||
$releaseTag = $env:PDCC_VERSION
|
||||
}
|
||||
|
||||
$tempDir = Join-Path $env:RUNNER_TEMP "pdcc-install"
|
||||
if (Test-Path -LiteralPath $tempDir) {
|
||||
Remove-Item -LiteralPath $tempDir -Recurse -Force
|
||||
}
|
||||
New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
|
||||
|
||||
$zipPath = Join-Path $tempDir $AssetName
|
||||
|
||||
if (Get-Command gh -ErrorAction SilentlyContinue) {
|
||||
Write-Host "Downloading PDCC via gh release download from $Repository ..."
|
||||
$ghArgs = @("release", "download", "--repo", $Repository, "--pattern", $AssetName, "--dir", $tempDir, "--clobber")
|
||||
if (-not [string]::IsNullOrWhiteSpace($releaseTag)) {
|
||||
$ghArgs = @("release", "download", $releaseTag, "--repo", $Repository, "--pattern", $AssetName, "--dir", $tempDir, "--clobber")
|
||||
}
|
||||
|
||||
& gh @ghArgs
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "gh release download failed for $Repository/$AssetName."
|
||||
}
|
||||
}
|
||||
else {
|
||||
if ([string]::IsNullOrWhiteSpace($releaseTag)) {
|
||||
throw "PDCC_VERSION is required when gh is unavailable."
|
||||
}
|
||||
|
||||
$downloadUrl = "https://github.com/$Repository/releases/download/$releaseTag/$AssetName"
|
||||
Write-Host "Downloading PDCC from $downloadUrl ..."
|
||||
Invoke-WebRequest -Uri $downloadUrl -OutFile $zipPath
|
||||
}
|
||||
|
||||
$extractDir = Join-Path $tempDir "extract"
|
||||
if (Test-Path -LiteralPath $extractDir) {
|
||||
Remove-Item -LiteralPath $extractDir -Recurse -Force
|
||||
}
|
||||
New-Item -ItemType Directory -Path $extractDir -Force | Out-Null
|
||||
Expand-Archive -LiteralPath $zipPath -DestinationPath $extractDir -Force
|
||||
|
||||
$copied = $false
|
||||
foreach ($file in Get-ChildItem -LiteralPath $extractDir -Recurse -File) {
|
||||
if ($file.Name -ieq $clientName) {
|
||||
Copy-Item -LiteralPath $file.FullName -Destination $clientPath -Force
|
||||
$copied = $true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (-not $copied) {
|
||||
throw "PDCC client executable not found in downloaded archive."
|
||||
}
|
||||
|
||||
if ($IsLinux) {
|
||||
try {
|
||||
chmod +x $clientPath | Out-Null
|
||||
}
|
||||
catch {
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "PDCC installed to $clientPath"
|
||||
59
scripts/Prepare-PdccOut.ps1
Normal file
59
scripts/Prepare-PdccOut.ps1
Normal file
@@ -0,0 +1,59 @@
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$SourceDir,
|
||||
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$OutputDir,
|
||||
|
||||
[string]$PlatformKey = "",
|
||||
|
||||
[string[]]$InstallerFiles = @()
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
$SourceDir = [System.IO.Path]::GetFullPath($SourceDir)
|
||||
$OutputDir = [System.IO.Path]::GetFullPath($OutputDir)
|
||||
|
||||
if (-not (Test-Path -LiteralPath $SourceDir)) {
|
||||
throw "Source directory not found: $SourceDir"
|
||||
}
|
||||
|
||||
if (Test-Path -LiteralPath $OutputDir) {
|
||||
Remove-Item -LiteralPath $OutputDir -Recurse -Force
|
||||
}
|
||||
New-Item -ItemType Directory -Path $OutputDir -Force | Out-Null
|
||||
|
||||
$payloadRoot = if ([string]::IsNullOrWhiteSpace($PlatformKey)) {
|
||||
$OutputDir
|
||||
} else {
|
||||
Join-Path $OutputDir $PlatformKey
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Path $payloadRoot -Force | Out-Null
|
||||
Get-ChildItem -LiteralPath $SourceDir -Force | ForEach-Object {
|
||||
Copy-Item -LiteralPath $_.FullName -Destination $payloadRoot -Recurse -Force
|
||||
}
|
||||
|
||||
if ($InstallerFiles.Count -gt 0) {
|
||||
$installerRoot = Join-Path $OutputDir "installers"
|
||||
if (-not (Test-Path -LiteralPath $installerRoot)) {
|
||||
New-Item -ItemType Directory -Path $installerRoot -Force | Out-Null
|
||||
}
|
||||
|
||||
foreach ($installer in $InstallerFiles) {
|
||||
if ([string]::IsNullOrWhiteSpace($installer)) {
|
||||
continue
|
||||
}
|
||||
|
||||
$installerPath = [System.IO.Path]::GetFullPath($installer)
|
||||
if (-not (Test-Path -LiteralPath $installerPath)) {
|
||||
throw "Installer file not found: $installerPath"
|
||||
}
|
||||
|
||||
$targetPath = Join-Path $installerRoot ([System.IO.Path]::GetFileName($installerPath))
|
||||
Copy-Item -LiteralPath $installerPath -Destination $targetPath -Force
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "Prepared PDCC staging directory: $payloadRoot"
|
||||
206
scripts/pdc-mock-server.py
Normal file
206
scripts/pdc-mock-server.py
Normal file
@@ -0,0 +1,206 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
from datetime import datetime, timezone
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _utc_now_text() -> str:
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
class PdcMockHandler(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
token = ""
|
||||
data_dir = Path(".")
|
||||
|
||||
def _write_json(self, status_code: int, payload: dict) -> None:
|
||||
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
self.send_response(status_code)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Connection", "close")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
self.wfile.flush()
|
||||
self.close_connection = True
|
||||
|
||||
def handle_expect_100(self) -> bool:
|
||||
self.send_response_only(100)
|
||||
self.end_headers()
|
||||
return True
|
||||
|
||||
def _read_chunked_body(self) -> bytes:
|
||||
chunks = bytearray()
|
||||
while True:
|
||||
size_line = self.rfile.readline()
|
||||
if not size_line:
|
||||
break
|
||||
|
||||
size_line = size_line.strip()
|
||||
if not size_line:
|
||||
continue
|
||||
|
||||
size_text = size_line.split(b";", 1)[0]
|
||||
chunk_size = int(size_text, 16)
|
||||
if chunk_size == 0:
|
||||
# Consume optional trailer headers until the terminating blank line.
|
||||
while True:
|
||||
trailer = self.rfile.readline()
|
||||
if trailer in (b"", b"\r\n", b"\n"):
|
||||
break
|
||||
break
|
||||
|
||||
remaining = chunk_size
|
||||
while remaining > 0:
|
||||
part = self.rfile.read(remaining)
|
||||
if not part:
|
||||
raise ConnectionError("unexpected end of stream while reading chunked request body")
|
||||
chunks.extend(part)
|
||||
remaining -= len(part)
|
||||
|
||||
chunk_terminator = self.rfile.read(2)
|
||||
if chunk_terminator == b"\r\n":
|
||||
continue
|
||||
if chunk_terminator[:1] != b"\n":
|
||||
raise ValueError("invalid chunk terminator")
|
||||
|
||||
return bytes(chunks)
|
||||
|
||||
def _read_request_body(self) -> bytes:
|
||||
transfer_encoding = (self.headers.get("Transfer-Encoding") or "").lower()
|
||||
if "chunked" in transfer_encoding:
|
||||
return self._read_chunked_body()
|
||||
|
||||
length = int(self.headers.get("Content-Length", "0"))
|
||||
if length <= 0:
|
||||
return b""
|
||||
return self.rfile.read(length)
|
||||
|
||||
def _read_json_body(self) -> tuple[dict, bytes]:
|
||||
raw = self._read_request_body()
|
||||
if not raw:
|
||||
return {}, raw
|
||||
try:
|
||||
return json.loads(raw.decode("utf-8")), raw
|
||||
except Exception:
|
||||
return {}, raw
|
||||
|
||||
def _save_payload(self, name: str, payload: dict, raw_body: bytes) -> None:
|
||||
out = self.data_dir / f"{name}.json"
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"savedAtUtc": _utc_now_text(),
|
||||
"path": self.path,
|
||||
"method": self.command,
|
||||
"headers": {key: value for key, value in self.headers.items()},
|
||||
"rawBodyLength": len(raw_body),
|
||||
"rawBodyPreview": raw_body[:4096].decode("utf-8", errors="replace"),
|
||||
"payload": payload,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
def _check_token(self) -> bool:
|
||||
expected = (self.token or "").strip()
|
||||
if not expected:
|
||||
return True
|
||||
provided = (self.headers.get("X-PDC-Token") or "").strip()
|
||||
return provided == expected
|
||||
|
||||
def do_GET(self) -> None:
|
||||
if self.path == "/healthz":
|
||||
self._write_json(200, {"ok": True, "timeUtc": _utc_now_text()})
|
||||
return
|
||||
|
||||
self._write_json(404, {"error": "not_found", "path": self.path})
|
||||
|
||||
def do_POST(self) -> None:
|
||||
print(
|
||||
f"[pdc-mock] {self.command} {self.path} "
|
||||
f"content-length={self.headers.get('Content-Length', '')} "
|
||||
f"transfer-encoding={self.headers.get('Transfer-Encoding', '')} "
|
||||
f"expect={self.headers.get('Expect', '')}"
|
||||
)
|
||||
|
||||
if not self._check_token():
|
||||
self._write_json(401, {"error": "unauthorized"})
|
||||
return
|
||||
|
||||
payload, raw_body = self._read_json_body()
|
||||
|
||||
if self.path == "/api/v1/fileMaps/diff":
|
||||
items = payload.get("items") if isinstance(payload, dict) else {}
|
||||
keys = sorted(items.keys()) if isinstance(items, dict) else []
|
||||
self._save_payload("filemaps-diff-request", payload, raw_body)
|
||||
# CI fallback mode: return empty diff to avoid long object uploads
|
||||
# against a local mock endpoint. Real PDC endpoint will return
|
||||
# actual missing object hashes.
|
||||
result = {
|
||||
"success": True,
|
||||
"code": 0,
|
||||
"message": "ok",
|
||||
"content": [],
|
||||
"Content": [],
|
||||
"requestedCount": len(keys),
|
||||
}
|
||||
self._write_json(200, result)
|
||||
return
|
||||
|
||||
if self.path == "/api/v1/fileMaps/upload":
|
||||
self._save_payload("filemaps-upload-request", payload, raw_body)
|
||||
result = {
|
||||
"success": True,
|
||||
"code": 0,
|
||||
"message": "ok",
|
||||
"content": True,
|
||||
"Content": True,
|
||||
}
|
||||
self._write_json(200, result)
|
||||
return
|
||||
|
||||
m = re.match(r"^/api/v1/distribution/([^/]+)/([^/]+)$", self.path)
|
||||
if m:
|
||||
primary_version = m.group(1)
|
||||
version = m.group(2)
|
||||
self._save_payload("distribution-request", payload, raw_body)
|
||||
result = {
|
||||
"success": True,
|
||||
"code": 0,
|
||||
"message": "ok",
|
||||
}
|
||||
self._write_json(200, result)
|
||||
return
|
||||
|
||||
self._write_json(404, {"error": "not_found", "path": self.path})
|
||||
|
||||
def log_message(self, fmt: str, *args) -> None:
|
||||
print(f"[pdc-mock] {self.address_string()} - {fmt % args}")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="PDC mock server for CI fallback")
|
||||
parser.add_argument("--host", default="127.0.0.1")
|
||||
parser.add_argument("--port", type=int, default=18765)
|
||||
parser.add_argument("--token", default="")
|
||||
parser.add_argument("--data-dir", required=True)
|
||||
args = parser.parse_args()
|
||||
|
||||
PdcMockHandler.token = args.token
|
||||
PdcMockHandler.data_dir = Path(args.data_dir)
|
||||
PdcMockHandler.data_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
server = ThreadingHTTPServer((args.host, args.port), PdcMockHandler)
|
||||
print(f"[pdc-mock] listening on http://{args.host}:{args.port}")
|
||||
server.serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user