From a8ac4eed6dc072d8f903c2f8e17e734a827b84b9 Mon Sep 17 00:00:00 2001 From: Adria Navarro Date: Thu, 30 Nov 2023 13:54:42 +0100 Subject: [PATCH] Autoextend without ttl --- .../backend-core/src/redis/redlockImpl.ts | 13 +++++++++---- packages/types/src/sdk/locks.ts | 19 +++++++++++++------ 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/packages/backend-core/src/redis/redlockImpl.ts b/packages/backend-core/src/redis/redlockImpl.ts index a4586a4495..2cabeccf1d 100644 --- a/packages/backend-core/src/redis/redlockImpl.ts +++ b/packages/backend-core/src/redis/redlockImpl.ts @@ -2,9 +2,9 @@ import Redlock from "redlock" import { getLockClient } from "./init" import { LockOptions, LockType } from "@budibase/types" import * as context from "../context" -import env from "../environment" import { logWarn } from "../logging" import { utils } from "@budibase/shared-core" +import { Duration } from "../utils" async function getClient( type: LockType, @@ -111,8 +111,13 @@ export async function doWithLock( try { const name = getLockName(opts) + const ttl = + opts.type === LockType.AUTO_EXTEND + ? Duration.fromSeconds(10).toMs() + : opts.ttl + // create the lock - lock = await redlock.lock(name, opts.ttl) + lock = await redlock.lock(name, ttl) if (opts.type === LockType.AUTO_EXTEND) { // We keep extending the lock while the task is running @@ -120,7 +125,7 @@ export async function doWithLock( timeout = setTimeout(async () => { let isExpired = false try { - lock = await lock!.extend(opts.ttl) + lock = await lock!.extend(ttl) } catch (err: any) { isExpired = err.message.includes("Cannot extend lock on resource") if (isExpired) { @@ -133,7 +138,7 @@ export async function doWithLock( if (!isExpired) { extendInIntervals() } - }, opts.ttl / 2) + }, ttl / 2) } extendInIntervals() diff --git a/packages/types/src/sdk/locks.ts b/packages/types/src/sdk/locks.ts index a04b8238a9..b9470402c1 100644 --- a/packages/types/src/sdk/locks.ts +++ b/packages/types/src/sdk/locks.ts @@ -22,7 +22,7 @@ export enum LockName { QUOTA_USAGE_EVENT = "quota_usage_event", } -export interface LockOptions { +export type LockOptions = { /** * The lock type determines which client to use */ @@ -36,10 +36,6 @@ export interface LockOptions { * The name for the lock */ name: LockName - /** - * The ttl to auto-expire the lock if not unlocked manually - */ - ttl: number /** * The individual resource to lock. This is useful for locking around very specific identifiers, e.g. a document that is prone to conflicts */ @@ -48,4 +44,15 @@ export interface LockOptions { * This is a system-wide lock - don't use tenancy in lock key */ systemLock?: boolean -} +} & ( + | { + /** + * The ttl to auto-expire the lock if not unlocked manually + */ + ttl: number + type: Exclude + } + | { + type: LockType.AUTO_EXTEND + } +)