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";
|
2026-08-07 11:06:20 +08:00
|
|
|
import { authForbidden, getRequestPrincipal } from "../../../lib/user-auth";
|
2026-07-30 12:06:41 +08:00
|
|
|
|
|
|
|
|
export const runtime = "edge";
|
|
|
|
|
|
|
|
|
|
export async function GET(request: Request) {
|
2026-08-07 11:06:20 +08:00
|
|
|
const principal = await getRequestPrincipal(request);
|
|
|
|
|
if (!principal) return authForbidden();
|
2026-07-30 12:06:41 +08:00
|
|
|
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;
|
|
|
|
|
}
|
2026-08-07 11:06:20 +08:00
|
|
|
const dashboard = await getDashboardData();
|
|
|
|
|
return Response.json(
|
|
|
|
|
principal.kind === "user" && principal.user.role === "user"
|
|
|
|
|
? { ...dashboard, accounts: [] }
|
|
|
|
|
: dashboard,
|
|
|
|
|
);
|
2026-07-30 12:06:41 +08:00
|
|
|
} catch (error) {
|
|
|
|
|
return Response.json(
|
|
|
|
|
{ error: error instanceof Error ? error.message : "加载失败" },
|
|
|
|
|
{ status: 500 },
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|