blib/lib/Dancer2/Plugin/DBIC/Async.pm

filter: Statementstmt 93.2% 97 / 104 Branchbran 70.8% 17 / 24 Conditioncond 63.6% 7 / 11 MC/DCmcdc 33.3% 2 / 6 Subroutinesub 93.3% 28 / 30 Podpod 100% 8 / 8 totaltotal 86.8% 159 / 183 CC 18 SCAR 10.2
CC
18
Cov
87%
_get_async
8.0
async_update
3.1
async_delete
3.1
CRAP 2.8
↑ Summary
1 package Dancer2::Plugin::DBIC::Async;
2  
3 4 $Dancer2::Plugin::DBIC::Async::VERSION = '0.06';
4 4 $Dancer2::Plugin::DBIC::Async::AUTHORITY = 'cpan:MANWAR';
5  
6 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 4 ▶use feature 'state';
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 4 ▶use Dancer2::Plugin;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 4 ▶use IO::Async::Loop;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 4 ▶use DBIx::Class::Async::Schema;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 4 ▶use Module::Runtime qw(use_module);
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 =encoding utf8
16  
17 =head1 NAME
18  
19 Dancer2::Plugin::DBIC::Async - High-concurrency DBIx::Class bridge for Dancer2
20  
21 =head1 VERSION
22  
23 Version 0.06
24  
25 =head1 BENEFITS
26  
27 The primary benefit of this plugin is B<Concurrency Throughput>. Unlike traditional
28 database plugins that block your Dancer2 worker during a query, this plugin
29 delegates I/O to a background worker pool.
30  
31 =head2 Non-Blocking I/O (Concurrency)
32  
33 In a traditional sync app, if a database query takes B<500ms>, that L<Dancer2>
34 worker is B<"busy"> and cannot accept any other incoming requests for that
35 B<half a second>.
36  
37 =over 4
38  
39 =item Sync
40  
41 B<10 workers> can handle exactly B<10 simultaneous long-running queries>. The
42 11th user must wait in the B<TCP queue>.
43  
44 =item Async
45  
46 A single worker can initiate dozens of database queries. While the database is
47 processing the data, the worker remains free to handle other incoming requests
48 or perform other I/O tasks.
49  
50 =back
51  
52 =head2 Parallelism within a Single Route
53  
54 With the sync plugin, if you need to fetch data from five different tables that don't depend on
55 each other, you must do them sequentially. With the async plugin, you can fire all five queries
56 simultaneously.
57  
58 # Regular Sync (Total time = sum of all queries)
59 my $user = rset('User')->find(1);
60 my $posts = rset('Post')->search({ uid => 1 });
61 my $friends = rset('Friend')->search({ uid => 1 });
62  
63 # Async (Total time = the time of the single slowest query)
64 my $user_f = async_rs('User')->find(1);
65 my $posts_f = async_rs('Post')->search({ uid => 1 });
66 my $friends_f = async_rs('Friend')->search({ uid => 1 });
67  
68 # Wait for all to finish
69 my ($user, $posts, $friends) = Future->wait_all($user_f, $posts_f, $friends_f)->get;
70  
71 =head2 Key Technical Differences
72  
73 =over 4
74  
75 =item B<Context Switching>
76  
77 In the sync version, the operating system might pause the process (context switch)
78 while waiting for the disk. In the async version, the Event Loop (L<IO::Async>) manages
79 this, which is much lighter on the CPU.
80  
81 =item B<Wait vs. Block>
82  
83 In the async version, we use B<wait_all> or B<then>. This tells the server:
84 B<"Keep this request in mind, but go help other users until the data comes back.">
85  
86 =item B<Error Handling>
87  
88 L<Futures> have built-in B<on_fail> handlers, making it easier to manage database
89 timeouts without crashing the whole worker process.
90  
91 =back
92  
93 =head2 Better Resource Utilisation
94  
95 Sync apps often solve scaling issues by adding more worker processes (e.g., increasing B<Starman> workers).
96 However, each worker consumes significant B<RAM>.
97  
98 =over 4
99  
100 =item Sync Scaling
101  
102 High Memory usage (100 workers = 100x memory).
103  
104 =item Async Scaling
105  
106 Low Memory usage (1 worker handles 100 connections).
107  
108 =back
109  
110 =head1 SYNOPSIS
111  
112 # In config.yml
113 plugins:
114 "DBIC::Async":
115 default:
116 schema_class: "MyApp::Schema"
117 dsn: "dbi:SQLite:dbname=myapp.db"
118 async:
119 workers: 4
120  
121 # In your Dancer2 app
122 use Dancer2;
123 use Dancer2::Plugin::DBIC::Async;
124 use Future;
125  
126 # Basic non-blocking count
127 get '/count' => sub {
128 my $count = async_count('User')->get;
129 return to_json({ total_users => $count });
130 };
131  
132 # Advanced: Parallel queries (non-blocking)
133 get '/dashboard' => sub {
134 my $query = query_parameters->get('q');
135  
136 # 1. Fire multiple queries simultaneously
137 my $search_f = async_search('User', { name => { -like => "%$query%" } });
138 my $count_f = async_count('User');
139  
140 # 2. Wait for all background workers to finish
141 Future->wait_all($search_f, $count_f)->get;
142  
143 # 3. Retrieve results (already deflated to HashRefs)
144 my @users = @{ $search_f->get };
145 my $total = $count_f->get;
146  
147 template 'dashboard' => {
148 users => \@users,
149 total => $total,
150 };
151 };
152  
153 # Flexible Update (Scalar ID or HashRef query)
154 post '/user/:id/deactivate' => sub {
155 my $id = route_parameters->get('id');
156 async_update('User', $id, { active => 0 })->get;
157 return "User deactivated";
158 };
159  
160 =head1 KEYWORDS
161  
162 =head2 async_db
163  
164 my $schema = async_db();
165 my $schema = async_db('custom_connection');
166  
167 Returns the underlying L<DBIx::Class::Async::Schema> instance for the
168 specified connection. Use this for complex operations like C<txn_do> or
169 direct storage management. The connection name defaults to C<'default'>.
170  
171 =head2 async_rs
172  
173 my $rs = async_rs('User');
174 my $f = $rs->search({ active => 1 })->page(2)->all;
175  
176 Returns a L<DBIx::Class::ResultSet> proxy for the specified source. Methods
177 called on this proxy return L<Future> objects instead of data. This is the
178 most flexible way to build complex, non-blocking queries.
179  
180 =head2 async_count
181  
182 my $f = async_count('User');
183 my $f = async_count('User', 'custom_connection');
184  
185 Returns a L<Future> that resolves to the integer count of records in the
186 specified source.
187  
188 =head2 async_find
189  
190 my $f = async_find('User', $id);
191 my $f = async_find('User', $id, 'custom_connection');
192  
193 Returns a L<Future> that resolves to a single record (as a deflated HashRef)
194 matching the provided primary key. Returns C<undef> if no record is found.
195  
196 =head2 async_search
197  
198 my $f = async_search('Contact', { active => 1 });
199 my $f = async_search('Contact', { id => 5 }, 'archive');
200  
201 Returns a L<Future> that resolves to an ArrayRef of HashRefs representing
202 the rows. This is the recommended way to fetch multiple records for
203 non-blocking templates or JSON responses.
204  
205 =head2 async_create
206  
207 my $f = async_create('User', { name => 'Alice', email => 'alice@example.com' });
208  
209 Returns a L<Future> that resolves to the newly created record as a deflated HashRef.
210  
211 =head2 async_update
212  
213 my $f = async_update('User', $id, { status => 'inactive' });
214 my $f = async_update('User', { status => 'pending' }, { status => 'active' });
215  
216 Returns a L<Future> that resolves to the number of rows updated (as an integer).
217  
218 B<Note:> The second argument can be either a scalar primary key (assumed to
219 be the column C<'id'>) or a standard L<DBIx::Class> search HashRef for
220 complex updates.
221  
222 =head2 async_delete
223  
224 my $f = async_delete('User', $id);
225 my $f = async_delete('User', { status => 'spam' });
226  
227 Returns a L<Future> that resolves to the number of rows deleted (as an integer).
228  
229 B<Note:> Like C<async_update>, the second argument can be a scalar primary
230 key (targeting the column C<'id'>) or a search HashRef.
231  
232 =head1 DATA FORMAT
233  
234 All keywords that return row data (C<async_find>, C<async_search>, C<async_create>)
235 return B<deflated HashRefs> rather than L<DBIx::Class::Row> objects. This
236 ensures that the data is safe to use outside of the background worker's event
237 loop and is ready for serialization to JSON or rendering in templates.
238  
239 =cut
240  
241 4 my %INSTANCES;
242  
243 4 plugin_keywords qw(
244 async_db
245 async_rs
246 async_count
247 async_find
248 async_search
249 async_create
250 async_update
251 async_delete
252 );
253  
254 0 ▶sub async_db :PluginKeyword {
Subroutine async_db: not called CC=1 SCAR=6.9
Pod documented
255 0 my ($plugin, $name) = @_;
256 0 return _get_async($plugin, $name);
257 4 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
258  
259 0 ▶sub async_rs :PluginKeyword {
Subroutine async_rs: not called CC=1 SCAR=6.9
Pod documented
260 0 my ($plugin, $source, $name) = @_;
261 0 return _get_async($plugin, $name)->resultset($source);
262 4 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
263  
264 7 ▶sub async_count :PluginKeyword {
Subroutine async_count: called CC=1 SCAR=0.0
Pod documented
265 7 my ($plugin, $source, $name) = @_;
266 return _get_async($plugin, $name)->resultset($source)->count->transform(
267 3 ▶ done => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
268 3 my $count = shift;
269 3 return $count + 0;
270 }
271 7 );
272 4 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
273  
274 5 ▶sub async_find :PluginKeyword {
Subroutine async_find: called CC=2 SCAR=7.0
Pod documented
275 5 my ($plugin, $source, $id, $name) = @_;
276  
277 # If the user passed a HashRef into the $name slot, they likely forgot
278 # the connection name is optional.
279 5 ▶ $name = undef if ref $name;
Branch: 1 branch
BranchTrueFalseTotal
if ref $name 0 5 5
280  
281 return _get_async($plugin, $name)->resultset($source)->find($id)->transform(
282 5 ▶ done => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
283 5 my $row = shift;
284 5 ▶ return undef unless $row;
Branch: 1 branch
BranchTrueFalseTotal
unless $row 1 4 5
285 4 return { $row->get_columns };
286 }
287 5 );
288 4 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
289  
290 1 ▶sub async_search :PluginKeyword {
Subroutine async_search: called CC=2 SCAR=7.6
Pod documented
291 1 my ($plugin, $source, $cond, $name) = @_;
292  
293 # Defensive check: If $cond was skipped and $name was passed in 3rd slot
294 # or if $name is a HashRef (meaning it's actually the condition).
295 1 ▶ if (ref $name eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $name eq "HASH") 0 1 1
296 # This shouldn't happen with the current signature, but protects
297 # against users confusing argument order.
298 0 my $tmp = $cond;
299 0 $cond = $name;
300 0 $name = $tmp;
301 }
302  
303 # Pass $name to _get_async; our improved _get_async
304 # will handle it if it's undef or invalid.
305 return _get_async($plugin, $name)
306 ->resultset($source)
307 ->search($cond)
308 ->all
309 ->transform(
310 1 ▶ done => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
311 1 my $rows = shift;
312 return [ map {
313 1 my %data = $_->get_columns;
314 10 \%data
315 } @$rows ];
316 }
317 1 );
318 4 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
319  
320 2 ▶sub async_create :PluginKeyword {
Subroutine async_create: called CC=2 SCAR=7.0
Pod documented
321 2 my ($plugin, $source, $data, $name) = @_;
322  
323 2 ▶ $name = undef if ref $name;
Branch: 1 branch
BranchTrueFalseTotal
if ref $name 0 2 2
324  
325 return _get_async($plugin, $name)->resultset($source)->create($data)->transform(
326 2 ▶ done => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
327 2 my $row = shift;
328 2 return { $row->get_columns };
329 }
330 2 );
331 4 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
332  
333 1 ▶sub async_update :PluginKeyword {
Subroutine async_update: called CC=3 SCAR=11.4
Pod documented
334 1 my ($plugin, $source, $query, $data, $name) = @_;
335  
336 # Defensive check: if $query is just a scalar ID, turn it into a hashref
337 1 ▶ $query = { id => $query } unless ref $query;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $query 1 0 1
338 1 ▶ $name = undef if ref $name;
Branch: 1 branch
BranchTrueFalseTotal
if ref $name 0 1 1
339  
340 return _get_async($plugin, $name)
341 ->resultset($source)
342 ->search($query)
343 ->update($data)
344 ->transform(
345 1 ▶ done => sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
346 1 my $result = shift;
347 # DBIC update returns the number of rows affected.
348 # We ensure it's returned as a pure integer.
349 1 ▶ return int($result // 0);
Condition50%1/2
$result // 0
l!l
10
MC/DC0%0/1
$result // 0
$result
Truth table50%1/2
A
A= $result
Aresult
11
00
350 }
351 1 );
352 4 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
353  
354 1 ▶sub async_delete :PluginKeyword {
Subroutine async_delete: called CC=3 SCAR=11.4
Pod documented
355 1 my ($plugin, $source, $query, $name) = @_;
356  
357 # Defensive check: handle scalar ID for backward compatibility in tests
358 1 ▶ $query = { id => $query } unless ref $query;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $query 1 0 1
359 1 ▶ $name = undef if ref $name;
Branch: 1 branch
BranchTrueFalseTotal
if ref $name 0 1 1
360  
361 return _get_async($plugin, $name)
362 ->resultset($source)
363 ->search($query)
364 ->delete
365 ->transform(
366 1 ▶ done => sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
367 1 my $result = shift;
368 # Return strictly as an integer
369 1 ▶ return int($result // 0);
Condition50%1/2
$result // 0
l!l
10
MC/DC0%0/1
$result // 0
$result
Truth table50%1/2
A
A= $result
Aresult
11
00
370 }
371 1 );
372 4 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
373  
374 17 ▶sub _get_async {
Subroutine _get_async: called CC=8 SCAR=20.8
375 17 my ($plugin, $name) = @_;
376  
377 # If $name is a reference (like a condition hash) or missing,
378 # it's clearly not the connection name.
379 17 ▶ if (!defined $name || ref $name) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $name or ref $name) 15 2 17
Condition66%2/3
not defined $name or ref $name
l!l&&r!l&&!r
1502
MC/DC50%1/2
not defined $name or ref $name
not defined $name ref $name
Truth table66%2/3
not(A) or B
A= not defined $nameB= ref $name
ABresult
1X1
011
000
380 15 $name = 'default';
381 }
382  
383 17 ▶ return $INSTANCES{$name} if $INSTANCES{$name};
Branch: 1 branch
BranchTrueFalseTotal
if $INSTANCES{$name} 10 7 17
384  
385 7 my $app = $plugin->app;
386 7 ▶ my $config = $app->config->{plugins}{'DBIC::Async'}{$name}
Branch: 1 branch
BranchTrueFalseTotal
my $config = $app->config->{"plugins"}{"DBIC::Async"}{$name} or die "No configuration for DBIC::Async connection '${name}'" 5 2 7
387 or die "No configuration for DBIC::Async connection '$name'";
388  
389 5 ▶ my $schema_class = $config->{schema_class} or die "schema_class required";
Branch: 1 branch
BranchTrueFalseTotal
my $schema_class = $config->{"schema_class"} or die "schema_class required" 4 1 5
390 4 use_module($schema_class);
391  
392 4 state $loop = IO::Async::Loop->new;
393  
394 my $schema = DBIx::Class::Async::Schema->connect(
395 $config->{dsn},
396 $config->{user},
397 $config->{password},
398 $config->{options} || {},
399 {
400 schema_class => $schema_class,
401 loop => $loop,
402 4 ▶ %{ $config->{async} || {} },
Condition75%3/4
$config->{'options'} || {}
l!l
04
$config->{'async'} || {}
l!l
13
MC/DC0%0/1
$config->{'options'} || {}
$config->{'options'}
MC/DC100%1/1
$config->{'async'} || {}
$config->{'async'}
Truth table50%1/2
A
A= $config->{'options'}
Aresult
11
00
Truth table100%2/2
A
A= $config->{'async'}
Aresult
11
00
403 }
404 );
405  
406 4 $INSTANCES{$name} = $schema;
407 4 return $schema;
408 }
409  
410 =head1 AUTHOR
411  
412 Mohammad Sajid Anwar, C<< <mohammad.anwar at yahoo.com> >>
413  
414 =head1 REPOSITORY
415  
416 L<https://github.com/manwar/Dancer2-Plugin-DBIC-Async>
417  
418 =head1 BUGS
419  
420 Please report any bugs or feature requests through the web interface at L<https://github.com/manwar/Dancer2-Plugin-DBIC-Async/issues>.
421 I will be notified and then you'll automatically be notified of progress on your
422 bug as I make changes.
423  
424 =head1 SUPPORT
425  
426 You can find documentation for this module with the perldoc command.
427  
428 perldoc Dancer2::Plugin::DBIC::Async
429  
430 You can also look for information at:
431  
432 =over 4
433  
434 =item * BUG Report
435  
436 L<https://github.com/manwar/Dancer2-Plugin-DBIC-Async/issues>
437  
438 =item * CPAN Ratings
439  
440 L<http://cpanratings.perl.org/d/Dancer2-Plugin-DBIC-Async>
441  
442 =item * Search MetaCPAN
443  
444 L<https://metacpan.org/dist/Dancer2-Plugin-DBIC-Async/>
445  
446 =back
447  
448 =head1 LICENSE AND COPYRIGHT
449  
450 Copyright (C) 2026 Mohammad Sajid Anwar.
451  
452 This program is free software; you can redistribute it and / or modify it under
453 the terms of the the Artistic License (2.0). You may obtain a copy of the full
454 license at:
455  
456 L<http://www.perlfoundation.org/artistic_license_2_0>
457  
458 Any use, modification, and distribution of the Standard or Modified Versions is
459 governed by this Artistic License.By using, modifying or distributing the Package,
460 you accept this license. Do not use, modify, or distribute the Package, if you do
461 not accept this license.
462  
463 If your Modified Version has been derived from a Modified Version made by someone
464 other than you,you are nevertheless required to ensure that your Modified Version
465 complies with the requirements of this license.
466  
467 This license does not grant you the right to use any trademark, service mark,
468 tradename, or logo of the Copyright Holder.
469  
470 This license includes the non-exclusive, worldwide, free-of-charge patent license
471 to make, have made, use, offer to sell, sell, import and otherwise transfer the
472 Package with respect to any patent claims licensable by the Copyright Holder that
473 are necessarily infringed by the Package. If you institute patent litigation
474 (including a cross-claim or counterclaim) against any party alleging that the
475 Package constitutes direct or contributory patent infringement,then this Artistic
476 License to you shall terminate on the date that such litigation is filed.
477  
478 Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND
479 CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED
480 WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
481 NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS
482 REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT,
483 INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE
484 OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
485  
486 =cut
487  
488 4 1; # End of Dancer2::Plugin::DBIC::Async
↑ Summary