Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor!: do not throw anymore when cant acquire a lock #5

Merged
merged 3 commits into from
Mar 14, 2024

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'

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
9 checks passed
@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.

1 participant