Local whole-file synchronization for PHP 8.4+. One implementation of native file locking, with explicit ownership, bounded waiting and stable lock files.
Development status: the monotonic clock API currently lives in the Componenta Clock refactoring branch. This repository is a development package, not a published stable release. Its Composer manifest temporarily requires that exact branch; a consuming root project would need to make the development dependency available itself.
All types are in Componenta\Stdlib.
| Type | Contract |
|---|---|
LockMode |
Shared (multiple cooperating readers), Exclusive (one owner). |
ResourceFileLock |
Acquire on an already-open native regular-file stream supplied by the caller. |
FileLock |
Open/create a separate stable lock file without truncating it; own its descriptor. |
FileLockGuard |
Single acquired lock; explicit idempotent release after successful release. |
FileLockSet |
All-or-nothing acquisition of a list of stable lock files in a consistent device/inode order. |
Each acquisition facade offers:
| Method | Result |
|---|---|
acquire(stream/path/paths, LockMode) |
Wait indefinitely for ownership (no library-imposed timeout). |
tryAcquire(stream/path/paths, LockMode) |
Return the guard/set, or null only for actual contention. |
acquireUntil(stream/path/paths, LockMode, Deadline, ?SleeperInterface) |
Wait with a monotonic deadline; throw FileLockTimeoutException if expired. |
For a single lock, the result is FileLockGuard; for a list of paths, it is FileLockSet. A deadline must still be live when a native attempt starts. Use tryAcquire() for an immediate attempt, including a zero waiting budget. An attempt begun before expiry may finish later: this is not a hard real-time deadline or a filesystem I/O timeout. Waiting polls only on contention and sleeps at most about one millisecond between attempts (rounding fractional microseconds upward, with a minimum positive sleep of one microsecond); the optional sleeper is primarily for testing and application waiting policies.
Call release() in a finally block. Destruction is best-effort fallback and does not report cleanup failures. FileLockGuard::isHeld() reports logical ownership of a still-open stream in the original process, not an independent kernel query. Guards and sets cannot be cloned or serialized.
- Borrowed streams must be native, open, regular local files. The caller must exclusively control their lock state, must not close, re-lock or otherwise manipulate that state during acquisition or while a guard is live, and must flush writes before releasing. Borrowed streams are never closed by the library. A second Componenta guard on the exact same live PHP resource is rejected; separately duplicated OS descriptors or external native locking are outside that check.
- Stable lock paths must be in an existing, application-private, trusted directory. All participating processes must agree on the same lock-file identity and locking protocol. The library never removes lock files, including on contention and failure. Do not rotate, rename or delete active lock files. Lock-file creation obeys the process umask; the caller owns directory permissions. Do not write application data into lock files.
- The opened descriptor is inspected; if the native metadata omits the inode, it is inspected once more without reopening the file. A still-missing identity is an infrastructure failure. Its immutable device/inode identity is compared with fresh directory-entry metadata before and after acquisition, and again between timed attempts. A path replacement observed during contention is an infrastructure error, not a timeout. POSIX symbolic/hard links and nonregular targets are rejected; nonblocking open avoids waiting on a substituted FIFO. These checks are defense in depth, not a guarantee against an attacker able to mutate the directory concurrently.
- For data files published by atomic rename, lock a separate stable file. A lock on the old data inode does not protect the new inode. Atomic file publication, flushing and durability are separate concerns.
- A set opens every distinct normalized path before locking, rejects different paths referring to one file, acquires in the same device/inode order, and releases partial acquisitions in reverse order. A shared deadline is not reset for each file. Duplicate normalized paths are deduplicated; an empty set is a no-op. Use the set API consistently for multi-resource operations: unrelated nested acquisitions or different protocols can still deadlock.
- Locks follow the platform's native
flock()semantics. This is not a distributed lock, lease, fencing mechanism, mandatory security boundary, fair queue or guarantee on arbitrary network filesystems or process-level-locking threaded SAPIs. Linux/POSIX advisory and Windows locking semantics differ. Only use filesystems with working whole-file locking and usable file identity. See the PHP documentation. - Do not use inherited guards or lock sets after forking, or pass them between processes. Explicit release of an inherited live guard or set is rejected before its ownership state changes. A child must acquire independently opened descriptors; the destructor does not explicitly unlock a parent's inherited guard. POSIX lock-file descriptors use close-on-exec.
The exceptions in Componenta\Stdlib\Exception implement FileLockExceptionInterface: FileLockFailureException (I/O or native failures), FileLockTimeoutException (elapsed deadline), FileLockCleanupException (retains both earlier and cleanup failures). Clock and sleeper runtime failures are reported as infrastructure errors, even when a collaborator throws an exception named like a lock timeout. Only expiry observed by the acquisition algorithm produces a timeout. Invalid arguments and ownership violations use standard argument/logic exceptions. Cleanup attempts every acquired resource even when a previous cleanup fails.
Run composer install and composer check (portable contract runner and maximum-level PHPStan). composer test:pest runs the same cases through Pest; composer coverage additionally reports parent-process coverage when a coverage driver is enabled. composer coverage:processes (Python 3 and Xdebug on Linux) merges actual child-process line hits into the executable-line set from Pest's Clover report. Workers terminated by a signal cannot flush their coverage. CI targets PHP 8.4 and 8.5 on Linux and Windows; Pest and coverage are exercised on Linux to avoid silent empty-suite discovery on Windows. The same contract cases can run without Composer: set COMPONENTA_CLOCK_SRC to the actual Clock refactoring checkout's src directory and run php tests/run.php. Multiprocess cases need proc_open and a local filesystem supporting flock().
Run composer mutation on Linux with Python 3 and Xdebug. Infection enumerates the default-profile AST mutants across the entire source tree, including uncovered lines. Each mutant is physically installed in an isolated copy of the package before the real contract suite runs, so child processes test the mutant rather than the original. The report in .mutation/results.json distinguishes failed assertions, survivors, timeouts, invalid mutations and unexpected process errors. Only failed contract checks count as kills in the strict score; no blanket exclusions or automatic timeout credit. CI also runs the exact Linux non-killed mutations on Windows, checking identical source, test and Clock dependency manifests. The cross-platform report uses the same denominator, credits a mutation only once when detected on either platform, and keeps Linux and Windows counts separate.
CI enforces a minimum of 90% for merged process line coverage and the strict cross-platform mutation score, using exact counts rather than rounded percentages. The complete denominator remains intact. See the 2026-11-30 mutation audit for the residual-mutation review.
This package deliberately does not depend on file readers, file writers, Session, HTTP middleware, DI or Symfony Lock.