Fast/Connector.pm

filter: Statementstmt 91.7% 134 / 146 Branchbran 72.7% 32 / 44 Conditioncond 56.0% 14 / 25 MC/DCmcdc 50.0% 7 / 14 Subroutinesub 100% 17 / 17 Podpod 100% 2 / 2 totaltotal 83.0% 206 / 248 CC 32 SCAR 23.6
CC
32
Cov
84%
_neutralize_inherited
23.1
dbh
17.4
disconnect
3.1
CRAP 10.5
« Fast/Transaction.pm ↑ Summary Fast/Schema.pm »
1 package DBIx::Fast::Connector;
2  
3 36 ▶use v5.38;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 36 ▶use Object::Pad 0.807;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 36 our $VERSION = '0.20';
7 36 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 36 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 36 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 # --- Fork handling, per process ----------------------------------------------
12 #
13 # Handles this process opened: refaddr => [ weak $dbh, owner pid ].
14 36 my %OWNED;
15  
16 # DBD::MariaDB (1.24, the current CPAN release) ignores InactiveDestroy /
17 # AutoInactiveDestroy in the child: DBI's END calls disconnect_all(), which
18 # mysql_close()s every connection the driver knows - including the ones
19 # inherited from the parent - and the COM_QUIT on the shared socket makes the
20 # server drop the PARENT's connection (upstream DBD-MariaDB PR #175, issue
21 # #210). A child therefore points each inherited MariaDB socket at /dev/null
22 # before anything can close it: the driver frees its resources normally, the
23 # quit goes nowhere, and the parent's connection survives (the fix the driver's
24 # maintainer suggests in #175, done from Perl). Other drivers honour
25 # InactiveDestroy and only get that flag.
26 13 ▶sub _neutralize_inherited ($dbh) {
Subroutine _neutralize_inherited: called CC=7 SCAR=31.4
27 13 ▶ return unless $dbh;
Branch: 1 branch
BranchTrueFalseTotal
unless $dbh 3 10 13
28 10 eval {
29 10 ▶ if (($dbh->{Driver}{Name} // '') eq 'MariaDB') {
Branch: 1 branch
BranchTrueFalseTotal
if (($dbh->{"Driver"}{"Name"} // "") eq "MariaDB") 0 10 10
Condition50%1/2
$dbh->{"Driver"}{"Name"} // ""
l!l
100
MC/DC0%0/1
$dbh->{"Driver"}{"Name"} // ""
$dbh->{"Driver"}{"Name"}
Truth table50%1/2
A
A= $dbh->{"Driver"}{"Name"}
Aresult
11
00
30 0 my $fd = $dbh->{mariadb_sockfd};
31 0 ▶ if (defined $fd && $fd >= 0 && open my $null, '+<', '/dev/null') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $fd and $fd >= 0 and open my $null, "+<", "/dev/null") 0 0 0
Condition0%0/6
defined $fd and $fd >= 0 and open my $null, "+<", "/dev/null"
!ll&&!rl&&r
000
defined $fd and $fd >= 0
!ll&&!rl&&r
000
MC/DC0%0/3
defined $fd and $fd >= 0 and open my $null, "+<", "/dev/null"
defined $fd $fd >= 0 open my $null, "+<", "/dev/null"
Truth table0%0/4
A and B and C
A= defined $fdB= $fd >= 0C= open my $null, "+<", "/dev/null"
ABCresult
0XX0
10X0
1100
1111
32 0 POSIX::dup2(fileno($null), $fd);
33 # With the socket gone, a regular disconnect is harmless (the quit
34 # goes to /dev/null) and lets the driver release the handle and keep
35 # DBI's active-handle accounting straight (InactiveDestroy here ends in
36 # "panic: DBI active kids" and exit status 22 at the child's exit).
37 0 local $dbh->{HandleError};
38 0 local $dbh->{RaiseError} = 0;
39 0 local $dbh->{PrintError} = 0;
40 0 local $dbh->{PrintWarn} = 0;
41 0 $dbh->{CachedKids} = {};
42 0 $dbh->disconnect;
43 0 return 1;
44 }
45 }
46 10 $dbh->STORE(InactiveDestroy => 1);
47 10 1;
48 };
49 }
50  
51 # Neutralize every handle this process did not open (i.e. inherited).
52 41 ▶sub _neutralize_all_inherited () {
Subroutine _neutralize_all_inherited: called CC=3 SCAR=11.0
53 41 for my $key (keys %OWNED) {
54 91 my ($dbh, $pid) = @{ $OWNED{$key} };
55 91 ▶ next if $pid == $$;
Branch: 1 branch
BranchTrueFalseTotal
if $pid == $$ 83 8 91
56 8 _neutralize_inherited($dbh);
57 8 delete $OWNED{$key};
58 }
59 }
60  
61 # Fork detection. With POSIX::AtFork (optional, XS) a child hook bumps a
62 # generation counter and neutralizes inherited sockets the moment the child
63 # starts, so dbh() compares two integers instead of reading $$ - a getpid()
64 # syscall per call on current glibc (~8-12% of a simple read). Without it,
65 # $$ as before.
66 36 our $FORK_GEN = 0;
67 36 ▶our $HAVE_ATFORK = eval {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require POSIX::AtFork; 'POSIX::AtFork'->add_to_child(sub { ++$FORK_GEN; _neutralize_all_inherited(); } ); 1 } } ? : 36 0 36
68 36 require POSIX::AtFork;
69 5 ▶ POSIX::AtFork->add_to_child(sub { $FORK_GEN++; _neutralize_all_inherited() });
Subroutine __ANON__: called CC=1 SCAR=0.0
70 36 1;
71 } ? 1 : 0;
72  
73 # Runs before DBI's END (END blocks run in reverse order of compilation and
74 # DBI's is compiled first), so a child that never touched the database still
75 # neutralizes what it inherited before DBI's disconnect_all.
76 36 ▶END { _neutralize_all_inherited() }
Subroutine END: called CC=1 SCAR=0.0
77  
78 class DBIx::Fast::Connector {
79 36 field $_dsn :param(dsn);
80 field $_user :param(user) = '';
81 36 field $_pass :param(pass) = '';
82 36 field $_attrs :param(attrs) = {};
83 # Coderef run with the fresh $dbh on every (re)connect. The parent DBIx::Fast
84 # uses it to (re)install HandleError/trace/quote/Profile, which otherwise
85 # would be lost on the new handle after a reconnect.
86 36 field $_on_connect :param(on_connect) = undef;
87  
88 36 field $_dbh;
89 field $_pid = $$;
90 36 field $_fork_gen = $FORK_GEN;
91 36 field $_last_ping = 0;
92 36 field $_ping_interval;
93 36 field $_skip_ping;
94  
95 ADJUST {
96 # Minimum seconds between server-side ping() calls. 1s catches server
97 # restarts and wait_timeout evictions without adding a roundtrip per query.
98 # Read per-instance so tests can override via local $ENV.
99 $_ping_interval = $ENV{DBIX_FAST_PING_INTERVAL} // 1;
100 # SQLite has no server-side connection to die, so skip ping entirely unless
101 # the interval is explicitly overridden.
102 $_skip_ping = !exists $ENV{DBIX_FAST_PING_INTERVAL}
103 && $_dsn =~ /^dbi:SQLite\b/i;
104 }
105  
106 # True when a (stale) handle had AutoCommit off, i.e. it was inside a
107 # transaction. Silently reconnecting a fresh autocommit session would land the
108 # rest of the transaction body on it and durably commit partial work with no
109 # error, so the caller fails loudly instead. The handle MUST be disposed
110 # before dying (see dbh) or the connector would stay poisoned for all calls.
111 6 ▶ method _in_txn ($dbh) {
Subroutine _in_txn: called CC=2 SCAR=6.9
112 6 my $autocommit = eval { $dbh->FETCH('AutoCommit') };
113 6 ▶ return defined $autocommit && !$autocommit;
Condition66%2/3
defined $autocommit && !$autocommit
!ll&&!rl&&r
033
MC/DC50%1/2
defined $autocommit && !$autocommit
defined $autocommit !$autocommit
Truth table66%2/3
A && not(B)
A= defined $autocommitB= !$autocommit
ABresult
0X0
100
111
114 36 }
115  
116 93 ▶ method _forked () {
Subroutine _forked: called CC=2 SCAR=7.0
117 93 ▶ return $HAVE_ATFORK ? $_fork_gen != $FORK_GEN : $_pid != $$;
Branch: 1 branch
BranchTrueFalseTotal
$DBIx::Fast::Connector::HAVE_ATFORK ? : 93 0 93
118 36 }
119  
120 933 ▶ method dbh () {
Subroutine dbh: called CC=17 SCAR=28.6
Pod documented
121 # Fork detection: the parent's handle is unusable in the child. Neutralize
122 # it BEFORE dropping it (see _neutralize_inherited).
123 # Inlined (not $self->_forked): this runs on every query.
124 933 ▶ if ($HAVE_ATFORK ? $_fork_gen != $FORK_GEN : $_pid != $$) {
Branch: 2 branches
BranchTrueFalseTotal
if ($DBIx::Fast::Connector::HAVE_ATFORK ? $_fork_gen != $DBIx::Fast::Connector::FORK_GEN : $_pid != $$) 1 932 933
$DBIx::Fast::Connector::HAVE_ATFORK ? : 933 0 933
125 1 _neutralize_inherited($_dbh);
126 1 ▶ delete $OWNED{ Scalar::Util::refaddr($_dbh) } if $_dbh;
Branch: 1 branch
BranchTrueFalseTotal
if $_dbh 1 0 1
127 1 undef $_dbh;
128 1 $_pid = $$;
129 1 $_fork_gen = $FORK_GEN;
130 }
131  
132 # Handle alive check (cheap, client-side)
133 933 ▶ if ($_dbh && !$_dbh->FETCH('Active')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_dbh and not $_dbh->FETCH("Active")) 4 929 933
Condition100%3/3
$_dbh and not $_dbh->FETCH("Active")
!ll&&!rl&&r
938364
MC/DC100%2/2
$_dbh and not $_dbh->FETCH("Active")
$_dbh not $_dbh->FETCH("Active")
Truth table100%3/3
A and not(B)
A= $_dbhB= not $_dbh->FETCH("Active")
ABresult
0X0
100
111
134 4 my $in_txn = $self->_in_txn($_dbh);
135 4 undef $_dbh; # dispose BEFORE dying
136 4 ▶ die "DBIx::Fast::Connector: connection lost mid-transaction\n" if $in_txn;
Branch: 1 branch
BranchTrueFalseTotal
if $in_txn 2 2 4
137 }
138  
139 # Server-side liveness check (throttled). DBI's Active flag does not detect
140 # connections closed by the server (wait_timeout, restart, network drop)
141 # until the next failing call. DBD::MariaDB 1.24 can segfault when a
142 # statement is prepared on such a handle, so we verify with ping first.
143 931 ▶ if ($_dbh && !$_skip_ping && $_ping_interval >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_dbh and not $_skip_ping and $_ping_interval >= 0) 7 924 931
Condition83%5/6
$_dbh and not $_skip_ping and $_ping_interval >= 0
!ll&&!rl&&r
92407
$_dbh and not $_skip_ping
!ll&&!rl&&r
958297
MC/DC66%2/3
$_dbh and not $_skip_ping and $_ping_interval >= 0
$_dbh not $_skip_ping $_ping_interval >= 0
Truth table75%3/4
A and not(B) and C
A= $_dbhB= not $_skip_pingC= $_ping_interval >= 0
ABCresult
0XX0
10X0
1100
1111
144 7 my $now = time;
145 7 ▶ if ($now - $_last_ping >= $_ping_interval) {
Branch: 1 branch
BranchTrueFalseTotal
if ($now - $_last_ping >= $_ping_interval) 2 5 7
146 2 my $alive = eval { $_dbh->ping };
147 2 ▶ if (!$alive) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $alive) { } 2 0 2
148 2 my $in_txn = $self->_in_txn($_dbh);
149 2 eval { $_dbh->STORE(InactiveDestroy => 1) };
150 2 undef $_dbh; # dispose BEFORE dying
151 2 ▶ die "DBIx::Fast::Connector: connection lost mid-transaction\n"
Branch: 1 branch
BranchTrueFalseTotal
if $in_txn 1 1 2
152 if $in_txn;
153 }
154 else {
155 0 $_last_ping = $now;
156 }
157 }
158 }
159  
160 # (Re)connect
161 930 ▶ unless ($_dbh) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($_dbh) 96 834 930
162 # eval: with RaiseError (our default) DBI->connect croaks with a message
163 # that embeds the DSN and username - and a DSN can carry a password.
164 # Rethrow with the driver error only. AutoInactiveDestroy keeps a handle
165 # inherited across fork() from sending a server-side disconnect when a
166 # child that never touched the DB exits.
167 96 ▶ $_dbh = eval {
Branch: 1 branch
BranchTrueFalseTotal
$_dbh = eval { do { "DBI"->connect($_dsn, $_user, $_pass, {"AutoInactiveDestroy", 1, %$_attrs}) } } or die 'DBIx::Fast::Connector: connect failed: ' . ($DBI::errstr // "unknown error") . "\n" 96 0 96
168 96 ▶ DBI->connect($_dsn, $_user, $_pass,
Condition0%0/2
$DBI::errstr // "unknown error"
l!l
00
MC/DC0%0/1
$DBI::errstr // "unknown error"
$DBI::errstr
Truth table0%0/2
A
A= $DBI::errstr
Aresult
11
00
169 { AutoInactiveDestroy => 1, %$_attrs })
170 } or die "DBIx::Fast::Connector: connect failed: "
171 . ($DBI::errstr // 'unknown error') . "\n";
172 96 $_pid = $$;
173 96 $_fork_gen = $FORK_GEN;
174 96 $_last_ping = time;
175 96 my $entry = [ $_dbh, $$ ];
176 96 Scalar::Util::weaken($entry->[0]);
177 96 $OWNED{ Scalar::Util::refaddr($_dbh) } = $entry;
178 # Reapply per-connection settings (HandleError/trace/quote/Profile) to the
179 # fresh handle so they survive reconnects.
180 96 ▶ $_on_connect->($_dbh) if $_on_connect;
Branch: 1 branch
BranchTrueFalseTotal
if $_on_connect 75 21 96
181 }
182  
183 930 return $_dbh;
184 36 }
185  
186 5 ▶ method disconnect () {
Subroutine disconnect: called CC=3 SCAR=11.3
Pod documented
187 5 ▶ if ($_dbh) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_dbh) 5 0 5
188 5 ▶ if ($self->_forked) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_forked) { } 0 5 5
189 # Forked child: never send a protocol-level disconnect on the socket
190 # shared with the parent - neutralize our copy and drop it.
191 0 _neutralize_inherited($_dbh);
192 } else {
193 5 $_dbh->disconnect;
194 }
195 5 delete $OWNED{ Scalar::Util::refaddr($_dbh) };
196 }
197 5 undef $_dbh;
198 36 }
199  
200 # A forked child usually drops the DBIx::Fast object (and this connector)
201 # while exiting, BEFORE END blocks run: neutralize the inherited handle here
202 # too, or its DBI destruction (AutoInactiveDestroy) leaves it registered in
203 # DBD::MariaDB for disconnect_all() to close on the parent's socket.
204 92 ▶ method DESTROY {
Subroutine DESTROY: called CC=3 SCAR=11.0
205 92 ▶ return unless $_dbh && $self->_forked;
Branch: 1 branch
BranchTrueFalseTotal
unless $_dbh and $self->_forked 88 4 92
Condition100%3/3
$_dbh and $self->_forked
!ll&&!rl&&r
4844
MC/DC100%2/2
$_dbh and $self->_forked
$_dbh $self->_forked
Truth table100%3/3
A and B
A= $_dbhB= $self->_forked
ABresult
0X0
100
111
206 4 _neutralize_inherited($_dbh);
207 4 delete $OWNED{ Scalar::Util::refaddr($_dbh) };
208 36 }
209  
210 36 method mode { }
211  
212 # --- Test seams: Object::Pad fields cannot be poked from outside, so tests
213 # that simulate a dead/forked handle drive these instead. Not part of the
214 # public API.
215 4 ▶ method _test_set_handle ($h) { $_dbh = $h; return $self }
Subroutine _test_set_handle: called CC=1 SCAR=0.0
216 4 ▶ method _test_set_pid ($p) { $_pid = $p; $_fork_gen = $FORK_GEN - ($p == $$ ? 0 : 1);
Subroutine _test_set_pid: called CC=2 SCAR=7.0
Branch: 1 branch
BranchTrueFalseTotal
$p == $$ ? : 4 0 4
217 4 return $self }
218 4 ▶ method _test_skip_ping ($v) { $_skip_ping = $v; return $self }
Subroutine _test_skip_ping: called CC=1 SCAR=0.0
219 }
220  
221 36 1;
222  
223 __END__
« Fast/Transaction.pm ↑ Summary Fast/Schema.pm »