@neon/skills 2.0.0 → 2.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/neon-logomark-dark.svg +10 -0
- package/assets/neon-logomark-light.svg +10 -0
- package/package.json +2 -1
- package/plugin.json +27 -2
- package/skills/neon/SKILL.md +25 -13
- package/skills/neon-ai-gateway/SKILL.md +1 -1
- package/skills/neon-functions/SKILL.md +32 -11
- package/skills/neon-functions/references/function-triggers.md +2 -0
- package/skills/neon-functions/references/native-binaries.md +188 -0
- package/skills/neon-functions/references/production-hardening.md +340 -0
- package/skills/neon-postgres/SKILL.md +1 -0
- package/skills/neon-postgres/references/lakebase-search-drizzle.md +172 -0
- package/skills/neon-postgres-branches/SKILL.md +2 -2
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
<svg width="64" height="64" viewBox="-4 -4 72 72" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2
|
+
<g clip-path="url(#clip0_329_14445)">
|
|
3
|
+
<path d="M57.113 7.01415V57.5526L37.5592 40.6076V57.5526H7V7L57.113 7.01415ZM13.1428 51.4168H31.4164V27.1437L50.9705 44.4238V13.1482L13.1428 13.1373V51.4168Z" fill="#34D59A"/>
|
|
4
|
+
</g>
|
|
5
|
+
<defs>
|
|
6
|
+
<clipPath id="clip0_329_14445">
|
|
7
|
+
<rect width="64" height="64" fill="white"/>
|
|
8
|
+
</clipPath>
|
|
9
|
+
</defs>
|
|
10
|
+
</svg>
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
<svg width="64" height="64" viewBox="-4 -4 72 72" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2
|
+
<g clip-path="url(#clip0_329_14442)">
|
|
3
|
+
<path d="M57.113 7.01415V57.5526L37.5592 40.6076V57.5526H7V7L57.113 7.01415ZM13.1428 51.4168H31.4164V27.1437L50.9705 44.4238V13.1482L13.1428 13.1373V51.4168Z" fill="#37C38F"/>
|
|
4
|
+
</g>
|
|
5
|
+
<defs>
|
|
6
|
+
<clipPath id="clip0_329_14442">
|
|
7
|
+
<rect width="64" height="64" fill="white"/>
|
|
8
|
+
</clipPath>
|
|
9
|
+
</defs>
|
|
10
|
+
</svg>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@neon/skills",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.1.1",
|
|
4
4
|
"description": "Agent Skills for Neon: Lakebase Postgres, branching, Object Storage, Functions, and the AI Gateway",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
],
|
|
23
23
|
"files": [
|
|
24
24
|
"skills/",
|
|
25
|
+
"assets/",
|
|
25
26
|
"plugin.json",
|
|
26
27
|
"mcp.json"
|
|
27
28
|
],
|
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
|
|
3
3
|
"name": "neon-postgres",
|
|
4
|
-
"version": "2.
|
|
4
|
+
"version": "2.1.1",
|
|
5
5
|
"description": "Manage your Neon backend with the Neon agent skills and the Neon MCP Server: Lakebase Postgres, branching, Object Storage, Functions, and the AI Gateway",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "Neon",
|
|
@@ -10,5 +10,30 @@
|
|
|
10
10
|
"homepage": "https://neon.com",
|
|
11
11
|
"repository": "https://github.com/neondatabase/agent-skills",
|
|
12
12
|
"license": "Apache-2.0",
|
|
13
|
-
"keywords": ["neon", "lakebase", "postgres", "serverless", "database", "mcp"]
|
|
13
|
+
"keywords": ["neon", "lakebase", "postgres", "serverless", "database", "mcp"],
|
|
14
|
+
"extensions": {
|
|
15
|
+
"com.openai": {
|
|
16
|
+
"interface": {
|
|
17
|
+
"displayName": "Neon",
|
|
18
|
+
"shortDescription": "Manage your Neon backend",
|
|
19
|
+
"longDescription": "Manage Neon projects directly through ChatGPT. Run SQL and transactions on Lakebase Postgres, inspect and diff table schemas, apply migrations on a temporary branch before committing them, and provision Auth and the Data API. Create copy-on-write branches for isolated work, query logs from Serverless Functions and Object Storage for debugging, tune slow queries, and search Neon docs all through natural language commands. Connect with OAuth. During authorization, choose read-only or full access. Always review and authorize actions before execution.",
|
|
20
|
+
"developerName": "Neon (A Databricks, Inc. company)",
|
|
21
|
+
"category": "Developer Tools",
|
|
22
|
+
"capabilities": ["Read", "Write"],
|
|
23
|
+
"websiteURL": "https://neon.com",
|
|
24
|
+
"supportURL": "https://neon.com/docs/introduction/support",
|
|
25
|
+
"privacyPolicyURL": "https://neon.com/privacy-policy",
|
|
26
|
+
"termsOfServiceURL": "https://neon.com/platform-terms",
|
|
27
|
+
"defaultPrompt": [
|
|
28
|
+
"Create a Neon database and add Neon Auth to my application.",
|
|
29
|
+
"Deploy a Neon Function that uses Neon Object Storage.",
|
|
30
|
+
"Add AI to my application with the Neon AI Gateway."
|
|
31
|
+
],
|
|
32
|
+
"composerIcon": "./assets/neon-logomark-light.svg",
|
|
33
|
+
"composerIconDark": "./assets/neon-logomark-dark.svg",
|
|
34
|
+
"logo": "./assets/neon-logomark-light.svg",
|
|
35
|
+
"logoDark": "./assets/neon-logomark-dark.svg"
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
14
39
|
}
|
package/skills/neon/SKILL.md
CHANGED
|
@@ -43,21 +43,21 @@ Object Storage, Functions, and AI Gateway are currently available on projects in
|
|
|
43
43
|
|
|
44
44
|
## Architecture: How to Use Neon
|
|
45
45
|
|
|
46
|
-
|
|
46
|
+
**Recommended: full-stack app with Neon as the backend.** Default to Next.js on Vercel (or Netlify, Cloudflare, or other app platforms). Prefer Next.js + Vercel first; TanStack Start, Nuxt, and SvelteKit are full-stack alternatives. The app owns its UI and server. Query Lakebase Postgres from route handlers, server functions, or Neon Functions.
|
|
47
47
|
|
|
48
|
-
Neon
|
|
48
|
+
Add [Neon Functions](https://neon.com/docs/compute/functions/overview.md) as a backend layer between the web app and Lakebase Postgres, Object Storage, Auth, and AI Gateway. A Hono API on Functions can expose endpoints with an OpenAPI specification for the web app and other clients (mobile, desktop). You can also add a Function for one job next to the data: Object Storage uploads, AI agents, Discord bots, WebSocket or SSE servers.
|
|
49
49
|
|
|
50
|
-
|
|
50
|
+
Functions support long-running requests that complement the web app. A Function must start returning a response within 15 minutes. WebSocket connections and HTTP streams stay open while data flows; send at least one byte every 15 minutes to keep a quiet stream alive. See [runtime limits](https://neon.com/docs/compute/functions/reference/runtime-limits.md).
|
|
51
51
|
|
|
52
|
-
|
|
52
|
+
For long agent or image streams, mint a JWT on the app server and have the client call the Function directly. See the `neon-functions` skill for authentication and runtime limits.
|
|
53
53
|
|
|
54
|
-
**
|
|
54
|
+
**Second best: client-only app with a Functions backend.** Host the SPA on Vercel (or Netlify, Cloudflare, or other app platforms) and call Functions from the browser. For an app using PostgREST or a `supabase-js` database client, prefer migrating database calls to REST endpoints in a Hono Function that queries Lakebase Postgres. Enforce authorization in the Function instead of relying on browser-facing RLS.
|
|
55
55
|
|
|
56
|
-
|
|
56
|
+
Neon provides backend primitives that compose with the app host. Neon does not host the frontend.
|
|
57
57
|
|
|
58
|
-
|
|
58
|
+
Offer the Data API only as a Supabase / PostgREST migration path when an existing PostgREST or `supabase-js` database client must keep working. Putting PostgREST in the browser and relying on RLS is easy to get wrong: misconfigured policies expose the database to the client. Do not recommend this for new apps. An installed Supabase package used only for Auth or Storage does not establish a database-client dependency. Route generic REST endpoint requests to a Function or existing app handler.
|
|
59
59
|
|
|
60
|
-
|
|
60
|
+
Functions have public HTTPS URLs. Verify a JWT or API key at the top of the handler and enforce authorization before accessing data. See the `neon-functions` skill.
|
|
61
61
|
|
|
62
62
|
## Convert an app onto Neon
|
|
63
63
|
|
|
@@ -194,25 +194,27 @@ Then inspect credentials without printing secrets. `NEON_API_KEY` or a `neon pro
|
|
|
194
194
|
|
|
195
195
|
### Combined setup: `neon init`
|
|
196
196
|
|
|
197
|
-
When both agent tooling and project setup are needed, use authenticated `neon init`. `--agent` takes the coding-agent name. `-y` skips prompts but does not supply project selection or credentials.
|
|
197
|
+
When both agent tooling and project setup are needed, use authenticated `neon init`. It sets up the current directory in place. `--agent` takes the coding-agent name. `-y` skips prompts but does not supply project selection or credentials.
|
|
198
198
|
|
|
199
199
|
Link an existing project:
|
|
200
200
|
|
|
201
201
|
```bash
|
|
202
|
-
neon init --
|
|
202
|
+
neon init --agent cursor \
|
|
203
203
|
--org-id <org-id> --project-id <project-id> -y
|
|
204
204
|
```
|
|
205
205
|
|
|
206
206
|
Create and link a project:
|
|
207
207
|
|
|
208
208
|
```bash
|
|
209
|
-
neon init --
|
|
209
|
+
neon init --agent cursor \
|
|
210
210
|
--org-id <org-id> --project-name my-app \
|
|
211
211
|
--region-id aws-us-east-2 -y
|
|
212
212
|
```
|
|
213
213
|
|
|
214
214
|
`--services` may declare `auth`, `data-api`, `functions`, `object-storage`, and `ai-gateway` (repeat the flag or comma-separate). Pass `none` for the bare starter policy. It writes `neon.ts`; it does not deploy or wire the app. Selecting `data-api` also declares Auth (the default Data API provider requires it). Use `data-api` only for PostgREST / Supabase database-client compatibility.
|
|
215
215
|
|
|
216
|
+
With `-y`, `init` installs the Neon plugin globally where the agent supports it (its MCP server signs in with OAuth). Other agents get skills and the MCP server globally, with an API key when the CLI is signed in. `--mcp-auth` and `--mcp-config-location` change the MCP setup; see `neon init --help`.
|
|
217
|
+
|
|
216
218
|
If `init` already installed the Neon plugin, do not also run `neon mcp` and `neon skills` for the same agent.
|
|
217
219
|
|
|
218
220
|
When tooling already exists, only one component is missing, or env writes need `--no-env-pull`, use the manual steps below. `init` has no `--no-env-pull`. Before a command that pulls env, inspect existing configuration. If a supplied `DATABASE_URL` or `AWS_*` value must stay, pass `--no-env-pull` on `link` / `checkout` and write env to a separate `--file`.
|
|
@@ -223,11 +225,21 @@ Use the install check above. Do not run `neon login` unattended. MCP remains the
|
|
|
223
225
|
|
|
224
226
|
### 2. Install the Neon MCP Server
|
|
225
227
|
|
|
228
|
+
Install globally, the CLI default. One install serves every project:
|
|
229
|
+
|
|
230
|
+
```bash
|
|
231
|
+
neon mcp --agent <agent> -y
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
This writes an API key into the agent's user config, reusing an existing Neon MCP key or minting one (needs `neon auth` or a personal API key). Always pass `--agent`; without it, `-y` writes to every installed agent.
|
|
235
|
+
|
|
236
|
+
Add `--oauth` to store only the server URL instead; the user signs in from the agent and picks scopes on the consent page. For a project-level install, always use OAuth so no key lands in a file git can commit:
|
|
237
|
+
|
|
226
238
|
```bash
|
|
227
|
-
neon mcp --oauth --project --agent
|
|
239
|
+
neon mcp --oauth --project --agent <agent> -y
|
|
228
240
|
```
|
|
229
241
|
|
|
230
|
-
|
|
242
|
+
`neon mcp --help` lists the other flags (`--read-only`, `--project-id`, `--category`) and supported agents.
|
|
231
243
|
|
|
232
244
|
For all available plugins and IDE integrations, see: https://neon.com/docs/ai/ai-agents-tools.md
|
|
233
245
|
|
|
@@ -175,7 +175,7 @@ const { text } = await generateText({
|
|
|
175
175
|
});
|
|
176
176
|
```
|
|
177
177
|
|
|
178
|
-
For a full AI SDK agent deployed as a Neon Function (streaming, tool calling, image generation, persistence), see the `neon-functions` skill's
|
|
178
|
+
For a full AI SDK agent deployed as a Neon Function (streaming, tool calling, image generation, persistence), see the `neon-functions` skill's [references/ai-sdk.md](https://neon.com/docs/ai/skills/neon-functions/references/ai-sdk.md).
|
|
179
179
|
|
|
180
180
|
## Build Agents with Mastra (Recommended)
|
|
181
181
|
|
|
@@ -13,8 +13,9 @@ description: >-
|
|
|
13
13
|
"streaming agent", "SSE server", "WebSocket server", "webhook handler",
|
|
14
14
|
"MCP server", "cron", "function trigger", "scheduled function", "cron job",
|
|
15
15
|
"object storage trigger", "on upload", "run code next to my database",
|
|
16
|
-
"function that won't time out", "function logs", "Neon Functions",
|
|
17
|
-
"Neon Compute"
|
|
16
|
+
"function that won't time out", "function logs", "Neon Functions",
|
|
17
|
+
"Neon Compute", "DDoS protection", "rate limiting", and
|
|
18
|
+
"production hardening".
|
|
18
19
|
metadata:
|
|
19
20
|
parent: neon
|
|
20
21
|
source: https://github.com/neondatabase/agent-skills/tree/main/skills/neon-functions
|
|
@@ -46,7 +47,7 @@ Reach for Neon Functions when the workload is a request/response handler that be
|
|
|
46
47
|
- **A backend that branches with your data.** Each branch runs its own version of the function at its own URL, against its own isolated database (and storage, and gateway) state. Preview deployments, CI, and dev environments each get a self-contained backend — deploying to a child never affects the parent.
|
|
47
48
|
- **Query Postgres from the Function (or an existing framework handler).** Prefer that over the Data API. Use the Data API when the application already uses PostgREST or Supabase-js database calls, or is migrating that client.
|
|
48
49
|
- **Webhooks, bots, and post-response work.** Webhook handlers that fan out into multiple DB writes, Discord/WebSocket bots, and fire-and-forget follow-ups via `waitUntil` (analytics, audit logs) all fit.
|
|
49
|
-
- **Recurring HTTP work.** A Function Trigger POSTs to the function on a cron (`type: "schedule"`). Same `fetch` handler, same 15-minute time-to-first-byte limit. See [Function Triggers](#function-triggers).
|
|
50
|
+
- **Recurring HTTP work.** A Function Trigger POSTs to the function on a cron (`type: "schedule"`) or when an object is created in Object Storage (`type: "storage_object_created"`). Same `fetch` handler, same 15-minute time-to-first-byte limit. See [Function Triggers](#function-triggers).
|
|
50
51
|
|
|
51
52
|
If the workload is a pure static site, or something that must run outside the supported regions (`aws-us-east-2`, `aws-us-east-1`, `aws-eu-central-1`, and `aws-ap-southeast-1`) today, this isn't the right tool yet (see [Timeouts and Runtime Limits](#timeouts-and-runtime-limits) and [Availability](#availability)).
|
|
52
53
|
|
|
@@ -57,7 +58,7 @@ If the workload is a pure static site, or something that must run outside the su
|
|
|
57
58
|
- **Close to your database** — Runs in the branch's region; `DATABASE_URL` injected automatically when the branch has Postgres.
|
|
58
59
|
- **Branchable** — Each branch runs its own function version at its own URL against its own isolated state.
|
|
59
60
|
- **Same CLI/API** — Deploy and manage via `neon`, `neon.ts`, or the Neon API.
|
|
60
|
-
- **Function Triggers** — Neon POSTs to the function on a cron. See [Function Triggers](#function-triggers).
|
|
61
|
+
- **Function Triggers** — Neon POSTs to the function on a cron or an object-storage upload. See [Function Triggers](#function-triggers).
|
|
61
62
|
|
|
62
63
|
## Availability
|
|
63
64
|
|
|
@@ -67,13 +68,19 @@ Check this precondition before setting anything up: Neon Functions is currently
|
|
|
67
68
|
|
|
68
69
|
Neon (Functions included) is **backend primitives, not full-stack app hosting**. Host your app on **Vercel** (or Netlify, or another frontend/app host); Functions are the long-running, stateful slice of your backend that lives next to your data. They compose with that platform in two ways:
|
|
69
70
|
|
|
70
|
-
- **Add a Function to a full-stack app.** Your Next.js / TanStack Start app on Vercel (or Netlify) owns UI, auth (Managed Auth, Better Auth, Clerk, or another IdP), and talks directly to Lakebase Postgres and Object Storage.
|
|
71
|
+
- **Add a Function to a full-stack app.** Your Next.js / TanStack Start app on Vercel (or Netlify) owns UI, auth (Managed Auth, Better Auth, Clerk, or another IdP), and talks directly to Lakebase Postgres and Object Storage. Add a Function as a Hono API layer for the web app and other clients, or for one job next to the data: Object Storage uploads, AI agents, Discord bots, WebSocket or SSE servers. (See [Functions as an Agent Backend](#functions-as-an-agent-backend-nextjs-and-similar-frameworks) for the client-direct pattern.)
|
|
71
72
|
- **Run the whole backend control plane on Functions.** Especially when the frontend is **client-only** — TanStack Router, React Router in client mode, and similar SPAs hosted on Vercel or Netlify — the client calls Functions **directly**. Build REST APIs and request/response agents, host **MCP servers**, and run anything stateful or that belongs close to Postgres and Object Storage.
|
|
72
73
|
|
|
73
|
-
Either way,
|
|
74
|
+
Either way, authenticate by caller: JWT or API key for app and public HTTP (see the WARNING under [Functions as an Agent Backend](#functions-as-an-agent-backend-nextjs-and-similar-frameworks)); `parseTriggerDelivery` for Function Trigger routes; production hardening in [Production hardening](references/production-hardening.md). Because a Function is just your backend, you can **move pieces between your host and Neon** — relocate an agent or a stateful WebSocket server onto a Function when it needs more runtime, and back if needed.
|
|
74
75
|
|
|
75
76
|
Prefer a Function, or an existing framework handler, that queries Postgres. Use Data API when the application already uses PostgREST/Supabase-js database calls or is migrating that client.
|
|
76
77
|
|
|
78
|
+
## Production hardening
|
|
79
|
+
|
|
80
|
+
Before exposing production routes, read [Production hardening](references/production-hardening.md).
|
|
81
|
+
|
|
82
|
+
Pick by caller: trusted app server, Function Trigger, or public consumer. Keep long browser streams on the client-direct JWT path unless a verified streaming-compatible proxy is required. Authentication rejects application work; requests to the native URL still reach the Function.
|
|
83
|
+
|
|
77
84
|
## Setup
|
|
78
85
|
|
|
79
86
|
Functions are declared in `neon.ts` (see the `neon` skill for the branch-first workflow and `neon.ts` basics). Add `@neon/config` and declare functions under `functions`, keyed by **slug**:
|
|
@@ -147,6 +154,16 @@ To deploy a single function without applying `neon.ts`: `neon functions deploy <
|
|
|
147
154
|
|
|
148
155
|
When `neon checkout` _creates_ a new branch and a `neon.ts` is present, it applies the policy automatically. Pass `--env <file>` on that create so Function env that reads `process.env` resolves (`neon checkout feat --create --env .env.local`). Existing process env wins over the file. Checking out an existing branch never reconciles it — apply config changes with `neon deploy --env <file>` (add `--update-existing` only after reviewing those changes).
|
|
149
156
|
|
|
157
|
+
### Native binaries and custom builds
|
|
158
|
+
|
|
159
|
+
The default deploy bundles `source` into one `index.mjs`, which cannot hold a compiled binary. Ship one as a separate archive file:
|
|
160
|
+
|
|
161
|
+
- npm package with a Node addon (`sharp`): `externalPackages: ["sharp"]`. The deploy installs its linux-arm64 glibc build and copies the files in.
|
|
162
|
+
- Your own build output (`.node`, `.so`, `.wasm`, data files): `bundler: "none"` with a prebuilt directory, or an inline `bundler: async (fn) => ({ "index.mjs": …, "bin/tool": … })`.
|
|
163
|
+
- A standalone executable you spawn: ship it as above, then copy it to `/run` and `chmod 755` it at startup. Files in `/opt/function` arrive as mode `644` on a read-only filesystem, and `/tmp` is `noexec`.
|
|
164
|
+
|
|
165
|
+
Runtime target, pros and cons, working snippets, and size limits: [references/native-binaries.md](references/native-binaries.md).
|
|
166
|
+
|
|
150
167
|
## Neon Infrastructure as Code (`neon.ts`)
|
|
151
168
|
|
|
152
169
|
The `functions` block from [Setup](#setup) is part of `neon.ts`, Neon's infrastructure-as-code file — one TypeScript file declares every function (its `source`, display `name`, and `env`) alongside any other branch services, in version control (see the `neon` skill for the full reference). Treat it like Terraform for your branch:
|
|
@@ -244,7 +261,7 @@ Functions are long-running but **still serverless** — they are a request/respo
|
|
|
244
261
|
|
|
245
262
|
## Functions as an Agent Backend (Next.js and Similar Frameworks)
|
|
246
263
|
|
|
247
|
-
A Neon Function is a great home for an AI agent precisely because it **doesn't time out** the way lambda-style serverless does (15-minute budget, see [Timeouts and Runtime Limits](#timeouts-and-runtime-limits)).
|
|
264
|
+
A Neon Function is a great home for an AI agent precisely because it **doesn't time out** the way lambda-style serverless does (15-minute budget, see [Timeouts and Runtime Limits](#timeouts-and-runtime-limits)). Proxying that stream through a Next.js route handler, Remix/SvelteKit/Nuxt action, or similar hosted on Vercel, Netlify, and the like **cuts the stream when it exceeds that host's configured duration or transport limits**, even though the Function would keep going. Keep the client-direct JWT path below as the default. A streaming-compatible proxy (HTTP-triggered Cloudflare Worker, after you verify the stream) is the public-consumer exception in [Production hardening](references/production-hardening.md).
|
|
248
265
|
|
|
249
266
|
**Building the agent itself.** The [Vercel AI SDK](https://ai-sdk.dev) and [Mastra](https://mastra.ai) are the recommended ways to build the agent — point either at the Neon AI Gateway (see the `neon-ai-gateway` skill) for one credential across every model, with no extra provider keys. For a complete AI SDK agent running as a Function (streaming `toUIMessageStreamResponse`, multi-step tool calling next to Postgres, and persisting generated images to Object Storage), see [references/ai-sdk.md](https://neon.com/docs/ai/skills/neon-functions/references/ai-sdk.md); for the Mastra equivalent with built-in tracing, see [references/mastra-studio.md](https://neon.com/docs/ai/skills/neon-functions/references/mastra-studio.md).
|
|
250
267
|
|
|
@@ -264,7 +281,7 @@ Browser ──▶ your app backend ──▶ Neon Function
|
|
|
264
281
|
- Add **CORS** so the browser can reach it (handle `OPTIONS`, set `Access-Control-Allow-Origin`/`-Headers`).
|
|
265
282
|
|
|
266
283
|
> [!WARNING]
|
|
267
|
-
> A Neon Function has a **public HTTPS URL — it is reachable by anyone.** A direct client→function call means there is no app backend in front of it to gate access, so **you must authenticate the function yourself.** Verify a JWT against the caller's JWKS, check a shared secret / API key, or reject the request. Never deploy an unauthenticated agent.
|
|
284
|
+
> A Neon Function has a **public HTTPS URL — it is reachable by anyone.** A direct client→function call means there is no app backend in front of it to gate access, so **you must authenticate the function yourself.** Verify a JWT against the caller's JWKS, check a shared secret / API key, or reject the request. Never deploy an unauthenticated agent. Browser callers use short-lived user tokens. Server or proxy origin secrets (`X-Secret`) stay server-side; see [Production hardening](references/production-hardening.md).
|
|
268
285
|
|
|
269
286
|
```typescript
|
|
270
287
|
// src/index.ts — verify the caller before doing any work
|
|
@@ -592,9 +609,9 @@ The same rules as WebSockets apply. **Heartbeat:** a stream stays open only whil
|
|
|
592
609
|
|
|
593
610
|
## Function Triggers
|
|
594
611
|
|
|
595
|
-
A Function Trigger POSTs JSON to your function on a cron. Declare it in `neon.ts`, apply with `neon deploy`, and authenticate the delivery with `
|
|
612
|
+
A Function Trigger POSTs JSON to your function on a cron (`schedule`) or when an object is created in Object Storage (`storage_object_created`). Declare it in `neon.ts`, apply with `neon deploy`, and authenticate the delivery with `parseTriggerDelivery` (`@neon/functions/triggers`). `parseTrigger` (Hono) and `parseTriggerInvocation` stay schedule-only. Prefer `neon.ts`; CLI and the Neon MCP trigger tools (`list_triggers`, `create_trigger`, …) are the backup.
|
|
596
613
|
|
|
597
|
-
Full field list, CLI, MCP, payload, inheritance, and both handler shapes: [references/function-triggers.md](references/function-triggers.md).
|
|
614
|
+
Trigger routes must not require a user JWT or `X-Secret`; Neon POSTs to the native URL without those. Production caller shapes: [references/production-hardening.md](references/production-hardening.md). Full field list, CLI, MCP, payload, inheritance, and both handler shapes: [references/function-triggers.md](references/function-triggers.md).
|
|
598
615
|
|
|
599
616
|
## MCP Servers
|
|
600
617
|
|
|
@@ -610,7 +627,7 @@ app.all("/mcp", async (c) => {
|
|
|
610
627
|
});
|
|
611
628
|
```
|
|
612
629
|
|
|
613
|
-
Because the function's URL is public, **authenticate before connecting the transport** — [Better Auth](https://better-auth.com) covers both OAuth (its MCP plugin makes your app the authorization server so third-party clients self-authorize per the MCP spec) and a simpler API-key / session-JWT check for your own callers. [references/mcp.md](https://neon.com/docs/ai/skills/neon-functions/references/mcp.md) has the full pattern — server with Postgres-backed tools via Drizzle, both Better Auth auth options, and testing with `mcporter` / `add-mcp`.
|
|
630
|
+
Because the function's URL is public, **authenticate before connecting the transport** — [Better Auth](https://better-auth.com) covers both OAuth (its MCP plugin makes your app the authorization server so third-party clients self-authorize per the MCP spec) and a simpler API-key / session-JWT check for your own callers. Public-consumer edge protection: [references/production-hardening.md](references/production-hardening.md). [references/mcp.md](https://neon.com/docs/ai/skills/neon-functions/references/mcp.md) has the full pattern — server with Postgres-backed tools via Drizzle, both Better Auth auth options, and testing with `mcporter` / `add-mcp`.
|
|
614
631
|
|
|
615
632
|
## Integrations and Observability
|
|
616
633
|
|
|
@@ -641,5 +658,9 @@ The Neon documentation is the source of truth and Functions is evolving rapidly,
|
|
|
641
658
|
- https://neon.com/docs/compute/functions/environment-variables.md
|
|
642
659
|
- https://neon.com/docs/compute/functions/reference/neon-ts.md
|
|
643
660
|
- https://neon.com/docs/compute/functions/reference/runtime-limits.md
|
|
661
|
+
- https://neon.com/docs/compute/functions/authentication.md
|
|
662
|
+
- https://neon.com/docs/compute/functions/custom-domains.md
|
|
644
663
|
- https://neon.com/docs/cli/triggers.md
|
|
645
664
|
- [references/function-triggers.md](references/function-triggers.md)
|
|
665
|
+
- [references/native-binaries.md](references/native-binaries.md)
|
|
666
|
+
- [references/production-hardening.md](references/production-hardening.md)
|
|
@@ -111,6 +111,8 @@ The Neon MCP server (`?category=functions`) exposes `list_triggers`, `get_trigge
|
|
|
111
111
|
|
|
112
112
|
Neon POSTs JSON. The Functions proxy drops client-supplied `x-neon-*` headers, so a present `x-neon-trigger-invocation-id` is from a trigger delivery. It must match `invocation_id` in the body.
|
|
113
113
|
|
|
114
|
+
A Function that also serves app or public HTTP must not apply JWT or `X-Secret` middleware to the trigger path. Neon trigger POSTs do not send those. Caller shapes: [production-hardening.md](production-hardening.md).
|
|
115
|
+
|
|
114
116
|
Schedule wire JSON (snake_case):
|
|
115
117
|
|
|
116
118
|
```json
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
# Shipping native binaries with a Function
|
|
2
|
+
|
|
3
|
+
The default deploy bundles `source` into a single `index.mjs` with esbuild. A compiled binary cannot be inlined into that file, so it has to ship as a separate file in the deploy archive. There are three ways to put it there. Pick by what the binary is:
|
|
4
|
+
|
|
5
|
+
| The binary is | Use |
|
|
6
|
+
| ------------------------------------------------------------------------------------------ | -------------------------------------------------------------- |
|
|
7
|
+
| An npm package backed by a Node-API addon (`sharp`, most `@napi-rs/*` packages) | [`externalPackages`](#externalpackages-npm-packages-with-a-node-addon) |
|
|
8
|
+
| A file your own build step produces: a `.node` addon, a `.so`, a `.wasm`, model weights | [`bundler: "none"`](#bundler-none-ship-a-prebuilt-directory) or a [custom `bundler`](#custom-bundler-return-the-file-map) |
|
|
9
|
+
| A standalone executable you spawn (`ffmpeg`, a Go or Rust CLI) | A custom `bundler` or `"none"`, plus [a copy to `/run` at startup](#standalone-executables) |
|
|
10
|
+
|
|
11
|
+
The examples use top-level `functions`, which needs `neon` CLI 4.20 or newer and `@neon/config` 1.6 or newer.
|
|
12
|
+
|
|
13
|
+
## The runtime a binary lands on
|
|
14
|
+
|
|
15
|
+
- **linux, arm64, glibc**, Node.js 24. A binary built for macOS or x64 cannot load there.
|
|
16
|
+
- The archive is extracted to `/opt/function`, a read-only filesystem. `import.meta.url` in the root `index.mjs` points there, so `new URL("./bin/tool", import.meta.url)` resolves to `/opt/function/bin/tool`.
|
|
17
|
+
- **Every file arrives with mode `644`.** Unix permission bits in the zip are dropped on extraction, and `chmod` in place fails with `EROFS`. A `.node` or `.so` loads fine (it is `dlopen`ed, not executed). Spawning a file from `/opt/function` fails with `EACCES`.
|
|
18
|
+
- `/tmp` is writable and mounted `noexec`: a copied binary still fails with `EACCES` after `chmod 755`.
|
|
19
|
+
- `/run` is a writable tmpfs that allows exec (about 990 MiB, backed by the function's 2048 MiB of memory).
|
|
20
|
+
|
|
21
|
+
The filesystem layout is observed behavior, not documented by Neon. Re-check it if spawning starts failing.
|
|
22
|
+
|
|
23
|
+
## `externalPackages`: npm packages with a Node addon
|
|
24
|
+
|
|
25
|
+
```typescript
|
|
26
|
+
// neon.ts
|
|
27
|
+
import { defineConfig } from "@neon/config/v1";
|
|
28
|
+
|
|
29
|
+
export default defineConfig({
|
|
30
|
+
functions: {
|
|
31
|
+
resize: {
|
|
32
|
+
name: "Resize",
|
|
33
|
+
source: "./src/resize.ts",
|
|
34
|
+
externalPackages: ["sharp"],
|
|
35
|
+
},
|
|
36
|
+
},
|
|
37
|
+
});
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
esbuild leaves `import sharp from "sharp"` unresolved. At deploy, the CLI installs the version of `sharp` from your project with `npm install --cpu=arm64 --os=linux --libc=glibc --ignore-scripts` into a temp directory, traces the files it reaches with `@vercel/nft`, and copies them into the archive under `node_modules/` with the tree layout intact. Only the installed version is read from your `node_modules`; the shipped files come from the temp install, and your `node_modules` is not modified.
|
|
41
|
+
|
|
42
|
+
The deploy fails with a named error when:
|
|
43
|
+
|
|
44
|
+
- the package is not installed in your project (no version to pin)
|
|
45
|
+
- the declared package itself does not install for linux-arm64 glibc (`EBADPLATFORM`)
|
|
46
|
+
- a staged `.node` or `.so` is not an AArch64 ELF binary
|
|
47
|
+
- `npm` is not on `PATH`
|
|
48
|
+
- the archive exceeds the [size limits](#size-limits)
|
|
49
|
+
|
|
50
|
+
It does not fail when a platform-specific optional dependency is silently skipped, or when a package that compiles from source at install time ships no binary (the staging install runs with `--ignore-scripts`). Those deploy and then fail at invoke. Use packages that publish a linux-arm64 glibc prebuild (`sharp` does), and invoke the deployed function once to confirm the addon loads.
|
|
51
|
+
|
|
52
|
+
A deploy and `neon dev` print an advisory warning for any bundled package that carries native code and is not declared. A package with a working JavaScript fallback (`ws` with `bufferutil`) triggers it too and needs no change. Do not silence it with `{ name, includeFiles: false }`: that externalizes the package and ships nothing, so a reached import throws `Cannot find module` on every invoke. `includeFiles: false` is only for an import the function never evaluates.
|
|
53
|
+
|
|
54
|
+
Under `neon dev`, the package is only kept out of the bundle and resolves from your own `node_modules` for your host.
|
|
55
|
+
|
|
56
|
+
Pros: one line in `neon.ts`; the target-platform install, file tracing, arch check, and size check are automatic; local dev uses your host build.
|
|
57
|
+
|
|
58
|
+
Cons: only for npm packages that publish a linux-arm64 glibc prebuild; transitive pins, overrides, and patches from your lockfile are not carried into the staged install; esbuild bundler only (`externalPackages` with `bundler: "none"` or a function fails validation).
|
|
59
|
+
|
|
60
|
+
## `bundler: "none"`: ship a prebuilt directory
|
|
61
|
+
|
|
62
|
+
Run your own build, then point `source` at its output. The directory root must contain `index.mjs` or `index.js`. Everything else in the directory ships as-is:
|
|
63
|
+
|
|
64
|
+
```text
|
|
65
|
+
dist/fn/
|
|
66
|
+
index.mjs # built by your step, reads ./native/addon.node
|
|
67
|
+
native/addon.node
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
```typescript
|
|
71
|
+
// neon.ts
|
|
72
|
+
import { defineConfig } from "@neon/config/v1";
|
|
73
|
+
|
|
74
|
+
export default defineConfig({
|
|
75
|
+
functions: {
|
|
76
|
+
api: { name: "API", source: "./dist/fn", bundler: "none" },
|
|
77
|
+
},
|
|
78
|
+
});
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
npm run build:fn && neon deploy --env .env.local
|
|
83
|
+
neon functions deploy api --src dist/fn --no-bundle # same thing, without neon.ts
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
`neon deploy` does not run your build step. Run it first, or use a [custom `bundler`](#custom-bundler-return-the-file-map) to keep the build inside `neon deploy`.
|
|
87
|
+
|
|
88
|
+
Pros: works with any build tool or framework output (`.mastra/output` is the common one); full control over the archive layout.
|
|
89
|
+
|
|
90
|
+
Cons: no architecture check, so a binary built for your laptop deploys and then fails at invoke; the build step is yours to keep in sync with `neon deploy`; TypeScript cannot ship unbundled.
|
|
91
|
+
|
|
92
|
+
## Custom `bundler`: return the file map
|
|
93
|
+
|
|
94
|
+
An inline function in `neon.ts` returns archive paths mapped to bytes. `neon deploy` zips the map, and `neon dev` serves the same map locally:
|
|
95
|
+
|
|
96
|
+
```typescript
|
|
97
|
+
// neon.ts
|
|
98
|
+
import { readFile } from "node:fs/promises";
|
|
99
|
+
import { build } from "esbuild";
|
|
100
|
+
import { defineConfig } from "@neon/config/v1";
|
|
101
|
+
|
|
102
|
+
export default defineConfig({
|
|
103
|
+
functions: {
|
|
104
|
+
transcode: {
|
|
105
|
+
name: "Transcode",
|
|
106
|
+
source: "./src/transcode.ts",
|
|
107
|
+
bundler: async (fn) => {
|
|
108
|
+
const out = await build({
|
|
109
|
+
entryPoints: [fn.source],
|
|
110
|
+
bundle: true,
|
|
111
|
+
platform: "node",
|
|
112
|
+
format: "esm",
|
|
113
|
+
write: false,
|
|
114
|
+
outfile: "index.mjs",
|
|
115
|
+
// CommonJS dependencies call require(); ESM output has none in scope.
|
|
116
|
+
banner: {
|
|
117
|
+
js: "import{createRequire}from'module';const require=createRequire(import.meta.url);",
|
|
118
|
+
},
|
|
119
|
+
});
|
|
120
|
+
return {
|
|
121
|
+
"index.mjs": out.outputFiles[0].contents,
|
|
122
|
+
"bin/ffmpeg": new Uint8Array(
|
|
123
|
+
await readFile(new URL("./vendor/linux-arm64/ffmpeg", import.meta.url)),
|
|
124
|
+
),
|
|
125
|
+
};
|
|
126
|
+
},
|
|
127
|
+
},
|
|
128
|
+
},
|
|
129
|
+
});
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
`esbuild` must be a dependency of your project. The map needs `index.mjs` or `index.js` at the root.
|
|
133
|
+
|
|
134
|
+
Pros: the build lives in `neon.ts`, so `neon deploy` and `neon dev` always build the same thing; any file from anywhere can go in the archive.
|
|
135
|
+
|
|
136
|
+
Cons: no architecture check; `externalPackages` cannot be combined with it, so an npm addon has to be copied into the map by hand, with its `node_modules/` layout.
|
|
137
|
+
|
|
138
|
+
## Standalone executables
|
|
139
|
+
|
|
140
|
+
Ship the executable with a custom `bundler` or `bundler: "none"`, then copy it to `/run` and mark it executable once per isolate:
|
|
141
|
+
|
|
142
|
+
```typescript
|
|
143
|
+
// src/transcode.ts
|
|
144
|
+
import { execFile } from "node:child_process";
|
|
145
|
+
import { chmod, copyFile, mkdir } from "node:fs/promises";
|
|
146
|
+
import { promisify } from "node:util";
|
|
147
|
+
|
|
148
|
+
const run = promisify(execFile);
|
|
149
|
+
|
|
150
|
+
let ffmpeg: Promise<string> | undefined;
|
|
151
|
+
function ffmpegPath(): Promise<string> {
|
|
152
|
+
if (process.env.FFMPEG_PATH) return Promise.resolve(process.env.FFMPEG_PATH);
|
|
153
|
+
ffmpeg ??= (async () => {
|
|
154
|
+
await mkdir("/run/bin", { recursive: true });
|
|
155
|
+
await copyFile(new URL("./bin/ffmpeg", import.meta.url), "/run/bin/ffmpeg");
|
|
156
|
+
await chmod("/run/bin/ffmpeg", 0o755);
|
|
157
|
+
return "/run/bin/ffmpeg";
|
|
158
|
+
})();
|
|
159
|
+
return ffmpeg;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export default {
|
|
163
|
+
async fetch() {
|
|
164
|
+
const { stdout } = await run(await ffmpegPath(), ["-version"]);
|
|
165
|
+
return new Response(stdout);
|
|
166
|
+
},
|
|
167
|
+
};
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
`neon dev` runs this code on your machine, where `/run` may not exist and a linux-arm64 binary cannot execute. Point it at a host install from the shell, and leave `FFMPEG_PATH` out of the function's deployed `env`:
|
|
171
|
+
|
|
172
|
+
```bash
|
|
173
|
+
FFMPEG_PATH="$(command -v ffmpeg)" neon dev
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
The binary must be statically linked, or its shared libraries must exist in the runtime image. The copy costs memory: `/run` is RAM-backed and counts against the function's 2048 MiB.
|
|
177
|
+
|
|
178
|
+
## Size limits
|
|
179
|
+
|
|
180
|
+
`bundler: "none"`, a custom `bundler`, and `externalPackages` staging check the archive before upload:
|
|
181
|
+
|
|
182
|
+
| Limit | Value |
|
|
183
|
+
| ------------------------ | ------- |
|
|
184
|
+
| Compressed zip | 10 MiB |
|
|
185
|
+
| Total uncompressed bytes | 64 MiB |
|
|
186
|
+
| Files in the archive | 4,096 |
|
|
187
|
+
|
|
188
|
+
Exceeding one fails the deploy. The byte-limit errors list the four largest files. Check an executable's size before building around it: a single static binary can use most of the 64 MiB.
|
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
# Production hardening for Neon Functions
|
|
2
|
+
|
|
3
|
+
A Function has a public HTTPS URL. Authenticate the caller, then pick extra
|
|
4
|
+
protection from who actually calls it. This file is the production path; JWT
|
|
5
|
+
and trigger parsers stay in [SKILL.md](../SKILL.md) and
|
|
6
|
+
[function-triggers.md](function-triggers.md).
|
|
7
|
+
|
|
8
|
+
https://neon.com/docs/compute/functions/authentication.md
|
|
9
|
+
|
|
10
|
+
## Choose the caller shape
|
|
11
|
+
|
|
12
|
+
Pick a row before writing code. Mixed routes: apply the matching row per
|
|
13
|
+
path, not one middleware for the whole Function.
|
|
14
|
+
|
|
15
|
+
| Caller | What to do | Do not |
|
|
16
|
+
| ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
|
|
17
|
+
| Trusted app server (Vercel/Netlify route, server action, queue worker) that finishes within that host's duration | The server calls the Function. Browser never sees the Function URL or the origin secret. Function returns 401 before any work. | Put the secret in client code. Proxy a long agent, WebSocket, or SSE stream through the app host without checking that host's duration. |
|
|
18
|
+
| Function Triggers only | `parseTriggerDelivery` (both types). Keep this path outside JWT and `X-Secret` middleware. | Require a user JWT or `X-Secret` on the trigger path. Invent `x-neon-invocation-id`. Treat `invocation_id` as a secret. |
|
|
19
|
+
| Public consumers (Open API, MCP, third-party HTTP) | A Cloudflare Worker Custom Domain you own, **not** registered as a Neon custom domain, proxies to the native invocation URL, sets `X-Secret`, and rate-limits at the edge. Function requires `X-Secret`, then the route's existing consumer auth. | Orange-cloud a Neon-registered custom-domain CNAME. Assume the native URL is closed. Put a human challenge in front of MCP. |
|
|
20
|
+
|
|
21
|
+
Browser-direct JWT agents stay on the client-direct path in SKILL.md. They
|
|
22
|
+
are not the trusted-app-server row.
|
|
23
|
+
|
|
24
|
+
## Native URL
|
|
25
|
+
|
|
26
|
+
The native invocation URL stays reachable after you add a custom domain or a
|
|
27
|
+
Worker. Application checks reject work; the request still occupies a Function
|
|
28
|
+
invocation until the handler returns.
|
|
29
|
+
|
|
30
|
+
Neon also enforces a default account-wide cap of 100 concurrent invocations
|
|
31
|
+
(`429`, body `per-account concurrency limit reached`, `Retry-After` in
|
|
32
|
+
seconds). That is not per-client DDoS protection.
|
|
33
|
+
https://neon.com/docs/compute/functions/reference/runtime-limits.md
|
|
34
|
+
|
|
35
|
+
Functions docs do not document a customer-configurable WAF, a switch to
|
|
36
|
+
disable the native URL, or a Functions ingress IP allowlist. Do not invent
|
|
37
|
+
those.
|
|
38
|
+
|
|
39
|
+
## Trusted app server
|
|
40
|
+
|
|
41
|
+
Keep the Function URL and origin secret in **server** env on the app host and
|
|
42
|
+
in Function `env`. Authenticate the app route first. Then `fetch` the
|
|
43
|
+
Function.
|
|
44
|
+
|
|
45
|
+
Headers:
|
|
46
|
+
|
|
47
|
+
```text
|
|
48
|
+
X-Secret: <server-only origin secret>
|
|
49
|
+
Authorization: <existing consumer credential, unchanged>
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
`X-Secret` is application-defined. Use it for the server hop when
|
|
53
|
+
`Authorization` already carries a user or consumer bearer token.
|
|
54
|
+
|
|
55
|
+
If the Function currently only checks `Authorization: Bearer <API_KEY>` and
|
|
56
|
+
nothing forwards a user token, keep that check. Do not migrate that header.
|
|
57
|
+
|
|
58
|
+
Compare `X-Secret` before parsing the body or touching Postgres. Missing
|
|
59
|
+
`ORIGIN_SECRET` fails at startup. Do not add CORS if browsers must not call
|
|
60
|
+
this Function.
|
|
61
|
+
|
|
62
|
+
```typescript
|
|
63
|
+
import { timingSafeEqual } from "node:crypto";
|
|
64
|
+
|
|
65
|
+
const originSecret = process.env.ORIGIN_SECRET;
|
|
66
|
+
if (!originSecret) throw new Error("ORIGIN_SECRET is required");
|
|
67
|
+
const expected = Buffer.from(originSecret);
|
|
68
|
+
|
|
69
|
+
function hasOriginSecret(request: Request): boolean {
|
|
70
|
+
const header = request.headers.get("x-secret");
|
|
71
|
+
if (header === null) return false;
|
|
72
|
+
const provided = Buffer.from(header);
|
|
73
|
+
if (provided.byteLength !== expected.byteLength) return false;
|
|
74
|
+
return timingSafeEqual(provided, expected);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export default {
|
|
78
|
+
async fetch(request: Request): Promise<Response> {
|
|
79
|
+
if (!hasOriginSecret(request)) {
|
|
80
|
+
return new Response("Unauthorized", { status: 401 });
|
|
81
|
+
}
|
|
82
|
+
return Response.json({ ok: true });
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Declare `ORIGIN_SECRET` in `neon.ts` `env` and on the app host.
|
|
88
|
+
|
|
89
|
+
Buffer the incoming body on the app-server `fetch`. Node `fetch` throws
|
|
90
|
+
`duplex option is required when sending a body` if you pass a streamed
|
|
91
|
+
`request.body`. `duplex: "half"` is Node-only; this hop is short, so
|
|
92
|
+
buffer instead. `redirect: "manual"` keeps `X-Secret` from following a
|
|
93
|
+
cross-origin redirect.
|
|
94
|
+
|
|
95
|
+
`NEON_FUNCTION_URL` is `invocation_url` from `neon functions get`. It ends
|
|
96
|
+
with `/`. This example calls that root. For a Function path, concatenate
|
|
97
|
+
onto that slash (`new URL("orders?limit=2", functionUrl)`). Do not copy the
|
|
98
|
+
app request's host or pathname onto the Function; a Next.js `/api/...` route
|
|
99
|
+
is not the Function path.
|
|
100
|
+
|
|
101
|
+
```typescript
|
|
102
|
+
const functionUrl = process.env.NEON_FUNCTION_URL;
|
|
103
|
+
const originSecret = process.env.ORIGIN_SECRET;
|
|
104
|
+
if (!functionUrl || !originSecret) {
|
|
105
|
+
throw new Error("NEON_FUNCTION_URL and ORIGIN_SECRET are required");
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const headers = new Headers({ "x-secret": originSecret });
|
|
109
|
+
const contentType = request.headers.get("content-type");
|
|
110
|
+
if (contentType) headers.set("content-type", contentType);
|
|
111
|
+
const authorization = request.headers.get("authorization");
|
|
112
|
+
if (authorization) headers.set("authorization", authorization);
|
|
113
|
+
|
|
114
|
+
return fetch(functionUrl, {
|
|
115
|
+
method: request.method,
|
|
116
|
+
headers,
|
|
117
|
+
body: request.body ? await request.arrayBuffer() : undefined,
|
|
118
|
+
redirect: "manual",
|
|
119
|
+
});
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
## Function Triggers only
|
|
123
|
+
|
|
124
|
+
Use the parsers in [function-triggers.md](function-triggers.md).
|
|
125
|
+
`parseTriggerDelivery` covers `schedule` and `storage_object_created`.
|
|
126
|
+
Hono `parseTrigger` and `parseTriggerInvocation` are schedule-only.
|
|
127
|
+
|
|
128
|
+
Neon POSTs to the native URL and does not send `X-Secret` or a user JWT. A
|
|
129
|
+
trigger path that requires those credentials drops real deliveries.
|
|
130
|
+
|
|
131
|
+
`invocation_id` is a correlation id. Presence of `x-neon-trigger-invocation-id`
|
|
132
|
+
after Neon strips client `x-neon-*` headers is the provenance check; matching
|
|
133
|
+
the body is consistency. https://neon.com/docs/compute/functions/triggers/overview.md
|
|
134
|
+
|
|
135
|
+
Local `neon dev` can send that header to simulate a tick. On the deployed
|
|
136
|
+
Function a client-supplied `x-neon-*` header is stripped.
|
|
137
|
+
|
|
138
|
+
## Public consumers through a Worker
|
|
139
|
+
|
|
140
|
+
Consumers call a hostname you control. Volumetric filtering happens there.
|
|
141
|
+
The Function still authenticates.
|
|
142
|
+
|
|
143
|
+
DNS:
|
|
144
|
+
|
|
145
|
+
- A Neon Function custom-domain CNAME must be DNS-only (grey cloud). A proxied
|
|
146
|
+
(orange-cloud) record blocks Neon domain validation.
|
|
147
|
+
https://neon.com/docs/compute/functions/custom-domains.md
|
|
148
|
+
- Attach a [Cloudflare Worker Custom Domain](https://developers.cloudflare.com/workers/configuration/routing/custom-domains/)
|
|
149
|
+
that is **not** registered with Neon. The Worker fetches the **native**
|
|
150
|
+
invocation URL.
|
|
151
|
+
|
|
152
|
+
Worker:
|
|
153
|
+
|
|
154
|
+
- Preserve method, pathname, query, body, and consumer `Authorization`.
|
|
155
|
+
- Set `X-Secret`. Do not use it as the consumer credential.
|
|
156
|
+
- Build the upstream URL from a fixed origin. Assign `pathname` and `search`
|
|
157
|
+
separately so a request path cannot change the authority.
|
|
158
|
+
- Apply Cloudflare DDoS / WAF / rate-limiting rules on that Worker hostname.
|
|
159
|
+
The forwarding snippet does not configure those rules.
|
|
160
|
+
- Disable the Worker's `workers.dev` route and Preview URLs. Hostname-scoped
|
|
161
|
+
rules do not apply to those endpoints, and they still run this forwarding
|
|
162
|
+
code. Inventory clients on those URLs first.
|
|
163
|
+
https://developers.cloudflare.com/workers/configuration/routing/workers-dev.md
|
|
164
|
+
Dashboard: Worker → Settings → Domains & Routes. A later Wrangler deploy
|
|
165
|
+
without `workers_dev: false` turns `workers.dev` back on.
|
|
166
|
+
- Do not buffer a streaming body. Do not add a browser challenge MCP or API
|
|
167
|
+
clients cannot pass.
|
|
168
|
+
|
|
169
|
+
Wrangler:
|
|
170
|
+
|
|
171
|
+
```jsonc
|
|
172
|
+
{
|
|
173
|
+
"workers_dev": false,
|
|
174
|
+
"preview_urls": false
|
|
175
|
+
}
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
```typescript
|
|
179
|
+
const FUNCTION_ORIGIN = "https://<invocation-host>"; // neon functions get
|
|
180
|
+
|
|
181
|
+
export default {
|
|
182
|
+
async fetch(
|
|
183
|
+
request: Request,
|
|
184
|
+
env: { ORIGIN_SECRET: string },
|
|
185
|
+
): Promise<Response> {
|
|
186
|
+
const incoming = new URL(request.url);
|
|
187
|
+
const upstream = new URL(FUNCTION_ORIGIN);
|
|
188
|
+
upstream.pathname = incoming.pathname;
|
|
189
|
+
upstream.search = incoming.search;
|
|
190
|
+
|
|
191
|
+
const headers = new Headers(request.headers);
|
|
192
|
+
headers.set("x-secret", env.ORIGIN_SECRET);
|
|
193
|
+
headers.delete("host");
|
|
194
|
+
|
|
195
|
+
return fetch(upstream, {
|
|
196
|
+
method: request.method,
|
|
197
|
+
headers,
|
|
198
|
+
body: request.body,
|
|
199
|
+
redirect: "manual",
|
|
200
|
+
});
|
|
201
|
+
},
|
|
202
|
+
};
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
Function: require `X-Secret` first (same helper as above), then apply **that
|
|
206
|
+
route's existing** consumer authentication. Browser preflight, OAuth
|
|
207
|
+
discovery, and intentionally public routes keep their current behavior. An
|
|
208
|
+
origin secret is not a user API key.
|
|
209
|
+
|
|
210
|
+
Requiring `X-Secret` on the native URL is a migration. Move legitimate
|
|
211
|
+
native-URL clients to the Worker first. Anyone who still hits the native URL
|
|
212
|
+
without the secret gets 401 after the request has reached Function compute.
|
|
213
|
+
|
|
214
|
+
HTTP-triggered Workers have no documented hard wall-clock duration while the
|
|
215
|
+
client stays connected. Still verify WebSocket, SSE, and long agent streams
|
|
216
|
+
against the chosen Worker before using this row for those workloads. If the
|
|
217
|
+
edge cannot hold the stream, keep client-direct JWT.
|
|
218
|
+
|
|
219
|
+
MCP: after switching consumers to the Worker hostname, confirm advertised
|
|
220
|
+
resource URLs, token audiences, existing client registrations, and one live
|
|
221
|
+
session as well as a fresh authorization. https://developers.cloudflare.com/workers/platform/limits/
|
|
222
|
+
|
|
223
|
+
## Limit authenticated application work
|
|
224
|
+
|
|
225
|
+
Edge rate limiting drops traffic before Neon. A limiter **inside** the
|
|
226
|
+
Function runs after the request arrived. Use it to cap expensive work for a
|
|
227
|
+
**verified** principal (user id, org id, API-key hash). Never use a
|
|
228
|
+
caller-supplied id. A global budget can cap total capacity; one caller can
|
|
229
|
+
consume it for everyone.
|
|
230
|
+
|
|
231
|
+
Request-rate limits do not cap simultaneous long-running work. Bound in-flight
|
|
232
|
+
expensive operations separately, in a shared store, not in module-scope
|
|
233
|
+
counters (those are per-isolate and vanish on eviction).
|
|
234
|
+
|
|
235
|
+
A query to Postgres on every anonymous request adds database work to a flood.
|
|
236
|
+
Postgres can hold per-principal counters at low-to-moderate authenticated
|
|
237
|
+
volume when you already have it; measure before relying on it. Prefer Redis
|
|
238
|
+
or edge limits when a database round trip per request is too expensive.
|
|
239
|
+
|
|
240
|
+
Optional Upstash quota after credential checks, before expensive work.
|
|
241
|
+
`60` per minute and `timeout: 1_000` are example policy. `RATE_LIMIT_PREFIX`
|
|
242
|
+
is the application + environment + quota name; `NEON_BRANCH` (a branch
|
|
243
|
+
**name**) is appended so branches do not share counters.
|
|
244
|
+
|
|
245
|
+
`Redis.fromEnv()` reads `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`.
|
|
246
|
+
Upstash `reset` is milliseconds since epoch. Upstash can report a timeout as
|
|
247
|
+
a successful `limit()` result; check `reason` before `success`. Await the
|
|
248
|
+
admission decision; pass `pending` to `waitUntil` so background writes do not
|
|
249
|
+
delay the response.
|
|
250
|
+
|
|
251
|
+
```typescript
|
|
252
|
+
import { waitUntil } from "@neon/functions";
|
|
253
|
+
import { Ratelimit } from "@upstash/ratelimit";
|
|
254
|
+
import { Redis } from "@upstash/redis";
|
|
255
|
+
|
|
256
|
+
const namespace = process.env.RATE_LIMIT_PREFIX;
|
|
257
|
+
if (!namespace) throw new Error("RATE_LIMIT_PREFIX is required");
|
|
258
|
+
|
|
259
|
+
const limiter = new Ratelimit({
|
|
260
|
+
redis: Redis.fromEnv(),
|
|
261
|
+
limiter: Ratelimit.slidingWindow(60, "1 m"),
|
|
262
|
+
prefix: `${namespace}:${process.env.NEON_BRANCH ?? "local"}`,
|
|
263
|
+
timeout: 1_000,
|
|
264
|
+
analytics: false,
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
export async function checkQuota(
|
|
268
|
+
authenticatedPrincipalId: string,
|
|
269
|
+
): Promise<Response | null> {
|
|
270
|
+
let result: Awaited<ReturnType<typeof limiter.limit>>;
|
|
271
|
+
try {
|
|
272
|
+
result = await limiter.limit(authenticatedPrincipalId);
|
|
273
|
+
} catch (error) {
|
|
274
|
+
console.error("Rate-limit store failed", error);
|
|
275
|
+
return new Response("Rate limiter unavailable", {
|
|
276
|
+
status: 503,
|
|
277
|
+
headers: { "Retry-After": "1" },
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
waitUntil(result.pending);
|
|
282
|
+
|
|
283
|
+
if (result.reason === "timeout") {
|
|
284
|
+
console.error("Rate-limit store timed out");
|
|
285
|
+
return new Response("Rate limiter unavailable", {
|
|
286
|
+
status: 503,
|
|
287
|
+
headers: { "Retry-After": "1" },
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
if (result.success) return null;
|
|
292
|
+
|
|
293
|
+
const retryAfterSeconds = Math.max(
|
|
294
|
+
1,
|
|
295
|
+
Math.ceil((result.reset - Date.now()) / 1000),
|
|
296
|
+
);
|
|
297
|
+
return new Response("Too Many Requests", {
|
|
298
|
+
status: 429,
|
|
299
|
+
headers: {
|
|
300
|
+
"Retry-After": String(retryAfterSeconds),
|
|
301
|
+
"RateLimit-Limit": String(result.limit),
|
|
302
|
+
"RateLimit-Remaining": String(result.remaining),
|
|
303
|
+
"RateLimit-Reset": String(retryAfterSeconds),
|
|
304
|
+
},
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
Preserve CORS headers on these responses when the route already sets them.
|
|
310
|
+
Do not relabel limiter failures as `401` or as quota exhaustion. `Retry-After`
|
|
311
|
+
is required on `429`. `RateLimit-*` is optional metadata; `RateLimit-Reset`
|
|
312
|
+
here is seconds until the window renews.
|
|
313
|
+
|
|
314
|
+
Do not rate-limit in the Function by `X-Forwarded-For`. That header is not a
|
|
315
|
+
documented trustworthy client-IP on Functions. IP limits belong at the edge.
|
|
316
|
+
|
|
317
|
+
## Preserve existing clients
|
|
318
|
+
|
|
319
|
+
- Direct-client JWT agents keep their token, JWKS, issuer, and audience.
|
|
320
|
+
Do not require `X-Secret` on those routes.
|
|
321
|
+
- CORS still has to succeed for legitimate browser origins, including on
|
|
322
|
+
401/429. CORS is not authentication.
|
|
323
|
+
- Inventory production and preview origins before tightening an allowlist.
|
|
324
|
+
- WebSocket and SSE handshake, heartbeat, and reconnect stay as documented
|
|
325
|
+
in SKILL.md.
|
|
326
|
+
- MCP OAuth discovery, tokens, methods, and streaming stay as documented in
|
|
327
|
+
[mcp.md](mcp.md). Authenticate before the transport.
|
|
328
|
+
- Adding a Worker does not by itself change the API's consumer credentials.
|
|
329
|
+
- Stored rows stay authorized by the verified identity, not by a quota key.
|
|
330
|
+
|
|
331
|
+
## Reject these
|
|
332
|
+
|
|
333
|
+
- Orange-cloud proxying a **Neon-registered** custom-domain CNAME.
|
|
334
|
+
- Shipping a server origin secret to the browser.
|
|
335
|
+
- Putting a long stream behind a host or Worker whose duration or transport
|
|
336
|
+
cannot hold it.
|
|
337
|
+
- Treating header/body equality as trigger provenance outside Neon's edge.
|
|
338
|
+
- In-memory counters as a cross-isolate quota.
|
|
339
|
+
- A Postgres lookup on every anonymous request as DDoS protection.
|
|
340
|
+
- Treating a native-URL `401` as traffic blocked before Function compute.
|
|
@@ -260,6 +260,7 @@ Use Lakebase Search for semantic, full-text, and hybrid search:
|
|
|
260
260
|
- For semantic search, read [Vector search](references/vector-search.md).
|
|
261
261
|
- For full-text search with BM25 ranking, read [Full-text search](references/full-text-search.md).
|
|
262
262
|
- For combining semantic and lexical results, read [Hybrid search](references/hybrid-search.md).
|
|
263
|
+
- For managing any of the above through Drizzle ORM, read [Managing Lakebase Search with Drizzle](references/lakebase-search-drizzle.md).
|
|
263
264
|
|
|
264
265
|
Links:
|
|
265
266
|
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
# Managing Lakebase Search with Drizzle
|
|
2
|
+
|
|
3
|
+
When the user wants Lakebase Search managed through Drizzle, treat the SQL in [Vector Search](vector-search.md), [Full-Text Search](full-text-search.md), and [Hybrid Search](hybrid-search.md) as the source of truth and apply it as below. Use Drizzle for all schema and migration management unless the user says otherwise.
|
|
4
|
+
|
|
5
|
+
Requires `drizzle-orm` 0.36+ and `drizzle-kit` 0.27+: the schema below returns its indexes as an array from the `pgTable` extra-config callback. Those versions also include generated-column support for the `tsvector` column, the custom-method `.using(...).op(...)` index API for `lakebase_ann`, the `vector` column type, and the `cosineDistance` helper.
|
|
6
|
+
|
|
7
|
+
Contents:
|
|
8
|
+
|
|
9
|
+
- [Config](#config): `drizzle.config.ts` and the migration connection
|
|
10
|
+
- [Extensions](#extensions): custom migration required to create extensions (Drizzle can't)
|
|
11
|
+
- [Schema](#schema): columns, generated `tsvector`, and the ANN index
|
|
12
|
+
- [BM25 Index](#bm25-index): created after the corpus is seeded
|
|
13
|
+
- [Query](#query): vector, BM25, and hybrid reads
|
|
14
|
+
- [Tune Per Query](#tune-per-query): per-query GUCs
|
|
15
|
+
|
|
16
|
+
Rules:
|
|
17
|
+
|
|
18
|
+
- Express everything Drizzle can in `schema.ts`: the columns, the generated `tsvector`, and the `lakebase_ann` index. Only `CREATE EXTENSION` and the post-seed `lakebase_bm25` index need custom migrations.
|
|
19
|
+
- Use `drizzle-kit generate` then `migrate`. Never run `drizzle-kit push` (it reconciles the database to `schema.ts`, so it drops the post-seed `lakebase_bm25` index and any other object not declared there)
|
|
20
|
+
- Run every migration over the direct (unpooled) connection.
|
|
21
|
+
- The extension must exist before the `vector` column and the `lakebase_ann` index that depend on it.
|
|
22
|
+
|
|
23
|
+
## Config
|
|
24
|
+
|
|
25
|
+
`drizzle-kit generate` and `migrate` read `drizzle.config.ts`. Point `dbCredentials.url` at the **direct (unpooled)** connection string:
|
|
26
|
+
|
|
27
|
+
```typescript
|
|
28
|
+
// drizzle.config.ts
|
|
29
|
+
import { defineConfig } from "drizzle-kit";
|
|
30
|
+
|
|
31
|
+
export default defineConfig({
|
|
32
|
+
schema: "./src/schema.ts",
|
|
33
|
+
out: "./drizzle",
|
|
34
|
+
dialect: "postgresql",
|
|
35
|
+
// Direct (unpooled) URL. Neon exposes it as DATABASE_URL_UNPOOLED.
|
|
36
|
+
dbCredentials: { url: process.env.DATABASE_URL_UNPOOLED },
|
|
37
|
+
});
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Extensions
|
|
41
|
+
|
|
42
|
+
Drizzle cannot express `CREATE EXTENSION`, and the `vector` column and `lakebase_ann` index below depend on `lakebase_vector`, so generate a custom migration for the extensions **first** so it runs before the schema migration:
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
npx drizzle-kit generate --custom --name=lakebase_extensions
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
```sql
|
|
49
|
+
-- drizzle/0000_lakebase_extensions.sql
|
|
50
|
+
CREATE EXTENSION IF NOT EXISTS lakebase_vector CASCADE;
|
|
51
|
+
CREATE EXTENSION IF NOT EXISTS lakebase_text;
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Schema
|
|
55
|
+
|
|
56
|
+
The columns, the generated `tsvector`, and the `lakebase_ann` index all go in `schema.ts`. `tsvector` has no built-in Drizzle type, so define it using the `customType`:
|
|
57
|
+
|
|
58
|
+
```typescript
|
|
59
|
+
// src/schema.ts
|
|
60
|
+
import { pgTable, bigint, text, vector, index, customType } from "drizzle-orm/pg-core";
|
|
61
|
+
import { sql } from "drizzle-orm";
|
|
62
|
+
|
|
63
|
+
const tsvector = customType<{ data: string }>({
|
|
64
|
+
dataType() {
|
|
65
|
+
return "tsvector";
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
export const documents = pgTable(
|
|
70
|
+
"documents",
|
|
71
|
+
{
|
|
72
|
+
id: bigint("id", { mode: "number" }).generatedByDefaultAsIdentity().primaryKey(),
|
|
73
|
+
title: text("title").notNull(),
|
|
74
|
+
body: text("body").notNull(),
|
|
75
|
+
embedding: vector("embedding", { dimensions: 1536 }),
|
|
76
|
+
bodyTsv: tsvector("body_tsv").generatedAlwaysAs(
|
|
77
|
+
sql`to_tsvector('english', "body")`,
|
|
78
|
+
),
|
|
79
|
+
},
|
|
80
|
+
(table) => [
|
|
81
|
+
index("documents_embedding_ann").using(
|
|
82
|
+
"lakebase_ann",
|
|
83
|
+
table.embedding.op("vector_cosine_ops"),
|
|
84
|
+
),
|
|
85
|
+
],
|
|
86
|
+
);
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Set the dimension to match your embedding model. Postgres maintains `body_tsv`, so never write it from the app. Generate and apply the migration after the extensions migration above:
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
npx drizzle-kit generate --name=lakebase_search
|
|
93
|
+
npx drizzle-kit migrate
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## BM25 Index
|
|
97
|
+
|
|
98
|
+
Keep the `lakebase_bm25` index out of `schema.ts`. It must be built only after the initial corpus is loaded, so its build-time statistics are meaningful (see [Full-text search](full-text-search.md)) — a schema migration would build it against an empty table. Add it in a later custom migration that runs after seeding:
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
npx drizzle-kit generate --custom --name=bm25_index
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
```sql
|
|
105
|
+
-- drizzle/NNNN_bm25_index.sql, applied after the corpus is seeded
|
|
106
|
+
CREATE INDEX documents_body_bm25 ON documents USING lakebase_bm25 (body_tsv);
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## Query
|
|
110
|
+
|
|
111
|
+
Use the query builder with Drizzle's `cosineDistance` helper for vector search. It emits the `<=>` operator, so keep the index on `vector_cosine_ops`:
|
|
112
|
+
|
|
113
|
+
```typescript
|
|
114
|
+
import { cosineDistance } from "drizzle-orm";
|
|
115
|
+
import { documents } from "./schema";
|
|
116
|
+
|
|
117
|
+
// queryEmbedding: number[] from the same model used for stored documents
|
|
118
|
+
const distance = cosineDistance(documents.embedding, queryEmbedding);
|
|
119
|
+
|
|
120
|
+
const rows = await db
|
|
121
|
+
.select({ id: documents.id, title: documents.title, distance })
|
|
122
|
+
.from(documents)
|
|
123
|
+
.orderBy(distance)
|
|
124
|
+
.limit(k);
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
BM25 has no Drizzle helper: `<@>` and `to_bm25query` require raw SQL. Reference the generated column by its `body_tsv` name. Bind user input as parameters through the `sql` template:
|
|
128
|
+
|
|
129
|
+
```typescript
|
|
130
|
+
import { sql } from "drizzle-orm";
|
|
131
|
+
|
|
132
|
+
const rows = await db.execute(sql`
|
|
133
|
+
SELECT id, title,
|
|
134
|
+
body_tsv <@> to_bm25query(
|
|
135
|
+
to_tsvector('english', ${queryText}),
|
|
136
|
+
'documents_body_bm25'::regclass
|
|
137
|
+
) AS score
|
|
138
|
+
FROM documents
|
|
139
|
+
ORDER BY score
|
|
140
|
+
LIMIT ${k}
|
|
141
|
+
`);
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
Run the [hybrid search](hybrid-search.md) RRF query the same way: raw SQL through `db.execute`.
|
|
145
|
+
|
|
146
|
+
## Tune Per Query
|
|
147
|
+
|
|
148
|
+
Per-query GUCs (`lakebase_ann.probes`, `lakebase_ann.epsilon`, `lakebase_bm25.default_limit`, `lakebase_bm25.prefilter`) must be set with `SET LOCAL` inside a transaction so they apply to the same pooled connection as the query:
|
|
149
|
+
|
|
150
|
+
```typescript
|
|
151
|
+
import { cosineDistance, sql } from "drizzle-orm";
|
|
152
|
+
import { documents } from "./schema";
|
|
153
|
+
|
|
154
|
+
const distance = cosineDistance(documents.embedding, queryEmbedding);
|
|
155
|
+
|
|
156
|
+
const rows = await db.transaction(async (tx) => {
|
|
157
|
+
// SET LOCAL scopes the GUC to this transaction's connection; do not hoist it out.
|
|
158
|
+
// Keep probes at 'auto' unless an IVF `lists` layout exists: a numeric value must
|
|
159
|
+
// match the `lists` shape or it errors ("need 0 probes ..."). See vector-search.md.
|
|
160
|
+
await tx.execute(sql`SET LOCAL lakebase_ann.probes = 'auto'`);
|
|
161
|
+
return tx
|
|
162
|
+
.select({ id: documents.id, title: documents.title, distance })
|
|
163
|
+
.from(documents)
|
|
164
|
+
.orderBy(distance)
|
|
165
|
+
.limit(k);
|
|
166
|
+
});
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
Sources:
|
|
170
|
+
|
|
171
|
+
- [Get started with Lakebase Search](https://neon.com/docs/ai/lakebase-search-get-started)
|
|
172
|
+
- [Schema migration with Lakebase Postgres and Drizzle ORM](https://neon.com/docs/guides/drizzle-migrations)
|
|
@@ -127,7 +127,7 @@ Schema-only branching is in Beta. If users report unexpected behavior, errors, o
|
|
|
127
127
|
1. Ask them to share feedback in the Neon Console:
|
|
128
128
|
- https://console.neon.tech/app/projects?modal=feedback
|
|
129
129
|
2. Recommend opening a support conversation in the Neon Discord:
|
|
130
|
-
- https://
|
|
130
|
+
- https://neon.com/discord
|
|
131
131
|
|
|
132
132
|
## Reset from Parent
|
|
133
133
|
|
|
@@ -282,7 +282,7 @@ Common CI/CD use cases for Neon branches:
|
|
|
282
282
|
- `neon branches create --name compliance-dev --parent main --schema-only --project-id <your-project-id> --expires-at 2026-12-15T18:02:16Z`
|
|
283
283
|
5. Mention Beta support path:
|
|
284
284
|
- https://console.neon.tech/app/projects?modal=feedback
|
|
285
|
-
- https://
|
|
285
|
+
- https://neon.com/discord
|
|
286
286
|
|
|
287
287
|
## Further Reading
|
|
288
288
|
|