Compare commits

..

17 Commits

Author SHA1 Message Date
lincube
3f927c41c8 ci: fix pdcc publish workdir bootstrap 2026-04-20 21:29:45 +08:00
lincube
44725d7ff3 ci: add pdcc publish heartbeat and timeout 2026-04-20 20:47:48 +08:00
lincube
e623aef350 ci: publish pdcc subchannels in one pass 2026-04-20 19:38:54 +08:00
lincube
63d5165860 ci: harden local pdc mock transport handling 2026-04-20 18:40:19 +08:00
lincube
6d513096d3 ci: pin pdcc client version separately from app version 2026-04-20 18:16:17 +08:00
lincube
f487a32149 ci: wire aws cli credentials for rainyun s3 2026-04-20 18:05:32 +08:00
lincube
a553f2f7aa Update App.axaml.cs 2026-04-20 17:42:16 +08:00
lincube
f03b74ff32 ci: fix pdcc variable mapping and pdc signing prechecks 2026-04-20 17:30:48 +08:00
lincube
bc1520a5d8 ci: make local pdc mock diff return empty for fast fallback 2026-04-20 16:41:34 +08:00
lincube
46341edbea ci: package pdcc subchannels with generated filemap and changelog 2026-04-20 15:39:55 +08:00
lincube
f421f574e1 ci: decouple pdcc installer version from publish config version 2026-04-20 15:28:11 +08:00
lincube
8ea8c684a9 ci: set pdcc version variable from release version 2026-04-20 15:19:16 +08:00
lincube
b411d91b35 ci: create pdcc publish root before invoking client 2026-04-20 15:07:14 +08:00
lincube
a2f0af9031 ci: ensure pdcc signing passphrase env is always set 2026-04-20 14:56:27 +08:00
lincube
5861d73964 ci: fallback pdcc signing key to update private key 2026-04-20 14:44:00 +08:00
lincube
64975d5752 ci: fix pdc mock process log redirection 2026-04-20 14:34:16 +08:00
lincube
8c58b1c43e ci: add local pdc mock fallback for release publish 2026-04-20 14:25:17 +08:00
5 changed files with 566 additions and 30 deletions

View File

@@ -721,16 +721,23 @@ jobs:
VERSION: ${{ needs.prepare.outputs.version }}
PRIMARY_VERSION: ${{ needs.prepare.outputs.version }}
PDCC_primaryVersion: ${{ needs.prepare.outputs.version }}
PDCC_VERSION: ${{ vars.PDC_CLIENT_VERSION }}
PDCC_version: ${{ needs.prepare.outputs.version }}
PDC_CLIENT_VERSION: ${{ vars.PDC_CLIENT_VERSION || '1.0.1.0' }}
S3_ENDPOINT: ${{ vars.S3_ENDPOINT }}
S3_BUCKET: ${{ vars.S3_BUCKET }}
S3_REGION: ${{ vars.S3_REGION }}
PDC_ENDPOINT: ${{ vars.PDC_ENDPOINT }}
PDC_TOKEN: ${{ secrets.PDC_TOKEN }}
PDC_SIGNING_KEY: ${{ secrets.PDC_SIGNING_KEY }}
PDC_SIGNING_KEY_PS: ${{ secrets.PDC_SIGNING_KEY_PS }}
UPDATE_PRIVATE_KEY_PEM: ${{ secrets.UPDATE_PRIVATE_KEY_PEM }}
S3_ACCESS_KEY: ${{ secrets.S3_ACCESS_KEY }}
S3_SECRET_KEY: ${{ secrets.S3_SECRET_KEY }}
AWS_ACCESS_KEY_ID: ${{ secrets.S3_ACCESS_KEY }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.S3_SECRET_KEY }}
AWS_DEFAULT_REGION: ${{ vars.S3_REGION }}
AWS_REGION: ${{ vars.S3_REGION }}
AWS_EC2_METADATA_DISABLED: "true"
steps:
- name: Checkout
uses: actions/checkout@v4
@@ -756,18 +763,44 @@ jobs:
run: |
$ErrorActionPreference = "Stop"
function Resolve-PgpPrivateKey([string]$value) {
if ([string]::IsNullOrWhiteSpace($value)) {
return $null
}
$trimmed = $value.Trim()
if ($trimmed -match '-----BEGIN PGP PRIVATE KEY BLOCK-----') {
return $trimmed
}
try {
$decoded = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($trimmed)).Trim()
if ($decoded -match '-----BEGIN PGP PRIVATE KEY BLOCK-----') {
return $decoded
}
}
catch {
}
return $trimmed
}
if ([string]::IsNullOrWhiteSpace($env:S3_ENDPOINT) -or
[string]::IsNullOrWhiteSpace($env:S3_BUCKET)) {
throw "Missing required S3 variables."
}
if ([string]::IsNullOrWhiteSpace($env:PDC_SIGNING_KEY)) {
if ([string]::IsNullOrWhiteSpace($env:UPDATE_PRIVATE_KEY_PEM)) {
throw "Missing UPDATE_PRIVATE_KEY_PEM or PDC_SIGNING_KEY."
}
$env:PDC_SIGNING_KEY = $env:UPDATE_PRIVATE_KEY_PEM
$resolvedSigningKey = Resolve-PgpPrivateKey $env:PDC_SIGNING_KEY
if ([string]::IsNullOrWhiteSpace($resolvedSigningKey)) {
$resolvedSigningKey = Resolve-PgpPrivateKey $env:UPDATE_PRIVATE_KEY_PEM
}
if ([string]::IsNullOrWhiteSpace($resolvedSigningKey)) {
throw "Missing PDC_SIGNING_KEY (PGP private key)."
}
if ($resolvedSigningKey -notmatch '-----BEGIN PGP PRIVATE KEY BLOCK-----') {
throw "PDC signing key format is invalid. Please provide armored OpenPGP private key in PDC_SIGNING_KEY."
}
Add-Content -Path $env:GITHUB_ENV -Value "PDC_SIGNING_KEY<<EOF`n$resolvedSigningKey`nEOF"
$workRoot = Join-Path $PWD "pdc-work"
if (Test-Path $workRoot) {
@@ -778,19 +811,137 @@ jobs:
$template = Get-Content -Path "phainon.yml" -Raw
$resolved = $template `
-replace '__FILE_REPO_ROOT__', "$($env:S3_ENDPOINT.TrimEnd('/'))/$($env:S3_BUCKET)/lanmountain/update/repo/" `
-replace '__ARCHIVE_ROOT__', "$($env:S3_ENDPOINT.TrimEnd('/'))/$($env:S3_BUCKET)/lanmountain/update/installers/"
-replace '__ARCHIVE_ROOT__', "$($env:S3_ENDPOINT.TrimEnd('/'))/$($env:S3_BUCKET)/lanmountain/update/archive"
Set-Content -Path (Join-Path $workRoot "phainon.resolved.yml") -Value $resolved -NoNewline
python3 -m pip install --user --upgrade awscli
Add-Content -Path $env:GITHUB_PATH -Value "$HOME/.local/bin"
- name: Verify S3 credentials and endpoint
shell: pwsh
run: |
$ErrorActionPreference = "Stop"
function Invoke-AwsChecked([string[]]$Arguments) {
& aws @Arguments
if ($LASTEXITCODE -ne 0) {
throw "aws command failed: aws $($Arguments -join ' ')"
}
}
$probeDir = Join-Path $PWD "pdc-work"
New-Item -ItemType Directory -Path $probeDir -Force | Out-Null
$probeFile = Join-Path $probeDir "s3-probe.txt"
Set-Content -Path $probeFile -Value "lanmountain pdc probe $(Get-Date -Format o)" -NoNewline
$probeKey = "lanmountain/update/probe/$($env:GITHUB_RUN_ID)-$($env:GITHUB_RUN_ATTEMPT).txt"
Invoke-AwsChecked @("--endpoint-url", "$env:S3_ENDPOINT", "--region", "$env:S3_REGION", "s3", "cp", $probeFile, "s3://$env:S3_BUCKET/$probeKey", "--only-show-errors")
Invoke-AwsChecked @("--endpoint-url", "$env:S3_ENDPOINT", "--region", "$env:S3_REGION", "s3", "rm", "s3://$env:S3_BUCKET/$probeKey", "--only-show-errors")
Write-Host "S3 probe succeeded."
- name: Bootstrap PDC Endpoint and Token
shell: pwsh
run: |
$ErrorActionPreference = "Stop"
$endpoint = $env:PDC_ENDPOINT
if ([string]::IsNullOrWhiteSpace($endpoint)) {
$endpoint = "http://127.0.0.1:18765"
}
$token = $env:PDC_TOKEN
if ([string]::IsNullOrWhiteSpace($token)) {
$token = "lmd-pdc-local-token"
}
Add-Content -Path $env:GITHUB_ENV -Value "PDC_ENDPOINT=$endpoint"
Add-Content -Path $env:GITHUB_ENV -Value "PDC_TOKEN=$token"
Write-Host "Using PDC endpoint: $endpoint"
- name: Start Local PDC Mock (Fallback)
shell: pwsh
run: |
$ErrorActionPreference = "Stop"
if ([string]::IsNullOrWhiteSpace($env:PDC_ENDPOINT)) {
throw "PDC_ENDPOINT is empty after bootstrap."
}
$uri = [Uri]$env:PDC_ENDPOINT
$isLocalHost = $uri.Host -eq "127.0.0.1" -or $uri.Host -eq "localhost"
if (-not $isLocalHost) {
Write-Host "Using external PDC endpoint: $($env:PDC_ENDPOINT)"
exit 0
}
if ([string]::IsNullOrWhiteSpace($env:PDC_TOKEN)) {
throw "PDC_TOKEN is empty after bootstrap."
}
$port = if ($uri.Port -gt 0) { $uri.Port } else { 18765 }
$dataDir = Join-Path $PWD "pdc-output/mock-pdc"
$workDir = Join-Path $PWD "pdc-work"
$logPath = Join-Path $workDir "pdc-mock.out.log"
$errLogPath = Join-Path $workDir "pdc-mock.err.log"
New-Item -ItemType Directory -Path $workDir -Force | Out-Null
New-Item -ItemType Directory -Path $dataDir -Force | Out-Null
if (Test-Path $logPath) {
Remove-Item -LiteralPath $logPath -Force
}
if (Test-Path $errLogPath) {
Remove-Item -LiteralPath $errLogPath -Force
}
$args = @(
"scripts/pdc-mock-server.py",
"--host", "127.0.0.1",
"--port", $port.ToString(),
"--token", $env:PDC_TOKEN,
"--data-dir", $dataDir
)
$process = Start-Process -FilePath "python3" -ArgumentList $args -PassThru -RedirectStandardOutput $logPath -RedirectStandardError $errLogPath
if (-not $process) {
throw "Failed to launch PDC mock server."
}
$healthUrl = "http://127.0.0.1:$port/healthz"
$ready = $false
for ($i = 0; $i -lt 20; $i++) {
Start-Sleep -Seconds 1
try {
$response = Invoke-WebRequest -Uri $healthUrl -Method Get -TimeoutSec 2
if ($response.StatusCode -eq 200) {
$ready = $true
break
}
}
catch {
}
}
if (-not $ready) {
if (Test-Path $logPath) {
Write-Host "===== pdc-mock stdout ====="
Get-Content -LiteralPath $logPath -ErrorAction SilentlyContinue | Write-Host
}
if (Test-Path $errLogPath) {
Write-Host "===== pdc-mock stderr ====="
Get-Content -LiteralPath $errLogPath -ErrorAction SilentlyContinue | Write-Host
}
throw "PDC mock server did not become ready in time. See $logPath and $errLogPath."
}
Write-Host "Local PDC mock is running at http://127.0.0.1:$port"
- name: Install PDCC
shell: pwsh
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
./scripts/Install-Pdcc.ps1 -Repository "ClassIsland/PhainonDistributionCenter" -OutputDir "./pdcc"
./scripts/Install-Pdcc.ps1 -Repository "ClassIsland/PhainonDistributionCenter" -Version "$env:PDC_CLIENT_VERSION" -OutputDir "./pdcc"
- name: Publish with PDCC
shell: pwsh
@@ -804,16 +955,43 @@ jobs:
$env:PDC_Token = $env:PDC_TOKEN
$env:S3_AccessKey = $env:S3_ACCESS_KEY
$env:S3_SecretKey = $env:S3_SECRET_KEY
if ([string]::IsNullOrWhiteSpace($env:PDC_SigningKey)) {
$env:PDC_SigningKey = $env:PDC_SIGNING_KEY
$signingKeyPs = $env:PDC_SIGNING_KEY_PS
if ([string]::IsNullOrWhiteSpace($signingKeyPs)) {
# Keep a non-empty value so PDCC required-env check passes on Linux runners.
$signingKeyPs = " "
}
$env:PDC_SigningKeyPs = $signingKeyPs
# Map config variables with exact names required by phainon placeholders.
$env:PDCC_version = $env:VERSION
$env:PDCC_primaryVersion = $env:PRIMARY_VERSION
$signingKey = $env:PDC_SIGNING_KEY
if ([string]::IsNullOrWhiteSpace($signingKey)) {
$signingKey = $env:UPDATE_PRIVATE_KEY_PEM
}
if ([string]::IsNullOrWhiteSpace($signingKey)) {
throw "Missing PDC signing key: PDC_SIGNING_KEY or UPDATE_PRIVATE_KEY_PEM."
}
if ($signingKey -notmatch '-----BEGIN PGP PRIVATE KEY BLOCK-----') {
throw "PDC signing key is not an armored OpenPGP private key."
}
$env:PDC_SigningKey = $signingKey
$workDir = Join-Path $PWD "pdc-work"
$stageRoot = Join-Path $PWD "pdc-stage"
$payloadRoot = Join-Path $PWD "payload-artifacts"
$installerRoot = Join-Path $PWD "installer-artifacts"
$outRoot = Join-Path $PWD "pdc-output"
$publishRoot = Join-Path $outRoot "published"
$client = Join-Path $PWD "pdcc/PhainonDistributionCenter.Client"
$config = Join-Path $PWD "pdc-work/phainon.resolved.yml"
$config = Join-Path $workDir "phainon.resolved.yml"
New-Item -ItemType Directory -Path $workDir -Force | Out-Null
if (-not (Test-Path -LiteralPath $config)) {
throw "Resolved PDCC config was not found: $config"
}
if (-not (Test-Path -LiteralPath $client)) {
throw "PDCC client was not found: $client"
}
if (Test-Path $stageRoot) {
Remove-Item -LiteralPath $stageRoot -Recurse -Force
@@ -823,6 +1001,7 @@ jobs:
}
New-Item -ItemType Directory -Path $stageRoot -Force | Out-Null
New-Item -ItemType Directory -Path $outRoot -Force | Out-Null
New-Item -ItemType Directory -Path $publishRoot -Force | Out-Null
$payloadArtifacts = Get-ChildItem -LiteralPath $payloadRoot -Directory
if (-not $payloadArtifacts) {
@@ -844,23 +1023,129 @@ jobs:
$stagedPayloadDir = Join-Path $stageRoot "payloads/$platformKey"
./scripts/Prepare-PdccOut.ps1 -SourceDir $payloadArtifact.FullName -OutputDir $stagedPayloadDir
$subChannel = ($platformKey -replace '-', '_') + "_release_folderClassic"
$env:PDC_SUBCHANNEL = $subChannel
Push-Location $stagedPayloadDir
try {
& $client $config Publish $env:PRIMARY_VERSION $env:VERSION (Join-Path $outRoot "published/$platformKey")
if ($LASTEXITCODE -ne 0) {
throw "PDCC Publish failed for $platformKey."
}
$parts = $platformKey.Split('-', 2)
if ($parts.Count -lt 2) {
throw "Invalid platform key format: $platformKey"
}
finally {
Pop-Location
$os = $parts[0]
$arch = $parts[1]
$packageName = "LanMountainDesktop_app_${os}_${arch}_release_folder.zip"
$packagePath = Join-Path $publishRoot $packageName
Write-Host "Preparing PDCC subchannel package for $platformKey..."
& $client $config GenerateFileMap $stagedPayloadDir
if ($LASTEXITCODE -ne 0) {
throw "PDCC GenerateFileMap failed for $platformKey."
}
if (Test-Path $packagePath) {
Remove-Item -LiteralPath $packagePath -Force
}
Compress-Archive -Path (Join-Path $stagedPayloadDir '*') -DestinationPath $packagePath -Force
$packageSizeMb = [Math]::Round((Get-Item -LiteralPath $packagePath).Length / 1MB, 2)
Write-Host "Prepared package: $packageName ($packageSizeMb MB)"
}
$subchannelPackages = Get-ChildItem -LiteralPath $publishRoot -File -Filter "LanMountainDesktop_app_*_release_folder.zip"
if (-not $subchannelPackages) {
throw "No PDCC subchannel packages were prepared."
}
Write-Host "Publishing $($subchannelPackages.Count) subchannels in a single PDCC Publish run..."
$subchannelPackages | Sort-Object Name | ForEach-Object { Write-Host " - $($_.Name)" }
$publishStdOut = Join-Path $workDir "pdcc-publish.stdout.log"
$publishStdErr = Join-Path $workDir "pdcc-publish.stderr.log"
if (Test-Path $publishStdOut) {
Remove-Item -LiteralPath $publishStdOut -Force
}
if (Test-Path $publishStdErr) {
Remove-Item -LiteralPath $publishStdErr -Force
}
function Write-NewLogLines([string]$path, [ref]$lineCount, [string]$prefix) {
if (-not (Test-Path -LiteralPath $path)) {
return
}
$lines = Get-Content -LiteralPath $path -ErrorAction SilentlyContinue
if ($null -eq $lines) {
return
}
if ($lines -is [string]) {
$lines = @($lines)
}
if ($lines.Count -le $lineCount.Value) {
return
}
for ($i = $lineCount.Value; $i -lt $lines.Count; $i++) {
Write-Host "[$prefix] $($lines[$i])"
}
$lineCount.Value = $lines.Count
}
$publishArgs = @(
$config,
"Publish",
$env:PRIMARY_VERSION,
$env:VERSION,
$publishRoot
)
$publishTimeoutMinutes = 20
if (-not [string]::IsNullOrWhiteSpace($env:PDC_PUBLISH_TIMEOUT_MINUTES)) {
$parsedTimeout = 0
if ([int]::TryParse($env:PDC_PUBLISH_TIMEOUT_MINUTES, [ref]$parsedTimeout) -and $parsedTimeout -gt 0) {
$publishTimeoutMinutes = $parsedTimeout
}
}
$publishProcess = Start-Process `
-FilePath $client `
-ArgumentList $publishArgs `
-WorkingDirectory $publishRoot `
-RedirectStandardOutput $publishStdOut `
-RedirectStandardError $publishStdErr `
-PassThru
if (-not $publishProcess) {
throw "Failed to start PDCC Publish process."
}
Write-Host "PDCC Publish process started. PID=$($publishProcess.Id), timeout=${publishTimeoutMinutes}m"
$publishStart = Get-Date
$stdoutLineCount = 0
$stderrLineCount = 0
while (-not $publishProcess.HasExited) {
Start-Sleep -Seconds 15
$publishProcess.Refresh()
Write-NewLogLines -path $publishStdOut -lineCount ([ref]$stdoutLineCount) -prefix "pdcc"
Write-NewLogLines -path $publishStdErr -lineCount ([ref]$stderrLineCount) -prefix "pdcc-err"
$elapsed = (Get-Date) - $publishStart
Write-Host ("PDCC Publish heartbeat: elapsed={0:mm\\:ss}, pid={1}" -f $elapsed, $publishProcess.Id)
if ($elapsed.TotalMinutes -ge $publishTimeoutMinutes) {
Stop-Process -Id $publishProcess.Id -Force -ErrorAction SilentlyContinue
throw "PDCC Publish exceeded timeout of ${publishTimeoutMinutes} minutes."
}
}
Write-NewLogLines -path $publishStdOut -lineCount ([ref]$stdoutLineCount) -prefix "pdcc"
Write-NewLogLines -path $publishStdErr -lineCount ([ref]$stderrLineCount) -prefix "pdcc-err"
if ($publishProcess.ExitCode -ne 0) {
throw "PDCC Publish failed with exit code $($publishProcess.ExitCode)."
}
if (Test-Path (Join-Path $stageRoot "installers")) {
aws --endpoint-url "$env:S3_ENDPOINT" s3 sync (Join-Path $stageRoot "installers") "s3://$env:S3_BUCKET/lanmountain/update/installers/" --only-show-errors
& aws --endpoint-url "$env:S3_ENDPOINT" --region "$env:S3_REGION" s3 sync (Join-Path $stageRoot "installers") "s3://$env:S3_BUCKET/lanmountain/update/installers/" --only-show-errors
if ($LASTEXITCODE -ne 0) {
throw "aws s3 sync failed for installer mirror upload."
}
}
- name: Upload PDC Assets
@@ -872,6 +1157,40 @@ jobs:
if-no-files-found: error
retention-days: 90
- name: Dump PDC Diagnostics
if: failure()
shell: pwsh
run: |
if (Test-Path "pdc-work/pdc-mock.out.log") {
Write-Host "===== pdc-mock stdout ====="
Get-Content "pdc-work/pdc-mock.out.log" -ErrorAction SilentlyContinue | Write-Host
}
if (Test-Path "pdc-work/pdc-mock.err.log") {
Write-Host "===== pdc-mock stderr ====="
Get-Content "pdc-work/pdc-mock.err.log" -ErrorAction SilentlyContinue | Write-Host
}
if (Test-Path "pdc-output/mock-pdc") {
Write-Host "===== pdc-mock captured payloads ====="
Get-ChildItem "pdc-output/mock-pdc" -Recurse -File | ForEach-Object {
Write-Host "--- $($_.FullName) ---"
Get-Content $_.FullName -ErrorAction SilentlyContinue | Write-Host
}
}
- name: Upload PDC Diagnostics Artifact
if: always()
uses: actions/upload-artifact@v4
with:
name: pdc-diagnostics
path: |
pdc-work/pdc-mock*.log
pdc-work/pdcc-publish*.log
pdc-output/mock-pdc/**
if-no-files-found: ignore
retention-days: 30
github-release:
needs: [ prepare, build-windows, build-linux, build-macos, publish-pdc ]
runs-on: ubuntu-latest

View File

@@ -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 窗口一直显示

View File

@@ -18,6 +18,15 @@ components:
variables:
number: 0
fileRepoRoot: "__FILE_REPO_ROOT__"
archiveRoot: "__ARCHIVE_ROOT__"
archiveRoot: "__ARCHIVE_ROOT__/$(primaryVersion)/$(version)/"
bucketKeyRoot: "lanmountain/update/repo/"
archiveBucketKeyRoot: "lanmountain/update/installers/"
archiveBucketKeyRoot: "lanmountain/update/archive/$(primaryVersion)/$(version)/"
appChangeLogPath: "$(thisFileDir)/../CHANGELOG.md"
appChangeLogTemplate: |
$(changeLog)
---
## Checksums And Downloads
$(hashes)

View File

@@ -36,10 +36,6 @@ if ([string]::IsNullOrWhiteSpace($releaseTag)) {
$releaseTag = $env:PDCC_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

206
scripts/pdc-mock-server.py Normal file
View 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()