Pg.pm

filter: Statementstmt 88.8% 16 / 18 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 6 / 6 Podpod n/a totaltotal 91.6% 22 / 24 CC 1 SCAR 0.5
CC
1
Cov
89%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Pg/Error.pm ↑ Summary Pg/Connection.pm »
1 package IO::Async::Pg;
2  
3 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 4 ▶use parent 'IO::Async::Notifier';
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 4 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 4 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 0 ▶use DBD::Pg;
Subroutine BEGIN: called CC=1 SCAR=2.6
10  
11 use IO::Async::Pg::Connection;
12 use IO::Async::Pg::Error;
13 use IO::Async::Pg::PubSub;
14 use IO::Async::Pg::Util qw(parse_dsn);
15  
16 our $VERSION = '0.001001';
17  
18 sub _init {
19 my ($self, $params) = @_;
20  
21 # Required
22 $self->{dsn} = delete $params->{dsn}
23 or die "dsn is required";
24  
25 # Pool configuration
26 $self->{min_connections} = delete $params->{min_connections} // 1;
27 $self->{max_connections} = delete $params->{max_connections} // 10;
28 $self->{idle_timeout} = delete $params->{idle_timeout} // 300;
29 $self->{queue_timeout} = delete $params->{queue_timeout} // 30;
30 $self->{connect_timeout} = delete $params->{connect_timeout} // 30;
31 $self->{statement_timeout} = delete $params->{statement_timeout};
32 $self->{max_queries} = delete $params->{max_queries};
33  
34 # Callbacks
35 $self->{on_connect} = delete $params->{on_connect};
36 $self->{on_release} = delete $params->{on_release};
37 $self->{on_log} = delete $params->{on_log};
38  
39 # Pool state
40 $self->{idle} = [];
41 $self->{active} = [];
42 $self->{waiting} = [];
43 $self->{pid} = $$;
44  
45 # Stats
46 $self->{stats} = {
47 created => 0,
48 released => 0,
49 discarded => 0,
50 connect_failures => 0,
51 timeouts => 0,
52 };
53  
54 # Parse DSN once
55 $self->{_parsed_dsn} = parse_dsn($self->{dsn});
56  
57 $self->SUPER::_init($params);
58 }
59  
60 sub _add_to_loop {
61 my ($self, $loop) = @_;
62 $self->SUPER::_add_to_loop($loop);
63  
64 # Record PID for fork detection
65 $self->{pid} = $$;
66  
67 # Ensure minimum connections (non-blocking)
68 $self->_ensure_min_connections;
69 }
70  
71 # Accessors
72 sub min_connections { shift->{min_connections} }
73 sub max_connections { shift->{max_connections} }
74 sub idle_count { scalar @{shift->{idle}} }
75 sub active_count { scalar @{shift->{active}} }
76 sub waiting_count { scalar @{shift->{waiting}} }
77 sub total_count { my $s = shift; scalar(@{$s->{idle}}) + scalar(@{$s->{active}}) }
78 sub stats { shift->{stats} }
79 sub safe_dsn { IO::Async::Pg::Util::safe_dsn(shift->{dsn}) }
80  
81 sub is_healthy {
82 my ($self) = @_;
83 return $self->total_count > 0 || $self->waiting_count < $self->{max_connections};
84 }
85  
86 # Get a connection from the pool
87 async sub connection {
88 my ($self) = @_;
89  
90 $self->_check_fork;
91  
92 # 1. Try to get an idle connection
93 if (my $conn = shift @{$self->{idle}}) {
94 push @{$self->{active}}, $conn;
95 $conn->{last_used} = time();
96 $conn->{released} = 0;
97 return $conn;
98 }
99  
100 # 2. Create new connection if under limit
101 if ($self->total_count < $self->{max_connections}) {
102 my $conn = await $self->_create_connection;
103 push @{$self->{active}}, $conn;
104 return $conn;
105 }
106  
107 # 3. Queue and wait
108 my $future = $self->loop->new_future;
109 my $waiting = {
110 future => $future,
111 queued_at => time(),
112 };
113 push @{$self->{waiting}}, $waiting;
114  
115 # Set up timeout
116 my $timeout_future;
117 if (my $timeout = $self->{queue_timeout}) {
118 $timeout_future = $self->loop->delay_future(after => $timeout);
119 $timeout_future->on_done(sub {
120 @{$self->{waiting}} = grep { $_ != $waiting } @{$self->{waiting}};
121 $self->{stats}{timeouts}++;
122 $future->fail(
123 IO::Async::Pg::Error::PoolExhausted->new(
124 message => "Connection pool exhausted (waited ${timeout}s)",
125 pool_size => $self->{max_connections},
126 )
127 ) unless $future->is_ready;
128 });
129 }
130  
131 my $conn = await $future;
132 $timeout_future->cancel if $timeout_future && !$timeout_future->is_ready;
133 return $conn;
134 }
135  
136 # Create a PubSub instance for LISTEN/NOTIFY
137 sub pubsub {
138 my ($self) = @_;
139  
140 my $pubsub = IO::Async::Pg::PubSub->new(pool => $self);
141 $self->add_child($pubsub);
142  
143 return $pubsub;
144 }
145  
146 # Create a new connection
147 async sub _create_connection {
148 my ($self) = @_;
149  
150 my $parsed = $self->{_parsed_dsn};
151  
152 my %attrs = (
153 AutoCommit => 1,
154 RaiseError => 1,
155 PrintError => 0,
156 pg_enable_utf8 => 1,
157 pg_server_prepare => 1,
158 );
159  
160 my $dbh = eval {
161 DBI->connect(
162 $parsed->{dbi_dsn},
163 $parsed->{user},
164 $parsed->{password},
165 \%attrs,
166 );
167 };
168  
169 if ($@ || !$dbh) {
170 my $err = $@ || DBI->errstr || 'Unknown connection error';
171 $self->{stats}{connect_failures}++;
172 die IO::Async::Pg::Error::Connection->new(
173 message => "Connection failed: $err",
174 dsn => $self->safe_dsn,
175 );
176 }
177  
178 # Set statement timeout if configured
179 if (my $timeout = $self->{statement_timeout}) {
180 $dbh->do("SET statement_timeout = '${timeout}s'");
181 }
182  
183 my $conn = IO::Async::Pg::Connection->new(
184 dbh => $dbh,
185 pool => $self,
186 created_at => time(),
187 query_count => 0,
188 );
189  
190 $self->add_child($conn);
191  
192 # Run on_connect callback
193 if (my $on_connect = $self->{on_connect}) {
194 eval { await $on_connect->($conn) };
195 if ($@) {
196 $self->_log(warn => "on_connect failed: $@");
197 $conn->_close_dbh;
198 $self->remove_child($conn);
199 $self->{stats}{connect_failures}++;
200 die $@;
201 }
202 }
203  
204 $self->{stats}{created}++;
205 return $conn;
206 }
207  
208 # Return connection to pool (called by Connection::release)
209 sub _return_connection {
210 my ($self, $conn) = @_;
211  
212 # Remove from active list
213 @{$self->{active}} = grep { $_ != $conn } @{$self->{active}};
214  
215 # Check if connection is still valid
216 if (!$conn->{dbh} || !$conn->{dbh}->ping) {
217 $self->_discard_connection($conn);
218 return;
219 }
220  
221 # Check max_queries limit
222 if ($self->{max_queries} && $conn->query_count >= $self->{max_queries}) {
223 $self->_discard_connection($conn);
224 $self->_ensure_min_connections;
225 return;
226 }
227  
228 # Run on_release callback
229 if (my $on_release = $self->{on_release}) {
230 my $cleanup = async sub {
231 eval {
232 # Reset connection state
233 await $conn->query('ROLLBACK') if $conn->{in_transaction};
234 await $on_release->($conn);
235 };
236 if ($@) {
237 $self->_log(warn => "on_release failed: $@");
238 $self->_discard_connection($conn);
239 return;
240 }
241 $self->_release_to_idle_or_waiting($conn);
242 };
243 $cleanup->()->retain;
244 }
245 else {
246 $self->_release_to_idle_or_waiting($conn);
247 }
248 }
249  
250 sub _release_to_idle_or_waiting {
251 my ($self, $conn) = @_;
252  
253 # If someone is waiting, give them this connection
254 if (my $waiting = shift @{$self->{waiting}}) {
255 push @{$self->{active}}, $conn;
256 $conn->{last_used} = time();
257 $conn->{released} = 0;
258 $waiting->{future}->done($conn);
259 return;
260 }
261  
262 # Otherwise return to idle pool
263 push @{$self->{idle}}, $conn;
264 $self->{stats}{released}++;
265 }
266  
267 sub _discard_connection {
268 my ($self, $conn) = @_;
269 $conn->_close_dbh;
270 eval { $self->remove_child($conn) };
271 $self->{stats}{discarded}++;
272 }
273  
274 sub _ensure_min_connections {
275 my ($self) = @_;
276  
277 my $needed = $self->{min_connections} - $self->total_count;
278 return if $needed <= 0;
279  
280 # Create connections in parallel (fire and forget)
281 for (1 .. $needed) {
282 my $f = $self->_create_connection;
283 $f->on_done(sub {
284 my ($conn) = @_;
285 push @{$self->{idle}}, $conn;
286 });
287 $f->on_fail(sub {
288 my ($err) = @_;
289 $self->_log(warn => "Failed to create initial connection: $err");
290 });
291 $f->retain;
292 }
293 }
294  
295 sub _check_fork {
296 my ($self) = @_;
297 if ($self->{pid} != $$) {
298 # We've forked - discard all connections
299 @{$self->{idle}} = ();
300 @{$self->{active}} = ();
301 $self->{pid} = $$;
302 }
303 }
304  
305 sub _log {
306 my ($self, $level, $message) = @_;
307 if (my $cb = $self->{on_log}) {
308 $cb->($level, $message);
309 }
310 else {
311 warn "IO::Async::Pg [$level]: $message\n";
312 }
313 }
314  
315 1;
316  
317 __END__
« Pg/Error.pm ↑ Summary Pg/Connection.pm »