diff --git a/docs/2.deploy/0.index.md b/docs/2.deploy/0.index.md index 3e439741fd..09c1330892 100644 --- a/docs/2.deploy/0.index.md +++ b/docs/2.deploy/0.index.md @@ -32,7 +32,7 @@ When deploying to production using CI/CD, Nitro tries to detect the provider env For Turborepo users, its Strict Environment Mode can interfere with zero-config detection. You may need to allow the detection variables explicitly or use Loose Environment Mode (the `--env-mode=loose` flag). :: -Other built-in providers are available with an explicit preset, including [Zephyr](/deploy/providers/zephyr). +Other built-in providers are available with an explicit preset, including [Neon Functions](/deploy/providers/neon) and [Zephyr](/deploy/providers/zephyr). ## Changing the deployment preset diff --git a/docs/2.deploy/20.providers/neon.md b/docs/2.deploy/20.providers/neon.md new file mode 100644 index 0000000000..832cc0d363 --- /dev/null +++ b/docs/2.deploy/20.providers/neon.md @@ -0,0 +1,184 @@ +# Neon Functions + +> Deploy Nitro apps to Neon Functions. + +**Preset:** `neon` + +:read-more{title="Neon Functions" to="https://neon.com/docs/compute/functions/overview"} + +[Neon Functions](https://neon.com/docs/compute/functions/overview) run Node.js 24 next to your Neon Postgres branch. + +The `neon` preset builds your app into a single function. Nitro serves your routes, server-side rendering, and public assets from it, and maps Nitro features to the Neon runtime: + +| Nitro feature | On Neon Functions | +| --- | --- | +| [Public assets](/docs/assets) | Served by the function from disk, with ETags and precompressed variants | +| [`event.waitUntil`](/docs/lifecycle) | Neon `waitUntil` (up to 15 minutes after the response) | +| [Database](/docs/database) | The branch's Postgres, with no connection string to configure | +| [Scheduled tasks](/docs/tasks) | [Neon Function Triggers](https://neon.com/docs/compute/functions/triggers/schedule) | +| [`shutdown` and `close` hooks](/docs/lifecycle#server-shutdown) | Called on `SIGINT`, before Neon stops an isolate | + +## Deploy with the Neon CLI + +1. Install the [Neon CLI](https://neon.com/docs/cli) and link your project to a Neon project and branch. Functions are available in [these regions](https://neon.com/docs/compute/functions/overview). + + ```bash + npm install -g neon@latest + neon link + ``` + +2. Build your app with the `neon` preset: + + ```bash + NITRO_PRESET=neon npx nitro build + ``` + + You can also set `preset: "neon"` in your Nitro config. + +3. Deploy the `.output` directory as a prebuilt function: + + ```bash + neon functions deploy myapp --src .output --no-bundle + ``` + + `myapp` is the function slug. It becomes part of the URL and can't be changed after the first deploy. A slug has 1 to 20 lowercase letters and digits, with no hyphens. + +4. Get the public URL of your function: + + ```bash + neon functions get myapp + ``` + +::note +Deploy the whole `.output` directory, not `.output/server`. Nitro writes an `index.mjs` entry at the root of `.output` for Neon Functions to load, and serves public assets from `.output/public`. +:: + +## Deploy with `neon.ts` + +To deploy your app with the rest of your Neon config, declare it in [`neon.ts`](https://neon.com/docs/reference/neon-ts) with `bundler: "none"`, so Neon ships the prebuilt output as is: + +```ts [neon.ts] +import { defineConfig } from "@neon/config/v1"; + +export default defineConfig({ + functions: { + myapp: { + name: "My Nitro app", + source: "./.output", + bundler: "none", + }, + }, +}); +``` + +Then build and deploy: + +```bash +NITRO_PRESET=neon npx nitro build +neon deploy +``` + +## Environment variables + +Neon injects the branch's service variables into every function at runtime, such as `DATABASE_URL`, `PGHOST`, `PGUSER`, `PGPASSWORD`, and `PGDATABASE`. See [Neon Functions environment variables](https://neon.com/docs/compute/functions/environment-variables). + +Set your own variables at deploy time. Variables with the `NITRO_` prefix override [runtime config](/docs/configuration#runtime-configuration): + +```bash +neon functions deploy myapp --src .output --no-bundle --env NITRO_API_TOKEN=secret +``` + +## Database + +When [database](/docs/database) support is enabled, the `neon` preset sets the default connection to the branch's Postgres. The `postgresql` connector reads the variables that Neon injects, so you don't configure a connection string: + +```ts [nitro.config.ts] +import { defineConfig } from "nitro"; + +export default defineConfig({ + preset: "neon", + experimental: { + database: true, + }, +}); +``` + +```ts [routes/users.ts] +import { defineHandler } from "nitro"; +import { useDatabase } from "nitro/database"; + +export default defineHandler(async () => { + const db = useDatabase(); + const { rows } = await db.sql`SELECT * FROM users LIMIT 10`; + return rows; +}); +``` + +::warning +Don't use SQLite connectors on Neon Functions. The filesystem is read-only outside `/tmp`, and `/tmp` is local to each isolate and lost when the isolate stops. +:: + +## WebSockets + +The `neon` preset doesn't support Nitro [WebSockets](/docs/websocket) yet. With `features.websocket` enabled, the build logs a warning, and WebSocket clients get a `426 Upgrade Required` response. + +For one-way, server-to-client updates, stream a response with [server-sent events](https://neon.com/docs/compute/functions/websockets#server-sent-events-sse). + +## Scheduled tasks + +Neon runs [scheduled tasks](/docs/tasks#scheduled-tasks) with [Function Triggers](https://neon.com/docs/compute/functions/triggers/schedule). For each cron expression in `scheduledTasks`, Nitro writes a function path to `.output/neon.json`: + +```json [.output/neon.json] +{ + "triggers": [ + { + "cron": "0 3 * * *", + "functionPath": "/_neon/cron/MCAzICogKiAq", + "tasks": ["db:cleanup"] + } + ] +} +``` + +Create a schedule trigger for each entry, pointing at its `functionPath`: + +```bash +neon triggers create --function-slug myapp --name db-cleanup \ + --cron "0 3 * * *" --function-path /_neon/cron/MCAzICogKiAq +``` + +Or declare the triggers in `neon.ts`: + +```ts [neon.ts] +import { defineConfig } from "@neon/config/v1"; + +export default defineConfig({ + functions: { + myapp: { name: "My Nitro app", source: "./.output", bundler: "none" }, + }, + triggers: { + "db-cleanup": { + type: "schedule", + function: "myapp", + cron: "0 3 * * *", + functionPath: "/_neon/cron/MCAzICogKiAq", + }, + }, +}); +``` + +Neon evaluates schedules in UTC and accepts only five numeric fields, so names like `MON`, macros like `@daily`, and a seconds field are rejected. Each task receives the trigger's scheduled time as `payload.scheduledTime`. Nitro rejects requests to these paths that don't come from Neon. + +## Caching and storage + +Every isolate has its own memory. The default in-memory [KV storage](/docs/storage) and [cache](/docs/cache) are not shared between isolates and are lost when an isolate stops. For data that must persist or be shared, use the branch's Postgres, or mount a KV driver backed by an external service. + +## Preview locally + +To preview the build locally, run: + +```bash +npx srvx --prod .output +``` + +`event.waitUntil` and scheduled trigger deliveries need the Neon Functions runtime, so test them on a deployed function. diff --git a/src/presets/_all.gen.ts b/src/presets/_all.gen.ts index ac443d86dc..d1246041df 100644 --- a/src/presets/_all.gen.ts +++ b/src/presets/_all.gen.ts @@ -18,6 +18,7 @@ import _genezio from "./genezio/preset.ts"; import _heroku from "./heroku/preset.ts"; import _iis from "./iis/preset.ts"; import _koyeb from "./koyeb/preset.ts"; +import _neon from "./neon/preset.ts"; import _netlify from "./netlify/preset.ts"; import _node from "./node/preset.ts"; import _renderCom from "./render.com/preset.ts"; @@ -48,6 +49,7 @@ export default [ ..._heroku, ..._iis, ..._koyeb, + ..._neon, ..._netlify, ..._node, ..._renderCom, diff --git a/src/presets/_types.gen.ts b/src/presets/_types.gen.ts index def1d334f5..89a05df2da 100644 --- a/src/presets/_types.gen.ts +++ b/src/presets/_types.gen.ts @@ -24,6 +24,6 @@ export interface PresetOptions { export const presetsWithConfig = ["awsAmplify","awsLambda","azure","cloudflare","firebase","iis","netlify","vercel","zephyr"] as const; -export type PresetName = "alwaysdata" | "aws-amplify" | "aws-lambda" | "azure-swa" | "base-worker" | "bun" | "cleavr" | "cloudflare-dev" | "cloudflare-durable" | "cloudflare-module" | "cloudflare-pages" | "cloudflare-pages-static" | "deno" | "deno-server" | "digital-ocean" | "edgeone" | "edgeone-pages" | "firebase-app-hosting" | "flight-control" | "genezio" | "github-pages" | "gitlab-pages" | "heroku" | "iis-handler" | "iis-node" | "koyeb" | "netlify" | "netlify-edge" | "netlify-static" | "nitro-dev" | "nitro-prerender" | "nitro-serve" | "node" | "node-cluster" | "node-middleware" | "node-server" | "platform-sh" | "render-com" | "standard" | "static" | "stormkit" | "upsun" | "vercel" | "vercel-dev" | "vercel-static" | "zeabur" | "zeabur-static" | "zephyr" | "zerops" | "zerops-static"; +export type PresetName = "alwaysdata" | "aws-amplify" | "aws-lambda" | "azure-swa" | "base-worker" | "bun" | "cleavr" | "cloudflare-dev" | "cloudflare-durable" | "cloudflare-module" | "cloudflare-pages" | "cloudflare-pages-static" | "deno" | "deno-server" | "digital-ocean" | "edgeone" | "edgeone-pages" | "firebase-app-hosting" | "flight-control" | "genezio" | "github-pages" | "gitlab-pages" | "heroku" | "iis-handler" | "iis-node" | "koyeb" | "neon" | "neon-functions" | "netlify" | "netlify-edge" | "netlify-static" | "nitro-dev" | "nitro-prerender" | "nitro-serve" | "node" | "node-cluster" | "node-middleware" | "node-server" | "platform-sh" | "render-com" | "standard" | "static" | "stormkit" | "upsun" | "vercel" | "vercel-dev" | "vercel-static" | "zeabur" | "zeabur-static" | "zephyr" | "zerops" | "zerops-static"; -export type PresetNameInput = "alwaysdata" | "aws-amplify" | "awsAmplify" | "aws_amplify" | "aws-lambda" | "awsLambda" | "aws_lambda" | "azure-swa" | "azureSwa" | "azure_swa" | "base-worker" | "baseWorker" | "base_worker" | "bun" | "cleavr" | "cloudflare-dev" | "cloudflareDev" | "cloudflare_dev" | "cloudflare-durable" | "cloudflareDurable" | "cloudflare_durable" | "cloudflare-module" | "cloudflareModule" | "cloudflare_module" | "cloudflare-pages" | "cloudflarePages" | "cloudflare_pages" | "cloudflare-pages-static" | "cloudflarePagesStatic" | "cloudflare_pages_static" | "deno" | "deno-server" | "denoServer" | "deno_server" | "digital-ocean" | "digitalOcean" | "digital_ocean" | "edgeone" | "edgeone-pages" | "edgeonePages" | "edgeone_pages" | "firebase-app-hosting" | "firebaseAppHosting" | "firebase_app_hosting" | "flight-control" | "flightControl" | "flight_control" | "genezio" | "github-pages" | "githubPages" | "github_pages" | "gitlab-pages" | "gitlabPages" | "gitlab_pages" | "heroku" | "iis-handler" | "iisHandler" | "iis_handler" | "iis-node" | "iisNode" | "iis_node" | "koyeb" | "netlify" | "netlify-edge" | "netlifyEdge" | "netlify_edge" | "netlify-static" | "netlifyStatic" | "netlify_static" | "nitro-dev" | "nitroDev" | "nitro_dev" | "nitro-prerender" | "nitroPrerender" | "nitro_prerender" | "nitro-serve" | "nitroServe" | "nitro_serve" | "node" | "node-cluster" | "nodeCluster" | "node_cluster" | "node-middleware" | "nodeMiddleware" | "node_middleware" | "node-server" | "nodeServer" | "node_server" | "platform-sh" | "platformSh" | "platform_sh" | "render-com" | "renderCom" | "render_com" | "standard" | "static" | "stormkit" | "upsun" | "vercel" | "vercel-dev" | "vercelDev" | "vercel_dev" | "vercel-static" | "vercelStatic" | "vercel_static" | "zeabur" | "zeabur-static" | "zeaburStatic" | "zeabur_static" | "zephyr" | "zerops" | "zerops-static" | "zeropsStatic" | "zerops_static" | (string & {}); +export type PresetNameInput = "alwaysdata" | "aws-amplify" | "awsAmplify" | "aws_amplify" | "aws-lambda" | "awsLambda" | "aws_lambda" | "azure-swa" | "azureSwa" | "azure_swa" | "base-worker" | "baseWorker" | "base_worker" | "bun" | "cleavr" | "cloudflare-dev" | "cloudflareDev" | "cloudflare_dev" | "cloudflare-durable" | "cloudflareDurable" | "cloudflare_durable" | "cloudflare-module" | "cloudflareModule" | "cloudflare_module" | "cloudflare-pages" | "cloudflarePages" | "cloudflare_pages" | "cloudflare-pages-static" | "cloudflarePagesStatic" | "cloudflare_pages_static" | "deno" | "deno-server" | "denoServer" | "deno_server" | "digital-ocean" | "digitalOcean" | "digital_ocean" | "edgeone" | "edgeone-pages" | "edgeonePages" | "edgeone_pages" | "firebase-app-hosting" | "firebaseAppHosting" | "firebase_app_hosting" | "flight-control" | "flightControl" | "flight_control" | "genezio" | "github-pages" | "githubPages" | "github_pages" | "gitlab-pages" | "gitlabPages" | "gitlab_pages" | "heroku" | "iis-handler" | "iisHandler" | "iis_handler" | "iis-node" | "iisNode" | "iis_node" | "koyeb" | "neon" | "neon-functions" | "neonFunctions" | "neon_functions" | "netlify" | "netlify-edge" | "netlifyEdge" | "netlify_edge" | "netlify-static" | "netlifyStatic" | "netlify_static" | "nitro-dev" | "nitroDev" | "nitro_dev" | "nitro-prerender" | "nitroPrerender" | "nitro_prerender" | "nitro-serve" | "nitroServe" | "nitro_serve" | "node" | "node-cluster" | "nodeCluster" | "node_cluster" | "node-middleware" | "nodeMiddleware" | "node_middleware" | "node-server" | "nodeServer" | "node_server" | "platform-sh" | "platformSh" | "platform_sh" | "render-com" | "renderCom" | "render_com" | "standard" | "static" | "stormkit" | "upsun" | "vercel" | "vercel-dev" | "vercelDev" | "vercel_dev" | "vercel-static" | "vercelStatic" | "vercel_static" | "zeabur" | "zeabur-static" | "zeaburStatic" | "zeabur_static" | "zephyr" | "zerops" | "zerops-static" | "zeropsStatic" | "zerops_static" | (string & {}); diff --git a/src/presets/neon/preset.ts b/src/presets/neon/preset.ts new file mode 100644 index 0000000000..ddb338f37c --- /dev/null +++ b/src/presets/neon/preset.ts @@ -0,0 +1,32 @@ +import { defineNitroPreset } from "../_utils/preset.ts"; +import { warnUnsupportedFeatures, writeNeonOutput } from "./utils.ts"; + +const neon = defineNitroPreset( + { + entry: "./neon/runtime/neon", + serveStatic: true, + commands: { + preview: "npx srvx --prod ./", + deploy: "neon functions deploy --src ./ --no-bundle", + }, + // Neon Functions inject `PGHOST`, `PGUSER`, `PGPASSWORD` and `PGDATABASE` for the + // branch Postgres, which `pg` reads at runtime. + database: { + default: { connector: "postgresql", options: { ssl: true } }, + }, + hooks: { + "build:before"(nitro) { + warnUnsupportedFeatures(nitro); + }, + async compiled(nitro) { + await writeNeonOutput(nitro); + }, + }, + }, + { + name: "neon" as const, + aliases: ["neon-functions"], + } +); + +export default [neon] as const; diff --git a/src/presets/neon/runtime/_shutdown.ts b/src/presets/neon/runtime/_shutdown.ts new file mode 100644 index 0000000000..1238a805ed --- /dev/null +++ b/src/presets/neon/runtime/_shutdown.ts @@ -0,0 +1,109 @@ +import type { NitroShutdownContext } from "nitro/types"; +import { useNitroHooks } from "nitro/app"; + +const inflight = new Set>(); +let shutdownWaitUntil: NitroShutdownContext["waitUntil"] | undefined; + +/** + * Keep a shutdown pending until `promise` settles: use it for requests and for the work they + * register with `waitUntil`. + */ +export function trackInflight(promise: Promise): Promise { + const settled = promise.then( + () => {}, + () => {} + ); + inflight.add(settled); + settled.finally(() => inflight.delete(settled)); + shutdownWaitUntil?.(settled); + return promise; +} + +/** + * Keep a shutdown pending until the response body is fully sent, cancelled or failed. The body + * is read one chunk at a time as the client pulls it, so it is never buffered. + */ +export function trackResponse(response: Response): Response { + const body = response.body; + if (!body) { + return response; + } + let settle!: () => void; + trackInflight(new Promise((resolve) => (settle = resolve))); + const reader = body.getReader(); + const tracked = new ReadableStream({ + async pull(controller) { + try { + const { done, value } = await reader.read(); + if (done) { + settle(); + controller.close(); + } else { + controller.enqueue(value); + } + } catch (error) { + settle(); + controller.error(error); + } + }, + cancel(reason) { + // Resolves once the source stream finished its own cancellation cleanup. + const cancelled = trackInflight(reader.cancel(reason)); + settle(); + return cancelled; + }, + }); + return new Response(tracked, { + status: response.status, + statusText: response.statusText, + headers: response.headers, + }); +} + +/** + * Call the Nitro `shutdown` hooks, then wait for in-flight requests and the work registered + * with `waitUntil` for up to `timeout` milliseconds, then call the `close` hooks. + * + * Neon sends `SIGINT` before stopping an isolate and stops it 5 seconds later, so the timeout + * leaves time for the `close` hooks within that window. + */ +export async function shutdownNitro({ timeout }: { timeout: number }): Promise { + try { + await callShutdownHooks(timeout); + await useNitroHooks().callHook("close"); + } catch (error) { + console.error("[nitro] Error while shutting down:", error); + } +} + +function callShutdownHooks(timeout: number): Promise { + const controller = new AbortController(); + return new Promise((resolve) => { + let pending = 0; + const timer = setTimeout(() => { + console.warn(`[nitro] Shutdown did not finish within ${timeout}ms.`); + controller.abort(); + resolve(); + }, timeout); + const waitUntil: NitroShutdownContext["waitUntil"] = (promise) => { + pending++; + Promise.resolve(promise) + .catch((error) => console.error("[nitro] Error while shutting down:", error)) + .finally(() => { + if (--pending === 0) { + clearTimeout(timer); + resolve(); + } + }); + }; + shutdownWaitUntil = waitUntil; + for (const promise of inflight) { + waitUntil(promise); + } + waitUntil( + Promise.resolve( + useNitroHooks().callHook("shutdown", { waitUntil, signal: controller.signal }) + ) + ); + }); +} diff --git a/src/presets/neon/runtime/neon.ts b/src/presets/neon/runtime/neon.ts new file mode 100644 index 0000000000..c133c30e56 --- /dev/null +++ b/src/presets/neon/runtime/neon.ts @@ -0,0 +1,66 @@ +import "#nitro/virtual/polyfills"; +import type { ServerRequest } from "srvx"; + +import { useNitroApp } from "nitro/app"; +import { runCronTasks } from "#nitro/runtime/task"; +import { trapUnhandledErrors } from "#nitro/runtime/error/hooks"; +import { shutdownNitro, trackInflight, trackResponse } from "./_shutdown.ts"; + +declare global { + // Published by the Neon Functions runtime for each invocation. + var NEON_REQUEST_CONTEXT: { waitUntil?: (promise: Promise) => void } | undefined; +} + +const CRON_PATH_PREFIX = "/_neon/cron/"; + +const nitroApp = useNitroApp(); + +trapUnhandledErrors(); + +// Neon sends `SIGINT` before stopping an isolate, and stops it 5 seconds later. +process.once("SIGINT", async () => { + await shutdownNitro({ timeout: 4000 }); + process.exit(0); +}); + +export default { + fetch(req: ServerRequest): Promise { + return trackInflight(handleRequest(req).then(trackResponse)); + }, +}; + +async function handleRequest(req: ServerRequest): Promise { + const context = globalThis.NEON_REQUEST_CONTEXT; + req.runtime ??= { name: "neon" } as ServerRequest["runtime"]; + if (!req.waitUntil && context?.waitUntil) { + req.waitUntil = (promise) => { + context.waitUntil!(trackInflight(Promise.resolve(promise))); + }; + } + req.ip ??= req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || undefined; + + if (import.meta._tasks && req.method === "POST") { + const { pathname } = new URL(req.url); + if (pathname.startsWith(CRON_PATH_PREFIX)) { + return runScheduledTrigger(req, pathname.slice(CRON_PATH_PREFIX.length)); + } + } + + return nitroApp.fetch(req); +} + +async function runScheduledTrigger(req: ServerRequest, encodedCron: string): Promise { + // Neon strips client-set `X-Neon-*` headers, so this one comes from a trigger delivery. + const invocationId = req.headers.get("x-neon-trigger-invocation-id"); + if (!invocationId) { + return Response.json({ error: "Not a Neon Function Trigger delivery" }, { status: 401 }); + } + const cron = Buffer.from(decodeURIComponent(encodedCron), "base64url").toString("utf8"); + const body = (await req.json().catch(() => ({}))) as { data?: { scheduled_at?: string } }; + const scheduledAt = body.data?.scheduled_at ? Date.parse(body.data.scheduled_at) : Number.NaN; + const results = await runCronTasks(cron, { + context: { waitUntil: req.waitUntil, neon: { invocationId } }, + payload: { scheduledTime: Number.isNaN(scheduledAt) ? Date.now() : scheduledAt }, + }); + return Response.json({ success: true, tasks: results.length }); +} diff --git a/src/presets/neon/utils.ts b/src/presets/neon/utils.ts new file mode 100644 index 0000000000..e2303c4ecc --- /dev/null +++ b/src/presets/neon/utils.ts @@ -0,0 +1,64 @@ +import type { Nitro } from "nitro/types"; +import { relative, resolve } from "pathe"; +import { writeFile } from "../_utils/fs.ts"; + +export const CRON_PATH_PREFIX = "/_neon/cron/"; + +export function warnUnsupportedFeatures(nitro: Nitro) { + if (nitro.options.features?.websocket) { + nitro.logger.warn( + "[neon] WebSockets are not supported by the `neon` preset yet. Upgrade requests are handled as regular HTTP requests." + ); + } + if (!nitro.options.experimental.database) { + return; + } + for (const [name, connection] of Object.entries(nitro.options.database || {})) { + if (/sqlite/.test(String(connection?.connector))) { + nitro.logger.warn( + `[neon] Database \`${name}\` uses the \`${connection!.connector}\` connector. Neon Functions have a read-only filesystem outside \`/tmp\`, and \`/tmp\` is per isolate and lost on eviction. Remove the connection to use the branch Postgres.` + ); + } + } +} + +export async function writeNeonOutput(nitro: Nitro) { + const { dir, serverDir, publicDir } = nitro.options.output; + for (const [option, path] of [ + ["output.serverDir", serverDir], + ["output.publicDir", publicDir], + ] as const) { + if (relative(dir, path).startsWith("..")) { + nitro.logger.warn( + `[neon] \`${option}\` (\`${path}\`) is outside \`output.dir\` (\`${dir}\`), so it is not part of the deployed function.` + ); + } + } + + // Neon Functions load `index.mjs` from the root of the deployed directory. When the server + // entry is already there, it is the handler itself. + const entry = relative(dir, resolve(serverDir, "index.mjs")); + if (entry !== "index.mjs") { + await writeFile(resolve(dir, "index.mjs"), `export { default } from "./${entry}";\n`); + } + + const triggers = Object.entries(nitro.options.scheduledTasks || {}).map(([cron, tasks]) => { + if (!/^(\S+\s+){4}\S+$/.test(cron.trim()) || /[a-z@?#]/i.test(cron)) { + nitro.logger.warn( + `[neon] Scheduled task cron \`${cron}\` is not a five-field numeric expression, which Neon Function Triggers require.` + ); + } + return { + cron, + functionPath: CRON_PATH_PREFIX + Buffer.from(cron).toString("base64url"), + tasks: Array.isArray(tasks) ? tasks : [tasks], + }; + }); + await writeFile(resolve(dir, "neon.json"), JSON.stringify({ triggers }, null, 2) + "\n"); + + if (triggers.length > 0) { + nitro.logger.info( + `[neon] Create a schedule trigger for each cron, using the \`functionPath\` from \`${relative(nitro.options.rootDir, resolve(dir, "neon.json"))}\`.` + ); + } +} diff --git a/test/presets/neon.test.ts b/test/presets/neon.test.ts new file mode 100644 index 0000000000..f586f68dfc --- /dev/null +++ b/test/presets/neon.test.ts @@ -0,0 +1,41 @@ +import { readFile } from "node:fs/promises"; +import { resolve } from "pathe"; +import { describe, expect, it } from "vitest"; +import { setupTest, testNitro } from "../tests.ts"; + +describe("nitro:preset:neon", async () => { + const ctx = await setupTest("neon"); + + testNitro( + ctx, + async () => { + // The root `index.mjs` is what Neon Functions load. + const entryPath = resolve(ctx.outDir, "index.mjs"); + const fetchHandler = await import(entryPath).then((m) => m.default.fetch); + return async ({ url, ...init }) => { + const pending: Promise[] = []; + globalThis.NEON_REQUEST_CONTEXT = { waitUntil: (promise) => pending.push(promise) }; + try { + return await fetchHandler(new Request(`https://test.com${url}`, init)); + } finally { + globalThis.NEON_REQUEST_CONTEXT = undefined; + } + }; + }, + (_ctx, callHandler) => { + it("writes the root entry and neon.json", async () => { + const entry = await readFile(resolve(ctx.outDir, "index.mjs"), "utf8"); + expect(entry).toBe(`export { default } from "./server/index.mjs";\n`); + const neon = JSON.parse(await readFile(resolve(ctx.outDir, "neon.json"), "utf8")); + expect(neon).toMatchObject({ triggers: expect.any(Array) }); + }); + + it("rejects cron paths without a trigger delivery header", async () => { + const res = await callHandler({ url: "/_neon/cron/KiAqICogKg", method: "POST" }); + if (ctx.nitro!.options.experimental.tasks) { + expect(res.status).toBe(401); + } + }); + } + ); +}); diff --git a/test/tests.ts b/test/tests.ts index 7c1b1aeae5..ba5ae63214 100644 --- a/test/tests.ts +++ b/test/tests.ts @@ -1184,7 +1184,8 @@ export function testNitro( !ctx.nitro!.options.node || ctx.isLambda || ctx.isWorker || - ["bun", "deno-server", "netlify", "netlify-legacy"].includes(ctx.preset) + // `neon` defaults to the branch Postgres injected by Neon Functions + ["bun", "deno-server", "netlify", "netlify-legacy", "neon"].includes(ctx.preset) )("Database", () => { it("works", async () => { const { data } = await callHandler({ url: "/api/db" }); diff --git a/test/unit/neon-shutdown.test.ts b/test/unit/neon-shutdown.test.ts new file mode 100644 index 0000000000..a74dc2f01a --- /dev/null +++ b/test/unit/neon-shutdown.test.ts @@ -0,0 +1,222 @@ +import type { NitroShutdownContext } from "nitro/types"; +import { FastResponse } from "srvx"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const hooks = vi.hoisted(() => ({ close: vi.fn(), shutdown: vi.fn() })); + +vi.mock("nitro/app", () => ({ + useNitroHooks: () => ({ + callHook: (name: keyof typeof hooks, ...args: unknown[]) => hooks[name](...args), + }), +})); + +const { shutdownNitro, trackInflight, trackResponse } = + await import("../../src/presets/neon/runtime/_shutdown.ts"); + +describe("neon shutdownNitro", () => { + beforeEach(() => { + for (const hook of Object.values(hooks)) { + hook.mockReset(); + hook.mockResolvedValue(undefined); + } + }); + + afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + it("waits for `shutdown` work before calling `close` hooks", async () => { + const events: string[] = []; + hooks.shutdown.mockImplementationOnce((ctx: NitroShutdownContext) => { + ctx.waitUntil(sleep(50).then(() => events.push("flushed"))); + }); + hooks.close.mockImplementationOnce(() => { + events.push("close"); + }); + + await shutdownNitro({ timeout: 1000 }); + + expect(events).toEqual(["flushed", "close"]); + }); + + it("stops waiting at the timeout and aborts the signal", async () => { + vi.useFakeTimers(); + vi.spyOn(console, "warn").mockImplementation(() => {}); + let signal!: AbortSignal; + hooks.shutdown.mockImplementationOnce((ctx: NitroShutdownContext) => { + signal = ctx.signal; + ctx.waitUntil(new Promise(() => {})); + }); + + const done = shutdownNitro({ timeout: 4000 }); + await vi.advanceTimersByTimeAsync(4000); + await done; + + expect(signal.aborted).toBe(true); + expect(hooks.close).toHaveBeenCalledOnce(); + }); + + it("waits for in-flight requests before calling `close` hooks", async () => { + const events: string[] = []; + hooks.close.mockImplementationOnce(() => { + events.push("close"); + }); + trackInflight(sleep(50).then(() => events.push("response"))); + + await shutdownNitro({ timeout: 1000 }); + + expect(events).toEqual(["response", "close"]); + }); + + it("waits for requests and `waitUntil` work that start during shutdown", async () => { + const events: string[] = []; + hooks.shutdown.mockImplementationOnce(() => { + trackInflight(sleep(50).then(() => events.push("late request"))); + }); + hooks.close.mockImplementationOnce(() => { + events.push("close"); + }); + + await shutdownNitro({ timeout: 1000 }); + + expect(events).toEqual(["late request", "close"]); + }); + + it("stops waiting for in-flight requests at the timeout", async () => { + vi.useFakeTimers(); + vi.spyOn(console, "warn").mockImplementation(() => {}); + let release!: () => void; + trackInflight(new Promise((resolve) => (release = resolve))); + + const done = shutdownNitro({ timeout: 4000 }); + await vi.advanceTimersByTimeAsync(4000); + await done; + + expect(hooks.close).toHaveBeenCalledOnce(); + release(); + }); + + it("does not fail the shutdown when a request rejects", async () => { + const rejected = Promise.reject(new Error("request failed")); + trackInflight(rejected).catch(() => {}); + + await shutdownNitro({ timeout: 1000 }); + + expect(hooks.close).toHaveBeenCalledOnce(); + }); + + it("waits for streamed response bodies to finish", async () => { + const events: string[] = []; + hooks.close.mockImplementationOnce(() => { + events.push("close"); + }); + const response = trackResponse(new Response(slowStream(["a", "b", "c"], 20))); + + const [body] = await Promise.all([ + response.text().then((text) => { + events.push("body"); + return text; + }), + shutdownNitro({ timeout: 1000 }), + ]); + + expect(body).toBe("abc"); + expect(events).toEqual(["body", "close"]); + }); + + it("stops tracking a response body when the client cancels it", async () => { + const response = trackResponse(new Response(slowStream(["a", "b"], 1000))); + await response.body!.cancel(); + + await shutdownNitro({ timeout: 1000 }); + + expect(hooks.close).toHaveBeenCalledOnce(); + }); + + it("waits for the source stream to finish cancelling", async () => { + const events: string[] = []; + hooks.close.mockImplementationOnce(() => { + events.push("close"); + }); + const source = new ReadableStream({ + async cancel() { + await sleep(50); + events.push("cancel cleanup"); + }, + }); + const response = trackResponse(new Response(source)); + + const cancelled = response.body!.cancel(); + await shutdownNitro({ timeout: 1000 }); + await cancelled; + + expect(events).toEqual(["cancel cleanup", "close"]); + }); + + it("stops tracking a response body that fails", async () => { + const failing = new ReadableStream({ + pull(controller) { + controller.error(new Error("stream failed")); + }, + }); + const response = trackResponse(new Response(failing)); + await expect(response.text()).rejects.toThrow("stream failed"); + + await shutdownNitro({ timeout: 1000 }); + + expect(hooks.close).toHaveBeenCalledOnce(); + }); + + it("keeps responses without a body as they are", async () => { + const response = new Response(null, { status: 204, headers: { "x-test": "1" } }); + + expect(trackResponse(response)).toBe(response); + }); + + // The bundle replaces the global `Response` with srvx `FastResponse`. + it.each([ + ["Response", Response], + ["FastResponse", FastResponse], + ])("keeps the status and headers of tracked responses (%s)", async (_name, ResponseClass) => { + vi.stubGlobal("Response", ResponseClass); + const response = trackResponse( + new ResponseClass("ok", { status: 404, statusText: "Not Found", headers: { "x-test": "1" } }) + ); + vi.unstubAllGlobals(); + + expect(response.status).toBe(404); + expect(response.statusText).toBe("Not Found"); + expect(response.headers.get("x-test")).toBe("1"); + expect(await response.text()).toBe("ok"); + }); + + it("logs hook errors instead of failing the shutdown", async () => { + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + hooks.shutdown.mockRejectedValueOnce(new Error("shutdown failed")); + + await shutdownNitro({ timeout: 1000 }); + + expect(error).toHaveBeenCalled(); + expect(hooks.close).toHaveBeenCalledOnce(); + }); +}); + +function slowStream(chunks: string[], ms: number) { + const encoder = new TextEncoder(); + return new ReadableStream({ + async pull(controller) { + const chunk = chunks.shift(); + if (chunk === undefined) { + controller.close(); + return; + } + await sleep(ms); + controller.enqueue(encoder.encode(chunk)); + }, + }); +} + +function sleep(ms: number) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} diff --git a/test/unit/neon.utils.test.ts b/test/unit/neon.utils.test.ts new file mode 100644 index 0000000000..fb37a2a444 --- /dev/null +++ b/test/unit/neon.utils.test.ts @@ -0,0 +1,44 @@ +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "pathe"; +import type { Nitro } from "nitro/types"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { writeNeonOutput } from "../../src/presets/neon/utils.ts"; + +describe("writeNeonOutput", () => { + let dir: string; + + beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), "nitro-neon-")); + }); + + afterEach(async () => { + await rm(dir, { recursive: true, force: true }); + }); + + function createNitro(output: { serverDir: string; publicDir: string }) { + return { + options: { rootDir: dir, output: { dir, ...output }, scheduledTasks: {} }, + logger: { warn: vi.fn(), info: vi.fn() }, + } as unknown as Nitro; + } + + it("writes a root entry that re-exports the server entry", async () => { + await writeNeonOutput( + createNitro({ serverDir: join(dir, "server"), publicDir: join(dir, "public") }) + ); + + expect(await readFile(join(dir, "index.mjs"), "utf8")).toBe( + `export { default } from "./server/index.mjs";\n` + ); + }); + + it("keeps the server entry when `output.serverDir` is `output.dir`", async () => { + const handler = "export default { fetch: () => new Response('ok') };\n"; + await writeFile(join(dir, "index.mjs"), handler); + + await writeNeonOutput(createNitro({ serverDir: dir, publicDir: join(dir, "public") })); + + expect(await readFile(join(dir, "index.mjs"), "utf8")).toBe(handler); + }); +});