@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.
- package/batteries/auth/hash.ts +102 -36
- package/batteries/auth/token-metadata.ts +25 -8
- package/batteries/auth/token.ts +5 -5
- package/batteries/openapi/index.ts +62 -41
- package/batteries/openapi/merge-openapi.ts +125 -33
- package/core/config.ts +40 -14
- package/core/discovery.ts +16 -10
- package/core/env-resolver.ts +25 -11
- package/core/factory.ts +150 -77
- package/core/spa.ts +14 -8
- package/db/client.ts +85 -245
- package/db/drizzle-clients.ts +65 -0
- package/db/failover.ts +300 -0
- package/db/index.ts +1 -0
- package/db/migrate.ts +7 -6
- package/db/pgedge.ts +307 -0
- package/db/test/client.test.ts +297 -0
- package/db/token-auth.ts +40 -0
- package/db/types.ts +96 -0
- package/dist/batteries/auth/hash.d.ts +10 -2
- package/dist/batteries/auth/hash.js +78 -43
- package/dist/batteries/auth/hash.js.map +1 -1
- package/dist/batteries/auth/token-metadata.d.ts +3 -3
- package/dist/batteries/auth/token-metadata.js +14 -6
- package/dist/batteries/auth/token-metadata.js.map +1 -1
- package/dist/batteries/auth/token.d.ts +3 -3
- package/dist/batteries/auth/token.js +2 -2
- package/dist/batteries/auth/token.js.map +1 -1
- package/dist/batteries/openapi/index.d.ts +51 -13
- package/dist/batteries/openapi/index.js +25 -15
- package/dist/batteries/openapi/index.js.map +1 -1
- package/dist/batteries/openapi/merge-openapi.d.ts +26 -2
- package/dist/batteries/openapi/merge-openapi.js +83 -26
- package/dist/batteries/openapi/merge-openapi.js.map +1 -1
- package/dist/core/config.d.ts +26 -9
- package/dist/core/config.js +8 -7
- package/dist/core/config.js.map +1 -1
- package/dist/core/discovery.d.ts +18 -9
- package/dist/core/discovery.js +1 -1
- package/dist/core/discovery.js.map +1 -1
- package/dist/core/env-resolver.d.ts +7 -4
- package/dist/core/env-resolver.js +7 -5
- package/dist/core/env-resolver.js.map +1 -1
- package/dist/core/factory.d.ts +36 -16
- package/dist/core/factory.js +70 -38
- package/dist/core/factory.js.map +1 -1
- package/dist/core/spa.js +9 -4
- package/dist/core/spa.js.map +1 -1
- package/dist/db/client.d.ts +16 -59
- package/dist/db/client.js +47 -171
- package/dist/db/client.js.map +1 -1
- package/dist/db/drizzle-clients.d.ts +6 -0
- package/dist/db/drizzle-clients.js +42 -0
- package/dist/db/drizzle-clients.js.map +1 -0
- package/dist/db/failover.d.ts +39 -0
- package/dist/db/failover.js +251 -0
- package/dist/db/failover.js.map +1 -0
- package/dist/db/index.d.ts +1 -0
- package/dist/db/index.js +1 -0
- package/dist/db/index.js.map +1 -1
- package/dist/db/migrate.js +4 -4
- package/dist/db/migrate.js.map +1 -1
- package/dist/db/pgedge.d.ts +14 -0
- package/dist/db/pgedge.js +218 -0
- package/dist/db/pgedge.js.map +1 -0
- package/dist/db/token-auth.d.ts +34 -0
- package/dist/db/token-auth.js +15 -0
- package/dist/db/token-auth.js.map +1 -0
- package/dist/db/types.d.ts +82 -0
- package/dist/db/types.js +2 -0
- package/dist/db/types.js.map +1 -0
- package/dist/logging/logger.d.ts +13 -13
- package/dist/logging/logger.js +11 -2
- package/dist/logging/logger.js.map +1 -1
- package/dist/logging/logging-middleware.d.ts +1 -1
- package/dist/logging/logging-middleware.js +6 -6
- package/dist/logging/logging-middleware.js.map +1 -1
- package/dist/middleware/ensure-api-token.d.ts +33 -4
- package/dist/middleware/ensure-api-token.js.map +1 -1
- package/dist/middleware/utils.d.ts +5 -1
- package/dist/middleware/utils.js +11 -7
- package/dist/middleware/utils.js.map +1 -1
- package/dist/network/router.d.ts +9 -6
- package/dist/network/router.js +3 -1
- package/dist/network/router.js.map +1 -1
- package/dist/network/service-discovery.d.ts +1 -1
- package/dist/network/service-discovery.js.map +1 -1
- package/dist/network/service-fetch.d.ts +6 -9
- package/dist/network/service-fetch.js +14 -4
- package/dist/network/service-fetch.js.map +1 -1
- package/dist/node/generate-wrangler-config.d.ts +28 -4
- package/dist/node/generate-wrangler-config.js +75 -20
- package/dist/node/generate-wrangler-config.js.map +1 -1
- package/logging/logger.ts +31 -21
- package/logging/logging-middleware.ts +12 -9
- package/middleware/ensure-api-token.ts +8 -6
- package/middleware/utils.ts +26 -8
- package/network/router.ts +17 -13
- package/network/service-discovery.ts +1 -1
- package/network/service-fetch.ts +26 -17
- package/node/generate-wrangler-config.ts +160 -24
- 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
|
|
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?:
|
|
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
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
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
|
-
|
|
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?:
|
|
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 (
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
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
|
-
|
|
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.
|
|
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
|
|
257
|
-
env,
|
|
258
|
-
getSinglePostgresBindingCandidates(postgresBindingRole)
|
|
259
|
-
);
|
|
156
|
+
const failoverOptions = resolvePgFailoverOptions(env, candidates.length);
|
|
260
157
|
|
|
261
|
-
if (
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
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
|
-
|
|
167
|
+
if (failoverOptions.enabled && candidates.length > 1) {
|
|
168
|
+
return createFailoverPgDrizzleClient(candidates, schema, failoverOptions);
|
|
270
169
|
}
|
|
271
170
|
|
|
272
|
-
|
|
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(
|
|
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
|
+
}
|