blib/lib/PAGI/Server/AsyncFile.pm

filter: Statementstmt 72.7% 88 / 121 Branchbran 39.2% 22 / 56 Conditioncond 54.5% 6 / 11 MC/DCmcdc 33.3% 2 / 6 Subroutinesub 87.5% 14 / 16 Podpod 100% 7 / 7 totaltotal 64.0% 139 / 217 CC 35 SCAR 41.6
CC
35
Cov
62%
_worker_operation
210.0
read_file_chunked
13.4
cleanup
7.9
CRAP 63.8
« blib/lib/PAGI/Server.pm ↑ Summary blib/lib/PAGI/Server/Connection.pm »
1 package PAGI::Server::AsyncFile;
2  
3 157 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 157 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 157 our $VERSION = '0.002013';
7  
8 157 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 157 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 157 ▶use IO::Async::Function;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 157 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 =head1 NAME
14  
15 PAGI::Server::AsyncFile - Non-blocking file I/O for PAGI::Server internals
16  
17 =head1 SYNOPSIS
18  
19 use PAGI::Server::AsyncFile;
20 use IO::Async::Loop;
21  
22 # Create or obtain an IO::Async::Loop
23 my $loop = IO::Async::Loop->new;
24  
25 # Read entire file
26 my $content = await PAGI::Server::AsyncFile->read_file($loop, '/path/to/file');
27  
28 # Read file in chunks (streaming)
29 await PAGI::Server::AsyncFile->read_file_chunked($loop, '/path/to/file', async sub {
30 my ($chunk) = @_;
31 # Process each chunk
32 }, chunk_size => 65536);
33  
34 # Write file
35 await PAGI::Server::AsyncFile->write_file($loop, '/path/to/file', $content);
36  
37 # Append to file
38 await PAGI::Server::AsyncFile->append_file($loop, '/path/to/file', $log_line);
39  
40 =head1 DESCRIPTION
41  
42 This module provides non-blocking file I/O operations using L<IO::Async::Function>
43 worker processes. It is used internally by L<PAGI::Server> for efficient file
44 streaming.
45  
46 B<Note:> This is a PAGI::Server internal module. PAGI applications are
47 loop-agnostic and should use synchronous file I/O (which is simple and fast
48 for typical file sizes) or bring their own async file library if needed.
49  
50 It uses L<IO::Async::Function> to offload blocking file operations to worker
51 processes, preventing the main event loop from being blocked during disk I/O.
52 Regular file I/O in POSIX is always blocking at the kernel level - even
53 C<select()>/C<poll()>/C<epoll()> report regular files as always "ready".
54 This module works around this limitation by running file operations in
55 separate worker processes, similar to how Node.js/libuv handles file I/O.
56  
57 =head1 CLASS METHODS
58  
59 =cut
60  
61 # Singleton function pool per loop (keyed by loop address)
62 157 my %_function_pools;
63  
64 # Get or create the function pool for a given loop
65 31 ▶sub _get_function {
Subroutine _get_function: called CC=3 SCAR=11.3
66 31 my ($class, $loop) = @_;
67  
68 31 ▶ my $loop_id = blessed($loop) ? "$loop" : 'default';
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($loop) ? : 31 0 31
69  
70 31 ▶ unless ($_function_pools{$loop_id}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($_function_pools{$loop_id}) 4 27 31
71 my $function = IO::Async::Function->new(
72 0 ▶ code => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
73 0 my ($op, @args) = @_;
74 0 return _worker_operation($op, @args);
75 },
76 4 min_workers => 1,
77 max_workers => 4,
78 idle_timeout => 30,
79 );
80  
81 4 $loop->add($function);
82 4 $_function_pools{$loop_id} = $function;
83 }
84  
85 31 return $_function_pools{$loop_id};
86 }
87  
88 # Worker process operations
89 0 ▶sub _worker_operation {
Subroutine _worker_operation: not called CC=14 SCAR=53.5
90 0 my ($op, @args) = @_;
91  
92 0 ▶ if ($op eq 'read_file') {
Branch: 6 branches
BranchTrueFalseTotal
if ($op eq 'read_file') { } 0 0 0
elsif ($op eq 'read_chunk') { } 0 0 0
elsif ($op eq 'write_file') { } 0 0 0
elsif ($op eq 'append_file') { } 0 0 0
elsif ($op eq 'file_size') { } 0 0 0
elsif ($op eq 'file_exists') { } 0 0 0
93 0 my ($path) = @args;
94 0 ▶ open my $fh, '<:raw', $path or die "Cannot open $path: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $path or die "Cannot open ${path}: $!" 0 0 0
95 0 local $/;
96 0 my $content = <$fh>;
97 0 close $fh;
98 0 return $content;
99 }
100 elsif ($op eq 'read_chunk') {
101 0 my ($path, $offset, $chunk_size) = @args;
102 0 ▶ open my $fh, '<:raw', $path or die "Cannot open $path: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $path or die "Cannot open ${path}: $!" 0 0 0
103 0 ▶ seek($fh, $offset, 0) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 0 0 0
104 0 my $bytes_read = read($fh, my $buffer, $chunk_size);
105 0 close $fh;
106 0 ▶ return ($buffer, $bytes_read // 0);
Condition0%0/2
$bytes_read // 0
l!l
00
MC/DC0%0/1
$bytes_read // 0
$bytes_read
Truth table0%0/2
A
A= $bytes_read
Aresult
11
00
107 }
108 elsif ($op eq 'write_file') {
109 0 my ($path, $content) = @args;
110 0 ▶ open my $fh, '>:raw', $path or die "Cannot open $path for writing: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">:raw", $path or die "Cannot open $path for writing: $!" 0 0 0
111 0 print $fh $content;
112 0 close $fh;
113 0 return length($content);
114 }
115 elsif ($op eq 'append_file') {
116 0 my ($path, $content) = @args;
117 0 ▶ open my $fh, '>>:raw', $path or die "Cannot open $path for appending: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">>:raw", $path or die "Cannot open $path for appending: $!" 0 0 0
118 0 print $fh $content;
119 0 close $fh;
120 0 return length($content);
121 }
122 elsif ($op eq 'file_size') {
123 0 my ($path) = @args;
124 0 return -s $path;
125 }
126 elsif ($op eq 'file_exists') {
127 0 my ($path) = @args;
128 0 ▶ return -f $path ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
-f $path ? : 0 0 0
129 }
130 else {
131 0 die "Unknown operation: $op";
132 }
133 }
134  
135 =head2 read_file
136  
137 my $content = await PAGI::Server::AsyncFile->read_file($loop, $path);
138  
139 Read the entire contents of a file asynchronously. Returns a Future that
140 resolves to the file contents.
141  
142 Parameters:
143  
144 =over 4
145  
146 =item * C<$loop> - IO::Async::Loop instance
147  
148 =item * C<$path> - Path to the file to read
149  
150 =back
151  
152 Throws an exception if the file cannot be read.
153  
154 =cut
155  
156 11 ▶async sub read_file {
Subroutine read_file: called CC=3 SCAR=11.0
Pod documented
157 11 my ($class, $loop, $path) = @_;
158  
159 11 ▶ die "File not found: $path" unless -f $path;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $path 1 10 11
160 10 ▶ die "Cannot read file: $path" unless -r $path;
Branch: 1 branch
BranchTrueFalseTotal
unless -r $path 0 10 10
161  
162 10 my $function = $class->_get_function($loop);
163 10 return await $function->call(args => ['read_file', $path]);
164 157 }
165  
166 =head2 read_file_chunked
167  
168 await PAGI::Server::AsyncFile->read_file_chunked($loop, $path, async sub {
169 my ($chunk) = @_;
170 # Process chunk
171 }, chunk_size => 65536);
172  
173 # For Range requests (partial file):
174 await PAGI::Server::AsyncFile->read_file_chunked($loop, $path, $callback,
175 offset => 1000, # Start at byte 1000
176 length => 5000, # Read 5000 bytes total
177 );
178  
179 Read a file in chunks, calling a callback for each chunk. This is suitable
180 for streaming large files without loading the entire file into memory.
181  
182 Parameters:
183  
184 =over 4
185  
186 =item * C<$loop> - IO::Async::Loop instance
187  
188 =item * C<$path> - Path to the file to read
189  
190 =item * C<$callback> - Async callback called with each chunk. Receives the chunk data.
191  
192 =item * C<%opts> - Options:
193  
194 =over 4
195  
196 =item * C<chunk_size> - Size of each chunk in bytes (default: 65536)
197  
198 =item * C<offset> - Byte offset to start reading from (default: 0)
199  
200 =item * C<length> - Maximum bytes to read; omit to read to EOF
201  
202 =back
203  
204 =back
205  
206 Returns a Future that resolves to the number of bytes read when complete.
207 The callback should return/await properly if it needs to do async operations.
208  
209 =cut
210  
211 9 ▶async sub read_file_chunked {
Subroutine read_file_chunked: called CC=13 SCAR=26.0
Pod documented
212 9 my ($class, $loop, $path, $callback, %opts) = @_;
213  
214 9 ▶ die "File not found: $path" unless -f $path;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $path 0 9 9
215 9 ▶ die "Cannot read file: $path" unless -r $path;
Branch: 1 branch
BranchTrueFalseTotal
unless -r $path 0 9 9
216  
217 9 ▶ my $chunk_size = $opts{chunk_size} // 65536;
Condition50%1/2
$opts{"chunk_size"} // 65536
l!l
90
MC/DC0%0/1
$opts{"chunk_size"} // 65536
$opts{"chunk_size"}
Truth table50%1/2
A
A= $opts{"chunk_size"}
Aresult
11
00
218 9 ▶ my $start_offset = $opts{offset} // 0;
Condition100%2/2
$opts{"offset"} // 0
l!l
63
MC/DC100%1/1
$opts{"offset"} // 0
$opts{"offset"}
Truth table100%2/2
A
A= $opts{"offset"}
Aresult
11
00
219 9 my $max_length = $opts{length}; # undef means read to EOF
220  
221 9 my $file_size = -s $path;
222 9 my $function = $class->_get_function($loop);
223  
224 9 my $offset = $start_offset;
225 9 my $bytes_sent = 0;
226  
227 # Calculate end position
228 9 ▶ my $end_pos = defined $max_length
Branch: 1 branch
BranchTrueFalseTotal
defined $max_length ? : 3 6 9
229 ? $start_offset + $max_length
230 : $file_size;
231 9 ▶ $end_pos = $file_size if $end_pos > $file_size;
Branch: 1 branch
BranchTrueFalseTotal
if $end_pos > $file_size 0 9 9
232  
233 9 ▶ while ($offset < $end_pos) {
Branch: 1 branch
BranchTrueFalseTotal
if ($offset < $end_pos) 28 8 36
234 28 my $to_read = $chunk_size;
235  
236 # Don't read past the end position
237 28 ▶ if ($offset + $to_read > $end_pos) {
Branch: 1 branch
BranchTrueFalseTotal
if ($offset + $to_read > $end_pos) 6 22 28
238 6 $to_read = $end_pos - $offset;
239 }
240  
241 28 ▶ last if $to_read <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $to_read <= 0 0 28 28
242  
243 28 my ($chunk, $bytes_read) = await $function->call(
244 args => ['read_chunk', $path, $offset, $to_read]
245 );
246  
247 28 ▶ last unless $bytes_read;
Branch: 1 branch
BranchTrueFalseTotal
unless $bytes_read 0 28 28
248  
249 # Call the callback - it may be async
250 28 my $result = $callback->($chunk);
251 28 ▶ if (blessed($result) && $result->can('get')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($result) and $result->can("get")) 17 11 28
Condition66%2/3
builtin::blessed($result) and $result->can("get")
!ll&&!rl&&r
11017
MC/DC50%1/2
builtin::blessed($result) and $result->can("get")
builtin::blessed($result) $result->can("get")
Truth table66%2/3
A and B
A= builtin::blessed($result)B= $result->can("get")
ABresult
0X0
100
111
252 17 await $result;
253 }
254  
255 27 $offset += $bytes_read;
256 27 $bytes_sent += $bytes_read;
257 }
258  
259 8 return $bytes_sent; # Return total bytes read
260 157 }
261  
262 =head2 write_file
263  
264 await PAGI::Server::AsyncFile->write_file($loop, $path, $content);
265  
266 Write content to a file asynchronously, replacing any existing content.
267  
268 Parameters:
269  
270 =over 4
271  
272 =item * C<$loop> - IO::Async::Loop instance
273  
274 =item * C<$path> - Path to the file to write
275  
276 =item * C<$content> - Content to write
277  
278 =back
279  
280 Returns a Future that resolves to the number of bytes written.
281  
282 =cut
283  
284 5 ▶async sub write_file {
Subroutine write_file: called CC=1 SCAR=0.0
Pod documented
285 5 my ($class, $loop, $path, $content) = @_;
286  
287 5 my $function = $class->_get_function($loop);
288 5 return await $function->call(args => ['write_file', $path, $content]);
289 157 }
290  
291 =head2 append_file
292  
293 await PAGI::Server::AsyncFile->append_file($loop, $path, $content);
294  
295 Append content to a file asynchronously.
296  
297 Parameters:
298  
299 =over 4
300  
301 =item * C<$loop> - IO::Async::Loop instance
302  
303 =item * C<$path> - Path to the file
304  
305 =item * C<$content> - Content to append
306  
307 =back
308  
309 Returns a Future that resolves to the number of bytes written.
310  
311 =cut
312  
313 4 ▶async sub append_file {
Subroutine append_file: called CC=1 SCAR=0.0
Pod documented
314 4 my ($class, $loop, $path, $content) = @_;
315  
316 4 my $function = $class->_get_function($loop);
317 4 return await $function->call(args => ['append_file', $path, $content]);
318 157 }
319  
320 =head2 file_size
321  
322 my $size = await PAGI::Server::AsyncFile->file_size($loop, $path);
323  
324 Get the size of a file asynchronously.
325  
326 =cut
327  
328 1 ▶async sub file_size {
Subroutine file_size: called CC=1 SCAR=0.0
Pod documented
329 1 my ($class, $loop, $path) = @_;
330  
331 1 my $function = $class->_get_function($loop);
332 1 return await $function->call(args => ['file_size', $path]);
333 157 }
334  
335 =head2 file_exists
336  
337 my $exists = await PAGI::Server::AsyncFile->file_exists($loop, $path);
338  
339 Check if a file exists asynchronously.
340  
341 =cut
342  
343 2 ▶async sub file_exists {
Subroutine file_exists: called CC=1 SCAR=0.0
Pod documented
344 2 my ($class, $loop, $path) = @_;
345  
346 2 my $function = $class->_get_function($loop);
347 2 return await $function->call(args => ['file_exists', $path]);
348 157 }
349  
350 =head2 cleanup
351  
352 PAGI::Server::AsyncFile->cleanup($loop);
353  
354 Clean up the worker pool for a given loop. Call this during application
355 shutdown to properly terminate worker processes.
356  
357 =cut
358  
359 1 ▶sub cleanup {
Subroutine cleanup: called CC=6 SCAR=20.7
Pod documented
360 1 my ($class, $loop) = @_;
361 1 ▶ $loop //= undef;
Condition50%1/2
$loop //= undef
l!l
10
MC/DC0%0/1
$loop //= undef
$loop
Truth table50%1/2
A
A= $loop
Aresult
11
00
362  
363 1 ▶ if ($loop) {
Branch: 1 branch
BranchTrueFalseTotal
if ($loop) { } 1 0 1
364 1 ▶ my $loop_id = blessed($loop) ? "$loop" : 'default';
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($loop) ? : 1 0 1
365 1 ▶ if (my $function = delete $_function_pools{$loop_id}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $function = delete $_function_pools{$loop_id}) 1 0 1
366 1 $loop->remove($function);
367 }
368 }
369 else {
370 # Clean up all pools
371 0 for my $loop_id (keys %_function_pools) {
372 0 my $function = delete $_function_pools{$loop_id};
373 # Can't remove without loop reference, but clearing the hash helps
374 }
375 }
376 }
377  
378 =head1 CONFIGURATION
379  
380 The worker pool is configured with sensible defaults:
381  
382 =over 4
383  
384 =item * C<min_workers>: 1 - Minimum worker processes to keep alive
385  
386 =item * C<max_workers>: 4 - Maximum concurrent worker processes
387  
388 =item * C<idle_timeout>: 30 - Seconds before idle workers are shut down
389  
390 =back
391  
392 These settings balance responsiveness with resource usage. For applications
393 with heavy file I/O, you may want to adjust these values by modifying the
394 C<_get_function> method or by configuring at the application level.
395  
396 =head1 THREAD SAFETY
397  
398 Each IO::Async::Loop gets its own worker pool. Worker processes are forked
399 from the main process, so they inherit the initial state but operate
400 independently. File operations in workers do not affect the main process
401 state.
402  
403 =head1 SEE ALSO
404  
405 L<IO::Async::Function>, L<IO::Async::Loop>, L<PAGI::Server>
406  
407 =head1 AUTHOR
408  
409 PAGI Contributors
410  
411 =cut
412  
413 157 1;
« blib/lib/PAGI/Server.pm ↑ Summary blib/lib/PAGI/Server/Connection.pm »