Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions docs/edge-runtime-process-once.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Fix: Edge Runtime `process.once` build warning

## 背景

`next build` 过程中出现 Edge Runtime 不支持 Node API 的告警:`process.once`。

### 复现基线(修复前)

在修复前的版本(例如 tag `v0.4.1`)上运行 `bun run build` 可看到 Edge Runtime 不支持 Node API 的告警,其 import trace 包含:

```text
A Node.js API is used (process.once) which is not supported in the Edge Runtime.
Import traces:
./src/lib/async-task-manager.ts
./src/lib/price-sync/cloud-price-updater.ts
./src/instrumentation.ts
```

相关导入链路(import trace)包含:

- `src/lib/async-task-manager.ts`
- `src/lib/price-sync/cloud-price-updater.ts`
- `src/instrumentation.ts`

## 变更

- `AsyncTaskManager`:
- 在 `process.env.NEXT_RUNTIME === "edge"` 时跳过初始化,避免触发 `process.once` 等 Node-only API。
- `cloud-price-updater`:
- 移除对 `AsyncTaskManager` 的顶层静态 import。
- 在 `requestCloudPriceTableSync()` 内部按需动态 import `AsyncTaskManager`,并在 Edge runtime 下直接 no-op。

## 验证

- `bun run lint`
- `bun run typecheck`
- Targeted coverage(仅统计本次相关文件):
- `bunx vitest run tests/unit/lib/async-task-manager-edge-runtime.test.ts tests/unit/price-sync/cloud-price-updater.test.ts --coverage --coverage.provider v8 --coverage.reporter text --coverage.include src/lib/async-task-manager.ts --coverage.include src/lib/price-sync/cloud-price-updater.ts`
- 结果:All files >= 90%(Statements / Branches / Functions / Lines)
- `bun run build`
- 结果:不再出现 Edge Runtime `process.once` 相关告警

## 回滚

如需回滚,优先按提交粒度回退(以 commit message 为准):

- `fix: skip async task manager init on edge`
- `fix: avoid static async task manager import`
- `test: cover edge runtime task scheduling`

定位对应提交(示例):

```bash
git log --oneline --grep "fix: skip async task manager init on edge"
git log --oneline --grep "fix: avoid static async task manager import"
git log --oneline --grep "test: cover edge runtime task scheduling"
```

## 备选方案(若回归)

如果未来 Next/Turbopack 的静态分析行为变化导致告警回归,可将 Node-only 的 signal hooks 拆分到 `*.node.ts`(例如 `async-task-manager.node.ts`),并仅在 `NEXT_RUNTIME !== "edge"` 的分支里动态引入。

## 快速定位(避免文档漂移)

```bash
rg -n "process\\.once" src/lib/async-task-manager.ts
rg -n "NEXT_RUNTIME|NEXT_PHASE" src/lib tests
rg -n "requestCloudPriceTableSync" src/lib/price-sync/cloud-price-updater.ts tests/unit/price-sync/cloud-price-updater.test.ts
```

## 备注

`.codex/plan/` 与 `.codex/issues/` 属于本地任务落盘目录,不应提交到 Git。
24 changes: 20 additions & 4 deletions src/lib/async-task-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,25 @@ interface TaskInfo {
class AsyncTaskManagerClass {
private tasks: Map<string, TaskInfo> = new Map();
private cleanupInterval: NodeJS.Timeout | null = null;
// Lazily initialize Node-only hooks on first use to avoid side effects at import time.
private initialized = false;

constructor() {
// Skip initialization during CI/build phase to avoid unnecessary logs and side effects
if (process.env.CI === "true" || process.env.NEXT_PHASE === "phase-production-build") {
logger.debug("[AsyncTaskManager] Skipping initialization in CI/build environment");
private initializeIfNeeded(): void {
if (this.initialized) {
return;
}
this.initialized = true;

// Skip initialization in Edge/CI environments to avoid Node-only APIs and side effects.
if (
process.env.NEXT_RUNTIME === "edge" ||
process.env.CI === "true" ||
process.env.NEXT_PHASE === "phase-production-build"
) {
logger.debug("[AsyncTaskManager] Skipping initialization in edge/CI environment", {
nextRuntime: process.env.NEXT_RUNTIME,
ci: process.env.CI,
});
return;
}

Expand Down Expand Up @@ -63,6 +77,8 @@ class AsyncTaskManagerClass {
* @returns AbortController(可用于取消任务)
*/
register(taskId: string, promise: Promise<void>, taskType = "unknown"): AbortController {
this.initializeIfNeeded();

// 如果任务已存在,先取消旧任务
if (this.tasks.has(taskId)) {
logger.warn("[AsyncTaskManager] Task already exists, cancelling old task", {
Expand Down
89 changes: 57 additions & 32 deletions src/lib/price-sync/cloud-price-updater.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { AsyncTaskManager } from "@/lib/async-task-manager";
import { logger } from "@/lib/logger";
import type { PriceUpdateResult } from "@/types/model-price";
import {
Expand Down Expand Up @@ -58,47 +57,73 @@ export function requestCloudPriceTableSync(options: {
reason: "missing-model" | "scheduled" | "manual";
throttleMs?: number;
}): void {
const throttleMs = options.throttleMs ?? DEFAULT_THROTTLE_MS;
const taskId = "cloud-price-table-sync";

// 去重:已有任务在跑则不重复触发
const active = AsyncTaskManager.getActiveTasks();
if (active.some((t) => t.taskId === taskId)) {
if (process.env.NEXT_RUNTIME === "edge") {
return;
}

const throttleMs = options.throttleMs ?? DEFAULT_THROTTLE_MS;
const taskId = "cloud-price-table-sync";

// 节流:避免短时间内频繁拉取云端价格表
const g = globalThis as unknown as { __CCH_CLOUD_PRICE_SYNC_LAST_AT__?: number };
const g = globalThis as unknown as {
__CCH_CLOUD_PRICE_SYNC_LAST_AT__?: number;
__CCH_CLOUD_PRICE_SYNC_SCHEDULING__?: boolean;
};
const lastAt = g.__CCH_CLOUD_PRICE_SYNC_LAST_AT__ ?? 0;
const now = Date.now();
if (now - lastAt < throttleMs) {
return;
}

AsyncTaskManager.register(
taskId,
(async () => {
try {
const result = await syncCloudPriceTableToDatabase();
if (!result.ok) {
logger.warn("[PriceSync] Cloud price sync task failed", {
reason: options.reason,
error: result.error,
});
return;
}
// 避免并发请求在 AsyncTaskManager 加载前重复触发(例如多请求同时命中 missing-model)
if (g.__CCH_CLOUD_PRICE_SYNC_SCHEDULING__) {
return;
}
g.__CCH_CLOUD_PRICE_SYNC_SCHEDULING__ = true;

void (async () => {
try {
const { AsyncTaskManager } = await import("@/lib/async-task-manager");

logger.info("[PriceSync] Cloud price sync task completed", {
reason: options.reason,
added: result.data.added.length,
updated: result.data.updated.length,
skippedConflicts: result.data.skippedConflicts?.length ?? 0,
total: result.data.total,
});
} finally {
g.__CCH_CLOUD_PRICE_SYNC_LAST_AT__ = Date.now();
// 去重:已有任务在跑则不重复触发
const active = AsyncTaskManager.getActiveTasks();
if (active.some((t) => t.taskId === taskId)) {
return;
}
})(),
"cloud_price_table_sync"
);

AsyncTaskManager.register(
taskId,
(async () => {
try {
const result = await syncCloudPriceTableToDatabase();
if (!result.ok) {
logger.warn("[PriceSync] Cloud price sync task failed", {
reason: options.reason,
error: result.error,
});
return;
}

logger.info("[PriceSync] Cloud price sync task completed", {
reason: options.reason,
added: result.data.added.length,
updated: result.data.updated.length,
skippedConflicts: result.data.skippedConflicts?.length ?? 0,
total: result.data.total,
});
} finally {
g.__CCH_CLOUD_PRICE_SYNC_LAST_AT__ = Date.now();
}
})(),
"cloud_price_table_sync"
);
} catch (error) {
logger.warn("[PriceSync] Cloud price sync scheduling failed", {
reason: options.reason,
error: error instanceof Error ? error.message : String(error),
});
} finally {
g.__CCH_CLOUD_PRICE_SYNC_SCHEDULING__ = false;
}
})();
}
Loading
Loading