lock changes (#9047)

This commit is contained in:
Martin McKeaveney 2022-12-15 12:45:53 +00:00 committed by GitHub
parent a8b0dc4646
commit 07d5ddf3bb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 25 additions and 7 deletions

View File

@ -13,6 +13,18 @@ const getClient = async (type: LockType): Promise<Redlock> => {
}
return noRetryRedlock
}
case LockType.DEFAULT: {
if (!noRetryRedlock) {
noRetryRedlock = await newRedlock(OPTIONS.DEFAULT)
}
return noRetryRedlock
}
case LockType.DELAY_500: {
if (!noRetryRedlock) {
noRetryRedlock = await newRedlock(OPTIONS.DELAY_500)
}
return noRetryRedlock
}
default: {
throw new Error(`Could not get redlock client: ${type}`)
}
@ -41,6 +53,9 @@ export const OPTIONS = {
// see https://www.awsarchitectureblog.com/2015/03/backoff.html
retryJitter: 100, // time in ms
},
DELAY_500: {
retryDelay: 500,
},
}
export const newRedlock = async (opts: Options = {}) => {
@ -55,19 +70,17 @@ export const doWithLock = async (opts: LockOptions, task: any) => {
let lock
try {
// aquire lock
let name: string
if (opts.systemLock) {
name = opts.name
} else {
name = `${tenancy.getTenantId()}_${opts.name}`
}
let name: string = `lock:${tenancy.getTenantId()}_${opts.name}`
if (opts.nameSuffix) {
name = name + `_${opts.nameSuffix}`
}
lock = await redlock.lock(name, opts.ttl)
// perform locked task
return task()
// need to await to ensure completion before unlocking
const result = await task()
return result
} catch (e: any) {
console.log("lock error")
// lock limit exceeded
if (e.name === "LockError") {
if (opts.type === LockType.TRY_ONCE) {

View File

@ -3,6 +3,7 @@ import {
Hosting,
MonthlyQuotaName,
PlanType,
PriceDuration,
Quotas,
StaticQuotaName,
} from "../../sdk"
@ -46,6 +47,7 @@ export interface Account extends CreateAccount {
tier: string // deprecated
planType?: PlanType
planTier?: number
planDuration?: PriceDuration
stripeCustomerId?: string
licenseKey?: string
licenseKeyActivatedAt?: number

View File

@ -4,11 +4,14 @@ export enum LockType {
* No retries will take place and no error will be thrown.
*/
TRY_ONCE = "try_once",
DEFAULT = "default",
DELAY_500 = "delay_500",
}
export enum LockName {
MIGRATIONS = "migrations",
TRIGGER_QUOTA = "trigger_quota",
SYNC_ACCOUNT_LICENSE = "sync_account_license",
}
export interface LockOptions {