Server/Dispatcher.pm

filter: Statementstmt 98.9% 91 / 92 Branchbran 93.1% 41 / 44 Conditioncond 75.0% 33 / 44 MC/DCmcdc 55.0% 11 / 20 Subroutinesub 100% 27 / 27 Podpod 100% 4 / 4 totaltotal 89.6% 207 / 231 CC 39 SCAR 20.4
CC
39
Cov
92%
_handle_one
18.0
_normalize_error
8.5
dispatch
7.0
CRAP 7.7
↑ Summary Server.pm »
1 package Catalyst::Plugin::JSONRPC::Server::Dispatcher;
2 8 ▶use v5.36;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 8 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 8 ▶use JSON::MaybeXS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
5 8 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 8 ▶use Carp qw/croak/;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 8 ▶use Scalar::Util qw/blessed/;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 8 ▶use Catalyst::Plugin::JSONRPC::Server::Error;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 8 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 8 our $VERSION = '0.003';
12  
13 =encoding utf8
14  
15 =head1 NAME
16  
17 Catalyst::Plugin::JSONRPC::Server::Dispatcher - pure JSON-RPC 2.0 protocol engine
18  
19 =head1 DESCRIPTION
20  
21 The Catalyst-free engine behind L<Catalyst::Plugin::JSONRPC::Server>: it parses
22 and validates JSON-RPC 2.0 envelopes (single and batch), routes to registered
23 handlers, and produces spec-compliant result/error responses. It has no
24 knowledge of Catalyst or of any application domain.
25  
26 =cut
27  
28 22 ▶has _handlers => ( is => 'ro', default => sub { {} } );
Subroutine __ANON__: called CC=1 SCAR=0.0
29 has _json => (
30 is => 'lazy',
31 # allow_nonref is REQUIRED: a top-level JSON scalar (e.g. '"x"' or '1') is
32 # valid JSON per RFC 8259, and must decode so dispatch() can reject it as a
33 # non-object with -32600 (Invalid Request). Without it, backends that
34 # default allow_nonref off (JSON::XS, older JSON::PP/Cpanel::JSON::XS) throw
35 # on decode, misreporting -32700 (Parse error). Seen as a CPAN Testers
36 # failure of t/dispatcher-errors.t "non-object request is invalid".
37 builder =>
38 8 ▶ sub { JSON::MaybeXS->new( utf8 => 1, canonical => 1, allow_nonref => 1 ) },
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine _build__json: called CC=1 SCAR=0.0
39 8 );
40  
41 # Maximum number of elements accepted in a batch array; 0 = unlimited. A finite
42 # default caps the trivial amplification of a huge batch in one small body,
43 # while staying generous enough for any realistic client.
44 8 has max_batch => ( is => 'ro', default => 1000 );
45  
46 33 ▶sub register ( $self, $method, $code ) {
Subroutine register: called CC=5 SCAR=16.6
Pod documented
47 33 ▶ croak "JSON-RPC method must be a non-empty string"
Branch: 1 branch
BranchTrueFalseTotal
if not defined $method or ref $method or not length $method 1 32 33
Condition50%3/6
not defined $method or ref $method or not length $method
l!l&&r!l&&!r
0132
not defined $method or ref $method
l!l&&r!l&&!r
0033
MC/DC33%1/3
not defined $method or ref $method or not length $method
not defined $method ref $method not length $method
Truth table50%2/4
not(A) or B or not(C)
A= not defined $methodB= ref $methodC= not length $method
ABCresult
1XX1
01X1
0011
0000
48 if !defined $method || ref $method || !length $method;
49 32 ▶ croak "JSON-RPC handler must be a CODE ref"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $code eq "CODE" 1 31 32
50 unless ref $code eq 'CODE';
51 31 $self->_handlers->{$method} = $code;
52 31 return $self;
53 }
54  
55 2 ▶sub encode ( $self, $data ) {
Subroutine encode: called CC=1 SCAR=0.0
Pod documented
56 2 return $self->_json->encode($data);
57 }
58  
59 # Like encode(), but never dies on a non-serializable value. A handler that
60 # returns something the JSON codec can't encode (a blessed object without
61 # TO_JSON, a coderef, a cyclic structure) would otherwise die here, outside the
62 # per-handler try/catch, and 500 the whole request/batch. Instead, salvage: any
63 # response element that won't encode is replaced by a -32603 (its id preserved),
64 # so one bad result can't take down the others.
65 14 ▶sub encode_safe ( $self, $data ) {
Subroutine encode_safe: called CC=3 SCAR=11.0
Pod documented
66 14 ▶ my $text = try { $self->_json->encode($data) } catch { undef };
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
67 14 ▶ return $text if defined $text;
Branch: 1 branch
BranchTrueFalseTotal
if defined $text 11 3 14
68 my $safe = ref $data eq 'ARRAY'
69 3 ▶ ? [ map { $self->_encodable_or_error($_) } @$data ]
Branch: 1 branch
BranchTrueFalseTotal
ref $data eq 'ARRAY' ? : 1 2 3
70 : $self->_encodable_or_error($data);
71 3 return $self->_json->encode($safe);
72 }
73  
74 4 ▶sub _encodable_or_error ( $self, $resp ) {
Subroutine _encodable_or_error: called CC=3 SCAR=11.0
75 4 ▶ return $resp if try { $self->_json->encode($resp); 1 } catch { 0 };
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
if &try(sub { $self->_json->encode($resp); 1; } , &catch(sub { 0; } )) 1 3 4
76 3 ▶ my $id = ref $resp eq 'HASH' ? $resp->{id} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $resp eq 'HASH' ? : 3 0 3
77 3 return { jsonrpc => '2.0',
78 error => { code => -32603, message => 'Internal error' }, id => $id };
79 }
80  
81 # Returns: hashref (single), arrayref (batch), or undef (nothing to send).
82 40 ▶sub dispatch ( $self, $json_text ) {
Subroutine dispatch: called CC=7 SCAR=19.5
Pod documented
83 40 my $decoded;
84 40 ▶ my $parsed = try { $decoded = $self->_json->decode($json_text); 1 }
Subroutine __ANON__: called CC=1 SCAR=0.0
85 40 ▶ catch { 0 };
Subroutine __ANON__: called CC=1 SCAR=0.0
86 40 ▶ return $self->_error( undef, -32700, 'Parse error' ) unless $parsed;
Branch: 1 branch
BranchTrueFalseTotal
unless $parsed 1 39 40
87  
88 39 ▶ if ( ref $decoded eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $decoded eq "ARRAY") 7 32 39
89 7 ▶ return $self->_error( undef, -32600, 'Invalid Request' )
Branch: 1 branch
BranchTrueFalseTotal
unless @$decoded 1 6 7
90 unless @$decoded;
91 6 ▶ return $self->_error( undef, -32600, 'Batch too large' )
Branch: 1 branch
BranchTrueFalseTotal
if $self->max_batch and @$decoded > $self->max_batch 1 5 6
Condition66%2/3
$self->max_batch and @$decoded > $self->max_batch
!ll&&!rl&&r
051
MC/DC50%1/2
$self->max_batch and @$decoded > $self->max_batch
$self->max_batch @$decoded > $self->max_batch
Truth table66%2/3
A and B
A= $self->max_batchB= @$decoded > $self->max_batch
ABresult
0X0
100
111
92 if $self->max_batch && @$decoded > $self->max_batch;
93 5 my @out = grep { defined } map { $self->_handle_one($_) } @$decoded;
94 5 ▶ return @out ? \@out : undef;
Branch: 1 branch
BranchTrueFalseTotal
@out ? : 4 1 5
95 }
96  
97 32 return $self->_handle_one($decoded);
98 }
99  
100 # One already-decoded request element -> response hashref or undef (notification)
101 43 ▶sub _handle_one ( $self, $req ) {
Subroutine _handle_one: called CC=18 SCAR=28.9
102 43 ▶ return $self->_error( undef, -32600, 'Invalid Request' )
Branch: 1 branch
BranchTrueFalseTotal
unless ref $req eq "HASH" 1 42 43
103 unless ref $req eq 'HASH';
104  
105 42 my $is_note = !exists $req->{id};
106 42 my $id = $req->{id}; # undef for notifications; may be a JSON null
107  
108 # Envelope validation. `id`, if present, must be a scalar (String/Number/
109 # Null): a structured id is malformed. `params`, if present, must be a
110 # structured value OR an explicit null (which we treat as "no params",
111 # passing undef to the handler).
112 my $valid =
113 defined $req->{jsonrpc} && $req->{jsonrpc} eq '2.0'
114 && defined $req->{method} && !ref $req->{method}
115 && ( $is_note || !ref $id )
116 && ( !exists $req->{params}
117 || !defined $req->{params}
118 || ref $req->{params} eq 'ARRAY'
119 42 ▶ || ref $req->{params} eq 'HASH' );
Condition92%25/27
defined $req->{'jsonrpc'} && $req->{'jsonrpc'} eq '2.0' && defined $req->{'method'} && !ref($req->{'method'}) && ($is_note || !ref($id)) && (!(exists $req->{'params'} && defined $req->{'params'}) || ref $req->{'params'} eq 'ARRAY' || ref $req->{'params'} eq 'HASH')
!ll&&!rl&&r
4137
defined $req->{"jsonrpc"} and $req->{"jsonrpc"} eq "2.0" and defined $req->{"method"} and not ref $req->{"method"} and $is_note || !ref($id)
!ll&&!rl&&r
3138
defined $req->{"jsonrpc"} and $req->{"jsonrpc"} eq "2.0" and defined $req->{"method"} and not ref $req->{"method"}
!ll&&!rl&&r
3039
defined $req->{"jsonrpc"} and $req->{"jsonrpc"} eq "2.0" and defined $req->{"method"}
!ll&&!rl&&r
3039
defined $req->{"jsonrpc"} and $req->{"jsonrpc"} eq "2.0"
!ll&&!rl&&r
2139
$is_note or not ref $id
l!l&&r!l&&!r
12261
not exists $req->{"params"} && defined $req->{"params"} or ref $req->{"params"} eq "ARRAY" or ref $req->{"params"} eq "HASH"
l!l&&r!l&&!r
3521
not exists $req->{"params"} && defined $req->{"params"} or ref $req->{"params"} eq "ARRAY"
l!l&&r!l&&!r
17183
exists $req->{'params'} && defined $req->{'params'}
!ll&&!rl&&r
16121
MC/DC80%8/10
defined $req->{'jsonrpc'} && $req->{'jsonrpc'} eq '2.0' && defined $req->{'method'} && !ref($req->{'method'}) && ($is_note || !ref($id)) && (!(exists $req->{'params'} && defined $req->{'params'}) || ref $req->{'params'} eq 'ARRAY' || ref $req->{'params'} eq 'HASH')
defined $req->{"jsonrpc"} $req->{"jsonrpc"} eq "2.0" defined $req->{"method"} not ref $req->{"method"} $is_note not ref $id exists $req->{'params'} defined $req->{'params'} ref $req->{"params"} eq "ARRAY" ref $req->{"params"} eq "HASH"
Truth table66%10/15
A and B and C and not(D) and E or not(F) && not(G && H) or I or J
A= defined $req->{"jsonrpc"}B= $req->{"jsonrpc"} eq "2.0"C= defined $req->{"method"}D= not ref $req->{"method"}E= $is_noteF= not ref $idG= exists $req->{'params'}H= defined $req->{'params'}I= ref $req->{"params"} eq "ARRAY"J= ref $req->{"params"} eq "HASH"
ABCDEFGHIJresult
0XXXXXXXXX0
10XXXXXXXX0
110XXXXXXX0
1110XXXXXX0
111100XXXX0
11111X11000
11110111000
11111X0XXX1
11111X10XX1
11111X111X1
11111X11011
1111010XXX1
11110110XX1
111101111X1
11110111011
120 42 ▶ unless ($valid) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($valid) 5 37 42
121 # A structurally-invalid element is NOT a notification even when it has
122 # no id, so it still gets a -32600 (per the JSON-RPC 2.0 examples). The
123 # reply id is the request id when that is a usable scalar, else null (a
124 # structured or absent id can't be echoed).
125 5 ▶ return $self->_error( ( ref $id ? undef : $id ), -32600, 'Invalid Request' );
Branch: 1 branch
BranchTrueFalseTotal
ref $id ? : 1 4 5
126 }
127  
128 37 my $handler = $self->_handlers->{ $req->{method} };
129 37 ▶ unless ($handler) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($handler) 6 31 37
130 6 ▶ return undef if $is_note;
Branch: 1 branch
BranchTrueFalseTotal
if $is_note 1 5 6
131 5 return $self->_error( $id, -32601, 'Method not found' );
132 }
133  
134 31 my ( $result, $err );
135 31 ▶ try { $result = $handler->( $req->{params} ) }
Subroutine __ANON__: called CC=1 SCAR=0.0
136 31 ▶ catch { $err = $_ };
Subroutine __ANON__: called CC=1 SCAR=0.0
137  
138 31 ▶ if ( defined $err ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $err) 3 28 31
139 3 ▶ return undef if $is_note;
Branch: 1 branch
BranchTrueFalseTotal
if $is_note 1 2 3
140 2 my ( $code, $message, $data ) = $self->_normalize_error($err);
141 2 return $self->_error( $id, $code, $message, $data );
142 }
143  
144 28 ▶ return undef if $is_note;
Branch: 1 branch
BranchTrueFalseTotal
if $is_note 10 18 28
145 18 return { jsonrpc => '2.0', result => $result, id => $id };
146 }
147  
148 16 ▶sub _error ( $self, $id, $code, $message, $data = undef ) {
Subroutine _error: called CC=3 SCAR=11.1
149 16 my %err = ( code => $code, message => $message );
150 16 ▶ $err{data} = $data if defined $data;
Branch: 1 branch
BranchTrueFalseTotal
if defined $data 0 16 16
151 16 return { jsonrpc => '2.0', error => \%err, id => $id };
152 }
153  
154 # Map a thrown value to (code, message, data). A plain die, or any unrecognised
155 # blessed object, becomes -32603 and the original text is NOT leaked to the
156 # client (only a typed ::Error or a { code, ... } hashref sets a specific code).
157 2 ▶sub _normalize_error ( $self, $err ) {
Subroutine _normalize_error: called CC=6 SCAR=21.4
158 2 ▶ if ( blessed $err && $err->isa('Catalyst::Plugin::JSONRPC::Server::Error') ) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($err) and $err->isa("Catalyst::Plugin::JSONRPC::Server::Error")) 1 1 2
Condition66%2/3
builtin::blessed($err) and $err->isa("Catalyst::Plugin::JSONRPC::Server::Error")
!ll&&!rl&&r
101
MC/DC50%1/2
builtin::blessed($err) and $err->isa("Catalyst::Plugin::JSONRPC::Server::Error")
builtin::blessed($err) $err->isa("Catalyst::Plugin::JSONRPC::Server::Error")
Truth table66%2/3
A and B
A= builtin::blessed($err)B= $err->isa("Catalyst::Plugin::JSONRPC::Server::Error")
ABresult
0X0
100
111
159 1 return ( $err->code, $err->message, $err->data );
160 }
161 1 ▶ if ( ref $err eq 'HASH' && defined $err->{code} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $err eq "HASH" and defined $err->{"code"}) 0 1 1
Condition33%1/3
ref $err eq "HASH" and defined $err->{"code"}
!ll&&!rl&&r
100
MC/DC0%0/2
ref $err eq "HASH" and defined $err->{"code"}
ref $err eq "HASH" defined $err->{"code"}
Truth table33%1/3
A and B
A= ref $err eq "HASH"B= defined $err->{"code"}
ABresult
0X0
100
111
162 0 ▶ return ( $err->{code}, $err->{message} // 'Error', $err->{data} );
Condition0%0/2
$err->{"message"} // "Error"
l!l
00
MC/DC0%0/1
$err->{"message"} // "Error"
$err->{"message"}
Truth table0%0/2
A
A= $err->{"message"}
Aresult
11
00
163 }
164 1 return ( -32603, 'Internal error', undef );
165 }
166  
167 =head1 METHODS
168  
169 =head2 register( $method => $coderef )
170  
171 Register a handler for a JSON-RPC method name (a non-empty string). The handler
172 is invoked as C<< $coderef->($params) >>. Return the result; to signal a
173 JSON-RPC error throw a L<Catalyst::Plugin::JSONRPC::Server::Error> (or C<die>
174 with a C<< { code, message, data } >> hashref). A plain C<die>, or any
175 unrecognised exception, becomes C<-32603> and its text is not leaked. Croaks on
176 a bad method name or non-coderef handler. Returns the dispatcher (chainable).
177  
178 =head2 dispatch( $json_text )
179  
180 Parse and dispatch a JSON-RPC 2.0 request (a single object or a batch array).
181 Returns a response hashref for a single call, an arrayref for a batch, or
182 C<undef> when there is nothing to send (a lone notification or an
183 all-notification batch). Never dies: malformed JSON yields a C<-32700>
184 parse-error response.
185  
186 =head2 encode( $data )
187  
188 Encode a response data structure to canonical UTF-8 JSON text. Dies if C<$data>
189 contains a value the JSON codec cannot serialize; prefer
190 L<< C<encode_safe>|/"encode_safe( $data )" >> for
191 untrusted handler output.
192  
193 =head2 encode_safe( $data )
194  
195 Like L<< C<encode>|/"encode( $data )" >>, but never dies: any response element
196 that will not serialize
197 (a blessed object without C<TO_JSON>, a coderef, a cyclic structure) is replaced
198 by a C<-32603> "Internal error" (its id preserved), so one bad handler result
199 cannot 500 the whole request or corrupt a batch.
200  
201 =head1 ATTRIBUTES
202  
203 =head2 max_batch
204  
205 Maximum number of elements accepted in a batch array (default 1000; C<0> =
206 unlimited). A batch beyond this is rejected with a single C<-32600> "Batch too
207 large".
208  
209 =cut
210  
211 8 1;
↑ Summary Server.pm »