blib/lib/Mojolicious/Plugin/Buffer/Lock/File.pm

filter: Statementstmt 99.0% 107 / 108 Branchbran 62.5% 15 / 24 Conditioncond 41.1% 7 / 17 MC/DCmcdc 9.0% 1 / 11 Subroutinesub 100% 26 / 26 Podpod 100% 3 / 3 totaltotal 84.1% 159 / 189 CC 19 SCAR 13.1
CC
19
Cov
87%
new
9.1
acquire
6.1
release
4.4
CRAP 3.7
« examples/hypnotoad/lib/MyApp.pm ↑ Summary blib/lib/Mojolicious/Plugin/Buffer/Lock/Redis.pm »
1 package Mojolicious::Plugin::Buffer::Lock::File;
2  
3 37 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 37 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 37 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 37 ▶use Mojo::Base -base;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 37 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 37 ▶use Fcntl qw(:flock O_CREAT O_RDWR);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 37 ▶use File::Path ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 37 ▶use File::Spec ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 37 ▶use Mojo::Util qw(encode md5_sum trim);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 37 ▶use Mojolicious::Plugin::Buffer::I18N qw(i18n);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 37 ▶use Params::Get qw(get_params);
Subroutine BEGIN: called CC=1 SCAR=0.0
16 37 ▶use Params::Validate::Strict qw(validate_strict);
Subroutine BEGIN: called CC=1 SCAR=0.0
17 37 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 37 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
19 37 ▶use Sub::Private { mode => 'enforce' };
Subroutine BEGIN: called CC=1 SCAR=0.0
20 37 ▶use Sub::Protected;
Subroutine BEGIN: called CC=1 SCAR=0.0
21  
22 37 ▶use version; our $VERSION = version->declare('0.002.0');
Subroutine BEGIN: called CC=1 SCAR=0.0
23  
24 # Lock files are created world-readable/writable before the umask is applied,
25 # so the directory's permissions decide who may take a lock
26 37 Readonly::Scalar my $LOCK_FILE_MODE => oct('0666');
27 37 Readonly::Scalar my $LOCK_FILE_SUFFIX => '.lock';
28  
29 37 has dir => undef;
30 37 has messages => undef;
31  
32 =encoding utf8
33  
34 =head1 NAME
35  
36 Mojolicious::Plugin::Buffer::Lock::File - flock-based lock backend
37  
38 =head1 VERSION
39  
40 Version 0.002.0
41  
42 =head1 SYNOPSIS
43  
44 The usual way: give the plugin a directory and let it build this backend.
45  
46 use Mojolicious::Lite;
47 use CHI;
48  
49 plugin 'Buffer' => {
50 cache => CHI->new(driver => 'File', root_dir => '/var/cache/myapp'),
51 cache_lock_dir => '/var/lib/myapp/buffer-locks',
52 };
53  
54 Build the backend yourself, for example to reword its messages, and pass it
55 as C<cache_lock>:
56  
57 use Mojolicious::Plugin::Buffer::Lock::File;
58  
59 my $lock = Mojolicious::Plugin::Buffer::Lock::File->new(
60 dir => '/var/lib/myapp/buffer-locks',
61 messages => {lock_failed => 'lock %{path} is broken: %{error}'},
62 );
63 plugin 'Buffer' => {cache => $cache, cache_lock => $lock};
64  
65 Use it on its own, for example so that only one copy of a cron job rebuilds
66 a report at a time:
67  
68 use Mojolicious::Plugin::Buffer::Lock::File;
69  
70 my $lock = Mojolicious::Plugin::Buffer::Lock::File->new(dir => '/run/myapp');
71  
72 # Always take BOTH return values (see COMMON PITFALLS)
73 my ($guard, $error) = $lock->acquire('nightly-report');
74 die "$error\n" if defined $error;
75 exit 0 unless $guard; # another copy is already running
76  
77 build_report();
78 $lock->release($guard);
79  
80 Spread the lock files over sub-directories by overriding the protected
81 C<_path> method in a subclass:
82  
83 package MyApp::Lock;
84 use Mojo::Base 'Mojolicious::Plugin::Buffer::Lock::File';
85 use File::Path ();
86 use File::Spec ();
87 use Mojo::Util qw(encode md5_sum);
88  
89 sub _path {
90 my ($self, $key) = @_;
91 my $digest = md5_sum(encode('UTF-8', $key));
92 my $sub = File::Spec->catdir($self->dir, substr($digest, 0, 2));
93 File::Path::make_path($sub);
94 return File::Spec->catfile($sub, "$digest.lock");
95 }
96  
97 =head1 DESCRIPTION
98  
99 This is the built-in lock backend for L<Mojolicious::Plugin::Buffer>. The
100 plugin uses it when you set
101 L<cache_lock_dir|Mojolicious::Plugin::Buffer/cache_lock_dir>.
102  
103 =head2 What problem does it solve?
104  
105 A web server often runs several copies of your program at the same time.
106 Each copy is called a I<worker>. When a page is not in the cache yet, every
107 worker that gets a request for it would build the same page at the same
108 time. That wastes work. A I<lock> lets exactly one worker build the page.
109 The other workers wait, then read the finished page from the cache.
110  
111 =head2 How it works, in plain words
112  
113 =over 4
114  
115 =item 1. Each cache key gets its own small, empty file in L</dir>. The file
116 name is the MD5 digest of the key, so any key makes a safe file name.
117  
118 =item 2. To take the lock, the backend opens that file and asks the operating
119 system for an exclusive lock on it (C<flock>). It does not wait: if another
120 open file handle already holds the lock, the answer is "busy" at once.
121  
122 =item 3. The lock lasts as long as the file stays open. The open file lives
123 inside the I<guard> that L</acquire> returns.
124  
125 =item 4. L</release> closes the file, which frees the lock. If the process
126 crashes or is killed, the operating system closes the file and frees the
127 lock too. So a dead worker can never block a key for ever.
128  
129 =back
130  
131 All workers must use the same directory. This works for workers on one
132 machine. For workers on different machines, use
133 L<Mojolicious::Plugin::Buffer::Lock::Redis>.
134  
135 =head2 Words used in this document
136  
137 =over 4
138  
139 =item key
140  
141 A text string that names one cache entry, for example C<buffer:0123abcd>.
142  
143 =item guard
144  
145 The value L</acquire> returns when you get the lock. Keep it, and give it
146 back to L</release>. Do not look inside it.
147  
148 =item flock
149  
150 The operating system's file-locking call. Only one open file handle can
151 hold an exclusive C<flock> on a file at a time.
152  
153 =back
154  
155 =head1 ATTRIBUTES
156  
157 Attributes are set with L</new>. Each one also has an accessor method with
158 the same name, made by L<Mojo::Base>.
159  
160 =head2 dir
161  
162 The directory that holds the lock files. It is required. L</new> creates it
163 (and any missing parent directories) and checks that it is writable.
164  
165 =head3 API SPECIFICATION
166  
167 =head4 Input
168  
169 # $lock->dir reads the value. $lock->dir($path) changes it WITHOUT
170 # creating or checking the directory; see COMMON PITFALLS.
171 { dir => { type => 'string', min => 1, optional => 1 } }
172  
173 =head4 Output
174  
175 # Return::Set schema: the path when reading, the object when writing
176 { type => 'string' }
177  
178 =head2 messages
179  
180 An optional hash of message overrides, keyed by message key. See
181 L<Mojolicious::Plugin::Buffer::I18N> for the keys and the text format. The
182 plugin passes its own C<messages> option here when it builds this backend
183 from C<cache_lock_dir>.
184  
185 =head3 API SPECIFICATION
186  
187 =head4 Input
188  
189 { messages => { type => 'hashref', optional => 1 } }
190  
191 =head4 Output
192  
193 # Return::Set schema: the hash (or undef) when reading, the object
194 # when writing
195 { type => 'hashref', optional => 1 }
196  
197 =head1 METHODS
198  
199 =head2 new
200  
201 my $lock = Mojolicious::Plugin::Buffer::Lock::File->new(dir => $dir);
202  
203 =head3 Purpose
204  
205 Create the backend, creating the lock directory if necessary.
206  
207 =head3 Arguments
208  
209 =over 4
210  
211 =item C<dir> (named, required)
212  
213 A directory path, as a non-empty string.
214  
215 =item C<messages> (named, optional)
216  
217 A hash of message overrides.
218  
219 =back
220  
221 =head3 Returns
222  
223 The new object.
224  
225 =head3 Side effects
226  
227 Creates C<dir> and any missing parents.
228  
229 =head3 Example
230  
231 my $lock = Mojolicious::Plugin::Buffer::Lock::File->new(
232 dir => '/var/lib/myapp/buffer-locks',
233 );
234  
235 =head3 API SPECIFICATION
236  
237 =head4 Input
238  
239 {
240 dir => { type => 'string', min => 1 },
241 messages => { type => 'hashref', optional => 1 },
242 }
243  
244 =head4 Output
245  
246 # Return::Set schema
247 { type => 'object', isa => 'Mojolicious::Plugin::Buffer::Lock::File' }
248  
249 =head3 MESSAGES
250  
251 Key Message Resolution
252 ---------------------- ---------------------------------------------- ---------------------------------
253 option_cache_lock_dir cache_lock_dir must be a directory path Pass a non-empty string
254 lock_dir_create_failed cannot create cache_lock_dir 'DIR': OS ERROR Fix the parent's permissions, or
255 the path (e.g. a file is in the
256 way)
257 lock_dir_not_writable cache_lock_dir 'DIR' is not a writable Change the owner or mode of DIR
258 directory
259  
260 All three croak. The OS error is Perl's C<$!> text and follows the
261 process's C<LC_MESSAGES> only inside C<use locale>.
262  
263 =cut
264  
265 43 ▶sub new {
Subroutine new: called CC=8 SCAR=22.1
Pod documented
266 43 my ($class, @args) = @_;
267  
268 # Params::Get accepts both new(dir => ...) and new({dir => ...})
269 43 ▶ my $self = $class->SUPER::new(get_params(undef, @args) // {});
Condition50%1/2
get_params(undef, @args) // {}
l!l
430
MC/DC0%0/1
get_params(undef, @args) // {}
get_params(undef, @args)
Truth table50%1/2
A
A= get_params(undef, @args)
Aresult
11
00
270 43 my $dir = $self->dir;
271  
272 43 ▶ croak $self->i18n('option_cache_lock_dir') unless _valid_dir($dir);
Branch: 1 branch
BranchTrueFalseTotal
unless _valid_dir($dir) 0 43 43
273  
274 # Ask File::Path for structured errors: plain $! text per path, without
275 # the "at FILE line N" its own die would add. The last entry is about
276 # the directory itself, which is the one the user named.
277 43 File::Path::make_path($dir, {error => \my $errors});
278 43 ▶ if ($errors && @$errors) {
Branch: 1 branch
BranchTrueFalseTotal
if ($errors and @$errors) 14 29 43
Condition66%2/3
$errors and @$errors
!ll&&!rl&&r
02914
MC/DC50%1/2
$errors and @$errors
$errors @$errors
Truth table66%2/3
A and B
A= $errorsB= @$errors
ABresult
0X0
100
111
279 14 my ($path, $message) = %{$errors->[-1]};
280 14 ▶ croak $self->i18n('lock_dir_create_failed', {dir => $dir, error => length($path) ? "$path: $message" : $message});
Branch: 1 branch
BranchTrueFalseTotal
length $path ? : 14 0 14
281 }
282 29 ▶ croak $self->i18n('lock_dir_not_writable', {dir => $dir}) unless -d $dir && -w $dir;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $dir and -w $dir 0 29 29
Condition33%1/3
-d $dir and -w $dir
!ll&&!rl&&r
0029
MC/DC0%0/2
-d $dir and -w $dir
-d $dir -w $dir
Truth table33%1/3
A and B
A= -d $dirB= -w $dir
ABresult
0X0
100
111
283  
284 29 return $self;
285 }
286  
287 =head2 acquire
288  
289 my ($guard, $error) = $lock->acquire($key);
290  
291 =head3 Purpose
292  
293 Try, without waiting, to become the only process building C<$key>.
294  
295 =head3 Arguments
296  
297 =over 4
298  
299 =item C<$key> (positional, required)
300  
301 The cache key: any defined string, in any language, emoji included. Only
302 its MD5 digest reaches the file system.
303  
304 =back
305  
306 =head3 Returns
307  
308 A two-element list, as the lock protocol in
309 L<Mojolicious::Plugin::Buffer/cache_lock> requires: C<($guard, undef)> when
310 the lock was taken, C<(undef, undef)> when another process holds it, and
311 C<(undef, $error)> on failure. The guard is opaque. Call it in list
312 context; see L</COMMON PITFALLS>.
313  
314 =head3 Side effects
315  
316 Creates the lock file if it does not exist and keeps it open while the
317 guard lives.
318  
319 =head3 Example
320  
321 my ($guard, $error) = $lock->acquire('buffer:0123abcd');
322 if ($guard) {
323 # ... build the entry ...
324 $lock->release($guard);
325 } elsif (defined $error) {
326 warn $error;
327 } else {
328 # somebody else is building it
329 }
330  
331 =head3 API SPECIFICATION
332  
333 =head4 Input
334  
335 { key => { type => 'string', position => 0 } }
336  
337 =head4 Output
338  
339 # Return::Set schema (list of two)
340 {
341 type => 'arrayref',
342 schema => [
343 { type => 'hashref', optional => 1 }, # guard
344 { type => 'string', optional => 1 }, # error
345 ],
346 }
347  
348 =head3 MESSAGES
349  
350 Key Message Resolution
351 ------------------ ----------------------------- ---------------------------------
352 lock_key_undefined cache key is not defined Pass a defined key
353 lock_open_failed cannot open PATH: OS ERROR Check the directory still exists
354 and is writable
355 lock_failed cannot lock PATH: OS ERROR The filesystem does not support
356 flock; use another backend
357  
358 These are returned, not thrown.
359  
360 =head3 PSEUDOCODE
361  
362 reject an undefined key
363 open (creating) DIR/md5(key).lock
364 on failure return the OS error
365 try a non-blocking exclusive flock
366 if it succeeded, return a guard holding the handle
367 close the handle
368 if flock said "would block", return (undef, undef)
369 otherwise return the OS error
370  
371 =cut
372  
373 54 ▶sub acquire {
Subroutine acquire: called CC=6 SCAR=18.1
Pod documented
374 54 my ($self, @args) = @_;
375  
376 # get_params() confesses on an empty list; no key is a returned error
377 54 ▶ my $key = @args ? get_params('key', @args)->{key} : undef;
Branch: 1 branch
BranchTrueFalseTotal
@args ? : 54 0 54
378 54 ▶ return (undef, $self->i18n('lock_key_undefined')) unless defined($key);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key 0 54 54
379  
380 54 my $path = $self->_path($key);
381  
382 # autodie turns a failed sysopen into an exception carrying $!
383 54 my $fh = eval { sysopen(my $handle, $path, O_RDWR | O_CREAT, $LOCK_FILE_MODE); $handle };
384 54 ▶ return (undef, $self->i18n('lock_open_failed', {path => $path, error => _os_error($@)})) unless $fh;
Branch: 1 branch
BranchTrueFalseTotal
unless $fh 6 48 54
385  
386 # autodie does not throw when a LOCK_NB flock would block: it returns
387 # false, which is the "somebody else holds it" answer
388 48 my $locked = eval { flock($fh, LOCK_EX | LOCK_NB) };
389 48 my $error = $@;
390 48 ▶ return ({fh => $fh, path => $path}, undef) if $locked;
Branch: 1 branch
BranchTrueFalseTotal
if $locked 24 24 48
391  
392 24 eval { close($fh) };
393 24 ▶ return (undef, undef) unless $error;
Branch: 1 branch
BranchTrueFalseTotal
unless $error 24 0 24
394 0 return (undef, $self->i18n('lock_failed', {path => $path, error => _os_error($error)}));
395 }
396  
397 =head2 release
398  
399 my ($ok, $error) = $lock->release($guard);
400  
401 =head3 Purpose
402  
403 Give up a lock taken by L</acquire>.
404  
405 =head3 Arguments
406  
407 =over 4
408  
409 =item C<$guard> (positional, required)
410  
411 A guard returned by L</acquire>. A false value, or a guard that was already
412 released, is accepted and ignored.
413  
414 =back
415  
416 =head3 Returns
417  
418 C<(1, undef)> on success, C<(0, $error)> if unlocking or closing failed. The
419 lock is gone either way, because the handle is closed.
420  
421 =head3 Side effects
422  
423 Unlocks and closes the lock file handle and removes it from the guard.
424  
425 =head3 Example
426  
427 my ($ok, $error) = $lock->release($guard);
428 warn $error unless $ok;
429  
430 =head3 API SPECIFICATION
431  
432 =head4 Input
433  
434 { guard => { type => 'hashref', optional => 1, position => 0 } }
435  
436 =head4 Output
437  
438 # Return::Set schema (list of two)
439 {
440 type => 'arrayref',
441 schema => [
442 { type => 'boolean' }, # released
443 { type => 'string', optional => 1 }, # error
444 ],
445 }
446  
447 =head3 MESSAGES
448  
449 Key Message Resolution
450 ------------- ----------------------------- -------------------------
451 unlock_failed cannot unlock PATH: OS ERROR Usually harmless: closing
452 the handle drops the lock
453  
454 =cut
455  
456 24 ▶sub release {
Subroutine release: called CC=4 SCAR=14.8
Pod documented
457 24 my ($self, $guard) = @_;
458  
459 24 ▶ my $fh = (ref($guard) eq 'HASH') ? delete($guard->{fh}) : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $guard eq 'HASH' ? : 24 0 24
460 24 ▶ my $ok = !$fh || eval { flock($fh, LOCK_UN); close($fh); 1 };
Condition33%1/3
!$fh || eval { do { &Mojolicious::Plugin::Buffer::Lock::File::flock($fh, 8); &Mojolicious::Plugin::Buffer::Lock::File::close($fh); 1 } }
l!l&&r!l&&!r
0240
MC/DC0%0/2
!$fh || eval { do { &Mojolicious::Plugin::Buffer::Lock::File::flock($fh, 8); &Mojolicious::Plugin::Buffer::Lock::File::close($fh); 1 } }
!$fh eval { do { &Mojolicious::Plugin::Buffer::Lock::File::flock($fh, 8); &Mojolicious::Plugin::Buffer::Lock::File::close($fh); 1 } }
Truth table33%1/3
not(A) || B
A= !$fhB= eval { do { &Mojolicious::Plugin::Buffer::Lock::File::flock($fh, 8); &Mojolicious::Plugin::Buffer::Lock::File::close($fh); 1 } }
ABresult
1X1
011
000
461  
462 # The handle is gone either way, so the lock is gone too; only report
463 return $ok
464 ? (1, undef)
465 24 ▶ : (0, $self->i18n('unlock_failed', {path => $guard->{path}, error => _os_error($@)}));
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 24 0 24
466 }
467  
468 # Purpose: Map a cache key to its lock file path.
469 # Entry criteria: $key is a defined string.
470 # Exit status: An absolute or dir-relative path ending in .lock.
471 # Side effects: None. Protected so a subclass can share a directory
472 # layout, e.g. sharding the files into subdirectories.
473 54 ▶sub _path :Protected {
Subroutine _path: called CC=1 SCAR=0.0
474 54 my ($self, $key) = @_;
475  
476 # md5_sum dies on characters above 255, so hash the UTF-8 bytes
477 54 return File::Spec->catfile($self->dir, md5_sum(encode('UTF-8', $key)) . $LOCK_FILE_SUFFIX);
478 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
479  
480 # Purpose: Check that a value can name the lock directory.
481 # Entry criteria: Any scalar.
482 # Exit status: True for a non-empty, non-reference string.
483 # Side effects: None.
484 43 ▶sub _valid_dir :Private {
Subroutine _valid_dir: called CC=2 SCAR=7.4
485 43 my $dir = shift;
486  
487 43 ▶ return eval { validate_strict(schema => {dir => {type => 'string', min => 1}}, input => {dir => $dir}); 1 } && !ref($dir);
Condition33%1/3
eval { do { validate_strict('schema', {'dir', {'type', 'string', 'min', 1}}, 'input', {'dir', $dir}); 1 } } && !ref($dir)
!ll&&!rl&&r
0043
MC/DC0%0/2
eval { do { validate_strict('schema', {'dir', {'type', 'string', 'min', 1}}, 'input', {'dir', $dir}); 1 } } && !ref($dir)
eval { do { validate_strict('schema', {'dir', {'type', 'string', 'min', 1}}, 'input', {'dir', $dir}); 1 } } !ref($dir)
Truth table33%1/3
A && not(B)
A= eval { do { validate_strict('schema', {'dir', {'type', 'string', 'min', 1}}, 'input', {'dir', $dir}); 1 } }B= !ref($dir)
ABresult
0X0
100
111
488 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
489  
490 # Purpose: Extract the OS error text from an exception.
491 # Entry criteria: An autodie::exception, or any other exception.
492 # Exit status: The $! text for an autodie exception, else the trimmed
493 # exception text.
494 # Side effects: None.
495 6 ▶sub _os_error :Private {
Subroutine _os_error: called CC=3 SCAR=13.1
496 6 my $exception = shift;
497  
498 6 ▶ return (blessed($exception) && $exception->isa('autodie::exception'))
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($exception) && $exception->isa('autodie::exception') ? : 6 0 6
Condition33%1/3
builtin::blessed($exception) and $exception->isa("autodie::exception")
!ll&&!rl&&r
006
MC/DC0%0/2
builtin::blessed($exception) and $exception->isa("autodie::exception")
builtin::blessed($exception) $exception->isa("autodie::exception")
Truth table33%1/3
A and B
A= builtin::blessed($exception)B= $exception->isa("autodie::exception")
ABresult
0X0
100
111
499 ? '' . $exception->errno
500 : trim("$exception");
501 37 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
502  
503 37 1;
504  
505 =head1 COMMON PITFALLS
506  
507 =over 4
508  
509 =item * B<Always take both return values.> L</acquire> returns a list of
510 two values. In scalar context Perl gives you only the I<last> one, which is
511 the error slot:
512  
513 my $guard = $lock->acquire($key); # WRONG: $guard is undef
514 my ($guard, $error) = $lock->acquire($key); # right
515  
516 The wrong form is worse than it looks. The real guard is thrown away at
517 once, which closes the file, so the lock you just took is released before
518 the next line runs.
519  
520 =item * B<Keep the guard while you work.> The lock lives inside the guard.
521 If the guard variable goes out of scope, the file is closed and the lock is
522 freed, even though you never called L</release>.
523  
524 =item * B<The lock is not re-entrant.> If your own process already holds
525 the lock for a key, a second C<acquire> for the same key returns "busy"
526 C<(undef, undef)>. This is true even for the same object, because each call
527 opens a new file handle.
528  
529 =item * B<Forking while you hold a lock shares it.> A child process made
530 with C<fork> inherits the open file, so the lock stays held until the parent
531 I<and> the child have closed it. Release locks before you fork.
532  
533 =item * B<Do not change C<dir> after C<new>.> L</new> creates and checks the
534 directory. Setting it later with C<< $lock->dir($path) >> skips both checks,
535 so a typing mistake only shows up as an error from every L</acquire>.
536  
537 =item * B<Lock files are never deleted.> There is one empty file per key
538 that was ever built. Deleting a file while another process has it open
539 would let two builders run, so only clean the directory while the
540 application is stopped.
541  
542 =item * B<Network file systems.> C<flock> is unreliable on some network
543 file systems, especially older NFS. Use
544 L<Mojolicious::Plugin::Buffer::Lock::Redis> when workers are on different
545 machines.
546  
547 =item * B<undef values.> C<acquire(undef)> does not die; it returns
548 C<(undef, 'cache key is not defined')>. The empty string is a valid key.
549 C<release(undef)> and releasing the same guard twice both return
550 C<(1, undef)> and do nothing. C<< new(dir =E<gt> undef) >> croaks.
551 C<< messages =E<gt> undef >> means "no overrides".
552  
553 =back
554  
555 =head1 ENCODING
556  
557 =over 4
558  
559 =item Keys
560  
561 Any Perl string is safe, including accented letters, any other non-ASCII
562 text and emoji. The key is encoded as UTF-8 bytes before it is hashed, so
563 the same characters always name the same lock file, however Perl stores
564 them internally. Only the MD5 digest reaches the file system. A subclass
565 that overrides C<_path> must do the same, because C<md5_sum> dies on a
566 character above U+00FF.
567  
568 =item dir
569  
570 A directory name goes to the operating system as bytes. An ASCII path is
571 always safe. For a non-ASCII path, pass a byte string that is already
572 encoded the way your file system expects, usually UTF-8:
573  
574 use Encode qw(encode);
575 my $lock = Mojolicious::Plugin::Buffer::Lock::File->new(
576 dir => encode('UTF-8', "/srv/caf\x{e9}/locks"),
577 );
578  
579 =item messages
580  
581 Override texts may hold any characters, including emoji. The messages this
582 module returns are Perl character strings. Print them to a handle with an
583 encoding layer, such as C<binmode(STDERR, ':encoding(UTF-8)')>, or Perl
584 warns "Wide character". L<Mojo::Log> encodes to UTF-8 by itself.
585  
586 =item Operating-system errors
587  
588 The text after C<OS ERROR> in a message is Perl's C<$!>. It is English
589 unless the program runs under C<use locale>.
590  
591 =back
592  
593 =head1 LIMITATIONS
594  
595 =over 4
596  
597 =item * Lock files are never deleted. Removing one while another process
598 has it open would let a third process lock a new file of the same name, and
599 two builders would run. They are empty, so the cost is one inode per key
600 ever built.
601  
602 =item * C<flock> is only advisory and is unreliable on some network
603 filesystems (older NFS in particular). Use the Redis backend there.
604  
605 =item * The protocol returns a two-element list rather than a reference,
606 because that is the documented interface third-party backends implement.
607  
608 =back
609  
610 =head1 SEE ALSO
611  
612 L<Mojolicious::Plugin::Buffer>, L<Mojolicious::Plugin::Buffer::Lock::Redis>,
613 L<Mojolicious::Plugin::Buffer::I18N>.
614  
615 =head1 AUTHOR
616  
617 Nigel Horne, C<< <njh at bandsman.co.uk> >>
618  
619 =head1 FORMAL SPECIFICATION
620  
621 This section describes the backend in the Z notation, for readers who want
622 an exact model. You do not need it to use the module. C<KEY> is the set of
623 cache keys, C<PATH> the set of file names and C<PID> the set of processes.
624 C<held> records which process holds the lock for each key.
625  
626 [KEY, PATH, PID, TEXT, Guard]
627  
628 file : KEY → PATH
629 ∀ k : KEY • file k = dir ⁀ "/" ⁀ md5(utf8(k)) ⁀ ".lock"
630  
631 ┌─ Locks ─────────────────────────────────────
632 │ dir : PATH
633 │ held : KEY ⇸ PID
634 ├─────────────────────────────────────────────
635 │ dir ≠ ∅
636 └─────────────────────────────────────────────
637  
638 ┌─ ProcessExit ───────────────────────────────
639 │ ΔLocks
640 │ p? : PID
641 ├─────────────────────────────────────────────
642 │ held′ = held ⩥ {p?}
643 └─────────────────────────────────────────────
644  
645 =head2 new
646  
647 ┌─ New ───────────────────────────────────────
648 │ Locks′
649 │ dir? : PATH ; fs, fs′ : PATH ⇸ Node ; result! : Locks
650 ├─────────────────────────────────────────────
651 │ dir? ≠ ∅
652 │ dir? ∈ dom fs′ ∧ isDirectory(fs′ dir?) ∧ writable(fs′ dir?)
653 │ fs ⊆ fs′
654 │ dir′ = dir? ∧ held′ = ∅ ∧ result! = θLocks′
655 └─────────────────────────────────────────────
656 -- Otherwise: croak, and fs′ may hold the parents created so far
657  
658 =head2 acquire
659  
660 C<ok> means the lock file could be opened and the file system supports
661 C<flock>. The lock is not re-entrant: when C<held key? = me> the result is
662 "busy", the same as for any other holder.
663  
664 ┌─ Acquire ───────────────────────────────────
665 │ ΔLocks
666 │ key? : KEY ; me : PID
667 │ guard! : Guard ∪ {⊥} ; error! : TEXT ∪ {⊥}
668 ├─────────────────────────────────────────────
669 │ ok ∧ key? ∉ dom held ⇒
670 │ held′ = held ⊕ {key? ↦ me} ∧ guard! ≠ ⊥ ∧ error! = ⊥
671 │ ok ∧ key? ∈ dom held ⇒
672 │ held′ = held ∧ guard! = ⊥ ∧ error! = ⊥
673 │ ¬ok ⇒
674 │ held′ = held ∧ guard! = ⊥ ∧ error! ≠ ⊥
675 └─────────────────────────────────────────────
676  
677 =head2 release
678  
679 ┌─ Release ───────────────────────────────────
680 │ ΔLocks
681 │ guard? : Guard ∪ {⊥} ; ok! : 𝔹 ; error! : TEXT ∪ {⊥}
682 ├─────────────────────────────────────────────
683 │ guard? ≠ ⊥ ⇒ held′ = {key(guard?)} ⩤ held
684 │ guard? = ⊥ ⇒ held′ = held ∧ ok! = true
685 │ ok! = true ⇔ error! = ⊥
686 └─────────────────────────────────────────────
687 -- The lock is gone even when ok! = false, because the handle is closed
688  
689 =head1 STATE DIAGRAM
690  
691 Each cache key's lock is in one of two states. The backend object itself
692 has no other state: after L</new> it is ready, and it stays ready. The
693 numbers on the arrows are explained below the picture.
694  
695 +-----------+ (1) +-----------+
696 | FREE | --------------------------> | HELD |
697 | (key k) | <-------------------------- | (key k) |
698 +-----------+ (2), (3) or (4) +-----------+
699 | ^ | ^
700 +-----+ (5), (7) +-----+ (6), (8)
701  
702 (1) acquire(k) [the file opens and flock is granted]
703 / returns (guard, undef); the file stays open inside the guard
704 (2) release(guard)
705 / unlock and close the file; returns (1, undef), or (0, error)
706 if unlocking failed - the lock is gone either way
707 (3) the guard goes out of scope
708 / Perl closes the file, which frees the lock
709 (4) the holding process exits or is killed
710 / the operating system closes the file, which frees the lock
711 (5) acquire(k) [the file cannot be opened, or flock is not supported]
712 / returns (undef, error); nothing changes
713 (6) acquire(k) [flock would block], from ANY process, the holder too
714 / returns (undef, undef); nothing changes
715 (7) release(undef), or release of a guard already released
716 / returns (1, undef); nothing changes
717 (8) fork()
718 / the child shares the open file, so the key stays HELD until
719 both processes have closed it
720  
721 The plugin's own use of these states is drawn in
722 L<Mojolicious::Plugin::Buffer/STATE DIAGRAM>.
723  
724 =head1 LICENSE AND COPYRIGHT
725  
726 Copyright 2026 Nigel Horne.
727  
728 This program is free software; you can redistribute it and/or modify it
729 under the terms of the GNU General Public License as published by the Free
730 Software Foundation; either version 2 of the License, or (at your option)
731 any later version.
732  
733 =cut
« examples/hypnotoad/lib/MyApp.pm ↑ Summary blib/lib/Mojolicious/Plugin/Buffer/Lock/Redis.pm »