Skip to content

Conversation

@Julien-R44
Copy link
Owner

this PR changes a crucial element of Verrou that simplifies the control flow. Previously, the acquire, run, acquireImmediately etc. methods threw an E_LOCK_TIMEOUT error if the lock could not be acquired

this sometimes made the flow a little complicated and not super readable :

try {
	await lock.acquireImmediately() 
	await criticalCode()
	return 'Order processed successfully'
} catch (err) {
	if (err instanceof errors.E_LOCK_ALREADY_ACQUIRED) {
		return 'Order is already being processed'
	}
} finally { 
	await lock.release()
}

Now, the methods will simply return a boolean to indicate whether the lock has been acquired or not. Example with acquire and acquireImmediately.

const acquired = await lock.acquireImmediately()
if (!acquired) return 'Order is already being processed'

try {	
	await criticalCode()
} finally {
	lock.release()
}

much simpler and easier to read this way.

for run and runImmediately it's a bit different. The functions now return tuples. Before, you had to do it like this:

try {
	const result = await lock.run(() => {
		return await criticalCode()
	})
	
	return 'Order processed successfully'
} catch (err) {
	if (err instanceof errors.E_LOCK_ALREADY_ACQUIRED) {
	   return 'Couldnt acquire the lock'
	}
}

And now, with the new version :

const [executed, result] = await lock.run(() => {
  return await criticalCode()
})

if (executed) return 'Order processed successfully'
return 'Couldnt acquire the lock'

@cloudflare-workers-and-pages
Copy link

cloudflare-workers-and-pages bot commented Mar 14, 2024

Deploying with  Cloudflare Pages  Cloudflare Pages

Latest commit: 1281cb5
Status: ✅  Deploy successful!
Preview URL: https://08a69623.verrou.pages.dev
Branch Preview URL: https://feat-acquire-flow.verrou.pages.dev

View logs

@Julien-R44 Julien-R44 merged commit 0e430cf into main Mar 14, 2024
@Julien-R44 Julien-R44 deleted the feat/acquire-flow branch March 14, 2024 11:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants