Fast/Connector.pm

filter: Statementstmt 93.4% 172 / 184 Branchbran 71.4% 40 / 56 Conditioncond 69.0% 29 / 42 MC/DCmcdc 59.0% 13 / 22 Subroutinesub 100% 21 / 21 Podpod 100% 2 / 2 totaltotal 84.7% 277 / 327 CC 44 SCAR 22.7
CC
44
Cov
85%
_neutralize_inherited
23.1
_dbh_check
18.6
dbh
7.0
CRAP 9.7
« Fast/Test/Mock.pm ↑ Summary Fast/Schema.pm »
1 package DBIx::Fast::Connector;
2  
3 40 ▶use v5.38;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 40 ▶use Object::Pad 0.807;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 40 our $VERSION = '0.22';
7 40 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 40 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 40 ▶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 40 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 29 ▶sub _neutralize_inherited ($dbh) {
Subroutine _neutralize_inherited: called CC=7 SCAR=31.4
27 29 ▶ return unless $dbh;
Branch: 1 branch
BranchTrueFalseTotal
unless $dbh 13 16 29
28 16 eval {
29 16 ▶ if (($dbh->{Driver}{Name} // '') eq 'MariaDB') {
Branch: 1 branch
BranchTrueFalseTotal
if (($dbh->{"Driver"}{"Name"} // "") eq "MariaDB") 0 16 16
Condition50%1/2
$dbh->{"Driver"}{"Name"} // ""
l!l
160
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 16 $dbh->STORE(InactiveDestroy => 1);
47 16 1;
48 };
49 }
50  
51 # Neutralize every handle this process did not open (i.e. inherited).
52 48 ▶sub _neutralize_all_inherited () {
Subroutine _neutralize_all_inherited: called CC=3 SCAR=11.0
53 48 for my $key (keys %OWNED) {
54 158 my ($dbh, $pid) = @{ $OWNED{$key} };
55 158 ▶ next if $pid == $$;
Branch: 1 branch
BranchTrueFalseTotal
if $pid == $$ 137 21 158
56 21 _neutralize_inherited($dbh);
57 21 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 # How many dbh() calls reuse the handle between two Active checks.
67 40 our $CHECK_EVERY = 100;
68  
69 40 our $FORK_GEN = 0;
70 40 ▶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 } } ? : 40 0 40
71 40 require POSIX::AtFork;
72 8 ▶ POSIX::AtFork->add_to_child(sub { $FORK_GEN++; _neutralize_all_inherited() });
Subroutine __ANON__: called CC=1 SCAR=0.0
73 40 1;
74 } ? 1 : 0;
75  
76 # Runs before DBI's END (END blocks run in reverse order of compilation and
77 # DBI's is compiled first), so a child that never touched the database still
78 # neutralizes what it inherited before DBI's disconnect_all.
79 40 ▶END { _neutralize_all_inherited() }
Subroutine END: called CC=1 SCAR=0.0
80  
81 class DBIx::Fast::Connector {
82 40 field $_dsn :param(dsn);
83 field $_user :param(user) = '';
84 40 field $_pass :param(pass) = '';
85 40 field $_attrs :param(attrs) = {};
86 # Coderef run with the fresh $dbh on every (re)connect. The parent DBIx::Fast
87 # uses it to (re)install HandleError/trace/quote/Profile, which otherwise
88 # would be lost on the new handle after a reconnect.
89 40 field $_on_connect :param(on_connect) = undef;
90  
91 40 field $_dbh;
92 field $_pid = $$;
93 40 field $_fork_gen = $FORK_GEN;
94 40 field $_last_ping = 0;
95 40 field $_ping_interval;
96 40 field $_skip_ping;
97 # Precomputed for the hot path of dbh() (see there): the process token that
98 # owns $_dbh (fork generation with POSIX::AtFork, else the pid) and the
99 # epoch second the next ping is due (undef = never). Kept in step by
100 # _sync_hot.
101 field $_owner = -1;
102 40 field $_ping_at;
103 # Calls left before the hot path checks Active again (_dbh_check). Any
104 # database error zeroes it (_recheck, from DBIx::Fast's HandleError), so a
105 # handle the driver marked inactive is still caught on the next call.
106 field $_budget = 0;
107  
108 40 ADJUST {
109 # Minimum seconds between server-side ping() calls. 1s catches server
110 # restarts and wait_timeout evictions without adding a roundtrip per query.
111 # Read per-instance so tests can override via local $ENV.
112 $_ping_interval = $ENV{DBIX_FAST_PING_INTERVAL} // 1;
113 # SQLite has no server-side connection to die, so skip ping entirely unless
114 # the interval is explicitly overridden.
115 $_skip_ping = !exists $ENV{DBIX_FAST_PING_INTERVAL}
116 && $_dsn =~ /^dbi:SQLite\b/i;
117 $self->_sync_hot;
118 }
119  
120 395 ▶ method _sync_hot () {
Subroutine _sync_hot: called CC=4 SCAR=14.0
121 395 ▶ $_owner = $HAVE_ATFORK ? $_fork_gen : $_pid;
Branch: 1 branch
BranchTrueFalseTotal
$DBIx::Fast::Connector::HAVE_ATFORK ? : 395 0 395
122 395 ▶ $_ping_at = ($_skip_ping || $_ping_interval < 0) ? undef : $_last_ping + $_ping_interval;
Branch: 1 branch
BranchTrueFalseTotal
$_skip_ping || $_ping_interval < 0 ? : 362 33 395
Condition66%2/3
$_skip_ping or $_ping_interval < 0
l!l&&r!l&&!r
362033
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
123 40 }
124  
125 # True when a (stale) handle had AutoCommit off, i.e. it was inside a
126 # transaction. Silently reconnecting a fresh autocommit session would land the
127 # rest of the transaction body on it and durably commit partial work with no
128 # error, so the caller fails loudly instead. The handle MUST be disposed
129 # before dying (see dbh) or the connector would stay poisoned for all calls.
130 7 ▶ method _in_txn ($dbh) {
Subroutine _in_txn: called CC=2 SCAR=7.0
131 7 my $autocommit = eval { $dbh->FETCH('AutoCommit') };
132 7 ▶ return defined $autocommit && !$autocommit;
Condition66%2/3
defined $autocommit && !$autocommit
!ll&&!rl&&r
043
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
133 40 }
134  
135 167 ▶ method _forked () {
Subroutine _forked: called CC=2 SCAR=7.0
136 167 ▶ return $HAVE_ATFORK ? $_fork_gen != $FORK_GEN : $_pid != $$;
Branch: 1 branch
BranchTrueFalseTotal
$DBIx::Fast::Connector::HAVE_ATFORK ? : 167 0 167
137 40 }
138  
139 # The handle for this process. Hot path: the handle exists, belongs to this
140 # process, is Active and no ping is due - one method touching three fields
141 # (Object::Pad binds every field a method mentions on entry, so the
142 # fork/ping/reconnect code, which needs eight more, lives in _dbh_check:
143 # 430 -> ~200 ns per query). Anything else goes through _dbh_check.
144 4864 ▶ method dbh () {
Subroutine dbh: called CC=7 SCAR=19.5
Pod documented
145 4864 ▶ return $_dbh
Branch: 2 branches
BranchTrueFalseTotal
if $_dbh and $_owner == ($DBIx::Fast::Connector::HAVE_ATFORK ? $DBIx::Fast::Connector::FORK_GEN : $$) and --$_budget > 0 and !defined($_ping_at) || time < $_ping_at 4640 224 4864
$DBIx::Fast::Connector::HAVE_ATFORK ? : 4698 0 4698
Condition100%12/12
$_dbh and $_owner == ($DBIx::Fast::Connector::HAVE_ATFORK ? $DBIx::Fast::Connector::FORK_GEN : $$) and --$_budget > 0 and !defined($_ping_at) || time < $_ping_at
!ll&&!rl&&r
22314640
$_dbh and $_owner == ($DBIx::Fast::Connector::HAVE_ATFORK ? $DBIx::Fast::Connector::FORK_GEN : $$) and --$_budget > 0
!ll&&!rl&&r
168554641
$_dbh and $_owner == ($DBIx::Fast::Connector::HAVE_ATFORK ? $DBIx::Fast::Connector::FORK_GEN : $$)
!ll&&!rl&&r
16624696
not defined $_ping_at or time < $_ping_at
l!l&&r!l&&!r
4577631
MC/DC100%5/5
$_dbh and $_owner == ($DBIx::Fast::Connector::HAVE_ATFORK ? $DBIx::Fast::Connector::FORK_GEN : $$) and --$_budget > 0 and !defined($_ping_at) || time < $_ping_at
$_dbh $_owner == ($DBIx::Fast::Connector::HAVE_ATFORK ? $DBIx::Fast::Connector::FORK_GEN : $$) --$_budget > 0 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= --$_budget > 0D= not defined $_ping_atE= time < $_ping_at
ABCDEresult
0XXXX0
10XXX0
110XX0
111000
1111X1
111011
146 if $_dbh
147 && $_owner == ($HAVE_ATFORK ? $FORK_GEN : $$)
148 && --$_budget > 0
149 && (!defined $_ping_at || time < $_ping_at);
150 224 return $self->_dbh_check;
151 40 }
152  
153 224 ▶ method _dbh_check () {
Subroutine _dbh_check: called CC=18 SCAR=29.2
154 # Fork detection: the parent's handle is unusable in the child. Neutralize
155 # it BEFORE dropping it (see _neutralize_inherited).
156 # Inlined (not $self->_forked): this runs on every query.
157 224 ▶ 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 != $$) 2 222 224
$DBIx::Fast::Connector::HAVE_ATFORK ? : 224 0 224
158 2 _neutralize_inherited($_dbh);
159 2 ▶ delete $OWNED{ Scalar::Util::refaddr($_dbh) } if $_dbh;
Branch: 1 branch
BranchTrueFalseTotal
if $_dbh 2 0 2
160 2 undef $_dbh;
161 2 $_pid = $$;
162 2 $_fork_gen = $FORK_GEN;
163 }
164  
165 # Handle alive check (cheap, client-side)
166 224 ▶ if ($_dbh && !$_dbh->FETCH('Active')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_dbh and not $_dbh->FETCH("Active")) 5 219 224
Condition100%3/3
$_dbh and not $_dbh->FETCH("Active")
!ll&&!rl&&r
168515
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
167 5 my $in_txn = $self->_in_txn($_dbh);
168 5 undef $_dbh; # dispose BEFORE dying
169 5 ▶ die "DBIx::Fast::Connector: connection lost mid-transaction\n" if $in_txn;
Branch: 1 branch
BranchTrueFalseTotal
if $in_txn 2 3 5
170 }
171  
172 # Server-side liveness check (throttled). DBI's Active flag does not detect
173 # connections closed by the server (wait_timeout, restart, network drop)
174 # until the next failing call. DBD::MariaDB 1.24 can segfault when a
175 # statement is prepared on such a handle, so we verify with ping first.
176 222 ▶ if ($_dbh && !$_skip_ping && $_ping_interval >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_dbh and not $_skip_ping and $_ping_interval >= 0) 3 219 222
Condition83%5/6
$_dbh and not $_skip_ping and $_ping_interval >= 0
!ll&&!rl&&r
21903
$_dbh and not $_skip_ping
!ll&&!rl&&r
171483
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
177 3 my $now = time;
178 3 ▶ if ($now - $_last_ping >= $_ping_interval) {
Branch: 1 branch
BranchTrueFalseTotal
if ($now - $_last_ping >= $_ping_interval) 2 1 3
179 2 my $alive = eval { $_dbh->ping };
180 2 ▶ if (!$alive) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $alive) { } 2 0 2
181 2 my $in_txn = $self->_in_txn($_dbh);
182 2 eval { $_dbh->STORE(InactiveDestroy => 1) };
183 2 undef $_dbh; # dispose BEFORE dying
184 2 ▶ die "DBIx::Fast::Connector: connection lost mid-transaction\n"
Branch: 1 branch
BranchTrueFalseTotal
if $in_txn 1 1 2
185 if $in_txn;
186 }
187 else {
188 0 $_last_ping = $now;
189 }
190 }
191 }
192  
193 # (Re)connect
194 221 ▶ unless ($_dbh) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($_dbh) 172 49 221
195 # eval: with RaiseError (our default) DBI->connect croaks with a message
196 # that embeds the DSN and username - and a DSN can carry a password.
197 # Rethrow with the driver error only. AutoInactiveDestroy keeps a handle
198 # inherited across fork() from sending a server-side disconnect when a
199 # child that never touched the DB exits.
200 172 ▶ $_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" 172 0 172
201 172 ▶ 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
202 { AutoInactiveDestroy => 1, %$_attrs })
203 } or die "DBIx::Fast::Connector: connect failed: "
204 . ($DBI::errstr // 'unknown error') . "\n";
205 172 $_pid = $$;
206 172 $_fork_gen = $FORK_GEN;
207 172 $_last_ping = time;
208 # A disconnect() on the handle itself (bypassing ours) must be seen
209 # by the next dbh() call, which skips the Active check between
210 # periodic ones. A DBI callback costs only when disconnect is called.
211 172 my $weak = $self;
212 172 Scalar::Util::weaken($weak);
213 172 ▶ my $cbs = $_dbh->{Callbacks} // {};
Condition50%1/2
$_dbh->{"Callbacks"} // {}
l!l
0172
MC/DC0%0/1
$_dbh->{"Callbacks"} // {}
$_dbh->{"Callbacks"}
Truth table50%1/2
A
A= $_dbh->{"Callbacks"}
Aresult
11
00
214 172 my $prev = $cbs->{disconnect};
215 172 ▶ $cbs->{disconnect} = sub { $weak->_recheck if $weak; $prev->(@_) if $prev; return };
Subroutine __ANON__: called CC=3 SCAR=11.4
Branch: 2 branches
BranchTrueFalseTotal
if $weak 15 0 15
if $prev 0 15 15
216 172 $_dbh->{Callbacks} = $cbs;
217 172 my $entry = [ $_dbh, $$ ];
218 172 Scalar::Util::weaken($entry->[0]);
219 172 $OWNED{ Scalar::Util::refaddr($_dbh) } = $entry;
220 # Reapply per-connection settings (HandleError/trace/quote/Profile) to the
221 # fresh handle so they survive reconnects.
222 172 ▶ $_on_connect->($_dbh) if $_on_connect;
Branch: 1 branch
BranchTrueFalseTotal
if $_on_connect 141 31 172
223 }
224  
225 221 $self->_sync_hot;
226 221 $_budget = $CHECK_EVERY;
227 221 return $_dbh;
228 40 }
229  
230 # Check the handle fully on the next dbh() call (after a database error).
231 48 ▶ method _recheck () { $_budget = 0 }
Subroutine _recheck: called CC=1 SCAR=0.0
232  
233 14 ▶ method disconnect () {
Subroutine disconnect: called CC=3 SCAR=11.3
Pod documented
234 14 ▶ if ($_dbh) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_dbh) 14 0 14
235 14 ▶ if ($self->_forked) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_forked) { } 0 14 14
236 # Forked child: never send a protocol-level disconnect on the socket
237 # shared with the parent - neutralize our copy and drop it.
238 0 _neutralize_inherited($_dbh);
239 } else {
240 14 $_dbh->disconnect;
241 }
242 14 delete $OWNED{ Scalar::Util::refaddr($_dbh) };
243 }
244 14 undef $_dbh;
245 40 }
246  
247 # A forked child usually drops the DBIx::Fast object (and this connector)
248 # while exiting, BEFORE END blocks run: neutralize the inherited handle here
249 # too, or its DBI destruction (AutoInactiveDestroy) leaves it registered in
250 # DBD::MariaDB for disconnect_all() to close on the parent's socket.
251 158 ▶ method DESTROY {
Subroutine DESTROY: called CC=3 SCAR=11.0
252 158 ▶ return unless $_dbh && $self->_forked;
Branch: 1 branch
BranchTrueFalseTotal
unless $_dbh and $self->_forked 152 6 158
Condition100%3/3
$_dbh and $self->_forked
!ll&&!rl&&r
91436
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
253 6 _neutralize_inherited($_dbh);
254 6 delete $OWNED{ Scalar::Util::refaddr($_dbh) };
255 40 }
256  
257 40 method mode { }
258  
259 # --- Test seams: Object::Pad fields cannot be poked from outside, so tests
260 # that simulate a dead/forked handle drive these instead. Not part of the
261 # public API.
262 4 ▶ method _test_set_handle ($h) { $_dbh = $h; $self->_sync_hot; $_budget = 0; return $self }
Subroutine _test_set_handle: called CC=1 SCAR=0.0
263 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
264 4 $self->_sync_hot; $_budget = 0; return $self }
265 4 ▶ method _test_skip_ping ($v) { $_skip_ping = $v; $self->_sync_hot; $_budget = 0; return $self }
Subroutine _test_skip_ping: called CC=1 SCAR=0.0
266 }
267  
268 40 1;
269  
270 __END__
« Fast/Test/Mock.pm ↑ Summary Fast/Schema.pm »