Knarr/Handler/Passthrough.pm

filter: Statementstmt 91.4% 139 / 152 Branchbran 60.9% 39 / 64 Conditioncond 52.6% 10 / 19 MC/DCmcdc 27.2% 3 / 11 Subroutinesub 92.0% 23 / 25 Podpod 0.0% 0 / 3 totaltotal 78.1% 214 / 274 CC 44 SCAR 20.8
CC
44
Cov
80%
__ANON__
15.5
_extract_text
14.4
_build_upstream_request
9.2
CRAP 8.0
« Knarr/Stream.pm ↑ Summary Knarr/Protocol/Anthropic.pm »
1 package Langertha::Knarr::Handler::Passthrough;
2 # ABSTRACT: Knarr handler that forwards requests verbatim to an upstream HTTP API
3 3 our $VERSION = '1.100';
4 3 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 3 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 3 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 3 ▶use HTTP::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 3 ▶use Net::Async::HTTP;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 3 ▶use IO::Async::Loop;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 3 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 3 ▶use Langertha::Knarr::Stream;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 3 ▶use Langertha::Knarr::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 3 with 'Langertha::Knarr::Handler';
15  
16  
17 # Forwards the original wire-format request to a real upstream API. The
18 # protocol's parser already turned the body into a Knarr::Request, so we
19 # rebuild a body from $request->raw and re-POST it. Headers (especially
20 # Authorization) are passed through if the caller registers them with the
21 # session via $request->extra->{forward_headers}.
22  
23 # Per-protocol upstream URLs. Keys are protocol names ("openai", "anthropic",
24 # "ollama"). Each value is the base URL of the upstream provider — e.g.
25 # https://api.openai.com or https://api.anthropic.com. Knarr appends the
26 # original request path to this base URL.
27 3 has upstreams => (
28 is => 'ro',
29 isa => 'HashRef[Str]',
30 required => 1,
31 );
32  
33 # Optional: a default Authorization header value to inject if the client
34 # didn't send one. If undef, the client must supply its own.
35 has default_auth => (
36 is => 'ro',
37 isa => 'Maybe[Str]',
38 2 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
39 3 );
40  
41 3 has model_id => ( is => 'ro', isa => 'Str', default => 'passthrough' );
42  
43 has loop => (
44 is => 'ro',
45 lazy => 1,
46 0 ▶ default => sub { IO::Async::Loop->new },
Subroutine __ANON__: not called CC=1 SCAR=6.9
47 3 );
48  
49 3 has _http => ( is => 'ro', lazy => 1, builder => '_build_http' );
50 sub _build_http {
51 2 ▶ my ($self) = @_;
Subroutine _build_http: called CC=1 SCAR=0.0
52 2 my $h = Net::Async::HTTP->new;
53 2 $self->loop->add($h);
54 2 return $h;
55 }
56  
57 2 ▶has _json => ( is => 'ro', default => sub { JSON::MaybeXS->new( utf8 => 1, canonical => 1 ) } );
Subroutine __ANON__: called CC=1 SCAR=0.0
58  
59 # Per-protocol path the request should hit upstream. We use the protocol
60 # defaults; this lookup table can be extended.
61 3 my %DEFAULT_PATH = (
62 openai => '/v1/chat/completions',
63 anthropic => '/v1/messages',
64 ollama => '/api/chat',
65 );
66  
67 sub _upstream_url {
68 9 ▶ my ($self, $protocol_name) = @_;
Subroutine _upstream_url: called CC=3 SCAR=11.3
69 9 ▶ my $base = $self->upstreams->{$protocol_name}
Branch: 1 branch
BranchTrueFalseTotal
my $base = $self->upstreams->{$protocol_name} or die "Passthrough: no upstream configured for protocol '${protocol_name}'\n" 0 9 9
70 or die "Passthrough: no upstream configured for protocol '$protocol_name'\n";
71 9 $base =~ s{/+$}{};
72 9 ▶ my $path = $DEFAULT_PATH{$protocol_name}
Branch: 1 branch
BranchTrueFalseTotal
my $path = $DEFAULT_PATH{$protocol_name} or die "Passthrough: no default path for protocol '${protocol_name}'\n" 0 9 9
73 or die "Passthrough: no default path for protocol '$protocol_name'\n";
74 9 return "$base$path";
75 }
76  
77 sub _build_upstream_request {
78 5 ▶ my ($self, $request, $force_stream) = @_;
Subroutine _build_upstream_request: called CC=8 SCAR=22.2
79 5 ▶ my $body = { %{ $request->raw || {} } };
Branch: 1 branch
BranchTrueFalseTotal
$request->raw or {} 0 5 5
80 5 ▶ $body->{stream} = $force_stream ? JSON::MaybeXS::true() : JSON::MaybeXS::false()
Branch: 2 branches
BranchTrueFalseTotal
if defined $force_stream 5 0 5
$force_stream ? : 2 3 5
81 if defined $force_stream;
82 5 my $url = $self->_upstream_url( $request->protocol );
83 5 my $http_req = HTTP::Request->new( POST => $url );
84 5 $http_req->header( 'Content-Type' => 'application/json' );
85 # Forward client auth headers (captured by protocol parsers)
86 5 ▶ if ( my $fwd = $request->extra->{forward_headers} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $fwd = $request->extra->{"forward_headers"}) 3 2 5
87 3 for my $h (keys %$fwd) {
88 0 $http_req->header( $h => $fwd->{$h} );
89 }
90 }
91 5 ▶ if ( my $auth = $self->default_auth ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $auth = $self->default_auth) 0 5 5
92 0 ▶ $http_req->header( Authorization => $auth ) unless $http_req->header('Authorization');
Branch: 1 branch
BranchTrueFalseTotal
unless $http_req->header("Authorization") 0 0 0
93 }
94 5 $http_req->content( $self->_json->encode($body) );
95 5 return $http_req;
96 }
97  
98 # Extract assistant text from an upstream response body for the protocol it
99 # came from. Bare-minimum extractor for sync mode; the streaming path
100 # forwards bytes verbatim and doesn't need this.
101 sub _extract_text {
102 3 ▶ my ($self, $protocol_name, $resp_body) = @_;
Subroutine _extract_text: called CC=12 SCAR=26.7
103 3 my $data = eval { $self->_json->decode($resp_body) };
104 3 ▶ return '' unless ref $data eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 0 3 3
105 3 ▶ if ( $protocol_name eq 'openai' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($protocol_name eq "openai") 1 2 3
106 1 ▶ return $data->{choices}[0]{message}{content} // '';
Condition50%1/2
$data->{"choices"}[0]{"message"}{"content"} // ""
l!l
10
MC/DC0%0/1
$data->{"choices"}[0]{"message"}{"content"} // ""
$data->{"choices"}[0]{"message"}{"content"}
Truth table50%1/2
A
A= $data->{"choices"}[0]{"message"}{"content"}
Aresult
11
00
107 }
108 2 ▶ if ( $protocol_name eq 'anthropic' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($protocol_name eq "anthropic") 1 1 2
109 1 my $bits = '';
110 1 ▶ for my $b ( @{ $data->{content} || [] } ) {
Branch: 1 branch
BranchTrueFalseTotal
$data->{"content"} or [] 0 1 1
111 1 ▶ $bits .= $b->{text} // '' if ($b->{type} // '') eq 'text';
Branch: 1 branch
BranchTrueFalseTotal
if ($b->{"type"} // "") eq "text" 1 0 1
Condition50%2/4
$b->{"type"} // ""
l!l
10
$b->{"text"} // ""
l!l
10
MC/DC0%0/1
$b->{"type"} // ""
$b->{"type"}
MC/DC0%0/1
$b->{"text"} // ""
$b->{"text"}
Truth table50%1/2
A
A= $b->{"type"}
Aresult
11
00
Truth table50%1/2
A
A= $b->{"text"}
Aresult
11
00
112 }
113 1 return $bits;
114 }
115 1 ▶ if ( $protocol_name eq 'ollama' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($protocol_name eq "ollama") 1 0 1
116 1 ▶ return $data->{message}{content} // '';
Condition50%1/2
$data->{"message"}{"content"} // ""
l!l
10
MC/DC0%0/1
$data->{"message"}{"content"} // ""
$data->{"message"}{"content"}
Truth table50%1/2
A
A= $data->{"message"}{"content"}
Aresult
11
00
117 }
118 0 return '';
119 }
120  
121 3 ▶async sub handle_chat_f {
Subroutine handle_chat_f: called CC=3 SCAR=11.4
Pod undocumented
122 3 my ($self, $session, $request) = @_;
123 3 my $http_req = $self->_build_upstream_request( $request, 0 );
124 3 my $resp = await $self->_http->do_request( request => $http_req );
125 3 ▶ die "Passthrough upstream failed: " . $resp->status_line . "\n" unless $resp->is_success;
Branch: 1 branch
BranchTrueFalseTotal
unless $resp->is_success 0 3 3
126 3 my $text = $self->_extract_text( $request->protocol, $resp->decoded_content );
127 3 ▶ return Langertha::Knarr::Response->new(
Condition33%1/3
$request->model // $self->model_id
l!l&&r!l&&!r
300
MC/DC0%0/2
$request->model // $self->model_id
$request->model $self->model_id
Truth table33%1/3
A // B
A= $request->modelB= $self->model_id
ABresult
1X1
011
000
128 content => $text,
129 model => $request->model // $self->model_id,
130 );
131 3 }
132  
133 2 ▶async sub handle_stream_f {
Subroutine handle_stream_f: called CC=1 SCAR=0.1
Pod undocumented
134 2 my ($self, $session, $request) = @_;
135 2 my $http_req = $self->_build_upstream_request( $request, 1 );
136  
137 2 my @queue;
138 my $pending;
139 2 my $finished = 0;
140 2 my $error;
141 2 my $buffer = '';
142  
143 my $deliver = sub {
144 8 ▶ my ($v) = @_;
Subroutine __ANON__: called CC=2 SCAR=7.2
145 8 ▶ if ( $pending ) { my $p = $pending; $pending = undef; $p->done($v) }
Branch: 1 branch
BranchTrueFalseTotal
if ($pending) { } 8 0 8
146 0 else { push @queue, $v }
147 2 };
148  
149 # Streaming request: hand the body chunks straight back as deltas. The
150 # upstream already speaks the same wire format the client requested, so
151 # we forward bytes 1:1 by extracting just the text content from each
152 # protocol-native chunk. The Knarr core then re-frames them via the
153 # client-side protocol's format_stream_chunk — keeping symmetry even
154 # when client and upstream use the same protocol.
155 2 my $proto_name = $request->protocol;
156 my $extract_chunk = sub {
157 8 ▶ my ($line) = @_;
Subroutine __ANON__: called CC=11 SCAR=27.4
158 8 ▶ if ( $proto_name eq 'openai' || $proto_name eq 'anthropic' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($proto_name eq "openai" or $proto_name eq "anthropic") 4 4 8
Condition66%2/3
$proto_name eq "openai" or $proto_name eq "anthropic"
l!l&&r!l&&!r
404
MC/DC50%1/2
$proto_name eq "openai" or $proto_name eq "anthropic"
$proto_name eq "openai" $proto_name eq "anthropic"
Truth table66%2/3
A or B
A= $proto_name eq "openai"B= $proto_name eq "anthropic"
ABresult
1X1
011
000
159 4 ▶ return undef unless $line =~ /^data:\s*(.+)$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $line =~ /^data:\s*(.+)$/ 0 4 4
160 4 my $payload = $1;
161 4 ▶ return undef if $payload eq '[DONE]';
Branch: 1 branch
BranchTrueFalseTotal
if $payload eq "[DONE]" 1 3 4
162 3 my $d = eval { $self->_json->decode($payload) };
163 3 ▶ return undef unless ref $d eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $d eq "HASH" 0 3 3
164 3 ▶ if ( $proto_name eq 'openai' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($proto_name eq 'openai') { } 3 0 3
165 3 return $d->{choices}[0]{delta}{content};
166 } else {
167 0 ▶ return $d->{delta}{text} if ($d->{type} // '') eq 'content_block_delta';
Branch: 1 branch
BranchTrueFalseTotal
if ($d->{"type"} // "") eq "content_block_delta" 0 0 0
Condition0%0/2
$d->{"type"} // ""
l!l
00
MC/DC0%0/1
$d->{"type"} // ""
$d->{"type"}
Truth table0%0/2
A
A= $d->{"type"}
Aresult
11
00
168 0 return undef;
169 }
170 }
171 4 ▶ if ( $proto_name eq 'ollama' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($proto_name eq "ollama") 4 0 4
172 4 my $d = eval { $self->_json->decode($line) };
173 4 ▶ return undef unless ref $d eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $d eq "HASH" 0 4 4
174 4 return $d->{message}{content};
175 }
176 0 return undef;
177 2 };
178  
179 my $f = $self->_http->do_request(
180 request => $http_req,
181 on_header => sub {
182 2 ▶ my ($r) = @_;
Subroutine __ANON__: called CC=1 SCAR=0.0
183 return sub {
184 10 ▶ my ($data) = @_;
Subroutine __ANON__: called CC=8 SCAR=20.8
185 10 ▶ if ( !defined $data ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $data) 2 8 10
186 2 $finished = 1;
187 2 $deliver->(undef);
188 2 return;
189 }
190 8 $buffer .= $data;
191 # Frame separator: blank line for SSE, single \n for NDJSON.
192 8 ▶ my $sep = $proto_name eq 'ollama' ? qr/\n/ : qr/\n\n/;
Branch: 1 branch
BranchTrueFalseTotal
$proto_name eq 'ollama' ? : 4 4 8
193 8 ▶ while ( $buffer =~ s/^(.*?)$sep//s ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($buffer =~ s/^(.*?)$sep//s) 8 8 16
194 8 my $frame = $1;
195 8 for my $line ( split /\n/, $frame ) {
196 8 ▶ next unless length $line;
Branch: 1 branch
BranchTrueFalseTotal
unless length $line 0 8 8
197 8 my $delta = $extract_chunk->($line);
198 8 ▶ $deliver->($delta) if defined $delta && length $delta;
Branch: 1 branch
BranchTrueFalseTotal
if defined $delta and length $delta 6 2 8
Condition100%3/3
defined $delta and length $delta
!ll&&!rl&&r
116
MC/DC100%2/2
defined $delta and length $delta
defined $delta length $delta
Truth table100%3/3
A and B
A= defined $deltaB= length $delta
ABresult
0X0
100
111
199 }
200 }
201 2 };
202 },
203 2 );
204 2 ▶ $f->on_fail( sub { $error = $_[0]; $finished = 1; $deliver->(undef) } );
Subroutine __ANON__: not called CC=1 SCAR=3.5
205 2 $f->retain;
206  
207 return Langertha::Knarr::Stream->new(
208 source => sub {
209 8 ▶ if ( @queue ) { return Future->done( shift @queue ) }
Subroutine __ANON__: called CC=4 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if (@queue) 0 8 8
210 8 ▶ if ( $finished ) { return $error ? Future->fail($error) : Future->done(undef) }
Branch: 2 branches
BranchTrueFalseTotal
if ($finished) 0 8 8
$error ? : 0 0 0
211 8 $pending = Future->new;
212 8 return $pending;
213 },
214 2 );
215 3 }
216  
217 sub list_models {
218 1 ▶ my ($self) = @_;
Subroutine list_models: called CC=1 SCAR=0.0
Pod undocumented
219 1 return [ { id => $self->model_id, object => 'model' } ];
220 }
221  
222 3 __PACKAGE__->meta->make_immutable;
223 3 1;
224  
225 __END__
226  
227 =pod
228  
229 =encoding UTF-8
230  
231 =head1 NAME
232  
233 Langertha::Knarr::Handler::Passthrough - Knarr handler that forwards requests verbatim to an upstream HTTP API
234  
235 =head1 VERSION
236  
237 version 1.100
238  
239 =head1 SYNOPSIS
240  
241 use Langertha::Knarr::Handler::Passthrough;
242  
243 my $handler = Langertha::Knarr::Handler::Passthrough->new(
244 upstreams => {
245 openai => 'https://api.openai.com',
246 anthropic => 'https://api.anthropic.com',
247 ollama => 'http://localhost:11434',
248 },
249 );
250  
251 =head1 DESCRIPTION
252  
253 Forwards the original wire-format request verbatim to a real upstream
254 API. The protocol's parser already turned the body into a
255 L<Langertha::Knarr::Request>; Passthrough rebuilds the upstream JSON
256 from C<$request-E<gt>raw> and re-POSTs it.
257  
258 Both sync and streaming requests are supported. For streaming, the
259 upstream's protocol-native chunks are extracted into plain text deltas
260 which the front-side protocol then re-frames — keeping symmetry even
261 when client and upstream use the same protocol.
262  
263 This is the building block behind Knarr's classic "configure your API
264 keys once, point everything at me" use case.
265  
266 =head2 upstreams
267  
268 Required. HashRef mapping protocol name (C<openai>, C<anthropic>,
269 C<ollama>) to upstream base URL. The protocol's default chat path is
270 appended.
271  
272 =head2 default_auth
273  
274 Optional. An C<Authorization> header value to inject when the client
275 didn't send one. Usually you let the client supply its own key.
276  
277 =head2 model_id
278  
279 Optional. Defaults to C<passthrough>.
280  
281 =head1 SUPPORT
282  
283 =head2 Issues
284  
285 Please report bugs and feature requests on GitHub at
286 L<https://github.com/Getty/langertha-knarr/issues>.
287  
288 =head2 IRC
289  
290 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
291  
292 =head1 CONTRIBUTING
293  
294 Contributions are welcome! Please fork the repository and submit a pull request.
295  
296 =head1 AUTHOR
297  
298 Torsten Raudssus <torsten@raudssus.de> L<https://raudssus.de/>
299  
300 =head1 COPYRIGHT AND LICENSE
301  
302 This software is copyright (c) 2026 by Torsten Raudssus.
303  
304 This is free software; you can redistribute it and/or modify it under
305 the same terms as the Perl 5 programming language system itself.
306  
307 =cut
« Knarr/Stream.pm ↑ Summary Knarr/Protocol/Anthropic.pm »