@owlmeans/postgres 0.1.18-rc.43 → 0.1.18-rc.45

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 (46) hide show
  1. package/README.md +5 -4
  2. package/agent-meta/manifest.json +2 -2
  3. package/agent-meta/skills/postgres/SKILL.md +1 -1
  4. package/build/bootstrap.d.ts.map +1 -1
  5. package/build/bootstrap.js +12 -7
  6. package/build/bootstrap.js.map +1 -1
  7. package/build/index.d.ts +2 -0
  8. package/build/index.d.ts.map +1 -1
  9. package/build/index.js.map +1 -1
  10. package/build/service.d.ts +1 -5
  11. package/build/service.d.ts.map +1 -1
  12. package/build/service.js +18 -9
  13. package/build/service.js.map +1 -1
  14. package/build/types.local.d.ts +5 -0
  15. package/build/types.local.d.ts.map +1 -0
  16. package/build/types.local.js +2 -0
  17. package/build/types.local.js.map +1 -0
  18. package/build/utils/config/types.d.ts +30 -0
  19. package/build/utils/config/types.d.ts.map +1 -0
  20. package/build/utils/config/types.js +2 -0
  21. package/build/utils/config/types.js.map +1 -0
  22. package/build/utils/config.d.ts +4 -24
  23. package/build/utils/config.d.ts.map +1 -1
  24. package/build/utils/config.js +74 -87
  25. package/build/utils/config.js.map +1 -1
  26. package/build/utils/connection/types.d.ts +17 -0
  27. package/build/utils/connection/types.d.ts.map +1 -0
  28. package/build/utils/connection/types.js +2 -0
  29. package/build/utils/connection/types.js.map +1 -0
  30. package/build/utils/connection.d.ts +2 -13
  31. package/build/utils/connection.d.ts.map +1 -1
  32. package/build/utils/connection.js +33 -37
  33. package/build/utils/connection.js.map +1 -1
  34. package/package.json +13 -12
  35. package/src/bootstrap.ts +13 -11
  36. package/src/index.ts +2 -0
  37. package/src/service.ts +23 -20
  38. package/src/types.local.ts +5 -0
  39. package/src/utils/config/types.ts +28 -0
  40. package/src/utils/config.ts +80 -89
  41. package/src/utils/connection/types.ts +17 -0
  42. package/src/utils/connection.ts +36 -36
  43. package/tests/context.ts +3 -3
  44. package/tests/criteria.spec.ts +2 -2
  45. package/tests/migration.spec.ts +3 -3
  46. package/tests/sync.spec.ts +3 -3
@@ -1,15 +1,4 @@
1
- import type { PostgresMeta } from '@owlmeans/postgres-resource';
2
1
  import type { Pool } from 'pg';
3
- /**
4
- * Wait for the server to answer a query, not merely to accept a socket.
5
- *
6
- * Postgres binds its port before it finishes recovery, so a sidecar or an operator managed
7
- * instance routinely accepts a connection and then refuses to run anything. Every OwlMeans
8
- * deployment grew its own copy of this loop; this is the one.
9
- *
10
- * @throws {PostgresConnectionError}
11
- */
12
- export declare const probe: (pool: Pool, meta: PostgresMeta, location: string) => Promise<void>;
13
- /** `CREATE SCHEMA IF NOT EXISTS` on a pooled connection. */
14
- export declare const ensureSchema: (pool: Pool, schema: string) => Promise<void>;
2
+ import type { PgConnectionHelper } from './connection/types.js';
3
+ export declare const makePgConnectionHelper: (pool: Pool) => PgConnectionHelper;
15
4
  //# sourceMappingURL=connection.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"connection.d.ts","sourceRoot":"","sources":["../../src/utils/connection.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAA;AAC/D,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,IAAI,CAAA;AAkB9B;;;;;;;;GAQG;AACH,eAAO,MAAM,KAAK,SAAgB,IAAI,QAAQ,YAAY,YAAY,MAAM,KAAG,OAAO,CAAC,IAAI,CAyB1F,CAAA;AAED,4DAA4D;AAC5D,eAAO,MAAM,YAAY,SAAgB,IAAI,UAAU,MAAM,KAAG,OAAO,CAAC,IAAI,CAM3E,CAAA"}
1
+ {"version":3,"file":"connection.d.ts","sourceRoot":"","sources":["../../src/utils/connection.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,IAAI,CAAA;AAG9B,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAA;AAkB/D,eAAO,MAAM,sBAAsB,SAAU,IAAI,KAAG,kBAuCnD,CAAA"}
@@ -1,5 +1,7 @@
1
- import { pgErrorToResourceError, PostgresConnectionError, quoteIdent } from '@owlmeans/postgres-resource';
1
+ import { pgErrorHelper, pgNameHelper, PostgresConnectionError } from '@owlmeans/postgres-resource';
2
+ import { logger } from '@owlmeans/log';
2
3
  import { DEF_RETRIES, DEF_RETRY_DELAY, TERMINAL_CONNECT_CODES } from '../consts.js';
4
+ const log = logger('postgres');
3
5
  /**
4
6
  * Retryable means "the server isn't up yet". A driver level failure carries no `code` at
5
7
  * all (`ECONNREFUSED`, DNS) and is exactly the case worth waiting on; a Postgres error
@@ -12,45 +14,39 @@ const isTransient = (error) => {
12
14
  }
13
15
  return !TERMINAL_CONNECT_CODES.includes(code);
14
16
  };
15
- /**
16
- * Wait for the server to answer a query, not merely to accept a socket.
17
- *
18
- * Postgres binds its port before it finishes recovery, so a sidecar or an operator managed
19
- * instance routinely accepts a connection and then refuses to run anything. Every OwlMeans
20
- * deployment grew its own copy of this loop; this is the one.
21
- *
22
- * @throws {PostgresConnectionError}
23
- */
24
- export const probe = async (pool, meta, location) => {
25
- const retries = Math.max(1, meta.retries ?? DEF_RETRIES);
26
- const delay = meta.retryDelayMillis ?? DEF_RETRY_DELAY;
27
- let last;
28
- for (let attempt = 1; attempt <= retries; ++attempt) {
17
+ export const makePgConnectionHelper = (pool) => {
18
+ const { pgErrorToResourceError } = pgErrorHelper;
19
+ const probe = async (meta, location) => {
20
+ const retries = Math.max(1, meta.retries ?? DEF_RETRIES);
21
+ const delay = meta.retryDelayMillis ?? DEF_RETRY_DELAY;
22
+ let last;
23
+ for (let attempt = 1; attempt <= retries; ++attempt) {
24
+ try {
25
+ await pool.query('SELECT 1');
26
+ return;
27
+ }
28
+ catch (error) {
29
+ last = error;
30
+ if (attempt === retries || !isTransient(error)) {
31
+ break;
32
+ }
33
+ log.debug('Postgres not ready, retrying', { location, attempt, retries, delay });
34
+ await new Promise(resolve => setTimeout(resolve, delay));
35
+ }
36
+ }
37
+ const translated = pgErrorToResourceError(last);
38
+ const failure = new PostgresConnectionError(`unreachable:${location}:${translated.message}`);
39
+ failure.cause = last;
40
+ throw failure;
41
+ };
42
+ const ensureSchema = async (schema) => {
29
43
  try {
30
- await pool.query('SELECT 1');
31
- return;
44
+ await pool.query(`CREATE SCHEMA IF NOT EXISTS ${pgNameHelper.quoteIdent(schema)}`);
32
45
  }
33
46
  catch (error) {
34
- last = error;
35
- if (attempt === retries || !isTransient(error)) {
36
- break;
37
- }
38
- console.log(`${location}: not ready (${attempt}/${retries}), retrying in ${delay}ms…`);
39
- await new Promise(resolve => setTimeout(resolve, delay));
47
+ throw pgErrorToResourceError(error);
40
48
  }
41
- }
42
- const translated = pgErrorToResourceError(last);
43
- const failure = new PostgresConnectionError(`unreachable:${location}:${translated.message}`);
44
- failure.cause = last;
45
- throw failure;
46
- };
47
- /** `CREATE SCHEMA IF NOT EXISTS` on a pooled connection. */
48
- export const ensureSchema = async (pool, schema) => {
49
- try {
50
- await pool.query(`CREATE SCHEMA IF NOT EXISTS ${quoteIdent(schema)}`);
51
- }
52
- catch (error) {
53
- throw pgErrorToResourceError(error);
54
- }
49
+ };
50
+ return { probe, ensureSchema };
55
51
  };
56
52
  //# sourceMappingURL=connection.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"connection.js","sourceRoot":"","sources":["../../src/utils/connection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,uBAAuB,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAA;AAIzG,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAA;AAEnF;;;;GAIG;AACH,MAAM,WAAW,GAAG,CAAC,KAAc,EAAW,EAAE;IAC9C,MAAM,IAAI,GAAI,KAAkC,EAAE,IAAI,CAAA;IACtD,IAAI,IAAI,IAAI,IAAI,EAAE,CAAC;QACjB,OAAO,IAAI,CAAA;IACb,CAAC;IAED,OAAO,CA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
1
1
  {
2
2
  "name": "@owlmeans/postgres",
3
- "version": "0.1.18-rc.43",
3
+ "version": "0.1.18-rc.45",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -22,20 +22,21 @@
22
22
  }
23
23
  },
24
24
  "dependencies": {
25
- "@owlmeans/basic-keys": "^0.1.18-rc.45",
26
- "@owlmeans/context": "^0.1.18-rc.32",
27
- "@owlmeans/postgres-resource": "^0.1.18-rc.41",
28
- "@owlmeans/resource": "^0.1.18-rc.37",
29
- "@owlmeans/server-context": "^0.1.18-rc.40",
30
- "drizzle-orm": "~0.45.2",
31
- "pg": "^8.22.0"
25
+ "@owlmeans/basic-keys": "^0.1.18-rc.48",
26
+ "@owlmeans/context": "^0.1.18-rc.34",
27
+ "@owlmeans/postgres-resource": "^0.1.18-rc.43",
28
+ "@owlmeans/resource": "^0.1.18-rc.40",
29
+ "@owlmeans/server-context": "^0.1.18-rc.43",
30
+ "@owlmeans/log": "^0.1.18-rc.2",
31
+ "drizzle-orm": "~0.45.3",
32
+ "pg": "^8.23.1"
32
33
  },
33
34
  "devDependencies": {
34
35
  "@owlmeans/dep-config": "workspace:*",
35
- "@owlmeans/test-integration": "^0.1.18-rc.30",
36
- "@types/bun": "^1.4.0",
37
- "@types/node": "^26.1.0",
38
- "@types/pg": "^8.20.4",
36
+ "@owlmeans/test-integration": "^0.1.18-rc.33",
37
+ "@types/bun": "^1.4.2",
38
+ "@types/node": "^26.6.4",
39
+ "@types/pg": "^8.23.1",
39
40
  "nodemon": "^3.1.14",
40
41
  "typescript": "^7.0.2"
41
42
  },
package/src/bootstrap.ts CHANGED
@@ -1,11 +1,12 @@
1
- import {
2
- assertSqlIdentifier, PostgresBootstrapError, quoteIdent, quoteLiteral
3
- } from '@owlmeans/postgres-resource'
1
+ import { pgNameHelper, PostgresBootstrapError } from '@owlmeans/postgres-resource'
2
+ import { logger } from '@owlmeans/log'
4
3
  import { Pool } from 'pg'
5
4
  import type { PoolClient } from 'pg'
6
5
 
7
6
  import type { BootstrapOptions, BootstrapReport, PostgresService } from './types.js'
8
- import { prepareConfig } from './utils/config.js'
7
+ import { pgConfigHelper } from './utils/config.js'
8
+
9
+ const log = logger('postgres')
9
10
 
10
11
  const exists = async (client: PoolClient, text: string, value: string): Promise<boolean> => {
11
12
  const result = await client.query(text, [value])
@@ -29,6 +30,7 @@ const exists = async (client: PoolClient, text: string, value: string): Promise<
29
30
  export const bootstrapDb = async (
30
31
  service: PostgresService, configAlias: string, opts: BootstrapOptions
31
32
  ): Promise<BootstrapReport> => {
33
+ const { assertSqlIdentifier, quoteIdent, quoteLiteral } = pgNameHelper
32
34
  const role = assertSqlIdentifier(opts.role, 'role')
33
35
  const database = assertSqlIdentifier(opts.database ?? opts.role, 'database')
34
36
  const schema = opts.schema != null ? assertSqlIdentifier(opts.schema, 'schema') : null
@@ -80,7 +82,7 @@ export const bootstrapDb = async (
80
82
  client.release()
81
83
  }
82
84
 
83
- const target = new Pool(prepareConfig(config, { database, max: 1 }))
85
+ const target = new Pool(pgConfigHelper.prepareConfig(config, { database, max: 1 }))
84
86
  try {
85
87
  if (schema != null) {
86
88
  /**
@@ -108,12 +110,12 @@ export const bootstrapDb = async (
108
110
  await target.end().catch(() => undefined)
109
111
  }
110
112
 
111
- console.log(
112
- `@owlmeans/postgres: bootstrap ${role}@${database} —`
113
- + ` role ${report.roleCreated ? 'created' : report.passwordRotated ? 'rotated' : 'present'},`
114
- + ` database ${report.databaseCreated ? 'created' : 'present'}`
115
- + (schema != null ? `, schema ${schema} ready` : '')
116
- )
113
+ log.info('Postgres bootstrap applied', {
114
+ role, database,
115
+ roleState: report.roleCreated ? 'created' : report.passwordRotated ? 'rotated' : 'present',
116
+ databaseState: report.databaseCreated ? 'created' : 'present',
117
+ ...(schema != null ? { schema } : {}),
118
+ }, { event: 'db.bootstrap' })
117
119
 
118
120
  return report
119
121
  }
package/src/index.ts CHANGED
@@ -4,4 +4,6 @@ export * from './bootstrap.js'
4
4
  export * from './middleware.js'
5
5
  export * from './service.js'
6
6
  export * from './utils/config.js'
7
+ export type * from './utils/config/types.js'
7
8
  export * from './utils/connection.js'
9
+ export type * from './utils/connection/types.js'
package/src/service.ts CHANGED
@@ -1,28 +1,27 @@
1
1
  import { makeKeyPairModel } from '@owlmeans/basic-keys'
2
2
  import { assertContext } from '@owlmeans/context'
3
- import {
4
- makeTx, pgErrorToResourceError, pgIdentifier, refOf, resolvePlaceholders
5
- } from '@owlmeans/postgres-resource'
6
- import type { PostgresDb, PostgresMeta } from '@owlmeans/postgres-resource'
3
+ import { makeTx, pgErrorHelper, pgNameHelper, pgPlaceholdersOf, type PostgresDb, type PostgresMeta } from '@owlmeans/postgres-resource'
4
+ import { logThrottle, logger } from '@owlmeans/log'
7
5
  import { createDbService } from '@owlmeans/resource'
8
- import type { ServerConfig, ServerContext } from '@owlmeans/server-context'
9
- import { drizzle } from 'drizzle-orm/node-postgres'
10
- import type { NodePgDatabase } from 'drizzle-orm/node-postgres'
11
- import { Pool } from 'pg'
12
- import type { QueryResultRow } from 'pg'
6
+ import { drizzle, type NodePgDatabase } from 'drizzle-orm/node-postgres'
7
+ import { Pool, type QueryResultRow } from 'pg'
13
8
 
14
9
  import { DEFAULT_ALIAS } from './consts.js'
15
10
  import { bootstrapDb } from './bootstrap.js'
16
11
  import { drainMiddleware } from './middleware.js'
17
12
  import type { PostgresService } from './types.js'
18
- import { poolDatabase, prepareConfig } from './utils/config.js'
19
- import { ensureSchema, probe } from './utils/connection.js'
13
+ import { pgConfigHelper } from './utils/config.js'
14
+ import { makePgConnectionHelper } from './utils/connection.js'
15
+ import type { Config, Context } from './types.local.js'
16
+
17
+ const log = logger('postgres')
20
18
 
21
- type Config = ServerConfig
22
- interface Context<C extends Config = Config> extends ServerContext<C> { }
23
19
 
24
20
  export const makePostgresDbService = (alias: string = DEFAULT_ALIAS): PostgresService => {
25
21
  const location = `postgres:${alias}`
22
+ const { pgErrorToResourceError } = pgErrorHelper
23
+ const { pgIdentifier } = pgNameHelper
24
+ const { poolDatabase, prepareConfig } = pgConfigHelper
26
25
 
27
26
  /**
28
27
  * Handles are cached per config alias rather than rebuilt per call: `db()` runs on every
@@ -66,6 +65,7 @@ export const makePostgresDbService = (alias: string = DEFAULT_ALIAS): PostgresSe
66
65
 
67
66
  const meta = (config.meta ?? {}) as PostgresMeta
68
67
  const pool = new Pool(prepareConfig(config))
68
+ const connection = makePgConnectionHelper(pool)
69
69
 
70
70
  /**
71
71
  * Not optional: node-postgres emits `error` on *idle* clients when the server closes
@@ -73,11 +73,13 @@ export const makePostgresDbService = (alias: string = DEFAULT_ALIAS): PostgresSe
73
73
  * on an EventEmitter terminates the process.
74
74
  */
75
75
  pool.on('error', error => {
76
- console.error(`${location}: idle client error — ${(error as Error).message}`)
76
+ if (logThrottle(`${location}:idle-error`)) {
77
+ log.warn('Postgres idle client error', { location, error })
78
+ }
77
79
  })
78
80
 
79
81
  try {
80
- await probe(pool, meta, location)
82
+ await connection.probe(meta, location)
81
83
  } catch (error) {
82
84
  await pool.end().catch(() => undefined)
83
85
  throw error
@@ -97,7 +99,7 @@ export const makePostgresDbService = (alias: string = DEFAULT_ALIAS): PostgresSe
97
99
  * from the service alias would leave an empty `postgres` schema behind on every boot.
98
100
  */
99
101
  if (config.schema != null) {
100
- await ensureSchema(pool, pgIdentifier(service.name(configAlias)))
102
+ await connection.ensureSchema(pgIdentifier(service.name(configAlias)))
101
103
  }
102
104
  },
103
105
 
@@ -109,7 +111,7 @@ export const makePostgresDbService = (alias: string = DEFAULT_ALIAS): PostgresSe
109
111
  qualify: resourceAlias => {
110
112
  const context = assertContext<Config, Context>(service.ctx as Context, location)
111
113
 
112
- return refOf(context, null, resourceAlias)
114
+ return pgPlaceholdersOf(context).refOf(null, resourceAlias)
113
115
  },
114
116
 
115
117
  query: async <Row extends QueryResultRow = QueryResultRow>(
@@ -119,7 +121,7 @@ export const makePostgresDbService = (alias: string = DEFAULT_ALIAS): PostgresSe
119
121
  const context = assertContext<Config, Context>(service.ctx as Context, location)
120
122
  try {
121
123
  const result = await db.pool.query<Row>(
122
- resolvePlaceholders(text, context, null), params as never[]
124
+ pgPlaceholdersOf(context).resolvePlaceholders(text, null), params as never[]
123
125
  )
124
126
 
125
127
  return result.rows
@@ -131,13 +133,14 @@ export const makePostgresDbService = (alias: string = DEFAULT_ALIAS): PostgresSe
131
133
  transaction: async (fn, configAlias) => {
132
134
  const db = await service.db(configAlias)
133
135
  const context = assertContext<Config, Context>(service.ctx as Context, location)
136
+ const placeholders = pgPlaceholdersOf(context)
134
137
  const client = await db.pool.connect()
135
138
  try {
136
139
  await client.query('BEGIN')
137
140
  const result = await fn(makeTx(
138
141
  client,
139
- text => resolvePlaceholders(text, context, null),
140
- resourceAlias => refOf(context, null, resourceAlias)
142
+ text => placeholders.resolvePlaceholders(text, null),
143
+ resourceAlias => placeholders.refOf(null, resourceAlias)
141
144
  ))
142
145
  await client.query('COMMIT')
143
146
 
@@ -0,0 +1,5 @@
1
+ import type { ServerConfig, ServerContext } from '@owlmeans/server-context'
2
+
3
+ export type Config = ServerConfig
4
+
5
+ export interface Context<C extends Config = Config> extends ServerContext<C> { }
@@ -0,0 +1,28 @@
1
+ import type { DbConfig } from '@owlmeans/resource'
2
+ import type { PoolConfig } from 'pg'
3
+
4
+ /** A db config entry as the `pg` pool configuration it describes. */
5
+ export interface PgConfigHelper {
6
+ /**
7
+ * Split a `postgres://` URL into pool fields.
8
+ *
9
+ * node-postgres accepts a `connectionString` directly, but the parsed values *override*
10
+ * every sibling field — so `{ connectionString, database }` silently ignores the
11
+ * database. Parsing here instead keeps overriding possible, which the admin path needs
12
+ * to reach both the maintenance database and the target one over the same credentials.
13
+ *
14
+ * @throws {PostgresConnectionError}
15
+ */
16
+ parseUrl: (url: string) => PoolConfig
17
+ /**
18
+ * Turn a {@link DbConfig} into a `pg` pool configuration.
19
+ *
20
+ * Values that start with `/` have already been read from disk by the `fileConfigReader`
21
+ * middleware, so a file mounted secret and a literal one are indistinguishable here —
22
+ * which is what lets a deployment move from env vars to mounted files without a code
23
+ * change.
24
+ */
25
+ prepareConfig: (config: DbConfig, overrides?: PoolConfig) => PoolConfig
26
+ /** Effective database of an open pool, as `pg` resolved it. */
27
+ poolDatabase: (pool: { options?: PoolConfig }) => string
28
+ }
@@ -4,106 +4,97 @@ import type { DbConfig } from '@owlmeans/resource'
4
4
  import type { PoolConfig } from 'pg'
5
5
 
6
6
  import { DEF_POOL_SIZE, DEF_PORT } from '../consts.js'
7
+ import type { PgConfigHelper } from './config/types.js'
7
8
 
8
- /**
9
- * Split a `postgres://` URL into pool fields.
10
- *
11
- * node-postgres accepts a `connectionString` directly, but the parsed values *override*
12
- * every sibling field — so `{ connectionString, database }` silently ignores the
13
- * database. Parsing here instead keeps overriding possible, which the admin path needs
14
- * to reach both the maintenance database and the target one over the same credentials.
15
- *
16
- * @throws {PostgresConnectionError}
17
- */
18
- export const parseUrl = (url: string): PoolConfig => {
19
- let parsed: URL
20
- try {
21
- parsed = new URL(url)
22
- } catch {
23
- throw new PostgresConnectionError('malformed-url')
24
- }
25
- if (!/^postgres(ql)?:$/.test(parsed.protocol)) {
26
- throw new PostgresConnectionError(`unexpected-protocol:${parsed.protocol.replace(':', '')}`)
27
- }
9
+ export const createPgConfigHelper = (): PgConfigHelper => {
10
+ const parseUrl = (url: string): PoolConfig => {
11
+ let parsed: URL
12
+ try {
13
+ parsed = new URL(url)
14
+ } catch {
15
+ throw new PostgresConnectionError('malformed-url')
16
+ }
17
+ if (!/^postgres(ql)?:$/.test(parsed.protocol)) {
18
+ throw new PostgresConnectionError(`unexpected-protocol:${parsed.protocol.replace(':', '')}`)
19
+ }
28
20
 
29
- const database = decodeURIComponent(parsed.pathname.replace(/^\//, ''))
30
- /** IPv6 literals arrive bracketed from `URL`; `pg` wants the bare address. */
31
- const host = decodeURIComponent(parsed.hostname).replace(/^\[|\]$/g, '')
32
- const mode = parsed.searchParams.get('sslmode')
21
+ const database = decodeURIComponent(parsed.pathname.replace(/^\//, ''))
22
+ /** IPv6 literals arrive bracketed from `URL`; `pg` wants the bare address. */
23
+ const host = decodeURIComponent(parsed.hostname).replace(/^\[|\]$/g, '')
24
+ const mode = parsed.searchParams.get('sslmode')
33
25
 
34
- const config: PoolConfig = {
35
- host,
36
- port: parsed.port !== '' ? parseInt(parsed.port, 10) : DEF_PORT
37
- }
38
- if (parsed.username !== '') {
39
- config.user = decodeURIComponent(parsed.username)
40
- }
41
- if (parsed.password !== '') {
42
- config.password = decodeURIComponent(parsed.password)
43
- }
44
- if (database !== '') {
45
- config.database = database
46
- }
47
- if (mode != null && mode !== 'disable') {
48
- /**
49
- * `no-verify` is what a self signed in-cluster certificate needs, and is the only
50
- * mode that may skip verification — anything else keeps the chain checked.
51
- */
52
- config.ssl = mode === 'no-verify' ? { rejectUnauthorized: false } : true
26
+ const config: PoolConfig = {
27
+ host,
28
+ port: parsed.port !== '' ? parseInt(parsed.port, 10) : DEF_PORT
29
+ }
30
+ if (parsed.username !== '') {
31
+ config.user = decodeURIComponent(parsed.username)
32
+ }
33
+ if (parsed.password !== '') {
34
+ config.password = decodeURIComponent(parsed.password)
35
+ }
36
+ if (database !== '') {
37
+ config.database = database
38
+ }
39
+ if (mode != null && mode !== 'disable') {
40
+ /**
41
+ * `no-verify` is what a self signed in-cluster certificate needs, and is the only
42
+ * mode that may skip verification — anything else keeps the chain checked.
43
+ */
44
+ config.ssl = mode === 'no-verify' ? { rejectUnauthorized: false } : true
45
+ }
46
+
47
+ return config
53
48
  }
54
49
 
55
- return config
56
- }
50
+ const prepareConfig = (config: DbConfig, overrides?: PoolConfig): PoolConfig => {
51
+ const meta = (config.meta ?? {}) as PostgresMeta
57
52
 
58
- /**
59
- * Turn a {@link DbConfig} into a `pg` pool configuration.
60
- *
61
- * Values that start with `/` have already been read from disk by the `fileConfigReader`
62
- * middleware, so a file mounted secret and a literal one are indistinguishable here —
63
- * which is what lets a deployment move from env vars to mounted files without a code
64
- * change.
65
- */
66
- export const prepareConfig = (config: DbConfig, overrides?: PoolConfig): PoolConfig => {
67
- const meta = (config.meta ?? {}) as PostgresMeta
53
+ /**
54
+ * `DbConfig.host` is an array for Mongo's replica sets. Postgres has no client side
55
+ * equivalent — multi-host failover is the pooler's job — so only the first is used.
56
+ */
57
+ const host = Array.isArray(config.host) ? config.host[0] : config.host
68
58
 
69
- /**
70
- * `DbConfig.host` is an array for Mongo's replica sets. Postgres has no client side
71
- * equivalent — multi-host failover is the pooler's job — so only the first is used.
72
- */
73
- const host = Array.isArray(config.host) ? config.host[0] : config.host
59
+ const base: PoolConfig = meta.url != null
60
+ ? parseUrl(meta.url)
61
+ : {
62
+ host,
63
+ port: config.port ?? DEF_PORT,
64
+ ...(config.user != null ? { user: config.user } : {}),
65
+ ...(config.secret != null ? { password: config.secret } : {}),
66
+ /** Absent, libpq falls back to the connection user's name. */
67
+ ...(meta.database != null ? { database: meta.database } : {})
68
+ }
74
69
 
75
- const base: PoolConfig = meta.url != null
76
- ? parseUrl(meta.url)
77
- : {
78
- host,
79
- port: config.port ?? DEF_PORT,
80
- ...(config.user != null ? { user: config.user } : {}),
81
- ...(config.secret != null ? { password: config.secret } : {}),
82
- /** Absent, libpq falls back to the connection user's name. */
83
- ...(meta.database != null ? { database: meta.database } : {})
70
+ const prepared: PoolConfig = {
71
+ ...base,
72
+ max: meta.max ?? DEF_POOL_SIZE,
73
+ ...(meta.ssl != null ? { ssl: meta.ssl as PoolConfig['ssl'] } : {}),
74
+ ...(meta.idleTimeoutMillis != null ? { idleTimeoutMillis: meta.idleTimeoutMillis } : {}),
75
+ ...(meta.connectionTimeoutMillis != null
76
+ ? { connectionTimeoutMillis: meta.connectionTimeoutMillis }
77
+ : {}),
78
+ /**
79
+ * A server side cap, so a query that outlives its caller stops holding a connection
80
+ * and its locks — the failure mode that turns one slow statement into a stuck pool.
81
+ */
82
+ ...(meta.statementTimeoutMillis != null
83
+ ? { statement_timeout: meta.statementTimeoutMillis }
84
+ : {}),
85
+ ...overrides
84
86
  }
85
87
 
86
- const prepared: PoolConfig = {
87
- ...base,
88
- max: meta.max ?? DEF_POOL_SIZE,
89
- ...(meta.ssl != null ? { ssl: meta.ssl as PoolConfig['ssl'] } : {}),
90
- ...(meta.idleTimeoutMillis != null ? { idleTimeoutMillis: meta.idleTimeoutMillis } : {}),
91
- ...(meta.connectionTimeoutMillis != null
92
- ? { connectionTimeoutMillis: meta.connectionTimeoutMillis }
93
- : {}),
94
- /**
95
- * A server side cap, so a query that outlives its caller stops holding a connection
96
- * and its locks — the failure mode that turns one slow statement into a stuck pool.
97
- */
98
- ...(meta.statementTimeoutMillis != null
99
- ? { statement_timeout: meta.statementTimeoutMillis }
100
- : {}),
101
- ...overrides
88
+ return prepared
102
89
  }
103
90
 
104
- return prepared
91
+ const poolDatabase = (pool: { options?: PoolConfig }): string =>
92
+ pool.options?.database ?? pool.options?.user ?? ''
93
+
94
+ return { parseUrl, prepareConfig, poolDatabase }
105
95
  }
106
96
 
107
- /** Effective database of an open pool, as `pg` resolved it. */
108
- export const poolDatabase = (pool: { options?: PoolConfig }): string =>
109
- pool.options?.database ?? pool.options?.user ?? ''
97
+ export const pgConfigHelper = createPgConfigHelper()
98
+
99
+ /** @deprecated compat:factory-refactor — use `pgConfigHelper.parseUrl(…)` */
100
+ export const parseUrl = (url: string): PoolConfig => pgConfigHelper.parseUrl(url)
@@ -0,0 +1,17 @@
1
+ import type { PostgresMeta } from '@owlmeans/postgres-resource'
2
+
3
+ /** Readiness and namespace setup over one pool. */
4
+ export interface PgConnectionHelper {
5
+ /**
6
+ * Wait for the server to answer a query, not merely to accept a socket.
7
+ *
8
+ * Postgres binds its port before it finishes recovery, so a sidecar or an operator managed
9
+ * instance routinely accepts a connection and then refuses to run anything. Every OwlMeans
10
+ * deployment grew its own copy of this loop; this is the one.
11
+ *
12
+ * @throws {PostgresConnectionError}
13
+ */
14
+ probe: (meta: PostgresMeta, location: string) => Promise<void>
15
+ /** `CREATE SCHEMA IF NOT EXISTS` on a pooled connection. */
16
+ ensureSchema: (schema: string) => Promise<void>
17
+ }