Files
koc-loop/app/api/bootstrap/route.ts

71 lines
2.0 KiB
TypeScript
Raw Normal View History

2026-07-30 12:06:41 +08:00
import { env } from "cloudflare:workers";
import { getRequestExecutionContext } from "vinext/shims/request-context";
import { backfillAccountProfiles } from "../../../lib/account-enrichment-service";
import { runDueScheduledCollections } from "../../../lib/collection-service";
import {
resolveCollectionMcpConfig,
type CollectionMcpBindings,
} from "../../../lib/mcp-collection-client";
import {
ensureSchema,
getDashboardData,
getRawDb,
seedIfEmpty,
} from "../../../lib/mvp-db";
import { adminForbidden, isAdminRequest } from "../../../lib/admin-auth";
export const runtime = "edge";
export async function GET(request: Request) {
if (!isAdminRequest(request)) return adminForbidden();
try {
await ensureSchema();
await seedIfEmpty();
const db = getRawDb();
const mcpConfig = resolveCollectionMcpConfig(
env as unknown as CollectionMcpBindings,
);
const collectionCatchup = runDueScheduledCollections(
db,
Date.now(),
mcpConfig,
"catchup",
).catch((error) => {
console.error(
"KOC collection catchup failed",
error instanceof Error ? error.message : "unknown error",
);
});
const accountBackfill = backfillAccountProfiles(
db,
mcpConfig,
10,
)
.then((result) => {
console.info("KOC account backfill completed", result);
})
.catch((error) => {
console.error(
"KOC account backfill failed",
error instanceof Error ? error.message : "unknown error",
);
});
const catchup = Promise.all([
collectionCatchup,
accountBackfill,
]);
const executionContext = getRequestExecutionContext();
if (executionContext) {
executionContext.waitUntil(catchup);
} else {
await catchup;
}
return Response.json(await getDashboardData());
} catch (error) {
return Response.json(
{ error: error instanceof Error ? error.message : "加载失败" },
{ status: 500 },
);
}
}