@zonastery/bursar 2.0.2 → 2.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/billing/auto-recharge-service.d.ts +1 -1
- package/dist/billing/auto-recharge-service.d.ts.map +1 -1
- package/dist/billing/auto-recharge-service.js +3 -2
- package/dist/billing/auto-recharge-service.js.map +1 -1
- package/dist/billing/billing-store.d.ts +1 -1
- package/dist/billing/billing-store.d.ts.map +1 -1
- package/dist/billing/billing-store.js.map +1 -1
- package/dist/billing/contracts.d.ts +2 -1
- package/dist/billing/contracts.d.ts.map +1 -1
- package/dist/billing/contracts.js.map +1 -1
- package/dist/billing/event-processor.d.ts.map +1 -1
- package/dist/billing/event-processor.js +18 -6
- package/dist/billing/event-processor.js.map +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.js +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
- package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/event.js +33 -1
- package/dist/billing/postgres/repositories/event.js.map +1 -1
- package/dist/billing/postgres/repositories/offer.d.ts +1 -1
- package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/offer.js +1 -1
- package/dist/billing/postgres/repositories/offer.js.map +1 -1
- package/dist/billing/postgres/repositories/topup.d.ts +1 -1
- package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/topup.js +1 -1
- package/dist/billing/postgres/repositories/topup.js.map +1 -1
- package/dist/billing/postgres/store.d.ts +1 -1
- package/dist/billing/postgres/store.d.ts.map +1 -1
- package/dist/billing/postgres/store.js +16 -6
- package/dist/billing/postgres/store.js.map +1 -1
- package/dist/billing/types/auto-recharge.d.ts +1 -1
- package/dist/billing/types/auto-recharge.d.ts.map +1 -1
- package/dist/billing/types/auto-recharge.js.map +1 -1
- package/dist/billing/types/catalog.d.ts +1 -1
- package/dist/billing/types/catalog.d.ts.map +1 -1
- package/dist/billing/types/catalog.js.map +1 -1
- package/dist/billing/types/documents.d.ts +1 -1
- package/dist/billing/types/documents.d.ts.map +1 -1
- package/dist/billing/types/documents.js.map +1 -1
- package/dist/billing/types/events.d.ts +8 -0
- package/dist/billing/types/events.d.ts.map +1 -1
- package/dist/billing/types/events.js.map +1 -1
- package/dist/breakdown.d.ts +1 -1
- package/dist/breakdown.d.ts.map +1 -1
- package/dist/breakdown.js +1 -1
- package/dist/breakdown.js.map +1 -1
- package/dist/commerce/service.d.ts.map +1 -1
- package/dist/commerce/service.js +58 -50
- package/dist/commerce/service.js.map +1 -1
- package/dist/commerce/types.d.ts +1 -1
- package/dist/commerce/types.d.ts.map +1 -1
- package/dist/commerce/types.js.map +1 -1
- package/dist/config/parse-utils.d.ts +1 -1
- package/dist/config/parse-utils.d.ts.map +1 -1
- package/dist/config/parse-utils.js +1 -1
- package/dist/config/parse-utils.js.map +1 -1
- package/dist/config/types.d.ts +1 -1
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/types.js.map +1 -1
- package/dist/config.js +1 -1
- package/dist/config.js.map +1 -1
- package/dist/credits/amount.d.ts +1 -1
- package/dist/credits/amount.d.ts.map +1 -1
- package/dist/credits/amount.js +1 -1
- package/dist/credits/amount.js.map +1 -1
- package/dist/credits/catalog-runtime.d.ts +1 -1
- package/dist/credits/catalog-runtime.d.ts.map +1 -1
- package/dist/credits/catalog-runtime.js +1 -1
- package/dist/credits/catalog-runtime.js.map +1 -1
- package/dist/credits/lease-workflow.d.ts +1 -1
- package/dist/credits/lease-workflow.d.ts.map +1 -1
- package/dist/credits/lease-workflow.js +1 -1
- package/dist/credits/lease-workflow.js.map +1 -1
- package/dist/credits/low-balance-monitor.d.ts +1 -1
- package/dist/credits/low-balance-monitor.d.ts.map +1 -1
- package/dist/credits/low-balance-monitor.js +1 -1
- package/dist/credits/low-balance-monitor.js.map +1 -1
- package/dist/credits/postgres/repositories/balance.js +1 -1
- package/dist/credits/postgres/repositories/balance.js.map +1 -1
- package/dist/credits/postgres/repositories/bucket.js +1 -1
- package/dist/credits/postgres/repositories/bucket.js.map +1 -1
- package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/lease.js +4 -2
- package/dist/credits/postgres/repositories/lease.js.map +1 -1
- package/dist/credits/postgres/repositories/team.d.ts +2 -1
- package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/team.js +19 -5
- package/dist/credits/postgres/repositories/team.js.map +1 -1
- package/dist/credits/postgres/store.d.ts +3 -3
- package/dist/credits/postgres/store.d.ts.map +1 -1
- package/dist/credits/postgres/store.js +6 -3
- package/dist/credits/postgres/store.js.map +1 -1
- package/dist/credits/postgres/value-mappers.d.ts +1 -1
- package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
- package/dist/credits/postgres/value-mappers.js +1 -1
- package/dist/credits/postgres/value-mappers.js.map +1 -1
- package/dist/credits/service-errors.d.ts +1 -1
- package/dist/credits/service-errors.d.ts.map +1 -1
- package/dist/credits/service-errors.js +1 -1
- package/dist/credits/service-errors.js.map +1 -1
- package/dist/credits/service-types.d.ts +4 -1
- package/dist/credits/service-types.d.ts.map +1 -1
- package/dist/credits/service-types.js.map +1 -1
- package/dist/credits/service.d.ts +5 -0
- package/dist/credits/service.d.ts.map +1 -1
- package/dist/credits/service.js +20 -5
- package/dist/credits/service.js.map +1 -1
- package/dist/credits/store.d.ts +10 -1
- package/dist/credits/store.d.ts.map +1 -1
- package/dist/credits/store.js +1 -1
- package/dist/credits/store.js.map +1 -1
- package/dist/credits/types/teams.d.ts +1 -0
- package/dist/credits/types/teams.d.ts.map +1 -1
- package/dist/credits/types/teams.js.map +1 -1
- package/dist/engine.js +1 -1
- package/dist/engine.js.map +1 -1
- package/dist/errors.d.ts +4 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +34 -0
- package/dist/errors.js.map +1 -1
- package/dist/expr/evaluator.d.ts +1 -1
- package/dist/expr/evaluator.d.ts.map +1 -1
- package/dist/expr/evaluator.js +1 -1
- package/dist/expr/evaluator.js.map +1 -1
- package/dist/expr.d.ts +1 -1
- package/dist/expr.d.ts.map +1 -1
- package/dist/expr.js +1 -1
- package/dist/expr.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/metrics.d.ts +1 -1
- package/dist/metrics.d.ts.map +1 -1
- package/dist/metrics.js.map +1 -1
- package/dist/node.d.ts +6 -3
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +1 -0
- package/dist/node.js.map +1 -1
- package/dist/providers/_shared.d.ts +3 -3
- package/dist/providers/_shared.d.ts.map +1 -1
- package/dist/providers/_shared.js +11 -6
- package/dist/providers/_shared.js.map +1 -1
- package/dist/providers/dodo/client-contract.d.ts +8 -15
- package/dist/providers/dodo/client-contract.d.ts.map +1 -1
- package/dist/providers/dodo/client-contract.js.map +1 -1
- package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
- package/dist/providers/dodo/event-mapper.js +18 -2
- package/dist/providers/dodo/event-mapper.js.map +1 -1
- package/dist/providers/dodo/provider.d.ts.map +1 -1
- package/dist/providers/dodo/provider.js +37 -26
- package/dist/providers/dodo/provider.js.map +1 -1
- package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
- package/dist/providers/stripe/event-mapper.js +71 -3
- package/dist/providers/stripe/event-mapper.js.map +1 -1
- package/dist/providers/types.d.ts +0 -1
- package/dist/providers/types.d.ts.map +1 -1
- package/dist/providers/types.js.map +1 -1
- package/dist/shared/diagnostics.d.ts +8 -0
- package/dist/shared/diagnostics.d.ts.map +1 -1
- package/dist/shared/diagnostics.js +49 -0
- package/dist/shared/diagnostics.js.map +1 -1
- package/dist/shared/postgres-client.d.ts +3 -0
- package/dist/shared/postgres-client.d.ts.map +1 -1
- package/dist/shared/postgres-client.js +15 -2
- package/dist/shared/postgres-client.js.map +1 -1
- package/dist/storage/adapters/clickhouse.d.ts +9 -2
- package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
- package/dist/storage/adapters/clickhouse.js +142 -36
- package/dist/storage/adapters/clickhouse.js.map +1 -1
- package/dist/storage/adapters/s3.d.ts +44 -6
- package/dist/storage/adapters/s3.d.ts.map +1 -1
- package/dist/storage/adapters/s3.js +59 -21
- package/dist/storage/adapters/s3.js.map +1 -1
- package/dist/storage/diagnostics.d.ts +105 -0
- package/dist/storage/diagnostics.d.ts.map +1 -0
- package/dist/storage/diagnostics.js +227 -0
- package/dist/storage/diagnostics.js.map +1 -0
- package/dist/storage/maintenance.d.ts +88 -0
- package/dist/storage/maintenance.d.ts.map +1 -0
- package/dist/storage/maintenance.js +266 -0
- package/dist/storage/maintenance.js.map +1 -0
- package/dist/storage/outbox-worker.d.ts +20 -0
- package/dist/storage/outbox-worker.d.ts.map +1 -1
- package/dist/storage/outbox-worker.js +152 -23
- package/dist/storage/outbox-worker.js.map +1 -1
- package/dist/storage/ports.d.ts +43 -1
- package/dist/storage/ports.d.ts.map +1 -1
- package/dist/storage/ports.js.map +1 -1
- package/dist/storage/postgres-repository.d.ts +7 -2
- package/dist/storage/postgres-repository.d.ts.map +1 -1
- package/dist/storage/postgres-repository.js +88 -8
- package/dist/storage/postgres-repository.js.map +1 -1
- package/dist/storage/runtime.d.ts +19 -2
- package/dist/storage/runtime.d.ts.map +1 -1
- package/dist/storage/runtime.js +216 -29
- package/dist/storage/runtime.js.map +1 -1
- package/dist/telemetry/index.d.ts +37 -0
- package/dist/telemetry/index.d.ts.map +1 -0
- package/dist/telemetry/index.js +115 -0
- package/dist/telemetry/index.js.map +1 -0
- package/dist/telemetry/opentelemetry.d.ts +25 -0
- package/dist/telemetry/opentelemetry.d.ts.map +1 -0
- package/dist/telemetry/opentelemetry.js +74 -0
- package/dist/telemetry/opentelemetry.js.map +1 -0
- package/package.json +11 -1
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/** Maximum diagnostic length accepted by the SQL layer. */
|
|
2
2
|
export const PERSISTED_DIAGNOSTIC_MAX_CHARACTERS = 8_192;
|
|
3
|
+
const DIAGNOSTIC_CODE_MAX_CHARACTERS = 128;
|
|
3
4
|
/** Return trimmed, non-empty text accepted by diagnostic SQL constraints. */
|
|
4
5
|
export function boundedDiagnosticMessage(value, fallback = "operation_failed") {
|
|
5
6
|
let message = value instanceof Error ? value.message : value == null ? "" : String(value);
|
|
@@ -15,4 +16,52 @@ export function boundedDiagnosticMessage(value, fallback = "operation_failed") {
|
|
|
15
16
|
export function optionalBoundedDiagnosticMessage(value) {
|
|
16
17
|
return value == null ? null : boundedDiagnosticMessage(value);
|
|
17
18
|
}
|
|
19
|
+
export function diagnosticErrorCode(value) {
|
|
20
|
+
try {
|
|
21
|
+
if (!isBursarError(value))
|
|
22
|
+
return null;
|
|
23
|
+
return isBursarErrorCode(value.code) ? value.code : null;
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/** Return a fixed error type without consulting mutable names or constructors. */
|
|
30
|
+
export function diagnosticErrorType(value) {
|
|
31
|
+
try {
|
|
32
|
+
if (isBursarError(value))
|
|
33
|
+
return "BursarError";
|
|
34
|
+
if (value instanceof AggregateError)
|
|
35
|
+
return "AggregateError";
|
|
36
|
+
if (value instanceof TypeError)
|
|
37
|
+
return "TypeError";
|
|
38
|
+
if (value instanceof RangeError)
|
|
39
|
+
return "RangeError";
|
|
40
|
+
if (value instanceof ReferenceError)
|
|
41
|
+
return "ReferenceError";
|
|
42
|
+
if (value instanceof SyntaxError)
|
|
43
|
+
return "SyntaxError";
|
|
44
|
+
if (value instanceof URIError)
|
|
45
|
+
return "URIError";
|
|
46
|
+
if (value instanceof EvalError)
|
|
47
|
+
return "EvalError";
|
|
48
|
+
if (value instanceof Error)
|
|
49
|
+
return "Error";
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return "UnknownError";
|
|
53
|
+
}
|
|
54
|
+
return "UnknownError";
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Return a persistence-safe diagnostic that never includes an exception
|
|
58
|
+
* message, payload fragment, URL, identifier, or arbitrary metadata.
|
|
59
|
+
*/
|
|
60
|
+
export function persistedDiagnosticSummary(value, fallback = "operation_failed") {
|
|
61
|
+
const operation = boundedDiagnosticMessage(fallback, "operation_failed")
|
|
62
|
+
.replaceAll(/[^A-Za-z0-9_.-]/gu, "_")
|
|
63
|
+
.slice(0, DIAGNOSTIC_CODE_MAX_CHARACTERS);
|
|
64
|
+
return `${operation || "operation_failed"}:${diagnosticErrorCode(value) ?? diagnosticErrorType(value)}`;
|
|
65
|
+
}
|
|
66
|
+
import { isBursarError, isBursarErrorCode } from "../errors.js";
|
|
18
67
|
//# sourceMappingURL=diagnostics.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"diagnostics.js","sourceRoot":"","sources":["../../src/shared/diagnostics.ts"],"names":[],"mappings":"AAAA,2DAA2D;AAC3D,MAAM,CAAC,MAAM,mCAAmC,GAAG,KAAK,CAAC;AAEzD,6EAA6E;AAC7E,MAAM,UAAU,wBAAwB,CAAC,KAAc,EAAE,QAAQ,GAAG,kBAAkB;IACpF,IAAI,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAC1F,OAAO,GAAG,OAAO,CAAC,UAAU,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC,IAAI,EAAE,CAAC;IACpD,IAAI,CAAC,OAAO,IAAI,KAAK,YAAY,KAAK;QAAE,OAAO,GAAG,KAAK,CAAC,IAAI,CAAC;IAE7D,MAAM,kBAAkB,GAAG,QAAQ,CAAC,UAAU,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC,IAAI,EAAE,IAAI,kBAAkB,CAAC;IAC5F,OAAO,KAAK,CAAC,IAAI,CAAC,OAAO,IAAI,kBAAkB,CAAC;SAC7C,KAAK,CAAC,CAAC,EAAE,mCAAmC,CAAC;SAC7C,IAAI,CAAC,EAAE,CAAC,CAAC;AACd,CAAC;AAED,yEAAyE;AACzE,MAAM,UAAU,gCAAgC,CAAC,KAAc;IAC7D,OAAO,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,wBAAwB,CAAC,KAAK,CAAC,CAAC;AAChE,CAAC","sourcesContent":["/** Maximum diagnostic length accepted by the SQL layer. */\nexport const PERSISTED_DIAGNOSTIC_MAX_CHARACTERS = 8_192;\n\n/** Return trimmed, non-empty text accepted by diagnostic SQL constraints. */\nexport function boundedDiagnosticMessage(value: unknown, fallback = \"operation_failed\"): string {\n let message = value instanceof Error ? value.message : value == null ? \"\" : String(value);\n message = message.replaceAll(\"\\0\", \"\\uFFFD\").trim();\n if (!message && value instanceof Error) message = value.name;\n\n const normalizedFallback = fallback.replaceAll(\"\\0\", \"\\uFFFD\").trim() || \"operation_failed\";\n return Array.from(message || normalizedFallback)\n .slice(0, PERSISTED_DIAGNOSTIC_MAX_CHARACTERS)\n .join(\"\");\n}\n\n/** Normalize an optional diagnostic while preserving an absent value. */\nexport function optionalBoundedDiagnosticMessage(value: unknown): string | null {\n return value == null ? null : boundedDiagnosticMessage(value);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"diagnostics.js","sourceRoot":"","sources":["../../src/shared/diagnostics.ts"],"names":[],"mappings":"AAAA,2DAA2D;AAC3D,MAAM,CAAC,MAAM,mCAAmC,GAAG,KAAK,CAAC;AAEzD,MAAM,8BAA8B,GAAG,GAAG,CAAC;AAE3C,6EAA6E;AAC7E,MAAM,UAAU,wBAAwB,CAAC,KAAc,EAAE,QAAQ,GAAG,kBAAkB;IACpF,IAAI,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,C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AAc;YAAE,OAAO,gBAAgB,CAAC;QAC7D,IAAI,KAAK,YAAY,SAAS;YAAE,OAAO,WAAW,CAAC;QACnD,IAAI,KAAK,YAAY,UAAU;YAAE,OAAO,YAAY,CAAC;QACrD,IAAI,KAAK,YAAY,cAAc;YAAE,OAAO,gBAAgB,CAAC;QAC7D,IAAI,KAAK,YAAY,WAAW;YAAE,OAAO,aAAa,CAAC;QACvD,IAAI,KAAK,YAAY,QAAQ;YAAE,OAAO,UAAU,CAAC;QACjD,IAAI,KAAK,YAAY,SAAS;YAAE,OAAO,WAAW,CAAC;QACnD,IAAI,KAAK,YAAY,KAAK;YAAE,OAAO,OAAO,CAAC;IAC7C,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,cAAc,CAAC;IACxB,CAAC;IACD,OAAO,cAAc,CAAC;AACxB,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,0BAA0B,CAAC,KAAc,EAAE,QAAQ,GAAG,kBAAkB;IACtF,MAAM,SAAS,GAAG,wBAAwB,CAAC,QAAQ,EAAE,kBAAkB,CAAC;SACrE,UAAU,CAAC,mBAAmB,EAAE,GAAG,CAAC;SACpC,KAAK,CAAC,CAAC,EAAE,8BAA8B,CAAC,CAAC;IAC5C,OAAO,GAAG,SAAS,IAAI,kBAAkB,IAAI,mBAAmB,CAAC,KAAK,CAAC,IAAI,mBAAmB,CAAC,KAAK,CAAC,EAAE,CAAC;AAC1G,CAAC;AACD,OAAO,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC","sourcesContent":["/** Maximum diagnostic length accepted by the SQL layer. */\nexport const PERSISTED_DIAGNOSTIC_MAX_CHARACTERS = 8_192;\n\nconst DIAGNOSTIC_CODE_MAX_CHARACTERS = 128;\n\n/** Return trimmed, non-empty text accepted by diagnostic SQL constraints. */\nexport function boundedDiagnosticMessage(value: unknown, fallback = \"operation_failed\"): string {\n let message = value instanceof Error ? value.message : value == null ? \"\" : String(value);\n message = message.replaceAll(\"\\0\", \"\\uFFFD\").trim();\n if (!message && value instanceof Error) message = value.name;\n\n const normalizedFallback = fallback.replaceAll(\"\\0\", \"\\uFFFD\").trim() || \"operation_failed\";\n return Array.from(message || normalizedFallback)\n .slice(0, PERSISTED_DIAGNOSTIC_MAX_CHARACTERS)\n .join(\"\");\n}\n\n/** Normalize an optional diagnostic while preserving an absent value. */\nexport function optionalBoundedDiagnosticMessage(value: unknown): string | null {\n return value == null ? null : boundedDiagnosticMessage(value);\n}\n\nexport function diagnosticErrorCode(value: unknown): string | null {\n try {\n if (!isBursarError(value)) return null;\n return isBursarErrorCode(value.code) ? value.code : null;\n } catch {\n return null;\n }\n}\n\n/** Return a fixed error type without consulting mutable names or constructors. */\nexport function diagnosticErrorType(value: unknown): string {\n try {\n if (isBursarError(value)) return \"BursarError\";\n if (value instanceof AggregateError) return \"AggregateError\";\n if (value instanceof TypeError) return \"TypeError\";\n if (value instanceof RangeError) return \"RangeError\";\n if (value instanceof ReferenceError) return \"ReferenceError\";\n if (value instanceof SyntaxError) return \"SyntaxError\";\n if (value instanceof URIError) return \"URIError\";\n if (value instanceof EvalError) return \"EvalError\";\n if (value instanceof Error) return \"Error\";\n } catch {\n return \"UnknownError\";\n }\n return \"UnknownError\";\n}\n\n/**\n * Return a persistence-safe diagnostic that never includes an exception\n * message, payload fragment, URL, identifier, or arbitrary metadata.\n */\nexport function persistedDiagnosticSummary(value: unknown, fallback = \"operation_failed\"): string {\n const operation = boundedDiagnosticMessage(fallback, \"operation_failed\")\n .replaceAll(/[^A-Za-z0-9_.-]/gu, \"_\")\n .slice(0, DIAGNOSTIC_CODE_MAX_CHARACTERS);\n return `${operation || \"operation_failed\"}:${diagnosticErrorCode(value) ?? diagnosticErrorType(value)}`;\n}\nimport { isBursarError, isBursarErrorCode } from \"../errors.js\";\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type BursarError } from "../errors.js";
|
|
2
2
|
import { type ProviderEnvironment } from "../providers/environment.js";
|
|
3
3
|
import type { QueryFn } from "./postgres-types.js";
|
|
4
|
+
import { type Instrumentation } from "../telemetry/index.js";
|
|
4
5
|
export interface PostgresPoolConfig {
|
|
5
6
|
connectionString: string;
|
|
6
7
|
connectionTimeoutMillis?: number;
|
|
@@ -46,6 +47,8 @@ export interface PostgresConnectionOptions {
|
|
|
46
47
|
applicationName?: string;
|
|
47
48
|
/** Receives typed errors emitted by idle pool clients. Must not throw. */
|
|
48
49
|
onPoolError?: (error: BursarError) => void;
|
|
50
|
+
/** Optional vendor-neutral instrumentation. Defaults to Bursar's no-op registry. */
|
|
51
|
+
instrumentation?: Instrumentation;
|
|
49
52
|
}
|
|
50
53
|
export interface PostgresClientOptions extends PostgresConnectionOptions {
|
|
51
54
|
poolConstructor?: PostgresPoolConstructor;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres-client.d.ts","sourceRoot":"","sources":["../../src/shared/postgres-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,WAAW,EAAsD,MAAM,cAAc,CAAC;AACpG,OAAO,EAEL,KAAK,mBAAmB,EACzB,MAAM,6BAA6B,CAAC;AAErC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;
|
|
1
|
+
{"version":3,"file":"postgres-client.d.ts","sourceRoot":"","sources":["../../src/shared/postgres-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,WAAW,EAAsD,MAAM,cAAc,CAAC;AACpG,OAAO,EAEL,KAAK,mBAAmB,EACzB,MAAM,6BAA6B,CAAC;AAErC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,EAA6B,KAAK,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAQxF,MAAM,WAAW,kBAAkB;IACjC,gBAAgB,EAAE,MAAM,CAAC;IACzB,uBAAuB,CAAC,EAAE,MAAM,CAAC;IACjC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,aAAa,CAAC,EAA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AsC;IACxE,OAAO,CAAC,kBAAkB,CAA6B;IACvD,OAAO,CAAC,YAAY,CAA8B;IAClD,OAAO,CAAC,MAAM,CAAS;gBAEX,SAAS,EAAE,YAAY,GAAG,MAAM,EAAE,OAAO,GAAE,qBAA0B;IAiDjF,QAAQ,CAAC,KAAK,EAAE,OAAO,CAwGnB;IAEJ,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;YAOR,SAAS;YAmBT,OAAO;YAcP,UAAU;YAQV,kBAAkB;CAajC;AAED,0EAA0E;AAC1E,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAO1D"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { ImportError as BursarImportError, StoreClosedError } from "../errors.js";
|
|
2
2
|
import { normalizeProviderEnvironment, } from "../providers/environment.js";
|
|
3
3
|
import { normalizePostgresError } from "./postgres-errors.js";
|
|
4
|
+
import { getDefaultInstrumentation } from "../telemetry/index.js";
|
|
4
5
|
const DEFAULT_CONNECTION_TIMEOUT_MS = 10_000;
|
|
5
6
|
const DEFAULT_STATEMENT_TIMEOUT_MS = 30_000;
|
|
6
7
|
const DEFAULT_IDLE_TRANSACTION_TIMEOUT_MS = 30_000;
|
|
@@ -33,6 +34,12 @@ function normalizeConnectionOptions(options) {
|
|
|
33
34
|
if (options.onPoolError !== undefined && typeof options.onPoolError !== "function") {
|
|
34
35
|
throw new TypeError("onPoolError must be a function");
|
|
35
36
|
}
|
|
37
|
+
const instrumentation = options.instrumentation ?? getDefaultInstrumentation();
|
|
38
|
+
if (typeof instrumentation !== "object" ||
|
|
39
|
+
instrumentation === null ||
|
|
40
|
+
typeof instrumentation.run !== "function") {
|
|
41
|
+
throw new TypeError("instrumentation must provide run()");
|
|
42
|
+
}
|
|
36
43
|
const applicationName = options.applicationName?.trim() || "bursar-js";
|
|
37
44
|
if (applicationName.includes("\0")) {
|
|
38
45
|
throw new TypeError("applicationName must not contain null bytes");
|
|
@@ -46,8 +53,14 @@ function normalizeConnectionOptions(options) {
|
|
|
46
53
|
maxConnections: integerOption(options.maxConnections, undefined, "maxConnections", 1),
|
|
47
54
|
applicationName,
|
|
48
55
|
onPoolError: options.onPoolError,
|
|
56
|
+
instrumentation,
|
|
49
57
|
};
|
|
50
58
|
}
|
|
59
|
+
function postgresTelemetryOperation(text) {
|
|
60
|
+
return /^\s*select\s+\*\s+from\s+bursar\.[a-z_][a-z0-9_]*\s*\(/i.test(text)
|
|
61
|
+
? "postgres.rpc"
|
|
62
|
+
: "postgres.query";
|
|
63
|
+
}
|
|
51
64
|
/** Build a pg Pool config with finite connection and statement deadlines. */
|
|
52
65
|
export function postgresPoolConfig(connectionString, options = {}) {
|
|
53
66
|
if (typeof connectionString !== "string") {
|
|
@@ -182,7 +195,7 @@ export class PostgresClient {
|
|
|
182
195
|
this.removePoolObserver = observePool(this.pool, this.connectionOptions.onPoolError);
|
|
183
196
|
}
|
|
184
197
|
}
|
|
185
|
-
query =
|
|
198
|
+
query = (text, params) => this.connectionOptions.instrumentation.run(postgresTelemetryOperation(text), { "bursar.backend": "postgres" }, async () => {
|
|
186
199
|
let pool;
|
|
187
200
|
try {
|
|
188
201
|
pool = await this.getPool();
|
|
@@ -277,7 +290,7 @@ export class PostgresClient {
|
|
|
277
290
|
notifyPoolError(this.connectionOptions.onPoolError, normalized);
|
|
278
291
|
}
|
|
279
292
|
}
|
|
280
|
-
};
|
|
293
|
+
});
|
|
281
294
|
close() {
|
|
282
295
|
if (this.closePromise)
|
|
283
296
|
return this.closePromise;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres-client.js","sourceRoot":"","sources":["../../src/shared/postgres-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoB,WAAW,IAAI,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AACpG,OAAO,EACL,4BAA4B,GAE7B,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,sBAAsB,EAA+B,MAAM,sBAAsB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CAAC,eAAe,CAAC;IAC9B,CAAC;CACF;AAED,0EAA0E;AAC1E,MAAM,UAAU,iBAAiB,CAAC,QAAgB;IAChD,IAAI,OAAO,QAAQ,KAAK,QAAQ;QAAE,MAAM,IAAI,SAAS,CAAC,yBAAyB,CAAC,CAAC;IACjF,MAAM,UAAU,GAAG,QAAQ,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IACjD,IAAI,CAAC,gEAAgE,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;QACvF,MAAM,IAAI,SAAS,CAAC,yBAAyB,CAAC,CAAC;IACjD,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["import { type BursarError, ImportError as BursarImportError, StoreClosedError } from \"../errors.js\";\nimport {\n normalizeProviderEnvironment,\n type ProviderEnvironment,\n} from \"../providers/environment.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 /** Financial provider namespace. Low-level credit-only clients default to `live`. */\n providerEnvironment?: ProviderEnvironment;\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 accessRole?: PostgresAccessRole;\n usageBackend?: \"postgres\" | \"clickhouse\";\n billingPayloadBackend?: \"postgres\" | \"s3\";\n}\n\nexport type PostgresAccessRole = \"bursar_client\" | \"bursar_operator\";\n\ninterface NormalizedPostgresConnectionOptions {\n providerEnvironment: ProviderEnvironment;\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 providerEnvironment: normalizeProviderEnvironment(options.providerEnvironment ?? \"live\"),\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 accessRole: PostgresAccessRole | null;\n private readonly usageBackend: \"postgres\" | \"clickhouse\";\n private readonly billingPayloadBackend: \"postgres\" | \"s3\";\n private readonly providerEnvironment: ProviderEnvironment;\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.accessRole !== undefined &&\n options.accessRole !== \"bursar_client\" &&\n options.accessRole !== \"bursar_operator\"\n ) {\n throw new TypeError(\"accessRole must be 'bursar_client' or 'bursar_operator'\");\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.accessRole = options.accessRole ?? (this.tenantId ? \"bursar_client\" : null);\n this.usageBackend = options.usageBackend ?? \"postgres\";\n this.billingPayloadBackend = options.billingPayloadBackend ?? \"postgres\";\n this.providerEnvironment = this.connectionOptions.providerEnvironment;\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 && !this.accessRole) {\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 if (this.accessRole) await client.query(`SET LOCAL ROLE ${this.accessRole}`);\n const settings = [\n `set_config('statement_timeout', $1, true)`,\n `set_config('idle_in_transaction_session_timeout', $2, true)`,\n ];\n const values: unknown[] = [\n String(this.connectionOptions.statementTimeoutMs),\n String(this.connectionOptions.idleTransactionTimeoutMs),\n ];\n if (this.tenantId) {\n settings.push(\n `set_config('bursar.tenant_id', $3, true)`,\n `set_config('bursar.usage_backend', $4, true)`,\n `set_config('bursar.billing_payload_backend', $5, true)`,\n `set_config('bursar.provider_environment', $6, true)`,\n );\n values.push(\n this.tenantId,\n this.usageBackend,\n this.billingPayloadBackend,\n this.providerEnvironment,\n );\n }\n await client.query(`SELECT ${settings.join(\", \")}`, values);\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 PostgresPoolConstructor;\n return this.poolConstructor;\n }\n}\n\n/** Normalize and validate a tenant UUID at SDK composition boundaries. */\nexport function 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"]}
|
|
1
|
+
{"version":3,"file":"postgres-client.js","sourceRoot":"","sources":["../../src/shared/postgres-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoB,WAAW,IAAI,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AACpG,OAAO,EACL,4BAA4B,GAE7B,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,sBAAsB,EAA+B,MAAM,sBAAsB,CAAC;AAE3F,OAAO,EAAE,yBAAyB,EAAwB,MAAM,uBAAuB,CAAC;AAExF,MAAM,6BAA6B,GAAG,MAAM,CAAC;AAC7C,MAAM,4BAA4B,GAAG,MAAM,CAAC;AAC5C,MAAM,mCAAmC,GAAG,MAAM,CAAC;AACnD,MAAM,uBAAuB,GAAG,KAAK,CAAC;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,KAAK,CAAC,kBAAkB;QAC9B,IAAI,IAAI,CAAC,eAAe;YAAE,OAAO,IAAI,CAAC,eAAe,CAAC;QACtD,IAAI,EAAuB,CAAC;QAC5B,IAAI,CAAC;YACH,EAAE,GAAG,MAAM,MAAM,CAAC,IAAI,CAAC,CAAC;QAC1B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,IAAI,iBAAiB,CAAC,sDAAsD,EAAE;gBAClF,KAAK;aACN,CAAC,CAAC;QACL,CAAC;QACD,IAAI,CAAC,eAAe,GAAG,EAAE,CAAC,IAA+B,CAAC;QAC1D,OAAO,IAAI,CAAC,eAAe,CAAC;IAC9B,CAAC;CACF;AAED,0EAA0E;AAC1E,MAAM,UAAU,iBAAiB,CAAC,QAAgB;IAChD,IAAI,OAAO,QAAQ,KAAK,QAAQ;QAAE,MAAM,IAAI,SAAS,CAAC,yBAAyB,CAAC,CAAC;IACjF,MAAM,UAAU,GAAG,QAAQ,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IACjD,IAAI,CAAC,gEAAgE,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;QACvF,MAAM,IAAI,SAAS,CAAC,yBAAyB,CAAC,CAAC;IACjD,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["import { type BursarError, ImportError as BursarImportError, StoreClosedError } from \"../errors.js\";\nimport {\n normalizeProviderEnvironment,\n type ProviderEnvironment,\n} from \"../providers/environment.js\";\nimport { normalizePostgresError, type PostgresOperationPhase } from \"./postgres-errors.js\";\nimport type { QueryFn } from \"./postgres-types.js\";\nimport { getDefaultInstrumentation, type Instrumentation } from \"../telemetry/index.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 /** Financial provider namespace. Low-level credit-only clients default to `live`. */\n providerEnvironment?: ProviderEnvironment;\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 /** Optional vendor-neutral instrumentation. Defaults to Bursar's no-op registry. */\n instrumentation?: Instrumentation;\n}\n\nexport interface PostgresClientOptions extends PostgresConnectionOptions {\n poolConstructor?: PostgresPoolConstructor;\n closedError?: () => Error;\n tenantId?: string;\n accessRole?: PostgresAccessRole;\n usageBackend?: \"postgres\" | \"clickhouse\";\n billingPayloadBackend?: \"postgres\" | \"s3\";\n}\n\nexport type PostgresAccessRole = \"bursar_client\" | \"bursar_operator\";\n\ninterface NormalizedPostgresConnectionOptions {\n providerEnvironment: ProviderEnvironment;\n connectionTimeoutMs: number;\n statementTimeoutMs: number;\n idleTransactionTimeoutMs: number;\n idleTimeoutMs?: number;\n maxConnections?: number;\n applicationName: string;\n onPoolError?: (error: BursarError) => void;\n instrumentation: Instrumentation;\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 instrumentation = options.instrumentation ?? getDefaultInstrumentation();\n if (\n typeof instrumentation !== \"object\" ||\n instrumentation === null ||\n typeof instrumentation.run !== \"function\"\n ) {\n throw new TypeError(\"instrumentation must provide run()\");\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 providerEnvironment: normalizeProviderEnvironment(options.providerEnvironment ?? \"live\"),\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 instrumentation,\n };\n}\n\nfunction postgresTelemetryOperation(text: string): \"postgres.query\" | \"postgres.rpc\" {\n return /^\\s*select\\s+\\*\\s+from\\s+bursar\\.[a-z_][a-z0-9_]*\\s*\\(/i.test(text)\n ? \"postgres.rpc\"\n : \"postgres.query\";\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 accessRole: PostgresAccessRole | null;\n private readonly usageBackend: \"postgres\" | \"clickhouse\";\n private readonly billingPayloadBackend: \"postgres\" | \"s3\";\n private readonly providerEnvironment: ProviderEnvironment;\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.accessRole !== undefined &&\n options.accessRole !== \"bursar_client\" &&\n options.accessRole !== \"bursar_operator\"\n ) {\n throw new TypeError(\"accessRole must be 'bursar_client' or 'bursar_operator'\");\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.accessRole = options.accessRole ?? (this.tenantId ? \"bursar_client\" : null);\n this.usageBackend = options.usageBackend ?? \"postgres\";\n this.billingPayloadBackend = options.billingPayloadBackend ?? \"postgres\";\n this.providerEnvironment = this.connectionOptions.providerEnvironment;\n if (this.pool) {\n this.removePoolObserver = observePool(this.pool, this.connectionOptions.onPoolError);\n }\n }\n\n readonly query: QueryFn = (text: string, params?: unknown[]) =>\n this.connectionOptions.instrumentation.run(\n postgresTelemetryOperation(text),\n { \"bursar.backend\": \"postgres\" },\n async () => {\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 && !this.accessRole) {\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 if (this.accessRole) await client.query(`SET LOCAL ROLE ${this.accessRole}`);\n const settings = [\n `set_config('statement_timeout', $1, true)`,\n `set_config('idle_in_transaction_session_timeout', $2, true)`,\n ];\n const values: unknown[] = [\n String(this.connectionOptions.statementTimeoutMs),\n String(this.connectionOptions.idleTransactionTimeoutMs),\n ];\n if (this.tenantId) {\n settings.push(\n `set_config('bursar.tenant_id', $3, true)`,\n `set_config('bursar.usage_backend', $4, true)`,\n `set_config('bursar.billing_payload_backend', $5, true)`,\n `set_config('bursar.provider_environment', $6, true)`,\n );\n values.push(\n this.tenantId,\n this.usageBackend,\n this.billingPayloadBackend,\n this.providerEnvironment,\n );\n }\n await client.query(`SELECT ${settings.join(\", \")}`, values);\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\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 PostgresPoolConstructor;\n return this.poolConstructor;\n }\n}\n\n/** Normalize and validate a tenant UUID at SDK composition boundaries. */\nexport function 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"]}
|
|
@@ -26,9 +26,9 @@ export interface ClickHouseUsageStoreOptions {
|
|
|
26
26
|
client: ClickHouseClient;
|
|
27
27
|
tenantId: string;
|
|
28
28
|
table?: string;
|
|
29
|
-
/** Create the usage projection table on first use. Defaults to
|
|
29
|
+
/** Create the usage projection table on first use. Defaults to false. */
|
|
30
30
|
createTable?: boolean;
|
|
31
|
-
/**
|
|
31
|
+
/** TTL used only by SDK-generated DDL when createTable/initializeSchema is used. */
|
|
32
32
|
retentionDays?: number | null;
|
|
33
33
|
}
|
|
34
34
|
/**
|
|
@@ -46,7 +46,13 @@ export declare class ClickHouseUsageStore implements UsageEventSink, UsageAnalyt
|
|
|
46
46
|
private initializePromise;
|
|
47
47
|
constructor(options: ClickHouseUsageStoreOptions);
|
|
48
48
|
initialize(): Promise<void>;
|
|
49
|
+
/** Explicitly create Bursar's standalone projection schema. */
|
|
50
|
+
initializeSchema(): Promise<void>;
|
|
49
51
|
writeUsage(event: UsageChargeExport, outboxEventId: string): Promise<void>;
|
|
52
|
+
/** Insert a batch in one ClickHouse request while retaining each outbox identity. */
|
|
53
|
+
writeUsageBatch(entries: readonly (readonly [UsageChargeExport, string])[]): Promise<void>;
|
|
54
|
+
/** Validate the existing schema without creating or modifying it. */
|
|
55
|
+
checkSchemaCompatibility(): Promise<void>;
|
|
50
56
|
spendByUser(start: Date, end: Date): Promise<SpendByUserRow[]>;
|
|
51
57
|
spendByModel(start: Date, end: Date): Promise<SpendByModelRow[]>;
|
|
52
58
|
topUsers(limit: number, start: Date, end: Date): Promise<TopUserRow[]>;
|
|
@@ -54,6 +60,7 @@ export declare class ClickHouseUsageStore implements UsageEventSink, UsageAnalyt
|
|
|
54
60
|
aggregateStats(start: Date, end: Date): Promise<AggregateStats>;
|
|
55
61
|
listUsageCharges(userId: string, options?: ListUsageChargesOptions): Promise<UsageChargePage>;
|
|
56
62
|
private createProjectionTable;
|
|
63
|
+
private projectUsage;
|
|
57
64
|
private spendRows;
|
|
58
65
|
private analyticsParams;
|
|
59
66
|
private queryRows;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clickhouse.d.ts","sourceRoot":"","sources":["../../../src/storage/adapters/clickhouse.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,cAAc,EACd,aAAa,EACb,eAAe,EACf,cAAc,EACd,UAAU,EACV,mBAAmB,EAEnB,eAAe,EACf,uBAAuB,EACvB,gBAAgB,EACjB,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAGrE,MAAM,WAAW,qBAAqB;IACpC,IAAI,CAAC,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC;CACvB;AAED;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAC/B,OAAO,CAAC,OAAO,EAAE;QAAE,KAAK,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IACtD,MAAM,CAAC,OAAO,EAAE;QACd,KAAK,EAAE,MAAM,CAAC;QACd,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC;QAClC,MAAM,EAAE,aAAa,CAAC;KACvB,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IACrB,KAAK,CAAC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,GAAG,EAAE,IAAI,GAAG,OAAO,CAAC,eAAe,EAAE,CAAC;IAShE,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,GAAG,OAAO,CAAC,UAAU,EAAE,CAAC;IAWtE,UAAU,CAAC,KAAK,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,GAAG,OAAO,CAAC,aAAa,EAAE,CAAC;IAuB5D,cAAc,CAAC,KAAK,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,GAAG,OAAO,CAAC,cAAc,CAAC;IA4B/D,gBAAgB,CACpB,MAAM,EAAE,MAAM,EACd,OAAO,GAAE,uBAA4B,GACpC,OAAO,CAAC,eAAe,CAAC;YA4Eb,qBAAqB;IA0CnC,OAAO,CAAC,YAAY;YAmCN,SAAS;IAwBvB,OAAO,CAAC,eAAe;YAQT,SAAS;CASxB"}
|
|
@@ -1,5 +1,34 @@
|
|
|
1
|
-
import Decimal from "decimal.js";
|
|
1
|
+
import { Decimal } from "decimal.js";
|
|
2
2
|
import { normalizeTenantId } from "../../shared/postgres-client.js";
|
|
3
|
+
const EXPECTED_SCHEMA_COLUMNS = {
|
|
4
|
+
tenant_id: ["UUID"],
|
|
5
|
+
outbox_event_id: ["UInt64"],
|
|
6
|
+
charge_id: ["UUID"],
|
|
7
|
+
account_id: ["UUID"],
|
|
8
|
+
subject_id: ["UUID"],
|
|
9
|
+
operation: ["String", "LowCardinality(String)"],
|
|
10
|
+
feature: ["Nullable(String)", "LowCardinality(Nullable(String))"],
|
|
11
|
+
model: ["Nullable(String)", "LowCardinality(Nullable(String))"],
|
|
12
|
+
region: ["Nullable(String)", "LowCardinality(Nullable(String))"],
|
|
13
|
+
measures: ["String"],
|
|
14
|
+
dimensions: ["String"],
|
|
15
|
+
metadata: ["String"],
|
|
16
|
+
requested: ["Decimal(20,6)"],
|
|
17
|
+
charged: ["Decimal(20,6)"],
|
|
18
|
+
allowance_requested: ["Decimal(20,6)"],
|
|
19
|
+
allowance_covered: ["Decimal(20,6)"],
|
|
20
|
+
billing_disposition: ["String", "LowCardinality(String)"],
|
|
21
|
+
catalog_revision_id: ["Nullable(UUID)"],
|
|
22
|
+
plan_id: ["Nullable(UUID)"],
|
|
23
|
+
rate_card_key: ["Nullable(String)"],
|
|
24
|
+
pricing_snapshot: ["String"],
|
|
25
|
+
ledger_entry_id: ["Nullable(UUID)"],
|
|
26
|
+
correction_of_charge_id: ["Nullable(UUID)"],
|
|
27
|
+
idempotency_key: ["String"],
|
|
28
|
+
request_digest: ["String"],
|
|
29
|
+
event_at: ["DateTime64(6,'UTC')"],
|
|
30
|
+
created_at: ["DateTime64(6,'UTC')"],
|
|
31
|
+
};
|
|
3
32
|
function validateRange(start, end) {
|
|
4
33
|
if (!(start instanceof Date) ||
|
|
5
34
|
!(end instanceof Date) ||
|
|
@@ -41,6 +70,19 @@ function readClickHouseDate(value) {
|
|
|
41
70
|
}
|
|
42
71
|
return `${normalized}Z`;
|
|
43
72
|
}
|
|
73
|
+
function normalizeClickHouseType(value) {
|
|
74
|
+
return value.replace(/\s+/g, "");
|
|
75
|
+
}
|
|
76
|
+
function normalizeOutboxEventId(value) {
|
|
77
|
+
if (!/^(?:0|[1-9]\d*)$/.test(value)) {
|
|
78
|
+
throw new TypeError("ClickHouse outboxEventId must be an unsigned integer string");
|
|
79
|
+
}
|
|
80
|
+
const parsed = BigInt(value);
|
|
81
|
+
if (parsed > 18446744073709551615n) {
|
|
82
|
+
throw new RangeError("ClickHouse outboxEventId exceeds UInt64");
|
|
83
|
+
}
|
|
84
|
+
return parsed.toString();
|
|
85
|
+
}
|
|
44
86
|
/**
|
|
45
87
|
* Idempotent ClickHouse usage projection plus the analytics read port.
|
|
46
88
|
*
|
|
@@ -59,7 +101,7 @@ export class ClickHouseUsageStore {
|
|
|
59
101
|
this.tenantId = normalizeTenantId(options.tenantId);
|
|
60
102
|
this.table = validateTableName(options.table ?? "bursar_usage_events");
|
|
61
103
|
this.quotedTable = quoteTable(this.table);
|
|
62
|
-
this.createTable = options.createTable ??
|
|
104
|
+
this.createTable = options.createTable ?? false;
|
|
63
105
|
this.retentionDays = options.retentionDays ?? null;
|
|
64
106
|
if (this.retentionDays !== null &&
|
|
65
107
|
(!Number.isInteger(this.retentionDays) ||
|
|
@@ -71,6 +113,10 @@ export class ClickHouseUsageStore {
|
|
|
71
113
|
initialize() {
|
|
72
114
|
if (!this.createTable)
|
|
73
115
|
return Promise.resolve();
|
|
116
|
+
return this.initializeSchema();
|
|
117
|
+
}
|
|
118
|
+
/** Explicitly create Bursar's standalone projection schema. */
|
|
119
|
+
initializeSchema() {
|
|
74
120
|
if (!this.initializePromise) {
|
|
75
121
|
this.initializePromise = this.createProjectionTable().catch((error) => {
|
|
76
122
|
this.initializePromise = null;
|
|
@@ -80,46 +126,72 @@ export class ClickHouseUsageStore {
|
|
|
80
126
|
return this.initializePromise;
|
|
81
127
|
}
|
|
82
128
|
async writeUsage(event, outboxEventId) {
|
|
129
|
+
await this.writeUsageBatch([[event, outboxEventId]]);
|
|
130
|
+
}
|
|
131
|
+
/** Insert a batch in one ClickHouse request while retaining each outbox identity. */
|
|
132
|
+
async writeUsageBatch(entries) {
|
|
133
|
+
if (entries.length === 0)
|
|
134
|
+
return;
|
|
135
|
+
const values = entries.map(([event, outboxEventId]) => this.projectUsage(event, outboxEventId));
|
|
83
136
|
await this.initialize();
|
|
84
|
-
if (event.tenantId !== this.tenantId) {
|
|
85
|
-
throw new Error("Usage event tenantId does not match ClickHouse store tenantId");
|
|
86
|
-
}
|
|
87
137
|
await this.client.insert({
|
|
88
138
|
table: this.table,
|
|
89
139
|
format: "JSONEachRow",
|
|
90
|
-
values
|
|
91
|
-
{
|
|
92
|
-
tenant_id: event.tenantId,
|
|
93
|
-
outbox_event_id: outboxEventId,
|
|
94
|
-
charge_id: event.chargeId,
|
|
95
|
-
account_id: event.accountId,
|
|
96
|
-
subject_id: event.subjectId,
|
|
97
|
-
operation: event.operation,
|
|
98
|
-
feature: event.feature,
|
|
99
|
-
model: event.model,
|
|
100
|
-
region: event.region,
|
|
101
|
-
measures: JSON.stringify(event.measures),
|
|
102
|
-
dimensions: JSON.stringify(event.dimensions),
|
|
103
|
-
metadata: JSON.stringify(event.metadata),
|
|
104
|
-
requested: event.requested,
|
|
105
|
-
charged: event.charged,
|
|
106
|
-
allowance_requested: event.allowanceRequested,
|
|
107
|
-
allowance_covered: event.allowanceCovered,
|
|
108
|
-
billing_disposition: event.billingDisposition,
|
|
109
|
-
catalog_revision_id: event.catalogRevisionId,
|
|
110
|
-
plan_id: event.planId,
|
|
111
|
-
rate_card_key: event.rateCardKey,
|
|
112
|
-
pricing_snapshot: JSON.stringify(event.pricingSnapshot),
|
|
113
|
-
ledger_entry_id: event.ledgerEntryId,
|
|
114
|
-
correction_of_charge_id: event.correctionOfChargeId,
|
|
115
|
-
idempotency_key: event.idempotencyKey,
|
|
116
|
-
request_digest: event.requestDigest,
|
|
117
|
-
event_at: clickHouseDate(event.eventAt),
|
|
118
|
-
created_at: clickHouseDate(event.createdAt),
|
|
119
|
-
},
|
|
120
|
-
],
|
|
140
|
+
values,
|
|
121
141
|
});
|
|
122
142
|
}
|
|
143
|
+
/** Validate the existing schema without creating or modifying it. */
|
|
144
|
+
async checkSchemaCompatibility() {
|
|
145
|
+
const [database = "", tableName] = this.table.includes(".")
|
|
146
|
+
? this.table.split(".")
|
|
147
|
+
: ["", this.table];
|
|
148
|
+
const result = await this.client.query({
|
|
149
|
+
query: `SELECT
|
|
150
|
+
c.name,
|
|
151
|
+
c.type,
|
|
152
|
+
t.engine,
|
|
153
|
+
t.engine_full,
|
|
154
|
+
t.sorting_key
|
|
155
|
+
FROM system.columns AS c
|
|
156
|
+
INNER JOIN system.tables AS t
|
|
157
|
+
ON t.database = c.database AND t.name = c.table
|
|
158
|
+
WHERE c.database = if(empty({database:String}), currentDatabase(), {database:String})
|
|
159
|
+
AND c.table = {tableName:String}
|
|
160
|
+
ORDER BY c.position`,
|
|
161
|
+
query_params: { database, tableName },
|
|
162
|
+
format: "JSONEachRow",
|
|
163
|
+
});
|
|
164
|
+
const rows = await result.json();
|
|
165
|
+
if (rows.length === 0) {
|
|
166
|
+
throw new Error(`ClickHouse table ${this.table} does not exist`);
|
|
167
|
+
}
|
|
168
|
+
const actual = new Map(rows.map((row) => [row.name, normalizeClickHouseType(row.type)]));
|
|
169
|
+
const mismatches = [];
|
|
170
|
+
for (const [name, expectedTypes] of Object.entries(EXPECTED_SCHEMA_COLUMNS)) {
|
|
171
|
+
const actualType = actual.get(name);
|
|
172
|
+
const accepted = expectedTypes.map(normalizeClickHouseType);
|
|
173
|
+
if (actualType === undefined)
|
|
174
|
+
mismatches.push(`missing ${name}`);
|
|
175
|
+
else if (!accepted.includes(actualType)) {
|
|
176
|
+
mismatches.push(`${name} is ${actualType}, expected ${accepted.join(" or ")}`);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
const schema = rows[0];
|
|
180
|
+
if (!schema?.engine.endsWith("ReplacingMergeTree")) {
|
|
181
|
+
mismatches.push(`engine ${schema?.engine ?? "unknown"} is not a ReplacingMergeTree`);
|
|
182
|
+
}
|
|
183
|
+
else if (!/\boutbox_event_id\b/.test(schema.engine_full)) {
|
|
184
|
+
mismatches.push("ReplacingMergeTree does not use outbox_event_id as its version column");
|
|
185
|
+
}
|
|
186
|
+
for (const keyColumn of ["tenant_id", "event_at", "charge_id"]) {
|
|
187
|
+
if (!new RegExp(`\\b${keyColumn}\\b`).test(schema?.sorting_key ?? "")) {
|
|
188
|
+
mismatches.push(`sorting key does not include ${keyColumn}`);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (mismatches.length > 0) {
|
|
192
|
+
throw new Error(`ClickHouse table ${this.table} is incompatible: ${mismatches.join("; ")}`);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
123
195
|
async spendByUser(start, end) {
|
|
124
196
|
const rows = await this.spendRows("subject_id", start, end);
|
|
125
197
|
return rows.map((row) => ({
|
|
@@ -299,6 +371,40 @@ export class ClickHouseUsageStore {
|
|
|
299
371
|
ORDER BY (tenant_id, event_at, charge_id)${ttl}`,
|
|
300
372
|
});
|
|
301
373
|
}
|
|
374
|
+
projectUsage(event, outboxEventId) {
|
|
375
|
+
if (event.tenantId !== this.tenantId) {
|
|
376
|
+
throw new Error("Usage event tenantId does not match ClickHouse store tenantId");
|
|
377
|
+
}
|
|
378
|
+
return {
|
|
379
|
+
tenant_id: event.tenantId,
|
|
380
|
+
outbox_event_id: normalizeOutboxEventId(outboxEventId),
|
|
381
|
+
charge_id: event.chargeId,
|
|
382
|
+
account_id: event.accountId,
|
|
383
|
+
subject_id: event.subjectId,
|
|
384
|
+
operation: event.operation,
|
|
385
|
+
feature: event.feature,
|
|
386
|
+
model: event.model,
|
|
387
|
+
region: event.region,
|
|
388
|
+
measures: JSON.stringify(event.measures),
|
|
389
|
+
dimensions: JSON.stringify(event.dimensions),
|
|
390
|
+
metadata: JSON.stringify(event.metadata),
|
|
391
|
+
requested: event.requested,
|
|
392
|
+
charged: event.charged,
|
|
393
|
+
allowance_requested: event.allowanceRequested,
|
|
394
|
+
allowance_covered: event.allowanceCovered,
|
|
395
|
+
billing_disposition: event.billingDisposition,
|
|
396
|
+
catalog_revision_id: event.catalogRevisionId,
|
|
397
|
+
plan_id: event.planId,
|
|
398
|
+
rate_card_key: event.rateCardKey,
|
|
399
|
+
pricing_snapshot: JSON.stringify(event.pricingSnapshot),
|
|
400
|
+
ledger_entry_id: event.ledgerEntryId,
|
|
401
|
+
correction_of_charge_id: event.correctionOfChargeId,
|
|
402
|
+
idempotency_key: event.idempotencyKey,
|
|
403
|
+
request_digest: event.requestDigest,
|
|
404
|
+
event_at: clickHouseDate(event.eventAt),
|
|
405
|
+
created_at: clickHouseDate(event.createdAt),
|
|
406
|
+
};
|
|
407
|
+
}
|
|
302
408
|
async spendRows(keyExpression, start, end, limit) {
|
|
303
409
|
validateRange(start, end);
|
|
304
410
|
const limitSql = limit === undefined ? "" : `\nLIMIT ${limit}`;
|