@danylohotvianskyi/bobra-framework 0.1.8 → 0.2.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.
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 +85 -245
  12. package/db/drizzle-clients.ts +65 -0
  13. package/db/failover.ts +300 -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 +297 -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 -59
  50. package/dist/db/client.js +47 -171
  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 +251 -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,109 +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
- 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
- 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
- function getSinglePostgresBindingCandidates(role?: PostgresBindingRole): string[] {
74
- const normalizedRole = normalizePostgresBindingRole(role);
75
-
76
- if (!normalizedRole) {
77
- return ['POSTGRES', 'POSTGRES_DEFAULT'];
78
- }
79
-
80
- return [`POSTGRES_${normalizedRole}`, 'POSTGRES', 'POSTGRES_DEFAULT'];
81
- }
82
-
83
- function resolvePostgresBindingByCandidates(
84
- env: AppEnvBindings,
85
- candidateBindingNames: string[]
86
- ): ResolvedPostgresBinding | undefined {
87
- for (const bindingName of candidateBindingNames) {
88
- const binding = env[bindingName];
89
- if (binding?.connectionString && typeof binding.connectionString === 'string') {
90
- return {
91
- bindingName,
92
- connectionString: binding.connectionString,
93
- };
94
- }
95
- }
96
-
97
- return undefined;
98
- }
99
-
100
- /**
101
- * Get database context based on environment.
102
- */
103
28
  export function getDatabaseContext<S extends DrizzleSchema>(
104
29
  env: AppEnvBindings,
105
30
  schema: S,
106
- optionsOrCfInfo?: any | DbContextOptions
31
+ optionsOrCfInfo?: CfInfo | DbContextOptions
107
32
  ): DatabaseContext<S> {
108
33
  const options = getNormalizedDbContextOptions(optionsOrCfInfo);
109
34
  const dbEngine = env.DB_ENGINE || 'auto-detect';
@@ -116,7 +41,6 @@ export function getDatabaseContext<S extends DrizzleSchema>(
116
41
  return { type: 'd1-sqlite', db: getDb(env, schema, options) };
117
42
  }
118
43
 
119
- // Auto-detect fallback
120
44
  if (hasPostgresBindings(env, options.postgresBindingRole)) {
121
45
  return { type: 'postgres', db: getDb(env, schema, options) };
122
46
  }
@@ -128,10 +52,7 @@ export function getDatabaseContext<S extends DrizzleSchema>(
128
52
  throw new Error('No supported database configuration found');
129
53
  }
130
54
 
131
- /**
132
- * cfInfo for backward compatibility
133
- */
134
- export function getNormalizedDbContextOptions(optionsOrCfInfo?: any): DbContextOptions {
55
+ export function getNormalizedDbContextOptions(optionsOrCfInfo?: CfInfo | DbContextOptions): DbContextOptions {
135
56
  if (!optionsOrCfInfo) return {};
136
57
  if (
137
58
  typeof optionsOrCfInfo === 'object' && (
@@ -143,58 +64,38 @@ export function getNormalizedDbContextOptions(optionsOrCfInfo?: any): DbContextO
143
64
  ) {
144
65
  return optionsOrCfInfo as DbContextOptions;
145
66
  }
146
- return { cfInfo: optionsOrCfInfo };
67
+ return { cfInfo: optionsOrCfInfo as CfInfo };
147
68
  }
148
69
 
149
- /**
150
- * Check if database context is SQLite
151
- */
152
70
  export function isSQLite(ctx: DatabaseContext): boolean {
153
71
  return ctx.type === 'd1-sqlite';
154
72
  }
155
73
 
156
- /**
157
- * Returns a Drizzle client using either D1 or PostgreSQL.
158
- * Consumers pass their own Drizzle schema for typed queries.
159
- */
160
- export const defaultPgEdgeRouter: PgEdgeRouter = (locations: string[], cfContinentStr?: string) => {
161
- let targetLocation = locations[0]!;
162
-
163
- if (cfContinentStr === 'EU' && locations.includes('eu')) {
164
- targetLocation = 'eu';
165
- } else if (cfContinentStr === 'NA' && locations.includes('us')) {
166
- targetLocation = 'us';
167
- } else if (locations.includes('eu')) {
168
- // Default to EU when continent is unknown
169
- targetLocation = 'eu';
170
- }
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
+ }
171
79
 
172
- return targetLocation;
173
- };
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
+ }
174
85
 
175
- /**
176
- * Returns a Drizzle client using either D1 or PostgreSQL.
177
- * Consumers pass their own Drizzle schema for typed queries.
178
- */
179
86
  export function getDb<S extends DrizzleSchema>(
180
87
  env: AppEnvBindings,
181
88
  schema: S,
182
- optionsOrCfInfo?: any | DbContextOptions
89
+ optionsOrCfInfo?: CfInfo | DbContextOptions
183
90
  ): DrizzleD1Client<S> | DrizzlePgClient<S> {
184
91
  const options = getNormalizedDbContextOptions(optionsOrCfInfo);
185
92
  const cfInfo = options.cfInfo;
186
93
  const pgEdgeRouter = options.pgEdgeRouter || defaultPgEdgeRouter;
187
94
  const postgresBindingRole = options.postgresBindingRole;
188
95
  const normalizedPostgresBindingRole = normalizePostgresBindingRole(postgresBindingRole);
189
-
190
96
  const dbEngine = env.DB_ENGINE || 'auto-detect';
191
-
192
97
  const logger = getLogger();
193
-
194
- // Resolve continent: prefer direct cf object, fall back to router-forwarded header
195
- const continent = cfInfo?.continent
196
- || (env as any).__cfContinent // allow explicit override
197
- || undefined;
98
+ const continent = cfInfo?.continent ?? env.__cfContinent ?? undefined;
198
99
 
199
100
  if (env.PGEDGE_DEBUG_LOGGING) {
200
101
  logger.debug('[getDb] Starting DB resolution', {
@@ -211,74 +112,63 @@ export function getDb<S extends DrizzleSchema>(
211
112
 
212
113
  if (dbEngine === 'postgres' || (dbEngine === 'auto-detect' && hasPostgresBindings(env))) {
213
114
  const locations = getPgEdgeLocations(env);
115
+ const { candidates, orderedLocations } = buildOrderedPostgresCandidates(
116
+ env,
117
+ postgresBindingRole,
118
+ locations,
119
+ pgEdgeRouter,
120
+ continent,
121
+ cfInfo
122
+ );
214
123
 
215
- if (locations.length > 0) {
216
- let orderedLocations = [...locations];
217
- let targetLocation: string | undefined;
218
-
219
- if (locations.length > 1) {
220
- const cfContinentStr = (continent || '').toUpperCase();
221
- targetLocation = pgEdgeRouter(locations, cfContinentStr, cfInfo);
222
-
223
- // Order locations so target goes first
224
- orderedLocations = [
225
- targetLocation,
226
- ...locations.filter(loc => loc !== targetLocation)
227
- ];
228
- }
229
-
230
- for (const loc of orderedLocations) {
231
- const resolved = resolvePostgresBindingByCandidates(
232
- env,
233
- getPostgresLocationBindingCandidates(loc, postgresBindingRole)
234
- );
235
-
236
- if (resolved) {
237
- if (env.PGEDGE_DEBUG_LOGGING) {
238
- logger.debug('[getDb] Using pgEdge binding', {
239
- targetLocation,
240
- selectedLocation: loc,
241
- selectedBinding: resolved.bindingName,
242
- postgresBindingRole: normalizedPostgresBindingRole || 'DEFAULT',
243
- });
244
- }
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
+ }
245
131
 
246
- return createPgDrizzleClient(resolved.connectionString, schema);
132
+ if (candidates.length === 0) {
133
+ const allAvailableBindings: Record<string, string[]> = {};
134
+ orderedLocations.forEach((location) => {
135
+ const available = getAvailablePostgresBindingsForLocation(env, location);
136
+ if (available.length > 0) {
137
+ allAvailableBindings[location] = available;
247
138
  }
248
- }
139
+ });
249
140
 
250
- logger.warn('[getDb] pgEdge enabled but no matching POSTGRES bindings found', {
141
+ logger.error('[getDb] No POSTGRES binding found', undefined, {
142
+ locationsCount: locations.length,
251
143
  orderedLocations,
252
144
  postgresBindingRole: normalizedPostgresBindingRole || 'DEFAULT',
145
+ allAvailableBindings,
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
+ ),
253
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.");
254
154
  }
255
155
 
256
- const singleResolved = resolvePostgresBindingByCandidates(
257
- env,
258
- getSinglePostgresBindingCandidates(postgresBindingRole)
259
- );
156
+ const failoverOptions = resolvePgFailoverOptions(env, candidates.length);
260
157
 
261
- if (singleResolved) {
262
- if (env.PGEDGE_DEBUG_LOGGING) {
263
- logger.debug('[getDb] Using single POSTGRES binding', {
264
- selectedBinding: singleResolved.bindingName,
265
- postgresBindingRole: normalizedPostgresBindingRole || 'DEFAULT',
266
- });
267
- }
158
+ if (env.PGEDGE_DEBUG_LOGGING) {
159
+ logger.debug('[getDb] PostgreSQL failover config', {
160
+ candidates: candidates.map(formatCandidateLabel),
161
+ failoverEnabled: failoverOptions.enabled,
162
+ failoverConnectionTimeoutMs: failoverOptions.connectionTimeoutMs,
163
+ failoverWarnLogging: failoverOptions.warnLogging,
164
+ });
165
+ }
268
166
 
269
- return createPgDrizzleClient(singleResolved.connectionString, schema);
167
+ if (failoverOptions.enabled && candidates.length > 1) {
168
+ return createFailoverPgDrizzleClient(candidates, schema, failoverOptions);
270
169
  }
271
170
 
272
- logger.error('[getDb] No POSTGRES binding found', undefined, {
273
- locationsCount: locations.length,
274
- hasFallbackPOSTGRES: !!resolvePostgresBindingByCandidates(
275
- env,
276
- getSinglePostgresBindingCandidates(postgresBindingRole)
277
- ),
278
- postgresBindingRole: normalizedPostgresBindingRole || 'DEFAULT',
279
- envKeys: Object.keys(env).filter(k => k.startsWith('POSTGRES') || k.startsWith('PGEDGE') || k === 'DB_ENGINE'),
280
- });
281
- 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);
282
172
  }
283
173
 
284
174
  if (dbEngine === 'd1-sqlite' || (dbEngine === 'auto-detect' && env.D1)) {
@@ -288,55 +178,5 @@ export function getDb<S extends DrizzleSchema>(
288
178
  return createD1DrizzleClient(env.D1, schema);
289
179
  }
290
180
 
291
- throw new Error("No database binding found: bind either POSTGRES or D1 in your worker");
292
- }
293
-
294
- export function createD1DrizzleClient<S extends DrizzleSchema>(d1: D1Database, schema: S): DrizzleD1Client<S> {
295
- return drizzleD1(d1, { schema });
296
- }
297
-
298
- export function createPgDrizzleClient<S extends DrizzleSchema>(connectionString: string, schema: S): DrizzlePgClient<S> {
299
- try {
300
- const pool = new Pool({ connectionString });
301
- const drizzleClient = drizzlePg(pool, { schema });
302
- return drizzleClient;
303
- } catch (error) {
304
- getLogger().error('[createPgDrizzleClient] Error creating PostgreSQL client:', error instanceof Error ? error : new Error(String(error)));
305
- throw error;
306
- }
307
- }
308
-
309
- export function getPgEdgeLocations(env: AppEnvBindings): string[] {
310
- const isPgEdgeEnabled = env.PGEDGE_ENABLED === true || env.PGEDGE_ENABLED === 'true';
311
- if (!isPgEdgeEnabled) return [];
312
-
313
- let pgedgeLocations: string[] = [];
314
- if (env.PGEDGE_LOCATIONS) {
315
- try {
316
- const parsed = typeof env.PGEDGE_LOCATIONS === 'string'
317
- ? JSON.parse(env.PGEDGE_LOCATIONS)
318
- : env.PGEDGE_LOCATIONS;
319
-
320
- if (Array.isArray(parsed) && parsed.every(item => typeof item === 'string')) {
321
- pgedgeLocations = parsed.map(item => item.toLowerCase());
322
- } else {
323
- getLogger().warn('PGEDGE_LOCATIONS must be an array of strings');
324
- }
325
- } catch (e) {
326
- getLogger().warn('Failed to parse PGEDGE_LOCATIONS', e instanceof Error ? e : new Error(String(e)));
327
- }
328
- }
329
- return pgedgeLocations;
330
- }
331
-
332
- export function hasPostgresBindings(env: AppEnvBindings, role?: PostgresBindingRole): boolean {
333
- if (resolvePostgresBindingByCandidates(env, getSinglePostgresBindingCandidates(role))) return true;
334
-
335
- const locations = getPgEdgeLocations(env);
336
- if (locations.length > 0) {
337
- return locations.some(loc =>
338
- !!resolvePostgresBindingByCandidates(env, getPostgresLocationBindingCandidates(loc, role))
339
- );
340
- }
341
- return false;
181
+ throw new Error('No database binding found: bind either POSTGRES or D1 in your worker');
342
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
+ }