Fast/Connector.pm

filter: Statementstmt 92.6% 152 / 164 Branchbran 69.2% 36 / 52 Conditioncond 67.5% 27 / 40 MC/DCmcdc 57.1% 12 / 21 Subroutinesub 100% 19 / 19 Podpod 100% 2 / 2 totaltotal 83.2% 248 / 298 CC 41 SCAR 22.9
CC
41
Cov
84%
_neutralize_inherited
23.1
_dbh_check
18.0
dbh
7.0
CRAP 9.9
« Fast/Test/Mock.pm ↑ Summary Fast/Profiler.pm »
1 package DBIx::Fast::Connector;
2  
3 37 ▶use v5.38;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 37 ▶use Object::Pad 0.807;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 37 our $VERSION = '0.21';
7 37 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 37 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 37 ▶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 37 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 17 ▶sub _neutralize_inherited ($dbh) {
Subroutine _neutralize_inherited: called CC=7 SCAR=31.4
27 17 ▶ return unless $dbh;
Branch: 1 branch
BranchTrueFalseTotal
unless $dbh 5 12 17
28 12 eval {
29 12 ▶ if (($dbh->{Driver}{Name} // '') eq 'MariaDB') {
Branch: 1 branch
BranchTrueFalseTotal
if (($dbh->{"Driver"}{"Name"} // "") eq "MariaDB") 0 12 12
Condition50%1/2
$dbh->{"Driver"}{"Name"} // ""
l!l
120
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 12 $dbh->STORE(InactiveDestroy => 1);
47 12 1;
48 };
49 }
50  
51 # Neutralize every handle this process did not open (i.e. inherited).
52 43 ▶sub _neutralize_all_inherited () {
Subroutine _neutralize_all_inherited: called CC=3 SCAR=11.0
53 43 for my $key (keys %OWNED) {
54 102 my ($dbh, $pid) = @{ $OWNED{$key} };
55 102 ▶ next if $pid == $$;
Branch: 1 branch
BranchTrueFalseTotal
if $pid == $$ 91 11 102
56 11 _neutralize_inherited($dbh);
57 11 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 37 our $FORK_GEN = 0;
67 37 ▶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 } } ? : 37 0 37
68 37 require POSIX::AtFork;
69 6 ▶ POSIX::AtFork->add_to_child(sub { $FORK_GEN++; _neutralize_all_inherited() });
Subroutine __ANON__: called CC=1 SCAR=0.0
70 37 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 37 ▶END { _neutralize_all_inherited() }
Subroutine END: called CC=1 SCAR=0.0
77  
78 class DBIx::Fast::Connector {
79 37 field $_dsn :param(dsn);
80 field $_user :param(user) = '';
81 37 field $_pass :param(pass) = '';
82 37 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 37 field $_on_connect :param(on_connect) = undef;
87  
88 37 field $_dbh;
89 field $_pid = $$;
90 37 field $_fork_gen = $FORK_GEN;
91 37 field $_last_ping = 0;
92 37 field $_ping_interval;
93 37 field $_skip_ping;
94 # Precomputed for the hot path of dbh() (see there): the process token that
95 # owns $_dbh (fork generation with POSIX::AtFork, else the pid) and the
96 # epoch second the next ping is due (undef = never). Kept in step by
97 # _sync_hot.
98 field $_owner = -1;
99 37 field $_ping_at;
100  
101 ADJUST {
102 # Minimum seconds between server-side ping() calls. 1s catches server
103 # restarts and wait_timeout evictions without adding a roundtrip per query.
104 # Read per-instance so tests can override via local $ENV.
105 $_ping_interval = $ENV{DBIX_FAST_PING_INTERVAL} // 1;
106 # SQLite has no server-side connection to die, so skip ping entirely unless
107 # the interval is explicitly overridden.
108 $_skip_ping = !exists $ENV{DBIX_FAST_PING_INTERVAL}
109 && $_dsn =~ /^dbi:SQLite\b/i;
110 $self->_sync_hot;
111 }
112  
113 233 ▶ method _sync_hot () {
Subroutine _sync_hot: called CC=4 SCAR=14.0
114 233 ▶ $_owner = $HAVE_ATFORK ? $_fork_gen : $_pid;
Branch: 1 branch
BranchTrueFalseTotal
$DBIx::Fast::Connector::HAVE_ATFORK ? : 233 0 233
115 233 ▶ $_ping_at = ($_skip_ping || $_ping_interval < 0) ? undef : $_last_ping + $_ping_interval;
Branch: 1 branch
BranchTrueFalseTotal
$_skip_ping || $_ping_interval < 0 ? : 201 32 233
Condition66%2/3
$_skip_ping or $_ping_interval < 0
l!l&&r!l&&!r
201032
MC/DC50%1/2
$_skip_ping or $_ping_interval < 0
$_skip_ping $_ping_interval < 0
Truth table66%2/3
A or B
A= $_skip_pingB= $_ping_interval < 0
ABresult
1X1
011
000
116 37 }
117  
118 # True when a (stale) handle had AutoCommit off, i.e. it was inside a
119 # transaction. Silently reconnecting a fresh autocommit session would land the
120 # rest of the transaction body on it and durably commit partial work with no
121 # error, so the caller fails loudly instead. The handle MUST be disposed
122 # before dying (see dbh) or the connector would stay poisoned for all calls.
123 6 ▶ method _in_txn ($dbh) {
Subroutine _in_txn: called CC=2 SCAR=7.0
124 6 my $autocommit = eval { $dbh->FETCH('AutoCommit') };
125 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
126 37 }
127  
128 108 ▶ method _forked () {
Subroutine _forked: called CC=2 SCAR=7.0
129 108 ▶ return $HAVE_ATFORK ? $_fork_gen != $FORK_GEN : $_pid != $$;
Branch: 1 branch
BranchTrueFalseTotal
$DBIx::Fast::Connector::HAVE_ATFORK ? : 108 0 108
130 37 }
131  
132 # The handle for this process. Hot path: the handle exists, belongs to this
133 # process, is Active and no ping is due - one method touching three fields
134 # (Object::Pad binds every field a method mentions on entry, so the
135 # fork/ping/reconnect code, which needs eight more, lives in _dbh_check:
136 # 430 -> ~200 ns per query). Anything else goes through _dbh_check.
137 982 ▶ method dbh () {
Subroutine dbh: called CC=7 SCAR=19.5
Pod documented
138 982 ▶ return $_dbh
Branch: 2 branches
BranchTrueFalseTotal
if $_dbh and $_owner == ($DBIx::Fast::Connector::HAVE_ATFORK ? $DBIx::Fast::Connector::FORK_GEN : $$) and $_dbh->FETCH("Active") and !defined($_ping_at) || time < $_ping_at 867 115 982
$DBIx::Fast::Connector::HAVE_ATFORK ? : 874 0 874
Condition100%12/12
$_dbh and $_owner == ($DBIx::Fast::Connector::HAVE_ATFORK ? $DBIx::Fast::Connector::FORK_GEN : $$) and $_dbh->FETCH("Active") and !defined($_ping_at) || time < $_ping_at
!ll&&!rl&&r
1132867
$_dbh and $_owner == ($DBIx::Fast::Connector::HAVE_ATFORK ? $DBIx::Fast::Connector::FORK_GEN : $$) and $_dbh->FETCH("Active")
!ll&&!rl&&r
1094869
$_dbh and $_owner == ($DBIx::Fast::Connector::HAVE_ATFORK ? $DBIx::Fast::Connector::FORK_GEN : $$)
!ll&&!rl&&r
1081873
not defined $_ping_at or time < $_ping_at
l!l&&r!l&&!r
803642
MC/DC100%5/5
$_dbh and $_owner == ($DBIx::Fast::Connector::HAVE_ATFORK ? $DBIx::Fast::Connector::FORK_GEN : $$) and $_dbh->FETCH("Active") and !defined($_ping_at) || time < $_ping_at
$_dbh $_owner == ($DBIx::Fast::Connector::HAVE_ATFORK ? $DBIx::Fast::Connector::FORK_GEN : $$) $_dbh->FETCH("Active") not defined $_ping_at time < $_ping_at
Truth table100%6/6
A and B and C and not(D) or E
A= $_dbhB= $_owner == ($DBIx::Fast::Connector::HAVE_ATFORK ? $DBIx::Fast::Connector::FORK_GEN : $$)C= $_dbh->FETCH("Active")D= not defined $_ping_atE= time < $_ping_at
ABCDEresult
0XXXX0
10XXX0
110XX0
111000
1111X1
111011
139 if $_dbh
140 && $_owner == ($HAVE_ATFORK ? $FORK_GEN : $$)
141 && $_dbh->FETCH('Active')
142 && (!defined $_ping_at || time < $_ping_at);
143 115 return $self->_dbh_check;
144 37 }
145  
146 115 ▶ method _dbh_check () {
Subroutine _dbh_check: called CC=17 SCAR=28.9
147 # Fork detection: the parent's handle is unusable in the child. Neutralize
148 # it BEFORE dropping it (see _neutralize_inherited).
149 # Inlined (not $self->_forked): this runs on every query.
150 115 ▶ 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 114 115
$DBIx::Fast::Connector::HAVE_ATFORK ? : 115 0 115
151 1 _neutralize_inherited($_dbh);
152 1 ▶ delete $OWNED{ Scalar::Util::refaddr($_dbh) } if $_dbh;
Branch: 1 branch
BranchTrueFalseTotal
if $_dbh 1 0 1
153 1 undef $_dbh;
154 1 $_pid = $$;
155 1 $_fork_gen = $FORK_GEN;
156 }
157  
158 # Handle alive check (cheap, client-side)
159 115 ▶ if ($_dbh && !$_dbh->FETCH('Active')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_dbh and not $_dbh->FETCH("Active")) 4 111 115
Condition100%3/3
$_dbh and not $_dbh->FETCH("Active")
!ll&&!rl&&r
10924
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
160 4 my $in_txn = $self->_in_txn($_dbh);
161 4 undef $_dbh; # dispose BEFORE dying
162 4 ▶ die "DBIx::Fast::Connector: connection lost mid-transaction\n" if $in_txn;
Branch: 1 branch
BranchTrueFalseTotal
if $in_txn 2 2 4
163 }
164  
165 # Server-side liveness check (throttled). DBI's Active flag does not detect
166 # connections closed by the server (wait_timeout, restart, network drop)
167 # until the next failing call. DBD::MariaDB 1.24 can segfault when a
168 # statement is prepared on such a handle, so we verify with ping first.
169 113 ▶ if ($_dbh && !$_skip_ping && $_ping_interval >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_dbh and not $_skip_ping and $_ping_interval >= 0) 2 111 113
Condition66%4/6
$_dbh and not $_skip_ping and $_ping_interval >= 0
!ll&&!rl&&r
11102
$_dbh and not $_skip_ping
!ll&&!rl&&r
11102
MC/DC33%1/3
$_dbh and not $_skip_ping and $_ping_interval >= 0
$_dbh not $_skip_ping $_ping_interval >= 0
Truth table50%2/4
A and not(B) and C
A= $_dbhB= not $_skip_pingC= $_ping_interval >= 0
ABCresult
0XX0
10X0
1100
1111
170 2 my $now = time;
171 2 ▶ if ($now - $_last_ping >= $_ping_interval) {
Branch: 1 branch
BranchTrueFalseTotal
if ($now - $_last_ping >= $_ping_interval) 2 0 2
172 2 my $alive = eval { $_dbh->ping };
173 2 ▶ if (!$alive) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $alive) { } 2 0 2
174 2 my $in_txn = $self->_in_txn($_dbh);
175 2 eval { $_dbh->STORE(InactiveDestroy => 1) };
176 2 undef $_dbh; # dispose BEFORE dying
177 2 ▶ die "DBIx::Fast::Connector: connection lost mid-transaction\n"
Branch: 1 branch
BranchTrueFalseTotal
if $in_txn 1 1 2
178 if $in_txn;
179 }
180 else {
181 0 $_last_ping = $now;
182 }
183 }
184 }
185  
186 # (Re)connect
187 112 ▶ unless ($_dbh) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($_dbh) 112 0 112
188 # eval: with RaiseError (our default) DBI->connect croaks with a message
189 # that embeds the DSN and username - and a DSN can carry a password.
190 # Rethrow with the driver error only. AutoInactiveDestroy keeps a handle
191 # inherited across fork() from sending a server-side disconnect when a
192 # child that never touched the DB exits.
193 112 ▶ $_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" 112 0 112
194 112 ▶ 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
195 { AutoInactiveDestroy => 1, %$_attrs })
196 } or die "DBIx::Fast::Connector: connect failed: "
197 . ($DBI::errstr // 'unknown error') . "\n";
198 112 $_pid = $$;
199 112 $_fork_gen = $FORK_GEN;
200 112 $_last_ping = time;
201 112 my $entry = [ $_dbh, $$ ];
202 112 Scalar::Util::weaken($entry->[0]);
203 112 $OWNED{ Scalar::Util::refaddr($_dbh) } = $entry;
204 # Reapply per-connection settings (HandleError/trace/quote/Profile) to the
205 # fresh handle so they survive reconnects.
206 112 ▶ $_on_connect->($_dbh) if $_on_connect;
Branch: 1 branch
BranchTrueFalseTotal
if $_on_connect 81 31 112
207 }
208  
209 112 $self->_sync_hot;
210 112 return $_dbh;
211 37 }
212  
213 10 ▶ method disconnect () {
Subroutine disconnect: called CC=3 SCAR=11.3
Pod documented
214 10 ▶ if ($_dbh) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_dbh) 10 0 10
215 10 ▶ if ($self->_forked) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_forked) { } 0 10 10
216 # Forked child: never send a protocol-level disconnect on the socket
217 # shared with the parent - neutralize our copy and drop it.
218 0 _neutralize_inherited($_dbh);
219 } else {
220 10 $_dbh->disconnect;
221 }
222 10 delete $OWNED{ Scalar::Util::refaddr($_dbh) };
223 }
224 10 undef $_dbh;
225 37 }
226  
227 # A forked child usually drops the DBIx::Fast object (and this connector)
228 # while exiting, BEFORE END blocks run: neutralize the inherited handle here
229 # too, or its DBI destruction (AutoInactiveDestroy) leaves it registered in
230 # DBD::MariaDB for disconnect_all() to close on the parent's socket.
231 108 ▶ method DESTROY {
Subroutine DESTROY: called CC=3 SCAR=11.0
232 108 ▶ return unless $_dbh && $self->_forked;
Branch: 1 branch
BranchTrueFalseTotal
unless $_dbh and $self->_forked 103 5 108
Condition100%3/3
$_dbh and $self->_forked
!ll&&!rl&&r
10935
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
233 5 _neutralize_inherited($_dbh);
234 5 delete $OWNED{ Scalar::Util::refaddr($_dbh) };
235 37 }
236  
237 37 method mode { }
238  
239 # --- Test seams: Object::Pad fields cannot be poked from outside, so tests
240 # that simulate a dead/forked handle drive these instead. Not part of the
241 # public API.
242 4 ▶ method _test_set_handle ($h) { $_dbh = $h; $self->_sync_hot; return $self }
Subroutine _test_set_handle: called CC=1 SCAR=0.0
243 4 ▶ method _test_set_pid ($p) { $_pid = $p; $_fork_gen = $FORK_GEN - ($p == $$ ? 0 : 1);
Subroutine _test_set_pid: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$p == $$ ? : 4 0 4
244 4 $self->_sync_hot; return $self }
245 4 ▶ method _test_skip_ping ($v) { $_skip_ping = $v; $self->_sync_hot; return $self }
Subroutine _test_skip_ping: called CC=1 SCAR=0.0
246 }
247  
248 37 1;
249  
250 __END__
« Fast/Test/Mock.pm ↑ Summary Fast/Profiler.pm »