Problem/Motivation
Now Drupal provides Locking mechanisms with two Lock API methods to acquire the lock
That's looks enough, but actually - not, because of this nuance in the function wait()
:
https://git.drupalcode.org/project/drupal/-/blob/11.x/core/lib/Drupal/Co...
/**
* Waits a short amount of time before a second lock acquire attempt.
* ...
* @return bool
* TRUE if the lock holds, FALSE if it may be available. You still need to
* acquire the lock manually and it may fail again.
*/
public function wait($name, $delay = 30);
The problem is here:
You still need to acquire the lock manually and it may fail again.
Let me elaborate on this.
If we have several parallel requests that waiting for the lock to be released, they produce multiple parallel SQL requests to check. Let's imagine two requests, for example.
When the lock is released, both two requests receives FALSE from the function wait(), and then - immediately tries to acquire the lock. And, in this case, one of two requests will obligatorily fail with acquiring the lock.
So, all developers, who need to acquire the lock in a reliable way, need to implement an infinite loop with "wait() + lock()" to workaround this, that is not good. Also, this loop produces a lot of load to the database.
One of the workarounds like this you can see here: https://git.drupalcode.org/project/test_helpers/-/commit/6d4f4e0028cd7e0...
Proposed resolution
As a solution, I propose to implement a new method "waitAndAcquire()" that will wait and acquire the lock at once.
And this can be implemented in a much better way than with the "wait() + lock()" loop, because we can produce "acquire lock" SQL queries (insert queries that fail if not released) instead of "check the lock" (just select queries) that can guarantee to acquire the lock directly during the query, not using a second query that can fail.
What do you think about this idea? And maybe someone has better ideas to resolve this issue?
Remaining tasks
User interface changes
Introduced terminology
API changes
Data model changes
Release notes snippet