blib/lib/Langertha/Knarr/PSGI.pm

filter: Statementstmt 18.7% 26 / 139 Branchbran 0.0% 0 / 66 Conditioncond 0.0% 0 / 39 MC/DCmcdc 0.0% 0 / 22 Subroutinesub 38.8% 7 / 18 Podpod 100% 1 / 1 totaltotal 11.9% 34 / 285 CC 51 SCAR 61.1
CC
51
Cov
11%
_handle_action
930.0
_handle_psgi
182.0
_slurp_body
42.0
CRAP 449.9
« blib/lib/Langertha/Knarr/CLI/Cmd/Start.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 1 our $VERSION = '1.103';
4 1 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use Log::Any qw( $log );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use Scalar::Util qw( blessed );
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use Langertha::Knarr::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use Langertha::Knarr::PSGI::FakeReq;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12  
13 # Wraps a Langertha::Knarr instance and returns a PSGI app coderef.
14 # Streaming requests are coerced into buffered responses: the full body is
15 # assembled (open + chunks + close + done) before being returned to the
16 # PSGI server. Use the native Net::Async::HTTP::Server entrypoint
17 # (Langertha::Knarr->run) if you need real streaming.
18  
19 1 has knarr => ( is => 'ro', required => 1 );
20  
21 has _json => (
22 is => 'ro',
23 0 ▶ default => sub { JSON::MaybeXS->new( utf8 => 1, canonical => 1 ) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
24 1 );
25  
26 0 ▶sub to_app {
Subroutine to_app: not called CC=1 SCAR=6.9
Pod documented
27 0 my ($self) = @_;
28 0 ▶ return sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
29 0 my ($env) = @_;
30 0 return $self->_handle_psgi($env);
31 0 };
32 }
33  
34 # The body is read once and kept in the environment: an error answer may
35 # need it (_error_body) before the action reads it.
36 0 ▶sub _read_body {
Subroutine _read_body: not called CC=2 SCAR=17.9
37 0 my ($self, $env) = @_;
38 0 ▶ return $env->{'knarr.body'} //= $self->_slurp_body($env);
Condition0%0/3
$env->{"knarr.body"} //= $self->_slurp_body($env)
l!l&&r!l&&!r
000
MC/DC0%0/2
$env->{"knarr.body"} //= $self->_slurp_body($env)
$env->{"knarr.body"} $self->_slurp_body($env)
Truth table0%0/3
A //= B
A= $env->{"knarr.body"}B= $self->_slurp_body($env)
ABresult
1X1
011
000
39 }
40  
41 0 ▶sub _slurp_body {
Subroutine _slurp_body: not called CC=6 SCAR=37.4
42 0 my ($self, $env) = @_;
43 0 ▶ my $input = $env->{'psgi.input'} or return '';
Branch: 1 branch
BranchTrueFalseTotal
my $input = $env->{"psgi.input"} or return "" 0 0 0
44 0 ▶ my $len = $env->{CONTENT_LENGTH} // 0;
Condition0%0/2
$env->{"CONTENT_LENGTH"} // 0
l!l
00
MC/DC0%0/1
$env->{"CONTENT_LENGTH"} // 0
$env->{"CONTENT_LENGTH"}
Truth table0%0/2
A
A= $env->{"CONTENT_LENGTH"}
Aresult
11
00
45 0 ▶ return '' unless $len;
Branch: 1 branch
BranchTrueFalseTotal
unless $len 0 0 0
46 0 my $body = '';
47 0 my $read = 0;
48 0 ▶ while ( $read < $len ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($read < $len) 0 0 0
49 0 my $chunk;
50 0 my $n = $input->read( $chunk, $len - $read );
51 0 ▶ last unless $n;
Branch: 1 branch
BranchTrueFalseTotal
unless $n 0 0 0
52 0 $body .= $chunk;
53 0 $read += $n;
54 }
55 0 return $body;
56 }
57  
58 # The request body for an error answer, read only for a protocol that
59 # addresses its errors with it (A2A's JSON-RPC id, k80); undef for any other.
60 0 ▶sub _error_body {
Subroutine _error_body: not called CC=3 SCAR=24.8
61 0 my ($self, $env, $proto) = @_;
62 0 ▶ return unless $proto && $proto->error_uses_body;
Branch: 1 branch
BranchTrueFalseTotal
unless $proto and $proto->error_uses_body 0 0 0
Condition0%0/3
$proto and $proto->error_uses_body
!ll&&!rl&&r
000
MC/DC0%0/2
$proto and $proto->error_uses_body
$proto $proto->error_uses_body
Truth table0%0/3
A and B
A= $protoB= $proto->error_uses_body
ABresult
0X0
100
111
63 0 return $self->_read_body($env);
64 }
65  
66 0 ▶sub _handle_psgi {
Subroutine _handle_psgi: not called CC=13 SCAR=52.0
67 0 my ($self, $env) = @_;
68 0 my $sb = $self->knarr;
69 0 my $method = $env->{REQUEST_METHOD};
70 0 ▶ my $path = $env->{PATH_INFO} // '/';
Condition0%0/2
$env->{"PATH_INFO"} // "/"
l!l
00
MC/DC0%0/1
$env->{"PATH_INFO"} // "/"
$env->{"PATH_INFO"}
Truth table0%0/2
A
A= $env->{"PATH_INFO"}
Aresult
11
00
71  
72 0 my $route = $sb->_match_route( $method, $path );
73 0 ▶ unless ( $route ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($route) 0 0 0
74 0 return [ 404, [ 'Content-Type' => 'application/json' ],
75 [ $self->_json->encode({ error => { message => "no route for $method $path" } }) ] ];
76 }
77  
78 0 my $proto = $route->{protocol};
79 0 my $action = $route->{action};
80 0 my $fake_http = Langertha::Knarr::PSGI::FakeReq->new( $env );
81  
82 # The admin routes, answered by the same admin as on the native server
83 # (k75). The body is read only once the key was checked and its
84 # Content-Length is within the limit; a prefork server gets 501, as each
85 # of its processes would hold a setup of its own.
86 0 ▶ if ( $route->{admin} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($route->{"admin"}) 0 0 0
87 my ($status, $ctype, $body, $headers) = $sb->admin->handle(
88 knarr => $sb,
89 action => $action,
90 request => $fake_http,
91 content_length => $env->{CONTENT_LENGTH} // 0,
92 0 ▶ body => sub { $self->_read_body($env) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
93 peer => $env->{REMOTE_ADDR},
94 0 ▶ multiprocess => $env->{'psgi.multiprocess'} ? 1 : 0,
Branch: 1 branch
BranchTrueFalseTotal
$env->{'psgi.multiprocess'} ? : 0 0 0
Condition0%0/2
$env->{"CONTENT_LENGTH"} // 0
l!l
00
MC/DC0%0/1
$env->{"CONTENT_LENGTH"} // 0
$env->{"CONTENT_LENGTH"}
Truth table0%0/2
A
A= $env->{"CONTENT_LENGTH"}
Aresult
11
00
95 );
96 0 ▶ return [ $status, [ 'Content-Type' => $ctype, map { @$_ } @{ $headers // [] } ], [ $body ] ];
Condition0%0/2
$headers // []
l!l
00
MC/DC0%0/1
$headers // []
$headers
Truth table0%0/2
A
A= $headers
Aresult
11
00
97 }
98  
99 # Same identify decision and 401/503 as the native server (k25, k82), in
100 # the route's protocol's error shape (k78), before any handler work and
101 # before the body is parsed, so a rejected streaming request never starts
102 # its stream. The check may block here.
103 0 my $identified = $sb->_identify( $fake_http, $action );
104 0 ▶ if ( my ($status, $ctype, $body) = $sb->_identify_refusal( $proto, $identified, $self->_error_body( $env, $proto ) ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = $sb->_identify_refusal($proto, $identified, $self->_error_body($env, $proto))) 0 0 0
105 0 return [ $status, [ 'Content-Type' => $ctype ], [ $body ] ];
106 }
107 0 ▶ my $identity = $identified->{identity} // {};
Condition0%0/2
$identified->{"identity"} // {}
l!l
00
MC/DC0%0/1
$identified->{"identity"} // {}
$identified->{"identity"}
Truth table0%0/2
A
A= $identified->{"identity"}
Aresult
11
00
108  
109 # No setup delivered yet (remote_config): 503, as on the native server (k75).
110 0 ▶ if ( my ($status, $ctype, $body) = $sb->_not_configured_answer( $proto, $self->_error_body( $env, $proto ) ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = $sb->_not_configured_answer($proto, $self->_error_body($env, $proto))) 0 0 0
111 0 return [ $status, [ 'Content-Type' => $ctype ], [ $body ] ];
112 }
113  
114 # Whatever fails from here is answered like the native server answers
115 # it, in the protocol's error shape: a handler failure with the status
116 # of its category (504 for an upstream timeout, k36; 404 for a model
117 # nothing serves, k41), anything else 500 (k78). A stream is buffered, so
118 # nothing has gone out yet when its handler fails, mid-stream included.
119 0 my ( $res, $sb_req, $raw_body );
120 0 ▶ return $res if eval { $res = $self->_handle_action( $env, $route, $fake_http, \$sb_req, \$raw_body, $identity ); 1 };
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { $res = $self->_handle_action($env, $route, $fake_http, \$sb_req, \$raw_body, $identity); 1 } } 0 0 0
121 0 my $e = $@;
122 0 ▶ my ( $message, $category ) = blessed($e) && $e->isa('Future::Exception')
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($e) && $e->isa('Future::Exception') ? : 0 0 0
Condition0%0/3
builtin::blessed($e) and $e->isa("Future::Exception")
!ll&&!rl&&r
000
MC/DC0%0/2
builtin::blessed($e) and $e->isa("Future::Exception")
builtin::blessed($e) $e->isa("Future::Exception")
Truth table0%0/3
A and B
A= builtin::blessed($e)B= $e->isa("Future::Exception")
ABresult
0X0
100
111
123 ? ( $e->message, $e->category ) : ( $e );
124 # The client gets the cleaned text; the log keeps the whole message (k79).
125 0 $log->errorf( 'Request error (%s): %s', $route->{action}, $message );
126 0 my ($status, $ctype, $body) = $sb->_handler_failure_answer( $proto, $message, $category, $sb_req, $raw_body );
127 0 return [ $status, [ 'Content-Type' => $ctype ], [ $body ] ];
128 }
129  
130 # A request past the auth and setup checks, answered as a PSGI response.
131 # Dies on any failure; _handle_psgi answers it. The parsed request is put
132 # into $$request_slot as soon as it exists, so the error answer can address it.
133 0 ▶sub _handle_action {
Subroutine _handle_action: not called CC=30 SCAR=68.4
134 0 my ($self, $env, $route, $fake_http, $request_slot, $body_slot, $identity) = @_;
135 0 my $sb = $self->knarr;
136 0 ▶ my $path = $env->{PATH_INFO} // '/';
Condition0%0/2
$env->{"PATH_INFO"} // "/"
l!l
00
MC/DC0%0/1
$env->{"PATH_INFO"} // "/"
$env->{"PATH_INFO"}
Truth table0%0/2
A
A= $env->{"PATH_INFO"}
Aresult
11
00
137 0 my $proto = $route->{protocol};
138 0 my $action = $route->{action};
139  
140 0 ▶ if ( $action eq 'models' || $action eq 'acp_agents' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($action eq "models" or $action eq "acp_agents") 0 0 0
Condition0%0/3
$action eq "models" or $action eq "acp_agents"
l!l&&r!l&&!r
000
MC/DC0%0/2
$action eq "models" or $action eq "acp_agents"
$action eq "models" $action eq "acp_agents"
Truth table0%0/3
A or B
A= $action eq "models"B= $action eq "acp_agents"
ABresult
1X1
011
000
141 0 my $models = $sb->_visible_models($identity);
142 0 my ($status, $headers, $body) = $proto->format_models_response($models);
143 0 return [ $status, [ %$headers ], [ $body ] ];
144 }
145 0 ▶ if ( $action eq 'manifest' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($action eq "manifest") 0 0 0
146 0 ▶ if ( my ($status, $ctype, $body) = $sb->_authorize_refusal( $proto, $identity, 'manifest', undef ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = $sb->_authorize_refusal($proto, $identity, "manifest", undef)) 0 0 0
147 0 return [ $status, [ 'Content-Type' => $ctype ], [ $body ] ];
148 }
149 my ($status, $body) = $sb->manifest_response(
150 scheme => $env->{'psgi.url_scheme'} // 'http',
151 host => $env->{HTTP_HOST}
152 // ( defined $env->{SERVER_NAME} ? $env->{SERVER_NAME} . ':' . ( $env->{SERVER_PORT} // 80 ) : undef ),
153 0 ▶ prefix => $env->{SCRIPT_NAME} // '',
Branch: 1 branch
BranchTrueFalseTotal
defined $env->{'SERVER_NAME'} ? : 0 0 0
Condition0%0/8
$env->{"psgi.url_scheme"} // "http"
l!l
00
$env->{"HTTP_HOST"} // (defined $env->{"SERVER_NAME"} ? $env->{"SERVER_NAME"} . ':' . ($env->{"SERVER_PORT"} // 80) : undef)
l!l
00
$env->{"SERVER_PORT"} // 80
l!l
00
$env->{"SCRIPT_NAME"} // ""
l!l
00
MC/DC0%0/1
$env->{"psgi.url_scheme"} // "http"
$env->{"psgi.url_scheme"}
MC/DC0%0/1
$env->{"HTTP_HOST"} // (defined $env->{"SERVER_NAME"} ? $env->{"SERVER_NAME"} . ':' . ($env->{"SERVER_PORT"} // 80) : undef)
$env->{"HTTP_HOST"}
MC/DC0%0/1
$env->{"SERVER_PORT"} // 80
$env->{"SERVER_PORT"}
MC/DC0%0/1
$env->{"SCRIPT_NAME"} // ""
$env->{"SCRIPT_NAME"}
Truth table0%0/2
A
A= $env->{"psgi.url_scheme"}
Aresult
11
00
Truth table0%0/2
A
A= $env->{"HTTP_HOST"}
Aresult
11
00
Truth table0%0/2
A
A= $env->{"SERVER_PORT"}
Aresult
11
00
Truth table0%0/2
A
A= $env->{"SCRIPT_NAME"}
Aresult
11
00
154 );
155 0 return [ $status, [ 'Content-Type' => 'application/json' ], [ $body ] ];
156 }
157 # The same table and methods as the native server (k29).
158 0 ▶ if ( my $simple = $sb->_simple_action($action) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $simple = $sb->_simple_action($action)) 0 0 0
159 0 my ($status, $headers, $body) = $sb->$simple( $proto, $self->_read_body($env), $identity );
160 0 return [ $status, [ %$headers ], [ $body ] ];
161 }
162 0 ▶ if ( $action eq 'a2a_card' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($action eq "a2a_card") 0 0 0
163 0 my ($status, $headers, $body) = $proto->format_agent_card;
164 0 return [ $status, [ %$headers ], [ $body ] ];
165 }
166 0 ▶ if ( $action ne 'chat' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($action ne "chat") 0 0 0
167 0 my ($status, $ctype, $body) = $sb->_error_answer( $proto, 500, "unknown action $action",
168 undef, $self->_error_body( $env, $proto ) );
169 0 return [ $status, [ 'Content-Type' => $ctype ], [ $body ] ];
170 }
171  
172 0 my $body = $self->_read_body($env);
173 0 ▶ $$body_slot = $body if $body_slot;
Branch: 1 branch
BranchTrueFalseTotal
if $body_slot 0 0 0
174 0 my $sb_req = $sb->_parse_chat_request( $proto, $fake_http, \$body, $identity );
175 0 ▶ $$request_slot = $sb_req if $request_slot;
Branch: 1 branch
BranchTrueFalseTotal
if $request_slot 0 0 0
176 # The model is known now (k82): refused before any handler work.
177 0 ▶ if ( my ($status, $ctype, $obody) = $sb->_authorize_refusal( $proto, $identity, 'chat', $sb_req->model, $sb_req, $body ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = $sb->_authorize_refusal($proto, $identity, "chat", $sb_req->model, $sb_req, $body)) 0 0 0
178 0 return [ $status, [ 'Content-Type' => $ctype ], [ $obody ] ];
179 }
180  
181 # Raw passthrough, decided and prepared by the same Knarr code as on the
182 # native server (k26): the client's bytes go 1:1 to the upstream and its
183 # answer comes back unchanged. A streaming answer is buffered, like every
184 # stream under this adapter. A discovered model the upstream refuses the
185 # client's key for falls through to the handler chain below, to its
186 # engine (k66).
187 0 ▶ if ( $sb->_is_raw_passthrough($sb_req) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sb->_is_raw_passthrough($sb_req)) 0 0 0
188 0 my ($http_req, $trace, $trace_from) = $sb->_raw_passthrough_request(
189 $sb_req, [ $fake_http->headers ], $body, $path );
190 # The failure as the future carries it, as the native on_fail sees it.
191 # A buffered stream still gets the stall timeout, not the total one: a
192 # long steady stream is legitimate (k35).
193 my ($resp, $err, $category) = $sb->raw_passthrough->_upstream_request_f(
194 request => $http_req, stream => $sb_req->stream ? 1 : 0 )
195 0 ▶ ->else( sub { Future->done( undef, @_[0, 1] ) } )->get;
Subroutine __ANON__: not called CC=1 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$sb_req->stream ? : 0 0 0
196 0 ▶ 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)) 0 0 0
Condition0%0/3
$resp and $sb->_raw_passthrough_falls_back($sb_req, $resp)
!ll&&!rl&&r
000
MC/DC0%0/2
$resp and $sb->_raw_passthrough_falls_back($sb_req, $resp)
$resp $sb->_raw_passthrough_falls_back($sb_req, $resp)
Truth table0%0/3
A and B
A= $respB= $sb->_raw_passthrough_falls_back($sb_req, $resp)
ABresult
0X0
100
111
197 0 ▶ $trace = $sb->_raw_passthrough_trace( $sb_req, $trace_from ) if $trace_from;
Branch: 1 branch
BranchTrueFalseTotal
if $trace_from 0 0 0
198 0 ▶ my ($status, $ctype, $obody, $oheaders) = $resp
Branch: 1 branch
BranchTrueFalseTotal
$resp ? : 0 0 0
Condition0%0/2
$err // "unknown error"
l!l
00
MC/DC0%0/1
$err // "unknown error"
$err
Truth table0%0/2
A
A= $err
Aresult
11
00
199 ? $sb->_raw_passthrough_answer( $sb_req, $trace, $resp )
200 : $sb->_raw_passthrough_failed( $proto, $sb_req, $trace, $err // 'unknown error', $category );
201 0 ▶ return [ $status, [ 'Content-Type' => $ctype, map { @$_ } @{ $oheaders // [] } ], [ $obody ] ];
Condition0%0/2
$oheaders // []
l!l
00
MC/DC0%0/1
$oheaders // []
$oheaders
Truth table0%0/2
A
A= $oheaders
Aresult
11
00
202 }
203 }
204  
205 0 my $session = $sb->session( $sb_req->session_id );
206 0 my $handler = $sb->handler;
207  
208 # A read the upstream has not fed yet is a plain pending Future (the
209 # stream's own queue), which cannot ->get by itself: run the loop until
210 # it is ready.
211 0 ▶ my $get = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
212 0 my ($f) = @_;
213 0 ▶ $sb->loop->await($f) unless $f->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
unless $f->is_ready 0 0 0
214 0 return $f->get;
215 0 };
216  
217 0 ▶ if ( $sb_req->stream ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sb_req->stream) 0 0 0
218 # Buffered streaming: drive the stream to completion, concatenate frames.
219 0 my $stream = $get->( $handler->handle_stream_f( $session, $sb_req ) );
220 0 my $out = $proto->format_stream_open($sb_req);
221 0 ▶ while ( defined( my $delta = $get->( $stream->next_chunk_f ) ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $delta = &$get($stream->next_chunk_f))) 0 0 0
222 0 $out .= $proto->format_stream_chunk( $delta, $sb_req );
223 }
224 0 ▶ my $finish_reason = $stream->can('finish_reason') ? $stream->finish_reason : undef;
Branch: 1 branch
BranchTrueFalseTotal
$stream->can('finish_reason') ? : 0 0 0
225 0 ▶ my $tool_calls = $stream->can('tool_calls') ? $stream->tool_calls : [];
Branch: 1 branch
BranchTrueFalseTotal
$stream->can('tool_calls') ? : 0 0 0
226 0 ▶ my $usage = $stream->can('usage') ? $stream->usage : undef;
Branch: 1 branch
BranchTrueFalseTotal
$stream->can('usage') ? : 0 0 0
227 0 $out .= $proto->format_stream_close( $sb_req, $finish_reason, $tool_calls, $usage );
228 0 $out .= $proto->format_stream_done( $sb_req, $finish_reason, $tool_calls, $usage );
229 0 return [ 200, [ 'Content-Type' => $proto->stream_content_type ], [ $out ] ];
230 }
231  
232 0 my $response = $get->( $handler->handle_chat_f( $session, $sb_req ) );
233 0 my ($status, $headers, $obody) = $proto->format_chat_response( $response, $sb_req );
234 0 return [ $status, [ %$headers ], [ $obody ] ];
235 }
236  
237 1 __PACKAGE__->meta->make_immutable;
238 1 1;
239  
240 __END__
« blib/lib/Langertha/Knarr/CLI/Cmd/Start.pm ↑ Summary blib/lib/Langertha/Knarr/Handler/Passthrough.pm »