document-drive 1.0.0-alpha.46 → 1.0.0-alpha.48

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "document-drive",
3
- "version": "1.0.0-alpha.46",
3
+ "version": "1.0.0-alpha.48",
4
4
  "license": "AGPL-3.0-only",
5
5
  "type": "module",
6
6
  "module": "./src/index.ts",
@@ -36,11 +36,19 @@ function storageToOperation(
36
36
  };
37
37
  }
38
38
 
39
+ type PrismaStorageOptions = {
40
+ maxTransactionRetries?: number;
41
+ }
42
+
43
+ const MAX_TRANSACTION_RETRIES = 5;
44
+
39
45
  export class PrismaStorage implements IDriveStorage {
40
46
  private db: PrismaClient;
47
+ private maxTransactionRetries: number;
41
48
 
42
- constructor(db: PrismaClient) {
49
+ constructor(db: PrismaClient, options?: PrismaStorageOptions) {
43
50
  this.db = db;
51
+ this.maxTransactionRetries = options?.maxTransactionRetries ?? MAX_TRANSACTION_RETRIES;
44
52
  }
45
53
 
46
54
  async createDrive(id: string, drive: DocumentDriveStorage): Promise<void> {
@@ -215,24 +223,37 @@ export class PrismaStorage implements IDriveStorage {
215
223
  header: DocumentHeader;
216
224
  updatedOperations?: Operation[] | undefined;
217
225
  } | null = null;
218
- await this.db.$transaction(async tx => {
219
- const document = await this.getDocument(drive, id, tx);
220
- if (!document) {
221
- throw new Error(`Document with id ${id} not found`);
222
- }
223
- result = await callback(document);
226
+ let retries = 0
224
227
 
225
- const { operations, header, updatedOperations } = result;
226
- return this._addDocumentOperations(
227
- tx,
228
- drive,
229
- id,
230
- operations,
231
- header,
232
- updatedOperations
233
- );
234
- });
228
+ while (retries < this.maxTransactionRetries) {
229
+ try {
230
+ await this.db.$transaction(async tx => {
231
+ const document = await this.getDocument(drive, id, tx);
232
+ if (!document) {
233
+ throw new Error(`Document with id ${id} not found`);
234
+ }
235
+ result = await callback(document);
235
236
 
237
+ const { operations, header, updatedOperations } = result;
238
+ return this._addDocumentOperations(
239
+ tx,
240
+ drive,
241
+ id,
242
+ operations,
243
+ header,
244
+ updatedOperations
245
+ );
246
+ }, { isolationLevel: "Serializable" });
247
+ break;
248
+ } catch (error) {
249
+ // transaction lock failed due to concurrent operations
250
+ if ((error as { code: string }).code === 'P2034') {
251
+ retries++
252
+ continue;
253
+ }
254
+ throw error;
255
+ }
256
+ }
236
257
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
237
258
  if (!result) {
238
259
  throw new Error('No operations were provided');