@zonastery/bursar 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (227) hide show
  1. package/README.md +108 -64
  2. package/dist/billing/auto-recharge-port.js.map +1 -1
  3. package/dist/billing/auto-recharge-service.js.map +1 -1
  4. package/dist/billing/billing-service.js.map +1 -1
  5. package/dist/billing/billing-store.d.ts +2 -2
  6. package/dist/billing/billing-store.d.ts.map +1 -1
  7. package/dist/billing/billing-store.js.map +1 -1
  8. package/dist/billing/contracts.js.map +1 -1
  9. package/dist/billing/event-handlers.d.ts.map +1 -1
  10. package/dist/billing/event-handlers.js +21 -4
  11. package/dist/billing/event-handlers.js.map +1 -1
  12. package/dist/billing/event-processor.d.ts +1 -0
  13. package/dist/billing/event-processor.d.ts.map +1 -1
  14. package/dist/billing/event-processor.js +35 -9
  15. package/dist/billing/event-processor.js.map +1 -1
  16. package/dist/billing/financial-event-handlers.js.map +1 -1
  17. package/dist/billing/index.d.ts +1 -0
  18. package/dist/billing/index.d.ts.map +1 -1
  19. package/dist/billing/index.js.map +1 -1
  20. package/dist/billing/management.js.map +1 -1
  21. package/dist/billing/policy-window.js.map +1 -1
  22. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
  23. package/dist/billing/postgres/repositories/auto-recharge.js +3 -1
  24. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  25. package/dist/billing/postgres/repositories/customer.js.map +1 -1
  26. package/dist/billing/postgres/repositories/dispute.js.map +1 -1
  27. package/dist/billing/postgres/repositories/event.d.ts +2 -2
  28. package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
  29. package/dist/billing/postgres/repositories/event.js +10 -12
  30. package/dist/billing/postgres/repositories/event.js.map +1 -1
  31. package/dist/billing/postgres/repositories/invoice.js.map +1 -1
  32. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  33. package/dist/billing/postgres/repositories/payment.js.map +1 -1
  34. package/dist/billing/postgres/repositories/preferences.js.map +1 -1
  35. package/dist/billing/postgres/repositories/refund.js.map +1 -1
  36. package/dist/billing/postgres/repositories/subscription.js.map +1 -1
  37. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  38. package/dist/billing/postgres/store.d.ts +7 -5
  39. package/dist/billing/postgres/store.d.ts.map +1 -1
  40. package/dist/billing/postgres/store.js +19 -4
  41. package/dist/billing/postgres/store.js.map +1 -1
  42. package/dist/billing/service-types.js.map +1 -1
  43. package/dist/billing/types/auto-recharge.js.map +1 -1
  44. package/dist/billing/types/catalog.js.map +1 -1
  45. package/dist/billing/types/common.js.map +1 -1
  46. package/dist/billing/types/documents.js.map +1 -1
  47. package/dist/billing/types/events.js.map +1 -1
  48. package/dist/billing/types/index.js.map +1 -1
  49. package/dist/billing/types/preferences.js.map +1 -1
  50. package/dist/billing/types/subscriptions.js.map +1 -1
  51. package/dist/breakdown.js.map +1 -1
  52. package/dist/browser.js.map +1 -1
  53. package/dist/bursar.d.ts +7 -3
  54. package/dist/bursar.d.ts.map +1 -1
  55. package/dist/bursar.js +12 -4
  56. package/dist/bursar.js.map +1 -1
  57. package/dist/catalog.d.ts +1 -0
  58. package/dist/catalog.d.ts.map +1 -1
  59. package/dist/catalog.js +1 -0
  60. package/dist/catalog.js.map +1 -1
  61. package/dist/commerce/errors.d.ts +3 -4
  62. package/dist/commerce/errors.d.ts.map +1 -1
  63. package/dist/commerce/errors.js +3 -5
  64. package/dist/commerce/errors.js.map +1 -1
  65. package/dist/commerce/index.js.map +1 -1
  66. package/dist/commerce/plan-change.js.map +1 -1
  67. package/dist/commerce/provider-registry.js.map +1 -1
  68. package/dist/commerce/service.d.ts.map +1 -1
  69. package/dist/commerce/service.js +47 -12
  70. package/dist/commerce/service.js.map +1 -1
  71. package/dist/commerce/types.d.ts +8 -0
  72. package/dist/commerce/types.d.ts.map +1 -1
  73. package/dist/commerce/types.js.map +1 -1
  74. package/dist/config/parse-access.js.map +1 -1
  75. package/dist/config/parse-commerce.js.map +1 -1
  76. package/dist/config/parse-credits.js.map +1 -1
  77. package/dist/config/parse-plans.d.ts.map +1 -1
  78. package/dist/config/parse-plans.js +23 -7
  79. package/dist/config/parse-plans.js.map +1 -1
  80. package/dist/config/parse-pricing.js.map +1 -1
  81. package/dist/config/parse-utils.js.map +1 -1
  82. package/dist/config/types.d.ts +14 -1
  83. package/dist/config/types.d.ts.map +1 -1
  84. package/dist/config/types.js.map +1 -1
  85. package/dist/config.d.ts +7 -1
  86. package/dist/config.d.ts.map +1 -1
  87. package/dist/config.js +64 -1
  88. package/dist/config.js.map +1 -1
  89. package/dist/credits/events.js.map +1 -1
  90. package/dist/credits/lease-workflow.js.map +1 -1
  91. package/dist/credits/low-balance-monitor.js.map +1 -1
  92. package/dist/credits/postgres/repositories/analytics.d.ts +5 -1
  93. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
  94. package/dist/credits/postgres/repositories/analytics.js +3 -1
  95. package/dist/credits/postgres/repositories/analytics.js.map +1 -1
  96. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  97. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  98. package/dist/credits/postgres/repositories/deduction.d.ts +9 -0
  99. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
  100. package/dist/credits/postgres/repositories/deduction.js +24 -0
  101. package/dist/credits/postgres/repositories/deduction.js.map +1 -1
  102. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  103. package/dist/credits/postgres/repositories/plan.d.ts +6 -1
  104. package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
  105. package/dist/credits/postgres/repositories/plan.js +15 -3
  106. package/dist/credits/postgres/repositories/plan.js.map +1 -1
  107. package/dist/credits/postgres/repositories/pricing.d.ts +3 -3
  108. package/dist/credits/postgres/repositories/pricing.d.ts.map +1 -1
  109. package/dist/credits/postgres/repositories/pricing.js +12 -6
  110. package/dist/credits/postgres/repositories/pricing.js.map +1 -1
  111. package/dist/credits/postgres/repositories/team.js.map +1 -1
  112. package/dist/credits/postgres/store.d.ts +12 -7
  113. package/dist/credits/postgres/store.d.ts.map +1 -1
  114. package/dist/credits/postgres/store.js +86 -13
  115. package/dist/credits/postgres/store.js.map +1 -1
  116. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  117. package/dist/credits/postgres/value-mappers.js +6 -2
  118. package/dist/credits/postgres/value-mappers.js.map +1 -1
  119. package/dist/credits/pricing-runtime.d.ts +3 -2
  120. package/dist/credits/pricing-runtime.d.ts.map +1 -1
  121. package/dist/credits/pricing-runtime.js +4 -4
  122. package/dist/credits/pricing-runtime.js.map +1 -1
  123. package/dist/credits/queries.js.map +1 -1
  124. package/dist/credits/service-errors.js.map +1 -1
  125. package/dist/credits/service-types.js.map +1 -1
  126. package/dist/credits/service.d.ts +16 -3
  127. package/dist/credits/service.d.ts.map +1 -1
  128. package/dist/credits/service.js +51 -5
  129. package/dist/credits/service.js.map +1 -1
  130. package/dist/credits/store.d.ts +8 -3
  131. package/dist/credits/store.d.ts.map +1 -1
  132. package/dist/credits/store.js +4 -0
  133. package/dist/credits/store.js.map +1 -1
  134. package/dist/credits/types/account.d.ts +1 -1
  135. package/dist/credits/types/account.d.ts.map +1 -1
  136. package/dist/credits/types/account.js.map +1 -1
  137. package/dist/credits/types/admission.js.map +1 -1
  138. package/dist/credits/types/analytics.js.map +1 -1
  139. package/dist/credits/types/catalog.d.ts +3 -1
  140. package/dist/credits/types/catalog.d.ts.map +1 -1
  141. package/dist/credits/types/catalog.js.map +1 -1
  142. package/dist/credits/types/grants.js.map +1 -1
  143. package/dist/credits/types/index.js.map +1 -1
  144. package/dist/credits/types/ledger.d.ts +10 -0
  145. package/dist/credits/types/ledger.d.ts.map +1 -1
  146. package/dist/credits/types/ledger.js.map +1 -1
  147. package/dist/credits/types/quotas.js.map +1 -1
  148. package/dist/credits/types/teams.js.map +1 -1
  149. package/dist/engine.js.map +1 -1
  150. package/dist/errors.d.ts +53 -4
  151. package/dist/errors.d.ts.map +1 -1
  152. package/dist/errors.js +61 -5
  153. package/dist/errors.js.map +1 -1
  154. package/dist/expr/ast.js.map +1 -1
  155. package/dist/expr/evaluator.js.map +1 -1
  156. package/dist/expr/language.js.map +1 -1
  157. package/dist/expr/parser.js.map +1 -1
  158. package/dist/expr/tokenizer.js.map +1 -1
  159. package/dist/expr.js +2 -2
  160. package/dist/expr.js.map +1 -1
  161. package/dist/generated/pricing-config.schema.json +37 -9
  162. package/dist/generated/pricing-config.types.d.ts +14 -3
  163. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  164. package/dist/generated/pricing-config.types.js.map +1 -1
  165. package/dist/index.d.ts +8 -6
  166. package/dist/index.d.ts.map +1 -1
  167. package/dist/index.js +2 -2
  168. package/dist/index.js.map +1 -1
  169. package/dist/load-pricing-file.d.ts.map +1 -1
  170. package/dist/load-pricing-file.js +8 -4
  171. package/dist/load-pricing-file.js.map +1 -1
  172. package/dist/metrics.js.map +1 -1
  173. package/dist/node.js.map +1 -1
  174. package/dist/providers/_shared.d.ts.map +1 -1
  175. package/dist/providers/_shared.js +41 -14
  176. package/dist/providers/_shared.js.map +1 -1
  177. package/dist/providers/dodo/client-contract.js.map +1 -1
  178. package/dist/providers/dodo/event-mapper.js.map +1 -1
  179. package/dist/providers/dodo/index.js.map +1 -1
  180. package/dist/providers/dodo/provider.js.map +1 -1
  181. package/dist/providers/index.js.map +1 -1
  182. package/dist/providers/mock/index.js.map +1 -1
  183. package/dist/providers/mock/provider.js.map +1 -1
  184. package/dist/providers/stripe/event-mapper.js.map +1 -1
  185. package/dist/providers/stripe/index.js.map +1 -1
  186. package/dist/providers/stripe/provider.js.map +1 -1
  187. package/dist/providers/types.js.map +1 -1
  188. package/dist/retry.d.ts +26 -4
  189. package/dist/retry.d.ts.map +1 -1
  190. package/dist/retry.js +65 -23
  191. package/dist/retry.js.map +1 -1
  192. package/dist/shared/diagnostics.d.ts +7 -0
  193. package/dist/shared/diagnostics.d.ts.map +1 -0
  194. package/dist/shared/diagnostics.js +18 -0
  195. package/dist/shared/diagnostics.js.map +1 -0
  196. package/dist/shared/logger.js.map +1 -1
  197. package/dist/shared/postgres-client.d.ts +38 -5
  198. package/dist/shared/postgres-client.d.ts.map +1 -1
  199. package/dist/shared/postgres-client.js +261 -25
  200. package/dist/shared/postgres-client.js.map +1 -1
  201. package/dist/shared/postgres-errors.d.ts +11 -0
  202. package/dist/shared/postgres-errors.d.ts.map +1 -0
  203. package/dist/shared/postgres-errors.js +105 -0
  204. package/dist/shared/postgres-errors.js.map +1 -0
  205. package/dist/shared/postgres-types.js.map +1 -1
  206. package/dist/shared/postgres-validation.d.ts.map +1 -1
  207. package/dist/shared/postgres-validation.js +1 -1
  208. package/dist/shared/postgres-validation.js.map +1 -1
  209. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  210. package/dist/storage/adapters/clickhouse.js +20 -2
  211. package/dist/storage/adapters/clickhouse.js.map +1 -1
  212. package/dist/storage/adapters/s3.js.map +1 -1
  213. package/dist/storage/outbox-worker.d.ts +2 -1
  214. package/dist/storage/outbox-worker.d.ts.map +1 -1
  215. package/dist/storage/outbox-worker.js +17 -3
  216. package/dist/storage/outbox-worker.js.map +1 -1
  217. package/dist/storage/ports.d.ts +1 -0
  218. package/dist/storage/ports.d.ts.map +1 -1
  219. package/dist/storage/ports.js.map +1 -1
  220. package/dist/storage/postgres-repository.d.ts.map +1 -1
  221. package/dist/storage/postgres-repository.js +11 -1
  222. package/dist/storage/postgres-repository.js.map +1 -1
  223. package/dist/storage/runtime.d.ts +11 -1
  224. package/dist/storage/runtime.d.ts.map +1 -1
  225. package/dist/storage/runtime.js +91 -35
  226. package/dist/storage/runtime.js.map +1 -1
  227. package/package.json +9 -3
@@ -1,29 +1,58 @@
1
+ import { type BursarError } from "../errors.js";
1
2
  import type { QueryFn } from "./postgres-types.js";
3
+ export interface PostgresPoolConfig {
4
+ connectionString: string;
5
+ connectionTimeoutMillis?: number;
6
+ statement_timeout?: number;
7
+ query_timeout?: number;
8
+ idle_in_transaction_session_timeout?: number;
9
+ idleTimeoutMillis?: number;
10
+ max?: number;
11
+ application_name?: string;
12
+ }
2
13
  export interface PostgresPool {
3
14
  query(text: string, params?: unknown[]): Promise<{
4
15
  rows: unknown[];
5
16
  }>;
6
17
  connect(): Promise<PostgresPoolClient>;
7
18
  end(): Promise<void>;
19
+ on?(event: "error", listener: (error: Error) => void): unknown;
8
20
  }
9
21
  export interface PostgresPoolClient {
10
22
  query(text: string, params?: unknown[]): Promise<{
11
23
  rows: unknown[];
12
24
  }>;
13
- release(): void;
25
+ release(error?: Error | boolean): void;
14
26
  }
15
27
  export interface PostgresPoolConstructor {
16
- new (config: {
17
- connectionString: string;
18
- }): PostgresPool;
28
+ new (config: PostgresPoolConfig): PostgresPool;
29
+ }
30
+ /** PostgreSQL deadline, pool, and observability controls. */
31
+ export interface PostgresConnectionOptions {
32
+ /** Time allowed to establish or acquire a connection. Defaults to 10 seconds. */
33
+ connectionTimeoutMs?: number;
34
+ /** Server-side statement deadline. Defaults to 30 seconds; set 0 to disable. */
35
+ statementTimeoutMs?: number;
36
+ /** Server-side idle transaction deadline. Defaults to 30 seconds; set 0 to disable. */
37
+ idleTransactionTimeoutMs?: number;
38
+ /** Idle pooled connection lifetime. Uses pg's default when omitted. */
39
+ idleTimeoutMs?: number;
40
+ /** Maximum connections in an SDK-owned pool. Uses pg's default when omitted. */
41
+ maxConnections?: number;
42
+ /** PostgreSQL application_name. Defaults to `bursar-js`. */
43
+ applicationName?: string;
44
+ /** Receives typed errors emitted by idle pool clients. Must not throw. */
45
+ onPoolError?: (error: BursarError) => void;
19
46
  }
20
- export interface PostgresClientOptions {
47
+ export interface PostgresClientOptions extends PostgresConnectionOptions {
21
48
  poolConstructor?: PostgresPoolConstructor;
22
49
  closedError?: () => Error;
23
50
  tenantId?: string;
24
51
  usageBackend?: "postgres" | "clickhouse";
25
52
  billingPayloadBackend?: "postgres" | "s3";
26
53
  }
54
+ /** Build a pg Pool config with finite connection and statement deadlines. */
55
+ export declare function postgresPoolConfig(connectionString: string, options?: PostgresConnectionOptions): PostgresPoolConfig;
27
56
  /**
28
57
  * Owns the lifecycle and lazy initialization of a PostgreSQL pool.
29
58
  *
@@ -40,10 +69,14 @@ export declare class PostgresClient {
40
69
  private readonly tenantId;
41
70
  private readonly usageBackend;
42
71
  private readonly billingPayloadBackend;
72
+ private readonly connectionOptions;
73
+ private removePoolObserver;
74
+ private closePromise;
43
75
  private closed;
44
76
  constructor(poolOrUrl: PostgresPool | string, options?: PostgresClientOptions);
45
77
  readonly query: QueryFn;
46
78
  close(): Promise<void>;
79
+ private closePool;
47
80
  private getPool;
48
81
  private createPool;
49
82
  private getPoolConstructor;
@@ -1 +1 @@
1
- {"version":3,"file":"postgres-client.d.ts","sourceRoot":"","sources":["../../src/shared/postgres-client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAEnD,MAAM,WAAW,YAAY;IAC3B,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;QAAE,IAAI,EAAE,OAAO,EAAE,CAAA;KAAE,CAAC,CAAC;IACtE,OAAO,IAAI,OAAO,CAAC,kBAAkB,CAAC,CAAC;IACvC,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACtB;AAED,MAAM,WAAW,kBAAkB;IACjC,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;QAAE,IAAI,EAAE,OAAO,EAAE,CAAA;KAAE,CAAC,CAAC;IACtE,OAAO,IAAI,IAAI,CAAC;CACjB;AAED,MAAM,WAAW,uBAAuB;IACtC,KAAK,MAAM,EAAE;QAAE,gBAAgB,EAAE,MAAM,CAAA;KAAE,GAAG,YAAY,CAAC;CAC1D;AAED,MAAM,WAAW,qBAAqB;IACpC,eAAe,CAAC,EAAE,uBAAuB,CAAC;IAC1C,WAA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ors.js";
2
+ import { normalizePostgresError } from "./postgres-errors.js";
3
+ const DEFAULT_CONNECTION_TIMEOUT_MS = 10_000;
4
+ const DEFAULT_STATEMENT_TIMEOUT_MS = 30_000;
5
+ const DEFAULT_IDLE_TRANSACTION_TIMEOUT_MS = 30_000;
6
+ const CLIENT_TIMEOUT_GRACE_MS = 1_000;
7
+ const MAX_POSTGRES_TIMEOUT_MS = 2_147_483_647;
8
+ function assertPostgresPool(value) {
9
+ if (typeof value !== "object" ||
10
+ value === null ||
11
+ typeof value.query !== "function" ||
12
+ typeof value.connect !== "function" ||
13
+ typeof value.end !== "function" ||
14
+ (value.on !== undefined &&
15
+ typeof value.on !== "function")) {
16
+ throw new TypeError("postgres pool must provide query(), connect(), and end() methods");
17
+ }
18
+ }
19
+ function integerOption(value, fallback, name, minimum, maximum = MAX_POSTGRES_TIMEOUT_MS) {
20
+ const normalized = value ?? fallback;
21
+ if (normalized === undefined)
22
+ return undefined;
23
+ if (!Number.isSafeInteger(normalized) || normalized < minimum || normalized > maximum) {
24
+ throw new RangeError(`${name} must be a safe integer between ${minimum} and ${maximum}`);
25
+ }
26
+ return normalized;
27
+ }
28
+ function normalizeConnectionOptions(options) {
29
+ if (options.applicationName !== undefined && typeof options.applicationName !== "string") {
30
+ throw new TypeError("applicationName must be a string");
31
+ }
32
+ if (options.onPoolError !== undefined && typeof options.onPoolError !== "function") {
33
+ throw new TypeError("onPoolError must be a function");
34
+ }
35
+ const applicationName = options.applicationName?.trim() || "bursar-js";
36
+ if (applicationName.includes("\0")) {
37
+ throw new TypeError("applicationName must not contain null bytes");
38
+ }
39
+ return {
40
+ connectionTimeoutMs: integerOption(options.connectionTimeoutMs, DEFAULT_CONNECTION_TIMEOUT_MS, "connectionTimeoutMs", 0),
41
+ statementTimeoutMs: integerOption(options.statementTimeoutMs, DEFAULT_STATEMENT_TIMEOUT_MS, "statementTimeoutMs", 0),
42
+ idleTransactionTimeoutMs: integerOption(options.idleTransactionTimeoutMs, DEFAULT_IDLE_TRANSACTION_TIMEOUT_MS, "idleTransactionTimeoutMs", 0),
43
+ idleTimeoutMs: integerOption(options.idleTimeoutMs, undefined, "idleTimeoutMs", 0),
44
+ maxConnections: integerOption(options.maxConnections, undefined, "maxConnections", 1),
45
+ applicationName,
46
+ onPoolError: options.onPoolError,
47
+ };
48
+ }
49
+ /** Build a pg Pool config with finite connection and statement deadlines. */
50
+ export function postgresPoolConfig(connectionString, options = {}) {
51
+ if (typeof connectionString !== "string") {
52
+ throw new TypeError("postgres connection string must be a string");
53
+ }
54
+ if (!connectionString.trim())
55
+ throw new TypeError("postgres connection string must not be empty");
56
+ const normalized = normalizeConnectionOptions(options);
57
+ const queryTimeout = normalized.statementTimeoutMs === 0
58
+ ? 0
59
+ : Math.min(normalized.statementTimeoutMs + CLIENT_TIMEOUT_GRACE_MS, MAX_POSTGRES_TIMEOUT_MS);
60
+ return {
61
+ connectionString,
62
+ connectionTimeoutMillis: normalized.connectionTimeoutMs,
63
+ statement_timeout: normalized.statementTimeoutMs,
64
+ query_timeout: queryTimeout,
65
+ idle_in_transaction_session_timeout: normalized.idleTransactionTimeoutMs,
66
+ application_name: normalized.applicationName,
67
+ ...(normalized.idleTimeoutMs !== undefined
68
+ ? { idleTimeoutMillis: normalized.idleTimeoutMs }
69
+ : {}),
70
+ ...(normalized.maxConnections !== undefined ? { max: normalized.maxConnections } : {}),
71
+ };
72
+ }
73
+ const poolObservers = new WeakMap();
74
+ function notifyPoolError(onPoolError, error) {
75
+ try {
76
+ onPoolError?.(error);
77
+ }
78
+ catch {
79
+ // Observability callbacks must never destabilize SDK control flow.
80
+ }
81
+ }
82
+ function observePool(pool, onPoolError) {
83
+ if (!pool.on)
84
+ return () => { };
85
+ const existing = poolObservers.get(pool);
86
+ if (existing) {
87
+ if (onPoolError)
88
+ existing.set(onPoolError, (existing.get(onPoolError) ?? 0) + 1);
89
+ return () => {
90
+ if (!onPoolError)
91
+ return;
92
+ const references = existing.get(onPoolError) ?? 0;
93
+ if (references <= 1)
94
+ existing.delete(onPoolError);
95
+ else
96
+ existing.set(onPoolError, references - 1);
97
+ };
98
+ }
99
+ const observers = new Map();
100
+ if (onPoolError)
101
+ observers.set(onPoolError, 1);
102
+ poolObservers.set(pool, observers);
103
+ pool.on("error", (error) => {
104
+ const normalized = normalizePostgresError(error, { operation: "pool", phase: "pool" });
105
+ for (const observer of observers.keys())
106
+ notifyPoolError(observer, normalized);
107
+ });
108
+ return () => {
109
+ if (!onPoolError)
110
+ return;
111
+ const references = observers.get(onPoolError) ?? 0;
112
+ if (references <= 1)
113
+ observers.delete(onPoolError);
114
+ else
115
+ observers.set(onPoolError, references - 1);
116
+ };
117
+ }
1
118
  /**
2
119
  * Owns the lifecycle and lazy initialization of a PostgreSQL pool.
3
120
  *
@@ -14,56 +131,161 @@ export class PostgresClient {
14
131
  tenantId;
15
132
  usageBackend;
16
133
  billingPayloadBackend;
134
+ connectionOptions;
135
+ removePoolObserver = null;
136
+ closePromise = null;
17
137
  closed = false;
18
138
  constructor(poolOrUrl, options = {}) {
139
+ if (typeof poolOrUrl !== "string")
140
+ assertPostgresPool(poolOrUrl);
141
+ if (options.poolConstructor !== undefined && typeof options.poolConstructor !== "function") {
142
+ throw new TypeError("poolConstructor must be a constructor");
143
+ }
144
+ if (options.closedError !== undefined && typeof options.closedError !== "function") {
145
+ throw new TypeError("closedError must be a function");
146
+ }
147
+ if (options.usageBackend !== undefined &&
148
+ options.usageBackend !== "postgres" &&
149
+ options.usageBackend !== "clickhouse") {
150
+ throw new TypeError("usageBackend must be 'postgres' or 'clickhouse'");
151
+ }
152
+ if (options.billingPayloadBackend !== undefined &&
153
+ options.billingPayloadBackend !== "postgres" &&
154
+ options.billingPayloadBackend !== "s3") {
155
+ throw new TypeError("billingPayloadBackend must be 'postgres' or 's3'");
156
+ }
157
+ this.connectionOptions = normalizeConnectionOptions(options);
19
158
  this.databaseUrl = typeof poolOrUrl === "string" ? poolOrUrl : null;
159
+ if (this.databaseUrl !== null && !this.databaseUrl.trim()) {
160
+ throw new TypeError("postgres connection string must not be empty");
161
+ }
20
162
  this.pool = typeof poolOrUrl === "string" ? null : poolOrUrl;
21
163
  this.poolConstructor = options.poolConstructor ?? null;
22
164
  this.ownsPool = typeof poolOrUrl === "string";
23
165
  this.closedError =
24
- options.closedError ?? (() => new Error("PostgreSQL client has been closed"));
25
- this.tenantId = options.tenantId ? normalizeTenantId(options.tenantId) : null;
166
+ options.closedError ?? (() => new StoreClosedError("PostgreSQL client has been closed"));
167
+ this.tenantId = options.tenantId === undefined ? null : normalizeTenantId(options.tenantId);
26
168
  this.usageBackend = options.usageBackend ?? "postgres";
27
169
  this.billingPayloadBackend = options.billingPayloadBackend ?? "postgres";
170
+ if (this.pool) {
171
+ this.removePoolObserver = observePool(this.pool, this.connectionOptions.onPoolError);
172
+ }
28
173
  }
29
174
  query = async (text, params) => {
30
- const pool = await this.getPool();
175
+ let pool;
176
+ try {
177
+ pool = await this.getPool();
178
+ }
179
+ catch (error) {
180
+ if (this.closed)
181
+ throw error;
182
+ throw normalizePostgresError(error, { operation: "query", phase: "connect" });
183
+ }
31
184
  if (!this.tenantId) {
32
- return (await pool.query(text, params)).rows;
185
+ try {
186
+ return (await pool.query(text, params)).rows;
187
+ }
188
+ catch (error) {
189
+ throw normalizePostgresError(error, {
190
+ operation: "query",
191
+ phase: "query",
192
+ indeterminate: true,
193
+ });
194
+ }
195
+ }
196
+ let client;
197
+ try {
198
+ client = await pool.connect();
199
+ }
200
+ catch (error) {
201
+ throw normalizePostgresError(error, { operation: "query", phase: "connect" });
33
202
  }
34
- const client = await pool.connect();
203
+ let phase = "begin";
204
+ let transactionStarted = false;
205
+ let discardConnection;
35
206
  try {
36
207
  await client.query("BEGIN");
37
- await client.query("SELECT set_config('bursar.tenant_id', $1, true)", [this.tenantId]);
38
- await client.query("SELECT set_config('bursar.usage_backend', $1, true)", [
208
+ transactionStarted = true;
209
+ phase = "configure";
210
+ await client.query(`SELECT set_config('bursar.tenant_id', $1, true), set_config('bursar.usage_backend', $2, true), set_config('bursar.billing_payload_backend', $3, true), set_config('statement_timeout', $4, true), set_config('idle_in_transaction_session_timeout', $5, true)`, [
211
+ this.tenantId,
39
212
  this.usageBackend,
40
- ]);
41
- await client.query("SELECT set_config('bursar.billing_payload_backend', $1, true)", [
42
213
  this.billingPayloadBackend,
214
+ String(this.connectionOptions.statementTimeoutMs),
215
+ String(this.connectionOptions.idleTransactionTimeoutMs),
43
216
  ]);
217
+ phase = "query";
44
218
  const result = await client.query(text, params);
219
+ phase = "commit";
45
220
  await client.query("COMMIT");
221
+ transactionStarted = false;
46
222
  return result.rows;
47
223
  }
48
224
  catch (error) {
49
- await client.query("ROLLBACK");
50
- throw error;
225
+ const failedPhase = phase;
226
+ let rollbackFailed = false;
227
+ if (transactionStarted) {
228
+ try {
229
+ phase = "rollback";
230
+ await client.query("ROLLBACK");
231
+ transactionStarted = false;
232
+ }
233
+ catch (rollbackError) {
234
+ rollbackFailed = true;
235
+ discardConnection =
236
+ rollbackError instanceof Error
237
+ ? rollbackError
238
+ : new Error("PostgreSQL rollback failed", { cause: rollbackError });
239
+ }
240
+ }
241
+ const normalized = normalizePostgresError(error, {
242
+ operation: "query",
243
+ phase: failedPhase,
244
+ indeterminate: failedPhase === "query" || failedPhase === "commit",
245
+ rollbackFailed,
246
+ });
247
+ throw normalized;
51
248
  }
52
249
  finally {
53
- client.release();
250
+ try {
251
+ client.release(discardConnection);
252
+ }
253
+ catch (releaseError) {
254
+ const normalized = normalizePostgresError(releaseError, {
255
+ operation: "release connection",
256
+ phase: "pool",
257
+ });
258
+ notifyPoolError(this.connectionOptions.onPoolError, normalized);
259
+ }
54
260
  }
55
261
  };
56
- async close() {
57
- if (this.closed)
58
- return;
262
+ close() {
263
+ if (this.closePromise)
264
+ return this.closePromise;
59
265
  this.closed = true;
60
- if (!this.ownsPool)
266
+ this.closePromise = this.closePool();
267
+ return this.closePromise;
268
+ }
269
+ async closePool() {
270
+ if (!this.ownsPool) {
271
+ this.removePoolObserver?.();
272
+ this.removePoolObserver = null;
61
273
  return;
62
- const pool = this.poolPromise ? await this.poolPromise : this.pool;
63
- if (pool)
64
- await pool.end();
65
- this.pool = null;
66
- this.poolPromise = null;
274
+ }
275
+ try {
276
+ const pool = this.poolPromise ? await this.poolPromise : this.pool;
277
+ if (pool)
278
+ await pool.end();
279
+ }
280
+ catch (error) {
281
+ throw normalizePostgresError(error, { operation: "close", phase: "close" });
282
+ }
283
+ finally {
284
+ this.pool = null;
285
+ this.poolPromise = null;
286
+ this.removePoolObserver?.();
287
+ this.removePoolObserver = null;
288
+ }
67
289
  }
68
290
  async getPool() {
69
291
  if (this.closed)
@@ -71,27 +293,41 @@ export class PostgresClient {
71
293
  if (this.pool)
72
294
  return this.pool;
73
295
  if (!this.databaseUrl)
74
- throw new Error("PostgreSQL client has no connection source");
296
+ throw new StoreClosedError("PostgreSQL client has no connection source");
75
297
  if (!this.poolPromise) {
76
- this.poolPromise = this.createPool(this.databaseUrl);
298
+ this.poolPromise = this.createPool(this.databaseUrl).catch((error) => {
299
+ this.poolPromise = null;
300
+ throw error;
301
+ });
77
302
  }
78
303
  return this.poolPromise;
79
304
  }
80
305
  async createPool(databaseUrl) {
81
306
  const Pool = await this.getPoolConstructor();
82
- const pool = new Pool({ connectionString: databaseUrl });
307
+ const pool = new Pool(postgresPoolConfig(databaseUrl, this.connectionOptions));
308
+ this.removePoolObserver = observePool(pool, this.connectionOptions.onPoolError);
83
309
  this.pool = pool;
84
310
  return pool;
85
311
  }
86
312
  async getPoolConstructor() {
87
313
  if (this.poolConstructor)
88
314
  return this.poolConstructor;
89
- const pg = await import("pg");
315
+ let pg;
316
+ try {
317
+ pg = await import("pg");
318
+ }
319
+ catch (cause) {
320
+ throw new BursarImportError("pg is required for PostgreSQL stores: npm install pg", {
321
+ cause,
322
+ });
323
+ }
90
324
  this.poolConstructor = pg.Pool;
91
325
  return this.poolConstructor;
92
326
  }
93
327
  }
94
328
  function normalizeTenantId(tenantId) {
329
+ if (typeof tenantId !== "string")
330
+ throw new TypeError("tenantId must be a UUID");
95
331
  const normalized = tenantId.trim().toLowerCase();
96
332
  if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(normalized)) {
97
333
  throw new TypeError("tenantId must be a UUID");
@@ -1 +1 @@
1
- {"version":3,"file":"postgres-client.js","sourceRoot":"","sources":["../../src/shared/postgres-client.ts"],"names":[],"mappings":"AAyBA;;;;;GAKG;AACH,MAAM,OAAO,cAAc;IACjB,IAAI,CAAsB;IAC1B,WAAW,GAAiC,IAAI,CAAC;IACjD,eAAe,CAAiC;IACvC,WAAW,CAAgB;IAC3B,QAAQ,CAAU;IAClB,WAAW,CAAc;IACzB,QAAQ,CAAgB;IACxB,YAAY,CAA4B;IACxC,qBAAqB,CAAoB;IAClD,MAAM,GAAG,KAAK,CAAC;IAEvB,YAAY,SAAgC,EAAE,UAAiC,EAAE;QAC/E,IAAI,CAAC,WAAW,GAAG,OAAO,SAAS,KAAK,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC;QACpE,IAAI,CAAC,IAAI,GAAG,OAAO,SAAS,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;QAC7D,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,eAAe,IAAI,IAAI,CAAC;QACvD,IAAI,CAAC,QAAQ,GAAG,OAAO,SAAS,KAAK,QAAQ,CAAC;QAC9C,IAAI,CAAC,WAAW;YACd,OAAO,CAAC,WAAW,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC,CAAC;QAChF,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,iBAAiB,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;QAC9E,IAAI,CAAC,YAAY,GAA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AACpB,CAAC","sourcesContent":["import { type BursarError, ImportError as BursarImportError, StoreClosedError } from \"../errors.js\";\nimport { normalizePostgresError, type PostgresOperationPhase } from \"./postgres-errors.js\";\nimport type { QueryFn } from \"./postgres-types.js\";\n\nconst DEFAULT_CONNECTION_TIMEOUT_MS = 10_000;\nconst DEFAULT_STATEMENT_TIMEOUT_MS = 30_000;\nconst DEFAULT_IDLE_TRANSACTION_TIMEOUT_MS = 30_000;\nconst CLIENT_TIMEOUT_GRACE_MS = 1_000;\nconst MAX_POSTGRES_TIMEOUT_MS = 2_147_483_647;\n\nexport interface PostgresPoolConfig {\n connectionString: string;\n connectionTimeoutMillis?: number;\n statement_timeout?: number;\n query_timeout?: number;\n idle_in_transaction_session_timeout?: number;\n idleTimeoutMillis?: number;\n max?: number;\n application_name?: string;\n}\n\nexport interface PostgresPool {\n query(text: string, params?: unknown[]): Promise<{ rows: unknown[] }>;\n connect(): Promise<PostgresPoolClient>;\n end(): Promise<void>;\n on?(event: \"error\", listener: (error: Error) => void): unknown;\n}\n\nexport interface PostgresPoolClient {\n query(text: string, params?: unknown[]): Promise<{ rows: unknown[] }>;\n release(error?: Error | boolean): void;\n}\n\nexport interface PostgresPoolConstructor {\n new (config: PostgresPoolConfig): PostgresPool;\n}\n\nfunction assertPostgresPool(value: unknown): asserts value is PostgresPool {\n if (\n typeof value !== \"object\" ||\n value === null ||\n typeof (value as Partial<PostgresPool>).query !== \"function\" ||\n typeof (value as Partial<PostgresPool>).connect !== \"function\" ||\n typeof (value as Partial<PostgresPool>).end !== \"function\" ||\n ((value as Partial<PostgresPool>).on !== undefined &&\n typeof (value as Partial<PostgresPool>).on !== \"function\")\n ) {\n throw new TypeError(\"postgres pool must provide query(), connect(), and end() methods\");\n }\n}\n\n/** PostgreSQL deadline, pool, and observability controls. */\nexport interface PostgresConnectionOptions {\n /** Time allowed to establish or acquire a connection. Defaults to 10 seconds. */\n connectionTimeoutMs?: number;\n /** Server-side statement deadline. Defaults to 30 seconds; set 0 to disable. */\n statementTimeoutMs?: number;\n /** Server-side idle transaction deadline. Defaults to 30 seconds; set 0 to disable. */\n idleTransactionTimeoutMs?: number;\n /** Idle pooled connection lifetime. Uses pg's default when omitted. */\n idleTimeoutMs?: number;\n /** Maximum connections in an SDK-owned pool. Uses pg's default when omitted. */\n maxConnections?: number;\n /** PostgreSQL application_name. Defaults to `bursar-js`. */\n applicationName?: string;\n /** Receives typed errors emitted by idle pool clients. Must not throw. */\n onPoolError?: (error: BursarError) => void;\n}\n\nexport interface PostgresClientOptions extends PostgresConnectionOptions {\n poolConstructor?: PostgresPoolConstructor;\n closedError?: () => Error;\n tenantId?: string;\n usageBackend?: \"postgres\" | \"clickhouse\";\n billingPayloadBackend?: \"postgres\" | \"s3\";\n}\n\ninterface NormalizedPostgresConnectionOptions {\n connectionTimeoutMs: number;\n statementTimeoutMs: number;\n idleTransactionTimeoutMs: number;\n idleTimeoutMs?: number;\n maxConnections?: number;\n applicationName: string;\n onPoolError?: (error: BursarError) => void;\n}\n\nfunction integerOption(\n value: number | undefined,\n fallback: number | undefined,\n name: string,\n minimum: number,\n maximum = MAX_POSTGRES_TIMEOUT_MS,\n): number | undefined {\n const normalized = value ?? fallback;\n if (normalized === undefined) return undefined;\n if (!Number.isSafeInteger(normalized) || normalized < minimum || normalized > maximum) {\n throw new RangeError(`${name} must be a safe integer between ${minimum} and ${maximum}`);\n }\n return normalized;\n}\n\nfunction normalizeConnectionOptions(\n options: PostgresConnectionOptions,\n): NormalizedPostgresConnectionOptions {\n if (options.applicationName !== undefined && typeof options.applicationName !== \"string\") {\n throw new TypeError(\"applicationName must be a string\");\n }\n if (options.onPoolError !== undefined && typeof options.onPoolError !== \"function\") {\n throw new TypeError(\"onPoolError must be a function\");\n }\n const applicationName = options.applicationName?.trim() || \"bursar-js\";\n if (applicationName.includes(\"\\0\")) {\n throw new TypeError(\"applicationName must not contain null bytes\");\n }\n return {\n connectionTimeoutMs: integerOption(\n options.connectionTimeoutMs,\n DEFAULT_CONNECTION_TIMEOUT_MS,\n \"connectionTimeoutMs\",\n 0,\n )!,\n statementTimeoutMs: integerOption(\n options.statementTimeoutMs,\n DEFAULT_STATEMENT_TIMEOUT_MS,\n \"statementTimeoutMs\",\n 0,\n )!,\n idleTransactionTimeoutMs: integerOption(\n options.idleTransactionTimeoutMs,\n DEFAULT_IDLE_TRANSACTION_TIMEOUT_MS,\n \"idleTransactionTimeoutMs\",\n 0,\n )!,\n idleTimeoutMs: integerOption(options.idleTimeoutMs, undefined, \"idleTimeoutMs\", 0),\n maxConnections: integerOption(options.maxConnections, undefined, \"maxConnections\", 1),\n applicationName,\n onPoolError: options.onPoolError,\n };\n}\n\n/** Build a pg Pool config with finite connection and statement deadlines. */\nexport function postgresPoolConfig(\n connectionString: string,\n options: PostgresConnectionOptions = {},\n): PostgresPoolConfig {\n if (typeof connectionString !== \"string\") {\n throw new TypeError(\"postgres connection string must be a string\");\n }\n if (!connectionString.trim()) throw new TypeError(\"postgres connection string must not be empty\");\n const normalized = normalizeConnectionOptions(options);\n const queryTimeout =\n normalized.statementTimeoutMs === 0\n ? 0\n : Math.min(normalized.statementTimeoutMs + CLIENT_TIMEOUT_GRACE_MS, MAX_POSTGRES_TIMEOUT_MS);\n return {\n connectionString,\n connectionTimeoutMillis: normalized.connectionTimeoutMs,\n statement_timeout: normalized.statementTimeoutMs,\n query_timeout: queryTimeout,\n idle_in_transaction_session_timeout: normalized.idleTransactionTimeoutMs,\n application_name: normalized.applicationName,\n ...(normalized.idleTimeoutMs !== undefined\n ? { idleTimeoutMillis: normalized.idleTimeoutMs }\n : {}),\n ...(normalized.maxConnections !== undefined ? { max: normalized.maxConnections } : {}),\n };\n}\n\ntype PoolErrorObserver = (error: BursarError) => void;\n\nconst poolObservers = new WeakMap<object, Map<PoolErrorObserver, number>>();\n\nfunction notifyPoolError(\n onPoolError: ((error: BursarError) => void) | undefined,\n error: BursarError,\n): void {\n try {\n onPoolError?.(error);\n } catch {\n // Observability callbacks must never destabilize SDK control flow.\n }\n}\n\nfunction observePool(pool: PostgresPool, onPoolError: PoolErrorObserver | undefined): () => void {\n if (!pool.on) return () => {};\n const existing = poolObservers.get(pool);\n if (existing) {\n if (onPoolError) existing.set(onPoolError, (existing.get(onPoolError) ?? 0) + 1);\n return () => {\n if (!onPoolError) return;\n const references = existing.get(onPoolError) ?? 0;\n if (references <= 1) existing.delete(onPoolError);\n else existing.set(onPoolError, references - 1);\n };\n }\n\n const observers = new Map<PoolErrorObserver, number>();\n if (onPoolError) observers.set(onPoolError, 1);\n poolObservers.set(pool, observers);\n pool.on(\"error\", (error) => {\n const normalized = normalizePostgresError(error, { operation: \"pool\", phase: \"pool\" });\n for (const observer of observers.keys()) notifyPoolError(observer, normalized);\n });\n return () => {\n if (!onPoolError) return;\n const references = observers.get(onPoolError) ?? 0;\n if (references <= 1) observers.delete(onPoolError);\n else observers.set(onPoolError, references - 1);\n };\n}\n\n/**\n * Owns the lifecycle and lazy initialization of a PostgreSQL pool.\n *\n * A supplied pool is borrowed and therefore never ended. A connection string\n * creates an owned pool on first use and closes it exactly once.\n */\nexport class PostgresClient {\n private pool: PostgresPool | null;\n private poolPromise: Promise<PostgresPool> | null = null;\n private poolConstructor: PostgresPoolConstructor | null;\n private readonly databaseUrl: string | null;\n private readonly ownsPool: boolean;\n private readonly closedError: () => Error;\n private readonly tenantId: string | null;\n private readonly usageBackend: \"postgres\" | \"clickhouse\";\n private readonly billingPayloadBackend: \"postgres\" | \"s3\";\n private readonly connectionOptions: NormalizedPostgresConnectionOptions;\n private removePoolObserver: (() => void) | null = null;\n private closePromise: Promise<void> | null = null;\n private closed = false;\n\n constructor(poolOrUrl: PostgresPool | string, options: PostgresClientOptions = {}) {\n if (typeof poolOrUrl !== \"string\") assertPostgresPool(poolOrUrl);\n if (options.poolConstructor !== undefined && typeof options.poolConstructor !== \"function\") {\n throw new TypeError(\"poolConstructor must be a constructor\");\n }\n if (options.closedError !== undefined && typeof options.closedError !== \"function\") {\n throw new TypeError(\"closedError must be a function\");\n }\n if (\n options.usageBackend !== undefined &&\n options.usageBackend !== \"postgres\" &&\n options.usageBackend !== \"clickhouse\"\n ) {\n throw new TypeError(\"usageBackend must be 'postgres' or 'clickhouse'\");\n }\n if (\n options.billingPayloadBackend !== undefined &&\n options.billingPayloadBackend !== \"postgres\" &&\n options.billingPayloadBackend !== \"s3\"\n ) {\n throw new TypeError(\"billingPayloadBackend must be 'postgres' or 's3'\");\n }\n this.connectionOptions = normalizeConnectionOptions(options);\n this.databaseUrl = typeof poolOrUrl === \"string\" ? poolOrUrl : null;\n if (this.databaseUrl !== null && !this.databaseUrl.trim()) {\n throw new TypeError(\"postgres connection string must not be empty\");\n }\n this.pool = typeof poolOrUrl === \"string\" ? null : poolOrUrl;\n this.poolConstructor = options.poolConstructor ?? null;\n this.ownsPool = typeof poolOrUrl === \"string\";\n this.closedError =\n options.closedError ?? (() => new StoreClosedError(\"PostgreSQL client has been closed\"));\n this.tenantId = options.tenantId === undefined ? null : normalizeTenantId(options.tenantId);\n this.usageBackend = options.usageBackend ?? \"postgres\";\n this.billingPayloadBackend = options.billingPayloadBackend ?? \"postgres\";\n if (this.pool) {\n this.removePoolObserver = observePool(this.pool, this.connectionOptions.onPoolError);\n }\n }\n\n readonly query: QueryFn = async (text: string, params?: unknown[]) => {\n let pool: PostgresPool;\n try {\n pool = await this.getPool();\n } catch (error) {\n if (this.closed) throw error;\n throw normalizePostgresError(error, { operation: \"query\", phase: \"connect\" });\n }\n\n if (!this.tenantId) {\n try {\n return (await pool.query(text, params)).rows;\n } catch (error) {\n throw normalizePostgresError(error, {\n operation: \"query\",\n phase: \"query\",\n indeterminate: true,\n });\n }\n }\n\n let client: PostgresPoolClient;\n try {\n client = await pool.connect();\n } catch (error) {\n throw normalizePostgresError(error, { operation: \"query\", phase: \"connect\" });\n }\n\n let phase: PostgresOperationPhase = \"begin\";\n let transactionStarted = false;\n let discardConnection: Error | undefined;\n try {\n await client.query(\"BEGIN\");\n transactionStarted = true;\n phase = \"configure\";\n await client.query(\n `SELECT set_config('bursar.tenant_id', $1, true), set_config('bursar.usage_backend', $2, true), set_config('bursar.billing_payload_backend', $3, true), set_config('statement_timeout', $4, true), set_config('idle_in_transaction_session_timeout', $5, true)`,\n [\n this.tenantId,\n this.usageBackend,\n this.billingPayloadBackend,\n String(this.connectionOptions.statementTimeoutMs),\n String(this.connectionOptions.idleTransactionTimeoutMs),\n ],\n );\n phase = \"query\";\n const result = await client.query(text, params);\n phase = \"commit\";\n await client.query(\"COMMIT\");\n transactionStarted = false;\n return result.rows;\n } catch (error) {\n const failedPhase = phase;\n let rollbackFailed = false;\n if (transactionStarted) {\n try {\n phase = \"rollback\";\n await client.query(\"ROLLBACK\");\n transactionStarted = false;\n } catch (rollbackError) {\n rollbackFailed = true;\n discardConnection =\n rollbackError instanceof Error\n ? rollbackError\n : new Error(\"PostgreSQL rollback failed\", { cause: rollbackError });\n }\n }\n const normalized = normalizePostgresError(error, {\n operation: \"query\",\n phase: failedPhase,\n indeterminate: failedPhase === \"query\" || failedPhase === \"commit\",\n rollbackFailed,\n });\n throw normalized;\n } finally {\n try {\n client.release(discardConnection);\n } catch (releaseError) {\n const normalized = normalizePostgresError(releaseError, {\n operation: \"release connection\",\n phase: \"pool\",\n });\n notifyPoolError(this.connectionOptions.onPoolError, normalized);\n }\n }\n };\n\n close(): Promise<void> {\n if (this.closePromise) return this.closePromise;\n this.closed = true;\n this.closePromise = this.closePool();\n return this.closePromise;\n }\n\n private async closePool(): Promise<void> {\n if (!this.ownsPool) {\n this.removePoolObserver?.();\n this.removePoolObserver = null;\n return;\n }\n try {\n const pool = this.poolPromise ? await this.poolPromise : this.pool;\n if (pool) await pool.end();\n } catch (error) {\n throw normalizePostgresError(error, { operation: \"close\", phase: \"close\" });\n } finally {\n this.pool = null;\n this.poolPromise = null;\n this.removePoolObserver?.();\n this.removePoolObserver = null;\n }\n }\n\n private async getPool(): Promise<PostgresPool> {\n if (this.closed) throw this.closedError();\n if (this.pool) return this.pool;\n if (!this.databaseUrl) throw new StoreClosedError(\"PostgreSQL client has no connection source\");\n\n if (!this.poolPromise) {\n this.poolPromise = this.createPool(this.databaseUrl).catch((error: unknown) => {\n this.poolPromise = null;\n throw error;\n });\n }\n return this.poolPromise;\n }\n\n private async createPool(databaseUrl: string): Promise<PostgresPool> {\n const Pool = await this.getPoolConstructor();\n const pool = new Pool(postgresPoolConfig(databaseUrl, this.connectionOptions));\n this.removePoolObserver = observePool(pool, this.connectionOptions.onPoolError);\n this.pool = pool;\n return pool;\n }\n\n private async getPoolConstructor(): Promise<PostgresPoolConstructor> {\n if (this.poolConstructor) return this.poolConstructor;\n let pg: typeof import(\"pg\");\n try {\n pg = await import(\"pg\");\n } catch (cause) {\n throw new BursarImportError(\"pg is required for PostgreSQL stores: npm install pg\", {\n cause,\n });\n }\n this.poolConstructor = pg.Pool as unknown as PostgresPoolConstructor;\n return this.poolConstructor;\n }\n}\n\nfunction normalizeTenantId(tenantId: string): string {\n if (typeof tenantId !== \"string\") throw new TypeError(\"tenantId must be a UUID\");\n const normalized = tenantId.trim().toLowerCase();\n if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(normalized)) {\n throw new TypeError(\"tenantId must be a UUID\");\n }\n return normalized;\n}\n"]}
@@ -0,0 +1,11 @@
1
+ import { type BursarError } from "../errors.js";
2
+ export type PostgresOperationPhase = "connect" | "begin" | "configure" | "query" | "commit" | "rollback" | "close" | "pool";
3
+ export interface PostgresErrorContext {
4
+ operation?: string;
5
+ phase?: PostgresOperationPhase;
6
+ indeterminate?: boolean;
7
+ rollbackFailed?: boolean;
8
+ }
9
+ /** Convert pg/network failures into the SDK's stable, cause-preserving taxonomy. */
10
+ export declare function normalizePostgresError(error: unknown, context?: PostgresErrorContext): BursarError;
11
+ //# sourceMappingURL=postgres-errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres-errors.d.ts","sourceRoot":"","sources":["../../src/shared/postgres-errors.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,WAAW,EAKjB,MAAM,cAAc,CAAC;AAEtB,MAAM,MAAM,sBAAsB,GAC9B,SAAS,GACT,OAAO,GACP,WAAW,GACX,OAAO,GACP,QAAQ,GACR,UAAU,GACV,OAAO,GACP,MAAM,CAAC;AAEX,MAAM,WAAW,oBAAoB;IACnC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,sBAAsB,CAAC;IAC/B,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,cAAc,CAAC,EAAE,OAAO,CAAC;CAC1B;AAmFD,oFAAoF;AACpF,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,OAAO,EACd,OAAO,GAAE,oBAAyB,GACjC,WAAW,CA0Bb"}
@@ -0,0 +1,105 @@
1
+ import { isBursarError, StoreError, StoreTimeoutError, StoreUnavailableError, } from "../errors.js";
2
+ const RETRYABLE_SQLSTATES = new Set([
3
+ "40001", // serialization_failure
4
+ "40P01", // deadlock_detected
5
+ "55P03", // lock_not_available
6
+ "57P01", // admin_shutdown
7
+ "57P02", // crash_shutdown
8
+ "57P03", // cannot_connect_now
9
+ "53300", // too_many_connections
10
+ ]);
11
+ const RETRYABLE_NETWORK_CODES = new Set([
12
+ "EAI_AGAIN",
13
+ "ECONNREFUSED",
14
+ "ECONNRESET",
15
+ "EHOSTDOWN",
16
+ "EHOSTUNREACH",
17
+ "ENETDOWN",
18
+ "ENETRESET",
19
+ "ENETUNREACH",
20
+ "ENOTFOUND",
21
+ "EPIPE",
22
+ "ESOCKETTIMEDOUT",
23
+ "ETIMEDOUT",
24
+ ]);
25
+ function errorProperty(error, property) {
26
+ if (typeof error !== "object" || error === null)
27
+ return undefined;
28
+ try {
29
+ return error[property];
30
+ }
31
+ catch {
32
+ return undefined;
33
+ }
34
+ }
35
+ function errorCode(error) {
36
+ const code = errorProperty(error, "code");
37
+ return typeof code === "string" && code.length > 0 ? code.toUpperCase() : undefined;
38
+ }
39
+ function errorMessage(error) {
40
+ if (error instanceof Error)
41
+ return error.message;
42
+ try {
43
+ return String(error);
44
+ }
45
+ catch {
46
+ return "Unknown PostgreSQL failure";
47
+ }
48
+ }
49
+ function isSqlState(code) {
50
+ return code != null && !RETRYABLE_NETWORK_CODES.has(code) && /^[0-9A-Z]{5}$/.test(code);
51
+ }
52
+ function isTimeout(error, code) {
53
+ if (code === "57014" || code === "ETIMEDOUT" || code === "ESOCKETTIMEDOUT")
54
+ return true;
55
+ const message = errorMessage(error);
56
+ return (message === "Query read timeout" ||
57
+ message === "timeout expired" ||
58
+ message === "timeout exceeded when trying to connect" ||
59
+ message === "Connection terminated due to connection timeout" ||
60
+ /\b(?:query|connection|statement) timed? ?out\b/i.test(message));
61
+ }
62
+ function isUnavailable(error, code) {
63
+ if (code?.startsWith("08"))
64
+ return true;
65
+ if (code && (RETRYABLE_SQLSTATES.has(code) || RETRYABLE_NETWORK_CODES.has(code)))
66
+ return true;
67
+ return /^Connection terminated (?:unexpectedly|due to connection timeout)/i.test(errorMessage(error));
68
+ }
69
+ function hasIndeterminateOutcome(error, code) {
70
+ if (code && RETRYABLE_NETWORK_CODES.has(code))
71
+ return true;
72
+ if (code?.startsWith("08"))
73
+ return true;
74
+ if (code === undefined && errorMessage(error) === "Query read timeout")
75
+ return true;
76
+ return /^Connection terminated (?:unexpectedly|due to connection timeout)/i.test(errorMessage(error));
77
+ }
78
+ /** Convert pg/network failures into the SDK's stable, cause-preserving taxonomy. */
79
+ export function normalizePostgresError(error, context = {}) {
80
+ if (isBursarError(error))
81
+ return error;
82
+ const code = errorCode(error);
83
+ const operation = context.operation ?? "operation";
84
+ const details = {
85
+ datastore: "postgresql",
86
+ operation,
87
+ ...(context.phase ? { phase: context.phase } : {}),
88
+ ...(isSqlState(code) ? { sqlState: code } : {}),
89
+ ...(code && !isSqlState(code) ? { networkCode: code } : {}),
90
+ ...(context.rollbackFailed ? { rollbackFailed: true } : {}),
91
+ };
92
+ const options = {
93
+ cause: error,
94
+ details,
95
+ indeterminate: (context.indeterminate ?? false) && hasIndeterminateOutcome(error, code),
96
+ };
97
+ if (isTimeout(error, code)) {
98
+ return new StoreTimeoutError(`PostgreSQL ${operation} timed out`, options);
99
+ }
100
+ if (isUnavailable(error, code)) {
101
+ return new StoreUnavailableError(`PostgreSQL ${operation} is temporarily unavailable`, options);
102
+ }
103
+ return new StoreError(`PostgreSQL ${operation} failed`, options);
104
+ }
105
+ //# sourceMappingURL=postgres-errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres-errors.js","sourceRoot":"","sources":["../../src/shared/postgres-errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,aAAa,EACb,UAAU,EACV,iBAAiB,EACjB,qBAAqB,GACtB,MAAM,cAAc,CAAC;AAmBtB,MAAM,mBAAmB,GAAG,IAAI,GAAG,CAAC;IAClC,OAAO,EAAE,wBAAwB;IACjC,OAAO,EAAE,oBAAoB;IAC7B,OAAO,EAAE,qBAAqB;IAC9B,OAAO,EAAE,iBAAiB;IAC1B,OAAO,EAAE,iBAAiB;IAC1B,OAAO,EAAE,qBAAqB;IAC9B,OAAO,EAAE,uBAAuB;CACjC,CAAC,CAAC;AAEH,MAAM,uBAAuB,GAAG,IAAI,GAAG,CAAC;IACtC,WAAW;IACX,cAAc;IACd,YAAY;IACZ,WAAW;IACX,cAAc;IACd,UAAU;IACV,WAAW;IACX,aAAa;IACb,WAAW;IACX,OAAO;IACP,iBAAiB;IACjB,WAAW;CACZ,CAAC,CAAC;AAEH,SAAS,aAAa,CAAC,KAAc,EAAE,QAAgB;IACrD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,SAAS,CAAC;IAClE,IAAI,CAAC;QACH,OAAQ,KAAiC,CAAC,QAAQ,CAAC,CAAC;IACtD,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC;AAED,SAAS,SA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C;QAC3D,GAAG,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAC5D,CAAC;IACF,MAAM,OAAO,GAAG;QACd,KAAK,EAAE,KAAK;QACZ,OAAO;QACP,aAAa,EAAE,CAAC,OAAO,CAAC,aAAa,IAAI,KAAK,CAAC,IAAI,uBAAuB,CAAC,KAAK,EAAE,IAAI,CAAC;KACxF,CAAC;IAEF,IAAI,SAAS,CAAC,KAAK,EAAE,IAAI,CAAC,EAAE,CAAC;QAC3B,OAAO,IAAI,iBAAiB,CAAC,cAAc,SAAS,YAAY,EAAE,OAAO,CAAC,CAAC;IAC7E,CAAC;IACD,IAAI,aAAa,CAAC,KAAK,EAAE,IAAI,CAAC,EAAE,CAAC;QAC/B,OAAO,IAAI,qBAAqB,CAAC,cAAc,SAAS,6BAA6B,EAAE,OAAO,CAAC,CAAC;IAClG,CAAC;IACD,OAAO,IAAI,UAAU,CAAC,cAAc,SAAS,SAAS,EAAE,OAAO,CAAC,CAAC;AACnE,CAAC","sourcesContent":["import {\n type BursarError,\n isBursarError,\n StoreError,\n StoreTimeoutError,\n StoreUnavailableError,\n} from \"../errors.js\";\n\nexport type PostgresOperationPhase =\n | \"connect\"\n | \"begin\"\n | \"configure\"\n | \"query\"\n | \"commit\"\n | \"rollback\"\n | \"close\"\n | \"pool\";\n\nexport interface PostgresErrorContext {\n operation?: string;\n phase?: PostgresOperationPhase;\n indeterminate?: boolean;\n rollbackFailed?: boolean;\n}\n\nconst RETRYABLE_SQLSTATES = new Set([\n \"40001\", // serialization_failure\n \"40P01\", // deadlock_detected\n \"55P03\", // lock_not_available\n \"57P01\", // admin_shutdown\n \"57P02\", // crash_shutdown\n \"57P03\", // cannot_connect_now\n \"53300\", // too_many_connections\n]);\n\nconst RETRYABLE_NETWORK_CODES = new Set([\n \"EAI_AGAIN\",\n \"ECONNREFUSED\",\n \"ECONNRESET\",\n \"EHOSTDOWN\",\n \"EHOSTUNREACH\",\n \"ENETDOWN\",\n \"ENETRESET\",\n \"ENETUNREACH\",\n \"ENOTFOUND\",\n \"EPIPE\",\n \"ESOCKETTIMEDOUT\",\n \"ETIMEDOUT\",\n]);\n\nfunction errorProperty(error: unknown, property: string): unknown {\n if (typeof error !== \"object\" || error === null) return undefined;\n try {\n return (error as Record<string, unknown>)[property];\n } catch {\n return undefined;\n }\n}\n\nfunction errorCode(error: unknown): string | undefined {\n const code = errorProperty(error, \"code\");\n return typeof code === \"string\" && code.length > 0 ? code.toUpperCase() : undefined;\n}\n\nfunction errorMessage(error: unknown): string {\n if (error instanceof Error) return error.message;\n try {\n return String(error);\n } catch {\n return \"Unknown PostgreSQL failure\";\n }\n}\n\nfunction isSqlState(code: string | undefined): code is string {\n return code != null && !RETRYABLE_NETWORK_CODES.has(code) && /^[0-9A-Z]{5}$/.test(code);\n}\n\nfunction isTimeout(error: unknown, code: string | undefined): boolean {\n if (code === \"57014\" || code === \"ETIMEDOUT\" || code === \"ESOCKETTIMEDOUT\") return true;\n const message = errorMessage(error);\n return (\n message === \"Query read timeout\" ||\n message === \"timeout expired\" ||\n message === \"timeout exceeded when trying to connect\" ||\n message === \"Connection terminated due to connection timeout\" ||\n /\\b(?:query|connection|statement) timed? ?out\\b/i.test(message)\n );\n}\n\nfunction isUnavailable(error: unknown, code: string | undefined): boolean {\n if (code?.startsWith(\"08\")) return true;\n if (code && (RETRYABLE_SQLSTATES.has(code) || RETRYABLE_NETWORK_CODES.has(code))) return true;\n return /^Connection terminated (?:unexpectedly|due to connection timeout)/i.test(\n errorMessage(error),\n );\n}\n\nfunction hasIndeterminateOutcome(error: unknown, code: string | undefined): boolean {\n if (code && RETRYABLE_NETWORK_CODES.has(code)) return true;\n if (code?.startsWith(\"08\")) return true;\n if (code === undefined && errorMessage(error) === \"Query read timeout\") return true;\n return /^Connection terminated (?:unexpectedly|due to connection timeout)/i.test(\n errorMessage(error),\n );\n}\n\n/** Convert pg/network failures into the SDK's stable, cause-preserving taxonomy. */\nexport function normalizePostgresError(\n error: unknown,\n context: PostgresErrorContext = {},\n): BursarError {\n if (isBursarError(error)) return error;\n\n const code = errorCode(error);\n const operation = context.operation ?? \"operation\";\n const details = {\n datastore: \"postgresql\",\n operation,\n ...(context.phase ? { phase: context.phase } : {}),\n ...(isSqlState(code) ? { sqlState: code } : {}),\n ...(code && !isSqlState(code) ? { networkCode: code } : {}),\n ...(context.rollbackFailed ? { rollbackFailed: true } : {}),\n };\n const options = {\n cause: error,\n details,\n indeterminate: (context.indeterminate ?? false) && hasIndeterminateOutcome(error, code),\n };\n\n if (isTimeout(error, code)) {\n return new StoreTimeoutError(`PostgreSQL ${operation} timed out`, options);\n }\n if (isUnavailable(error, code)) {\n return new StoreUnavailableError(`PostgreSQL ${operation} is temporarily unavailable`, options);\n }\n return new StoreError(`PostgreSQL ${operation} failed`, options);\n}\n"]}