forked from linkong/planet
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
@@ -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),
|
||||
|
||||
Reference in new issue
Block a user