blib/lib/Langertha/Role/Runtime/MetricsPoll.pm

filter: Statementstmt 97.1% 68 / 70 Branchbran 66.6% 4 / 6 Conditioncond 62.5% 5 / 8 MC/DCmcdc 20.0% 1 / 5 Subroutinesub 100% 14 / 14 Podpod 100% 5 / 5 totaltotal 89.8% 97 / 108 CC 7 SCAR 7.1
CC
7
Cov
92%
export_otlp_f
4.0
poll_metrics_f
3.3
metrics_url
2.0
CRAP 2.0
« blib/lib/Langertha/Engine/Remote.pm ↑ Summary blib/lib/Langertha/Engine/Hetzner.pm »
1 package Langertha::Role::Runtime::MetricsPoll;
2 # ABSTRACT: Async Prometheus /metrics scraper for self-hosted engines
3 35 our $VERSION = '0.503';
4 35 ▶use Moose::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 35 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 35 ▶use Log::Any qw( $log );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 35 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 35 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
9 35 ▶use HTTP::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 35 ▶use Langertha::Runtime::Metrics;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 35 requires qw(
14 json
15 url
16 );
17  
18 # poll_metrics_f decodes the scraped body through Role::HTTP's bounded decoder
19 # (karr k346), so this role needs Role::HTTP composed too. Every composer today
20 # (vLLM, SGLang, LlamaCpp) has it via Engine::OpenAIBase; require the attribute
21 # so a future MetricsPoll-only composer fails at composition, not at runtime.
22 35 requires 'response_max_bytes';
23  
24  
25 24 ▶sub metrics_url {
Subroutine metrics_url: called CC=2 SCAR=7.0
Pod documented
26 24 my ( $self ) = @_;
27 24 ▶ croak "metrics_url requires a url attribute" unless $self->has_url;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_url 0 24 24
28 24 my $uri = URI->new($self->url);
29 24 my $path = $uri->path;
30 # Strip trailing slashes and then a trailing /v1 segment so we get the
31 # bare server root before appending /metrics. /v1 is the OpenAI-compatible
32 # base; /metrics lives at the root for vLLM, SGLang, llama.cpp. A prefix
33 # the server is mounted under (a proxy's /vllm) stays (k306).
34 24 $path =~ s{/+\z}{};
35 24 $path =~ s{/v1\z}{};
36 24 $uri->path($path . '/metrics');
37 24 return $uri->as_string;
38 }
39  
40  
41 2 ▶sub _croak {
Subroutine _croak: called CC=1 SCAR=0.0
42 2 my ($msg) = @_;
43 2 croak($msg);
44 }
45  
46 # The _async_http backend (and its _async_loop) come from
47 # Langertha::Role::AsyncHTTP (composed below): injected client >
48 # Net::Async::HTTP > synchronous LWP fallback. The sync wrappers
49 # (poll_metrics / export_otlp) block with ->get, which drives the pending
50 # future's own loop and never creates one, so the sync fallback runs
51 # without an event loop.
52 35 with 'Langertha::Role::AsyncHTTP';
53  
54 16 ▶async sub poll_metrics_f {
Subroutine poll_metrics_f: called CC=3 SCAR=11.9
Pod documented
55 16 my ( $self, @prefixes ) = @_;
56  
57 16 my $url = $self->metrics_url;
58 16 $log->debugf("[%s] scraping %s", ref($self), $url);
59  
60 16 my $request = HTTP::Request->new(GET => $url);
61  
62 16 my $response = await $self->_async_do_request_f(
63 request => $request,
64 );
65  
66 14 ▶ unless ( $response->is_success ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success) 0 14 14
67 0 $log->errorf("[%s] /metrics fetch failed: %s",
68 ref($self), $response->status_line);
69 0 _croak("".(ref($self))." /metrics fetch failed: ".$response->status_line);
70 }
71  
72 # Bounded Content-Encoding decode (karr k346): a self-hosted /metrics endpoint
73 # (or a proxy in front of it) is not trusted to be well-behaved, so a gzip
74 # body inflates under response_max_bytes (Role::HTTP) or is refused with the
75 # too-big croak rather than expanding unbounded in memory.
76 14 ▶ my $body = $self->_bounded_decoded_content($response) // $response->content;
Condition33%1/3
$self->_bounded_decoded_content($response) // $response->content
l!l&&r!l&&!r
1200
MC/DC0%0/2
$self->_bounded_decoded_content($response) // $response->content
$self->_bounded_decoded_content($response) $response->content
Truth table33%1/3
A // B
A= $self->_bounded_decoded_content($response)B= $response->content
ABresult
1X1
011
000
77 12 return Langertha::Runtime::Metrics->new
78 ->parse_and_filter($body, @prefixes);
79 35 }
80  
81  
82 3 ▶sub poll_metrics {
Subroutine poll_metrics: called CC=1 SCAR=0.0
Pod documented
83 3 my ( $self, @prefixes ) = @_;
84 # Synchronous variant. ->get is loop-agnostic: a pending future from
85 # Net::Async::HTTP (or an injected client on the caller's own loop) is an
86 # IO::Async::Future — or whatever Future subclass that client uses — and
87 # its await() drives the loop it belongs to; Future::AsyncAwait builds
88 # the returned future from the first pending one it awaited. On the sync
89 # fallback the future is already complete. No private loop is created.
90 3 return $self->poll_metrics_f(@prefixes)->get;
91 }
92  
93  
94 # The OTLP serializer stays a lazy load, but the require lives in this plain
95 # sub and never in an async sub's own frame: with a coderef in @INC, perl
96 # localizes $INC around the hook call, and Future::AsyncAwait (0.71, perl
97 # 5.38+) aborts the process when it suspends a frame that still holds that
98 # savestack entry (karr k193, t/48_async_require_inc_hook.t). The local is
99 # unwound when this sub returns, before export_otlp_f awaits.
100 6 ▶sub _otlp_json {
Subroutine _otlp_json: called CC=1 SCAR=0.0
101 6 my ( $records, %opts ) = @_;
102 6 require Langertha::Runtime::Metrics::OTLP;
103 6 return Langertha::Runtime::Metrics::OTLP->new->to_json($records, %opts);
104 }
105  
106 7 ▶async sub export_otlp_f {
Subroutine export_otlp_f: called CC=4 SCAR=13.9
Pod documented
107 7 my ( $self, $records, %opts ) = @_;
108 my $endpoint = $opts{endpoint}
109 7 ▶ // _croak("export_otlp_f requires an endpoint option");
Condition66%2/3
$opts{"endpoint"} // _croak("export_otlp_f requires an endpoint option")
l!l&&r!l&&!r
610
MC/DC0%0/2
$opts{"endpoint"} // _croak("export_otlp_f requires an endpoint option")
$opts{"endpoint"} _croak("export_otlp_f requires an endpoint option")
Truth table33%1/3
A // B
A= $opts{"endpoint"}B= _croak("export_otlp_f requires an endpoint option")
ABresult
1X1
011
000
110  
111 6 my $body = _otlp_json($records, %opts);
112  
113 6 my @headers = ( 'Content-Type' => 'application/json' );
114 6 ▶ push @headers, %{ $opts{headers} || {} };
Condition100%2/2
$opts{'headers'} || {}
l!l
15
MC/DC100%1/1
$opts{'headers'} || {}
$opts{'headers'}
Truth table100%2/2
A
A= $opts{'headers'}
Aresult
11
00
115  
116 6 my $request = HTTP::Request->new( POST => $endpoint, \@headers, $body );
117  
118 6 $log->debugf("[%s] exporting %d records to %s",
119 ref($self), scalar(@$records), $endpoint);
120  
121 6 my $response = await $self->_async_do_request_f(
122 request => $request,
123 );
124  
125 6 ▶ unless ( $response->is_success ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success) 1 5 6
126 1 $log->errorf("[%s] OTLP export failed: %s",
127 ref($self), $response->status_line);
128 1 _croak("".(ref($self))." OTLP export failed: ".$response->status_line);
129 }
130  
131 5 return $response;
132 35 }
133  
134  
135 2 ▶sub export_otlp {
Subroutine export_otlp: called CC=1 SCAR=0.0
Pod documented
136 2 my ( $self, $records, %opts ) = @_;
137 # Synchronous variant; ->get drives the future's own loop (see
138 # poll_metrics).
139 2 return $self->export_otlp_f($records, %opts)->get;
140 }
141  
142  
143  
144 35 1;
145  
146 __END__
147  
148 =pod
149  
150 =encoding UTF-8
151  
152 =head1 NAME
153  
154 Langertha::Role::Runtime::MetricsPoll - Async Prometheus /metrics scraper for self-hosted engines
155  
156 =head1 VERSION
157  
158 version 0.503
159  
160 =head1 SYNOPSIS
161  
162 use Langertha::Engine::vLLM;
163  
164 my $vllm = Langertha::Engine::vLLM->new(
165 url => 'http://localhost:8000/v1',
166 );
167  
168 # Async — preferred for live systems
169 my $records = await $vllm->poll_metrics_f;
170 # Returns: [ { name => 'vllm:num_requests_running', type => 'gauge',
171 # value => 3, labels => { model_name => 'Qwen/...' } }, ... ]
172  
173 # Sync wrapper
174 my $records = $vllm->poll_metrics;
175  
176 =head1 DESCRIPTION
177  
178 Composes onto self-hosted engines that expose a Prometheus
179 C<GET /metrics> endpoint at the server's C<url> attribute. The role
180 scrapes the body, parses it via L<Langertha::Runtime::Metrics>, and
181 returns the parsed ArrayRef. No filtering is applied by default —
182 pass a prefix to L</poll_metrics_f($prefix)> or filter with
183 L<Langertha::Runtime::Metrics/filter_prefix> downstream.
184  
185 The parsed records can be exported to any OTLP/HTTP metrics receiver
186 (OpenTelemetry Collector, Prometheus, Grafana) via
187 L</export_otlp_f> / L</export_otlp>, which serialize them with
188 L<Langertha::Runtime::Metrics::OTLP>. B<Langfuse does not ingest OTLP
189 metrics> — see L</export_otlp_f> for the details and sources.
190  
191 The endpoint path is derived by stripping the trailing C</v1> (or
192 any trailing slash) from C<url>, then appending C</metrics>. Engines
193 whose C<url> is e.g. C<http://localhost:8000/v1> therefore hit
194 C<http://localhost:8000/metrics> — matching the convention used by
195 vLLM, SGLang, and llama.cpp's built-in server.
196  
197 B<Authentication:> None. These are local servers; no C<api_key>
198 header is sent. If a deployment sits behind auth, layer it on
199 externally (proxy or L<Langertha::Role::HTTP/generate_http_request>
200 extension).
201  
202 B<Ollama> is intentionally B<not> composed with this role:
203 Ollama's runtime stats live at C</api/ps> in JSON, not
204 C</metrics> in Prometheus text. See
205 L<Langertha::Runtime::Metrics::EngineContract> for the wire
206 contract and the follow-up karr ticket tracked alongside that
207 document for the JSON-to-Prometheus adapter work.
208  
209 =head2 metrics_url
210  
211 my $url = $engine->metrics_url;
212  
213 Derives the C</metrics> URL from the engine's C<url> attribute by
214 stripping trailing slashes and a trailing C</v1> path segment, then
215 appending C</metrics>. Any other path prefix is kept, so
216 C<http://host/vllm/v1> and C<http://host/vllm> both give
217 C<http://host/vllm/metrics>. Returns the full URL as a string.
218  
219 =head2 poll_metrics_f
220  
221 my $records = await $engine->poll_metrics_f;
222 my $vllm = await $engine->poll_metrics_f('vllm:');
223  
224 Async scrape. Returns a Future that resolves to the ArrayRef of
225 parsed L<Langertha::Runtime::Metrics> records. Optional prefix
226 arguments OR-filter the parser output (see
227 L<Langertha::Runtime::Metrics/parse_and_filter>).
228  
229 Croaks on a non-success HTTP response.
230  
231 =head2 poll_metrics
232  
233 my $records = $engine->poll_metrics;
234  
235 Synchronous scrape. Returns the ArrayRef of records or croaks on HTTP
236 failure. It blocks on L</poll_metrics_f> with C<< ->get >>, which drives
237 the loop the pending future belongs to: the engine's L<IO::Async::Loop> on
238 the L<Net::Async::HTTP> backend, or the loop of an injected C<_async_http>
239 client. On the synchronous L<Langertha::Request::SyncHTTP> fallback the
240 future is already complete, so no event loop is created
241 (L<Langertha::Role::AsyncHTTP>).
242  
243 Use this only when no event loop is already running. Inside an
244 async context prefer L</poll_metrics_f>.
245  
246 =head2 export_otlp_f
247  
248 my $response = await $engine->export_otlp_f($records,
249 endpoint => 'http://localhost:4318/v1/metrics',
250 headers => { Authorization => 'Basic ...' },
251 service_name => 'vllm',
252 resource_attributes => { trace_id => 'trace-123' },
253 );
254  
255 Async export. Serializes the parsed records (the ArrayRef from
256 L</poll_metrics_f>) into an OTLP/HTTP JSON metrics payload via
257 L<Langertha::Runtime::Metrics::OTLP> and POSTs it to C<endpoint>.
258 Returns the L<HTTP::Response>. Croaks on a non-success HTTP response.
259  
260 C<%opts> are passed through to
261 L<Langertha::Runtime::Metrics::OTLP/build_payload> (C<service_name>,
262 C<resource_attributes>, C<scope_name>, C<timestamp>) plus:
263  
264 =over 4
265  
266 =item * C<endpoint> — required. The OTLP/HTTP metrics receiver URL, e.g.
267 C<http://localhost:4318/v1/metrics> (OpenTelemetry Collector), a
268 Prometheus OTLP receiver, or Grafana.
269  
270 =item * C<headers> — optional HashRef of extra request headers (e.g.
271 C<Authorization> for a protected receiver).
272  
273 =back
274  
275 B<Langfuse note:> Langfuse does B<not> ingest OTLP metrics. Its
276 C</api/public/otel> endpoint accepts traces only; a POST to
277 C</api/public/otel/v1/metrics> is accepted and silently discarded (dummy
278 route since langfuse/langfuse#6408), and C</api/public/metrics> is a
279 read-only query API over Langfuse's own trace data. Point this exporter
280 at a real OTLP metrics backend (Collector, Prometheus, Grafana). Sources:
281 L<https://github.com/langfuse/langfuse/issues/6395> and
282 L<https://github.com/orgs/langfuse/discussions/10686>.
283  
284 =head2 export_otlp
285  
286 my $response = $engine->export_otlp($records, endpoint => '...');
287  
288 Synchronous export. Returns the L<HTTP::Response> or croaks on HTTP
289 failure. Like L</poll_metrics> it blocks on L</export_otlp_f> with
290 C<< ->get >>, driving the pending future's own loop; on the synchronous
291 L<Langertha::Request::SyncHTTP> fallback the future is already complete,
292 so no event loop is created (L<Langertha::Role::AsyncHTTP>).
293  
294 Use this only when no event loop is already running. Inside an
295 async context prefer L</export_otlp_f>.
296  
297 =head1 SEE ALSO
298  
299 =over 4
300  
301 =item * L<Langertha::Runtime::Metrics> - The parser this role drives
302  
303 =item * L<Langertha::Runtime::Metrics::OTLP> - OTLP/HTTP JSON serializer used by L</export_otlp_f>
304  
305 =item * L<Langertha::Runtime::Metrics::EngineContract> - Per-engine wire contract
306  
307 =item * L<Langertha::Engine::vLLM> - vLLM self-hosted engine (composes this role)
308  
309 =item * L<Langertha::Engine::SGLang> - SGLang self-hosted engine (composes this role)
310  
311 =item * L<Langertha::Engine::LlamaCpp> - llama.cpp server engine (composes this role)
312  
313 =back
314  
315 =head1 SUPPORT
316  
317 =head2 Issues
318  
319 Please report bugs and feature requests on GitHub at
320 L<https://github.com/Getty/langertha/issues>.
321  
322 =head2 IRC
323  
324 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
325  
326 =head1 CONTRIBUTING
327  
328 Contributions are welcome! Please fork the repository and submit a pull request.
329  
330 =head1 AUTHOR
331  
332 Torsten Raudssus <getty@cpan.org>
333  
334 =head1 COPYRIGHT AND LICENSE
335  
336 This software is copyright (c) 2026 by Torsten Raudssus L<https://raudssus.de/>.
337  
338 This is free software; you can redistribute it and/or modify it under
339 the same terms as the Perl 5 programming language system itself.
340  
341 =cut
« blib/lib/Langertha/Engine/Remote.pm ↑ Summary blib/lib/Langertha/Engine/Hetzner.pm »