release: bump version to 0.84.0
This commit is contained in:
1 parent
3b1b9ef68c
commit
e1cc27f13d
241 files changed
+42779
-6027
No files matched your search
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "planet-client",
|
||||
"version": "0.83.0",
|
||||
"version": "0.84.0",
|
||||
"description": "Intelligent Planet Program - Native Electron Earth Viewer",
|
||||
"private": true,
|
||||
"packageManager": "bun@1",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { dirname, join, sep } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
import { compileEarthRuntime } from '../../frontend/scripts/compile-earth-runtime.mjs'
|
||||
@@ -60,6 +60,7 @@ for (const [name, asset] of assets) {
|
||||
const workerEntrypoints = [
|
||||
join(earthSourceDir, 'js/satellite-position-worker.js'),
|
||||
join(earthSourceDir, 'js/surface-line-lod-worker.js'),
|
||||
join(earthSourceDir, 'js/boundary-tile-worker.js'),
|
||||
]
|
||||
const workerBuild = await Bun.build({
|
||||
entrypoints: workerEntrypoints,
|
||||
@@ -73,10 +74,17 @@ if (!workerBuild.success) {
|
||||
throw new AggregateError(workerBuild.logs, 'Failed to bundle Earth Web Workers')
|
||||
}
|
||||
|
||||
// Earth boundary PMTiles artifacts are served by the backend API
|
||||
// (/api/v1/earth/boundaries/...); legacy local builds must never ship in the
|
||||
// desktop installer.
|
||||
const legacyBoundaryArtifacts = join(earthSourceDir, 'data', 'boundaries')
|
||||
for (const folder of ['css', 'assets', 'data']) {
|
||||
const srcFolder = join(earthSourceDir, folder)
|
||||
if (existsSync(srcFolder)) {
|
||||
cpSync(srcFolder, join(bundleEarthDir, folder), { recursive: true })
|
||||
cpSync(srcFolder, join(bundleEarthDir, folder), {
|
||||
recursive: true,
|
||||
filter: (src) => src !== legacyBoundaryArtifacts && !src.startsWith(`${legacyBoundaryArtifacts}${sep}`),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -315,6 +315,7 @@ if (!singleInstanceLock) {
|
||||
installEarthSessionHandlers(session.defaultSession, {
|
||||
earthBundleRoot,
|
||||
getEarthOverlayRoot: () => hotUpdater.getOverlayRoot(),
|
||||
boundaryCacheDir: path.join(app.getPath('userData'), 'earth-cache', 'boundaries'),
|
||||
getBackendUrl: () => configStore.get().backendUrl,
|
||||
getEarthAuthToken: (opts) => earthAuth.getToken(opts),
|
||||
})
|
||||
@@ -494,12 +495,12 @@ if (!singleInstanceLock) {
|
||||
if (isHeadlessSmoke) {
|
||||
const smokeTimeout = setTimeout(() => {
|
||||
app.exit(1)
|
||||
}, 22000)
|
||||
}, 25000)
|
||||
|
||||
mainWindow.webContents.once('did-finish-load', async () => {
|
||||
try {
|
||||
const earthStartup = await mainWindow!.webContents.executeJavaScript(`new Promise((resolve) => {
|
||||
const deadline = performance.now() + 8000;
|
||||
const deadline = performance.now() + 14000;
|
||||
const poll = () => {
|
||||
const ready = document.documentElement.dataset.earthStartupReady === '1';
|
||||
const progress = document.documentElement.dataset.earthStartupProgress || '';
|
||||
@@ -561,7 +562,7 @@ if (!singleInstanceLock) {
|
||||
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
|
||||
resolve({
|
||||
mounted: Boolean(host && sr),
|
||||
hasPresentedBy: copy.includes('PRESENTED BY'),
|
||||
hasPresentedBy: copy.includes('PRESENTED BY') || copy.includes('联合研制'),
|
||||
hasPresenterZh: copy.includes('临空智能媒体研究院'),
|
||||
hasPresenterEn: copy.includes('Intelligent Media Institute'),
|
||||
emblemLoaded: Boolean(img && img.complete && img.naturalWidth > 0),
|
||||
|
||||
@@ -101,7 +101,11 @@ export function parseByteRange(rangeHeader: string | null, totalSize: number): B
|
||||
return { kind: 'range', start, end }
|
||||
}
|
||||
|
||||
export function createStaticFileResponse(filePath: string, requestHeaders: Headers): Response {
|
||||
export function createStaticFileResponse(
|
||||
filePath: string,
|
||||
requestHeaders: Headers,
|
||||
options?: { method?: string; cacheControl?: string },
|
||||
): Response {
|
||||
let stat: fs.Stats
|
||||
try {
|
||||
stat = fs.statSync(filePath)
|
||||
@@ -112,6 +116,9 @@ export function createStaticFileResponse(filePath: string, requestHeaders: Heade
|
||||
return new Response('Not Found', { status: 404 })
|
||||
}
|
||||
|
||||
const method = (options?.method || 'GET').toUpperCase()
|
||||
const isHead = method === 'HEAD'
|
||||
const cacheControl = options?.cacheControl || 'no-cache'
|
||||
const totalSize = stat.size
|
||||
const contentType = getMimeType(filePath)
|
||||
const rangeResult = parseByteRange(requestHeaders.get('range'), totalSize)
|
||||
@@ -129,39 +136,192 @@ export function createStaticFileResponse(filePath: string, requestHeaders: Heade
|
||||
if (rangeResult.kind === 'range') {
|
||||
const { start, end } = rangeResult
|
||||
const chunkSize = end - start + 1
|
||||
const stream = Readable.toWeb(fs.createReadStream(filePath, { start, end })) as ReadableStream
|
||||
return new Response(stream, {
|
||||
const body = isHead
|
||||
? null
|
||||
: (Readable.toWeb(fs.createReadStream(filePath, { start, end })) as ReadableStream)
|
||||
return new Response(body, {
|
||||
status: 206,
|
||||
headers: {
|
||||
'Content-Type': contentType,
|
||||
'Content-Length': String(chunkSize),
|
||||
'Content-Range': `bytes ${start}-${end}/${totalSize}`,
|
||||
'Accept-Ranges': 'bytes',
|
||||
'Cache-Control': 'no-cache',
|
||||
'Cache-Control': cacheControl,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const stream = Readable.toWeb(fs.createReadStream(filePath)) as ReadableStream
|
||||
return new Response(stream, {
|
||||
const body = isHead ? null : (Readable.toWeb(fs.createReadStream(filePath)) as ReadableStream)
|
||||
return new Response(body, {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': contentType,
|
||||
'Content-Length': String(totalSize),
|
||||
'Accept-Ranges': 'bytes',
|
||||
'Cache-Control': 'no-cache',
|
||||
'Cache-Control': cacheControl,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const BOUNDARY_FILES_PREFIX = '/api/v1/earth/boundaries/files/'
|
||||
const BOUNDARY_ARTIFACT_NAME_RE = /^[A-Za-z0-9._-]+\.(pmtiles|json)$/
|
||||
const BOUNDARY_PREFIX_GROUPS = ['earth-boundaries.', 'hover-index.', 'hover-borders.', 'geo-labels.']
|
||||
|
||||
function resolveBoundaryCacheName(pathname: string): string | null {
|
||||
if (!pathname.startsWith(BOUNDARY_FILES_PREFIX)) return null
|
||||
const rawName = pathname.slice(BOUNDARY_FILES_PREFIX.length)
|
||||
if (!rawName || rawName.includes('/')) return null
|
||||
let decoded: string
|
||||
try {
|
||||
decoded = decodeURIComponent(rawName)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
if (!BOUNDARY_ARTIFACT_NAME_RE.test(decoded) || decoded.includes('..')) {
|
||||
return null
|
||||
}
|
||||
return decoded
|
||||
}
|
||||
|
||||
function cleanupOldBoundaryArtifacts(cacheDir: string, keepFileName: string): void {
|
||||
const prefix = BOUNDARY_PREFIX_GROUPS.find((item) => keepFileName.startsWith(item))
|
||||
if (!prefix) return
|
||||
try {
|
||||
for (const entry of fs.readdirSync(cacheDir)) {
|
||||
if (entry === keepFileName || entry === `${keepFileName}.tmp`) continue
|
||||
if (entry.startsWith(prefix)) {
|
||||
fs.rmSync(path.join(cacheDir, entry), { force: true })
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Cleanup failures never break serving the cached artifact.
|
||||
}
|
||||
}
|
||||
|
||||
export function createEarthProtocolHandler(options: {
|
||||
earthBundleRoot: string
|
||||
getEarthOverlayRoot?: () => string | null
|
||||
boundaryCacheDir?: string
|
||||
getBackendUrl: () => string
|
||||
getEarthAuthToken?: (opts?: { forceRefresh?: boolean }) => Promise<string | null>
|
||||
fetchImpl?: typeof fetch
|
||||
}): (request: Request) => Promise<Response> {
|
||||
const fetchImpl = options.fetchImpl ?? fetch
|
||||
const boundaryCacheDir = options.boundaryCacheDir
|
||||
const inFlightBoundaryDownloads = new Map<string, Promise<void>>()
|
||||
|
||||
const scheduleBoundaryDownload = (
|
||||
fileName: string,
|
||||
targetUrl: URL,
|
||||
buildAuthHeaders: (forceRefresh?: boolean) => Promise<Headers>,
|
||||
): void => {
|
||||
if (!boundaryCacheDir || inFlightBoundaryDownloads.has(fileName)) return
|
||||
|
||||
const job = (async () => {
|
||||
try {
|
||||
fs.mkdirSync(boundaryCacheDir, { recursive: true })
|
||||
const finalPath = path.join(boundaryCacheDir, fileName)
|
||||
if (fs.existsSync(finalPath)) return
|
||||
const tmpPath = `${finalPath}.tmp`
|
||||
|
||||
let existingBytes = 0
|
||||
try {
|
||||
const tmpStat = fs.statSync(tmpPath)
|
||||
if (tmpStat.isFile() && tmpStat.size > 0) existingBytes = tmpStat.size
|
||||
} catch {
|
||||
existingBytes = 0
|
||||
}
|
||||
|
||||
const makeReqHeaders = async (forceRefresh = false): Promise<Headers> => {
|
||||
const headers = await buildAuthHeaders(forceRefresh)
|
||||
headers.delete('range')
|
||||
headers.delete('accept-encoding')
|
||||
if (existingBytes > 0) {
|
||||
headers.set('range', `bytes=${existingBytes}-`)
|
||||
}
|
||||
return headers
|
||||
}
|
||||
|
||||
let resp = await fetchImpl(targetUrl.toString(), { method: 'GET', headers: await makeReqHeaders(false) })
|
||||
if (resp.status === 401 && options.getEarthAuthToken) {
|
||||
try {
|
||||
await resp.body?.cancel()
|
||||
} catch {
|
||||
// Ignore cancel error before retry.
|
||||
}
|
||||
resp = await fetchImpl(targetUrl.toString(), { method: 'GET', headers: await makeReqHeaders(true) })
|
||||
}
|
||||
|
||||
if (resp.status === 416 && existingBytes > 0) {
|
||||
try {
|
||||
await resp.body?.cancel()
|
||||
} catch {
|
||||
// Ignore cancel error before restart.
|
||||
}
|
||||
fs.rmSync(tmpPath, { force: true })
|
||||
existingBytes = 0
|
||||
resp = await fetchImpl(targetUrl.toString(), { method: 'GET', headers: await makeReqHeaders(false) })
|
||||
}
|
||||
|
||||
if ((resp.status !== 200 && resp.status !== 206) || !resp.body) {
|
||||
try {
|
||||
await resp.body?.cancel()
|
||||
} catch {
|
||||
// Ignore stream cleanup failure.
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const append = resp.status === 206 && existingBytes > 0
|
||||
let expectedTotalBytes: number | null = null
|
||||
if (resp.status === 206) {
|
||||
const contentRange = resp.headers.get('content-range') || ''
|
||||
const match = /^bytes\s+\d+-\d+\/(\d+)$/i.exec(contentRange.trim())
|
||||
if (match) expectedTotalBytes = Number(match[1])
|
||||
} else {
|
||||
const lenHeader = Number(resp.headers.get('content-length') || 0)
|
||||
if (Number.isFinite(lenHeader) && lenHeader > 0) expectedTotalBytes = lenHeader
|
||||
}
|
||||
|
||||
const writer = fs.createWriteStream(tmpPath, { flags: append ? 'a' : 'w' })
|
||||
let writtenBytes = append ? existingBytes : 0
|
||||
const reader = resp.body.getReader()
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
if (!value || value.byteLength === 0) continue
|
||||
writtenBytes += value.byteLength
|
||||
if (!writer.write(value)) {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
writer.once('drain', resolve)
|
||||
writer.once('error', reject)
|
||||
})
|
||||
}
|
||||
}
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
writer.end(() => resolve())
|
||||
writer.once('error', reject)
|
||||
})
|
||||
} catch (err) {
|
||||
writer.destroy()
|
||||
throw err
|
||||
}
|
||||
|
||||
if (expectedTotalBytes !== null && writtenBytes !== expectedTotalBytes) {
|
||||
return
|
||||
}
|
||||
fs.renameSync(tmpPath, finalPath)
|
||||
cleanupOldBoundaryArtifacts(boundaryCacheDir, fileName)
|
||||
} catch {
|
||||
// Background cache write errors are non-fatal; next attempt resumes or refetches.
|
||||
}
|
||||
})().finally(() => {
|
||||
inFlightBoundaryDownloads.delete(fileName)
|
||||
})
|
||||
|
||||
inFlightBoundaryDownloads.set(fileName, job)
|
||||
}
|
||||
|
||||
return async (request: Request): Promise<Response> => {
|
||||
const parsedUrl = new URL(request.url)
|
||||
@@ -192,6 +352,26 @@ export function createEarthProtocolHandler(options: {
|
||||
}
|
||||
|
||||
const method = request.method.toUpperCase()
|
||||
const boundaryFileName =
|
||||
boundaryCacheDir && (method === 'GET' || method === 'HEAD')
|
||||
? resolveBoundaryCacheName(parsedUrl.pathname)
|
||||
: null
|
||||
if (boundaryFileName && boundaryCacheDir) {
|
||||
const cachedFilePath = path.join(boundaryCacheDir, boundaryFileName)
|
||||
try {
|
||||
if (fs.statSync(cachedFilePath).isFile()) {
|
||||
return createStaticFileResponse(cachedFilePath, request.headers, {
|
||||
method,
|
||||
cacheControl: 'public, max-age=31536000, immutable',
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
// Cache miss: proxy upstream immediately while populating disk cache in background.
|
||||
}
|
||||
if (method === 'GET') {
|
||||
scheduleBoundaryDownload(boundaryFileName, targetUrl, buildForwardHeaders)
|
||||
}
|
||||
}
|
||||
const hasBody = method !== 'GET' && method !== 'HEAD'
|
||||
try {
|
||||
const makeInit = (headers: Headers): RequestInit & { duplex?: 'half' } => {
|
||||
|
||||
@@ -30,6 +30,7 @@ export function installEarthSessionHandlers(
|
||||
options: {
|
||||
earthBundleRoot: string
|
||||
getEarthOverlayRoot?: () => string | null
|
||||
boundaryCacheDir?: string
|
||||
getBackendUrl: () => string
|
||||
getEarthAuthToken?: (opts?: { forceRefresh?: boolean }) => Promise<string | null>
|
||||
},
|
||||
@@ -37,6 +38,7 @@ export function installEarthSessionHandlers(
|
||||
const handler = createEarthProtocolHandler({
|
||||
earthBundleRoot: options.earthBundleRoot,
|
||||
getEarthOverlayRoot: options.getEarthOverlayRoot,
|
||||
boundaryCacheDir: options.boundaryCacheDir,
|
||||
getBackendUrl: options.getBackendUrl,
|
||||
getEarthAuthToken: options.getEarthAuthToken,
|
||||
fetchImpl: (input, init) => net.fetch(input as string, init),
|
||||
|
||||
@@ -146,6 +146,79 @@ describe('protocol-core static and range handling', () => {
|
||||
),
|
||||
).rejects.toThrow()
|
||||
})
|
||||
|
||||
test('caches boundary artifacts to disk, cleans stale versions, and serves local 206/HEAD', async () => {
|
||||
const fs = require('node:fs')
|
||||
const boundaryCacheDir = path.join(tempRoot, 'boundary-cache')
|
||||
fs.mkdirSync(boundaryCacheDir, { recursive: true })
|
||||
const staleFile = path.join(boundaryCacheDir, 'earth-boundaries.oldver.pmtiles')
|
||||
writeFileSync(staleFile, 'stale-data', 'utf8')
|
||||
|
||||
const payload = 'PMTiles-Mock-Archive-Payload-0123456789'
|
||||
const upstreamCalls: Array<{ url: string; range: string | null }> = []
|
||||
const handler = createEarthProtocolHandler({
|
||||
earthBundleRoot: bundleRoot,
|
||||
boundaryCacheDir,
|
||||
getBackendUrl: () => 'http://127.0.0.1:8000',
|
||||
fetchImpl: (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const headers = new Headers(init?.headers)
|
||||
const range = headers.get('range')
|
||||
upstreamCalls.push({ url: String(input), range })
|
||||
if (range && /^bytes=(\d+)-(\d*)$/.test(range)) {
|
||||
const match = /^bytes=(\d+)-(\d*)$/.exec(range)!
|
||||
const start = Number(match[1])
|
||||
const end = match[2] ? Math.min(Number(match[2]), payload.length - 1) : payload.length - 1
|
||||
const slice = payload.slice(start, end + 1)
|
||||
return new Response(slice, {
|
||||
status: 206,
|
||||
headers: {
|
||||
'Content-Range': `bytes ${start}-${end}/${payload.length}`,
|
||||
'Content-Length': String(slice.length),
|
||||
Accept: 'bytes',
|
||||
},
|
||||
})
|
||||
}
|
||||
return new Response(payload, {
|
||||
status: 200,
|
||||
headers: { 'Content-Length': String(payload.length) },
|
||||
})
|
||||
}) as typeof fetch,
|
||||
})
|
||||
|
||||
// First Range request misses local disk cache -> proxies upstream AND caches full file in background.
|
||||
const url = 'planet://earth/api/v1/earth/boundaries/files/earth-boundaries.newver.pmtiles'
|
||||
const first = await handler(new Request(url, { headers: { Range: 'bytes=0-6' } }))
|
||||
expect(first.status).toBe(206)
|
||||
expect(await first.text()).toBe('PMTiles')
|
||||
|
||||
const targetPath = path.join(boundaryCacheDir, 'earth-boundaries.newver.pmtiles')
|
||||
for (let i = 0; i < 40 && !fs.existsSync(targetPath); i += 1) {
|
||||
await new Promise((r) => setTimeout(r, 15))
|
||||
}
|
||||
expect(fs.existsSync(targetPath)).toBe(true)
|
||||
expect(fs.existsSync(staleFile)).toBe(false)
|
||||
|
||||
// Subsequent Range and HEAD requests hit local disk cache with zero upstream calls.
|
||||
const callsBeforeHit = upstreamCalls.length
|
||||
const hitRange = await handler(new Request(url, { headers: { Range: 'bytes=8-11' } }))
|
||||
expect(hitRange.status).toBe(206)
|
||||
expect(hitRange.headers.get('Content-Range')).toBe(`bytes 8-11/${payload.length}`)
|
||||
expect(hitRange.headers.get('Cache-Control')).toContain('immutable')
|
||||
expect(await hitRange.text()).toBe('Mock')
|
||||
|
||||
const hitHead = await handler(new Request(url, { method: 'HEAD' }))
|
||||
expect(hitHead.status).toBe(200)
|
||||
expect(hitHead.headers.get('Content-Length')).toBe(String(payload.length))
|
||||
expect(await hitHead.text()).toBe('')
|
||||
expect(upstreamCalls.length).toBe(callsBeforeHit)
|
||||
|
||||
// Path traversal or unexpected extensions are never read/written from local boundary cache.
|
||||
const traversal = await handler(
|
||||
new Request('planet://earth/api/v1/earth/boundaries/files/..%2Fsecret.pmtiles'),
|
||||
)
|
||||
expect(traversal.status).toBe(200)
|
||||
expect(upstreamCalls.length).toBe(callsBeforeHit + 1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('external links and runtime config', () => {
|
||||
|
||||
Reference in new issue
Block a user