Class
Claim
A handle on a name that one holder at a time can hold across the whole server, from Swerve::claim.
Introduction#
The handle claims nothing until acquire().
A claim is a file in a temporary directory (below $SWERVE_TMPDIR, by default the system's) that the master creates before it forks the workers: a hard link to a file with the pid of the holder in it. Linking is atomic and fails while the name is held, so the first to try when the name is free wins, there is no queue, and a waiting acquire() tries again every 20 ms. It is held until it is released, its handle is destroyed, or its worker exits or dies (the master clears what a dead worker held). Draining does not release a claim: a long-lived holder should release it itself when Swerve::draining(), so that a reload is not held up. Names are a namespace of their own, apart from the cache's keys. Without a master it works the same, in a directory of the process that dies with it: two handles conflict, also in one process.
Class synopsis#
final class Claim {
/* Methods */
public Claim::__construct(string $name)
public Claim::available(): bool
public Claim::acquire(float $timeout = 0.0): ?static
public Claim::held(): bool
public Claim::release(): void
public Claim::__destruct()
}Properties#
| Name | Type | Description |
|---|---|---|
$name | readonly string |
Methods#
| Method | Description |
|---|---|
__construct | A handle on $name; Swerve::claim is how an application gets one. |
available | Whether nobody holds the name now; nothing is claimed. |
acquire | Take the name, trying every 20 ms for up to $timeout seconds when another holds it. |
held | Whether this handle holds the name: it was acquired and not released. |
release | Give the claim up, so that another can take it. |
__destruct | Releases: synchronous, so it cannot suspend. |
Examples#
use Swerve\Swerve;
phasync::run(function () {
$mine = Swerve::claim('import');
$yours = Swerve::claim('import'); // two handles on one name conflict, also in one process
var_dump($mine->available()); // nobody holds it; nothing is claimed
var_dump($mine->acquire() === $mine); // the handle, now holding it
var_dump($yours->acquire()); // null: held by another
var_dump($mine->held(), $yours->held());
$mine->release();
var_dump($yours->acquire() === $yours);
});bool(true) bool(true) NULL bool(true) bool(false) bool(true)
if ($claim = Swerve::claim('nightly-report')->acquire()) {
...
} // released when $claim goes out of scope$claim = Swerve::claim('import');
if ($claim->acquire(timeout: 5.0)) { // tries every 20 ms for up to 5 s
import_feed();
$claim->release();
}See also#
Swerve::claimA handle on the name$name, which one holder at a time can hold across the workers.Swerve::cacheThe cache every worker shares, held by the master process.Swerve::drainingWhether this worker drains: it is shutting down, reloading or being recycled.