neon-testing 2.6.2 → 3.0.0-beta.0
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/README.md +87 -41
- package/package.json +49 -39
- package/src/bun.ts +13 -0
- package/src/core.ts +372 -0
- package/src/lib/barrier.ts +22 -0
- package/src/lib/expires-in.ts +24 -0
- package/src/lib/singleton.ts +10 -0
- package/src/lib/ssl.ts +24 -0
- package/src/lib/with-retry.ts +55 -0
- package/src/lib/ws-error.ts +17 -0
- package/src/setup.ts +8 -0
- package/src/utils.ts +2 -0
- package/src/vitest.ts +12 -0
- package/dist/barrier.d.ts +0 -6
- package/dist/barrier.d.ts.map +0 -1
- package/dist/barrier.js +0 -19
- package/dist/barrier.js.map +0 -1
- package/dist/browser-empty.d.ts +0 -2
- package/dist/browser-empty.d.ts.map +0 -1
- package/dist/browser-empty.js +0 -4
- package/dist/browser-empty.js.map +0 -1
- package/dist/index.d.ts +0 -113
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js +0 -272
- package/dist/index.js.map +0 -1
- package/dist/singleton.d.ts +0 -5
- package/dist/singleton.d.ts.map +0 -1
- package/dist/singleton.js +0 -11
- package/dist/singleton.js.map +0 -1
- package/dist/utils.d.ts +0 -9
- package/dist/utils.d.ts.map +0 -1
- package/dist/utils.js +0 -9
- package/dist/utils.js.map +0 -1
- package/dist/vite-plugin.d.ts +0 -13
- package/dist/vite-plugin.d.ts.map +0 -1
- package/dist/vite-plugin.js +0 -26
- package/dist/vite-plugin.js.map +0 -1
- package/dist/vitest-setup.d.ts +0 -3
- package/dist/vitest-setup.d.ts.map +0 -1
- package/dist/vitest-setup.js +0 -10
- package/dist/vitest-setup.js.map +0 -1
package/src/core.ts
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* https://neon.com/docs/reference/typescript-sdk
|
|
3
|
+
*/
|
|
4
|
+
import {
|
|
5
|
+
createApiClient,
|
|
6
|
+
EndpointType,
|
|
7
|
+
type Branch,
|
|
8
|
+
} from "@neondatabase/api-client";
|
|
9
|
+
import { applySslMode } from "./lib/ssl";
|
|
10
|
+
import { validateExpiresIn } from "./lib/expires-in";
|
|
11
|
+
import { neonWsErrorHandler } from "./lib/ws-error";
|
|
12
|
+
import { withRetry } from "./lib/with-retry";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Test-runner lifecycle hooks
|
|
16
|
+
*
|
|
17
|
+
* Injected so the core stays runner-agnostic. Most users don't build these by
|
|
18
|
+
* hand — import the pre-wired factory from `neon-testing/vitest` or
|
|
19
|
+
* `neon-testing/bun`, which supply them automatically.
|
|
20
|
+
*/
|
|
21
|
+
export interface NeonTestingHooks {
|
|
22
|
+
beforeAll: (fn: () => void | Promise<void>) => void;
|
|
23
|
+
afterAll: (fn: () => void | Promise<void>) => void;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Configuration for the Neon test-branch factory.
|
|
28
|
+
*
|
|
29
|
+
* `hooks` are injected by the per-runner entry (`neon-testing/vitest` or
|
|
30
|
+
* `neon-testing/bun`); the remaining fields control how each test branch is
|
|
31
|
+
* created and torn down.
|
|
32
|
+
*/
|
|
33
|
+
export interface MakeNeonTestingCoreOptions {
|
|
34
|
+
/**
|
|
35
|
+
* Test-runner lifecycle hooks (supplied by `neon-testing/vitest` or
|
|
36
|
+
* `neon-testing/bun`)
|
|
37
|
+
*/
|
|
38
|
+
hooks: NeonTestingHooks;
|
|
39
|
+
/**
|
|
40
|
+
* The Neon API key, this is used to create and teardown test branches (required)
|
|
41
|
+
*
|
|
42
|
+
* https://neon.com/docs/manage/api-keys#creating-api-keys
|
|
43
|
+
*/
|
|
44
|
+
apiKey: string;
|
|
45
|
+
/**
|
|
46
|
+
* The Neon project ID to operate on (required)
|
|
47
|
+
*
|
|
48
|
+
* https://console.neon.tech/app/projects
|
|
49
|
+
*/
|
|
50
|
+
projectId: string;
|
|
51
|
+
/**
|
|
52
|
+
* The parent branch ID for the new branch (default: undefined)
|
|
53
|
+
*
|
|
54
|
+
* If omitted or undefined, test branches will be created from the project's
|
|
55
|
+
* default branch.
|
|
56
|
+
*/
|
|
57
|
+
parentBranchId?: string;
|
|
58
|
+
/**
|
|
59
|
+
* Whether to create a schema-only branch (default: false)
|
|
60
|
+
*/
|
|
61
|
+
schemaOnly?: boolean;
|
|
62
|
+
/**
|
|
63
|
+
* The type of connection to create (default: "pooler")
|
|
64
|
+
*/
|
|
65
|
+
endpoint?: "pooler" | "direct";
|
|
66
|
+
/**
|
|
67
|
+
* Delete the test branch in afterAll (default: true)
|
|
68
|
+
*
|
|
69
|
+
* Disabling this will leave each test branch in the Neon project after the
|
|
70
|
+
* test suite runs
|
|
71
|
+
*/
|
|
72
|
+
deleteBranch?: boolean;
|
|
73
|
+
/**
|
|
74
|
+
* Automatically close Neon WebSocket connections opened during tests before
|
|
75
|
+
* deleting the branch (default: false)
|
|
76
|
+
*
|
|
77
|
+
* Suppresses the specific Neon WebSocket "Connection terminated unexpectedly"
|
|
78
|
+
* error that may surface when deleting a branch with open WebSocket
|
|
79
|
+
* connections
|
|
80
|
+
*
|
|
81
|
+
* Vitest only — under Bun the uncaughtException suppression does not
|
|
82
|
+
* intercept, so close connections explicitly there instead.
|
|
83
|
+
*/
|
|
84
|
+
autoCloseWebSockets?: boolean;
|
|
85
|
+
/**
|
|
86
|
+
* Time in seconds until the branch expires and is automatically deleted
|
|
87
|
+
* (default: 600 = 10 minutes)
|
|
88
|
+
*
|
|
89
|
+
* This provides automatic cleanup for dangling branches from interrupted or
|
|
90
|
+
* failed test runs. Set to `null` to disable automatic expiration.
|
|
91
|
+
*
|
|
92
|
+
* Must be a positive integer. Maximum 30 days (2,592,000 seconds).
|
|
93
|
+
*
|
|
94
|
+
* https://neon.com/docs/guides/branch-expiration
|
|
95
|
+
*/
|
|
96
|
+
expiresIn?: number | null;
|
|
97
|
+
/**
|
|
98
|
+
* The database role to connect as (default: project owner role)
|
|
99
|
+
*
|
|
100
|
+
* The role must exist in the parent branch. Roles are automatically
|
|
101
|
+
* copied to test branches when branching.
|
|
102
|
+
*/
|
|
103
|
+
roleName?: string;
|
|
104
|
+
/**
|
|
105
|
+
* The database to connect to (default: project default database)
|
|
106
|
+
*/
|
|
107
|
+
databaseName?: string;
|
|
108
|
+
/**
|
|
109
|
+
* Override the `sslmode` query param on the connection URI (default:
|
|
110
|
+
* undefined — URI is passed through unchanged)
|
|
111
|
+
*
|
|
112
|
+
* Neon's API returns URIs with `sslmode=require`. In pg v9 the meaning of
|
|
113
|
+
* `require` changes to libpq semantics (encrypt, but don't verify the CA).
|
|
114
|
+
*
|
|
115
|
+
* - `"verify-full"` — strict CA verification (silences the pg v9 warning)
|
|
116
|
+
* - `"require"` — preserves today's effective behavior under pg v9 by also
|
|
117
|
+
* setting `uselibpqcompat=true`
|
|
118
|
+
*
|
|
119
|
+
* Only affects drivers that parse `sslmode` (e.g. `pg`). The Neon
|
|
120
|
+
* serverless driver ignores it.
|
|
121
|
+
*/
|
|
122
|
+
sslMode?: "verify-full" | "require";
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Options for the `makeNeonTesting` factories — core options minus the injected hooks */
|
|
126
|
+
export type MakeNeonTestingOptions = Omit<MakeNeonTestingCoreOptions, "hooks">;
|
|
127
|
+
|
|
128
|
+
/** Per-file overrides accepted by the returned `neonTesting()` function */
|
|
129
|
+
export type NeonTestingOptions = Partial<
|
|
130
|
+
Omit<MakeNeonTestingOptions, "apiKey">
|
|
131
|
+
>;
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Low-level factory that creates a Neon test-branch setup/teardown function.
|
|
135
|
+
* Runner-agnostic — you inject the lifecycle hooks via `options.hooks`.
|
|
136
|
+
*
|
|
137
|
+
* Most users want a pre-wired entry instead: `neon-testing/vitest` or
|
|
138
|
+
* `neon-testing/bun`. Reach for this core factory only for other runners
|
|
139
|
+
* (jest, node:test, …).
|
|
140
|
+
*
|
|
141
|
+
* @param factoryOptions - see {@link MakeNeonTestingCoreOptions}
|
|
142
|
+
* @returns A setup/teardown function with attached utilities:
|
|
143
|
+
* - `deleteAllTestBranches()` - delete all test branches
|
|
144
|
+
* - `api` - the Neon API client
|
|
145
|
+
*
|
|
146
|
+
* @example
|
|
147
|
+
* ```ts
|
|
148
|
+
* import { beforeAll, afterAll } from "vitest"; // or any runner
|
|
149
|
+
* import { makeNeonTestingCore } from "neon-testing/core";
|
|
150
|
+
*
|
|
151
|
+
* export const neonTesting = makeNeonTestingCore({
|
|
152
|
+
* apiKey: process.env.NEON_API_KEY!,
|
|
153
|
+
* projectId: process.env.NEON_PROJECT_ID!,
|
|
154
|
+
* hooks: { beforeAll, afterAll },
|
|
155
|
+
* });
|
|
156
|
+
* ```
|
|
157
|
+
*/
|
|
158
|
+
export function makeNeonTestingCore(
|
|
159
|
+
factoryOptions: MakeNeonTestingCoreOptions,
|
|
160
|
+
) {
|
|
161
|
+
// Validate factory options
|
|
162
|
+
validateExpiresIn(factoryOptions.expiresIn);
|
|
163
|
+
|
|
164
|
+
const apiClient = createApiClient({ apiKey: factoryOptions.apiKey });
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Delete all test branches (branches with the "integration-test: true" annotation)
|
|
168
|
+
*/
|
|
169
|
+
async function deleteAllTestBranches() {
|
|
170
|
+
const { data } = await apiClient.listProjectBranches({
|
|
171
|
+
projectId: factoryOptions.projectId,
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
for (const branch of data.branches) {
|
|
175
|
+
const isTestBranch =
|
|
176
|
+
data.annotations[branch.id]?.value["integration-test"] === "true";
|
|
177
|
+
|
|
178
|
+
if (isTestBranch) {
|
|
179
|
+
await apiClient.deleteProjectBranch(
|
|
180
|
+
factoryOptions.projectId,
|
|
181
|
+
branch.id,
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Setup/teardown function for a test file.
|
|
189
|
+
*
|
|
190
|
+
* Registers lifecycle hooks (via the injected `hooks`) that:
|
|
191
|
+
* - Create an isolated test branch from your parent branch
|
|
192
|
+
* - Set `DATABASE_URL` environment variable to the test branch connection URI
|
|
193
|
+
* - Automatically delete the test branch after tests complete (unless `deleteBranch: false`)
|
|
194
|
+
* - Automatically expire branches after 10 minutes for cleanup (unless `expiresIn: null`)
|
|
195
|
+
*
|
|
196
|
+
* @param overrides - Optional per-file overrides for the factory options
|
|
197
|
+
* @returns A function that provides access to the current Neon branch object
|
|
198
|
+
*/
|
|
199
|
+
const neonTesting = (
|
|
200
|
+
/** Override any factory options except apiKey */
|
|
201
|
+
overrides?: NeonTestingOptions,
|
|
202
|
+
) => {
|
|
203
|
+
// Validate overrides
|
|
204
|
+
if (overrides?.expiresIn !== undefined) {
|
|
205
|
+
validateExpiresIn(overrides.expiresIn);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// Merge factory options with overrides
|
|
209
|
+
const options = { ...factoryOptions, ...overrides };
|
|
210
|
+
|
|
211
|
+
// Each test file gets its own branch and database client
|
|
212
|
+
let branch: Branch | undefined;
|
|
213
|
+
|
|
214
|
+
// List of tracked Neon WebSocket connections
|
|
215
|
+
// Lazily initialized when autoCloseWebSockets is enabled (avoids
|
|
216
|
+
// referencing the WebSocket global on runtimes that lack it, e.g. Node 20)
|
|
217
|
+
let neonSockets: Set<WebSocket> | undefined;
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Create a new test branch
|
|
221
|
+
*
|
|
222
|
+
* @returns The connection URI for the new branch
|
|
223
|
+
*/
|
|
224
|
+
async function createBranch() {
|
|
225
|
+
// Calculate expiration timestamp if expiresIn is set
|
|
226
|
+
const expiresIn =
|
|
227
|
+
options.expiresIn === undefined ? 600 : options.expiresIn; // Default: 10 minutes
|
|
228
|
+
|
|
229
|
+
const expiresAt =
|
|
230
|
+
expiresIn !== null
|
|
231
|
+
? new Date(Date.now() + expiresIn * 1000).toISOString()
|
|
232
|
+
: undefined;
|
|
233
|
+
|
|
234
|
+
const { data } = await apiClient.createProjectBranch(options.projectId, {
|
|
235
|
+
branch: {
|
|
236
|
+
name: `test/${crypto.randomUUID()}`,
|
|
237
|
+
...(options.parentBranchId
|
|
238
|
+
? { parent_id: options.parentBranchId }
|
|
239
|
+
: {}),
|
|
240
|
+
...(options.schemaOnly ? { init_source: "schema-only" } : {}),
|
|
241
|
+
...(expiresAt ? { expires_at: expiresAt } : {}),
|
|
242
|
+
},
|
|
243
|
+
endpoints: [{ type: EndpointType.ReadWrite }],
|
|
244
|
+
annotation_value: {
|
|
245
|
+
"integration-test": "true",
|
|
246
|
+
},
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
branch = data.branch;
|
|
250
|
+
|
|
251
|
+
// Determine role and database (handles multi-role/database projects)
|
|
252
|
+
const targetRole =
|
|
253
|
+
options.roleName ??
|
|
254
|
+
data.roles?.find((r) => r.name === "neondb_owner")?.name ??
|
|
255
|
+
data.roles?.[0]?.name;
|
|
256
|
+
const targetDatabase =
|
|
257
|
+
options.databaseName ??
|
|
258
|
+
data.databases?.find((d) => d.name === "neondb")?.name ??
|
|
259
|
+
data.databases?.[0]?.name;
|
|
260
|
+
|
|
261
|
+
if (!targetRole) {
|
|
262
|
+
throw new Error("No role available in branch");
|
|
263
|
+
}
|
|
264
|
+
if (!targetDatabase) {
|
|
265
|
+
throw new Error("No database available in branch");
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// Validate specified role exists
|
|
269
|
+
if (
|
|
270
|
+
options.roleName &&
|
|
271
|
+
!data.roles?.some((r) => r.name === options.roleName)
|
|
272
|
+
) {
|
|
273
|
+
throw new Error(`Role not found: ${options.roleName}`);
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// Validate specified database exists
|
|
277
|
+
if (
|
|
278
|
+
options.databaseName &&
|
|
279
|
+
!data.databases?.some((d) => d.name === options.databaseName)
|
|
280
|
+
) {
|
|
281
|
+
throw new Error(`Database not found: ${options.databaseName}`);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// Use getConnectionUri API (works for all cases, including multi-role projects)
|
|
285
|
+
const { data: uriData } = await apiClient.getConnectionUri({
|
|
286
|
+
projectId: options.projectId,
|
|
287
|
+
branch_id: branch.id,
|
|
288
|
+
role_name: targetRole,
|
|
289
|
+
database_name: targetDatabase,
|
|
290
|
+
pooled: options.endpoint !== "direct",
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
return applySslMode(uriData.uri, options.sslMode);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Delete the test branch
|
|
298
|
+
*/
|
|
299
|
+
async function deleteBranch() {
|
|
300
|
+
if (!branch?.id) {
|
|
301
|
+
throw new Error("No branch to delete");
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
await apiClient.deleteProjectBranch(options.projectId, branch.id);
|
|
305
|
+
branch = undefined;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
factoryOptions.hooks.beforeAll(async () => {
|
|
309
|
+
process.env.DATABASE_URL = await withRetry(createBranch, {
|
|
310
|
+
maxRetries: 8,
|
|
311
|
+
baseDelayMs: 1000,
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
if (options.autoCloseWebSockets) {
|
|
315
|
+
neonSockets = new Set<WebSocket>();
|
|
316
|
+
|
|
317
|
+
// Custom WebSocket constructor that tracks Neon WebSocket connections
|
|
318
|
+
class TrackingWebSocket extends WebSocket {
|
|
319
|
+
constructor(url: string) {
|
|
320
|
+
super(url);
|
|
321
|
+
|
|
322
|
+
// Only track Neon WebSocket connections
|
|
323
|
+
if (!url.includes(".neon.tech/")) return;
|
|
324
|
+
|
|
325
|
+
neonSockets!.add(this);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// Install a custom WebSocket constructor that tracks Neon WebSocket
|
|
330
|
+
// connections and closes them before deleting the branch
|
|
331
|
+
try {
|
|
332
|
+
const { neonConfig } = await import("@neondatabase/serverless");
|
|
333
|
+
neonConfig.webSocketConstructor = TrackingWebSocket;
|
|
334
|
+
} catch {
|
|
335
|
+
throw new Error(
|
|
336
|
+
"autoCloseWebSockets requires @neondatabase/serverless to be installed. Run: npm install @neondatabase/serverless",
|
|
337
|
+
);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
});
|
|
341
|
+
|
|
342
|
+
factoryOptions.hooks.afterAll(async () => {
|
|
343
|
+
delete process.env.DATABASE_URL;
|
|
344
|
+
|
|
345
|
+
// Close all tracked Neon WebSocket connections before deleting the branch
|
|
346
|
+
if (options.autoCloseWebSockets && neonSockets) {
|
|
347
|
+
// Suppress Neon WebSocket "Connection terminated unexpectedly" error
|
|
348
|
+
process.prependListener("uncaughtException", neonWsErrorHandler);
|
|
349
|
+
|
|
350
|
+
// Close tracked Neon WebSocket connections before deleting the branch
|
|
351
|
+
neonSockets.forEach((ws) => ws.close());
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
if (options.deleteBranch !== false) {
|
|
355
|
+
await deleteBranch();
|
|
356
|
+
}
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* Return the Neon branch object
|
|
361
|
+
*
|
|
362
|
+
* @returns The Neon branch object
|
|
363
|
+
*/
|
|
364
|
+
return () => branch;
|
|
365
|
+
};
|
|
366
|
+
|
|
367
|
+
// Attach utilities
|
|
368
|
+
neonTesting.deleteAllTestBranches = deleteAllTestBranches;
|
|
369
|
+
neonTesting.api = apiClient;
|
|
370
|
+
|
|
371
|
+
return neonTesting;
|
|
372
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Creates a synchronization barrier that blocks until `count` callers have
|
|
3
|
+
* arrived, then releases all of them simultaneously
|
|
4
|
+
*/
|
|
5
|
+
export function createBarrier(count: number) {
|
|
6
|
+
let arrived = 0;
|
|
7
|
+
let release: () => void;
|
|
8
|
+
|
|
9
|
+
const barrier = new Promise<void>((resolve) => {
|
|
10
|
+
release = resolve;
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
return async () => {
|
|
14
|
+
arrived++;
|
|
15
|
+
|
|
16
|
+
if (arrived === count) {
|
|
17
|
+
release();
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
await barrier;
|
|
21
|
+
};
|
|
22
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Validates the expiresIn option
|
|
3
|
+
*/
|
|
4
|
+
export function validateExpiresIn(expiresIn: number | null | undefined) {
|
|
5
|
+
if (expiresIn === null) {
|
|
6
|
+
return;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
if (expiresIn === undefined) {
|
|
10
|
+
return;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
if (!Number.isInteger(expiresIn)) {
|
|
14
|
+
throw new Error("expiresIn must be an integer");
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
if (expiresIn <= 0) {
|
|
18
|
+
throw new Error("expiresIn must be a positive integer");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
if (expiresIn > 2592000) {
|
|
22
|
+
throw new Error("expiresIn must not exceed 30 days (2,592,000 seconds)");
|
|
23
|
+
}
|
|
24
|
+
}
|
package/src/lib/ssl.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rewrite the `sslmode` (and related) query params on a Neon connection URI.
|
|
3
|
+
*
|
|
4
|
+
* Neon's API returns URIs with `sslmode=require`. In pg v9 /
|
|
5
|
+
* pg-connection-string v3 this mode will adopt libpq semantics (encrypt
|
|
6
|
+
* without CA verification) instead of today's effective `verify-full`.
|
|
7
|
+
*/
|
|
8
|
+
export function applySslMode(
|
|
9
|
+
uri: string,
|
|
10
|
+
mode: "verify-full" | "require" | undefined,
|
|
11
|
+
): string {
|
|
12
|
+
if (mode === undefined) return uri;
|
|
13
|
+
|
|
14
|
+
const url = new URL(uri);
|
|
15
|
+
url.searchParams.set("sslmode", mode);
|
|
16
|
+
|
|
17
|
+
if (mode === "require") {
|
|
18
|
+
url.searchParams.set("uselibpqcompat", "true");
|
|
19
|
+
} else {
|
|
20
|
+
url.searchParams.delete("uselibpqcompat");
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
return url.toString();
|
|
24
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reusable API call wrapper with automatic retry on 423 errors with exponential
|
|
3
|
+
* backoff
|
|
4
|
+
*
|
|
5
|
+
* https://neon.com/docs/reference/typescript-sdk#error-handling
|
|
6
|
+
* https://neon.com/docs/changelog/2022-07-20
|
|
7
|
+
*/
|
|
8
|
+
export async function withRetry<T>(
|
|
9
|
+
fn: () => Promise<T>,
|
|
10
|
+
options: {
|
|
11
|
+
maxRetries: number;
|
|
12
|
+
baseDelayMs: number;
|
|
13
|
+
},
|
|
14
|
+
): Promise<T> {
|
|
15
|
+
if (!Number.isInteger(options.maxRetries) || options.maxRetries <= 0) {
|
|
16
|
+
throw new Error("maxRetries must be a positive integer");
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
if (!Number.isInteger(options.baseDelayMs) || options.baseDelayMs <= 0) {
|
|
20
|
+
throw new Error("baseDelayMs must be a positive integer");
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
for (let attempt = 1; attempt <= options.maxRetries; attempt++) {
|
|
24
|
+
try {
|
|
25
|
+
return await fn();
|
|
26
|
+
} catch (error: any) {
|
|
27
|
+
const status = error?.response?.status;
|
|
28
|
+
|
|
29
|
+
// Retry on 423 (resource locked) with exponential backoff
|
|
30
|
+
if (status === 423 && attempt < options.maxRetries) {
|
|
31
|
+
const delay = options.baseDelayMs * Math.pow(2, attempt - 1);
|
|
32
|
+
|
|
33
|
+
console.log(
|
|
34
|
+
`API call failed with 423, retrying in ${delay}ms (attempt ${attempt}/${options.maxRetries})`,
|
|
35
|
+
);
|
|
36
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
37
|
+
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Surface Neon API error details that are otherwise buried in the Axios error
|
|
42
|
+
if (error?.response?.data?.code) {
|
|
43
|
+
const { code, message } = error.response.data;
|
|
44
|
+
throw new Error(
|
|
45
|
+
`Neon API error - HTTP ${status} - ${code} - ${message}`,
|
|
46
|
+
{ cause: error },
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Non-API errors (network, timeouts, etc.) pass through as-is
|
|
51
|
+
throw error;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
throw new Error("apiCallWithRetry reached unexpected end");
|
|
55
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Error handler: Suppress Neon WebSocket "Connection terminated unexpectedly"
|
|
3
|
+
* error
|
|
4
|
+
*/
|
|
5
|
+
export const neonWsErrorHandler = (error: Error) => {
|
|
6
|
+
const isNeonWsClose =
|
|
7
|
+
error.message.includes("Connection terminated unexpectedly") &&
|
|
8
|
+
error.stack?.includes("@neondatabase/serverless");
|
|
9
|
+
|
|
10
|
+
if (isNeonWsClose) {
|
|
11
|
+
// Swallow this specific Neon WS termination error
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// For any other error, detach and rethrow
|
|
16
|
+
throw error;
|
|
17
|
+
};
|
package/src/setup.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Removes any existing DATABASE_URL so a test file that forgot to call
|
|
2
|
+
// `neonTesting()` can't reach the pre-configured database. Loaded as a
|
|
3
|
+
// test-runner preload (Vitest `setupFiles` / Bun `bunfig` `preload`).
|
|
4
|
+
if (process.env.DATABASE_URL && process.env.NEON_TESTING_DEBUG === "true") {
|
|
5
|
+
console.debug("[neon-testing] Clearing existing DATABASE_URL");
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
delete process.env.DATABASE_URL;
|
package/src/utils.ts
ADDED
package/src/vitest.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { beforeAll, afterAll } from "vitest";
|
|
2
|
+
import { makeNeonTestingCore } from "./core";
|
|
3
|
+
import type { MakeNeonTestingOptions } from "./core";
|
|
4
|
+
|
|
5
|
+
export type { MakeNeonTestingOptions, NeonTestingOptions } from "./core";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Create a Neon test-branch factory wired to Vitest's lifecycle hooks.
|
|
9
|
+
*/
|
|
10
|
+
export function makeNeonTesting(options: MakeNeonTestingOptions) {
|
|
11
|
+
return makeNeonTestingCore({ ...options, hooks: { beforeAll, afterAll } });
|
|
12
|
+
}
|
package/dist/barrier.d.ts
DELETED
package/dist/barrier.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"barrier.d.ts","sourceRoot":"","sources":["../src/barrier.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,uBAiB1C"}
|
package/dist/barrier.js
DELETED
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Creates a synchronization barrier that blocks until `count` callers have
|
|
3
|
-
* arrived, then releases all of them simultaneously
|
|
4
|
-
*/
|
|
5
|
-
export function createBarrier(count) {
|
|
6
|
-
let arrived = 0;
|
|
7
|
-
let release;
|
|
8
|
-
const barrier = new Promise((resolve) => {
|
|
9
|
-
release = resolve;
|
|
10
|
-
});
|
|
11
|
-
return async () => {
|
|
12
|
-
arrived++;
|
|
13
|
-
if (arrived === count) {
|
|
14
|
-
release();
|
|
15
|
-
}
|
|
16
|
-
await barrier;
|
|
17
|
-
};
|
|
18
|
-
}
|
|
19
|
-
//# sourceMappingURL=barrier.js.map
|
package/dist/barrier.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"barrier.js","sourceRoot":"","sources":["../src/barrier.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,UAAU,aAAa,CAAC,KAAa;IACzC,IAAI,OAAO,GAAG,CAAC,CAAC;IAChB,IAAI,OAAmB,CAAC;IAExB,MAAM,OAAO,GAAG,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE;QAC5C,OAAO,GAAG,OAAO,CAAC;IACpB,CAAC,CAAC,CAAC;IAEH,OAAO,KAAK,IAAI,EAAE;QAChB,OAAO,EAAE,CAAC;QAEV,IAAI,OAAO,KAAK,KAAK,EAAE,CAAC;YACtB,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,MAAM,OAAO,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Creates a synchronization barrier that blocks until `count` callers have\n * arrived, then releases all of them simultaneously\n */\nexport function createBarrier(count: number) {\n let arrived = 0;\n let release: () => void;\n\n const barrier = new Promise<void>((resolve) => {\n release = resolve;\n });\n\n return async () => {\n arrived++;\n\n if (arrived === count) {\n release();\n }\n\n await barrier;\n };\n}\n"]}
|
package/dist/browser-empty.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"browser-empty.d.ts","sourceRoot":"","sources":["../src/browser-empty.ts"],"names":[],"mappings":"AAAA,wBAAgB,WAAW,SAE1B"}
|
package/dist/browser-empty.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"browser-empty.js","sourceRoot":"","sources":["../src/browser-empty.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,WAAW;IACzB,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;AAC3E,CAAC","sourcesContent":["export function neonTesting() {\n throw new Error(\"neon-testing/vite is Node-only (Vite/Vitest context).\");\n}\n"]}
|