mirror of
https://github.com/wwiinnddyy/LanMountainDesktop.git
synced 2026-06-26 03:44:25 +08:00
Compare commits
27 Commits
v0.8.5.2
...
d31aa90b9c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d31aa90b9c | ||
|
|
0878bcab5a | ||
|
|
4d5bea0c46 | ||
|
|
8323b8cb61 | ||
|
|
82f1e77393 | ||
|
|
a31ae3cd58 | ||
|
|
3f927c41c8 | ||
|
|
44725d7ff3 | ||
|
|
e623aef350 | ||
|
|
63d5165860 | ||
|
|
6d513096d3 | ||
|
|
f487a32149 | ||
|
|
a553f2f7aa | ||
|
|
f03b74ff32 | ||
|
|
bc1520a5d8 | ||
|
|
46341edbea | ||
|
|
f421f574e1 | ||
|
|
8ea8c684a9 | ||
|
|
b411d91b35 | ||
|
|
a2f0af9031 | ||
|
|
5861d73964 | ||
|
|
64975d5752 | ||
|
|
8c58b1c43e | ||
|
|
e82c5d41fd | ||
|
|
8447910fee | ||
|
|
81e0081721 | ||
|
|
fb21bcd8ec |
370
.github/workflows/release.yml
vendored
370
.github/workflows/release.yml
vendored
@@ -1,4 +1,4 @@
|
||||
name: Release
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
@@ -127,7 +127,7 @@ jobs:
|
||||
exit 1
|
||||
}
|
||||
|
||||
# 鏄剧ず鍙戝竷缁撴灉
|
||||
# 閺勫墽銇氶崣鎴濈缂佹挻鐏?
|
||||
Write-Host "Launcher published to: $launcherPublishDir"
|
||||
$exeFile = Get-ChildItem -Path $launcherPublishDir -Filter "*.exe" | Select-Object -First 1
|
||||
if ($exeFile) {
|
||||
@@ -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,154 @@ 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
|
||||
|
||||
publish-plonds:
|
||||
needs: [ prepare, build-windows, build-linux ]
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
VERSION: ${{ needs.prepare.outputs.version }}
|
||||
S3_ENDPOINT: ${{ vars.S3_ENDPOINT }}
|
||||
S3_BUCKET: ${{ vars.S3_BUCKET }}
|
||||
S3_REGION: ${{ vars.S3_REGION }}
|
||||
UPDATE_PRIVATE_KEY_PEM: ${{ secrets.UPDATE_PRIVATE_KEY_PEM }}
|
||||
PLONDS_SIGNING_KEY: ${{ secrets.PLONDS_SIGNING_KEY }}
|
||||
PDC_SIGNING_KEY: ${{ secrets.PDC_SIGNING_KEY }}
|
||||
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"
|
||||
AWS_REQUEST_CHECKSUM_CALCULATION: "WHEN_REQUIRED"
|
||||
AWS_RESPONSE_CHECKSUM_VALIDATION: "WHEN_REQUIRED"
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup .NET
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: ${{ env.DOTNET_VERSION }}
|
||||
dotnet-quality: 'preview'
|
||||
|
||||
- name: Download app payload artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: artifacts/app-payload
|
||||
pattern: app-payload-*
|
||||
|
||||
- name: Download installer artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: artifacts/installers
|
||||
pattern: installer-*
|
||||
|
||||
- name: Prepare signing key
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
function Test-PemKey {
|
||||
param([string]$PemText)
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($PemText)) {
|
||||
return $false
|
||||
}
|
||||
|
||||
$rsa = [System.Security.Cryptography.RSA]::Create()
|
||||
try {
|
||||
$rsa.ImportFromPem($PemText)
|
||||
return $true
|
||||
}
|
||||
catch {
|
||||
return $false
|
||||
}
|
||||
finally {
|
||||
$rsa.Dispose()
|
||||
}
|
||||
}
|
||||
|
||||
$candidates = @(
|
||||
$env:PLONDS_SIGNING_KEY,
|
||||
$env:UPDATE_PRIVATE_KEY_PEM,
|
||||
$env:PDC_SIGNING_KEY
|
||||
)
|
||||
|
||||
$key = $null
|
||||
foreach ($candidate in $candidates) {
|
||||
if (Test-PemKey $candidate) {
|
||||
$key = $candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($key)) {
|
||||
throw "Missing a valid PEM signing key in PLONDS_SIGNING_KEY, UPDATE_PRIVATE_KEY_PEM, or PDC_SIGNING_KEY."
|
||||
}
|
||||
|
||||
$keyPath = Join-Path $PWD "update-private-key.pem"
|
||||
[System.IO.File]::WriteAllText($keyPath, $key, [System.Text.Encoding]::ASCII)
|
||||
Add-Content -Path $env:GITHUB_ENV -Value "UPDATE_PRIVATE_KEY_PATH=$keyPath"
|
||||
|
||||
- name: Probe S3 access
|
||||
if: ${{ env.S3_ENDPOINT != '' && env.S3_BUCKET != '' && env.S3_ACCESS_KEY != '' && env.S3_SECRET_KEY != '' }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
aws --version
|
||||
aws --endpoint-url "$S3_ENDPOINT" --region "$S3_REGION" s3 ls "s3://$S3_BUCKET" >/dev/null
|
||||
echo "S3 access probe succeeded for $S3_BUCKET"
|
||||
|
||||
- name: Build PLONDS assets
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
./scripts/Publish-Plonds.ps1 `
|
||||
-Version $env:VERSION `
|
||||
-AppArtifactsRoot (Join-Path $PWD "artifacts/app-payload") `
|
||||
-InstallerArtifactsRoot (Join-Path $PWD "artifacts/installers") `
|
||||
-OutputDir (Join-Path $PWD "plonds-output") `
|
||||
-PrivateKeyPath $env:UPDATE_PRIVATE_KEY_PATH `
|
||||
-Channel "stable" `
|
||||
-S3Endpoint $env:S3_ENDPOINT `
|
||||
-S3Bucket $env:S3_BUCKET `
|
||||
-S3Region $env:S3_REGION
|
||||
|
||||
- name: Upload PLONDS assets
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: plonds-assets
|
||||
path: |
|
||||
plonds-output/release-assets/**
|
||||
plonds-output/published/**
|
||||
if-no-files-found: error
|
||||
retention-days: 90
|
||||
github-release:
|
||||
needs: [ prepare, build-windows, build-linux, build-macos ]
|
||||
needs: [ prepare, build-windows, build-linux, build-macos, publish-plonds ]
|
||||
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 PLONDS artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: artifacts/plonds
|
||||
pattern: plonds-assets
|
||||
|
||||
- name: List artifacts structure
|
||||
run: |
|
||||
@@ -892,10 +871,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/plonds -type f \( -name "files-*.json" -o -name "files-*.json.sig" -o -name "update-*.zip" -o -name "plonds-*.json" -o -name "plonds-*.json.sig" \) -exec cp -v {} release-files/ \;
|
||||
echo ""
|
||||
echo "Files ready for release:"
|
||||
ls -lh release-files/ || echo "No files found in release-files"
|
||||
@@ -908,44 +885,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:
|
||||
@@ -967,12 +906,12 @@ jobs:
|
||||
|
||||
Installation: Double-click the .exe file and follow the wizard.
|
||||
|
||||
### Incremental Update Assets
|
||||
### Incremental Update Assets`n - **plonds-filemap-windows-x64.json / plonds-filemap-windows-x64.json.sig**`n - **plonds-filemap-windows-x86.json / plonds-filemap-windows-x86.json.sig**`n - **plonds-filemap-linux-x64.json / plonds-filemap-linux-x64.json.sig**`n`n ### Legacy Fallback Assets
|
||||
- **files-windows-x64.json / files-windows-x64.json.sig / update-windows-x64.zip**
|
||||
- **files-windows-x86.json / files-windows-x86.json.sig / update-windows-x86.zip**
|
||||
- **files-linux-x64.json / files-linux-x64.json.sig / update-linux-x64.zip**
|
||||
|
||||
Existing users: Launcher will detect platform-matching signed assets and apply update on next startup.
|
||||
Existing users: Host will prefer staged PLONDS payloads and keep the Launcher responsible for apply + rollback. Legacy signed file-map assets remain attached as a fallback path.
|
||||
|
||||
### Linux
|
||||
- **LanMountainDesktop-${{ needs.prepare.outputs.version }}-linux-x64.deb** - Debian package (x64)
|
||||
@@ -983,3 +922,4 @@ jobs:
|
||||
|
||||
See commits for changes.
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
|
||||
@@ -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(PlondsUpdateMetadata))]
|
||||
[JsonSerializable(typeof(PlondsFileMap))]
|
||||
[JsonSerializable(typeof(PlondsComponentEntry))]
|
||||
[JsonSerializable(typeof(PlondsFileEntry))]
|
||||
[JsonSerializable(typeof(PlondsHashDescriptor))]
|
||||
[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 PlondsUpdateMetadata
|
||||
{
|
||||
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 PlondsFileMap
|
||||
{
|
||||
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<PlondsComponentEntry> Components { get; set; } = [];
|
||||
|
||||
public List<PlondsFileEntry> Files { get; set; } = [];
|
||||
}
|
||||
|
||||
internal sealed class PlondsComponentEntry
|
||||
{
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
public string? Version { get; set; }
|
||||
|
||||
public Dictionary<string, string> Metadata { get; set; } = [];
|
||||
|
||||
public List<PlondsFileEntry> Files { get; set; } = [];
|
||||
}
|
||||
|
||||
internal sealed class PlondsFileEntry
|
||||
{
|
||||
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 PlondsHashDescriptor? Hash { get; set; }
|
||||
|
||||
public Dictionary<string, string> Metadata { get; set; } = [];
|
||||
}
|
||||
|
||||
internal sealed class PlondsHashDescriptor
|
||||
{
|
||||
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,
|
||||
PlondsUpdatePayload? PlondsPayload = null);
|
||||
|
||||
public sealed record PlondsUpdatePayload(
|
||||
string DistributionId,
|
||||
string ChannelId,
|
||||
string SubChannel,
|
||||
string? FileMapJson,
|
||||
string? FileMapSignature,
|
||||
string? FileMapJsonUrl,
|
||||
string? FileMapSignatureUrl);
|
||||
|
||||
public sealed record UpdateDownloadResult(
|
||||
bool Success,
|
||||
|
||||
@@ -11,15 +11,17 @@ using System.Threading.Tasks;
|
||||
namespace LanMountainDesktop.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Best-effort PDC client that maps PDC responses to the existing update result model.
|
||||
/// This keeps launcher update contracts stable while allowing a gradual migration.
|
||||
/// Thin PLONDS client used by the host app.
|
||||
/// The host keeps responsibility for checking and downloading updates; Launcher only applies staged payloads.
|
||||
/// </summary>
|
||||
public sealed class PdcReleaseUpdateService : IDisposable
|
||||
public sealed class PlondsReleaseUpdateService : IDisposable
|
||||
{
|
||||
private const string DefaultApiBasePath = "/api/plonds/v1";
|
||||
|
||||
private readonly HttpClient _httpClient;
|
||||
private readonly bool _ownsHttpClient;
|
||||
|
||||
public PdcReleaseUpdateService(HttpClient? httpClient = null)
|
||||
public PlondsReleaseUpdateService(HttpClient? httpClient = null)
|
||||
{
|
||||
if (httpClient is null)
|
||||
{
|
||||
@@ -79,25 +81,40 @@ public sealed class PdcReleaseUpdateService : IDisposable
|
||||
LatestVersionText: "-",
|
||||
Release: null,
|
||||
PreferredAsset: null,
|
||||
ErrorMessage: "PDC endpoint is not configured.",
|
||||
ErrorMessage: "PLONDS endpoint is not configured.",
|
||||
ForceMode: isForce);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var metadataUrl = BuildUri(endpoint, "api/v1/public/distributions/metadata");
|
||||
var metadata = await GetContentNodeAsync(metadataUrl, cancellationToken).ConfigureAwait(false);
|
||||
var apiBasePath = ResolveApiBasePath();
|
||||
var metadataUrl = BuildApiUrl(endpoint, apiBasePath, "metadata");
|
||||
var metadata = await GetJsonNodeAsync(metadataUrl, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var channelId = ResolveChannelId(metadata, includePrerelease);
|
||||
if (string.IsNullOrWhiteSpace(channelId))
|
||||
{
|
||||
channelId = includePrerelease ? "preview" : "stable";
|
||||
}
|
||||
|
||||
var latestUrl = BuildUri(
|
||||
var channelId = ResolveChannelId(includePrerelease);
|
||||
var platform = ResolvePlatform();
|
||||
var latestUrl = BuildApiUrl(
|
||||
endpoint,
|
||||
$"api/v1/public/distributions/latest/{Uri.EscapeDataString(channelId)}?appVersion={Uri.EscapeDataString(normalizedCurrentVersionText)}");
|
||||
var latestNode = await GetContentNodeAsync(latestUrl, cancellationToken).ConfigureAwait(false);
|
||||
apiBasePath,
|
||||
$"channels/{Uri.EscapeDataString(channelId)}/{Uri.EscapeDataString(platform)}/latest?currentVersion={Uri.EscapeDataString(normalizedCurrentVersionText)}");
|
||||
|
||||
JsonElement latestNode;
|
||||
try
|
||||
{
|
||||
latestNode = await GetJsonNodeAsync(latestUrl, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (InvalidOperationException ex) when (ex.Message.StartsWith("HTTP 204", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return new UpdateCheckResult(
|
||||
Success: true,
|
||||
IsUpdateAvailable: false,
|
||||
CurrentVersionText: normalizedCurrentVersionText,
|
||||
LatestVersionText: normalizedCurrentVersionText,
|
||||
Release: null,
|
||||
PreferredAsset: null,
|
||||
ErrorMessage: null,
|
||||
ForceMode: isForce);
|
||||
}
|
||||
|
||||
var latestVersionText = ReadString(latestNode, "version") ?? "-";
|
||||
if (!TryParseVersion(latestVersionText, out var latestVersion) || latestVersion is null)
|
||||
@@ -109,7 +126,7 @@ public sealed class PdcReleaseUpdateService : IDisposable
|
||||
LatestVersionText: latestVersionText,
|
||||
Release: null,
|
||||
PreferredAsset: null,
|
||||
ErrorMessage: "PDC latest distribution version is invalid.",
|
||||
ErrorMessage: "PLONDS latest distribution version is invalid.",
|
||||
ForceMode: isForce);
|
||||
}
|
||||
|
||||
@@ -123,7 +140,7 @@ public sealed class PdcReleaseUpdateService : IDisposable
|
||||
LatestVersionText: latestVersionText,
|
||||
Release: null,
|
||||
PreferredAsset: null,
|
||||
ErrorMessage: "PDC latest distribution id is missing.",
|
||||
ErrorMessage: "PLONDS latest distribution id is missing.",
|
||||
ForceMode: isForce);
|
||||
}
|
||||
|
||||
@@ -141,14 +158,15 @@ public sealed class PdcReleaseUpdateService : IDisposable
|
||||
ForceMode: false);
|
||||
}
|
||||
|
||||
var subChannel = ResolveSubChannel();
|
||||
var distributionUrl = BuildUri(
|
||||
var distributionUrl = BuildApiUrl(
|
||||
endpoint,
|
||||
$"api/v1/public/distributions/{Uri.EscapeDataString(distributionId)}/{Uri.EscapeDataString(subChannel)}");
|
||||
var distributionNode = await GetContentNodeAsync(distributionUrl, cancellationToken).ConfigureAwait(false);
|
||||
apiBasePath,
|
||||
$"distributions/{Uri.EscapeDataString(distributionId)}");
|
||||
var distributionNode = await GetJsonNodeAsync(distributionUrl, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var assets = ResolveAssets(distributionNode);
|
||||
if (assets.Count == 0)
|
||||
var assets = ResolveInstallerAssets(distributionNode);
|
||||
var payload = ResolvePlondsPayload(distributionNode, distributionId, channelId, platform);
|
||||
if (assets.Count == 0 && !HasPlondsPayload(payload))
|
||||
{
|
||||
return new UpdateCheckResult(
|
||||
Success: false,
|
||||
@@ -157,16 +175,17 @@ public sealed class PdcReleaseUpdateService : IDisposable
|
||||
LatestVersionText: latestVersionText,
|
||||
Release: null,
|
||||
PreferredAsset: null,
|
||||
ErrorMessage: "PDC distribution response does not expose downloadable update assets.",
|
||||
ErrorMessage: "PLONDS distribution response does not expose downloadable update assets.",
|
||||
ForceMode: isForce);
|
||||
}
|
||||
|
||||
var publishedAt = ParsePublishedAt(distributionNode) ?? DateTimeOffset.UtcNow;
|
||||
var release = new GitHubReleaseInfo(
|
||||
TagName: $"v{latestVersionText}",
|
||||
Name: $"PDC Distribution {latestVersionText}",
|
||||
Name: $"PLONDS Distribution {latestVersionText}",
|
||||
IsPrerelease: includePrerelease,
|
||||
IsDraft: false,
|
||||
PublishedAt: DateTimeOffset.UtcNow,
|
||||
PublishedAt: publishedAt,
|
||||
Assets: assets);
|
||||
|
||||
return new UpdateCheckResult(
|
||||
@@ -175,9 +194,10 @@ public sealed class PdcReleaseUpdateService : IDisposable
|
||||
CurrentVersionText: normalizedCurrentVersionText,
|
||||
LatestVersionText: latestVersionText,
|
||||
Release: release,
|
||||
PreferredAsset: null,
|
||||
PreferredAsset: SelectPreferredInstallerAsset(assets),
|
||||
ErrorMessage: null,
|
||||
ForceMode: isForce);
|
||||
ForceMode: isForce,
|
||||
PlondsPayload: payload);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
@@ -192,12 +212,12 @@ public sealed class PdcReleaseUpdateService : IDisposable
|
||||
LatestVersionText: "-",
|
||||
Release: null,
|
||||
PreferredAsset: null,
|
||||
ErrorMessage: $"PDC request failed: {ex.Message}",
|
||||
ErrorMessage: $"PLONDS request failed: {ex.Message}",
|
||||
ForceMode: isForce);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<JsonElement> GetContentNodeAsync(string url, CancellationToken cancellationToken)
|
||||
private async Task<JsonElement> GetJsonNodeAsync(string url, CancellationToken cancellationToken)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, url);
|
||||
var token = ResolveToken();
|
||||
@@ -224,15 +244,39 @@ public sealed class PdcReleaseUpdateService : IDisposable
|
||||
return root.Clone();
|
||||
}
|
||||
|
||||
private static IReadOnlyList<GitHubReleaseAsset> ResolveAssets(JsonElement distributionNode)
|
||||
private static IReadOnlyList<GitHubReleaseAsset> ResolveInstallerAssets(JsonElement distributionNode)
|
||||
{
|
||||
var assets = new List<GitHubReleaseAsset>();
|
||||
if (distributionNode.ValueKind != JsonValueKind.Object)
|
||||
|
||||
if (TryGetPropertyIgnoreCase(distributionNode, "installerMirrors", out var installersNode) &&
|
||||
installersNode.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var installerNode in installersNode.EnumerateArray())
|
||||
{
|
||||
if (installerNode.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var name = ReadString(installerNode, "name");
|
||||
var url = ReadString(installerNode, "url") ?? ReadString(installerNode, "downloadUrl");
|
||||
if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(url))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var size = ReadInt64(installerNode, "size") ?? 0L;
|
||||
var sha256 = ReadString(installerNode, "sha256");
|
||||
assets.Add(new GitHubReleaseAsset(name, url, size, sha256));
|
||||
}
|
||||
}
|
||||
|
||||
if (assets.Count > 0)
|
||||
{
|
||||
return assets;
|
||||
}
|
||||
|
||||
if (distributionNode.TryGetProperty("assets", out var assetsNode) &&
|
||||
if (TryGetPropertyIgnoreCase(distributionNode, "assets", out var assetsNode) &&
|
||||
assetsNode.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var assetNode in assetsNode.EnumerateArray())
|
||||
@@ -243,9 +287,9 @@ public sealed class PdcReleaseUpdateService : IDisposable
|
||||
}
|
||||
|
||||
var name = ReadString(assetNode, "name");
|
||||
var url = ReadString(assetNode, "url") ??
|
||||
ReadString(assetNode, "downloadUrl") ??
|
||||
ReadString(assetNode, "browserDownloadUrl");
|
||||
var url = ReadString(assetNode, "url")
|
||||
?? ReadString(assetNode, "downloadUrl")
|
||||
?? ReadString(assetNode, "browserDownloadUrl");
|
||||
if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(url))
|
||||
{
|
||||
continue;
|
||||
@@ -257,91 +301,133 @@ public sealed class PdcReleaseUpdateService : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
if (assets.Count > 0)
|
||||
{
|
||||
return assets;
|
||||
}
|
||||
|
||||
// Field-level fallback for service-side URL projection.
|
||||
var manifestUrl = ReadString(distributionNode, "manifestUrl")
|
||||
?? ReadString(distributionNode, "fileMapUrl");
|
||||
var signatureUrl = ReadString(distributionNode, "signatureUrl")
|
||||
?? ReadString(distributionNode, "fileMapSignatureUrl");
|
||||
var archiveUrl = ReadString(distributionNode, "archiveUrl")
|
||||
?? ReadString(distributionNode, "updateArchiveUrl")
|
||||
?? ReadString(distributionNode, "payloadUrl");
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(manifestUrl))
|
||||
{
|
||||
assets.Add(new GitHubReleaseAsset("files.json", manifestUrl, 0, null));
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(signatureUrl))
|
||||
{
|
||||
assets.Add(new GitHubReleaseAsset("files.json.sig", signatureUrl, 0, null));
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(archiveUrl))
|
||||
{
|
||||
assets.Add(new GitHubReleaseAsset("update.zip", archiveUrl, 0, null));
|
||||
}
|
||||
|
||||
return assets;
|
||||
}
|
||||
|
||||
private static string ResolveChannelId(JsonElement metadataNode, bool includePrerelease)
|
||||
private static PlondsUpdatePayload ResolvePlondsPayload(
|
||||
JsonElement distributionNode,
|
||||
string distributionId,
|
||||
string channelId,
|
||||
string platform)
|
||||
{
|
||||
if (metadataNode.ValueKind != JsonValueKind.Object ||
|
||||
!metadataNode.TryGetProperty("channels", out var channelsNode))
|
||||
{
|
||||
return includePrerelease ? "preview" : "stable";
|
||||
}
|
||||
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");
|
||||
|
||||
var defaultChannelId = ReadString(metadataNode, "defaultChannelId") ?? string.Empty;
|
||||
if (channelsNode.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
return defaultChannelId;
|
||||
}
|
||||
|
||||
string? matchedPreview = null;
|
||||
string? matchedStable = null;
|
||||
|
||||
foreach (var channel in channelsNode.EnumerateObject())
|
||||
{
|
||||
var name = ReadString(channel.Value, "name") ?? channel.Name;
|
||||
if (string.IsNullOrWhiteSpace(matchedPreview) &&
|
||||
(name.Contains("preview", StringComparison.OrdinalIgnoreCase) ||
|
||||
name.Contains("beta", StringComparison.OrdinalIgnoreCase) ||
|
||||
name.Contains("dev", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
matchedPreview = channel.Name;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(matchedStable) &&
|
||||
(name.Contains("stable", StringComparison.OrdinalIgnoreCase) ||
|
||||
name.Contains("release", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
matchedStable = channel.Name;
|
||||
}
|
||||
}
|
||||
|
||||
if (includePrerelease)
|
||||
{
|
||||
return matchedPreview ?? defaultChannelId ?? "preview";
|
||||
}
|
||||
|
||||
return matchedStable ?? defaultChannelId ?? "stable";
|
||||
return new PlondsUpdatePayload(
|
||||
DistributionId: distributionId,
|
||||
ChannelId: channelId,
|
||||
SubChannel: platform,
|
||||
FileMapJson: fileMapJson,
|
||||
FileMapSignature: fileMapSignature,
|
||||
FileMapJsonUrl: fileMapJsonUrl,
|
||||
FileMapSignatureUrl: fileMapSignatureUrl);
|
||||
}
|
||||
|
||||
private static string ResolveSubChannel()
|
||||
private static bool HasPlondsPayload(PlondsUpdatePayload payload)
|
||||
{
|
||||
var configured = Environment.GetEnvironmentVariable("LANMOUNTAIN_PDC_SUBCHANNEL")
|
||||
?? Environment.GetEnvironmentVariable("PDC_SUBCHANNEL");
|
||||
if (!string.IsNullOrWhiteSpace(configured))
|
||||
return !string.IsNullOrWhiteSpace(payload.FileMapJson)
|
||||
|| !string.IsNullOrWhiteSpace(payload.FileMapJsonUrl);
|
||||
}
|
||||
|
||||
private static GitHubReleaseAsset? SelectPreferredInstallerAsset(IReadOnlyList<GitHubReleaseAsset> assets)
|
||||
{
|
||||
if (assets is null || assets.Count == 0)
|
||||
{
|
||||
return configured.Trim();
|
||||
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(bool includePrerelease)
|
||||
{
|
||||
return includePrerelease
|
||||
? UpdateSettingsValues.ChannelPreview
|
||||
: UpdateSettingsValues.ChannelStable;
|
||||
}
|
||||
|
||||
private static string ResolvePlatform()
|
||||
{
|
||||
var os = OperatingSystem.IsWindows()
|
||||
? "windows"
|
||||
: OperatingSystem.IsLinux()
|
||||
@@ -358,43 +444,58 @@ public sealed class PdcReleaseUpdateService : IDisposable
|
||||
_ => "x64"
|
||||
};
|
||||
|
||||
return $"{os}_{arch}_release_folderClassic";
|
||||
return $"{os}-{arch}";
|
||||
}
|
||||
|
||||
private static string? ResolveEndpoint()
|
||||
{
|
||||
var endpoint = Environment.GetEnvironmentVariable("LANMOUNTAIN_PDC_ENDPOINT")
|
||||
?? Environment.GetEnvironmentVariable("PDC_ENDPOINT");
|
||||
var endpoint = Environment.GetEnvironmentVariable("LANMOUNTAIN_PLONDS_ENDPOINT")
|
||||
?? Environment.GetEnvironmentVariable("PLONDS_ENDPOINT");
|
||||
return string.IsNullOrWhiteSpace(endpoint) ? null : endpoint.Trim().TrimEnd('/');
|
||||
}
|
||||
|
||||
private static string? ResolveToken()
|
||||
{
|
||||
var token = Environment.GetEnvironmentVariable("LANMOUNTAIN_PDC_TOKEN")
|
||||
?? Environment.GetEnvironmentVariable("PDC_TOKEN");
|
||||
var token = Environment.GetEnvironmentVariable("LANMOUNTAIN_PLONDS_TOKEN")
|
||||
?? Environment.GetEnvironmentVariable("PLONDS_TOKEN");
|
||||
return string.IsNullOrWhiteSpace(token) ? null : token.Trim();
|
||||
}
|
||||
|
||||
private static string BuildUri(string endpoint, string relativePath)
|
||||
private static string ResolveApiBasePath()
|
||||
{
|
||||
return $"{endpoint.TrimEnd('/')}/{relativePath.TrimStart('/')}";
|
||||
var configured = Environment.GetEnvironmentVariable("LANMOUNTAIN_PLONDS_API_BASE_PATH")
|
||||
?? Environment.GetEnvironmentVariable("PLONDS_API_BASE_PATH");
|
||||
if (string.IsNullOrWhiteSpace(configured))
|
||||
{
|
||||
return DefaultApiBasePath;
|
||||
}
|
||||
|
||||
var normalized = configured.Trim();
|
||||
return normalized.StartsWith("/", StringComparison.Ordinal) ? normalized : "/" + normalized;
|
||||
}
|
||||
|
||||
private static string BuildApiUrl(string endpoint, string apiBasePath, string relativePath)
|
||||
{
|
||||
return $"{endpoint.TrimEnd('/')}/{apiBasePath.Trim('/').TrimEnd('/')}/{relativePath.TrimStart('/')}";
|
||||
}
|
||||
|
||||
private static string? ReadString(JsonElement node, string propertyName)
|
||||
{
|
||||
if (node.ValueKind != JsonValueKind.Object || !node.TryGetProperty(propertyName, out var value))
|
||||
if (!TryGetPropertyIgnoreCase(node, propertyName, out var value))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return value.ValueKind == JsonValueKind.String
|
||||
? value.GetString()
|
||||
: value.ToString();
|
||||
: value.ValueKind is JsonValueKind.Null or JsonValueKind.Undefined
|
||||
? null
|
||||
: value.ToString();
|
||||
}
|
||||
|
||||
private static long? ReadInt64(JsonElement node, string propertyName)
|
||||
{
|
||||
if (node.ValueKind != JsonValueKind.Object || !node.TryGetProperty(propertyName, out var value))
|
||||
if (!TryGetPropertyIgnoreCase(node, propertyName, out var value))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
@@ -410,6 +511,37 @@ public sealed class PdcReleaseUpdateService : IDisposable
|
||||
: null;
|
||||
}
|
||||
|
||||
private static DateTimeOffset? ParsePublishedAt(JsonElement node)
|
||||
{
|
||||
var text = ReadString(node, "publishedAt");
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var value)
|
||||
? value
|
||||
: null;
|
||||
}
|
||||
|
||||
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 bool TryParseVersion(string? value, out Version? version)
|
||||
{
|
||||
version = null;
|
||||
@@ -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<PlondsUpdatePayload?> GetPlondsUpdatePayloadAsync(Version currentVersion, bool includePrerelease, bool isForce = false, CancellationToken cancellationToken = default);
|
||||
Task<UpdateDownloadResult> DownloadAssetAsync(
|
||||
GitHubReleaseAsset asset,
|
||||
string destinationFilePath,
|
||||
|
||||
@@ -752,7 +752,7 @@ internal sealed class UpdateSettingsService : IUpdateSettingsService, IDisposabl
|
||||
{
|
||||
private readonly ISettingsService _settingsService;
|
||||
private readonly GitHubReleaseUpdateService _githubReleaseUpdateService = new("wwiinnddyy", "LanMountainDesktop");
|
||||
private readonly PdcReleaseUpdateService _pdcReleaseUpdateService = new();
|
||||
private readonly PlondsReleaseUpdateService _plondsReleaseUpdateService = new();
|
||||
|
||||
public UpdateSettingsService(ISettingsService settingsService)
|
||||
{
|
||||
@@ -842,6 +842,18 @@ internal sealed class UpdateSettingsService : IUpdateSettingsService, IDisposabl
|
||||
return CheckForUpdatesCoreAsync(currentVersion, includePrerelease, isForce: true, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<PlondsUpdatePayload?> GetPlondsUpdatePayloadAsync(
|
||||
Version currentVersion,
|
||||
bool includePrerelease,
|
||||
bool isForce = false,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var result = isForce
|
||||
? await _plondsReleaseUpdateService.ForceCheckForUpdatesAsync(currentVersion, includePrerelease, cancellationToken)
|
||||
: await _plondsReleaseUpdateService.CheckForUpdatesAsync(currentVersion, includePrerelease, cancellationToken);
|
||||
return result.Success ? result.PlondsPayload : null;
|
||||
}
|
||||
|
||||
public Task<UpdateDownloadResult> DownloadAssetAsync(
|
||||
GitHubReleaseAsset asset,
|
||||
string destinationFilePath,
|
||||
@@ -879,7 +891,7 @@ internal sealed class UpdateSettingsService : IUpdateSettingsService, IDisposabl
|
||||
public void Dispose()
|
||||
{
|
||||
_githubReleaseUpdateService.Dispose();
|
||||
_pdcReleaseUpdateService.Dispose();
|
||||
_plondsReleaseUpdateService.Dispose();
|
||||
}
|
||||
|
||||
private async Task<UpdateCheckResult> CheckForUpdatesCoreAsync(
|
||||
@@ -889,20 +901,20 @@ internal sealed class UpdateSettingsService : IUpdateSettingsService, IDisposabl
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var source = UpdateSettingsValues.NormalizeDownloadSource(_settingsService.Load().UpdateDownloadSource);
|
||||
if (string.Equals(source, UpdateSettingsValues.DownloadSourcePdc, StringComparison.OrdinalIgnoreCase))
|
||||
if (string.Equals(source, UpdateSettingsValues.DownloadSourcePlonds, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var pdcResult = isForce
|
||||
? await _pdcReleaseUpdateService.ForceCheckForUpdatesAsync(currentVersion, includePrerelease, cancellationToken)
|
||||
: await _pdcReleaseUpdateService.CheckForUpdatesAsync(currentVersion, includePrerelease, cancellationToken);
|
||||
var plondsResult = isForce
|
||||
? await _plondsReleaseUpdateService.ForceCheckForUpdatesAsync(currentVersion, includePrerelease, cancellationToken)
|
||||
: await _plondsReleaseUpdateService.CheckForUpdatesAsync(currentVersion, includePrerelease, cancellationToken);
|
||||
|
||||
if (pdcResult.Success)
|
||||
if (plondsResult.Success)
|
||||
{
|
||||
return pdcResult;
|
||||
return plondsResult;
|
||||
}
|
||||
|
||||
AppLogger.Warn(
|
||||
"UpdateSettings",
|
||||
$"PDC update check failed and will fallback to GitHub. Error: {pdcResult.ErrorMessage}");
|
||||
$"PLONDS update check failed and will fallback to GitHub. Error: {plondsResult.ErrorMessage}");
|
||||
}
|
||||
|
||||
return isForce
|
||||
@@ -1259,14 +1271,14 @@ internal sealed class ApplicationInfoService : IApplicationInfoService
|
||||
|
||||
public string GetAppVersionText()
|
||||
{
|
||||
// 优先从环境变量读取(Launcher 传递)
|
||||
// 浼樺厛浠庣幆澧冨彉閲忚鍙栵紙Launcher 浼犻€掞級
|
||||
var envVersion = Environment.GetEnvironmentVariable(LanMountainDesktop.Shared.Contracts.Launcher.LauncherIpcConstants.VersionEnvVar);
|
||||
if (!string.IsNullOrWhiteSpace(envVersion))
|
||||
{
|
||||
return envVersion;
|
||||
}
|
||||
|
||||
// 回退:从程序集读取
|
||||
// Fallback: read from application assembly.
|
||||
var assembly = typeof(App).Assembly;
|
||||
var informationalVersion = assembly
|
||||
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?
|
||||
@@ -1306,14 +1318,14 @@ internal sealed class ApplicationInfoService : IApplicationInfoService
|
||||
|
||||
public string GetAppCodenameText()
|
||||
{
|
||||
// 优先从环境变量读取(Launcher 传递)
|
||||
// 浼樺厛浠庣幆澧冨彉閲忚鍙栵紙Launcher 浼犻€掞級
|
||||
var envCodename = Environment.GetEnvironmentVariable(LanMountainDesktop.Shared.Contracts.Launcher.LauncherIpcConstants.CodenameEnvVar);
|
||||
if (!string.IsNullOrWhiteSpace(envCodename))
|
||||
{
|
||||
return envCodename;
|
||||
}
|
||||
|
||||
// 回退:使用默认开发代号
|
||||
// Fallback: use default codename.
|
||||
return DefaultCodename;
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,12 @@ 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 DownloadSourcePlonds = "stcn";
|
||||
public const string DownloadSourcePdc = DownloadSourcePlonds;
|
||||
public const string DownloadSourceStcn = DownloadSourcePlonds;
|
||||
public const string LegacyDownloadSourcePlonds = "pdc";
|
||||
public const string LegacyDownloadSourcePdc = LegacyDownloadSourcePlonds;
|
||||
public const string DownloadSourceGitHub = "github";
|
||||
public const string DownloadSourceGhProxy = "gh-proxy";
|
||||
|
||||
@@ -52,9 +57,14 @@ public static class UpdateSettingsValues
|
||||
|
||||
public static string NormalizeDownloadSource(string? value)
|
||||
{
|
||||
if (string.Equals(value, DownloadSourcePdc, StringComparison.OrdinalIgnoreCase))
|
||||
if (string.Equals(value, LegacyDownloadSourcePlonds, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return DownloadSourcePdc;
|
||||
return DownloadSourceStcn;
|
||||
}
|
||||
|
||||
if (string.Equals(value, DownloadSourcePlonds, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return DownloadSourcePlonds;
|
||||
}
|
||||
|
||||
if (string.Equals(value, DownloadSourceGhProxy, StringComparison.OrdinalIgnoreCase))
|
||||
@@ -67,8 +77,8 @@ public static class UpdateSettingsValues
|
||||
return DownloadSourceGitHub;
|
||||
}
|
||||
|
||||
// Default to PDC. Runtime will fallback to GitHub if PDC is unavailable.
|
||||
return DownloadSourcePdc;
|
||||
// Default to STCN(PLONDS/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 PlondsFileMapName = "plonds-filemap.json";
|
||||
private const string PlondsFileMapSignatureName = "plonds-filemap.sig";
|
||||
private const string PlondsUpdateStateName = "plonds-update.json";
|
||||
|
||||
private static readonly HttpClient PlondsHttpClient = new()
|
||||
{
|
||||
Timeout = TimeSpan.FromMinutes(5)
|
||||
};
|
||||
|
||||
private static readonly ResumableDownloadService PlondsDownloadService = new(PlondsHttpClient);
|
||||
|
||||
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.PlondsPayload 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.PlondsPayload is null && checkResult.Release is null)
|
||||
{
|
||||
return new UpdateDownloadResult(false, null, "No update payload is available for delta download.");
|
||||
}
|
||||
|
||||
if (checkResult.PlondsPayload is not null)
|
||||
{
|
||||
return await DownloadPlondsDeltaUpdateAsync(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> DownloadPlondsDeltaUpdateAsync(
|
||||
UpdateCheckResult checkResult,
|
||||
IProgress<double>? progress = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var payload = checkResult.PlondsPayload;
|
||||
if (payload is null)
|
||||
{
|
||||
return new UpdateDownloadResult(false, null, "PLONDS 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, PlondsFileMapName);
|
||||
var signaturePath = Path.Combine(incomingDir, PlondsFileMapSignatureName);
|
||||
var updateStatePath = Path.Combine(incomingDir, PlondsUpdateStateName);
|
||||
|
||||
var fileMapJson = await EnsurePlondsTextResourceAsync(
|
||||
payload.FileMapJson,
|
||||
payload.FileMapJsonUrl,
|
||||
fileMapPath,
|
||||
cancellationToken);
|
||||
|
||||
var fileMapSignature = await EnsurePlondsTextResourceAsync(
|
||||
payload.FileMapSignature,
|
||||
payload.FileMapSignatureUrl,
|
||||
signaturePath,
|
||||
cancellationToken);
|
||||
|
||||
var downloadEntries = ParsePlondsDownloadEntries(fileMapJson);
|
||||
if (downloadEntries.Count == 0)
|
||||
{
|
||||
return new UpdateDownloadResult(false, null, "PLONDS 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<PlondsDownloadedObjectInfo>(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 = GetPlondsObjectDestinationPath(objectsDir, entry.ObjectHashHex);
|
||||
var destinationDirectory = Path.GetDirectoryName(destinationPath);
|
||||
if (!string.IsNullOrWhiteSpace(destinationDirectory))
|
||||
{
|
||||
Directory.CreateDirectory(destinationDirectory);
|
||||
}
|
||||
|
||||
if (File.Exists(destinationPath))
|
||||
{
|
||||
var existingHash = await ComputeFileSha256HexAsync(destinationPath, cancellationToken);
|
||||
if (string.Equals(existingHash, entry.ObjectHashHex, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
objectResults.Add(new PlondsDownloadedObjectInfo(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 PlondsDownloadService.DownloadAsync(
|
||||
entry.DownloadUrl,
|
||||
destinationPath,
|
||||
downloadOptions,
|
||||
null,
|
||||
cancellationToken);
|
||||
|
||||
if (!downloadResult.Success)
|
||||
{
|
||||
return new UpdateDownloadResult(false, null, $"Failed to download PLONDS object {entry.RelativePath}: {downloadResult.ErrorMessage}");
|
||||
}
|
||||
|
||||
var actualHash = await ComputeFileSha256HexAsync(destinationPath, cancellationToken);
|
||||
if (!string.IsNullOrWhiteSpace(actualHash) &&
|
||||
!string.Equals(actualHash, entry.ObjectHashHex, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return new UpdateDownloadResult(false, null, $"PLONDS object hash mismatch for {entry.RelativePath}. Expected: {entry.ObjectHashHex}, Actual: {actualHash}");
|
||||
}
|
||||
|
||||
objectResults.Add(new PlondsDownloadedObjectInfo(entry.ComponentId, entry.RelativePath, entry.DownloadUrl, entry.ObjectHashHex, destinationPath));
|
||||
completedItems++;
|
||||
progress?.Report((double)completedItems / totalSteps);
|
||||
}
|
||||
|
||||
var updateState = new PlondsUpdateState(
|
||||
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", $"PLONDS 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 PLONDS 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,356 @@ 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(PlondsUpdateStateName, StringComparison.OrdinalIgnoreCase)
|
||||
|| pendingPath.EndsWith(PlondsFileMapName, StringComparison.OrdinalIgnoreCase)
|
||||
|| pendingPath.EndsWith(PlondsFileMapSignatureName, StringComparison.OrdinalIgnoreCase)
|
||||
|| pendingPath.Contains(IncomingDirectoryName, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static string GetPlondsObjectDestinationPath(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> EnsurePlondsTextResourceAsync(
|
||||
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("PLONDS payload does not contain a file map source.");
|
||||
}
|
||||
|
||||
var downloadResult = await PlondsDownloadService.DownloadAsync(
|
||||
sourceUrl,
|
||||
destinationPath,
|
||||
cancellationToken: cancellationToken);
|
||||
|
||||
if (!downloadResult.Success)
|
||||
{
|
||||
throw new InvalidOperationException($"Failed to download PLONDS file map resource: {downloadResult.ErrorMessage}");
|
||||
}
|
||||
|
||||
return await File.ReadAllTextAsync(destinationPath, cancellationToken);
|
||||
}
|
||||
|
||||
private static IReadOnlyList<PlondsDownloadEntry> ParsePlondsDownloadEntries(string fileMapJson)
|
||||
{
|
||||
var entries = new List<PlondsDownloadEntry>();
|
||||
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))
|
||||
{
|
||||
return entries;
|
||||
}
|
||||
|
||||
if (componentsNode.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
foreach (var component in componentsNode.EnumerateObject())
|
||||
{
|
||||
if (component.Value.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!TryGetPropertyIgnoreCase(component.Value, "files", out var filesNode))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
AppendDownloadEntries(entries, component.Name, filesNode);
|
||||
}
|
||||
}
|
||||
else if (componentsNode.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var component in componentsNode.EnumerateArray())
|
||||
{
|
||||
if (component.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var componentId = ReadStringIgnoreCase(component, "id")
|
||||
?? ReadStringIgnoreCase(component, "name")
|
||||
?? "app";
|
||||
if (!TryGetPropertyIgnoreCase(component, "files", out var filesNode))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
AppendDownloadEntries(entries, componentId, filesNode);
|
||||
}
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
private static void AppendDownloadEntries(ICollection<PlondsDownloadEntry> entries, string componentId, JsonElement filesNode)
|
||||
{
|
||||
if (filesNode.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
foreach (var fileEntry in filesNode.EnumerateObject())
|
||||
{
|
||||
if (fileEntry.Value.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (TryCreateDownloadEntry(componentId, fileEntry.Name, fileEntry.Value, out var entry))
|
||||
{
|
||||
entries.Add(entry);
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (filesNode.ValueKind != JsonValueKind.Array)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var fileEntry in filesNode.EnumerateArray())
|
||||
{
|
||||
if (fileEntry.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var relativePath = ReadStringIgnoreCase(fileEntry, "path");
|
||||
if (TryCreateDownloadEntry(componentId, relativePath, fileEntry, out var entry))
|
||||
{
|
||||
entries.Add(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryCreateDownloadEntry(
|
||||
string componentId,
|
||||
string? relativePath,
|
||||
JsonElement fileNode,
|
||||
out PlondsDownloadEntry entry)
|
||||
{
|
||||
entry = default!;
|
||||
|
||||
var normalizedPath = string.IsNullOrWhiteSpace(relativePath)
|
||||
? null
|
||||
: relativePath.Trim();
|
||||
var downloadUrl = ReadStringIgnoreCase(fileNode, "objecturl")
|
||||
?? ReadStringIgnoreCase(fileNode, "downloadurl")
|
||||
?? ReadStringIgnoreCase(fileNode, "archivedownloadurl")
|
||||
?? ReadStringIgnoreCase(fileNode, "url");
|
||||
var hashHex = ReadStringIgnoreCase(fileNode, "sha256")
|
||||
?? ReadStringIgnoreCase(fileNode, "filesha256")
|
||||
?? ReadStringIgnoreCase(fileNode, "contenthash");
|
||||
|
||||
if ((string.IsNullOrWhiteSpace(hashHex) || string.IsNullOrWhiteSpace(downloadUrl)) &&
|
||||
TryGetPropertyIgnoreCase(fileNode, "hash", out var hashNode) &&
|
||||
hashNode.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
var algorithm = ReadStringIgnoreCase(hashNode, "algorithm");
|
||||
if (string.IsNullOrWhiteSpace(algorithm) ||
|
||||
algorithm.Contains("sha256", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
hashHex ??= ReadStringIgnoreCase(hashNode, "value");
|
||||
}
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(normalizedPath) ||
|
||||
string.IsNullOrWhiteSpace(downloadUrl) ||
|
||||
string.IsNullOrWhiteSpace(hashHex))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
entry = new PlondsDownloadEntry(
|
||||
componentId,
|
||||
normalizedPath,
|
||||
downloadUrl,
|
||||
NormalizeHashText(hashHex));
|
||||
return true;
|
||||
}
|
||||
|
||||
private static async Task<string?> ComputeFileSha256HexAsync(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 SHA256.HashDataAsync(stream, cancellationToken);
|
||||
return Convert.ToHexString(hashBytes).ToLowerInvariant();
|
||||
}
|
||||
|
||||
private static string NormalizeHashText(string hash)
|
||||
{
|
||||
var normalized = hash.Trim();
|
||||
var separator = normalized.IndexOf(':');
|
||||
if (separator >= 0 && separator < normalized.Length - 1)
|
||||
{
|
||||
normalized = normalized[(separator + 1)..];
|
||||
}
|
||||
|
||||
return normalized.Replace("-", string.Empty).Trim().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 PlondsDownloadEntry(
|
||||
string ComponentId,
|
||||
string RelativePath,
|
||||
string DownloadUrl,
|
||||
string ObjectHashHex);
|
||||
|
||||
private sealed record PlondsDownloadedObjectInfo(
|
||||
string ComponentId,
|
||||
string RelativePath,
|
||||
string SourceUrl,
|
||||
string ObjectHashHex,
|
||||
string LocalPath);
|
||||
|
||||
private sealed record PlondsUpdateState(
|
||||
string VersionText,
|
||||
string DistributionId,
|
||||
string ChannelId,
|
||||
string SubChannel,
|
||||
string FileMapPath,
|
||||
string FileMapSignaturePath,
|
||||
string ObjectsDirectory,
|
||||
DateTimeOffset DownloadedAtUtc,
|
||||
string FileMapJson,
|
||||
string FileMapSignature,
|
||||
IReadOnlyList<PlondsDownloadedObjectInfo> Objects);
|
||||
|
||||
private static bool TryResolveDeltaAssets(
|
||||
IReadOnlyList<GitHubReleaseAsset> assets,
|
||||
out GitHubReleaseAsset manifestAsset,
|
||||
@@ -327,6 +871,11 @@ public sealed class UpdateWorkflowService
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(checkResult);
|
||||
|
||||
if (checkResult.PlondsPayload 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 +914,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 +932,12 @@ public sealed class UpdateWorkflowService
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(checkResult);
|
||||
|
||||
if (checkResult.PlondsPayload 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 +981,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 +1004,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, PlondsFileMapName);
|
||||
var pdcSignaturePath = Path.Combine(Path.GetDirectoryName(pdcUpdatePath) ?? string.Empty, PlondsFileMapSignatureName);
|
||||
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, "PLONDS 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 +1056,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.PlondsPayload is null))
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -495,7 +1068,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 +1092,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);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<Version>0.1.0</Version>
|
||||
<VersionPrefix>0.1.0</VersionPrefix>
|
||||
<PackageVersion>0.1.0</PackageVersion>
|
||||
<AssemblyVersion>0.1.0.0</AssemblyVersion>
|
||||
<FileVersion>0.1.0.0</FileVersion>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
93
PenguinLogisticsOnlineNetworkDistributionSystem/README.md
Normal file
93
PenguinLogisticsOnlineNetworkDistributionSystem/README.md
Normal file
@@ -0,0 +1,93 @@
|
||||
# PLONDS Skeleton
|
||||
|
||||
Penguin Logistics Online Network Distribution System, or PLONDS, is the standalone update-distribution skeleton for LanMountainDesktop.
|
||||
|
||||
This directory is intentionally isolated from the main app and Launcher. It contains only the new distribution protocol, a thin read-only API, and sample S3-style metadata files.
|
||||
|
||||
## Directory Layout
|
||||
|
||||
```text
|
||||
PenguinLogisticsOnlineNetworkDistributionSystem/
|
||||
README.md
|
||||
src/
|
||||
Plonds.Shared/
|
||||
Plonds.Api/
|
||||
sample-data/
|
||||
meta/
|
||||
channels/
|
||||
stable/
|
||||
windows-x64/
|
||||
windows-x86/
|
||||
linux-x64/
|
||||
distributions/
|
||||
```
|
||||
|
||||
## Projects
|
||||
|
||||
- `Plonds.Shared` provides protocol constants and models.
|
||||
- `Plonds.Core` owns hashing, diffing, object-repo generation, manifest generation, signing, and publish orchestration.
|
||||
- `Plonds.Tool` is the CI-facing CLI entrypoint. PowerShell should stay as a thin wrapper around this tool.
|
||||
- `Plonds.Api` is a thin read-only API that reads metadata from a local folder laid out like S3.
|
||||
|
||||
## Architecture
|
||||
|
||||
PLONDS is intentionally built around a single C# implementation stack so the protocol and publish behavior do not drift across languages.
|
||||
|
||||
```text
|
||||
Host App
|
||||
-> checks updates, downloads objects, stages incoming payload
|
||||
Launcher
|
||||
-> verifies signature, applies file map, switches deployment, rolls back
|
||||
|
||||
PLONDS.Api
|
||||
-> read-only metadata projection for clients
|
||||
PLONDS.Tool
|
||||
-> CI/release command surface
|
||||
PLONDS.Core
|
||||
-> hash/diff/object-repo/sign/publish implementation
|
||||
PLONDS.Shared
|
||||
-> protocol constants and DTOs
|
||||
```
|
||||
|
||||
Rules for v1:
|
||||
|
||||
- Core protocol behavior should live in `Plonds.Core`, not in PowerShell scripts.
|
||||
- `scripts/*.ps1` may remain only as thin wrappers for GitHub Actions and local convenience.
|
||||
- Host keeps download responsibility.
|
||||
- Launcher keeps apply, atomic switch, snapshot, and rollback responsibility.
|
||||
|
||||
## Storage Layout
|
||||
|
||||
The first version keeps one fixed object root:
|
||||
|
||||
```text
|
||||
lanmountain/update/
|
||||
repo/sha256/<prefix>/<hash>
|
||||
meta/channels/<channel>/<platform>/latest.json
|
||||
meta/distributions/<distributionId>.json
|
||||
installers/<platform>/<version>/...
|
||||
```
|
||||
|
||||
Planned but not enabled in v1:
|
||||
|
||||
```text
|
||||
lanmountain/update/repo-compressed/<algo>/<prefix>/<hash>
|
||||
lanmountain/update/patches/<algo>/<baseHash>/<targetHash>
|
||||
```
|
||||
|
||||
## Public Endpoints
|
||||
|
||||
The API base path is `/api/plonds/v1`.
|
||||
|
||||
- `GET /healthz`
|
||||
- `GET /api/plonds/v1/metadata`
|
||||
- `GET /api/plonds/v1/channels/{channel}/{platform}/latest?currentVersion=...`
|
||||
- `GET /api/plonds/v1/distributions/{distributionId}`
|
||||
|
||||
## Local Run
|
||||
|
||||
```powershell
|
||||
dotnet run --project src/Plonds.Api
|
||||
```
|
||||
|
||||
By default the API reads metadata from `sample-data`.
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"channel": "stable",
|
||||
"platform": "linux-x64",
|
||||
"distributionId": "plonds-0.8.5.2-linux-x64",
|
||||
"version": "0.8.5.2",
|
||||
"publishedAt": "2026-04-20T00:00:00Z",
|
||||
"distributionPath": "meta/distributions/plonds-0.8.5.2-linux-x64.json",
|
||||
"fileMapPath": "meta/distributions/plonds-0.8.5.2-linux-x64.json"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"channel": "stable",
|
||||
"platform": "windows-x64",
|
||||
"distributionId": "plonds-0.8.5.2-windows-x64",
|
||||
"version": "0.8.5.2",
|
||||
"publishedAt": "2026-04-20T00:00:00Z",
|
||||
"distributionPath": "meta/distributions/plonds-0.8.5.2-windows-x64.json",
|
||||
"fileMapPath": "meta/distributions/plonds-0.8.5.2-windows-x64.json"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"channel": "stable",
|
||||
"platform": "windows-x86",
|
||||
"distributionId": "plonds-0.8.5.2-windows-x86",
|
||||
"version": "0.8.5.2",
|
||||
"publishedAt": "2026-04-20T00:00:00Z",
|
||||
"distributionPath": "meta/distributions/plonds-0.8.5.2-windows-x86.json",
|
||||
"fileMapPath": "meta/distributions/plonds-0.8.5.2-windows-x86.json"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
{
|
||||
"distributionId": "plonds-0.8.5.2-linux-x64",
|
||||
"version": "0.8.5.2",
|
||||
"channel": "stable",
|
||||
"platform": "linux-x64",
|
||||
"publishedAt": "2026-04-20T00:00:00Z",
|
||||
"components": [
|
||||
{
|
||||
"id": "app",
|
||||
"root": "app-0.8.5.2/",
|
||||
"mode": "file-object",
|
||||
"metadata": {
|
||||
"allowDiffUpdate": "true"
|
||||
},
|
||||
"files": [
|
||||
{
|
||||
"path": "LanMountainDesktop",
|
||||
"op": "replace",
|
||||
"contentHash": "sha256-placeholder-lanmountain-linux",
|
||||
"size": 2048000,
|
||||
"mode": "file-object",
|
||||
"objectKey": "repo/sha256/sha256-placeholder-lanmountain-linux"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "installers",
|
||||
"root": "installers/linux-x64/",
|
||||
"mode": "file-object",
|
||||
"files": [
|
||||
{
|
||||
"path": "LanMountainDesktop-0.8.5.2-linux-x64.deb",
|
||||
"op": "add",
|
||||
"contentHash": "sha256-placeholder-linux-x64-installer",
|
||||
"size": 3096576,
|
||||
"mode": "file-object",
|
||||
"objectKey": "installers/linux-x64/LanMountainDesktop-0.8.5.2-linux-x64.deb"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"installerMirrors": [
|
||||
{
|
||||
"platform": "linux",
|
||||
"arch": "x64",
|
||||
"url": "https://downloads.example.invalid/lanmountain/linux-x64/LanMountainDesktop-0.8.5.2-linux-x64.deb",
|
||||
"fileName": "LanMountainDesktop-0.8.5.2-linux-x64.deb"
|
||||
}
|
||||
],
|
||||
"capabilities": [
|
||||
"file-object",
|
||||
"compressed-object",
|
||||
"binary-patch"
|
||||
],
|
||||
"signatures": [
|
||||
{
|
||||
"algorithm": "rsa-sha256",
|
||||
"keyId": "lanmountain-main",
|
||||
"signature": "placeholder-signature"
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"notes": "sample distribution for PLONDS skeleton"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
{
|
||||
"distributionId": "plonds-0.8.5.2-windows-x64",
|
||||
"version": "0.8.5.2",
|
||||
"channel": "stable",
|
||||
"platform": "windows-x64",
|
||||
"publishedAt": "2026-04-20T00:00:00Z",
|
||||
"components": [
|
||||
{
|
||||
"id": "app",
|
||||
"root": "app-0.8.5.2/",
|
||||
"mode": "file-object",
|
||||
"metadata": {
|
||||
"allowDiffUpdate": "true"
|
||||
},
|
||||
"files": [
|
||||
{
|
||||
"path": "LanMountainDesktop.exe",
|
||||
"op": "replace",
|
||||
"contentHash": "sha256-placeholder-lanmountain-exe",
|
||||
"size": 1024000,
|
||||
"mode": "file-object",
|
||||
"objectKey": "repo/sha256/sha256-placeholder-lanmountain-exe"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "installers",
|
||||
"root": "installers/windows-x64/",
|
||||
"mode": "file-object",
|
||||
"files": [
|
||||
{
|
||||
"path": "LanMountainDesktop-Setup-0.8.5.2-x64.exe",
|
||||
"op": "add",
|
||||
"contentHash": "sha256-placeholder-windows-x64-installer",
|
||||
"size": 2048000,
|
||||
"mode": "file-object",
|
||||
"objectKey": "installers/windows-x64/LanMountainDesktop-Setup-0.8.5.2-x64.exe"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"installerMirrors": [
|
||||
{
|
||||
"platform": "windows",
|
||||
"arch": "x64",
|
||||
"url": "https://downloads.example.invalid/lanmountain/windows-x64/LanMountainDesktop-Setup-0.8.5.2-x64.exe",
|
||||
"fileName": "LanMountainDesktop-Setup-0.8.5.2-x64.exe"
|
||||
}
|
||||
],
|
||||
"capabilities": [
|
||||
"file-object",
|
||||
"compressed-object",
|
||||
"binary-patch"
|
||||
],
|
||||
"signatures": [
|
||||
{
|
||||
"algorithm": "rsa-sha256",
|
||||
"keyId": "lanmountain-main",
|
||||
"signature": "placeholder-signature"
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"notes": "sample distribution for PLONDS skeleton"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
{
|
||||
"distributionId": "plonds-0.8.5.2-windows-x86",
|
||||
"version": "0.8.5.2",
|
||||
"channel": "stable",
|
||||
"platform": "windows-x86",
|
||||
"publishedAt": "2026-04-20T00:00:00Z",
|
||||
"components": [
|
||||
{
|
||||
"id": "app",
|
||||
"root": "app-0.8.5.2/",
|
||||
"mode": "file-object",
|
||||
"metadata": {
|
||||
"allowDiffUpdate": "true"
|
||||
},
|
||||
"files": [
|
||||
{
|
||||
"path": "LanMountainDesktop.exe",
|
||||
"op": "replace",
|
||||
"contentHash": "sha256-placeholder-lanmountain-exe-x86",
|
||||
"size": 983040,
|
||||
"mode": "file-object",
|
||||
"objectKey": "repo/sha256/sha256-placeholder-lanmountain-exe-x86"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "installers",
|
||||
"root": "installers/windows-x86/",
|
||||
"mode": "file-object",
|
||||
"files": [
|
||||
{
|
||||
"path": "LanMountainDesktop-Setup-0.8.5.2-x86.exe",
|
||||
"op": "add",
|
||||
"contentHash": "sha256-placeholder-windows-x86-installer",
|
||||
"size": 1982464,
|
||||
"mode": "file-object",
|
||||
"objectKey": "installers/windows-x86/LanMountainDesktop-Setup-0.8.5.2-x86.exe"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"installerMirrors": [
|
||||
{
|
||||
"platform": "windows",
|
||||
"arch": "x86",
|
||||
"url": "https://downloads.example.invalid/lanmountain/windows-x86/LanMountainDesktop-Setup-0.8.5.2-x86.exe",
|
||||
"fileName": "LanMountainDesktop-Setup-0.8.5.2-x86.exe"
|
||||
}
|
||||
],
|
||||
"capabilities": [
|
||||
"file-object",
|
||||
"compressed-object",
|
||||
"binary-patch"
|
||||
],
|
||||
"signatures": [
|
||||
{
|
||||
"algorithm": "rsa-sha256",
|
||||
"keyId": "lanmountain-main",
|
||||
"signature": "placeholder-signature"
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"notes": "sample distribution for PLONDS skeleton"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace Plonds.Api.Configuration;
|
||||
|
||||
public sealed class PlondsApiOptions
|
||||
{
|
||||
public string StorageRoot { get; set; } = Plonds.Shared.PlondsConstants.DefaultStorageRoot;
|
||||
|
||||
public string MetaRoot { get; set; } = Plonds.Shared.PlondsConstants.DefaultMetaRoot;
|
||||
|
||||
public string ApiBasePath { get; set; } = Plonds.Shared.PlondsConstants.DefaultApiBasePath;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<PropertyGroup>
|
||||
<RootNamespace>Plonds.Api</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Plonds.Shared\Plonds.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
using Microsoft.Extensions.Options;
|
||||
using Plonds.Api.Configuration;
|
||||
using Plonds.Api.Services;
|
||||
using Plonds.Shared;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
builder.Services.Configure<PlondsApiOptions>(builder.Configuration.GetSection("Plonds"));
|
||||
builder.Services.AddSingleton(sp =>
|
||||
{
|
||||
var options = sp.GetRequiredService<IOptions<PlondsApiOptions>>().Value;
|
||||
return options;
|
||||
});
|
||||
builder.Services.AddSingleton<IPlondsManifestStore>(sp =>
|
||||
{
|
||||
var options = sp.GetRequiredService<PlondsApiOptions>();
|
||||
return new FileSystemPlondsManifestStore(options);
|
||||
});
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
var apiBasePath = app.Configuration["Plonds:ApiBasePath"];
|
||||
if (string.IsNullOrWhiteSpace(apiBasePath))
|
||||
{
|
||||
apiBasePath = PlondsConstants.DefaultApiBasePath;
|
||||
}
|
||||
|
||||
if (!apiBasePath.StartsWith('/'))
|
||||
{
|
||||
apiBasePath = "/" + apiBasePath;
|
||||
}
|
||||
|
||||
app.MapGet("/healthz", () => Results.Ok(new { status = "ok", protocol = PlondsConstants.ProtocolName, version = PlondsConstants.ProtocolVersion }));
|
||||
|
||||
app.MapGet($"{apiBasePath}/metadata", async (IPlondsManifestStore store, CancellationToken cancellationToken) =>
|
||||
{
|
||||
var catalog = await store.GetCatalogAsync(cancellationToken);
|
||||
return Results.Ok(catalog);
|
||||
});
|
||||
|
||||
app.MapGet($"{apiBasePath}/channels/{{channel}}/{{platform}}/latest", async (
|
||||
string channel,
|
||||
string platform,
|
||||
string? currentVersion,
|
||||
IPlondsManifestStore store,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
var latest = await store.GetLatestAsync(channel, platform, cancellationToken);
|
||||
if (latest is null)
|
||||
{
|
||||
return Results.NotFound(new
|
||||
{
|
||||
error = "latest_pointer_not_found",
|
||||
channel,
|
||||
platform
|
||||
});
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(currentVersion) &&
|
||||
Version.TryParse(currentVersion, out var current) &&
|
||||
Version.TryParse(latest.Version, out var target) &&
|
||||
target <= current)
|
||||
{
|
||||
return Results.NoContent();
|
||||
}
|
||||
|
||||
return Results.Ok(latest);
|
||||
});
|
||||
|
||||
app.MapGet($"{apiBasePath}/distributions/{{distributionId}}", async (string distributionId, IPlondsManifestStore store, CancellationToken cancellationToken) =>
|
||||
{
|
||||
var distribution = await store.GetDistributionAsync(distributionId, cancellationToken);
|
||||
if (distribution is null)
|
||||
{
|
||||
return Results.NotFound(new
|
||||
{
|
||||
error = "distribution_not_found",
|
||||
distributionId
|
||||
});
|
||||
}
|
||||
|
||||
return Results.Ok(distribution);
|
||||
});
|
||||
|
||||
app.Run();
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
using System.Text.Json;
|
||||
using Plonds.Api.Configuration;
|
||||
using Plonds.Shared;
|
||||
using Plonds.Shared.Models;
|
||||
|
||||
namespace Plonds.Api.Services;
|
||||
|
||||
public sealed class FileSystemPlondsManifestStore : IPlondsManifestStore
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web)
|
||||
{
|
||||
WriteIndented = true
|
||||
};
|
||||
|
||||
private readonly PlondsApiOptions _options;
|
||||
private readonly string _storageRootFullPath;
|
||||
private readonly string _metaRootFullPath;
|
||||
|
||||
public FileSystemPlondsManifestStore(PlondsApiOptions options)
|
||||
{
|
||||
_options = options;
|
||||
_storageRootFullPath = ResolveRootPath(options.StorageRoot);
|
||||
_metaRootFullPath = Path.Combine(_storageRootFullPath, options.MetaRoot);
|
||||
}
|
||||
|
||||
public Task<PlondsMetadataCatalog> GetCatalogAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
_ = cancellationToken;
|
||||
|
||||
var channelsRoot = Path.Combine(_metaRootFullPath, "channels");
|
||||
var latest = new List<PlondsChannelPointer>();
|
||||
if (Directory.Exists(channelsRoot))
|
||||
{
|
||||
foreach (var latestPath in Directory.EnumerateFiles(channelsRoot, "latest.json", SearchOption.AllDirectories))
|
||||
{
|
||||
var pointer = ReadLatestPointer(latestPath);
|
||||
if (pointer is not null)
|
||||
{
|
||||
latest.Add(pointer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var catalog = new PlondsMetadataCatalog(
|
||||
ProtocolName: PlondsConstants.ProtocolName,
|
||||
ProtocolVersion: PlondsConstants.ProtocolVersion,
|
||||
StorageRoot: _storageRootFullPath,
|
||||
MetaRoot: _metaRootFullPath,
|
||||
Latest: latest.OrderBy(x => x.Channel, StringComparer.OrdinalIgnoreCase)
|
||||
.ThenBy(x => x.Platform, StringComparer.OrdinalIgnoreCase)
|
||||
.ToArray(),
|
||||
Metadata: new Dictionary<string, string>
|
||||
{
|
||||
["apiBasePath"] = PlondsConstants.DefaultApiBasePath
|
||||
});
|
||||
|
||||
return Task.FromResult(catalog);
|
||||
}
|
||||
|
||||
public Task<PlondsChannelPointer?> GetLatestAsync(string channel, string platform, CancellationToken cancellationToken = default)
|
||||
{
|
||||
_ = cancellationToken;
|
||||
return Task.FromResult(ReadLatestPointer(GetLatestPath(channel, platform)));
|
||||
}
|
||||
|
||||
public Task<PlondsDistributionInfo?> GetDistributionAsync(string distributionId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
_ = cancellationToken;
|
||||
|
||||
var path = GetDistributionPath(distributionId);
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
return Task.FromResult<PlondsDistributionInfo?>(null);
|
||||
}
|
||||
|
||||
var json = File.ReadAllText(path);
|
||||
var distribution = JsonSerializer.Deserialize<PlondsDistributionInfo>(json, JsonOptions);
|
||||
return Task.FromResult(distribution);
|
||||
}
|
||||
|
||||
private PlondsChannelPointer? ReadLatestPointer(string path)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var json = File.ReadAllText(path);
|
||||
var pointer = JsonSerializer.Deserialize<PlondsChannelPointer>(json, JsonOptions);
|
||||
return pointer;
|
||||
}
|
||||
|
||||
private string GetLatestPath(string channel, string platform)
|
||||
{
|
||||
return Path.Combine(_metaRootFullPath, "channels", channel, platform, "latest.json");
|
||||
}
|
||||
|
||||
private string GetDistributionPath(string distributionId)
|
||||
{
|
||||
return Path.Combine(_metaRootFullPath, "distributions", $"{distributionId}.json");
|
||||
}
|
||||
|
||||
private static string ResolveRootPath(string root)
|
||||
{
|
||||
if (Path.IsPathRooted(root))
|
||||
{
|
||||
return Path.GetFullPath(root);
|
||||
}
|
||||
|
||||
var candidates = new List<string>();
|
||||
|
||||
AddCandidateChain(candidates, Directory.GetCurrentDirectory(), root);
|
||||
AddCandidateChain(candidates, AppContext.BaseDirectory, root);
|
||||
|
||||
foreach (var candidate in candidates.Distinct(StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
if (Directory.Exists(candidate))
|
||||
{
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
return candidates.FirstOrDefault() ?? Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, root));
|
||||
}
|
||||
|
||||
private static void AddCandidateChain(ICollection<string> candidates, string? startDirectory, string relativeRoot)
|
||||
{
|
||||
var current = string.IsNullOrWhiteSpace(startDirectory)
|
||||
? null
|
||||
: Path.GetFullPath(startDirectory);
|
||||
|
||||
while (!string.IsNullOrWhiteSpace(current))
|
||||
{
|
||||
candidates.Add(Path.GetFullPath(Path.Combine(current, relativeRoot)));
|
||||
current = Directory.GetParent(current)?.FullName;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using Plonds.Shared.Models;
|
||||
|
||||
namespace Plonds.Api.Services;
|
||||
|
||||
public interface IPlondsManifestStore
|
||||
{
|
||||
Task<PlondsMetadataCatalog> GetCatalogAsync(CancellationToken cancellationToken = default);
|
||||
|
||||
Task<PlondsChannelPointer?> GetLatestAsync(string channel, string platform, CancellationToken cancellationToken = default);
|
||||
|
||||
Task<PlondsDistributionInfo?> GetDistributionAsync(string distributionId, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Plonds": {
|
||||
"StorageRoot": "sample-data",
|
||||
"MetaRoot": "meta",
|
||||
"ApiBasePath": "/api/plonds/v1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Plonds.Shared\Plonds.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace Plonds.Core.Publishing;
|
||||
|
||||
public sealed record PlatformPublishResult(
|
||||
string Platform,
|
||||
string DistributionId,
|
||||
string CurrentAppDirectory,
|
||||
string? PreviousDirectory,
|
||||
string PreviousVersion,
|
||||
string FileMapPath,
|
||||
string SignaturePath,
|
||||
string DistributionPath,
|
||||
string LatestPath,
|
||||
IReadOnlyList<string> InstallerFiles);
|
||||
@@ -0,0 +1,16 @@
|
||||
namespace Plonds.Core.Publishing;
|
||||
|
||||
public sealed record PlondsGenerateOptions(
|
||||
string CurrentVersion,
|
||||
string CurrentDirectory,
|
||||
string Platform,
|
||||
string OutputRoot,
|
||||
string PreviousVersion = "0.0.0",
|
||||
string? PreviousDirectory = null,
|
||||
string Channel = "stable",
|
||||
string? DistributionId = null,
|
||||
string? RepoBaseUrl = null,
|
||||
string? FileMapUrl = null,
|
||||
string? FileMapSignatureUrl = null,
|
||||
string? InstallerDirectory = null,
|
||||
string? InstallerBaseUrl = null);
|
||||
@@ -0,0 +1,351 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Plonds.Core.Publishing;
|
||||
|
||||
public sealed class PlondsGenerator
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
WriteIndented = true
|
||||
};
|
||||
|
||||
public PlatformPublishResult Generate(PlondsGenerateOptions options)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
|
||||
var currentDirectory = Path.GetFullPath(options.CurrentDirectory);
|
||||
if (!Directory.Exists(currentDirectory))
|
||||
{
|
||||
throw new DirectoryNotFoundException($"Current directory not found: {currentDirectory}");
|
||||
}
|
||||
|
||||
var previousDirectory = string.IsNullOrWhiteSpace(options.PreviousDirectory)
|
||||
? null
|
||||
: Path.GetFullPath(options.PreviousDirectory);
|
||||
|
||||
var distributionId = string.IsNullOrWhiteSpace(options.DistributionId)
|
||||
? $"plonds-{options.CurrentVersion}-{options.Platform}"
|
||||
: options.DistributionId.Trim();
|
||||
|
||||
var outputRoot = Path.GetFullPath(options.OutputRoot);
|
||||
var repoRoot = Path.Combine(outputRoot, "repo", "sha256");
|
||||
var manifestsRoot = Path.Combine(outputRoot, "manifests", distributionId);
|
||||
var metaDistributionRoot = Path.Combine(outputRoot, "meta", "distributions");
|
||||
var metaChannelRoot = Path.Combine(outputRoot, "meta", "channels", options.Channel, options.Platform);
|
||||
var installerMirrorRoot = Path.Combine(outputRoot, "installers", options.Platform, options.CurrentVersion);
|
||||
|
||||
Directory.CreateDirectory(repoRoot);
|
||||
Directory.CreateDirectory(manifestsRoot);
|
||||
Directory.CreateDirectory(metaDistributionRoot);
|
||||
Directory.CreateDirectory(metaChannelRoot);
|
||||
|
||||
var previousManifest = ScanDirectory(previousDirectory);
|
||||
var currentManifest = ScanDirectory(currentDirectory);
|
||||
var fileEntries = BuildFileEntries(previousManifest, currentManifest, repoRoot, options.RepoBaseUrl);
|
||||
var installerMirrors = BuildInstallerMirrors(options.Platform, installerMirrorRoot, options.InstallerDirectory, options.InstallerBaseUrl);
|
||||
var publishedAt = DateTimeOffset.UtcNow;
|
||||
|
||||
var fileMap = new FileMapDocument(
|
||||
FormatVersion: "1.0",
|
||||
DistributionId: distributionId,
|
||||
FromVersion: options.PreviousVersion,
|
||||
ToVersion: options.CurrentVersion,
|
||||
Platform: options.Platform,
|
||||
Channel: options.Channel,
|
||||
PublishedAt: publishedAt,
|
||||
Capabilities: ["file-object"],
|
||||
Components:
|
||||
[
|
||||
new ComponentDocument(
|
||||
Id: "app",
|
||||
Root: "/",
|
||||
Mode: "file-object",
|
||||
Files: fileEntries,
|
||||
Metadata: new Dictionary<string, string> { ["component"] = "app" })
|
||||
],
|
||||
Metadata: new Dictionary<string, string>
|
||||
{
|
||||
["protocol"] = "PLONDS",
|
||||
["mode"] = "file-object"
|
||||
});
|
||||
|
||||
var distribution = new DistributionDocument(
|
||||
DistributionId: distributionId,
|
||||
Version: options.CurrentVersion,
|
||||
Channel: options.Channel,
|
||||
Platform: options.Platform,
|
||||
PublishedAt: publishedAt,
|
||||
FileMapUrl: options.FileMapUrl,
|
||||
FileMapSignatureUrl: options.FileMapSignatureUrl,
|
||||
Components: fileMap.Components,
|
||||
InstallerMirrors: installerMirrors,
|
||||
Capabilities: ["file-object"],
|
||||
Metadata: new Dictionary<string, string> { ["protocol"] = "PLONDS" });
|
||||
|
||||
var latest = new LatestPointerDocument(
|
||||
DistributionId: distributionId,
|
||||
Version: options.CurrentVersion,
|
||||
Channel: options.Channel,
|
||||
Platform: options.Platform,
|
||||
PublishedAt: publishedAt);
|
||||
|
||||
var fileMapPath = Path.Combine(manifestsRoot, "plonds-filemap.json");
|
||||
var distributionPath = Path.Combine(metaDistributionRoot, distributionId + ".json");
|
||||
var latestPath = Path.Combine(metaChannelRoot, "latest.json");
|
||||
|
||||
WriteJson(fileMapPath, fileMap);
|
||||
WriteJson(distributionPath, distribution);
|
||||
WriteJson(latestPath, latest);
|
||||
|
||||
return new PlatformPublishResult(
|
||||
options.Platform,
|
||||
distributionId,
|
||||
currentDirectory,
|
||||
previousDirectory,
|
||||
options.PreviousVersion,
|
||||
fileMapPath,
|
||||
fileMapPath + ".sig",
|
||||
distributionPath,
|
||||
latestPath,
|
||||
installerMirrors.Select(x => x.FileName ?? string.Empty).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray());
|
||||
}
|
||||
|
||||
private static Dictionary<string, FileFingerprint> ScanDirectory(string? root)
|
||||
{
|
||||
var manifest = new Dictionary<string, FileFingerprint>(StringComparer.OrdinalIgnoreCase);
|
||||
if (string.IsNullOrWhiteSpace(root) || !Directory.Exists(root))
|
||||
{
|
||||
return manifest;
|
||||
}
|
||||
|
||||
var resolvedRoot = Path.GetFullPath(root);
|
||||
foreach (var filePath in Directory.EnumerateFiles(resolvedRoot, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
var relativePath = Path.GetRelativePath(resolvedRoot, filePath).Replace('\\', '/');
|
||||
if (ShouldIgnore(relativePath))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var fileInfo = new FileInfo(filePath);
|
||||
manifest[relativePath] = new FileFingerprint(relativePath, filePath, ComputeSha256(filePath), fileInfo.Length);
|
||||
}
|
||||
|
||||
return manifest;
|
||||
}
|
||||
|
||||
private static List<FileEntryDocument> BuildFileEntries(
|
||||
Dictionary<string, FileFingerprint> previousManifest,
|
||||
Dictionary<string, FileFingerprint> currentManifest,
|
||||
string repoRoot,
|
||||
string? repoBaseUrl)
|
||||
{
|
||||
var entries = new List<FileEntryDocument>();
|
||||
|
||||
foreach (var path in currentManifest.Keys.OrderBy(x => x, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
var current = currentManifest[path];
|
||||
if (previousManifest.TryGetValue(path, out var previous) &&
|
||||
string.Equals(current.Sha256, previous.Sha256, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
entries.Add(new FileEntryDocument(
|
||||
Path: path,
|
||||
Action: "reuse",
|
||||
Sha256: current.Sha256,
|
||||
Size: current.Size,
|
||||
Mode: "file-object",
|
||||
ObjectKey: null,
|
||||
ObjectUrl: null,
|
||||
Metadata: null));
|
||||
continue;
|
||||
}
|
||||
|
||||
var action = previousManifest.ContainsKey(path) ? "replace" : "add";
|
||||
var objectKey = CopyContentObject(current.FullPath, repoRoot, current.Sha256);
|
||||
var objectUrl = string.IsNullOrWhiteSpace(repoBaseUrl)
|
||||
? null
|
||||
: $"{repoBaseUrl.TrimEnd('/')}/{objectKey}";
|
||||
|
||||
entries.Add(new FileEntryDocument(
|
||||
Path: path,
|
||||
Action: action,
|
||||
Sha256: current.Sha256,
|
||||
Size: current.Size,
|
||||
Mode: "file-object",
|
||||
ObjectKey: objectKey,
|
||||
ObjectUrl: objectUrl,
|
||||
Metadata: new Dictionary<string, string> { ["mode"] = "file-object" }));
|
||||
}
|
||||
|
||||
foreach (var path in previousManifest.Keys.OrderBy(x => x, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
if (!currentManifest.ContainsKey(path))
|
||||
{
|
||||
entries.Add(new FileEntryDocument(
|
||||
Path: path,
|
||||
Action: "delete",
|
||||
Sha256: string.Empty,
|
||||
Size: 0,
|
||||
Mode: "file-object",
|
||||
ObjectKey: null,
|
||||
ObjectUrl: null,
|
||||
Metadata: null));
|
||||
}
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
private static List<InstallerMirrorDocument> BuildInstallerMirrors(
|
||||
string platform,
|
||||
string installerMirrorRoot,
|
||||
string? installerSourceDirectory,
|
||||
string? installerBaseUrl)
|
||||
{
|
||||
var result = new List<InstallerMirrorDocument>();
|
||||
if (string.IsNullOrWhiteSpace(installerSourceDirectory) || !Directory.Exists(installerSourceDirectory))
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(installerMirrorRoot);
|
||||
foreach (var sourceFile in Directory.EnumerateFiles(installerSourceDirectory))
|
||||
{
|
||||
var fileName = Path.GetFileName(sourceFile);
|
||||
var destinationPath = Path.Combine(installerMirrorRoot, fileName);
|
||||
File.Copy(sourceFile, destinationPath, overwrite: true);
|
||||
|
||||
var url = string.IsNullOrWhiteSpace(installerBaseUrl)
|
||||
? null
|
||||
: $"{installerBaseUrl.TrimEnd('/')}/{Uri.EscapeDataString(fileName)}";
|
||||
result.Add(new InstallerMirrorDocument(
|
||||
Platform: platform,
|
||||
Arch: ResolveArch(platform),
|
||||
Url: url,
|
||||
FileName: fileName,
|
||||
Sha256: ComputeSha256(destinationPath),
|
||||
Size: new FileInfo(destinationPath).Length));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static string ResolveArch(string platform)
|
||||
{
|
||||
if (platform.EndsWith("-x86", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return "x86";
|
||||
}
|
||||
|
||||
if (platform.EndsWith("-arm64", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return "arm64";
|
||||
}
|
||||
|
||||
return "x64";
|
||||
}
|
||||
|
||||
private static bool ShouldIgnore(string relativePath)
|
||||
{
|
||||
var normalized = relativePath.Trim().Replace('\\', '/');
|
||||
if (string.IsNullOrWhiteSpace(normalized))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return normalized.Equals(".current", StringComparison.OrdinalIgnoreCase) ||
|
||||
normalized.Equals(".partial", StringComparison.OrdinalIgnoreCase) ||
|
||||
normalized.Equals(".destroy", StringComparison.OrdinalIgnoreCase) ||
|
||||
normalized.StartsWith(".current/", StringComparison.OrdinalIgnoreCase) ||
|
||||
normalized.StartsWith(".partial/", StringComparison.OrdinalIgnoreCase) ||
|
||||
normalized.StartsWith(".destroy/", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static string CopyContentObject(string sourcePath, string repoRoot, string sha256)
|
||||
{
|
||||
var prefix = sha256[..Math.Min(2, sha256.Length)];
|
||||
var relativeKey = $"{prefix}/{sha256}";
|
||||
var destinationPath = Path.Combine(repoRoot, prefix, sha256);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)!);
|
||||
if (!File.Exists(destinationPath))
|
||||
{
|
||||
File.Copy(sourcePath, destinationPath, overwrite: true);
|
||||
}
|
||||
|
||||
return relativeKey.Replace('\\', '/');
|
||||
}
|
||||
|
||||
private static string ComputeSha256(string filePath)
|
||||
{
|
||||
using var stream = File.OpenRead(filePath);
|
||||
return Convert.ToHexString(SHA256.HashData(stream)).ToLowerInvariant();
|
||||
}
|
||||
|
||||
private static void WriteJson<T>(string path, T value)
|
||||
{
|
||||
var json = JsonSerializer.Serialize(value, JsonOptions);
|
||||
File.WriteAllText(path, json, new UTF8Encoding(false));
|
||||
}
|
||||
|
||||
private sealed record FileFingerprint(string RelativePath, string FullPath, string Sha256, long Size);
|
||||
|
||||
private sealed record FileMapDocument(
|
||||
string FormatVersion,
|
||||
string DistributionId,
|
||||
string FromVersion,
|
||||
string ToVersion,
|
||||
string Platform,
|
||||
string Channel,
|
||||
DateTimeOffset PublishedAt,
|
||||
IReadOnlyList<string> Capabilities,
|
||||
IReadOnlyList<ComponentDocument> Components,
|
||||
IReadOnlyDictionary<string, string>? Metadata);
|
||||
|
||||
private sealed record DistributionDocument(
|
||||
string DistributionId,
|
||||
string Version,
|
||||
string Channel,
|
||||
string Platform,
|
||||
DateTimeOffset PublishedAt,
|
||||
string? FileMapUrl,
|
||||
string? FileMapSignatureUrl,
|
||||
IReadOnlyList<ComponentDocument> Components,
|
||||
IReadOnlyList<InstallerMirrorDocument> InstallerMirrors,
|
||||
IReadOnlyList<string> Capabilities,
|
||||
IReadOnlyDictionary<string, string>? Metadata);
|
||||
|
||||
private sealed record LatestPointerDocument(
|
||||
string DistributionId,
|
||||
string Version,
|
||||
string Channel,
|
||||
string Platform,
|
||||
DateTimeOffset PublishedAt);
|
||||
|
||||
private sealed record ComponentDocument(
|
||||
string Id,
|
||||
string Root,
|
||||
string Mode,
|
||||
IReadOnlyList<FileEntryDocument> Files,
|
||||
IReadOnlyDictionary<string, string>? Metadata);
|
||||
|
||||
private sealed record FileEntryDocument(
|
||||
string Path,
|
||||
string Action,
|
||||
string Sha256,
|
||||
long Size,
|
||||
string Mode,
|
||||
string? ObjectKey,
|
||||
string? ObjectUrl,
|
||||
IReadOnlyDictionary<string, string>? Metadata);
|
||||
|
||||
private sealed record InstallerMirrorDocument(
|
||||
string Platform,
|
||||
string Arch,
|
||||
string? Url,
|
||||
string? FileName,
|
||||
string? Sha256,
|
||||
long Size);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace Plonds.Core.Publishing;
|
||||
|
||||
public sealed record PlondsPublishOptions(
|
||||
string Version,
|
||||
string AppArtifactsRoot,
|
||||
string InstallerArtifactsRoot,
|
||||
string OutputRoot,
|
||||
string PrivateKeyPath,
|
||||
string Channel = "stable",
|
||||
string? BaselineRoot = null,
|
||||
string? RepoBaseUrl = null,
|
||||
string? InstallerBaseUrl = null);
|
||||
@@ -0,0 +1,230 @@
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Plonds.Core.Security;
|
||||
using Plonds.Shared;
|
||||
using Plonds.Shared.Models;
|
||||
|
||||
namespace Plonds.Core.Publishing;
|
||||
|
||||
public sealed class PlondsPublisher
|
||||
{
|
||||
private static readonly PlatformConfig[] SupportedPlatforms =
|
||||
[
|
||||
new("windows-x64", "app-payload-windows-x64", [".exe"], ["x64"]),
|
||||
new("windows-x86", "app-payload-windows-x86", [".exe"], ["x86"]),
|
||||
new("linux-x64", "app-payload-linux-x64", [".deb"], ["linux", "x64"])
|
||||
];
|
||||
|
||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
WriteIndented = true
|
||||
};
|
||||
|
||||
private readonly PlondsGenerator _generator = new();
|
||||
private readonly RsaFileSigner _signer = new();
|
||||
|
||||
public IReadOnlyList<PlatformPublishResult> Publish(PlondsPublishOptions options)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
|
||||
var results = new List<PlatformPublishResult>();
|
||||
var releaseAssetsRoot = Path.Combine(Path.GetFullPath(options.OutputRoot), "release-assets");
|
||||
Directory.CreateDirectory(releaseAssetsRoot);
|
||||
|
||||
foreach (var config in SupportedPlatforms)
|
||||
{
|
||||
var artifactRoot = Path.Combine(Path.GetFullPath(options.AppArtifactsRoot), config.ArtifactName);
|
||||
if (!Directory.Exists(artifactRoot))
|
||||
{
|
||||
throw new DirectoryNotFoundException($"App payload artifact root not found for {config.Platform}: {artifactRoot}");
|
||||
}
|
||||
|
||||
var currentAppDirectory = FindCurrentAppDirectory(artifactRoot, options.Version);
|
||||
if (currentAppDirectory is null)
|
||||
{
|
||||
throw new DirectoryNotFoundException($"Unable to locate app payload directory for {config.Platform} under {artifactRoot}");
|
||||
}
|
||||
|
||||
var baselineRoot = string.IsNullOrWhiteSpace(options.BaselineRoot)
|
||||
? Path.Combine(Path.GetFullPath(options.OutputRoot), "_baselines")
|
||||
: Path.GetFullPath(options.BaselineRoot);
|
||||
var platformBaselineRoot = Path.Combine(baselineRoot, config.Platform);
|
||||
var previousDirectory = Path.Combine(platformBaselineRoot, "current");
|
||||
var previousVersionPath = Path.Combine(platformBaselineRoot, "version.txt");
|
||||
Directory.CreateDirectory(platformBaselineRoot);
|
||||
if (!Directory.Exists(previousDirectory))
|
||||
{
|
||||
Directory.CreateDirectory(previousDirectory);
|
||||
}
|
||||
|
||||
var previousVersion = File.Exists(previousVersionPath)
|
||||
? File.ReadAllText(previousVersionPath).Trim()
|
||||
: "0.0.0";
|
||||
|
||||
var installerSourceDirectory = PrepareInstallerMirrorInput(
|
||||
config,
|
||||
options.InstallerArtifactsRoot,
|
||||
Path.Combine(platformBaselineRoot, "installers"));
|
||||
|
||||
var distributionId = $"plonds-{options.Version}-{config.Platform}";
|
||||
var repoBaseUrl = options.RepoBaseUrl;
|
||||
var fileMapUrl = repoBaseUrl is null
|
||||
? null
|
||||
: $"{repoBaseUrl.TrimEnd('/').Replace("/repo/sha256", "/manifests")}/{distributionId}/plonds-filemap.json";
|
||||
var fileMapSignatureUrl = fileMapUrl is null ? null : fileMapUrl + ".sig";
|
||||
var installerBaseUrl = string.IsNullOrWhiteSpace(options.InstallerBaseUrl)
|
||||
? null
|
||||
: $"{options.InstallerBaseUrl.TrimEnd('/')}/{config.Platform}/{options.Version}";
|
||||
|
||||
var result = _generator.Generate(new PlondsGenerateOptions(
|
||||
CurrentVersion: options.Version,
|
||||
CurrentDirectory: currentAppDirectory,
|
||||
Platform: config.Platform,
|
||||
OutputRoot: options.OutputRoot,
|
||||
PreviousVersion: previousVersion,
|
||||
PreviousDirectory: previousDirectory,
|
||||
Channel: options.Channel,
|
||||
DistributionId: distributionId,
|
||||
RepoBaseUrl: repoBaseUrl,
|
||||
FileMapUrl: fileMapUrl,
|
||||
FileMapSignatureUrl: fileMapSignatureUrl,
|
||||
InstallerDirectory: installerSourceDirectory,
|
||||
InstallerBaseUrl: installerBaseUrl));
|
||||
|
||||
_signer.SignFile(result.FileMapPath, options.PrivateKeyPath, result.SignaturePath);
|
||||
|
||||
CopyReleaseAsset(result.FileMapPath, Path.Combine(releaseAssetsRoot, $"plonds-filemap-{config.Platform}.json"));
|
||||
CopyReleaseAsset(result.SignaturePath, Path.Combine(releaseAssetsRoot, $"plonds-filemap-{config.Platform}.json.sig"));
|
||||
CopyReleaseAsset(result.DistributionPath, Path.Combine(releaseAssetsRoot, $"plonds-distribution-{config.Platform}.json"));
|
||||
CopyReleaseAsset(result.LatestPath, Path.Combine(releaseAssetsRoot, $"plonds-latest-{config.Platform}.json"));
|
||||
|
||||
MirrorBaseline(currentAppDirectory, previousDirectory, previousVersionPath, options.Version);
|
||||
results.Add(result);
|
||||
}
|
||||
|
||||
WriteMetadataCatalog(options, results);
|
||||
return results;
|
||||
}
|
||||
|
||||
private static void WriteMetadataCatalog(PlondsPublishOptions options, IReadOnlyList<PlatformPublishResult> results)
|
||||
{
|
||||
var outputRoot = Path.GetFullPath(options.OutputRoot);
|
||||
var metadataRoot = Path.Combine(outputRoot, "meta");
|
||||
Directory.CreateDirectory(metadataRoot);
|
||||
|
||||
var generatedAt = DateTimeOffset.UtcNow;
|
||||
var latestPointers = results
|
||||
.Select(result => new PlondsChannelPointer(
|
||||
Channel: options.Channel,
|
||||
Platform: result.Platform,
|
||||
DistributionId: result.DistributionId,
|
||||
Version: options.Version,
|
||||
PublishedAt: generatedAt,
|
||||
DistributionPath: $"distributions/{result.DistributionId}.json",
|
||||
FileMapPath: $"../manifests/{result.DistributionId}/plonds-filemap.json"))
|
||||
.OrderBy(pointer => pointer.Channel, StringComparer.OrdinalIgnoreCase)
|
||||
.ThenBy(pointer => pointer.Platform, StringComparer.OrdinalIgnoreCase)
|
||||
.ToArray();
|
||||
|
||||
var catalog = new PlondsMetadataCatalog(
|
||||
ProtocolName: PlondsConstants.ProtocolName,
|
||||
ProtocolVersion: PlondsConstants.ProtocolVersion,
|
||||
StorageRoot: outputRoot,
|
||||
MetaRoot: metadataRoot,
|
||||
Latest: latestPointers,
|
||||
Metadata: new Dictionary<string, string>
|
||||
{
|
||||
["generatedBy"] = "Plonds.Tool",
|
||||
["channel"] = options.Channel,
|
||||
["generatedAt"] = generatedAt.ToString("O")
|
||||
});
|
||||
|
||||
var metadataPath = Path.Combine(metadataRoot, "metadata.json");
|
||||
File.WriteAllText(metadataPath, JsonSerializer.Serialize(catalog, JsonOptions), new UTF8Encoding(false));
|
||||
}
|
||||
|
||||
private static void MirrorBaseline(string currentAppDirectory, string previousDirectory, string previousVersionPath, string version)
|
||||
{
|
||||
if (Directory.Exists(previousDirectory))
|
||||
{
|
||||
Directory.Delete(previousDirectory, recursive: true);
|
||||
}
|
||||
|
||||
CopyDirectory(currentAppDirectory, previousDirectory);
|
||||
File.WriteAllText(previousVersionPath, version);
|
||||
}
|
||||
|
||||
private static string? FindCurrentAppDirectory(string artifactRoot, string version)
|
||||
{
|
||||
var preferred = Directory.EnumerateDirectories(artifactRoot, $"app-{version}", SearchOption.AllDirectories).FirstOrDefault();
|
||||
if (preferred is not null)
|
||||
{
|
||||
return preferred;
|
||||
}
|
||||
|
||||
return Directory.EnumerateDirectories(artifactRoot, "app-*", SearchOption.AllDirectories)
|
||||
.OrderBy(x => x, StringComparer.OrdinalIgnoreCase)
|
||||
.FirstOrDefault();
|
||||
}
|
||||
|
||||
private static string PrepareInstallerMirrorInput(PlatformConfig config, string installerArtifactsRoot, string destinationRoot)
|
||||
{
|
||||
var installerFiles = FindInstallerFiles(config, installerArtifactsRoot);
|
||||
if (Directory.Exists(destinationRoot))
|
||||
{
|
||||
Directory.Delete(destinationRoot, recursive: true);
|
||||
}
|
||||
Directory.CreateDirectory(destinationRoot);
|
||||
|
||||
foreach (var file in installerFiles)
|
||||
{
|
||||
File.Copy(file, Path.Combine(destinationRoot, Path.GetFileName(file)), overwrite: true);
|
||||
}
|
||||
|
||||
return destinationRoot;
|
||||
}
|
||||
|
||||
private static List<string> FindInstallerFiles(PlatformConfig config, string installerArtifactsRoot)
|
||||
{
|
||||
var files = Directory.EnumerateFiles(Path.GetFullPath(installerArtifactsRoot), "*", SearchOption.AllDirectories);
|
||||
return files
|
||||
.Where(file => config.InstallerExtensions.Contains(Path.GetExtension(file), StringComparer.OrdinalIgnoreCase))
|
||||
.Where(file =>
|
||||
{
|
||||
var fileName = Path.GetFileName(file);
|
||||
return config.FileNameTokens.All(token => fileName.Contains(token, StringComparison.OrdinalIgnoreCase));
|
||||
})
|
||||
.ToList();
|
||||
}
|
||||
|
||||
private static void CopyReleaseAsset(string sourcePath, string destinationPath)
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)!);
|
||||
File.Copy(sourcePath, destinationPath, overwrite: true);
|
||||
}
|
||||
|
||||
private static void CopyDirectory(string sourceDir, string destinationDir)
|
||||
{
|
||||
Directory.CreateDirectory(destinationDir);
|
||||
foreach (var directory in Directory.EnumerateDirectories(sourceDir, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
var relativePath = Path.GetRelativePath(sourceDir, directory);
|
||||
Directory.CreateDirectory(Path.Combine(destinationDir, relativePath));
|
||||
}
|
||||
|
||||
foreach (var file in Directory.EnumerateFiles(sourceDir, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
var relativePath = Path.GetRelativePath(sourceDir, file);
|
||||
var destinationPath = Path.Combine(destinationDir, relativePath);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)!);
|
||||
File.Copy(file, destinationPath, overwrite: true);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record PlatformConfig(
|
||||
string Platform,
|
||||
string ArtifactName,
|
||||
IReadOnlyList<string> InstallerExtensions,
|
||||
IReadOnlyList<string> FileNameTokens);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Plonds.Core.Security;
|
||||
|
||||
public sealed class RsaFileSigner
|
||||
{
|
||||
public string SignFile(string filePath, string privateKeyPath, string? outputPath = null)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(filePath);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(privateKeyPath);
|
||||
|
||||
if (!File.Exists(filePath))
|
||||
{
|
||||
throw new FileNotFoundException("Manifest file not found.", filePath);
|
||||
}
|
||||
|
||||
if (!File.Exists(privateKeyPath))
|
||||
{
|
||||
throw new FileNotFoundException("Private key PEM file not found.", privateKeyPath);
|
||||
}
|
||||
|
||||
outputPath ??= filePath + ".sig";
|
||||
|
||||
var payload = File.ReadAllBytes(filePath);
|
||||
var privateKeyPem = File.ReadAllText(privateKeyPath, Encoding.ASCII);
|
||||
if (string.IsNullOrWhiteSpace(privateKeyPem))
|
||||
{
|
||||
throw new InvalidOperationException("Private key PEM is empty.");
|
||||
}
|
||||
|
||||
using var rsa = RSA.Create();
|
||||
rsa.ImportFromPem(privateKeyPem);
|
||||
var signature = rsa.SignData(payload, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
||||
File.WriteAllText(outputPath, Convert.ToBase64String(signature), Encoding.ASCII);
|
||||
return outputPath;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace Plonds.Shared.Models;
|
||||
|
||||
public sealed record PlondsChannelPointer(
|
||||
string Channel,
|
||||
string Platform,
|
||||
string DistributionId,
|
||||
string Version,
|
||||
DateTimeOffset PublishedAt,
|
||||
string? DistributionPath = null,
|
||||
string? FileMapPath = null);
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace Plonds.Shared.Models;
|
||||
|
||||
public sealed record PlondsComponent(
|
||||
string Id,
|
||||
string Root,
|
||||
string Mode,
|
||||
IReadOnlyList<PlondsFileEntry> Files,
|
||||
IReadOnlyDictionary<string, string>? Metadata = null);
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace Plonds.Shared.Models;
|
||||
|
||||
public sealed record PlondsDistributionInfo(
|
||||
string DistributionId,
|
||||
string Version,
|
||||
string Channel,
|
||||
string Platform,
|
||||
DateTimeOffset PublishedAt,
|
||||
IReadOnlyList<PlondsComponent> Components,
|
||||
IReadOnlyList<PlondsMirrorAsset> InstallerMirrors,
|
||||
IReadOnlyList<string> Capabilities,
|
||||
IReadOnlyList<PlondsSignatureDescriptor> Signatures,
|
||||
IReadOnlyDictionary<string, string>? Metadata = null);
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace Plonds.Shared.Models;
|
||||
|
||||
public sealed record PlondsFileEntry(
|
||||
string Path,
|
||||
string Op,
|
||||
string ContentHash,
|
||||
long Size,
|
||||
string Mode,
|
||||
string? ObjectKey = null,
|
||||
string? Compression = null,
|
||||
string? PatchBaseHash = null,
|
||||
string? PatchObjectKey = null);
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace Plonds.Shared.Models;
|
||||
|
||||
public sealed record PlondsFileMap(
|
||||
string FormatVersion,
|
||||
string DistributionId,
|
||||
string SourceVersion,
|
||||
string TargetVersion,
|
||||
string Platform,
|
||||
IReadOnlyList<PlondsComponent> Components,
|
||||
IReadOnlyList<string> Capabilities,
|
||||
IReadOnlyList<PlondsSignatureDescriptor> Signatures,
|
||||
IReadOnlyDictionary<string, string>? Metadata = null);
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace Plonds.Shared.Models;
|
||||
|
||||
public sealed record PlondsMetadataCatalog(
|
||||
string ProtocolName,
|
||||
string ProtocolVersion,
|
||||
string StorageRoot,
|
||||
string MetaRoot,
|
||||
IReadOnlyList<PlondsChannelPointer> Latest,
|
||||
IReadOnlyDictionary<string, string>? Metadata = null);
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace Plonds.Shared.Models;
|
||||
|
||||
public sealed record PlondsMirrorAsset(
|
||||
string Platform,
|
||||
string Arch,
|
||||
string Url,
|
||||
string? FileName = null,
|
||||
string? Sha256 = null,
|
||||
long Size = 0);
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace Plonds.Shared.Models;
|
||||
|
||||
public sealed record PlondsSignatureDescriptor(
|
||||
string Algorithm,
|
||||
string KeyId,
|
||||
string Signature);
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<RootNamespace>Plonds.Shared</RootNamespace>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
namespace Plonds.Shared;
|
||||
|
||||
public static class PlondsConstants
|
||||
{
|
||||
public const string ProtocolName = "PLONDS";
|
||||
public const string ProtocolVersion = "1.0";
|
||||
|
||||
public const string DefaultApiBasePath = "/api/plonds/v1";
|
||||
public const string DefaultStorageRoot = "sample-data";
|
||||
public const string DefaultMetaRoot = "meta";
|
||||
public const string DefaultRepoRoot = "repo";
|
||||
public const string DefaultInstallersRoot = "installers";
|
||||
|
||||
public const string FileObjectMode = "file-object";
|
||||
public const string CompressedObjectMode = "compressed-object";
|
||||
public const string BinaryPatchMode = "binary-patch";
|
||||
|
||||
public static readonly string[] SupportedFileModes =
|
||||
[
|
||||
FileObjectMode,
|
||||
CompressedObjectMode,
|
||||
BinaryPatchMode
|
||||
];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace Plonds.Shared;
|
||||
|
||||
public enum PlondsFileOperation
|
||||
{
|
||||
Add,
|
||||
Replace,
|
||||
Reuse,
|
||||
Delete
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Plonds.Core\Plonds.Core.csproj" />
|
||||
<ProjectReference Include="..\Plonds.Shared\Plonds.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,142 @@
|
||||
using Plonds.Core.Publishing;
|
||||
using Plonds.Core.Security;
|
||||
|
||||
return await PlondsCli.RunAsync(args);
|
||||
|
||||
internal static class PlondsCli
|
||||
{
|
||||
public static Task<int> RunAsync(string[] args)
|
||||
{
|
||||
if (args.Length == 0)
|
||||
{
|
||||
PrintUsage();
|
||||
return Task.FromResult(1);
|
||||
}
|
||||
|
||||
var command = args[0].Trim().ToLowerInvariant();
|
||||
var options = ParseOptions(args.Skip(1).ToArray());
|
||||
|
||||
try
|
||||
{
|
||||
switch (command)
|
||||
{
|
||||
case "generate":
|
||||
RunGenerate(options);
|
||||
return Task.FromResult(0);
|
||||
case "sign":
|
||||
RunSign(options);
|
||||
return Task.FromResult(0);
|
||||
case "publish":
|
||||
RunPublish(options);
|
||||
return Task.FromResult(0);
|
||||
default:
|
||||
Console.Error.WriteLine($"Unknown command: {command}");
|
||||
PrintUsage();
|
||||
return Task.FromResult(1);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine(ex.Message);
|
||||
return Task.FromResult(1);
|
||||
}
|
||||
}
|
||||
|
||||
private static void RunGenerate(Dictionary<string, string> options)
|
||||
{
|
||||
var generator = new PlondsGenerator();
|
||||
var result = generator.Generate(new PlondsGenerateOptions(
|
||||
CurrentVersion: Require(options, "current-version"),
|
||||
CurrentDirectory: Require(options, "current-dir"),
|
||||
Platform: Require(options, "platform"),
|
||||
OutputRoot: Require(options, "output-dir"),
|
||||
PreviousVersion: Get(options, "previous-version", "0.0.0") ?? "0.0.0",
|
||||
PreviousDirectory: Get(options, "previous-dir"),
|
||||
Channel: Get(options, "channel", "stable") ?? "stable",
|
||||
DistributionId: Get(options, "distribution-id"),
|
||||
RepoBaseUrl: Get(options, "repo-base-url"),
|
||||
FileMapUrl: Get(options, "file-map-url"),
|
||||
FileMapSignatureUrl: Get(options, "file-map-signature-url"),
|
||||
InstallerDirectory: Get(options, "installer-directory"),
|
||||
InstallerBaseUrl: Get(options, "installer-base-url")));
|
||||
|
||||
Console.WriteLine($"Generated PLONDS artifacts for {result.Platform}: {result.DistributionId}");
|
||||
Console.WriteLine(result.FileMapPath);
|
||||
}
|
||||
|
||||
private static void RunSign(Dictionary<string, string> options)
|
||||
{
|
||||
var signer = new RsaFileSigner();
|
||||
var signaturePath = signer.SignFile(
|
||||
Require(options, "manifest"),
|
||||
Require(options, "private-key"),
|
||||
Get(options, "output"));
|
||||
Console.WriteLine(signaturePath);
|
||||
}
|
||||
|
||||
private static void RunPublish(Dictionary<string, string> options)
|
||||
{
|
||||
var publisher = new PlondsPublisher();
|
||||
var results = publisher.Publish(new PlondsPublishOptions(
|
||||
Version: Require(options, "version"),
|
||||
AppArtifactsRoot: Require(options, "app-artifacts-root"),
|
||||
InstallerArtifactsRoot: Require(options, "installer-artifacts-root"),
|
||||
OutputRoot: Require(options, "output-dir"),
|
||||
PrivateKeyPath: Require(options, "private-key"),
|
||||
Channel: Get(options, "channel", "stable") ?? "stable",
|
||||
BaselineRoot: Get(options, "baseline-root"),
|
||||
RepoBaseUrl: Get(options, "repo-base-url"),
|
||||
InstallerBaseUrl: Get(options, "installer-base-url")));
|
||||
|
||||
foreach (var result in results)
|
||||
{
|
||||
Console.WriteLine($"{result.Platform}: {result.DistributionId}");
|
||||
}
|
||||
}
|
||||
|
||||
private static Dictionary<string, string> ParseOptions(string[] args)
|
||||
{
|
||||
var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
for (var index = 0; index < args.Length; index++)
|
||||
{
|
||||
var token = args[index];
|
||||
if (!token.StartsWith("--", StringComparison.Ordinal))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var key = token[2..];
|
||||
var value = index + 1 < args.Length && !args[index + 1].StartsWith("--", StringComparison.Ordinal)
|
||||
? args[++index]
|
||||
: "true";
|
||||
result[key] = value;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static string Require(IReadOnlyDictionary<string, string> options, string key)
|
||||
{
|
||||
if (options.TryGetValue(key, out var value) && !string.IsNullOrWhiteSpace(value))
|
||||
{
|
||||
return value;
|
||||
}
|
||||
|
||||
throw new InvalidOperationException($"Missing required option --{key}");
|
||||
}
|
||||
|
||||
private static string? Get(IReadOnlyDictionary<string, string> options, string key, string? defaultValue = null)
|
||||
{
|
||||
return options.TryGetValue(key, out var value) && !string.IsNullOrWhiteSpace(value)
|
||||
? value
|
||||
: defaultValue;
|
||||
}
|
||||
|
||||
private static void PrintUsage()
|
||||
{
|
||||
Console.WriteLine("PLONDS Tool");
|
||||
Console.WriteLine(" generate --current-version <v> --current-dir <dir> --platform <platform> --output-dir <dir> [--previous-version <v>] [--previous-dir <dir>]");
|
||||
Console.WriteLine(" sign --manifest <file> --private-key <pem> [--output <file>]");
|
||||
Console.WriteLine(" publish --version <v> --app-artifacts-root <dir> --installer-artifacts-root <dir> --output-dir <dir> --private-key <pem> [--baseline-root <dir>]");
|
||||
}
|
||||
}
|
||||
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)
|
||||
|
||||
87
scripts/Generate-PlondsArtifacts.ps1
Normal file
87
scripts/Generate-PlondsArtifacts.ps1
Normal file
@@ -0,0 +1,87 @@
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$CurrentVersion,
|
||||
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$CurrentDir,
|
||||
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Platform,
|
||||
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$OutputDir,
|
||||
|
||||
[Parameter(Mandatory = $false)]
|
||||
[string]$PreviousVersion = "",
|
||||
|
||||
[Parameter(Mandatory = $false)]
|
||||
[string]$PreviousDir = "",
|
||||
|
||||
[Parameter(Mandatory = $false)]
|
||||
[string]$Channel = "stable",
|
||||
|
||||
[Parameter(Mandatory = $false)]
|
||||
[string]$DistributionId = "",
|
||||
|
||||
[Parameter(Mandatory = $false)]
|
||||
[string]$RepoBaseUrl = "",
|
||||
|
||||
[Parameter(Mandatory = $false)]
|
||||
[string]$FileMapUrl = "",
|
||||
|
||||
[Parameter(Mandatory = $false)]
|
||||
[string]$FileMapSignatureUrl = "",
|
||||
|
||||
[Parameter(Mandatory = $false)]
|
||||
[string]$InstallerDirectory = "",
|
||||
|
||||
[Parameter(Mandatory = $false)]
|
||||
[string]$InstallerBaseUrl = ""
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
$toolProject = Join-Path $PSScriptRoot "..\PenguinLogisticsOnlineNetworkDistributionSystem\src\Plonds.Tool\Plonds.Tool.csproj"
|
||||
if (-not (Test-Path -LiteralPath $toolProject)) {
|
||||
throw "PLONDS tool project not found: $toolProject"
|
||||
}
|
||||
|
||||
$arguments = @(
|
||||
"run",
|
||||
"--project", $toolProject,
|
||||
"--",
|
||||
"generate",
|
||||
"--current-version", $CurrentVersion,
|
||||
"--current-dir", $CurrentDir,
|
||||
"--platform", $Platform,
|
||||
"--output-dir", $OutputDir,
|
||||
"--previous-version", $(if ([string]::IsNullOrWhiteSpace($PreviousVersion)) { "0.0.0" } else { $PreviousVersion }),
|
||||
"--channel", $Channel
|
||||
)
|
||||
|
||||
if (-not [string]::IsNullOrWhiteSpace($PreviousDir)) {
|
||||
$arguments += @("--previous-dir", $PreviousDir)
|
||||
}
|
||||
if (-not [string]::IsNullOrWhiteSpace($DistributionId)) {
|
||||
$arguments += @("--distribution-id", $DistributionId)
|
||||
}
|
||||
if (-not [string]::IsNullOrWhiteSpace($RepoBaseUrl)) {
|
||||
$arguments += @("--repo-base-url", $RepoBaseUrl)
|
||||
}
|
||||
if (-not [string]::IsNullOrWhiteSpace($FileMapUrl)) {
|
||||
$arguments += @("--file-map-url", $FileMapUrl)
|
||||
}
|
||||
if (-not [string]::IsNullOrWhiteSpace($FileMapSignatureUrl)) {
|
||||
$arguments += @("--file-map-signature-url", $FileMapSignatureUrl)
|
||||
}
|
||||
if (-not [string]::IsNullOrWhiteSpace($InstallerDirectory)) {
|
||||
$arguments += @("--installer-directory", $InstallerDirectory)
|
||||
}
|
||||
if (-not [string]::IsNullOrWhiteSpace($InstallerBaseUrl)) {
|
||||
$arguments += @("--installer-base-url", $InstallerBaseUrl)
|
||||
}
|
||||
|
||||
& dotnet @arguments
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "PLONDS generate command failed."
|
||||
}
|
||||
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"
|
||||
482
scripts/Publish-Plonds.ps1
Normal file
482
scripts/Publish-Plonds.ps1
Normal file
@@ -0,0 +1,482 @@
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Version,
|
||||
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$AppArtifactsRoot,
|
||||
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$InstallerArtifactsRoot,
|
||||
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$OutputDir,
|
||||
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$PrivateKeyPath,
|
||||
|
||||
[Parameter(Mandatory = $false)]
|
||||
[string]$Channel = "stable",
|
||||
|
||||
[Parameter(Mandatory = $false)]
|
||||
[string]$S3Endpoint = "",
|
||||
|
||||
[Parameter(Mandatory = $false)]
|
||||
[string]$S3Bucket = "",
|
||||
|
||||
[Parameter(Mandatory = $false)]
|
||||
[string]$S3Region = ""
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
function Get-PlatformConfigurations {
|
||||
return @(
|
||||
@{
|
||||
Platform = "windows-x64"
|
||||
ArtifactName = "app-payload-windows-x64"
|
||||
},
|
||||
@{
|
||||
Platform = "windows-x86"
|
||||
ArtifactName = "app-payload-windows-x86"
|
||||
},
|
||||
@{
|
||||
Platform = "linux-x64"
|
||||
ArtifactName = "app-payload-linux-x64"
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
function Resolve-AppDirectory {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$SearchRoot,
|
||||
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Version
|
||||
)
|
||||
|
||||
$preferred = Get-ChildItem -LiteralPath $SearchRoot -Recurse -Directory -Filter "app-$Version" -ErrorAction SilentlyContinue |
|
||||
Select-Object -First 1
|
||||
if ($preferred) {
|
||||
return $preferred.FullName
|
||||
}
|
||||
|
||||
$fallback = Get-ChildItem -LiteralPath $SearchRoot -Recurse -Directory -Filter "app-*" -ErrorAction SilentlyContinue |
|
||||
Sort-Object FullName |
|
||||
Select-Object -First 1
|
||||
return $fallback?.FullName
|
||||
}
|
||||
|
||||
function Invoke-AwsCommandIfPossible {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string[]]$Arguments,
|
||||
|
||||
[Parameter(Mandatory = $false)]
|
||||
[switch]$IgnoreFailure
|
||||
)
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($S3Endpoint) -or [string]::IsNullOrWhiteSpace($S3Bucket)) {
|
||||
return
|
||||
}
|
||||
|
||||
$previousRequestChecksumCalculation = $env:AWS_REQUEST_CHECKSUM_CALCULATION
|
||||
$previousResponseChecksumValidation = $env:AWS_RESPONSE_CHECKSUM_VALIDATION
|
||||
|
||||
# Rainyun's S3-compatible endpoint rejects AWS CLI v2's default checksum headers
|
||||
# during multipart uploads. Restrict checksum behavior to API-required cases only.
|
||||
$env:AWS_REQUEST_CHECKSUM_CALCULATION = "WHEN_REQUIRED"
|
||||
$env:AWS_RESPONSE_CHECKSUM_VALIDATION = "WHEN_REQUIRED"
|
||||
|
||||
try {
|
||||
if ($IgnoreFailure) {
|
||||
& aws @Arguments 2>$null
|
||||
}
|
||||
else {
|
||||
& aws @Arguments
|
||||
}
|
||||
}
|
||||
finally {
|
||||
if ($null -eq $previousRequestChecksumCalculation) {
|
||||
Remove-Item Env:AWS_REQUEST_CHECKSUM_CALCULATION -ErrorAction SilentlyContinue
|
||||
}
|
||||
else {
|
||||
$env:AWS_REQUEST_CHECKSUM_CALCULATION = $previousRequestChecksumCalculation
|
||||
}
|
||||
|
||||
if ($null -eq $previousResponseChecksumValidation) {
|
||||
Remove-Item Env:AWS_RESPONSE_CHECKSUM_VALIDATION -ErrorAction SilentlyContinue
|
||||
}
|
||||
else {
|
||||
$env:AWS_RESPONSE_CHECKSUM_VALIDATION = $previousResponseChecksumValidation
|
||||
}
|
||||
}
|
||||
|
||||
if ($LASTEXITCODE -ne 0 -and -not $IgnoreFailure) {
|
||||
throw "aws command failed: aws $($Arguments -join ' ')"
|
||||
}
|
||||
}
|
||||
|
||||
function Get-S3Key {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Prefix,
|
||||
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$RelativePath
|
||||
)
|
||||
|
||||
$trimmedPrefix = $Prefix.Trim('/').Replace('\', '/')
|
||||
$trimmedRelativePath = $RelativePath.TrimStart('\', '/').Replace('\', '/')
|
||||
return "$trimmedPrefix/$trimmedRelativePath"
|
||||
}
|
||||
|
||||
function Get-RelativePath {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Root,
|
||||
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Path
|
||||
)
|
||||
|
||||
$rootPath = [System.IO.Path]::GetFullPath($Root)
|
||||
if (-not $rootPath.EndsWith([System.IO.Path]::DirectorySeparatorChar)) {
|
||||
$rootPath += [System.IO.Path]::DirectorySeparatorChar
|
||||
}
|
||||
|
||||
$pathValue = [System.IO.Path]::GetFullPath($Path)
|
||||
return [System.IO.Path]::GetRelativePath($rootPath, $pathValue)
|
||||
}
|
||||
|
||||
function Get-RemoteS3Keys {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$Prefix
|
||||
)
|
||||
|
||||
$keys = [System.Collections.Generic.List[string]]::new()
|
||||
$continuationToken = $null
|
||||
|
||||
do {
|
||||
$arguments = @(
|
||||
"--endpoint-url", $S3Endpoint,
|
||||
"--region", $S3Region,
|
||||
"s3api", "list-objects-v2",
|
||||
"--bucket", $S3Bucket,
|
||||
"--prefix", $Prefix,
|
||||
"--output", "json"
|
||||
)
|
||||
|
||||
if (-not [string]::IsNullOrWhiteSpace($continuationToken)) {
|
||||
$arguments += @("--continuation-token", $continuationToken)
|
||||
}
|
||||
|
||||
$json = Invoke-AwsCommandIfPossible -Arguments $arguments
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($json)) {
|
||||
break
|
||||
}
|
||||
|
||||
$response = $json | ConvertFrom-Json
|
||||
if ($response.Contents) {
|
||||
foreach ($item in $response.Contents) {
|
||||
if (-not [string]::IsNullOrWhiteSpace($item.Key)) {
|
||||
$keys.Add($item.Key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($response.IsTruncated -and -not [string]::IsNullOrWhiteSpace($response.NextContinuationToken)) {
|
||||
$continuationToken = $response.NextContinuationToken
|
||||
}
|
||||
else {
|
||||
$continuationToken = $null
|
||||
}
|
||||
} while (-not [string]::IsNullOrWhiteSpace($continuationToken))
|
||||
|
||||
return $keys
|
||||
}
|
||||
|
||||
function Upload-DirectoryToS3 {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$LocalRoot,
|
||||
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$RemotePrefix,
|
||||
|
||||
[Parameter(Mandatory = $false)]
|
||||
[switch]$DeleteExtraRemoteObjects
|
||||
)
|
||||
|
||||
if (-not (Test-Path -LiteralPath $LocalRoot)) {
|
||||
throw "Local upload root not found: $LocalRoot"
|
||||
}
|
||||
|
||||
$files = Get-ChildItem -LiteralPath $LocalRoot -Recurse -File | Sort-Object FullName
|
||||
$uploadedKeys = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal)
|
||||
|
||||
if ($files.Count -eq 0) {
|
||||
Write-Host "No files found under $LocalRoot; skipping upload."
|
||||
}
|
||||
|
||||
$index = 0
|
||||
foreach ($file in $files) {
|
||||
$index++
|
||||
$relativePath = Get-RelativePath -Root $LocalRoot -Path $file.FullName
|
||||
$key = Get-S3Key -Prefix $RemotePrefix -RelativePath $relativePath
|
||||
$null = $uploadedKeys.Add($key)
|
||||
|
||||
if ($index -eq 1 -or $index % 25 -eq 0 -or $index -eq $files.Count) {
|
||||
Write-Host "Uploading $index/$($files.Count): $key"
|
||||
}
|
||||
|
||||
Invoke-AwsCommandIfPossible -Arguments @(
|
||||
"--endpoint-url", $S3Endpoint,
|
||||
"--region", $S3Region,
|
||||
"s3api", "put-object",
|
||||
"--bucket", $S3Bucket,
|
||||
"--key", $key,
|
||||
"--body", $file.FullName
|
||||
)
|
||||
}
|
||||
|
||||
if ($DeleteExtraRemoteObjects) {
|
||||
$remoteKeys = Get-RemoteS3Keys -Prefix $RemotePrefix.Trim('/').Replace('\', '/')
|
||||
foreach ($remoteKey in $remoteKeys) {
|
||||
if (-not $uploadedKeys.Contains($remoteKey)) {
|
||||
Write-Host "Deleting stale remote object: $remoteKey"
|
||||
Invoke-AwsCommandIfPossible -Arguments @(
|
||||
"--endpoint-url", $S3Endpoint,
|
||||
"--region", $S3Region,
|
||||
"s3api", "delete-object",
|
||||
"--bucket", $S3Bucket,
|
||||
"--key", $remoteKey
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Upload-FileToS3 {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$LocalPath,
|
||||
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$RemoteKey
|
||||
)
|
||||
|
||||
if (-not (Test-Path -LiteralPath $LocalPath)) {
|
||||
throw "Local upload file not found: $LocalPath"
|
||||
}
|
||||
|
||||
Invoke-AwsCommandIfPossible -Arguments @(
|
||||
"--endpoint-url", $S3Endpoint,
|
||||
"--region", $S3Region,
|
||||
"s3api", "put-object",
|
||||
"--bucket", $S3Bucket,
|
||||
"--key", $RemoteKey.Trim('/').Replace('\', '/'),
|
||||
"--body", $LocalPath
|
||||
)
|
||||
}
|
||||
|
||||
if (-not (Test-Path -LiteralPath $PrivateKeyPath)) {
|
||||
throw "Private key file not found: $PrivateKeyPath"
|
||||
}
|
||||
|
||||
$toolProject = Join-Path $PSScriptRoot "..\PenguinLogisticsOnlineNetworkDistributionSystem\src\Plonds.Tool\Plonds.Tool.csproj"
|
||||
if (-not (Test-Path -LiteralPath $toolProject)) {
|
||||
throw "PLONDS tool project not found: $toolProject"
|
||||
}
|
||||
|
||||
$supportedPlatforms = Get-PlatformConfigurations
|
||||
$publishedRoot = Join-Path $OutputDir "published"
|
||||
$releaseAssetsRoot = Join-Path $OutputDir "release-assets"
|
||||
$baselineRoot = Join-Path $OutputDir "_baselines"
|
||||
|
||||
New-Item -ItemType Directory -Path $publishedRoot -Force | Out-Null
|
||||
New-Item -ItemType Directory -Path $releaseAssetsRoot -Force | Out-Null
|
||||
New-Item -ItemType Directory -Path $baselineRoot -Force | Out-Null
|
||||
|
||||
foreach ($config in $supportedPlatforms) {
|
||||
$platform = $config.Platform
|
||||
$platformBaselineRoot = Join-Path $baselineRoot $platform
|
||||
$baselineCurrentDir = Join-Path $platformBaselineRoot "current"
|
||||
$baselineVersionPath = Join-Path $platformBaselineRoot "version.txt"
|
||||
|
||||
New-Item -ItemType Directory -Path $baselineCurrentDir -Force | Out-Null
|
||||
|
||||
if (-not [string]::IsNullOrWhiteSpace($S3Endpoint) -and -not [string]::IsNullOrWhiteSpace($S3Bucket)) {
|
||||
Invoke-AwsCommandIfPossible -Arguments @(
|
||||
"--endpoint-url", $S3Endpoint,
|
||||
"--region", $S3Region,
|
||||
"s3", "sync",
|
||||
"s3://$S3Bucket/lanmountain/update/baselines/$platform/current/",
|
||||
$baselineCurrentDir,
|
||||
"--only-show-errors"
|
||||
) -IgnoreFailure
|
||||
|
||||
Invoke-AwsCommandIfPossible -Arguments @(
|
||||
"--endpoint-url", $S3Endpoint,
|
||||
"--region", $S3Region,
|
||||
"s3", "cp",
|
||||
"s3://$S3Bucket/lanmountain/update/baselines/$platform/version.txt",
|
||||
$baselineVersionPath,
|
||||
"--only-show-errors"
|
||||
) -IgnoreFailure
|
||||
}
|
||||
}
|
||||
|
||||
$repoBaseUrl = if ([string]::IsNullOrWhiteSpace($S3Endpoint) -or [string]::IsNullOrWhiteSpace($S3Bucket)) {
|
||||
$null
|
||||
}
|
||||
else {
|
||||
"$($S3Endpoint.TrimEnd('/'))/$S3Bucket/lanmountain/update/repo/sha256"
|
||||
}
|
||||
|
||||
$installerBaseUrl = if ([string]::IsNullOrWhiteSpace($S3Endpoint) -or [string]::IsNullOrWhiteSpace($S3Bucket)) {
|
||||
$null
|
||||
}
|
||||
else {
|
||||
"$($S3Endpoint.TrimEnd('/'))/$S3Bucket/lanmountain/update/installers"
|
||||
}
|
||||
|
||||
$legacySnapshots = @{}
|
||||
foreach ($config in $supportedPlatforms) {
|
||||
$platform = $config.Platform
|
||||
$platformBaselineRoot = Join-Path $baselineRoot $platform
|
||||
$baselineCurrentDir = Join-Path $platformBaselineRoot "current"
|
||||
$baselineVersionPath = Join-Path $platformBaselineRoot "version.txt"
|
||||
$snapshotRoot = Join-Path $platformBaselineRoot "previous-snapshot"
|
||||
|
||||
if (Test-Path -LiteralPath $snapshotRoot) {
|
||||
Remove-Item -LiteralPath $snapshotRoot -Recurse -Force
|
||||
}
|
||||
New-Item -ItemType Directory -Path $snapshotRoot -Force | Out-Null
|
||||
|
||||
$previousVersion = if (Test-Path -LiteralPath $baselineVersionPath) {
|
||||
(Get-Content -LiteralPath $baselineVersionPath -Raw).Trim()
|
||||
}
|
||||
else {
|
||||
"0.0.0"
|
||||
}
|
||||
|
||||
$baselineItems = @(Get-ChildItem -LiteralPath $baselineCurrentDir -Force -ErrorAction SilentlyContinue)
|
||||
if ($baselineItems.Count -gt 0) {
|
||||
foreach ($baselineItem in $baselineItems) {
|
||||
Copy-Item -LiteralPath $baselineItem.FullName -Destination $snapshotRoot -Recurse -Force
|
||||
}
|
||||
$snapshotDir = $snapshotRoot
|
||||
}
|
||||
else {
|
||||
$snapshotDir = Join-Path $platformBaselineRoot "empty"
|
||||
New-Item -ItemType Directory -Path $snapshotDir -Force | Out-Null
|
||||
}
|
||||
|
||||
$legacySnapshots[$platform] = @{
|
||||
PreviousVersion = $previousVersion
|
||||
PreviousDir = $snapshotDir
|
||||
}
|
||||
}
|
||||
|
||||
$publishArguments = @(
|
||||
"run",
|
||||
"--project", $toolProject,
|
||||
"--",
|
||||
"publish",
|
||||
"--version", $Version,
|
||||
"--app-artifacts-root", $AppArtifactsRoot,
|
||||
"--installer-artifacts-root", $InstallerArtifactsRoot,
|
||||
"--output-dir", $publishedRoot,
|
||||
"--private-key", $PrivateKeyPath,
|
||||
"--baseline-root", $baselineRoot,
|
||||
"--channel", $Channel
|
||||
)
|
||||
|
||||
if (-not [string]::IsNullOrWhiteSpace($repoBaseUrl)) {
|
||||
$publishArguments += @("--repo-base-url", $repoBaseUrl)
|
||||
}
|
||||
if (-not [string]::IsNullOrWhiteSpace($installerBaseUrl)) {
|
||||
$publishArguments += @("--installer-base-url", $installerBaseUrl)
|
||||
}
|
||||
|
||||
& dotnet @publishArguments
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "PLONDS publish command failed."
|
||||
}
|
||||
|
||||
foreach ($config in $supportedPlatforms) {
|
||||
$platform = $config.Platform
|
||||
$artifactRoot = Join-Path $AppArtifactsRoot $config.ArtifactName
|
||||
if (-not (Test-Path -LiteralPath $artifactRoot)) {
|
||||
throw "App payload artifact root not found for ${platform}: $artifactRoot"
|
||||
}
|
||||
|
||||
$currentAppDir = Resolve-AppDirectory -SearchRoot $artifactRoot -Version $Version
|
||||
if ([string]::IsNullOrWhiteSpace($currentAppDir)) {
|
||||
throw "Unable to locate app payload directory for $platform under $artifactRoot"
|
||||
}
|
||||
|
||||
$distributionId = "plonds-$Version-$platform"
|
||||
$manifestPath = Join-Path $publishedRoot "manifests/$distributionId/plonds-filemap.json"
|
||||
$manifestSignaturePath = "$manifestPath.sig"
|
||||
|
||||
$legacyOutputDir = Join-Path $OutputDir "legacy/$platform"
|
||||
New-Item -ItemType Directory -Path $legacyOutputDir -Force | Out-Null
|
||||
|
||||
$legacyState = $legacySnapshots[$platform]
|
||||
& (Join-Path $PSScriptRoot "Generate-DeltaPackage.ps1") `
|
||||
-PreviousVersion $legacyState.PreviousVersion `
|
||||
-CurrentVersion $Version `
|
||||
-PreviousDir $legacyState.PreviousDir `
|
||||
-CurrentDir $currentAppDir `
|
||||
-OutputDir $legacyOutputDir
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Generate-DeltaPackage.ps1 failed for $platform"
|
||||
}
|
||||
|
||||
$legacyManifestPath = Join-Path $legacyOutputDir "files.json"
|
||||
$legacySignaturePath = Join-Path $legacyOutputDir "files.json.sig"
|
||||
& (Join-Path $PSScriptRoot "Sign-FileMap.ps1") `
|
||||
-FilesJsonPath $legacyManifestPath `
|
||||
-PrivateKeyPath $PrivateKeyPath `
|
||||
-OutputPath $legacySignaturePath
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Failed to sign legacy manifest for $platform"
|
||||
}
|
||||
|
||||
Copy-Item -LiteralPath $manifestPath -Destination (Join-Path $releaseAssetsRoot "plonds-filemap-$platform.json") -Force
|
||||
Copy-Item -LiteralPath $manifestSignaturePath -Destination (Join-Path $releaseAssetsRoot "plonds-filemap-$platform.json.sig") -Force
|
||||
Copy-Item -LiteralPath (Join-Path $publishedRoot "meta/distributions/$distributionId.json") -Destination (Join-Path $releaseAssetsRoot "plonds-distribution-$platform.json") -Force
|
||||
Copy-Item -LiteralPath (Join-Path $publishedRoot "meta/channels/$Channel/$platform/latest.json") -Destination (Join-Path $releaseAssetsRoot "plonds-latest-$platform.json") -Force
|
||||
|
||||
Copy-Item -LiteralPath $legacyManifestPath -Destination (Join-Path $releaseAssetsRoot "files-$platform.json") -Force
|
||||
Copy-Item -LiteralPath $legacySignaturePath -Destination (Join-Path $releaseAssetsRoot "files-$platform.json.sig") -Force
|
||||
Copy-Item -LiteralPath (Join-Path $legacyOutputDir "update.zip") -Destination (Join-Path $releaseAssetsRoot "update-$platform.zip") -Force
|
||||
}
|
||||
|
||||
if (-not [string]::IsNullOrWhiteSpace($S3Endpoint) -and -not [string]::IsNullOrWhiteSpace($S3Bucket)) {
|
||||
Upload-DirectoryToS3 -LocalRoot $publishedRoot -RemotePrefix "lanmountain/update"
|
||||
|
||||
foreach ($config in $supportedPlatforms) {
|
||||
$platform = $config.Platform
|
||||
$platformBaselineRoot = Join-Path $baselineRoot $platform
|
||||
$baselineCurrentDir = Join-Path $platformBaselineRoot "current"
|
||||
$baselineVersionPath = Join-Path $platformBaselineRoot "version.txt"
|
||||
|
||||
Upload-DirectoryToS3 `
|
||||
-LocalRoot $baselineCurrentDir `
|
||||
-RemotePrefix "lanmountain/update/baselines/$platform/current" `
|
||||
-DeleteExtraRemoteObjects
|
||||
|
||||
Upload-FileToS3 `
|
||||
-LocalPath $baselineVersionPath `
|
||||
-RemoteKey "lanmountain/update/baselines/$platform/version.txt"
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "PLONDS publish staging completed."
|
||||
Write-Host "Published root: $publishedRoot"
|
||||
Write-Host "Release assets: $releaseAssetsRoot"
|
||||
@@ -1,4 +1,4 @@
|
||||
param(
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$FilesJsonPath,
|
||||
|
||||
@@ -11,46 +11,16 @@ param(
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
if ($PSVersionTable.PSVersion.Major -lt 7) {
|
||||
throw "Sign-FileMap.ps1 requires PowerShell 7 or newer."
|
||||
}
|
||||
|
||||
if (-not (Test-Path -LiteralPath $FilesJsonPath)) {
|
||||
throw "Manifest file not found: $FilesJsonPath"
|
||||
}
|
||||
|
||||
if (-not (Test-Path -LiteralPath $PrivateKeyPath)) {
|
||||
throw "Private key file not found: $PrivateKeyPath"
|
||||
}
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($OutputPath)) {
|
||||
$OutputPath = "$FilesJsonPath.sig"
|
||||
}
|
||||
|
||||
$resolvedManifestPath = (Resolve-Path -LiteralPath $FilesJsonPath).Path
|
||||
$manifestBytes = [System.IO.File]::ReadAllBytes($resolvedManifestPath)
|
||||
|
||||
$privateKeyPem = Get-Content -LiteralPath $PrivateKeyPath -Raw
|
||||
if ([string]::IsNullOrWhiteSpace($privateKeyPem)) {
|
||||
throw "Private key PEM is empty: $PrivateKeyPath"
|
||||
$toolProject = Join-Path $PSScriptRoot "..\PenguinLogisticsOnlineNetworkDistributionSystem\src\Plonds.Tool\Plonds.Tool.csproj"
|
||||
if (-not (Test-Path -LiteralPath $toolProject)) {
|
||||
throw "PLONDS tool project not found: $toolProject"
|
||||
}
|
||||
|
||||
$rsa = [System.Security.Cryptography.RSA]::Create()
|
||||
try {
|
||||
$rsa.ImportFromPem($privateKeyPem)
|
||||
$signatureBytes = $rsa.SignData(
|
||||
$manifestBytes,
|
||||
[System.Security.Cryptography.HashAlgorithmName]::SHA256,
|
||||
[System.Security.Cryptography.RSASignaturePadding]::Pkcs1
|
||||
)
|
||||
& dotnet run --project $toolProject -- sign --manifest $FilesJsonPath --private-key $PrivateKeyPath --output $OutputPath
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "PLONDS sign command failed."
|
||||
}
|
||||
finally {
|
||||
$rsa.Dispose()
|
||||
}
|
||||
|
||||
$signatureBase64 = [Convert]::ToBase64String($signatureBytes)
|
||||
[System.IO.File]::WriteAllText($OutputPath, $signatureBase64, [System.Text.Encoding]::ASCII)
|
||||
|
||||
Write-Host "Signed manifest file."
|
||||
Write-Host "Manifest: $FilesJsonPath"
|
||||
Write-Host "Signature: $OutputPath"
|
||||
|
||||
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