Skip to content

ActivityPub-federated video streaming platform using P2P directly in your web browser

Don't collide concurrent serializations

Chocobozzz998e448a216f
diff --git a/server/core/helpers/database-utils.ts b/server/core/helpers/database-utils.ts
index 7a05084ebf..90357813fe 100644
--- a/server/core/helpers/database-utils.ts
+++ b/server/core/helpers/database-utils.ts
@@ -1,3 +1,4 @@
+import { wait } from '@peertube/peertube-core-utils'
import { sequelizeTypescript } from '@server/initializers/database.js'
import { Transaction } from 'sequelize'
import { Model } from 'sequelize-typescript'
@@ -8,6 +9,9 @@ export type RetryTransactionWrapperOptions = {
retryUniqueConstraintViolation?: boolean // default false
}
+const RETRY_BASE_DELAY_MS = 50
+const RETRY_MAX_DELAY_MS = 1000
+
export async function retryTransactionWrapper<T> (
functionToRetry: () => Promise<T>,
options: RetryTransactionWrapperOptions = {}
@@ -33,10 +37,19 @@ export async function retryTransactionWrapper<T> (
throw err
}
+
+ await wait(getRetryDelayMs(attempts))
}
}
}
+// Don't collide concurrent serializations
+function getRetryDelayMs (attempts: number) {
+ const maxDelay = Math.min(RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** (attempts - 1))
+
+ return Math.floor(Math.random() * maxDelay)
+}
+
export function saveInTransactionWithRetries<T extends Pick<Model, 'save' | 'changed'>> (
model: T,
isolationLevel: Transaction.ISOLATION_LEVELS = Transaction.ISOLATION_LEVELS.SERIALIZABLE