blib/lib/Langertha/Knarr/PSGI.pm

filter: Statementstmt 97.3% 111 / 114 Branchbran 80.3% 45 / 56 Conditioncond 57.6% 15 / 26 MC/DCmcdc 33.3% 5 / 15 Subroutinesub 100% 13 / 13 Podpod 100% 1 / 1 totaltotal 84.4% 190 / 225 CC 40 SCAR 31.3
CC
40
Cov
87%
_handle_psgi
35.4
_read_body
6.1
__ANON__
3.2
CRAP 22.9
« blib/lib/Langertha/Knarr/CLI/Cmd/Check.pm ↑ Summary blib/lib/Langertha/Knarr/Handler/Passthrough.pm »
1 package Langertha::Knarr::PSGI;
2 # ABSTRACT: PSGI adapter for Langertha::Knarr (buffered, no streaming)
3 28 our $VERSION = '1.102';
4 28 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 28 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 28 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 28 ▶use Langertha::Knarr::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 28 ▶use Langertha::Knarr::PSGI::FakeReq;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10  
11 # Wraps a Langertha::Knarr instance and returns a PSGI app coderef.
12 # Streaming requests are coerced into buffered responses: the full body is
13 # assembled (open + chunks + close + done) before being returned to the
14 # PSGI server. Use the native Net::Async::HTTP::Server entrypoint
15 # (Langertha::Knarr->run) if you need real streaming.
16  
17 28 has knarr => ( is => 'ro', required => 1 );
18  
19 has _json => (
20 is => 'ro',
21 62 ▶ default => sub { JSON::MaybeXS->new( utf8 => 1, canonical => 1 ) },
Subroutine __ANON__: called CC=1 SCAR=0.0
22 28 );
23  
24 62 ▶sub to_app {
Subroutine to_app: called CC=1 SCAR=0.0
Pod documented
25 62 my ($self) = @_;
26 502 ▶ return sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
27 502 my ($env) = @_;
28 502 return $self->_handle_psgi($env);
29 62 };
30 }
31  
32 364 ▶sub _read_body {
Subroutine _read_body: called CC=6 SCAR=18.0
33 364 my ($self, $env) = @_;
34 364 ▶ my $input = $env->{'psgi.input'} or return '';
Branch: 1 branch
BranchTrueFalseTotal
my $input = $env->{"psgi.input"} or return "" 364 0 364
35 364 ▶ my $len = $env->{CONTENT_LENGTH} // 0;
Condition50%1/2
$env->{"CONTENT_LENGTH"} // 0
l!l
3640
MC/DC0%0/1
$env->{"CONTENT_LENGTH"} // 0
$env->{"CONTENT_LENGTH"}
Truth table50%1/2
A
A= $env->{"CONTENT_LENGTH"}
Aresult
11
00
36 364 ▶ return '' unless $len;
Branch: 1 branch
BranchTrueFalseTotal
unless $len 14 350 364
37 350 my $body = '';
38 350 my $read = 0;
39 350 ▶ while ( $read < $len ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($read < $len) 350 350 700
40 350 my $chunk;
41 350 my $n = $input->read( $chunk, $len - $read );
42 350 ▶ last unless $n;
Branch: 1 branch
BranchTrueFalseTotal
unless $n 0 350 350
43 350 $body .= $chunk;
44 350 $read += $n;
45 }
46 350 return $body;
47 }
48  
49 502 ▶sub _handle_psgi {
Subroutine _handle_psgi: called CC=32 SCAR=35.7
50 502 my ($self, $env) = @_;
51 502 my $sb = $self->knarr;
52 502 my $method = $env->{REQUEST_METHOD};
53 502 ▶ my $path = $env->{PATH_INFO} // '/';
Condition50%1/2
$env->{"PATH_INFO"} // "/"
l!l
5020
MC/DC0%0/1
$env->{"PATH_INFO"} // "/"
$env->{"PATH_INFO"}
Truth table50%1/2
A
A= $env->{"PATH_INFO"}
Aresult
11
00
54  
55 502 my $route = $sb->_match_route( $method, $path );
56 502 ▶ unless ( $route ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($route) 1 501 502
57 1 return [ 404, [ 'Content-Type' => 'application/json' ],
58 [ $self->_json->encode({ error => { message => "no route for $method $path" } }) ] ];
59 }
60  
61 501 my $proto = $route->{protocol};
62 501 my $action = $route->{action};
63  
64 # Same auth decision and 401 as the native server (k25), before any
65 # handler work, so a rejected streaming request never starts its stream.
66 501 my $fake_http = Langertha::Knarr::PSGI::FakeReq->new( $env );
67 501 ▶ unless ( $sb->_check_auth( $fake_http, $action ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sb->_check_auth($fake_http, $action)) 76 425 501
68 76 my ($status, $ctype, $body) = $sb->_unauthorized;
69 76 return [ $status, [ 'Content-Type' => $ctype ], [ $body ] ];
70 }
71  
72 425 ▶ if ( $action eq 'models' || $action eq 'acp_agents' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($action eq "models" or $action eq "acp_agents") 31 394 425
Condition100%3/3
$action eq "models" or $action eq "acp_agents"
l!l&&r!l&&!r
2110394
MC/DC100%2/2
$action eq "models" or $action eq "acp_agents"
$action eq "models" $action eq "acp_agents"
Truth table100%3/3
A or B
A= $action eq "models"B= $action eq "acp_agents"
ABresult
1X1
011
000
73 31 my $models = $sb->handler->list_models;
74 31 my ($status, $headers, $body) = $proto->format_models_response($models);
75 31 return [ $status, [ %$headers ], [ $body ] ];
76 }
77 394 ▶ if ( $action eq 'manifest' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($action eq "manifest") 12 382 394
78 my ($status, $body) = $sb->manifest_response(
79 scheme => $env->{'psgi.url_scheme'} // 'http',
80 host => $env->{HTTP_HOST}
81 // ( defined $env->{SERVER_NAME} ? $env->{SERVER_NAME} . ':' . ( $env->{SERVER_PORT} // 80 ) : undef ),
82 12 ▶ prefix => $env->{SCRIPT_NAME} // '',
Branch: 1 branch
BranchTrueFalseTotal
defined $env->{'SERVER_NAME'} ? : 0 0 0
Condition33%3/9
$env->{"psgi.url_scheme"} // "http"
l!l
120
$env->{"HTTP_HOST"} // (defined $env->{"SERVER_NAME"} ? $env->{"SERVER_NAME"} . ':' . ($env->{"SERVER_PORT"} // 80) : undef)
l!l&&r!l&&!r
1200
$env->{"SERVER_PORT"} // 80
l!l
00
$env->{"SCRIPT_NAME"} // ""
l!l
120
MC/DC0%0/1
$env->{"psgi.url_scheme"} // "http"
$env->{"psgi.url_scheme"}
MC/DC0%0/2
$env->{"HTTP_HOST"} // (defined $env->{"SERVER_NAME"} ? $env->{"SERVER_NAME"} . ':' . ($env->{"SERVER_PORT"} // 80) : undef)
$env->{"HTTP_HOST"} (defined $env->{"SERVER_NAME"} ? $env->{"SERVER_NAME"} . ':' . ($env->{"SERVER_PORT"} // 80) : undef)
MC/DC0%0/1
$env->{"SERVER_PORT"} // 80
$env->{"SERVER_PORT"}
MC/DC0%0/1
$env->{"SCRIPT_NAME"} // ""
$env->{"SCRIPT_NAME"}
Truth table50%1/2
A
A= $env->{"psgi.url_scheme"}
Aresult
11
00
Truth table33%1/3
A // B
A= $env->{"HTTP_HOST"}B= (defined $env->{"SERVER_NAME"} ? $env->{"SERVER_NAME"} . ':' . ($env->{"SERVER_PORT"} // 80) : undef)
ABresult
1X1
011
000
Truth table0%0/2
A
A= $env->{"SERVER_PORT"}
Aresult
11
00
Truth table50%1/2
A
A= $env->{"SCRIPT_NAME"}
Aresult
11
00
83 );
84 12 return [ $status, [ 'Content-Type' => 'application/json' ], [ $body ] ];
85 }
86 # The same table and methods as the native server (k29).
87 382 ▶ if ( my $simple = $sb->_simple_action($action) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $simple = $sb->_simple_action($action)) 38 344 382
88 38 my ($status, $headers, $body) = $sb->$simple( $proto, $self->_read_body($env) );
89 38 return [ $status, [ %$headers ], [ $body ] ];
90 }
91 344 ▶ if ( $action eq 'a2a_card' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($action eq "a2a_card") 18 326 344
92 18 my ($status, $headers, $body) = $proto->format_agent_card;
93 18 return [ $status, [ %$headers ], [ $body ] ];
94 }
95 326 ▶ if ( $action ne 'chat' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($action ne "chat") 0 326 326
96 0 return [ 500, [ 'Content-Type' => 'application/json' ],
97 [ $self->_json->encode({ error => { message => "unknown action $action" } }) ] ];
98 }
99  
100 326 my $body = $self->_read_body($env);
101 326 my $sb_req = $sb->_parse_chat_request( $proto, $fake_http, \$body );
102  
103 # Raw passthrough, decided and prepared by the same Knarr code as on the
104 # native server (k26): the client's bytes go 1:1 to the upstream and its
105 # answer comes back unchanged. A streaming answer is buffered, like every
106 # stream under this adapter. A discovered model the upstream refuses the
107 # client's key for falls through to the handler chain below, to its
108 # engine (k66).
109 326 ▶ if ( $sb->_is_raw_passthrough($sb_req) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sb->_is_raw_passthrough($sb_req)) 96 230 326
110 96 my ($http_req, $trace, $trace_from) = $sb->_raw_passthrough_request(
111 $sb_req, [ $fake_http->headers ], $body, $path );
112 # The failure as the future carries it, as the native on_fail sees it.
113 # A buffered stream still gets the stall timeout, not the total one: a
114 # long steady stream is legitimate (k35).
115 my ($resp, $err, $category) = $sb->raw_passthrough->_upstream_request_f(
116 request => $http_req, stream => $sb_req->stream ? 1 : 0 )
117 96 ▶ ->else( sub { Future->done( undef, @_[0, 1] ) } )->get;
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
$sb_req->stream ? : 42 54 96
118 96 ▶ unless ( $resp && $sb->_raw_passthrough_falls_back( $sb_req, $resp ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($resp and $sb->_raw_passthrough_falls_back($sb_req, $resp)) 92 4 96
Condition100%3/3
$resp and $sb->_raw_passthrough_falls_back($sb_req, $resp)
!ll&&!rl&&r
10824
MC/DC100%2/2
$resp and $sb->_raw_passthrough_falls_back($sb_req, $resp)
$resp $sb->_raw_passthrough_falls_back($sb_req, $resp)
Truth table100%3/3
A and B
A= $respB= $sb->_raw_passthrough_falls_back($sb_req, $resp)
ABresult
0X0
100
111
119 92 ▶ $trace = $sb->_raw_passthrough_trace( $sb_req, $trace_from ) if $trace_from;
Branch: 1 branch
BranchTrueFalseTotal
if $trace_from 16 76 92
120 92 ▶ my ($status, $ctype, $obody, $oheaders) = $resp
Branch: 1 branch
BranchTrueFalseTotal
$resp ? : 82 10 92
Condition50%1/2
$err // "unknown error"
l!l
100
MC/DC0%0/1
$err // "unknown error"
$err
Truth table50%1/2
A
A= $err
Aresult
11
00
121 ? $sb->_raw_passthrough_answer( $sb_req, $trace, $resp )
122 : $sb->_raw_passthrough_failed( $proto, $sb_req, $trace, $err // 'unknown error', $category );
123 92 ▶ return [ $status, [ 'Content-Type' => $ctype, map { @$_ } @{ $oheaders // [] } ], [ $obody ] ];
Condition100%2/2
$oheaders // []
l!l
8210
MC/DC100%1/1
$oheaders // []
$oheaders
Truth table100%2/2
A
A= $oheaders
Aresult
11
00
124 }
125 }
126  
127 234 my $session = $sb->session( $sb_req->session_id );
128 234 my $handler = $sb->handler;
129  
130 # An upstream timeout in the handler chain answers 504 in the protocol's
131 # error shape, as the native server does (k36), a model nothing serves
132 # 404 (k41). A buffered stream has sent nothing yet, so it gets the same
133 # answer, like the raw passthrough under this adapter. Any other failure
134 # dies as before.
135 234 my @answer;
136 26 ▶ my $answered = sub {
Subroutine __ANON__: called CC=3 SCAR=11.8
137 26 my ($e) = @_;
138 26 ▶ return 0 unless ref $e && eval { $e->isa('Future::Exception') };
Branch: 1 branch
BranchTrueFalseTotal
unless ref $e and eval { do { $e->isa("Future::Exception") } } 0 26 26
Condition33%1/3
ref $e and eval {
!ll&&!rl&&r
0026
MC/DC0%0/2
ref $e and eval { do { $e->isa("Future::Exception") } }
ref $e eval { do { $e->isa("Future::Exception") } }
Truth table33%1/3
A and B
A= ref $eB= eval { do { $e->isa("Future::Exception") } }
ABresult
0X0
100
111
139 26 @answer = $sb->_handler_failure_answer( $proto, $e->message, $e->category );
140 26 return scalar @answer;
141 234 };
142 # A read the upstream has not fed yet is a plain pending Future (the
143 # stream's own queue), which cannot ->get by itself: run the loop until
144 # it is ready.
145 473 ▶ my $get = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
146 473 my ($f) = @_;
147 473 ▶ $sb->loop->await($f) unless $f->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
unless $f->is_ready 71 402 473
148 473 return $f->get;
149 234 };
150  
151 234 ▶ if ( $sb_req->stream ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sb_req->stream) 117 117 234
152 # Buffered streaming: drive the stream to completion, concatenate frames.
153 117 my $out = eval {
154 117 my $stream = $get->( $handler->handle_stream_f( $session, $sb_req ) );
155 113 my $out = $proto->format_stream_open($sb_req);
156 113 ▶ while ( defined( my $delta = $get->( $stream->next_chunk_f ) ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $delta = &$get($stream->next_chunk_f))) 126 101 227
157 126 $out .= $proto->format_stream_chunk( $delta, $sb_req );
158 }
159 101 ▶ my $finish_reason = $stream->can('finish_reason') ? $stream->finish_reason : undef;
Branch: 1 branch
BranchTrueFalseTotal
$stream->can('finish_reason') ? : 101 0 101
160 101 ▶ my $tool_calls = $stream->can('tool_calls') ? $stream->tool_calls : [];
Branch: 1 branch
BranchTrueFalseTotal
$stream->can('tool_calls') ? : 101 0 101
161 101 ▶ my $usage = $stream->can('usage') ? $stream->usage : undef;
Branch: 1 branch
BranchTrueFalseTotal
$stream->can('usage') ? : 101 0 101
162 101 $out .= $proto->format_stream_close( $sb_req, $finish_reason, $tool_calls, $usage );
163 101 $out .= $proto->format_stream_done( $sb_req, $finish_reason, $tool_calls, $usage );
164 101 $out;
165 };
166 117 ▶ if ( my $e = $@ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $e = $@) 16 101 117
167 16 ▶ return [ $answer[0], [ 'Content-Type' => $answer[1] ], [ $answer[2] ] ] if $answered->($e);
Branch: 1 branch
BranchTrueFalseTotal
if &$answered($e) 16 0 16
168 0 die $e;
169 }
170 101 return [ 200, [ 'Content-Type' => $proto->stream_content_type ], [ $out ] ];
171 }
172  
173 117 my $response = eval { $get->( $handler->handle_chat_f( $session, $sb_req ) ) };
174 117 ▶ if ( my $e = $@ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $e = $@) 10 107 117
175 10 ▶ return [ $answer[0], [ 'Content-Type' => $answer[1] ], [ $answer[2] ] ] if $answered->($e);
Branch: 1 branch
BranchTrueFalseTotal
if &$answered($e) 10 0 10
176 0 die $e;
177 }
178 107 my ($status, $headers, $obody) = $proto->format_chat_response( $response, $sb_req );
179 107 return [ $status, [ %$headers ], [ $obody ] ];
180 }
181  
182 28 __PACKAGE__->meta->make_immutable;
183 28 1;
184  
185 __END__
186  
187 =pod
188  
189 =encoding UTF-8
190  
191 =head1 NAME
192  
193 Langertha::Knarr::PSGI - PSGI adapter for Langertha::Knarr (buffered, no streaming)
194  
195 =head1 VERSION
196  
197 version 1.102
198  
199 =head1 SYNOPSIS
200  
201 use Langertha::Knarr;
202 use Langertha::Knarr::PSGI;
203  
204 my $knarr = Langertha::Knarr->new( handler => $handler );
205 my $app = Langertha::Knarr::PSGI->new( knarr => $knarr )->to_app;
206 # $app is now a Plack-compatible coderef
207  
208 # Run with any PSGI server:
209 # plackup -s Starman -p 8088 app.psgi
210  
211 =head1 DESCRIPTION
212  
213 Adapter that wraps a L<Langertha::Knarr> instance and exposes it as a
214 PSGI app, so you can deploy Knarr behind any Plack server (Starman,
215 Twiggy, Gazelle, mod_perl, etc.) instead of running its native
216 L<Net::Async::HTTP::Server> loop.
217  
218 B<Streaming responses are buffered.> The PSGI streaming protocol's
219 delayed-response form does work in theory but mixes badly with
220 L<IO::Async> in the same process; for honesty's sake this adapter
221 just drives the inner stream to completion in a blocking loop and
222 returns the full assembled body. Use the native
223 L<Langertha::Knarr/run> entry point if you need real-time streaming.
224  
225 Raw passthrough works as on the native server: with a
226 C<raw_passthrough> handler and a C<router> set on the Knarr, a chat request for a
227 model the router does not configure is sent to the upstream byte for byte
228 with the client's headers (minus the proxy key, see
229 L<Langertha::Knarr/auth_token>), and the upstream's status, headers and body
230 come back unchanged (see L<Langertha::Knarr/raw_passthrough>). A streamed
231 passthrough answer is buffered like any other stream here; its
232 C<Content-Encoding> is handled as on the native server. A discovered
233 model's C<401> falls back to its engine as there, streamed or not.
234  
235 One limit is the PSGI server's: it hands over a request header the client
236 sent twice as one value joined with C<, > (one C<HTTP_*> key), so the
237 upstream gets that header once, as that joined value. The native server
238 forwards each line. The same holds for the auth headers a
239 L<Langertha::Knarr::Handler::Passthrough> in the handler chain forwards
240 (C<forward_headers>, see L<Langertha::Knarr::Request/forward_header_pairs>).
241  
242 Requests are authenticated exactly like on the native server: with
243 L<Langertha::Knarr/auth_token> set, every route except the A2A agent card
244 needs the key as C<Authorization: Bearer> or C<x-api-key>, and a missing
245 or wrong key gets the same C<401> JSON error.
246  
247 =head2 knarr
248  
249 Required. The L<Langertha::Knarr> instance to expose.
250  
251 =head2 to_app
252  
253 Returns the PSGI coderef.
254  
255 =head1 SUPPORT
256  
257 =head2 Issues
258  
259 Please report bugs and feature requests on GitHub at
260 L<https://github.com/Getty/langertha-knarr/issues>.
261  
262 =head2 IRC
263  
264 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
265  
266 =head1 CONTRIBUTING
267  
268 Contributions are welcome! Please fork the repository and submit a pull request.
269  
270 =head1 AUTHOR
271  
272 Torsten Raudssus <torsten@raudssus.de> L<https://raudssus.de/>
273  
274 =head1 COPYRIGHT AND LICENSE
275  
276 This software is copyright (c) 2026 by Torsten Raudssus.
277  
278 This is free software; you can redistribute it and/or modify it under
279 the same terms as the Perl 5 programming language system itself.
280  
281 =cut
« blib/lib/Langertha/Knarr/CLI/Cmd/Check.pm ↑ Summary blib/lib/Langertha/Knarr/Handler/Passthrough.pm »