blib/lib/PAGI/Request/MultipartStream.pm

filter: Statementstmt 97.2% 210 / 216 Branchbran 87.0% 94 / 108 Conditioncond 57.8% 33 / 57 MC/DCmcdc 25.7% 9 / 35 Subroutinesub 94.1% 32 / 34 Podpod 100% 2 / 2 totaltotal 84.0% 380 / 452 CC 77 SCAR 18.6
CC
77
Cov
88%
_pump
11.1
next
11.1
new
10.9
CRAP 6.5
« blib/lib/PAGI/Middleware/Healthcheck.pm ↑ Summary blib/lib/PAGI/Middleware/ETag.pm »
1 package PAGI::Request::MultipartStream;
2 4 $PAGI::Request::MultipartStream::VERSION = '0.002002';
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  
6 4 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 4 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 4 ▶use HTTP::MultiPartParser;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 =head1 NAME
11  
12 PAGI::Request::MultipartStream - Pull-based streaming multipart/form-data engine
13  
14 =head1 SYNOPSIS
15  
16 use PAGI::Request::MultipartStream;
17 use Future::AsyncAwait;
18  
19 # Usually obtained via $req->multipart_stream, not constructed directly:
20 my $stream = $req->multipart_stream;
21  
22 while (defined(my $part = await $stream->next)) {
23 if ($part->is_file) {
24 await $part->stream_to_file($path);
25 }
26 else {
27 my $value = await $part->value; # raw bytes; you decode
28 }
29 }
30  
31 =head1 DESCRIPTION
32  
33 A pull-based streaming parser for C<multipart/form-data> request bodies. Each
34 part of the body is exposed in turn as a L<PAGI::Request::Part> via C<next>,
35 and B<the application decides where each part goes>: you choose its sink (a
36 file, an object store, an async transform) per part, rather than accepting the
37 buffered, spool-each-upload-to-a-temp-file behaviour of C<form_params> and
38 C<upload> in L<PAGI::Request>.
39  
40 Because you own the sink, it can be fully asynchronous: C<stream_to> awaits a
41 sink that returns a Future, so a slow downstream naturally backpressures the
42 read. This is what the buffered multipart path cannot offer -- its spool to a
43 temp file is blocking.
44  
45 Internally this drives L<HTTP::MultiPartParser> on demand, bridging its
46 push-based callbacks onto an internal event queue that C<next> and the part
47 methods consume.
48  
49 B<Mutually exclusive with the buffered body methods.> An HTTP request body can
50 only be consumed once. Once you create a multipart stream you cannot also call
51 C<body>/C<text>/C<json>/C<form_params>/C<uploads>, and a stream cannot be
52 created if the body was already read; see L<PAGI::Request/multipart_stream>.
53  
54 =cut
55  
56 4 our $MAX_FILES = 1000;
57 4 our $MAX_FIELDS = 1000;
58 4 our $MAX_FIELD_SIZE = 1024 * 1024; # buffered per-field cap
59 4 our $MAX_FILE_SIZE = 100 * 1024 * 1024;
60 4 our $MAX_REQUEST_BODY = 1024 * 1024 * 1024; # defense-in-depth; server max_body_size is primary
61  
62 =head1 CONSTRUCTOR
63  
64 =head2 new
65  
66 my $stream = PAGI::Request::MultipartStream->new(
67 receive => $receive, # required: PAGI receive callback
68 boundary => $boundary, # required: multipart boundary
69 max_files => 1000, # optional limits (defaults shown)
70 max_fields => 1000,
71 max_field_size => 1024 * 1024,
72 max_file_size => 100 * 1024 * 1024,
73 max_request_body => 1024 * 1024 * 1024,
74 );
75  
76 Creates a new streaming multipart engine. Most applications do not call this
77 directly -- they obtain a ready-built stream from
78 L<PAGI::Request/multipart_stream>, which extracts the boundary from the
79 request's C<Content-Type> and passes through the same limit options.
80  
81 C<receive> and C<boundary> are required. The remaining options cap the body to
82 bound memory and resource use:
83  
84 =over 4
85  
86 =item * C<max_files> - Maximum number of file parts. Default: 1000.
87  
88 =item * C<max_fields> - Maximum number of non-file (field) parts. Default: 1000.
89  
90 =item * C<max_field_size> - Maximum size, in bytes, of any single field part.
91 Default: 1 MiB (1024 * 1024).
92  
93 =item * C<max_file_size> - Maximum size, in bytes, of any single file part.
94 Default: 100 MiB (100 * 1024 * 1024).
95  
96 =item * C<max_request_body> - Maximum total bytes read from the request body.
97 Default: 1 GiB (1024 * 1024 * 1024). This is a per-stream defence-in-depth
98 cap; the PAGI server's C<max_body_size> is the primary aggregate limit on the
99 request body.
100  
101 =back
102  
103 =cut
104  
105 21 ▶sub new {
Subroutine new: called CC=9 SCAR=23.9
Pod documented
106 21 my ($class, %args) = @_;
107 21 ▶ croak "receive is required" unless $args{receive};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"receive"} 0 21 21
108 21 ▶ croak "boundary is required" unless defined $args{boundary} && length $args{boundary};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args{"boundary"} and length $args{"boundary"} 1 20 21
Condition66%2/3
defined $args{"boundary"} and length $args{"boundary"}
!ll&&!rl&&r
0120
MC/DC50%1/2
defined $args{"boundary"} and length $args{"boundary"}
defined $args{"boundary"} length $args{"boundary"}
Truth table66%2/3
A and B
A= defined $args{"boundary"}B= length $args{"boundary"}
ABresult
0X0
100
111
109 my $self = bless {
110 receive => $args{receive},
111 boundary => $args{boundary},
112 max_files => $args{max_files} // $MAX_FILES,
113 max_fields => $args{max_fields} // $MAX_FIELDS,
114 max_field_size => $args{max_field_size} // $MAX_FIELD_SIZE,
115 max_file_size => $args{max_file_size} // $MAX_FILE_SIZE,
116 20 ▶ max_request_body => $args{max_request_body} // $MAX_REQUEST_BODY,
Condition60%9/15
$args{"max_files"} // $PAGI::Request::MultipartStream::MAX_FILES
l!l&&r!l&&!r
0200
$args{"max_fields"} // $PAGI::Request::MultipartStream::MAX_FIELDS
l!l&&r!l&&!r
1190
$args{"max_field_size"} // $PAGI::Request::MultipartStream::MAX_FIELD_SIZE
l!l&&r!l&&!r
1190
$args{"max_file_size"} // $PAGI::Request::MultipartStream::MAX_FILE_SIZE
l!l&&r!l&&!r
2180
$args{"max_request_body"} // $PAGI::Request::MultipartStream::MAX_REQUEST_BODY
l!l&&r!l&&!r
1190
MC/DC0%0/2
$args{"max_files"} // $PAGI::Request::MultipartStream::MAX_FILES
$args{"max_files"} $PAGI::Request::MultipartStream::MAX_FILES
MC/DC0%0/2
$args{"max_fields"} // $PAGI::Request::MultipartStream::MAX_FIELDS
$args{"max_fields"} $PAGI::Request::MultipartStream::MAX_FIELDS
MC/DC0%0/2
$args{"max_field_size"} // $PAGI::Request::MultipartStream::MAX_FIELD_SIZE
$args{"max_field_size"} $PAGI::Request::MultipartStream::MAX_FIELD_SIZE
MC/DC0%0/2
$args{"max_file_size"} // $PAGI::Request::MultipartStream::MAX_FILE_SIZE
$args{"max_file_size"} $PAGI::Request::MultipartStream::MAX_FILE_SIZE
MC/DC0%0/2
$args{"max_request_body"} // $PAGI::Request::MultipartStream::MAX_REQUEST_BODY
$args{"max_request_body"} $PAGI::Request::MultipartStream::MAX_REQUEST_BODY
Truth table33%1/3
A // B
A= $args{"max_files"}B= $PAGI::Request::MultipartStream::MAX_FILES
ABresult
1X1
011
000
Truth table66%2/3
A // B
A= $args{"max_fields"}B= $PAGI::Request::MultipartStream::MAX_FIELDS
ABresult
1X1
011
000
Truth table66%2/3
A // B
A= $args{"max_field_size"}B= $PAGI::Request::MultipartStream::MAX_FIELD_SIZE
ABresult
1X1
011
000
Truth table66%2/3
A // B
A= $args{"max_file_size"}B= $PAGI::Request::MultipartStream::MAX_FILE_SIZE
ABresult
1X1
011
000
Truth table66%2/3
A // B
A= $args{"max_request_body"}B= $PAGI::Request::MultipartStream::MAX_REQUEST_BODY
ABresult
1X1
011
000
117 _queue => [], # FIFO: ['part',\%meta] | ['body',$chunk]
118 _file_count => 0,
119 _field_count => 0,
120 _bytes_total => 0,
121 _cur_is_file => 0,
122 _cur_bytes => 0,
123 _cur_name => undef,
124 _current => undef, # current Part
125 _exhausted => 0,
126 _parser_finished => 0, # guard: finish() is called at most once
127 _failed => undef, # sticky failure message (poisons the stream)
128 }, $class;
129 20 $self->{_parser} = $self->_build_parser;
130 20 return $self;
131 }
132  
133 # Parse the on_header arrayref of header lines into
134 # {name,filename,content_type,encoding,headers}. is_file := defined(filename).
135 24 ▶sub _disposition {
Subroutine _disposition: called CC=4 SCAR=13.9
136 24 my ($lines) = @_;
137  
138 # $lines is an arrayref of raw header lines, e.g.
139 # 'Content-Disposition: form-data; name="x"'
140 24 my %headers;
141 24 for my $line (@$lines) {
142 35 ▶ if ($line =~ /^([^:]+):\s*(.*)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^([^:]+):\s*(.*)$/) 35 0 35
143 35 $headers{lc($1)} = $2;
144 }
145 }
146  
147 24 my $disposition = _parse_content_disposition(\%headers);
148  
149 return {
150 name => $disposition->{name},
151 filename => $disposition->{filename},
152 content_type => $headers{'content-type'} // 'text/plain',
153 24 ▶ encoding => $headers{'content-transfer-encoding'},
Condition100%2/2
$headers{"content-type"} // "text/plain"
l!l
1113
MC/DC100%1/1
$headers{"content-type"} // "text/plain"
$headers{"content-type"}
Truth table100%2/2
A
A= $headers{"content-type"}
Aresult
11
00
154 headers => \%headers,
155 };
156 }
157  
158 24 ▶sub _parse_content_disposition {
Subroutine _parse_content_disposition: called CC=5 SCAR=18.1
159 24 my ($headers) = @_;
160 24 ▶ my $cd = $headers->{'content-disposition'} // '';
Condition50%1/2
$headers->{"content-disposition"} // ""
l!l
240
MC/DC0%0/1
$headers->{"content-disposition"} // ""
$headers->{"content-disposition"}
Truth table50%1/2
A
A= $headers->{"content-disposition"}
Aresult
11
00
161  
162 24 my %result;
163  
164 # Parse name="value" pairs
165 24 ▶ while ($cd =~ /(\w+)="([^"]*)"/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cd =~ /(\w+)="([^"]*)"/g) 37 24 61
166 37 $result{$1} = $2;
167 }
168 # Also handle unquoted values
169 24 ▶ while ($cd =~ /(\w+)=([^;\s"]+)/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cd =~ /(\w+)=([^;\s"]+)/g) 0 24 24
170 0 ▶ $result{$1} //= $2;
Condition0%0/3
$result{$1} //= $2
l!l&&r!l&&!r
000
MC/DC0%0/2
$result{$1} //= $2
$result{$1} $2
Truth table0%0/3
A //= B
A= $result{$1}B= $2
ABresult
1X1
011
000
171 }
172  
173 24 return \%result;
174 }
175  
176 20 ▶sub _build_parser {
Subroutine _build_parser: called CC=1 SCAR=0.0
177 20 my ($self) = @_;
178 return HTTP::MultiPartParser->new(
179 boundary => $self->{boundary},
180 26 ▶ on_header => sub {
Subroutine __ANON__: called CC=7 SCAR=19.5
181 26 my ($headers) = @_;
182 26 ▶ return if $self->{_failed};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_failed"} 2 24 26
183 24 my $meta = _disposition($headers);
184 24 ▶ my $is_file = defined $meta->{filename} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $meta->{'filename'} ? : 13 11 24
185 24 ▶ if ($is_file) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_file) { } 13 11 24
186 $self->{_failed} = "Too many file parts (max $self->{max_files})"
187 13 ▶ if ++$self->{_file_count} > $self->{max_files};
Branch: 1 branch
BranchTrueFalseTotal
if ++$self->{"_file_count"} > $self->{"max_files"} 0 13 13
188 } else {
189 $self->{_failed} = "Too many field parts (max $self->{max_fields})"
190 11 ▶ if ++$self->{_field_count} > $self->{max_fields};
Branch: 1 branch
BranchTrueFalseTotal
if ++$self->{"_field_count"} > $self->{"max_fields"} 1 10 11
191 }
192 24 ▶ return if $self->{_failed};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_failed"} 1 23 24
193 23 $self->{_cur_is_file} = $is_file;
194 23 $self->{_cur_bytes} = 0;
195 23 $self->{_cur_name} = $meta->{name};
196 23 push @{$self->{_queue}}, ['part', $meta];
197 },
198 24 ▶ on_body => sub {
Subroutine __ANON__: called CC=6 SCAR=17.9
199 24 my ($chunk, $final) = @_;
200 24 ▶ return if $self->{_failed};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_failed"} 3 21 24
201 21 $self->{_cur_bytes} += length $chunk;
202 21 ▶ my $max = $self->{_cur_is_file} ? $self->{max_file_size} : $self->{max_field_size};
Branch: 1 branch
BranchTrueFalseTotal
$self->{'_cur_is_file'} ? : 11 10 21
203 21 ▶ if ($self->{_cur_bytes} > $max) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_cur_bytes"} > $max) 3 18 21
204 $self->{_failed} = sprintf("%s part '%s' too large (max %d bytes)",
205 3 ▶ ($self->{_cur_is_file} ? 'File' : 'Field'), ($self->{_cur_name} // ''), $max);
Branch: 1 branch
BranchTrueFalseTotal
$self->{'_cur_is_file'} ? : 2 1 3
Condition50%1/2
$self->{"_cur_name"} // ""
l!l
30
MC/DC0%0/1
$self->{"_cur_name"} // ""
$self->{"_cur_name"}
Truth table50%1/2
A
A= $self->{"_cur_name"}
Aresult
11
00
206 3 return; # stop enqueuing -- bounds the queue
207 }
208 18 push @{$self->{_queue}}, ['body', $chunk];
209 },
210 2 ▶ on_error => sub { $self->{_failed} //= "Multipart parse error: $_[0]" },
Subroutine __ANON__: called CC=2 SCAR=7.6
Condition50%1/2
$self->{"_failed"} //= "Multipart parse error: $_[0]"
l!l
02
MC/DC0%0/1
$self->{"_failed"} //= "Multipart parse error: $_[0]"
$self->{"_failed"}
Truth table50%1/2
A
A= $self->{"_failed"}
Aresult
11
00
211 20 );
212 }
213  
214 # Feed exactly one network message. Returns true if it fed data, false at exhaustion.
215 32 ▶async sub _pump {
Subroutine _pump: called CC=11 SCAR=24.1
216 32 my ($self) = @_;
217 32 ▶ return 0 if $self->{_exhausted};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_exhausted"} 7 25 32
218 25 my $msg = await $self->{receive}->();
219 25 ▶ if (!$msg || !$msg->{type} || $msg->{type} eq 'http.disconnect') {
Branch: 1 branch
BranchTrueFalseTotal
if (not $msg && $msg->{"type"} or $msg->{"type"} eq "http.disconnect") 4 21 25
Condition50%3/6
not $msg && $msg->{"type"} or $msg->{"type"} eq "http.disconnect"
l!l&&r!l&&!r
0421
$msg && $msg->{'type'}
!ll&&!rl&&r
0025
MC/DC33%1/3
not $msg && $msg->{"type"} or $msg->{"type"} eq "http.disconnect"
$msg $msg->{'type'} $msg->{"type"} eq "http.disconnect"
Truth table50%2/4
not(A && B) or C
A= $msgB= $msg->{'type'}C= $msg->{"type"} eq "http.disconnect"
ABCresult
0XX1
10X1
1111
1100
220 4 $self->{_exhausted} = 1;
221 4 ▶ $self->_finish_parser if $self->{_bytes_total} > 0; # 0 bytes => empty stream, clean EOF
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_bytes_total"} > 0 3 1 4
222 4 return 0;
223 }
224 21 ▶ if (defined $msg->{body} && length $msg->{body}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $msg->{"body"} and length $msg->{"body"}) 20 1 21
Condition66%2/3
defined $msg->{"body"} and length $msg->{"body"}
!ll&&!rl&&r
0120
MC/DC50%1/2
defined $msg->{"body"} and length $msg->{"body"}
defined $msg->{"body"} length $msg->{"body"}
Truth table66%2/3
A and B
A= defined $msg->{"body"}B= length $msg->{"body"}
ABresult
0X0
100
111
225 20 $self->{_bytes_total} += length $msg->{body};
226 20 ▶ if ($self->{_bytes_total} > $self->{max_request_body}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_bytes_total"} > $self->{"max_request_body"}) 1 19 20
227 1 $self->{_failed} = "Request body exceeded max_request_body ($self->{max_request_body} bytes)";
228 1 $self->{_exhausted} = 1;
229 1 return 0;
230 }
231 19 $self->{_parser}->parse($msg->{body}); # fires callbacks (enqueue + bookkeep)
232 }
233 20 ▶ unless ($msg->{more}) { $self->{_exhausted} = 1; $self->_finish_parser if $self->{_bytes_total} > 0; }
Branch: 2 branches
BranchTrueFalseTotal
unless ($msg->{"more"}) 13 7 20
if $self->{"_bytes_total"} > 0 12 1 13
234 20 return 1;
235 4 }
236  
237 # Finalize the parser once bytes have been fed and the stream has ended.
238 # HTTP::MultiPartParser->finish on a complete stream (closing boundary already
239 # parsed) is a clean no-op; called mid-part it signals truncation. The parser
240 # routes that end-of-stream condition through on_error (which records into the
241 # sticky _failed) rather than dying, so the eval guard is defence-in-depth in
242 # case finish ever throws. When finish is what introduces the failure we reword
243 # it to a clear "incomplete upload" message; a pre-existing failure (e.g. a
244 # size-limit hit) is preserved untouched.
245 15 ▶sub _finish_parser {
Subroutine _finish_parser: called CC=6 SCAR=18.3
246 15 my ($self) = @_;
247 15 ▶ return if $self->{_parser_finished};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_parser_finished"} 0 15 15
248 15 $self->{_parser_finished} = 1;
249 15 my $had_failure = defined $self->{_failed};
250 15 ▶ eval { $self->{_parser}->finish; 1 } or $self->{_failed} //= "Multipart parse error (finish): $@";
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->{"_parser"}->finish; 1 } } or $self->{"_failed"} //= "Multipart parse error (finish): $@" 15 0 15
Condition0%0/2
$self->{"_failed"} //= "Multipart parse error (finish): $@"
l!l
00
MC/DC0%0/1
$self->{"_failed"} //= "Multipart parse error (finish): $@"
$self->{"_failed"}
Truth table0%0/2
A
A= $self->{"_failed"}
Aresult
11
00
251 15 ▶ if (!$had_failure && defined $self->{_failed}) { # finish introduced it => truncation
Branch: 1 branch
BranchTrueFalseTotal
if (not $had_failure and defined $self->{"_failed"}) 2 13 15
Condition100%3/3
not $had_failure and defined $self->{"_failed"}
!ll&&!rl&&r
492
MC/DC100%2/2
not $had_failure and defined $self->{"_failed"}
not $had_failure defined $self->{"_failed"}
Truth table100%3/3
not(A) and B
A= not $had_failureB= defined $self->{"_failed"}
ABresult
0X0
100
111
252 2 $self->{_failed} = "Incomplete multipart upload: client disconnected or stream ended before the closing boundary";
253 }
254 15 return;
255 }
256  
257 =head1 METHODS
258  
259 =head2 next
260  
261 my $part = await $stream->next;
262  
263 Returns a Future resolving to the next L<PAGI::Request::Part>, or C<undef> when
264 the stream is exhausted (end of body).
265  
266 Advancing past a part whose body you have not fully consumed auto-drains the
267 remainder of that part first, so you can always loop on C<next> without
268 reading every part. To discard a part deliberately (and signal that intent),
269 call C<< $part->skip >>.
270  
271 Croaks if a size or count limit is breached, or if the upload is truncated
272 (see L</LIMITS AND ERRORS>).
273  
274 =cut
275  
276 27 ▶async sub next {
Subroutine next: called CC=11 SCAR=24.1
Pod documented
277 27 my ($self) = @_;
278 27 ▶ croak $self->{_failed} if $self->{_failed};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_failed"} 1 26 27
279 26 ▶ if ($self->{_current} && !$self->{_current}{_done}) { await $self->{_current}->skip; } # auto-drain
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_current"} and not $self->{"_current"}{"_done"}) 7 19 26
Condition100%3/3
$self->{"_current"} and not $self->{"_current"}{"_done"}
!ll&&!rl&&r
1817
MC/DC100%2/2
$self->{"_current"} and not $self->{"_current"}{"_done"}
$self->{"_current"} not $self->{"_current"}{"_done"}
Truth table100%3/3
A and not(B)
A= $self->{"_current"}B= not $self->{"_current"}{"_done"}
ABresult
0X0
100
111
280 26 while (1) {
281 44 ▶ croak $self->{_failed} if $self->{_failed};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_failed"} 3 41 44
282 0 ▶ shift @{$self->{_queue}} while @{$self->{_queue}} && $self->{_queue}[0][0] eq 'body'; # defensive
Branch: 1 branch
BranchTrueFalseTotal
@{$self->{"_queue"};} and $self->{"_queue"}[0][0] eq "body" and do { shift @{$$self{"_queue"};} } 0 41 41
Condition66%2/3
@{$self->{"_queue"};} and $self->{"_queue"}[0][0] eq "body"
!ll&&!rl&&r
23180
MC/DC0%0/2
@{$self->{"_queue"};} and $self->{"_queue"}[0][0] eq "body"
@{$self->{"_queue"};} $self->{"_queue"}[0][0] eq "body"
Truth table66%2/3
A and B
A= @{$self->{"_queue"};}B= $self->{"_queue"}[0][0] eq "body"
ABresult
0X0
100
111
283 41 ▶ if (@{$self->{_queue}} && $self->{_queue}[0][0] eq 'part') {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{"_queue"};} and $self->{"_queue"}[0][0] eq "part") 18 23 41
Condition66%2/3
@{$self->{"_queue"};} and $self->{"_queue"}[0][0] eq "part"
!ll&&!rl&&r
23018
MC/DC50%1/2
@{$self->{"_queue"};} and $self->{"_queue"}[0][0] eq "part"
@{$self->{"_queue"};} $self->{"_queue"}[0][0] eq "part"
Truth table66%2/3
A and B
A= @{$self->{"_queue"};}B= $self->{"_queue"}[0][0] eq "part"
ABresult
0X0
100
111
284 18 my (undef, $meta) = @{ shift @{$self->{_queue}} };
285 18 $self->{_current} = PAGI::Request::Part->new(stream => $self, meta => $meta);
286 18 return $self->{_current};
287 }
288 23 ▶ last unless await $self->_pump;
Branch: 1 branch
BranchTrueFalseTotal
unless <custom op await> 5 18 23
289 }
290 5 ▶ croak $self->{_failed} if $self->{_failed}; # truncation surfaces via _failed (set by finish)
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_failed"} 1 4 5
291 4 return undef;
292 4 }
293  
294 # Next body chunk for the current part: the chunk, or undef when the part ends.
295 28 ▶async sub _next_chunk {
Subroutine _next_chunk: called CC=7 SCAR=19.5
296 28 my ($self) = @_;
297 28 while (1) {
298 30 ▶ croak $self->{_failed} if $self->{_failed};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_failed"} 1 29 30
299 29 ▶ if (@{$self->{_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{"_queue"};}) 20 9 29
300 20 my $kind = $self->{_queue}[0][0];
301 20 ▶ if ($kind eq 'body') { my $ev = shift @{$self->{_queue}}; return $ev->[1]; }
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "body") 13 7 20
302 7 ▶ return undef if $kind eq 'part'; # next part began -> current done
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "part" 7 0 7
303 }
304 9 ▶ if (!(await $self->_pump)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (<custom op await>) 7 2 9
305 7 ▶ croak $self->{_failed} if $self->{_failed}; # truncation surfaces via _failed (set by finish)
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_failed"} 2 5 7
306 5 return undef; # clean EOF (complete body, then disconnect)
307 }
308 }
309 4 }
310  
311 package PAGI::Request::Part;
312 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
313 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
314  
315 4 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
316 4 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
317 4 ▶use Fcntl qw(O_WRONLY O_CREAT O_EXCL O_NOFOLLOW);
Subroutine BEGIN: called CC=1 SCAR=0.0
318  
319 =head1 NAME
320  
321 PAGI::Request::Part - A single part of a streaming multipart request
322  
323 =head1 DESCRIPTION
324  
325 A value object representing one part yielded by
326 L<PAGI::Request::MultipartStream>. It carries the part's metadata (name,
327 filename, headers) and provides the methods that consume the part's body: pull
328 it chunk by chunk, buffer it whole, or drain it to a sink of your choosing.
329  
330 A part's body must be consumed before the next part is fetched. Calling
331 C<< $stream->next >> while a part is only partially read drains the rest of
332 the current part automatically.
333  
334 =head1 CONSTRUCTOR
335  
336 =head2 new
337  
338 my $part = PAGI::Request::Part->new(stream => $stream, meta => \%meta);
339  
340 Constructs a part bound to its owning stream. Parts are normally created by
341 L<PAGI::Request::MultipartStream/next>, not by application code.
342  
343 =head1 METHODS
344  
345 =head2 name
346  
347 my $name = $part->name;
348  
349 The part's form field name, taken from its C<Content-Disposition> header.
350  
351 =head2 filename
352  
353 my $filename = $part->filename;
354  
355 The part's filename from C<Content-Disposition>, or C<undef> for non-file
356 (field) parts.
357  
358 =head2 content_type
359  
360 my $type = $part->content_type;
361  
362 The part's C<Content-Type> header. Defaults to C<text/plain> if the part sent
363 no C<Content-Type>.
364  
365 =head2 encoding
366  
367 my $encoding = $part->encoding;
368  
369 The part's C<Content-Transfer-Encoding> header, or C<undef> if not present.
370  
371 =head2 headers
372  
373 my $headers = $part->headers;
374  
375 A hashref of all the part's headers, keyed by lower-cased header name.
376  
377 =head2 is_file
378  
379 if ($part->is_file) { ... }
380  
381 True if the part has a filename (i.e. is a file upload), false otherwise.
382  
383 =head2 type
384  
385 my $type = $part->type; # 'file' or 'field'
386  
387 Returns the string C<'file'> for file parts and C<'field'> for non-file parts.
388  
389 =head2 next_chunk
390  
391 my $chunk = await $part->next_chunk;
392  
393 Returns this part's next body chunk as raw bytes, or C<undef> once the part's
394 body is exhausted. This is the low-level primitive; C<value>, C<stream_to>,
395 and C<stream_to_file> are built on it.
396  
397 =head2 value
398  
399 my $bytes = await $part->value;
400  
401 Buffers and returns the part's entire body as B<raw bytes> -- no decoding is
402 applied, so a text field encoded as UTF-8 (or any other charset) must be
403 decoded by the caller. Intended for small field parts; the buffered size is
404 bounded by the relevant per-part size limit (C<max_field_size> for fields,
405 C<max_file_size> for files), which croaks if exceeded.
406  
407 =head2 stream_to
408  
409 my $count = await $part->stream_to($cb);
410 my $count = await $part->stream_to(async sub ($chunk) { await $sink->write($chunk) });
411  
412 Drains the rest of the part to a sink callback, returning the number of bytes
413 processed. The callback is invoked with each chunk of raw bytes and may be
414 asynchronous: if it returns a Future, C<stream_to> awaits it before reading
415 the next chunk, giving the sink natural backpressure over the network read.
416  
417 If the sink callback throws, the error poisons the stream -- a later
418 C<< $stream->next >> will croak -- and the failed part is B<not> auto-drained,
419 since the application has signalled it is aborting. The exception is re-thrown
420 to the caller.
421  
422 =head2 stream_to_file
423  
424 my $count = await $part->stream_to_file($path);
425  
426 Writes the part's body to a B<new> file at C<$path>, returning the number of
427 bytes written. The file is opened with C<O_CREAT|O_EXCL|O_NOFOLLOW>: the call
428 B<refuses to overwrite an existing path or to follow a symlink>, croaking
429 instead. The result of C<close> is checked. On any error -- a write failure, a
430 limit breach, a truncated upload, or a failed C<close> -- the partially
431 written file is unlinked before the method croaks.
432  
433 =head2 skip
434  
435 await $part->skip;
436  
437 Drains and discards any remaining body of this part. Use this to deliberately
438 ignore a part; C<< $stream->next >> would otherwise drain it for you anyway.
439  
440 =head1 LIMITS AND ERRORS
441  
442 Size and count limits are enforced as bytes arrive from the network, before
443 your sink ever sees them, so an oversized part cannot stream partway into your
444 sink before being rejected. A per-part size overflow names the offending part
445 in its error message (for example, C<< File part 'avatar' too large >>).
446 Exceeding C<max_files>, C<max_fields>, or C<max_request_body> likewise causes
447 the next C<next>/consume call to croak.
448  
449 A client disconnect that truncates a part mid-stream croaks with an
450 C<"Incomplete multipart upload"> message (the closing boundary was never
451 seen). By contrast, a complete body -- or an entirely empty one -- followed by
452 a disconnect ends cleanly, with C<next> simply returning C<undef>.
453  
454 =head1 SEE ALSO
455  
456 L<PAGI::Request>, L<PAGI::Request::BodyStream>
457  
458 =cut
459  
460 18 ▶sub new { my ($c,%a)=@_; bless { stream=>$a{stream}, meta=>$a{meta}, _done=>0 }, $c }
Subroutine new: called CC=1 SCAR=0.0
461 1 ▶sub name { $_[0]{meta}{name} }
Subroutine name: called CC=1 SCAR=0.0
462 3 ▶sub filename { $_[0]{meta}{filename} }
Subroutine filename: called CC=1 SCAR=0.0
463 1 ▶sub content_type { $_[0]{meta}{content_type} }
Subroutine content_type: called CC=1 SCAR=0.0
464 0 ▶sub encoding { $_[0]{meta}{encoding} }
Subroutine encoding: not called CC=1 SCAR=6.9
465 0 ▶sub headers { $_[0]{meta}{headers} }
Subroutine headers: not called CC=1 SCAR=6.9
466 4 ▶sub is_file { defined $_[0]{meta}{filename} ? 1 : 0 }
Subroutine is_file: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0]{'meta'}{'filename'} ? : 3 1 4
467 2 ▶sub type { $_[0]->is_file ? 'file' : 'field' }
Subroutine type: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$_[0]->is_file ? : 1 1 2
468 7 ▶async sub skip { my $s=shift; 1 while defined(await $s->{stream}->_next_chunk); $s->{_done}=1; return; }
Subroutine skip: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
defined <custom op await> and do { '???' } 7 7 14
469  
470 14 ▶async sub next_chunk {
Subroutine next_chunk: called CC=3 SCAR=11.0
471 14 my ($self) = @_;
472 14 ▶ return undef if $self->{_done};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_done"} 0 14 14
473 14 my $chunk = await $self->{stream}->_next_chunk;
474 11 ▶ $self->{_done} = 1 unless defined $chunk;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $chunk 5 6 11
475 11 return $chunk;
476 4 }
477  
478 3 ▶async sub value { # buffer the whole part (small fields). RAW BYTES.
Subroutine value: called CC=2 SCAR=6.9
479 3 my ($self) = @_;
480 3 my $buf = '';
481 3 ▶ while (defined(my $c = await $self->next_chunk)) { $buf .= $c }
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $c = <custom op await>)) 3 3 6
482 3 return $buf;
483 4 }
484  
485 2 ▶async sub stream_to { # drain to a (possibly async) sink callback
Subroutine stream_to: called CC=7 SCAR=19.8
486 2 my ($self, $cb) = @_;
487 2 ▶ croak "callback is required" unless $cb;
Branch: 1 branch
BranchTrueFalseTotal
unless $cb 0 2 2
488 2 my $n = 0;
489 2 my $ok = eval {
490 2 ▶ while (defined(my $c = await $self->next_chunk)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $c = <custom op await>)) 2 1 3
491 2 my $r = $cb->($c);
492 1 ▶ await $r if ref $r && $r->can('get'); # allow an async sink (returns a Future)
Branch: 1 branch
BranchTrueFalseTotal
if ref $r and $r->can("get") 1 0 1
Condition33%1/3
ref $r and $r->can("get")
!ll&&!rl&&r
001
MC/DC0%0/2
ref $r and $r->can("get")
ref $r $r->can("get")
Truth table33%1/3
A and B
A= ref $rB= $r->can("get")
ABresult
0X0
100
111
493 1 $n += length $c;
494 }
495 1 1;
496 };
497 2 ▶ if (!$ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 1 1 2
498 1 my $err = $@;
499 # poison the stream so a later ->next croaks; do NOT auto-drain (the app aborted)
500 1 ▶ $self->{stream}{_failed} //= "sink error: $err";
Condition50%1/2
$self->{"stream"}{"_failed"} //= "sink error: $err"
l!l
01
MC/DC0%0/1
$self->{"stream"}{"_failed"} //= "sink error: $err"
$self->{"stream"}{"_failed"}
Truth table50%1/2
A
A= $self->{"stream"}{"_failed"}
Aresult
11
00
501 1 die $err;
502 }
503 1 return $n;
504 4 }
505  
506 4 ▶async sub stream_to_file {
Subroutine stream_to_file: called CC=7 SCAR=19.7
507 4 my ($self, $path) = @_;
508 4 ▶ croak "path is required" unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 0 4 4
509 4 ▶ sysopen(my $fh, $path, O_WRONLY|O_CREAT|O_EXCL|O_NOFOLLOW, 0600)
Branch: 1 branch
BranchTrueFalseTotal
sysopen my $fh, $path, 131265, 384 or croak("Cannot create ${path}: $!") 3 1 4
510 or croak "Cannot create $path: $!";
511 3 binmode $fh;
512 3 my $written = 0;
513 3 my $ok = eval {
514 3 ▶ while (defined(my $c = await $self->next_chunk)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $c = <custom op await>)) 1 1 2
515 1 ▶ print $fh $c or die "write to $path failed: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
print $fh $c or die "write to $path failed: $!\n" 1 0 1
516 1 $written += length $c;
517 }
518 1 1;
519 };
520 3 my $err = $@;
521 3 my $close_ok = close $fh;
522 3 ▶ if (!$ok) { unlink $path; croak $err; } # write/limit/disconnect error wins
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 2 1 3
523 0 ▶ unless ($close_ok) { unlink $path; croak "Cannot close $path: $!"; }
Branch: 1 branch
BranchTrueFalseTotal
unless ($close_ok) 0 1 1
524 1 return $written;
525 4 }
526  
527 4 1;
« blib/lib/PAGI/Middleware/Healthcheck.pm ↑ Summary blib/lib/PAGI/Middleware/ETag.pm »