Skip to content
Merged
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
85 changes: 85 additions & 0 deletions apps/web/__tests__/unit/developer-api-cold-path.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { fileURLToPath } from "node:url";
import { build, type Metafile } from "esbuild";
Comment thread
richiemcilroy marked this conversation as resolved.
Resolved
import { describe, expect, it } from "vitest";

// A cold start of a developer API function evaluates every module the route
// imports statically. Sign-in (next-auth, SSO) and email rendering are only
// needed by cookie-authenticated requests and by billing emails, so they must
// stay behind dynamic imports and out of these routes' startup graph.
const webRoot = fileURLToPath(new URL("../../", import.meta.url));

const ROUTES = [
"app/api/developer/v1/[...route]/route.ts",
"app/api/developer/mcp/route.ts",
];

const NOT_AT_STARTUP = [
"packages/database/auth/auth-options",
"packages/database/auth/session",
"packages/database/emails/",
"node_modules/next-auth/",
"node_modules/nodemailer/",
"node_modules/@workos-inc/",
"node_modules/@react-email/",
"node_modules/resend/",
];

async function staticGraph(route: string) {
const result = await build({
entryPoints: [route],
absWorkingDir: webRoot,
bundle: true,
write: false,
metafile: true,
platform: "node",
format: "esm",
logLevel: "silent",
tsconfig: "tsconfig.json",
conditions: ["react-server", "node"],
external: ["next", "next/*", "@vercel/*"],
loader: {
".node": "empty",
".wasm": "empty",
".svg": "empty",
".png": "empty",
".css": "empty",
},
});
const inputs: Metafile["inputs"] = result.metafile.inputs;
const entry = Object.keys(inputs).find((path) => path.endsWith(route));
if (!entry) throw new Error(`entry not found for ${route}`);
const parent = new Map<string, string | null>([[entry, null]]);
const queue = [entry];
while (queue.length > 0) {
const current = queue.shift() as string;
for (const imported of inputs[current]?.imports ?? []) {
if (imported.kind === "dynamic-import") continue;
if (parent.has(imported.path) || !inputs[imported.path]) continue;
parent.set(imported.path, current);
queue.push(imported.path);
}
}
return parent;
}

function chainTo(parent: Map<string, string | null>, path: string) {
const chain: string[] = [];
for (let at: string | null | undefined = path; at; at = parent.get(at)) {
chain.unshift(at.replace(/^.*node_modules\//, ""));
}
return chain.join(" -> ");
}

describe("developer API cold path", () => {
it.each(ROUTES)(
"%s does not load sign-in or email code at startup",
async (route) => {
const parent = await staticGraph(route);
const offenders = [...parent.keys()]
.filter((path) => NOT_AT_STARTUP.some((part) => path.includes(part)))
.map((path) => chainTo(parent, path));
expect(offenders.slice(0, 3)).toEqual([]);
},
60_000,
);
});
3 changes: 2 additions & 1 deletion apps/web/app/api/utils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { db } from "@cap/database";
import { isBlockedAccountEmail } from "@cap/database/auth/domain-utils";
import { isCrossSiteCookieWrite } from "@cap/database/auth/request-site";
import { getCurrentUser } from "@cap/database/auth/session";
import type { getCurrentUser } from "@cap/database/auth/session";
import {
authApiKeys,
developerApiKeys,
Expand Down Expand Up @@ -493,6 +493,7 @@ async function getAuth(c: Context) {
user = res[0]?.users;
if (user && isBlockedAccountEmail(user.email)) user = undefined;
} else if (!isCrossSiteCookieWrite(c.req.raw)) {
const { getCurrentUser } = await import("@cap/database/auth/session");
user = await getCurrentUser();
}

Expand Down
11 changes: 8 additions & 3 deletions apps/web/lib/infra-billing-emails.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import { db } from "@cap/database";
import { sendEmail } from "@cap/database/emails/config";
import { InfraOutOfCredit } from "@cap/database/emails/infra-out-of-credit";
import { InfraTopUpFailed } from "@cap/database/emails/infra-top-up-failed";
import {
developerApps,
developerCreditAccounts,
Expand Down Expand Up @@ -58,6 +55,10 @@ export async function sendInfraOutOfCreditEmail({
try {
const recipient = await recipientFor(accountId);
if (!recipient) return false;
const [{ sendEmail }, { InfraOutOfCredit }] = await Promise.all([
import("@cap/database/emails/config"),
import("@cap/database/emails/infra-out-of-credit"),
]);
const result = await sendEmail({
email: recipient.email,
subject: `${recipient.appName} is out of Cap Infra credit`,
Expand Down Expand Up @@ -87,6 +88,10 @@ export async function sendInfraTopUpFailedEmail({
try {
const recipient = await recipientFor(accountId);
if (!recipient) return false;
const [{ sendEmail }, { InfraTopUpFailed }] = await Promise.all([
import("@cap/database/emails/config"),
import("@cap/database/emails/infra-top-up-failed"),
]);
await sendEmail({
email: recipient.email,
subject: `The auto top-up for ${recipient.appName} was declined`,
Expand Down
1 change: 1 addition & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@
"@vitest/ui": "^3.2.0",
"autoprefixer": "^10.4.14",
"cross-env": "^7.0.3",
"esbuild": "0.25.12",
"eslint": "^9.30.1",
"eslint-config-next": "16.4.5",
"glob": "^14.0.4",
Expand Down
1 change: 1 addition & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 6 additions & 2 deletions packages/web-backend/src/Auth.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { getServerSession } from "@cap/database/auth/auth-options";
import { isBlockedAccountEmail } from "@cap/database/auth/domain-utils";
import { isCrossSiteCookieWrite } from "@cap/database/auth/request-site";
import * as Db from "@cap/database/schema";
Expand Down Expand Up @@ -31,7 +30,12 @@ export const getCurrentUser = Effect.gen(function* () {
return Option.none<typeof Db.users.$inferSelect>();

return yield* Option.fromNullable(
yield* Effect.tryPromise(() => getServerSession()),
yield* Effect.tryPromise(async () => {
const { getServerSession } = await import(
"@cap/database/auth/auth-options"
);
return getServerSession();
}),
).pipe(
Option.map((session) =>
Effect.gen(function* () {
Expand Down
Loading