Compare commits

...
2 Commits
Author SHA1 Message Date
linkong 352b34e7c6 release: bump version to 0.79.1
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
2026-11-24 21:00:42 +08:00
linkong 1e9508f2f1 ci: deploy published Planet releases by image digest
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
2026-11-24 17:27:54 +08:00
32 changed files with 2819 additions and 97 deletions

No files matched your search

+12 -5
View File
@@ -179,12 +179,19 @@ Push to remote:
### Step 9 — Publish and verify the Gitea Release
When remote publication is requested, verify the remote tag points to the
release commit. Check the tag's Gitea Actions run and its release job. A queued
run without an online runner does not publish anything.
release commit. For `gitea.rclaw.top/linkong/planet`, publish from the workstation
using the command below. The publisher builds the three production images and
the desktop packages from the tag. A published stable release triggers the
server's two-minute Compose deployment check. The workstation can go offline
after publication. Check the live update manifest and the running image digests
before reporting production deployment complete.
If the job cannot start or finish, use the packaged client artifacts for the
exact tag. Reuse verified artifacts when available, or build with Bun from the
tag in a clean checkout. Use an asset directory that contains only this release.
```bash
python3 scripts/release_publish.py --tag vx.x.x --use-git-credential
```
When verified desktop artifacts for the exact tag already exist, pass their
directory explicitly. A queued Gitea Actions run does not block local publication.
```bash
python3 scripts/release_publish.py --tag vx.x.x --assets-dir client/release --dry-run
+15 -25
View File
@@ -4,8 +4,7 @@ on:
push:
branches:
- main
tags:
- "v*"
# Tagged production releases are published on demand from the workstation.
workflow_dispatch:
env:
@@ -17,18 +16,18 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Resolve image tags
id: meta
run: |
echo "sha_tag=${GITHUB_SHA}" >> "$GITHUB_OUTPUT"
if printf "%s" "${GITHUB_REF}" | grep -q '^refs/tags/v'; then
echo "release_tag=${GITHUB_REF_NAME}" >> "$GITHUB_OUTPUT"
else
echo "release_tag=" >> "$GITHUB_OUTPUT"
fi
- name: Login to registry
run: echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login "$REGISTRY" -u "${{ secrets.REGISTRY_USER }}" --password-stdin
- name: Build and push images
env:
REGISTRY_USER: ${{ secrets.REGISTRY_USER }}
REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
run: printf '%s' "$REGISTRY_PASSWORD" | docker login "$REGISTRY" -u "$REGISTRY_USER" --password-stdin
- name: Publish immutable production images
if: startsWith(github.ref, 'refs/tags/v')
run: |
export PLANET_RELEASE_DOCKER_CONFIG="${DOCKER_CONFIG:-$HOME/.docker}"
python3 scripts/production_release.py "$GITHUB_REF_NAME"
- name: Build and push staging images
if: "!startsWith(github.ref, 'refs/tags/v')"
run: |
for service in frontend admin backend aiprovider; do
extra_build_args=""
@@ -52,18 +51,13 @@ jobs:
;;
esac
image="$REGISTRY/$IMAGE_NAMESPACE/$service:${{ steps.meta.outputs.sha_tag }}"
image="$REGISTRY/$IMAGE_NAMESPACE/$service:$GITHUB_SHA"
docker build $extra_build_args -t "$image" -f "$dockerfile" "$context"
docker push "$image"
if [ -n "${{ steps.meta.outputs.release_tag }}" ]; then
release_image="$REGISTRY/$IMAGE_NAMESPACE/$service:${{ steps.meta.outputs.release_tag }}"
docker tag "$image" "$release_image"
docker push "$release_image"
fi
done
client_release:
needs: images
if: startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
steps:
@@ -82,12 +76,8 @@ jobs:
- name: Publish Gitea Release with client packages
env:
GITEA_TOKEN: ${{ secrets.RELEASE_TOKEN || github.token }}
CLIENT_UPDATE_PUBLISH_URL: ${{ secrets.CLIENT_UPDATE_PUBLISH_URL }}
CLIENT_UPDATE_PUBLISH_TOKEN: ${{ secrets.CLIENT_UPDATE_PUBLISH_TOKEN }}
run: |
python3 scripts/release_publish.py \
--tag "${GITHUB_REF_NAME}" \
--assets-dir client/release \
--changelog docs/CHANGELOG.md \
--hotfix-publish-url "${CLIENT_UPDATE_PUBLISH_URL}" \
--hotfix-publish-token "${CLIENT_UPDATE_PUBLISH_TOKEN}"
--changelog docs/CHANGELOG.md
+1 -1
View File
@@ -1 +1 @@
0.79.0
0.79.1
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "planet-client",
"version": "0.79.0",
"version": "0.79.1",
"description": "Intelligent Planet Program - Native Electron Earth Viewer",
"private": true,
"packageManager": "bun@1",
+137 -12
View File
@@ -2,6 +2,7 @@ import fs from 'node:fs'
import path from 'node:path'
export type SplashTheme = 'singularity' | 'off'
export type GpuRenderMode = 'auto' | 'high-performance' | 'low-power' | 'software'
export interface ServerEndpoints {
backendUrl: string
@@ -11,6 +12,23 @@ export interface ServerEndpoints {
export interface PersistedUserConfig extends Partial<ServerEndpoints> {
splashTheme?: SplashTheme
gpuMode?: GpuRenderMode
}
export type GpuHandoffTarget = 'default' | 'high-performance' | 'low-power' | 'software'
export function normalizeGpuHandoffTarget(raw: unknown): GpuHandoffTarget | undefined {
if (typeof raw !== 'string') return undefined
const normalized = raw.trim().toLowerCase()
if (
normalized === 'default' ||
normalized === 'high-performance' ||
normalized === 'low-power' ||
normalized === 'software'
) {
return normalized
}
return undefined
}
export interface DesktopLaunchFlags {
@@ -22,11 +40,15 @@ export interface DesktopLaunchFlags {
smokeOutputPath: string | null
deepLinkUrl: string | null
splashThemeOverride?: SplashTheme
gpuModeOverride?: GpuRenderMode
gpuHandoff: boolean
gpuHandoffTarget?: GpuHandoffTarget
}
export interface DesktopRuntimeConfig extends ServerEndpoints, DesktopLaunchFlags {
wsUrl: string
splashTheme: SplashTheme
gpuMode: GpuRenderMode
}
const LEGACY_ACTIVE_THEMES: ReadonlySet<string> = new Set([
@@ -47,6 +69,35 @@ export function normalizeSplashTheme(
return LEGACY_ACTIVE_THEMES.has(normalized) ? 'singularity' : fallback
}
export function normalizeGpuMode(
raw: unknown,
fallback: GpuRenderMode = 'auto',
): GpuRenderMode {
if (typeof raw !== 'string') return fallback
const normalized = raw.trim().toLowerCase()
if (normalized === 'auto') return 'auto'
if (
normalized === 'high-performance' ||
normalized === 'high' ||
normalized === 'discrete' ||
normalized === 'dgpu'
) {
return 'high-performance'
}
if (
normalized === 'low-power' ||
normalized === 'low' ||
normalized === 'integrated' ||
normalized === 'igpu'
) {
return 'low-power'
}
if (normalized === 'software' || normalized === 'cpu' || normalized === 'swiftshader') {
return 'software'
}
return fallback
}
export const DEFAULT_ENDPOINTS: Readonly<ServerEndpoints> = {
backendUrl: 'https://rclaw.top',
adminUrl: 'https://admin.rclaw.top',
@@ -115,6 +166,7 @@ export function parseLaunchArgs(argv: string[]): {
headlessSmoke: false,
smokeOutputPath: null,
deepLinkUrl: null,
gpuHandoff: false,
}
for (let i = 0; i < argv.length; i += 1) {
@@ -136,6 +188,22 @@ export function parseLaunchArgs(argv: string[]): {
flags.splashThemeOverride = normalizeSplashTheme(arg.slice('--splash-theme='.length))
} else if (arg === '--splash-theme' && argv[i + 1]) {
flags.splashThemeOverride = normalizeSplashTheme(argv[++i])
} else if (arg.startsWith('--gpu-mode=')) {
flags.gpuModeOverride = normalizeGpuMode(arg.slice('--gpu-mode='.length))
} else if (arg === '--gpu-mode' && argv[i + 1]) {
flags.gpuModeOverride = normalizeGpuMode(argv[++i])
} else if (arg === '--software-gl') {
flags.gpuModeOverride = 'software'
} else if (arg === '--low-power-gpu') {
flags.gpuModeOverride = 'low-power'
} else if (arg === '--high-performance-gpu') {
flags.gpuModeOverride = 'high-performance'
} else if (arg === '--gpu-handoff') {
flags.gpuHandoff = true
} else if (arg.startsWith('--gpu-handoff-target=')) {
flags.gpuHandoffTarget = normalizeGpuHandoffTarget(arg.slice('--gpu-handoff-target='.length))
} else if (arg === '--gpu-handoff-target' && argv[i + 1]) {
flags.gpuHandoffTarget = normalizeGpuHandoffTarget(argv[++i])
} else if (arg === '--fullscreen') {
flags.fullscreen = true
} else if (arg === '--kiosk') {
@@ -157,6 +225,55 @@ export function parseLaunchArgs(argv: string[]): {
return { endpoints, flags }
}
function getPortableConfigPaths(exeDir: string, resourcesDir?: string): string[] {
const candidates: string[] = []
if (exeDir) {
candidates.push(path.join(exeDir, 'planet-earth.json'))
}
if (resourcesDir) {
candidates.push(path.join(resourcesDir, 'planet-earth.json'))
}
return candidates
}
function readFirstPortableConfig(paths: string[]): PersistedUserConfig {
for (const candidate of paths) {
const data = readJsonFileSafe(candidate)
if (Object.keys(data).length > 0) {
return data
}
}
return {}
}
export function readPreReadyGpuMode(options: {
userDataDir: string
exeDir: string
resourcesDir?: string
argv: string[]
env?: NodeJS.ProcessEnv
}): GpuRenderMode {
const env = options.env ?? process.env
const { flags } = parseLaunchArgs(options.argv)
const portable = readFirstPortableConfig(getPortableConfigPaths(options.exeDir, options.resourcesDir))
const userSaved = options.userDataDir ? readJsonFileSafe(path.join(options.userDataDir, 'config.json')) : {}
return normalizeGpuMode(
flags.gpuModeOverride ?? env.PLANET_GPU_MODE ?? portable.gpuMode ?? userSaved.gpuMode,
'auto',
)
}
export function readPreReadyGpuHandoff(argv: string[]): {
gpuHandoff: boolean
gpuHandoffTarget?: GpuHandoffTarget
} {
const { flags } = parseLaunchArgs(argv)
return {
gpuHandoff: flags.gpuHandoff,
gpuHandoffTarget: flags.gpuHandoffTarget,
}
}
export class DesktopConfigStore {
private readonly userConfigPath: string
private readonly portableConfigPaths: string[]
@@ -172,10 +289,7 @@ export class DesktopConfigStore {
env?: NodeJS.ProcessEnv
}) {
this.userConfigPath = path.join(options.userDataDir, 'config.json')
this.portableConfigPaths = [
path.join(options.exeDir, 'planet-earth.json'),
...(options.resourcesDir ? [path.join(options.resourcesDir, 'planet-earth.json')] : []),
]
this.portableConfigPaths = getPortableConfigPaths(options.exeDir, options.resourcesDir)
const parsed = parseLaunchArgs(options.argv)
this.cliEndpoints = parsed.endpoints
this.launchFlags = parsed.flags
@@ -184,14 +298,7 @@ export class DesktopConfigStore {
private resolve(env: NodeJS.ProcessEnv): DesktopRuntimeConfig {
const userSaved = readJsonFileSafe(this.userConfigPath)
let portable: PersistedUserConfig = {}
for (const candidate of this.portableConfigPaths) {
const data = readJsonFileSafe(candidate)
if (Object.keys(data).length > 0) {
portable = data
break
}
}
const portable = readFirstPortableConfig(this.portableConfigPaths)
const backendUrl = normalizeHttpUrl(
this.cliEndpoints.backendUrl ?? env.PLANET_BACKEND_URL ?? portable.backendUrl ?? userSaved.backendUrl,
@@ -212,6 +319,13 @@ export class DesktopConfigStore {
userSaved.splashTheme,
'singularity',
)
const gpuMode = normalizeGpuMode(
this.launchFlags.gpuModeOverride ??
env.PLANET_GPU_MODE ??
portable.gpuMode ??
userSaved.gpuMode,
'auto',
)
return {
backendUrl,
@@ -219,6 +333,7 @@ export class DesktopConfigStore {
motionWsUrl,
wsUrl: deriveBackendWsUrl(backendUrl),
splashTheme,
gpuMode,
...this.launchFlags,
}
}
@@ -260,4 +375,14 @@ export class DesktopConfigStore {
}
return this.get()
}
updateGpuMode(rawMode: unknown): DesktopRuntimeConfig {
const nextMode = normalizeGpuMode(rawMode, this.current.gpuMode)
this.writeUserConfig({ gpuMode: nextMode })
this.current = {
...this.current,
gpuMode: nextMode,
}
return this.get()
}
}
+321
View File
@@ -0,0 +1,321 @@
import { execFile, execFileSync } from 'node:child_process'
import fs from 'node:fs'
import path from 'node:path'
import { promisify } from 'node:util'
import type { BrowserWindow } from 'electron'
import type { GpuRenderMode } from './config'
import {
canAutoSwitchGpu,
createVramHysteresisTracker,
detectIntegratedGpuFromRegistryOutput,
parseNvidiaSmiCsv,
VRAM_LOW_THRESHOLD_MIB,
VRAM_MONITOR_INTERVAL_MS,
type DiscreteVramSample,
type ResolvedGpuTarget,
type StartupGpuDecision,
type StartupGpuDecisionReason,
} from './gpu-policy'
const execFileAsync = promisify(execFile)
const HANDOFF_RECORD_MAX_AGE_MS = 30_000
const HANDOFF_RECORD_FILE = 'gpu-handoff.json'
const NVIDIA_SMI_ARGS = [
'--query-gpu=name,memory.used,memory.free,memory.total',
'--format=csv,noheader,nounits',
]
const DISPLAY_CLASS_REG_ARGS = [
'query',
'HKLM\\SYSTEM\\CurrentControlSet\\Control\\Class\\{4d36e968-e325-11ce-bfc1-08002be10318}',
'/s',
'/v',
'DriverDesc',
]
export interface GpuHandoffRecord {
lastSwitchAt: number
target: ResolvedGpuTarget
reason: 'low-fps-low-vram' | 'vram-recovered' | 'manual'
freeMiB?: number
avgFps?: number
}
export interface GpuRuntimeSummary {
requestedMode: GpuRenderMode
activeTarget: ResolvedGpuTarget
reason: StartupGpuDecisionReason
hasIntegratedGpu: boolean
latestVramSample: DiscreteVramSample | null
}
export interface AdaptiveGpuMonitor {
start(): void
stop(): void
handleLowFpsReport(report: { avgFps: number; sustainedMs: number }): Promise<void>
consumePendingHandoffToast(): { message: string; type: 'info' | 'success' } | null
getRuntimeSummary(): GpuRuntimeSummary
}
export function readGpuHandoffRecord(userDataDir: string): GpuHandoffRecord | null {
if (!userDataDir) return null
try {
const filePath = path.join(userDataDir, HANDOFF_RECORD_FILE)
if (!fs.existsSync(filePath)) return null
const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')) as Partial<GpuHandoffRecord>
if (
!parsed ||
typeof parsed.lastSwitchAt !== 'number' ||
!Number.isFinite(parsed.lastSwitchAt) ||
typeof parsed.target !== 'string' ||
typeof parsed.reason !== 'string'
) {
return null
}
return parsed as GpuHandoffRecord
} catch {
return null
}
}
export function writeGpuHandoffRecord(userDataDir: string, record: GpuHandoffRecord): void {
if (!userDataDir) return
try {
const filePath = path.join(userDataDir, HANDOFF_RECORD_FILE)
fs.mkdirSync(path.dirname(filePath), { recursive: true })
fs.writeFileSync(filePath, `${JSON.stringify(record, null, 2)}\n`, 'utf8')
} catch {
// Ignore non-critical handoff state write failures.
}
}
export function probeWindowsGpuEnvironmentSync(): {
vramSample: DiscreteVramSample | null
hasIntegratedGpu: boolean
} {
if (process.platform !== 'win32') {
return { vramSample: null, hasIntegratedGpu: false }
}
let vramSample: DiscreteVramSample | null = null
try {
const out = execFileSync('nvidia-smi', NVIDIA_SMI_ARGS, {
encoding: 'utf8',
timeout: 800,
windowsHide: true,
stdio: ['ignore', 'pipe', 'ignore'],
})
vramSample = parseNvidiaSmiCsv(out)
} catch {
vramSample = null
}
let hasIntegratedGpu = false
try {
const out = execFileSync('reg.exe', DISPLAY_CLASS_REG_ARGS, {
encoding: 'utf8',
timeout: 800,
windowsHide: true,
stdio: ['ignore', 'pipe', 'ignore'],
})
hasIntegratedGpu = detectIntegratedGpuFromRegistryOutput(out)
} catch {
hasIntegratedGpu = false
}
return { vramSample, hasIntegratedGpu }
}
export async function probeDiscreteVramAsync(): Promise<DiscreteVramSample | null> {
if (process.platform !== 'win32') {
return null
}
try {
const { stdout } = await execFileAsync('nvidia-smi', NVIDIA_SMI_ARGS, {
encoding: 'utf8',
timeout: 2000,
windowsHide: true,
})
return parseNvidiaSmiCsv(stdout)
} catch {
return null
}
}
export async function probeIntegratedGpuAsync(): Promise<boolean> {
if (process.platform !== 'win32') {
return false
}
try {
const { stdout } = await execFileAsync('reg.exe', DISPLAY_CLASS_REG_ARGS, {
encoding: 'utf8',
timeout: 2000,
windowsHide: true,
})
return detectIntegratedGpuFromRegistryOutput(stdout)
} catch {
return false
}
}
export function createAdaptiveGpuMonitor(options: {
userDataDir: string
startupDecision: StartupGpuDecision
getConfiguredMode: () => GpuRenderMode
getMainWindow: () => BrowserWindow | null
onAutoSwitch: (target: ResolvedGpuTarget, record: GpuHandoffRecord) => void
onStatusUpdated?: () => void
}): AdaptiveGpuMonitor {
let latestVramSample: DiscreteVramSample | null = options.startupDecision.vramSample
let switching = false
let toastConsumed = false
let intervalTimer: ReturnType<typeof setInterval> | null = null
const lastSwitchAt = readGpuHandoffRecord(options.userDataDir)?.lastSwitchAt ?? null
const activeTarget = options.startupDecision.target
const isDiscrete = activeTarget === 'default' || activeTarget === 'high-performance'
const isOffloaded = activeTarget === 'low-power' || activeTarget === 'software'
const tracker = createVramHysteresisTracker({
activeTarget,
hasIntegratedGpu: options.startupDecision.hasIntegratedGpu,
})
const triggerAutoSwitch = (target: ResolvedGpuTarget, record: GpuHandoffRecord) => {
if (switching) return
switching = true
if (intervalTimer) {
clearInterval(intervalTimer)
intervalTimer = null
}
writeGpuHandoffRecord(options.userDataDir, record)
options.onAutoSwitch(target, record)
}
const tickOffloadedRecovery = async () => {
if (switching || !isOffloaded || options.getConfiguredMode() !== 'auto') return
if (!canAutoSwitchGpu(lastSwitchAt, Date.now())) return
const win = options.getMainWindow()
if (!win || win.isDestroyed() || win.isMinimized()) return
const sample = await probeDiscreteVramAsync()
latestVramSample = sample
options.onStatusUpdated?.()
if (switching || options.getConfiguredMode() !== 'auto') return
const action = tracker.observe(sample)
if (!action || action.kind !== 'switch-to-discrete') return
const now = Date.now()
if (!canAutoSwitchGpu(lastSwitchAt, now)) return
console.info(
`[planet-client] Discrete GPU VRAM recovered (freeMiB=${action.sample.freeMiB}); auto-switching back to discrete GPU`,
)
triggerAutoSwitch('default', {
lastSwitchAt: now,
target: 'default',
reason: 'vram-recovered',
freeMiB: action.sample.freeMiB,
})
}
return {
start() {
if (process.platform !== 'win32' || options.startupDecision.reason === 'headless-smoke') {
return
}
if (!isOffloaded || intervalTimer) return
intervalTimer = setInterval(() => {
void tickOffloadedRecovery()
}, VRAM_MONITOR_INTERVAL_MS)
},
stop() {
if (intervalTimer) {
clearInterval(intervalTimer)
intervalTimer = null
}
},
async handleLowFpsReport(report: { avgFps: number; sustainedMs: number }): Promise<void> {
if (
process.platform !== 'win32' ||
options.startupDecision.reason === 'headless-smoke' ||
switching ||
!isDiscrete ||
options.getConfiguredMode() !== 'auto'
) {
return
}
const now = Date.now()
if (!canAutoSwitchGpu(lastSwitchAt, now)) return
const sample = await probeDiscreteVramAsync()
latestVramSample = sample
options.onStatusUpdated?.()
if (
switching ||
options.getConfiguredMode() !== 'auto' ||
!sample ||
sample.freeMiB >= VRAM_LOW_THRESHOLD_MIB
) {
return
}
const hasIgpu = options.startupDecision.hasIntegratedGpu || (await probeIntegratedGpuAsync())
const nextTarget: ResolvedGpuTarget = hasIgpu ? 'low-power' : 'software'
const switchNow = Date.now()
if (!canAutoSwitchGpu(lastSwitchAt, switchNow)) return
console.info(
`[planet-client] Sustained low FPS (${report.avgFps} fps for ${report.sustainedMs}ms) with low discrete VRAM (freeMiB=${sample.freeMiB}); auto-switching to ${nextTarget}`,
)
triggerAutoSwitch(nextTarget, {
lastSwitchAt: switchNow,
target: nextTarget,
reason: 'low-fps-low-vram',
freeMiB: sample.freeMiB,
avgFps: report.avgFps,
})
},
consumePendingHandoffToast(): { message: string; type: 'info' | 'success' } | null {
if (toastConsumed || options.startupDecision.reason !== 'gpu-handoff') {
return null
}
toastConsumed = true
const record = readGpuHandoffRecord(options.userDataDir)
if (!record || Date.now() - record.lastSwitchAt >= HANDOFF_RECORD_MAX_AGE_MS) {
return null
}
if (record.reason === 'low-fps-low-vram') {
return record.target === 'software'
? { message: '独显显存不足且帧率偏低,已自动切换至 CPU 软渲染', type: 'info' }
: {
message: '独显显存不足且帧率偏低,已自动切换至集成核显渲染(保留全部特效)',
type: 'info',
}
}
if (record.reason === 'vram-recovered') {
return { message: '独显显存已充足,已自动切回独立显卡渲染', type: 'success' }
}
return null
},
getRuntimeSummary(): GpuRuntimeSummary {
return {
requestedMode: options.getConfiguredMode(),
activeTarget: options.startupDecision.target,
reason: options.startupDecision.reason,
hasIntegratedGpu: options.startupDecision.hasIntegratedGpu,
latestVramSample,
}
},
}
}
+316 -4
View File
@@ -1,16 +1,168 @@
import type { GpuRenderMode } from './config'
export const VRAM_LOW_THRESHOLD_MIB = 2048
export const VRAM_RECOVER_THRESHOLD_MIB = 3584
export const VRAM_MONITOR_INTERVAL_MS = 5_000
export const VRAM_SWITCH_CONSECUTIVE_REQUIRED = 2
export const LOW_FPS_THRESHOLD = 20
export const LOW_FPS_SUSTAINED_MS = 5_000
export const FPS_STARTUP_WARMUP_MS = 6_000
export const FPS_REPORT_COOLDOWN_MS = 15_000
export const AUTO_SWITCH_COOLDOWN_MS = 45_000
export interface ChromiumSwitch {
name: string
value?: string
}
export type ResolvedGpuTarget = 'default' | 'high-performance' | 'low-power' | 'software'
export interface DiscreteVramSample {
gpuName: string
usedMiB: number
freeMiB: number
totalMiB: number
}
export type StartupGpuDecisionReason =
| 'headless-smoke'
| 'gpu-handoff'
| 'user-software'
| 'user-low-power'
| 'user-high-performance'
| 'low-vram-igpu'
| 'low-vram-software'
| 'normal-gpu'
export interface StartupGpuDecision {
target: ResolvedGpuTarget
requestedMode: GpuRenderMode
reason: StartupGpuDecisionReason
vramSample: DiscreteVramSample | null
hasIntegratedGpu: boolean
}
export interface VramMonitorAction {
kind: 'switch-to-discrete' | 'switch-to-low-power' | 'switch-to-software'
sample: DiscreteVramSample
}
export interface GpuPolicyInput {
platform: NodeJS.Platform
headlessSmoke: boolean
softwareGl: boolean
softwareGl?: boolean
target?: ResolvedGpuTarget
}
const VIRTUAL_DISPLAY_ADAPTER_RE = /microsoft basic|remote display|parsec|virtual|indirect|mirage/i
const INTEL_ADAPTER_RE = /\bintel\b/i
const INTEL_DISCRETE_ARC_RE = /\barc\b.*\b[ab]\d{3}\b/i
const AMD_INTEGRATED_RE = /\bamd\s+radeon(?:\(tm\))?\s+(?:graphics|\d+m\b|vega\s+\d+\s+graphics)/i
function parseMiBField(raw: string | undefined): number | null {
if (!raw) return null
const trimmed = raw.trim()
if (!trimmed || /n\/a/i.test(trimmed)) return null
const cleaned = trimmed.replace(/\s*mib$/i, '')
if (!/^\d+(?:\.\d+)?$/.test(cleaned)) return null
const num = Number(cleaned)
return Number.isFinite(num) ? num : null
}
export function parseNvidiaSmiCsv(stdout: string): DiscreteVramSample | null {
if (!stdout) return null
for (const rawLine of stdout.split(/\r?\n/)) {
const line = rawLine.trim()
if (!line) continue
const parts = line.split(',')
if (parts.length < 4) continue
const gpuName = parts.slice(0, -3).join(',').trim()
const usedMiB = parseMiBField(parts[parts.length - 3])
const freeMiB = parseMiBField(parts[parts.length - 2])
const totalMiB = parseMiBField(parts[parts.length - 1])
if (
!gpuName ||
usedMiB === null ||
freeMiB === null ||
totalMiB === null ||
usedMiB < 0 ||
freeMiB < 0 ||
totalMiB <= 0
) {
continue
}
return { gpuName, usedMiB, freeMiB, totalMiB }
}
return null
}
export function detectIntegratedGpuFromRegistryOutput(stdout: string): boolean {
if (!stdout) return false
for (const rawLine of stdout.split(/\r?\n/)) {
const match = /^\s*DriverDesc\s+REG_SZ\s+(.+?)\s*$/i.exec(rawLine)
if (!match) continue
const desc = match[1].trim()
if (!desc || VIRTUAL_DISPLAY_ADAPTER_RE.test(desc)) continue
if (INTEL_ADAPTER_RE.test(desc) && !INTEL_DISCRETE_ARC_RE.test(desc)) {
return true
}
if (AMD_INTEGRATED_RE.test(desc)) {
return true
}
}
return false
}
export function chooseStartupGpuTarget(input: {
platform: NodeJS.Platform
headlessSmoke: boolean
requestedMode: GpuRenderMode
handoffTarget?: ResolvedGpuTarget
vramSample: DiscreteVramSample | null
hasIntegratedGpu: boolean
}): StartupGpuDecision {
const base = {
requestedMode: input.requestedMode,
vramSample: input.vramSample,
hasIntegratedGpu: input.hasIntegratedGpu,
}
if (input.headlessSmoke) {
return { ...base, target: 'software', reason: 'headless-smoke' }
}
if (input.requestedMode === 'software') {
return { ...base, target: 'software', reason: 'user-software' }
}
if (input.requestedMode === 'low-power') {
return { ...base, target: 'low-power', reason: 'user-low-power' }
}
if (input.requestedMode === 'high-performance') {
return { ...base, target: 'high-performance', reason: 'user-high-performance' }
}
if (input.handoffTarget) {
return { ...base, target: input.handoffTarget, reason: 'gpu-handoff' }
}
if (
input.platform === 'win32' &&
input.vramSample &&
input.vramSample.freeMiB < VRAM_LOW_THRESHOLD_MIB
) {
return input.hasIntegratedGpu
? { ...base, target: 'low-power', reason: 'low-vram-igpu' }
: { ...base, target: 'software', reason: 'low-vram-software' }
}
return { ...base, target: 'default', reason: 'normal-gpu' }
}
export function resolveChromiumGpuSwitches(input: GpuPolicyInput): ChromiumSwitch[] {
if (input.headlessSmoke || input.softwareGl) {
const effectiveTarget: ResolvedGpuTarget =
input.headlessSmoke || input.softwareGl || input.target === 'software'
? 'software'
: (input.target ?? 'default')
if (effectiveTarget === 'software') {
return [
{ name: 'disable-gpu' },
{ name: 'use-gl', value: 'angle' },
@@ -19,15 +171,175 @@ export function resolveChromiumGpuSwitches(input: GpuPolicyInput): ChromiumSwitc
]
}
// Avoid forcing enable-zero-copy / enable-gpu-rasterization / force_high_performance_gpu:
// Avoid forcing enable-zero-copy / enable-gpu-rasterization:
// on Windows dual-GPU setups with high baseline VRAM usage they can provoke driver TDRs.
const switches: ChromiumSwitch[] = [{ name: 'disable-renderer-backgrounding' }]
const switches: ChromiumSwitch[] = []
if (effectiveTarget === 'low-power') {
switches.push({ name: 'force_low_power_gpu' })
} else if (effectiveTarget === 'high-performance') {
switches.push({ name: 'force_high_performance_gpu' })
}
switches.push({ name: 'disable-renderer-backgrounding' })
if (input.platform === 'linux') {
switches.push({ name: 'ozone-platform-hint', value: 'auto' })
}
return switches
}
export function createVramHysteresisTracker(options: {
activeTarget: ResolvedGpuTarget
hasIntegratedGpu: boolean
lowThresholdMiB?: number
recoverThresholdMiB?: number
requiredConsecutive?: number
}) {
const lowThresholdMiB = options.lowThresholdMiB ?? VRAM_LOW_THRESHOLD_MIB
const recoverThresholdMiB = options.recoverThresholdMiB ?? VRAM_RECOVER_THRESHOLD_MIB
const requiredConsecutive = Math.max(1, options.requiredConsecutive ?? VRAM_SWITCH_CONSECUTIVE_REQUIRED)
let streak = 0
return {
observe(sample: DiscreteVramSample | null): VramMonitorAction | null {
if (!sample) {
streak = 0
return null
}
if (options.activeTarget === 'low-power' || options.activeTarget === 'software') {
if (sample.freeMiB >= recoverThresholdMiB) {
streak += 1
if (streak >= requiredConsecutive) {
return { kind: 'switch-to-discrete', sample }
}
} else {
streak = 0
}
return null
}
if (sample.freeMiB < lowThresholdMiB) {
streak += 1
if (streak >= requiredConsecutive) {
return {
kind: options.hasIntegratedGpu ? 'switch-to-low-power' : 'switch-to-software',
sample,
}
}
} else {
streak = 0
}
return null
},
reset(): void {
streak = 0
},
}
}
export function createSustainedLowFpsTracker(
options: {
thresholdFps?: number
sustainedMs?: number
sampleWindowMs?: number
reportCooldownMs?: number
} = {},
) {
const thresholdFps = options.thresholdFps ?? LOW_FPS_THRESHOLD
const sustainedMs = options.sustainedMs ?? LOW_FPS_SUSTAINED_MS
const sampleWindowMs = options.sampleWindowMs ?? 1000
const reportCooldownMs = options.reportCooldownMs ?? FPS_REPORT_COOLDOWN_MS
let bucketStartMs: number | null = null
let bucketFrames = 0
let lowDurationMs = 0
let lowFrames = 0
let lastReportedAt = -Infinity
return {
onFrame(nowMs: number): { avgFps: number; sustainedMs: number } | null {
if (!Number.isFinite(nowMs)) return null
if (bucketStartMs === null) {
bucketStartMs = nowMs
bucketFrames = 0
return null
}
bucketFrames += 1
const elapsedMs = nowMs - bucketStartMs
if (elapsedMs < sampleWindowMs) {
return null
}
const fps = (bucketFrames * 1000) / elapsedMs
bucketStartMs = nowMs
if (fps < thresholdFps) {
lowDurationMs += elapsedMs
lowFrames += bucketFrames
bucketFrames = 0
if (lowDurationMs >= sustainedMs && nowMs - lastReportedAt >= reportCooldownMs) {
const avgFps = Math.round(((lowFrames * 1000) / lowDurationMs) * 10) / 10
const reportedDuration = Math.round(lowDurationMs)
lastReportedAt = nowMs
lowDurationMs = 0
lowFrames = 0
return { avgFps, sustainedMs: reportedDuration }
}
return null
}
bucketFrames = 0
lowDurationMs = 0
lowFrames = 0
return null
},
reset(): void {
bucketStartMs = null
bucketFrames = 0
lowDurationMs = 0
lowFrames = 0
},
}
}
export function canAutoSwitchGpu(
lastSwitchAt: number | null | undefined,
nowMs: number,
cooldownMs = AUTO_SWITCH_COOLDOWN_MS,
): boolean {
return !lastSwitchAt || !Number.isFinite(lastSwitchAt) || nowMs - lastSwitchAt >= cooldownMs
}
export function stripGpuOverrideArgs(argv: string[]): string[] {
const stripped: string[] = []
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i]
if (
arg === '--software-gl' ||
arg === '--low-power-gpu' ||
arg === '--high-performance-gpu' ||
arg === '--gpu-handoff' ||
arg.startsWith('--gpu-mode=') ||
arg.startsWith('--gpu-handoff-target=')
) {
continue
}
if (arg === '--gpu-mode' || arg === '--gpu-handoff-target') {
i += 1
continue
}
stripped.push(arg)
}
return stripped
}
export function buildGpuHandoffArgs(argv: string[], target?: ResolvedGpuTarget): string[] {
return [
...stripGpuOverrideArgs(argv),
'--gpu-handoff',
...(target ? [`--gpu-handoff-target=${target}`] : []),
]
}
export function isGpuProcessCrash(
details: { type?: string; reason?: string } | null | undefined,
): boolean {
+127 -7
View File
@@ -1,25 +1,68 @@
import fs from 'node:fs'
import path from 'node:path'
import { app, BrowserWindow, ipcMain, Menu, session, shell } from 'electron'
import { app, BrowserWindow, dialog, ipcMain, Menu, session, shell } from 'electron'
import { DesktopConfigStore, normalizeSplashTheme, type ServerEndpoints } from './config'
import { DesktopConfigStore, normalizeSplashTheme, readPreReadyGpuHandoff, readPreReadyGpuMode, type GpuRenderMode, type ServerEndpoints } from './config'
import { DESKTOP_SCHEME, registerDesktopLink } from './desktop-link'
import { isGpuProcessCrash, resolveChromiumGpuSwitches } from './gpu-policy'
import { createAdaptiveGpuMonitor, probeWindowsGpuEnvironmentSync } from './gpu-monitor'
import { buildGpuHandoffArgs, chooseStartupGpuTarget, isGpuProcessCrash, resolveChromiumGpuSwitches, stripGpuOverrideArgs, type ResolvedGpuTarget } from './gpu-policy'
import { PERIODIC_UPDATE_CHECK_INTERVAL_MS } from './hot-update-core'
import { createHotUpdateController } from './hot-updater'
import { buildApplicationMenu } from './menu'
import { EARTH_ORIGIN, installEarthSessionHandlers, registerEarthScheme } from './protocol'
import { createMainWindow, dismissMenuBarOnPointerDown, toggleWindowOrientation } from './window'
import { createMainWindow, dismissMenuBarOnPointerDown, flushWindowState, toggleWindowOrientation } from './window'
registerEarthScheme()
const isHeadlessSmoke = process.argv.includes('--headless-smoke')
const isSoftwareGl = process.argv.includes('--software-gl')
let preReadyUserDataDir = ''
let preReadyExeDir = process.cwd()
try {
preReadyUserDataDir = app.getPath('userData')
} catch {
preReadyUserDataDir = ''
}
try {
preReadyExeDir = path.dirname(app.getPath('exe'))
} catch {
preReadyExeDir = process.cwd()
}
const requestedGpuMode = readPreReadyGpuMode({
userDataDir: preReadyUserDataDir,
exeDir: preReadyExeDir,
resourcesDir: process.resourcesPath,
argv: process.argv,
})
const preReadyHandoff = readPreReadyGpuHandoff(process.argv)
const preReadyGpuEnv =
!isHeadlessSmoke &&
!preReadyHandoff.gpuHandoffTarget &&
requestedGpuMode === 'auto' &&
process.platform === 'win32'
? probeWindowsGpuEnvironmentSync()
: { vramSample: null, hasIntegratedGpu: false }
const startupGpuDecision = chooseStartupGpuTarget({
platform: process.platform,
headlessSmoke: isHeadlessSmoke,
requestedMode: requestedGpuMode,
handoffTarget: preReadyHandoff.gpuHandoffTarget,
vramSample: preReadyGpuEnv.vramSample,
hasIntegratedGpu: preReadyGpuEnv.hasIntegratedGpu,
})
if (startupGpuDecision.reason === 'low-vram-igpu' || startupGpuDecision.reason === 'low-vram-software') {
console.info(
`[planet-client] Adaptive GPU selected ${startupGpuDecision.target} (reason=${startupGpuDecision.reason}, freeMiB=${startupGpuDecision.vramSample?.freeMiB ?? 'unknown'})`,
)
}
for (const sw of resolveChromiumGpuSwitches({
platform: process.platform,
headlessSmoke: isHeadlessSmoke,
softwareGl: isSoftwareGl,
target: startupGpuDecision.target,
})) {
if (sw.value !== undefined) {
app.commandLine.appendSwitch(sw.name, sw.value)
@@ -119,6 +162,22 @@ if (!singleInstanceLock) {
})
const earthBundleRoot = resolveEarthBundleRoot()
const relaunchDesktopApp = (relaunchOptions?: {
gpuHandoff?: boolean
gpuHandoffTarget?: ResolvedGpuTarget
}) => {
flushWindowState(mainWindow)
if (singleInstanceLock) {
app.releaseSingleInstanceLock()
}
const rawArgs = process.argv.slice(1)
const args = relaunchOptions?.gpuHandoff
? buildGpuHandoffArgs(rawArgs, relaunchOptions.gpuHandoffTarget)
: stripGpuOverrideArgs(rawArgs)
app.relaunch({ args })
app.exit(0)
}
const hotUpdater = createHotUpdateController({
userDataDir: app.getPath('userData'),
shellVersion: app.getVersion(),
@@ -129,6 +188,29 @@ if (!singleInstanceLock) {
},
})
const gpuMonitor = createAdaptiveGpuMonitor({
userDataDir: app.getPath('userData'),
startupDecision: startupGpuDecision,
getConfiguredMode: () => configStore.get().gpuMode,
getMainWindow: () => mainWindow,
onAutoSwitch: (nextTarget) => {
relaunchDesktopApp({ gpuHandoff: true, gpuHandoffTarget: nextTarget })
},
onStatusUpdated: () => {
refreshApplicationMenu()
},
})
const sendPendingHandoffToast = () => {
if (isHeadlessSmoke || !mainWindow || mainWindow.isDestroyed() || mainWindow.webContents.isDestroyed()) {
return
}
const toast = gpuMonitor.consumePendingHandoffToast()
if (toast) {
mainWindow.webContents.send('planet:update-status', toast)
}
}
const refreshApplicationMenu = () => {
if (!mainWindow || mainWindow.isDestroyed()) return
Menu.setApplicationMenu(
@@ -139,6 +221,27 @@ if (!singleInstanceLock) {
onCheckForUpdates: () => {
void hotUpdater.checkForUpdates({ manual: true })
},
getGpuStatus: () => gpuMonitor.getRuntimeSummary(),
onSelectGpuMode: async (nextMode: GpuRenderMode) => {
configStore.updateGpuMode(nextMode)
refreshApplicationMenu()
const targetWin = mainWindow && !mainWindow.isDestroyed() ? mainWindow : undefined
const boxOptions = {
type: 'info' as const,
title: '渲染设备设置 / GPU Mode',
message: '渲染设备模式已更新,需重启客户端生效',
detail: '是否立即重启 Planet Earth?(重启约需 1-2 秒,将保留全部视觉特效)',
buttons: ['立即重启 / Restart Now', '稍后手动重启 / Later'],
defaultId: 0,
cancelId: 1,
}
const { response } = targetWin
? await dialog.showMessageBox(targetWin, boxOptions)
: await dialog.showMessageBox(boxOptions)
if (response === 0) {
relaunchDesktopApp({ gpuHandoff: true })
}
},
}),
)
}
@@ -152,9 +255,21 @@ if (!singleInstanceLock) {
ipcMain.on('planet:earth-startup-ready', () => {
if (!isHeadlessSmoke) {
hotUpdater.markStartupReady()
sendPendingHandoffToast()
}
})
ipcMain.on('planet:low-fps-report', (_event, payload: unknown) => {
if (isHeadlessSmoke || !payload || typeof payload !== 'object') return
const candidate = payload as { avgFps?: unknown; sustainedMs?: unknown }
const avgFps = Number(candidate.avgFps)
const sustainedMs = Number(candidate.sustainedMs)
if (!Number.isFinite(avgFps) || avgFps <= 0 || !Number.isFinite(sustainedMs) || sustainedMs <= 0) {
return
}
void gpuMonitor.handleLowFpsReport({ avgFps, sustainedMs })
})
ipcMain.handle('planet:check-for-updates', async () => {
await hotUpdater.checkForUpdates({ manual: true })
})
@@ -170,6 +285,9 @@ if (!singleInstanceLock) {
wsUrl: cfg.wsUrl,
forceShowFps: cfg.forceShowFps,
splashTheme: cfg.splashTheme,
gpuMode: cfg.gpuMode,
gpuTarget: startupGpuDecision.target,
gpuHandoff: cfg.gpuHandoff,
headlessSmoke: cfg.headlessSmoke,
isElectron: true,
platform: process.platform,
@@ -259,6 +377,7 @@ if (!singleInstanceLock) {
})
hotUpdater.startStartupWatchdog()
mainWindow.webContents.once('did-finish-load', () => {
gpuMonitor.start()
autoUpdateTimer = setTimeout(() => {
autoUpdateTimer = null
if (mainWindow && !mainWindow.isDestroyed()) {
@@ -274,6 +393,7 @@ if (!singleInstanceLock) {
}
})
mainWindow.once('closed', () => {
gpuMonitor.stop()
if (autoUpdateTimer) {
clearTimeout(autoUpdateTimer)
autoUpdateTimer = null
@@ -358,7 +478,7 @@ if (!singleInstanceLock) {
mounted: Boolean(host && sr),
hasPresentedBy: copy.includes('PRESENTED BY'),
hasPresenterZh: copy.includes('临空智能媒体研究院'),
hasPresenterEn: copy.includes('Institute of Intelligent Media'),
hasPresenterEn: copy.includes('Intelligent Media Institute'),
emblemLoaded: Boolean(img && img.complete && img.naturalWidth > 0),
emblemWidth: img ? img.naturalWidth : 0,
activeTheme,
+68 -2
View File
@@ -1,15 +1,33 @@
import { app, Menu, shell, type BrowserWindow, type MenuItemConstructorOptions } from 'electron'
import type { DesktopConfigStore, SplashTheme } from './config'
import type { DesktopConfigStore, GpuRenderMode, SplashTheme } from './config'
import type { GpuRuntimeSummary } from './gpu-monitor'
import type { HotUpdateVersionInfo } from './hot-updater'
import { openServerSettingsDialog, toggleWindowOrientation } from './window'
import type { HotUpdateVersionInfo } from './hot-updater'
function formatGpuSummaryLabel(summary: GpuRuntimeSummary): string {
const targetLabel =
summary.activeTarget === 'low-power'
? '集成核显'
: summary.activeTarget === 'software'
? 'CPU 软渲染'
: summary.activeTarget === 'high-performance' || summary.latestVramSample
? '独立显卡'
: '硬件 GPU'
const modeTag = summary.requestedMode === 'auto' ? '自动' : '手动'
const vramTag = summary.latestVramSample
? ` · 独显空闲 ${(summary.latestVramSample.freeMiB / 1024).toFixed(1)} GB`
: ''
return `当前生效: ${targetLabel} (${modeTag}${vramTag})`
}
export function buildApplicationMenu(options: {
mainWindow: BrowserWindow
configStore: DesktopConfigStore
getVersionInfo?: () => HotUpdateVersionInfo
onCheckForUpdates?: () => void
getGpuStatus?: () => GpuRuntimeSummary
onSelectGpuMode?: (mode: GpuRenderMode) => void | Promise<void>
}): Menu {
const sendAction = (action: string) => {
if (!options.mainWindow.isDestroyed()) {
@@ -23,6 +41,8 @@ export function buildApplicationMenu(options: {
}
const currentSplashTheme = options.configStore.get().splashTheme
const currentGpuMode = options.configStore.get().gpuMode
const gpuSummary = options.getGpuStatus?.()
const selectSplashTheme = (theme: SplashTheme) => {
options.configStore.updateSplashTheme(theme)
@@ -92,6 +112,52 @@ export function buildApplicationMenu(options: {
},
],
},
{
label: '渲染设备 / GPU Mode',
submenu: [
...(gpuSummary
? [
{
label: formatGpuSummaryLabel(gpuSummary),
enabled: false,
},
{ type: 'separator' as const },
]
: []),
{
label: '自动(卡顿缺显存切核显,显存空出自动回独显) / Auto',
type: 'radio',
checked: currentGpuMode === 'auto',
click: () => {
void options.onSelectGpuMode?.('auto')
},
},
{
label: '独立显卡(高性能) / Discrete GPU',
type: 'radio',
checked: currentGpuMode === 'high-performance',
click: () => {
void options.onSelectGpuMode?.('high-performance')
},
},
{
label: '集成核显(不占独显显存) / Integrated GPU',
type: 'radio',
checked: currentGpuMode === 'low-power',
click: () => {
void options.onSelectGpuMode?.('low-power')
},
},
{
label: '纯 CPU 软渲染 / Software GL',
type: 'radio',
checked: currentGpuMode === 'software',
click: () => {
void options.onSelectGpuMode?.('software')
},
},
],
},
{ type: 'separator' },
{
label: '打开运维控制台 / Open Admin Console',
+18 -5
View File
@@ -21,6 +21,12 @@ import {
import { EARTH_ENTRY_URL, EARTH_ORIGIN } from './protocol'
const resetAltMenuTrackers = new WeakMap<BrowserWindow, () => void>()
const windowStateFlushers = new WeakMap<BrowserWindow, () => void>()
export function flushWindowState(win: BrowserWindow | null): void {
if (!win || win.isDestroyed()) return
windowStateFlushers.get(win)?.()
}
interface OrientationWindowState {
lastLandscapeBounds: Rect | null
@@ -296,14 +302,17 @@ export function createMainWindow(options: {
}
}
win.on('resize', captureNormalBounds)
win.on('move', captureNormalBounds)
win.on('close', () => {
const flushCurrentWindowState = () => {
captureNormalBounds()
if (!runtimeConfig.headlessSmoke) {
saveWindowState(statePath, win, lastNormalBounds)
}
})
}
windowStateFlushers.set(win, flushCurrentWindowState)
win.on('resize', captureNormalBounds)
win.on('move', captureNormalBounds)
win.on('close', flushCurrentWindowState)
win.on('minimize', () => {
if (!win.isDestroyed()) {
@@ -346,7 +355,10 @@ export function createMainWindow(options: {
}
const showGate = createWindowShowGate({
requireSplashFirstPaint: !runtimeConfig.headlessSmoke && runtimeConfig.splashTheme !== 'off',
requireSplashFirstPaint:
!runtimeConfig.headlessSmoke &&
!runtimeConfig.gpuHandoff &&
runtimeConfig.splashTheme !== 'off',
fallbackDelayMs: 1500,
onReveal: revealMainWindow,
})
@@ -359,6 +371,7 @@ export function createMainWindow(options: {
ipcMain.on('planet:splash-first-paint', onSplashFirstPaint)
win.once('closed', () => {
windowStateFlushers.delete(win)
showGate.dispose()
ipcMain.removeListener('planet:splash-first-paint', onSplashFirstPaint)
})
+94
View File
@@ -0,0 +1,94 @@
import {
createSustainedLowFpsTracker,
FPS_STARTUP_WARMUP_MS,
} from '../main/gpu-policy'
export function startDesktopLowFpsWatcher(options: {
onLowFps: (report: { avgFps: number; sustainedMs: number }) => void
}): () => void {
const tracker = createSustainedLowFpsTracker()
let disposed = false
let rafId = 0
let warmupTimer: ReturnType<typeof setTimeout> | null = null
let startupReady = document.documentElement?.dataset?.earthStartupReady === '1'
let warmupDone = false
let desktopMinimized = false
const isActive = () =>
!disposed && startupReady && warmupDone && !desktopMinimized && !document.hidden
const stopLoop = () => {
if (rafId) {
cancelAnimationFrame(rafId)
rafId = 0
}
tracker.reset()
}
const tick = (now: number) => {
if (!isActive()) {
rafId = 0
tracker.reset()
return
}
const report = tracker.onFrame(now)
if (report) {
options.onLowFps(report)
}
rafId = requestAnimationFrame(tick)
}
const syncLoop = () => {
if (!isActive()) {
stopLoop()
return
}
if (!rafId) {
rafId = requestAnimationFrame(tick)
}
}
const beginWarmup = () => {
if (disposed || warmupDone || warmupTimer) return
warmupTimer = setTimeout(() => {
warmupTimer = null
warmupDone = true
syncLoop()
}, FPS_STARTUP_WARMUP_MS)
}
const onStartupReady = () => {
startupReady = true
beginWarmup()
}
const onVisibilityChange = () => {
syncLoop()
}
const onDesktopVisibility = (event: Event) => {
const detail = (event as CustomEvent<{ minimized?: boolean }>).detail
desktopMinimized = Boolean(detail?.minimized)
syncLoop()
}
if (startupReady) {
beginWarmup()
} else {
window.addEventListener('earth:startup-ready', onStartupReady, { once: true })
}
document.addEventListener('visibilitychange', onVisibilityChange)
window.addEventListener('planet-desktop:visibility', onDesktopVisibility)
return () => {
disposed = true
stopLoop()
if (warmupTimer) {
clearTimeout(warmupTimer)
warmupTimer = null
}
window.removeEventListener('earth:startup-ready', onStartupReady)
document.removeEventListener('visibilitychange', onVisibilityChange)
window.removeEventListener('planet-desktop:visibility', onDesktopVisibility)
}
}
+18 -1
View File
@@ -1,5 +1,6 @@
import { contextBridge, ipcRenderer } from 'electron'
import { startDesktopLowFpsWatcher } from './fps-watcher'
import { createDesktopSplashController, type SplashTheme } from './splash'
interface PreloadRuntimeConfig {
@@ -9,6 +10,9 @@ interface PreloadRuntimeConfig {
wsUrl: string
forceShowFps: boolean
splashTheme: SplashTheme
gpuMode?: string
gpuTarget?: string
gpuHandoff?: boolean
headlessSmoke: boolean
isElectron: true
platform: string
@@ -27,7 +31,7 @@ const splashController = createDesktopSplashController({
},
})
if (!runtimeConfig.headlessSmoke && runtimeConfig.splashTheme !== 'off') {
if (!runtimeConfig.headlessSmoke && !runtimeConfig.gpuHandoff && runtimeConfig.splashTheme !== 'off') {
let bootStarted = false
const tryStartBoot = () => {
if (bootStarted || !document.documentElement) return false
@@ -54,6 +58,19 @@ if (!runtimeConfig.headlessSmoke && runtimeConfig.splashTheme !== 'off') {
}
}
if (
!runtimeConfig.headlessSmoke &&
runtimeConfig.platform === 'win32' &&
runtimeConfig.gpuMode === 'auto' &&
(runtimeConfig.gpuTarget === 'default' || runtimeConfig.gpuTarget === 'high-performance')
) {
startDesktopLowFpsWatcher({
onLowFps: (report) => {
ipcRenderer.send('planet:low-fps-report', report)
},
})
}
contextBridge.exposeInMainWorld('__PLANET_RUNTIME_CONFIG__', runtimeConfig)
contextBridge.exposeInMainWorld('planetDesktop', {
+1 -1
View File
@@ -779,7 +779,7 @@ export function createDesktopSplashController(options: {
<div class="splash-presenter-copy">
<span class="splash-presenter-kicker">PRESENTED BY</span>
<span class="splash-presenter-zh">临空智能媒体研究院</span>
<span class="splash-presenter-en">Institute of Intelligent Media</span>
<span class="splash-presenter-en">Intelligent Media Institute</span>
</div>
</div>
</footer>
+400 -4
View File
@@ -1,10 +1,46 @@
import { describe, expect, test } from 'bun:test'
import { mkdtempSync, rmSync } from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { isGpuProcessCrash, resolveChromiumGpuSwitches } from '../src/main/gpu-policy'
import { afterAll, beforeAll, describe, expect, test } from 'bun:test'
import {
DesktopConfigStore,
normalizeGpuMode,
parseLaunchArgs,
readPreReadyGpuHandoff,
readPreReadyGpuMode,
} from '../src/main/config'
import {
buildGpuHandoffArgs,
canAutoSwitchGpu,
chooseStartupGpuTarget,
createSustainedLowFpsTracker,
createVramHysteresisTracker,
detectIntegratedGpuFromRegistryOutput,
isGpuProcessCrash,
parseNvidiaSmiCsv,
resolveChromiumGpuSwitches,
stripGpuOverrideArgs,
VRAM_LOW_THRESHOLD_MIB,
VRAM_RECOVER_THRESHOLD_MIB,
} from '../src/main/gpu-policy'
import { computeSplashCanvasSize } from '../src/preload/splash'
let tempRoot = ''
beforeAll(() => {
tempRoot = mkdtempSync(path.join(os.tmpdir(), 'planet-gpu-policy-test-'))
})
afterAll(() => {
if (tempRoot) {
rmSync(tempRoot, { recursive: true, force: true })
}
})
describe('chromium GPU switch policy and splash pixel budget', () => {
test('win32 hardware mode avoids risky zero-copy and forced GPU switches', () => {
test('win32 hardware mode avoids risky zero-copy and forced GPU switches by default', () => {
const switches = resolveChromiumGpuSwitches({
platform: 'win32',
headlessSmoke: false,
@@ -14,10 +50,33 @@ describe('chromium GPU switch policy and splash pixel budget', () => {
expect(names).not.toContain('enable-zero-copy')
expect(names).not.toContain('enable-gpu-rasterization')
expect(names).not.toContain('force_high_performance_gpu')
expect(names).not.toContain('force_low_power_gpu')
expect(names).toContain('disable-renderer-backgrounding')
expect(names).not.toContain('ozone-platform-hint')
})
test('low-power and high-performance targets emit matching Chromium GPU preference switches without enable-zero-copy', () => {
const igpuSwitches = resolveChromiumGpuSwitches({
platform: 'win32',
headlessSmoke: false,
target: 'low-power',
})
expect(igpuSwitches).toEqual([
{ name: 'force_low_power_gpu' },
{ name: 'disable-renderer-backgrounding' },
])
const dgpuSwitches = resolveChromiumGpuSwitches({
platform: 'win32',
headlessSmoke: false,
target: 'high-performance',
})
expect(dgpuSwitches).toEqual([
{ name: 'force_high_performance_gpu' },
{ name: 'disable-renderer-backgrounding' },
])
})
test('linux hardware mode adds ozone auto hint without enable-zero-copy', () => {
const switches = resolveChromiumGpuSwitches({
platform: 'linux',
@@ -30,10 +89,11 @@ describe('chromium GPU switch policy and splash pixel budget', () => {
])
})
test('headless smoke and explicit software-gl select SwiftShader safely', () => {
test('headless smoke, explicit software-gl, and target=software select SwiftShader safely', () => {
for (const flags of [
{ headlessSmoke: true, softwareGl: false },
{ headlessSmoke: false, softwareGl: true },
{ headlessSmoke: false, target: 'software' as const },
]) {
const switches = resolveChromiumGpuSwitches({ platform: 'win32', ...flags })
expect(switches).toEqual([
@@ -70,3 +130,339 @@ describe('chromium GPU switch policy and splash pixel budget', () => {
expect(native4k.height).toBe(1620)
})
})
describe('adaptive VRAM probing, GPU decision, and hysteresis', () => {
test('parseNvidiaSmiCsv parses single and multi-line CSV while skipping invalid rows', () => {
expect(
parseNvidiaSmiCsv('NVIDIA GeForce RTX 5070 Ti, 14651, 1345, 16303\n'),
).toEqual({
gpuName: 'NVIDIA GeForce RTX 5070 Ti',
usedMiB: 14651,
freeMiB: 1345,
totalMiB: 16303,
})
expect(
parseNvidiaSmiCsv(
'\n[N/A], [N/A], [N/A], [N/A]\nNVIDIA GeForce RTX 4090, 4096 MiB, 20480 MiB, 24576 MiB\n',
),
).toEqual({
gpuName: 'NVIDIA GeForce RTX 4090',
usedMiB: 4096,
freeMiB: 20480,
totalMiB: 24576,
})
expect(parseNvidiaSmiCsv('')).toBeNull()
expect(parseNvidiaSmiCsv('Failed to initialize NVML')).toBeNull()
})
test('detectIntegratedGpuFromRegistryOutput distinguishes iGPU from single-GPU and virtual adapters', () => {
expect(
detectIntegratedGpuFromRegistryOutput(`
HKEY_LOCAL_MACHINE\\...\\0000
DriverDesc REG_SZ Intel(R) Graphics
HKEY_LOCAL_MACHINE\\...\\0001
DriverDesc REG_SZ NVIDIA GeForce RTX 5070 Ti
`),
).toBe(true)
expect(
detectIntegratedGpuFromRegistryOutput(`
DriverDesc REG_SZ AMD Radeon(TM) Graphics
DriverDesc REG_SZ NVIDIA GeForce RTX 4060 Laptop GPU
`),
).toBe(true)
expect(
detectIntegratedGpuFromRegistryOutput(`
DriverDesc REG_SZ NVIDIA GeForce RTX 5070 Ti
DriverDesc REG_SZ Microsoft Basic Display Adapter
DriverDesc REG_SZ Parsec Virtual Display Adapter
`),
).toBe(false)
expect(
detectIntegratedGpuFromRegistryOutput(`
DriverDesc REG_SZ Intel(R) Arc(TM) A770 Graphics
DriverDesc REG_SZ NVIDIA GeForce RTX 5070 Ti
`),
).toBe(false)
})
test('chooseStartupGpuTarget handles low VRAM auto offload, recovery, explicit modes, and smoke', () => {
const lowVramSample = {
gpuName: 'NVIDIA GeForce RTX 5070 Ti',
usedMiB: 14651,
freeMiB: 1345,
totalMiB: 16303,
}
const healthyVramSample = {
gpuName: 'NVIDIA GeForce RTX 5070 Ti',
usedMiB: 4000,
freeMiB: 8000,
totalMiB: 16303,
}
expect(
chooseStartupGpuTarget({
platform: 'win32',
headlessSmoke: false,
requestedMode: 'auto',
vramSample: lowVramSample,
hasIntegratedGpu: true,
}),
).toEqual({
target: 'low-power',
requestedMode: 'auto',
reason: 'low-vram-igpu',
vramSample: lowVramSample,
hasIntegratedGpu: true,
})
expect(
chooseStartupGpuTarget({
platform: 'win32',
headlessSmoke: false,
requestedMode: 'auto',
vramSample: lowVramSample,
hasIntegratedGpu: false,
}),
).toEqual({
target: 'software',
requestedMode: 'auto',
reason: 'low-vram-software',
vramSample: lowVramSample,
hasIntegratedGpu: false,
})
expect(
chooseStartupGpuTarget({
platform: 'win32',
headlessSmoke: false,
requestedMode: 'auto',
vramSample: healthyVramSample,
hasIntegratedGpu: true,
}),
).toEqual({
target: 'default',
requestedMode: 'auto',
reason: 'normal-gpu',
vramSample: healthyVramSample,
hasIntegratedGpu: true,
})
expect(
chooseStartupGpuTarget({
platform: 'win32',
headlessSmoke: false,
requestedMode: 'high-performance',
vramSample: lowVramSample,
hasIntegratedGpu: true,
}).reason,
).toBe('user-high-performance')
expect(
chooseStartupGpuTarget({
platform: 'win32',
headlessSmoke: false,
requestedMode: 'low-power',
vramSample: healthyVramSample,
hasIntegratedGpu: true,
}).target,
).toBe('low-power')
expect(
chooseStartupGpuTarget({
platform: 'win32',
headlessSmoke: true,
requestedMode: 'high-performance',
vramSample: healthyVramSample,
hasIntegratedGpu: true,
}),
).toMatchObject({ target: 'software', reason: 'headless-smoke' })
})
test('createVramHysteresisTracker enforces consecutive readings and deadband', () => {
const lowSample = { gpuName: 'RTX 5070 Ti', usedMiB: 14500, freeMiB: 1500, totalMiB: 16303 }
const midSample = { gpuName: 'RTX 5070 Ti', usedMiB: 13000, freeMiB: 3000, totalMiB: 16303 }
const highSample = { gpuName: 'RTX 5070 Ti', usedMiB: 11000, freeMiB: VRAM_RECOVER_THRESHOLD_MIB, totalMiB: 16303 }
const igpuTracker = createVramHysteresisTracker({
activeTarget: 'low-power',
hasIntegratedGpu: true,
})
expect(igpuTracker.observe(midSample)).toBeNull()
expect(igpuTracker.observe(highSample)).toBeNull()
expect(igpuTracker.observe(midSample)).toBeNull() // streak reset
expect(igpuTracker.observe(highSample)).toBeNull()
expect(igpuTracker.observe(highSample)).toEqual({
kind: 'switch-to-discrete',
sample: highSample,
})
const dgpuWithIgpu = createVramHysteresisTracker({
activeTarget: 'default',
hasIntegratedGpu: true,
})
expect(dgpuWithIgpu.observe(midSample)).toBeNull()
expect(dgpuWithIgpu.observe({ ...lowSample, freeMiB: VRAM_LOW_THRESHOLD_MIB - 1 })).toBeNull()
expect(dgpuWithIgpu.observe(null)).toBeNull() // missing reading resets streak
expect(dgpuWithIgpu.observe(lowSample)).toBeNull()
expect(dgpuWithIgpu.observe(lowSample)).toEqual({
kind: 'switch-to-low-power',
sample: lowSample,
})
const dgpuNoIgpu = createVramHysteresisTracker({
activeTarget: 'high-performance',
hasIntegratedGpu: false,
})
expect(dgpuNoIgpu.observe(lowSample)).toBeNull()
expect(dgpuNoIgpu.observe(lowSample)).toEqual({
kind: 'switch-to-software',
sample: lowSample,
})
})
test('stripGpuOverrideArgs removes CLI GPU override flags cleanly', () => {
expect(
stripGpuOverrideArgs([
'--fullscreen',
'--software-gl',
'--gpu-mode=low-power',
'--gpu-mode',
'high-performance',
'--low-power-gpu',
'--high-performance-gpu',
'planet-earth://open',
]),
).toEqual(['--fullscreen', 'planet-earth://open'])
})
test('gpuMode config normalization, CLI flags, persistence, and readPreReadyGpuMode precedence work', () => {
expect(normalizeGpuMode('AUTO')).toBe('auto')
expect(normalizeGpuMode('igpu')).toBe('low-power')
expect(normalizeGpuMode('discrete')).toBe('high-performance')
expect(normalizeGpuMode('cpu')).toBe('software')
expect(normalizeGpuMode('unknown', 'low-power')).toBe('low-power')
expect(parseLaunchArgs(['--low-power-gpu']).flags.gpuModeOverride).toBe('low-power')
expect(parseLaunchArgs(['--high-performance-gpu']).flags.gpuModeOverride).toBe('high-performance')
expect(parseLaunchArgs(['--software-gl']).flags.gpuModeOverride).toBe('software')
expect(parseLaunchArgs(['--gpu-mode', 'igpu']).flags.gpuModeOverride).toBe('low-power')
const userDataDir = path.join(tempRoot, 'gpu-user-data')
const exeDir = path.join(tempRoot, 'gpu-exe-dir')
const store = new DesktopConfigStore({ userDataDir, exeDir, argv: [], env: {} })
expect(store.get().gpuMode).toBe('auto')
store.updateEndpoints({ backendUrl: 'https://rclaw.test' })
store.updateGpuMode('low-power')
expect(
readPreReadyGpuMode({ userDataDir, exeDir, argv: [], env: {} }),
).toBe('low-power')
expect(
readPreReadyGpuMode({ userDataDir, exeDir, argv: [], env: { PLANET_GPU_MODE: 'high-performance' } }),
).toBe('high-performance')
expect(
readPreReadyGpuMode({
userDataDir,
exeDir,
argv: ['--software-gl'],
env: { PLANET_GPU_MODE: 'high-performance' },
}),
).toBe('software')
const reloaded = new DesktopConfigStore({ userDataDir, exeDir, argv: [], env: {} })
expect(reloaded.get().gpuMode).toBe('low-power')
expect(reloaded.get().backendUrl).toBe('https://rclaw.test')
})
test('createSustainedLowFpsTracker ignores brief dips and triggers after 5s below 20 FPS with cooldown', () => {
const tracker = createSustainedLowFpsTracker()
let now = 0
expect(tracker.onFrame(now)).toBeNull()
// Simulate 10 FPS (100ms frame delta) for 4 seconds -> not yet 5s sustained
for (let sec = 0; sec < 4; sec += 1) {
for (let f = 0; f < 10; f += 1) {
now += 100
expect(tracker.onFrame(now)).toBeNull()
}
}
// Recover above 20 FPS -> resets low streak
for (let f = 0; f < 30; f += 1) {
now += 35
expect(tracker.onFrame(now)).toBeNull()
}
// Now sustain 10 FPS for 5 full seconds -> triggers on 5th second
let trigger: { avgFps: number; sustainedMs: number } | null = null
for (let sec = 0; sec < 5; sec += 1) {
for (let f = 0; f < 10; f += 1) {
now += 100
const res = tracker.onFrame(now)
if (res) trigger = res
}
}
expect(trigger).not.toBeNull()
expect(trigger!.avgFps).toBeGreaterThanOrEqual(9.5)
expect(trigger!.avgFps).toBeLessThan(11)
expect(trigger!.sustainedMs).toBeGreaterThanOrEqual(5000)
// Within 15s report cooldown -> suppressed even if slow again
for (let sec = 0; sec < 5; sec += 1) {
for (let f = 0; f < 10; f += 1) {
now += 100
expect(tracker.onFrame(now)).toBeNull()
}
}
// Reset clears accumulated low duration cleanly
tracker.reset()
now += 20_000
expect(tracker.onFrame(now)).toBeNull()
for (let sec = 0; sec < 4; sec += 1) {
for (let f = 0; f < 10; f += 1) {
now += 100
expect(tracker.onFrame(now)).toBeNull()
}
}
})
test('canAutoSwitchGpu, handoff target decision, and handoff CLI args preserve state across relaunch', () => {
expect(canAutoSwitchGpu(null, 10_000)).toBe(true)
expect(canAutoSwitchGpu(10_000, 40_000)).toBe(false)
expect(canAutoSwitchGpu(10_000, 55_000)).toBe(true)
expect(
chooseStartupGpuTarget({
platform: 'win32',
headlessSmoke: false,
requestedMode: 'auto',
handoffTarget: 'low-power',
vramSample: null,
hasIntegratedGpu: true,
}),
).toMatchObject({ target: 'low-power', reason: 'gpu-handoff' })
const args = buildGpuHandoffArgs(
['--fullscreen', '--gpu-handoff', '--gpu-handoff-target=low-power', 'planet-earth://open'],
'default',
)
expect(args).toEqual([
'--fullscreen',
'planet-earth://open',
'--gpu-handoff',
'--gpu-handoff-target=default',
])
expect(readPreReadyGpuHandoff(args)).toEqual({
gpuHandoff: true,
gpuHandoffTarget: 'default',
})
expect(stripGpuOverrideArgs(args)).toEqual(['--fullscreen', 'planet-earth://open'])
})
})
@@ -0,0 +1,14 @@
[Unit]
Description=Deploy the latest published Planet release
After=network-online.target docker.service
Wants=network-online.target
Requires=docker.service
[Service]
Type=oneshot
UMask=0077
Nice=10
StateDirectory=planet-release-deploy
StateDirectoryMode=0700
TimeoutStartSec=45min
ExecStart=/usr/bin/python3 /usr/local/lib/planet-release/production_deploy.py
@@ -0,0 +1,11 @@
[Unit]
Description=Check Gitea for published Planet releases
[Timer]
OnCalendar=*:0/2
Persistent=true
AccuracySec=5s
Unit=planet-release-deploy.service
[Install]
WantedBy=timers.target
+12
View File
@@ -8,6 +8,18 @@ This project follows the repository versioning rule:
- `improvement` -> `+0.0.1`(bugfix + 小功能混合)
- `bugfix` -> `+0.0.1`
## [0.79.1] — 2026-11-24
Released: 2026-11-24
### Highlights
- On Windows, automatic GPU selection checks free discrete GPU memory at startup. Below 2 GiB it requests integrated graphics when available and falls back to software rendering otherwise.
- During use, five seconds below 20 FPS prompts a second memory check before switching away from the discrete GPU. An automatic switch starts a 45-second cooldown. Once it expires, the client checks every five seconds and switches back after two consecutive readings of at least 3.5 GiB free. Automatic relaunches skip the splash and restore the window state.
- The splash screen and Earth interface now use **Intelligent Media Institute** as the English name of 临空智能媒体研究院 (IMI).
---
## [0.79.0] — 2026-11-24
Released: 2026-11-24
+1 -1
View File
@@ -44,7 +44,7 @@ Earth now supports both a **Web browser entry** and a **native Electron desktop
- **Runtime endpoint injection**: Preload injects synchronous `window.__PLANET_RUNTIME_CONFIG__` (`backendUrl`, `adminUrl`, `wsUrl`, `motionWsUrl`, `localMediaPipeBaseUrl`, `isElectron`) and `window.planetDesktop`. `realtime.js`, `motion-control.js`, and `motion-browser-provider.js` consume those endpoints and load bundled MediaPipe assets locally first.
- **Cross-process live synchronization**: Because Electron Earth runs outside the Admin origin, backend API mutations for compute comparison settings, brand config, and about info push `earth_updates` reload hints (`compute_configuration`, `earth_brand`, `earth_about`) over `/ws` alongside same-origin `BroadcastChannel` notices.
- **Native window controls and frame pacing**: Desktop uses a native dark OS frame so window buttons never overlap `#media-panel`, lowers minimum window dimensions to `360×480` so manual narrowing enters Earth's mobile layout (`<= 820px`), and adds one-click **View → Toggle Portrait & Landscape** (`CmdOrCtrl+Shift+M`) in the native `Alt` menu bar alongside saved portrait/landscape bounds; it also locks Chromium page zoom (`setVisualZoomLevelLimits(1, 1)`) while forwarding pinch (`wheel + ctrlKey`) and `CmdOrCtrl + =/-/0` to 3D globe zoom, and stabilizes frame pacing by coalescing HUD glow pointer moves and globe hover raycasting into `requestAnimationFrame`, caching `DOMRect` via `ResizeObserver`, clamping `deltaTime` (`<= 50 ms`), and pausing renders on minimize via `planet-desktop:visibility`.
- **Switchable desktop splash screen and zero-flash readiness gate**: [Desktop splash controller](/home/ray/dev/linkong/planet/client/src/preload/splash.ts) mounts via a `document` `MutationObserver` in preload the instant `<html>` is created and synchronously paints frame 1, while [Window show gate](/home/ray/dev/linkong/planet/client/src/main/show-gate.ts) waits for both `ready-to-show` and `planet:splash-first-paint` before showing the OS window so raw HTML never flashes; meanwhile `frontend/public/earth/js/main.js` and `controls.js` emit non-visual `earth:startup-progress` and `earth:startup-ready` lifecycle events (with zero Web UI/DOM impact) only after startup layers, `applyDeferredLayerVisibilitySettings` user-preference layers, stats/media readiness, and rendered 3D GPU frames settle before revealing the Earth viewport. It provides three real-coastline 3D Canvas themes (`singularity`, `constellation`, `horizon`, plus `off`), displays the transparent ZJU seal (`zju-emblem.png`) and `PRESENTED BY 临空智能媒体研究院 / Institute of Intelligent Media` lockup, and is controllable via splash pills, `Planet Earth → Splash Screen`, `CmdOrCtrl+Shift+S`, or `--splash-theme`.
- **Switchable desktop splash screen and zero-flash readiness gate**: [Desktop splash controller](/home/ray/dev/linkong/planet/client/src/preload/splash.ts) mounts via a `document` `MutationObserver` in preload the instant `<html>` is created and synchronously paints frame 1, while [Window show gate](/home/ray/dev/linkong/planet/client/src/main/show-gate.ts) waits for both `ready-to-show` and `planet:splash-first-paint` before showing the OS window so raw HTML never flashes; meanwhile `frontend/public/earth/js/main.js` and `controls.js` emit non-visual `earth:startup-progress` and `earth:startup-ready` lifecycle events (with zero Web UI/DOM impact) only after startup layers, `applyDeferredLayerVisibilitySettings` user-preference layers, stats/media readiness, and rendered 3D GPU frames settle before revealing the Earth viewport. It provides three real-coastline 3D Canvas themes (`singularity`, `constellation`, `horizon`, plus `off`), displays the transparent ZJU seal (`zju-emblem.png`) and `PRESENTED BY 临空智能媒体研究院 / Intelligent Media Institute` lockup, and is controllable via splash pills, `Planet Earth → Splash Screen`, `CmdOrCtrl+Shift+S`, or `--splash-theme`.
Earth frontend is essentially a single shared visualization core under `public/earth` powering both Web and Desktop.
+38
View File
@@ -473,6 +473,44 @@ uv run pytest backend/tests/test_otp_service.py
5. After deployment, open Earth, enable "Border Lines", and inspect China's southeast coast, Taiwan, Hainan, the South China Sea, Zangnan, Kosovo, and Gaza for hover behavior and boundary policy.
6. If no high-precision manifest/PMTiles exists locally, Earth uses the bundled `frontend/public/earth/data/countries-admin0.min.geojson` fallback. If high-precision assets exist but tile requests fail, troubleshoot PMTiles range requests, manifest provider, Nginx `.pmtiles` static serving, and sha256 consistency.
## Publish locally and deploy production releases automatically
Push the stable version tag to Gitea. On a new publishing workstation, sign in to the dedicated Docker configuration with a Gitea token scoped to `write:package`. Git release credentials and the package writer credential are stored separately.
```bash
docker --config "${XDG_CONFIG_HOME:-$HOME/.config}/planet/registry" login gitea.rclaw.top --username linkong
```
Run the following command from the tagged commit.
```bash
python3 scripts/release_publish.py --tag "$(git describe --tags --exact-match)" --use-git-credential
```
The publisher builds Linux amd64 images for `admin`, `backend`, and `aiprovider` from the tag, then verifies their revisions and digests in Gitea. Admin uses the lightweight build target. Desktop packages are built from the same commit by default. Pass `--assets-dir client/release` to reuse complete packages and a hotfix built for that tag. Repeat the same command after an interrupted upload to reuse the original build and verified attachments. The workstation can go offline once publication succeeds.
The production host checks the latest stable Gitea Release approximately every two minutes using `planet-release-deploy.timer`. Once all three images and the hotfix checksum are available, it pulls the images by digest, backs up PostgreSQL, updates AI Provider, backend, and Admin in order, verifies their endpoints, publishes the Earth hotfix, and downloads it to verify its checksum. The host retains its Compose configuration, memory limits, and data volumes. Apply the release-specific infrastructure migration first when a release requires new mounts, services, or incompatible database changes.
A failed rollout restores the previous application images and hotfix manifest while preserving database writes. An interrupted rollout resumes recovery on the next check. A failed version waits for an explicit retry or a newer release. The most recent pre-change database backups and version records are under `/var/lib/planet-release-deploy/last-success/` and `last-failed/`. Retry after resolving the underlying error.
```bash
systemctl list-timers planet-release-deploy.timer
journalctl -u planet-release-deploy.service -n 40
sudo python3 /usr/local/lib/planet-release/production_deploy.py --check
sudo python3 /usr/local/lib/planet-release/production_deploy.py --retry
```
To provision a replacement host, restore `/etc/planet/deploy.env`, `/opt/planet/current`, and the production volumes. Install the controller from a trusted checkout and verify the current deployment before enabling its timer.
```bash
sudo install -d /usr/local/lib/planet-release
sudo install -m 0644 scripts/{production_deploy,production_registry,release_publish}.py /usr/local/lib/planet-release/
sudo install -m 0644 deploy/systemd/planet-release-deploy.{service,timer} /etc/systemd/system/
sudo systemctl daemon-reload
sudo python3 /usr/local/lib/planet-release/production_deploy.py --check
sudo systemctl enable --now planet-release-deploy.timer
```
## Related Docs
- [planet.sh Startup Mechanism](/home/ray/dev/linkong/planet/docs/technical/en/ops-planet-sh-startup.md)
+1 -1
View File
@@ -42,7 +42,7 @@ Earth 现同时支持**Web 浏览入口**与**原生 Electron 桌面客户端入
- **运行时端点注入**:桌面预加载脚本暴露同步 `window.__PLANET_RUNTIME_CONFIG__`(`backendUrl`、`adminUrl`、`wsUrl`、`motionWsUrl`、`localMediaPipeBaseUrl`、`isElectron`)及受控 `window.planetDesktop` 桥接,`realtime.js`、`motion-control.js` 与 `motion-browser-provider.js` 自动读取该配置并优先加载本地 MediaPipe WASM。
- **跨进程实时同步**:由于 Electron 桌面端与 `planet_admin` 容器不在同一浏览器源,后台对算力配置、Earth 品牌信息及关于信息的修改除广播 `BroadcastChannel` 外,同时经后端 WebSocket 推送 `earth_updates`(`compute_configuration` / `earth_brand` / `earth_about`),使桌面端与浏览器端同步刷新。
- **原生窗口与帧率稳定**:桌面端使用原生暗色标题栏避免遮挡右上角 `#media-panel`,窗口最小尺寸放宽至 `360×480` 以支持手动拖窄进入移动端布局(`<= 820px`),并可通过 `Alt` 菜单栏 **视图 / View → 切换横竖屏 / Toggle Portrait & Landscape**(或 `CmdOrCtrl+Shift+M`)一键切换横竖屏比例;同时禁用 Chromium 页面缩放并将触控板捏合(`wheel + ctrlKey`)及 `CmdOrCtrl + =/-/0` 映射至 3D 视角缩放;`controls.js` 对液态玻璃光斑响应、`frame-stats.js` 布局刷新与 `main.js` 地球悬停拾取采用 `ResizeObserver` + `requestAnimationFrame` 合帧并限制 `deltaTime` 尖峰,窗口最小化时通过 `planet-desktop:visibility` 暂停空转渲染。
- **多方案桌面端启动画面与无闪烁就绪门控**:[桌面端启动画面控制器](/home/ray/dev/linkong/planet/client/src/preload/splash.ts) 通过预加载脚本里的 `document` `MutationObserver` 在解析出 `<html>` 的第一时间挂载隔离 Shadow DOM 蒙层并同步绘制首帧,[窗口展示门控](/home/ray/dev/linkong/planet/client/src/main/show-gate.ts) 同时等待 `ready-to-show` 与 `planet:splash-first-paint` 后才显示窗口,彻底消除启动瞬间的原始网页闪屏;同时 `frontend/public/earth/js/main.js` 与 `controls.js` 在保持 Web 端视觉与交互完全一致的前提下,通过非可视化的 `earth:startup-progress` / `earth:startup-ready` 生命周期事件在完成 `applyDeferredLayerVisibilitySettings` 用户偏好图层恢复、统计/新闻直播初始化及首帧 3D GPU 渲染后再触发星核/星轨/破晓退场;内置三套 3D Canvas 动态启动方案(`singularity` / `constellation` / `horizon`),展示透明浙大校徽与 `PRESENTED BY 临空智能媒体研究院 / Institute of Intelligent Media` 署名,可通过启动页切换按钮、`Alt → Planet Earth → 启动画面方案`、`CmdOrCtrl+Shift+S` 重播及 `--splash-theme` 切换。
- **多方案桌面端启动画面与无闪烁就绪门控**:[桌面端启动画面控制器](/home/ray/dev/linkong/planet/client/src/preload/splash.ts) 通过预加载脚本里的 `document` `MutationObserver` 在解析出 `<html>` 的第一时间挂载隔离 Shadow DOM 蒙层并同步绘制首帧,[窗口展示门控](/home/ray/dev/linkong/planet/client/src/main/show-gate.ts) 同时等待 `ready-to-show` 与 `planet:splash-first-paint` 后才显示窗口,彻底消除启动瞬间的原始网页闪屏;同时 `frontend/public/earth/js/main.js` 与 `controls.js` 在保持 Web 端视觉与交互完全一致的前提下,通过非可视化的 `earth:startup-progress` / `earth:startup-ready` 生命周期事件在完成 `applyDeferredLayerVisibilitySettings` 用户偏好图层恢复、统计/新闻直播初始化及首帧 3D GPU 渲染后再触发星核/星轨/破晓退场;内置三套 3D Canvas 动态启动方案(`singularity` / `constellation` / `horizon`),展示透明浙大校徽与 `PRESENTED BY 临空智能媒体研究院 / Intelligent Media Institute` 署名,可通过启动页切换按钮、`Alt → Planet Earth → 启动画面方案`、`CmdOrCtrl+Shift+S` 重播及 `--splash-theme` 切换。
所以 Earth 前端本质上是 `public/earth` 下的一套独立可视化内核,同时服务 Web 与桌面端。
+38
View File
@@ -473,6 +473,44 @@ uv run pytest backend/tests/test_otp_service.py
5. 部署后打开智能星球,开启“国界线”,放大中国东南海岸、台湾、海南、南海、藏南、科索沃、加沙等区域验证 hover 和边界口径。
6. 如果本地没有高精 manifest/PMTiles,Earth 会使用 `frontend/public/earth/data/countries-admin0.min.geojson` 低精度 fallback;如果高精产物存在但瓦片请求失败,按 PMTiles range 请求、manifest provider、Nginx `.pmtiles` 静态返回和 sha256 一致性排查。
## 在本机发版,生产机自动部署
把正式版本标签推送到 Gitea 后,在发版机的 Planet 仓库执行以下命令。首次配置发版机时,使用具有 `write:package` 权限的 Gitea 令牌登录专用 Docker 配置目录。Git 发布凭据与镜像推送凭据分别保存。
```bash
docker --config "${XDG_CONFIG_HOME:-$HOME/.config}/planet/registry" login gitea.rclaw.top --username linkong
```
日常发版时在已打标签的提交上执行以下命令。
```bash
python3 scripts/release_publish.py --tag "$(git describe --tags --exact-match)" --use-git-credential
```
发布器从标签提交构建 Linux amd64 的 `admin`、`backend`、`aiprovider` 镜像,并核验仓库中的提交标签与摘要。Admin 使用轻量构建目标。默认从同一提交打包桌面客户端。已经备好该标签的各平台安装包和热更新包时可加 `--assets-dir client/release`。上传中断后重复同一命令即可复用已构建的镜像和已校验的附件。发布命令成功后可以关闭本机。
生产机的 `planet-release-deploy.timer` 约每两分钟读取 Gitea 最新正式 Release。新版本的三个镜像和热更新校验文件齐全后,服务按不可变摘要拉取镜像,备份 PostgreSQL,依次更新 AI Provider、后端和 Admin,再验证接口、发布并回读 Earth 热更新包。主机沿用当前生产 Compose、内存限制和数据卷。需要新增挂载、服务或数据库不兼容变更时,先按该版本的迁移方案调整主机配置。
上线失败时,服务恢复上一版的镜像摘要和热更新清单,保留数据库里的业务写入。事务记录在重启后仍可恢复。失败的版本会暂停自动重试,较新的正式版仍可上线。`/var/lib/planet-release-deploy/last-success/` 和 `last-failed/` 分别保留最近一次成功或失败切换前的数据库备份和版本信息。确认故障已排除后可以单独重试该版本。
```bash
systemctl list-timers planet-release-deploy.timer
journalctl -u planet-release-deploy.service -n 40
sudo python3 /usr/local/lib/planet-release/production_deploy.py --check
sudo python3 /usr/local/lib/planet-release/production_deploy.py --retry
```
替换部署主机时,从受信任的运维检出中安装控制程序和定时器。先恢复 `/etc/planet/deploy.env`、`/opt/planet/current` 及当前生产数据卷,再校验当前版本并启用定时器。
```bash
sudo install -d /usr/local/lib/planet-release
sudo install -m 0644 scripts/{production_deploy,production_registry,release_publish}.py /usr/local/lib/planet-release/
sudo install -m 0644 deploy/systemd/planet-release-deploy.{service,timer} /etc/systemd/system/
sudo systemctl daemon-reload
sudo python3 /usr/local/lib/planet-release/production_deploy.py --check
sudo systemctl enable --now planet-release-deploy.timer
```
## 相关文档
- [planet.sh 启动机制](/home/ray/dev/linkong/planet/docs/technical/zh/ops-planet-sh-startup.md)
+2 -1
View File
@@ -16,12 +16,13 @@
## Current Version
- `main` 当前主线历史推导到:`0.16.5`
- `dev` 当前开发分支历史推导到:`0.79.0`
- `dev` 当前开发分支历史推导到:`0.79.1`
## Timeline
| Version | Type | Branch | Commit | Summary |
| --- | --- | --- | --- | --- |
| `0.79.1` | improvement | `dev` | `v0.79.1` | Windows 根据显存与帧率自动切换显卡,保留 45 秒切换冷却与窗口状态,统一 IMI 英文名称 |
| `0.79.0` | feature | `dev` | `v0.79.0` | 破晓-星核统一启动动效、Phase 1 L1 热更新体系与 Windows GPU/WebGL 恢复加固 |
| `0.78.0` | feature | `dev` | `v0.78.0` | 全局单份采集策略、短期船舶航迹、精简生产部署和桌面协议注册 |
| `0.77.0` | feature | `dev` | `v0.77.0` | 新增原生 Electron Earth 桌面客户端(多方案 3D 启动页/横竖屏/离线协议/Gitea 自动发布)、轻量 Admin 独立容器、全球综合态势工作台与算力对比增强 |
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "planet-frontend",
"version": "0.79.0",
"version": "0.79.1",
"private": true,
"packageManager": "bun@1",
"dependencies": {
+2 -2
View File
@@ -871,7 +871,7 @@ const EXACT_TRANSLATIONS = {
"出品方": "Producer",
"策划人": "Planners",
"产品兼开发者": "Product & Development",
"浙江大学临空智能媒体研究院": "Zhejiang University Linkong Institute of Intelligent Media",
"浙江大学临空智能媒体研究院": "Zhejiang University Linkong Intelligent Media Institute",
"方兴东、黄柳青": "Fang Xingdong, Huang Liuqing",
"钱坤、张鸽、齐鹏": "Qian Kun, Zhang Ge, Qi Peng",
"面向临空场景下的智能媒体研究、全球态势感知与多源开放数据巡航,提供可视化观测、事件聚合与交互式探索能力。": "For intelligent media research, global situational awareness, and multi-source open-data cruise in linkong scenarios, providing visual observation, event aggregation, and interactive exploration.",
@@ -981,7 +981,7 @@ const EXACT_TRANSLATIONS = {
"搜索结果": "Search results",
"调整地球默认大小": "Adjust default Earth size",
"调整地形透明度": "Adjust terrain opacity",
"浙江大学临空智能媒体研究院 Logo": "Zhejiang University Linkong Institute of Intelligent Media Logo",
"浙江大学临空智能媒体研究院 Logo": "Zhejiang University Linkong Intelligent Media Institute Logo",
"Earth 页面发生未捕获错误": "Earth page uncaught error",
"Earth 页面发生未处理 Promise 错误": "Earth page unhandled Promise error",
"等待动捕数据": "Waiting for motion data",
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "planet"
version = "0.79.0"
version = "0.79.1"
description = "智能星球计划 - 态势感知系统"
requires-python = ">=3.14"
dependencies = [
+1
View File
@@ -24,6 +24,7 @@ main() {
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_docker_proxy.py
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_docker_mirror.py
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_database_startup.py
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_production_release.py
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_windows_restart.py
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_error_diagnostics.py
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_tool_resolution.py
+239
View File
@@ -0,0 +1,239 @@
import hashlib
import io
import json
import sys
import tarfile
import tempfile
import unittest
from contextlib import ExitStack
from pathlib import Path
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import production_deploy as deploy
import production_registry as registry
import production_release as publisher
def hotfix(tag):
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as archive:
for name, data in {
"bundle-meta.json": json.dumps({"version": tag[1:], "shellVersion": tag[1:]}).encode(),
"index.html": b"<html>release test</html>",
}.items():
member = tarfile.TarInfo(name)
member.size = len(data)
archive.addfile(member, io.BytesIO(data))
return buf.getvalue()
class TransactionTests(unittest.TestCase):
old, tag = "v1.0.0", "v1.1.0"
def setUp(self):
self.stack = ExitStack()
self.addCleanup(self.stack.close)
base = Path(self.stack.enter_context(tempfile.TemporaryDirectory()))
self.host = deploy.Host(base / "host", base / "settings", base / "state")
self.host.state.mkdir()
folder = self.host.directory(self.old)
folder.mkdir(parents=True)
for name in deploy.HOST_FILES:
(folder / name).write_text("host-managed")
deploy.point_current(self.host, self.old)
self.old_refs = {key: "previous-" + key for key in registry.SERVICES}
self.new_refs = {key: "candidate-" + key for key in registry.SERVICES}
lines = [f"{key}={self.old_refs[name]}" for name, key in registry.SERVICES.items()]
self.host.env.write_text(
"\n".join(lines + ["LIMIT=500m", "CLIENT_UPDATE_PUBLISH_TOKEN=fixture"]) + "\n"
)
self.running = self.old_refs.copy()
self.manifest = base / "manifest.json"
self.original = b'{"bundle":{"version":"1.0.0","sha256":"previous"}}'
self.manifest.write_bytes(self.original)
self.calls = []
self.data = hotfix(self.tag)
self.sha = hashlib.sha256(self.data).hexdigest()
self.release = {"tag_name": self.tag, "draft": False, "prerelease": False}
self.mock("read_url", return_value=json.dumps(self.release).encode())
self.mock("tag_commit", return_value="f" * 40)
self.images = self.mock("resolved_images", return_value=self.new_refs)
self.mock("release_bundle", return_value=("bundle.tar.gz", self.data, self.sha))
self.mock("inspect", side_effect=lambda name: {"Config": {"Image": self.running[name]}})
self.mock("data_containers", return_value={"postgres": "same-db", "redis": "same-redis"})
self.mock("live_manifest_path", return_value=self.manifest)
self.mock("docker", side_effect=lambda *args: self.calls.append(args[0]))
self.mock("backup_database", side_effect=lambda p: p.write_bytes(b"verified backup"))
self.mock("check_routes", side_effect=lambda: self.calls.append("health"))
self.service = self.mock("rollout_services", side_effect=self.roll)
self.publish = self.mock("publish_hotfix_bundle", side_effect=self.publish_data)
self.verify = self.mock("check_hotfix", side_effect=self.verify_data)
def mock(self, name, **kwargs):
return self.stack.enter_context(patch.object(deploy, name, **kwargs))
def roll(self, host, tag, refs):
self.calls.append(tag)
self.running.update(refs)
def publish_data(self, **kwargs):
self.calls.append("hotfix")
archive, digest = kwargs["assets"][0]
self.assertEqual(hashlib.sha256(archive.read_bytes()).hexdigest(), digest)
self.manifest.write_text(
json.dumps({"bundle": {"version": kwargs["tag"][1:], "sha256": digest}})
)
def verify_data(self, tag, digest, shell_version=None):
self.assertEqual(
json.loads(self.manifest.read_bytes())["bundle"], {"version": tag[1:], "sha256": digest}
)
def test_new_release_and_duplicate_tick(self):
deploy.reconcile(self.host)
self.assertEqual(self.calls, ["pull"] * 3 + [self.tag, "health", "hotfix"])
self.assertEqual(self.host.current(), self.tag)
self.assertEqual(self.running, self.new_refs)
self.assertIn("LIMIT=500m\n", self.host.env.read_text())
self.assertTrue((self.host.state / "last-success/database.dump").is_file())
deploy.reconcile(self.host)
self.assertEqual(self.service.call_count, 1)
def test_manifest_failure_restores_previous_release_and_parks_it(self):
def verify(tag, sha, shell_version=None):
if tag == self.tag:
raise RuntimeError("independent public download failed")
self.verify_data(tag, sha)
self.verify.side_effect = verify
with self.assertRaisesRegex(RuntimeError, "download failed"):
deploy.reconcile(self.host)
self.assertEqual(self.host.current(), self.old)
self.assertEqual(self.running, self.old_refs)
self.assertEqual(self.manifest.read_bytes(), self.original)
self.assertTrue((self.host.state / "last-failed/database.dump").is_file())
deploy.reconcile(self.host)
self.assertEqual(self.service.call_count, 2)
self.verify.side_effect = self.verify_data
deploy.reconcile(self.host, retry=True)
self.assertEqual(self.host.current(), self.tag)
def test_interrupted_rollout_recovers_before_processing_latest(self):
self.service.side_effect = KeyboardInterrupt()
with self.assertRaises(KeyboardInterrupt):
deploy.reconcile(self.host)
self.assertTrue((self.host.state / "pending/release.json").is_file())
self.service.side_effect = self.roll
deploy.reconcile(self.host)
self.assertFalse((self.host.state / "pending").exists())
self.assertEqual(self.host.current(), self.old)
self.assertEqual(self.running, self.old_refs)
self.assertEqual(self.calls.count(self.old), 1)
self.publish.assert_not_called()
def test_incomplete_publication_does_not_change_production(self):
self.images.side_effect = RuntimeError("image is missing")
env = self.host.env.read_bytes()
with self.assertRaisesRegex(RuntimeError, "image is missing"):
deploy.reconcile(self.host)
self.assertEqual(self.host.env.read_bytes(), env)
self.assertFalse((self.host.state / "pending").exists())
self.service.assert_not_called()
def test_drafts_prereleases_and_older_versions_never_roll_out(self):
for tag, draft, pre in [
(self.tag, True, False),
(self.tag, False, True),
("v0.9.9", False, False),
]:
data = json.dumps({"tag_name": tag, "draft": draft, "prerelease": pre}).encode()
with patch.object(deploy, "read_url", return_value=data):
deploy.reconcile(self.host)
self.images.assert_not_called()
class ImageTests(unittest.TestCase):
def test_interrupted_upload_reuses_identical_local_artifacts(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
supplied = root / "supplied"
supplied.mkdir()
cache = root / "cache"
tag = "v1.2.3"
for name in (
"Planet Earth-1.2.3-win.zip",
"Planet Earth-1.2.3-mac.zip",
"planet_1.2.3.deb",
):
(supplied / name).write_bytes(b"original")
(supplied / "planet-earth-bundle-1.2.3.tar.gz").write_bytes(hotfix(tag))
suffixes = (".zip", ".deb", ".tar.gz")
publisher.cached_packages(root, supplied, cache, tag, suffixes)
original = "Planet Earth-1.2.3-win.zip"
(supplied / original).write_bytes(b"later build")
publisher.cached_packages(root, supplied, cache, tag, suffixes)
self.assertEqual((cache / original).read_bytes(), b"original")
(cache / original).write_bytes(b"corrupt cache")
with self.assertRaisesRegex(ValueError, "differ"):
publisher.cached_packages(root, supplied, cache, tag, suffixes)
def test_builds_only_missing_service_from_tag_and_verifies_after_push(self):
with (
tempfile.TemporaryDirectory() as temp,
patch.object(publisher, "resolve_image") as resolve,
patch.object(publisher.subprocess, "run") as run,
):
resolve.side_effect = ["provider-pin", "backend-pin", None, "admin-pin"]
publisher.ensure_images(Path(temp), "v1.2.3", "a" * 40)
args = run.call_args.args[0]
self.assertIn("linux/amd64", args)
self.assertIn("PLANET_FRONTEND_TARGET=admin", args)
self.assertIn("org.opencontainers.image.revision=" + "a" * 40, args)
self.assertTrue(any("push=true" in x and "admin:v1.2.3" in x for x in args))
run.assert_called_once()
def test_registry_verifies_actual_config_and_commit_before_accepting_digest(self):
commit = "a" * 40
cfg = json.dumps(
{
"os": "linux",
"architecture": "amd64",
"config": {
"Labels": {
"org.opencontainers.image.revision": commit,
"planet.frontend.target": "admin",
}
},
}
).encode()
raw = json.dumps({"config": {"digest": registry.digest(cfg)}}).encode()
with patch.object(registry, "read_url", side_effect=[b'{"token":"read"}', raw, cfg]):
pin = registry.resolve_image("admin", "v1.2.3", commit)
self.assertTrue(pin.endswith("@" + registry.digest(raw)))
for bad_commit, bad_cfg in [("b" * 40, cfg), (commit, cfg + b" ")]:
with (
patch.object(registry, "read_url", side_effect=[b'{"token":"read"}', raw, bad_cfg]),
self.assertRaises(ValueError),
):
registry.resolve_image("admin", "v1.2.3", bad_commit)
def test_corrupt_bundle_and_duplicate_checksum_are_rejected(self):
tag = "v1.2.3"
name = "planet-earth-bundle-1.2.3.tar.gz"
data = hotfix(tag)
expected = f"{hashlib.sha256(data).hexdigest()} {name}\n".encode()
release = {
"tag_name": tag,
"assets": [{"name": name, "size": len(data)}, {"name": "SHA256SUMS.txt", "size": 99}],
}
for sums, content in [(expected + expected, data), (expected, b"x" * len(data))]:
with (
patch.object(registry, "read_url", side_effect=[sums, content]),
self.assertRaises(ValueError),
):
registry.release_bundle(release, tag)
if __name__ == "__main__":
unittest.main()
+479
View File
@@ -0,0 +1,479 @@
#!/usr/bin/env python3
"""Reconcile published Planet releases with the existing lightweight production Compose stack."""
from __future__ import annotations
import argparse
import fcntl
import hashlib
import io
import json
import os
import shutil
import subprocess
import sys
import tarfile
import tempfile
import time
from dataclasses import dataclass
from pathlib import Path
if __package__:
from .production_registry import (
API,
REPO,
SERVER,
SERVICES,
read_url,
release_bundle,
resolve_image,
tag_commit,
version,
)
from .release_publish import publish_hotfix_bundle
else:
from production_registry import (
API,
REPO,
SERVER,
SERVICES,
read_url,
release_bundle,
resolve_image,
tag_commit,
version,
)
from release_publish import publish_hotfix_bundle
PUBLIC = "https://rclaw.top"
ADMIN = "https://admin.rclaw.top"
PROJECT = "planet-production"
HOST_FILES = (
"compose.yaml",
"compose.pilot.yaml",
"planet-https.conf",
"planet-api-locations.conf",
)
@dataclass(frozen=True)
class Host:
root: Path = Path("/opt/planet")
env: Path = Path("/etc/planet/deploy.env")
state: Path = Path("/var/lib/planet-release-deploy")
def directory(self, tag):
version(tag)
path = self.root / "releases" / tag
if path.is_symlink():
raise ValueError("Release directories must not be symbolic links")
return path
def current(self):
path = (self.root / "current").resolve(strict=True)
if path != self.directory(path.name):
raise ValueError("Unexpected active release directory")
return path.name
def sync_directory(path):
fd = os.open(path, os.O_DIRECTORY | os.O_RDONLY)
try:
os.fsync(fd)
finally:
os.close(fd)
def atomic_file(path, data, mode=0o600):
fd, name = tempfile.mkstemp(prefix="." + path.name, dir=path.parent)
try:
with os.fdopen(fd, "wb") as out:
os.fchmod(out.fileno(), mode)
out.write(data)
out.flush()
os.fsync(out.fileno())
os.replace(name, path)
sync_directory(path.parent)
finally:
Path(name).unlink(missing_ok=True)
def point_current(host, tag):
link = host.root / "current"
with tempfile.TemporaryDirectory(dir=host.root) as temp:
candidate = Path(temp) / "current"
candidate.symlink_to(host.directory(tag))
os.replace(candidate, link)
sync_directory(host.root)
def env_settings(host):
return dict(
line.split("=", 1)
for line in host.env.read_text().splitlines()
if "=" in line and not line.lstrip().startswith("#")
)
def set_images(host, images):
values = {SERVICES[service]: images[service] for service in SERVICES}
found = set()
lines = host.env.read_text().splitlines(keepends=True)
for index, line in enumerate(lines):
key = line.partition("=")[0]
if key in values:
found.add(key)
lines[index] = f"{key}={values[key]}\n"
if missing := values.keys() - found:
raise ValueError("Missing production image settings: " + ", ".join(sorted(missing)))
atomic_file(host.env, "".join(lines).encode())
def docker(*args):
return subprocess.check_output(["docker", *map(str, args)], text=True).strip()
def container_name(service):
return "planet_deploy_" + service
def inspect(service):
return json.loads(docker("inspect", container_name(service)))[0]
def data_containers():
return {name: inspect(name)["Id"] for name in ("postgres", "redis")}
def live_manifest_path():
mounts = inspect("backend")["Mounts"]
[mount] = [m for m in mounts if m["Destination"] == "/app/backend/data/client-updates"]
if mount.get("Name") != PROJECT + "_client_updates_data" or mount["Type"] != "volume":
raise RuntimeError("Expected the persistent production client update volume")
return Path(mount["Source"]) / "manifest.json"
def stage_config(host, previous, tag):
source, target = host.directory(previous), host.directory(tag)
target.mkdir(exist_ok=True)
sync_directory(target.parent)
for name in HOST_FILES:
original, dest = source / name, target / name
if dest.exists():
if dest.is_symlink() or dest.read_bytes() != original.read_bytes():
raise RuntimeError(f"Existing host configuration differs: {dest}")
else:
atomic_file(dest, original.read_bytes(), original.stat().st_mode & 0o777)
return target
def rollout_services(host, tag, images):
directory = host.directory(tag)
for name in SERVICES:
print(f"Starting {name} from {images[name]}", flush=True)
docker(
"compose",
"--project-name",
PROJECT,
"--env-file",
host.env,
"-f",
directory / "compose.yaml",
"-f",
directory / "compose.pilot.yaml",
"up",
"-d",
"--no-deps",
"--no-build",
"--pull",
"never",
name,
)
deadline = time.monotonic() + 100
while True:
container = inspect(name)
state = container["State"]
if (
container["Config"]["Image"] == images[name]
and state["Status"] == "running"
and state.get("Health", {}).get("Status") == "healthy"
):
break
if (
state["Status"] in ("exited", "dead")
or state.get("OOMKilled")
or time.monotonic() >= deadline
):
raise RuntimeError(f"{name} did not become healthy")
time.sleep(2)
def check_routes():
for url in (PUBLIC + "/health/ready", PUBLIC + "/api/v1/visualization/geo/summary"):
if not isinstance(json.loads(read_url(url)), dict):
raise RuntimeError(f"Unexpected response from {url}")
if b"<html" not in read_url(ADMIN + "/earth").lower():
raise RuntimeError("Admin Earth entry did not return HTML")
def check_hotfix(tag, sha, shell_version=None):
manifest = json.loads(read_url(PUBLIC + "/api/v1/client/update-manifest"))
bundle = manifest.get("bundle") or {}
path = f"/api/v1/client/updates/files/planet-earth-bundle-{tag[1:]}.tar.gz"
if (
manifest.get("shell", {}).get("version") != (shell_version or tag[1:])
or bundle.get("version") != tag[1:]
or bundle.get("sha256") != sha
or bundle.get("url") != path
):
raise RuntimeError("Live hotfix manifest does not match the release")
if hashlib.sha256(read_url(PUBLIC + path, limit=32 * 1024 * 1024)).hexdigest() != sha:
raise RuntimeError("Live hotfix download failed SHA-256 verification")
def minimum_shell(data, tag):
with tarfile.open(fileobj=io.BytesIO(data), mode="r:gz") as archive:
member = archive.getmember("bundle-meta.json")
if not member.isfile() or member.size > 8192:
raise ValueError("Invalid hotfix metadata")
meta = json.load(archive.extractfile(member))
if meta.get("version") != tag[1:]:
raise ValueError("Hotfix metadata version differs from the release")
minimum = meta.get("minShellVersion") or meta["shellVersion"]
if version("v" + minimum) > version(tag):
raise ValueError("Hotfix requires a newer shell than the release")
return minimum
def backup_database(target):
with target.open("xb") as out:
subprocess.run(
[
"docker",
"exec",
container_name("postgres"),
"sh",
"-ec",
'exec pg_dump -Fc -Z 1 -U "$POSTGRES_USER" "$POSTGRES_DB"',
],
stdout=out,
check=True,
)
os.fsync(out.fileno())
with target.open("rb") as source:
catalog = subprocess.check_output(
["docker", "exec", "-i", container_name("postgres"), "pg_restore", "-l"], stdin=source
)
if b"TABLE DATA" not in catalog:
raise RuntimeError("Pre-deployment database backup failed verification")
def save_journal(host, journal, manifest):
with tempfile.TemporaryDirectory(dir=host.state) as scratch:
directory = Path(scratch) / "transaction"
directory.mkdir()
atomic_file(directory / "release.json", json.dumps(journal).encode())
if manifest.exists():
atomic_file(directory / "previous-manifest.json", manifest.read_bytes())
backup_database(directory / "database.dump")
sync_directory(directory)
os.rename(directory, host.state / "pending")
sync_directory(host.state)
def finish_journal(host, name):
previous = host.state / name
if previous.exists():
shutil.rmtree(previous)
os.rename(host.state / "pending", previous)
sync_directory(host.state)
def rollback(host):
pending = host.state / "pending"
journal = json.loads((pending / "release.json").read_text())
previous = journal["previous"]
print(f"Restoring {previous} after interrupted or unsuccessful {journal['tag']}", flush=True)
manifest = Path(journal["manifest"])
old = pending / "previous-manifest.json"
before = old.read_bytes() if old.exists() else None
current = manifest.read_bytes() if manifest.exists() else None
if current != before:
bundle = json.loads(current or b"{}").get("bundle") or {}
if bundle.get("version") != journal["tag"][1:] or bundle.get("sha256") != journal["sha"]:
raise RuntimeError(
"Hotfix manifest changed independently; preserved the transaction for review"
)
if before is None:
manifest.unlink()
sync_directory(manifest.parent)
else:
atomic_file(manifest, before, 0o644)
set_images(host, journal["old_images"])
rollout_services(host, previous, journal["old_images"])
point_current(host, previous)
check_routes()
if before:
old_manifest = json.loads(before)
bundle = old_manifest.get("bundle")
if bundle:
check_hotfix(
"v" + bundle["version"],
bundle["sha256"],
old_manifest.get("shell", {}).get("version"),
)
finish_journal(host, "last-failed")
print(f"Rollback to {previous} verified", flush=True)
def resolved_images(tag, commit):
images = {}
for service in SERVICES:
ref = resolve_image(service, tag, commit)
if not ref:
raise RuntimeError(f"Waiting for the published {service}:{tag} image")
images[service] = ref
return images
def deploy(host, release, previous, tag, images, commit):
name, data, sha = release_bundle(release, tag)
minimum = minimum_shell(data, tag)
settings = env_settings(host)
token = settings.get("CLIENT_UPDATE_PUBLISH_TOKEN", "").strip("'\u0022")
if not token:
raise RuntimeError("Production hotfix publisher credential is missing")
old_images = {n: settings[k].strip("'\u0022") for n, k in SERVICES.items()}
for service, ref in images.items():
docker("pull", "--platform", "linux/amd64", ref)
if inspect(service)["Config"]["Image"] != old_images[service]:
raise RuntimeError("Running image differs from the host configuration: " + service)
stage_config(host, previous, tag)
manifest = live_manifest_path()
bundle_path = manifest.parent / name
if bundle_path.exists() and hashlib.sha256(bundle_path.read_bytes()).hexdigest() != sha:
raise RuntimeError("Existing versioned hotfix file has different contents")
original_stores = data_containers()
save_journal(
host,
dict(
tag=tag,
previous=previous,
old_images=old_images,
manifest=str(manifest),
sha=sha,
commit=commit,
),
manifest,
)
try:
set_images(host, images)
rollout_services(host, tag, images)
check_routes()
if data_containers() != original_stores:
raise RuntimeError("PostgreSQL or Redis container identity changed")
with tempfile.TemporaryDirectory(dir=host.state) as tmp:
archive = Path(tmp) / name
archive.write_bytes(data)
publish_hotfix_bundle(
publish_url=PUBLIC,
publish_token=token,
tag=tag,
notes=release.get("body") or "",
release_html_url=f"{SERVER}/{REPO}/releases/tag/{tag}",
assets=[(archive, sha)],
min_shell_version=minimum,
)
check_hotfix(tag, sha)
point_current(host, tag)
finish_journal(host, "last-success")
except Exception as exc:
print(f"Deploying {tag} failed: {exc}", file=sys.stderr, flush=True)
rollback(host)
raise
print(f"Deployed {tag} at {commit}", flush=True)
def reconcile(host, *, check=False, retry=False):
if (host.state / "pending").exists():
if check:
raise RuntimeError("A previous rollout is pending recovery")
rollback(host)
previous = host.current()
release = json.loads(read_url(API + "/releases/latest"))
tag = release["tag_name"]
if release.get("draft") or release.get("prerelease"):
return
try:
candidate_version = version(tag)
except ValueError:
print(f"Ignoring release with a non-production tag: {tag!r}")
return
if candidate_version < version(previous):
return
if tag == previous and not check:
print(f"{tag} is already active")
return
commit = tag_commit(tag)
failed = host.state / "last-failed/release.json"
if (
tag != previous
and failed.is_file()
and json.loads(failed.read_text())["tag"] == tag
and not retry
):
print(f"{tag} previously rolled back; waiting for a new release or --retry", flush=True)
return
images = resolved_images(tag, commit)
if check:
_, data, sha = release_bundle(release, tag)
minimum_shell(data, tag)
if tag == previous:
for name, ref in images.items():
container = inspect(name)
if (
container["Config"]["Image"] != ref
or container["State"]["Health"]["Status"] != "healthy"
):
raise RuntimeError("Active service differs from the release: " + name)
check_routes()
check_hotfix(tag, sha)
print(f"Verified {tag} at {commit}; active release {previous}", flush=True)
return
deploy(host, release, previous, tag, images, commit)
def main():
parser = argparse.ArgumentParser(description=__doc__)
group = parser.add_mutually_exclusive_group()
group.add_argument(
"--check", action="store_true", help="Verify the release without switching production"
)
group.add_argument(
"--retry", action="store_true", help="Retry the latest release after a verified rollback"
)
args = parser.parse_args()
os.umask(0o077)
host = Host()
host.state.mkdir(mode=0o700, parents=True, exist_ok=True)
with (host.state / "lock").open("a") as lock:
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
print("Another production release check is running")
return
reconcile(host, check=args.check, retry=args.retry)
if __name__ == "__main__":
try:
main()
except (
RuntimeError,
ValueError,
KeyError,
OSError,
tarfile.TarError,
subprocess.SubprocessError,
) as exc:
sys.exit(f"Production release check failed: {exc}")
+155
View File
@@ -0,0 +1,155 @@
"""Read the public Planet release and immutable linux/amd64 images from Gitea."""
from __future__ import annotations
import hashlib
import json
import re
import time
import urllib.error
import urllib.parse
import urllib.request
SERVER = "https://gitea.rclaw.top"
REPO = "linkong/planet"
REGISTRY = urllib.parse.urlsplit(SERVER).netloc
API = f"{SERVER}/api/v1/repos/{REPO}"
SERVICES = {
"aiprovider": "AI_PROVIDER_IMAGE_NAME",
"backend": "BACKEND_IMAGE_NAME",
"admin": "ADMIN_IMAGE_NAME",
}
MANIFEST_TYPES = ", ".join(
(
"application/vnd.oci.image.index.v1+json",
"application/vnd.oci.image.manifest.v1+json",
"application/vnd.docker.distribution.manifest.list.v2+json",
"application/vnd.docker.distribution.manifest.v2+json",
)
)
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args):
return None
def read_url(url, *, headers=None, limit=2 * 1024 * 1024):
"""Bound a release download and keep authorization on its original HTTPS endpoint."""
request = urllib.request.Request(url, headers=headers or {})
for attempt in range(3):
try:
with urllib.request.build_opener(NoRedirect()).open(request, timeout=30) as response:
data = response.read(limit + 1)
if len(data) > limit:
raise ValueError(f"Release response exceeds {limit} bytes")
return data
except urllib.error.HTTPError as exc:
if exc.code not in (502, 503, 504) or attempt == 2:
raise
except (urllib.error.URLError, TimeoutError, ConnectionError) as exc:
if attempt == 2:
raise RuntimeError(f"Could not read release metadata from {url}") from exc
time.sleep(1 + attempt)
def version(tag):
if not isinstance(tag, str) or not re.fullmatch(
r"v(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)", tag
):
raise ValueError(f"Expected a stable version tag, got {tag!r}")
return tuple(int(part) for part in tag[1:].split("."))
def tag_commit(tag):
version(tag)
commit = json.loads(read_url(f"{API}/tags/{tag}"))["commit"]["sha"]
if not re.fullmatch("[0-9a-f]{40,64}", commit):
raise ValueError("Invalid Gitea commit ID")
return commit
def release_bundle(release, tag):
"""Read the published hotfix and check it against the release checksum file."""
version(tag)
if release.get("tag_name") != tag or release.get("draft") or release.get("prerelease"):
raise ValueError("Expected the selected stable, published release")
assets = release.get("assets") or []
sizes = {entry["name"]: entry["size"] for entry in assets}
if len(assets) != len(sizes):
raise ValueError("Duplicate release attachment names")
name = f"planet-earth-bundle-{tag[1:]}.tar.gz"
base = f"{SERVER}/{REPO}/releases/download/{tag}"
if not 0 < sizes.get(name, 0) <= 32 * 1024 * 1024 or "SHA256SUMS.txt" not in sizes:
raise ValueError("Release has no complete Earth bundle and checksum list")
sums = read_url(f"{base}/SHA256SUMS.txt", limit=128 * 1024).decode().splitlines()
hashes = [line.split(" ", 1)[0] for line in sums if line.endswith(" " + name)]
data = read_url(f"{base}/{name}", limit=sizes[name])
sha = hashlib.sha256(data).hexdigest()
if hashes != [sha] or len(data) != sizes[name]:
raise ValueError("Earth bundle failed release SHA-256 or size verification")
return name, data, sha
def image_name(service):
if service not in SERVICES:
raise ValueError(f"Unexpected production service: {service}")
return f"{REGISTRY}/{REPO}/{service}"
def digest(data):
return "sha256:" + hashlib.sha256(data).hexdigest()
def descriptor_digest(desc):
value = desc["digest"]
if not re.fullmatch(r"sha256:[a-f0-9]{64}", value):
raise ValueError("Registry returned an invalid digest")
return value
def resolve_image(service, tag, commit):
"""Return the immutable platform image; only an absent tag returns None."""
version(tag)
name = image_name(service)
repository = f"{REPO}/{service}"
query = urllib.parse.urlencode(
{"service": "container_registry", "scope": f"repository:{repository}:pull"}
)
token = json.loads(read_url(f"{SERVER}/v2/token?{query}"))["token"]
headers = {"Authorization": "Bearer " + token, "Accept": MANIFEST_TYPES}
base = f"{SERVER}/v2/{repository}"
try:
raw = read_url(f"{base}/manifests/{tag}", headers=headers)
except urllib.error.HTTPError as exc:
if exc.code == 404:
return None
raise
manifest = json.loads(raw)
if "manifests" in manifest:
candidates = [
entry
for entry in manifest["manifests"]
if entry.get("platform", {}).get("os") == "linux"
and entry["platform"].get("architecture") == "amd64"
]
if len(candidates) != 1:
raise ValueError(f"{name}:{tag} must contain one linux/amd64 image")
selected = descriptor_digest(candidates[0])
raw = read_url(f"{base}/manifests/{selected}", headers=headers)
if digest(raw) != selected:
raise ValueError("Registry platform manifest failed digest verification")
manifest = json.loads(raw)
config_digest = descriptor_digest(manifest["config"])
config_raw = read_url(f"{base}/blobs/{config_digest}", headers=headers)
if digest(config_raw) != config_digest:
raise ValueError("Registry image configuration failed digest verification")
config = json.loads(config_raw)
labels = config.get("config", {}).get("Labels") or {}
if (config.get("os"), config.get("architecture")) != ("linux", "amd64"):
raise ValueError(f"{name}:{tag} is not a linux/amd64 image")
if labels.get("org.opencontainers.image.revision") != commit:
raise ValueError(f"{name}:{tag} belongs to a different commit")
if service == "admin" and labels.get("planet.frontend.target") != "admin":
raise ValueError("The production Admin image must be built with the admin-only target")
return f"{name}:{tag}@{digest(raw)}"
+223
View File
@@ -0,0 +1,223 @@
"""Prepare a tagged Planet release on the publishing workstation."""
from __future__ import annotations
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
from contextlib import contextmanager
from pathlib import Path
if __package__:
from .production_registry import (
REPO,
SERVER,
SERVICES,
image_name,
resolve_image,
tag_commit,
version,
)
else:
from production_registry import (
REPO,
SERVER,
SERVICES,
image_name,
resolve_image,
tag_commit,
version,
)
def git(*args, cwd=None):
return subprocess.check_output(["git", *args], cwd=cwd, text=True).strip()
def verified_tag(tag):
commit = tag_commit(tag)
if git("rev-parse", "--verify", f"{commit}^{{commit}}") != commit:
raise RuntimeError("The remote release commit is not available locally")
if git("show", f"{commit}:VERSION") != tag[1:]:
raise ValueError("Tagged VERSION differs from the published tag")
return commit
def docker_config():
config = os.environ.get("PLANET_RELEASE_DOCKER_CONFIG")
if config:
return Path(config).expanduser()
return (
Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "planet" / "registry"
)
def ensure_images(source, tag, commit):
for service in SERVICES:
pin = resolve_image(service, tag, commit)
if not pin:
context = source / "frontend" if service == "admin" else source
dockerfile = (
context / "Dockerfile" if service == "admin" else source / service / "Dockerfile"
)
cmd = [
"docker",
"--config",
str(docker_config()),
"buildx",
"build",
"--platform",
"linux/amd64",
"--provenance=false",
"--file",
str(dockerfile),
"--label",
f"org.opencontainers.image.revision={commit}",
"--label",
f"org.opencontainers.image.version={tag[1:]}",
"--label",
f"org.opencontainers.image.source={SERVER}/{REPO}",
]
if service == "admin":
cmd += [
"--build-arg",
"PLANET_FRONTEND_TARGET=admin",
"--label",
"planet.frontend.target=admin",
]
uv_config = Path.home() / ".config/uv/uv.toml"
if service != "admin" and uv_config.is_file():
cmd += ["--secret", f"id=planet_uv_config,src={uv_config}"]
cmd += [
"--output",
f"type=image,name={image_name(service)}:{tag},push=true,compression=gzip,force-compression=true",
str(context),
]
subprocess.run(cmd, check=True)
pin = resolve_image(service, tag, commit)
if not pin:
raise RuntimeError(f"Pushed image is not visible: {service}:{tag}")
print(f"Verified {pin}", flush=True)
def select_packages(directory, tag, suffixes):
number = re.compile(rf"(?<![\d.]){re.escape(tag[1:])}(?!\d|\.\d)")
paths = (
[
p
for p in directory.iterdir()
if p.is_file() and number.search(p.name) and p.name.lower().endswith(suffixes)
]
if directory.is_dir()
else []
)
names = [p.name.lower() for p in paths]
if not (
any(n.endswith(".exe") or n.endswith("-win.zip") for n in names)
and any(n.endswith(".dmg") or "mac" in n and n.endswith(".zip") for n in names)
and any(n.endswith((".appimage", ".deb")) for n in names)
and f"planet-earth-bundle-{tag[1:]}.tar.gz" in names
):
return []
bundle = directory / f"planet-earth-bundle-{tag[1:]}.tar.gz"
with tarfile.open(bundle, "r:gz") as archive:
member = archive.getmember("bundle-meta.json")
if not member.isfile() or member.size > 8192:
raise ValueError("Invalid hotfix package metadata")
if json.load(archive.extractfile(member)).get("version") != tag[1:]:
raise ValueError("Hotfix contents do not match the release tag")
return paths
@contextmanager
def local_release_lock(path):
with path.open("a+b") as lock:
if os.name == "nt":
import msvcrt
lock.seek(0)
msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1)
else:
import fcntl
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
yield
def package_hash(path):
with path.open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def cached_packages(source, supplied, cache, tag, suffixes):
if not cache.exists():
if supplied is None:
subprocess.run(["./planet.sh", "bundle", "--all"], cwd=source, check=True)
supplied = source / "client/release"
packages = select_packages(supplied, tag, suffixes)
if not packages:
raise RuntimeError(f"Missing tagged desktop clients or Earth hotfix in {supplied}")
with tempfile.TemporaryDirectory(dir=cache.parent) as tmp:
stage = Path(tmp) / "assets"
stage.mkdir()
for package in packages:
shutil.copy2(package, stage / package.name)
sums = {p.name: package_hash(p) for p in stage.iterdir()}
(stage / "checksums.json").write_text(json.dumps(sums))
os.rename(stage, cache)
packages = select_packages(cache, tag, suffixes)
expected = json.loads((cache / "checksums.json").read_text())
if not packages or {p.name: package_hash(p) for p in packages} != expected:
raise ValueError("The saved release artifacts differ from the original build")
return packages
@contextmanager
def prepare(tag, assets_dir, suffixes, *, already_published=False):
version(tag)
commit = verified_tag(tag)
state = Path(os.environ.get("XDG_STATE_HOME") or Path.home() / ".local/state")
state = state / "planet-releases" / tag / "publisher"
state.mkdir(mode=0o700, parents=True, exist_ok=True)
cache = state / commit
with (
local_release_lock(state / "lock"),
tempfile.TemporaryDirectory(prefix="planet-publish-") as tmp,
):
worktree = Path(tmp) / "src"
subprocess.run(
["git", "worktree", "add", "--quiet", "--detach", str(worktree), commit], check=True
)
try:
ensure_images(worktree, tag, commit)
stage = Path(tmp) / "assets"
stage.mkdir()
if not already_published:
for package in cached_packages(worktree, assets_dir, cache, tag, suffixes):
try:
os.link(package, stage / package.name)
except OSError:
shutil.copy2(package, stage / package.name)
yield stage, worktree / "docs/CHANGELOG.md"
# The verified public release now holds these bytes. Keep the cache on upload failure.
if cache.exists():
shutil.rmtree(cache)
finally:
# This detached checkout and its generated build files are private to this invocation.
subprocess.run(["git", "worktree", "remove", "--force", str(worktree)], check=True)
if __name__ == "__main__":
if len(sys.argv) != 2:
sys.exit("Usage: production_release.py vX.Y.Z")
release_tag = sys.argv[1]
revision = verified_tag(release_tag)
if git("rev-parse", "HEAD") != revision or git("status", "--porcelain", "--untracked-files=no"):
sys.exit("Image-only CI jobs require a clean checkout at the tagged commit")
ensure_images(Path.cwd(), release_tag, revision)
+71 -21
View File
@@ -11,6 +11,8 @@ import os
import re
import subprocess
import sys
import tarfile
import time
import urllib.error
import urllib.parse
import urllib.request
@@ -24,6 +26,10 @@ class RejectRedirects(urllib.request.HTTPRedirectHandler):
return None
class RetryableUploadError(RuntimeError):
"""The server may already have received the attachment."""
API_OPENER = urllib.request.build_opener(RejectRedirects())
@@ -226,7 +232,8 @@ def upload_asset_with_curl(
capture_output=True,
)
if proc.returncode != 0:
raise RuntimeError(
error = RetryableUploadError if proc.returncode in (6, 7, 18, 28, 52, 55, 56, 92) else RuntimeError
raise error(
f"curl upload failed for {file_path.name} (exit={proc.returncode}): {proc.stderr.strip()}"
)
@@ -243,7 +250,8 @@ def upload_asset_with_curl(
"Check Gitea app.ini [attachment] MAX_SIZE and Nginx/Ingress client_max_body_size (>= 300M)."
)
if status_code != 201:
raise RuntimeError(f"Upload failed for {file_path.name} (HTTP {status_code})")
error = RetryableUploadError if status_code in (408, 409, 429, 502, 503, 504) else RuntimeError
raise error(f"Upload failed for {file_path.name} (HTTP {status_code})")
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
@@ -251,7 +259,7 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
parser.add_argument("--tag", required=True, help="Git release tag, e.g. v0.77.0")
parser.add_argument(
"--assets-dir",
default="client/release",
default=None,
help="Directory containing packaged client binaries (default: client/release)",
)
parser.add_argument(
@@ -387,17 +395,30 @@ def publish_release(
if path.name in existing:
verify_existing_asset(existing[path.name], path, sha, server, authorization)
print(f"verified existing {path.name}", flush=True)
for path, _sha in assets:
for path, sha in assets:
if path.name in existing:
continue
name = urllib.parse.quote(path.name, safe="")
print(f"uploading {path.name}...", flush=True)
upload_asset_with_curl(f"{release_url}/assets?name={name}", authorization, path)
for attempt in range(3):
try:
upload_asset_with_curl(f"{release_url}/assets?name={name}", authorization, path)
break
except RetryableUploadError:
received = list_assets(release_url, authorization).get(path.name)
if received:
verify_existing_asset(received, path, sha, server, authorization)
break
if attempt == 2:
raise
time.sleep(2 ** attempt)
uploaded = list_assets(release_url, authorization)
for path, _sha in assets:
for path, sha in assets:
if uploaded.get(path.name, {}).get("size") != path.stat().st_size:
raise RuntimeError(f"Missing or incomplete attachment: {path.name}")
if path.name not in existing or uploaded[path.name].get("id") != existing[path.name].get("id"):
verify_existing_asset(uploaded[path.name], path, sha, server, authorization)
status, published = api_request(
"PATCH", release_url, authorization, {"name": tag, "body": notes, "draft": False}
@@ -416,6 +437,7 @@ def publish_hotfix_bundle(
notes: str,
release_html_url: str,
assets: list[tuple[Path, str]],
min_shell_version: str | None = None,
) -> None:
hotfix_tar = next(
(
@@ -448,15 +470,15 @@ def publish_hotfix_bundle(
"@-",
"-F",
f"file=@{hotfix_tar}",
"-F",
"--form-string",
f"version={version}",
"-F",
f"min_shell_version={version}",
"-F",
"--form-string",
f"min_shell_version={min_shell_version or version}",
"--form-string",
f"shell_version={version}",
"-F",
"--form-string",
f"shell_download_url={release_html_url}",
"-F",
"--form-string",
f"release_notes={notes[:2000]}",
endpoint,
],
@@ -495,14 +517,14 @@ def main(argv: list[str] | None = None) -> int:
print("error: unable to resolve Gitea server URL or owner/repo slug", file=sys.stderr)
return 1
notes = extract_release_notes(Path(args.changelog), args.tag)
assets_dir = Path(args.assets_dir)
assets = collect_release_assets(assets_dir)
if not assets:
print(f"error: no distributable assets found in {assets_dir}", file=sys.stderr)
return 1
assets_dir = Path(args.assets_dir or "client/release")
if args.dry_run:
notes = extract_release_notes(Path(args.changelog), args.tag)
assets = collect_release_assets(assets_dir)
if not assets:
print(f"error: no distributable assets found in {assets_dir}", file=sys.stderr)
return 1
print(f"server: {server}")
print(f"repo: {repo}")
print(f"tag: {args.tag}")
@@ -514,13 +536,41 @@ def main(argv: list[str] | None = None) -> int:
return 0
try:
if args.use_git_credential:
if __package__:
from .production_registry import API, REPO, SERVER, release_bundle
from .production_release import prepare
else:
from production_registry import API, REPO, SERVER, release_bundle
from production_release import prepare
production = (server, repo) == (SERVER, REPO) and re.fullmatch(r"v\d+\.\d+\.\d+", args.tag)
token = os.environ.get("GITEA_TOKEN")
if not token and (not production or os.environ.get("GITHUB_SERVER_URL", "").rstrip("/") == server):
token = os.environ.get("GITHUB_TOKEN")
if args.use_git_credential or (production and not token):
authorization = git_credential_authorization(origin, server, repo)
else:
token = os.environ.get("GITEA_TOKEN") or os.environ.get("GITHUB_TOKEN")
if not token:
raise RuntimeError("Set GITEA_TOKEN or use the saved HTTPS Git credential")
authorization = f"token {token}"
if production:
status, public = api_request("GET", f"{API}/releases/tags/{args.tag}", authorization)
if status not in (200, 404):
raise RuntimeError(f"Cannot inspect the release (HTTP {status})")
published = status == 200 and isinstance(public, dict) and public.get("draft") is False
supplied = assets_dir if args.assets_dir else None
with prepare(args.tag, supplied, ASSET_SUFFIXES, already_published=published) as (stage, changelog):
if published:
release_bundle(public, args.tag)
print(f"Verified published release {args.tag}; production follows stable releases")
else:
notes = extract_release_notes(changelog, args.tag)
publish_release(server, repo, args.tag, notes, collect_release_assets(stage), authorization)
return 0
notes = extract_release_notes(Path(args.changelog), args.tag)
assets = collect_release_assets(assets_dir)
if not assets:
raise RuntimeError(f"No distributable assets found in {assets_dir}")
release_html_url = publish_release(server, repo, args.tag, notes, assets, authorization)
hotfix_url = str(args.hotfix_publish_url or "").strip()
hotfix_token = str(args.hotfix_publish_token or "").strip()
@@ -533,7 +583,7 @@ def main(argv: list[str] | None = None) -> int:
release_html_url=release_html_url,
assets=assets,
)
except (RuntimeError, urllib.error.URLError, TimeoutError) as exc:
except (RuntimeError, ValueError, KeyError, OSError, subprocess.SubprocessError, tarfile.TarError) as exc:
print(f"error: {exc}", file=sys.stderr)
return 1
return 0
Generated
+1 -1
View File
@@ -757,7 +757,7 @@ wheels = [
[[package]]
name = "planet"
version = "0.79.0"
version = "0.79.1"
source = { virtual = "." }
dependencies = [
{ name = "aiofiles" },