NAME

AnyEvent::MCP::File - private state file locking and replacement

DESCRIPTION

Internal utility for small state files shared by MCP processes, such as the workdir ID registry. lock obtains a lock on the current pathname; replace writes a complete new version atomically. The caller owns serialization, validation and the lock's lifetime.

For example, after building a new complete file body:

use AnyEvent::MCP::File ();

my $lock = AnyEvent::MCP::File::lock $path;
# read and validate the current state under this lock
AnyEvent::MCP::File::replace $path, $new_bytes;
close $lock;

The lock protects cooperating writers, not other programs that write the file without this protocol. Use AnyEvent::MCP::Workdirs for the workdir registry rather than implementing its update rules here.

FUNCTIONS

$lock = AnyEvent::MCP::File::lock $file

Create the parent directory and file if necessary, and lock the current file exclusively. Retries if an atomic replacement changed the pathname while waiting for the lock. Keep the returned handle alive through reading, modifying and replacing the file. All writers must use this locking protocol.

AnyEvent::MCP::File::replace $file, $bytes

Write bytes to a temporary file beside $file, preserve the mode of an existing file, then atomically rename over $file. The caller holds the lock. Removes the temporary file on failure. This provides atomic visibility, not crash durability.