@contember/database 2.1.0-rc.3 → 2.2.0-alpha.10
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/CLAUDE.md +22 -0
- package/dist/development/index.cjs +9 -0
- package/dist/development/index.cjs.map +1 -1
- package/dist/development/index.js +10 -1
- package/dist/development/index.js.map +1 -1
- package/dist/development/src/builders/CaseStatement.cjs.map +1 -1
- package/dist/development/src/builders/CaseStatement.js.map +1 -1
- package/dist/development/src/builders/ColumnExpressionFactory.cjs.map +1 -1
- package/dist/development/src/builders/ColumnExpressionFactory.js.map +1 -1
- package/dist/development/src/builders/Compiler.cjs.map +1 -1
- package/dist/development/src/builders/Compiler.js.map +1 -1
- package/dist/development/src/builders/ConditionBuilder.cjs +6 -0
- package/dist/development/src/builders/ConditionBuilder.cjs.map +1 -1
- package/dist/development/src/builders/ConditionBuilder.js +6 -0
- package/dist/development/src/builders/ConditionBuilder.js.map +1 -1
- package/dist/development/src/builders/DeleteBuilder.cjs.map +1 -1
- package/dist/development/src/builders/DeleteBuilder.js.map +1 -1
- package/dist/development/src/builders/InsertBuilder.cjs.map +1 -1
- package/dist/development/src/builders/InsertBuilder.js.map +1 -1
- package/dist/development/src/builders/LimitByGroupWrapper.cjs +1 -1
- package/dist/development/src/builders/LimitByGroupWrapper.cjs.map +1 -1
- package/dist/development/src/builders/LimitByGroupWrapper.js +1 -1
- package/dist/development/src/builders/LimitByGroupWrapper.js.map +1 -1
- package/dist/development/src/builders/SelectBuilder.cjs.map +1 -1
- package/dist/development/src/builders/SelectBuilder.js.map +1 -1
- package/dist/development/src/builders/UpdateBuilder.cjs.map +1 -1
- package/dist/development/src/builders/UpdateBuilder.js.map +1 -1
- package/dist/development/src/builders/WindowFunction.cjs +1 -1
- package/dist/development/src/builders/WindowFunction.cjs.map +1 -1
- package/dist/development/src/builders/WindowFunction.js +1 -1
- package/dist/development/src/builders/WindowFunction.js.map +1 -1
- package/dist/development/src/builders/internal/Returning.cjs.map +1 -1
- package/dist/development/src/builders/internal/Returning.js.map +1 -1
- package/dist/development/src/builders/internal/Subqueries.cjs.map +1 -1
- package/dist/development/src/builders/internal/Subqueries.js.map +1 -1
- package/dist/development/src/builders/internal/Where.cjs.map +1 -1
- package/dist/development/src/builders/internal/Where.js.map +1 -1
- package/dist/development/src/builders/internal/With.cjs.map +1 -1
- package/dist/development/src/builders/internal/With.js.map +1 -1
- package/dist/development/src/builders/utils.cjs.map +1 -1
- package/dist/development/src/builders/utils.js.map +1 -1
- package/dist/development/src/client/AcquiredConnection.cjs +105 -32
- package/dist/development/src/client/AcquiredConnection.cjs.map +1 -1
- package/dist/development/src/client/AcquiredConnection.js +107 -34
- package/dist/development/src/client/AcquiredConnection.js.map +1 -1
- package/dist/development/src/client/Client.cjs +9 -1
- package/dist/development/src/client/Client.cjs.map +1 -1
- package/dist/development/src/client/Client.js +9 -1
- package/dist/development/src/client/Client.js.map +1 -1
- package/dist/development/src/client/Connection.cjs +19 -1
- package/dist/development/src/client/Connection.cjs.map +1 -1
- package/dist/development/src/client/Connection.js +19 -1
- package/dist/development/src/client/Connection.js.map +1 -1
- package/dist/development/src/client/EventManager.cjs +6 -2
- package/dist/development/src/client/EventManager.cjs.map +1 -1
- package/dist/development/src/client/EventManager.js +6 -2
- package/dist/development/src/client/EventManager.js.map +1 -1
- package/dist/development/src/client/Pool.cjs.map +1 -1
- package/dist/development/src/client/Pool.js.map +1 -1
- package/dist/development/src/client/RequestMemoryBudget.cjs +237 -0
- package/dist/development/src/client/RequestMemoryBudget.cjs.map +1 -0
- package/dist/development/src/client/RequestMemoryBudget.js +237 -0
- package/dist/development/src/client/RequestMemoryBudget.js.map +1 -0
- package/dist/development/src/client/ScopeLimitedConnection.cjs +37 -0
- package/dist/development/src/client/ScopeLimitedConnection.cjs.map +1 -0
- package/dist/development/src/client/ScopeLimitedConnection.js +37 -0
- package/dist/development/src/client/ScopeLimitedConnection.js.map +1 -0
- package/dist/development/src/client/Transaction.cjs +20 -8
- package/dist/development/src/client/Transaction.cjs.map +1 -1
- package/dist/development/src/client/Transaction.js +21 -9
- package/dist/development/src/client/Transaction.js.map +1 -1
- package/dist/development/src/client/cancelRunningStatement.cjs +32 -0
- package/dist/development/src/client/cancelRunningStatement.cjs.map +1 -0
- package/dist/development/src/client/cancelRunningStatement.js +32 -0
- package/dist/development/src/client/cancelRunningStatement.js.map +1 -0
- package/dist/development/src/client/errors.cjs +6 -0
- package/dist/development/src/client/errors.cjs.map +1 -1
- package/dist/development/src/client/errors.js +6 -0
- package/dist/development/src/client/errors.js.map +1 -1
- package/dist/development/src/metadata/DatabaseMetadata.cjs.map +1 -1
- package/dist/development/src/metadata/DatabaseMetadata.js.map +1 -1
- package/dist/development/src/metadata/DatabaseMetadataResolver.cjs.map +1 -1
- package/dist/development/src/metadata/DatabaseMetadataResolver.js.map +1 -1
- package/dist/development/src/metadata/IndexMetadata.cjs.map +1 -1
- package/dist/development/src/metadata/IndexMetadata.js.map +1 -1
- package/dist/development/src/metadata/UniqueConstraintMetadata.cjs.map +1 -1
- package/dist/development/src/metadata/UniqueConstraintMetadata.js.map +1 -1
- package/dist/development/src/queryable/DatabaseQuery.cjs.map +1 -1
- package/dist/development/src/queryable/DatabaseQuery.js.map +1 -1
- package/dist/development/src/queryable/DatabaseQueryable.cjs.map +1 -1
- package/dist/development/src/queryable/DatabaseQueryable.js.map +1 -1
- package/dist/development/src/utils/ConstraintHelper.cjs.map +1 -1
- package/dist/development/src/utils/ConstraintHelper.js.map +1 -1
- package/dist/development/src/utils/Semaphore.cjs +43 -0
- package/dist/development/src/utils/Semaphore.cjs.map +1 -0
- package/dist/development/src/utils/Semaphore.js +43 -0
- package/dist/development/src/utils/Semaphore.js.map +1 -0
- package/dist/development/src/utils/createDatabaseIfNotExists.cjs.map +1 -1
- package/dist/development/src/utils/createDatabaseIfNotExists.js.map +1 -1
- package/dist/development/src/utils/listen.cjs.map +1 -1
- package/dist/development/src/utils/listen.js.map +1 -1
- package/dist/development/src/utils/pgClientFactory.cjs +9 -4
- package/dist/development/src/utils/pgClientFactory.cjs.map +1 -1
- package/dist/development/src/utils/pgClientFactory.js +9 -4
- package/dist/development/src/utils/pgClientFactory.js.map +1 -1
- package/dist/development/src/utils/retryTransaction.cjs.map +1 -1
- package/dist/development/src/utils/retryTransaction.js.map +1 -1
- package/dist/development/src/utils/sql.cjs.map +1 -1
- package/dist/development/src/utils/sql.js.map +1 -1
- package/dist/development/src/utils/withDatabaseAdvisoryLock.cjs.map +1 -1
- package/dist/development/src/utils/withDatabaseAdvisoryLock.js.map +1 -1
- package/dist/production/index.cjs +9 -0
- package/dist/production/index.cjs.map +1 -1
- package/dist/production/index.js +10 -1
- package/dist/production/index.js.map +1 -1
- package/dist/production/src/builders/CaseStatement.cjs.map +1 -1
- package/dist/production/src/builders/CaseStatement.js.map +1 -1
- package/dist/production/src/builders/ColumnExpressionFactory.cjs.map +1 -1
- package/dist/production/src/builders/ColumnExpressionFactory.js.map +1 -1
- package/dist/production/src/builders/Compiler.cjs.map +1 -1
- package/dist/production/src/builders/Compiler.js.map +1 -1
- package/dist/production/src/builders/ConditionBuilder.cjs +6 -0
- package/dist/production/src/builders/ConditionBuilder.cjs.map +1 -1
- package/dist/production/src/builders/ConditionBuilder.js +6 -0
- package/dist/production/src/builders/ConditionBuilder.js.map +1 -1
- package/dist/production/src/builders/DeleteBuilder.cjs.map +1 -1
- package/dist/production/src/builders/DeleteBuilder.js.map +1 -1
- package/dist/production/src/builders/InsertBuilder.cjs.map +1 -1
- package/dist/production/src/builders/InsertBuilder.js.map +1 -1
- package/dist/production/src/builders/LimitByGroupWrapper.cjs +1 -1
- package/dist/production/src/builders/LimitByGroupWrapper.cjs.map +1 -1
- package/dist/production/src/builders/LimitByGroupWrapper.js +1 -1
- package/dist/production/src/builders/LimitByGroupWrapper.js.map +1 -1
- package/dist/production/src/builders/SelectBuilder.cjs.map +1 -1
- package/dist/production/src/builders/SelectBuilder.js.map +1 -1
- package/dist/production/src/builders/UpdateBuilder.cjs.map +1 -1
- package/dist/production/src/builders/UpdateBuilder.js.map +1 -1
- package/dist/production/src/builders/WindowFunction.cjs +1 -1
- package/dist/production/src/builders/WindowFunction.cjs.map +1 -1
- package/dist/production/src/builders/WindowFunction.js +1 -1
- package/dist/production/src/builders/WindowFunction.js.map +1 -1
- package/dist/production/src/builders/internal/Returning.cjs.map +1 -1
- package/dist/production/src/builders/internal/Returning.js.map +1 -1
- package/dist/production/src/builders/internal/Subqueries.cjs.map +1 -1
- package/dist/production/src/builders/internal/Subqueries.js.map +1 -1
- package/dist/production/src/builders/internal/Where.cjs.map +1 -1
- package/dist/production/src/builders/internal/Where.js.map +1 -1
- package/dist/production/src/builders/internal/With.cjs.map +1 -1
- package/dist/production/src/builders/internal/With.js.map +1 -1
- package/dist/production/src/builders/utils.cjs.map +1 -1
- package/dist/production/src/builders/utils.js.map +1 -1
- package/dist/production/src/client/AcquiredConnection.cjs +105 -32
- package/dist/production/src/client/AcquiredConnection.cjs.map +1 -1
- package/dist/production/src/client/AcquiredConnection.js +107 -34
- package/dist/production/src/client/AcquiredConnection.js.map +1 -1
- package/dist/production/src/client/Client.cjs +9 -1
- package/dist/production/src/client/Client.cjs.map +1 -1
- package/dist/production/src/client/Client.js +9 -1
- package/dist/production/src/client/Client.js.map +1 -1
- package/dist/production/src/client/Connection.cjs +19 -1
- package/dist/production/src/client/Connection.cjs.map +1 -1
- package/dist/production/src/client/Connection.js +19 -1
- package/dist/production/src/client/Connection.js.map +1 -1
- package/dist/production/src/client/EventManager.cjs +6 -2
- package/dist/production/src/client/EventManager.cjs.map +1 -1
- package/dist/production/src/client/EventManager.js +6 -2
- package/dist/production/src/client/EventManager.js.map +1 -1
- package/dist/production/src/client/Pool.cjs.map +1 -1
- package/dist/production/src/client/Pool.js.map +1 -1
- package/dist/production/src/client/RequestMemoryBudget.cjs +237 -0
- package/dist/production/src/client/RequestMemoryBudget.cjs.map +1 -0
- package/dist/production/src/client/RequestMemoryBudget.js +237 -0
- package/dist/production/src/client/RequestMemoryBudget.js.map +1 -0
- package/dist/production/src/client/ScopeLimitedConnection.cjs +37 -0
- package/dist/production/src/client/ScopeLimitedConnection.cjs.map +1 -0
- package/dist/production/src/client/ScopeLimitedConnection.js +37 -0
- package/dist/production/src/client/ScopeLimitedConnection.js.map +1 -0
- package/dist/production/src/client/Transaction.cjs +20 -8
- package/dist/production/src/client/Transaction.cjs.map +1 -1
- package/dist/production/src/client/Transaction.js +21 -9
- package/dist/production/src/client/Transaction.js.map +1 -1
- package/dist/production/src/client/cancelRunningStatement.cjs +32 -0
- package/dist/production/src/client/cancelRunningStatement.cjs.map +1 -0
- package/dist/production/src/client/cancelRunningStatement.js +32 -0
- package/dist/production/src/client/cancelRunningStatement.js.map +1 -0
- package/dist/production/src/client/errors.cjs +6 -0
- package/dist/production/src/client/errors.cjs.map +1 -1
- package/dist/production/src/client/errors.js +6 -0
- package/dist/production/src/client/errors.js.map +1 -1
- package/dist/production/src/metadata/DatabaseMetadata.cjs.map +1 -1
- package/dist/production/src/metadata/DatabaseMetadata.js.map +1 -1
- package/dist/production/src/metadata/DatabaseMetadataResolver.cjs.map +1 -1
- package/dist/production/src/metadata/DatabaseMetadataResolver.js.map +1 -1
- package/dist/production/src/metadata/IndexMetadata.cjs.map +1 -1
- package/dist/production/src/metadata/IndexMetadata.js.map +1 -1
- package/dist/production/src/metadata/UniqueConstraintMetadata.cjs.map +1 -1
- package/dist/production/src/metadata/UniqueConstraintMetadata.js.map +1 -1
- package/dist/production/src/queryable/DatabaseQuery.cjs.map +1 -1
- package/dist/production/src/queryable/DatabaseQuery.js.map +1 -1
- package/dist/production/src/queryable/DatabaseQueryable.cjs.map +1 -1
- package/dist/production/src/queryable/DatabaseQueryable.js.map +1 -1
- package/dist/production/src/utils/ConstraintHelper.cjs.map +1 -1
- package/dist/production/src/utils/ConstraintHelper.js.map +1 -1
- package/dist/production/src/utils/Semaphore.cjs +43 -0
- package/dist/production/src/utils/Semaphore.cjs.map +1 -0
- package/dist/production/src/utils/Semaphore.js +43 -0
- package/dist/production/src/utils/Semaphore.js.map +1 -0
- package/dist/production/src/utils/createDatabaseIfNotExists.cjs.map +1 -1
- package/dist/production/src/utils/createDatabaseIfNotExists.js.map +1 -1
- package/dist/production/src/utils/listen.cjs.map +1 -1
- package/dist/production/src/utils/listen.js.map +1 -1
- package/dist/production/src/utils/pgClientFactory.cjs +9 -4
- package/dist/production/src/utils/pgClientFactory.cjs.map +1 -1
- package/dist/production/src/utils/pgClientFactory.js +9 -4
- package/dist/production/src/utils/pgClientFactory.js.map +1 -1
- package/dist/production/src/utils/retryTransaction.cjs.map +1 -1
- package/dist/production/src/utils/retryTransaction.js.map +1 -1
- package/dist/production/src/utils/sql.cjs.map +1 -1
- package/dist/production/src/utils/sql.js.map +1 -1
- package/dist/production/src/utils/withDatabaseAdvisoryLock.cjs.map +1 -1
- package/dist/production/src/utils/withDatabaseAdvisoryLock.js.map +1 -1
- package/dist/tests/cases/integration/requestMemoryBudget.test.d.ts +2 -0
- package/dist/tests/cases/integration/requestMemoryBudget.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/acquiredConnection.test.d.ts +2 -0
- package/dist/tests/cases/unit/acquiredConnection.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/createConnectionMockAlt.d.ts +6 -3
- package/dist/tests/cases/unit/createConnectionMockAlt.d.ts.map +1 -1
- package/dist/tests/cases/unit/requestMemoryBudget.test.d.ts +2 -0
- package/dist/tests/cases/unit/requestMemoryBudget.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/scopeLimitedConnection.test.d.ts +2 -0
- package/dist/tests/cases/unit/scopeLimitedConnection.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/semaphore.test.d.ts +2 -0
- package/dist/tests/cases/unit/semaphore.test.d.ts.map +1 -0
- package/dist/tests/src/tags.d.ts.map +1 -1
- package/dist/tests/tsconfig.tsbuildinfo +1 -1
- package/dist/types/Literal.d.ts.map +1 -1
- package/dist/types/builders/CaseStatement.d.ts +2 -2
- package/dist/types/builders/CaseStatement.d.ts.map +1 -1
- package/dist/types/builders/ColumnExpressionFactory.d.ts +6 -6
- package/dist/types/builders/ColumnExpressionFactory.d.ts.map +1 -1
- package/dist/types/builders/Compiler.d.ts +5 -5
- package/dist/types/builders/Compiler.d.ts.map +1 -1
- package/dist/types/builders/ConditionBuilder.d.ts +8 -6
- package/dist/types/builders/ConditionBuilder.d.ts.map +1 -1
- package/dist/types/builders/DeleteBuilder.d.ts +8 -8
- package/dist/types/builders/DeleteBuilder.d.ts.map +1 -1
- package/dist/types/builders/InsertBuilder.d.ts +10 -10
- package/dist/types/builders/InsertBuilder.d.ts.map +1 -1
- package/dist/types/builders/LimitByGroupWrapper.d.ts +3 -3
- package/dist/types/builders/LimitByGroupWrapper.d.ts.map +1 -1
- package/dist/types/builders/QueryBuilder.d.ts +5 -5
- package/dist/types/builders/QueryBuilder.d.ts.map +1 -1
- package/dist/types/builders/SelectBuilder.d.ts +9 -9
- package/dist/types/builders/SelectBuilder.d.ts.map +1 -1
- package/dist/types/builders/UpdateBuilder.d.ts +9 -9
- package/dist/types/builders/UpdateBuilder.d.ts.map +1 -1
- package/dist/types/builders/WindowFunction.d.ts +4 -3
- package/dist/types/builders/WindowFunction.d.ts.map +1 -1
- package/dist/types/builders/index.d.ts +12 -12
- package/dist/types/builders/index.d.ts.map +1 -1
- package/dist/types/builders/internal/Returning.d.ts +3 -3
- package/dist/types/builders/internal/Returning.d.ts.map +1 -1
- package/dist/types/builders/internal/Subqueries.d.ts +4 -4
- package/dist/types/builders/internal/Subqueries.d.ts.map +1 -1
- package/dist/types/builders/internal/Where.d.ts +3 -3
- package/dist/types/builders/internal/Where.d.ts.map +1 -1
- package/dist/types/builders/internal/With.d.ts +3 -3
- package/dist/types/builders/internal/With.d.ts.map +1 -1
- package/dist/types/builders/utils.d.ts +2 -2
- package/dist/types/builders/utils.d.ts.map +1 -1
- package/dist/types/client/AcquiredConnection.d.ts +9 -4
- package/dist/types/client/AcquiredConnection.d.ts.map +1 -1
- package/dist/types/client/Client.d.ts +12 -4
- package/dist/types/client/Client.d.ts.map +1 -1
- package/dist/types/client/Connection.d.ts +12 -4
- package/dist/types/client/Connection.d.ts.map +1 -1
- package/dist/types/client/EventManager.d.ts +6 -2
- package/dist/types/client/EventManager.d.ts.map +1 -1
- package/dist/types/client/PgClient.d.ts +12 -1
- package/dist/types/client/PgClient.d.ts.map +1 -1
- package/dist/types/client/Pool.d.ts +3 -3
- package/dist/types/client/Pool.d.ts.map +1 -1
- package/dist/types/client/RequestMemoryBudget.d.ts +41 -0
- package/dist/types/client/RequestMemoryBudget.d.ts.map +1 -0
- package/dist/types/client/ScopeLimitedConnection.d.ts +34 -0
- package/dist/types/client/ScopeLimitedConnection.d.ts.map +1 -0
- package/dist/types/client/Transaction.d.ts +5 -5
- package/dist/types/client/Transaction.d.ts.map +1 -1
- package/dist/types/client/cancelRunningStatement.d.ts +7 -0
- package/dist/types/client/cancelRunningStatement.d.ts.map +1 -0
- package/dist/types/client/errors.d.ts +3 -0
- package/dist/types/client/errors.d.ts.map +1 -1
- package/dist/types/client/index.d.ts +8 -7
- package/dist/types/client/index.d.ts.map +1 -1
- package/dist/types/index.d.ts +11 -10
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/metadata/DatabaseMetadata.d.ts +3 -3
- package/dist/types/metadata/DatabaseMetadata.d.ts.map +1 -1
- package/dist/types/metadata/DatabaseMetadataResolver.d.ts +2 -2
- package/dist/types/metadata/DatabaseMetadataResolver.d.ts.map +1 -1
- package/dist/types/metadata/ForeignKeyConstraintMetadata.d.ts.map +1 -1
- package/dist/types/metadata/IndexMetadata.d.ts.map +1 -1
- package/dist/types/metadata/UniqueConstraintMetadata.d.ts.map +1 -1
- package/dist/types/metadata/index.d.ts +5 -5
- package/dist/types/metadata/index.d.ts.map +1 -1
- package/dist/types/metadata/stringArrayEquals.d.ts.map +1 -1
- package/dist/types/queryable/DatabaseQuery.d.ts +1 -1
- package/dist/types/queryable/DatabaseQuery.d.ts.map +1 -1
- package/dist/types/queryable/DatabaseQueryable.d.ts +1 -1
- package/dist/types/queryable/DatabaseQueryable.d.ts.map +1 -1
- package/dist/types/queryable/index.d.ts +2 -2
- package/dist/types/queryable/index.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/dist/types/types.d.ts +16 -0
- package/dist/types/types.d.ts.map +1 -1
- package/dist/types/utils/ConstraintHelper.d.ts +2 -2
- package/dist/types/utils/ConstraintHelper.d.ts.map +1 -1
- package/dist/types/utils/Mutex.d.ts.map +1 -1
- package/dist/types/utils/Semaphore.d.ts +17 -0
- package/dist/types/utils/Semaphore.d.ts.map +1 -0
- package/dist/types/utils/createDatabaseIfNotExists.d.ts +1 -1
- package/dist/types/utils/createDatabaseIfNotExists.d.ts.map +1 -1
- package/dist/types/utils/index.d.ts +11 -10
- package/dist/types/utils/index.d.ts.map +1 -1
- package/dist/types/utils/listen.d.ts +1 -1
- package/dist/types/utils/listen.d.ts.map +1 -1
- package/dist/types/utils/pgClientFactory.d.ts +3 -3
- package/dist/types/utils/pgClientFactory.d.ts.map +1 -1
- package/dist/types/utils/retryTransaction.d.ts.map +1 -1
- package/dist/types/utils/sql.d.ts +1 -1
- package/dist/types/utils/sql.d.ts.map +1 -1
- package/dist/types/utils/withDatabaseAdvisoryLock.d.ts +1 -1
- package/dist/types/utils/withDatabaseAdvisoryLock.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/builders/CaseStatement.ts +3 -3
- package/src/builders/ColumnExpressionFactory.ts +7 -7
- package/src/builders/Compiler.ts +9 -9
- package/src/builders/ConditionBuilder.ts +13 -7
- package/src/builders/DeleteBuilder.ts +8 -8
- package/src/builders/InsertBuilder.ts +11 -11
- package/src/builders/LimitByGroupWrapper.ts +6 -6
- package/src/builders/QueryBuilder.ts +5 -5
- package/src/builders/SelectBuilder.ts +11 -11
- package/src/builders/UpdateBuilder.ts +10 -10
- package/src/builders/WindowFunction.ts +7 -6
- package/src/builders/index.ts +12 -12
- package/src/builders/internal/Returning.ts +4 -4
- package/src/builders/internal/Subqueries.ts +4 -4
- package/src/builders/internal/Where.ts +4 -4
- package/src/builders/internal/With.ts +4 -4
- package/src/builders/utils.ts +4 -4
- package/src/client/AcquiredConnection.ts +131 -39
- package/src/client/Client.ts +16 -6
- package/src/client/Connection.ts +27 -7
- package/src/client/EventManager.ts +12 -2
- package/src/client/PgClient.ts +16 -1
- package/src/client/Pool.ts +5 -5
- package/src/client/RequestMemoryBudget.ts +260 -0
- package/src/client/ScopeLimitedConnection.ts +65 -0
- package/src/client/Transaction.ts +24 -11
- package/src/client/cancelRunningStatement.ts +36 -0
- package/src/client/errors.ts +6 -0
- package/src/client/index.ts +8 -7
- package/src/index.ts +12 -10
- package/src/metadata/DatabaseMetadata.ts +3 -3
- package/src/metadata/DatabaseMetadataResolver.ts +5 -5
- package/src/metadata/IndexMetadata.ts +1 -1
- package/src/metadata/UniqueConstraintMetadata.ts +1 -1
- package/src/metadata/index.ts +5 -5
- package/src/queryable/DatabaseQuery.ts +2 -2
- package/src/queryable/DatabaseQueryable.ts +1 -1
- package/src/queryable/index.ts +2 -2
- package/src/types.ts +16 -0
- package/src/utils/ConstraintHelper.ts +3 -3
- package/src/utils/Semaphore.ts +49 -0
- package/src/utils/createDatabaseIfNotExists.ts +3 -3
- package/src/utils/index.ts +11 -10
- package/src/utils/listen.ts +2 -2
- package/src/utils/pgClientFactory.ts +18 -10
- package/src/utils/retryTransaction.ts +1 -1
- package/src/utils/sql.ts +1 -1
- package/src/utils/withDatabaseAdvisoryLock.ts +1 -1
- package/tests/cases/integration/requestMemoryBudget.test.ts +296 -0
- package/tests/cases/unit/acquiredConnection.test.ts +154 -0
- package/tests/cases/unit/connection.test.ts +34 -2
- package/tests/cases/unit/createConnectionMockAlt.ts +18 -4
- package/tests/cases/unit/eventManager.test.ts +2 -2
- package/tests/cases/unit/pool.test.ts +1 -1
- package/tests/cases/unit/queryBuilder.test.ts +29 -4
- package/tests/cases/unit/requestMemoryBudget.test.ts +287 -0
- package/tests/cases/unit/scopeLimitedConnection.test.ts +204 -0
- package/tests/cases/unit/semaphore.test.ts +53 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"EventManager.js","sources":["../../../../../packages/database/src/client/EventManager.ts"],"sourcesContent":["import { Connection } from './Connection'\n\nclass EventManager {\n\tprivate readonly listeners = {\n\t\t[EventManager.Event.queryStart]: [] as EventManager.QueryStartCallback[],\n\t\t[EventManager.Event.queryEnd]: [] as EventManager.QueryEndCallback[],\n\t\t[EventManager.Event.queryError]: [] as EventManager.QueryStartCallback[],\n\t}\n\n\tconstructor(\n\t\tpublic readonly parent: EventManager | null = null,\n\t) {}\n\n\ton<Event extends keyof EventManager.ListenerTypes>(event: Event, cb: EventManager.ListenerTypes[Event]): void {\n\t\t;(this.listeners[event] as EventManager.ListenerTypes[Event][]).push(cb)\n\t}\n\n\tfire<Event extends EventManager.Event>(event: Event, ...params: Parameters<EventManager.ListenerTypes[Event]>): void {\n\t\t;(this.listeners[event] as EventManager.ListenerTypes[Event][]).forEach((cb: EventManager.ListenerTypes[Event]) => cb(...(params as [any, any])))\n\t\tif (this.parent) {\n\t\t\tthis.parent.fire(event, ...params)\n\t\t}\n\t}\n\n\tremoveListener<Event extends EventManager.Event>(\n\t\tevent: EventManager.Event,\n\t\tcb: EventManager.ListenerTypes[Event],\n\t): void {\n\t\tthis.listeners[event] = (this.listeners[event] as EventManager.ListenerTypes[Event][]).filter(it => it !== cb) as any[]\n\t}\n}\n\nnamespace EventManager {\n\texport enum Event {\n\t\tqueryStart = 'queryStart',\n\t\tqueryEnd = 'queryEnd',\n\t\tqueryError = 'queryError',\n\t}\n\n\texport type QueryStartCallback = (query: Connection.Query) => void\n\texport type QueryEndCallback = (query: Connection.Query, result: Connection.Result) => void\n\texport type QueryErrorCallback = (query: Connection.Query, error: Error) => void\n\n\texport interface ListenerTypes {\n\t\t[EventManager.Event.queryStart]: QueryStartCallback\n\t\t[EventManager.Event.queryEnd]: QueryEndCallback\n\t\t[EventManager.Event.queryError]: QueryErrorCallback\n\t}\n\n\texport type ListenersList = { [T in keyof ListenerTypes]: ListenerTypes[T][] }\n}\n\nexport { EventManager }\n"],"names":["EventManager","Event"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"EventManager.js","sources":["../../../../../packages/database/src/client/EventManager.ts"],"sourcesContent":["import { Connection } from './Connection.js'\nimport { RequestMemoryBudget } from './RequestMemoryBudget.js'\n\nclass EventManager {\n\t/** Every query bound to a budget is refused once it is exhausted; only queries that also charge it account their rows. */\n\tpublic readonly memoryBudget: RequestMemoryBudget | undefined\n\tpublic readonly chargesMemoryBudget: boolean\n\n\tprivate readonly listeners = {\n\t\t[EventManager.Event.queryStart]: [] as EventManager.QueryStartCallback[],\n\t\t[EventManager.Event.queryEnd]: [] as EventManager.QueryEndCallback[],\n\t\t[EventManager.Event.queryError]: [] as EventManager.QueryStartCallback[],\n\t}\n\n\tconstructor(\n\t\tpublic readonly parent: EventManager | null = null,\n\t\tmemoryBudget: RequestMemoryBudget | null | undefined = parent?.memoryBudget,\n\t\tchargesMemoryBudget: boolean = parent?.chargesMemoryBudget ?? false,\n\t) {\n\t\tthis.memoryBudget = memoryBudget ?? undefined\n\t\tthis.chargesMemoryBudget = this.memoryBudget !== undefined && chargesMemoryBudget\n\t}\n\n\ton<Event extends keyof EventManager.ListenerTypes>(event: Event, cb: EventManager.ListenerTypes[Event]): void {\n\t\t;(this.listeners[event] as EventManager.ListenerTypes[Event][]).push(cb)\n\t}\n\n\tfire<Event extends EventManager.Event>(event: Event, ...params: Parameters<EventManager.ListenerTypes[Event]>): void {\n\t\t;(this.listeners[event] as EventManager.ListenerTypes[Event][]).forEach((cb: EventManager.ListenerTypes[Event]) => cb(...(params as [any, any])))\n\t\tif (this.parent) {\n\t\t\tthis.parent.fire(event, ...params)\n\t\t}\n\t}\n\n\tremoveListener<Event extends EventManager.Event>(\n\t\tevent: EventManager.Event,\n\t\tcb: EventManager.ListenerTypes[Event],\n\t): void {\n\t\tthis.listeners[event] = (this.listeners[event] as EventManager.ListenerTypes[Event][]).filter(it => it !== cb) as any[]\n\t}\n}\n\nnamespace EventManager {\n\texport enum Event {\n\t\tqueryStart = 'queryStart',\n\t\tqueryEnd = 'queryEnd',\n\t\tqueryError = 'queryError',\n\t}\n\n\texport type QueryStartCallback = (query: Connection.Query) => void\n\texport type QueryEndCallback = (query: Connection.Query, result: Connection.Result) => void\n\texport type QueryErrorCallback = (query: Connection.Query, error: Error) => void\n\n\texport interface ListenerTypes {\n\t\t[EventManager.Event.queryStart]: QueryStartCallback\n\t\t[EventManager.Event.queryEnd]: QueryEndCallback\n\t\t[EventManager.Event.queryError]: QueryErrorCallback\n\t}\n\n\texport type ListenersList = { [T in keyof ListenerTypes]: ListenerTypes[T][] }\n}\n\nexport { EventManager }\n"],"names":["EventManager","Event"],"mappings":";;;AAGA,MAAM,aAAa;AAAA,EAWlB,YACiB,SAA8B,MAC9C,eAAuD,QAAQ,cAC/D,sBAA+B,QAAQ,uBAAuB,OAC7D;AAHe,SAAA,SAAA;AAVjB,kBAAA,MAAgB,cAAA;AAChB,kBAAA,MAAgB,qBAAA;AAEhB,kBAAA,MAAiB,aAAY;AAAA,MAC5B,CAAC,aAAa,MAAM,UAAU,GAAG,CAAA;AAAA,MACjC,CAAC,aAAa,MAAM,QAAQ,GAAG,CAAA;AAAA,MAC/B,CAAC,aAAa,MAAM,UAAU,GAAG,CAAA;AAAA,IAAC,CACnC;AAOC,SAAK,eAAe,gBAAgB;AACpC,SAAK,sBAAsB,KAAK,iBAAiB,UAAa;AAAA,EAC/D;AAAA,EAEA,GAAmD,OAAc,IAA6C;AAC3G,SAAK,UAAU,KAAK,EAA0C,KAAK,EAAE;AAAA,EACxE;AAAA,EAEA,KAAuC,UAAiB,QAA6D;AAClH,SAAK,UAAU,KAAK,EAA0C,QAAQ,CAAC,OAA0C,GAAG,GAAI,MAAqB,CAAC;AAChJ,QAAI,KAAK,QAAQ;AAChB,WAAK,OAAO,KAAK,OAAO,GAAG,MAAM;AAAA,IAClC;AAAA,EACD;AAAA,EAEA,eACC,OACA,IACO;AACP,SAAK,UAAU,KAAK,IAAK,KAAK,UAAU,KAAK,EAA0C,OAAO,CAAA,OAAM,OAAO,EAAE;AAAA,EAC9G;AACD;AAAA,CAEA,CAAUA,kBAAV;AACQ,GAAA,CAAKC,WAAL;AACNA,WAAA,YAAA,IAAa;AACbA,WAAA,UAAA,IAAW;AACXA,WAAA,YAAA,IAAa;AAAA,EAAA,GAHFD,cAAA,UAAAA,cAAA,QAAA,CAAA,EAAA;AAAA,GADH,iBAAA,eAAA,CAAA,EAAA;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Pool.cjs","sources":["../../../../../packages/database/src/client/Pool.ts"],"sourcesContent":["import { ImplementationException } from '../exceptions'\nimport { ClientErrorCodes } from './errorCodes'\nimport { EventEmitter } from 'node:events'\nimport { ClientError, DatabaseError } from './errors'\nimport { PgClientFactory } from '../utils'\nimport { PgClient } from './PgClient'\n\nexport type PoolLogger = (message: string, status: PoolStatus) => void\n\nexport type PoolConfig = Partial<PoolConfigInternal> & Pick<PoolConfigInternal, 'logError'>\n\ninterface PoolConfigInternal {\n\t/** maximum number of connections in a pool */\n\tmaxConnections: number\n\t/** maximum number of connections concurrently establishing*/\n\tmaxConnecting: number\n\t/** maximum connection attempts during given period */\n\trateLimitCount: number\n\t/** period for rate limiting */\n\trateLimitPeriodMs: number\n\t/** maximum number of idle connections. when reached, will be disposed immediately */\n\tmaxIdle: number\n\t/** interval between retries of recoverable errors */\n\treconnectIntervalMs: number\n\t/** timeout to dispose idle connections */\n\tidleTimeoutMs: number\n\t/** timeout of pending item waiting for a connection. also used for retries of recoverable errors */\n\tacquireTimeoutMs: number\n\t/** how many times can a single connection be acquired */\n\tmaxUses?: number\n\t/** max age of connection. when reached, connection will be disposed after returning to a pool */\n\tmaxAgeMs?: number\n\t/** internal logging, mainly for debugging and testing */\n\tlog?: PoolLogger\n\t/** logging of out-of-stack errors */\n\tlogError: (error: ClientError) => void\n}\n\nexport type PoolStats = { [K in keyof typeof poolStatsDescription]: number }\n\nexport interface PoolStatus {\n\t/** maximum number of connections in a pool */\n\tmax: number\n\t/** number of items waiting for a connections */\n\tpending: number\n\t/** number of active (acquired) connections */\n\tactive: number\n\t/** number of available idle connections */\n\tidle: number\n\t/** number of currently establishing connections */\n\tconnecting: number\n\tstats: PoolStats\n}\n\nexport const poolStatsDescription = {\n\tconnection_started_count: 'Total number of connection attempts when started.',\n\tconnection_established_count: 'Total number of established connections.',\n\tconnection_recoverable_error_count: 'Number of connections that failed on recoverable error (e.g. 53300) and retry was tried.',\n\tconnection_error_count: 'Number of non-recoverable errors or recoverable errors reaching max attempts.',\n\tconnection_disposed_idle_timeout_count: 'Number of idle connection, that was disposed after configured timeout.',\n\tconnection_disposed_idle_max_count:\n\t\t'Number of idle connections, that was immediately disposed, because maximum number of idle connection was reached.',\n\tconnection_disposed_old_count: 'Number of connections, that was too old after it was released.',\n\tconnection_disposed_manual_count: 'Number of manually disposed connection (e.g. due to exception on given connection).',\n\tconnection_released_count: 'Number of connection returned to the pool.',\n\tconnection_reused_immediately_count: 'Number of connections, that was reused by pending item immediately after it was returned to the pool.',\n\tconnection_reused_later_count: 'Number of idle connections, that was reused later.',\n\n\tconnection_established_idle_count: 'Number of newly established connections, which was not used (e.g. some connection was returned earlier).',\n\n\titem_queued_count: 'Number of queued items requesting a connection.',\n\titem_timeout_count: 'Number of items waiting for connection, which timed out.',\n\titem_rejected_count: 'Number of items rejected with an error.',\n\n\titem_resolved_new_ms_count: 'Number of queued items resolved with newly established connection.',\n\titem_resolved_new_ms_sum: 'Waiting time of queued items, which was resolved with a new connection.',\n\titem_resolved_released_ms_count: 'Number of queued items resolved with released connection.',\n\titem_resolved_released_ms_sum: 'Waiting time of queued items, which was resolved with a released connection.',\n}\n\nclass PoolConnection {\n\tpublic disposed = false\n\tpublic uses = 0\n\tpublic createdAt = Date.now()\n\tpublic timerId: ReturnType<typeof setTimeout> | null = null\n\n\tconstructor(\n\t\tpublic readonly client: PgClient,\n\t) {\n\t}\n}\n\nclass PendingItem {\n\tpublic readonly createdAt = Date.now()\n\n\tconstructor(\n\t\tpublic resolve: (connection: PoolConnection) => void,\n\t\tpublic reject: (error: Error) => void,\n\t) {\n\t}\n}\n\nclass Pool {\n\t/**\n\t * pool was closed by calling end().\n\t * All connection was disposed, and it is not possible to acquire new one\n\t */\n\tprivate ended = false\n\n\t/**\n\t * current count of connection attempts\n\t * also includes timeout between recoverable retries\n\t */\n\tprivate connectingCount = 0\n\n\t/**\n\t * Remaining number of connections per floating period.\n\t */\n\tprivate remainingRateLimit: number\n\n\t/**\n\t * available idle connections\n\t */\n\tprivate idle: PoolConnection[] = []\n\n\t/**\n\t * currently acquired connections\n\t */\n\tprivate active = new Set<PoolConnection>()\n\n\t/**\n\t * items waiting for released or newly established connection\n\t */\n\tprivate queue: PendingItem[] = []\n\n\tprivate poolConfig: PoolConfigInternal\n\n\tprivate poolStats: PoolStats = {\n\t\tconnection_started_count: 0,\n\t\tconnection_established_count: 0,\n\t\tconnection_recoverable_error_count: 0,\n\t\tconnection_error_count: 0,\n\t\tconnection_disposed_idle_timeout_count: 0,\n\t\tconnection_disposed_idle_max_count: 0,\n\t\tconnection_disposed_old_count: 0,\n\t\tconnection_disposed_manual_count: 0,\n\t\tconnection_released_count: 0,\n\t\tconnection_reused_immediately_count: 0,\n\t\tconnection_reused_later_count: 0,\n\t\tconnection_established_idle_count: 0,\n\t\titem_queued_count: 0,\n\t\titem_timeout_count: 0,\n\t\titem_rejected_count: 0,\n\t\titem_resolved_new_ms_count: 0,\n\t\titem_resolved_new_ms_sum: 0,\n\t\titem_resolved_released_ms_count: 0,\n\t\titem_resolved_released_ms_sum: 0,\n\t}\n\n\tprivate lastRecoverableError: {\n\t\terror: any\n\t\ttime: number\n\t} | undefined\n\n\tconstructor(\n\t\tprivate clientFactory: PgClientFactory,\n\t\tpoolConfig: PoolConfig,\n\t) {\n\t\tconst maxConnections = poolConfig.maxConnections ?? 10\n\t\tconst maxConnecting = Math.ceil(maxConnections / 2)\n\t\tthis.poolConfig = {\n\t\t\tmaxConnections,\n\t\t\tmaxConnecting,\n\t\t\tmaxIdle: maxConnections,\n\t\t\trateLimitCount: maxConnecting * 5,\n\t\t\trateLimitPeriodMs: 1000,\n\t\t\tidleTimeoutMs: 10_000,\n\t\t\tacquireTimeoutMs: 10_000,\n\t\t\treconnectIntervalMs: 100,\n\t\t\t...poolConfig,\n\t\t}\n\t\tthis.remainingRateLimit = this.poolConfig.rateLimitCount\n\t}\n\n\tpublic acquire(): Promise<PoolConnection> {\n\t\tif (this.ended) {\n\t\t\tthrow new PoolClosedError()\n\t\t}\n\t\tconst poolConnection = this.idle.pop()\n\t\tif (poolConnection !== undefined) {\n\t\t\tif (poolConnection.timerId) {\n\t\t\t\tclearTimeout(poolConnection.timerId)\n\t\t\t}\n\t\t\tpoolConnection.uses++\n\t\t\tthis.active.add(poolConnection)\n\t\t\tthis.poolStats.connection_reused_later_count++\n\t\t\tthis.log('Item fulfilled with an idle connection.')\n\n\t\t\treturn Promise.resolve(poolConnection)\n\t\t}\n\t\tconst pendingItem = this.createPendingItem()\n\t\tthis.maybeCreateNew()\n\t\treturn pendingItem\n\t}\n\n\tpublic release(poolConnection: PoolConnection): void {\n\t\tif (this.ended) {\n\t\t\treturn\n\t\t}\n\t\tthis.log('Releasing a connection.')\n\t\tif (!this.active.delete(poolConnection)) {\n\t\t\tthrow new ImplementationException('Connection does not belong to this pool.')\n\t\t}\n\t\tif (\n\t\t\t(this.poolConfig.maxUses && poolConnection.uses >= this.poolConfig.maxUses)\n\t\t\t|| (this.poolConfig.maxAgeMs && poolConnection.createdAt + this.poolConfig.maxAgeMs < Date.now())\n\t\t) {\n\t\t\tsetImmediate(async () => {\n\t\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\t\tthis.poolStats.connection_disposed_old_count++\n\t\t\t\tthis.log('Connection has reached max age or usage and was disposed.')\n\t\t\t})\n\t\t\tthis.maybeCreateNew()\n\t\t\treturn\n\t\t}\n\t\tthis.handleAvailableConnection(poolConnection)\n\t}\n\n\tpublic dispose(poolConnection: PoolConnection): void {\n\t\tif (this.ended) {\n\t\t\treturn\n\t\t}\n\t\tthis.poolStats.connection_disposed_manual_count++\n\t\tthis.log('Releasing and disposing a connection.')\n\t\tif (!this.active.delete(poolConnection)) {\n\t\t\tthrow new ImplementationException('Connection does not belong to this pool.')\n\t\t}\n\t\tsetImmediate(async () => {\n\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\tthis.log('Connection errored and was disposed.')\n\t\t})\n\t\tthis.maybeCreateNew()\n\t}\n\n\tpublic async end(): Promise<void> {\n\t\tthis.ended = true\n\t\tthis.queue.forEach(it => it.reject(new PoolClosedError()))\n\t\tthis.queue = []\n\t\tconst allConnections = [...this.idle, ...Array.from(this.active)]\n\t\tawait Promise.allSettled(allConnections.map(it => this.disposeConnection(it)))\n\t\tthis.idle = []\n\t\tthis.active.clear()\n\t}\n\n\tpublic async closeIdle(): Promise<void> {\n\t\tthis.log('Disposing all idle connection on request.')\n\t\tconst idle = this.idle\n\t\tthis.idle = []\n\t\tawait Promise.allSettled(idle.map(it => this.disposeConnection(it)))\n\t}\n\n\tpublic getPoolStatus(): PoolStatus {\n\t\treturn {\n\t\t\tmax: this.poolConfig.maxConnections,\n\t\t\tactive: this.active.size,\n\t\t\tidle: this.idle.length,\n\t\t\tpending: this.queue.length,\n\t\t\tconnecting: this.connectingCount,\n\t\t\tstats: this.poolStats,\n\t\t}\n\t}\n\n\tprivate async maybeCreateNew(): Promise<void> {\n\t\tif (this.ended) {\n\t\t\treturn\n\t\t}\n\t\tif (this.queue.length === 0) {\n\t\t\tthis.log('Not connecting, queue is empty.')\n\t\t\treturn\n\t\t}\n\t\tconst connectingCount = this.connectingCount\n\t\tif (connectingCount >= this.queue.length) {\n\t\t\tthis.log('Not connecting, already establishing connection for all queued items.')\n\t\t\treturn\n\t\t}\n\t\tconst idleCount = this.idle.length\n\t\tif ((this.active.size + idleCount + connectingCount) >= this.poolConfig.maxConnections) {\n\t\t\tthis.log('Not connecting, max connections reached.')\n\t\t\treturn\n\t\t}\n\t\tif (connectingCount >= this.poolConfig.maxConnecting) {\n\t\t\tthis.log('Not connecting, maximum concurrent connection attempts in progress.')\n\t\t\treturn\n\t\t}\n\t\tif (this.remainingRateLimit <= 0) {\n\t\t\tthis.log('Not connecting, rate limit reached.')\n\t\t\treturn\n\t\t}\n\n\t\tthis.log('Creating a new connection')\n\t\tconst client = this.clientFactory()\n\t\tconst poolConnection = new PoolConnection(client)\n\n\t\tclient.on('error', e => {\n\t\t\tthis.log('Client error on idle connection has occurred: ' + e.message)\n\t\t\tthis.poolConfig.logError(new ClientError(e, 'runtime error'))\n\t\t\tthis.poolStats.connection_error_count++\n\n\t\t\tif (!this.active.has(poolConnection)) {\n\t\t\t\tthis.removeIdleConnection(poolConnection)\n\t\t\t\tthis.disposeConnection(poolConnection)\n\t\t\t}\n\t\t})\n\n\t\ttry {\n\t\t\tthis.connectingCount++\n\t\t\tthis.remainingRateLimit--\n\t\t\tthis.poolStats.connection_started_count++\n\n\t\t\tawait client.connect()\n\n\t\t\tthis.poolStats.connection_established_count++\n\t\t\tthis.connectingCount--\n\n\t\t\tthis.log('Connection established')\n\n\t\t\tif (this.ended) {\n\t\t\t\treturn this.disposeConnection(poolConnection)\n\t\t\t}\n\n\t\t\tthis.handleAvailableConnection(poolConnection)\n\t\t\tthis.maybeCreateNew()\n\t\t} catch (e: any) {\n\t\t\tthis.log('Connection error occurred: ' + e.message)\n\t\t\tthis.disposeConnection(poolConnection)\n\n\t\t\tif (\n\t\t\t\te.code === ClientErrorCodes.TOO_MANY_CONNECTIONS\n\t\t\t\t|| e.code === ClientErrorCodes.CANNOT_CONNECT_NOW // server starting\n\t\t\t\t|| e.message === 'timeout expired' // https://github.com/brianc/node-postgres/blob/c7dc621d3fb52c158eb23aa31dea6bd440700a4a/packages/pg/lib/client.js#L105\n\t\t\t\t|| e.code === 'ETIMEDOUT'\n\t\t\t) {\n\t\t\t\tthis.lastRecoverableError = { error: e, time: Date.now() }\n\t\t\t\tthis.poolStats.connection_recoverable_error_count++\n\t\t\t\tthis.log('Recoverable error, retrying in a moment.')\n\t\t\t\tthis.poolConfig.logError(new ClientError(e, 'recoverable connection error'))\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis.connectingCount--\n\t\t\t\t\tthis.log('Retrying')\n\t\t\t\t\tthis.maybeCreateNew()\n\t\t\t\t}, this.poolConfig.reconnectIntervalMs)\n\t\t\t} else {\n\t\t\t\tthis.poolStats.connection_error_count++\n\t\t\t\tthis.connectingCount--\n\t\t\t\tconst clientError = new ClientError(e, 'connection error')\n\t\t\t\tif (this.active.size === 0 && this.queue.length > 0) {\n\t\t\t\t\tconst pendingItem = this.queue.shift()\n\t\t\t\t\tif (!pendingItem) throw new Error()\n\t\t\t\t\tthis.log('Connecting failed, rejecting pending item')\n\t\t\t\t\tpendingItem.reject(clientError)\n\t\t\t\t\tthis.poolStats.item_rejected_count++\n\t\t\t\t} else {\n\t\t\t\t\tthis.log('Connecting failed, emitting error')\n\t\t\t\t\tthis.poolConfig.logError(clientError)\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tsetTimeout(() => {\n\t\t\t\tif (this.remainingRateLimit === 0) {\n\t\t\t\t\tthis.log('Rate limit renewed.')\n\t\t\t\t}\n\t\t\t\tthis.remainingRateLimit++\n\t\t\t\tthis.maybeCreateNew()\n\t\t\t}, this.poolConfig.rateLimitPeriodMs)\n\t\t}\n\t}\n\n\tprivate createPendingItem(): Promise<PoolConnection> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tconst acquireTimeoutError = new AcquireTimeoutError(\n\t\t\t\t\tthis.lastRecoverableError && this.lastRecoverableError.time > item.createdAt\n\t\t\t\t\t\t? this.lastRecoverableError.error\n\t\t\t\t\t\t: undefined,\n\t\t\t\t)\n\t\t\t\titem.reject(acquireTimeoutError)\n\t\t\t\tconst index = this.queue.indexOf(item)\n\t\t\t\tif (index > -1) {\n\t\t\t\t\tthis.queue.splice(index, 1)\n\t\t\t\t}\n\t\t\t\tthis.poolStats.item_timeout_count++\n\t\t\t\tthis.log('Queued item timed out')\n\t\t\t}, this.poolConfig.acquireTimeoutMs)\n\n\t\t\tconst item = new PendingItem(it => {\n\t\t\t\tconst duration = Date.now() - item.createdAt\n\t\t\t\tconst isNew = it.uses === 0\n\t\t\t\tthis.log(`Queued item fulfilled with ${!isNew ? 'released' : 'new'} connection.`)\n\n\t\t\t\tif (isNew) {\n\t\t\t\t\tthis.poolStats.item_resolved_new_ms_count++\n\t\t\t\t\tthis.poolStats.item_resolved_new_ms_sum += duration\n\t\t\t\t} else {\n\t\t\t\t\tthis.poolStats.item_resolved_released_ms_count++\n\t\t\t\t\tthis.poolStats.item_resolved_released_ms_sum += duration\n\t\t\t\t}\n\t\t\t\tclearTimeout(timeout)\n\t\t\t\tresolve(it)\n\t\t\t}, it => {\n\t\t\t\tclearTimeout(timeout)\n\t\t\t\treject(it)\n\t\t\t})\n\n\t\t\tthis.poolStats.item_queued_count++\n\t\t\tthis.queue.push(item)\n\t\t\tthis.log(`Item added to a queue.`)\n\t\t})\n\t}\n\n\tprivate handleAvailableConnection(poolConnection: PoolConnection) {\n\t\tconst item = this.queue.shift()\n\t\tconst isNew = poolConnection.uses === 0\n\t\tif (!isNew) {\n\t\t\tthis.poolStats.connection_released_count++\n\t\t}\n\t\tif (item) {\n\t\t\tthis.active.add(poolConnection)\n\t\t\titem.resolve(poolConnection)\n\t\t\tif (!isNew) {\n\t\t\t\tthis.poolStats.connection_reused_immediately_count++\n\t\t\t}\n\t\t\tpoolConnection.uses++\n\t\t\treturn\n\t\t}\n\t\tif (isNew) {\n\t\t\tthis.poolStats.connection_established_idle_count++\n\t\t}\n\t\tif (this.idle.length >= this.poolConfig.maxIdle) {\n\t\t\tsetImmediate(async () => {\n\t\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\t\tthis.poolStats.connection_disposed_idle_max_count++\n\t\t\t\tthis.log('Too many idle connections, connection disposed.')\n\t\t\t})\n\t\t} else {\n\t\t\tpoolConnection.timerId = setTimeout(async () => {\n\t\t\t\tif (this.removeIdleConnection(poolConnection)) {\n\t\t\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\t\t\tthis.poolStats.connection_disposed_idle_timeout_count++\n\t\t\t\t\tthis.log('Idle connection disposed after timeout.')\n\t\t\t\t}\n\t\t\t}, this.poolConfig.idleTimeoutMs)\n\t\t\tthis.idle.push(poolConnection)\n\t\t\tthis.log('Connection is idle and available.')\n\t\t}\n\t}\n\n\tprivate removeIdleConnection(poolConnection: PoolConnection) {\n\t\tconst index = this.idle.indexOf(poolConnection)\n\t\tif (index > -1) {\n\t\t\tthis.idle.splice(index, 1)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\tprivate async disposeConnection(connection: PoolConnection) {\n\t\tif (connection.disposed) {\n\t\t\tthrow new PoolError('Connection is already disposed')\n\t\t}\n\t\tconnection.disposed = true\n\t\tconst doEnd = async () => {\n\t\t\ttry {\n\t\t\t\tawait connection.client.end()\n\t\t\t} catch (e: any) {\n\t\t\t\tthis.poolConfig.logError(new ClientError(e, 'disposal error'))\n\t\t\t}\n\t\t}\n\t\tawait Promise.race([\n\t\t\tdoEnd(),\n\t\t\tnew Promise(resolve => setTimeout(resolve, 5_000)),\n\t\t])\n\t}\n\n\tprivate log(message: string) {\n\t\tif (!this.poolConfig.log) return\n\t\tconst poolStatus = this.getPoolStatus()\n\t\tthis.poolConfig.log(message, poolStatus)\n\t}\n}\n\nexport { Pool }\n\nexport class PoolError extends DatabaseError {\n}\n\nexport class AcquireTimeoutError extends PoolError {\n\tconstructor(previous: any) {\n\t\tsuper('Failed to acquire a connection' + (previous && 'message' in previous ? `. Last error: ${previous.message}` : ''), previous)\n\t}\n}\n\nexport class PoolClosedError extends PoolError {\n\tconstructor() {\n\t\tsuper('Pool is already closed')\n\t}\n}\n"],"names":["ImplementationException","ClientError","ClientErrorCodes","DatabaseError"],"mappings":";;;;;;;;AAsDO,MAAM,uBAAuB;AAAA,EACnC,0BAA0B;AAAA,EAC1B,8BAA8B;AAAA,EAC9B,oCAAoC;AAAA,EACpC,wBAAwB;AAAA,EACxB,wCAAwC;AAAA,EACxC,oCACC;AAAA,EACD,+BAA+B;AAAA,EAC/B,kCAAkC;AAAA,EAClC,2BAA2B;AAAA,EAC3B,qCAAqC;AAAA,EACrC,+BAA+B;AAAA,EAE/B,mCAAmC;AAAA,EAEnC,mBAAmB;AAAA,EACnB,oBAAoB;AAAA,EACpB,qBAAqB;AAAA,EAErB,4BAA4B;AAAA,EAC5B,0BAA0B;AAAA,EAC1B,iCAAiC;AAAA,EACjC,+BAA+B;AAChC;AAEA,MAAM,eAAe;AAAA,EAMpB,YACiB,QACf;AADe,SAAA,SAAA;AANjB,kBAAA,MAAO,YAAW,KAAA;AAClB,kBAAA,MAAO,QAAO,CAAA;AACd,kBAAA,MAAO,aAAY,KAAK,IAAA,CAAI;AAC5B,kBAAA,MAAO,WAAgD,IAAA;AAAA,EAKvD;AACD;AAEA,MAAM,YAAY;AAAA,EAGjB,YACQ,SACA,QACN;AAFM,SAAA,UAAA;AACA,SAAA,SAAA;AAJR,kBAAA,MAAgB,aAAY,KAAK,IAAA,CAAI;AAAA,EAMrC;AACD;AAEA,MAAM,KAAK;AAAA,EA8DV,YACS,eACR,YACC;AAFO,SAAA,gBAAA;AA1DT,kBAAA,MAAQ,SAAQ,KAAA;AAMhB,kBAAA,MAAQ,mBAAkB,CAAA;AAK1B,kBAAA,MAAQ,oBAAA;AAKR,kBAAA,MAAQ,QAAyB,EAAC;AAKlC,kBAAA,MAAQ,8BAAa,IAAA,CAAoB;AAKzC,kBAAA,MAAQ,SAAuB,EAAC;AAEhC,kBAAA,MAAQ,YAAA;AAER,kBAAA,MAAQ,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AW,SAAS,GAAK,CAAC;AAAA,IAAA,CACjD;AAAA,EACF;AAAA,EAEQ,IAAI,SAAiB;AAC5B,QAAI,CAAC,KAAK,WAAW,IAAK;AAC1B,UAAM,aAAa,KAAK,cAAA;AACxB,SAAK,WAAW,IAAI,SAAS,UAAU;AAAA,EACxC;AACD;AAIO,MAAM,kBAAkBE,OAAAA,cAAc;AAC7C;AAEO,MAAM,4BAA4B,UAAU;AAAA,EAClD,YAAY,UAAe;AAC1B,UAAM,oCAAoC,YAAY,aAAa,WAAW,iBAAiB,SAAS,OAAO,KAAK,KAAK,QAAQ;AAAA,EAClI;AACD;AAEO,MAAM,wBAAwB,UAAU;AAAA,EAC9C,cAAc;AACb,UAAM,wBAAwB;AAAA,EAC/B;AACD;;;;;;"}
|
|
1
|
+
{"version":3,"file":"Pool.cjs","sources":["../../../../../packages/database/src/client/Pool.ts"],"sourcesContent":["import { ImplementationException } from '../exceptions.js'\nimport { ClientErrorCodes } from './errorCodes.js'\nimport { EventEmitter } from 'node:events'\nimport { ClientError, DatabaseError } from './errors.js'\nimport { PgClientFactory } from '../utils/index.js'\nimport { PgClient } from './PgClient.js'\n\nexport type PoolLogger = (message: string, status: PoolStatus) => void\n\nexport type PoolConfig = Partial<PoolConfigInternal> & Pick<PoolConfigInternal, 'logError'>\n\ninterface PoolConfigInternal {\n\t/** maximum number of connections in a pool */\n\tmaxConnections: number\n\t/** maximum number of connections concurrently establishing*/\n\tmaxConnecting: number\n\t/** maximum connection attempts during given period */\n\trateLimitCount: number\n\t/** period for rate limiting */\n\trateLimitPeriodMs: number\n\t/** maximum number of idle connections. when reached, will be disposed immediately */\n\tmaxIdle: number\n\t/** interval between retries of recoverable errors */\n\treconnectIntervalMs: number\n\t/** timeout to dispose idle connections */\n\tidleTimeoutMs: number\n\t/** timeout of pending item waiting for a connection. also used for retries of recoverable errors */\n\tacquireTimeoutMs: number\n\t/** how many times can a single connection be acquired */\n\tmaxUses?: number\n\t/** max age of connection. when reached, connection will be disposed after returning to a pool */\n\tmaxAgeMs?: number\n\t/** internal logging, mainly for debugging and testing */\n\tlog?: PoolLogger\n\t/** logging of out-of-stack errors */\n\tlogError: (error: ClientError) => void\n}\n\nexport type PoolStats = { [K in keyof typeof poolStatsDescription]: number }\n\nexport interface PoolStatus {\n\t/** maximum number of connections in a pool */\n\tmax: number\n\t/** number of items waiting for a connections */\n\tpending: number\n\t/** number of active (acquired) connections */\n\tactive: number\n\t/** number of available idle connections */\n\tidle: number\n\t/** number of currently establishing connections */\n\tconnecting: number\n\tstats: PoolStats\n}\n\nexport const poolStatsDescription = {\n\tconnection_started_count: 'Total number of connection attempts when started.',\n\tconnection_established_count: 'Total number of established connections.',\n\tconnection_recoverable_error_count: 'Number of connections that failed on recoverable error (e.g. 53300) and retry was tried.',\n\tconnection_error_count: 'Number of non-recoverable errors or recoverable errors reaching max attempts.',\n\tconnection_disposed_idle_timeout_count: 'Number of idle connection, that was disposed after configured timeout.',\n\tconnection_disposed_idle_max_count:\n\t\t'Number of idle connections, that was immediately disposed, because maximum number of idle connection was reached.',\n\tconnection_disposed_old_count: 'Number of connections, that was too old after it was released.',\n\tconnection_disposed_manual_count: 'Number of manually disposed connection (e.g. due to exception on given connection).',\n\tconnection_released_count: 'Number of connection returned to the pool.',\n\tconnection_reused_immediately_count: 'Number of connections, that was reused by pending item immediately after it was returned to the pool.',\n\tconnection_reused_later_count: 'Number of idle connections, that was reused later.',\n\n\tconnection_established_idle_count: 'Number of newly established connections, which was not used (e.g. some connection was returned earlier).',\n\n\titem_queued_count: 'Number of queued items requesting a connection.',\n\titem_timeout_count: 'Number of items waiting for connection, which timed out.',\n\titem_rejected_count: 'Number of items rejected with an error.',\n\n\titem_resolved_new_ms_count: 'Number of queued items resolved with newly established connection.',\n\titem_resolved_new_ms_sum: 'Waiting time of queued items, which was resolved with a new connection.',\n\titem_resolved_released_ms_count: 'Number of queued items resolved with released connection.',\n\titem_resolved_released_ms_sum: 'Waiting time of queued items, which was resolved with a released connection.',\n}\n\nclass PoolConnection {\n\tpublic disposed = false\n\tpublic uses = 0\n\tpublic createdAt = Date.now()\n\tpublic timerId: ReturnType<typeof setTimeout> | null = null\n\n\tconstructor(\n\t\tpublic readonly client: PgClient,\n\t) {\n\t}\n}\n\nclass PendingItem {\n\tpublic readonly createdAt = Date.now()\n\n\tconstructor(\n\t\tpublic resolve: (connection: PoolConnection) => void,\n\t\tpublic reject: (error: Error) => void,\n\t) {\n\t}\n}\n\nclass Pool {\n\t/**\n\t * pool was closed by calling end().\n\t * All connection was disposed, and it is not possible to acquire new one\n\t */\n\tprivate ended = false\n\n\t/**\n\t * current count of connection attempts\n\t * also includes timeout between recoverable retries\n\t */\n\tprivate connectingCount = 0\n\n\t/**\n\t * Remaining number of connections per floating period.\n\t */\n\tprivate remainingRateLimit: number\n\n\t/**\n\t * available idle connections\n\t */\n\tprivate idle: PoolConnection[] = []\n\n\t/**\n\t * currently acquired connections\n\t */\n\tprivate active = new Set<PoolConnection>()\n\n\t/**\n\t * items waiting for released or newly established connection\n\t */\n\tprivate queue: PendingItem[] = []\n\n\tprivate poolConfig: PoolConfigInternal\n\n\tprivate poolStats: PoolStats = {\n\t\tconnection_started_count: 0,\n\t\tconnection_established_count: 0,\n\t\tconnection_recoverable_error_count: 0,\n\t\tconnection_error_count: 0,\n\t\tconnection_disposed_idle_timeout_count: 0,\n\t\tconnection_disposed_idle_max_count: 0,\n\t\tconnection_disposed_old_count: 0,\n\t\tconnection_disposed_manual_count: 0,\n\t\tconnection_released_count: 0,\n\t\tconnection_reused_immediately_count: 0,\n\t\tconnection_reused_later_count: 0,\n\t\tconnection_established_idle_count: 0,\n\t\titem_queued_count: 0,\n\t\titem_timeout_count: 0,\n\t\titem_rejected_count: 0,\n\t\titem_resolved_new_ms_count: 0,\n\t\titem_resolved_new_ms_sum: 0,\n\t\titem_resolved_released_ms_count: 0,\n\t\titem_resolved_released_ms_sum: 0,\n\t}\n\n\tprivate lastRecoverableError: {\n\t\terror: any\n\t\ttime: number\n\t} | undefined\n\n\tconstructor(\n\t\tprivate clientFactory: PgClientFactory,\n\t\tpoolConfig: PoolConfig,\n\t) {\n\t\tconst maxConnections = poolConfig.maxConnections ?? 10\n\t\tconst maxConnecting = Math.ceil(maxConnections / 2)\n\t\tthis.poolConfig = {\n\t\t\tmaxConnections,\n\t\t\tmaxConnecting,\n\t\t\tmaxIdle: maxConnections,\n\t\t\trateLimitCount: maxConnecting * 5,\n\t\t\trateLimitPeriodMs: 1000,\n\t\t\tidleTimeoutMs: 10_000,\n\t\t\tacquireTimeoutMs: 10_000,\n\t\t\treconnectIntervalMs: 100,\n\t\t\t...poolConfig,\n\t\t}\n\t\tthis.remainingRateLimit = this.poolConfig.rateLimitCount\n\t}\n\n\tpublic acquire(): Promise<PoolConnection> {\n\t\tif (this.ended) {\n\t\t\tthrow new PoolClosedError()\n\t\t}\n\t\tconst poolConnection = this.idle.pop()\n\t\tif (poolConnection !== undefined) {\n\t\t\tif (poolConnection.timerId) {\n\t\t\t\tclearTimeout(poolConnection.timerId)\n\t\t\t}\n\t\t\tpoolConnection.uses++\n\t\t\tthis.active.add(poolConnection)\n\t\t\tthis.poolStats.connection_reused_later_count++\n\t\t\tthis.log('Item fulfilled with an idle connection.')\n\n\t\t\treturn Promise.resolve(poolConnection)\n\t\t}\n\t\tconst pendingItem = this.createPendingItem()\n\t\tthis.maybeCreateNew()\n\t\treturn pendingItem\n\t}\n\n\tpublic release(poolConnection: PoolConnection): void {\n\t\tif (this.ended) {\n\t\t\treturn\n\t\t}\n\t\tthis.log('Releasing a connection.')\n\t\tif (!this.active.delete(poolConnection)) {\n\t\t\tthrow new ImplementationException('Connection does not belong to this pool.')\n\t\t}\n\t\tif (\n\t\t\t(this.poolConfig.maxUses && poolConnection.uses >= this.poolConfig.maxUses)\n\t\t\t|| (this.poolConfig.maxAgeMs && poolConnection.createdAt + this.poolConfig.maxAgeMs < Date.now())\n\t\t) {\n\t\t\tsetImmediate(async () => {\n\t\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\t\tthis.poolStats.connection_disposed_old_count++\n\t\t\t\tthis.log('Connection has reached max age or usage and was disposed.')\n\t\t\t})\n\t\t\tthis.maybeCreateNew()\n\t\t\treturn\n\t\t}\n\t\tthis.handleAvailableConnection(poolConnection)\n\t}\n\n\tpublic dispose(poolConnection: PoolConnection): void {\n\t\tif (this.ended) {\n\t\t\treturn\n\t\t}\n\t\tthis.poolStats.connection_disposed_manual_count++\n\t\tthis.log('Releasing and disposing a connection.')\n\t\tif (!this.active.delete(poolConnection)) {\n\t\t\tthrow new ImplementationException('Connection does not belong to this pool.')\n\t\t}\n\t\tsetImmediate(async () => {\n\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\tthis.log('Connection errored and was disposed.')\n\t\t})\n\t\tthis.maybeCreateNew()\n\t}\n\n\tpublic async end(): Promise<void> {\n\t\tthis.ended = true\n\t\tthis.queue.forEach(it => it.reject(new PoolClosedError()))\n\t\tthis.queue = []\n\t\tconst allConnections = [...this.idle, ...Array.from(this.active)]\n\t\tawait Promise.allSettled(allConnections.map(it => this.disposeConnection(it)))\n\t\tthis.idle = []\n\t\tthis.active.clear()\n\t}\n\n\tpublic async closeIdle(): Promise<void> {\n\t\tthis.log('Disposing all idle connection on request.')\n\t\tconst idle = this.idle\n\t\tthis.idle = []\n\t\tawait Promise.allSettled(idle.map(it => this.disposeConnection(it)))\n\t}\n\n\tpublic getPoolStatus(): PoolStatus {\n\t\treturn {\n\t\t\tmax: this.poolConfig.maxConnections,\n\t\t\tactive: this.active.size,\n\t\t\tidle: this.idle.length,\n\t\t\tpending: this.queue.length,\n\t\t\tconnecting: this.connectingCount,\n\t\t\tstats: this.poolStats,\n\t\t}\n\t}\n\n\tprivate async maybeCreateNew(): Promise<void> {\n\t\tif (this.ended) {\n\t\t\treturn\n\t\t}\n\t\tif (this.queue.length === 0) {\n\t\t\tthis.log('Not connecting, queue is empty.')\n\t\t\treturn\n\t\t}\n\t\tconst connectingCount = this.connectingCount\n\t\tif (connectingCount >= this.queue.length) {\n\t\t\tthis.log('Not connecting, already establishing connection for all queued items.')\n\t\t\treturn\n\t\t}\n\t\tconst idleCount = this.idle.length\n\t\tif ((this.active.size + idleCount + connectingCount) >= this.poolConfig.maxConnections) {\n\t\t\tthis.log('Not connecting, max connections reached.')\n\t\t\treturn\n\t\t}\n\t\tif (connectingCount >= this.poolConfig.maxConnecting) {\n\t\t\tthis.log('Not connecting, maximum concurrent connection attempts in progress.')\n\t\t\treturn\n\t\t}\n\t\tif (this.remainingRateLimit <= 0) {\n\t\t\tthis.log('Not connecting, rate limit reached.')\n\t\t\treturn\n\t\t}\n\n\t\tthis.log('Creating a new connection')\n\t\tconst client = this.clientFactory()\n\t\tconst poolConnection = new PoolConnection(client)\n\n\t\tclient.on('error', e => {\n\t\t\tthis.log('Client error on idle connection has occurred: ' + e.message)\n\t\t\tthis.poolConfig.logError(new ClientError(e, 'runtime error'))\n\t\t\tthis.poolStats.connection_error_count++\n\n\t\t\tif (!this.active.has(poolConnection)) {\n\t\t\t\tthis.removeIdleConnection(poolConnection)\n\t\t\t\tthis.disposeConnection(poolConnection)\n\t\t\t}\n\t\t})\n\n\t\ttry {\n\t\t\tthis.connectingCount++\n\t\t\tthis.remainingRateLimit--\n\t\t\tthis.poolStats.connection_started_count++\n\n\t\t\tawait client.connect()\n\n\t\t\tthis.poolStats.connection_established_count++\n\t\t\tthis.connectingCount--\n\n\t\t\tthis.log('Connection established')\n\n\t\t\tif (this.ended) {\n\t\t\t\treturn this.disposeConnection(poolConnection)\n\t\t\t}\n\n\t\t\tthis.handleAvailableConnection(poolConnection)\n\t\t\tthis.maybeCreateNew()\n\t\t} catch (e: any) {\n\t\t\tthis.log('Connection error occurred: ' + e.message)\n\t\t\tthis.disposeConnection(poolConnection)\n\n\t\t\tif (\n\t\t\t\te.code === ClientErrorCodes.TOO_MANY_CONNECTIONS\n\t\t\t\t|| e.code === ClientErrorCodes.CANNOT_CONNECT_NOW // server starting\n\t\t\t\t|| e.message === 'timeout expired' // https://github.com/brianc/node-postgres/blob/c7dc621d3fb52c158eb23aa31dea6bd440700a4a/packages/pg/lib/client.js#L105\n\t\t\t\t|| e.code === 'ETIMEDOUT'\n\t\t\t) {\n\t\t\t\tthis.lastRecoverableError = { error: e, time: Date.now() }\n\t\t\t\tthis.poolStats.connection_recoverable_error_count++\n\t\t\t\tthis.log('Recoverable error, retrying in a moment.')\n\t\t\t\tthis.poolConfig.logError(new ClientError(e, 'recoverable connection error'))\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis.connectingCount--\n\t\t\t\t\tthis.log('Retrying')\n\t\t\t\t\tthis.maybeCreateNew()\n\t\t\t\t}, this.poolConfig.reconnectIntervalMs)\n\t\t\t} else {\n\t\t\t\tthis.poolStats.connection_error_count++\n\t\t\t\tthis.connectingCount--\n\t\t\t\tconst clientError = new ClientError(e, 'connection error')\n\t\t\t\tif (this.active.size === 0 && this.queue.length > 0) {\n\t\t\t\t\tconst pendingItem = this.queue.shift()\n\t\t\t\t\tif (!pendingItem) throw new Error()\n\t\t\t\t\tthis.log('Connecting failed, rejecting pending item')\n\t\t\t\t\tpendingItem.reject(clientError)\n\t\t\t\t\tthis.poolStats.item_rejected_count++\n\t\t\t\t} else {\n\t\t\t\t\tthis.log('Connecting failed, emitting error')\n\t\t\t\t\tthis.poolConfig.logError(clientError)\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tsetTimeout(() => {\n\t\t\t\tif (this.remainingRateLimit === 0) {\n\t\t\t\t\tthis.log('Rate limit renewed.')\n\t\t\t\t}\n\t\t\t\tthis.remainingRateLimit++\n\t\t\t\tthis.maybeCreateNew()\n\t\t\t}, this.poolConfig.rateLimitPeriodMs)\n\t\t}\n\t}\n\n\tprivate createPendingItem(): Promise<PoolConnection> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tconst acquireTimeoutError = new AcquireTimeoutError(\n\t\t\t\t\tthis.lastRecoverableError && this.lastRecoverableError.time > item.createdAt\n\t\t\t\t\t\t? this.lastRecoverableError.error\n\t\t\t\t\t\t: undefined,\n\t\t\t\t)\n\t\t\t\titem.reject(acquireTimeoutError)\n\t\t\t\tconst index = this.queue.indexOf(item)\n\t\t\t\tif (index > -1) {\n\t\t\t\t\tthis.queue.splice(index, 1)\n\t\t\t\t}\n\t\t\t\tthis.poolStats.item_timeout_count++\n\t\t\t\tthis.log('Queued item timed out')\n\t\t\t}, this.poolConfig.acquireTimeoutMs)\n\n\t\t\tconst item = new PendingItem(it => {\n\t\t\t\tconst duration = Date.now() - item.createdAt\n\t\t\t\tconst isNew = it.uses === 0\n\t\t\t\tthis.log(`Queued item fulfilled with ${!isNew ? 'released' : 'new'} connection.`)\n\n\t\t\t\tif (isNew) {\n\t\t\t\t\tthis.poolStats.item_resolved_new_ms_count++\n\t\t\t\t\tthis.poolStats.item_resolved_new_ms_sum += duration\n\t\t\t\t} else {\n\t\t\t\t\tthis.poolStats.item_resolved_released_ms_count++\n\t\t\t\t\tthis.poolStats.item_resolved_released_ms_sum += duration\n\t\t\t\t}\n\t\t\t\tclearTimeout(timeout)\n\t\t\t\tresolve(it)\n\t\t\t}, it => {\n\t\t\t\tclearTimeout(timeout)\n\t\t\t\treject(it)\n\t\t\t})\n\n\t\t\tthis.poolStats.item_queued_count++\n\t\t\tthis.queue.push(item)\n\t\t\tthis.log(`Item added to a queue.`)\n\t\t})\n\t}\n\n\tprivate handleAvailableConnection(poolConnection: PoolConnection) {\n\t\tconst item = this.queue.shift()\n\t\tconst isNew = poolConnection.uses === 0\n\t\tif (!isNew) {\n\t\t\tthis.poolStats.connection_released_count++\n\t\t}\n\t\tif (item) {\n\t\t\tthis.active.add(poolConnection)\n\t\t\titem.resolve(poolConnection)\n\t\t\tif (!isNew) {\n\t\t\t\tthis.poolStats.connection_reused_immediately_count++\n\t\t\t}\n\t\t\tpoolConnection.uses++\n\t\t\treturn\n\t\t}\n\t\tif (isNew) {\n\t\t\tthis.poolStats.connection_established_idle_count++\n\t\t}\n\t\tif (this.idle.length >= this.poolConfig.maxIdle) {\n\t\t\tsetImmediate(async () => {\n\t\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\t\tthis.poolStats.connection_disposed_idle_max_count++\n\t\t\t\tthis.log('Too many idle connections, connection disposed.')\n\t\t\t})\n\t\t} else {\n\t\t\tpoolConnection.timerId = setTimeout(async () => {\n\t\t\t\tif (this.removeIdleConnection(poolConnection)) {\n\t\t\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\t\t\tthis.poolStats.connection_disposed_idle_timeout_count++\n\t\t\t\t\tthis.log('Idle connection disposed after timeout.')\n\t\t\t\t}\n\t\t\t}, this.poolConfig.idleTimeoutMs)\n\t\t\tthis.idle.push(poolConnection)\n\t\t\tthis.log('Connection is idle and available.')\n\t\t}\n\t}\n\n\tprivate removeIdleConnection(poolConnection: PoolConnection) {\n\t\tconst index = this.idle.indexOf(poolConnection)\n\t\tif (index > -1) {\n\t\t\tthis.idle.splice(index, 1)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\tprivate async disposeConnection(connection: PoolConnection) {\n\t\tif (connection.disposed) {\n\t\t\tthrow new PoolError('Connection is already disposed')\n\t\t}\n\t\tconnection.disposed = true\n\t\tconst doEnd = async () => {\n\t\t\ttry {\n\t\t\t\tawait connection.client.end()\n\t\t\t} catch (e: any) {\n\t\t\t\tthis.poolConfig.logError(new ClientError(e, 'disposal error'))\n\t\t\t}\n\t\t}\n\t\tawait Promise.race([\n\t\t\tdoEnd(),\n\t\t\tnew Promise(resolve => setTimeout(resolve, 5_000)),\n\t\t])\n\t}\n\n\tprivate log(message: string) {\n\t\tif (!this.poolConfig.log) return\n\t\tconst poolStatus = this.getPoolStatus()\n\t\tthis.poolConfig.log(message, poolStatus)\n\t}\n}\n\nexport { Pool }\n\nexport class PoolError extends DatabaseError {\n}\n\nexport class AcquireTimeoutError extends PoolError {\n\tconstructor(previous: any) {\n\t\tsuper('Failed to acquire a connection' + (previous && 'message' in previous ? `. Last error: ${previous.message}` : ''), previous)\n\t}\n}\n\nexport class PoolClosedError extends PoolError {\n\tconstructor() {\n\t\tsuper('Pool is already closed')\n\t}\n}\n"],"names":["ImplementationException","ClientError","ClientErrorCodes","DatabaseError"],"mappings":";;;;;;;;AAsDO,MAAM,uBAAuB;AAAA,EACnC,0BAA0B;AAAA,EAC1B,8BAA8B;AAAA,EAC9B,oCAAoC;AAAA,EACpC,wBAAwB;AAAA,EACxB,wCAAwC;AAAA,EACxC,oCACC;AAAA,EACD,+BAA+B;AAAA,EAC/B,kCAAkC;AAAA,EAClC,2BAA2B;AAAA,EAC3B,qCAAqC;AAAA,EACrC,+BAA+B;AAAA,EAE/B,mCAAmC;AAAA,EAEnC,mBAAmB;AAAA,EACnB,oBAAoB;AAAA,EACpB,qBAAqB;AAAA,EAErB,4BAA4B;AAAA,EAC5B,0BAA0B;AAAA,EAC1B,iCAAiC;AAAA,EACjC,+BAA+B;AAChC;AAEA,MAAM,eAAe;AAAA,EAMpB,YACiB,QACf;AADe,SAAA,SAAA;AANjB,kBAAA,MAAO,YAAW,KAAA;AAClB,kBAAA,MAAO,QAAO,CAAA;AACd,kBAAA,MAAO,aAAY,KAAK,IAAA,CAAI;AAC5B,kBAAA,MAAO,WAAgD,IAAA;AAAA,EAKvD;AACD;AAEA,MAAM,YAAY;AAAA,EAGjB,YACQ,SACA,QACN;AAFM,SAAA,UAAA;AACA,SAAA,SAAA;AAJR,kBAAA,MAAgB,aAAY,KAAK,IAAA,CAAI;AAAA,EAMrC;AACD;AAEA,MAAM,KAAK;AAAA,EA8DV,YACS,eACR,YACC;AAFO,SAAA,gBAAA;AA1DT,kBAAA,MAAQ,SAAQ,KAAA;AAMhB,kBAAA,MAAQ,mBAAkB,CAAA;AAK1B,kBAAA,MAAQ,oBAAA;AAKR,kBAAA,MAAQ,QAAyB,EAAC;AAKlC,kBAAA,MAAQ,8BAAa,IAAA,CAAoB;AAKzC,kBAAA,MAAQ,SAAuB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AA,MAClB,MAAA;AAAA,MACA,IAAI,QAAQ,CAAA,YAAW,WAAW,SAAS,GAAK,CAAC;AAAA,IAAA,CACjD;AAAA,EACF;AAAA,EAEQ,IAAI,SAAiB;AAC5B,QAAI,CAAC,KAAK,WAAW,IAAK;AAC1B,UAAM,aAAa,KAAK,cAAA;AACxB,SAAK,WAAW,IAAI,SAAS,UAAU;AAAA,EACxC;AACD;AAIO,MAAM,kBAAkBE,OAAAA,cAAc;AAC7C;AAEO,MAAM,4BAA4B,UAAU;AAAA,EAClD,YAAY,UAAe;AAC1B,UAAM,oCAAoC,YAAY,aAAa,WAAW,iBAAiB,SAAS,OAAO,KAAK,KAAK,QAAQ;AAAA,EAClI;AACD;AAEO,MAAM,wBAAwB,UAAU;AAAA,EAC9C,cAAc;AACb,UAAM,wBAAwB;AAAA,EAC/B;AACD;;;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Pool.js","sources":["../../../../../packages/database/src/client/Pool.ts"],"sourcesContent":["import { ImplementationException } from '../exceptions'\nimport { ClientErrorCodes } from './errorCodes'\nimport { EventEmitter } from 'node:events'\nimport { ClientError, DatabaseError } from './errors'\nimport { PgClientFactory } from '../utils'\nimport { PgClient } from './PgClient'\n\nexport type PoolLogger = (message: string, status: PoolStatus) => void\n\nexport type PoolConfig = Partial<PoolConfigInternal> & Pick<PoolConfigInternal, 'logError'>\n\ninterface PoolConfigInternal {\n\t/** maximum number of connections in a pool */\n\tmaxConnections: number\n\t/** maximum number of connections concurrently establishing*/\n\tmaxConnecting: number\n\t/** maximum connection attempts during given period */\n\trateLimitCount: number\n\t/** period for rate limiting */\n\trateLimitPeriodMs: number\n\t/** maximum number of idle connections. when reached, will be disposed immediately */\n\tmaxIdle: number\n\t/** interval between retries of recoverable errors */\n\treconnectIntervalMs: number\n\t/** timeout to dispose idle connections */\n\tidleTimeoutMs: number\n\t/** timeout of pending item waiting for a connection. also used for retries of recoverable errors */\n\tacquireTimeoutMs: number\n\t/** how many times can a single connection be acquired */\n\tmaxUses?: number\n\t/** max age of connection. when reached, connection will be disposed after returning to a pool */\n\tmaxAgeMs?: number\n\t/** internal logging, mainly for debugging and testing */\n\tlog?: PoolLogger\n\t/** logging of out-of-stack errors */\n\tlogError: (error: ClientError) => void\n}\n\nexport type PoolStats = { [K in keyof typeof poolStatsDescription]: number }\n\nexport interface PoolStatus {\n\t/** maximum number of connections in a pool */\n\tmax: number\n\t/** number of items waiting for a connections */\n\tpending: number\n\t/** number of active (acquired) connections */\n\tactive: number\n\t/** number of available idle connections */\n\tidle: number\n\t/** number of currently establishing connections */\n\tconnecting: number\n\tstats: PoolStats\n}\n\nexport const poolStatsDescription = {\n\tconnection_started_count: 'Total number of connection attempts when started.',\n\tconnection_established_count: 'Total number of established connections.',\n\tconnection_recoverable_error_count: 'Number of connections that failed on recoverable error (e.g. 53300) and retry was tried.',\n\tconnection_error_count: 'Number of non-recoverable errors or recoverable errors reaching max attempts.',\n\tconnection_disposed_idle_timeout_count: 'Number of idle connection, that was disposed after configured timeout.',\n\tconnection_disposed_idle_max_count:\n\t\t'Number of idle connections, that was immediately disposed, because maximum number of idle connection was reached.',\n\tconnection_disposed_old_count: 'Number of connections, that was too old after it was released.',\n\tconnection_disposed_manual_count: 'Number of manually disposed connection (e.g. due to exception on given connection).',\n\tconnection_released_count: 'Number of connection returned to the pool.',\n\tconnection_reused_immediately_count: 'Number of connections, that was reused by pending item immediately after it was returned to the pool.',\n\tconnection_reused_later_count: 'Number of idle connections, that was reused later.',\n\n\tconnection_established_idle_count: 'Number of newly established connections, which was not used (e.g. some connection was returned earlier).',\n\n\titem_queued_count: 'Number of queued items requesting a connection.',\n\titem_timeout_count: 'Number of items waiting for connection, which timed out.',\n\titem_rejected_count: 'Number of items rejected with an error.',\n\n\titem_resolved_new_ms_count: 'Number of queued items resolved with newly established connection.',\n\titem_resolved_new_ms_sum: 'Waiting time of queued items, which was resolved with a new connection.',\n\titem_resolved_released_ms_count: 'Number of queued items resolved with released connection.',\n\titem_resolved_released_ms_sum: 'Waiting time of queued items, which was resolved with a released connection.',\n}\n\nclass PoolConnection {\n\tpublic disposed = false\n\tpublic uses = 0\n\tpublic createdAt = Date.now()\n\tpublic timerId: ReturnType<typeof setTimeout> | null = null\n\n\tconstructor(\n\t\tpublic readonly client: PgClient,\n\t) {\n\t}\n}\n\nclass PendingItem {\n\tpublic readonly createdAt = Date.now()\n\n\tconstructor(\n\t\tpublic resolve: (connection: PoolConnection) => void,\n\t\tpublic reject: (error: Error) => void,\n\t) {\n\t}\n}\n\nclass Pool {\n\t/**\n\t * pool was closed by calling end().\n\t * All connection was disposed, and it is not possible to acquire new one\n\t */\n\tprivate ended = false\n\n\t/**\n\t * current count of connection attempts\n\t * also includes timeout between recoverable retries\n\t */\n\tprivate connectingCount = 0\n\n\t/**\n\t * Remaining number of connections per floating period.\n\t */\n\tprivate remainingRateLimit: number\n\n\t/**\n\t * available idle connections\n\t */\n\tprivate idle: PoolConnection[] = []\n\n\t/**\n\t * currently acquired connections\n\t */\n\tprivate active = new Set<PoolConnection>()\n\n\t/**\n\t * items waiting for released or newly established connection\n\t */\n\tprivate queue: PendingItem[] = []\n\n\tprivate poolConfig: PoolConfigInternal\n\n\tprivate poolStats: PoolStats = {\n\t\tconnection_started_count: 0,\n\t\tconnection_established_count: 0,\n\t\tconnection_recoverable_error_count: 0,\n\t\tconnection_error_count: 0,\n\t\tconnection_disposed_idle_timeout_count: 0,\n\t\tconnection_disposed_idle_max_count: 0,\n\t\tconnection_disposed_old_count: 0,\n\t\tconnection_disposed_manual_count: 0,\n\t\tconnection_released_count: 0,\n\t\tconnection_reused_immediately_count: 0,\n\t\tconnection_reused_later_count: 0,\n\t\tconnection_established_idle_count: 0,\n\t\titem_queued_count: 0,\n\t\titem_timeout_count: 0,\n\t\titem_rejected_count: 0,\n\t\titem_resolved_new_ms_count: 0,\n\t\titem_resolved_new_ms_sum: 0,\n\t\titem_resolved_released_ms_count: 0,\n\t\titem_resolved_released_ms_sum: 0,\n\t}\n\n\tprivate lastRecoverableError: {\n\t\terror: any\n\t\ttime: number\n\t} | undefined\n\n\tconstructor(\n\t\tprivate clientFactory: PgClientFactory,\n\t\tpoolConfig: PoolConfig,\n\t) {\n\t\tconst maxConnections = poolConfig.maxConnections ?? 10\n\t\tconst maxConnecting = Math.ceil(maxConnections / 2)\n\t\tthis.poolConfig = {\n\t\t\tmaxConnections,\n\t\t\tmaxConnecting,\n\t\t\tmaxIdle: maxConnections,\n\t\t\trateLimitCount: maxConnecting * 5,\n\t\t\trateLimitPeriodMs: 1000,\n\t\t\tidleTimeoutMs: 10_000,\n\t\t\tacquireTimeoutMs: 10_000,\n\t\t\treconnectIntervalMs: 100,\n\t\t\t...poolConfig,\n\t\t}\n\t\tthis.remainingRateLimit = this.poolConfig.rateLimitCount\n\t}\n\n\tpublic acquire(): Promise<PoolConnection> {\n\t\tif (this.ended) {\n\t\t\tthrow new PoolClosedError()\n\t\t}\n\t\tconst poolConnection = this.idle.pop()\n\t\tif (poolConnection !== undefined) {\n\t\t\tif (poolConnection.timerId) {\n\t\t\t\tclearTimeout(poolConnection.timerId)\n\t\t\t}\n\t\t\tpoolConnection.uses++\n\t\t\tthis.active.add(poolConnection)\n\t\t\tthis.poolStats.connection_reused_later_count++\n\t\t\tthis.log('Item fulfilled with an idle connection.')\n\n\t\t\treturn Promise.resolve(poolConnection)\n\t\t}\n\t\tconst pendingItem = this.createPendingItem()\n\t\tthis.maybeCreateNew()\n\t\treturn pendingItem\n\t}\n\n\tpublic release(poolConnection: PoolConnection): void {\n\t\tif (this.ended) {\n\t\t\treturn\n\t\t}\n\t\tthis.log('Releasing a connection.')\n\t\tif (!this.active.delete(poolConnection)) {\n\t\t\tthrow new ImplementationException('Connection does not belong to this pool.')\n\t\t}\n\t\tif (\n\t\t\t(this.poolConfig.maxUses && poolConnection.uses >= this.poolConfig.maxUses)\n\t\t\t|| (this.poolConfig.maxAgeMs && poolConnection.createdAt + this.poolConfig.maxAgeMs < Date.now())\n\t\t) {\n\t\t\tsetImmediate(async () => {\n\t\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\t\tthis.poolStats.connection_disposed_old_count++\n\t\t\t\tthis.log('Connection has reached max age or usage and was disposed.')\n\t\t\t})\n\t\t\tthis.maybeCreateNew()\n\t\t\treturn\n\t\t}\n\t\tthis.handleAvailableConnection(poolConnection)\n\t}\n\n\tpublic dispose(poolConnection: PoolConnection): void {\n\t\tif (this.ended) {\n\t\t\treturn\n\t\t}\n\t\tthis.poolStats.connection_disposed_manual_count++\n\t\tthis.log('Releasing and disposing a connection.')\n\t\tif (!this.active.delete(poolConnection)) {\n\t\t\tthrow new ImplementationException('Connection does not belong to this pool.')\n\t\t}\n\t\tsetImmediate(async () => {\n\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\tthis.log('Connection errored and was disposed.')\n\t\t})\n\t\tthis.maybeCreateNew()\n\t}\n\n\tpublic async end(): Promise<void> {\n\t\tthis.ended = true\n\t\tthis.queue.forEach(it => it.reject(new PoolClosedError()))\n\t\tthis.queue = []\n\t\tconst allConnections = [...this.idle, ...Array.from(this.active)]\n\t\tawait Promise.allSettled(allConnections.map(it => this.disposeConnection(it)))\n\t\tthis.idle = []\n\t\tthis.active.clear()\n\t}\n\n\tpublic async closeIdle(): Promise<void> {\n\t\tthis.log('Disposing all idle connection on request.')\n\t\tconst idle = this.idle\n\t\tthis.idle = []\n\t\tawait Promise.allSettled(idle.map(it => this.disposeConnection(it)))\n\t}\n\n\tpublic getPoolStatus(): PoolStatus {\n\t\treturn {\n\t\t\tmax: this.poolConfig.maxConnections,\n\t\t\tactive: this.active.size,\n\t\t\tidle: this.idle.length,\n\t\t\tpending: this.queue.length,\n\t\t\tconnecting: this.connectingCount,\n\t\t\tstats: this.poolStats,\n\t\t}\n\t}\n\n\tprivate async maybeCreateNew(): Promise<void> {\n\t\tif (this.ended) {\n\t\t\treturn\n\t\t}\n\t\tif (this.queue.length === 0) {\n\t\t\tthis.log('Not connecting, queue is empty.')\n\t\t\treturn\n\t\t}\n\t\tconst connectingCount = this.connectingCount\n\t\tif (connectingCount >= this.queue.length) {\n\t\t\tthis.log('Not connecting, already establishing connection for all queued items.')\n\t\t\treturn\n\t\t}\n\t\tconst idleCount = this.idle.length\n\t\tif ((this.active.size + idleCount + connectingCount) >= this.poolConfig.maxConnections) {\n\t\t\tthis.log('Not connecting, max connections reached.')\n\t\t\treturn\n\t\t}\n\t\tif (connectingCount >= this.poolConfig.maxConnecting) {\n\t\t\tthis.log('Not connecting, maximum concurrent connection attempts in progress.')\n\t\t\treturn\n\t\t}\n\t\tif (this.remainingRateLimit <= 0) {\n\t\t\tthis.log('Not connecting, rate limit reached.')\n\t\t\treturn\n\t\t}\n\n\t\tthis.log('Creating a new connection')\n\t\tconst client = this.clientFactory()\n\t\tconst poolConnection = new PoolConnection(client)\n\n\t\tclient.on('error', e => {\n\t\t\tthis.log('Client error on idle connection has occurred: ' + e.message)\n\t\t\tthis.poolConfig.logError(new ClientError(e, 'runtime error'))\n\t\t\tthis.poolStats.connection_error_count++\n\n\t\t\tif (!this.active.has(poolConnection)) {\n\t\t\t\tthis.removeIdleConnection(poolConnection)\n\t\t\t\tthis.disposeConnection(poolConnection)\n\t\t\t}\n\t\t})\n\n\t\ttry {\n\t\t\tthis.connectingCount++\n\t\t\tthis.remainingRateLimit--\n\t\t\tthis.poolStats.connection_started_count++\n\n\t\t\tawait client.connect()\n\n\t\t\tthis.poolStats.connection_established_count++\n\t\t\tthis.connectingCount--\n\n\t\t\tthis.log('Connection established')\n\n\t\t\tif (this.ended) {\n\t\t\t\treturn this.disposeConnection(poolConnection)\n\t\t\t}\n\n\t\t\tthis.handleAvailableConnection(poolConnection)\n\t\t\tthis.maybeCreateNew()\n\t\t} catch (e: any) {\n\t\t\tthis.log('Connection error occurred: ' + e.message)\n\t\t\tthis.disposeConnection(poolConnection)\n\n\t\t\tif (\n\t\t\t\te.code === ClientErrorCodes.TOO_MANY_CONNECTIONS\n\t\t\t\t|| e.code === ClientErrorCodes.CANNOT_CONNECT_NOW // server starting\n\t\t\t\t|| e.message === 'timeout expired' // https://github.com/brianc/node-postgres/blob/c7dc621d3fb52c158eb23aa31dea6bd440700a4a/packages/pg/lib/client.js#L105\n\t\t\t\t|| e.code === 'ETIMEDOUT'\n\t\t\t) {\n\t\t\t\tthis.lastRecoverableError = { error: e, time: Date.now() }\n\t\t\t\tthis.poolStats.connection_recoverable_error_count++\n\t\t\t\tthis.log('Recoverable error, retrying in a moment.')\n\t\t\t\tthis.poolConfig.logError(new ClientError(e, 'recoverable connection error'))\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis.connectingCount--\n\t\t\t\t\tthis.log('Retrying')\n\t\t\t\t\tthis.maybeCreateNew()\n\t\t\t\t}, this.poolConfig.reconnectIntervalMs)\n\t\t\t} else {\n\t\t\t\tthis.poolStats.connection_error_count++\n\t\t\t\tthis.connectingCount--\n\t\t\t\tconst clientError = new ClientError(e, 'connection error')\n\t\t\t\tif (this.active.size === 0 && this.queue.length > 0) {\n\t\t\t\t\tconst pendingItem = this.queue.shift()\n\t\t\t\t\tif (!pendingItem) throw new Error()\n\t\t\t\t\tthis.log('Connecting failed, rejecting pending item')\n\t\t\t\t\tpendingItem.reject(clientError)\n\t\t\t\t\tthis.poolStats.item_rejected_count++\n\t\t\t\t} else {\n\t\t\t\t\tthis.log('Connecting failed, emitting error')\n\t\t\t\t\tthis.poolConfig.logError(clientError)\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tsetTimeout(() => {\n\t\t\t\tif (this.remainingRateLimit === 0) {\n\t\t\t\t\tthis.log('Rate limit renewed.')\n\t\t\t\t}\n\t\t\t\tthis.remainingRateLimit++\n\t\t\t\tthis.maybeCreateNew()\n\t\t\t}, this.poolConfig.rateLimitPeriodMs)\n\t\t}\n\t}\n\n\tprivate createPendingItem(): Promise<PoolConnection> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tconst acquireTimeoutError = new AcquireTimeoutError(\n\t\t\t\t\tthis.lastRecoverableError && this.lastRecoverableError.time > item.createdAt\n\t\t\t\t\t\t? this.lastRecoverableError.error\n\t\t\t\t\t\t: undefined,\n\t\t\t\t)\n\t\t\t\titem.reject(acquireTimeoutError)\n\t\t\t\tconst index = this.queue.indexOf(item)\n\t\t\t\tif (index > -1) {\n\t\t\t\t\tthis.queue.splice(index, 1)\n\t\t\t\t}\n\t\t\t\tthis.poolStats.item_timeout_count++\n\t\t\t\tthis.log('Queued item timed out')\n\t\t\t}, this.poolConfig.acquireTimeoutMs)\n\n\t\t\tconst item = new PendingItem(it => {\n\t\t\t\tconst duration = Date.now() - item.createdAt\n\t\t\t\tconst isNew = it.uses === 0\n\t\t\t\tthis.log(`Queued item fulfilled with ${!isNew ? 'released' : 'new'} connection.`)\n\n\t\t\t\tif (isNew) {\n\t\t\t\t\tthis.poolStats.item_resolved_new_ms_count++\n\t\t\t\t\tthis.poolStats.item_resolved_new_ms_sum += duration\n\t\t\t\t} else {\n\t\t\t\t\tthis.poolStats.item_resolved_released_ms_count++\n\t\t\t\t\tthis.poolStats.item_resolved_released_ms_sum += duration\n\t\t\t\t}\n\t\t\t\tclearTimeout(timeout)\n\t\t\t\tresolve(it)\n\t\t\t}, it => {\n\t\t\t\tclearTimeout(timeout)\n\t\t\t\treject(it)\n\t\t\t})\n\n\t\t\tthis.poolStats.item_queued_count++\n\t\t\tthis.queue.push(item)\n\t\t\tthis.log(`Item added to a queue.`)\n\t\t})\n\t}\n\n\tprivate handleAvailableConnection(poolConnection: PoolConnection) {\n\t\tconst item = this.queue.shift()\n\t\tconst isNew = poolConnection.uses === 0\n\t\tif (!isNew) {\n\t\t\tthis.poolStats.connection_released_count++\n\t\t}\n\t\tif (item) {\n\t\t\tthis.active.add(poolConnection)\n\t\t\titem.resolve(poolConnection)\n\t\t\tif (!isNew) {\n\t\t\t\tthis.poolStats.connection_reused_immediately_count++\n\t\t\t}\n\t\t\tpoolConnection.uses++\n\t\t\treturn\n\t\t}\n\t\tif (isNew) {\n\t\t\tthis.poolStats.connection_established_idle_count++\n\t\t}\n\t\tif (this.idle.length >= this.poolConfig.maxIdle) {\n\t\t\tsetImmediate(async () => {\n\t\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\t\tthis.poolStats.connection_disposed_idle_max_count++\n\t\t\t\tthis.log('Too many idle connections, connection disposed.')\n\t\t\t})\n\t\t} else {\n\t\t\tpoolConnection.timerId = setTimeout(async () => {\n\t\t\t\tif (this.removeIdleConnection(poolConnection)) {\n\t\t\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\t\t\tthis.poolStats.connection_disposed_idle_timeout_count++\n\t\t\t\t\tthis.log('Idle connection disposed after timeout.')\n\t\t\t\t}\n\t\t\t}, this.poolConfig.idleTimeoutMs)\n\t\t\tthis.idle.push(poolConnection)\n\t\t\tthis.log('Connection is idle and available.')\n\t\t}\n\t}\n\n\tprivate removeIdleConnection(poolConnection: PoolConnection) {\n\t\tconst index = this.idle.indexOf(poolConnection)\n\t\tif (index > -1) {\n\t\t\tthis.idle.splice(index, 1)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\tprivate async disposeConnection(connection: PoolConnection) {\n\t\tif (connection.disposed) {\n\t\t\tthrow new PoolError('Connection is already disposed')\n\t\t}\n\t\tconnection.disposed = true\n\t\tconst doEnd = async () => {\n\t\t\ttry {\n\t\t\t\tawait connection.client.end()\n\t\t\t} catch (e: any) {\n\t\t\t\tthis.poolConfig.logError(new ClientError(e, 'disposal error'))\n\t\t\t}\n\t\t}\n\t\tawait Promise.race([\n\t\t\tdoEnd(),\n\t\t\tnew Promise(resolve => setTimeout(resolve, 5_000)),\n\t\t])\n\t}\n\n\tprivate log(message: string) {\n\t\tif (!this.poolConfig.log) return\n\t\tconst poolStatus = this.getPoolStatus()\n\t\tthis.poolConfig.log(message, poolStatus)\n\t}\n}\n\nexport { Pool }\n\nexport class PoolError extends DatabaseError {\n}\n\nexport class AcquireTimeoutError extends PoolError {\n\tconstructor(previous: any) {\n\t\tsuper('Failed to acquire a connection' + (previous && 'message' in previous ? `. Last error: ${previous.message}` : ''), previous)\n\t}\n}\n\nexport class PoolClosedError extends PoolError {\n\tconstructor() {\n\t\tsuper('Pool is already closed')\n\t}\n}\n"],"names":[],"mappings":";;;;;;AAsDO,MAAM,uBAAuB;AAAA,EACnC,0BAA0B;AAAA,EAC1B,8BAA8B;AAAA,EAC9B,oCAAoC;AAAA,EACpC,wBAAwB;AAAA,EACxB,wCAAwC;AAAA,EACxC,oCACC;AAAA,EACD,+BAA+B;AAAA,EAC/B,kCAAkC;AAAA,EAClC,2BAA2B;AAAA,EAC3B,qCAAqC;AAAA,EACrC,+BAA+B;AAAA,EAE/B,mCAAmC;AAAA,EAEnC,mBAAmB;AAAA,EACnB,oBAAoB;AAAA,EACpB,qBAAqB;AAAA,EAErB,4BAA4B;AAAA,EAC5B,0BAA0B;AAAA,EAC1B,iCAAiC;AAAA,EACjC,+BAA+B;AAChC;AAEA,MAAM,eAAe;AAAA,EAMpB,YACiB,QACf;AADe,SAAA,SAAA;AANjB,kBAAA,MAAO,YAAW,KAAA;AAClB,kBAAA,MAAO,QAAO,CAAA;AACd,kBAAA,MAAO,aAAY,KAAK,IAAA,CAAI;AAC5B,kBAAA,MAAO,WAAgD,IAAA;AAAA,EAKvD;AACD;AAEA,MAAM,YAAY;AAAA,EAGjB,YACQ,SACA,QACN;AAFM,SAAA,UAAA;AACA,SAAA,SAAA;AAJR,kBAAA,MAAgB,aAAY,KAAK,IAAA,CAAI;AAAA,EAMrC;AACD;AAEA,MAAM,KAAK;AAAA,EA8DV,YACS,eACR,YACC;AAFO,SAAA,gBAAA;AA1DT,kBAAA,MAAQ,SAAQ,KAAA;AAMhB,kBAAA,MAAQ,mBAAkB,CAAA;AAK1B,kBAAA,MAAQ,oBAAA;AAKR,kBAAA,MAAQ,QAAyB,EAAC;AAKlC,kBAAA,MAAQ,8BAAa,IAAA,CAAoB;AAKzC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Q,CAAA,YAAW,WAAW,SAAS,GAAK,CAAC;AAAA,IAAA,CACjD;AAAA,EACF;AAAA,EAEQ,IAAI,SAAiB;AAC5B,QAAI,CAAC,KAAK,WAAW,IAAK;AAC1B,UAAM,aAAa,KAAK,cAAA;AACxB,SAAK,WAAW,IAAI,SAAS,UAAU;AAAA,EACxC;AACD;AAIO,MAAM,kBAAkB,cAAc;AAC7C;AAEO,MAAM,4BAA4B,UAAU;AAAA,EAClD,YAAY,UAAe;AAC1B,UAAM,oCAAoC,YAAY,aAAa,WAAW,iBAAiB,SAAS,OAAO,KAAK,KAAK,QAAQ;AAAA,EAClI;AACD;AAEO,MAAM,wBAAwB,UAAU;AAAA,EAC9C,cAAc;AACb,UAAM,wBAAwB;AAAA,EAC/B;AACD;"}
|
|
1
|
+
{"version":3,"file":"Pool.js","sources":["../../../../../packages/database/src/client/Pool.ts"],"sourcesContent":["import { ImplementationException } from '../exceptions.js'\nimport { ClientErrorCodes } from './errorCodes.js'\nimport { EventEmitter } from 'node:events'\nimport { ClientError, DatabaseError } from './errors.js'\nimport { PgClientFactory } from '../utils/index.js'\nimport { PgClient } from './PgClient.js'\n\nexport type PoolLogger = (message: string, status: PoolStatus) => void\n\nexport type PoolConfig = Partial<PoolConfigInternal> & Pick<PoolConfigInternal, 'logError'>\n\ninterface PoolConfigInternal {\n\t/** maximum number of connections in a pool */\n\tmaxConnections: number\n\t/** maximum number of connections concurrently establishing*/\n\tmaxConnecting: number\n\t/** maximum connection attempts during given period */\n\trateLimitCount: number\n\t/** period for rate limiting */\n\trateLimitPeriodMs: number\n\t/** maximum number of idle connections. when reached, will be disposed immediately */\n\tmaxIdle: number\n\t/** interval between retries of recoverable errors */\n\treconnectIntervalMs: number\n\t/** timeout to dispose idle connections */\n\tidleTimeoutMs: number\n\t/** timeout of pending item waiting for a connection. also used for retries of recoverable errors */\n\tacquireTimeoutMs: number\n\t/** how many times can a single connection be acquired */\n\tmaxUses?: number\n\t/** max age of connection. when reached, connection will be disposed after returning to a pool */\n\tmaxAgeMs?: number\n\t/** internal logging, mainly for debugging and testing */\n\tlog?: PoolLogger\n\t/** logging of out-of-stack errors */\n\tlogError: (error: ClientError) => void\n}\n\nexport type PoolStats = { [K in keyof typeof poolStatsDescription]: number }\n\nexport interface PoolStatus {\n\t/** maximum number of connections in a pool */\n\tmax: number\n\t/** number of items waiting for a connections */\n\tpending: number\n\t/** number of active (acquired) connections */\n\tactive: number\n\t/** number of available idle connections */\n\tidle: number\n\t/** number of currently establishing connections */\n\tconnecting: number\n\tstats: PoolStats\n}\n\nexport const poolStatsDescription = {\n\tconnection_started_count: 'Total number of connection attempts when started.',\n\tconnection_established_count: 'Total number of established connections.',\n\tconnection_recoverable_error_count: 'Number of connections that failed on recoverable error (e.g. 53300) and retry was tried.',\n\tconnection_error_count: 'Number of non-recoverable errors or recoverable errors reaching max attempts.',\n\tconnection_disposed_idle_timeout_count: 'Number of idle connection, that was disposed after configured timeout.',\n\tconnection_disposed_idle_max_count:\n\t\t'Number of idle connections, that was immediately disposed, because maximum number of idle connection was reached.',\n\tconnection_disposed_old_count: 'Number of connections, that was too old after it was released.',\n\tconnection_disposed_manual_count: 'Number of manually disposed connection (e.g. due to exception on given connection).',\n\tconnection_released_count: 'Number of connection returned to the pool.',\n\tconnection_reused_immediately_count: 'Number of connections, that was reused by pending item immediately after it was returned to the pool.',\n\tconnection_reused_later_count: 'Number of idle connections, that was reused later.',\n\n\tconnection_established_idle_count: 'Number of newly established connections, which was not used (e.g. some connection was returned earlier).',\n\n\titem_queued_count: 'Number of queued items requesting a connection.',\n\titem_timeout_count: 'Number of items waiting for connection, which timed out.',\n\titem_rejected_count: 'Number of items rejected with an error.',\n\n\titem_resolved_new_ms_count: 'Number of queued items resolved with newly established connection.',\n\titem_resolved_new_ms_sum: 'Waiting time of queued items, which was resolved with a new connection.',\n\titem_resolved_released_ms_count: 'Number of queued items resolved with released connection.',\n\titem_resolved_released_ms_sum: 'Waiting time of queued items, which was resolved with a released connection.',\n}\n\nclass PoolConnection {\n\tpublic disposed = false\n\tpublic uses = 0\n\tpublic createdAt = Date.now()\n\tpublic timerId: ReturnType<typeof setTimeout> | null = null\n\n\tconstructor(\n\t\tpublic readonly client: PgClient,\n\t) {\n\t}\n}\n\nclass PendingItem {\n\tpublic readonly createdAt = Date.now()\n\n\tconstructor(\n\t\tpublic resolve: (connection: PoolConnection) => void,\n\t\tpublic reject: (error: Error) => void,\n\t) {\n\t}\n}\n\nclass Pool {\n\t/**\n\t * pool was closed by calling end().\n\t * All connection was disposed, and it is not possible to acquire new one\n\t */\n\tprivate ended = false\n\n\t/**\n\t * current count of connection attempts\n\t * also includes timeout between recoverable retries\n\t */\n\tprivate connectingCount = 0\n\n\t/**\n\t * Remaining number of connections per floating period.\n\t */\n\tprivate remainingRateLimit: number\n\n\t/**\n\t * available idle connections\n\t */\n\tprivate idle: PoolConnection[] = []\n\n\t/**\n\t * currently acquired connections\n\t */\n\tprivate active = new Set<PoolConnection>()\n\n\t/**\n\t * items waiting for released or newly established connection\n\t */\n\tprivate queue: PendingItem[] = []\n\n\tprivate poolConfig: PoolConfigInternal\n\n\tprivate poolStats: PoolStats = {\n\t\tconnection_started_count: 0,\n\t\tconnection_established_count: 0,\n\t\tconnection_recoverable_error_count: 0,\n\t\tconnection_error_count: 0,\n\t\tconnection_disposed_idle_timeout_count: 0,\n\t\tconnection_disposed_idle_max_count: 0,\n\t\tconnection_disposed_old_count: 0,\n\t\tconnection_disposed_manual_count: 0,\n\t\tconnection_released_count: 0,\n\t\tconnection_reused_immediately_count: 0,\n\t\tconnection_reused_later_count: 0,\n\t\tconnection_established_idle_count: 0,\n\t\titem_queued_count: 0,\n\t\titem_timeout_count: 0,\n\t\titem_rejected_count: 0,\n\t\titem_resolved_new_ms_count: 0,\n\t\titem_resolved_new_ms_sum: 0,\n\t\titem_resolved_released_ms_count: 0,\n\t\titem_resolved_released_ms_sum: 0,\n\t}\n\n\tprivate lastRecoverableError: {\n\t\terror: any\n\t\ttime: number\n\t} | undefined\n\n\tconstructor(\n\t\tprivate clientFactory: PgClientFactory,\n\t\tpoolConfig: PoolConfig,\n\t) {\n\t\tconst maxConnections = poolConfig.maxConnections ?? 10\n\t\tconst maxConnecting = Math.ceil(maxConnections / 2)\n\t\tthis.poolConfig = {\n\t\t\tmaxConnections,\n\t\t\tmaxConnecting,\n\t\t\tmaxIdle: maxConnections,\n\t\t\trateLimitCount: maxConnecting * 5,\n\t\t\trateLimitPeriodMs: 1000,\n\t\t\tidleTimeoutMs: 10_000,\n\t\t\tacquireTimeoutMs: 10_000,\n\t\t\treconnectIntervalMs: 100,\n\t\t\t...poolConfig,\n\t\t}\n\t\tthis.remainingRateLimit = this.poolConfig.rateLimitCount\n\t}\n\n\tpublic acquire(): Promise<PoolConnection> {\n\t\tif (this.ended) {\n\t\t\tthrow new PoolClosedError()\n\t\t}\n\t\tconst poolConnection = this.idle.pop()\n\t\tif (poolConnection !== undefined) {\n\t\t\tif (poolConnection.timerId) {\n\t\t\t\tclearTimeout(poolConnection.timerId)\n\t\t\t}\n\t\t\tpoolConnection.uses++\n\t\t\tthis.active.add(poolConnection)\n\t\t\tthis.poolStats.connection_reused_later_count++\n\t\t\tthis.log('Item fulfilled with an idle connection.')\n\n\t\t\treturn Promise.resolve(poolConnection)\n\t\t}\n\t\tconst pendingItem = this.createPendingItem()\n\t\tthis.maybeCreateNew()\n\t\treturn pendingItem\n\t}\n\n\tpublic release(poolConnection: PoolConnection): void {\n\t\tif (this.ended) {\n\t\t\treturn\n\t\t}\n\t\tthis.log('Releasing a connection.')\n\t\tif (!this.active.delete(poolConnection)) {\n\t\t\tthrow new ImplementationException('Connection does not belong to this pool.')\n\t\t}\n\t\tif (\n\t\t\t(this.poolConfig.maxUses && poolConnection.uses >= this.poolConfig.maxUses)\n\t\t\t|| (this.poolConfig.maxAgeMs && poolConnection.createdAt + this.poolConfig.maxAgeMs < Date.now())\n\t\t) {\n\t\t\tsetImmediate(async () => {\n\t\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\t\tthis.poolStats.connection_disposed_old_count++\n\t\t\t\tthis.log('Connection has reached max age or usage and was disposed.')\n\t\t\t})\n\t\t\tthis.maybeCreateNew()\n\t\t\treturn\n\t\t}\n\t\tthis.handleAvailableConnection(poolConnection)\n\t}\n\n\tpublic dispose(poolConnection: PoolConnection): void {\n\t\tif (this.ended) {\n\t\t\treturn\n\t\t}\n\t\tthis.poolStats.connection_disposed_manual_count++\n\t\tthis.log('Releasing and disposing a connection.')\n\t\tif (!this.active.delete(poolConnection)) {\n\t\t\tthrow new ImplementationException('Connection does not belong to this pool.')\n\t\t}\n\t\tsetImmediate(async () => {\n\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\tthis.log('Connection errored and was disposed.')\n\t\t})\n\t\tthis.maybeCreateNew()\n\t}\n\n\tpublic async end(): Promise<void> {\n\t\tthis.ended = true\n\t\tthis.queue.forEach(it => it.reject(new PoolClosedError()))\n\t\tthis.queue = []\n\t\tconst allConnections = [...this.idle, ...Array.from(this.active)]\n\t\tawait Promise.allSettled(allConnections.map(it => this.disposeConnection(it)))\n\t\tthis.idle = []\n\t\tthis.active.clear()\n\t}\n\n\tpublic async closeIdle(): Promise<void> {\n\t\tthis.log('Disposing all idle connection on request.')\n\t\tconst idle = this.idle\n\t\tthis.idle = []\n\t\tawait Promise.allSettled(idle.map(it => this.disposeConnection(it)))\n\t}\n\n\tpublic getPoolStatus(): PoolStatus {\n\t\treturn {\n\t\t\tmax: this.poolConfig.maxConnections,\n\t\t\tactive: this.active.size,\n\t\t\tidle: this.idle.length,\n\t\t\tpending: this.queue.length,\n\t\t\tconnecting: this.connectingCount,\n\t\t\tstats: this.poolStats,\n\t\t}\n\t}\n\n\tprivate async maybeCreateNew(): Promise<void> {\n\t\tif (this.ended) {\n\t\t\treturn\n\t\t}\n\t\tif (this.queue.length === 0) {\n\t\t\tthis.log('Not connecting, queue is empty.')\n\t\t\treturn\n\t\t}\n\t\tconst connectingCount = this.connectingCount\n\t\tif (connectingCount >= this.queue.length) {\n\t\t\tthis.log('Not connecting, already establishing connection for all queued items.')\n\t\t\treturn\n\t\t}\n\t\tconst idleCount = this.idle.length\n\t\tif ((this.active.size + idleCount + connectingCount) >= this.poolConfig.maxConnections) {\n\t\t\tthis.log('Not connecting, max connections reached.')\n\t\t\treturn\n\t\t}\n\t\tif (connectingCount >= this.poolConfig.maxConnecting) {\n\t\t\tthis.log('Not connecting, maximum concurrent connection attempts in progress.')\n\t\t\treturn\n\t\t}\n\t\tif (this.remainingRateLimit <= 0) {\n\t\t\tthis.log('Not connecting, rate limit reached.')\n\t\t\treturn\n\t\t}\n\n\t\tthis.log('Creating a new connection')\n\t\tconst client = this.clientFactory()\n\t\tconst poolConnection = new PoolConnection(client)\n\n\t\tclient.on('error', e => {\n\t\t\tthis.log('Client error on idle connection has occurred: ' + e.message)\n\t\t\tthis.poolConfig.logError(new ClientError(e, 'runtime error'))\n\t\t\tthis.poolStats.connection_error_count++\n\n\t\t\tif (!this.active.has(poolConnection)) {\n\t\t\t\tthis.removeIdleConnection(poolConnection)\n\t\t\t\tthis.disposeConnection(poolConnection)\n\t\t\t}\n\t\t})\n\n\t\ttry {\n\t\t\tthis.connectingCount++\n\t\t\tthis.remainingRateLimit--\n\t\t\tthis.poolStats.connection_started_count++\n\n\t\t\tawait client.connect()\n\n\t\t\tthis.poolStats.connection_established_count++\n\t\t\tthis.connectingCount--\n\n\t\t\tthis.log('Connection established')\n\n\t\t\tif (this.ended) {\n\t\t\t\treturn this.disposeConnection(poolConnection)\n\t\t\t}\n\n\t\t\tthis.handleAvailableConnection(poolConnection)\n\t\t\tthis.maybeCreateNew()\n\t\t} catch (e: any) {\n\t\t\tthis.log('Connection error occurred: ' + e.message)\n\t\t\tthis.disposeConnection(poolConnection)\n\n\t\t\tif (\n\t\t\t\te.code === ClientErrorCodes.TOO_MANY_CONNECTIONS\n\t\t\t\t|| e.code === ClientErrorCodes.CANNOT_CONNECT_NOW // server starting\n\t\t\t\t|| e.message === 'timeout expired' // https://github.com/brianc/node-postgres/blob/c7dc621d3fb52c158eb23aa31dea6bd440700a4a/packages/pg/lib/client.js#L105\n\t\t\t\t|| e.code === 'ETIMEDOUT'\n\t\t\t) {\n\t\t\t\tthis.lastRecoverableError = { error: e, time: Date.now() }\n\t\t\t\tthis.poolStats.connection_recoverable_error_count++\n\t\t\t\tthis.log('Recoverable error, retrying in a moment.')\n\t\t\t\tthis.poolConfig.logError(new ClientError(e, 'recoverable connection error'))\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis.connectingCount--\n\t\t\t\t\tthis.log('Retrying')\n\t\t\t\t\tthis.maybeCreateNew()\n\t\t\t\t}, this.poolConfig.reconnectIntervalMs)\n\t\t\t} else {\n\t\t\t\tthis.poolStats.connection_error_count++\n\t\t\t\tthis.connectingCount--\n\t\t\t\tconst clientError = new ClientError(e, 'connection error')\n\t\t\t\tif (this.active.size === 0 && this.queue.length > 0) {\n\t\t\t\t\tconst pendingItem = this.queue.shift()\n\t\t\t\t\tif (!pendingItem) throw new Error()\n\t\t\t\t\tthis.log('Connecting failed, rejecting pending item')\n\t\t\t\t\tpendingItem.reject(clientError)\n\t\t\t\t\tthis.poolStats.item_rejected_count++\n\t\t\t\t} else {\n\t\t\t\t\tthis.log('Connecting failed, emitting error')\n\t\t\t\t\tthis.poolConfig.logError(clientError)\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tsetTimeout(() => {\n\t\t\t\tif (this.remainingRateLimit === 0) {\n\t\t\t\t\tthis.log('Rate limit renewed.')\n\t\t\t\t}\n\t\t\t\tthis.remainingRateLimit++\n\t\t\t\tthis.maybeCreateNew()\n\t\t\t}, this.poolConfig.rateLimitPeriodMs)\n\t\t}\n\t}\n\n\tprivate createPendingItem(): Promise<PoolConnection> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tconst acquireTimeoutError = new AcquireTimeoutError(\n\t\t\t\t\tthis.lastRecoverableError && this.lastRecoverableError.time > item.createdAt\n\t\t\t\t\t\t? this.lastRecoverableError.error\n\t\t\t\t\t\t: undefined,\n\t\t\t\t)\n\t\t\t\titem.reject(acquireTimeoutError)\n\t\t\t\tconst index = this.queue.indexOf(item)\n\t\t\t\tif (index > -1) {\n\t\t\t\t\tthis.queue.splice(index, 1)\n\t\t\t\t}\n\t\t\t\tthis.poolStats.item_timeout_count++\n\t\t\t\tthis.log('Queued item timed out')\n\t\t\t}, this.poolConfig.acquireTimeoutMs)\n\n\t\t\tconst item = new PendingItem(it => {\n\t\t\t\tconst duration = Date.now() - item.createdAt\n\t\t\t\tconst isNew = it.uses === 0\n\t\t\t\tthis.log(`Queued item fulfilled with ${!isNew ? 'released' : 'new'} connection.`)\n\n\t\t\t\tif (isNew) {\n\t\t\t\t\tthis.poolStats.item_resolved_new_ms_count++\n\t\t\t\t\tthis.poolStats.item_resolved_new_ms_sum += duration\n\t\t\t\t} else {\n\t\t\t\t\tthis.poolStats.item_resolved_released_ms_count++\n\t\t\t\t\tthis.poolStats.item_resolved_released_ms_sum += duration\n\t\t\t\t}\n\t\t\t\tclearTimeout(timeout)\n\t\t\t\tresolve(it)\n\t\t\t}, it => {\n\t\t\t\tclearTimeout(timeout)\n\t\t\t\treject(it)\n\t\t\t})\n\n\t\t\tthis.poolStats.item_queued_count++\n\t\t\tthis.queue.push(item)\n\t\t\tthis.log(`Item added to a queue.`)\n\t\t})\n\t}\n\n\tprivate handleAvailableConnection(poolConnection: PoolConnection) {\n\t\tconst item = this.queue.shift()\n\t\tconst isNew = poolConnection.uses === 0\n\t\tif (!isNew) {\n\t\t\tthis.poolStats.connection_released_count++\n\t\t}\n\t\tif (item) {\n\t\t\tthis.active.add(poolConnection)\n\t\t\titem.resolve(poolConnection)\n\t\t\tif (!isNew) {\n\t\t\t\tthis.poolStats.connection_reused_immediately_count++\n\t\t\t}\n\t\t\tpoolConnection.uses++\n\t\t\treturn\n\t\t}\n\t\tif (isNew) {\n\t\t\tthis.poolStats.connection_established_idle_count++\n\t\t}\n\t\tif (this.idle.length >= this.poolConfig.maxIdle) {\n\t\t\tsetImmediate(async () => {\n\t\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\t\tthis.poolStats.connection_disposed_idle_max_count++\n\t\t\t\tthis.log('Too many idle connections, connection disposed.')\n\t\t\t})\n\t\t} else {\n\t\t\tpoolConnection.timerId = setTimeout(async () => {\n\t\t\t\tif (this.removeIdleConnection(poolConnection)) {\n\t\t\t\t\tawait this.disposeConnection(poolConnection)\n\t\t\t\t\tthis.poolStats.connection_disposed_idle_timeout_count++\n\t\t\t\t\tthis.log('Idle connection disposed after timeout.')\n\t\t\t\t}\n\t\t\t}, this.poolConfig.idleTimeoutMs)\n\t\t\tthis.idle.push(poolConnection)\n\t\t\tthis.log('Connection is idle and available.')\n\t\t}\n\t}\n\n\tprivate removeIdleConnection(poolConnection: PoolConnection) {\n\t\tconst index = this.idle.indexOf(poolConnection)\n\t\tif (index > -1) {\n\t\t\tthis.idle.splice(index, 1)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\tprivate async disposeConnection(connection: PoolConnection) {\n\t\tif (connection.disposed) {\n\t\t\tthrow new PoolError('Connection is already disposed')\n\t\t}\n\t\tconnection.disposed = true\n\t\tconst doEnd = async () => {\n\t\t\ttry {\n\t\t\t\tawait connection.client.end()\n\t\t\t} catch (e: any) {\n\t\t\t\tthis.poolConfig.logError(new ClientError(e, 'disposal error'))\n\t\t\t}\n\t\t}\n\t\tawait Promise.race([\n\t\t\tdoEnd(),\n\t\t\tnew Promise(resolve => setTimeout(resolve, 5_000)),\n\t\t])\n\t}\n\n\tprivate log(message: string) {\n\t\tif (!this.poolConfig.log) return\n\t\tconst poolStatus = this.getPoolStatus()\n\t\tthis.poolConfig.log(message, poolStatus)\n\t}\n}\n\nexport { Pool }\n\nexport class PoolError extends DatabaseError {\n}\n\nexport class AcquireTimeoutError extends PoolError {\n\tconstructor(previous: any) {\n\t\tsuper('Failed to acquire a connection' + (previous && 'message' in previous ? `. Last error: ${previous.message}` : ''), previous)\n\t}\n}\n\nexport class PoolClosedError extends PoolError {\n\tconstructor() {\n\t\tsuper('Pool is already closed')\n\t}\n}\n"],"names":[],"mappings":";;;;;;AAsDO,MAAM,uBAAuB;AAAA,EACnC,0BAA0B;AAAA,EAC1B,8BAA8B;AAAA,EAC9B,oCAAoC;AAAA,EACpC,wBAAwB;AAAA,EACxB,wCAAwC;AAAA,EACxC,oCACC;AAAA,EACD,+BAA+B;AAAA,EAC/B,kCAAkC;AAAA,EAClC,2BAA2B;AAAA,EAC3B,qCAAqC;AAAA,EACrC,+BAA+B;AAAA,EAE/B,mCAAmC;AAAA,EAEnC,mBAAmB;AAAA,EACnB,oBAAoB;AAAA,EACpB,qBAAqB;AAAA,EAErB,4BAA4B;AAAA,EAC5B,0BAA0B;AAAA,EAC1B,iCAAiC;AAAA,EACjC,+BAA+B;AAChC;AAEA,MAAM,eAAe;AAAA,EAMpB,YACiB,QACf;AADe,SAAA,SAAA;AANjB,kBAAA,MAAO,YAAW,KAAA;AAClB,kBAAA,MAAO,QAAO,CAAA;AACd,kBAAA,MAAO,aAAY,KAAK,IAAA,CAAI;AAC5B,kBAAA,MAAO,WAAgD,IAAA;AAAA,EAKvD;AACD;AAEA,MAAM,YAAY;AAAA,EAGjB,YACQ,SACA,QACN;AAFM,SAAA,UAAA;AACA,SAAA,SAAA;AAJR,kBAAA,MAAgB,aAAY,KAAK,IAAA,CAAI;AAAA,EAMrC;AACD;AAEA,MAAM,KAAK;AAAA,EA8DV,YACS,eACR,YACC;AAFO,SAAA,gBAAA;AA1DT,kBAAA,MAAQ,SAAQ,KAAA;AAMhB,kBAAA,MAAQ,mBAAkB,CAAA;AAK1B,kBAAA,MAAQ,oBAAA;AAKR,kBAAA,MAAQ,QAAyB,EAAC;AAKlC,kBAAA,MAAQ,8BAAa,IAAA,CAAoB;AAKzC,kBAAA,MAAQ,SAAuB,EAAC;AAEhC,kBAAA,MAAQ,YAAA;A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AAAA,EACF;AAAA,EAEQ,IAAI,SAAiB;AAC5B,QAAI,CAAC,KAAK,WAAW,IAAK;AAC1B,UAAM,aAAa,KAAK,cAAA;AACxB,SAAK,WAAW,IAAI,SAAS,UAAU;AAAA,EACxC;AACD;AAIO,MAAM,kBAAkB,cAAc;AAC7C;AAEO,MAAM,4BAA4B,UAAU;AAAA,EAClD,YAAY,UAAe;AAC1B,UAAM,oCAAoC,YAAY,aAAa,WAAW,iBAAiB,SAAS,OAAO,KAAK,KAAK,QAAQ;AAAA,EAClI;AACD;AAEO,MAAM,wBAAwB,UAAU;AAAA,EAC9C,cAAc;AACb,UAAM,wBAAwB;AAAA,EAC/B;AACD;"}
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const node_buffer = require("node:buffer");
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
6
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
7
|
+
const rowCompletionOverheadBytes = 256;
|
|
8
|
+
const maximumRecursiveEstimateDepth = 64;
|
|
9
|
+
const isBun = process.versions.bun !== void 0;
|
|
10
|
+
const validateRequestMemoryBudgetOptions = ({ warnBytes, maxBytes }) => {
|
|
11
|
+
if (!Number.isSafeInteger(warnBytes) || warnBytes <= 0) {
|
|
12
|
+
return "warnBytes must be a positive safe integer";
|
|
13
|
+
}
|
|
14
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {
|
|
15
|
+
return "maxBytes must be a positive safe integer";
|
|
16
|
+
}
|
|
17
|
+
if (warnBytes > maxBytes) {
|
|
18
|
+
return "warnBytes must not exceed maxBytes";
|
|
19
|
+
}
|
|
20
|
+
return void 0;
|
|
21
|
+
};
|
|
22
|
+
class RequestMemoryBudgetExceededError extends Error {
|
|
23
|
+
constructor() {
|
|
24
|
+
super("Request memory budget exceeded");
|
|
25
|
+
this.name = "RequestMemoryBudgetExceededError";
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
class RequestMemoryBudget {
|
|
29
|
+
constructor(options) {
|
|
30
|
+
this.options = options;
|
|
31
|
+
__publicField(this, "databaseBytes", 0);
|
|
32
|
+
__publicField(this, "hydrationBytes", 0);
|
|
33
|
+
__publicField(this, "peakBytes", 0);
|
|
34
|
+
__publicField(this, "databaseRows", 0);
|
|
35
|
+
__publicField(this, "largestDatabaseRowBytes", 0);
|
|
36
|
+
__publicField(this, "databaseStrings", new StringMemoryEstimate());
|
|
37
|
+
__publicField(this, "failure");
|
|
38
|
+
__publicField(this, "exceededListeners", /* @__PURE__ */ new Set());
|
|
39
|
+
const optionsError = validateRequestMemoryBudgetOptions(options);
|
|
40
|
+
if (optionsError) {
|
|
41
|
+
throw new Error(`Invalid request memory budget: ${optionsError}`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
get exceeded() {
|
|
45
|
+
return this.failure !== void 0;
|
|
46
|
+
}
|
|
47
|
+
check() {
|
|
48
|
+
if (this.failure) {
|
|
49
|
+
throw this.failure;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** Calls the listener once the budget is exceeded, immediately when it already is. Returns the unsubscribe. */
|
|
53
|
+
onExceeded(listener) {
|
|
54
|
+
if (this.failure) {
|
|
55
|
+
listener(this.failure);
|
|
56
|
+
return () => {
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
this.exceededListeners.add(listener);
|
|
60
|
+
return () => this.exceededListeners.delete(listener);
|
|
61
|
+
}
|
|
62
|
+
addDatabaseRow(row) {
|
|
63
|
+
this.check();
|
|
64
|
+
this.databaseRows++;
|
|
65
|
+
let rowBytes = 40;
|
|
66
|
+
for (const key in row) {
|
|
67
|
+
if (Object.prototype.hasOwnProperty.call(row, key)) {
|
|
68
|
+
rowBytes += 16 + estimateValueBytes(row[key], this.databaseStrings);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
this.databaseBytes += rowBytes;
|
|
72
|
+
this.largestDatabaseRowBytes = Math.max(this.largestDatabaseRowBytes, rowBytes);
|
|
73
|
+
this.update();
|
|
74
|
+
}
|
|
75
|
+
addHydrationBytes(bytes) {
|
|
76
|
+
this.check();
|
|
77
|
+
this.hydrationBytes += bytes;
|
|
78
|
+
this.update();
|
|
79
|
+
}
|
|
80
|
+
snapshot() {
|
|
81
|
+
return {
|
|
82
|
+
estimatedRetainedBytes: this.databaseBytes + this.hydrationBytes,
|
|
83
|
+
reservedCompletionBytes: this.getCompletionBytes(),
|
|
84
|
+
estimatedPeakBytes: this.peakBytes,
|
|
85
|
+
databaseRows: this.databaseRows,
|
|
86
|
+
databaseBytes: this.databaseBytes,
|
|
87
|
+
hydrationBytes: this.hydrationBytes,
|
|
88
|
+
warnBytes: this.options.warnBytes,
|
|
89
|
+
maxBytes: this.options.maxBytes,
|
|
90
|
+
warningThresholdExceeded: this.peakBytes > this.options.warnBytes,
|
|
91
|
+
maxBytesExceeded: this.peakBytes > this.options.maxBytes
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
getCompletionBytes() {
|
|
95
|
+
const projectedCompletionBytes = (this.databaseBytes - this.databaseStrings.retainedBytes) * 2 + this.databaseStrings.serializedBytes + this.hydrationBytes;
|
|
96
|
+
const decodingBytes = this.largestDatabaseRowBytes * (isBun ? 3 : 1);
|
|
97
|
+
return Math.max(projectedCompletionBytes, decodingBytes) + this.databaseRows * rowCompletionOverheadBytes;
|
|
98
|
+
}
|
|
99
|
+
update() {
|
|
100
|
+
const estimatedBytes = this.databaseBytes + this.hydrationBytes + this.getCompletionBytes();
|
|
101
|
+
this.peakBytes = Math.max(this.peakBytes, estimatedBytes);
|
|
102
|
+
if (estimatedBytes > this.options.maxBytes) {
|
|
103
|
+
const failure = new RequestMemoryBudgetExceededError();
|
|
104
|
+
this.failure = failure;
|
|
105
|
+
const listeners = [...this.exceededListeners];
|
|
106
|
+
this.exceededListeners.clear();
|
|
107
|
+
listeners.forEach((listener) => listener(failure));
|
|
108
|
+
throw failure;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
function estimateValueBytes(value, strings) {
|
|
113
|
+
return estimateScalarBytes(value, strings) ?? estimateStructuredValueBytes(value, strings, 0);
|
|
114
|
+
}
|
|
115
|
+
function estimateStructuredValueBytes(value, strings, depth) {
|
|
116
|
+
if (depth >= maximumRecursiveEstimateDepth) {
|
|
117
|
+
return estimateDeepValueBytes(value, strings);
|
|
118
|
+
}
|
|
119
|
+
if (Array.isArray(value)) {
|
|
120
|
+
let bytes2 = 32 + value.length * 8;
|
|
121
|
+
for (let i = 0; i < value.length; i++) {
|
|
122
|
+
const item = value[i];
|
|
123
|
+
const scalarBytes = estimateScalarBytes(item, strings);
|
|
124
|
+
bytes2 += scalarBytes ?? estimateStructuredValueBytes(item, strings, depth + 1);
|
|
125
|
+
}
|
|
126
|
+
return bytes2;
|
|
127
|
+
}
|
|
128
|
+
let bytes = 32;
|
|
129
|
+
if (value !== null && typeof value === "object") {
|
|
130
|
+
for (const key in value) {
|
|
131
|
+
if (Object.prototype.hasOwnProperty.call(value, key)) {
|
|
132
|
+
const item = Reflect.get(value, key);
|
|
133
|
+
const scalarBytes = estimateScalarBytes(item, strings);
|
|
134
|
+
strings.addPropertyName(key);
|
|
135
|
+
bytes += 16 + (scalarBytes ?? estimateStructuredValueBytes(item, strings, depth + 1));
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return bytes;
|
|
140
|
+
}
|
|
141
|
+
function estimateDeepValueBytes(value, strings) {
|
|
142
|
+
const scalarBytes = estimateScalarBytes(value, strings);
|
|
143
|
+
if (scalarBytes !== void 0) {
|
|
144
|
+
return scalarBytes;
|
|
145
|
+
}
|
|
146
|
+
let bytes = 0;
|
|
147
|
+
const pending = [[value].values()];
|
|
148
|
+
while (pending.length > 0) {
|
|
149
|
+
const next = pending[pending.length - 1].next();
|
|
150
|
+
if (next.done) {
|
|
151
|
+
pending.pop();
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
const current = next.value;
|
|
155
|
+
const scalarBytes2 = estimateScalarBytes(current, strings);
|
|
156
|
+
if (scalarBytes2 !== void 0) {
|
|
157
|
+
bytes += scalarBytes2;
|
|
158
|
+
} else if (Array.isArray(current)) {
|
|
159
|
+
bytes += 32 + current.length * 8;
|
|
160
|
+
pending.push(current.values());
|
|
161
|
+
} else if (current !== null && typeof current === "object") {
|
|
162
|
+
bytes += 32;
|
|
163
|
+
let hasNestedValues = false;
|
|
164
|
+
for (const key in current) {
|
|
165
|
+
if (!Object.prototype.hasOwnProperty.call(current, key)) {
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
strings.addPropertyName(key);
|
|
169
|
+
bytes += 16;
|
|
170
|
+
const scalarBytes3 = estimateScalarBytes(Reflect.get(current, key), strings);
|
|
171
|
+
if (scalarBytes3 === void 0) {
|
|
172
|
+
hasNestedValues = true;
|
|
173
|
+
} else {
|
|
174
|
+
bytes += scalarBytes3;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
if (hasNestedValues) {
|
|
178
|
+
pending.push(nestedValues(current));
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return bytes;
|
|
183
|
+
function* nestedValues(object) {
|
|
184
|
+
for (const key in object) {
|
|
185
|
+
if (Object.prototype.hasOwnProperty.call(object, key)) {
|
|
186
|
+
const value2 = Reflect.get(object, key);
|
|
187
|
+
if (value2 !== null && typeof value2 === "object" && !(value2 instanceof Date) && !ArrayBuffer.isView(value2)) {
|
|
188
|
+
yield value2;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
function estimateScalarBytes(value, strings) {
|
|
195
|
+
if (typeof value === "string") {
|
|
196
|
+
return 24 + strings.add(value);
|
|
197
|
+
}
|
|
198
|
+
if (value === null || typeof value !== "object") {
|
|
199
|
+
return 8;
|
|
200
|
+
}
|
|
201
|
+
if (value instanceof Date) {
|
|
202
|
+
return 40;
|
|
203
|
+
}
|
|
204
|
+
if (ArrayBuffer.isView(value)) {
|
|
205
|
+
return 64 + value.byteLength;
|
|
206
|
+
}
|
|
207
|
+
return void 0;
|
|
208
|
+
}
|
|
209
|
+
class StringMemoryEstimate {
|
|
210
|
+
constructor() {
|
|
211
|
+
__publicField(this, "codeUnits", 0);
|
|
212
|
+
__publicField(this, "storageBytes", 0);
|
|
213
|
+
__publicField(this, "nonAscii", false);
|
|
214
|
+
}
|
|
215
|
+
get retainedBytes() {
|
|
216
|
+
return this.storageBytes;
|
|
217
|
+
}
|
|
218
|
+
get serializedBytes() {
|
|
219
|
+
return this.codeUnits * (this.nonAscii ? 2 : 1);
|
|
220
|
+
}
|
|
221
|
+
add(value) {
|
|
222
|
+
const ascii = node_buffer.Buffer.byteLength(value) === value.length;
|
|
223
|
+
this.nonAscii || (this.nonAscii = !ascii);
|
|
224
|
+
this.codeUnits += value.length;
|
|
225
|
+
const bytes = ascii ? value.length : value.length * 2;
|
|
226
|
+
this.storageBytes += bytes;
|
|
227
|
+
return bytes;
|
|
228
|
+
}
|
|
229
|
+
// Runtimes share property names between objects of one shape; only their serialized copies are new.
|
|
230
|
+
addPropertyName(key) {
|
|
231
|
+
this.codeUnits += key.length;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
exports.RequestMemoryBudget = RequestMemoryBudget;
|
|
235
|
+
exports.RequestMemoryBudgetExceededError = RequestMemoryBudgetExceededError;
|
|
236
|
+
exports.validateRequestMemoryBudgetOptions = validateRequestMemoryBudgetOptions;
|
|
237
|
+
//# sourceMappingURL=RequestMemoryBudget.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"RequestMemoryBudget.cjs","sources":["../../../../../packages/database/src/client/RequestMemoryBudget.ts"],"sourcesContent":["import { Buffer } from 'node:buffer'\n\nexport interface RequestMemoryBudgetOptions {\n\twarnBytes: number\n\tmaxBytes: number\n}\n\nconst rowCompletionOverheadBytes = 256\nconst maximumRecursiveEstimateDepth = 64\nconst isBun = process.versions.bun !== undefined\n\nexport const validateRequestMemoryBudgetOptions = ({ warnBytes, maxBytes }: RequestMemoryBudgetOptions): string | undefined => {\n\tif (!Number.isSafeInteger(warnBytes) || warnBytes <= 0) {\n\t\treturn 'warnBytes must be a positive safe integer'\n\t}\n\tif (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {\n\t\treturn 'maxBytes must be a positive safe integer'\n\t}\n\tif (warnBytes > maxBytes) {\n\t\treturn 'warnBytes must not exceed maxBytes'\n\t}\n\treturn undefined\n}\n\nexport class RequestMemoryBudgetExceededError extends Error {\n\tconstructor() {\n\t\tsuper('Request memory budget exceeded')\n\t\tthis.name = 'RequestMemoryBudgetExceededError'\n\t}\n}\n\nexport class RequestMemoryBudget {\n\tprivate databaseBytes = 0\n\tprivate hydrationBytes = 0\n\tprivate peakBytes = 0\n\tprivate databaseRows = 0\n\tprivate largestDatabaseRowBytes = 0\n\tprivate readonly databaseStrings = new StringMemoryEstimate()\n\tprivate failure: RequestMemoryBudgetExceededError | undefined\n\t// A plain set rather than an AbortSignal: every in-flight query of the request listens, and Node 20 warns above ten signal listeners.\n\tprivate readonly exceededListeners = new Set<(failure: RequestMemoryBudgetExceededError) => void>()\n\n\tconstructor(private readonly options: RequestMemoryBudgetOptions) {\n\t\tconst optionsError = validateRequestMemoryBudgetOptions(options)\n\t\tif (optionsError) {\n\t\t\tthrow new Error(`Invalid request memory budget: ${optionsError}`)\n\t\t}\n\t}\n\n\tget exceeded(): boolean {\n\t\treturn this.failure !== undefined\n\t}\n\n\tcheck(): void {\n\t\tif (this.failure) {\n\t\t\tthrow this.failure\n\t\t}\n\t}\n\n\t/** Calls the listener once the budget is exceeded, immediately when it already is. Returns the unsubscribe. */\n\tonExceeded(listener: (failure: RequestMemoryBudgetExceededError) => void): () => void {\n\t\tif (this.failure) {\n\t\t\tlistener(this.failure)\n\t\t\treturn () => {}\n\t\t}\n\t\tthis.exceededListeners.add(listener)\n\t\treturn () => this.exceededListeners.delete(listener)\n\t}\n\n\taddDatabaseRow(row: Record<string, unknown>): void {\n\t\tthis.check()\n\t\tthis.databaseRows++\n\t\tlet rowBytes = 40\n\t\tfor (const key in row) {\n\t\t\tif (Object.prototype.hasOwnProperty.call(row, key)) {\n\t\t\t\trowBytes += 16 + estimateValueBytes(row[key], this.databaseStrings)\n\t\t\t}\n\t\t}\n\t\tthis.databaseBytes += rowBytes\n\t\tthis.largestDatabaseRowBytes = Math.max(this.largestDatabaseRowBytes, rowBytes)\n\t\tthis.update()\n\t}\n\n\taddHydrationBytes(bytes: number): void {\n\t\tthis.check()\n\t\tthis.hydrationBytes += bytes\n\t\tthis.update()\n\t}\n\n\tsnapshot() {\n\t\treturn {\n\t\t\testimatedRetainedBytes: this.databaseBytes + this.hydrationBytes,\n\t\t\treservedCompletionBytes: this.getCompletionBytes(),\n\t\t\testimatedPeakBytes: this.peakBytes,\n\t\t\tdatabaseRows: this.databaseRows,\n\t\t\tdatabaseBytes: this.databaseBytes,\n\t\t\thydrationBytes: this.hydrationBytes,\n\t\t\twarnBytes: this.options.warnBytes,\n\t\t\tmaxBytes: this.options.maxBytes,\n\t\t\twarningThresholdExceeded: this.peakBytes > this.options.warnBytes,\n\t\t\tmaxBytesExceeded: this.peakBytes > this.options.maxBytes,\n\t\t}\n\t}\n\n\tprivate getCompletionBytes(): number {\n\t\t// GraphQL shares scalar strings with DB results; completion allocates structures and serialized text.\n\t\tconst projectedCompletionBytes = (this.databaseBytes - this.databaseStrings.retainedBytes) * 2\n\t\t\t+ this.databaseStrings.serializedBytes + this.hydrationBytes\n\t\t// Decoding a row and serializing the response happen in different phases.\n\t\t// JSC includes pg's growing buffers in its heap account; V8 reports them as external memory.\n\t\tconst decodingBytes = this.largestDatabaseRowBytes * (isBun ? 3 : 1)\n\t\treturn Math.max(projectedCompletionBytes, decodingBytes)\n\t\t\t+ this.databaseRows * rowCompletionOverheadBytes\n\t}\n\n\tprivate update(): void {\n\t\tconst estimatedBytes = this.databaseBytes + this.hydrationBytes + this.getCompletionBytes()\n\t\tthis.peakBytes = Math.max(this.peakBytes, estimatedBytes)\n\t\tif (estimatedBytes > this.options.maxBytes) {\n\t\t\tconst failure = new RequestMemoryBudgetExceededError()\n\t\t\tthis.failure = failure\n\t\t\tconst listeners = [...this.exceededListeners]\n\t\t\tthis.exceededListeners.clear()\n\t\t\tlisteners.forEach(listener => listener(failure))\n\t\t\tthrow failure\n\t\t}\n\t}\n}\n\nfunction estimateValueBytes(value: unknown, strings: StringMemoryEstimate): number {\n\treturn estimateScalarBytes(value, strings) ?? estimateStructuredValueBytes(value, strings, 0)\n}\n\nfunction estimateStructuredValueBytes(value: unknown, strings: StringMemoryEstimate, depth: number): number {\n\tif (depth >= maximumRecursiveEstimateDepth) {\n\t\treturn estimateDeepValueBytes(value, strings)\n\t}\n\tif (Array.isArray(value)) {\n\t\tlet bytes = 32 + value.length * 8\n\t\tfor (let i = 0; i < value.length; i++) {\n\t\t\tconst item: unknown = value[i]\n\t\t\tconst scalarBytes = estimateScalarBytes(item, strings)\n\t\t\tbytes += scalarBytes ?? estimateStructuredValueBytes(item, strings, depth + 1)\n\t\t}\n\t\treturn bytes\n\t}\n\tlet bytes = 32\n\tif (value !== null && typeof value === 'object') {\n\t\tfor (const key in value) {\n\t\t\tif (Object.prototype.hasOwnProperty.call(value, key)) {\n\t\t\t\tconst item: unknown = Reflect.get(value, key)\n\t\t\t\tconst scalarBytes = estimateScalarBytes(item, strings)\n\t\t\t\tstrings.addPropertyName(key)\n\t\t\t\tbytes += 16 + (scalarBytes ?? estimateStructuredValueBytes(item, strings, depth + 1))\n\t\t\t}\n\t\t}\n\t}\n\treturn bytes\n}\n\nfunction estimateDeepValueBytes(value: unknown, strings: StringMemoryEstimate): number {\n\tconst scalarBytes = estimateScalarBytes(value, strings)\n\tif (scalarBytes !== undefined) {\n\t\treturn scalarBytes\n\t}\n\tlet bytes = 0\n\tconst pending: Iterator<unknown>[] = [[value].values()]\n\twhile (pending.length > 0) {\n\t\tconst next = pending[pending.length - 1].next()\n\t\tif (next.done) {\n\t\t\tpending.pop()\n\t\t\tcontinue\n\t\t}\n\t\tconst current: unknown = next.value\n\t\tconst scalarBytes = estimateScalarBytes(current, strings)\n\t\tif (scalarBytes !== undefined) {\n\t\t\tbytes += scalarBytes\n\t\t} else if (Array.isArray(current)) {\n\t\t\tbytes += 32 + current.length * 8\n\t\t\tpending.push(current.values())\n\t\t} else if (current !== null && typeof current === 'object') {\n\t\t\tbytes += 32\n\t\t\tlet hasNestedValues = false\n\t\t\tfor (const key in current) {\n\t\t\t\tif (!Object.prototype.hasOwnProperty.call(current, key)) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tstrings.addPropertyName(key)\n\t\t\t\tbytes += 16\n\t\t\t\tconst scalarBytes = estimateScalarBytes(Reflect.get(current, key), strings)\n\t\t\t\tif (scalarBytes === undefined) {\n\t\t\t\t\thasNestedValues = true\n\t\t\t\t} else {\n\t\t\t\t\tbytes += scalarBytes\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hasNestedValues) {\n\t\t\t\tpending.push(nestedValues(current))\n\t\t\t}\n\t\t}\n\t}\n\treturn bytes\n\n\tfunction* nestedValues(object: object): Generator<unknown> {\n\t\tfor (const key in object) {\n\t\t\tif (Object.prototype.hasOwnProperty.call(object, key)) {\n\t\t\t\tconst value: unknown = Reflect.get(object, key)\n\t\t\t\tif (value !== null && typeof value === 'object' && !(value instanceof Date) && !ArrayBuffer.isView(value)) {\n\t\t\t\t\tyield value\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction estimateScalarBytes(value: unknown, strings: StringMemoryEstimate): number | undefined {\n\tif (typeof value === 'string') {\n\t\treturn 24 + strings.add(value)\n\t}\n\tif (value === null || typeof value !== 'object') {\n\t\treturn 8\n\t}\n\tif (value instanceof Date) {\n\t\treturn 40\n\t}\n\tif (ArrayBuffer.isView(value)) {\n\t\treturn 64 + value.byteLength\n\t}\n\treturn undefined\n}\n\nclass StringMemoryEstimate {\n\tprivate codeUnits = 0\n\tprivate storageBytes = 0\n\tprivate nonAscii = false\n\n\tget retainedBytes(): number {\n\t\treturn this.storageBytes\n\t}\n\n\tget serializedBytes(): number {\n\t\t// One non-ASCII string can promote the entire serialized JSON string to two-byte storage.\n\t\treturn this.codeUnits * (this.nonAscii ? 2 : 1)\n\t}\n\n\tadd(value: string): number {\n\t\t// A native length comparison avoids a JavaScript character loop and RegExp.input, which can retain a request string.\n\t\tconst ascii = Buffer.byteLength(value) === value.length\n\t\tthis.nonAscii ||= !ascii\n\t\tthis.codeUnits += value.length\n\t\tconst bytes = ascii ? value.length : value.length * 2\n\t\tthis.storageBytes += bytes\n\t\treturn bytes\n\t}\n\n\t// Runtimes share property names between objects of one shape; only their serialized copies are new.\n\taddPropertyName(key: string): void {\n\t\tthis.codeUnits += key.length\n\t}\n}\n"],"names":["bytes","scalarBytes","value","Buffer"],"mappings":";;;;;;AAOA,MAAM,6BAA6B;AACnC,MAAM,gCAAgC;AACtC,MAAM,QAAQ,QAAQ,SAAS,QAAQ;AAEhC,MAAM,qCAAqC,CAAC,EAAE,WAAW,eAA+D;AAC9H,MAAI,CAAC,OAAO,cAAc,SAAS,KAAK,aAAa,GAAG;AACvD,WAAO;AAAA,EACR;AACA,MAAI,CAAC,OAAO,cAAc,QAAQ,KAAK,YAAY,GAAG;AACrD,WAAO;AAAA,EACR;AACA,MAAI,YAAY,UAAU;AACzB,WAAO;AAAA,EACR;AACA,SAAO;AACR;AAEO,MAAM,yCAAyC,MAAM;AAAA,EAC3D,cAAc;AACb,UAAM,gCAAgC;AACtC,SAAK,OAAO;AAAA,EACb;AACD;AAEO,MAAM,oBAAoB;AAAA,EAWhC,YAA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