|
1 | 1 | import { Worker } from 'node:worker_threads'; |
2 | | -import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; |
| 2 | +import { emitDiagnostic, getDiagnosticsMeta } from '@agent-device/host-kit/diagnostics'; |
3 | 3 | import { AppError, toAppErrorCode } from '@agent-device/kernel/errors'; |
4 | 4 | import type { Rect } from '@agent-device/kernel/snapshot'; |
5 | 5 | import { resolveInternalEntryModulePath } from './internal-entry.ts'; |
@@ -39,16 +39,31 @@ type PendingJob = { |
39 | 39 |
|
40 | 40 | let worker: Worker | null = null; |
41 | 41 | let workerUnavailable = false; |
42 | | -let warnedWorkerUnavailable = false; |
| 42 | +let workerUnavailableReason: string | undefined; |
| 43 | +let reportedWorkerUnavailable = false; |
43 | 44 | let nextJobId = 0; |
44 | 45 | const pendingJobs = new Map<number, PendingJob>(); |
45 | 46 |
|
46 | | -/** Permanently degrades to the sync path and reports the reason once. */ |
| 47 | +/** Permanently degrades to the sync path; the reason is reported by the first scope that sees it. */ |
47 | 48 | function markWorkerUnavailable(reason: string): void { |
48 | 49 | workerUnavailable = true; |
49 | | - if (warnedWorkerUnavailable) return; |
50 | | - warnedWorkerUnavailable = true; |
51 | | - emitDiagnostic({ level: 'warn', phase: 'png_worker_unavailable', data: { reason } }); |
| 50 | + workerUnavailableReason ??= reason; |
| 51 | + reportWorkerUnavailable(); |
| 52 | +} |
| 53 | + |
| 54 | +/** |
| 55 | + * A pre-warm at daemon startup runs outside any diagnostics scope, where the event would be |
| 56 | + * dropped, so the report waits for the first request scope that reaches the degraded path. |
| 57 | + */ |
| 58 | +function reportWorkerUnavailable(): void { |
| 59 | + if (reportedWorkerUnavailable || workerUnavailableReason === undefined) return; |
| 60 | + if (Object.keys(getDiagnosticsMeta()).length === 0) return; |
| 61 | + reportedWorkerUnavailable = true; |
| 62 | + emitDiagnostic({ |
| 63 | + level: 'warn', |
| 64 | + phase: 'png_worker_unavailable', |
| 65 | + data: { reason: workerUnavailableReason }, |
| 66 | + }); |
52 | 67 | } |
53 | 68 |
|
54 | 69 | function handleWorkerMessage(message: PngWorkerResponse): void { |
@@ -97,7 +112,10 @@ function updateWorkerRef(): void { |
97 | 112 | } |
98 | 113 |
|
99 | 114 | function obtainWorker(): Worker | null { |
100 | | - if (workerUnavailable) return null; |
| 115 | + if (workerUnavailable) { |
| 116 | + reportWorkerUnavailable(); |
| 117 | + return null; |
| 118 | + } |
101 | 119 | if (worker) return worker; |
102 | 120 | const modulePath = resolveInternalEntryModulePath(import.meta.url, PNG_WORKER_ENTRYPOINT); |
103 | 121 | if (!modulePath) { |
|
0 commit comments