blib/lib/PAGI/FastAPI/Queue/Driver/Redis.pm

filter: Statementstmt 81.8% 9 / 11 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 4 / 4 Podpod n/a totaltotal 86.6% 13 / 15 CC 1 SCAR 0.7
CC
1
Cov
82%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
↑ Summary
1 package PAGI::FastAPI::Queue::Driver::Redis;
2  
3 1 ▶use v5.38;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use experimental 'class';
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 our $VERSION = qv('v0.0.1');
8 our $AUTHORITY = 'cpan:MANWAR';
9  
10 0 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=2.6
11 use Future::AsyncAwait;
12 use JSON::PP;
13  
14 use PAGI::FastAPI::Queue::Driver;
15  
16 class PAGI::FastAPI::Queue::Driver::Redis :isa(PAGI::FastAPI::Queue::Driver) {
17 field $redis :param = undef;
18 field $host :param = '127.0.0.1';
19 field $port :param = 6379;
20 field $uri :param = undef;
21 field $username :param = undef;
22 field $password :param = undef;
23 field $database :param = undef;
24 field $prefix :param = 'pagi:queue:';
25 field $scan_count :param = 100;
26  
27 field $connect_future;
28 field $json = JSON::PP->new->allow_nonref->canonical;
29  
30 ADJUST {
31 unless (defined $redis) {
32 require Async::Redis;
33  
34 my %opts = (host => $host, port => $port);
35 $opts{uri} = $uri if defined $uri;
36 $opts{username} = $username if defined $username;
37 $opts{password} = $password if defined $password;
38 $opts{database} = $database if defined $database;
39  
40 $redis = Async::Redis->new(%opts);
41 }
42 }
43  
44 method _key ($topic) {
45 return "$prefix$topic";
46 }
47  
48 # Connects lazily (and only once) on first use, rather than in ADJUST,
49 # since connecting is asynchronous and ADJUST cannot await.
50 async method _client () {
51 $connect_future //= $redis->connect;
52 await $connect_future;
53 return $redis;
54 }
55  
56 async method push ($topic, $payload) {
57 my $client = await $self->_client;
58 await $client->rpush($self->_key($topic), $json->encode($payload));
59 return 1;
60 }
61  
62 async method pop ($topic) {
63 my $client = await $self->_client;
64 my $raw = await $client->lpop($self->_key($topic));
65 return undef unless defined $raw;
66 return $json->decode($raw);
67 }
68  
69 async method size ($topic = undef) {
70 my $client = await $self->_client;
71  
72 if (defined $topic) {
73 return await $client->llen($self->_key($topic));
74 }
75  
76 my $total = 0;
77 my $cursor = 0;
78 do {
79 my ($next_cursor, $keys) = await $client->scan(
80 $cursor, 'MATCH', "$prefix*", 'COUNT', $scan_count,
81 );
82 $cursor = $next_cursor;
83  
84 if (@$keys) {
85 my @lens = await Future->needs_all(
86 map { $client->llen($_) } @$keys
87 );
88 $total += $_ for @lens;
89 }
90 } while ($cursor != 0);
91  
92 return $total;
93 }
94  
95 # Not part of the PAGI::FastAPI::Queue::Driver contract. Call from an
96 # $app->on_shutdown() hook to release the underlying connection cleanly.
97 method disconnect () {
98 $redis->disconnect if $redis;
99 return 1;
100 }
101 }
102  
103 =encoding utf-8
104  
105 =head1 NAME
106  
107 PAGI::FastAPI::Queue::Driver::Redis - Redis Storage Driver for PAGI::FastAPI::Queue
108  
109 =head1 VERSION
110  
111 Version v0.0.1
112  
113 =head1 SYNOPSIS
114  
115 use PAGI::FastAPI::Queue;
116 use PAGI::FastAPI::Depends qw(Depends);
117  
118 my $queue = PAGI::FastAPI::Queue->new(
119 driver => 'PAGI::FastAPI::Queue::Driver::Redis',
120 options => {
121 host => '127.0.0.1',
122 port => 6379,
123 prefix => 'myapp:queue:',
124 },
125 );
126  
127 $app->post('/jobs',
128 dependencies => [ Depends($queue->dep, key => 'queue') ],
129 handler => async sub ($c) {
130 await $c->stash->{queue}->push('emails', { to => 'a@b.com' });
131 return { queued => 1 };
132 },
133 );
134  
135 # Release the connection on shutdown (optional; not part of the
136 # PAGI::FastAPI::Queue::Driver contract, so reach the driver directly)
137 $app->on_shutdown(async sub {
138 # e.g. if you kept a reference to the driver instance yourself
139 # $driver->disconnect;
140 });
141  
142 =head1 DESCRIPTION
143  
144 C<PAGI::FastAPI::Queue::Driver::Redis> is a storage driver plugin for
145 L<PAGI::FastAPI::Queue>. It stores each topic as a Redis list (C<RPUSH> to
146 enqueue, C<LPOP> to dequeue), so queued items are shared across every
147 worker process and host pointed at the same Redis instance and C<prefix>,
148 unlike the built-in L<PAGI::FastAPI::Queue::Driver::Memory>, which is
149 scoped to a single process.
150  
151 Payloads (any Perl scalar - including hashrefs/arrayrefs) are serialised
152 with L<JSON::PP> before being stored, and deserialised on C<pop>, so the
153 round-trip behaviour matches L<PAGI::FastAPI::Queue::Driver::Memory> for
154 any JSON-representable value.
155  
156 =head2 Why L<Async::Redis> and not L<Net::Async::Redis>?
157  
158 L<PAGI::FastAPI> documents L<Future::IO> as the event-loop-agnostic
159 target for anything loop-driven, with L<IO::Async> (used by the reference
160 C<PAGI::Server>) treated as an implementation detail applications
161 shouldn't depend on directly (see
162 L<PAGI::FastAPI/"EVENT LOOPS: FUTURE::IO IS THE GOAL, IO::ASYNC IS AN
163 IMPLEMENTATION DETAIL">). L<Async::Redis> is built directly on
164 L<Future::IO> rather than tying itself to L<IO::Async>, so this driver
165 keeps working regardless of which backend a given PAGI server ends up
166 using, with no reactor-bridging required.
167  
168 =head2 Aggregate C<size()> and C<SCAN>
169  
170 Unlike L<PAGI::FastAPI::Queue::Driver::Memory>, Redis has no O(1) way to
171 enumerate "every list under this driver". C<size()> with no C<$topic>
172 therefore walks the keyspace with Redis's cursor-based C<SCAN> command
173 (never the blocking C<KEYS> command), matching on C<"$prefix*">, and sums
174 C<LLEN> across whatever keys it finds. This is a best-effort snapshot, not
175 an atomic one: concurrent pushes/pops elsewhere during the scan can make
176 the total slightly stale. Prefer C<size($topic)> when you only care about
177 one topic; it's a single C<LLEN> call.
178  
179 =head1 METHODS
180  
181 Inherits C<push>, C<pop>, and C<size> from L<PAGI::FastAPI::Queue::Driver>.
182  
183 =head2 C<new(%options)>
184  
185 =over 4
186  
187 =item * C<redis> - (Optional) A pre-built, C<Async::Redis>-compatible
188 client instance to use instead of constructing one. Useful for sharing a
189 single connection across multiple drivers, for supplying your own
190 pre-configured client (TLS, auth, custom timeouts), or for injecting a
191 test double. When given, C<host>/C<port>/C<uri>/C<username>/C<password>/
192 C<database> are ignored.
193  
194 =item * C<host> - (Optional) Redis host. Defaults to C<'127.0.0.1'>.
195  
196 =item * C<port> - (Optional) Redis port. Defaults to C<6379>.
197  
198 =item * C<uri> - (Optional) A full C<redis://> connection URI, forwarded
199 to C<Async::Redis-E<gt>new> as-is. When given together with C<host>/
200 C<port>, C<uri> takes precedence in C<Async::Redis> itself.
201  
202 =item * C<username> / C<password> - (Optional) Redis 6+ ACL / AUTH
203 credentials.
204  
205 =item * C<database> - (Optional) Redis logical database index to C<SELECT>.
206  
207 =item * C<prefix> - (Optional) Key namespace prefix. Defaults to
208 C<'pagi:queue:'>. Each topic is stored under C<"$prefix$topic">. Use a
209 distinct C<prefix> per application when sharing one Redis instance across
210 multiple apps.
211  
212 =item * C<scan_count> - (Optional) C<COUNT> hint passed to each C<SCAN>
213 call made by aggregate C<size()>. Defaults to C<100>. Higher values mean
214 fewer round-trips but larger batches per call.
215  
216 =back
217  
218 The underlying client connects lazily: no network I/O happens in C<new()>
219 or C<ADJUST>, only on the first C<push>/C<pop>/C<size> call, and only
220 once per driver instance.
221  
222 =head2 C<disconnect()>
223  
224 Not part of the L<PAGI::FastAPI::Queue::Driver> contract and not exposed
225 through L<PAGI::FastAPI::Queue>. Closes the underlying client connection.
226 Call it directly on the driver instance (not through C<PAGI::FastAPI::Queue>,
227 which does not expose its backend) from an C<< $app->on_shutdown >> hook
228 if you want a clean shutdown. Synchronous (does not return a L<Future>).
229 Safe to skip; the OS reclaims the socket on process exit regardless.
230  
231 =head1 DEPENDENCIES
232  
233 Requires L<Async::Redis> (not installed automatically as a hard
234 C<PREREQ_PM> dependency solely because C<redis> can also be supplied
235 pre-built by the caller; if you don't pass C<redis>, install
236 L<Async::Redis> yourself).
237  
238 =head1 SEE ALSO
239  
240 L<PAGI::FastAPI::Queue>, L<PAGI::FastAPI::Queue::Driver>,
241 L<PAGI::FastAPI::Queue::Driver::Memory>, L<Async::Redis>
242  
243 =head1 AUTHOR
244  
245 Mohammad Sajid Anwar, C<< <mohammad.anwar at yahoo.com> >>
246  
247 =head1 REPOSITORY
248  
249 L<https://github.com/manwar/PAGI-FastAPI-Queue-Driver-Redis>
250  
251 =head1 BUGS
252  
253 Please report any bugs or feature requests through the web interface at L<https://github.com/manwar/PAGI-FastAPI-Queue-Driver-Redis/issues>.
254 I will be notified and then you'll automatically be notified of progress on your
255 bug as I make changes.
256  
257 =head1 SUPPORT
258  
259 You can find documentation for this module with the perldoc command.
260  
261 perldoc PAGI::FastAPI::Queue::Driver::Redis
262  
263 You can also look for information at:
264  
265 =over 4
266  
267 =item * BUG Report
268  
269 L<https://github.com/manwar/PAGI-FastAPI-Queue-Driver-Redis/issues>
270  
271 =item * CPAN Ratings
272  
273 L<http://cpanratings.perl.org/d/PAGI-FastAPI-Queue-Driver-Redis>
274  
275 =item * Search MetaCPAN
276  
277 L<https://metacpan.org/dist/PAGI-FastAPI-Queue-Driver-Redis/>
278  
279 =back
280  
281 =head1 LICENSE AND COPYRIGHT
282  
283 Copyright (C) 2026 Mohammad Sajid Anwar.
284  
285 This program is free software; you can redistribute it and/or modify it under
286 the terms of the Artistic License (2.0).
287  
288 =cut
289  
290 1; # End of PAGI::FastAPI::Queue::Driver::Redis
↑ Summary