blib/lib/Langertha/Runtime/Metrics.pm

filter: Statementstmt 100% 67 / 67 Branchbran 88.2% 30 / 34 Conditioncond 66.6% 12 / 18 MC/DCmcdc 41.6% 5 / 12 Subroutinesub 100% 8 / 8 Podpod 100% 3 / 3 totaltotal 88.0% 125 / 142 CC 27 SCAR 18.6
CC
27
Cov
92%
parse
10.1
_parse_labels
6.0
parse_and_filter
6.0
CRAP 6.4
« blib/lib/Langertha/Pricing.pm ↑ Summary blib/lib/Langertha/Metrics.pm »
1 package Langertha::Runtime::Metrics;
2 # ABSTRACT: Prometheus text exposition format parser with prefix filter
3 35 our $VERSION = '0.503';
4 35 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 35 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
6 35 ▶use Scalar::Util qw( blessed );
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8  
9 35 has _default_type => (
10 is => 'ro',
11 isa => 'Str',
12 default => 'untyped',
13 );
14  
15 22 ▶sub parse {
Subroutine parse: called CC=10 SCAR=23.2
Pod documented
16 22 my ( $self, $payload ) = @_;
17 22 ▶ croak "parse() requires a payload string"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $payload and ref $payload ne "HASH" 1 21 22
Condition66%2/3
defined $payload and ref $payload ne "HASH"
!ll&&!rl&&r
1021
MC/DC50%1/2
defined $payload and ref $payload ne "HASH"
defined $payload ref $payload ne "HASH"
Truth table66%2/3
A and B
A= defined $payloadB= ref $payload ne "HASH"
ABresult
0X0
100
111
18 unless defined $payload && ref($payload) ne 'HASH';
19  
20 21 my @records;
21 my %type_for;
22  
23 21 for my $line ( split /\r?\n/, $payload ) {
24 105 ▶ next if $line eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $line eq "" 0 105 105
25 105 ▶ next if $line =~ /^\s*$/;
Branch: 1 branch
BranchTrueFalseTotal
if $line =~ /^\s*$/ 0 105 105
26  
27 105 ▶ if ( $line =~ /^\#\s*TYPE\s+(\S+)\s+(\S+)\s*$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^\#\s*TYPE\s+(\S+)\s+(\S+)\s*$/) 30 75 105
28 30 $type_for{$1} = $2;
29 30 next;
30 }
31 75 ▶ next if $line =~ /^\s*#/; # HELP and other directives
Branch: 1 branch
BranchTrueFalseTotal
if $line =~ /^\s*#/ 30 45 75
32  
33 # Sample line.
34  
35 # Sample line. Three shapes per the Prometheus spec:
36 # metric_name [labels] value [timestamp]
37 # metric_name value [timestamp]
38 # Prometheus values are always numeric (or the special floats NaN /
39 # +Inf / -Inf), so we anchor the value group to that — without the
40 # numeric anchor, plain English lines like "this is a comment" match
41 # the lenient name+value pattern and become bogus records.
42 45 my ( $name, $labels_str, $value );
43 # A quoted label value may itself contain } (k306).
44 45 ▶ if ( $line =~ /^([a-zA-Z_:][a-zA-Z0-9_:]*)(\{(?:[^"}]|"(?:[^"\\]|\\.)*")*\})?\s+(-?\d+(?:\.\d+)?(?:[eE][-+]?\d+)?|NaN|\+?Inf|-Inf)/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^([a-zA-Z_:][a-zA-Z0-9_:]*)(\{(?:[^"}]|"(?:[^"\\]|\\.)*")*\})?\s+(-?\d+(?:\.\d+)?(?:[eE][-+]?\d+)?|NaN|\+?Inf|-Inf)/) { } 44 1 45
45 44 ( $name, $labels_str, $value ) = ( $1, $2, $3 );
46 }
47 else {
48 # Unparseable — skip rather than croak; partial scrapes survive.
49 1 next;
50 }
51  
52 44 my $labels = $self->_parse_labels($labels_str);
53 44 my $numeric = 0 + $value; # numeric coercion; non-numeric values (NaN,
54 # +Inf) round-trip as 0 / inf in Perl — good
55 # enough for the shape contract.
56  
57 44 ▶ push @records, {
Condition66%2/3
$self->_resolve_type(\%type_for, $name) || $self->_default_type
l!l&&r!l&&!r
3770
MC/DC0%0/2
$self->_resolve_type(\%type_for, $name) || $self->_default_type
$self->_resolve_type(\%type_for, $name) $self->_default_type
Truth table66%2/3
A || B
A= $self->_resolve_type(\%type_for, $name)B= $self->_default_type
ABresult
1X1
011
000
58 name => $name,
59 type => $self->_resolve_type(\%type_for, $name) || $self->_default_type,
60 value => $numeric,
61 labels => $labels,
62 };
63 }
64  
65 21 return \@records;
66 }
67  
68 # Resolve the declared TYPE for a series name. Histograms and summaries
69 # emit TYPE for the base name only — `_bucket`, `_sum`, `_count` (and the
70 # summary's analogous suffixes) inherit it. Look up the most-specific
71 # match first, then walk the name progressively left-to-right.
72 44 ▶sub _resolve_type {
Subroutine _resolve_type: called CC=4 SCAR=13.9
73 44 my ( $self, $type_for, $name ) = @_;
74 44 ▶ return $type_for->{$name} if exists $type_for->{$name};
Branch: 1 branch
BranchTrueFalseTotal
if exists $$type_for{$name} 27 17 44
75 17 my @parts = split /_/, $name;
76 17 ▶ while ( @parts > 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@parts > 1) 20 7 27
77 20 pop @parts;
78 20 my $candidate = join '_', @parts;
79 20 ▶ return $type_for->{$candidate} if exists $type_for->{$candidate};
Branch: 1 branch
BranchTrueFalseTotal
if exists $$type_for{$candidate} 10 10 20
80 }
81 7 return undef;
82 }
83  
84  
85 44 ▶sub _parse_labels {
Subroutine _parse_labels: called CC=6 SCAR=18.0
86 44 my ( $self, $labels_str ) = @_;
87 44 ▶ return {} unless defined $labels_str && length $labels_str;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $labels_str and length $labels_str 20 24 44
Condition66%2/3
defined $labels_str and length $labels_str
!ll&&!rl&&r
20024
MC/DC50%1/2
defined $labels_str and length $labels_str
defined $labels_str length $labels_str
Truth table66%2/3
A and B
A= defined $labels_strB= length $labels_str
ABresult
0X0
100
111
88 # Strip surrounding braces
89 24 $labels_str =~ s/^\{//;
90 24 $labels_str =~ s/\}$//;
91 24 ▶ return {} unless length $labels_str;
Branch: 1 branch
BranchTrueFalseTotal
unless length $labels_str 0 24 24
92  
93 24 my %labels;
94 # name="value" pairs per the exposition format: optional whitespace
95 # around names, '=' and ',', a trailing comma allowed; a quoted value may
96 # hold commas, '}' and the escapes \\ \" \n (vLLM joins its LoRA adapter
97 # list with commas — k306). A malformed rest ends the parse; the pairs
98 # read so far are kept.
99 24 ▶ while ( $labels_str =~ /\G\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*"((?:[^"\\]|\\.)*)"\s*(?:,|\z)/gc ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($labels_str =~ /\G\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*"((?:[^"\\]|\\.)*)"\s*(?:,|\z)/cg) 34 24 58
100 34 my ( $k, $v ) = ( $1, $2 );
101 34 ▶ $v =~ s/\\(.)/$1 eq 'n' ? "\n" : $1/ge;
Branch: 1 branch
BranchTrueFalseTotal
$1 eq 'n' ? : 1 4 5
102 34 $labels{$k} = $v;
103 }
104 24 return \%labels;
105 }
106  
107 4 ▶sub filter_prefix {
Subroutine filter_prefix: called CC=5 SCAR=16.4
Pod documented
108 4 my ( $self, $records, $prefix ) = @_;
109 4 ▶ croak "filter_prefix() requires an ArrayRef of records"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $records eq "ARRAY" 0 4 4
110 unless ref($records) eq 'ARRAY';
111 4 ▶ croak "filter_prefix() requires a string prefix"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $prefix and not ref $prefix 1 3 4
Condition66%2/3
defined $prefix and not ref $prefix
!ll&&!rl&&r
103
MC/DC50%1/2
defined $prefix and not ref $prefix
defined $prefix not ref $prefix
Truth table66%2/3
A and not(B)
A= defined $prefixB= not ref $prefix
ABresult
0X0
100
111
112 unless defined $prefix && !ref($prefix);
113 3 ▶ my @filtered = grep { defined $_->{name} && index( $_->{name}, $prefix ) == 0 } @$records;
Condition66%2/3
defined $$_{'name'} && index($$_{'name'}, $prefix) == 0
!ll&&!rl&&r
013
MC/DC50%1/2
defined $$_{'name'} && index($$_{'name'}, $prefix) == 0
defined $$_{'name'} index($$_{'name'}, $prefix) == 0
Truth table66%2/3
A && B
A= defined $$_{'name'}B= index($$_{'name'}, $prefix) == 0
ABresult
0X0
100
111
114 3 return \@filtered;
115 }
116  
117  
118 15 ▶sub parse_and_filter {
Subroutine parse_and_filter: called CC=6 SCAR=17.9
Pod documented
119 15 my ( $self, $payload, @prefixes ) = @_;
120 15 my $records = $self->parse($payload);
121 15 ▶ return $records unless @prefixes;
Branch: 1 branch
BranchTrueFalseTotal
unless @prefixes 9 6 15
122 6 my @kept;
123 6 PREFIX: for my $r ( @$records ) {
124 25 for my $p ( @prefixes ) {
125 32 ▶ if ( defined $r->{name} && index( $r->{name}, $p ) == 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$r{"name"} and index($$r{"name"}, $p) == 0) 19 13 32
Condition66%2/3
defined $$r{"name"} and index($$r{"name"}, $p) == 0
!ll&&!rl&&r
01319
MC/DC50%1/2
defined $$r{"name"} and index($$r{"name"}, $p) == 0
defined $$r{"name"} index($$r{"name"}, $p) == 0
Truth table66%2/3
A and B
A= defined $$r{"name"}B= index($$r{"name"}, $p) == 0
ABresult
0X0
100
111
126 19 push @kept, $r;
127 19 next PREFIX;
128 }
129 }
130 }
131 6 return \@kept;
132 }
133  
134  
135 35 __PACKAGE__->meta->make_immutable;
136  
137  
138 35 1;
139  
140 __END__
141  
142 =pod
143  
144 =encoding UTF-8
145  
146 =head1 NAME
147  
148 Langertha::Runtime::Metrics - Prometheus text exposition format parser with prefix filter
149  
150 =head1 VERSION
151  
152 version 0.503
153  
154 =head1 SYNOPSIS
155  
156 use Langertha::Runtime::Metrics;
157  
158 my $metrics = Langertha::Runtime::Metrics->new;
159  
160 my $records = $metrics->parse($prometheus_payload);
161  
162 # Filter to engine-specific keys only
163 my $vllm_only = $metrics->filter_prefix($records, 'vllm:');
164  
165 # Same, in one step
166 my $vllm_only = $metrics->parse_and_filter($prometheus_payload, 'vllm:');
167  
168 =head1 DESCRIPTION
169  
170 Parser for the Prometheus text exposition format. Accepts a raw
171 payload string (the body of a C<GET /metrics> response) and returns
172 an ArrayRef of HashRefs with shape:
173  
174 {
175 name => 'vllm:gpu_cache_usage_perc', # metric name (str)
176 type => 'gauge', # counter | gauge | histogram |
177 # summary | untyped
178 value => 0.42, # numeric value
179 labels => { model_name => 'Qwen/Qwen2.5-7B-Instruct' }, # label set
180 # (HashRef, possibly empty)
181 }
182  
183 Only sample lines are returned. C<# HELP> and C<# TYPE> directive lines
184 inform the C<type> field on the following sample(s) but are not emitted
185 on their own.
186  
187 Counter / gauge / untyped lines yield a single record each. Histogram
188 and summary lines yield one record per emitted series (the C<_bucket>,
189 C<_sum>, and C<_count> series that follow the C<# TYPE histogram>
190 directive).
191  
192 The parser is intentionally permissive: malformed lines are skipped
193 with a warning rather than croaking, so a partial scrape (truncated
194 body, comment-only line at EOF) returns the lines it could parse
195 rather than nothing.
196  
197 =head2 Wire contract
198  
199 The exact metric-key shape per engine lives in
200 L<Langertha::Runtime::Metrics::EngineContract>. Use C<filter_prefix> to
201 restrict the parser output to that engine's allowlist before doing
202 anything with the records (logging, OTLP export, etc.) — Prometheus
203 C<process_*> and C<go_*> entries ship from the same /metrics body and
204 are not engine-specific.
205  
206 =head2 parse
207  
208 my $records = $metrics->parse($payload);
209  
210 Parses a Prometheus text-format payload into an ArrayRef of
211 C<< { name, type, value, labels } >> HashRefs. See L</DESCRIPTION> for
212 the exact shape. Malformed lines are skipped, never fatal.
213  
214 =head2 filter_prefix
215  
216 my $vllm = $metrics->filter_prefix($records, 'vllm:');
217 my $sg = $metrics->filter_prefix($records, 'sglang:');
218 my $llama = $metrics->filter_prefix($records, 'llama_');
219  
220 Returns the subset of C<$records> whose C<name> starts with the given
221 prefix. Use to restrict parser output to the engine's allowlist per
222 L<Langertha::Runtime::Metrics::EngineContract>.
223  
224 =head2 parse_and_filter
225  
226 my $vllm = $metrics->parse_and_filter($payload, 'vllm:');
227 my $both = $metrics->parse_and_filter($payload, 'vllm:', 'http:');
228  
229 Convenience wrapper around L</parse> + L</filter_prefix>. Multiple
230 prefixes are OR-ed (a record is kept if it matches B<any> prefix).
231  
232 =head1 SEE ALSO
233  
234 =over 4
235  
236 =item * L<Langertha::Runtime::Metrics::EngineContract> - Per-engine wire contract (allowlist prefixes, URL paths)
237  
238 =item * L<Langertha::Role::Runtime::MetricsPoll> - Async scraper that drives this parser
239  
240 =item * L<Langertha::Runtime::Metrics::OTLP> - Serializes the record shape into an OTLP/HTTP JSON metrics payload
241  
242 =item * L<https://prometheus.io/docs/instrumenting/exposition_formats/> - Prometheus text exposition format spec
243  
244 =back
245  
246 =head1 SUPPORT
247  
248 =head2 Issues
249  
250 Please report bugs and feature requests on GitHub at
251 L<https://github.com/Getty/langertha/issues>.
252  
253 =head2 IRC
254  
255 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
256  
257 =head1 CONTRIBUTING
258  
259 Contributions are welcome! Please fork the repository and submit a pull request.
260  
261 =head1 AUTHOR
262  
263 Torsten Raudssus <getty@cpan.org>
264  
265 =head1 COPYRIGHT AND LICENSE
266  
267 This software is copyright (c) 2026 by Torsten Raudssus L<https://raudssus.de/>.
268  
269 This is free software; you can redistribute it and/or modify it under
270 the same terms as the Perl 5 programming language system itself.
271  
272 =cut
« blib/lib/Langertha/Pricing.pm ↑ Summary blib/lib/Langertha/Metrics.pm »