blib/lib/Punk/Observe/Backend/Pg.pm

filter: Statementstmt 65.5% 19 / 29 Branchbran 0.0% 0 / 4 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 85.7% 6 / 7 Podpod n/a totaltotal 62.5% 25 / 40 CC 3 SCAR 15.4
CC
3
Cov
58%
_locked
12.0
BEGIN
1.0
BEGIN
1.0
CRAP 4.7
« blib/lib/Punk/Observe/Backend.pm ↑ Summary blib/lib/Punk/Observe/Backend/SQLite.pm »
1 package Punk::Observe::Backend::Pg;
2  
3 1 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 1 ▶use parent -norequire, 'Punk::Observe::Backend';
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 1 ▶use Punk::Observe ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 1 our $VERSION = $Punk::Observe::VERSION;
12  
13 # The key for pg_advisory_lock. Chosen once and written down rather than
14 # hashed at runtime: a key that varies with a Perl version, or with hash
15 # randomisation, is a lock two processes do not share.
16 #
17 # IT FITS A 32-BIT IV, deliberately. `pg_advisory_lock` takes a bigint and the
18 # obvious thing is to use the range - but several supported perls have a
19 # 32-bit IV, where a 17-digit constant becomes an NV and reaches DBI as a
20 # float. The lock would then be taken on a different key, or on none, on
21 # exactly the platforms nobody tests interactively.
22 1 ▶use constant MIGRATE_LOCK => 1_953_657_198; # "po" in the low bytes
Subroutine BEGIN: called CC=1 SCAR=0.0
23  
24 # AN ADVISORY LOCK, NOT A TABLE LOCK.
25 #
26 # PostgreSQL has a real one, so unlike SQLite there is no need to make the
27 # transaction do double duty. `pg_advisory_lock` blocks until it is granted
28 # and is held until unlocked or the session ends - so a worker killed mid
29 # migration releases it by disconnecting, rather than leaving a row behind
30 # that the next boot has to reason about.
31 #
32 # Session-scoped rather than transaction-scoped, deliberately: the migration
33 # runs several statements and PostgreSQL is happy to run DDL inside a
34 # transaction, but the caller may already own one and
35 # `pg_advisory_xact_lock` would then release at their commit rather than ours.
36 0 ▶sub _locked {
Subroutine _locked: not called CC=3 SCAR=24.8
37 0 my ($self, $code) = @_;
38 0 my $dbh = $self->dbh;
39  
40 0 $dbh->do('SELECT pg_advisory_lock(?)', undef, MIGRATE_LOCK);
41 0 my @r = eval { $code->() };
42 0 my $err = $@;
43 # Released whatever happened. A lock leaked here is a boot that hangs
44 # forever the next time, which is a worse failure than the one that
45 # caused it.
46 0 eval { $dbh->do('SELECT pg_advisory_unlock(?)', undef, MIGRATE_LOCK) };
47 0 ▶ die $err if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 0 0
48 0 ▶ return wantarray ? @r : $r[0];
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
49 }
50  
51 1 1;
52  
53 __END__
« blib/lib/Punk/Observe/Backend.pm ↑ Summary blib/lib/Punk/Observe/Backend/SQLite.pm »