From 2484b61e149273d788170c4d64e679b5b0f8155d Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Mon, 2 Dec 2024 22:42:58 -0800 Subject: update reverse logic --- lib/db.ts | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) (limited to 'lib') diff --git a/lib/db.ts b/lib/db.ts index 09e559bb..a047f291 100644 --- a/lib/db.ts +++ b/lib/db.ts @@ -41,22 +41,30 @@ local total = tonumber(ARGV[1]) local credit = tonumber(ARGV[2]) local hash = ARGV[3] --- Hardcoded TTL for the processing state -local processingTTL = 5 +-- Hardcoded TTL for the processing state (in milliseconds) +local processingTTL = 5000 --- Attempt to atomically claim the payment with a timeout -if redis.call('setex', paymentKey, processingTTL, 'processing') then - -- Only process if successfully claimed +-- Generate a unique lock identifier for this script instance +local uniqueId = tostring(redis.call('incr', 'lock:counter')) .. ':' .. redis.call('time')[2] + +-- Attempt to atomically claim the payment with a lock +local lockSet = redis.call('set', paymentKey, uniqueId, 'NX', 'PX', processingTTL) + +if lockSet then + -- Remove the lock immediately to prevent re-entry + redis.call('del', paymentKey) + + -- Proceed with processing redis.call('incrby', balanceKey, total) redis.call('incrby', creditKey, credit) - redis.call('del', paymentKey) redis.call('del', hashKey) redis.call('lrem', paymentsKey, 0, pid) redis.call('srem', 'pending', hash) + return pid else - -- Payment already being processed or processed - return nil + -- Another process holds the lock; throw an error + error("Payment has already been reversed") end `; -- cgit v1.2.3