@nathapp/nestjs-prisma 4.3.0 → 4.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -198,6 +198,57 @@ await prismaService.withTransaction(async (tx) => {
198
198
  Both `forRoot` and `forRootAsync` provide the same context to the service and
199
199
  transaction manager for that connection.
200
200
 
201
+ ### Retrying a rolled-back write conflict
202
+
203
+ `await tx.run(fn, { retryOnWriteConflict: true })` lets the outer transaction
204
+ owner replay `fn` on Prisma `P2034`. Each attempt starts a fresh transaction;
205
+ `maxWait`, `timeout` and `isolationLevel` apply per attempt. The default is one
206
+ attempt. Opting in allows three total, with a short jittered delay between them.
207
+ A nested call cannot enable retries. Duplicate keys, timeouts and failures with
208
+ an unknown commit outcome are not retried.
209
+
210
+ Only opt in if the entire callback is safe to repeat. Keep writes (including
211
+ outbox records) on the same transaction client, re-read decision inputs on each
212
+ attempt, and emit events or perform external I/O after the outer `run` resolves.
213
+
214
+ ### Independent transactions (`requiresNew`)
215
+
216
+ By default `run` joins an active transaction. `await tx.run(fn, { propagation: 'requiresNew' })`
217
+ instead always starts a new transaction on the root client. It is the active
218
+ transaction only inside `fn`; the outer transaction resumes afterwards, and a plain
219
+ `run` nested in `fn` joins the new one. Use it for writes that must persist even if
220
+ the caller later rolls back (security revocations, audit records, lockout counters):
221
+
222
+ - The inner commit survives an outer rollback.
223
+ - An error thrown inside it rolls back only the inner transaction. The outer
224
+ transaction is not poisoned (SEC-16 applies to joined runs only), and the error
225
+ still reaches the caller of `run`.
226
+ - `maxWait`, `timeout`, `isolationLevel` and `retryOnWriteConflict` apply to the new
227
+ transaction; a retry replays only the inner callback.
228
+ - An outer run with `retryOnWriteConflict` replays its callback, so each attempt
229
+ commits a new `requiresNew` transaction. Inner commits do not roll back, so the
230
+ inner work must be safe to repeat.
231
+ - An unknown `propagation` value (for example `'requires_new'`) throws instead of
232
+ silently joining.
233
+
234
+ Caveats:
235
+
236
+ - It needs a second pooled connection while the outer transaction still holds one.
237
+ On single-connection setups, for example the Prisma 7 SQLite adapter, which
238
+ serializes transactions, it deadlocks and is unsupported. The manager throws a
239
+ clear error when it detects a SQLite adapter and `requiresNew` runs inside an
240
+ active transaction; other single-connection adapters cannot be detected, so make
241
+ sure the pool has at least two connections.
242
+ - Each concurrent outer transaction using `requiresNew` holds two connections. Size
243
+ the pool for at least 2x the peak number of concurrent outer transactions; when
244
+ it is exhausted, Prisma fails after `maxWait` (default 2000 ms).
245
+ - If the outer transaction holds row locks on rows the inner one writes, the inner
246
+ transaction waits on its own caller until the lock timeout. Use it only for rows
247
+ the outer transaction has not locked.
248
+
249
+ The real-database proof is opt-in and needs Docker: `npm run test:db` starts
250
+ `postgres:16` and `mysql:8.4` with testcontainers. It is not part of `npm test`.
251
+
201
252
  ## Multi-DB and transactions
202
253
 
203
254
  For multiple databases in one process, call `PrismaModule.forRoot` once per
@@ -18,6 +18,17 @@ const async_hooks_1 = require("async_hooks");
18
18
  const prisma_constants_1 = require("../prisma.constants");
19
19
  const prisma_transaction_constants_1 = require("./prisma-transaction.constants");
20
20
  const prisma_tx_state_1 = require("./prisma-tx-state");
21
+ const promises_1 = require("node:timers/promises");
22
+ const MAX_WRITE_CONFLICT_ATTEMPTS = 3;
23
+ function isWriteConflict(error) {
24
+ return error instanceof Error && 'code' in error && error.code === 'P2034' &&
25
+ Object.prototype.toString.call(error) === '[object PrismaClientKnownRequestError]';
26
+ }
27
+ function usesSingleConnectionAdapter(client) {
28
+ var _a;
29
+ const adapter = (_a = client._engineConfig) === null || _a === void 0 ? void 0 : _a.adapter;
30
+ return (adapter === null || adapter === void 0 ? void 0 : adapter.provider) === 'sqlite';
31
+ }
21
32
  const toPrismaTxOptions = (o) => ({
22
33
  maxWait: o.maxWait,
23
34
  timeout: o.timeout,
@@ -29,8 +40,17 @@ let PrismaTransactionManager = class PrismaTransactionManager {
29
40
  this.als = externalAls !== null && externalAls !== void 0 ? externalAls : new async_hooks_1.AsyncLocalStorage();
30
41
  }
31
42
  async run(fn, options) {
43
+ const propagation = options === null || options === void 0 ? void 0 : options.propagation;
44
+ if (propagation !== undefined && propagation !== 'required' && propagation !== 'requiresNew') {
45
+ throw new Error(`Unknown transaction propagation ${JSON.stringify(propagation)}: expected 'required' or 'requiresNew'`);
46
+ }
32
47
  const current = this.als.getStore();
33
- if (current) {
48
+ const requiresNew = (options === null || options === void 0 ? void 0 : options.propagation) === 'requiresNew';
49
+ if (current && requiresNew && usesSingleConnectionAdapter(this.prisma)) {
50
+ throw new Error("propagation 'requiresNew' inside an active transaction is not supported on single-connection " +
51
+ 'adapters (for example SQLite): it needs a second connection and would deadlock');
52
+ }
53
+ if (current && !requiresNew) {
34
54
  try {
35
55
  return await fn();
36
56
  }
@@ -39,14 +59,26 @@ let PrismaTransactionManager = class PrismaTransactionManager {
39
59
  throw err;
40
60
  }
41
61
  }
42
- return this.prisma.$transaction(async (tx) => {
43
- const state = (0, prisma_tx_state_1.registerTxState)(tx);
44
- const result = await this.als.run(tx, fn);
45
- if (state.poisoned) {
46
- throw new Error('Nested transaction failure: the outer transaction was rolled back because an inner run() threw (SEC-16)');
62
+ const prismaOptions = options && toPrismaTxOptions(options);
63
+ const maxAttempts = (options === null || options === void 0 ? void 0 : options.retryOnWriteConflict) === true ? MAX_WRITE_CONFLICT_ATTEMPTS : 1;
64
+ for (let attempt = 1;; attempt++) {
65
+ try {
66
+ return await this.prisma.$transaction(async (tx) => {
67
+ const state = (0, prisma_tx_state_1.registerTxState)(tx);
68
+ const result = await this.als.run(tx, fn);
69
+ if (state.poisoned) {
70
+ throw new Error('Nested transaction failure: the outer transaction was rolled back because an inner run() threw (SEC-16)');
71
+ }
72
+ return result;
73
+ }, prismaOptions);
47
74
  }
48
- return result;
49
- }, options && toPrismaTxOptions(options));
75
+ catch (error) {
76
+ if (attempt >= maxAttempts || !isWriteConflict(error)) {
77
+ throw error;
78
+ }
79
+ await (0, promises_1.setTimeout)(1 + Math.floor(Math.random() * 10 * attempt));
80
+ }
81
+ }
50
82
  }
51
83
  getClient() {
52
84
  var _a;
@@ -1 +1 @@
1
- {"version":3,"file":"prisma-transaction-manager.js","sourceRoot":"","sources":["../../lib/transaction/prisma-transaction-manager.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,2CAA8D;AAC9D,6CAAgD;AAGhD,0DAAqD;AACrD,iFAAwE;AACxE,uDAA8D;AAE9D,MAAM,iBAAiB,GAAG,CAAC,CAAwB,EAAE,EAAE,CAAC,CAAC;IACvD,OAAO,EAAE,CAAC,CAAC,OAAO;IAClB,OAAO,EAAE,CAAC,CAAC,OAAO;IAClB,cAAc,EAAE,CAAC,CAAC,cAAuB;CAC1C,CAAC,CAAC;AA+BI,IAAM,wBAAwB,GAA9B,MAAM,wBAAwB;IAGnC,YAC6C,MAE1C,EAC2C,WAAiD;QAHlD,WAAM,GAAN,MAAM,CAEhD;QAGD,IAAI,CAAC,GAAG,GAAG,WAAW,aAAX,WAAW,cAAX,WAAW,GAAI,IAAI,+BAAiB,EAAoB,CAAC;IACtE,CAAC;IAgBD,KAAK,CAAC,GAAG,CAAI,EAAoB,EAAE,OAA+B;QAEhE,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC;QACpC,IAAI,OAAO,EAAE,CAAC;YACZ,IAAI,CAAC;gBAAC,OAAO,MAAM,EAAE,EAAE,CAAC;YAAC,CAAC;YAC1B,OAAO,GAAG,EAAE,CAAC;gBAAC,IAAA,0BAAQ,EAAC,OAAO,CAAC,CAAC;gBAAC,MAAM,GAAG,CAAC;YAAC,CAAC;QAC/C,CAAC;QAED,OAAQ,IAAI,CAAC,MAAc,CAAC,YAAY,CAAC,KAAK,EAAE,EAAoB,EAAE,EAAE;YACtE,MAAM,KAAK,GAAG,IAAA,iCAAe,EAAC,EAAE,CAAC,CAAC;YAClC,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,EAAE,EAA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,CAAC;IAMD,SAAS;;QACP,OAAO,CAAC,MAAA,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,mCAAI,IAAI,CAAC,MAAM,CAAM,CAAC;IACnD,CAAC;IAKD,eAAe;QACb,OAAO,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,KAAK,SAAS,CAAC;IAC3C,CAAC;CACF,CAAA;AAzFY,4DAAwB;mCAAxB,wBAAwB;IADpC,IAAA,mBAAU,GAAE;IAKR,WAAA,IAAA,eAAM,EAAC,IAAA,iCAAc,GAAE,CAAC,CAAA;IAGxB,WAAA,IAAA,iBAAQ,GAAE,CAAA;IAAE,WAAA,IAAA,eAAM,EAAC,qDAAsB,CAAC,CAAA;6CAAe,+BAAiB;GAPlE,wBAAwB,CAyFpC"}
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "@nathapp/nestjs-prisma",
3
- "version": "4.3.0",
3
+ "version": "4.3.2",
4
4
  "description": "NestJS Prisma integration with multi-database support",
5
5
  "scripts": {
6
6
  "clean": "rimraf dist/ .turbo/",
7
7
  "build": "rimraf dist && tsc -p tsconfig.json",
8
8
  "test": "jest --config ./test/jest-test.json",
9
9
  "test:cov": "jest --config ./test/jest-test.json --coverage",
10
+ "test:db": "jest --config ./test/jest-db.json --runInBand --forceExit",
10
11
  "type-check": "tsc --noEmit -p tsconfig.json",
11
12
  "lint": "eslint -c .eslintrc.js \"lib/**/*.ts\" \"test/**/*.ts\"",
12
13
  "lint:fix": "eslint -c .eslintrc.js --fix \"lib/**/*.ts\" \"test/**/*.ts\"",
@@ -20,16 +21,19 @@
20
21
  "types": "dist/index.d.ts",
21
22
  "main": "dist/index.js",
22
23
  "dependencies": {
23
- "@nathapp/nestjs-common": "^4.3.0",
24
- "@nathapp/nestjs-data": "^4.3.0"
24
+ "@nathapp/nestjs-common": "^4.3.2",
25
+ "@nathapp/nestjs-data": "^4.3.2"
25
26
  },
26
27
  "devDependencies": {
27
28
  "@nathapp/eslint-config": "1.0.1",
28
29
  "@nathapp/typescript-config": "1.0.1",
29
30
  "@golevelup/ts-jest": "^3.0.0",
31
+ "@prisma/adapter-mariadb": "7.10.0",
32
+ "@prisma/adapter-pg": "7.10.0",
30
33
  "@prisma/client": "^7.10.0",
31
34
  "eslint": "^8.57.0",
32
35
  "prisma": "^7.10.0",
36
+ "testcontainers": "12.0.3",
33
37
  "typescript": "^5"
34
38
  },
35
39
  "peerDependencies": {