Server.pm

filter: Statementstmt 100% 51 / 51 Branchbran 80.0% 16 / 20 Conditioncond 70.5% 12 / 17 MC/DCmcdc 27.2% 3 / 11 Subroutinesub 100% 9 / 9 Podpod 100% 3 / 3 totaltotal 84.6% 94 / 111 CC 20 SCAR 17.2
CC
20
Cov
90%
_jsonrpc_read_body
9.2
jsonrpc_dispatch_with
6.0
_jsonrpc_max_body_bytes
5.1
CRAP 5.6
« Server/Dispatcher.pm ↑ Summary Server/Error.pm »
1 package Catalyst::Plugin::JSONRPC::Server;
2 5 ▶use v5.36;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 5 ▶use Catalyst::Plugin::JSONRPC::Server::Dispatcher;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 5 our $VERSION = '0.004';
6  
7 =encoding utf8
8  
9 =head1 NAME
10  
11 Catalyst::Plugin::JSONRPC::Server - Generic JSON-RPC 2.0 server plugin for Catalyst
12  
13 =head1 SYNOPSIS
14  
15 package MyApp;
16 use Catalyst qw/+Catalyst::Plugin::JSONRPC::Server/;
17 __PACKAGE__->setup;
18  
19 sub rpc :Path('/rpc') :Args(0) {
20 my ( $self, $c ) = @_;
21 $c->jsonrpc_register( add => sub ($params) { $params->{a} + $params->{b} } );
22 $c->jsonrpc_dispatch;
23 }
24  
25 =head1 DESCRIPTION
26  
27 Adds JSON-RPC 2.0 request dispatch to a Catalyst application. The protocol
28 engine lives in L<Catalyst::Plugin::JSONRPC::Server::Dispatcher>; this module is
29 the thin Catalyst seam: it adds C<jsonrpc_register> and C<jsonrpc_dispatch> to
30 the context.
31  
32 The dispatcher used by C<jsonrpc_register>/C<jsonrpc_dispatch> is built fresh for
33 each request and cached on the context, so handlers (and anything they close
34 over, such as C<$c>) never leak into a later request. It is therefore safe to
35 register handlers inside a request action, as the SYNOPSIS does.
36  
37 =head1 CONFIGURATION
38  
39 Under the C<'Catalyst::Plugin::JSONRPC::Server'> config key:
40  
41 =over 4
42  
43 =item C<max_body_bytes>
44  
45 Maximum raw request body size the plugin will read (default 10 MiB; C<0> =
46 unlimited). A larger body is rejected with a C<-32600> "Request too large".
47  
48 =back
49  
50 The per-request dispatcher's C<max_batch> (maximum batch-array length, default
51 1000; C<0> = unlimited) is a
52 L<Catalyst::Plugin::JSONRPC::Server::Dispatcher> attribute; supply your own
53 dispatcher via
54 L<< C<jsonrpc_dispatch_with>|/"jsonrpc_dispatch_with( $dispatcher, $body =
55 undef, $empty_status = 204 )" >> to change it.
56  
57 =cut
58  
59 # Default cap on the raw request body (bytes); 0 = unlimited. Overridable per app
60 # via $c->config->{'Catalyst::Plugin::JSONRPC::Server'}{max_body_bytes}.
61 5 my $DEFAULT_MAX_BODY_BYTES = 10 * 1024 * 1024;
62  
63 # Per-request dispatcher: built fresh for each request and cached on the context
64 # object, so handlers (and anything they close over, such as $c) never leak into
65 # a later request served by the same worker. Re-registering a method name within
66 # a request is idempotent.
67 27 ▶sub _jsonrpc_dispatcher ( $c ) {
Subroutine _jsonrpc_dispatcher: called CC=2 SCAR=7.2
68 27 ▶ return $c->{'__jsonrpc_dispatcher'}
Condition66%2/3
$c->{"__jsonrpc_dispatcher"} //= "Catalyst::Plugin::JSONRPC::Server::Dispatcher"->new
l!l&&r!l&&!r
14130
MC/DC0%0/2
$c->{"__jsonrpc_dispatcher"} //= "Catalyst::Plugin::JSONRPC::Server::Dispatcher"->new
$c->{"__jsonrpc_dispatcher"} "Catalyst::Plugin::JSONRPC::Server::Dispatcher"->new
Truth table66%2/3
A //= B
A= $c->{"__jsonrpc_dispatcher"}B= "Catalyst::Plugin::JSONRPC::Server::Dispatcher"->new
ABresult
1X1
011
000
69 //= Catalyst::Plugin::JSONRPC::Server::Dispatcher->new;
70 }
71  
72 15 ▶sub jsonrpc_register ( $c, $method, $code ) {
Subroutine jsonrpc_register: called CC=1 SCAR=0.0
Pod documented
73 15 $c->_jsonrpc_dispatcher->register( $method, $code );
74 15 return $c;
75 }
76  
77 12 ▶sub jsonrpc_dispatch ( $c, $body = undef ) {
Subroutine jsonrpc_dispatch: called CC=2 SCAR=6.9
Pod documented
78 12 return $c->jsonrpc_dispatch_with( $c->_jsonrpc_dispatcher, $body );
79 }
80  
81 17 ▶sub jsonrpc_dispatch_with ( $c, $dispatcher, $body = undef, $empty_status = 204 ) {
Subroutine jsonrpc_dispatch_with: called CC=6 SCAR=17.9
Pod documented
82 17 my $res = $c->response;
83  
84 # When we read the body ourselves, an oversize body comes back as a scalar
85 # ref sentinel; reject it before parsing. A caller-supplied $body (a string)
86 # is the caller's responsibility and is not size-checked here.
87 17 ▶ my $read = $body // $c->_jsonrpc_read_body;
Condition66%2/3
$body // $c->_jsonrpc_read_body
l!l&&r!l&&!r
1070
MC/DC0%0/2
$body // $c->_jsonrpc_read_body
$body $c->_jsonrpc_read_body
Truth table66%2/3
A // B
A= $bodyB= $c->_jsonrpc_read_body
ABresult
1X1
011
000
88 17 ▶ if ( ref $read ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $read) 2 15 17
89 2 return $c->_jsonrpc_write( $dispatcher, {
90 jsonrpc => '2.0',
91 error => { code => -32600, message => 'Request too large' },
92 id => undef,
93 }, 200 );
94 }
95  
96 15 my $data = $dispatcher->dispatch($read);
97  
98 15 ▶ if ( !defined $data ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $data) 5 10 15
99 5 $res->status($empty_status);
100 5 $res->body(q{});
101 5 return undef;
102 }
103 10 return $c->_jsonrpc_write( $dispatcher, $data, 200 );
104 }
105  
106 12 ▶sub _jsonrpc_write ( $c, $dispatcher, $data, $status ) {
Subroutine _jsonrpc_write: called CC=1 SCAR=0.0
107 12 my $res = $c->response;
108 12 $res->status($status);
109 12 $res->content_type('application/json');
110 # encode_safe: a handler result that won't serialize degrades to a -32603
111 # here rather than dying (outside any try) and turning into an HTTP 500.
112 12 $res->body( $dispatcher->encode_safe($data) );
113 12 return $data;
114 }
115  
116 7 ▶sub _jsonrpc_max_body_bytes ( $c ) {
Subroutine _jsonrpc_max_body_bytes: called CC=5 SCAR=16.3
117 7 ▶ return $DEFAULT_MAX_BODY_BYTES unless $c->can('config');
Branch: 1 branch
BranchTrueFalseTotal
unless $c->can("config") 1 6 7
118 6 ▶ my $conf = $c->config or return $DEFAULT_MAX_BODY_BYTES;
Branch: 1 branch
BranchTrueFalseTotal
my $conf = $c->config or return $DEFAULT_MAX_BODY_BYTES 6 0 6
119 6 ▶ my $cfg = $conf->{'Catalyst::Plugin::JSONRPC::Server'} || {};
Condition100%2/2
$conf->{'Catalyst::Plugin::JSONRPC::Server'} || {}
l!l
33
MC/DC100%1/1
$conf->{'Catalyst::Plugin::JSONRPC::Server'} || {}
$conf->{'Catalyst::Plugin::JSONRPC::Server'}
Truth table100%2/2
A
A= $conf->{'Catalyst::Plugin::JSONRPC::Server'}
Aresult
11
00
120 6 ▶ return $cfg->{max_body_bytes} // $DEFAULT_MAX_BODY_BYTES;
Condition66%2/3
$cfg->{"max_body_bytes"} // $DEFAULT_MAX_BODY_BYTES
l!l&&r!l&&!r
330
MC/DC0%0/2
$cfg->{"max_body_bytes"} // $DEFAULT_MAX_BODY_BYTES
$cfg->{"max_body_bytes"} $DEFAULT_MAX_BODY_BYTES
Truth table66%2/3
A // B
A= $cfg->{"max_body_bytes"}B= $DEFAULT_MAX_BODY_BYTES
ABresult
1X1
011
000
121 }
122  
123 # Read the raw (undecoded) request body. Catalyst buffers it; $c->request->body
124 # is a (usually seekable) filehandle for content types it does not parse (e.g.
125 # application/json). Returns '' when there is no body, or a scalar ref sentinel
126 # when the body exceeds the configured size cap. We use the builtin binmode/seek
127 # (not method calls) so this works on both blessed IO objects and plain glob
128 # filehandles; binmode guarantees raw bytes, which the Dispatcher's utf8 codec
129 # expects.
130 7 ▶sub _jsonrpc_read_body ( $c ) {
Subroutine _jsonrpc_read_body: called CC=9 SCAR=22.2
131 7 my $body = $c->request->body;
132 7 ▶ return q{} unless defined $body;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $body 0 7 7
133 7 my $limit = $c->_jsonrpc_max_body_bytes;
134  
135 # Some configs hand back a string rather than a filehandle. The cap applies
136 # to every body we read ourselves, not just the filehandle branch, so this
137 # is size-checked too (a caller-supplied body stays the caller's problem --
138 # see jsonrpc_dispatch_with). Bodies are raw bytes by contract, so length()
139 # is the byte count.
140 7 ▶ unless ( ref $body ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $body) 2 5 7
141 2 ▶ return \'too_large' if $limit && length($body) > $limit;
Branch: 1 branch
BranchTrueFalseTotal
if $limit and length $body > $limit 1 1 2
Condition66%2/3
$limit and length $body > $limit
!ll&&!rl&&r
011
MC/DC50%1/2
$limit and length $body > $limit
$limit length $body > $limit
Truth table66%2/3
A and B
A= $limitB= length $body > $limit
ABresult
0X0
100
111
142 1 return $body;
143 }
144  
145 5 binmode $body; # raw bytes (codec does the utf8 decode)
146 5 ▶ if ($limit) {
Branch: 1 branch
BranchTrueFalseTotal
if ($limit) 5 0 5
147 5 seek $body, 0, 2; # SEEK_END: size it without slurping
148 5 my $size = tell $body;
149 5 ▶ if ( defined $size && $size > $limit ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $size and $size > $limit) 1 4 5
Condition66%2/3
defined $size and $size > $limit
!ll&&!rl&&r
041
MC/DC50%1/2
defined $size and $size > $limit
defined $size $size > $limit
Truth table66%2/3
A and B
A= defined $sizeB= $size > $limit
ABresult
0X0
100
111
150 1 seek $body, 0, 0;
151 1 return \'too_large'; # sentinel: caller emits -32600
152 }
153 }
154 4 seek $body, 0, 0; # rewind (Catalyst may have read it)
155 4 local $/ = undef; # slurp mode
156 4 my $content = <$body>;
157 4 ▶ return defined $content ? $content : q{};
Branch: 1 branch
BranchTrueFalseTotal
defined $content ? : 4 0 4
158 }
159  
160 =head1 METHODS
161  
162 =head2 jsonrpc_register( $method => $coderef )
163  
164 Register a handler for a JSON-RPC method name. The handler is invoked as
165 C<< $coderef->($params) >>, where C<$params> is the request's C<params>
166 (an arrayref, hashref, or undef). Return the result; to signal a JSON-RPC
167 error, throw a L<Catalyst::Plugin::JSONRPC::Server::Error> (or C<die> with a
168 C<< { code, message, data } >> hashref). A plain C<die> becomes a C<-32603>
169 internal error whose text is not leaked. Returns C<$c> (chainable).
170  
171 =head2 jsonrpc_dispatch( $body = undef )
172  
173 Dispatch a JSON-RPC 2.0 request. Pass the raw JSON body, or omit it to have the
174 plugin read the raw request body from C<< $c->request->body >>. Writes the HTTP
175 response (200 with the JSON envelope for a result or error, or 204 with an
176 empty body when there is nothing to send, i.e. a notification) and returns the
177 response data (hashref or arrayref) or C<undef>.
178  
179 Delegates to
180 L<< C<jsonrpc_dispatch_with>|/"jsonrpc_dispatch_with( $dispatcher, $body =
181 undef, $empty_status = 204 )" >> using the per-request dispatcher.
182  
183 =head2 jsonrpc_dispatch_with( $dispatcher, $body = undef, $empty_status = 204 )
184  
185 Like C<jsonrpc_dispatch>, but dispatches against a caller-supplied
186 L<Catalyst::Plugin::JSONRPC::Server::Dispatcher>. Use this when you want to
187 control the dispatcher yourself, e.g. to pre-register a fixed handler set once,
188 or to set a non-default C<max_batch>. (A consumer such as an MCP plugin builds a
189 fresh per-request dispatcher and dispatches it here.)
190  
191 C<$dispatcher> must be a L<Catalyst::Plugin::JSONRPC::Server::Dispatcher>
192 instance. C<$body> is the raw JSON string; when omitted the plugin reads the raw
193 request body from C<< $c->request->body >> (subject to C<max_body_bytes>).
194 C<$empty_status> is the HTTP status used when there is nothing to send (a
195 notification or all-notification batch); it defaults to C<204>, but a transport
196 that requires a different code (e.g. MCP's Streamable HTTP, which mandates
197 C<202 Accepted>) can pass it. Writes the HTTP response and returns the response
198 data (hashref or arrayref) or C<undef>. A handler result that will not serialize
199 degrades to a C<-32603> error rather than dying (see
200 L<Catalyst::Plugin::JSONRPC::Server::Dispatcher/encode_safe>).
201  
202 =head1 EXAMPLES
203  
204 A runnable example lives in F<examples/>: a small Catalyst app exposing C<echo>
205 and C<sum> over JSON-RPC, plus a core-Perl client. Start it with
206 C<plackup examples/app.psgi> and run C<perl examples/client.pl>. See
207 F<examples/README.md>.
208  
209 =head1 AUTHOR
210  
211 Mike Whitaker <mike@altrion.org>
212  
213 Built with tool assistance from Claude Code/(mostly) Opus 4.8 to accelerate
214 code generation and maximise test coverage (and reduce typing :D).
215  
216 With thanks to
217  
218 =over
219  
220 =item *
221  
222 Jesse Vincent for C</superpowers> (L<https://github.com/obra/superpowers>) and
223 the C<AGENTS.md> boilerplate
224  
225 =item *
226  
227 Curtis "Ovid" Poe for C</paad> (L<https://github.com/Ovid/paad>)
228  
229 =back
230  
231 for providing an agentic development framework that keeps code authority
232 firmly where it belongs.
233  
234 Iteratively reviewed by Finn Kempers <finn@shadow.cat> with analysis from
235 ZCode/GLM-5.2.
236  
237 =head1 LICENSE
238  
239 This library is free software; you can redistribute it and/or modify it
240 under the terms of the Artistic License, as distributed with Perl.
241  
242 =cut
243  
244 5 1;
« Server/Dispatcher.pm ↑ Summary Server/Error.pm »