@getstrata/core 2.2.60 → 3.0.4
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/CHANGELOG.md +26 -0
- package/dist/core/audit/exportAuditLogs.d.ts +12 -3
- package/dist/core/audit/exportStore.d.ts +6 -2
- package/dist/core/audit/siemFormatter.d.ts +2 -2
- package/dist/core/auth/abilityCatalog.d.ts +1 -9
- package/dist/core/auth/authContext.d.ts +2 -0
- package/dist/core/auth/authOutcome.d.ts +32 -0
- package/dist/core/auth/authReader.d.ts +22 -0
- package/dist/core/auth/basicAuthGuard.d.ts +19 -3
- package/dist/core/auth/emailVerification.d.ts +1 -1
- package/dist/core/auth/guard.d.ts +27 -6
- package/dist/core/auth/intendedUrlCookie.d.ts +13 -7
- package/dist/core/auth/jwt.d.ts +5 -4
- package/dist/core/auth/jwtGuard.d.ts +7 -6
- package/dist/core/auth/membershipContext.d.ts +10 -7
- package/dist/core/auth/membershipContextMiddleware.d.ts +3 -3
- package/dist/core/auth/membershipMiddleware.d.ts +1 -2
- package/dist/core/auth/membershipServiceImplementation.d.ts +1 -1
- package/dist/core/auth/oauth/oidcIdToken.d.ts +25 -16
- package/dist/core/auth/oauth/oidcProvider.d.ts +6 -4
- package/dist/core/auth/oauth/providers.d.ts +3 -1
- package/dist/core/auth/oneTimeToken.d.ts +2 -3
- package/dist/core/auth/passwordConfirmCookie.d.ts +15 -6
- package/dist/core/auth/passwordLogin.d.ts +5 -5
- package/dist/core/auth/pendingMfaCookie.d.ts +2 -2
- package/dist/core/auth/policy.d.ts +23 -10
- package/dist/core/auth/requireAuthCapability.d.ts +3 -0
- package/dist/core/auth/resolveMembershipService.d.ts +3 -2
- package/dist/core/auth/saml/samlAssertionReplay.d.ts +4 -4
- package/dist/core/auth/saml/samlServiceProvider.d.ts +11 -7
- package/dist/core/auth/scimAuthMiddleware.d.ts +10 -3
- package/dist/core/auth/sessionCookie.d.ts +20 -9
- package/dist/core/auth/sessionGuard.d.ts +14 -3
- package/dist/core/cache/createCacheStore.d.ts +6 -3
- package/dist/core/cache/redisCacheStore.d.ts +5 -1
- package/dist/core/cache/repository.d.ts +5 -1
- package/dist/core/cache/simpleCache.d.ts +2 -1
- package/dist/core/cache/tokens.d.ts +8 -0
- package/dist/core/config/applicationConfig.d.ts +21 -0
- package/dist/core/config/configSnapshot.d.ts +3 -0
- package/dist/core/config/envSchema.d.ts +3 -2
- package/dist/core/contracts/application.d.ts +153 -0
- package/dist/core/contracts/authUserDirectory.d.ts +24 -7
- package/dist/core/contracts/container.d.ts +20 -23
- package/dist/core/contracts/di.d.ts +4 -2
- package/dist/core/contracts/executionContext.d.ts +5 -0
- package/dist/core/contracts/executionOperations.d.ts +10 -0
- package/dist/core/contracts/executionOwnership.d.ts +38 -0
- package/dist/core/contracts/persistence.d.ts +20 -0
- package/dist/core/contracts/serviceTokens.d.ts +32 -18
- package/dist/core/contracts/services.d.ts +63 -0
- package/dist/core/contracts/token.d.ts +19 -0
- package/dist/core/crypto/fieldEncryption.d.ts +19 -7
- package/dist/core/crypto/fieldEncryptionRotation.d.ts +21 -5
- package/dist/core/crypto/mfaSecret.d.ts +10 -3
- package/dist/core/database/baseRepository.d.ts +14 -10
- package/dist/core/database/bindings.d.ts +6 -0
- package/dist/core/database/bunSql.d.ts +3 -12
- package/dist/core/database/definitions.d.ts +209 -0
- package/dist/core/database/dialect.d.ts +5 -24
- package/dist/core/database/driverPorts.d.ts +116 -0
- package/dist/core/database/errors.d.ts +47 -7
- package/dist/core/database/factory.d.ts +51 -31
- package/dist/core/database/index.d.ts +9 -10
- package/dist/core/database/keyset.d.ts +2 -1
- package/dist/core/database/legacyNativeTransaction.d.ts +5 -0
- package/dist/core/database/manager.d.ts +12 -0
- package/dist/core/database/model.d.ts +91 -97
- package/dist/core/database/modelQuery.d.ts +9 -5
- package/dist/core/database/modelRegistry.d.ts +52 -33
- package/dist/core/database/mysqlConnection.d.ts +1 -19
- package/dist/core/database/mysqlNative.d.ts +38 -0
- package/dist/core/database/nativeTransactions.d.ts +16 -0
- package/dist/core/database/ormInternal.d.ts +85 -0
- package/dist/core/database/ormRuntime.d.ts +4 -0
- package/dist/core/database/ownedReadOnlyObservation.d.ts +16 -0
- package/dist/core/database/postgresNative.d.ts +11 -0
- package/dist/core/database/query.d.ts +24 -23
- package/dist/core/database/queryPlanSnapshot.d.ts +7 -0
- package/dist/core/database/rawMysql.d.ts +7 -0
- package/dist/core/database/rawPostgres.d.ts +23 -0
- package/dist/core/database/rawSqlite.d.ts +6 -0
- package/dist/core/database/relationQueries.d.ts +3 -2
- package/dist/core/database/relationQuery.d.ts +24 -6
- package/dist/core/database/repositoryQuery.d.ts +6 -1
- package/dist/core/database/schema/driver.d.ts +1 -1
- package/dist/core/database/seeders/types.d.ts +1 -1
- package/dist/core/database/session.d.ts +13 -0
- package/dist/core/database/sessionFactory.d.ts +9 -0
- package/dist/core/database/sqlDialects.d.ts +22 -0
- package/dist/core/database/tokens.d.ts +7 -0
- package/dist/core/database/transactionSession.d.ts +43 -0
- package/dist/core/errors/http.d.ts +4 -1
- package/dist/core/events/{eventBus.d.ts → eventBusClass.d.ts} +1 -3
- package/dist/core/events/index.d.ts +2 -3
- package/dist/core/events/outbox/index.d.ts +44 -13
- package/dist/core/events/outbox/metrics.d.ts +4 -4
- package/dist/core/events/outbox/workerTransport.d.ts +17 -0
- package/dist/core/http/authMiddleware.d.ts +2 -2
- package/dist/core/http/authorizeMiddleware.d.ts +2 -2
- package/dist/core/http/bodySizeLimitMiddleware.d.ts +1 -1
- package/dist/core/http/conditionalResponse.d.ts +7 -2
- package/dist/core/http/contentSecurityPolicy.d.ts +4 -3
- package/dist/core/http/corsMiddleware.d.ts +2 -1
- package/dist/core/http/csrfMiddleware.d.ts +6 -1
- package/dist/core/http/csrfToken.d.ts +17 -7
- package/dist/core/http/databaseError.d.ts +4 -0
- package/dist/core/http/etag.d.ts +5 -2
- package/dist/core/http/flashMiddleware.d.ts +1 -1
- package/dist/core/http/flashSession.d.ts +13 -7
- package/dist/core/http/index.d.ts +1 -1
- package/dist/core/http/loginThrottleMiddleware.d.ts +3 -3
- package/dist/core/http/memoryThrottleMiddleware.d.ts +2 -2
- package/dist/core/http/parseMultipartUpload.d.ts +3 -2
- package/dist/core/http/requestMetaContext.d.ts +5 -0
- package/dist/core/http/requireAbilityMiddleware.d.ts +1 -1
- package/dist/core/http/requireAuthMiddleware.d.ts +2 -2
- package/dist/core/http/requirePasswordConfirmMiddleware.d.ts +2 -1
- package/dist/core/http/requireVerifiedMiddleware.d.ts +2 -2
- package/dist/core/http/requireWebAuthMiddleware.d.ts +2 -2
- package/dist/core/http/response.d.ts +4 -3
- package/dist/core/http/scimThrottleMiddleware.d.ts +4 -3
- package/dist/core/http/securedRouteModelBinding.d.ts +10 -3
- package/dist/core/http/securityHeadersMiddleware.d.ts +1 -2
- package/dist/core/http/signedUrl.d.ts +8 -6
- package/dist/core/http/throttleMiddleware.d.ts +9 -5
- package/dist/core/http/uploads.d.ts +9 -3
- package/dist/core/http/webErrorResponse.d.ts +8 -2
- package/dist/core/jobs/exportAuditLogsJob.d.ts +5 -2
- package/dist/core/jobs/invalidateCacheTagsJob.d.ts +5 -4
- package/dist/core/lifecycle/gracefulShutdown.d.ts +2 -5
- package/dist/core/logging/requestLoggingMiddleware.d.ts +1 -1
- package/dist/core/mail/mailer.d.ts +7 -5
- package/dist/core/openapi/generator.d.ts +12 -4
- package/dist/core/openapi/registeredRoute.d.ts +4 -4
- package/dist/core/queue/createAppQueue.d.ts +9 -4
- package/dist/core/queue/failedJobMetrics.d.ts +11 -2
- package/dist/core/queue/failedJobRepository.d.ts +6 -3
- package/dist/core/queue/failedJobService.d.ts +1 -0
- package/dist/core/queue/index.d.ts +16 -6
- package/dist/core/queue/jobRegistry.d.ts +3 -2
- package/dist/core/queue/jobRunner.d.ts +10 -4
- package/dist/core/queue/publicQueue.d.ts +18 -9
- package/dist/core/queue/queueConfig.d.ts +20 -10
- package/dist/core/queue/queueHandoff.d.ts +31 -0
- package/dist/core/queue/queueMetrics.d.ts +10 -3
- package/dist/core/queue/queueServices.d.ts +28 -0
- package/dist/core/queue/queueWorkerTransport.d.ts +28 -0
- package/dist/core/queue/redisQueue.d.ts +19 -10
- package/dist/core/queue/redisQueueKeys.d.ts +5 -5
- package/dist/core/queue/redisStreams.d.ts +17 -10
- package/dist/core/queue/resilientQueue.d.ts +10 -4
- package/dist/core/queue/types.d.ts +1 -0
- package/dist/core/runtime/appKeyPrefix.d.ts +5 -5
- package/dist/core/runtime/application.d.ts +7 -0
- package/dist/core/runtime/executionContext.d.ts +9 -0
- package/dist/core/runtime/executionTasks.d.ts +49 -0
- package/dist/core/runtime/resourceJournal.d.ts +67 -0
- package/dist/core/runtime/serviceGraph.d.ts +14 -0
- package/dist/core/security/oauthState.d.ts +13 -9
- package/dist/core/security/publicReads.d.ts +2 -2
- package/dist/core/security/safeFetch.d.ts +1 -0
- package/dist/core/security/safeUrl.d.ts +3 -0
- package/dist/core/security/scimTenantTokens.d.ts +1 -1
- package/dist/core/security/tokenExpiry.d.ts +1 -1
- package/dist/core/security/webhookSignature.d.ts +1 -1
- package/dist/core/storage/storage.d.ts +24 -16
- package/dist/core/tenant/databaseTenantContext.d.ts +5 -7
- package/dist/core/tenant/resolveTenant.d.ts +2 -2
- package/dist/core/tenant/scopedDatabasePolicy.d.ts +8 -0
- package/dist/core/tenant/tenantDatabaseScope.d.ts +3 -7
- package/dist/core/tenant/tenantMiddleware.d.ts +15 -4
- package/dist/core/tracing/otel.d.ts +4 -6
- package/dist/core/tracing/tracingMiddleware.d.ts +3 -3
- package/dist/core/view/etaViewEngine.d.ts +1 -1
- package/dist/core/view/index.d.ts +5 -4
- package/dist/core/view/tokens.d.ts +8 -0
- package/dist/core/view/viewRenderer.d.ts +2 -2
- package/dist/core/view/webErrorView.d.ts +8 -7
- package/dist/core/view/webLayoutData.d.ts +6 -4
- package/dist/entries/audit/exportAuditLogs.js +87 -1024
- package/dist/entries/audit/siemFormatter.js +4 -90
- package/dist/entries/auth/abilityCatalog.js +28 -0
- package/dist/entries/auth/accessControl.js +5 -16
- package/dist/entries/auth/accountStateMigration.js +216 -236
- package/dist/entries/auth/authOutcome.js +80 -0
- package/dist/entries/auth/authReader.js +68 -0
- package/dist/entries/auth/basicAuthGuard.js +144 -1249
- package/dist/entries/auth/emailVerification.js +2 -2
- package/dist/entries/auth/intendedUrlCookie.js +35 -59
- package/dist/entries/auth/jwt.js +22 -47
- package/dist/entries/auth/jwtGuard.js +99 -231
- package/dist/entries/auth/membershipMiddleware.js +71 -10
- package/dist/entries/auth/membershipScope.js +16 -22
- package/dist/entries/auth/membershipService.js +11 -28
- package/dist/entries/auth/oauth/oidcProvider.js +59 -64
- package/dist/entries/auth/oauth/providers.js +12 -95
- package/dist/entries/auth/oauth/samlProvider.js +53 -1080
- package/dist/entries/auth/oneTimeToken.js +27 -289
- package/dist/entries/auth/passwordConfirmCookie.js +40 -63
- package/dist/entries/auth/passwordLogin.js +94 -399
- package/dist/entries/auth/pendingMfaCookie.js +6 -6
- package/dist/entries/auth/policy.js +22 -56
- package/dist/entries/auth/saml/samlServiceProvider.js +55 -1084
- package/dist/entries/auth/scimAuthMiddleware.js +16 -3358
- package/dist/entries/auth/sessionCookie.js +58 -73
- package/dist/entries/auth/sessionGuard.js +95 -248
- package/dist/entries/auth/tokenHash.js +11 -43
- package/dist/entries/cache/createCacheStore.js +126 -117
- package/dist/entries/cache/repository.js +25 -0
- package/dist/entries/cache/simpleCache.js +12 -7
- package/dist/entries/cache/tokens.js +9 -0
- package/dist/entries/config/applicationConfig.js +163 -0
- package/dist/entries/config/envSchema.js +21 -4
- package/dist/entries/contracts/application.js +1 -0
- package/dist/entries/contracts/authUserDirectory.js +10 -0
- package/dist/entries/contracts/container.js +99 -26
- package/dist/entries/contracts/di.js +3 -0
- package/dist/entries/contracts/executionContext.js +7 -0
- package/dist/entries/contracts/executionOperations.js +7 -0
- package/dist/entries/contracts/executionOwnership.js +7 -0
- package/dist/entries/contracts/membership.js +1 -0
- package/dist/entries/contracts/persistence.js +1 -0
- package/dist/entries/contracts/serviceTokens.js +26 -116
- package/dist/entries/contracts/services.js +98 -0
- package/dist/entries/contracts/token.js +41 -0
- package/dist/entries/crypto/fieldEncryption.js +49 -50
- package/dist/entries/crypto/mfaSecret.js +86 -82
- package/dist/entries/database/acquisitionMetrics.js +107 -0
- package/dist/entries/database/baseRepository.d.ts +2 -0
- package/dist/entries/database/bindings.js +2082 -0
- package/dist/entries/database/definitions.js +175 -0
- package/dist/entries/database/errors.js +114 -89
- package/dist/entries/database/factory.js +67 -28
- package/dist/entries/database/migrations.js +172 -224
- package/dist/entries/database/model.d.ts +1 -0
- package/dist/entries/database/ownedReadOnlyObservation.js +1282 -0
- package/dist/entries/database/query.js +159 -161
- package/dist/entries/database/repositoryQuery.d.ts +1 -0
- package/dist/entries/database/repositoryQuery.js +1 -1373
- package/dist/entries/database/schema.js +216 -236
- package/dist/entries/database/session.js +1 -0
- package/dist/entries/database/sqliteConnection.js +525 -83
- package/dist/entries/database/tokens.js +9 -0
- package/dist/entries/errors/http.js +118 -1
- package/dist/entries/http/authMiddleware.js +8 -5
- package/dist/entries/http/authorizeMiddleware.js +1 -1
- package/dist/entries/http/bodySizeLimitMiddleware.js +2 -2
- package/dist/entries/http/clientIp.js +2 -2
- package/dist/entries/http/conditionalResponse.js +19 -7
- package/dist/entries/http/corsMiddleware.js +6 -101
- package/dist/entries/http/csrfMiddleware.js +92 -106
- package/dist/entries/http/csrfToken.js +58 -94
- package/dist/entries/http/etag.js +7 -4
- package/dist/entries/http/flashMiddleware.js +57 -99
- package/dist/entries/http/flashSession.js +41 -68
- package/dist/entries/http/memoryThrottleMiddleware.js +43 -186
- package/dist/entries/http/metricsMiddleware.js +2 -16
- package/dist/entries/http/parseMultipartUpload.js +15 -29
- package/dist/entries/http/requireAbilityMiddleware.js +2 -2
- package/dist/entries/http/requirePasswordConfirmMiddleware.js +19 -31
- package/dist/entries/http/requireVerifiedMiddleware.js +4 -7
- package/dist/entries/http/requireWebAuthMiddleware.js +2 -2
- package/dist/entries/http/response.js +67 -233
- package/dist/entries/http/routeMiddleware.js +0 -14
- package/dist/entries/http/scimThrottleMiddleware.js +43 -237
- package/dist/entries/http/securedRouteModelBinding.js +37 -25
- package/dist/entries/http/securityHeadersMiddleware.js +8 -25
- package/dist/entries/http/signedUrl.js +20 -110
- package/dist/entries/http/throttleMiddleware.js +41 -185
- package/dist/entries/http/uploads.js +9 -24
- package/dist/entries/jobs/exportAuditLogsJob.js +17 -1498
- package/dist/entries/jobs/invalidateCacheTagsJob.js +12 -47
- package/dist/entries/logging/requestLoggingMiddleware.js +4 -4
- package/dist/entries/mail/mailer.js +68 -78
- package/dist/entries/openapi/generator.js +33 -100
- package/dist/entries/queue/createAppQueue.js +416 -256
- package/dist/entries/queue/failedJobRepository.js +17 -8
- package/dist/entries/queue/failedJobService.js +1 -0
- package/dist/entries/queue/jobRunner.js +141 -66
- package/dist/entries/queue/publicQueue.js +411 -257
- package/dist/entries/queue/queueConfig.js +61 -0
- package/dist/entries/queue/queueHandoff.js +318 -0
- package/dist/entries/queue/queueMetrics.js +989 -1386
- package/dist/entries/queue/queueServices.js +133 -0
- package/dist/entries/queue/queueWorkerTransport.js +1703 -0
- package/dist/entries/queue/redisQueue.js +282 -180
- package/dist/entries/queue.js +6 -45
- package/dist/entries/runtime/application.js +1585 -0
- package/dist/entries/runtime/asyncContextStore.js +0 -16
- package/dist/entries/security/oauthState.js +35 -67
- package/dist/entries/security/publicReads.js +4 -4
- package/dist/entries/security/safeFetch.js +1 -0
- package/dist/entries/security/scimTenantTokens.js +3 -3
- package/dist/entries/security/tokenExpiry.js +2 -2
- package/dist/entries/security/totp.js +1 -87
- package/dist/entries/security/webhookSignature.js +2 -90
- package/dist/entries/storage/storage.js +120 -45
- package/dist/entries/tenant/databaseTenantContext.js +6 -907
- package/dist/entries/tenant/publicTenantHost.js +78 -0
- package/dist/entries/tenant/resolveTenant.js +14 -0
- package/dist/entries/tenant/scopedDatabasePolicy.js +75 -0
- package/dist/entries/tenant/tenancyConfig.js +1 -19
- package/dist/entries/tenant/tenantDatabaseScope.js +3 -892
- package/dist/entries/tracing/tracingMiddleware.js +104 -173
- package/dist/entries/view/tokens.js +11 -0
- package/dist/framework/public-api.d.ts +62 -44
- package/dist/index.js +10435 -11351
- package/dist/internal/ormInternal.js +117 -0
- package/dist/internal/ormRuntime.js +5000 -0
- package/package.json +158 -46
- package/dist/core/database/bindConnection.d.ts +0 -1
- package/dist/core/database/boundConnection.d.ts +0 -5
- package/dist/core/database/defaultConnection.d.ts +0 -7
- package/dist/core/database/namedConnections.d.ts +0 -15
- package/dist/core/database/readOnlyCollector.d.ts +0 -7
- package/dist/core/database/repositoryConnection.d.ts +0 -4
- package/dist/core/database/transaction.d.ts +0 -23
- package/dist/core/database/transactionControl.d.ts +0 -6
- package/dist/core/events/deferredModelEvents.d.ts +0 -7
- package/dist/core/facades/index.d.ts +0 -10
- package/dist/core/runtime/applicationRegistry.d.ts +0 -18
- package/dist/entries/database/bindConnection.js +0 -1
- package/dist/entries/database/boundConnection.js +0 -1
- package/dist/entries/database/defaultConnection.js +0 -1
- package/dist/entries/database/namedConnections.js +0 -1
- package/dist/entries/database/repositoryConnection.js +0 -1
- package/dist/entries/database/transaction.js +0 -1
- package/dist/entries/facades.js +0 -711
- package/dist/entries/runtime/applicationRegistry.js +0 -1
|
@@ -0,0 +1,1282 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// ../../src/core/database/ownedReadOnlyObservation.ts
|
|
3
|
+
import { CORE_EXECUTION_OPERATIONS_TOKEN } from "@getstrata/core/contracts/executionOperations";
|
|
4
|
+
import { CORE_EXECUTION_OWNERSHIP_TOKEN } from "@getstrata/core/contracts/executionOwnership";
|
|
5
|
+
import { DATABASE_SESSION_TOKEN } from "@getstrata/core/database/tokens";
|
|
6
|
+
import { assertNoOwnedTransaction, DATABASE_OWNERSHIP_TOKEN } from "#strata-orm-internal";
|
|
7
|
+
|
|
8
|
+
// ../../src/core/config/configSnapshot.ts
|
|
9
|
+
function copyApplicationConfig(value, ancestors = new Set) {
|
|
10
|
+
if (value === null || typeof value === "string" || typeof value === "boolean")
|
|
11
|
+
return value;
|
|
12
|
+
if (typeof value === "number" && Number.isFinite(value))
|
|
13
|
+
return value;
|
|
14
|
+
if (typeof value !== "object" || ancestors.has(value)) {
|
|
15
|
+
throw new TypeError("Application config must contain acyclic plain data.");
|
|
16
|
+
}
|
|
17
|
+
const array = Array.isArray(value);
|
|
18
|
+
const prototype = Object.getPrototypeOf(value);
|
|
19
|
+
if (prototype !== (array ? Array.prototype : Object.prototype) && !(prototype === null && !array)) {
|
|
20
|
+
throw new TypeError("Application config must contain only plain objects and arrays.");
|
|
21
|
+
}
|
|
22
|
+
if (Object.getOwnPropertySymbols(value).length > 0) {
|
|
23
|
+
throw new TypeError("Application config cannot contain symbol keys.");
|
|
24
|
+
}
|
|
25
|
+
const descriptors = Object.getOwnPropertyDescriptors(value);
|
|
26
|
+
for (const [key, descriptor] of Object.entries(descriptors)) {
|
|
27
|
+
if (!(array && key === "length") && (!descriptor.enumerable || !("value" in descriptor))) {
|
|
28
|
+
throw new TypeError("Application config cannot contain accessors or hidden properties.");
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
ancestors.add(value);
|
|
32
|
+
try {
|
|
33
|
+
if (array) {
|
|
34
|
+
const length = descriptors.length.value;
|
|
35
|
+
if (Object.keys(descriptors).length !== length + 1) {
|
|
36
|
+
throw new TypeError("Application config arrays must be dense and have no extra properties.");
|
|
37
|
+
}
|
|
38
|
+
const result = [];
|
|
39
|
+
for (let index = 0;index < length; index++) {
|
|
40
|
+
const descriptor = descriptors[String(index)];
|
|
41
|
+
if (!descriptor)
|
|
42
|
+
throw new TypeError("Application config arrays must be dense.");
|
|
43
|
+
result.push(copyApplicationConfig(descriptor.value, ancestors));
|
|
44
|
+
}
|
|
45
|
+
return Object.freeze(result);
|
|
46
|
+
}
|
|
47
|
+
const result = {};
|
|
48
|
+
for (const [key, descriptor] of Object.entries(descriptors)) {
|
|
49
|
+
Object.defineProperty(result, key, {
|
|
50
|
+
value: copyApplicationConfig(descriptor.value, ancestors),
|
|
51
|
+
enumerable: true
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
return Object.freeze(result);
|
|
55
|
+
} finally {
|
|
56
|
+
ancestors.delete(value);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// ../../src/core/tenant/scopedDatabasePolicy.ts
|
|
61
|
+
import { assertSameSessionSelection } from "#strata-orm-internal";
|
|
62
|
+
function assertBypassIdentifier(identifier) {
|
|
63
|
+
if (typeof identifier === "number" ? Number.isSafeInteger(identifier) && identifier > 0 : typeof identifier === "string" && identifier.trim().length > 0)
|
|
64
|
+
return;
|
|
65
|
+
throw new TypeError("RLS bypass requires a caller-supplied identifier that pins the row.");
|
|
66
|
+
}
|
|
67
|
+
function createScopedPolicy(ownership, context, selectedRoot) {
|
|
68
|
+
return Object.freeze({
|
|
69
|
+
run: (selected, policy, work) => {
|
|
70
|
+
assertSameSessionSelection(selectedRoot, selected);
|
|
71
|
+
if (!policy || typeof policy !== "object" || !["tenant", "identifier", "bypass"].includes(policy.kind))
|
|
72
|
+
throw new TypeError("Invalid established database policy.");
|
|
73
|
+
if (selected.dialect.driver !== "pgsql") {
|
|
74
|
+
throw new TypeError("RLS tenant scope requires PostgreSQL.");
|
|
75
|
+
}
|
|
76
|
+
if (typeof work !== "function")
|
|
77
|
+
throw new TypeError("Policy callback must be a function.");
|
|
78
|
+
if (policy.kind === "tenant") {
|
|
79
|
+
if (typeof policy.tenantId !== "number")
|
|
80
|
+
throw new TypeError("Tenant identity must be a positive integer.");
|
|
81
|
+
assertBypassIdentifier(policy.tenantId);
|
|
82
|
+
if (!context.tenant || context.tenant.id !== policy.tenantId)
|
|
83
|
+
throw new Error("Established tenant identity mismatch.");
|
|
84
|
+
}
|
|
85
|
+
if (policy.kind === "identifier")
|
|
86
|
+
assertBypassIdentifier(policy.identifier);
|
|
87
|
+
const applied = Object.freeze(policy.kind === "tenant" ? { kind: "tenant", tenantId: policy.tenantId } : policy.kind === "identifier" ? { kind: "identifier", identifier: String(policy.identifier).trim() } : { kind: "bypass" });
|
|
88
|
+
return selected.transaction(async (child) => {
|
|
89
|
+
const [previous] = await child.execute({
|
|
90
|
+
text: `SELECT current_setting('app.tenant_id', true) AS tenant_id,
|
|
91
|
+
current_setting('app.bypass_rls', true) AS bypass_rls,
|
|
92
|
+
current_setting('app.bypass_identifier', true) AS bypass_identifier`,
|
|
93
|
+
params: []
|
|
94
|
+
});
|
|
95
|
+
if (applied.kind === "tenant") {
|
|
96
|
+
await child.execute({
|
|
97
|
+
text: `SELECT set_config('app.tenant_id', $1, true), set_config('app.bypass_rls', $2, true)`,
|
|
98
|
+
params: [String(applied.tenantId), "false"]
|
|
99
|
+
});
|
|
100
|
+
} else if (applied.kind === "bypass") {
|
|
101
|
+
await child.execute({
|
|
102
|
+
text: `SELECT set_config('app.bypass_rls', $1, true)`,
|
|
103
|
+
params: ["true"]
|
|
104
|
+
});
|
|
105
|
+
} else {
|
|
106
|
+
await child.execute({
|
|
107
|
+
text: `SELECT set_config('app.bypass_identifier', $1, true)`,
|
|
108
|
+
params: [String(applied.identifier).trim()]
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
const observation = await ownership.joined(() => work(child));
|
|
112
|
+
if (!observation.body.ok)
|
|
113
|
+
throw observation.body.error;
|
|
114
|
+
if (observation.strictFailed || observation.retained)
|
|
115
|
+
return observation.body.value;
|
|
116
|
+
await child.execute({
|
|
117
|
+
text: `SELECT set_config('app.tenant_id', $1, true),
|
|
118
|
+
set_config('app.bypass_rls', $2, true), set_config('app.bypass_identifier', $3, true)`,
|
|
119
|
+
params: [
|
|
120
|
+
previous?.tenant_id ?? "",
|
|
121
|
+
previous?.bypass_rls ?? "",
|
|
122
|
+
previous?.bypass_identifier ?? ""
|
|
123
|
+
]
|
|
124
|
+
});
|
|
125
|
+
return observation.body.value;
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// ../../src/core/database/isolatedReadOnlyObservation.ts
|
|
132
|
+
var childSource = `
|
|
133
|
+
import { Database } from 'bun:sqlite';
|
|
134
|
+
let db;
|
|
135
|
+
let mysql;
|
|
136
|
+
process.on('message', async message => {
|
|
137
|
+
try {
|
|
138
|
+
if (message.init) {
|
|
139
|
+
if (message.driver === 'mysql') {
|
|
140
|
+
const module = await import(message.module);
|
|
141
|
+
mysql = await module.createConnection({ uri: message.url, timezone: 'Z', connectTimeout: message.timeoutMs });
|
|
142
|
+
await mysql.query("SET time_zone = '+00:00'");
|
|
143
|
+
await mysql.query('SET SESSION max_execution_time = ' + message.timeoutMs);
|
|
144
|
+
await mysql.query('SET SESSION lock_wait_timeout = 1');
|
|
145
|
+
await mysql.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ');
|
|
146
|
+
await mysql.query('START TRANSACTION READ ONLY');
|
|
147
|
+
} else {
|
|
148
|
+
db = new Database(message.filename, { readonly: true, create: false });
|
|
149
|
+
db.exec('PRAGMA busy_timeout = 0');
|
|
150
|
+
db.exec('PRAGMA query_only = ON');
|
|
151
|
+
db.exec('BEGIN');
|
|
152
|
+
}
|
|
153
|
+
process.send({ ok: true, rows: [] });
|
|
154
|
+
} else {
|
|
155
|
+
const rows = mysql ? (message.params.length ? await mysql.execute(message.query, message.params) : await mysql.query(message.query))[0] : db.query(message.query).all(...message.params);
|
|
156
|
+
process.send({ ok: true, rows });
|
|
157
|
+
}
|
|
158
|
+
} catch {
|
|
159
|
+
// No SQL, file paths, payloads or driver exception text crosses the error channel.
|
|
160
|
+
process.send({ ok: false });
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
`;
|
|
164
|
+
async function observeIsolatedReadOnly(profile, operation, options) {
|
|
165
|
+
options.signal.throwIfAborted();
|
|
166
|
+
if (!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs < 1 || options.timeoutMs > 5000)
|
|
167
|
+
throw new TypeError("SQL observation timeout must be between 1 and 5000 milliseconds.");
|
|
168
|
+
const executable = Bun.which("bun", { PATH: process.env.PATH ?? "" });
|
|
169
|
+
if (!executable)
|
|
170
|
+
throw new Error("SQL observations require the Bun CLI on PATH.");
|
|
171
|
+
let pending;
|
|
172
|
+
let stopped = false;
|
|
173
|
+
const { promise: aborted, reject: rejectAbort } = Promise.withResolvers();
|
|
174
|
+
const fail = (error) => {
|
|
175
|
+
pending?.reject(error);
|
|
176
|
+
pending = undefined;
|
|
177
|
+
};
|
|
178
|
+
const child = Bun.spawn({
|
|
179
|
+
cmd: [
|
|
180
|
+
executable,
|
|
181
|
+
"--no-env-file",
|
|
182
|
+
`--config=${process.platform === "win32" ? "NUL" : "/dev/null"}`,
|
|
183
|
+
"-e",
|
|
184
|
+
childSource
|
|
185
|
+
],
|
|
186
|
+
env: {},
|
|
187
|
+
stdout: "ignore",
|
|
188
|
+
stderr: "ignore",
|
|
189
|
+
serialization: "advanced",
|
|
190
|
+
ipc(message) {
|
|
191
|
+
const response = message;
|
|
192
|
+
const request = pending;
|
|
193
|
+
pending = undefined;
|
|
194
|
+
if (response?.ok === true && Array.isArray(response.rows))
|
|
195
|
+
request?.resolve(response.rows);
|
|
196
|
+
else
|
|
197
|
+
request?.reject(new Error("Read-only SQL observation failed."));
|
|
198
|
+
}
|
|
199
|
+
});
|
|
200
|
+
const exited = child.exited.then(() => {
|
|
201
|
+
fail(new Error("SQL observation process exited."));
|
|
202
|
+
});
|
|
203
|
+
const abort = (reason) => {
|
|
204
|
+
stopped = true;
|
|
205
|
+
child.kill("SIGKILL");
|
|
206
|
+
fail(reason);
|
|
207
|
+
rejectAbort(reason);
|
|
208
|
+
};
|
|
209
|
+
const onAbort = () => abort(options.signal.reason);
|
|
210
|
+
options.signal.addEventListener("abort", onAbort, { once: true });
|
|
211
|
+
const timer = setTimeout(() => abort(new Error("SQL observation timed out.")), options.timeoutMs);
|
|
212
|
+
const request = (message) => {
|
|
213
|
+
if (stopped)
|
|
214
|
+
return Promise.reject(new Error("SQL observation is closed."));
|
|
215
|
+
if (pending)
|
|
216
|
+
return Promise.reject(new Error("Concurrent SQL observation queries are not supported."));
|
|
217
|
+
return new Promise((resolve, reject) => {
|
|
218
|
+
pending = { resolve, reject };
|
|
219
|
+
child.send(message);
|
|
220
|
+
});
|
|
221
|
+
};
|
|
222
|
+
try {
|
|
223
|
+
if (options.signal.aborted)
|
|
224
|
+
onAbort();
|
|
225
|
+
const work = (async () => {
|
|
226
|
+
await request({ init: true, ...profile, timeoutMs: options.timeoutMs });
|
|
227
|
+
options.signal.throwIfAborted();
|
|
228
|
+
return operation({
|
|
229
|
+
async unsafe(query, params = []) {
|
|
230
|
+
return await request({
|
|
231
|
+
query,
|
|
232
|
+
params: params.map((value) => profile.driver === "sqlite" && value instanceof Date ? value.toISOString() : value)
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
});
|
|
236
|
+
})();
|
|
237
|
+
return await Promise.race([work, aborted]);
|
|
238
|
+
} finally {
|
|
239
|
+
stopped = true;
|
|
240
|
+
clearTimeout(timer);
|
|
241
|
+
options.signal.removeEventListener("abort", onAbort);
|
|
242
|
+
child.kill("SIGKILL");
|
|
243
|
+
fail(new Error("SQL observation is closed."));
|
|
244
|
+
await exited;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// ../../src/core/database/rawSqlite.ts
|
|
249
|
+
import { Database } from "bun:sqlite";
|
|
250
|
+
import { resolve } from "path";
|
|
251
|
+
|
|
252
|
+
// ../../src/core/database/nativeTransactions.ts
|
|
253
|
+
var failure = (error) => Object.freeze({ error });
|
|
254
|
+
function nativeTransaction(control) {
|
|
255
|
+
let state = "idle";
|
|
256
|
+
let sequence = 0;
|
|
257
|
+
let running = false;
|
|
258
|
+
const knownState = () => control.state?.() ?? "unknown";
|
|
259
|
+
async function run(work, savepoint) {
|
|
260
|
+
const phases = [];
|
|
261
|
+
let stage = Object.freeze({ kind: "callback-not-entered" });
|
|
262
|
+
let terminalFailure = null;
|
|
263
|
+
let data = "not-started";
|
|
264
|
+
let open = false;
|
|
265
|
+
let childActive = false;
|
|
266
|
+
const phase = async (name, sql) => {
|
|
267
|
+
try {
|
|
268
|
+
const reply = await control.control(sql);
|
|
269
|
+
phases.push(Object.freeze({ phase: name, acknowledgement: "confirmed-reply", failure: null }));
|
|
270
|
+
return reply;
|
|
271
|
+
} catch (error) {
|
|
272
|
+
const proof = knownState();
|
|
273
|
+
phases.push(Object.freeze({
|
|
274
|
+
phase: name,
|
|
275
|
+
acknowledgement: name === "commit" && proof === "transaction-active" || name === "begin" && proof === "idle" ? "proven-not-applied" : "unknown",
|
|
276
|
+
failure: failure(error)
|
|
277
|
+
}));
|
|
278
|
+
state = proof;
|
|
279
|
+
throw error;
|
|
280
|
+
}
|
|
281
|
+
};
|
|
282
|
+
const result = () => Object.freeze({
|
|
283
|
+
data,
|
|
284
|
+
nativeState: state,
|
|
285
|
+
stage,
|
|
286
|
+
phases: Object.freeze([...phases]),
|
|
287
|
+
failure: terminalFailure
|
|
288
|
+
});
|
|
289
|
+
try {
|
|
290
|
+
await phase(savepoint ? "savepoint" : "begin", savepoint ? `SAVEPOINT ${savepoint}` : control.beginSql ?? "BEGIN");
|
|
291
|
+
state = "transaction-active";
|
|
292
|
+
open = true;
|
|
293
|
+
} catch (error) {
|
|
294
|
+
terminalFailure = failure(error);
|
|
295
|
+
data = state === "idle" && !savepoint ? "not-started" : "unknown";
|
|
296
|
+
return result();
|
|
297
|
+
}
|
|
298
|
+
const transaction = Object.freeze({
|
|
299
|
+
execute(statement) {
|
|
300
|
+
if (!open || childActive)
|
|
301
|
+
return Promise.reject(new Error("Native transaction branch is not active."));
|
|
302
|
+
return control.execute(statement);
|
|
303
|
+
},
|
|
304
|
+
async savepoint(callback) {
|
|
305
|
+
if (!open || childActive)
|
|
306
|
+
throw new Error("Native transaction branch is not active.");
|
|
307
|
+
childActive = true;
|
|
308
|
+
try {
|
|
309
|
+
return await run(callback, `strata_sp_${++sequence}`);
|
|
310
|
+
} finally {
|
|
311
|
+
childActive = false;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
});
|
|
315
|
+
stage = Object.freeze({ kind: "callback-running" });
|
|
316
|
+
try {
|
|
317
|
+
const decision = await work(transaction);
|
|
318
|
+
if (!decision || decision.finish !== "commit" && decision.finish !== "rollback")
|
|
319
|
+
throw new TypeError("Invalid native transaction decision.");
|
|
320
|
+
stage = Object.freeze({
|
|
321
|
+
kind: "decided",
|
|
322
|
+
decision: Object.freeze({ finish: decision.finish, result: decision.result })
|
|
323
|
+
});
|
|
324
|
+
} catch (error) {
|
|
325
|
+
stage = Object.freeze({ kind: "callback-failed", error });
|
|
326
|
+
} finally {
|
|
327
|
+
open = false;
|
|
328
|
+
}
|
|
329
|
+
const rollback = async () => {
|
|
330
|
+
if (savepoint) {
|
|
331
|
+
await phase("rollback-to", `ROLLBACK TO SAVEPOINT ${savepoint}`);
|
|
332
|
+
await phase("release-savepoint", `RELEASE SAVEPOINT ${savepoint}`);
|
|
333
|
+
state = "transaction-active";
|
|
334
|
+
} else {
|
|
335
|
+
await phase("rollback", "ROLLBACK");
|
|
336
|
+
state = "idle";
|
|
337
|
+
}
|
|
338
|
+
};
|
|
339
|
+
if (stage.kind === "decided" && stage.decision.finish === "commit") {
|
|
340
|
+
try {
|
|
341
|
+
const reply = await phase(savepoint ? "release-savepoint" : "commit", savepoint ? `RELEASE SAVEPOINT ${savepoint}` : "COMMIT");
|
|
342
|
+
data = savepoint ? "released" : reply.command === "ROLLBACK" ? "rolled-back" : "committed";
|
|
343
|
+
state = savepoint ? "transaction-active" : "idle";
|
|
344
|
+
} catch (error) {
|
|
345
|
+
terminalFailure = failure(error);
|
|
346
|
+
const commitNotApplied = !savepoint && state === "transaction-active" && control.state !== undefined;
|
|
347
|
+
data = "unknown";
|
|
348
|
+
try {
|
|
349
|
+
await rollback();
|
|
350
|
+
if (savepoint || commitNotApplied)
|
|
351
|
+
data = "rolled-back";
|
|
352
|
+
} catch {}
|
|
353
|
+
}
|
|
354
|
+
} else {
|
|
355
|
+
try {
|
|
356
|
+
await rollback();
|
|
357
|
+
data = "rolled-back";
|
|
358
|
+
} catch (error) {
|
|
359
|
+
terminalFailure = failure(error);
|
|
360
|
+
data = "unknown";
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
return result();
|
|
364
|
+
}
|
|
365
|
+
return {
|
|
366
|
+
get state() {
|
|
367
|
+
return state;
|
|
368
|
+
},
|
|
369
|
+
async begin(work) {
|
|
370
|
+
if (running)
|
|
371
|
+
throw new Error("Native pin already has an active transaction.");
|
|
372
|
+
running = true;
|
|
373
|
+
try {
|
|
374
|
+
return await run(work);
|
|
375
|
+
} finally {
|
|
376
|
+
running = false;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
// ../../src/core/database/sqlDialects.ts
|
|
383
|
+
function assertSafeIdentifier(identifier) {
|
|
384
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(identifier)) {
|
|
385
|
+
throw new Error(`Invalid SQL identifier: ${identifier}`);
|
|
386
|
+
}
|
|
387
|
+
return identifier;
|
|
388
|
+
}
|
|
389
|
+
function quoteIdentifierFor(dialect, column) {
|
|
390
|
+
return dialect.quoteIdentifier(column);
|
|
391
|
+
}
|
|
392
|
+
var postgresDialect = Object.freeze({
|
|
393
|
+
driver: "pgsql",
|
|
394
|
+
placeholder(index) {
|
|
395
|
+
return `$${index}`;
|
|
396
|
+
},
|
|
397
|
+
quoteIdentifier(identifier) {
|
|
398
|
+
return `"${assertSafeIdentifier(identifier)}"`;
|
|
399
|
+
},
|
|
400
|
+
nowExpression() {
|
|
401
|
+
return "NOW()";
|
|
402
|
+
},
|
|
403
|
+
epochMillisecondsExpression() {
|
|
404
|
+
return "CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)";
|
|
405
|
+
},
|
|
406
|
+
rowLockClause(skipLocked = false) {
|
|
407
|
+
return ` FOR UPDATE${skipLocked ? " SKIP LOCKED" : ""}`;
|
|
408
|
+
},
|
|
409
|
+
timestampValue(value) {
|
|
410
|
+
return value.toISOString();
|
|
411
|
+
},
|
|
412
|
+
returningClause(columns) {
|
|
413
|
+
return ` RETURNING ${columns}`;
|
|
414
|
+
},
|
|
415
|
+
ilikeOperator() {
|
|
416
|
+
return "ILIKE";
|
|
417
|
+
},
|
|
418
|
+
nullsLastSuffix() {
|
|
419
|
+
return " NULLS LAST";
|
|
420
|
+
},
|
|
421
|
+
castToText(expression) {
|
|
422
|
+
return `${expression}::text`;
|
|
423
|
+
},
|
|
424
|
+
upsertSuffix(conflictColumns, updateColumns) {
|
|
425
|
+
const target = conflictColumns.map((column) => quoteIdentifierFor(this, column)).join(", ");
|
|
426
|
+
if (updateColumns.length === 0) {
|
|
427
|
+
return ` ON CONFLICT (${target}) DO NOTHING`;
|
|
428
|
+
}
|
|
429
|
+
const assignments = updateColumns.map((column) => {
|
|
430
|
+
const quoted = quoteIdentifierFor(this, column);
|
|
431
|
+
return `${quoted} = excluded.${quoted}`;
|
|
432
|
+
}).join(", ");
|
|
433
|
+
return ` ON CONFLICT (${target}) DO UPDATE SET ${assignments}`;
|
|
434
|
+
}
|
|
435
|
+
});
|
|
436
|
+
var mysqlDialect = Object.freeze({
|
|
437
|
+
driver: "mysql",
|
|
438
|
+
placeholder() {
|
|
439
|
+
return "?";
|
|
440
|
+
},
|
|
441
|
+
quoteIdentifier(identifier) {
|
|
442
|
+
return `\`${assertSafeIdentifier(identifier)}\``;
|
|
443
|
+
},
|
|
444
|
+
nowExpression() {
|
|
445
|
+
return "CURRENT_TIMESTAMP";
|
|
446
|
+
},
|
|
447
|
+
epochMillisecondsExpression() {
|
|
448
|
+
return "CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000 AS UNSIGNED)";
|
|
449
|
+
},
|
|
450
|
+
rowLockClause(skipLocked = false) {
|
|
451
|
+
return ` FOR UPDATE${skipLocked ? " SKIP LOCKED" : ""}`;
|
|
452
|
+
},
|
|
453
|
+
timestampValue(value) {
|
|
454
|
+
return value.toISOString().slice(0, 19).replace("T", " ");
|
|
455
|
+
},
|
|
456
|
+
returningClause() {
|
|
457
|
+
return "";
|
|
458
|
+
},
|
|
459
|
+
ilikeOperator() {
|
|
460
|
+
return "LIKE";
|
|
461
|
+
},
|
|
462
|
+
nullsLastSuffix() {
|
|
463
|
+
return "";
|
|
464
|
+
},
|
|
465
|
+
castToText(expression) {
|
|
466
|
+
return `CAST(${expression} AS CHAR)`;
|
|
467
|
+
},
|
|
468
|
+
upsertSuffix(conflictColumns, updateColumns) {
|
|
469
|
+
if (updateColumns.length === 0) {
|
|
470
|
+
const anchor = quoteIdentifierFor(this, conflictColumns[0] ?? "");
|
|
471
|
+
return ` ON DUPLICATE KEY UPDATE ${anchor} = ${anchor}`;
|
|
472
|
+
}
|
|
473
|
+
const assignments = updateColumns.map((column) => {
|
|
474
|
+
const quoted = quoteIdentifierFor(this, column);
|
|
475
|
+
return `${quoted} = VALUES(${quoted})`;
|
|
476
|
+
}).join(", ");
|
|
477
|
+
return ` ON DUPLICATE KEY UPDATE ${assignments}`;
|
|
478
|
+
}
|
|
479
|
+
});
|
|
480
|
+
var sqliteDialect = Object.freeze({
|
|
481
|
+
driver: "sqlite",
|
|
482
|
+
placeholder() {
|
|
483
|
+
return "?";
|
|
484
|
+
},
|
|
485
|
+
quoteIdentifier(identifier) {
|
|
486
|
+
return `"${assertSafeIdentifier(identifier)}"`;
|
|
487
|
+
},
|
|
488
|
+
nowExpression() {
|
|
489
|
+
return "strftime('%Y-%m-%dT%H:%M:%fZ', 'now')";
|
|
490
|
+
},
|
|
491
|
+
epochMillisecondsExpression() {
|
|
492
|
+
return "CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)";
|
|
493
|
+
},
|
|
494
|
+
rowLockClause() {
|
|
495
|
+
return "";
|
|
496
|
+
},
|
|
497
|
+
timestampValue(value) {
|
|
498
|
+
return value.toISOString();
|
|
499
|
+
},
|
|
500
|
+
returningClause(columns) {
|
|
501
|
+
return ` RETURNING ${columns}`;
|
|
502
|
+
},
|
|
503
|
+
ilikeOperator() {
|
|
504
|
+
return "LIKE";
|
|
505
|
+
},
|
|
506
|
+
nullsLastSuffix() {
|
|
507
|
+
return "";
|
|
508
|
+
},
|
|
509
|
+
castToText(expression) {
|
|
510
|
+
return `CAST(${expression} AS TEXT)`;
|
|
511
|
+
},
|
|
512
|
+
upsertSuffix(conflictColumns, updateColumns) {
|
|
513
|
+
const target = conflictColumns.map((column) => quoteIdentifierFor(this, column)).join(", ");
|
|
514
|
+
if (updateColumns.length === 0) {
|
|
515
|
+
return ` ON CONFLICT (${target}) DO NOTHING`;
|
|
516
|
+
}
|
|
517
|
+
const assignments = updateColumns.map((column) => {
|
|
518
|
+
const quoted = quoteIdentifierFor(this, column);
|
|
519
|
+
return `${quoted} = excluded.${quoted}`;
|
|
520
|
+
}).join(", ");
|
|
521
|
+
return ` ON CONFLICT (${target}) DO UPDATE SET ${assignments}`;
|
|
522
|
+
}
|
|
523
|
+
});
|
|
524
|
+
var dialects = Object.freeze({
|
|
525
|
+
pgsql: postgresDialect,
|
|
526
|
+
mysql: mysqlDialect,
|
|
527
|
+
sqlite: sqliteDialect
|
|
528
|
+
});
|
|
529
|
+
function dialectFor(driver) {
|
|
530
|
+
if (!Object.hasOwn(dialects, driver))
|
|
531
|
+
throw new TypeError("Unsupported SQL driver.");
|
|
532
|
+
return dialects[driver];
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
// ../../src/core/database/rawSqlite.ts
|
|
536
|
+
function sqliteFilename(filename) {
|
|
537
|
+
if (!filename.trim())
|
|
538
|
+
throw new Error("SQLite path is not configured. Pass a filename or :memory:.");
|
|
539
|
+
return filename === ":memory:" ? filename : resolve(filename);
|
|
540
|
+
}
|
|
541
|
+
function isRowReturning(sql) {
|
|
542
|
+
const upper = sql.replace(/\s+/g, " ").trim().toUpperCase();
|
|
543
|
+
return upper.includes(" RETURNING ") || upper.startsWith("SELECT") || upper.startsWith("WITH") || upper.startsWith("PRAGMA") || upper.startsWith("EXPLAIN");
|
|
544
|
+
}
|
|
545
|
+
function openRawSqlitePool(options) {
|
|
546
|
+
let filename;
|
|
547
|
+
try {
|
|
548
|
+
filename = sqliteFilename(options.filename);
|
|
549
|
+
} catch (error) {
|
|
550
|
+
return { ok: false, error, disposition: "not-acquired" };
|
|
551
|
+
}
|
|
552
|
+
let db;
|
|
553
|
+
try {
|
|
554
|
+
db = new Database(filename, { create: true });
|
|
555
|
+
} catch (error) {
|
|
556
|
+
return { ok: false, error, disposition: "unknown" };
|
|
557
|
+
}
|
|
558
|
+
try {
|
|
559
|
+
db.exec("PRAGMA foreign_keys = ON");
|
|
560
|
+
db.exec("PRAGMA busy_timeout = 5000");
|
|
561
|
+
if (filename !== ":memory:") {
|
|
562
|
+
db.exec("PRAGMA journal_mode = WAL");
|
|
563
|
+
db.exec("PRAGMA synchronous = NORMAL");
|
|
564
|
+
}
|
|
565
|
+
} catch (error) {
|
|
566
|
+
try {
|
|
567
|
+
db.close();
|
|
568
|
+
return { ok: false, error, disposition: "cleaned" };
|
|
569
|
+
} catch (cleanupError) {
|
|
570
|
+
return { ok: false, error, disposition: "unknown", cleanupErrors: [cleanupError] };
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
let tail = Promise.resolve();
|
|
574
|
+
let pending = 0;
|
|
575
|
+
let closed = false;
|
|
576
|
+
let quarantined = false;
|
|
577
|
+
function check() {
|
|
578
|
+
if (closed)
|
|
579
|
+
throw new Error("SQLite connection is closed.");
|
|
580
|
+
if (quarantined)
|
|
581
|
+
throw new Error("SQLite connection is quarantined after uncertain native state.");
|
|
582
|
+
}
|
|
583
|
+
function execute(statement) {
|
|
584
|
+
try {
|
|
585
|
+
check();
|
|
586
|
+
const query = db.query(statement.text);
|
|
587
|
+
const params = statement.params.map((value) => value instanceof Date ? value.toISOString() : value);
|
|
588
|
+
if (isRowReturning(statement.text))
|
|
589
|
+
return Promise.resolve(query.all(...params));
|
|
590
|
+
query.run(...params);
|
|
591
|
+
return Promise.resolve([]);
|
|
592
|
+
} catch (error) {
|
|
593
|
+
return Promise.reject(error);
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
function enqueue(work) {
|
|
597
|
+
try {
|
|
598
|
+
check();
|
|
599
|
+
} catch (error) {
|
|
600
|
+
return Promise.reject(error);
|
|
601
|
+
}
|
|
602
|
+
pending++;
|
|
603
|
+
const result = tail.then(() => {
|
|
604
|
+
check();
|
|
605
|
+
return work();
|
|
606
|
+
}).finally(() => {
|
|
607
|
+
pending--;
|
|
608
|
+
});
|
|
609
|
+
tail = result.then(() => {}, () => {});
|
|
610
|
+
return result;
|
|
611
|
+
}
|
|
612
|
+
const pool = Object.freeze({
|
|
613
|
+
dialect: dialectFor("sqlite"),
|
|
614
|
+
capabilities: Object.freeze({
|
|
615
|
+
driver: "sqlite",
|
|
616
|
+
transactions: true,
|
|
617
|
+
savepoints: true,
|
|
618
|
+
rowLocks: false,
|
|
619
|
+
postgresRls: false,
|
|
620
|
+
cancellableCheckout: false,
|
|
621
|
+
observableCheckout: false,
|
|
622
|
+
isolatedDiscard: false
|
|
623
|
+
}),
|
|
624
|
+
execute(statement) {
|
|
625
|
+
return enqueue(() => execute(statement));
|
|
626
|
+
},
|
|
627
|
+
checkout(options = {}) {
|
|
628
|
+
if (options.signal !== undefined || options.metrics !== undefined)
|
|
629
|
+
return Promise.resolve({
|
|
630
|
+
ok: false,
|
|
631
|
+
error: new Error("SQLite logical checkout does not support acquisition signal or metrics."),
|
|
632
|
+
disposition: "not-acquired"
|
|
633
|
+
});
|
|
634
|
+
return new Promise((publish) => {
|
|
635
|
+
const reservation = enqueue(async () => {
|
|
636
|
+
let unlock;
|
|
637
|
+
const slot = new Promise((done) => {
|
|
638
|
+
unlock = done;
|
|
639
|
+
});
|
|
640
|
+
let disposal;
|
|
641
|
+
const protocol = nativeTransaction({
|
|
642
|
+
execute,
|
|
643
|
+
beginSql: "BEGIN IMMEDIATE",
|
|
644
|
+
state: () => db.inTransaction ? "transaction-active" : "idle",
|
|
645
|
+
control: async (sql) => {
|
|
646
|
+
check();
|
|
647
|
+
db.exec(sql);
|
|
648
|
+
return {};
|
|
649
|
+
}
|
|
650
|
+
});
|
|
651
|
+
const pin = Object.freeze({
|
|
652
|
+
begin: (work) => {
|
|
653
|
+
if (disposal)
|
|
654
|
+
return Promise.reject(new Error("SQLite pin is no longer active."));
|
|
655
|
+
return protocol.begin(work);
|
|
656
|
+
},
|
|
657
|
+
async release() {
|
|
658
|
+
if (disposal)
|
|
659
|
+
return disposal;
|
|
660
|
+
if (db.inTransaction || protocol.state !== "idle") {
|
|
661
|
+
quarantined = true;
|
|
662
|
+
unlock();
|
|
663
|
+
disposal = Object.freeze({
|
|
664
|
+
ok: false,
|
|
665
|
+
error: new Error("SQLite logical slot is not safely idle."),
|
|
666
|
+
ownership: "retained"
|
|
667
|
+
});
|
|
668
|
+
await reservation;
|
|
669
|
+
return disposal;
|
|
670
|
+
}
|
|
671
|
+
disposal = Object.freeze({ ok: true });
|
|
672
|
+
unlock();
|
|
673
|
+
await reservation;
|
|
674
|
+
return disposal;
|
|
675
|
+
},
|
|
676
|
+
async discard() {
|
|
677
|
+
if (disposal)
|
|
678
|
+
return disposal;
|
|
679
|
+
quarantined = true;
|
|
680
|
+
disposal = Object.freeze({
|
|
681
|
+
ok: false,
|
|
682
|
+
error: new Error("SQLite shared handle quarantined; isolated discard is unavailable."),
|
|
683
|
+
ownership: "retained"
|
|
684
|
+
});
|
|
685
|
+
unlock();
|
|
686
|
+
await reservation;
|
|
687
|
+
return disposal;
|
|
688
|
+
}
|
|
689
|
+
});
|
|
690
|
+
publish({ ok: true, value: pin });
|
|
691
|
+
await slot;
|
|
692
|
+
});
|
|
693
|
+
reservation.catch((error) => publish({ ok: false, error, disposition: "not-acquired" }));
|
|
694
|
+
});
|
|
695
|
+
},
|
|
696
|
+
close() {
|
|
697
|
+
if (pending > 0)
|
|
698
|
+
throw new Error("Drain SQLite operations before closing the connection.");
|
|
699
|
+
db.close();
|
|
700
|
+
closed = true;
|
|
701
|
+
}
|
|
702
|
+
});
|
|
703
|
+
return { ok: true, value: pool };
|
|
704
|
+
}
|
|
705
|
+
function createRawSqlitePool(options) {
|
|
706
|
+
const outcome = openRawSqlitePool(options);
|
|
707
|
+
if (outcome.ok)
|
|
708
|
+
return outcome.value;
|
|
709
|
+
if (outcome.cleanupErrors?.length)
|
|
710
|
+
throw new AggregateError([outcome.error, ...outcome.cleanupErrors], "SQLite initialization and cleanup failed.");
|
|
711
|
+
throw outcome.error;
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
// ../../src/core/database/transactionSession.ts
|
|
715
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
716
|
+
import { mapDatabaseError, PersistenceError } from "@getstrata/core/database/errors";
|
|
717
|
+
import { runWithTransactionLineage } from "#strata-orm-internal";
|
|
718
|
+
function rejected(error) {
|
|
719
|
+
const promise = Promise.reject(error);
|
|
720
|
+
promise.catch(() => {});
|
|
721
|
+
return promise;
|
|
722
|
+
}
|
|
723
|
+
function failure2(error) {
|
|
724
|
+
return Object.freeze({ error });
|
|
725
|
+
}
|
|
726
|
+
function scopeError() {
|
|
727
|
+
return new PersistenceError("DATABASE_TRANSACTION_SCOPE");
|
|
728
|
+
}
|
|
729
|
+
function signalAccessor() {
|
|
730
|
+
const getter = Object.getOwnPropertyDescriptor(AbortSignal.prototype, "aborted")?.get;
|
|
731
|
+
if (!getter)
|
|
732
|
+
throw new TypeError("Platform AbortSignal accessors are required.");
|
|
733
|
+
return getter;
|
|
734
|
+
}
|
|
735
|
+
var signalAborted = signalAccessor();
|
|
736
|
+
var throwIfAborted = AbortSignal.prototype.throwIfAborted;
|
|
737
|
+
function checkSignal(signal) {
|
|
738
|
+
if (signal !== undefined)
|
|
739
|
+
throwIfAborted.call(signal);
|
|
740
|
+
}
|
|
741
|
+
function snapshotTransactionOptions(input) {
|
|
742
|
+
if (!input || typeof input !== "object" || Array.isArray(input))
|
|
743
|
+
throw new PersistenceError("DATABASE_CONFIG_INVALID");
|
|
744
|
+
const prototype = Object.getPrototypeOf(input);
|
|
745
|
+
if (prototype !== Object.prototype && prototype !== null)
|
|
746
|
+
throw new PersistenceError("DATABASE_CONFIG_INVALID");
|
|
747
|
+
const result = {};
|
|
748
|
+
for (const key of Reflect.ownKeys(input)) {
|
|
749
|
+
if (key !== "acquisitionSignal" && key !== "acquisitionMetrics")
|
|
750
|
+
throw new PersistenceError("DATABASE_CONFIG_INVALID");
|
|
751
|
+
const descriptor = Object.getOwnPropertyDescriptor(input, key);
|
|
752
|
+
if (!descriptor || !("value" in descriptor) || !descriptor.enumerable)
|
|
753
|
+
throw new PersistenceError("DATABASE_CONFIG_INVALID");
|
|
754
|
+
if (descriptor.value !== undefined)
|
|
755
|
+
result[key] = descriptor.value;
|
|
756
|
+
}
|
|
757
|
+
if (result.acquisitionSignal !== undefined)
|
|
758
|
+
signalAborted.call(result.acquisitionSignal);
|
|
759
|
+
return Object.freeze(result);
|
|
760
|
+
}
|
|
761
|
+
function snapshotStatement(input) {
|
|
762
|
+
if (!input || typeof input !== "object")
|
|
763
|
+
throw new PersistenceError("DATABASE_CONFIG_INVALID");
|
|
764
|
+
const text = Object.getOwnPropertyDescriptor(input, "text");
|
|
765
|
+
const params = Object.getOwnPropertyDescriptor(input, "params");
|
|
766
|
+
if (!text || !("value" in text) || typeof text.value !== "string" || !text.value.trim() || !params || !("value" in params) || !Array.isArray(params.value))
|
|
767
|
+
throw new PersistenceError("DATABASE_CONFIG_INVALID");
|
|
768
|
+
const descriptors = Object.getOwnPropertyDescriptors(params.value);
|
|
769
|
+
const length = descriptors.length?.value;
|
|
770
|
+
if (typeof length !== "number" || !Number.isSafeInteger(length) || length < 0 || length > 4294967295)
|
|
771
|
+
throw new PersistenceError("DATABASE_CONFIG_INVALID");
|
|
772
|
+
const copied = [];
|
|
773
|
+
for (let index = 0;index < length; index++) {
|
|
774
|
+
const item = descriptors[String(index)];
|
|
775
|
+
if (!item || !("value" in item))
|
|
776
|
+
throw new PersistenceError("DATABASE_CONFIG_INVALID");
|
|
777
|
+
copied.push(item.value);
|
|
778
|
+
}
|
|
779
|
+
return Object.freeze({ text: text.value, params: Object.freeze(copied) });
|
|
780
|
+
}
|
|
781
|
+
function summary(errors) {
|
|
782
|
+
if (errors.length === 1)
|
|
783
|
+
return errors[0];
|
|
784
|
+
const result = new AggregateError([...errors], "Database transaction failures.", {
|
|
785
|
+
cause: errors[0]
|
|
786
|
+
});
|
|
787
|
+
Object.freeze(result.errors);
|
|
788
|
+
return Object.freeze(result);
|
|
789
|
+
}
|
|
790
|
+
function actualResult(business) {
|
|
791
|
+
return business?.kind === "joined" && business.observation.invoked ? business.observation.body : undefined;
|
|
792
|
+
}
|
|
793
|
+
function healthy(business) {
|
|
794
|
+
return business.kind === "joined" && business.observation.body.ok && !business.observation.strictFailed && !business.observation.retained && !business.requestedRollback && business.sqlFailure === null && !business.poisoned;
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
class TransactionRuntime {
|
|
798
|
+
context;
|
|
799
|
+
operations;
|
|
800
|
+
ownership;
|
|
801
|
+
attachRegistry;
|
|
802
|
+
rootSession;
|
|
803
|
+
ownerForPool;
|
|
804
|
+
storage = new AsyncLocalStorage;
|
|
805
|
+
constructor(context, operations, ownership, attachRegistry, rootSession, ownerForPool) {
|
|
806
|
+
this.context = context;
|
|
807
|
+
this.operations = operations;
|
|
808
|
+
this.ownership = ownership;
|
|
809
|
+
this.attachRegistry = attachRegistry;
|
|
810
|
+
this.rootSession = rootSession;
|
|
811
|
+
this.ownerForPool = ownerForPool;
|
|
812
|
+
}
|
|
813
|
+
assertOutside() {
|
|
814
|
+
this.operations.assertActive();
|
|
815
|
+
if (this.storage.getStore())
|
|
816
|
+
throw scopeError();
|
|
817
|
+
}
|
|
818
|
+
assertBranch(branch) {
|
|
819
|
+
this.operations.assertActive();
|
|
820
|
+
if (this.storage.getStore() !== branch || branch.phase === "terminal" || branch.child || branch.poison)
|
|
821
|
+
throw scopeError();
|
|
822
|
+
if (!branch.boundary)
|
|
823
|
+
throw scopeError();
|
|
824
|
+
branch.boundary.assertWithin();
|
|
825
|
+
}
|
|
826
|
+
facade(branch) {
|
|
827
|
+
if (branch.facade)
|
|
828
|
+
return branch.facade;
|
|
829
|
+
let registry;
|
|
830
|
+
const assertActive = () => this.assertBranch(branch);
|
|
831
|
+
const run = (work) => {
|
|
832
|
+
try {
|
|
833
|
+
assertActive();
|
|
834
|
+
return this.operations.operation(() => {
|
|
835
|
+
assertActive();
|
|
836
|
+
return work();
|
|
837
|
+
});
|
|
838
|
+
} catch (error) {
|
|
839
|
+
return rejected(error);
|
|
840
|
+
}
|
|
841
|
+
};
|
|
842
|
+
const session = {
|
|
843
|
+
repository: (definition) => registry.repository(definition),
|
|
844
|
+
model: (definition) => registry.model(definition),
|
|
845
|
+
dialect: branch.pool.dialect,
|
|
846
|
+
capabilities: branch.pool.capabilities,
|
|
847
|
+
execute: (input) => {
|
|
848
|
+
try {
|
|
849
|
+
this.assertBranch(branch);
|
|
850
|
+
const statement = snapshotStatement(input);
|
|
851
|
+
return this.operations.operation(() => {
|
|
852
|
+
this.assertBranch(branch);
|
|
853
|
+
const failed = (error) => {
|
|
854
|
+
const mapped = mapDatabaseError(error);
|
|
855
|
+
branch.sqlFailure ??= failure2(mapped);
|
|
856
|
+
throw mapped;
|
|
857
|
+
};
|
|
858
|
+
try {
|
|
859
|
+
return Promise.resolve(branch.raw.execute(statement)).catch(failed);
|
|
860
|
+
} catch (error) {
|
|
861
|
+
return failed(error);
|
|
862
|
+
}
|
|
863
|
+
});
|
|
864
|
+
} catch (error) {
|
|
865
|
+
return rejected(error);
|
|
866
|
+
}
|
|
867
|
+
},
|
|
868
|
+
transaction: (work) => {
|
|
869
|
+
try {
|
|
870
|
+
this.assertBranch(branch);
|
|
871
|
+
if (typeof work !== "function")
|
|
872
|
+
throw new TypeError("Transaction callback must be a function.");
|
|
873
|
+
if (!branch.pool.capabilities.savepoints)
|
|
874
|
+
throw new PersistenceError("DATABASE_UNSUPPORTED_CAPABILITY");
|
|
875
|
+
branch.child = true;
|
|
876
|
+
const promise = this.operations.operation(() => this.nested(branch, work));
|
|
877
|
+
promise.then(() => {
|
|
878
|
+
branch.child = false;
|
|
879
|
+
}, () => {
|
|
880
|
+
branch.child = false;
|
|
881
|
+
});
|
|
882
|
+
return promise;
|
|
883
|
+
} catch (error) {
|
|
884
|
+
return rejected(error);
|
|
885
|
+
}
|
|
886
|
+
},
|
|
887
|
+
afterCommit: (work) => {
|
|
888
|
+
this.assertBranch(branch);
|
|
889
|
+
if (typeof work !== "function")
|
|
890
|
+
throw new TypeError("After-commit callback must be a function.");
|
|
891
|
+
branch.observers.push(work);
|
|
892
|
+
},
|
|
893
|
+
requestRollback: () => {
|
|
894
|
+
this.assertBranch(branch);
|
|
895
|
+
branch.rollback = true;
|
|
896
|
+
}
|
|
897
|
+
};
|
|
898
|
+
registry = this.attachRegistry(session, {
|
|
899
|
+
pool: branch.pool,
|
|
900
|
+
branch,
|
|
901
|
+
transactional: true,
|
|
902
|
+
assertActive,
|
|
903
|
+
run,
|
|
904
|
+
registerRestore: (restore) => {
|
|
905
|
+
assertActive();
|
|
906
|
+
branch.restores.push({ kind: "restore", restore, consumed: false, outerOnly: false });
|
|
907
|
+
},
|
|
908
|
+
root: () => this.rootSession(branch.pool)
|
|
909
|
+
});
|
|
910
|
+
branch.facade = Object.freeze(session);
|
|
911
|
+
return branch.facade;
|
|
912
|
+
}
|
|
913
|
+
async business(pool, raw, work, attempt) {
|
|
914
|
+
const branch = {
|
|
915
|
+
pool,
|
|
916
|
+
raw,
|
|
917
|
+
phase: "open",
|
|
918
|
+
child: false,
|
|
919
|
+
rollback: false,
|
|
920
|
+
sqlFailure: null,
|
|
921
|
+
poison: null,
|
|
922
|
+
childFailure: null,
|
|
923
|
+
observers: [],
|
|
924
|
+
restores: attempt.restores
|
|
925
|
+
};
|
|
926
|
+
attempt.branch = branch;
|
|
927
|
+
try {
|
|
928
|
+
const observation = await this.ownership.joined((task) => {
|
|
929
|
+
branch.boundary = task;
|
|
930
|
+
try {
|
|
931
|
+
return work(this.facade(branch));
|
|
932
|
+
} finally {
|
|
933
|
+
branch.phase = "joining";
|
|
934
|
+
}
|
|
935
|
+
}, (invoke) => this.storage.run(branch, () => runWithTransactionLineage(this.ownerForPool(branch.pool), () => branch.phase !== "terminal", invoke)));
|
|
936
|
+
return Object.freeze({
|
|
937
|
+
kind: "joined",
|
|
938
|
+
observation,
|
|
939
|
+
requestedRollback: branch.rollback,
|
|
940
|
+
sqlFailure: branch.sqlFailure,
|
|
941
|
+
poisoned: branch.poison !== null,
|
|
942
|
+
childFailure: branch.childFailure,
|
|
943
|
+
observers: Object.freeze([...branch.observers])
|
|
944
|
+
});
|
|
945
|
+
} catch (error) {
|
|
946
|
+
return Object.freeze({ kind: "not-admitted", error });
|
|
947
|
+
} finally {
|
|
948
|
+
branch.phase = "terminal";
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
newAttempt() {
|
|
952
|
+
return {
|
|
953
|
+
stage: Object.freeze({ kind: "callback-not-entered" }),
|
|
954
|
+
nativeFailure: null,
|
|
955
|
+
nativeState: "idle",
|
|
956
|
+
releaseAcknowledged: false,
|
|
957
|
+
checkoutFailed: false,
|
|
958
|
+
restores: []
|
|
959
|
+
};
|
|
960
|
+
}
|
|
961
|
+
async control(task, attempt, pool, native, work, admission) {
|
|
962
|
+
let continuation;
|
|
963
|
+
const callback = task.bindNative((raw) => {
|
|
964
|
+
if (attempt.stage.kind !== "callback-not-entered")
|
|
965
|
+
return rejected(new PersistenceError("DATABASE_TRANSACTION_FAILED"));
|
|
966
|
+
attempt.stage = Object.freeze({ kind: "callback-running" });
|
|
967
|
+
continuation = (async () => {
|
|
968
|
+
try {
|
|
969
|
+
checkSignal(admission);
|
|
970
|
+
const business = await this.business(pool, raw, work, attempt);
|
|
971
|
+
attempt.business = business;
|
|
972
|
+
const decision = Object.freeze({
|
|
973
|
+
finish: healthy(business) ? "commit" : "rollback",
|
|
974
|
+
result: business
|
|
975
|
+
});
|
|
976
|
+
attempt.stage = Object.freeze({ kind: "decided", decision });
|
|
977
|
+
return decision;
|
|
978
|
+
} catch (error) {
|
|
979
|
+
attempt.stage = Object.freeze({ kind: "callback-failed", error });
|
|
980
|
+
throw error;
|
|
981
|
+
}
|
|
982
|
+
})();
|
|
983
|
+
continuation.catch(() => {});
|
|
984
|
+
return continuation;
|
|
985
|
+
});
|
|
986
|
+
try {
|
|
987
|
+
attempt.terminal = await native(callback);
|
|
988
|
+
attempt.nativeState = attempt.terminal.nativeState;
|
|
989
|
+
if (attempt.terminal.failure || attempt.terminal.data === "unknown") {
|
|
990
|
+
if (attempt.branch)
|
|
991
|
+
attempt.branch.poison = attempt.terminal.failure ?? failure2(new PersistenceError("DATABASE_TRANSACTION_UNKNOWN"));
|
|
992
|
+
}
|
|
993
|
+
} catch (error) {
|
|
994
|
+
attempt.nativeFailure = failure2(error);
|
|
995
|
+
attempt.nativeState = "unknown";
|
|
996
|
+
if (attempt.branch)
|
|
997
|
+
attempt.branch.poison = attempt.nativeFailure;
|
|
998
|
+
} finally {
|
|
999
|
+
if (continuation)
|
|
1000
|
+
await continuation.catch(() => {});
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
evidence(attempt, joined) {
|
|
1004
|
+
const errors = [];
|
|
1005
|
+
const business = attempt.business;
|
|
1006
|
+
if (attempt.preAdmissionFailure)
|
|
1007
|
+
errors.push(attempt.preAdmissionFailure.error);
|
|
1008
|
+
if (business?.kind === "not-admitted")
|
|
1009
|
+
errors.push(business.error);
|
|
1010
|
+
else if (business?.kind === "joined" && business.observation.invoked && !business.observation.body.ok)
|
|
1011
|
+
errors.push(business.observation.body.error);
|
|
1012
|
+
if (business?.kind === "joined" && business.childFailure)
|
|
1013
|
+
errors.push(business.childFailure.error);
|
|
1014
|
+
if (attempt.stage.kind === "callback-failed")
|
|
1015
|
+
errors.push(attempt.stage.error);
|
|
1016
|
+
const phases = attempt.terminal?.phases ?? [];
|
|
1017
|
+
const failedPhases = phases.filter((phase) => phase.failure !== null);
|
|
1018
|
+
for (const phase of failedPhases)
|
|
1019
|
+
if (phase.failure)
|
|
1020
|
+
errors.push(phase.failure.error);
|
|
1021
|
+
if (attempt.terminal?.failure && failedPhases.length === 0 && attempt.stage.kind !== "callback-failed")
|
|
1022
|
+
errors.push(attempt.terminal.failure.error);
|
|
1023
|
+
if (attempt.nativeFailure)
|
|
1024
|
+
errors.push(attempt.nativeFailure.error);
|
|
1025
|
+
for (const occurrence of joined.strict)
|
|
1026
|
+
errors.push(occurrence.error);
|
|
1027
|
+
return errors;
|
|
1028
|
+
}
|
|
1029
|
+
result(attempt, joined, nested) {
|
|
1030
|
+
const terminal = attempt.terminal;
|
|
1031
|
+
const business = attempt.business;
|
|
1032
|
+
const result = actualResult(business);
|
|
1033
|
+
const data = terminal?.data === "released" ? "unknown" : terminal?.data ?? (attempt.checkoutFailed || attempt.stage.kind === "callback-not-entered" && !attempt.nativeFailure ? "not-started" : "unknown");
|
|
1034
|
+
const errors = this.evidence(attempt, joined);
|
|
1035
|
+
if (!joined.body.ok && joined.invoked)
|
|
1036
|
+
errors.push(joined.body.error);
|
|
1037
|
+
const intendedRollback = business?.kind === "joined" && business.requestedRollback;
|
|
1038
|
+
const sqlFailure = business?.kind === "joined" ? business.sqlFailure : null;
|
|
1039
|
+
const acknowledged = nested ? terminal?.data === "released" : terminal?.data === "committed";
|
|
1040
|
+
const rolledBack = terminal?.data === "rolled-back";
|
|
1041
|
+
if (!errors.length && !joined.strictFailed && !joined.retained && result?.ok && (acknowledged && business !== undefined && healthy(business) || rolledBack && intendedRollback && !sqlFailure))
|
|
1042
|
+
return result.value;
|
|
1043
|
+
if (rolledBack && result && !result.ok && errors.length === 1 && !joined.strictFailed && !joined.retained)
|
|
1044
|
+
throw result.error;
|
|
1045
|
+
if (rolledBack && attempt.stage.kind === "callback-failed" && errors.length === 1 && !joined.strictFailed && !joined.retained)
|
|
1046
|
+
throw attempt.stage.error;
|
|
1047
|
+
const options = {
|
|
1048
|
+
data,
|
|
1049
|
+
...result ? { result } : {},
|
|
1050
|
+
...errors.length ? { cause: summary(errors) } : {}
|
|
1051
|
+
};
|
|
1052
|
+
if (data === "unknown")
|
|
1053
|
+
throw new PersistenceError("DATABASE_TRANSACTION_UNKNOWN", options);
|
|
1054
|
+
if (rolledBack && result?.ok && sqlFailure && errors.length === 0)
|
|
1055
|
+
throw new PersistenceError("DATABASE_TRANSACTION_ROLLBACK_ONLY", {
|
|
1056
|
+
...options,
|
|
1057
|
+
cause: sqlFailure.error
|
|
1058
|
+
});
|
|
1059
|
+
throw new PersistenceError("DATABASE_TRANSACTION_FAILED", options);
|
|
1060
|
+
}
|
|
1061
|
+
markUnknown(entries) {
|
|
1062
|
+
for (const entry of entries) {
|
|
1063
|
+
if (entry.kind === "child")
|
|
1064
|
+
this.markUnknown(entry.entries);
|
|
1065
|
+
else
|
|
1066
|
+
entry.outerOnly = true;
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
async restoreHistory(task, entries, outer) {
|
|
1070
|
+
for (let index = entries.length - 1;index >= 0; index--) {
|
|
1071
|
+
const entry = entries[index];
|
|
1072
|
+
if (!entry)
|
|
1073
|
+
continue;
|
|
1074
|
+
if (entry.kind === "child")
|
|
1075
|
+
await this.restoreHistory(task, entry.entries, outer);
|
|
1076
|
+
else if (!entry.consumed && (outer || !entry.outerOnly)) {
|
|
1077
|
+
entry.consumed = true;
|
|
1078
|
+
await task.finalize(() => {
|
|
1079
|
+
entry.restore();
|
|
1080
|
+
return;
|
|
1081
|
+
});
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
async nested(parent, work) {
|
|
1086
|
+
const attempt = this.newAttempt();
|
|
1087
|
+
parent.restores.push({ kind: "child", entries: attempt.restores });
|
|
1088
|
+
const joined = await this.ownership.joined(async (task) => {
|
|
1089
|
+
await this.control(task, attempt, parent.pool, (callback) => parent.raw.savepoint(callback), work);
|
|
1090
|
+
if (attempt.terminal?.data === "rolled-back")
|
|
1091
|
+
await this.restoreHistory(task, attempt.restores, false);
|
|
1092
|
+
else if (attempt.terminal?.data !== "released")
|
|
1093
|
+
this.markUnknown(attempt.restores);
|
|
1094
|
+
});
|
|
1095
|
+
const unsafe = !attempt.terminal || attempt.terminal.data !== "released" && attempt.terminal.data !== "rolled-back" || attempt.nativeFailure !== null;
|
|
1096
|
+
if (unsafe)
|
|
1097
|
+
parent.poison = failure2(new PersistenceError("DATABASE_TRANSACTION_UNKNOWN"));
|
|
1098
|
+
if (attempt.terminal?.data === "released" && attempt.business?.kind === "joined" && healthy(attempt.business) && !joined.strictFailed && !joined.retained)
|
|
1099
|
+
for (const observer of attempt.business.observers)
|
|
1100
|
+
parent.observers.push(observer);
|
|
1101
|
+
try {
|
|
1102
|
+
return this.result(attempt, joined, true);
|
|
1103
|
+
} catch (error) {
|
|
1104
|
+
if (unsafe && !joined.strictFailed)
|
|
1105
|
+
parent.childFailure ??= failure2(error);
|
|
1106
|
+
throw error;
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
run(pool, work, options = {}) {
|
|
1110
|
+
try {
|
|
1111
|
+
this.assertOutside();
|
|
1112
|
+
if (typeof work !== "function")
|
|
1113
|
+
throw new TypeError("Transaction callback must be a function.");
|
|
1114
|
+
const settings = snapshotTransactionOptions(options);
|
|
1115
|
+
if (settings.acquisitionSignal !== undefined && !pool.capabilities.cancellableCheckout || settings.acquisitionMetrics !== undefined && !pool.capabilities.observableCheckout)
|
|
1116
|
+
throw new PersistenceError("DATABASE_UNSUPPORTED_CAPABILITY");
|
|
1117
|
+
checkSignal(settings.acquisitionSignal);
|
|
1118
|
+
const admission = settings.acquisitionSignal;
|
|
1119
|
+
const checkout = Object.freeze({
|
|
1120
|
+
...pool.capabilities.cancellableCheckout ? { signal: admission ?? this.context.signal } : {},
|
|
1121
|
+
...settings.acquisitionMetrics !== undefined ? { metrics: settings.acquisitionMetrics } : {}
|
|
1122
|
+
});
|
|
1123
|
+
return this.operations.operation(async () => {
|
|
1124
|
+
const attempt = this.newAttempt();
|
|
1125
|
+
const joined = await this.ownership.joined(async (task) => {
|
|
1126
|
+
let pin;
|
|
1127
|
+
let opened = false;
|
|
1128
|
+
try {
|
|
1129
|
+
pin = await task.acquire({
|
|
1130
|
+
name: "database.transaction.pin",
|
|
1131
|
+
open: () => {
|
|
1132
|
+
opened = true;
|
|
1133
|
+
return pool.checkout(checkout);
|
|
1134
|
+
},
|
|
1135
|
+
close: async (owned) => {
|
|
1136
|
+
const ack = await (attempt.nativeState === "idle" ? owned.release() : owned.discard());
|
|
1137
|
+
if (!ack.ok)
|
|
1138
|
+
throw ack.error;
|
|
1139
|
+
attempt.releaseAcknowledged = true;
|
|
1140
|
+
}
|
|
1141
|
+
});
|
|
1142
|
+
} catch (error) {
|
|
1143
|
+
attempt.checkoutFailed = true;
|
|
1144
|
+
if (!opened)
|
|
1145
|
+
attempt.preAdmissionFailure = failure2(error);
|
|
1146
|
+
return;
|
|
1147
|
+
}
|
|
1148
|
+
await this.control(task, attempt, pool, (callback) => pin.begin(callback), work, admission);
|
|
1149
|
+
if (attempt.terminal?.data === "rolled-back")
|
|
1150
|
+
await this.restoreHistory(task, attempt.restores, true);
|
|
1151
|
+
});
|
|
1152
|
+
const value = this.result(attempt, joined, false);
|
|
1153
|
+
if (attempt.terminal?.data === "committed" && attempt.releaseAcknowledged && attempt.business?.kind === "joined") {
|
|
1154
|
+
for (const observer of attempt.business.observers) {
|
|
1155
|
+
let observed;
|
|
1156
|
+
try {
|
|
1157
|
+
observed = await this.ownership.joined(() => observer(), (invoke) => this.storage.run(undefined, invoke));
|
|
1158
|
+
} catch (error) {
|
|
1159
|
+
throw new PersistenceError("DATABASE_POST_COMMIT_FAILED", {
|
|
1160
|
+
data: "committed",
|
|
1161
|
+
cause: error,
|
|
1162
|
+
result: actualResult(attempt.business)
|
|
1163
|
+
});
|
|
1164
|
+
}
|
|
1165
|
+
if (!observed.body.ok || observed.strictFailed || observed.retained) {
|
|
1166
|
+
const errors = [];
|
|
1167
|
+
if (observed.invoked && !observed.body.ok)
|
|
1168
|
+
errors.push(observed.body.error);
|
|
1169
|
+
for (const item of observed.strict)
|
|
1170
|
+
errors.push(item.error);
|
|
1171
|
+
throw new PersistenceError("DATABASE_POST_COMMIT_FAILED", {
|
|
1172
|
+
data: "committed",
|
|
1173
|
+
result: actualResult(attempt.business),
|
|
1174
|
+
...errors.length ? { cause: summary(errors) } : {}
|
|
1175
|
+
});
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
return value;
|
|
1180
|
+
});
|
|
1181
|
+
} catch (error) {
|
|
1182
|
+
return rejected(error);
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
// ../../src/core/database/ownedReadOnlyObservation.ts
|
|
1188
|
+
function createOwnedReadOnlyObservation(application, connection, options, observationOptions = {}) {
|
|
1189
|
+
if (!connection.trim())
|
|
1190
|
+
throw new TypeError("Read-only observation needs a connection name.");
|
|
1191
|
+
const configured = copyApplicationConfig(options);
|
|
1192
|
+
const dialect = dialectFor(configured.driver);
|
|
1193
|
+
const postgresPolicy = observationOptions.postgresPolicy;
|
|
1194
|
+
if (postgresPolicy !== undefined && postgresPolicy !== "bypass")
|
|
1195
|
+
throw new TypeError("Unsupported PostgreSQL observation policy.");
|
|
1196
|
+
return (timeoutMs, work) => {
|
|
1197
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 5000)
|
|
1198
|
+
throw new TypeError("SQL observation timeout must be between 1 and 5000 milliseconds.");
|
|
1199
|
+
if (typeof work !== "function")
|
|
1200
|
+
throw new TypeError("SQL observation requires a callback.");
|
|
1201
|
+
const deadline = performance.now() + timeoutMs;
|
|
1202
|
+
const timeout = new AbortController;
|
|
1203
|
+
const timeoutError = new Error("SQL observation timed out.");
|
|
1204
|
+
const timer = setTimeout(() => timeout.abort(timeoutError), timeoutMs);
|
|
1205
|
+
const remaining = () => {
|
|
1206
|
+
timeout.signal.throwIfAborted();
|
|
1207
|
+
const value = Math.floor(deadline - performance.now());
|
|
1208
|
+
if (value < 1)
|
|
1209
|
+
throw timeoutError;
|
|
1210
|
+
return value;
|
|
1211
|
+
};
|
|
1212
|
+
const actual = application.run({
|
|
1213
|
+
kind: "command",
|
|
1214
|
+
actor: { kind: "system", policy: "metrics.read-only" },
|
|
1215
|
+
signal: timeout.signal
|
|
1216
|
+
}, async (scope) => {
|
|
1217
|
+
const owner = scope.resolve(DATABASE_OWNERSHIP_TOKEN);
|
|
1218
|
+
const configuredPool = owner.connections[connection];
|
|
1219
|
+
if (!configuredPool)
|
|
1220
|
+
throw new TypeError("Unknown read-only observation connection.");
|
|
1221
|
+
assertNoOwnedTransaction({ app: owner.app, configuredPool }, "SQL observations require an independent transaction.");
|
|
1222
|
+
const database = scope.resolve(DATABASE_SESSION_TOKEN).connection(connection);
|
|
1223
|
+
if (database.dialect.driver !== configured.driver)
|
|
1224
|
+
throw new TypeError("Read-only observation driver differs from the selected connection.");
|
|
1225
|
+
const ownership = scope.resolve(CORE_EXECUTION_OWNERSHIP_TOKEN);
|
|
1226
|
+
const operations = scope.resolve(CORE_EXECUTION_OPERATIONS_TOKEN);
|
|
1227
|
+
if (configured.driver === "pgsql") {
|
|
1228
|
+
return database.transaction(async (child) => {
|
|
1229
|
+
await child.execute({
|
|
1230
|
+
text: "SELECT set_config('statement_timeout', $1, true)",
|
|
1231
|
+
params: [`${remaining()}ms`]
|
|
1232
|
+
});
|
|
1233
|
+
await child.execute({ text: "SET TRANSACTION READ ONLY", params: [] });
|
|
1234
|
+
const observe = (selected) => work(Object.freeze({ dialect: selected.dialect, execute: selected.execute }), remaining);
|
|
1235
|
+
const result = postgresPolicy === "bypass" ? await createScopedPolicy(ownership, scope.context, database).run(child, { kind: "bypass" }, observe) : await observe(child);
|
|
1236
|
+
remaining();
|
|
1237
|
+
return result;
|
|
1238
|
+
}, { acquisitionSignal: scope.context.signal });
|
|
1239
|
+
}
|
|
1240
|
+
const profile = configured.driver === "sqlite" ? { driver: "sqlite", filename: sqliteFilename(configured.filename) } : {
|
|
1241
|
+
driver: "mysql",
|
|
1242
|
+
url: configured.url,
|
|
1243
|
+
module: import.meta.resolve("mysql2/promise")
|
|
1244
|
+
};
|
|
1245
|
+
if (profile.driver === "sqlite" && profile.filename === ":memory:")
|
|
1246
|
+
throw new TypeError("SQL observations require file-backed SQLite.");
|
|
1247
|
+
return observeIsolatedReadOnly(profile, async (native) => {
|
|
1248
|
+
const joined = await ownership.joined(async () => {
|
|
1249
|
+
const executor = Object.freeze({
|
|
1250
|
+
dialect,
|
|
1251
|
+
execute: (input) => {
|
|
1252
|
+
try {
|
|
1253
|
+
operations.assertActive();
|
|
1254
|
+
const statement = snapshotStatement(input);
|
|
1255
|
+
return operations.operation(async () => {
|
|
1256
|
+
remaining();
|
|
1257
|
+
return native.unsafe(statement.text, statement.params);
|
|
1258
|
+
});
|
|
1259
|
+
} catch (error) {
|
|
1260
|
+
const rejected = Promise.reject(error);
|
|
1261
|
+
rejected.catch(() => {});
|
|
1262
|
+
return rejected;
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
});
|
|
1266
|
+
remaining();
|
|
1267
|
+
const result = await work(executor, remaining);
|
|
1268
|
+
remaining();
|
|
1269
|
+
return result;
|
|
1270
|
+
});
|
|
1271
|
+
if (!joined.body.ok)
|
|
1272
|
+
throw joined.body.error;
|
|
1273
|
+
return joined.body.value;
|
|
1274
|
+
}, { signal: scope.context.signal, timeoutMs: remaining() });
|
|
1275
|
+
});
|
|
1276
|
+
actual.finally(() => clearTimeout(timer)).catch(() => {});
|
|
1277
|
+
return actual;
|
|
1278
|
+
};
|
|
1279
|
+
}
|
|
1280
|
+
export {
|
|
1281
|
+
createOwnedReadOnlyObservation
|
|
1282
|
+
};
|