2 # Copyright (C) 2021 all contributors <meta@public-inbox.org>
3 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 use strict; use v5.10.1; use PublicInbox::TestCommon;
7 use PublicInbox::DS qw(now);
9 use PublicInbox::OnDestroy;
10 use_ok 'PublicInbox::MboxLock';
11 my ($tmpdir, $for_destroy) = tmpdir();
13 my $mbl = PublicInbox::MboxLock->acq($f, 1, ['dotlock']);
14 ok(-f "$f.lock", 'dotlock created');
16 ok(!-f "$f.lock", 'dotlock gone');
17 $mbl = PublicInbox::MboxLock->acq($f, 1, ['none']);
18 ok(!-f "$f.lock", 'no dotlock with none');
21 opendir my $cur, '.' or BAIL_OUT $!;
22 my $od = on_destroy \&chdir, $cur;
24 my $abs = "$tmpdir/rel.lock";
25 my $rel = PublicInbox::MboxLock->acq('rel', 1, ['dotlock']);
27 ok(-f $abs, 'lock with abs path created');
29 ok(!-f $abs, 'lock gone despite being in the wrong dir');
33 PublicInbox::MboxLock->acq($f, 1, ['bogus']);
34 fail "should not succeed with `bogus'";
36 ok($@, "fails on `bogus' lock method");
38 PublicInbox::MboxLock->acq($f, 1, ['timeout=1']);
39 fail "should not succeed with only timeout";
41 ok($@, "fails with only `timeout=' and no lock method");
43 my $defaults = PublicInbox::MboxLock->defaults;
44 is(ref($defaults), 'ARRAY', 'default lock methods');
45 my $test_rw_lock = sub {
47 my $m = ["$func,timeout=0.000001"];
49 pipe(my ($r, $w)) or BAIL_OUT "pipe: $!";
51 my $pid = fork // BAIL_OUT "fork $!";
53 eval { PublicInbox::MboxLock->acq($f, 1, $m) };
55 syswrite $w, "E: $err";
60 is($?, 0, "$func r/w lock behaved as expected #$i");
62 ok($d < 1, "$func r/w timeout #$i") or diag "elapsed=$d";
63 my $err = do { local $/; <$r> };
66 like($err, qr/\Q$msg\E/, "got EAGAIN in child #$i");
70 my $test_ro_lock = sub {
74 my $pid = fork // BAIL_OUT "fork $!";
76 eval { PublicInbox::MboxLock->acq($f, 0, [ $func ]) };
80 is($?, 0, "$func ro lock behaved as expected #$i");
82 ok($d < 1, "$func timeout respected #$i") or diag "elapsed=$d";
87 grep(/fcntl/, @$defaults) or skip 'File::FcntlLock not available', 1;
88 my $top = PublicInbox::MboxLock->acq($f, 1, $defaults);
89 ok($top, 'fcntl lock acquired');
90 $test_rw_lock->('fcntl');
92 $top = PublicInbox::MboxLock->acq($f, 0, $defaults);
93 ok($top, 'fcntl read lock acquired');
94 $test_ro_lock->('fcntl');
96 $mbl = PublicInbox::MboxLock->acq($f, 1, ['flock']);
97 ok($mbl, 'flock acquired');
98 $test_rw_lock->('flock');
100 $mbl = PublicInbox::MboxLock->acq($f, 0, ['flock']);
101 $test_ro_lock->('flock');