test(fleet): handle PDFs from direct print requests

This commit is contained in:
2026-10-03 19:27:03 +08:00
parent dbc7688516
commit e5af1ba758
2 changed files with 36 additions and 5 deletions
+7 -5
View File
@@ -30,10 +30,11 @@ export function guardFleetWrites(context, checkpoint, { guardFetch = false } = {
const scope = new AsyncLocalStorage(), originalFetch = globalThis.fetch
const direct = { async requestWithBody(method, path, body, token, headers, request) {
const nativeResponse = await originalFetch(request), copy = nativeResponse.clone()
const content = await copy.text()
const bytes = new Uint8Array(await copy.arrayBuffer()), contentType = nativeResponse.headers.get('content-type') || ''
const content = /json|text|xml|html/i.test(contentType) ? new TextDecoder().decode(bytes) : ''
let payload = null
try { payload = content ? JSON.parse(content) : null } catch { /* Keep bounded diagnostic only. */ }
return { nativeResponse, http: nativeResponse.status, body: payload, raw: payload ? null : content.slice(0, 500),
return { nativeResponse, http: nativeResponse.status, body: payload, bytes, contentType, raw: payload || !content ? null : content.slice(0, 500),
requestId: payload?.requestId || nativeResponse.headers.get('x-request-id'),
traceId: payload?.traceId || nativeResponse.headers.get('x-trace-id') }
} }
@@ -65,13 +66,14 @@ export function guardFleetWrites(context, checkpoint, { guardFetch = false } = {
try {
const response = await scope.run(true, () => original.apply(this, arguments))
const http = response?.http, payload = response?.body, code = id(payload?.code)
const binary = name === 'requestBinary' && response?.bytes instanceof Uint8Array
const pdf = binary && http === 200 && /^application\/pdf(?:\s*;|$)/i.test(response.contentType || '')
const expectsPdf = name === 'requestBinary' || owner === direct && /(?:^|,)\s*application\/pdf(?:\s*[;,]|$)/i.test(headers?.accept || '')
const binary = (name === 'requestBinary' || owner === direct) && response?.bytes instanceof Uint8Array
const pdf = expectsPdf && binary && http === 200 && /^application\/pdf(?:\s*;|$)/i.test(response.contentType || '')
&& response.bytes.length > 4 && Buffer.from(response.bytes.subarray(0, 5)).toString('ascii') === '%PDF-'
const definite = Number.isInteger(http) && http >= 200 && http < 500
&& response.requestId && response.traceId
&& (pdf || payload && typeof payload === 'object' && !Array.isArray(payload)
&& (name !== 'requestBinary' && http === 200 && code === '200' || /^[A-Z]\d{4}$/.test(code) && (http === 200 || http >= 400)))
&& (!expectsPdf && http === 200 && code === '200' || /^[A-Z]\d{4}$/.test(code) && (http === 200 || http >= 400)))
Object.assign(entry, { status: definite ? 'RESPONDED' : 'UNKNOWN_RESULT', http, code,
requestId: response?.requestId, traceId: response?.traceId, raw: boundedFleetDiagnostic(response?.raw),
responseBody: redactFleetWrite(response?.body), finishedAt: new Date().toISOString() })