@danylohotvianskyi/bobra-framework 0.1.9 → 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 +80 -415
  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 -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 +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/failover.ts ADDED
@@ -0,0 +1,300 @@
1
+ import { Client, Pool, type PoolClient, type QueryResult, type QueryResultRow } from 'pg';
2
+ import { getLogger } from '../logging/logger';
3
+ import { formatCandidateLabel, readCandidateConnectionString } from './pgedge';
4
+ import type { PgFailoverOptions, PostgresCandidate } from './types';
5
+
6
+ type ErrorWithCode = Error & {
7
+ code?: unknown;
8
+ cause?: unknown;
9
+ };
10
+
11
+ const TRANSIENT_NODE_ERROR_CODES = new Set([
12
+ 'ECONNRESET',
13
+ 'ECONNREFUSED',
14
+ 'ETIMEDOUT',
15
+ 'ENOTFOUND',
16
+ 'EAI_AGAIN',
17
+ 'EPIPE',
18
+ ]);
19
+
20
+ const TRANSIENT_PG_SQLSTATE_CODES = new Set([
21
+ '57P01',
22
+ '57P02',
23
+ '57P03',
24
+ ]);
25
+
26
+ export function toError(error: unknown): Error {
27
+ return error instanceof Error ? error : new Error(String(error));
28
+ }
29
+
30
+ export function readErrorCode(error: unknown): string | undefined {
31
+ if (!error || typeof error !== 'object') return undefined;
32
+ const code = (error as { code?: unknown }).code;
33
+ return typeof code === 'string' ? code : undefined;
34
+ }
35
+
36
+ export function readErrorMessage(error: unknown): string {
37
+ if (error instanceof Error) return error.message;
38
+ if (typeof error === 'object' && error !== null) {
39
+ const message = (error as { message?: unknown }).message;
40
+ if (typeof message === 'string') return message;
41
+ }
42
+ return String(error);
43
+ }
44
+
45
+ export function isTransientConnectionOrUnavailableError(error: unknown): boolean {
46
+ let currentError: unknown = error;
47
+ const visited = new Set<unknown>();
48
+
49
+ while (currentError && typeof currentError === 'object' && !visited.has(currentError)) {
50
+ visited.add(currentError);
51
+
52
+ const errorCode = readErrorCode(currentError);
53
+ if (errorCode) {
54
+ if (TRANSIENT_NODE_ERROR_CODES.has(errorCode)) return true;
55
+ if (errorCode.startsWith('UND_ERR_')) return true;
56
+ if (errorCode.startsWith('08')) return true;
57
+ if (TRANSIENT_PG_SQLSTATE_CODES.has(errorCode)) return true;
58
+ if (errorCode === '58000') {
59
+ const message = readErrorMessage(currentError).toLowerCase();
60
+ const isHyperdriveTransient = message.includes('pool acquisition')
61
+ || message.includes('server connection attempt failed');
62
+ if (isHyperdriveTransient) return true;
63
+ }
64
+ }
65
+
66
+ currentError = (currentError as ErrorWithCode).cause;
67
+ }
68
+
69
+ return false;
70
+ }
71
+
72
+ type PoolEventName = Parameters<Pool['on']>[0];
73
+ type PoolListener = Parameters<Pool['on']>[1];
74
+
75
+ export interface FailoverPoolAdapter {
76
+ query: (...args: unknown[]) => Promise<QueryResult<QueryResultRow>>;
77
+ connect: () => Promise<PoolClient>;
78
+ end: () => Promise<void>;
79
+ on: (event: PoolEventName, listener: PoolListener) => unknown;
80
+ }
81
+
82
+ export interface FailoverDirectClientAdapter {
83
+ connect: () => Promise<void>;
84
+ query: (...args: unknown[]) => Promise<QueryResult<QueryResultRow>>;
85
+ end: () => Promise<void>;
86
+ release: () => void;
87
+ }
88
+
89
+ export function attachPoolErrorLogger(pool: FailoverPoolAdapter, context: Record<string, unknown>): void {
90
+ pool.on('error', (error: Error) => {
91
+ getLogger().warn('[getDb] PostgreSQL pool emitted background error', {
92
+ ...context,
93
+ errorCode: readErrorCode(error) || null,
94
+ message: readErrorMessage(error),
95
+ });
96
+ });
97
+ }
98
+
99
+ export class FailoverPgPool extends Pool {
100
+ private readonly pools = new Map<string, FailoverPoolAdapter>();
101
+ private readonly registeredListeners: Array<{ event: PoolEventName; listener: PoolListener }> = [];
102
+ private readonly healthyCandidateBindings = new Set<string>();
103
+
104
+ constructor(
105
+ private readonly candidates: PostgresCandidate[],
106
+ private readonly failoverOptions: PgFailoverOptions,
107
+ private readonly poolFactory: (candidate: PostgresCandidate, options: PgFailoverOptions) => FailoverPoolAdapter = (
108
+ candidate,
109
+ options
110
+ ) => new Pool({
111
+ connectionString: readCandidateConnectionString(candidate),
112
+ connectionTimeoutMillis: options.connectionTimeoutMs,
113
+ }),
114
+ private readonly directClientFactory: (
115
+ candidate: PostgresCandidate,
116
+ options: PgFailoverOptions
117
+ ) => FailoverDirectClientAdapter = (candidate, options) => {
118
+ const client = new Client({
119
+ connectionString: readCandidateConnectionString(candidate),
120
+ connectionTimeoutMillis: options.connectionTimeoutMs,
121
+ });
122
+
123
+ return {
124
+ connect: async () => {
125
+ await client.connect();
126
+ },
127
+ query: (...args: unknown[]) => {
128
+ const queryFn = client.query.bind(client) as (...queryArgs: unknown[]) => Promise<QueryResult<QueryResultRow>>;
129
+ return queryFn(...args);
130
+ },
131
+ end: () => client.end(),
132
+ release: () => {
133
+ void client.end().catch((error) => {
134
+ getLogger().warn('[getDb] Failed to close direct PostgreSQL failover client', {
135
+ binding: candidate.bindingName,
136
+ location: candidate.location || null,
137
+ errorCode: readErrorCode(error) || null,
138
+ message: readErrorMessage(error),
139
+ });
140
+ });
141
+ },
142
+ };
143
+ }
144
+ ) {
145
+ super();
146
+ }
147
+
148
+ private getPool(candidate: PostgresCandidate): FailoverPoolAdapter {
149
+ const existingPool = this.pools.get(candidate.bindingName);
150
+ if (existingPool) return existingPool;
151
+
152
+ const pool = this.poolFactory(candidate, this.failoverOptions);
153
+ attachPoolErrorLogger(pool, {
154
+ binding: candidate.bindingName,
155
+ location: candidate.location || null,
156
+ operation: 'pool',
157
+ });
158
+
159
+ for (const { event, listener } of this.registeredListeners) {
160
+ pool.on(event, listener);
161
+ }
162
+
163
+ this.pools.set(candidate.bindingName, pool);
164
+ return pool;
165
+ }
166
+
167
+ on(event: PoolEventName, listener: PoolListener): this {
168
+ super.on(event, listener);
169
+ this.registeredListeners.push({ event, listener });
170
+ for (const pool of this.pools.values()) {
171
+ pool.on(event, listener);
172
+ }
173
+ return this;
174
+ }
175
+
176
+ private invalidateCandidate(candidate: PostgresCandidate): void {
177
+ this.healthyCandidateBindings.delete(candidate.bindingName);
178
+
179
+ const pool = this.pools.get(candidate.bindingName);
180
+ if (!pool) return;
181
+
182
+ this.pools.delete(candidate.bindingName);
183
+ void pool.end().catch(() => undefined);
184
+ }
185
+
186
+ private async connectCandidate(candidate: PostgresCandidate): Promise<PoolClient> {
187
+ if (this.healthyCandidateBindings.has(candidate.bindingName)) {
188
+ const pool = this.getPool(candidate);
189
+ return await pool.connect();
190
+ }
191
+
192
+ const directClient = this.directClientFactory(candidate, this.failoverOptions);
193
+ await directClient.connect();
194
+ this.healthyCandidateBindings.add(candidate.bindingName);
195
+
196
+ return directClient as unknown as PoolClient;
197
+ }
198
+
199
+ async query<R extends QueryResultRow = QueryResultRow>(...args: unknown[]): Promise<QueryResult<R>> {
200
+ const logger = getLogger();
201
+ let lastError: Error | undefined;
202
+ const attemptedBindings: string[] = [];
203
+
204
+ for (let index = 0; index < this.candidates.length; index += 1) {
205
+ const candidate = this.candidates[index]!;
206
+ attemptedBindings.push(candidate.bindingName);
207
+ let client: PoolClient | undefined;
208
+
209
+ try {
210
+ client = await this.connectCandidate(candidate);
211
+ const queryFn = client.query.bind(client) as (...queryArgs: unknown[]) => Promise<QueryResult<R>>;
212
+ return await queryFn(...args);
213
+ } catch (error) {
214
+ lastError = toError(error);
215
+ this.invalidateCandidate(candidate);
216
+ const hasNextCandidate = index < this.candidates.length - 1;
217
+ const shouldFallback = hasNextCandidate && isTransientConnectionOrUnavailableError(error);
218
+
219
+ if (!shouldFallback) {
220
+ break;
221
+ }
222
+
223
+ if (this.failoverOptions.warnLogging) {
224
+ const nextCandidate = this.candidates[index + 1]!;
225
+ logger.warn('[getDb] Falling back to another PostgreSQL candidate after transient query error', {
226
+ operation: client ? 'query' : 'connect',
227
+ failedBinding: candidate.bindingName,
228
+ failedLocation: candidate.location || null,
229
+ fallbackBinding: nextCandidate.bindingName,
230
+ fallbackLocation: nextCandidate.location || null,
231
+ locationChanged: (candidate.location || null) !== (nextCandidate.location || null),
232
+ errorCode: readErrorCode(error) || null,
233
+ message: readErrorMessage(error),
234
+ });
235
+ }
236
+ } finally {
237
+ client?.release();
238
+ }
239
+ }
240
+
241
+ const errorToThrow = lastError ?? new Error('Postgres query failed without an error payload');
242
+ logger.error('[getDb] PostgreSQL failover exhausted for query', errorToThrow, {
243
+ attemptedBindings,
244
+ candidates: this.candidates.map(formatCandidateLabel),
245
+ transientClassified: isTransientConnectionOrUnavailableError(errorToThrow),
246
+ });
247
+ throw errorToThrow;
248
+ }
249
+
250
+ async connect(): Promise<PoolClient> {
251
+ const logger = getLogger();
252
+ let lastError: Error | undefined;
253
+ const attemptedBindings: string[] = [];
254
+
255
+ for (let index = 0; index < this.candidates.length; index += 1) {
256
+ const candidate = this.candidates[index]!;
257
+ attemptedBindings.push(candidate.bindingName);
258
+ try {
259
+ return await this.connectCandidate(candidate);
260
+ } catch (error) {
261
+ lastError = toError(error);
262
+ this.invalidateCandidate(candidate);
263
+ const hasNextCandidate = index < this.candidates.length - 1;
264
+ const shouldFallback = hasNextCandidate && isTransientConnectionOrUnavailableError(error);
265
+
266
+ if (!shouldFallback) {
267
+ break;
268
+ }
269
+
270
+ if (this.failoverOptions.warnLogging) {
271
+ const nextCandidate = this.candidates[index + 1]!;
272
+ logger.warn('[getDb] Falling back to another PostgreSQL candidate after transient connect error', {
273
+ operation: 'connect',
274
+ failedBinding: candidate.bindingName,
275
+ failedLocation: candidate.location || null,
276
+ fallbackBinding: nextCandidate.bindingName,
277
+ fallbackLocation: nextCandidate.location || null,
278
+ locationChanged: (candidate.location || null) !== (nextCandidate.location || null),
279
+ errorCode: readErrorCode(error) || null,
280
+ message: readErrorMessage(error),
281
+ });
282
+ }
283
+ }
284
+ }
285
+
286
+ const errorToThrow = lastError ?? new Error('Postgres connect failed without an error payload');
287
+ logger.error('[getDb] PostgreSQL failover exhausted for connect', errorToThrow, {
288
+ attemptedBindings,
289
+ candidates: this.candidates.map(formatCandidateLabel),
290
+ transientClassified: isTransientConnectionOrUnavailableError(errorToThrow),
291
+ });
292
+ throw errorToThrow;
293
+ }
294
+
295
+ async end(): Promise<void> {
296
+ const pools = [...this.pools.values()];
297
+ await Promise.all(pools.map((pool) => pool.end().catch(() => undefined)));
298
+ await super.end().catch(() => undefined);
299
+ }
300
+ }
package/db/index.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export * from './client';
2
2
  export * from './utils';
3
+ export * from './token-auth';
package/db/migrate.ts CHANGED
@@ -46,7 +46,8 @@ if (typeof process !== 'undefined' && process.versions && process.versions.node)
46
46
 
47
47
  // Only import Node.js specific modules conditionally
48
48
  let execSync: Function | null = null;
49
- let fs: any = null;
49
+ type NodeFsModule = typeof import('fs');
50
+ let fs: NodeFsModule | null = null;
50
51
 
51
52
  // Check if we're in Node.js environment
52
53
  const isNode = typeof process !== 'undefined' && process.versions && process.versions.node;
@@ -55,7 +56,7 @@ if (isNode) {
55
56
  // We're in Node.js - import Node-specific modules
56
57
  const childProcess = require('child_process');
57
58
  execSync = childProcess.execSync;
58
- fs = require('fs');
59
+ fs = require('fs') as NodeFsModule;
59
60
  }
60
61
 
61
62
  // Import DB modules that work in both environments
@@ -328,8 +329,8 @@ async function createInitialTokenPostgres(connectionString: string) {
328
329
  }
329
330
  const { token, record } = await createPublicApiToken({ initToken: true, name: 'Initial Instance Token' });
330
331
  await sqlClient`
331
- INSERT INTO tokens (uid, name, token_hash, token_salt, ip_addresses, expires_at, created_at, last_used_at, init_token)
332
- VALUES (${record.uid}, ${record.name || null}, ${record.tokenHash}, ${record.tokenSalt}, ${JSON.stringify(record.ipAddresses || [])}::jsonb, ${new Date(record.expiresAt)}, ${new Date(record.createdAt)}, ${null}, ${true})
332
+ INSERT INTO tokens (uid, name, token_hash, token_salt, expires_at, created_at, last_used_at, init_token)
333
+ VALUES (${record.uid}, ${record.name || null}, ${record.tokenHash}, ${record.tokenSalt}, ${new Date(record.expiresAt)}, ${new Date(record.createdAt)}, ${null}, ${true})
333
334
  `;
334
335
 
335
336
  // Run any app-specific SQL after core token insert (e.g. linking token to organizations)
@@ -389,8 +390,8 @@ async function createInitialTokenD1(options: { wranglerConfig: string, local?: b
389
390
  if (need) {
390
391
  // Core token insert — runs for all Bobra apps
391
392
  const coreSql = [
392
- `INSERT INTO tokens (uid, name, token_hash, token_salt, ip_addresses, expires_at, created_at, last_used_at, init_token)`,
393
- `SELECT '${record.uid}', ${record.name ? `'${record.name.replace(/'/g, "''")}'` : 'NULL'}, '${record.tokenHash}', '${record.tokenSalt}', '[]', '${new Date(record.expiresAt).toISOString()}', '${new Date(record.createdAt).toISOString()}', NULL, 1`,
393
+ `INSERT INTO tokens (uid, name, token_hash, token_salt, expires_at, created_at, last_used_at, init_token)`,
394
+ `SELECT '${record.uid}', ${record.name ? `'${record.name.replace(/'/g, "''")}'` : 'NULL'}, '${record.tokenHash}', '${record.tokenSalt}', '${new Date(record.expiresAt).toISOString()}', '${new Date(record.createdAt).toISOString()}', NULL, 1`,
394
395
  `WHERE (SELECT created FROM init_token_created WHERE id = 'singleton') = 0;`,
395
396
  "UPDATE init_token_created SET created = 1, created_at = datetime('now') WHERE id = 'singleton' AND created = 0;"
396
397
  ].join(' ').replace(/\\n/g, ' ');
package/db/pgedge.ts ADDED
@@ -0,0 +1,307 @@
1
+ import { getLogger } from '../logging/logger';
2
+ import type {
3
+ AppEnvBindings,
4
+ CfInfo,
5
+ PgEdgeRouter,
6
+ PgFailoverOptions,
7
+ PostgresBinding,
8
+ PostgresBindingRole,
9
+ PostgresCandidate,
10
+ ResolvedPostgresBinding,
11
+ } from './types';
12
+
13
+ const DEFAULT_FAILOVER_CONNECTION_TIMEOUT_MS = 2000;
14
+
15
+ function isPostgresBinding(value: unknown): value is PostgresBinding {
16
+ return typeof value === 'object' && value !== null;
17
+ }
18
+
19
+ export function normalizePostgresBindingRole(role?: PostgresBindingRole): string | undefined {
20
+ const trimmedRole = role?.trim();
21
+ if (!trimmedRole) return undefined;
22
+
23
+ const normalizedRole = trimmedRole.toUpperCase().replace(/[^A-Z0-9_]/g, '_');
24
+ if (!normalizedRole || normalizedRole === 'DEFAULT') return undefined;
25
+ return normalizedRole;
26
+ }
27
+
28
+ export function getPostgresLocationBindingCandidates(location: string, role?: PostgresBindingRole): string[] {
29
+ const normalizedLocation = location.toUpperCase();
30
+ const normalizedRole = normalizePostgresBindingRole(role);
31
+
32
+ if (!normalizedRole) {
33
+ return [
34
+ `POSTGRES_${normalizedLocation}`,
35
+ `POSTGRES_${normalizedLocation}_DEFAULT`,
36
+ ];
37
+ }
38
+
39
+ return [
40
+ `POSTGRES_${normalizedLocation}_${normalizedRole}`,
41
+ `POSTGRES_${normalizedLocation}`,
42
+ `POSTGRES_${normalizedLocation}_DEFAULT`,
43
+ ];
44
+ }
45
+
46
+ export function getAvailablePostgresBindingsForLocation(env: AppEnvBindings, location: string): string[] {
47
+ const normalizedLocation = location.toUpperCase();
48
+ const availableBindings: string[] = [];
49
+
50
+ Object.keys(env).forEach((key) => {
51
+ if (key.startsWith(`POSTGRES_${normalizedLocation}_`) || key === `POSTGRES_${normalizedLocation}`) {
52
+ if (isPostgresBinding(env[key])) {
53
+ availableBindings.push(key);
54
+ }
55
+ }
56
+ });
57
+
58
+ return availableBindings;
59
+ }
60
+
61
+ function getSinglePostgresBindingCandidates(role?: PostgresBindingRole): string[] {
62
+ const normalizedRole = normalizePostgresBindingRole(role);
63
+
64
+ if (!normalizedRole) {
65
+ return ['POSTGRES', 'POSTGRES_DEFAULT'];
66
+ }
67
+
68
+ return [`POSTGRES_${normalizedRole}`, 'POSTGRES', 'POSTGRES_DEFAULT'];
69
+ }
70
+
71
+ function resolvePostgresBindingByCandidates(
72
+ env: AppEnvBindings,
73
+ candidateBindingNames: string[]
74
+ ): ResolvedPostgresBinding | undefined {
75
+ for (const bindingName of candidateBindingNames) {
76
+ const binding = env[bindingName];
77
+ if (isPostgresBinding(binding)) {
78
+ return {
79
+ bindingName,
80
+ binding,
81
+ };
82
+ }
83
+ }
84
+
85
+ return undefined;
86
+ }
87
+
88
+ function parseBooleanEnv(value: unknown, defaultValue: boolean): boolean {
89
+ if (typeof value === 'boolean') return value;
90
+ if (typeof value === 'string') {
91
+ const normalizedValue = value.trim().toLowerCase();
92
+ if (normalizedValue === 'true') return true;
93
+ if (normalizedValue === 'false') return false;
94
+ }
95
+ return defaultValue;
96
+ }
97
+
98
+ function parsePositiveIntegerEnv(value: unknown, defaultValue: number): number {
99
+ if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
100
+ return Math.floor(value);
101
+ }
102
+
103
+ if (typeof value === 'string') {
104
+ const parsed = Number.parseInt(value, 10);
105
+ if (Number.isFinite(parsed) && parsed > 0) {
106
+ return parsed;
107
+ }
108
+ }
109
+
110
+ return defaultValue;
111
+ }
112
+
113
+ function resolveFallbackBindingCandidates(
114
+ availableBindings: string[],
115
+ normalizedPostgresBindingRole?: string
116
+ ): string[] {
117
+ if (!normalizedPostgresBindingRole) {
118
+ const liveBindings = availableBindings.filter((binding) => binding.endsWith('_LIVE'));
119
+ return liveBindings.length > 0 ? liveBindings : availableBindings;
120
+ }
121
+
122
+ const fallbackCandidates = availableBindings.filter(
123
+ (binding) => !binding.includes(`_${normalizedPostgresBindingRole}`)
124
+ );
125
+ return fallbackCandidates.length > 0 ? fallbackCandidates : availableBindings;
126
+ }
127
+
128
+ function resolvePostgresLocationCandidate(
129
+ env: AppEnvBindings,
130
+ location: string,
131
+ postgresBindingRole?: PostgresBindingRole
132
+ ): PostgresCandidate | undefined {
133
+ const normalizedPostgresBindingRole = normalizePostgresBindingRole(postgresBindingRole);
134
+ const directResolved = resolvePostgresBindingByCandidates(
135
+ env,
136
+ getPostgresLocationBindingCandidates(location, postgresBindingRole)
137
+ );
138
+
139
+ if (directResolved) {
140
+ return {
141
+ ...directResolved,
142
+ location,
143
+ };
144
+ }
145
+
146
+ const availableBindings = getAvailablePostgresBindingsForLocation(env, location);
147
+ if (availableBindings.length === 0) return undefined;
148
+
149
+ const preferredBindings = resolveFallbackBindingCandidates(
150
+ availableBindings,
151
+ normalizedPostgresBindingRole
152
+ );
153
+ const fallbackBinding = resolvePostgresBindingByCandidates(env, preferredBindings);
154
+
155
+ if (!fallbackBinding) return undefined;
156
+ return {
157
+ ...fallbackBinding,
158
+ location,
159
+ };
160
+ }
161
+
162
+ function resolveSinglePostgresCandidate(
163
+ env: AppEnvBindings,
164
+ postgresBindingRole?: PostgresBindingRole
165
+ ): PostgresCandidate | undefined {
166
+ const directResolved = resolvePostgresBindingByCandidates(
167
+ env,
168
+ getSinglePostgresBindingCandidates(postgresBindingRole)
169
+ );
170
+
171
+ if (directResolved) {
172
+ return directResolved;
173
+ }
174
+
175
+ const normalizedPostgresBindingRole = normalizePostgresBindingRole(postgresBindingRole);
176
+ const allPostgresBindings = Object.keys(env).filter(
177
+ (key) => key.startsWith('POSTGRES') && isPostgresBinding(env[key])
178
+ );
179
+
180
+ if (allPostgresBindings.length === 0) return undefined;
181
+
182
+ const preferredBindings = resolveFallbackBindingCandidates(
183
+ allPostgresBindings,
184
+ normalizedPostgresBindingRole
185
+ );
186
+ return resolvePostgresBindingByCandidates(env, preferredBindings);
187
+ }
188
+
189
+ function dedupePostgresCandidates(candidates: PostgresCandidate[]): PostgresCandidate[] {
190
+ const seenBindingNames = new Set<string>();
191
+ const dedupedCandidates: PostgresCandidate[] = [];
192
+
193
+ for (const candidate of candidates) {
194
+ if (seenBindingNames.has(candidate.bindingName)) continue;
195
+ seenBindingNames.add(candidate.bindingName);
196
+ dedupedCandidates.push(candidate);
197
+ }
198
+
199
+ return dedupedCandidates;
200
+ }
201
+
202
+ export function buildOrderedPostgresCandidates(
203
+ env: AppEnvBindings,
204
+ postgresBindingRole: PostgresBindingRole | undefined,
205
+ locations: string[],
206
+ pgEdgeRouter: PgEdgeRouter,
207
+ continent: string | undefined,
208
+ cfInfo: CfInfo | undefined
209
+ ): { candidates: PostgresCandidate[]; orderedLocations: string[] } {
210
+ if (locations.length === 0) {
211
+ const singleCandidate = resolveSinglePostgresCandidate(env, postgresBindingRole);
212
+ return {
213
+ candidates: singleCandidate ? [singleCandidate] : [],
214
+ orderedLocations: [],
215
+ };
216
+ }
217
+
218
+ let orderedLocations = [...locations];
219
+ if (locations.length > 1) {
220
+ const targetLocation = pgEdgeRouter(locations, (continent || '').toUpperCase(), cfInfo);
221
+ orderedLocations = [targetLocation, ...locations.filter((location) => location !== targetLocation)];
222
+ }
223
+
224
+ const pgEdgeCandidates = orderedLocations
225
+ .map((location) => resolvePostgresLocationCandidate(env, location, postgresBindingRole))
226
+ .filter((candidate): candidate is PostgresCandidate => !!candidate);
227
+ const singleCandidate = resolveSinglePostgresCandidate(env, postgresBindingRole);
228
+
229
+ return {
230
+ candidates: dedupePostgresCandidates(singleCandidate ? [...pgEdgeCandidates, singleCandidate] : pgEdgeCandidates),
231
+ orderedLocations,
232
+ };
233
+ }
234
+
235
+ export function resolvePgFailoverOptions(env: AppEnvBindings, candidateCount: number): PgFailoverOptions {
236
+ const defaultFailoverEnabled = candidateCount > 1;
237
+ return {
238
+ enabled: parseBooleanEnv(env.PGEDGE_FAILOVER_ENABLED, defaultFailoverEnabled),
239
+ connectionTimeoutMs: parsePositiveIntegerEnv(
240
+ env.PGEDGE_FAILOVER_CONNECTION_TIMEOUT_MS,
241
+ DEFAULT_FAILOVER_CONNECTION_TIMEOUT_MS
242
+ ),
243
+ warnLogging: parseBooleanEnv(env.PGEDGE_FAILOVER_WARN_LOGGING, true),
244
+ };
245
+ }
246
+
247
+ export function formatCandidateLabel(candidate: PostgresCandidate): string {
248
+ return candidate.location ? `${candidate.bindingName}(${candidate.location})` : candidate.bindingName;
249
+ }
250
+
251
+ export function readCandidateConnectionString(candidate: PostgresCandidate): string {
252
+ return candidate.binding.connectionString;
253
+ }
254
+
255
+ export const defaultPgEdgeRouter: PgEdgeRouter = (locations: string[], cfContinentStr?: string) => {
256
+ let targetLocation = locations[0]!;
257
+
258
+ if (cfContinentStr === 'EU' && locations.includes('eu')) {
259
+ targetLocation = 'eu';
260
+ } else if (cfContinentStr === 'NA' && locations.includes('us')) {
261
+ targetLocation = 'us';
262
+ } else if (locations.includes('eu')) {
263
+ targetLocation = 'eu';
264
+ }
265
+
266
+ return targetLocation;
267
+ };
268
+
269
+ export function getPgEdgeLocations(env: AppEnvBindings): string[] {
270
+ const isPgEdgeEnabled = env.PGEDGE_ENABLED === true || env.PGEDGE_ENABLED === 'true';
271
+ if (!isPgEdgeEnabled) return [];
272
+
273
+ let pgedgeLocations: string[] = [];
274
+ if (env.PGEDGE_LOCATIONS) {
275
+ try {
276
+ const parsed = typeof env.PGEDGE_LOCATIONS === 'string'
277
+ ? JSON.parse(env.PGEDGE_LOCATIONS)
278
+ : env.PGEDGE_LOCATIONS;
279
+
280
+ if (Array.isArray(parsed) && parsed.every((item) => typeof item === 'string')) {
281
+ pgedgeLocations = parsed.map((item) => item.toLowerCase());
282
+ } else {
283
+ getLogger().warn('PGEDGE_LOCATIONS must be an array of strings');
284
+ }
285
+ } catch (e) {
286
+ const parseError = e instanceof Error ? e : new Error(String(e));
287
+ getLogger().warn('Failed to parse PGEDGE_LOCATIONS', {
288
+ name: parseError.name,
289
+ message: parseError.message,
290
+ });
291
+ }
292
+ }
293
+ return pgedgeLocations;
294
+ }
295
+
296
+ export function hasPostgresBindings(env: AppEnvBindings, role?: PostgresBindingRole): boolean {
297
+ const locations = getPgEdgeLocations(env);
298
+ const { candidates } = buildOrderedPostgresCandidates(
299
+ env,
300
+ role,
301
+ locations,
302
+ defaultPgEdgeRouter,
303
+ undefined,
304
+ undefined
305
+ );
306
+ return candidates.length > 0;
307
+ }