@danylohotvianskyi/bobra-framework 0.1.9 → 0.2.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.
Files changed (102) hide show
  1. package/batteries/auth/hash.ts +102 -36
  2. package/batteries/auth/token-metadata.ts +25 -8
  3. package/batteries/auth/token.ts +5 -5
  4. package/batteries/openapi/index.ts +62 -41
  5. package/batteries/openapi/merge-openapi.ts +125 -33
  6. package/core/config.ts +40 -14
  7. package/core/discovery.ts +16 -10
  8. package/core/env-resolver.ts +25 -11
  9. package/core/factory.ts +150 -77
  10. package/core/spa.ts +14 -8
  11. package/db/client.ts +80 -415
  12. package/db/drizzle-clients.ts +65 -0
  13. package/db/failover.ts +318 -0
  14. package/db/index.ts +1 -0
  15. package/db/migrate.ts +7 -6
  16. package/db/pgedge.ts +307 -0
  17. package/db/test/client.test.ts +346 -0
  18. package/db/token-auth.ts +40 -0
  19. package/db/types.ts +96 -0
  20. package/dist/batteries/auth/hash.d.ts +10 -2
  21. package/dist/batteries/auth/hash.js +78 -43
  22. package/dist/batteries/auth/hash.js.map +1 -1
  23. package/dist/batteries/auth/token-metadata.d.ts +3 -3
  24. package/dist/batteries/auth/token-metadata.js +14 -6
  25. package/dist/batteries/auth/token-metadata.js.map +1 -1
  26. package/dist/batteries/auth/token.d.ts +3 -3
  27. package/dist/batteries/auth/token.js +2 -2
  28. package/dist/batteries/auth/token.js.map +1 -1
  29. package/dist/batteries/openapi/index.d.ts +51 -13
  30. package/dist/batteries/openapi/index.js +25 -15
  31. package/dist/batteries/openapi/index.js.map +1 -1
  32. package/dist/batteries/openapi/merge-openapi.d.ts +26 -2
  33. package/dist/batteries/openapi/merge-openapi.js +83 -26
  34. package/dist/batteries/openapi/merge-openapi.js.map +1 -1
  35. package/dist/core/config.d.ts +26 -9
  36. package/dist/core/config.js +8 -7
  37. package/dist/core/config.js.map +1 -1
  38. package/dist/core/discovery.d.ts +18 -9
  39. package/dist/core/discovery.js +1 -1
  40. package/dist/core/discovery.js.map +1 -1
  41. package/dist/core/env-resolver.d.ts +7 -4
  42. package/dist/core/env-resolver.js +7 -5
  43. package/dist/core/env-resolver.js.map +1 -1
  44. package/dist/core/factory.d.ts +36 -16
  45. package/dist/core/factory.js +70 -38
  46. package/dist/core/factory.js.map +1 -1
  47. package/dist/core/spa.js +9 -4
  48. package/dist/core/spa.js.map +1 -1
  49. package/dist/db/client.d.ts +16 -66
  50. package/dist/db/client.js +40 -311
  51. package/dist/db/client.js.map +1 -1
  52. package/dist/db/drizzle-clients.d.ts +6 -0
  53. package/dist/db/drizzle-clients.js +42 -0
  54. package/dist/db/drizzle-clients.js.map +1 -0
  55. package/dist/db/failover.d.ts +39 -0
  56. package/dist/db/failover.js +267 -0
  57. package/dist/db/failover.js.map +1 -0
  58. package/dist/db/index.d.ts +1 -0
  59. package/dist/db/index.js +1 -0
  60. package/dist/db/index.js.map +1 -1
  61. package/dist/db/migrate.js +4 -4
  62. package/dist/db/migrate.js.map +1 -1
  63. package/dist/db/pgedge.d.ts +14 -0
  64. package/dist/db/pgedge.js +218 -0
  65. package/dist/db/pgedge.js.map +1 -0
  66. package/dist/db/token-auth.d.ts +34 -0
  67. package/dist/db/token-auth.js +15 -0
  68. package/dist/db/token-auth.js.map +1 -0
  69. package/dist/db/types.d.ts +82 -0
  70. package/dist/db/types.js +2 -0
  71. package/dist/db/types.js.map +1 -0
  72. package/dist/logging/logger.d.ts +13 -13
  73. package/dist/logging/logger.js +11 -2
  74. package/dist/logging/logger.js.map +1 -1
  75. package/dist/logging/logging-middleware.d.ts +1 -1
  76. package/dist/logging/logging-middleware.js +6 -6
  77. package/dist/logging/logging-middleware.js.map +1 -1
  78. package/dist/middleware/ensure-api-token.d.ts +33 -4
  79. package/dist/middleware/ensure-api-token.js.map +1 -1
  80. package/dist/middleware/utils.d.ts +5 -1
  81. package/dist/middleware/utils.js +11 -7
  82. package/dist/middleware/utils.js.map +1 -1
  83. package/dist/network/router.d.ts +9 -6
  84. package/dist/network/router.js +3 -1
  85. package/dist/network/router.js.map +1 -1
  86. package/dist/network/service-discovery.d.ts +1 -1
  87. package/dist/network/service-discovery.js.map +1 -1
  88. package/dist/network/service-fetch.d.ts +6 -9
  89. package/dist/network/service-fetch.js +14 -4
  90. package/dist/network/service-fetch.js.map +1 -1
  91. package/dist/node/generate-wrangler-config.d.ts +28 -4
  92. package/dist/node/generate-wrangler-config.js +75 -20
  93. package/dist/node/generate-wrangler-config.js.map +1 -1
  94. package/logging/logger.ts +31 -21
  95. package/logging/logging-middleware.ts +12 -9
  96. package/middleware/ensure-api-token.ts +8 -6
  97. package/middleware/utils.ts +26 -8
  98. package/network/router.ts +17 -13
  99. package/network/service-discovery.ts +1 -1
  100. package/network/service-fetch.ts +26 -17
  101. package/node/generate-wrangler-config.ts +160 -24
  102. package/package.json +10 -7
package/db/client.ts CHANGED
@@ -1,129 +1,34 @@
1
- import { drizzle as drizzlePg } from 'drizzle-orm/node-postgres';
2
- import { drizzle as drizzleD1 } from 'drizzle-orm/d1';
3
- import { Pool } from 'pg';
4
1
  import { getLogger } from '../logging/logger';
5
- import type { D1Database, Hyperdrive } from '@cloudflare/workers-types';
2
+ import {
3
+ buildOrderedPostgresCandidates,
4
+ defaultPgEdgeRouter,
5
+ formatCandidateLabel,
6
+ getAvailablePostgresBindingsForLocation,
7
+ getPgEdgeLocations,
8
+ hasPostgresBindings,
9
+ normalizePostgresBindingRole,
10
+ resolvePgFailoverOptions,
11
+ } from './pgedge';
12
+ import { createD1DrizzleClient, createFailoverPgDrizzleClient, createPrimaryPgDrizzleClient } from './drizzle-clients';
13
+ import type {
14
+ AppEnvBindings,
15
+ CfInfo,
16
+ DatabaseContext,
17
+ DbContextOptions,
18
+ DrizzleD1Client,
19
+ DrizzlePgClient,
20
+ DrizzleSchema,
21
+ } from './types';
22
+
23
+ export * from './types';
24
+ export * from './pgedge';
25
+ export * from './failover';
26
+ export * from './drizzle-clients';
6
27
 
7
- export interface AppEnvBindings {
8
- D1?: D1Database;
9
- POSTGRES?: { connectionString: string };
10
- DB_ENGINE?: string;
11
- POSTGRES_URL?: string;
12
- HYPERDRIVE?: Hyperdrive;
13
- DEPLOYMENT_CONTEXT?: 'cloudflare' | 'self-hosted';
14
- PGEDGE_ENABLED?: boolean | string;
15
- PGEDGE_LOCATIONS?: string;
16
- [key: string]: any;
17
- }
18
-
19
- type DrizzleSchema = Record<string, unknown>;
20
-
21
- export type DrizzleD1Client<S extends DrizzleSchema = DrizzleSchema> = ReturnType<typeof drizzleD1<S>>;
22
- export type DrizzlePgClient<S extends DrizzleSchema = DrizzleSchema> = ReturnType<typeof drizzlePg<S>>;
23
-
24
- /**
25
- * Database context for operations
26
- */
27
- export interface DatabaseContext<S extends DrizzleSchema = DrizzleSchema> {
28
- type: 'postgres' | 'd1-sqlite';
29
- db: DrizzleD1Client<S> | DrizzlePgClient<S>;
30
- }
31
-
32
- export type PgEdgeRouter = (locations: string[], cfContinentStr?: string, cfInfo?: any) => string;
33
- export type PostgresBindingRole = string;
34
-
35
- export interface DbContextOptions {
36
- cfInfo?: any;
37
- pgEdgeRouter?: PgEdgeRouter;
38
- postgresBindingRole?: PostgresBindingRole;
39
- }
40
-
41
- interface ResolvedPostgresBinding {
42
- bindingName: string;
43
- connectionString: string;
44
- }
45
-
46
- export function normalizePostgresBindingRole(role?: PostgresBindingRole): string | undefined {
47
- const trimmedRole = role?.trim();
48
- if (!trimmedRole) return undefined;
49
-
50
- const normalizedRole = trimmedRole.toUpperCase().replace(/[^A-Z0-9_]/g, '_');
51
- if (!normalizedRole || normalizedRole === 'DEFAULT') return undefined;
52
- return normalizedRole;
53
- }
54
-
55
- export function getPostgresLocationBindingCandidates(location: string, role?: PostgresBindingRole): string[] {
56
- const normalizedLocation = location.toUpperCase();
57
- const normalizedRole = normalizePostgresBindingRole(role);
58
-
59
- if (!normalizedRole) {
60
- return [
61
- `POSTGRES_${normalizedLocation}`,
62
- `POSTGRES_${normalizedLocation}_DEFAULT`,
63
- ];
64
- }
65
-
66
- return [
67
- `POSTGRES_${normalizedLocation}_${normalizedRole}`,
68
- `POSTGRES_${normalizedLocation}`,
69
- `POSTGRES_${normalizedLocation}_DEFAULT`,
70
- ];
71
- }
72
-
73
- /**
74
- * Get all available postgres bindings for a specific location
75
- * This helps determine what bindings are actually available for fallback logic
76
- */
77
- export function getAvailablePostgresBindingsForLocation(env: AppEnvBindings, location: string): string[] {
78
- const normalizedLocation = location.toUpperCase();
79
- const availableBindings: string[] = [];
80
-
81
- // Add any binding that starts with POSTGRES_{LOCATION}
82
- Object.keys(env).forEach(key => {
83
- if (key.startsWith(`POSTGRES_${normalizedLocation}_`) || key === `POSTGRES_${normalizedLocation}`) {
84
- if (env[key]?.connectionString && typeof env[key].connectionString === 'string') {
85
- availableBindings.push(key);
86
- }
87
- }
88
- });
89
-
90
- return availableBindings;
91
- }
92
-
93
- function getSinglePostgresBindingCandidates(role?: PostgresBindingRole): string[] {
94
- const normalizedRole = normalizePostgresBindingRole(role);
95
-
96
- if (!normalizedRole) {
97
- return ['POSTGRES', 'POSTGRES_DEFAULT'];
98
- }
99
-
100
- return [`POSTGRES_${normalizedRole}`, 'POSTGRES', 'POSTGRES_DEFAULT'];
101
- }
102
-
103
- function resolvePostgresBindingByCandidates(
104
- env: AppEnvBindings,
105
- candidateBindingNames: string[]
106
- ): ResolvedPostgresBinding | undefined {
107
- for (const bindingName of candidateBindingNames) {
108
- const binding = env[bindingName];
109
- if (binding?.connectionString && typeof binding.connectionString === 'string') {
110
- return {
111
- bindingName,
112
- connectionString: binding.connectionString,
113
- };
114
- }
115
- }
116
-
117
- return undefined;
118
- }
119
-
120
- /**
121
- * Get database context based on environment.
122
- */
123
28
  export function getDatabaseContext<S extends DrizzleSchema>(
124
29
  env: AppEnvBindings,
125
30
  schema: S,
126
- optionsOrCfInfo?: any | DbContextOptions
31
+ optionsOrCfInfo?: CfInfo | DbContextOptions
127
32
  ): DatabaseContext<S> {
128
33
  const options = getNormalizedDbContextOptions(optionsOrCfInfo);
129
34
  const dbEngine = env.DB_ENGINE || 'auto-detect';
@@ -136,7 +41,6 @@ export function getDatabaseContext<S extends DrizzleSchema>(
136
41
  return { type: 'd1-sqlite', db: getDb(env, schema, options) };
137
42
  }
138
43
 
139
- // Auto-detect fallback
140
44
  if (hasPostgresBindings(env, options.postgresBindingRole)) {
141
45
  return { type: 'postgres', db: getDb(env, schema, options) };
142
46
  }
@@ -148,10 +52,7 @@ export function getDatabaseContext<S extends DrizzleSchema>(
148
52
  throw new Error('No supported database configuration found');
149
53
  }
150
54
 
151
- /**
152
- * cfInfo for backward compatibility
153
- */
154
- export function getNormalizedDbContextOptions(optionsOrCfInfo?: any): DbContextOptions {
55
+ export function getNormalizedDbContextOptions(optionsOrCfInfo?: CfInfo | DbContextOptions): DbContextOptions {
155
56
  if (!optionsOrCfInfo) return {};
156
57
  if (
157
58
  typeof optionsOrCfInfo === 'object' && (
@@ -163,58 +64,38 @@ export function getNormalizedDbContextOptions(optionsOrCfInfo?: any): DbContextO
163
64
  ) {
164
65
  return optionsOrCfInfo as DbContextOptions;
165
66
  }
166
- return { cfInfo: optionsOrCfInfo };
67
+ return { cfInfo: optionsOrCfInfo as CfInfo };
167
68
  }
168
69
 
169
- /**
170
- * Check if database context is SQLite
171
- */
172
70
  export function isSQLite(ctx: DatabaseContext): boolean {
173
71
  return ctx.type === 'd1-sqlite';
174
72
  }
175
73
 
176
- /**
177
- * Returns a Drizzle client using either D1 or PostgreSQL.
178
- * Consumers pass their own Drizzle schema for typed queries.
179
- */
180
- export const defaultPgEdgeRouter: PgEdgeRouter = (locations: string[], cfContinentStr?: string) => {
181
- let targetLocation = locations[0]!;
182
-
183
- if (cfContinentStr === 'EU' && locations.includes('eu')) {
184
- targetLocation = 'eu';
185
- } else if (cfContinentStr === 'NA' && locations.includes('us')) {
186
- targetLocation = 'us';
187
- } else if (locations.includes('eu')) {
188
- // Default to EU when continent is unknown
189
- targetLocation = 'eu';
190
- }
74
+ export function isSQLiteContext<S extends DrizzleSchema>(
75
+ ctx: DatabaseContext<S>
76
+ ): ctx is { type: 'd1-sqlite'; db: DrizzleD1Client<S> } {
77
+ return ctx.type === 'd1-sqlite';
78
+ }
191
79
 
192
- return targetLocation;
193
- };
80
+ export function isPostgresContext<S extends DrizzleSchema>(
81
+ ctx: DatabaseContext<S>
82
+ ): ctx is { type: 'postgres'; db: DrizzlePgClient<S> } {
83
+ return ctx.type === 'postgres';
84
+ }
194
85
 
195
- /**
196
- * Returns a Drizzle client using either D1 or PostgreSQL.
197
- * Consumers pass their own Drizzle schema for typed queries.
198
- */
199
86
  export function getDb<S extends DrizzleSchema>(
200
87
  env: AppEnvBindings,
201
88
  schema: S,
202
- optionsOrCfInfo?: any | DbContextOptions
89
+ optionsOrCfInfo?: CfInfo | DbContextOptions
203
90
  ): DrizzleD1Client<S> | DrizzlePgClient<S> {
204
91
  const options = getNormalizedDbContextOptions(optionsOrCfInfo);
205
92
  const cfInfo = options.cfInfo;
206
93
  const pgEdgeRouter = options.pgEdgeRouter || defaultPgEdgeRouter;
207
94
  const postgresBindingRole = options.postgresBindingRole;
208
95
  const normalizedPostgresBindingRole = normalizePostgresBindingRole(postgresBindingRole);
209
-
210
96
  const dbEngine = env.DB_ENGINE || 'auto-detect';
211
-
212
97
  const logger = getLogger();
213
-
214
- // Resolve continent: prefer direct cf object, fall back to router-forwarded header
215
- const continent = cfInfo?.continent
216
- || (env as any).__cfContinent // allow explicit override
217
- || undefined;
98
+ const continent = cfInfo?.continent ?? env.__cfContinent ?? undefined;
218
99
 
219
100
  if (env.PGEDGE_DEBUG_LOGGING) {
220
101
  logger.debug('[getDb] Starting DB resolution', {
@@ -231,203 +112,63 @@ export function getDb<S extends DrizzleSchema>(
231
112
 
232
113
  if (dbEngine === 'postgres' || (dbEngine === 'auto-detect' && hasPostgresBindings(env))) {
233
114
  const locations = getPgEdgeLocations(env);
115
+ const { candidates, orderedLocations } = buildOrderedPostgresCandidates(
116
+ env,
117
+ postgresBindingRole,
118
+ locations,
119
+ pgEdgeRouter,
120
+ continent,
121
+ cfInfo
122
+ );
234
123
 
235
- if (locations.length > 0) {
236
- let orderedLocations = [...locations];
237
- let targetLocation: string | undefined;
238
-
239
- if (locations.length > 1) {
240
- const cfContinentStr = (continent || '').toUpperCase();
241
- targetLocation = pgEdgeRouter(locations, cfContinentStr, cfInfo);
242
-
243
- // Order locations so target goes first
244
- orderedLocations = [
245
- targetLocation,
246
- ...locations.filter(loc => loc !== targetLocation)
247
- ];
248
- }
249
-
250
- for (const loc of orderedLocations) {
251
- const candidates = getPostgresLocationBindingCandidates(loc, postgresBindingRole);
252
- const resolved = resolvePostgresBindingByCandidates(env, candidates);
253
-
254
- if (env.PGEDGE_DEBUG_LOGGING) {
255
- logger.debug('[getDb] Checking location for pgEdge binding', {
256
- targetLocation,
257
- selectedLocation: loc,
258
- candidates,
259
- resolved: resolved?.bindingName || null,
260
- postgresBindingRole: normalizedPostgresBindingRole || 'DEFAULT',
261
- originalRole: postgresBindingRole,
262
- });
263
- }
264
-
265
- if (resolved) {
266
- if (env.PGEDGE_DEBUG_LOGGING) {
267
- logger.debug('[getDb] Using pgEdge binding', {
268
- targetLocation,
269
- selectedLocation: loc,
270
- selectedBinding: resolved.bindingName,
271
- postgresBindingRole: normalizedPostgresBindingRole || 'DEFAULT',
272
- });
273
- }
274
-
275
- return createPgDrizzleClient(resolved.connectionString, schema);
276
- }
277
-
278
- // If no binding found with the specified role, try fallback logic
279
- // This should handle both cases: when a role is specified and when DEFAULT is used
280
- const availableBindings = getAvailablePostgresBindingsForLocation(env, loc);
281
-
282
- if (env.PGEDGE_DEBUG_LOGGING) {
283
- logger.debug('[getDb] Checking fallback logic', {
284
- selectedLocation: loc,
285
- normalizedPostgresBindingRole,
286
- originalRole: postgresBindingRole,
287
- availableBindings,
288
- hasAvailableBindings: availableBindings.length > 0,
289
- });
290
- }
291
-
292
- if (availableBindings.length > 0) {
293
- // If there are available bindings, try to use them
294
- let preferredBindings = availableBindings;
295
-
296
- if (!normalizedPostgresBindingRole) {
297
- // When DEFAULT is requested (normalized to undefined), prefer LIVE bindings
298
- const liveBindings = availableBindings.filter(binding =>
299
- binding.endsWith('_LIVE')
300
- );
301
- if (liveBindings.length > 0) {
302
- preferredBindings = liveBindings;
303
- }
304
- } else {
305
- // When a specific role is requested, try to find bindings without that role first
306
- const fallbackCandidates = availableBindings.filter(binding =>
307
- !binding.includes(`_${normalizedPostgresBindingRole}`)
308
- );
309
-
310
- if (fallbackCandidates.length > 0) {
311
- preferredBindings = fallbackCandidates;
312
- }
313
- }
314
-
315
- const fallbackBinding = resolvePostgresBindingByCandidates(env, preferredBindings);
316
- if (fallbackBinding) {
317
- logger.warn(`[getDb] Falling back to available binding for location ${loc}`, {
318
- targetLocation,
319
- selectedLocation: loc,
320
- selectedBinding: fallbackBinding.bindingName,
321
- requestedRole: postgresBindingRole || 'DEFAULT',
322
- normalizedRole: normalizedPostgresBindingRole,
323
- availableBindings,
324
- preferredBindings,
325
- });
326
- return createPgDrizzleClient(fallbackBinding.connectionString, schema);
327
- }
328
- }
329
- }
124
+ if (env.PGEDGE_DEBUG_LOGGING) {
125
+ logger.debug('[getDb] Resolved postgres binding candidates', {
126
+ postgresBindingRole: normalizedPostgresBindingRole || 'DEFAULT',
127
+ orderedLocations,
128
+ candidates: candidates.map(formatCandidateLabel),
129
+ });
130
+ }
330
131
 
331
- // Enhanced error message with available bindings
132
+ if (candidates.length === 0) {
332
133
  const allAvailableBindings: Record<string, string[]> = {};
333
- orderedLocations.forEach(loc => {
334
- const available = getAvailablePostgresBindingsForLocation(env, loc);
134
+ orderedLocations.forEach((location) => {
135
+ const available = getAvailablePostgresBindingsForLocation(env, location);
335
136
  if (available.length > 0) {
336
- allAvailableBindings[loc] = available;
137
+ allAvailableBindings[location] = available;
337
138
  }
338
139
  });
339
-
340
- logger.error('[getDb] pgEdge enabled but no matching POSTGRES bindings found', undefined, {
140
+
141
+ logger.error('[getDb] No POSTGRES binding found', undefined, {
142
+ locationsCount: locations.length,
341
143
  orderedLocations,
342
144
  postgresBindingRole: normalizedPostgresBindingRole || 'DEFAULT',
343
145
  allAvailableBindings,
344
- envKeys: Object.keys(env).filter(k => k.startsWith('POSTGRES') || k.startsWith('PGEDGE') || k === 'DB_ENGINE'),
146
+ allAvailablePostgresBindings: Object.keys(env).filter(
147
+ (key) => key.startsWith('POSTGRES') && typeof env[key] === 'object' && env[key] !== null
148
+ ),
149
+ envKeys: Object.keys(env).filter(
150
+ (key) => key.startsWith('POSTGRES') || key.startsWith('PGEDGE') || key === 'DB_ENGINE'
151
+ ),
345
152
  });
153
+ throw new Error("POSTGRES binding with connectionString is required when DB_ENGINE is set to 'postgres'. If using roles, ensure role-specific bindings exist or fallback POSTGRES bindings are configured.");
346
154
  }
347
155
 
348
- const singleResolved = resolvePostgresBindingByCandidates(
349
- env,
350
- getSinglePostgresBindingCandidates(postgresBindingRole)
351
- );
156
+ const failoverOptions = resolvePgFailoverOptions(env, candidates.length);
352
157
 
353
- if (singleResolved) {
354
- if (env.PGEDGE_DEBUG_LOGGING) {
355
- logger.debug('[getDb] Using single POSTGRES binding', {
356
- selectedBinding: singleResolved.bindingName,
357
- postgresBindingRole: normalizedPostgresBindingRole || 'DEFAULT',
358
- });
359
- }
360
-
361
- return createPgDrizzleClient(singleResolved.connectionString, schema);
362
- }
363
-
364
- // Fallback logic for single bindings when role is specified but not found
365
- // This should handle both cases: when a role is specified and when DEFAULT is used
366
- const allPostgresBindings = Object.keys(env).filter(key =>
367
- key.startsWith('POSTGRES') &&
368
- env[key]?.connectionString &&
369
- typeof env[key].connectionString === 'string'
370
- );
371
-
372
158
  if (env.PGEDGE_DEBUG_LOGGING) {
373
- logger.debug('[getDb] Checking single binding fallback logic', {
374
- normalizedPostgresBindingRole,
375
- originalRole: postgresBindingRole,
376
- allPostgresBindings,
377
- hasAvailableBindings: allPostgresBindings.length > 0,
159
+ logger.debug('[getDb] PostgreSQL failover config', {
160
+ candidates: candidates.map(formatCandidateLabel),
161
+ failoverEnabled: failoverOptions.enabled,
162
+ failoverConnectionTimeoutMs: failoverOptions.connectionTimeoutMs,
163
+ failoverWarnLogging: failoverOptions.warnLogging,
378
164
  });
379
165
  }
380
-
381
- if (allPostgresBindings.length > 0) {
382
- let preferredBindings = allPostgresBindings;
383
-
384
- if (!normalizedPostgresBindingRole) {
385
- // When DEFAULT is requested (normalized to undefined), prefer LIVE bindings
386
- const liveBindings = allPostgresBindings.filter(binding =>
387
- binding.endsWith('_LIVE')
388
- );
389
- if (liveBindings.length > 0) {
390
- preferredBindings = liveBindings;
391
- }
392
- } else {
393
- // When a specific role is requested, try to find bindings without that role first
394
- const fallbackCandidates = allPostgresBindings.filter(binding =>
395
- !binding.includes(`_${normalizedPostgresBindingRole}`)
396
- );
397
-
398
- if (fallbackCandidates.length > 0) {
399
- preferredBindings = fallbackCandidates;
400
- }
401
- }
402
-
403
- const fallbackBinding = resolvePostgresBindingByCandidates(env, preferredBindings);
404
- if (fallbackBinding) {
405
- logger.warn('[getDb] Falling back to available POSTGRES binding', {
406
- selectedBinding: fallbackBinding.bindingName,
407
- requestedRole: postgresBindingRole || 'DEFAULT',
408
- normalizedRole: normalizedPostgresBindingRole,
409
- availableBindings: allPostgresBindings,
410
- preferredBindings,
411
- });
412
- return createPgDrizzleClient(fallbackBinding.connectionString, schema);
413
- }
166
+
167
+ if (failoverOptions.enabled && candidates.length > 1) {
168
+ return createFailoverPgDrizzleClient(candidates, schema, failoverOptions);
414
169
  }
415
170
 
416
- logger.error('[getDb] No POSTGRES binding found', undefined, {
417
- locationsCount: locations.length,
418
- hasFallbackPOSTGRES: !!resolvePostgresBindingByCandidates(
419
- env,
420
- getSinglePostgresBindingCandidates(postgresBindingRole)
421
- ),
422
- postgresBindingRole: normalizedPostgresBindingRole || 'DEFAULT',
423
- allAvailablePostgresBindings: Object.keys(env).filter(key =>
424
- key.startsWith('POSTGRES') &&
425
- env[key]?.connectionString &&
426
- typeof env[key].connectionString === 'string'
427
- ),
428
- envKeys: Object.keys(env).filter(k => k.startsWith('POSTGRES') || k.startsWith('PGEDGE') || k === 'DB_ENGINE'),
429
- });
430
- throw new Error("POSTGRES binding with connectionString is required when DB_ENGINE is set to 'postgres'. If using roles, ensure role-specific bindings exist or fallback POSTGRES bindings are configured.");
171
+ return createPrimaryPgDrizzleClient(candidates[0]!, schema);
431
172
  }
432
173
 
433
174
  if (dbEngine === 'd1-sqlite' || (dbEngine === 'auto-detect' && env.D1)) {
@@ -437,81 +178,5 @@ export function getDb<S extends DrizzleSchema>(
437
178
  return createD1DrizzleClient(env.D1, schema);
438
179
  }
439
180
 
440
- throw new Error("No database binding found: bind either POSTGRES or D1 in your worker");
441
- }
442
-
443
- export function createD1DrizzleClient<S extends DrizzleSchema>(d1: D1Database, schema: S): DrizzleD1Client<S> {
444
- return drizzleD1(d1, { schema });
445
- }
446
-
447
- export function createPgDrizzleClient<S extends DrizzleSchema>(connectionString: string, schema: S): DrizzlePgClient<S> {
448
- try {
449
- const pool = new Pool({ connectionString });
450
- const drizzleClient = drizzlePg(pool, { schema });
451
- return drizzleClient;
452
- } catch (error) {
453
- getLogger().error('[createPgDrizzleClient] Error creating PostgreSQL client:', error instanceof Error ? error : new Error(String(error)));
454
- throw error;
455
- }
456
- }
457
-
458
- export function getPgEdgeLocations(env: AppEnvBindings): string[] {
459
- const isPgEdgeEnabled = env.PGEDGE_ENABLED === true || env.PGEDGE_ENABLED === 'true';
460
- if (!isPgEdgeEnabled) return [];
461
-
462
- let pgedgeLocations: string[] = [];
463
- if (env.PGEDGE_LOCATIONS) {
464
- try {
465
- const parsed = typeof env.PGEDGE_LOCATIONS === 'string'
466
- ? JSON.parse(env.PGEDGE_LOCATIONS)
467
- : env.PGEDGE_LOCATIONS;
468
-
469
- if (Array.isArray(parsed) && parsed.every(item => typeof item === 'string')) {
470
- pgedgeLocations = parsed.map(item => item.toLowerCase());
471
- } else {
472
- getLogger().warn('PGEDGE_LOCATIONS must be an array of strings');
473
- }
474
- } catch (e) {
475
- getLogger().warn('Failed to parse PGEDGE_LOCATIONS', e instanceof Error ? e : new Error(String(e)));
476
- }
477
- }
478
- return pgedgeLocations;
479
- }
480
-
481
- export function hasPostgresBindings(env: AppEnvBindings, role?: PostgresBindingRole): boolean {
482
- // Check single bindings first
483
- if (resolvePostgresBindingByCandidates(env, getSinglePostgresBindingCandidates(role))) return true;
484
-
485
- // Check single bindings with fallback logic (same as getDb)
486
- const allPostgresBindings = Object.keys(env).filter(key =>
487
- key.startsWith('POSTGRES') &&
488
- env[key]?.connectionString &&
489
- typeof env[key].connectionString === 'string'
490
- );
491
-
492
- if (allPostgresBindings.length > 0) {
493
- // If there are any POSTGRES bindings, consider them available
494
- // This matches the fallback logic in getDb
495
- return true;
496
- }
497
-
498
- // Check pgEdge location bindings with fallback logic
499
- const locations = getPgEdgeLocations(env);
500
- if (locations.length > 0) {
501
- return locations.some(loc => {
502
- // First try exact match
503
- if (resolvePostgresBindingByCandidates(env, getPostgresLocationBindingCandidates(loc, role))) {
504
- return true;
505
- }
506
-
507
- // Then try fallback logic (same as getDb)
508
- const availableBindings = getAvailablePostgresBindingsForLocation(env, loc);
509
- if (availableBindings.length > 0) {
510
- return true;
511
- }
512
-
513
- return false;
514
- });
515
- }
516
- return false;
181
+ throw new Error('No database binding found: bind either POSTGRES or D1 in your worker');
517
182
  }
@@ -0,0 +1,65 @@
1
+ import { drizzle as drizzlePg } from 'drizzle-orm/node-postgres';
2
+ import { drizzle as drizzleD1 } from 'drizzle-orm/d1';
3
+ import { Pool } from 'pg';
4
+ import type { D1Database } from '@cloudflare/workers-types';
5
+ import { getLogger } from '../logging/logger';
6
+ import { attachPoolErrorLogger, FailoverPgPool } from './failover';
7
+ import { readCandidateConnectionString } from './pgedge';
8
+ import type {
9
+ DrizzleD1Client,
10
+ DrizzlePgClient,
11
+ DrizzleSchema,
12
+ PgFailoverOptions,
13
+ PostgresCandidate,
14
+ } from './types';
15
+
16
+ export function createD1DrizzleClient<S extends DrizzleSchema>(d1: D1Database, schema: S): DrizzleD1Client<S> {
17
+ return drizzleD1(d1, { schema });
18
+ }
19
+
20
+ export function createPgDrizzleClient<S extends DrizzleSchema>(
21
+ connectionString: string,
22
+ schema: S,
23
+ connectionTimeoutMs?: number
24
+ ): DrizzlePgClient<S> {
25
+ try {
26
+ const poolConfig: { connectionString: string; connectionTimeoutMillis?: number } = { connectionString };
27
+ if (connectionTimeoutMs !== undefined) {
28
+ poolConfig.connectionTimeoutMillis = connectionTimeoutMs;
29
+ }
30
+ const pool = new Pool(poolConfig);
31
+ attachPoolErrorLogger(pool, {
32
+ binding: 'POSTGRES',
33
+ location: null,
34
+ operation: 'pool',
35
+ });
36
+ return drizzlePg(pool, { schema });
37
+ } catch (error) {
38
+ getLogger().error('[createPgDrizzleClient] Error creating PostgreSQL client:', error instanceof Error ? error : new Error(String(error)));
39
+ throw error;
40
+ }
41
+ }
42
+
43
+ export function createFailoverPgDrizzleClient<S extends DrizzleSchema>(
44
+ candidates: PostgresCandidate[],
45
+ schema: S,
46
+ failoverOptions: PgFailoverOptions
47
+ ): DrizzlePgClient<S> {
48
+ try {
49
+ const failoverPool = new FailoverPgPool(candidates, failoverOptions);
50
+ return drizzlePg(failoverPool as unknown as Pool, { schema });
51
+ } catch (error) {
52
+ getLogger().error(
53
+ '[createPgDrizzleClient] Error creating failover PostgreSQL client:',
54
+ error instanceof Error ? error : new Error(String(error))
55
+ );
56
+ throw error;
57
+ }
58
+ }
59
+
60
+ export function createPrimaryPgDrizzleClient<S extends DrizzleSchema>(
61
+ candidate: PostgresCandidate,
62
+ schema: S
63
+ ): DrizzlePgClient<S> {
64
+ return createPgDrizzleClient(readCandidateConnectionString(candidate), schema);
65
+ }