blib/lib/Algorithm/ToNumberMunger.pm

filter: Statementstmt 90.8% 1037 / 1142 Branchbran 75.5% 583 / 772 Conditioncond 67.7% 237 / 350 MC/DCmcdc 48.3% 100 / 207 Subroutinesub 91.4% 170 / 186 Podpod 100% 5 / 5 totaltotal 80.0% 2132 / 2662 CC 548 SCAR 27.5
CC
548
Cov
82%
_eps_spec
182.0
_build_eps_multi
156.0
_build_eps
42.0
CRAP 15.7
↑ Summary lib/Algorithm/ToNumberMunger.xs »
1 package Algorithm::ToNumberMunger;
2  
3 6 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 6 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 6 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 6 ▶use Carp qw(carp croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 6 ▶use Scalar::Util qw(looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 =head1 NAME
11  
12 Algorithm::ToNumberMunger - Compile declarative specs into closures that munge raw values into numbers.
13  
14 =head1 VERSION
15  
16 Version 0.1.0
17  
18 =cut
19  
20 6 our $VERSION = '0.1.0';
21  
22 # Feature hashing (the 'hash' munger) is a tight per-byte FNV-1a loop with a
23 # 32-bit modular multiply. That is exactly the kind of work XS is good at and
24 # pure Perl is bad at (both for speed and, on a 32-bit perl, for correctness of
25 # the wrap-around), so we compile it in C when we can. Everything else here is a
26 # hash lookup or a couple of flops -- crossing the XS boundary per row would
27 # only make those slower, so they stay pure Perl. If the XS did not build (no
28 # compiler at install time) we fall back to a pure-Perl FNV-1a, which is exact
29 # on a 64-bit perl.
30 6 our $HAVE_XS = 0;
31 6 eval {
32 6 require XSLoader;
33 6 XSLoader::load( __PACKAGE__, $VERSION );
34 6 $HAVE_XS = 1;
35 6 1;
36 };
37  
38 =head1 SYNOPSIS
39  
40 use Algorithm::ToNumberMunger;
41  
42 # one munger from a spec hash
43 my $code = Algorithm::ToNumberMunger->build(
44 { munger => 'enum', map => { GET => 0, POST => 1, PUT => 2 } },
45 );
46 my $n = $code->('POST'); # 1
47  
48 # a whole table of them at once, from a 'field => spec' hash
49 my $by_tag = Algorithm::ToNumberMunger->build_all(
50 \%mungers,
51 );
52 my $row_value = $by_tag->{method}->($raw{method});
53  
54 =head1 DESCRIPTION
55  
56 Many numeric pipelines -- anomaly detectors, feature stores, CSV loaders --
57 want every column to be a number, but the values they are handed are not always
58 numbers to begin with: an HTTP method is a string, a timestamp is a formatted
59 date, a high-cardinality label wants bucketing. An B<input munger> turns such a
60 raw value into a single number. Munging happens on the input side, before a row
61 is stored.
62  
63 Mungers are declared as a plain data spec -- a hash naming a built-in munger and
64 carrying that munger's parameters -- so a table of them can be read straight out
65 of JSON or a config file:
66  
67 {
68 "method": { "munger": "enum", "map": { "GET": 0, "POST": 1 } },
69 "bytes": { "munger": "log", "offset": 1 },
70 "label": { "munger": "hash", "buckets": 1024 }
71 }
72  
73 B<Any field without an entry is raw> and is passed through unchanged; this module
74 is only concerned with fields that name a munger.
75  
76 This class does not read or write files. It B<compiles> a spec into a closure
77 that maps one raw value to one number, so a caller can build its mungers once
78 from configuration and then apply them per row with no re-parsing. All
79 configuration errors are caught at build time; the returned closure only croaks
80 on genuinely un-mungeable I<input>.
81  
82 =head1 CLASS METHODS
83  
84 =head2 build
85  
86 my $code = ...->build( \%spec );
87 my $code = ...->build( \%spec, $tag_name ); # $tag_name only sharpens errors
88  
89 Compile a single munger spec into a coderef. C<%spec> must contain a C<munger>
90 key naming one of the L</BUILT-IN MUNGERS>; the remaining keys are that munger's
91 parameters. Croaks on an unknown munger name or an invalid parameter set. The
92 optional second argument is only used to make error messages point at a tag.
93  
94 =cut
95  
96 # name => builder. Each builder validates its slice of the spec up front and
97 # returns the per-value closure. Keeping them in a table (rather than a big
98 # if/elsif) is what makes known_mungers() and has_munger() cheap and honest.
99 6 my %BUILDERS = (
100 enum => \&_build_enum,
101 frozen_freq_map => \&_build_frozen_freq_map,
102 bool => \&_build_bool,
103 length => \&_build_length,
104 entropy => \&_build_entropy,
105 ngram => \&_build_ngram,
106 char => \&_build_char,
107 run => \&_build_run,
108 count => \&_build_count,
109 match => \&_build_match,
110 bucket => \&_build_bucket,
111 quantile => \&_build_quantile,
112 scale => \&_build_scale,
113 zscore => \&_build_zscore,
114 log => \&_build_log,
115 clamp => \&_build_clamp,
116 num => \&_build_num,
117 bit => \&_build_bit,
118 ip_class => \&_build_ip_class,
119 cidr => \&_build_cidr,
120 geoip_country => \&_build_geoip_country,
121 datetime => \&_build_datetime,
122 hash => \&_build_hash,
123 chain => \&_build_chain,
124 eps => \&_build_eps,
125 mgcp_enum => \&_build_mgcp_enum,
126 );
127  
128 # Status-class mungers (http_enum, smtp_enum, sip_enum, ...) are one transform
129 # -- collapse a numeric reply code to its leading digit, int(code/div), with a
130 # divisor of 100 (10 for gemini's two-digit codes) -- differing only in which
131 # range 'strict' accepts. Register them all from this table so a new protocol
132 # is a single line and they can never drift apart. mgcp_enum is deliberately
133 # NOT a row here: its strict range has a hole (8xx exists, 6xx/7xx do not),
134 # which a single [lo, hi] cannot express, so it has its own builder below.
135 6 my %STATUS_PROTO = (
136 http => [ 100, 599 ], # 1xx-5xx
137 smtp => [ 200, 599 ], # 2xx-5xx; SMTP never issues 1yz in practice
138 sip => [ 100, 699 ], # 1xx-6xx; SIP adds a 6xx global-failure class
139 ftp => [ 100, 599 ], # 1xx-5xx FTP reply codes
140 rtsp => [ 100, 599 ], # RTSP (RFC 2326) reuses HTTP's status scheme
141 nntp => [ 100, 599 ], # 1xx-5xx NNTP (RFC 3977), SMTP-convention codes
142 dict => [ 100, 599 ], # DICT (RFC 2229) uses SMTP-style codes
143 gemini => [ 10, 69, 10 ], # two-digit codes, 1x-6x; class = int(code/10)
144 );
145 6 for my $proto ( keys %STATUS_PROTO ) {
146 48 my ( $lo, $hi, $div ) = @{ $STATUS_PROTO{$proto} };
147 48 ▶ $div = 100 unless defined $div;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $div 42 6 48
148 $BUILDERS{"${proto}_enum"}
149 16 ▶ = sub { _status_class_munger( $proto, $lo, $hi, $div, @_ ) };
Subroutine __ANON__: called CC=1 SCAR=0.0
150 }
151  
152 # ratio and combine consume several source fields at once, so they are only
153 # buildable through compile()'s multi-input form ('from' as an arrayref) -- a
154 # scalar build can never hand them more than one value. Registering a stub
155 # keeps known_mungers() honest and turns "used it as a scalar munger" into a
156 # pointed error instead of an unknown-munger one.
157 6 for my $name (qw(ratio combine)) {
158 2 ▶ $BUILDERS{$name} = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
159 2 my ( $spec, $where ) = @_;
160 2 croak "$name munger$where combines several inputs; it is only usable "
161 . "via compile() with 'from' as an arrayref of source fields";
162 12 };
163 }
164  
165 286 ▶sub build {
Subroutine build: called CC=6 SCAR=18.6
Pod documented
166 286 my ( $class, $spec, $tag ) = @_;
167 286 ▶ my $where = defined $tag ? " for tag '$tag'" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $tag ? : 11 275 286
168  
169 286 ▶ croak "munger spec$where must be a hashref"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $spec eq "HASH" 0 286 286
170 unless ref $spec eq 'HASH';
171  
172 286 my $name = $spec->{munger};
173 286 ▶ croak "munger spec$where has no 'munger' name"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 0 286 286
Condition33%1/3
defined $name and length $name
!ll&&!rl&&r
00286
MC/DC0%0/2
defined $name and length $name
defined $name length $name
Truth table33%1/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
174 unless defined $name && length $name;
175  
176 286 ▶ my $builder = $BUILDERS{$name}
Branch: 1 branch
BranchTrueFalseTotal
my $builder = $BUILDERS{$name} or croak("unknown munger '${name}'$where (known: " . join(", ", $class->known_mungers) . ')') 285 1 286
177 or croak "unknown munger '$name'$where (known: " . join( ', ', $class->known_mungers ) . ')';
178  
179 285 return $builder->( $spec, $where );
180 } ## end sub build
181  
182 =head2 build_all
183  
184 my $by_tag = ...->build_all( $info->{mungers} );
185  
186 Compile a whole C<mungers> hash (tag name => spec) into a hash of tag name =>
187 coderef. A false/absent argument yields an empty hashref (every tag is raw).
188 Croaks if any spec is invalid, naming the offending tag.
189  
190 =cut
191  
192 2 ▶sub build_all {
Subroutine build_all: called CC=4 SCAR=13.9
Pod documented
193 2 my ( $class, $mungers ) = @_;
194 2 ▶ return {} unless $mungers;
Branch: 1 branch
BranchTrueFalseTotal
unless $mungers 1 1 2
195  
196 1 ▶ croak "'mungers' must be a hashref"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $mungers eq "HASH" 0 1 1
197 unless ref $mungers eq 'HASH';
198  
199 1 my %by_tag;
200 1 for my $tag ( keys %$mungers ) {
201 2 $by_tag{$tag} = $class->build( $mungers->{$tag}, $tag );
202 }
203 1 return \%by_tag;
204 } ## end sub build_all
205  
206 =head2 compile
207  
208 my $plan = ...->compile( tags => \@tags, mungers => $info->{mungers} );
209 my $row = $plan->apply_named( \%named_input ); # numbers, in tags order
210  
211 Compile a set's C<tags> and (optional) C<mungers> into a B<plan> object that maps
212 one input record to a fully-numeric row in tag order. Unlike L</build_all> (which
213 just compiles each spec in isolation), C<compile> understands the whole set:
214  
215 =over 4
216  
217 =item * a scalar munger, keyed by its output tag, fills that one column; its
218 input is read from the tag's own name, or from C<< from => 'other' >> to alias a
219 source field;
220  
221 =item * an B<expanding> munger, keyed by any label and carrying C<< into =>
222 [tag, ...] >>, reads one source (C<from>, defaulting to the label) and fills
223 several columns at once -- this is how a single timestamp becomes both a
224 C<sin>/C<cos> pair without the two ever drifting apart (see L</datetime>);
225  
226 =item * a B<combining> munger, keyed by its output tag and carrying a C<from>
227 B<list> (C<< from => ['bytes_out', 'bytes_in'] >>), reads several source
228 fields and fills that one column -- this is how a ratio becomes a single
229 feature without precomputing it upstream (see L</ratio> and L</combine>). The
230 sources are raw input fields, not other (possibly munged) columns;
231  
232 =item * every remaining tag is B<raw> and passed through unchanged.
233  
234 =back
235  
236 Coverage is validated up front: C<compile> croaks if two mungers write the same
237 column, if an C<into> names a column not in C<tags>, if a munger key is neither a
238 tag nor an expander, if an expander's output count does not match its C<into>,
239 or if a C<from> list is given to a munger that cannot combine inputs. The
240 returned plan has two methods, both returning an arrayref of numbers in C<tags>
241 order: C<apply_named(\%hash)> (keyed by field name, the only form that supports
242 expanders and combiners) and C<apply_positional(\@row)> (positional; croaks if
243 the set has any expanding or combining munger, since a shared or combined
244 source cannot be expressed by position).
245  
246 =cut
247  
248 # name => builder returning ($list_returning_code, $arity), for the mungers that
249 # can fan one input out into several columns via 'into'.
250 6 my %MULTI_BUILDERS = (
251 datetime => \&_build_datetime_multi,
252 eps => \&_build_eps_multi,
253 chain => \&_build_chain_multi,
254 );
255  
256 9 ▶sub _build_multi {
Subroutine _build_multi: called CC=4 SCAR=14.5
257 9 my ( $class, $spec, $where ) = @_;
258 9 my $name = $spec->{munger};
259 9 ▶ croak "munger spec$where has no 'munger' name"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 0 9 9
Condition33%1/3
defined $name and length $name
!ll&&!rl&&r
009
MC/DC0%0/2
defined $name and length $name
defined $name length $name
Truth table33%1/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
260 unless defined $name && length $name;
261 9 ▶ my $builder = $MULTI_BUILDERS{$name}
Branch: 1 branch
BranchTrueFalseTotal
my $builder = $MULTI_BUILDERS{$name} or croak("munger '${name}'$where does not support multiple outputs " . q[('into'); only these do: ] . join(", ", sort(keys %MULTI_BUILDERS))) 8 1 9
262 or croak "munger '$name'$where does not support multiple outputs "
263 . "('into'); only these do: "
264 . join( ', ', sort keys %MULTI_BUILDERS );
265 8 return $builder->( $spec, $where );
266 } ## end sub _build_multi
267  
268 # name => builder returning the N-input closure, for the mungers that combine
269 # several source fields ('from' as an arrayref) into one column. The builder is
270 # handed the source count so arity errors surface at compile time.
271 6 my %COMBINE_BUILDERS = (
272 ratio => \&_build_ratio,
273 combine => \&_build_combine_op,
274 );
275  
276 14 ▶sub _build_combine {
Subroutine _build_combine: called CC=4 SCAR=14.5
277 14 my ( $class, $spec, $where, $nsrc ) = @_;
278 14 my $name = $spec->{munger};
279 14 ▶ croak "munger spec$where has no 'munger' name"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 0 14 14
Condition33%1/3
defined $name and length $name
!ll&&!rl&&r
0014
MC/DC0%0/2
defined $name and length $name
defined $name length $name
Truth table33%1/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
280 unless defined $name && length $name;
281 14 ▶ my $builder = $COMBINE_BUILDERS{$name}
Branch: 1 branch
BranchTrueFalseTotal
my $builder = $COMBINE_BUILDERS{$name} or croak("munger '${name}'$where does not support multiple inputs " . q[(a 'from' list); only these do: ] . join(", ", sort(keys %COMBINE_BUILDERS))) 13 1 14
282 or croak "munger '$name'$where does not support multiple inputs "
283 . "(a 'from' list); only these do: "
284 . join( ', ', sort keys %COMBINE_BUILDERS );
285 13 return $builder->( $spec, $where, $nsrc );
286 } ## end sub _build_combine
287  
288 25 ▶sub compile {
Subroutine compile: called CC=22 SCAR=31.3
Pod documented
289 25 my ( $class, %args ) = @_;
290  
291 25 my $tags = $args{tags};
292 25 ▶ croak "compile requires a non-empty 'tags' arrayref"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $tags eq "ARRAY" and @$tags 0 25 25
Condition33%1/3
ref $tags eq "ARRAY" and @$tags
!ll&&!rl&&r
0025
MC/DC0%0/2
ref $tags eq "ARRAY" and @$tags
ref $tags eq "ARRAY" @$tags
Truth table33%1/3
A and B
A= ref $tags eq "ARRAY"B= @$tags
ABresult
0X0
100
111
293 unless ref $tags eq 'ARRAY' && @$tags;
294 25 ▶ my $mungers = $args{mungers} || {};
Condition100%2/2
$args{'mungers'} || {}
l!l
241
MC/DC100%1/1
$args{'mungers'} || {}
$args{'mungers'}
Truth table100%2/2
A
A= $args{'mungers'}
Aresult
11
00
295 25 ▶ croak "compile: 'mungers' must be a hashref"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $mungers eq "HASH" 0 25 25
296 unless ref $mungers eq 'HASH';
297  
298 25 my %pos;
299 25 for my $i ( 0 .. $#$tags ) {
300 croak "compile: duplicate tag '$tags->[$i]'"
301 41 ▶ if exists $pos{ $tags->[$i] };
Branch: 1 branch
BranchTrueFalseTotal
if exists $pos{$tags->[$i]} 0 41 41
302 41 $pos{ $tags->[$i] } = $i;
303 }
304  
305 25 my ( @scalar, @expand, @combine, %claimed );
306 24 ▶ my $claim = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
307 24 my ( $tag, $by ) = @_;
308 croak "munger '$by' targets unknown column '$tag'"
309 24 ▶ unless exists $pos{$tag};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $pos{$tag} 1 23 24
310 croak "two mungers write column '$tag'"
311 23 ▶ if $claimed{$tag}++;
Branch: 1 branch
BranchTrueFalseTotal
if $claimed{$tag}++ 1 22 23
312 25 };
313  
314 25 for my $key ( sort keys %$mungers ) {
315 32 my $spec = $mungers->{$key};
316 32 ▶ croak "munger '$key' spec must be a hashref"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $spec eq "HASH" 0 32 32
317 unless ref $spec eq 'HASH';
318 32 ▶ my $from = defined $spec->{from} ? $spec->{from} : $key;
Branch: 1 branch
BranchTrueFalseTotal
defined $spec->{'from'} ? : 24 8 32
319  
320 32 ▶ if ( ref $from eq 'ARRAY' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $from eq 'ARRAY') { } 17 15 32
elsif (defined $spec->{'into'}) { } 9 6 15
321 17 ▶ croak "munger '$key': a 'from' list needs at least 2 source fields"
Branch: 1 branch
BranchTrueFalseTotal
unless @$from >= 2 1 16 17
322 unless @$from >= 2;
323 croak "munger '$key': 'into' cannot be combined with a 'from' list"
324 16 ▶ if defined $spec->{into};
Branch: 1 branch
BranchTrueFalseTotal
if defined $spec->{"into"} 1 15 16
325 croak "munger '$key' is not a declared tag and has no 'into'"
326 15 ▶ unless exists $pos{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $pos{$key} 1 14 15
327 14 my $code = $class->_build_combine( $spec, " for '$key'", scalar @$from );
328 9 $claim->( $key, $key );
329 9 push @combine, { tag => $key, from => [@$from], code => $code };
330 } elsif ( defined $spec->{into} ) {
331 9 my $into = $spec->{into};
332 9 ▶ croak "munger '$key': 'into' must be a non-empty arrayref"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $into eq "ARRAY" and @$into 0 9 9
Condition33%1/3
ref $into eq "ARRAY" and @$into
!ll&&!rl&&r
009
MC/DC0%0/2
ref $into eq "ARRAY" and @$into
ref $into eq "ARRAY" @$into
Truth table33%1/3
A and B
A= ref $into eq "ARRAY"B= @$into
ABresult
0X0
100
111
333 unless ref $into eq 'ARRAY' && @$into;
334 9 my ( $code, $arity ) = $class->_build_multi( $spec, " for '$key'" );
335 7 ▶ croak "munger '$key' produces $arity value(s) but 'into' lists " . scalar(@$into)
Branch: 1 branch
BranchTrueFalseTotal
unless $arity == @$into 1 6 7
336 unless $arity == @$into;
337 6 $claim->( $_, $key ) for @$into;
338 5 push @expand, { from => $from, into => [@$into], code => $code };
339 } else {
340 croak "munger '$key' is not a declared tag and has no 'into'"
341 6 ▶ unless exists $pos{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $pos{$key} 1 5 6
342 5 $claim->( $key, $key );
343 4 push @scalar, { tag => $key, from => $from, code => $class->build( $spec, $key ) };
344 }
345 } ## end for my $key ( sort keys %$mungers )
346  
347 11 for my $tag (@$tags) {
348 push @scalar, { tag => $tag, from => $tag, code => undef }
349 26 ▶ unless $claimed{$tag};
Branch: 1 branch
BranchTrueFalseTotal
unless $claimed{$tag} 5 21 26
350 }
351  
352 11 return bless {
353 tags => [@$tags],
354 pos => \%pos,
355 scalar => \@scalar,
356 expand => \@expand,
357 combine => \@combine,
358 },
359 "${class}::Plan";
360 } ## end sub compile
361  
362 =head2 known_mungers
363  
364 my @names = ...->known_mungers;
365  
366 The sorted list of built-in munger names this version understands.
367  
368 =head2 has_munger
369  
370 if ( ...->has_munger('enum') ) { ... }
371  
372 True if the named munger is built in.
373  
374 =cut
375  
376 2 ▶sub known_mungers { my @names = sort keys %BUILDERS; return @names }
Subroutine known_mungers: called CC=1 SCAR=0.0
Pod documented
377 5 ▶sub has_munger { return exists $BUILDERS{ $_[1] } }
Subroutine has_munger: called CC=1 SCAR=0.0
Pod documented
378  
379 =head1 BUILT-IN MUNGERS
380  
381 Every munger returns a plain number and, where the input cannot be interpreted,
382 croaks -- the Writer would reject a non-numeric field anyway, so failing at the
383 munger gives a better message. Parameters are validated when the munger is
384 built, not per row.
385  
386 =head2 enum
387  
388 { munger => 'enum', map => { GET => 0, POST => 1 }, default => -1 }
389  
390 Categorical string to number via an explicit C<map>. All map values must be
391 numeric. Without a C<default>, an unmapped input croaks; with one, unmapped
392 inputs (including C<undef>) yield the default.
393  
394 =cut
395  
396 4 ▶sub _build_enum {
Subroutine _build_enum: called CC=7 SCAR=20.1
397 4 my ( $spec, $where ) = @_;
398  
399 4 my $map = $spec->{map};
400 4 ▶ croak "enum munger$where requires a 'map' hashref"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $map eq "HASH" 0 4 4
401 unless ref $map eq 'HASH';
402  
403 4 for my $k ( keys %$map ) {
404 croak "enum munger$where: map value for '$k' ('"
405 . ( defined $map->{$k} ? $map->{$k} : 'undef' )
406 . "') is not numeric"
407 7 ▶ unless looks_like_number( $map->{$k} );
Branch: 2 branches
BranchTrueFalseTotal
unless &looks_like_number($map->{$k}) 0 7 7
defined $map->{$k} ? : 0 0 0
408 }
409  
410 4 my $has_default = exists $spec->{default};
411 4 my $default = $spec->{default};
412 4 ▶ croak "enum munger$where: 'default' must be numeric"
Branch: 1 branch
BranchTrueFalseTotal
if $has_default and not &looks_like_number($default) 0 4 4
Condition66%2/3
$has_default and not &looks_like_number($default)
!ll&&!rl&&r
310
MC/DC0%0/2
$has_default and not &looks_like_number($default)
$has_default not &looks_like_number($default)
Truth table66%2/3
A and not(B)
A= $has_defaultB= not &looks_like_number($default)
ABresult
0X0
100
111
413 if $has_default && !looks_like_number($default);
414  
415 # Copy so a later edit of the caller's spec cannot mutate a live munger.
416 4 my %m = %$map;
417 7 ▶ return sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
418 7 my ($v) = @_;
419 7 ▶ return $m{$v} if defined $v && exists $m{$v};
Branch: 1 branch
BranchTrueFalseTotal
if defined $v and exists $m{$v} 4 3 7
Condition100%3/3
defined $v and exists $m{$v}
!ll&&!rl&&r
124
MC/DC100%2/2
defined $v and exists $m{$v}
defined $v exists $m{$v}
Truth table100%3/3
A and B
A= defined $vB= exists $m{$v}
ABresult
0X0
100
111
420 3 ▶ return $default if $has_default;
Branch: 1 branch
BranchTrueFalseTotal
if $has_default 2 1 3
421 1 ▶ croak "enum munger$where: no mapping for '" . ( defined $v ? $v : 'undef' ) . "'";
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 1 0 1
422 4 };
423 } ## end sub _build_enum
424  
425 =head2 frozen_freq_map
426  
427 { munger => 'frozen_freq_map', counts => { jpg => 40213, exe => 12, scr => 3 },
428 total => 67560 }
429 # defaults: mode => 'neg_log_prob', smoothing => 1, unseen => 'rare'
430  
431 Frequency-encoding from a B<precomputed, frozen> count table: the rarer a value
432 was when the table was built, the more anomalous it scores. This is C<enum>'s
433 cousin -- a value-to-number map -- except the numbers are derived from observed
434 C<counts> rather than hand-authored, with the smoothing and unseen-value policy
435 that "rare = interesting" needs. It stays a stateless munger: the table is
436 computed offline and shipped in C<info.json>; this class only I<applies> it.
437  
438 C<counts> maps each value to how many times it was seen. C<total> is the overall
439 observation count; it defaults to the sum of C<counts>, but may be given
440 explicitly and larger so you can B<prune the long tail> out of C<counts> while
441 still computing correct probabilities. The emitted number depends on C<mode>:
442  
443 =over 4
444  
445 =item * C<neg_log_prob> (default) - self-information C<-ln(prob)>: rare values
446 score high, common ones low. This is the axis "rare = interesting" describes and
447 what an Isolation Forest splits on most naturally.
448  
449 =item * C<freq> - the probability itself, C<(count + smoothing) / denom>.
450  
451 =item * C<log_count> - C<ln(1 + count)>, the count with its heavy tail tamed.
452  
453 =item * C<count> - the raw count.
454  
455 =back
456  
457 Probabilities use add-one style C<smoothing> (default C<1>), treating "unseen" as
458 one aggregate bucket: C<prob(v) = (count + smoothing) / (total + smoothing*(V+1))>
459 where C<V> is the number of listed values. C<unseen> controls what a value absent
460 from the table maps to -- C<'rare'> (default) emits that value under the current
461 mode as if it had been seen zero times (for C<neg_log_prob>/C<freq> this is the
462 smoothed unseen bucket, for C<count>/C<log_count> it is C<0>), or a number to
463 force a fixed default. Because an unseen value is usually the very thing you are
464 hunting, mapping it to "maximally rare" rather than erroring is the point.
465  
466 C<frozen_freq_map> only suits B<bounded, moderate-cardinality> columns (extensions,
467 vendor classes, named pipes, keyboard layouts, link addresses): the table lives
468 in C<info.json>, so a huge one bloats every read -- building one past
469 C<$Algorithm::ToNumberMunger::FROZEN_FREQ_MAP_WARN_KEYS>
470 values (default 10000) warns. For unbounded cardinality (JA3, full user-agents)
471 use L</hash> instead, which needs no table but keeps only decorrelation, not
472 commonness.
473  
474 =cut
475  
476 # name => 1 for the recognized frozen_freq_map output modes.
477 6 my %FREQ_MODE = map { $_ => 1 } qw(neg_log_prob freq log_count count);
478  
479 # Building a table larger than this warns: info.json ships the whole map, so a
480 # high-cardinality column belongs in the 'hash' munger instead.
481 6 our $FROZEN_FREQ_MAP_WARN_KEYS = 10_000;
482  
483 10 ▶sub _build_frozen_freq_map {
Subroutine _build_frozen_freq_map: called CC=23 SCAR=32.3
484 10 my ( $spec, $where ) = @_;
485  
486 10 my $counts = $spec->{counts};
487 10 ▶ croak "frozen_freq_map munger$where requires a non-empty 'counts' hashref"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $counts eq "HASH" and %$counts 1 9 10
Condition66%2/3
ref $counts eq "HASH" and %$counts
!ll&&!rl&&r
019
MC/DC50%1/2
ref $counts eq "HASH" and %$counts
ref $counts eq "HASH" %$counts
Truth table66%2/3
A and B
A= ref $counts eq "HASH"B= %$counts
ABresult
0X0
100
111
488 unless ref $counts eq 'HASH' && %$counts;
489  
490 9 my $sum = 0;
491 9 for my $k ( keys %$counts ) {
492 13 my $c = $counts->{$k};
493 13 ▶ croak "frozen_freq_map munger$where: count for '$k' ('"
Branch: 2 branches
BranchTrueFalseTotal
unless &looks_like_number($c) and $c >= 0 0 13 13
defined $c ? : 0 0 0
Condition33%1/3
&looks_like_number($c) and $c >= 0
!ll&&!rl&&r
0013
MC/DC0%0/2
&looks_like_number($c) and $c >= 0
&looks_like_number($c) $c >= 0
Truth table33%1/3
A and B
A= &looks_like_number($c)B= $c >= 0
ABresult
0X0
100
111
494 . ( defined $c ? $c : 'undef' )
495 . "') is not a non-negative number"
496 unless looks_like_number($c) && $c >= 0;
497 13 $sum += $c;
498 }
499  
500 9 my $V = keys %$counts;
501 9 ▶ carp "frozen_freq_map munger$where: 'counts' has $V keys; a table this large bloats "
Branch: 1 branch
BranchTrueFalseTotal
if $V > $Algorithm::ToNumberMunger::FROZEN_FREQ_MAP_WARN_KEYS 1 8 9
502 . "info.json -- consider the 'hash' munger for unbounded cardinality"
503 if $V > $FROZEN_FREQ_MAP_WARN_KEYS;
504  
505 9 ▶ my $total = defined $spec->{total} ? $spec->{total} : $sum;
Branch: 1 branch
BranchTrueFalseTotal
defined $spec->{'total'} ? : 2 7 9
506 9 ▶ croak "frozen_freq_map munger$where: 'total' must be numeric"
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($total) 0 9 9
507 unless looks_like_number($total);
508 9 ▶ croak "frozen_freq_map munger$where: 'total' ($total) must be >= sum of counts ($sum)"
Branch: 1 branch
BranchTrueFalseTotal
if $total < $sum 1 8 9
509 if $total < $sum;
510  
511 8 ▶ my $mode = defined $spec->{mode} ? $spec->{mode} : 'neg_log_prob';
Branch: 1 branch
BranchTrueFalseTotal
defined $spec->{'mode'} ? : 5 3 8
512 croak "frozen_freq_map munger$where: unknown mode '$mode' (known: " . join( ', ', sort keys %FREQ_MODE ) . ')'
513 8 ▶ unless $FREQ_MODE{$mode};
Branch: 1 branch
BranchTrueFalseTotal
unless $FREQ_MODE{$mode} 1 7 8
514  
515 7 ▶ my $s = defined $spec->{smoothing} ? $spec->{smoothing} : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $spec->{'smoothing'} ? : 2 5 7
516 7 ▶ croak "frozen_freq_map munger$where: 'smoothing' must be a non-negative number"
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($s) and $s >= 0 0 7 7
Condition33%1/3
&looks_like_number($s) and $s >= 0
!ll&&!rl&&r
007
MC/DC0%0/2
&looks_like_number($s) and $s >= 0
&looks_like_number($s) $s >= 0
Truth table33%1/3
A and B
A= &looks_like_number($s)B= $s >= 0
ABresult
0X0
100
111
517 unless looks_like_number($s) && $s >= 0;
518  
519 7 ▶ my $unseen = defined $spec->{unseen} ? $spec->{unseen} : 'rare';
Branch: 1 branch
BranchTrueFalseTotal
defined $spec->{'unseen'} ? : 1 6 7
520 7 ▶ croak "frozen_freq_map munger$where: 'unseen' must be 'rare' or a number"
Branch: 1 branch
BranchTrueFalseTotal
unless $unseen eq "rare" or &looks_like_number($unseen) 0 7 7
Condition66%2/3
$unseen eq "rare" or &looks_like_number($unseen)
l!l&&r!l&&!r
610
MC/DC0%0/2
$unseen eq "rare" or &looks_like_number($unseen)
$unseen eq "rare" &looks_like_number($unseen)
Truth table66%2/3
A or B
A= $unseen eq "rare"B= &looks_like_number($unseen)
ABresult
1X1
011
000
521 unless $unseen eq 'rare' || looks_like_number($unseen);
522  
523 # An unseen value under neg_log_prob has probability s/denom; with no
524 # smoothing that is 0 and -ln(0) is infinite, which would poison the column.
525 # Refuse to build rather than emit inf.
526 7 ▶ croak "frozen_freq_map munger$where: mode 'neg_log_prob' with unseen => 'rare' needs "
Branch: 1 branch
BranchTrueFalseTotal
if $mode eq "neg_log_prob" and $unseen eq "rare" and $s == 0 1 6 7
Condition83%5/6
$mode eq "neg_log_prob" and $unseen eq "rare" and $s == 0
!ll&&!rl&&r
421
$mode eq "neg_log_prob" and $unseen eq "rare"
!ll&&!rl&&r
403
MC/DC66%2/3
$mode eq "neg_log_prob" and $unseen eq "rare" and $s == 0
$mode eq "neg_log_prob" $unseen eq "rare" $s == 0
Truth table75%3/4
A and B and C
A= $mode eq "neg_log_prob"B= $unseen eq "rare"C= $s == 0
ABCresult
0XX0
10X0
1100
1111
527 . "smoothing > 0 (an unseen value would otherwise be infinitely surprising)"
528 if $mode eq 'neg_log_prob' && $unseen eq 'rare' && $s == 0;
529  
530 # Smoothed-probability denominator, treating "unseen" as one extra bucket.
531 6 my $denom = $total + $s * ( $V + 1 );
532  
533 # raw count -> emitted number under the chosen mode.
534 15 ▶ my $emit_for = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
535 15 my ($c) = @_;
536 15 ▶ return $c if $mode eq 'count';
Branch: 1 branch
BranchTrueFalseTotal
if $mode eq "count" 7 8 15
537 8 ▶ return log( 1 + $c ) if $mode eq 'log_count';
Branch: 1 branch
BranchTrueFalseTotal
if $mode eq "log_count" 0 8 8
538 8 my $p = ( $c + $s ) / $denom;
539 8 ▶ return $p if $mode eq 'freq';
Branch: 1 branch
BranchTrueFalseTotal
if $mode eq "freq" 3 5 8
540 5 return -log($p); # neg_log_prob
541 6 };
542  
543 6 my %emit = map { $_ => $emit_for->( $counts->{$_} ) } keys %$counts;
544 6 ▶ my $unseen_value = $unseen eq 'rare' ? $emit_for->(0) : $unseen;
Branch: 1 branch
BranchTrueFalseTotal
$unseen eq 'rare' ? : 5 1 6
545  
546 13 ▶ return sub {
Subroutine __ANON__: called CC=3 SCAR=11.1
547 13 my ($v) = @_;
548 13 ▶ return defined $v && exists $emit{$v} ? $emit{$v} : $unseen_value;
Branch: 1 branch
BranchTrueFalseTotal
defined $v && exists $emit{$v} ? : 7 6 13
Condition66%2/3
defined $v and exists $emit{$v}
!ll&&!rl&&r
067
MC/DC50%1/2
defined $v and exists $emit{$v}
defined $v exists $emit{$v}
Truth table66%2/3
A and B
A= defined $vB= exists $emit{$v}
ABresult
0X0
100
111
549 6 };
550 } ## end sub _build_frozen_freq_map
551  
552 =head2 http_enum
553  
554 { munger => 'http_enum' }
555 { munger => 'http_enum', strict => 1 }
556  
557 Collapse an HTTP status code to its class: C<1xx> to C<1>, C<2xx> to C<2>, C<3xx>
558 to C<3>, and so on (i.e. C<int(code / 100)>). This is the usual bucketing for an
559 HTTP status column -- the forest cares far more about "was this a 4xx vs a 2xx"
560 than about C<403> vs C<404>, and it keeps the feature low-cardinality without
561 having to spell out every code in an C<enum> C<map>. The input must be numeric.
562  
563 By default any numeric input is bucketed, so a bogus C<700> would quietly become
564 C<7>. With a true C<strict>, inputs outside the valid HTTP status range
565 (C<100>-C<599>) croak instead, so a malformed code is caught at write time rather
566 than smuggled into the model as a spurious class.
567  
568 =head2 smtp_enum
569  
570 { munger => 'smtp_enum' }
571 { munger => 'smtp_enum', strict => 1 }
572  
573 The SMTP counterpart of L</http_enum>: collapse an SMTP reply code to its leading
574 digit (C<int(code / 100)>), since that digit I<is> the reply's meaning -- C<2yz>
575 completion, C<3yz> intermediate, C<4yz> transient failure, C<5yz> permanent
576 failure. As with C<http_enum> this keeps the column low-cardinality and lets the
577 forest weigh "a 5xx where a 2xx was expected" without enumerating every code.
578  
579 With a true C<strict>, inputs outside the valid SMTP reply range (C<200>-C<599>)
580 croak. SMTP never issues C<1yz> replies in practice (no command permits a
581 positive-preliminary reply), so the strict floor is C<200> rather than
582 C<http_enum>'s C<100>.
583  
584 =head2 sip_enum
585  
586 { munger => 'sip_enum' }
587 { munger => 'sip_enum', strict => 1 }
588  
589 The SIP counterpart of L</http_enum>: collapse a SIP status code to its leading
590 digit (C<int(code / 100)>). SIP reuses HTTP's class scheme but adds a sixth
591 class -- C<1xx> provisional, C<2xx> success, C<3xx> redirection, C<4xx> client
592 error, C<5xx> server error, C<6xx> global failure.
593  
594 With a true C<strict>, inputs outside the valid SIP status range (C<100>-C<699>)
595 croak. The ceiling is C<699> rather than C<http_enum>'s C<599> precisely because
596 of that C<6xx> global-failure class.
597  
598 =head2 ftp_enum
599  
600 { munger => 'ftp_enum' }
601 { munger => 'ftp_enum', strict => 1 }
602  
603 The FTP counterpart of L</http_enum>, for FTP reply codes: C<int(code / 100)>,
604 bucketing into C<1yz>-C<5yz>. With a true C<strict>, inputs outside C<100>-C<599>
605 croak.
606  
607 =head2 rtsp_enum
608  
609 { munger => 'rtsp_enum' }
610 { munger => 'rtsp_enum', strict => 1 }
611  
612 The RTSP counterpart of L</http_enum>. RTSP (RFC 2326) deliberately reuses
613 HTTP's status scheme, so codes collapse to their leading digit the same way.
614 With a true C<strict>, inputs outside C<100>-C<599> croak.
615  
616 =head2 nntp_enum
617  
618 { munger => 'nntp_enum' }
619 { munger => 'nntp_enum', strict => 1 }
620  
621 The NNTP counterpart of L</http_enum>, for NNTP (RFC 3977) reply codes, which
622 follow the SMTP convention -- C<1xx> informational, C<2xx> success, C<3xx>
623 send-more-input, C<4xx> transient failure, C<5xx> permanent failure. Unlike
624 SMTP, NNTP does issue C<1xx> replies (help text, capability lists), so the
625 strict floor is C<100> rather than C<smtp_enum>'s C<200>. With a true
626 C<strict>, inputs outside C<100>-C<599> croak.
627  
628 =head2 dict_enum
629  
630 { munger => 'dict_enum' }
631 { munger => 'dict_enum', strict => 1 }
632  
633 The DICT counterpart of L</http_enum>, for DICT protocol (RFC 2229) status
634 codes, which use the SMTP-style code classes. With a true C<strict>, inputs
635 outside C<100>-C<599> croak.
636  
637 =head2 gemini_enum
638  
639 { munger => 'gemini_enum' }
640 { munger => 'gemini_enum', strict => 1 }
641  
642 Like L</http_enum> but for the Gemini protocol, whose status codes are B<two>
643 digits -- C<1x> input expected, C<2x> success, C<3x> redirect, C<4x> temporary
644 failure, C<5x> permanent failure, C<6x> client certificate required -- so the
645 class is C<int(code / 10)>. With a true C<strict>, inputs outside C<10>-C<69>
646 croak.
647  
648 =cut
649  
650 # Shared closure for the status-class mungers registered from %STATUS_PROTO.
651 16 ▶sub _status_class_munger {
Subroutine _status_class_munger: called CC=2 SCAR=6.9
652 16 my ( $proto, $lo, $hi, $div, $spec, $where ) = @_;
653 16 ▶ my $strict = $spec->{strict} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$spec->{'strict'} ? : 8 8 16
654 62 ▶ return sub {
Subroutine __ANON__: called CC=6 SCAR=17.9
655 62 my ($v) = @_;
656 62 ▶ croak "${proto}_enum munger$where: '" . ( defined $v ? $v : 'undef' ) . "' is not a numeric status code"
Branch: 2 branches
BranchTrueFalseTotal
unless &looks_like_number($v) 3 59 62
defined $v ? : 3 0 3
657 unless looks_like_number($v);
658 59 ▶ croak "${proto}_enum munger$where: status code '$v' is out of range " . "($lo-$hi)"
Branch: 1 branch
BranchTrueFalseTotal
if $strict and $v < $lo || $v > $hi 12 47 59
Condition100%6/6
$strict and $v < $lo || $v > $hi
!ll&&!rl&&r
331412
$v < $lo or $v > $hi
l!l&&r!l&&!r
4814
MC/DC100%3/3
$strict and $v < $lo || $v > $hi
$strict $v < $lo $v > $hi
Truth table100%4/4
A and B or C
A= $strictB= $v < $loC= $v > $hi
ABCresult
0XX0
1000
11X1
1011
659 if $strict && ( $v < $lo || $v > $hi );
660 47 return int( $v / $div );
661 16 };
662 } ## end sub _status_class_munger
663  
664 =head2 mgcp_enum
665  
666 { munger => 'mgcp_enum' }
667 { munger => 'mgcp_enum', strict => 1 }
668  
669 The MGCP counterpart of L</http_enum>, for MGCP (RFC 3435) response codes:
670 C<int(code / 100)>. MGCP's classes are C<1xx> provisional, C<2xx> success,
671 C<4xx> transient error, C<5xx> permanent error, and C<8xx> package-specific --
672 there are no C<6xx> or C<7xx> codes, so the valid set has a B<hole> in it.
673 With a true C<strict>, inputs outside C<100>-C<599> B<and> outside
674 C<800>-C<899> croak. (That hole is why this is a hand-written builder rather
675 than another row of the shared status-class table, which can only express one
676 contiguous range.)
677  
678 =cut
679  
680 # MGCP's strict range is [100,599] union [800,899] -- 8xx package-specific
681 # codes are real, 6xx/7xx are not -- which %STATUS_PROTO's single [lo, hi]
682 # cannot express, hence this dedicated builder.
683 2 ▶sub _build_mgcp_enum {
Subroutine _build_mgcp_enum: called CC=2 SCAR=6.9
684 2 my ( $spec, $where ) = @_;
685 2 ▶ my $strict = $spec->{strict} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$spec->{'strict'} ? : 1 1 2
686 15 ▶ return sub {
Subroutine __ANON__: called CC=8 SCAR=20.8
687 15 my ($v) = @_;
688 15 ▶ croak "mgcp_enum munger$where: '" . ( defined $v ? $v : 'undef' ) . "' is not a numeric status code"
Branch: 2 branches
BranchTrueFalseTotal
unless &looks_like_number($v) 1 14 15
defined $v ? : 1 0 1
689 unless looks_like_number($v);
690 14 ▶ croak "mgcp_enum munger$where: status code '$v' is out of range " . "(100-599 or 800-899)"
Branch: 1 branch
BranchTrueFalseTotal
if $strict and not $v >= 100 && $v <= 599 || $v >= 800 && $v <= 899 4 10 14
Condition100%12/12
$strict and not $v >= 100 && $v <= 599 || $v >= 800 && $v <= 899
!ll&&!rl&&r
644
$v >= 100 && $v <= 599 || $v >= 800 && $v <= 899
l!l&&r!l&&!r
224
$v >= 100 and $v <= 599
!ll&&!rl&&r
152
$v >= 800 and $v <= 899
!ll&&!rl&&r
312
MC/DC100%5/5
$strict and not $v >= 100 && $v <= 599 || $v >= 800 && $v <= 899
$strict $v >= 100 $v <= 599 $v >= 800 $v <= 899
Truth table75%6/8
A and not(B and C || D and E)
A= $strictB= $v >= 100C= $v <= 599D= $v >= 800E= $v <= 899
ABCDEresult
0XXXX0
111XX0
10X110
110110
10X0X1
10X101
1100X1
110101
691 if $strict && !( ( $v >= 100 && $v <= 599 ) || ( $v >= 800 && $v <= 899 ) );
692 10 return int( $v / 100 );
693 2 };
694 } ## end sub _build_mgcp_enum
695  
696 =head2 dns_rcode_enum
697  
698 { munger => 'dns_rcode_enum' }
699 { munger => 'dns_rcode_enum', default => -1 }
700  
701 The first of the B<named-map enums>: like L</enum>, except the C<map> is baked
702 in from a well-known registry instead of hand-authored (and inevitably
703 typo'd). All named-map enums share the same lookup rules: names are matched
704 B<case-insensitively>; where the emitted numbers are the protocol's own wire
705 encoding (as here -- rcode C<3> I<is> C<NXDOMAIN>), a numeric input is passed
706 through unchanged, so mixed feeds (one tool logs C<NXDOMAIN>, another logs
707 C<3>) land in one consistent column; and an unmapped value croaks unless the
708 spec supplies a numeric C<default>. As with C<enum>, an unrecognized value is
709 often exactly the anomaly worth keeping, so C<< default => -1 >> is the usual
710 escape hatch.
711  
712 This one maps DNS RCODE names to their IANA values: C<NOERROR> 0, C<FORMERR>
713 1, C<SERVFAIL> 2, C<NXDOMAIN> 3, C<NOTIMP> 4 (alias C<NOTIMPL>), C<REFUSED> 5,
714 C<YXDOMAIN> 6, C<YXRRSET> 7, C<NXRRSET> 8, C<NOTAUTH> 9, C<NOTZONE> 10,
715 C<DSOTYPENI> 11, and the extended rcodes C<BADVERS>/C<BADSIG> 16, C<BADKEY>
716 17, C<BADTIME> 18, C<BADMODE> 19, C<BADNAME> 20, C<BADALG> 21, C<BADTRUNC> 22,
717 C<BADCOOKIE> 23.
718  
719 =head2 dns_qtype_enum
720  
721 { munger => 'dns_qtype_enum', default => -1 }
722  
723 Named-map enum (lookup rules as L</dns_rcode_enum>; numeric inputs pass
724 through) mapping DNS RR type names to their IANA numbers: C<A> 1, C<NS> 2,
725 C<CNAME> 5, C<SOA> 6, C<NULL> 10, C<PTR> 12, C<MX> 15, C<TXT> 16, C<AAAA> 28,
726 C<SRV> 33, C<NAPTR> 35, C<DS> 43, C<RRSIG> 46, C<DNSKEY> 48, C<TLSA> 52,
727 C<SVCB> 64, C<HTTPS> 65, C<AXFR> 252, C<ANY> (or C<*>) 255, C<URI> 256,
728 C<CAA> 257, and the rest of the commonly-observed registry. The query-type mix
729 is a classic DNS-tunneling feature -- C<TXT>/C<NULL>-heavy traffic where
730 C<A>/C<AAAA> is normal.
731  
732 =head2 syslog_severity_enum
733  
734 { munger => 'syslog_severity_enum' }
735  
736 Named-map enum (lookup rules as L</dns_rcode_enum>; numeric inputs pass
737 through) mapping syslog severity names to their RFC 5424 codes: C<emerg> 0
738 (alias C<panic>), C<alert> 1, C<crit> 2, C<err> 3 (alias C<error>),
739 C<warning> 4 (alias C<warn>), C<notice> 5, C<info> 6 (alias
740 C<informational>), C<debug> 7. Genuinely ordinal -- lower is more severe --
741 so a threshold split on it is meaningful.
742  
743 =head2 syslog_facility_enum
744  
745 { munger => 'syslog_facility_enum' }
746  
747 Named-map enum (lookup rules as L</dns_rcode_enum>; numeric inputs pass
748 through) mapping syslog facility names to their RFC 5424 codes: C<kern> 0,
749 C<user> 1, C<mail> 2, C<daemon> 3, C<auth> 4 (alias C<security>), C<syslog> 5,
750 C<lpr> 6, C<news> 7, C<uucp> 8, C<cron> 9, C<authpriv> 10, C<ftp> 11, C<ntp>
751 12, C<audit> 13, C<alert> 14, C<clock> 15, and C<local0>-C<local7> 16-23.
752  
753 =head2 ip_proto_enum
754  
755 { munger => 'ip_proto_enum', default => -1 }
756  
757 Named-map enum (lookup rules as L</dns_rcode_enum>; numeric inputs pass
758 through) mapping IP protocol names to their IANA protocol numbers: C<icmp> 1,
759 C<igmp> 2, C<ipip> 4 (alias C<ipencap>), C<tcp> 6, C<egp> 8, C<udp> 17,
760 C<dccp> 33, C<ipv6> 41, C<rsvp> 46, C<gre> 47, C<esp> 50, C<ah> 51,
761 C<icmpv6> 58 (alias C<ipv6-icmp>), C<ospf> 89, C<pim> 103, C<sctp> 132,
762 C<udplite> 136. The map is frozen here rather than delegated to
763 C<getprotobyname> so a value munges to the same number on every host.
764  
765 =head2 tls_version_enum
766  
767 { munger => 'tls_version_enum', default => -1 }
768  
769 Named-map enum (lookup rules as L</dns_rcode_enum>) mapping a TLS/SSL protocol
770 version name to an B<ordinal>: C<SSLv2> 0, C<SSLv3> 1, C<TLSv1> 2, C<TLSv1.1>
771 3, C<TLSv1.2> 4, C<TLSv1.3> 5, with the common spelling variants (C<ssl3>,
772 C<tls1.2>, ...) accepted. Ordinal so "older than expected" is a monotone
773 feature a threshold split can express. Because these ordinals are this
774 module's invention rather than a wire encoding, numeric inputs are B<not>
775 passed through -- a C<1.2> would land on the wrong scale -- and croak like
776 any other unmapped value (or take the C<default>).
777  
778 =head2 http_method_enum
779  
780 { munger => 'http_method_enum', default => -1 }
781  
782 Named-map enum (lookup rules as L</dns_rcode_enum>) for the registered HTTP
783 request methods: C<GET> 0, C<HEAD> 1, C<POST> 2, C<PUT> 3, C<DELETE> 4,
784 C<CONNECT> 5, C<OPTIONS> 6, C<TRACE> 7, C<PATCH> 8. HTTP has no numeric
785 method encoding, so these are unordered ordinals of this module's invention
786 (a canonical map beats every set inventing its own numbering) and numeric
787 inputs are not passed through. An unlisted -- possibly probing -- method
788 croaks unless a C<default> is given, and that unlisted-method signal is often
789 the interesting one.
790  
791 =head2 sip_method_enum
792  
793 { munger => 'sip_method_enum', default => -1 }
794  
795 Named-map enum (lookup rules as L</dns_rcode_enum>) for the SIP request
796 methods: C<INVITE> 0, C<ACK> 1, C<BYE> 2, C<CANCEL> 3, C<REGISTER> 4,
797 C<OPTIONS> 5, C<PRACK> 6, C<SUBSCRIBE> 7, C<NOTIFY> 8, C<PUBLISH> 9,
798 C<INFO> 10, C<REFER> 11, C<MESSAGE> 12, C<UPDATE> 13. Like
799 L</http_method_enum> these are ordinals of this module's invention, so
800 numeric inputs are not passed through.
801  
802 =head2 dhcp_msgtype_enum
803  
804 { munger => 'dhcp_msgtype_enum' }
805  
806 Named-map enum (lookup rules as L</dns_rcode_enum>; numeric inputs pass
807 through) mapping DHCP message-type names to their option-53 values:
808 C<DISCOVER> 1, C<OFFER> 2, C<REQUEST> 3, C<DECLINE> 4, C<ACK> 5, C<NAK> 6,
809 C<RELEASE> 7, C<INFORM> 8 -- each also accepted with the C<DHCP> prefix
810 (C<DHCPDISCOVER>, ...) that most tooling logs.
811  
812 =head2 app_proto_enum
813  
814 { munger => 'app_proto_enum', default => -1 }
815  
816 Named-map enum (lookup rules as L</dns_rcode_enum>) for Suricata's
817 C<app_proto> field -- the detected application-layer protocol on a flow or
818 alert (C<http>, C<dns>, C<tls>, C<ssh>, C<smtp>, C<dcerpc>, C<quic>, ...),
819 including C<failed> and C<unknown>, which are usually the very rows worth
820 keeping. These are unordered ordinals of this module's invention (Suricata
821 logs a string, not a number), so numeric inputs are B<not> passed through.
822 C<ssl> is accepted as an alias for C<tls> and C<ikev2> for C<ike>. This is
823 distinct from L</ip_proto_enum>, which numbers the L4 protocol
824 (C<tcp>/C<udp>/...) rather than the app layer riding on it.
825  
826 =head2 tcp_state_enum
827  
828 { munger => 'tcp_state_enum', default => -1 }
829  
830 Named-map enum (lookup rules as L</dns_rcode_enum>) mapping the TCP state
831 machine, as Suricata logs it under C<flow.tcp.state>, to an B<ordinal> along
832 the connection lifecycle: C<none> 0, C<syn_sent> 1, C<syn_recv> 2,
833 C<established> 3, C<fin_wait1> 4, C<fin_wait2> 5, C<closing> 6, C<time_wait>
834 7, C<close_wait> 8, C<last_ack> 9, C<closed> 10. Ordinal so "further along
835 teardown than expected" is a monotone feature a threshold split can express.
836 Being ordinals of our own invention, numeric inputs are not passed through.
837  
838 =head2 flow_state_enum
839  
840 { munger => 'flow_state_enum', default => -1 }
841  
842 Named-map enum (lookup rules as L</dns_rcode_enum>) for Suricata's
843 C<flow.state>: C<new> 0, C<established> 1, C<closed> 2, C<bypassed> 3,
844 C<local_bypass> 4 -- roughly ordinal along the flow lifecycle. Numeric inputs
845 are not passed through.
846  
847 =head2 flow_reason_enum
848  
849 { munger => 'flow_reason_enum', default => -1 }
850  
851 Named-map enum (lookup rules as L</dns_rcode_enum>) for Suricata's
852 C<flow.reason>, why a flow was logged out: C<timeout> 0, C<forced> 1,
853 C<shutdown> 2, C<unknown> 3. Numeric inputs are not passed through.
854  
855 =head2 suricata_action_enum
856  
857 { munger => 'suricata_action_enum', default => -1 }
858  
859 Named-map enum (lookup rules as L</dns_rcode_enum>) for Suricata's
860 C<alert.action> and the related rule/drop actions: C<allowed> 0, C<blocked>
861 1, C<pass> 2, C<drop> 3, C<reject> 4, C<alert> 5. In IDS mode the field is
862 C<allowed>/C<blocked>; the rule-action names are accepted too for IPS feeds
863 and C<drop> events. Numeric inputs are not passed through.
864  
865 =head2 postfix_status_enum
866  
867 { munger => 'postfix_status_enum', default => -1 }
868  
869 Named-map enum (lookup rules as L</dns_rcode_enum>) for Postfix's delivery
870 C<status=> disposition, numbered in a rough sent-to-failed severity order so
871 a threshold split is meaningful: C<sent> 0, C<deferred> 1, C<bounced> 2,
872 C<expired> 3, C<deliverable> 4, C<undeliverable> 5, C<hold> 6, C<discard> 7,
873 C<filtered> 8, C<reject> 9, C<softbounce> 10. Stock delivery agents emit only
874 C<sent>/C<deferred>/C<bounced>/C<expired>; C<deliverable>/C<undeliverable> come
875 from address verification (C<verify>), and the remainder cover HOLD/DISCARD
876 actions and values common log normalizers emit. Being labels of this module's
877 numbering, numeric inputs are not passed through.
878  
879 =head2 spf_result_enum
880  
881 { munger => 'spf_result_enum', default => -1 }
882  
883 Named-map enum (lookup rules as L</dns_rcode_enum>) for an SPF check result
884 (RFC 7208), as logged by policyd-spf or carried in an C<Authentication-Results>
885 header, numbered pass-to-fail: C<pass> 0, C<neutral> 1, C<none> 2, C<softfail>
886 3, C<fail> 4, C<temperror> 5, C<permerror> 6. The older spellings C<error>
887 (for C<temperror>) and C<unknown> (for C<permerror>) are accepted as aliases.
888 Numeric inputs are not passed through.
889  
890 =head2 dkim_result_enum
891  
892 { munger => 'dkim_result_enum', default => -1 }
893  
894 Named-map enum (lookup rules as L</dns_rcode_enum>) for a DKIM verification
895 result (RFC 8601), as logged by opendkim or carried in an
896 C<Authentication-Results> header, numbered pass-to-fail: C<pass> 0, C<neutral>
897 1, C<none> 2, C<policy> 3, C<fail> 4, C<temperror> 5, C<permerror> 6. The older
898 spellings C<error> (for C<temperror>) and C<unknown> (for C<permerror>) are
899 accepted as aliases. Numeric inputs are not passed through.
900  
901 =head2 dmarc_result_enum
902  
903 { munger => 'dmarc_result_enum', default => -1 }
904  
905 Named-map enum (lookup rules as L</dns_rcode_enum>) for a DMARC evaluation
906 result (RFC 7489 / RFC 8601), as logged by opendmarc or carried in an
907 C<Authentication-Results> header: C<pass> 0, C<none> 1, C<fail> 2, C<temperror>
908 3, C<permerror> 4, and opendmarc's C<bestguesspass> 5. This is the DMARC
909 I<result> (did the message pass alignment), not the policy I<disposition>
910 (C<none>/C<quarantine>/C<reject>) -- for that, use a plain L</enum>. Numeric
911 inputs are not passed through.
912  
913 =head2 sasl_mech_enum
914  
915 { munger => 'sasl_mech_enum', default => -1 }
916  
917 Named-map enum (lookup rules as L</dns_rcode_enum>) for the SASL
918 authentication mechanism -- as Dovecot logs C<mech=>, Postfix logs
919 C<sasl_method=>, and submission/IMAP/POP3 auth report -- numbered in a rough
920 B<weakest-to-strongest> order so the ordinal carries a little signal on its
921 own: the cleartext and C<anonymous> mechanisms sort low, the legacy
922 challenge-response ones (C<cram-md5>, C<digest-md5>, C<ntlm>, ...) in the
923 middle, then C<srp>/C<scram-*>, the OAuth/federated tokens, and finally the
924 Kerberos/GSS and certificate (C<external>) mechanisms. About two dozen
925 mechanisms are baked in, covering the IANA registry plus the ubiquitous
926 non-registered C<login>, C<xoauth2>, and C<apop>. Being ordinals of this
927 module's numbering, numeric inputs are not passed through; an unlisted
928 mechanism croaks unless a numeric C<default> is given.
929  
930 If you would rather the number carry B<no> implied gradient, see
931 L</sasl_mech_iana_enum>, which numbers the same set alphabetically.
932  
933 =head2 sasl_mech_iana_enum
934  
935 { munger => 'sasl_mech_iana_enum', default => -1 }
936  
937 The nominal counterpart of L</sasl_mech_enum>: the B<same> set of SASL
938 mechanisms (the two share one list, so they can never cover different
939 mechanisms), but numbered B<alphabetically> rather than by strength -- a
940 purely categorical encoding for when a strength gradient would be a
941 misleading feature. Lookup rules and the no-numeric-passthrough behaviour are
942 as L</sasl_mech_enum>.
943  
944 =head2 http_version_enum
945  
946 { munger => 'http_version_enum', default => -1 }
947  
948 Named-map enum (lookup rules as L</dns_rcode_enum>) mapping the HTTP protocol
949 version to an B<ordinal>: C<HTTP/0.9> 0, C<HTTP/1.0> 1, C<HTTP/1.1> 2,
950 C<HTTP/2.0> 3, C<HTTP/3.0> 4. The access-log spelling (C<HTTP/1.1>), the bare
951 number (C<1.1>), and the ALPN/shorthand forms (C<h2>, C<h2c>, C<h3>) are all
952 accepted, so an Apache/nginx C<%H> field and a Suricata C<http.protocol> land
953 in one column. Ordinal so "older than expected" (a C<0.9>/C<1.0> request from
954 a scanner) is a monotone feature a threshold split can express. Because these
955 are ordinals of our own numbering -- and a logged C<2> denotes version C<2.0>,
956 not the integer two -- numeric inputs are B<not> passed through.
957  
958 =head2 spamassassin_autolearn_enum
959  
960 { munger => 'spamassassin_autolearn_enum', default => -1 }
961  
962 Named-map enum (lookup rules as L</dns_rcode_enum>) for SpamAssassin's
963 C<autolearn=> field: C<no> 0, C<ham> 1, C<spam> 2, C<disabled> 3, C<failed> 4,
964 C<unavailable> 5, C<unknown> 6. The numbering is essentially nominal (the
965 Bayes auto-learn outcome is a category, not a scale), arranged only so the
966 "nothing was learned" states cluster away from the ham/spam ones. The spam
967 I<score> is already a number for L</num>, and the spam/ham verdict a L</bool>;
968 this covers the one autolearn field neither derives. Numeric inputs are not
969 passed through.
970  
971 =head2 rspamd_action_enum
972  
973 { munger => 'rspamd_action_enum', default => -1 }
974  
975 Named-map enum (lookup rules as L</dns_rcode_enum>) for rspamd's action,
976 numbered by B<increasing severity> so the ordinal is a usable feature on its
977 own: C<no action> 0, C<greylist> 1, C<add header> 2, C<rewrite subject> 3,
978 C<soft reject> 4, C<reject> 5. Both the space and underscore spellings rspamd
979 emits (C<no action>/C<no_action>, C<add header>/C<add_header>, ...) are
980 accepted. Numeric inputs are not passed through.
981  
982 =head2 ssh_auth_method_enum
983  
984 { munger => 'ssh_auth_method_enum', default => -1 }
985  
986 Named-map enum (lookup rules as L</dns_rcode_enum>) for the OpenSSH
987 authentication method logged by C<sshd> (the word after C<Accepted>/C<Failed>,
988 or the C<method=> field): C<none> 0, C<password> 1, C<keyboard-interactive> 2,
989 C<hostbased> 3, C<publickey> 4, C<gssapi-with-mic> 5, C<gssapi-keyex> 6, with
990 bare C<gssapi> aliased to C<gssapi-with-mic>. Numbered roughly
991 B<weakest-to-strongest> so "weaker credential than expected" is a monotone
992 feature; the ordering is a judgement call, not a registry. Numeric inputs are
993 not passed through.
994  
995 =head2 amavis_category_enum
996  
997 { munger => 'amavis_category_enum', default => -1 }
998  
999 Named-map enum (lookup rules as L</dns_rcode_enum>) for the amavisd-new
1000 content category, ordered clean-to-worst: C<clean> 0, C<oversized> 1,
1001 C<unchecked> 2, C<spammy> 3, C<spam> 4, C<badheader> 5, C<banned> 6,
1002 C<infected> 7, C<mtablocked> 8. The hyphenated spellings (C<bad-header>,
1003 C<mta-blocked>) and the legacy C<virus> (for C<infected>) are accepted as
1004 aliases. The Passed/Blocked I<action> itself is a L</bool>; this is the
1005 finer-grained reason. Numeric inputs are not passed through.
1006  
1007 =head2 systemd_result_enum
1008  
1009 { munger => 'systemd_result_enum', default => -1 }
1010  
1011 Named-map enum (lookup rules as L</dns_rcode_enum>) for a systemd unit
1012 C<result> (as in C<Failed with result 'timeout'>): C<success> 0, C<protocol>
1013 1, C<timeout> 2, C<exit-code> 3, C<signal> 4, C<core-dump> 5, C<watchdog> 6,
1014 C<start-limit-hit> 7, C<oom-kill> 8, C<resources> 9. The underscore spellings
1015 (C<exit_code>, C<core_dump>, C<start_limit_hit>, C<oom_kill>) are accepted as
1016 aliases. Numeric inputs are not passed through.
1017  
1018 =head2 clamav_result_enum
1019  
1020 { munger => 'clamav_result_enum', default => -1 }
1021  
1022 Named-map enum (lookup rules as L</dns_rcode_enum>) for a ClamAV per-target
1023 verdict as logged by C<clamd> / clamav-milter: C<OK> 0, C<FOUND> 1, C<ERROR>
1024 2. Small but exactly the signal worth flagging (a C<FOUND> line). Numeric
1025 inputs are not passed through.
1026  
1027 =head2 kerberos_etype_enum
1028  
1029 { munger => 'kerberos_etype_enum', default => -1 }
1030  
1031 Named-map enum for the Kerberos ticket encryption type -- Windows events
1032 4768/4769 (logged as hex, C<0x17>) and any other AD/Kerberos source. The
1033 values are the RFC 3961 etype numbers, which B<are> the wire encoding, so
1034 (unlike most of the enums here) a decimal input passes through unchanged: the
1035 map exists only to resolve the hex spellings (C<0x17> => 23, C<0x12> => 18,
1036 ...) and the RFC/MIT names (C<rc4-hmac>/C<rc4>/C<arcfour-hmac> => 23,
1037 C<aes256-cts-hmac-sha1-96>/C<aes256> => 18, C<aes128> => 17, C<des3> => 16,
1038 C<des-cbc-md5> => 3, C<des-cbc-crc> => 1) onto that same number. The classic
1039 use is flagging C<rc4-hmac> (0x17) as a downgrade/roasting signal against an
1040 C<aes256> baseline. Lookup is case-insensitive; an unlisted etype croaks
1041 unless a numeric C<default> is given.
1042  
1043 =head2 windows_integrity_level_enum
1044  
1045 { munger => 'windows_integrity_level_enum', default => -1 }
1046  
1047 Named-map enum (lookup rules as L</dns_rcode_enum>) for the Windows / Sysmon
1048 process integrity level, as an B<ordinal>: C<untrusted> 0, C<low> 1, C<medium>
1049 2, C<high> 3, C<system> 4 (with C<mediumplus> folded into C<medium>). The
1050 C<S-1-16-*> mandatory-label SIDs Windows sometimes logs in place of the word
1051 (C<S-1-16-12288> => 3, ...) are accepted as aliases. Ordinal so "higher
1052 privilege than expected" is a monotone feature. Numeric inputs are not passed
1053 through.
1054  
1055 =head2 windows_logon_status_enum
1056  
1057 { munger => 'windows_logon_status_enum', default => -1 }
1058  
1059 Named-map enum (lookup rules as L</dns_rcode_enum>) for the NTSTATUS
1060 sub-status on a failed Windows logon (events 4625/4776), collapsed to a
1061 compact B<reason category> rather than the raw 32-bit code: C<0xC0000064>
1062 (no such user) 0, C<0xC000006A> (bad password) 1, C<0xC000006D> (generic bad
1063 user/pass) 2, C<0xC000006F> (outside hours) 3, C<0xC0000070> (workstation
1064 restriction) 4, C<0xC0000071> (password expired) 5, C<0xC0000072> (disabled)
1065 6, C<0xC0000193> (account expired) 7, C<0xC0000133> (clock skew) 8,
1066 C<0xC0000224> (must change password) 9, C<0xC0000234> (locked out) 10,
1067 C<0xC000015B> (logon type not granted) 11. Keys are the hex codes exactly as
1068 logged (matched case-insensitively); only the common logon subset is baked in,
1069 so an unlisted code croaks unless a numeric C<default> is given. Numeric
1070 inputs are not passed through.
1071  
1072 =head2 windows_impersonation_level_enum
1073  
1074 { munger => 'windows_impersonation_level_enum', default => -1 }
1075  
1076 Named-map enum (lookup rules as L</dns_rcode_enum>) for the event 4624
1077 impersonation level, ordered by reach: C<anonymous> 0, C<identification> 1,
1078 C<impersonation> 2, C<delegation> 3. The C<%%1832> / C<%%1833> message tokens
1079 Windows often emits in place of the words (Identification / Impersonation) are
1080 accepted as aliases. Numeric inputs are not passed through.
1081  
1082 =head2 aad_signin_error_enum
1083  
1084 { munger => 'aad_signin_error_enum', default => -1 }
1085  
1086 Named-map enum for the Azure AD / Entra sign-in C<ResultType> error code,
1087 collapsed to a compact B<reason category> rather than the raw code: C<0>
1088 (success) 0, invalid-password (C<50126>, C<50056>) 1, no-such-user (C<50034>)
1089 2, disabled (C<50057>) 3, locked / smart-lockout (C<50053>) 4, password-expired
1090 (C<50055>, C<50144>) 5, MFA-required (C<50074>, C<50076>, C<50079>) 6,
1091 MFA-failed (C<500121>, C<50158>) 7, blocked-by-conditional-access (C<53003>,
1092 C<53000>, C<53001>, C<530032>) 8, session-expired (C<50173>) 9. Although
1093 C<ResultType> is already numeric, the code space is huge and sparse and its
1094 magnitude carries no signal -- this maps the common codes onto a handful of
1095 meaningful buckets (and, unlike L</hash>, keeps related codes together). Keys
1096 are the codes as logged; only the common subset is baked in, so an unlisted
1097 code croaks unless a numeric C<default> is given. Because the output is a
1098 category of our own numbering, numeric inputs are B<not> passed through.
1099  
1100 =head2 risk_level_enum
1101  
1102 { munger => 'risk_level_enum', default => -1 }
1103  
1104 Named-map enum (lookup rules as L</dns_rcode_enum>) for the Entra Identity
1105 Protection C<riskLevel> as an B<ordinal>: C<none> 0, C<low> 1, C<medium> 2,
1106 C<high> 3. C<hidden> and C<unknownFutureValue> are left to the C<default>
1107 (they are not points on the scale). Numeric inputs are not passed through.
1108  
1109 =head2 aws_principal_type_enum
1110  
1111 { munger => 'aws_principal_type_enum', default => -1 }
1112  
1113 Named-map enum (lookup rules as L</dns_rcode_enum>) for the CloudTrail
1114 C<userIdentity.type>: C<Root> 0, C<IAMUser> 1, C<AssumedRole> 2,
1115 C<FederatedUser> 3, C<SAMLUser> 4, C<WebIdentityUser> 5, C<Directory> 6,
1116 C<IdentityCenterUser> 7, C<AWSAccount> 8, C<AWSService> 9, C<Unknown> 10. The
1117 numbering is nominal (distinct stable numbers, not a scale); C<Root> is the
1118 value you actually alert on. Numeric inputs are not passed through.
1119  
1120 =head2 aad_client_app_enum
1121  
1122 { munger => 'aad_client_app_enum', default => -1 }
1123  
1124 Named-map enum (lookup rules as L</dns_rcode_enum>) for the Azure AD
1125 C<ClientAppUsed>, numbered so the modern clients sort low (C<Browser> 0,
1126 C<Mobile Apps and Desktop clients> 1) and the B<legacy-auth> protocols -- which
1127 cannot satisfy MFA -- sort high (C<Exchange ActiveSync>, C<IMAP4>, C<POP3>,
1128 C<Authenticated SMTP>, C<MAPI Over HTTP>, C<Exchange Web Services>, C<Exchange
1129 Online PowerShell>, C<AutoDiscover>, C<Offline Address Book>, C<Other
1130 clients>, from 2 up). A "C<< >= 2 >> means legacy auth" threshold is the
1131 intended feature. C<imap>/C<pop>/C<mapi> short forms are accepted as aliases.
1132 Numeric inputs are not passed through.
1133  
1134 =head2 risk_state_enum
1135  
1136 { munger => 'risk_state_enum', default => -1 }
1137  
1138 Named-map enum (lookup rules as L</dns_rcode_enum>) for the Entra Identity
1139 Protection C<riskState>: C<none> 0, C<confirmedSafe> 1, C<remediated> 2,
1140 C<dismissed> 3, C<atRisk> 4, C<confirmedCompromised> 5. Numeric inputs are not
1141 passed through.
1142  
1143 =head2 vpc_flow_log_status_enum
1144  
1145 { munger => 'vpc_flow_log_status_enum', default => -1 }
1146  
1147 Named-map enum (lookup rules as L</dns_rcode_enum>) for the AWS VPC Flow Logs
1148 C<log-status>: C<OK> 0, C<NODATA> 1, C<SKIPDATA> 2. (The per-flow
1149 C<ACCEPT>/C<REJECT> action is a plain L</bool>; this is the capture-health
1150 field.) Numeric inputs are not passed through.
1151  
1152 =head2 aws_event_type_enum
1153  
1154 { munger => 'aws_event_type_enum', default => -1 }
1155  
1156 Named-map enum (lookup rules as L</dns_rcode_enum>) for the CloudTrail
1157 C<eventType>: C<AwsApiCall> 0, C<AwsServiceEvent> 1, C<AwsConsoleAction> 2,
1158 C<AwsConsoleSignIn> 3, C<AwsCloudTrailInsight> 4. C<AwsConsoleSignIn> is the
1159 one worth flagging. Numeric inputs are not passed through.
1160  
1161 =head2 conditional_access_result_enum
1162  
1163 { munger => 'conditional_access_result_enum', default => -1 }
1164  
1165 Named-map enum (lookup rules as L</dns_rcode_enum>) for the Azure AD sign-in
1166 C<conditionalAccessStatus>: C<success> 0, C<notApplied> 1, C<notEnabled> 2,
1167 C<reportOnly> 3, C<failure> 4. Numeric inputs are not passed through.
1168  
1169 =cut
1170  
1171 # Named-map enums: baked-in value->number maps for well-known registries,
1172 # registered as "<name>_enum". Keys are stored lowercase; lookup lowercases
1173 # the input, giving the case-insensitive matching the POD promises. 'numeric'
1174 # says whether a numeric input is passed through as-is -- set only where the
1175 # numbers are the protocol's own encoding (a qtype 28 IS AAAA on the wire);
1176 # where they are ordinals of our own invention (tls_version, the method
1177 # enums), passthrough would mix scales, so a number croaks like any other
1178 # unmapped value.
1179  
1180 # SASL mechanism names, ordered weakest-to-strongest, for sasl_mech_enum. The
1181 # same set is numbered alphabetically for sasl_mech_iana_enum, so the two
1182 # mungers can never end up covering different mechanisms. Includes the IANA
1183 # registry plus the ubiquitous non-registered login/xoauth2/apop.
1184 6 my @SASL_MECHS_BY_STRENGTH = qw(
1185 anonymous plain login
1186 apop cram-md5 digest-md5 ntlm skey otp securid rpa kerberos_v4
1187 srp scram-sha-1 scram-sha-1-plus scram-sha-256 scram-sha-256-plus
1188 xoauth2 oauthbearer openid20 saml20
1189 gssapi gs2-krb5 gss-spnego external
1190 );
1191  
1192 my %NAMED_ENUM = (
1193 dns_rcode => {
1194 numeric => 1,
1195 map => {
1196 noerror => 0,
1197 formerr => 1,
1198 servfail => 2,
1199 nxdomain => 3,
1200 notimp => 4,
1201 notimpl => 4,
1202 refused => 5,
1203 yxdomain => 6,
1204 yxrrset => 7,
1205 nxrrset => 8,
1206 notauth => 9,
1207 notzone => 10,
1208 dsotypeni => 11,
1209 badvers => 16,
1210 badsig => 16,
1211 badkey => 17,
1212 badtime => 18,
1213 badmode => 19,
1214 badname => 20,
1215 badalg => 21,
1216 badtrunc => 22,
1217 badcookie => 23,
1218 },
1219 },
1220 dns_qtype => {
1221 numeric => 1,
1222 map => {
1223 a => 1,
1224 ns => 2,
1225 cname => 5,
1226 soa => 6,
1227 mb => 7,
1228 mg => 8,
1229 mr => 9,
1230 'null' => 10,
1231 wks => 11,
1232 ptr => 12,
1233 hinfo => 13,
1234 minfo => 14,
1235 mx => 15,
1236 txt => 16,
1237 rp => 17,
1238 afsdb => 18,
1239 sig => 24,
1240 key => 25,
1241 aaaa => 28,
1242 loc => 29,
1243 srv => 33,
1244 naptr => 35,
1245 kx => 36,
1246 cert => 37,
1247 dname => 39,
1248 opt => 41,
1249 ds => 43,
1250 sshfp => 44,
1251 ipseckey => 45,
1252 rrsig => 46,
1253 nsec => 47,
1254 dnskey => 48,
1255 dhcid => 49,
1256 nsec3 => 50,
1257 nsec3param => 51,
1258 tlsa => 52,
1259 smimea => 53,
1260 hip => 55,
1261 cds => 59,
1262 cdnskey => 60,
1263 openpgpkey => 61,
1264 csync => 62,
1265 zonemd => 63,
1266 svcb => 64,
1267 https => 65,
1268 eui48 => 108,
1269 eui64 => 109,
1270 tkey => 249,
1271 tsig => 250,
1272 ixfr => 251,
1273 axfr => 252,
1274 any => 255,
1275 '*' => 255,
1276 uri => 256,
1277 caa => 257,
1278 },
1279 },
1280 syslog_severity => {
1281 numeric => 1,
1282 map => {
1283 emerg => 0,
1284 panic => 0,
1285 alert => 1,
1286 crit => 2,
1287 err => 3,
1288 error => 3,
1289 warning => 4,
1290 warn => 4,
1291 notice => 5,
1292 info => 6,
1293 informational => 6,
1294 debug => 7,
1295 },
1296 },
1297 syslog_facility => {
1298 numeric => 1,
1299 map => {
1300 kern => 0,
1301 user => 1,
1302 mail => 2,
1303 daemon => 3,
1304 auth => 4,
1305 security => 4,
1306 syslog => 5,
1307 lpr => 6,
1308 news => 7,
1309 uucp => 8,
1310 cron => 9,
1311 authpriv => 10,
1312 ftp => 11,
1313 ntp => 12,
1314 audit => 13,
1315 alert => 14,
1316 clock => 15,
1317 48 ( map { ( "local$_" => 16 + $_ ) } 0 .. 7 ),
1318 },
1319 },
1320 ip_proto => {
1321 numeric => 1,
1322 map => {
1323 icmp => 1,
1324 igmp => 2,
1325 ipip => 4,
1326 ipencap => 4,
1327 tcp => 6,
1328 egp => 8,
1329 udp => 17,
1330 dccp => 33,
1331 ipv6 => 41,
1332 rsvp => 46,
1333 gre => 47,
1334 esp => 50,
1335 ah => 51,
1336 icmpv6 => 58,
1337 'ipv6-icmp' => 58,
1338 ospf => 89,
1339 pim => 103,
1340 sctp => 132,
1341 udplite => 136,
1342 },
1343 },
1344 tls_version => {
1345 numeric => 0,
1346 map => {
1347 sslv2 => 0,
1348 ssl2 => 0,
1349 sslv3 => 1,
1350 ssl3 => 1,
1351 tlsv1 => 2,
1352 'tlsv1.0' => 2,
1353 tls1 => 2,
1354 'tls1.0' => 2,
1355 'tlsv1.1' => 3,
1356 'tls1.1' => 3,
1357 'tlsv1.2' => 4,
1358 'tls1.2' => 4,
1359 'tlsv1.3' => 5,
1360 'tls1.3' => 5,
1361 },
1362 },
1363 http_method => {
1364 numeric => 0,
1365 map => {
1366 get => 0,
1367 head => 1,
1368 post => 2,
1369 put => 3,
1370 delete => 4,
1371 connect => 5,
1372 options => 6,
1373 trace => 7,
1374 patch => 8,
1375 },
1376 },
1377 sip_method => {
1378 numeric => 0,
1379 map => {
1380 invite => 0,
1381 ack => 1,
1382 bye => 2,
1383 cancel => 3,
1384 register => 4,
1385 options => 5,
1386 prack => 6,
1387 subscribe => 7,
1388 notify => 8,
1389 publish => 9,
1390 info => 10,
1391 refer => 11,
1392 message => 12,
1393 update => 13,
1394 },
1395 },
1396 dhcp_msgtype => {
1397 numeric => 1,
1398 map => {
1399 (
1400 48 map { ( $_->[0] => $_->[1], "dhcp$_->[0]" => $_->[1] ) } [ discover => 1 ],
1401 [ offer => 2 ],
1402 [ request => 3 ],
1403 [ decline => 4 ],
1404 [ ack => 5 ],
1405 [ nak => 6 ],
1406 [ release => 7 ],
1407 [ inform => 8 ]
1408 ),
1409 },
1410 },
1411 app_proto => {
1412 numeric => 0,
1413 map => {
1414 # Ordinals of our own invention (Suricata's app_proto is a string
1415 # label with no wire number), assigned from a fixed order so a value
1416 # munges to the same number on every host. 'failed'/'unknown' are
1417 # kept as their own classes -- an un-parsed app layer is often the
1418 # interesting row.
1419 do {
1420 6 my @order = qw(
1421 unknown failed http http2 ftp ftp-data smtp imap
1422 tls ssh smb dcerpc dns modbus enip dnp3 nfs ntp
1423 tftp ike krb5 quic dhcp snmp sip rfb mqtt rdp
1424 telnet pgsql ldap websocket bittorrent-dht
1425 );
1426 6 my %m = map { $order[$_] => $_ } 0 .. $#order;
1427 6 $m{ssl} = $m{tls}; # Suricata's older spelling
1428 6 $m{ikev2} = $m{ike};
1429 6 %m;
1430 },
1431 },
1432 },
1433 tcp_state => {
1434 numeric => 0,
1435 map => {
1436 # The TCP state machine (flow.tcp.state), numbered along the
1437 # connection lifecycle so the ordinal is meaningful.
1438 do {
1439 6 my @order = qw(
1440 none syn_sent syn_recv established
1441 fin_wait1 fin_wait2 closing time_wait
1442 close_wait last_ack closed
1443 );
1444 6 map { $order[$_] => $_ } 0 .. $#order;
1445 },
1446 },
1447 },
1448 flow_state => {
1449 numeric => 0,
1450 map => {
1451 new => 0,
1452 established => 1,
1453 closed => 2,
1454 bypassed => 3,
1455 local_bypass => 4,
1456 },
1457 },
1458 flow_reason => {
1459 numeric => 0,
1460 map => {
1461 timeout => 0,
1462 forced => 1,
1463 shutdown => 2,
1464 unknown => 3,
1465 },
1466 },
1467 suricata_action => {
1468 numeric => 0,
1469 map => {
1470 allowed => 0,
1471 blocked => 1,
1472 pass => 2,
1473 drop => 3,
1474 reject => 4,
1475 alert => 5,
1476 },
1477 },
1478 postfix_status => {
1479 numeric => 0,
1480 map => {
1481 sent => 0,
1482 deferred => 1,
1483 bounced => 2,
1484 expired => 3,
1485 deliverable => 4,
1486 undeliverable => 5,
1487 hold => 6,
1488 discard => 7,
1489 filtered => 8,
1490 reject => 9,
1491 softbounce => 10,
1492 },
1493 },
1494 spf_result => {
1495 numeric => 0,
1496 map => {
1497 pass => 0,
1498 neutral => 1,
1499 none => 2,
1500 softfail => 3,
1501 fail => 4,
1502 temperror => 5,
1503 error => 5, # older spelling of temperror
1504 permerror => 6,
1505 unknown => 6, # older spelling of permerror
1506 },
1507 },
1508 dkim_result => {
1509 numeric => 0,
1510 map => {
1511 pass => 0,
1512 neutral => 1,
1513 none => 2,
1514 policy => 3,
1515 fail => 4,
1516 temperror => 5,
1517 error => 5, # older spelling of temperror
1518 permerror => 6,
1519 unknown => 6, # older spelling of permerror
1520 },
1521 },
1522 dmarc_result => {
1523 numeric => 0,
1524 map => {
1525 pass => 0,
1526 none => 1,
1527 fail => 2,
1528 temperror => 3,
1529 permerror => 4,
1530 bestguesspass => 5,
1531 },
1532 },
1533 sasl_mech => {
1534 numeric => 0,
1535 map => {
1536 do {
1537 6 my @o = @SASL_MECHS_BY_STRENGTH;
1538 6 map { $o[$_] => $_ } 0 .. $#o;
1539 },
1540 },
1541 },
1542 sasl_mech_iana => {
1543 numeric => 0,
1544 map => {
1545 do {
1546 6 my @o = sort @SASL_MECHS_BY_STRENGTH;
1547 6 map { $o[$_] => $_ } 0 .. $#o;
1548 },
1549 },
1550 },
1551 http_version => {
1552 numeric => 0, # a logged "2" is version 2.0, not the integer two
1553 map => {
1554 # Ordinal so "older than expected" is a monotone feature. Accepts
1555 # the access-log spelling (HTTP/1.1), the bare number (1.1), and
1556 # the ALPN/h2 shorthands.
1557 do {
1558 6 my %v = (
1559 'http/0.9' => 0,
1560 'http/1.0' => 1,
1561 'http/1.1' => 2,
1562 'http/2.0' => 3,
1563 'http/3.0' => 4,
1564 );
1565 6 $v{'0.9'} = 0;
1566 6 $v{'1.0'} = 1;
1567 6 $v{'1.1'} = 2;
1568 6 $v{'2.0'} = $v{'2'} = $v{'http/2'} = $v{'h2'} = $v{'h2c'} = 3;
1569 6 $v{'3.0'} = $v{'3'} = $v{'http/3'} = $v{'h3'} = 4;
1570 6 %v;
1571 },
1572 },
1573 },
1574 spamassassin_autolearn => {
1575 numeric => 0,
1576 map => {
1577 # SpamAssassin's autolearn= field. Nominal, but ordered so
1578 # "no learning happened" sorts below the ham/spam outcomes.
1579 no => 0,
1580 ham => 1,
1581 spam => 2,
1582 disabled => 3,
1583 failed => 4,
1584 unavailable => 5,
1585 unknown => 6,
1586 },
1587 },
1588 rspamd_action => {
1589 numeric => 0,
1590 map => {
1591 # rspamd's action, ordered by severity. Accept both the space
1592 # and underscore spellings rspamd emits across its outputs.
1593 do {
1594 6 my %a = (
1595 'no action' => 0,
1596 'greylist' => 1,
1597 'add header' => 2,
1598 'rewrite subject' => 3,
1599 'soft reject' => 4,
1600 'reject' => 5,
1601 );
1602 6 $a{'no_action'} = $a{'noaction'} = 0;
1603 6 $a{'add_header'} = 2;
1604 6 $a{'rewrite_subject'} = 3;
1605 6 $a{'soft_reject'} = $a{'soft-reject'} = 4;
1606 6 %a;
1607 },
1608 },
1609 },
1610 ssh_auth_method => {
1611 numeric => 0,
1612 map => {
1613 # OpenSSH authentication method, ordered by credential strength
1614 # (weakest first) so "weaker than expected" is monotone. The
1615 # ordering is a judgement call, not an IANA registry.
1616 do {
1617 6 my @o = qw(
1618 none password keyboard-interactive
1619 hostbased publickey
1620 gssapi-with-mic gssapi-keyex
1621 );
1622 6 my %m = map { $o[$_] => $_ } 0 .. $#o;
1623 6 $m{'gssapi'} = $m{'gssapi-with-mic'};
1624 6 %m;
1625 },
1626 },
1627 },
1628 amavis_category => {
1629 numeric => 0,
1630 map => {
1631 # amavisd-new content category, ordered clean -> worst.
1632 do {
1633 6 my @o = qw(
1634 clean oversized unchecked spammy spam
1635 badheader banned infected mtablocked
1636 );
1637 6 my %m = map { $o[$_] => $_ } 0 .. $#o;
1638 6 $m{'bad-header'} = $m{'badheader'};
1639 6 $m{'virus'} = $m{'infected'};
1640 6 $m{'mta-blocked'} = $m{'mtablocked'};
1641 6 %m;
1642 },
1643 },
1644 },
1645 systemd_result => {
1646 numeric => 0,
1647 map => {
1648 # systemd unit "result" (e.g. "Failed with result 'timeout'").
1649 do {
1650 6 my @o = qw(
1651 success protocol timeout exit-code signal
1652 core-dump watchdog start-limit-hit oom-kill resources
1653 );
1654 6 my %m = map { $o[$_] => $_ } 0 .. $#o;
1655 6 $m{'exit_code'} = $m{'exit-code'};
1656 6 $m{'core_dump'} = $m{'core-dump'};
1657 6 $m{'start_limit_hit'} = $m{'start-limit-hit'};
1658 6 $m{'oom_kill'} = $m{'oom-kill'};
1659 6 %m;
1660 },
1661 },
1662 },
1663 clamav_result => {
1664 numeric => 0,
1665 map => {
1666 # clamd / clamav-milter per-target verdict.
1667 ok => 0,
1668 found => 1,
1669 error => 2,
1670 },
1671 },
1672 kerberos_etype => {
1673 numeric => 1, # RFC 3961 etype numbers are the wire value; a logged 23 IS rc4
1674 map => {
1675 # Windows logs the ticket encryption type as hex ("0x17"); the
1676 # RFC/MIT names appear in other Kerberos logs. Everything resolves
1677 # to the decimal etype number, so a decimal input passes through.
1678 do {
1679 6 my %e = (
1680 'des-cbc-crc' => 1,
1681 'des-cbc-md5' => 3,
1682 'des3-cbc-sha1' => 16,
1683 'aes128-cts-hmac-sha1-96' => 17,
1684 'aes256-cts-hmac-sha1-96' => 18,
1685 'rc4-hmac' => 23,
1686 'rc4-hmac-exp' => 24,
1687 );
1688 6 $e{'des3'} = 16;
1689 6 $e{'aes128'} = 17;
1690 6 $e{'aes256'} = 18;
1691 6 $e{'arcfour-hmac'} = $e{'rc4'} = 23;
1692 6 $e{'0x1'} = 1;
1693 6 $e{'0x3'} = 3;
1694 6 $e{'0x10'} = 16;
1695 6 $e{'0x11'} = 17;
1696 6 $e{'0x12'} = 18;
1697 6 $e{'0x17'} = 23;
1698 6 $e{'0x18'} = 24;
1699 6 %e;
1700 },
1701 },
1702 },
1703 windows_integrity_level => {
1704 numeric => 0,
1705 map => {
1706 # Sysmon IntegrityLevel; ordinal so "higher privilege than
1707 # expected" is monotone. Text labels plus the S-1-16-* mandatory
1708 # label SIDs Windows sometimes logs in their place.
1709 do {
1710 6 my %m = (
1711 untrusted => 0,
1712 low => 1,
1713 medium => 2,
1714 high => 3,
1715 system => 4,
1716 );
1717 6 $m{'mediumplus'} = 2;
1718 6 $m{'s-1-16-0'} = 0;
1719 6 $m{'s-1-16-4096'} = 1;
1720 6 $m{'s-1-16-8192'} = 2;
1721 6 $m{'s-1-16-12288'} = 3;
1722 6 $m{'s-1-16-16384'} = 4;
1723 6 %m;
1724 },
1725 },
1726 },
1727 windows_logon_status => {
1728 numeric => 0,
1729 map => {
1730 # Common NTSTATUS sub-status codes on failed logons (4625/4776),
1731 # mapped to a compact reason category -- the raw 32-bit value is
1732 # not itself a useful feature. Keys are the hex codes as logged.
1733 '0xc0000064' => 0, # user name does not exist
1734 '0xc000006a' => 1, # bad password
1735 '0xc000006d' => 2, # bad user name or password (generic)
1736 '0xc000006f' => 3, # outside authorized hours
1737 '0xc0000070' => 4, # workstation restriction
1738 '0xc0000071' => 5, # password expired
1739 '0xc0000072' => 6, # account disabled
1740 '0xc0000193' => 7, # account expired
1741 '0xc0000133' => 8, # clock skew between client and server
1742 '0xc0000224' => 9, # must change password at next logon
1743 '0xc0000234' => 10, # account locked out
1744 '0xc000015b' => 11, # logon type not granted
1745 },
1746 },
1747 windows_impersonation_level => {
1748 numeric => 0,
1749 map => {
1750 # 4624 ImpersonationLevel; ordinal by reach. Text labels plus the
1751 # two "%%18xx" message tokens Windows most often emits in place.
1752 anonymous => 0,
1753 identification => 1,
1754 impersonation => 2,
1755 delegation => 3,
1756 '%%1832' => 1,
1757 '%%1833' => 2,
1758 },
1759 },
1760 aad_signin_error => {
1761 numeric => 0,
1762 map => {
1763 # Azure AD / Entra sign-in ResultType codes collapsed to a compact
1764 # reason category -- the raw code is a huge sparse space whose
1765 # magnitude carries no signal. Keys are the numeric codes as
1766 # logged; only the common subset is baked in, the rest take the
1767 # default.
1768 '0' => 0, # success
1769 '50126' => 1, # invalid username or password
1770 '50056' => 1, # invalid or null password
1771 '50034' => 2, # user does not exist in directory
1772 '50057' => 3, # account disabled
1773 '50053' => 4, # account locked / smart lockout
1774 '50055' => 5, # password expired
1775 '50144' => 5, # AD password expired
1776 '50074' => 6, # strong auth (MFA) required
1777 '50076' => 6, # MFA required by conditional access
1778 '50079' => 6, # user must enroll for MFA
1779 '500121' => 7, # MFA denied / authentication failed
1780 '50158' => 7, # external security challenge not satisfied
1781 '53003' => 8, # blocked by conditional access
1782 '53000' => 8, # device not compliant (CA)
1783 '53001' => 8, # device not domain joined (CA)
1784 '530032' => 8, # blocked by security policy (CA)
1785 '50173' => 9, # fresh auth token required (session expired)
1786 },
1787 },
1788 risk_level => {
1789 numeric => 0,
1790 map => {
1791 # Entra Identity Protection riskLevel, ordinal. hidden /
1792 # unknownFutureValue are left to the default.
1793 none => 0,
1794 low => 1,
1795 medium => 2,
1796 high => 3,
1797 },
1798 },
1799 aws_principal_type => {
1800 numeric => 0,
1801 map => {
1802 # CloudTrail userIdentity.type. Nominal (distinct stable numbers);
1803 # 'root' is the value you actually alert on.
1804 do {
1805 6 my @o = qw(
1806 root iamuser assumedrole federateduser samluser
1807 webidentityuser directory identitycenteruser
1808 awsaccount awsservice unknown
1809 );
1810 6 map { $o[$_] => $_ } 0 .. $#o;
1811 },
1812 },
1813 },
1814 aad_client_app => {
1815 numeric => 0,
1816 map => {
1817 # Azure AD ClientAppUsed. Numbered so the modern clients sort low
1818 # and the legacy-auth protocols (which cannot do MFA) sort high --
1819 # a ">= 2 means legacy auth" threshold is the feature you want.
1820 6 do {
1821 6 my %m = (
1822 'browser' => 0,
1823 'mobile apps and desktop clients' => 1,
1824 );
1825 6 my @legacy = (
1826 'exchange activesync',
1827 'imap4',
1828 'pop3',
1829 'authenticated smtp',
1830 'smtp',
1831 'mapi over http',
1832 'exchange web services',
1833 'exchange online powershell',
1834 'autodiscover',
1835 'offline address book',
1836 'other clients',
1837 );
1838 6 my $i = 2;
1839 6 $m{$_} = $i++ for @legacy;
1840 6 $m{'imap'} = $m{'imap4'};
1841 6 $m{'pop'} = $m{'pop3'};
1842 6 $m{'mapi'} = $m{'mapi over http'};
1843 6 %m;
1844 },
1845 },
1846 },
1847 risk_state => {
1848 numeric => 0,
1849 map => {
1850 # Entra Identity Protection riskState.
1851 none => 0,
1852 confirmedsafe => 1,
1853 remediated => 2,
1854 dismissed => 3,
1855 atrisk => 4,
1856 confirmedcompromised => 5,
1857 },
1858 },
1859 vpc_flow_log_status => {
1860 numeric => 0,
1861 map => {
1862 # VPC Flow Logs log-status.
1863 ok => 0,
1864 nodata => 1,
1865 skipdata => 2,
1866 },
1867 },
1868 aws_event_type => {
1869 numeric => 0,
1870 map => {
1871 # CloudTrail eventType. AwsConsoleSignIn is the one you flag.
1872 awsapicall => 0,
1873 awsserviceevent => 1,
1874 awsconsoleaction => 2,
1875 awsconsolesignin => 3,
1876 awscloudtrailinsight => 4,
1877 },
1878 },
1879 conditional_access_result => {
1880 numeric => 0,
1881 map => {
1882 # Azure AD sign-in conditionalAccessStatus.
1883 success => 0,
1884 notapplied => 1,
1885 notenabled => 2,
1886 reportonly => 3,
1887 failure => 4,
1888 },
1889 },
1890 );
1891 6 for my $name ( keys %NAMED_ENUM ) {
1892 234 my $e = $NAMED_ENUM{$name};
1893 48 ▶ $BUILDERS{"${name}_enum"} = sub { _named_enum_munger( $name, $e, @_ ) };
Subroutine __ANON__: called CC=1 SCAR=0.0
1894 }
1895  
1896 # Shared closure for the named-map enums registered from %NAMED_ENUM.
1897 48 ▶sub _named_enum_munger {
Subroutine _named_enum_munger: called CC=3 SCAR=11.0
1898 48 my ( $name, $e, $spec, $where ) = @_;
1899  
1900 48 my $has_default = exists $spec->{default};
1901 48 my $default = $spec->{default};
1902 48 ▶ croak "${name}_enum munger$where: 'default' must be numeric"
Branch: 1 branch
BranchTrueFalseTotal
if $has_default and not &looks_like_number($default) 1 47 48
Condition100%3/3
$has_default and not &looks_like_number($default)
!ll&&!rl&&r
21261
MC/DC100%2/2
$has_default and not &looks_like_number($default)
$has_default not &looks_like_number($default)
Truth table100%3/3
A and not(B)
A= $has_defaultB= not &looks_like_number($default)
ABresult
0X0
100
111
1903 if $has_default && !looks_like_number($default);
1904  
1905 47 my ( $map, $numeric ) = @{$e}{qw(map numeric)};
1906 332 ▶ return sub {
Subroutine __ANON__: called CC=7 SCAR=19.5
1907 332 my ($v) = @_;
1908 332 ▶ if ( defined $v ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $v) 331 1 332
1909 331 ▶ return $v + 0 if $numeric && looks_like_number($v);
Branch: 1 branch
BranchTrueFalseTotal
if $numeric and &looks_like_number($v) 6 325 331
Condition100%3/3
$numeric and &looks_like_number($v)
!ll&&!rl&&r
285406
MC/DC100%2/2
$numeric and &looks_like_number($v)
$numeric &looks_like_number($v)
Truth table100%3/3
A and B
A= $numericB= &looks_like_number($v)
ABresult
0X0
100
111
1910 325 my $k = lc $v;
1911 325 ▶ return $map->{$k} if exists $map->{$k};
Branch: 1 branch
BranchTrueFalseTotal
if exists $map->{$k} 300 25 325
1912 }
1913 26 ▶ return $default if $has_default;
Branch: 1 branch
BranchTrueFalseTotal
if $has_default 17 9 26
1914 9 ▶ croak "${name}_enum munger$where: no mapping for '" . ( defined $v ? $v : 'undef' ) . "'";
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 9 0 9
1915 47 }; ## end sub
1916 } ## end sub _named_enum_munger
1917  
1918 =head2 bool
1919  
1920 { munger => 'bool' } # Perl truthiness -> 1/0
1921 { munger => 'bool', true => [ 'yes', 'Y', '1', 'true' ] }
1922  
1923 Coerce to C<1> or C<0>. With a C<true> list, only those (string-compared) values
1924 are C<1>; otherwise ordinary Perl truthiness is used.
1925  
1926 =cut
1927  
1928 2 ▶sub _build_bool {
Subroutine _build_bool: called CC=3 SCAR=11.0
1929 2 my ( $spec, $where ) = @_;
1930  
1931 2 ▶ if ( exists $spec->{true} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $spec->{"true"}) 1 1 2
1932 croak "bool munger$where: 'true' must be an arrayref"
1933 1 ▶ unless ref $spec->{true} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $spec->{"true"} eq "ARRAY" 0 1 1
1934 1 my %true = map { $_ => 1 } @{ $spec->{true} };
1935 3 ▶ return sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1936 3 my ($v) = @_;
1937 3 ▶ return exists $true{ defined $v ? $v : '' } ? 1 : 0;
Branch: 2 branches
BranchTrueFalseTotal
exists $true{defined $v ? $v : ''} ? : 1 2 3
defined $v ? : 2 1 3
1938 1 };
1939 }
1940  
1941 1 ▶ return sub { $_[0] ? 1 : 0 };
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$_[0] ? : 1 1 2
1942 } ## end sub _build_bool
1943  
1944 =head2 length
1945  
1946 { munger => 'length' }
1947  
1948 The character length of the stringified input, C<undef> counting as C<0> (an
1949 absent value is a zero-length one -- e.g. an SNI-absent TLS record). This is the
1950 cheap shape feature behind every C<*_length> column (domain, URL, filename, SNI,
1951 hostname, ...): tunneling and generated names run long, so raw length is a
1952 surprisingly strong corroborator next to L</entropy>. Length is counted in
1953 B<characters>, not bytes, so a multi-byte name is measured as a human would read
1954 it; use L</entropy> (which is byte-oriented) when you want per-symbol randomness.
1955  
1956 =cut
1957  
1958 7 ▶sub _build_length {
Subroutine _build_length: called CC=1 SCAR=0.0
1959 7 my ( $spec, $where ) = @_;
1960 13 ▶ return sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1961 13 my ($v) = @_;
1962 13 ▶ return length( defined $v ? "$v" : '' );
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 12 1 13
1963 7 };
1964 }
1965  
1966 =head2 entropy
1967  
1968 { munger => 'entropy' }
1969  
1970 Shannon entropy of the input string, in B<bits per symbol> -- i.e.
1971 C<-sum(p*log2(p))> over the frequencies of its bytes. This is the single most
1972 common feature in the pipeline (DGA domains, randomized filenames, forged
1973 User-Agents, generated SNIs / hostnames / principal names), because
1974 machine-generated strings spread their characters far more evenly than
1975 human-chosen ones and so score high, while a real word scores low. An empty
1976 string is C<0>; the maximum is C<8> (every byte value equally likely).
1977  
1978 Entropy is computed over the string's B<UTF-8 bytes> (matching L</hash>), so the
1979 value is well-defined regardless of the scalar's internal encoding flag. Like
1980 C<hash>, this munger is XS-accelerated -- a per-byte histogram plus a C<log> per
1981 distinct byte -- with a pure-Perl fallback that produces identical values;
1982 C<$Algorithm::ToNumberMunger::HAVE_XS> says which
1983 is in use.
1984  
1985 =cut
1986  
1987 1 ▶sub _build_entropy {
Subroutine _build_entropy: called CC=2 SCAR=7.1
1988 1 my ( $spec, $where ) = @_;
1989 1 ▶ my $fn = $HAVE_XS ? \&_entropy_xs : \&_entropy_pp;
Branch: 1 branch
BranchTrueFalseTotal
$Algorithm::ToNumberMunger::HAVE_XS ? : 1 0 1
1990 12 ▶ return sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
1991 12 my ($v) = @_;
1992 12 ▶ return $fn->( defined $v ? "$v" : '' );
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 12 0 12
1993 1 };
1994 }
1995  
1996 # Pure-Perl Shannon entropy (bits), used only when the XS did not build. Byte
1997 # view via an explicit encode so it matches the XS's SvPVutf8, and so the same
1998 # string scores the same regardless of its internal flag.
1999 6 ▶sub _entropy_pp {
Subroutine _entropy_pp: called CC=4 SCAR=13.9
2000 6 my ($str) = @_;
2001 6 utf8::encode($str);
2002 6 my $n = length $str;
2003 6 ▶ return 0 unless $n;
Branch: 1 branch
BranchTrueFalseTotal
unless $n 1 5 6
2004 5 my %count;
2005 5 $count{$_}++ for unpack 'C*', $str;
2006 5 my $ln2 = log(2);
2007 5 my $h = 0;
2008  
2009 5 for my $c ( values %count ) {
2010 28 my $p = $c / $n;
2011 28 $h -= $p * ( log($p) / $ln2 );
2012 }
2013 5 return $h;
2014 } ## end sub _entropy_pp
2015  
2016 =head2 ngram
2017  
2018 { munger => 'ngram', counts => { th => 152, he => 128, in => 94, ... } }
2019 # defaults: smoothing => 1, fold_case => 1; n is inferred from the keys
2020  
2021 Mean per-gram surprisal of the input string against a B<precomputed, frozen>
2022 n-gram count table: C<sum(-ln p(gram)) / gram_count>, each gram's probability
2023 smoothed exactly as in L</frozen_freq_map>. This is C<frozen_freq_map>'s sequential cousin
2024 and the strongest single gibberish detector: L</entropy> misses
2025 I<pronounceable> generated names and is unreliable on short strings, while an
2026 n-gram score against (say) hostname bigram statistics catches both -- real
2027 words ride the common bigrams and score low, generated names keep hitting rare
2028 ones and score high. Dividing by the gram count keeps scores comparable across
2029 lengths.
2030  
2031 C<counts> maps each n-gram to how often it was observed when the table was
2032 built; all keys must be the same length, and that length B<is> C<n> (bigrams
2033 are the usual choice -- a 26x26 table stays tiny in C<info.json>; past
2034 C<$FROZEN_FREQ_MAP_WARN_KEYS> entries it warns like C<frozen_freq_map>). C<total> defaults
2035 to the sum of counts and may be given larger to prune the tail, exactly as in
2036 C<frozen_freq_map>. A gram absent from the table gets the smoothed unseen-bucket
2037 probability -- an unseen gram is the interesting case -- so C<smoothing> must
2038 be > 0 (default C<1>). With C<fold_case> (default on) the input is lowercased
2039 before scoring, matching the usual lowercased table. A string with no grams
2040 (shorter than C<n>) scores C<0>. Grams are taken over B<characters>, matching
2041 L</length> rather than the byte-oriented C<entropy>.
2042  
2043 =cut
2044  
2045 7 ▶sub _build_ngram {
Subroutine _build_ngram: called CC=19 SCAR=29.6
2046 7 my ( $spec, $where ) = @_;
2047  
2048 7 my $counts = $spec->{counts};
2049 7 ▶ croak "ngram munger$where requires a non-empty 'counts' hashref"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $counts eq "HASH" and %$counts 1 6 7
Condition66%2/3
ref $counts eq "HASH" and %$counts
!ll&&!rl&&r
016
MC/DC50%1/2
ref $counts eq "HASH" and %$counts
ref $counts eq "HASH" %$counts
Truth table66%2/3
A and B
A= ref $counts eq "HASH"B= %$counts
ABresult
0X0
100
111
2050 unless ref $counts eq 'HASH' && %$counts;
2051  
2052 6 my $n;
2053 6 my $sum = 0;
2054 6 for my $g ( keys %$counts ) {
2055 9 ▶ $n = length $g unless defined $n;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n 6 3 9
2056 9 ▶ croak "ngram munger$where: all 'counts' keys must be the same length "
Branch: 1 branch
BranchTrueFalseTotal
unless length $g == $n 1 8 9
2057 . "(that length is n); got '$g' alongside a $n-gram"
2058 unless length($g) == $n;
2059 8 my $c = $counts->{$g};
2060 8 ▶ croak "ngram munger$where: count for '$g' ('"
Branch: 2 branches
BranchTrueFalseTotal
unless &looks_like_number($c) and $c >= 0 1 7 8
defined $c ? : 1 0 1
Condition66%2/3
&looks_like_number($c) and $c >= 0
!ll&&!rl&&r
107
MC/DC50%1/2
&looks_like_number($c) and $c >= 0
&looks_like_number($c) $c >= 0
Truth table66%2/3
A and B
A= &looks_like_number($c)B= $c >= 0
ABresult
0X0
100
111
2061 . ( defined $c ? $c : 'undef' )
2062 . "') is not a non-negative number"
2063 unless looks_like_number($c) && $c >= 0;
2064 7 $sum += $c;
2065 } ## end for my $g ( keys %$counts )
2066 4 ▶ croak "ngram munger$where: 'counts' keys must be at least 1 character"
Branch: 1 branch
BranchTrueFalseTotal
unless $n >= 1 0 4 4
2067 unless $n >= 1;
2068  
2069 4 my $V = keys %$counts;
2070 4 ▶ carp "ngram munger$where: 'counts' has $V keys; a table this large bloats info.json"
Branch: 1 branch
BranchTrueFalseTotal
if $V > $Algorithm::ToNumberMunger::FROZEN_FREQ_MAP_WARN_KEYS 0 4 4
2071 if $V > $FROZEN_FREQ_MAP_WARN_KEYS;
2072  
2073 4 ▶ my $total = defined $spec->{total} ? $spec->{total} : $sum;
Branch: 1 branch
BranchTrueFalseTotal
defined $spec->{'total'} ? : 1 3 4
2074 4 ▶ croak "ngram munger$where: 'total' must be numeric"
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($total) 0 4 4
2075 unless looks_like_number($total);
2076 4 ▶ croak "ngram munger$where: 'total' ($total) must be >= sum of counts ($sum)"
Branch: 1 branch
BranchTrueFalseTotal
if $total < $sum 1 3 4
2077 if $total < $sum;
2078  
2079 3 ▶ my $s = defined $spec->{smoothing} ? $spec->{smoothing} : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $spec->{'smoothing'} ? : 1 2 3
2080 3 ▶ croak "ngram munger$where: 'smoothing' must be a number > 0 "
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($s) and $s > 0 1 2 3
Condition66%2/3
&looks_like_number($s) and $s > 0
!ll&&!rl&&r
012
MC/DC50%1/2
&looks_like_number($s) and $s > 0
&looks_like_number($s) $s > 0
Truth table66%2/3
A and B
A= &looks_like_number($s)B= $s > 0
ABresult
0X0
100
111
2081 . '(an unseen gram would otherwise be infinitely surprising)'
2082 unless looks_like_number($s) && $s > 0;
2083  
2084 2 ▶ my $fold = exists $spec->{fold_case} ? ( $spec->{fold_case} ? 1 : 0 ) : 1;
Branch: 2 branches
BranchTrueFalseTotal
exists $spec->{'fold_case'} ? : 1 1 2
$spec->{'fold_case'} ? : 0 1 1
2085  
2086 # Same smoothed-probability scheme as frozen_freq_map, "unseen" as one extra
2087 # bucket; surprisal precomputed per listed gram.
2088 2 my $denom = $total + $s * ( $V + 1 );
2089 2 my %si = map { $_ => -log( ( $counts->{$_} + $s ) / $denom ) } keys %$counts;
2090 2 my $unseen = -log( $s / $denom );
2091  
2092 12 ▶ return sub {
Subroutine __ANON__: called CC=6 SCAR=17.9
2093 12 my ($v) = @_;
2094 12 ▶ my $str = defined $v ? "$v" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 11 1 12
2095 12 ▶ $str = lc $str if $fold;
Branch: 1 branch
BranchTrueFalseTotal
if $fold 10 2 12
2096 12 my $grams = length($str) - $n + 1;
2097 12 ▶ return 0 if $grams < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $grams < 1 3 9 12
2098 9 my $tot = 0;
2099 9 for my $i ( 0 .. $grams - 1 ) {
2100 14 my $g = substr( $str, $i, $n );
2101 14 ▶ $tot += exists $si{$g} ? $si{$g} : $unseen;
Branch: 1 branch
BranchTrueFalseTotal
exists $si{$g} ? : 9 5 14
2102 }
2103 9 return $tot / $grams;
2104 2 }; ## end sub
2105 } ## end sub _build_ngram
2106  
2107 =head2 char
2108  
2109 { munger => 'char', class => 'non_alnum', mode => 'ratio' }
2110 { munger => 'char', class => 'non_ascii' } # mode defaults to count
2111  
2112 Count the characters of the input that fall in a named C<class>, either as a raw
2113 C<count> (default) or, with C<< mode => 'ratio' >>, as a fraction of the string's
2114 length (C<0> for an empty string). This is the injection / obfuscation detector
2115 behind columns like C<url_non_alnum> (a I<ratio>, so it stays independent of
2116 length) and C<filename_non_ascii> (a I<count>): payloads and homoglyph tricks
2117 are dense with punctuation, percent-encoding, or non-ASCII where normal input is
2118 not. Counting is over B<characters>, so C<non_ascii> means codepoints above 127.
2119  
2120 Recognised classes: C<alnum> / C<non_alnum>, C<ascii> / C<non_ascii>, C<digit>,
2121 C<alpha>, C<upper>, C<lower>, C<vowel>, C<consonant>, C<xdigit>, C<space>,
2122 C<punct>. C<vowel> and C<consonant> are the ASCII letters (C<y> counting as a
2123 consonant) -- a vowel/consonant I<ratio> is a DGA corroborator that catches
2124 consonant-heavy random strings C<entropy> alone underrates; C<xdigit> is
2125 C<0-9a-fA-F>, dense in encoded payloads.
2126  
2127 =cut
2128  
2129 # class name => a counting sub over an (already copied) string. The literal-
2130 # range classes count with tr///, which runs at C speed -- an order of
2131 # magnitude faster than tallying regex matches. tr/// needs its ranges spelled
2132 # at compile time, hence one sub per class rather than a data table. The 'run'
2133 # munger's %RUN_RE mirrors these class names; keep the two in sync.
2134 my %CHAR_COUNT = (
2135 0 ▶ alnum => sub { $_[0] =~ tr/A-Za-z0-9// },
Subroutine __ANON__: not called CC=1 SCAR=6.9
2136 3 ▶ non_alnum => sub { $_[0] =~ tr/A-Za-z0-9//c },
Subroutine __ANON__: called CC=1 SCAR=0.0
2137 0 ▶ ascii => sub { $_[0] =~ tr/\x00-\x7f// },
Subroutine __ANON__: not called CC=1 SCAR=6.9
2138 2 ▶ non_ascii => sub { $_[0] =~ tr/\x00-\x7f//c },
Subroutine __ANON__: called CC=1 SCAR=0.0
2139 1 ▶ digit => sub { $_[0] =~ tr/0-9// },
Subroutine __ANON__: called CC=1 SCAR=0.0
2140 0 ▶ alpha => sub { $_[0] =~ tr/A-Za-z// },
Subroutine __ANON__: not called CC=1 SCAR=6.9
2141 0 ▶ upper => sub { $_[0] =~ tr/A-Z// },
Subroutine __ANON__: not called CC=1 SCAR=6.9
2142 0 ▶ lower => sub { $_[0] =~ tr/a-z// },
Subroutine __ANON__: not called CC=1 SCAR=6.9
2143 1 ▶ vowel => sub { $_[0] =~ tr/aeiouAEIOU// },
Subroutine __ANON__: called CC=1 SCAR=0.0
2144 1 ▶ consonant => sub { $_[0] =~ tr/b-df-hj-np-tv-zB-DF-HJ-NP-TV-Z// },
Subroutine __ANON__: called CC=1 SCAR=0.0
2145 1 ▶ xdigit => sub { $_[0] =~ tr/0-9A-Fa-f// },
Subroutine __ANON__: called CC=1 SCAR=0.0
2146 # space and punct match richer classes (\s, [[:punct:]], including their
2147 # Unicode behavior) that tr/// ranges cannot reproduce; they stay on the
2148 # regex so their semantics do not change.
2149 1 ▶ space => sub { my $n = () = $_[0] =~ /\s/g; $n },
Subroutine __ANON__: called CC=1 SCAR=0.0
2150 1 ▶ punct => sub { my $n = () = $_[0] =~ /[[:punct:]]/g; $n },
Subroutine __ANON__: called CC=1 SCAR=0.0
2151 6 );
2152  
2153 10 ▶sub _build_char {
Subroutine _build_char: called CC=7 SCAR=19.5
2154 10 my ( $spec, $where ) = @_;
2155  
2156 10 my $class = $spec->{class};
2157 10 ▶ croak "char munger$where requires a 'class'"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class 0 10 10
2158 unless defined $class;
2159 10 ▶ my $count = $CHAR_COUNT{$class}
Branch: 1 branch
BranchTrueFalseTotal
my $count = $CHAR_COUNT{$class} or croak("char munger${where}: unknown class '${class}' (known: " . join(", ", sort(keys %CHAR_COUNT)) . ')') 9 1 10
2160 or croak "char munger$where: unknown class '$class' (known: " . join( ', ', sort keys %CHAR_COUNT ) . ')';
2161  
2162 9 ▶ my $mode = defined $spec->{mode} ? $spec->{mode} : 'count';
Branch: 1 branch
BranchTrueFalseTotal
defined $spec->{'mode'} ? : 2 7 9
2163 9 ▶ croak "char munger$where: 'mode' must be 'count' or 'ratio'"
Branch: 1 branch
BranchTrueFalseTotal
unless $mode eq "count" or $mode eq "ratio" 1 8 9
Condition100%3/3
$mode eq "count" or $mode eq "ratio"
l!l&&r!l&&!r
711
MC/DC100%2/2
$mode eq "count" or $mode eq "ratio"
$mode eq "count" $mode eq "ratio"
Truth table100%3/3
A or B
A= $mode eq "count"B= $mode eq "ratio"
ABresult
1X1
011
000
2164 unless $mode eq 'count' || $mode eq 'ratio';
2165 8 ▶ my $ratio = $mode eq 'ratio' ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$mode eq 'ratio' ? : 1 7 8
2166  
2167 11 ▶ return sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
2168 11 my ($v) = @_;
2169 11 ▶ my $s = defined $v ? "$v" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 11 0 11
2170 11 my $n = $count->($s);
2171 11 ▶ return $n unless $ratio;
Branch: 1 branch
BranchTrueFalseTotal
unless $ratio 8 3 11
2172 3 my $len = length $s;
2173 3 ▶ return $len ? $n / $len : 0;
Branch: 1 branch
BranchTrueFalseTotal
$len ? : 2 1 3
2174 8 };
2175 } ## end sub _build_char
2176  
2177 =head2 run
2178  
2179 { munger => 'run', class => 'consonant' }
2180 { munger => 'run', class => 'digit' }
2181  
2182 The length of the longest unbroken run of characters in a named C<class> --
2183 the same class names L</char> recognises. Where C<char> counts how many such
2184 characters occur in total, C<run> measures how tightly they clump: the
2185 longest consonant run and longest digit run are staple generated-name (DGA)
2186 features that neither total counts nor L</entropy> capture, because a real
2187 word breaks its consonants up with vowels while a random string will happily
2188 emit six in a row. An empty or undef input is C<0>.
2189  
2190 =cut
2191  
2192 # class name => a character-class pattern for the 'run' munger. Mirrors
2193 # %CHAR_COUNT's class names (keep in sync); runs need a regex quantifier, so
2194 # tr///'s speed trick does not apply here.
2195 6 my %RUN_RE = (
2196 alnum => '[A-Za-z0-9]',
2197 non_alnum => '[^A-Za-z0-9]',
2198 ascii => '[\x00-\x7f]',
2199 non_ascii => '[^\x00-\x7f]',
2200 digit => '[0-9]',
2201 alpha => '[A-Za-z]',
2202 upper => '[A-Z]',
2203 lower => '[a-z]',
2204 vowel => '[aeiouAEIOU]',
2205 consonant => '[b-df-hj-np-tv-zB-DF-HJ-NP-TV-Z]',
2206 xdigit => '[0-9A-Fa-f]',
2207 space => '\s',
2208 punct => '[[:punct:]]',
2209 );
2210  
2211 4 ▶sub _build_run {
Subroutine _build_run: called CC=3 SCAR=11.0
2212 4 my ( $spec, $where ) = @_;
2213  
2214 4 my $class = $spec->{class};
2215 4 ▶ croak "run munger$where requires a 'class'"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class 1 3 4
2216 unless defined $class;
2217 3 ▶ my $cc = $RUN_RE{$class}
Branch: 1 branch
BranchTrueFalseTotal
my $cc = $RUN_RE{$class} or croak("run munger${where}: unknown class '${class}' (known: " . join(", ", sort(keys %RUN_RE)) . ')') 2 1 3
2218 or croak "run munger$where: unknown class '$class' (known: " . join( ', ', sort keys %RUN_RE ) . ')';
2219 2 my $re = qr/((?:$cc)+)/;
2220  
2221 6 ▶ return sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
2222 6 my ($v) = @_;
2223 6 ▶ my $s = defined $v ? "$v" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 5 1 6
2224 6 my $max = 0;
2225 6 ▶ while ( $s =~ /$re/g ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($s =~ /$re/g) 6 6 12
2226 6 ▶ $max = length $1 if length $1 > $max;
Branch: 1 branch
BranchTrueFalseTotal
if length $1 > $max 4 2 6
2227 }
2228 6 return $max;
2229 2 };
2230 } ## end sub _build_run
2231  
2232 =head2 count
2233  
2234 { munger => 'count', of => '/' } # url_path_depth, topic_depth
2235 { munger => 'count', of => '.', plus => 1 } # label_count (dots + 1)
2236  
2237 Count non-overlapping occurrences of a literal substring C<of> in the input,
2238 optionally adding a constant C<plus>. This is the segment/depth feature behind
2239 C<url_path_depth> and C<topic_depth> (count of C<`/`>) and C<label_count> (dots
2240 plus one). C<of> is matched literally, not as a pattern, so C<.> means a literal
2241 dot.
2242  
2243 =cut
2244  
2245 4 ▶sub _build_count {
Subroutine _build_count: called CC=5 SCAR=16.2
2246 4 my ( $spec, $where ) = @_;
2247  
2248 4 my $of = $spec->{of};
2249 4 ▶ croak "count munger$where requires a non-empty 'of' string"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $of and length $of 1 3 4
Condition66%2/3
defined $of and length $of
!ll&&!rl&&r
103
MC/DC50%1/2
defined $of and length $of
defined $of length $of
Truth table66%2/3
A and B
A= defined $ofB= length $of
ABresult
0X0
100
111
2250 unless defined $of && length $of;
2251  
2252 3 ▶ my $plus = defined $spec->{plus} ? $spec->{plus} : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $spec->{'plus'} ? : 1 2 3
2253 3 ▶ croak "count munger$where: 'plus' must be numeric"
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($plus) 0 3 3
2254 unless looks_like_number($plus);
2255  
2256 # index() beats a global regex match here: no pattern engine, and no
2257 # per-call list of matches just to count them. Advancing by length($of)
2258 # keeps the non-overlapping semantics m//g had.
2259 3 my $oflen = length $of;
2260 6 ▶ return sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
2261 6 my ($v) = @_;
2262 6 ▶ my $s = defined $v ? "$v" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 6 0 6
2263 6 my $n = 0;
2264 6 my $p = 0;
2265 6 ▶ while ( ( $p = index( $s, $of, $p ) ) >= 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (($p = index($s, $of, $p)) >= 0) 10 6 16
2266 10 $n++;
2267 10 $p += $oflen;
2268 }
2269 6 return $n + $plus;
2270 3 }; ## end sub
2271 } ## end sub _build_count
2272  
2273 =head2 match
2274  
2275 { munger => 'match', pattern => '^xn--' } # punycode label
2276 { munger => 'match', pattern => '%[0-9A-Fa-f]{2}', mode => 'count' }
2277  
2278 Match the input against a Perl regular expression C<pattern>: C<1>/C<0> under
2279 the default C<< mode => 'bool' >>, or the number of non-overlapping matches
2280 with C<< mode => 'count' >>. A true C<ignore_case> makes the match
2281 case-insensitive. This is the catch-all shape test behind flags like "is this
2282 label punycode" or "is the Host an IP literal", and counters like
2283 percent-escapes in a URL -- anything L</char> and L</count> are not expressive
2284 enough for. The pattern is compiled at build time, so a broken one fails at
2285 C<write_info> rather than per row.
2286  
2287 B<Trust note:> a pattern cannot execute code (Perl requires C<use re 'eval'>
2288 for that, which this module does not enable), but a pathological pattern can
2289 still backtrack catastrophically and stall a writer. Treat munger specs --
2290 like the rest of C<info.json> -- as configuration from a trusted operator,
2291 not as untrusted input.
2292  
2293 =cut
2294  
2295 6 ▶sub _build_match {
Subroutine _build_match: called CC=9 SCAR=22.0
2296 6 my ( $spec, $where ) = @_;
2297  
2298 6 my $pat = $spec->{pattern};
2299 6 ▶ croak "match munger$where requires a non-empty 'pattern'"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pat and length $pat 1 5 6
Condition66%2/3
defined $pat and length $pat
!ll&&!rl&&r
105
MC/DC50%1/2
defined $pat and length $pat
defined $pat length $pat
Truth table66%2/3
A and B
A= defined $patB= length $pat
ABresult
0X0
100
111
2300 unless defined $pat && length $pat;
2301  
2302 5 ▶ my $mode = defined $spec->{mode} ? $spec->{mode} : 'bool';
Branch: 1 branch
BranchTrueFalseTotal
defined $spec->{'mode'} ? : 2 3 5
2303 5 ▶ croak "match munger$where: 'mode' must be 'bool' or 'count'"
Branch: 1 branch
BranchTrueFalseTotal
unless $mode eq "bool" or $mode eq "count" 1 4 5
Condition100%3/3
$mode eq "bool" or $mode eq "count"
l!l&&r!l&&!r
311
MC/DC100%2/2
$mode eq "bool" or $mode eq "count"
$mode eq "bool" $mode eq "count"
Truth table100%3/3
A or B
A= $mode eq "bool"B= $mode eq "count"
ABresult
1X1
011
000
2304 unless $mode eq 'bool' || $mode eq 'count';
2305  
2306 # qr// on spec text cannot run code -- (?{...}) needs 'use re "eval"',
2307 # which is not enabled here -- but it can be syntactically invalid, so
2308 # compile eagerly and croak at build time.
2309 4 ▶ my $re = eval { $spec->{ignore_case} ? qr/$pat/i : qr/$pat/ };
Branch: 1 branch
BranchTrueFalseTotal
$spec->{'ignore_case'} ? : 1 3 4
2310 4 ▶ croak "match munger$where: cannot compile pattern '$pat': $@"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $re 1 3 4
2311 unless defined $re;
2312  
2313 3 ▶ if ( $mode eq 'bool' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mode eq "bool") 2 1 3
2314 4 ▶ return sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
2315 4 ▶ my $s = defined $_[0] ? "$_[0]" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] ? : 3 1 4
2316 4 ▶ return $s =~ $re ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$s =~ /$re/ ? : 2 2 4
2317 2 };
2318 }
2319 2 ▶ return sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
2320 2 ▶ my $s = defined $_[0] ? "$_[0]" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] ? : 2 0 2
2321 2 my $n = () = $s =~ /$re/g;
2322 2 return $n;
2323 1 };
2324 } ## end sub _build_match
2325  
2326 =head2 bucket
2327  
2328 { munger => 'bucket', bounds => [ 1024, 49152 ] } # dest_port classes
2329  
2330 Map a number to a bucket index by ascending C<bounds>: the result is how many
2331 bounds the value is greater than or equal to. With C<< bounds => [1024, 49152] >>
2332 a value under C<1024> is C<0> (well-known), C<1024>-C<49151> is C<1> (registered),
2333 and C<49152>+ is C<2> (ephemeral) -- the classic port classing, where the literal
2334 port number is meaningless to a threshold split but the I<class> is a real
2335 signal. C<bounds> must be strictly ascending; N bounds yield indices C<0>..C<N>.
2336  
2337 This generalises the C<*_enum> status-class mungers, which are the special case
2338 of bucketing a reply code by its leading digit.
2339  
2340 =cut
2341  
2342 3 ▶sub _build_bucket {
Subroutine _build_bucket: called CC=8 SCAR=21.4
2343 3 my ( $spec, $where ) = @_;
2344  
2345 3 my $bounds = $spec->{bounds};
2346 3 ▶ croak "bucket munger$where requires a non-empty 'bounds' arrayref"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $bounds eq "ARRAY" and @$bounds 1 2 3
Condition66%2/3
ref $bounds eq "ARRAY" and @$bounds
!ll&&!rl&&r
012
MC/DC50%1/2
ref $bounds eq "ARRAY" and @$bounds
ref $bounds eq "ARRAY" @$bounds
Truth table66%2/3
A and B
A= ref $bounds eq "ARRAY"B= @$bounds
ABresult
0X0
100
111
2347 unless ref $bounds eq 'ARRAY' && @$bounds;
2348  
2349 2 my @b = @$bounds;
2350 2 for my $i ( 0 .. $#b ) {
2351 4 ▶ croak "bucket munger$where: bound[$i] ('" . ( defined $b[$i] ? $b[$i] : 'undef' ) . "') is not numeric"
Branch: 2 branches
BranchTrueFalseTotal
unless &looks_like_number($b[$i]) 0 4 4
defined $b[$i] ? : 0 0 0
2352 unless looks_like_number( $b[$i] );
2353 4 ▶ croak "bucket munger$where: 'bounds' must be strictly ascending"
Branch: 1 branch
BranchTrueFalseTotal
if $i and $b[$i] <= $b[$i - 1] 1 3 4
Condition100%3/3
$i and $b[$i] <= $b[$i - 1]
!ll&&!rl&&r
211
MC/DC100%2/2
$i and $b[$i] <= $b[$i - 1]
$i $b[$i] <= $b[$i - 1]
Truth table100%3/3
A and B
A= $iB= $b[$i] <= $b[$i - 1]
ABresult
0X0
100
111
2354 if $i && $b[$i] <= $b[ $i - 1 ];
2355 }
2356  
2357 6 ▶ return sub {
Subroutine __ANON__: called CC=5 SCAR=16.7
2358 6 my ($v) = @_;
2359 6 ▶ croak "bucket munger$where: '" . ( defined $v ? $v : 'undef' ) . "' is not numeric"
Branch: 2 branches
BranchTrueFalseTotal
unless &looks_like_number($v) 0 6 6
defined $v ? : 0 0 0
2360 unless looks_like_number($v);
2361 6 my $idx = 0;
2362 6 for my $bound (@b) {
2363 10 ▶ last if $v < $bound;
Branch: 1 branch
BranchTrueFalseTotal
if $v < $bound 4 6 10
2364 6 $idx++;
2365 }
2366 6 return $idx;
2367 1 }; ## end sub
2368 } ## end sub _build_bucket
2369  
2370 =head2 quantile
2371  
2372 { munger => 'quantile', bounds => [ 40, 180, 460, 2200, 64000 ] }
2373  
2374 Piecewise-linear ECDF: map a number onto C<[0, 1]> by where it falls among
2375 ascending C<bounds> taken from the training data's quantiles (e.g. its
2376 min / p25 / p50 / p75 / max). Values at or below the first bound map to C<0>,
2377 at or above the last to C<1>, and anything between two adjacent bounds
2378 interpolates linearly between their positions. This is L</bucket>'s continuous
2379 sibling and the heavy-tail normaliser to reach for when L</log> is not enough
2380 and L</zscore> would let one outlier stretch the whole scale: after the
2381 transform the training distribution is roughly uniform, so a forest threshold
2382 split lands anywhere in it with equal ease. C<bounds> must be strictly
2383 ascending with at least two values; like C<zscore>, the parameters are
2384 supplied rather than learned, so munging stays stateless.
2385  
2386 =cut
2387  
2388 3 ▶sub _build_quantile {
Subroutine _build_quantile: called CC=8 SCAR=20.9
2389 3 my ( $spec, $where ) = @_;
2390  
2391 3 my $bounds = $spec->{bounds};
2392 3 ▶ croak "quantile munger$where requires a 'bounds' arrayref with at least 2 values"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $bounds eq "ARRAY" and @$bounds >= 2 1 2 3
Condition66%2/3
ref $bounds eq "ARRAY" and @$bounds >= 2
!ll&&!rl&&r
012
MC/DC50%1/2
ref $bounds eq "ARRAY" and @$bounds >= 2
ref $bounds eq "ARRAY" @$bounds >= 2
Truth table66%2/3
A and B
A= ref $bounds eq "ARRAY"B= @$bounds >= 2
ABresult
0X0
100
111
2393 unless ref $bounds eq 'ARRAY' && @$bounds >= 2;
2394  
2395 2 my @b = @$bounds;
2396 2 for my $i ( 0 .. $#b ) {
2397 7 ▶ croak "quantile munger$where: bound[$i] ('" . ( defined $b[$i] ? $b[$i] : 'undef' ) . "') is not numeric"
Branch: 2 branches
BranchTrueFalseTotal
unless &looks_like_number($b[$i]) 0 7 7
defined $b[$i] ? : 0 0 0
2398 unless looks_like_number( $b[$i] );
2399 7 ▶ croak "quantile munger$where: 'bounds' must be strictly ascending"
Branch: 1 branch
BranchTrueFalseTotal
if $i and $b[$i] <= $b[$i - 1] 1 6 7
Condition100%3/3
$i and $b[$i] <= $b[$i - 1]
!ll&&!rl&&r
241
MC/DC100%2/2
$i and $b[$i] <= $b[$i - 1]
$i $b[$i] <= $b[$i - 1]
Truth table100%3/3
A and B
A= $iB= $b[$i] <= $b[$i - 1]
ABresult
0X0
100
111
2400 if $i && $b[$i] <= $b[ $i - 1 ];
2401 }
2402 1 my $segs = $#b;
2403  
2404 9 ▶ return sub {
Subroutine __ANON__: called CC=6 SCAR=17.9
2405 9 my ($v) = @_;
2406 9 ▶ croak "quantile munger$where: '" . ( defined $v ? $v : 'undef' ) . "' is not numeric"
Branch: 2 branches
BranchTrueFalseTotal
unless &looks_like_number($v) 1 8 9
defined $v ? : 1 0 1
2407 unless looks_like_number($v);
2408 8 ▶ return 0 if $v <= $b[0];
Branch: 1 branch
BranchTrueFalseTotal
if $v <= $b[0] 2 6 8
2409 6 ▶ return 1 if $v >= $b[-1];
Branch: 1 branch
BranchTrueFalseTotal
if $v >= $b[-1] 2 4 6
2410 4 my $i = 0;
2411 4 ▶ $i++ while $v >= $b[ $i + 1 ];
Branch: 1 branch
BranchTrueFalseTotal
$v >= $b[$i + 1] and do { ++$i } 5 4 9
2412 4 return ( $i + ( $v - $b[$i] ) / ( $b[ $i + 1 ] - $b[$i] ) ) / $segs;
2413 1 }; ## end sub
2414 } ## end sub _build_quantile
2415  
2416 =head2 scale
2417  
2418 { munger => 'scale', min => 0, max => 1000, clamp => 1 }
2419  
2420 Min-max normalisation: C<(v - min) / (max - min)>, mapping C<[min, max]> onto
2421 C<[0, 1]>. C<min> and C<max> must differ. With a true C<clamp>, results are
2422 pinned into C<[0, 1]> so out-of-range inputs cannot escape the unit interval.
2423  
2424 =cut
2425  
2426 3 ▶sub _build_scale {
Subroutine _build_scale: called CC=5 SCAR=16.4
2427 3 my ( $spec, $where ) = @_;
2428  
2429 3 my ( $min, $max ) = @{$spec}{qw(min max)};
2430 3 ▶ croak "scale munger$where requires numeric 'min' and 'max'"
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($min) and &looks_like_number($max) 0 3 3
Condition33%1/3
&looks_like_number($min) and &looks_like_number($max)
!ll&&!rl&&r
003
MC/DC0%0/2
&looks_like_number($min) and &looks_like_number($max)
&looks_like_number($min) &looks_like_number($max)
Truth table33%1/3
A and B
A= &looks_like_number($min)B= &looks_like_number($max)
ABresult
0X0
100
111
2431 unless looks_like_number($min) && looks_like_number($max);
2432  
2433 3 my $range = $max - $min;
2434 3 ▶ croak "scale munger$where: 'min' and 'max' must differ"
Branch: 1 branch
BranchTrueFalseTotal
if $range == 0 1 2 3
2435 if $range == 0;
2436  
2437 2 ▶ my $clamp = $spec->{clamp} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$spec->{'clamp'} ? : 1 1 2
2438 4 ▶ return sub {
Subroutine __ANON__: called CC=6 SCAR=18.2
2439 4 my ($v) = @_;
2440 4 ▶ croak "scale munger$where: '" . ( defined $v ? $v : 'undef' ) . "' is not numeric"
Branch: 2 branches
BranchTrueFalseTotal
unless &looks_like_number($v) 0 4 4
defined $v ? : 0 0 0
2441 unless looks_like_number($v);
2442 4 my $s = ( $v - $min ) / $range;
2443 4 ▶ if ($clamp) { $s = 0 if $s < 0; $s = 1 if $s > 1; }
Branch: 3 branches
BranchTrueFalseTotal
if ($clamp) 2 2 4
if $s < 0 1 1 2
if $s > 1 1 1 2
2444 4 return $s;
2445 2 };
2446 } ## end sub _build_scale
2447  
2448 =head2 zscore
2449  
2450 { munger => 'zscore', mean => 42.0, std => 7.5 }
2451  
2452 Standardise: C<(v - mean) / std>. C<std> must be non-zero. The C<mean>/C<std>
2453 are supplied (this module does not learn them) so munging stays stateless and a
2454 row can be munged in isolation.
2455  
2456 =cut
2457  
2458 2 ▶sub _build_zscore {
Subroutine _build_zscore: called CC=4 SCAR=14.9
2459 2 my ( $spec, $where ) = @_;
2460  
2461 2 my ( $mean, $std ) = @{$spec}{qw(mean std)};
2462 2 ▶ croak "zscore munger$where requires numeric 'mean' and 'std'"
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($mean) and &looks_like_number($std) 0 2 2
Condition33%1/3
&looks_like_number($mean) and &looks_like_number($std)
!ll&&!rl&&r
002
MC/DC0%0/2
&looks_like_number($mean) and &looks_like_number($std)
&looks_like_number($mean) &looks_like_number($std)
Truth table33%1/3
A and B
A= &looks_like_number($mean)B= &looks_like_number($std)
ABresult
0X0
100
111
2463 unless looks_like_number($mean) && looks_like_number($std);
2464 2 ▶ croak "zscore munger$where: 'std' must be non-zero"
Branch: 1 branch
BranchTrueFalseTotal
if $std == 0 1 1 2
2465 if $std == 0;
2466  
2467 2 ▶ return sub {
Subroutine __ANON__: called CC=3 SCAR=13.1
2468 2 my ($v) = @_;
2469 2 ▶ croak "zscore munger$where: '" . ( defined $v ? $v : 'undef' ) . "' is not numeric"
Branch: 2 branches
BranchTrueFalseTotal
unless &looks_like_number($v) 0 2 2
defined $v ? : 0 0 0
2470 unless looks_like_number($v);
2471 2 return ( $v - $mean ) / $std;
2472 1 };
2473 } ## end sub _build_zscore
2474  
2475 =head2 log
2476  
2477 { munger => 'log' } # natural log
2478 { munger => 'log', offset => 1 } # log1p-style, so 0 is allowed
2479 { munger => 'log', base => 10, offset => 1 }
2480  
2481 Logarithm of C<v + offset>. Heavy-tailed counts (bytes, durations) compress well
2482 under a log, which keeps a few huge values from dominating the forest. C<offset>
2483 (default C<0>) shifts the input so zeros/small values are representable; the
2484 shifted value must be strictly positive or the input croaks. C<base> defaults to
2485 natural log.
2486  
2487 =cut
2488  
2489 8 ▶sub _build_log {
Subroutine _build_log: called CC=7 SCAR=19.8
2490 8 my ( $spec, $where ) = @_;
2491  
2492 8 ▶ my $offset = exists $spec->{offset} ? $spec->{offset} : 0;
Branch: 1 branch
BranchTrueFalseTotal
exists $spec->{'offset'} ? : 6 2 8
2493 8 ▶ croak "log munger$where: 'offset' must be numeric"
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($offset) 0 8 8
2494 unless looks_like_number($offset);
2495  
2496 8 my $ln_base;
2497 8 ▶ if ( defined $spec->{base} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $spec->{"base"}) 2 6 8
2498 croak "log munger$where: 'base' must be numeric and > 0 and != 1"
2499 unless looks_like_number( $spec->{base} )
2500 && $spec->{base} > 0
2501 2 ▶ && $spec->{base} != 1;
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($spec->{"base"}) and $spec->{"base"} > 0 and $spec->{"base"} != 1 1 1 2
Condition66%4/6
&looks_like_number($spec->{"base"}) and $spec->{"base"} > 0 and $spec->{"base"} != 1
!ll&&!rl&&r
101
&looks_like_number($spec->{"base"}) and $spec->{"base"} > 0
!ll&&!rl&&r
101
MC/DC33%1/3
&looks_like_number($spec->{"base"}) and $spec->{"base"} > 0 and $spec->{"base"} != 1
&looks_like_number($spec->{"base"}) $spec->{"base"} > 0 $spec->{"base"} != 1
Truth table50%2/4
A and B and C
A= &looks_like_number($spec->{"base"})B= $spec->{"base"} > 0C= $spec->{"base"} != 1
ABCresult
0XX0
10X0
1100
1111
2502 1 $ln_base = log( $spec->{base} );
2503 }
2504  
2505 9 ▶ return sub {
Subroutine __ANON__: called CC=5 SCAR=16.5
2506 9 my ($v) = @_;
2507 9 ▶ croak "log munger$where: '" . ( defined $v ? $v : 'undef' ) . "' is not numeric"
Branch: 2 branches
BranchTrueFalseTotal
unless &looks_like_number($v) 0 9 9
defined $v ? : 0 0 0
2508 unless looks_like_number($v);
2509 9 my $x = $v + $offset;
2510 9 ▶ croak "log munger$where: value+offset must be > 0 (got $x)"
Branch: 1 branch
BranchTrueFalseTotal
unless $x > 0 1 8 9
2511 unless $x > 0;
2512 8 my $r = log($x);
2513 8 ▶ $r /= $ln_base if defined $ln_base;
Branch: 1 branch
BranchTrueFalseTotal
if defined $ln_base 1 7 8
2514 8 return $r;
2515 7 }; ## end sub
2516 } ## end sub _build_log
2517  
2518 =head2 clamp
2519  
2520 { munger => 'clamp', min => 0 }
2521 { munger => 'clamp', min => 0, max => 65535 }
2522  
2523 Pass the number through, pinned into C<[min, max]>. Either bound may be omitted
2524 to clamp on one side only. Unlike C<scale> this does not rescale; it only caps
2525 outliers before they reach the model.
2526  
2527 =cut
2528  
2529 3 ▶sub _build_clamp {
Subroutine _build_clamp: called CC=10 SCAR=24.5
2530 3 my ( $spec, $where ) = @_;
2531  
2532 3 my ( $min, $max ) = @{$spec}{qw(min max)};
2533 3 my $have_min = defined $min;
2534 3 my $have_max = defined $max;
2535 3 ▶ croak "clamp munger$where needs at least one of 'min' or 'max'"
Branch: 1 branch
BranchTrueFalseTotal
unless $have_min or $have_max 1 2 3
Condition66%2/3
$have_min or $have_max
l!l&&r!l&&!r
201
MC/DC50%1/2
$have_min or $have_max
$have_min $have_max
Truth table66%2/3
A or B
A= $have_minB= $have_max
ABresult
1X1
011
000
2536 unless $have_min || $have_max;
2537 2 ▶ croak "clamp munger$where: 'min' must be numeric"
Branch: 1 branch
BranchTrueFalseTotal
if $have_min and not &looks_like_number($min) 0 2 2
Condition33%1/3
$have_min and not &looks_like_number($min)
!ll&&!rl&&r
020
MC/DC0%0/2
$have_min and not &looks_like_number($min)
$have_min not &looks_like_number($min)
Truth table33%1/3
A and not(B)
A= $have_minB= not &looks_like_number($min)
ABresult
0X0
100
111
2538 if $have_min && !looks_like_number($min);
2539 2 ▶ croak "clamp munger$where: 'max' must be numeric"
Branch: 1 branch
BranchTrueFalseTotal
if $have_max and not &looks_like_number($max) 0 2 2
Condition66%2/3
$have_max and not &looks_like_number($max)
!ll&&!rl&&r
110
MC/DC0%0/2
$have_max and not &looks_like_number($max)
$have_max not &looks_like_number($max)
Truth table66%2/3
A and not(B)
A= $have_maxB= not &looks_like_number($max)
ABresult
0X0
100
111
2540 if $have_max && !looks_like_number($max);
2541 2 ▶ croak "clamp munger$where: 'min' must be <= 'max'"
Branch: 1 branch
BranchTrueFalseTotal
if $have_min and $have_max and $min > $max 0 2 2
Condition66%4/6
$have_min and $have_max and $min > $max
!ll&&!rl&&r
110
$have_min and $have_max
!ll&&!rl&&r
011
MC/DC0%0/3
$have_min and $have_max and $min > $max
$have_min $have_max $min > $max
Truth table50%2/4
A and B and C
A= $have_minB= $have_maxC= $min > $max
ABCresult
0XX0
10X0
1100
1111
2542 if $have_min && $have_max && $min > $max;
2543  
2544 5 ▶ return sub {
Subroutine __ANON__: called CC=7 SCAR=20.1
2545 5 my ($v) = @_;
2546 5 ▶ croak "clamp munger$where: '" . ( defined $v ? $v : 'undef' ) . "' is not numeric"
Branch: 2 branches
BranchTrueFalseTotal
unless &looks_like_number($v) 0 5 5
defined $v ? : 0 0 0
2547 unless looks_like_number($v);
2548 5 ▶ $v = $min if $have_min && $v < $min;
Branch: 1 branch
BranchTrueFalseTotal
if $have_min and $v < $min 2 3 5
Condition66%2/3
$have_min and $v < $min
!ll&&!rl&&r
032
MC/DC50%1/2
$have_min and $v < $min
$have_min $v < $min
Truth table66%2/3
A and B
A= $have_minB= $v < $min
ABresult
0X0
100
111
2549 5 ▶ $v = $max if $have_max && $v > $max;
Branch: 1 branch
BranchTrueFalseTotal
if $have_max and $v > $max 1 4 5
Condition100%3/3
$have_max and $v > $max
!ll&&!rl&&r
221
MC/DC100%2/2
$have_max and $v > $max
$have_max $v > $max
Truth table100%3/3
A and B
A= $have_maxB= $v > $max
ABresult
0X0
100
111
2550 5 return $v;
2551 2 };
2552 } ## end sub _build_clamp
2553  
2554 =head2 num
2555  
2556 { munger => 'num', base => 16 } # '0x1a' or '1a' -> 26
2557 { munger => 'num' } # plain numeric coercion
2558  
2559 Parse a string as a number in C<base> (2-36, default 10). Base 10 simply
2560 validates and numifies. Other bases accept the digits C<0-9a-z> below the
2561 base, case-insensitively, an optional leading C<->, and the conventional
2562 prefix for that base (C<0x> for 16, C<0b> for 2, C<0o> for 8). Plenty of
2563 tooling logs flag words and IDs in hex (C<0x2f>), which the Writer would
2564 reject as non-numeric; this munger is the bridge. Croaks on anything that is
2565 not a clean number in the chosen base.
2566  
2567 =cut
2568  
2569 7 ▶sub _build_num {
Subroutine _build_num: called CC=10 SCAR=23.2
2570 7 my ( $spec, $where ) = @_;
2571  
2572 7 ▶ my $base = defined $spec->{base} ? $spec->{base} : 10;
Branch: 1 branch
BranchTrueFalseTotal
defined $spec->{'base'} ? : 6 1 7
2573 7 ▶ croak "num munger$where: 'base' must be an integer from 2 to 36"
Branch: 1 branch
BranchTrueFalseTotal
unless $base =~ /\A[0-9]+\z/ and $base >= 2 and $base <= 36 2 5 7
Condition83%5/6
$base =~ /\A[0-9]+\z/ and $base >= 2 and $base <= 36
!ll&&!rl&&r
115
$base =~ /\A[0-9]+\z/ and $base >= 2
!ll&&!rl&&r
016
MC/DC66%2/3
$base =~ /\A[0-9]+\z/ and $base >= 2 and $base <= 36
$base =~ /\A[0-9]+\z/ $base >= 2 $base <= 36
Truth table75%3/4
A and B and C
A= $base =~ /\A[0-9]+\z/B= $base >= 2C= $base <= 36
ABCresult
0XX0
10X0
1100
1111
2574 unless $base =~ /\A[0-9]+\z/ && $base >= 2 && $base <= 36;
2575  
2576 5 ▶ if ( $base == 10 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($base == 10) 1 4 5
2577 3 ▶ return sub {
Subroutine __ANON__: called CC=3 SCAR=11.1
2578 3 my ($v) = @_;
2579 3 ▶ croak "num munger$where: '" . ( defined $v ? $v : 'undef' ) . "' is not numeric"
Branch: 2 branches
BranchTrueFalseTotal
unless &looks_like_number($v) 1 2 3
defined $v ? : 1 0 1
2580 unless looks_like_number($v);
2581 2 return $v + 0;
2582 1 };
2583 }
2584  
2585 4 my %digit;
2586 4 my $i = 0;
2587 4 $digit{$_} = $i++ for ( '0' .. '9', 'a' .. 'z' );
2588 # Strip only the base's own conventional prefix; for other bases a letter
2589 # like 'b' is just a digit, so there is nothing to disambiguate.
2590 4 ▶ my $prefix
Branch: 3 branches
BranchTrueFalseTotal
$base == 16 ? : 2 2 4
$base == 8 ? : 1 1 2
$base == 2 ? : 1 0 1
2591 = $base == 16 ? qr/\A0x/
2592 : $base == 8 ? qr/\A0o/
2593 : $base == 2 ? qr/\A0b/
2594 : undef;
2595  
2596 11 ▶ return sub {
Subroutine __ANON__: called CC=9 SCAR=22.3
2597 11 my ($v) = @_;
2598 11 ▶ my $s = defined $v ? lc "$v" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 11 0 11
2599 11 ▶ my $err = "num munger$where: '" . ( defined $v ? $v : 'undef' ) . "' is not a base-$base number";
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 11 0 11
2600 11 my $neg = $s =~ s/\A-//;
2601 11 ▶ $s =~ s/$prefix// if defined $prefix;
Branch: 1 branch
BranchTrueFalseTotal
if defined $prefix 11 0 11
2602 11 ▶ croak $err unless length $s;
Branch: 1 branch
BranchTrueFalseTotal
unless length $s 1 10 11
2603 10 my $n = 0;
2604 10 for my $c ( split //, $s ) {
2605 25 my $d = $digit{$c};
2606 25 ▶ croak $err unless defined $d && $d < $base;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $d and $d < $base 1 24 25
Condition66%2/3
defined $d and $d < $base
!ll&&!rl&&r
0124
MC/DC50%1/2
defined $d and $d < $base
defined $d $d < $base
Truth table66%2/3
A and B
A= defined $dB= $d < $base
ABresult
0X0
100
111
2607 24 $n = $n * $base + $d;
2608 }
2609 9 ▶ return $neg ? -$n : $n;
Branch: 1 branch
BranchTrueFalseTotal
$neg ? : 1 8 9
2610 4 }; ## end sub
2611 } ## end sub _build_num
2612  
2613 =head2 ratio
2614  
2615 # 'io_ratio' is a tag; bytes_out and bytes_in are input fields
2616 "io_ratio": { "munger": "ratio", "from": ["bytes_out", "bytes_in"] }
2617 { munger => 'ratio', from => [qw(bytes_out bytes_in)], zero => -1 }
2618  
2619 First source divided by the second: with C<< from => [a, b] >> the column gets
2620 C<a / b>. Asymmetry between two counters is a classic feature the counters
2621 alone cannot express -- bytes out over bytes in flags exfiltration, requests
2622 over responses flags scanning -- and the division has to happen at munge time
2623 because a forest split only ever sees one column. A zero denominator yields
2624 C<zero> (default C<0>) instead of dying, since "nothing came back" is a
2625 legitimate row, not bad input; pick a C<zero> outside the ratio's normal range
2626 if you want those rows to stand out. Both inputs must be numeric.
2627  
2628 This is a B<multi-input> munger: it only makes sense with several sources, so
2629 it is only usable through L</compile> with C<from> as an arrayref of exactly
2630 two field names (and thus C<apply_named> / C<write_named>). The sources are
2631 raw input fields, not other columns.
2632  
2633 =head2 combine
2634  
2635 { munger => 'combine', op => 'sum', from => [qw(bytes_in bytes_out)] }
2636 { munger => 'combine', op => 'max', from => [qw(req_time resp_time)] }
2637  
2638 Fold two or more numeric source fields into one column with C<op>: C<sum>,
2639 C<diff> (first minus second; exactly two sources), C<product>, C<min>, C<max>,
2640 or C<mean>. The general-purpose sibling of L</ratio> for when the interesting
2641 feature is a total, a gap, or an extreme across fields rather than any one
2642 field. Every input must be numeric.
2643  
2644 Like C<ratio>, this is a B<multi-input> munger: only usable through
2645 L</compile> with C<from> as an arrayref of source field names.
2646  
2647 =cut
2648  
2649 3 ▶sub _build_ratio {
Subroutine _build_ratio: called CC=4 SCAR=13.9
2650 3 my ( $spec, $where, $nsrc ) = @_;
2651  
2652 3 ▶ croak "ratio munger$where takes exactly 2 source fields (numerator, denominator), not $nsrc"
Branch: 1 branch
BranchTrueFalseTotal
unless $nsrc == 2 1 2 3
2653 unless $nsrc == 2;
2654  
2655 2 ▶ my $zero = defined $spec->{zero} ? $spec->{zero} : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $spec->{'zero'} ? : 1 1 2
2656 2 ▶ croak "ratio munger$where: 'zero' must be numeric"
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($zero) 0 2 2
2657 unless looks_like_number($zero);
2658  
2659 5 ▶ return sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
2660 5 for my $v (@_) {
2661 10 ▶ croak "ratio munger$where: '" . ( defined $v ? $v : 'undef' ) . "' is not numeric"
Branch: 2 branches
BranchTrueFalseTotal
unless &looks_like_number($v) 1 9 10
defined $v ? : 1 0 1
2662 unless looks_like_number($v);
2663 }
2664 4 ▶ return $zero if $_[1] == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $_[1] == 0 2 2 4
2665 2 return $_[0] / $_[1];
2666 2 };
2667 } ## end sub _build_ratio
2668  
2669 # op => fold over the already numeric-checked source values. A table so the
2670 # error message can enumerate them and a new op is one line.
2671 my %COMBINE_OPS = (
2672 3 ▶ sum => sub { my $t = 0; $t += $_ for @_; return $t },
Subroutine __ANON__: called CC=2 SCAR=6.9
2673 1 ▶ diff => sub { return $_[0] - $_[1] },
Subroutine __ANON__: called CC=1 SCAR=0.0
2674 1 ▶ product => sub { my $t = 1; $t *= $_ for @_; return $t },
Subroutine __ANON__: called CC=2 SCAR=6.9
2675 1 ▶ min => sub {
Subroutine __ANON__: called CC=3 SCAR=11.1
2676 1 my $t = shift;
2677 1 ▶ for (@_) { $t = $_ if $_ < $t }
Branch: 1 branch
BranchTrueFalseTotal
if $_ < $t 1 0 1
2678 1 return $t;
2679 },
2680 1 ▶ max => sub {
Subroutine __ANON__: called CC=3 SCAR=11.1
2681 1 my $t = shift;
2682 1 ▶ for (@_) { $t = $_ if $_ > $t }
Branch: 1 branch
BranchTrueFalseTotal
if $_ > $t 0 1 1
2683 1 return $t;
2684 },
2685 1 ▶ mean => sub { my $t = 0; $t += $_ for @_; return $t / @_ },
Subroutine __ANON__: called CC=2 SCAR=6.9
2686 6 );
2687  
2688 10 ▶sub _build_combine_op {
Subroutine _build_combine_op: called CC=6 SCAR=18.2
2689 10 my ( $spec, $where, $nsrc ) = @_;
2690  
2691 10 my $op = $spec->{op};
2692 10 ▶ croak "combine munger$where requires an 'op' (one of: " . join( ', ', sort keys %COMBINE_OPS ) . ')'
Branch: 1 branch
BranchTrueFalseTotal
unless defined $op and length $op 1 9 10
Condition66%2/3
defined $op and length $op
!ll&&!rl&&r
109
MC/DC50%1/2
defined $op and length $op
defined $op length $op
Truth table66%2/3
A and B
A= defined $opB= length $op
ABresult
0X0
100
111
2693 unless defined $op && length $op;
2694 9 ▶ my $fold = $COMBINE_OPS{$op}
Branch: 1 branch
BranchTrueFalseTotal
my $fold = $COMBINE_OPS{$op} or croak("combine munger${where}: unknown op '${op}' (known: " . join(", ", sort(keys %COMBINE_OPS)) . ')') 8 1 9
2695 or croak "combine munger$where: unknown op '$op' (known: " . join( ', ', sort keys %COMBINE_OPS ) . ')';
2696 8 ▶ croak "combine munger$where: op 'diff' takes exactly 2 source fields, not $nsrc"
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "diff" and $nsrc != 2 1 7 8
Condition100%3/3
$op eq "diff" and $nsrc != 2
!ll&&!rl&&r
611
MC/DC100%2/2
$op eq "diff" and $nsrc != 2
$op eq "diff" $nsrc != 2
Truth table100%3/3
A and B
A= $op eq "diff"B= $nsrc != 2
ABresult
0X0
100
111
2697 if $op eq 'diff' && $nsrc != 2;
2698  
2699 8 ▶ return sub {
Subroutine __ANON__: called CC=4 SCAR=16.6
2700 8 for my $v (@_) {
2701 18 ▶ croak "combine munger$where: '" . ( defined $v ? $v : 'undef' ) . "' is not numeric"
Branch: 2 branches
BranchTrueFalseTotal
unless &looks_like_number($v) 0 18 18
defined $v ? : 0 0 0
2702 unless looks_like_number($v);
2703 }
2704 8 return $fold->(@_);
2705 7 };
2706 } ## end sub _build_combine_op
2707  
2708 =head2 bit
2709  
2710 { munger => 'bit', mask => '0x12' } # SYN or ACK set?
2711 { munger => 'bit', mask => '0x02', mode => 'all' } # the SYN bit itself
2712 { munger => 'bit', mode => 'popcount' } # how many flags at all
2713 { munger => 'bit', mask => '0x0f', mode => 'value' } # low nibble, 0-15
2714 { munger => 'bit', mask => '0x02', base => 16 } # Suricata tcp_flags "1b"
2715  
2716 Bit-level features from an integer flags word (TCP flags, DNS header flags,
2717 protocol option words): the raw word is meaningless to a threshold split, but
2718 individual bits and bit I<counts> are real signals. The input must be a
2719 non-negative integer, in decimal or C<0x> hex (so a logged C<0x12> works
2720 as-is); C<mask> may be written either way too.
2721  
2722 Set C<< base => 16 >> to read the B<input> as bare hexadecimal with no C<0x>
2723 prefix -- Suricata logs C<tcp.tcp_flags> (and C<tcp_flags_ts>/C<tcp_flags_tc>)
2724 as e.g. C<"1b">, which is otherwise ambiguous with decimal. A C<0x> prefix on
2725 the input is still accepted under C<< base => 16 >>. C<mask> is always written
2726 in decimal or C<0x> hex regardless of C<base>. Modes:
2727  
2728 =over 4
2729  
2730 =item * C<any> (default) - C<1> if any bit of C<mask> is set in the value.
2731  
2732 =item * C<all> - C<1> only if every bit of C<mask> is set.
2733  
2734 =item * C<value> - the masked bits, shifted down to the mask's lowest set
2735 bit: C<< mask => '0x0f' >> extracts the low nibble as C<0>-C<15>.
2736  
2737 =item * C<popcount> - the number of set bits in C<value & mask>; C<mask> is
2738 optional here and defaults to all bits. An abnormal flag I<count> (a
2739 Christmas-tree packet) is anomalous even when each individual bit is common.
2740  
2741 =back
2742  
2743 C<mask> is required (and must be non-zero) for every mode except C<popcount>.
2744  
2745 =cut
2746  
2747 6 my %BIT_MODE = map { $_ => 1 } qw(any all value popcount);
2748  
2749 # Accept an integer in decimal or 0x-hex form; returns the number, or undef
2750 # if it is neither. Shared by bit's mask (spec) and value (input) parsing.
2751 23 ▶sub _bit_int {
Subroutine _bit_int: called CC=4 SCAR=13.9
2752 23 my ($v) = @_;
2753 23 ▶ return undef unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 23 23
2754 23 ▶ return hex($v) if $v =~ /\A0x[0-9a-f]+\z/i;
Branch: 1 branch
BranchTrueFalseTotal
if $v =~ /\A0x[0-9a-f]+\z/i 10 13 23
2755 13 ▶ return $v + 0 if $v =~ /\A[0-9]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $v =~ /\A[0-9]+\z/ 10 3 13
2756 3 return undef;
2757 }
2758  
2759 # Parse an input value as bare hex (a '0x' prefix is tolerated), for bit's
2760 # 'base => 16' mode. Suricata logs tcp_flags as "1b" with no prefix, which
2761 # _bit_int would read as decimal (or reject), hence a separate parser opted
2762 # into per munger rather than a change to the ambiguous default.
2763 5 ▶sub _bit_hex {
Subroutine _bit_hex: called CC=3 SCAR=11.0
2764 5 my ($v) = @_;
2765 5 ▶ return undef unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 5 5
2766 5 ▶ return hex($1) if $v =~ /\A(?:0x)?([0-9a-f]+)\z/i;
Branch: 1 branch
BranchTrueFalseTotal
if $v =~ /\A(?:0x)?([0-9a-f]+)\z/i 4 1 5
2767 1 return undef;
2768 }
2769  
2770 13 ▶sub _build_bit {
Subroutine _build_bit: called CC=15 SCAR=27.1
2771 13 my ( $spec, $where ) = @_;
2772  
2773 13 ▶ my $mode = defined $spec->{mode} ? $spec->{mode} : 'any';
Branch: 1 branch
BranchTrueFalseTotal
defined $spec->{'mode'} ? : 7 6 13
2774 croak "bit munger$where: unknown mode '$mode' (known: " . join( ', ', sort keys %BIT_MODE ) . ')'
2775 13 ▶ unless $BIT_MODE{$mode};
Branch: 1 branch
BranchTrueFalseTotal
unless $BIT_MODE{$mode} 1 12 13
2776  
2777 # Input base: 10 (default, decimal or 0x hex) or 16 (bare hex, for feeds
2778 # like Suricata's tcp_flags). Only the per-row input parser changes; the
2779 # mask below is always read with _bit_int.
2780 12 ▶ my $base = defined $spec->{base} ? $spec->{base} : 10;
Branch: 1 branch
BranchTrueFalseTotal
defined $spec->{'base'} ? : 3 9 12
2781 12 ▶ croak "bit munger$where: 'base' must be 10 or 16"
Branch: 1 branch
BranchTrueFalseTotal
unless $base eq 10 or $base eq 16 1 11 12
Condition100%3/3
$base eq 10 or $base eq 16
l!l&&r!l&&!r
921
MC/DC100%2/2
$base eq 10 or $base eq 16
$base eq 10 $base eq 16
Truth table100%3/3
A or B
A= $base eq 10B= $base eq 16
ABresult
1X1
011
000
2782 unless $base eq '10' || $base eq '16';
2783 11 ▶ my $parse_in = $base eq '16' ? \&_bit_hex : \&_bit_int;
Branch: 1 branch
BranchTrueFalseTotal
$base eq '16' ? : 2 9 11
2784 11 ▶ my $in_form = $base eq '16' ? 'hex' : 'decimal or 0x hex';
Branch: 1 branch
BranchTrueFalseTotal
$base eq '16' ? : 2 9 11
2785  
2786 11 my $mask;
2787 11 ▶ if ( defined $spec->{mask} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $spec->{'mask'}) { } 8 3 11
elsif ($mode ne 'popcount') { } 1 2 3
2788 8 $mask = _bit_int( $spec->{mask} );
2789 8 ▶ croak "bit munger$where: 'mask' must be a non-negative integer " . '(decimal or 0x hex)'
Branch: 1 branch
BranchTrueFalseTotal
unless defined $mask 1 7 8
2790 unless defined $mask;
2791 7 ▶ croak "bit munger$where: 'mask' must be non-zero"
Branch: 1 branch
BranchTrueFalseTotal
if $mask == 0 and $mode ne "popcount" 1 6 7
Condition66%2/3
$mask == 0 and $mode ne "popcount"
!ll&&!rl&&r
601
MC/DC50%1/2
$mask == 0 and $mode ne "popcount"
$mask == 0 $mode ne "popcount"
Truth table66%2/3
A and B
A= $mask == 0B= $mode ne "popcount"
ABresult
0X0
100
111
2792 if $mask == 0 && $mode ne 'popcount';
2793 } elsif ( $mode ne 'popcount' ) {
2794 1 croak "bit munger$where: mode '$mode' requires a 'mask'";
2795 }
2796  
2797 # For 'value', bake in the shift down to the mask's lowest set bit.
2798 8 my $shift = 0;
2799 8 ▶ if ( $mode eq 'value' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mode eq "value") 1 7 8
2800 1 my $m = $mask;
2801 1 ▶ until ( $m & 1 ) { $m >>= 1; $shift++; }
Branch: 1 branch
BranchTrueFalseTotal
unless ($m & 1) 4 1 5
2802 }
2803  
2804 20 ▶ return sub {
Subroutine __ANON__: called CC=10 SCAR=23.1
2805 20 my ($v) = @_;
2806 20 ▶ my $n = $parse_in->( defined $v ? "$v" : undef );
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 20 0 20
2807 20 ▶ croak "bit munger$where: '" . ( defined $v ? $v : 'undef' ) . "' is not a non-negative integer ($in_form)"
Branch: 2 branches
BranchTrueFalseTotal
unless defined $n 3 17 20
defined $v ? : 3 0 3
2808 unless defined $n;
2809 17 ▶ $n &= $mask if defined $mask;
Branch: 1 branch
BranchTrueFalseTotal
if defined $mask 13 4 17
2810 17 ▶ return sprintf( '%b', $n ) =~ tr/1// if $mode eq 'popcount';
Branch: 1 branch
BranchTrueFalseTotal
if $mode eq "popcount" 5 12 17
2811 12 ▶ return $n ? 1 : 0 if $mode eq 'any';
Branch: 2 branches
BranchTrueFalseTotal
if $mode eq "any" 6 6 12
$n ? : 4 2 6
2812 6 ▶ return $n == $mask ? 1 : 0 if $mode eq 'all';
Branch: 2 branches
BranchTrueFalseTotal
if $mode eq "all" 4 2 6
$n == $mask ? : 2 2 4
2813 2 return $n >> $shift; # value
2814 8 }; ## end sub
2815 } ## end sub _build_bit
2816  
2817 =head2 ip_class
2818  
2819 { munger => 'ip_class' }
2820 { munger => 'ip_class', default => -1 }
2821  
2822 Collapse an IPv4 or IPv6 address to its address-space class -- to addresses
2823 what the status-class enums are to reply codes: the literal address is
2824 high-cardinality noise, but "an internal host suddenly talking multicast" is
2825 a class-level signal. Classes and their emitted numbers:
2826  
2827 0 global anything not covered below
2828 1 private 10/8, 172.16/12, 192.168/16, 100.64/10 (CGNAT), fc00::/7 (ULA)
2829 2 loopback 127/8, ::1
2830 3 link_local 169.254/16, fe80::/10
2831 4 multicast 224/4, ff00::/8
2832 5 broadcast 255.255.255.255
2833 6 unspecified 0.0.0.0, ::
2834 7 reserved 0/8, 192.0.0/24, the documentation nets (192.0.2/24,
2835 198.51.100/24, 203.0.113/24, 2001:db8::/32), benchmarking
2836 (198.18/15), 240/4, and the 100::/64 discard prefix
2837  
2838 An IPv4-mapped IPv6 address (C<::ffff:a.b.c.d>) is classified as its embedded
2839 IPv4 address. An unparseable input croaks, or yields the numeric C<default>
2840 when one is given. IPv6 parsing uses L<Socket>'s C<inet_pton>, loaded lazily
2841 the way L</datetime> loads Time::Piece. For B<site-specific> zones (DMZ,
2842 server VLAN, guest Wi-Fi) use L</cidr>, which knows your networks instead of
2843 the RFCs'.
2844  
2845 =head2 cidr
2846  
2847 { munger => 'cidr',
2848 nets => [ '10.10.0.0/16', '10.20.0.0/16', '2001:db8:5::/48' ],
2849 default => -1 }
2850  
2851 Membership in a list of CIDR networks: the result is the (0-based) index of
2852 the B<first> net in C<nets> containing the address -- L</bucket> for address
2853 space, and the way a site encodes its own zones (DMZ vs. server VLAN vs.
2854 guest Wi-Fi) that L</ip_class>'s generic RFC classes cannot know about.
2855 C<nets> may mix IPv4 and IPv6; an address is only tested against nets of its
2856 own family. Overlapping nets are fine -- list the most specific first, since
2857 the first match wins. An input that is unparseable or in none of the listed
2858 nets croaks, or yields the numeric C<default> when one is given (a catch-all
2859 C<default> is the usual configuration).
2860  
2861 =cut
2862  
2863 # Parse an IP address string: (4, $int) for IPv4, (6, $bytes16) for IPv6, or
2864 # an empty list for neither. v4 goes through a regex (also pinning the
2865 # dotted-quad form, so inet_pton's odd shorthands never sneak in); v6 leans
2866 # on Socket's inet_pton, loaded lazily so no munger that skips IPs pays for
2867 # it.
2868 51 ▶sub _parse_ip {
Subroutine _parse_ip: called CC=9 SCAR=23.5
2869 51 my ($s) = @_;
2870 51 ▶ if ( $s =~ /\A([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\z/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($s =~ /\A([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\z/) 31 20 51
2871 31 ▶ return unless $1 <= 255 && $2 <= 255 && $3 <= 255 && $4 <= 255;
Branch: 1 branch
BranchTrueFalseTotal
unless $1 <= 255 and $2 <= 255 and $3 <= 255 and $4 <= 255 1 30 31
Condition44%4/9
$1 <= 255 and $2 <= 255 and $3 <= 255 and $4 <= 255
!ll&&!rl&&r
0130
$1 <= 255 and $2 <= 255 and $3 <= 255
!ll&&!rl&&r
0031
$1 <= 255 and $2 <= 255
!ll&&!rl&&r
0031
MC/DC25%1/4
$1 <= 255 and $2 <= 255 and $3 <= 255 and $4 <= 255
$1 <= 255 $2 <= 255 $3 <= 255 $4 <= 255
Truth table40%2/5
A and B and C and D
A= $1 <= 255B= $2 <= 255C= $3 <= 255D= $4 <= 255
ABCDresult
0XXX0
10XX0
110X0
11100
11111
2872 30 return ( 4, ( $1 << 24 ) | ( $2 << 16 ) | ( $3 << 8 ) | $4 );
2873 }
2874 20 ▶ if ( index( $s, ':' ) >= 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (index($s, ":") != -1) 14 6 20
2875 14 require Socket;
2876 14 my $b = eval { Socket::inet_pton( Socket::AF_INET6(), $s ) };
2877 14 ▶ return ( 6, $b ) if defined $b && length $b == 16;
Branch: 1 branch
BranchTrueFalseTotal
if defined $b and length $b == 16 14 0 14
Condition33%1/3
defined $b and length $b == 16
!ll&&!rl&&r
0014
MC/DC0%0/2
defined $b and length $b == 16
defined $b length $b == 16
Truth table33%1/3
A and B
A= defined $bB= length $b == 16
ABresult
0X0
100
111
2878 }
2879 6 return;
2880 } ## end sub _parse_ip
2881  
2882 # The ip_class class names, pinned to their emitted numbers.
2883 6 my %IP_CLASS = (
2884 global => 0,
2885 private => 1,
2886 loopback => 2,
2887 link_local => 3,
2888 multicast => 4,
2889 broadcast => 5,
2890 unspecified => 6,
2891 reserved => 7,
2892 );
2893  
2894 21 ▶sub _ip4_class {
Subroutine _ip4_class: called CC=32 SCAR=35.2
2895 21 my ($n) = @_;
2896 21 ▶ return 'unspecified' if $n == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $n == 0 1 20 21
2897 20 ▶ return 'broadcast' if $n == 0xffffffff;
Branch: 1 branch
BranchTrueFalseTotal
if $n == 4294967295 1 19 20
2898 19 my $a = $n >> 24;
2899 19 my $b = ( $n >> 16 ) & 0xff;
2900 19 my $c = ( $n >> 8 ) & 0xff;
2901 19 ▶ return 'reserved' if $a == 0; # 0/8 "this network"
Branch: 1 branch
BranchTrueFalseTotal
if $a == 0 1 18 19
2902 18 ▶ return 'private' if $a == 10;
Branch: 1 branch
BranchTrueFalseTotal
if $a == 10 2 16 18
2903 16 ▶ return 'private' if $a == 100 && $b >= 64 && $b <= 127; # CGNAT 100.64/10
Branch: 1 branch
BranchTrueFalseTotal
if $a == 100 and $b >= 64 and $b <= 127 1 15 16
Condition83%5/6
$a == 100 and $b >= 64 and $b <= 127
!ll&&!rl&&r
1411
$a == 100 and $b >= 64
!ll&&!rl&&r
1402
MC/DC66%2/3
$a == 100 and $b >= 64 and $b <= 127
$a == 100 $b >= 64 $b <= 127
Truth table75%3/4
A and B and C
A= $a == 100B= $b >= 64C= $b <= 127
ABCresult
0XX0
10X0
1100
1111
2904 15 ▶ return 'loopback' if $a == 127;
Branch: 1 branch
BranchTrueFalseTotal
if $a == 127 1 14 15
2905 14 ▶ return 'link_local' if $a == 169 && $b == 254;
Branch: 1 branch
BranchTrueFalseTotal
if $a == 169 and $b == 254 1 13 14
Condition66%2/3
$a == 169 and $b == 254
!ll&&!rl&&r
1301
MC/DC50%1/2
$a == 169 and $b == 254
$a == 169 $b == 254
Truth table66%2/3
A and B
A= $a == 169B= $b == 254
ABresult
0X0
100
111
2906 13 ▶ return 'private' if $a == 172 && $b >= 16 && $b <= 31;
Branch: 1 branch
BranchTrueFalseTotal
if $a == 172 and $b >= 16 and $b <= 31 1 12 13
Condition83%5/6
$a == 172 and $b >= 16 and $b <= 31
!ll&&!rl&&r
1111
$a == 172 and $b >= 16
!ll&&!rl&&r
1102
MC/DC66%2/3
$a == 172 and $b >= 16 and $b <= 31
$a == 172 $b >= 16 $b <= 31
Truth table75%3/4
A and B and C
A= $a == 172B= $b >= 16C= $b <= 31
ABCresult
0XX0
10X0
1100
1111
2907 12 ▶ return 'reserved' if $a == 192 && $b == 0 && ( $c == 0 || $c == 2 );
Branch: 1 branch
BranchTrueFalseTotal
if $a == 192 and $b == 0 and $c == 0 || $c == 2 1 11 12
Condition66%6/9
$a == 192 and $b == 0 and $c == 0 || $c == 2
!ll&&!rl&&r
1101
$a == 192 and $b == 0
!ll&&!rl&&r
1011
$c == 0 or $c == 2
l!l&&r!l&&!r
010
MC/DC50%2/4
$a == 192 and $b == 0 and $c == 0 || $c == 2
$a == 192 $b == 0 $c == 0 $c == 2
Truth table60%3/5
A and B and C or D
A= $a == 192B= $b == 0C= $c == 0D= $c == 2
ABCDresult
0XXX0
10XX0
11000
111X1
11011
2908 11 ▶ return 'private' if $a == 192 && $b == 168;
Branch: 1 branch
BranchTrueFalseTotal
if $a == 192 and $b == 168 1 10 11
Condition66%2/3
$a == 192 and $b == 168
!ll&&!rl&&r
1001
MC/DC50%1/2
$a == 192 and $b == 168
$a == 192 $b == 168
Truth table66%2/3
A and B
A= $a == 192B= $b == 168
ABresult
0X0
100
111
2909 10 ▶ return 'reserved' if $a == 198 && ( $b == 18 || $b == 19 ); # benchmarking
Branch: 1 branch
BranchTrueFalseTotal
if $a == 198 and $b == 18 || $b == 19 1 9 10
Condition83%5/6
$a == 198 and $b == 18 || $b == 19
!ll&&!rl&&r
811
$b == 18 or $b == 19
l!l&&r!l&&!r
101
MC/DC66%2/3
$a == 198 and $b == 18 || $b == 19
$a == 198 $b == 18 $b == 19
Truth table75%3/4
A and B or C
A= $a == 198B= $b == 18C= $b == 19
ABCresult
0XX0
1000
11X1
1011
2910 9 ▶ return 'reserved' if $a == 198 && $b == 51 && $c == 100; # TEST-NET-2
Branch: 1 branch
BranchTrueFalseTotal
if $a == 198 and $b == 51 and $c == 100 1 8 9
Condition66%4/6
$a == 198 and $b == 51 and $c == 100
!ll&&!rl&&r
801
$a == 198 and $b == 51
!ll&&!rl&&r
801
MC/DC33%1/3
$a == 198 and $b == 51 and $c == 100
$a == 198 $b == 51 $c == 100
Truth table50%2/4
A and B and C
A= $a == 198B= $b == 51C= $c == 100
ABCresult
0XX0
10X0
1100
1111
2911 8 ▶ return 'reserved' if $a == 203 && $b == 0 && $c == 113; # TEST-NET-3
Branch: 1 branch
BranchTrueFalseTotal
if $a == 203 and $b == 0 and $c == 113 1 7 8
Condition66%4/6
$a == 203 and $b == 0 and $c == 113
!ll&&!rl&&r
701
$a == 203 and $b == 0
!ll&&!rl&&r
701
MC/DC33%1/3
$a == 203 and $b == 0 and $c == 113
$a == 203 $b == 0 $c == 113
Truth table50%2/4
A and B and C
A= $a == 203B= $b == 0C= $c == 113
ABCresult
0XX0
10X0
1100
1111
2912 7 ▶ return 'multicast' if $a >= 224 && $a <= 239;
Branch: 1 branch
BranchTrueFalseTotal
if $a >= 224 and $a <= 239 2 5 7
Condition100%3/3
$a >= 224 and $a <= 239
!ll&&!rl&&r
412
MC/DC100%2/2
$a >= 224 and $a <= 239
$a >= 224 $a <= 239
Truth table100%3/3
A and B
A= $a >= 224B= $a <= 239
ABresult
0X0
100
111
2913 5 ▶ return 'reserved' if $a >= 240; # 240/4 future use
Branch: 1 branch
BranchTrueFalseTotal
if $a >= 240 1 4 5
2914 4 return 'global';
2915 } ## end sub _ip4_class
2916  
2917 10 ▶sub _ip6_class {
Subroutine _ip6_class: called CC=22 SCAR=31.3
2918 10 my ($bytes) = @_;
2919 10 my @o = unpack 'C16', $bytes;
2920 10 my $lead0 = 1;
2921 10 ▶ for my $i ( 0 .. 14 ) { $lead0 &&= $o[$i] == 0 }
Condition100%3/3
$lead0 &&= $o[$i] == 0
!ll&&!rl&&r
92850
MC/DC100%2/2
$lead0 &&= $o[$i] == 0
$lead0 $o[$i] == 0
Truth table100%3/3
A &&= B
A= $lead0B= $o[$i] == 0
ABresult
0X0
100
111
2922 10 ▶ if ($lead0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($lead0) 2 8 10
2923 2 ▶ return 'unspecified' if $o[15] == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $o[15] == 0 1 1 2
2924 1 ▶ return 'loopback' if $o[15] == 1;
Branch: 1 branch
BranchTrueFalseTotal
if $o[15] == 1 1 0 1
2925 }
2926 # v4-mapped ::ffff:a.b.c.d -- classify as the embedded v4 address.
2927 8 my $map = 1;
2928 8 ▶ for my $i ( 0 .. 9 ) { $map &&= $o[$i] == 0 }
Condition100%3/3
$map &&= $o[$i] == 0
!ll&&!rl&&r
54620
MC/DC100%2/2
$map &&= $o[$i] == 0
$map $o[$i] == 0
Truth table100%3/3
A &&= B
A= $mapB= $o[$i] == 0
ABresult
0X0
100
111
2929 8 ▶ return _ip4_class( ( $o[12] << 24 ) | ( $o[13] << 16 ) | ( $o[14] << 8 ) | $o[15] )
Branch: 1 branch
BranchTrueFalseTotal
if $map and $o[10] == 255 and $o[11] == 255 2 6 8
Condition66%4/6
$map and $o[10] == 255 and $o[11] == 255
!ll&&!rl&&r
602
$map and $o[10] == 255
!ll&&!rl&&r
602
MC/DC33%1/3
$map and $o[10] == 255 and $o[11] == 255
$map $o[10] == 255 $o[11] == 255
Truth table50%2/4
A and B and C
A= $mapB= $o[10] == 255C= $o[11] == 255
ABCresult
0XX0
10X0
1100
1111
2930 if $map && $o[10] == 0xff && $o[11] == 0xff;
2931 6 ▶ return 'multicast' if $o[0] == 0xff;
Branch: 1 branch
BranchTrueFalseTotal
if $o[0] == 255 1 5 6
2932 5 ▶ return 'private' if ( $o[0] & 0xfe ) == 0xfc; # ULA fc00::/7
Branch: 1 branch
BranchTrueFalseTotal
if ($o[0] & 254) == 252 1 4 5
2933 4 ▶ return 'link_local' if $o[0] == 0xfe && ( $o[1] & 0xc0 ) == 0x80; # fe80::/10
Branch: 1 branch
BranchTrueFalseTotal
if $o[0] == 254 and ($o[1] & 192) == 128 1 3 4
Condition66%2/3
$o[0] == 254 and ($o[1] & 192) == 128
!ll&&!rl&&r
301
MC/DC50%1/2
$o[0] == 254 and ($o[1] & 192) == 128
$o[0] == 254 ($o[1] & 192) == 128
Truth table66%2/3
A and B
A= $o[0] == 254B= ($o[1] & 192) == 128
ABresult
0X0
100
111
2934 3 ▶ return 'reserved' if $o[0] == 0x20 && $o[1] == 0x01 && $o[2] == 0x0d && $o[3] == 0xb8; # 2001:db8::/32
Branch: 1 branch
BranchTrueFalseTotal
if $o[0] == 32 and $o[1] == 1 and $o[2] == 13 and $o[3] == 184 1 2 3
Condition66%6/9
$o[0] == 32 and $o[1] == 1 and $o[2] == 13 and $o[3] == 184
!ll&&!rl&&r
201
$o[0] == 32 and $o[1] == 1 and $o[2] == 13
!ll&&!rl&&r
201
$o[0] == 32 and $o[1] == 1
!ll&&!rl&&r
201
MC/DC25%1/4
$o[0] == 32 and $o[1] == 1 and $o[2] == 13 and $o[3] == 184
$o[0] == 32 $o[1] == 1 $o[2] == 13 $o[3] == 184
Truth table40%2/5
A and B and C and D
A= $o[0] == 32B= $o[1] == 1C= $o[2] == 13D= $o[3] == 184
ABCDresult
0XXX0
10XX0
110X0
11100
11111
2935 2 my $discard = $o[0] == 0x01; # 100::/64
2936 2 ▶ for my $i ( 1 .. 7 ) { $discard &&= $o[$i] == 0 }
Condition66%2/3
$discard &&= $o[$i] == 0
!ll&&!rl&&r
707
MC/DC50%1/2
$discard &&= $o[$i] == 0
$discard $o[$i] == 0
Truth table66%2/3
A &&= B
A= $discardB= $o[$i] == 0
ABresult
0X0
100
111
2937 2 ▶ return 'reserved' if $discard;
Branch: 1 branch
BranchTrueFalseTotal
if $discard 1 1 2
2938 1 return 'global';
2939 } ## end sub _ip6_class
2940  
2941 3 ▶sub _build_ip_class {
Subroutine _build_ip_class: called CC=3 SCAR=11.0
2942 3 my ( $spec, $where ) = @_;
2943  
2944 3 my $has_default = exists $spec->{default};
2945 3 my $default = $spec->{default};
2946 3 ▶ croak "ip_class munger$where: 'default' must be numeric"
Branch: 1 branch
BranchTrueFalseTotal
if $has_default and not &looks_like_number($default) 1 2 3
Condition100%3/3
$has_default and not &looks_like_number($default)
!ll&&!rl&&r
111
MC/DC100%2/2
$has_default and not &looks_like_number($default)
$has_default not &looks_like_number($default)
Truth table100%3/3
A and not(B)
A= $has_defaultB= not &looks_like_number($default)
ABresult
0X0
100
111
2947 if $has_default && !looks_like_number($default);
2948  
2949 33 ▶ return sub {
Subroutine __ANON__: called CC=6 SCAR=17.9
2950 33 my ($v) = @_;
2951 33 ▶ my ( $fam, $p ) = _parse_ip( defined $v ? "$v" : '' );
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 32 1 33
2952 33 ▶ if ($fam) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fam) 29 4 33
2953 29 ▶ return $IP_CLASS{ $fam == 4 ? _ip4_class($p) : _ip6_class($p) };
Branch: 1 branch
BranchTrueFalseTotal
$fam == 4 ? : 19 10 29
2954 }
2955 4 ▶ return $default if $has_default;
Branch: 1 branch
BranchTrueFalseTotal
if $has_default 2 2 4
2956 2 ▶ croak "ip_class munger$where: '" . ( defined $v ? $v : 'undef' ) . "' is not a parseable IP address";
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 2 0 2
2957 2 };
2958 } ## end sub _build_ip_class
2959  
2960 # Build a 16-byte netmask string for an IPv6 prefix length.
2961 2 ▶sub _v6_mask {
Subroutine _v6_mask: called CC=2 SCAR=7.0
2962 2 my ($len) = @_;
2963 2 my $mask = "\xff" x int( $len / 8 );
2964 2 ▶ $mask .= chr( ( 0xff << ( 8 - $len % 8 ) ) & 0xff ) if $len % 8;
Branch: 1 branch
BranchTrueFalseTotal
if $len % 8 0 2 2
2965 2 return $mask . ( "\0" x ( 16 - length $mask ) );
2966 }
2967  
2968 8 ▶sub _build_cidr {
Subroutine _build_cidr: called CC=14 SCAR=26.5
2969 8 my ( $spec, $where ) = @_;
2970  
2971 8 my $nets = $spec->{nets};
2972 8 ▶ croak "cidr munger$where requires a non-empty 'nets' arrayref"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $nets eq "ARRAY" and @$nets 1 7 8
Condition66%2/3
ref $nets eq "ARRAY" and @$nets
!ll&&!rl&&r
017
MC/DC50%1/2
ref $nets eq "ARRAY" and @$nets
ref $nets eq "ARRAY" @$nets
Truth table66%2/3
A and B
A= ref $nets eq "ARRAY"B= @$nets
ABresult
0X0
100
111
2973 unless ref $nets eq 'ARRAY' && @$nets;
2974  
2975 # [family, masked network, mask] per net; & on the 16-byte v6 strings is
2976 # Perl's bitwise string AND, so both families match the same way.
2977 7 my @match;
2978 7 for my $i ( 0 .. $#$nets ) {
2979 9 my $net = $nets->[$i];
2980 9 ▶ croak "cidr munger$where: nets[$i] ('"
Branch: 2 branches
BranchTrueFalseTotal
unless defined $net and $net =~ m[\A(.+)/([0-9]{1,3})\z] 1 8 9
defined $net ? : 1 0 1
Condition66%2/3
defined $net and $net =~ m[\A(.+)/([0-9]{1,3})\z]
!ll&&!rl&&r
018
MC/DC50%1/2
defined $net and $net =~ m[\A(.+)/([0-9]{1,3})\z]
defined $net $net =~ m[\A(.+)/([0-9]{1,3})\z]
Truth table66%2/3
A and B
A= defined $netB= $net =~ m[\A(.+)/([0-9]{1,3})\z]
ABresult
0X0
100
111
2981 . ( defined $net ? $net : 'undef' )
2982 . "') is not in 'address/prefix' form"
2983 unless defined $net && $net =~ m{\A(.+)/([0-9]{1,3})\z};
2984 8 my ( $addr, $len ) = ( $1, $2 );
2985 8 my ( $fam, $p ) = _parse_ip($addr);
2986 8 ▶ croak "cidr munger$where: nets[$i] ('$net') has an unparseable address"
Branch: 1 branch
BranchTrueFalseTotal
unless $fam 1 7 8
2987 unless $fam;
2988 7 ▶ my $max = $fam == 4 ? 32 : 128;
Branch: 1 branch
BranchTrueFalseTotal
$fam == 4 ? : 5 2 7
2989 7 ▶ croak "cidr munger$where: nets[$i] ('$net') prefix length must be 0-$max"
Branch: 1 branch
BranchTrueFalseTotal
if $len > $max 1 6 7
2990 if $len > $max;
2991 6 ▶ my $mask
Branch: 2 branches
BranchTrueFalseTotal
$fam == 4 ? : 4 2 6
$len == 0 ? : 1 3 4
2992 = $fam == 4
2993 ? ( $len == 0 ? 0 : ( 0xffffffff << ( 32 - $len ) ) & 0xffffffff )
2994 : _v6_mask($len);
2995 6 push @match, [ $fam, $p & $mask, $mask ];
2996 } ## end for my $i ( 0 .. $#$nets )
2997  
2998 4 my $has_default = exists $spec->{default};
2999 4 my $default = $spec->{default};
3000 4 ▶ croak "cidr munger$where: 'default' must be numeric"
Branch: 1 branch
BranchTrueFalseTotal
if $has_default and not &looks_like_number($default) 0 4 4
Condition66%2/3
$has_default and not &looks_like_number($default)
!ll&&!rl&&r
130
MC/DC0%0/2
$has_default and not &looks_like_number($default)
$has_default not &looks_like_number($default)
Truth table66%2/3
A and not(B)
A= $has_defaultB= not &looks_like_number($default)
ABresult
0X0
100
111
3001 if $has_default && !looks_like_number($default);
3002  
3003 10 ▶ return sub {
Subroutine __ANON__: called CC=10 SCAR=23.1
3004 10 my ($v) = @_;
3005 10 ▶ my ( $fam, $p ) = _parse_ip( defined $v ? "$v" : '' );
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 10 0 10
3006 10 ▶ if ($fam) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fam) 8 2 10
3007 8 for my $i ( 0 .. $#match ) {
3008 15 my ( $f, $network, $mask ) = @{ $match[$i] };
3009 15 ▶ next unless $f == $fam;
Branch: 1 branch
BranchTrueFalseTotal
unless $f == $fam 6 9 15
3010 9 ▶ return $i
Branch: 2 branches
BranchTrueFalseTotal
if $fam == 4 ? ($p & $mask) == $network : ($p & $mask) eq $network 4 5 9
$fam == 4 ? : 7 2 9
3011 if $fam == 4
3012 ? ( ( $p & $mask ) == $network )
3013 : ( ( $p & $mask ) eq $network );
3014 }
3015 4 ▶ return $default if $has_default;
Branch: 1 branch
BranchTrueFalseTotal
if $has_default 3 1 4
3016 1 croak "cidr munger$where: '$v' is in none of the listed networks (and no 'default')";
3017 } ## end if ($fam)
3018 2 ▶ return $default if $has_default;
Branch: 1 branch
BranchTrueFalseTotal
if $has_default 1 1 2
3019 1 ▶ croak "cidr munger$where: '" . ( defined $v ? $v : 'undef' ) . "' is not a parseable IP address";
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 1 0 1
3020 4 }; ## end sub
3021 } ## end sub _build_cidr
3022  
3023 =head2 geoip_country
3024  
3025 { munger => 'geoip_country', default => -1 }
3026 { munger => 'geoip_country',
3027 mmdb => '/var/db/GeoIP/GeoLite2-Country.mmdb',
3028 default => -1 }
3029  
3030 Look an IPv4 or IPv6 address up in a MaxMind DB and emit its country as a
3031 number. Where L</ip_class> answers "what kind of address" and L</cidr> "which
3032 of my networks", this answers "whose country". The number is derived
3033 arithmetically from the ISO 3166-1 alpha-2 code the database reports --
3034 C<(letter1 * 26) + letter2> with C<A> as C<0>, so C<AA> is C<0>, C<GB> is
3035 C<157>, C<SE> is C<472>, C<ZZ> is C<675> -- rather than looked up in a
3036 baked-in registry table: every possible two-letter code (including
3037 user-assigned ones like Kosovo's C<XK>) has a stable number without this
3038 module ever needing a registry update. The encoding is purely categorical;
3039 the magnitude carries no meaning.
3040  
3041 The database file is found by trying, in order:
3042  
3043 =over 4
3044  
3045 =item 1. C<mmdb> in the spec, when given;
3046  
3047 =item 2. the C<TONUMBERMUNGER_GEOIP_MMDB> environment variable;
3048  
3049 =item 3. C<$Algorithm::ToNumberMunger::GEOIP_COUNTRY_MMDB>, for an app to set
3050 once at startup;
3051  
3052 =item 4. the usual geoipupdate install locations -- C<GeoIP2-Country.mmdb>
3053 then C<GeoLite2-Country.mmdb> in each of C</var/db/GeoIP>, C</var/lib/GeoIP>,
3054 C</usr/share/GeoIP>, and C</usr/local/share/GeoIP>.
3055  
3056 =back
3057  
3058 So a spec normally names no path at all -- where the db lives is deployment
3059 detail, not configuration -- and on a host with a stock geoipupdate setup it
3060 just works. A country-level db is the natural fit, but any MaxMind db whose
3061 records carry a C<country> section (the City dbs do) works. The record's
3062 C<country> is used first, falling back to C<registered_country> when
3063 geolocation data is absent (anonymous-proxy and satellite networks often only
3064 have a registration). An input that is not a parseable address, or that
3065 resolves to no country -- private and unallocated space never does -- croaks,
3066 or yields the numeric C<default> when one is given; since every feed contains
3067 internal addresses, a C<default> is the usual configuration.
3068  
3069 The database is opened once at build time (no db found anywhere, or an
3070 unreadable file, fails there rather than per row) via
3071 L<IP::Geolocation::MMDB>, which is loaded lazily the way L</datetime> loads
3072 Time::Piece -- it is only a dependency if this munger is used.
3073  
3074 =cut
3075  
3076 # App-settable default database path for geoip_country, consulted after the
3077 # TONUMBERMUNGER_GEOIP_MMDB environment variable and before the well-known
3078 # geoipupdate locations.
3079 6 our $GEOIP_COUNTRY_MMDB;
3080  
3081 # The well-known geoipupdate install locations _resolve_geoip_mmdb scans last:
3082 # every directory is tried against every name, commercial db first.
3083 6 my @GEOIP_MMDB_DIRS = qw(/var/db/GeoIP /var/lib/GeoIP /usr/share/GeoIP /usr/local/share/GeoIP);
3084 6 my @GEOIP_MMDB_NAMES = qw(GeoIP2-Country.mmdb GeoLite2-Country.mmdb);
3085  
3086 # Resolve which MaxMind db file a geoip_country build should open, per the
3087 # order the POD promises: spec, environment, package variable, well-known
3088 # paths.
3089 #
3090 # Args:
3091 # spec - the munger spec hashref; only its optional 'mmdb' (path string)
3092 # is consulted
3093 # where - the " for tag '...'"/'' suffix used to sharpen croak messages
3094 #
3095 # Returns the path string of the first existing candidate. A candidate named
3096 # by spec/env/package variable that does not exist is a configuration error
3097 # and croaks (naming its source) rather than being silently skipped; croaks
3098 # too when nothing names a db and no well-known path has one.
3099 #
3100 # my $path = _resolve_geoip_mmdb( { munger => 'geoip_country' }, '' );
3101 13 ▶sub _resolve_geoip_mmdb {
Subroutine _resolve_geoip_mmdb: called CC=8 SCAR=20.9
3102 13 my ( $spec, $where ) = @_;
3103  
3104 my @named = (
3105 [ "'mmdb' in the spec", $spec->{mmdb} ],
3106 13 [ 'the TONUMBERMUNGER_GEOIP_MMDB env variable', $ENV{TONUMBERMUNGER_GEOIP_MMDB} ],
3107 [ '$Algorithm::ToNumberMunger::GEOIP_COUNTRY_MMDB', $GEOIP_COUNTRY_MMDB ],
3108 );
3109 13 for my $candidate (@named) {
3110 20 my ( $source, $path ) = @$candidate;
3111 20 ▶ next unless defined $path && length $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path and length $path 8 12 20
Condition66%2/3
defined $path and length $path
!ll&&!rl&&r
8012
MC/DC50%1/2
defined $path and length $path
defined $path length $path
Truth table66%2/3
A and B
A= defined $pathB= length $path
ABresult
0X0
100
111
3112 12 ▶ croak "geoip_country munger$where: mmdb file '$path' (from $source) does not exist"
Branch: 1 branch
BranchTrueFalseTotal
unless -f $path 2 10 12
3113 unless -f $path;
3114 10 return $path;
3115 }
3116  
3117 1 for my $dir (@GEOIP_MMDB_DIRS) {
3118 4 for my $name (@GEOIP_MMDB_NAMES) {
3119 8 ▶ return "$dir/$name" if -f "$dir/$name";
Branch: 1 branch
BranchTrueFalseTotal
if -f "$dir/$name" 0 8 8
3120 }
3121 }
3122  
3123 1 croak "geoip_country munger$where: no mmdb database found -- none named by "
3124 . "the spec, TONUMBERMUNGER_GEOIP_MMDB, or "
3125 . '$Algorithm::ToNumberMunger::GEOIP_COUNTRY_MMDB, and no '
3126 . 'GeoIP2-Country.mmdb/GeoLite2-Country.mmdb under '
3127 . join( ', ', @GEOIP_MMDB_DIRS );
3128 } ## end sub _resolve_geoip_mmdb
3129  
3130 # Builder for the geoip_country munger. Resolves and opens the MaxMind db up
3131 # front, then returns the per-value closure.
3132 #
3133 # Args (from the spec hash):
3134 # mmdb - path to a MaxMind DB file whose records carry a 'country'
3135 # section; optional, see _resolve_geoip_mmdb for the fallbacks
3136 # tried when absent
3137 # default - number emitted when a value cannot be resolved to a country
3138 # (unparseable address, address not in the db, or a malformed
3139 # country code in the db); optional -- without it such a value
3140 # croaks
3141 #
3142 # Returns a coderef mapping one address string to its country's number,
3143 # preferring the record's geolocated 'country' section and falling back to
3144 # 'registered_country'. The number is (letter1 * 26) + letter2 of the ISO
3145 # 3166-1 alpha-2 code with 'A' as 0 -- stable for any two-letter code with no
3146 # registry table to maintain.
3147 #
3148 # my $code = _build_geoip_country(
3149 # { munger => 'geoip_country', default => -1 },
3150 # " for tag 'src_country'" );
3151 # $code->('81.2.69.160'); # 157 (GB)
3152 # $code->('10.0.0.1'); # -1 (private space resolves to no country)
3153 13 ▶sub _build_geoip_country {
Subroutine _build_geoip_country: called CC=5 SCAR=16.1
3154 13 my ( $spec, $where ) = @_;
3155  
3156 13 my $mmdb = _resolve_geoip_mmdb( $spec, $where );
3157  
3158 # Lazy like datetime's Time::Piece: only a geoip_country build pays for
3159 # (or needs) IP::Geolocation::MMDB.
3160 10 ▶ eval { require IP::Geolocation::MMDB; 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require IP::Geolocation::MMDB; 1 } } or croak("geoip_country munger$where requires IP::Geolocation::MMDB, " . "which failed to load: $@") 10 0 10
3161 or croak "geoip_country munger$where requires IP::Geolocation::MMDB, " . "which failed to load: $@";
3162  
3163 10 my $db = eval { IP::Geolocation::MMDB->new( file => $mmdb ) };
3164 10 ▶ croak "geoip_country munger$where: could not open mmdb file '$mmdb': $@"
Branch: 1 branch
BranchTrueFalseTotal
unless $db 1 9 10
3165 unless $db;
3166  
3167 9 my $has_default = exists $spec->{default};
3168 9 my $default = $spec->{default};
3169 9 ▶ croak "geoip_country munger$where: 'default' must be numeric"
Branch: 1 branch
BranchTrueFalseTotal
if $has_default and not &looks_like_number($default) 1 8 9
Condition100%3/3
$has_default and not &looks_like_number($default)
!ll&&!rl&&r
621
MC/DC100%2/2
$has_default and not &looks_like_number($default)
$has_default not &looks_like_number($default)
Truth table100%3/3
A and not(B)
A= $has_defaultB= not &looks_like_number($default)
ABresult
0X0
100
111
3170 if $has_default && !looks_like_number($default);
3171  
3172 21 ▶ return sub {
Subroutine __ANON__: called CC=11 SCAR=24.2
3173 21 my ($v) = @_;
3174 21 ▶ if ( defined $v ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $v) 19 2 21
3175 19 my $record = eval { $db->record_for_address("$v") };
3176 19 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 2 17 19
3177 2 ▶ return $default if $has_default;
Branch: 1 branch
BranchTrueFalseTotal
if $has_default 1 1 2
3178 1 croak "geoip_country munger$where: '$v' is not a parseable IP address";
3179 }
3180 17 ▶ if ( ref $record eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $record eq "HASH") 12 5 17
3181 # Prefer where the address IS over where it is merely
3182 # registered; proxy/satellite records often lack the former.
3183 12 for my $section (qw(country registered_country)) {
3184 12 ▶ next unless ref $record->{$section} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $record->{$section} eq "HASH" 0 12 12
3185 12 my $alpha2 = $record->{$section}{iso_code};
3186 12 ▶ next unless defined $alpha2 && uc($alpha2) =~ /\A([A-Z])([A-Z])\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $alpha2 and uc($alpha2) =~ /\A([A-Z])([A-Z])\z/ 0 12 12
Condition33%1/3
defined $alpha2 and uc($alpha2) =~ /\A([A-Z])([A-Z])\z/
!ll&&!rl&&r
0012
MC/DC0%0/2
defined $alpha2 and uc($alpha2) =~ /\A([A-Z])([A-Z])\z/
defined $alpha2 uc($alpha2) =~ /\A([A-Z])([A-Z])\z/
Truth table33%1/3
A and B
A= defined $alpha2B= uc($alpha2) =~ /\A([A-Z])([A-Z])\z/
ABresult
0X0
100
111
3187 12 return ( ord($1) - 65 ) * 26 + ( ord($2) - 65 );
3188 }
3189 } ## end if ( ref $record eq 'HASH' )
3190 } ## end if ( defined $v )
3191 7 ▶ return $default if $has_default;
Branch: 1 branch
BranchTrueFalseTotal
if $has_default 4 3 7
3192 3 ▶ croak "geoip_country munger$where: '" . ( defined $v ? $v : 'undef' ) . "' resolves to no country";
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 2 1 3
3193 8 }; ## end sub
3194 } ## end sub _build_geoip_country
3195  
3196 =head2 datetime
3197  
3198 { munger => 'datetime', format => '%Y-%m-%dT%H:%M:%S', part => 'epoch' }
3199 { munger => 'datetime', format => '%Y-%m-%d %H:%M:%S', part => 'hour' }
3200  
3201 Parse a formatted timestamp with L<Time::Piece> (C<strptime>, so C<format> is a
3202 standard strptime pattern) and extract one numeric C<part>:
3203  
3204 =over 4
3205  
3206 =item * C<epoch> (default) - seconds since the epoch.
3207  
3208 =item * C<year>, C<mon> (1-12), C<mday> (1-31), C<hour>, C<min>, C<sec>.
3209  
3210 =item * C<wday> - day of week, C<0>=Sunday .. C<6>=Saturday.
3211  
3212 =item * C<yday> - day of year, C<0>-based.
3213  
3214 =item * C<frac_day> - time of day as a fraction in C<[0, 1)>, i.e.
3215 C<(hour*3600 + min*60 + sec) / 86400>. Handy as a cyclic-ish time-of-day feature.
3216  
3217 =item * C<frac_week> - position within the week as a fraction in C<[0, 1)>, the
3218 week starting Sunday to match C<wday>: C<(wday*86400 + hour*3600 + min*60 + sec)
3219 / 604800>. Like C<frac_day> but cycling over a week, so a weekly rhythm (weekend
3220 vs. weekday, or a Monday-morning batch) shows up as a feature.
3221  
3222 =item * C<sin_day> / C<cos_day>, C<sin_week> / C<cos_week> - the C<frac_*> value
3223 mapped onto a circle, C<sin(2*pi*frac)> and C<cos(2*pi*frac)>. Prefer these over
3224 the raw C<frac_*> when feeding the forest: a plain fraction has a false seam at
3225 the wrap (23:59 and 00:00 sit at opposite ends, 1 vs 0, though they are a minute
3226 apart), whereas the sin/cos pair is continuous across midnight/Sunday. Store
3227 I<both> of a pair in two columns so the position is unambiguous.
3228  
3229 =back
3230  
3231 Time features often carry the anomaly (a job that normally runs at 03:00
3232 suddenly firing at noon, or a weekday task firing on a Sunday), which is why this
3233 is a first-class munger.
3234  
3235 B<Multi-output form.> A cyclic pair belongs together -- C<sin> alone collides
3236 (C<sin> is symmetric about its peak, so two different times map to one value) and
3237 the forest then treats distinct times as identical. To emit a pair atomically,
3238 give C<parts> (plural) and route them to two columns with C<into> (see
3239 L</compile>):
3240  
3241 "time_of_week": {
3242 "munger": "datetime", "from": "timestamp",
3243 "format": "%Y-%m-%dT%H:%M:%S",
3244 "parts": [ "sin_week", "cos_week" ],
3245 "into": [ "time_sin", "time_cos" ]
3246 }
3247  
3248 The timestamp is parsed once and both columns are filled together, so they can
3249 never drift apart or be half-configured. C<parts> and C<into> must be the same
3250 length. (Using C<parts> without C<into>, or C<part> with C<into>, is an error.)
3251  
3252 B<Performance.> Two transparent accelerations, both value-identical to the plain
3253 path: a one-slot memo returns the previous result when the same stamp string
3254 repeats (the common case in bursty event streams); and when the format is built
3255 from only the six numeric codes C<%Y %m %d %H %M %S> (once each, e.g.
3256 C<%Y-%m-%dT%H:%M:%S>), parsing skips C<strptime> for a compiled regex plus
3257 integer date math, falling back to C<strptime> for any value the regex does not
3258 match B<or whose fields are out of range> (a month C<13>, an hour C<24>, a
3259 C<Feb 30>) -- so an invalid stamp croaks or normalizes exactly as C<strptime>
3260 would, never silently feeding nonsense to the date math. Like C<strptime>
3261 without a zone code, stamps are treated as UTC.
3262  
3263 =cut
3264  
3265 # Fraction (in [0,1)) of the way through the day / week, shared by the frac_*
3266 # parts and their sin/cos cyclic encodings.
3267 1 ▶sub _frac_day {
Subroutine _frac_day: called CC=1 SCAR=0.0
3268 1 my $t = shift;
3269 1 return ( $t->hour * 3600 + $t->min * 60 + $t->sec ) / 86400;
3270 }
3271  
3272 2 ▶sub _frac_week {
Subroutine _frac_week: called CC=1 SCAR=0.0
3273 2 my $t = shift;
3274 2 return ( $t->day_of_week * 86400 + $t->hour * 3600 + $t->min * 60 + $t->sec ) / 604800;
3275 }
3276  
3277 6 my $TWO_PI = 2 * atan2( 0, -1 ); # atan2(0,-1) == pi, core-only, no POSIX
3278  
3279 # part name => how to pull it off a Time::Piece object.
3280 my %DATETIME_PART = (
3281 23 ▶ epoch => sub { $_[0]->epoch },
Subroutine __ANON__: called CC=1 SCAR=0.0
3282 5 ▶ year => sub { $_[0]->year },
Subroutine __ANON__: called CC=1 SCAR=0.0
3283 3 ▶ mon => sub { $_[0]->mon },
Subroutine __ANON__: called CC=1 SCAR=0.0
3284 5 ▶ mday => sub { $_[0]->mday },
Subroutine __ANON__: called CC=1 SCAR=0.0
3285 9 ▶ hour => sub { $_[0]->hour },
Subroutine __ANON__: called CC=1 SCAR=0.0
3286 1 ▶ min => sub { $_[0]->min },
Subroutine __ANON__: called CC=1 SCAR=0.0
3287 2 ▶ sec => sub { $_[0]->sec },
Subroutine __ANON__: called CC=1 SCAR=0.0
3288 3 ▶ wday => sub { $_[0]->day_of_week },
Subroutine __ANON__: called CC=1 SCAR=0.0
3289 1 ▶ yday => sub { $_[0]->yday },
Subroutine __ANON__: called CC=1 SCAR=0.0
3290 frac_day => \&_frac_day,
3291 frac_week => \&_frac_week,
3292 0 ▶ sin_day => sub { sin( $TWO_PI * _frac_day( $_[0] ) ) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
3293 0 ▶ cos_day => sub { cos( $TWO_PI * _frac_day( $_[0] ) ) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
3294 1 ▶ sin_week => sub { sin( $TWO_PI * _frac_week( $_[0] ) ) },
Subroutine __ANON__: called CC=1 SCAR=0.0
3295 1 ▶ cos_week => sub { cos( $TWO_PI * _frac_week( $_[0] ) ) },
Subroutine __ANON__: called CC=1 SCAR=0.0
3296 6 );
3297  
3298 # ---- fast fixed-format engine ----------------------------------------------
3299 #
3300 # Time::Piece->strptime costs microseconds per call. When the format is built
3301 # from only the six all-numeric codes below (once each, e.g. the ubiquitous
3302 # '%Y-%m-%dT%H:%M:%S'), we can compile it to a capture regex and derive every
3303 # part with integer math instead -- several times faster, and bit-identical:
3304 # both paths treat the stamp as UTC (strptime with no zone does the same).
3305 # Anything fancier (%b, %z, %j, ...) stays on strptime.
3306  
3307 # strptime code => [ field name, capture pattern ].
3308 6 my %FAST_CODE = (
3309 Y => [ 'year', '[0-9]{4}' ],
3310 m => [ 'mon', '[0-9]{2}' ],
3311 d => [ 'mday', '[0-9]{2}' ],
3312 H => [ 'hour', '[0-9]{2}' ],
3313 M => [ 'min', '[0-9]{2}' ],
3314 S => [ 'sec', '[0-9]{2}' ],
3315 );
3316  
3317 # Compile a strptime format into { re, idx } for the arithmetic fast path --
3318 # idx maps field name (year/mon/...) to its capture position -- or return undef
3319 # when the format is not fast-eligible. All six codes must appear exactly once
3320 # so every part can be derived.
3321 104 ▶sub _compile_fast_format {
Subroutine _compile_fast_format: called CC=7 SCAR=19.6
3322 104 my ($format) = @_;
3323 104 my $re = '';
3324 104 my %idx = ();
3325 104 my $n = 0;
3326 104 my $rest = $format;
3327 104 ▶ while ( length $rest ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $rest) 624 49 673
3328 624 ▶ if ( $rest =~ s/\A%(.)//s ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($rest =~ s/\A%(.)//s) { } 369 255 624
elsif ($rest =~ s/\A([^%]+)//s) { } 255 0 255
3329 369 ▶ my $f = $FAST_CODE{$1} or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $f = $FAST_CODE{$1} or return undef 314 55 369
3330 314 ▶ return undef if exists $idx{ $f->[0] };
Branch: 1 branch
BranchTrueFalseTotal
if exists $idx{$f->[0]} 0 314 314
3331 314 $idx{ $f->[0] } = $n++;
3332 314 $re .= '(' . $f->[1] . ')';
3333 } elsif ( $rest =~ s/\A([^%]+)//s ) {
3334 255 $re .= quotemeta($1);
3335 } else {
3336 0 return undef; # lone trailing '%' -- not fast-eligible
3337 }
3338 } ## end while ( length $rest )
3339 49 ▶ return undef unless keys %idx == 6;
Branch: 1 branch
BranchTrueFalseTotal
unless keys %idx == 6 13 36 49
3340 36 return { re => qr/\A$re\z/, idx => \%idx };
3341 } ## end sub _compile_fast_format
3342  
3343 # A regex match only proves each fast-path field is digits of the right width,
3344 # not that the six of them form a real timestamp: '2026-13-01T25:00:00' matches
3345 # the shape. Fields out of range (month 13, hour 24, Feb 30) must not reach the
3346 # blind integer date math -- they are routed to strptime instead, which stays
3347 # the judge of whether such a stamp croaks or normalizes (Time::Piece rolls
3348 # Feb 30 over into March), keeping the two paths value-identical. Seconds stop
3349 # at 59: a :60 leap second is not representable in epoch math, so strptime
3350 # arbitrates it too.
3351 6 my @DAYS_IN_MONTH = ( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
3352  
3353 156 ▶sub _fast_fields_in_range {
Subroutine _fast_fields_in_range: called CC=12 SCAR=24.9
3354 156 my ( $c, $idx ) = @_;
3355 156 my ( $y, $m, $d, $H, $M, $S ) = @{$c}[ @{$idx}{qw(year mon mday hour min sec)} ];
3356 156 ▶ return 0 if $m < 1 || $m > 12;
Branch: 1 branch
BranchTrueFalseTotal
if $m < 1 or $m > 12 11 145 156
Condition100%3/3
$m < 1 or $m > 12
l!l&&r!l&&!r
56145
MC/DC100%2/2
$m < 1 or $m > 12
$m < 1 $m > 12
Truth table100%3/3
A or B
A= $m < 1B= $m > 12
ABresult
1X1
011
000
3357 145 my $dim = $DAYS_IN_MONTH[ $m - 1 ];
3358 145 ▶ $dim = 29 if $m == 2 && ( ( !( $y % 4 ) && $y % 100 ) || !( $y % 400 ) );
Branch: 1 branch
BranchTrueFalseTotal
if $m == 2 and !($y % 4) && $y % 100 || !($y % 400) 20 125 145
Condition100%9/9
$m == 2 and !($y % 4) && $y % 100 || !($y % 400)
!ll&&!rl&&r
1101520
not $y % 4 and $y % 100 or not $y % 400
l!l&&r!l&&!r
51515
not $y % 4 and $y % 100
!ll&&!rl&&r
10205
MC/DC100%4/4
$m == 2 and !($y % 4) && $y % 100 || !($y % 400)
$m == 2 not $y % 4 $y % 100 not $y % 400
Truth table83%5/6
A and not(B) and C or not(D)
A= $m == 2B= not $y % 4C= $y % 100D= not $y % 400
ABCDresult
0XXX0
10X00
11000
111X1
10X11
11011
3359 145 ▶ return 0 if $d < 1 || $d > $dim;
Branch: 1 branch
BranchTrueFalseTotal
if $d < 1 or $d > $dim 20 125 145
Condition100%3/3
$d < 1 or $d > $dim
l!l&&r!l&&!r
515125
MC/DC100%2/2
$d < 1 or $d > $dim
$d < 1 $d > $dim
Truth table100%3/3
A or B
A= $d < 1B= $d > $dim
ABresult
1X1
011
000
3360 125 ▶ return 0 if $H > 23 || $M > 59 || $S > 59;
Branch: 1 branch
BranchTrueFalseTotal
if $H > 23 or $M > 59 or $S > 59 10 115 125
Condition83%5/6
$H > 23 or $M > 59 or $S > 59
l!l&&r!l&&!r
100115
$H > 23 or $M > 59
l!l&&r!l&&!r
55115
MC/DC66%2/3
$H > 23 or $M > 59 or $S > 59
$H > 23 $M > 59 $S > 59
Truth table75%3/4
A or B or C
A= $H > 23B= $M > 59C= $S > 59
ABCresult
1XX1
01X1
0011
0000
3361 115 return 1;
3362 } ## end sub _fast_fields_in_range
3363  
3364 # Days since 1970-01-01 for a proleptic-Gregorian date (Howard Hinnant's
3365 # days-from-civil). Pure integer math; Perl's % already yields a non-negative
3366 # result for the wday derivation even on pre-1970 dates.
3367 62 ▶sub _days_from_civil {
Subroutine _days_from_civil: called CC=3 SCAR=11.0
3368 62 my ( $y, $m, $d ) = @_;
3369 62 $y -= $m <= 2;
3370 62 ▶ my $era = int( ( $y >= 0 ? $y : $y - 399 ) / 400 );
Branch: 1 branch
BranchTrueFalseTotal
$y >= 0 ? : 62 0 62
3371 62 my $yoe = $y - $era * 400;
3372 62 ▶ my $doy = int( ( 153 * ( $m + ( $m > 2 ? -3 : 9 ) ) + 2 ) / 5 ) + $d - 1;
Branch: 1 branch
BranchTrueFalseTotal
$m > 2 ? : 42 20 62
3373 62 my $doe = $yoe * 365 + int( $yoe / 4 ) - int( $yoe / 100 ) + $doy;
3374 62 return $era * 146097 + $doe - 719468;
3375 }
3376  
3377 # part name => factory(\%idx) => getter(\@captures). Mirrors %DATETIME_PART;
3378 # t/mungers-datetime-fast.t asserts the two stay value-identical. The factories
3379 # bake the capture positions in at build time so a per-row getter indexes the
3380 # raw capture array directly -- no intermediate hash per row, which is where
3381 # the fast path's time would otherwise go. Slot 6 of the capture array caches
3382 # days-from-civil so a multi-part (sin/cos) extraction computes it once.
3383 6 my %DATETIME_PART_FAST;
3384 {
3385 6 ▶ my $days_of = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
3386 22 my ( $iy, $im, $id ) = @{ $_[0] }{qw(year mon mday)};
3387 60 ▶ return sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
3388 60 my $c = shift;
3389 60 ▶ return defined $c->[6]
Branch: 1 branch
BranchTrueFalseTotal
defined $c->[6] ? : 4 56 60
3390 ? $c->[6]
3391 : ( $c->[6] = _days_from_civil( $c->[$iy], $c->[$im], $c->[$id] ) );
3392 22 };
3393 6 };
3394 25 ▶ my $sod_of = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
3395 25 my ( $ih, $in, $is ) = @{ $_[0] }{qw(hour min sec)};
3396 25 ▶ return sub { $_[0][$ih] * 3600 + $_[0][$in] * 60 + $_[0][$is] };
Subroutine __ANON__: called CC=1 SCAR=0.0
3397 6 };
3398 6 ▶ my $frac_day_of = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
3399 6 my $sod = $sod_of->( $_[0] );
3400 6 ▶ return sub { $sod->( $_[0] ) / 86400 };
Subroutine __ANON__: called CC=1 SCAR=0.0
3401 6 };
3402 13 ▶ my $frac_week_of = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
3403 13 my ( $days, $sod ) = ( $days_of->( $_[0] ), $sod_of->( $_[0] ) );
3404 29 ▶ return sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
3405 29 my $c = shift;
3406 29 return ( ( ( $days->($c) + 4 ) % 7 ) * 86400 + $sod->($c) ) / 604800;
3407 13 };
3408 6 };
3409 36 ▶ my $field_of = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
3410 36 my ($name) = @_;
3411 12 ▶ return sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
3412 12 my $i = $_[0]{$name};
3413 57 ▶ return sub { $_[0][$i] + 0 }
Subroutine __ANON__: called CC=1 SCAR=0.0
3414 36 };
3415 6 };
3416  
3417 %DATETIME_PART_FAST = (
3418 year => $field_of->('year'),
3419 mon => $field_of->('mon'),
3420 mday => $field_of->('mday'),
3421 hour => $field_of->('hour'),
3422 min => $field_of->('min'),
3423 sec => $field_of->('sec'),
3424 6 ▶ epoch => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
3425 6 my ( $days, $sod ) = ( $days_of->( $_[0] ), $sod_of->( $_[0] ) );
3426 6 ▶ return sub { $days->( $_[0] ) * 86400 + $sod->( $_[0] ) };
Subroutine __ANON__: called CC=1 SCAR=0.0
3427 },
3428 2 ▶ wday => sub { # epoch day 0 = Thursday = 4
Subroutine __ANON__: called CC=1 SCAR=0.0
3429 2 my $days = $days_of->( $_[0] );
3430 2 ▶ return sub { ( $days->( $_[0] ) + 4 ) % 7 };
Subroutine __ANON__: called CC=1 SCAR=0.0
3431 },
3432 1 ▶ yday => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
3433 1 my ($idx) = @_;
3434 1 my $days = $days_of->($idx);
3435 1 my $iy = $idx->{year};
3436 6 ▶ return sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
3437 6 my $c = shift;
3438 6 return $days->($c) - _days_from_civil( $c->[$iy], 1, 1 );
3439 1 };
3440 },
3441 frac_day => $frac_day_of,
3442 frac_week => $frac_week_of,
3443 2 ▶ sin_day => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
3444 2 my $f = $frac_day_of->( $_[0] );
3445 2 ▶ return sub { sin( $TWO_PI * $f->( $_[0] ) ) };
Subroutine __ANON__: called CC=1 SCAR=0.0
3446 },
3447 2 ▶ cos_day => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
3448 2 my $f = $frac_day_of->( $_[0] );
3449 2 ▶ return sub { cos( $TWO_PI * $f->( $_[0] ) ) };
Subroutine __ANON__: called CC=1 SCAR=0.0
3450 },
3451 5 ▶ sin_week => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
3452 5 my $f = $frac_week_of->( $_[0] );
3453 5 ▶ return sub { sin( $TWO_PI * $f->( $_[0] ) ) };
Subroutine __ANON__: called CC=1 SCAR=0.0
3454 },
3455 6 ▶ cos_week => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
3456 6 my $f = $frac_week_of->( $_[0] );
3457 6 ▶ return sub { cos( $TWO_PI * $f->( $_[0] ) ) };
Subroutine __ANON__: called CC=1 SCAR=0.0
3458 },
3459 6 );
3460 }
3461  
3462 # Build the parse/getter machinery for a datetime spec: ($parse, $getter_for),
3463 # where $parse->($v) yields whatever the getters consume (a capture array on
3464 # the fast path, a Time::Piece object otherwise) and $getter_for->($part)
3465 # resolves a part name to a getter closure, croaking on an unknown part.
3466 # Shared by the scalar and multi-output builders so the choice is made in
3467 # exactly one place.
3468 91 ▶sub _datetime_engine {
Subroutine _datetime_engine: called CC=4 SCAR=13.9
3469 91 my ( $format, $where ) = @_;
3470 91 ▶ croak "datetime munger$where requires a strptime 'format'"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $format and length $format 0 91 91
Condition33%1/3
defined $format and length $format
!ll&&!rl&&r
0091
MC/DC0%0/2
defined $format and length $format
defined $format length $format
Truth table33%1/3
A and B
A= defined $formatB= length $format
ABresult
0X0
100
111
3471 unless defined $format && length $format;
3472  
3473 # Time::Piece is not core on the ancient perls Makefile.PL still nominally
3474 # supports, so only pull it in for the one munger that needs it. The fast
3475 # path keeps it loaded too: a regex mismatch falls back to strptime so the
3476 # fast path can never reject a value the slow path would have accepted.
3477 91 require Time::Piece;
3478  
3479 98 ▶ my $strptime = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
3480 98 my ($v) = @_;
3481 98 my $t = eval { Time::Piece->strptime( $v, $format ) };
3482 98 ▶ croak "datetime munger$where: cannot parse '$v' with '$format'"
Branch: 1 branch
BranchTrueFalseTotal
unless $t 23 75 98
3483 unless $t;
3484 75 return $t;
3485 91 };
3486  
3487 91 ▶ if ( my $fast = _compile_fast_format($format) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $fast = _compile_fast_format($format)) 36 55 91
3488 36 my ( $re, $idx ) = @{$fast}{qw(re idx)};
3489 158 ▶ my $parse = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
3490 158 my ($v) = @_;
3491 158 ▶ croak "datetime munger$where: undefined value" unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 158 158
3492 158 ▶ if ( my @c = $v =~ $re ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@c) = $v =~ /$re/) 156 2 158
3493 156 ▶ return \@c if _fast_fields_in_range( \@c, $idx );
Branch: 1 branch
BranchTrueFalseTotal
if _fast_fields_in_range(\@c, $idx) 115 41 156
3494 }
3495 # Regex mismatch or out-of-range fields: let strptime be the judge,
3496 # rebuilding the capture array (normalized, when strptime chooses
3497 # to normalize rather than reject) in this format's capture order.
3498 43 my $t = $strptime->($v);
3499 21 my @c;
3500 21 @c[ @{$idx}{qw(year mon mday hour min sec)} ]
3501 = ( $t->year, $t->mon, $t->mday, $t->hour, $t->min, $t->sec );
3502 21 return \@c;
3503 36 }; ## end $parse = sub
3504 40 ▶ my $getter_for = sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
3505 40 my ($part) = @_;
3506 40 ▶ my $factory = $DATETIME_PART_FAST{$part}
Branch: 1 branch
BranchTrueFalseTotal
my $factory = $DATETIME_PART_FAST{$part} or croak("datetime munger${where}: unknown part '${part}' (known: " . join(", ", sort(keys %DATETIME_PART)) . ')') 40 0 40
3507 or croak "datetime munger$where: unknown part '$part' (known: "
3508 . join( ', ', sort keys %DATETIME_PART ) . ')';
3509 40 return $factory->($idx);
3510 36 };
3511 36 return ( $parse, $getter_for );
3512 } ## end if ( my $fast = _compile_fast_format($format...))
3513  
3514 56 ▶ my $parse = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
3515 56 my ($v) = @_;
3516 56 ▶ croak "datetime munger$where: undefined value" unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 1 55 56
3517 55 return $strptime->($v);
3518 55 };
3519 56 ▶ my $getter_for = sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
3520 56 my ($part) = @_;
3521 56 ▶ my $get = $DATETIME_PART{$part}
Branch: 1 branch
BranchTrueFalseTotal
my $get = $DATETIME_PART{$part} or croak("datetime munger${where}: unknown part '${part}' (known: " . join(", ", sort(keys %DATETIME_PART)) . ')') 56 0 56
3522 or croak "datetime munger$where: unknown part '$part' (known: "
3523 . join( ', ', sort keys %DATETIME_PART ) . ')';
3524 56 return $get;
3525 55 };
3526 55 return ( $parse, $getter_for );
3527 } ## end sub _datetime_engine
3528  
3529 85 ▶sub _build_datetime {
Subroutine _build_datetime: called CC=3 SCAR=11.0
3530 85 my ( $spec, $where ) = @_;
3531  
3532 croak "datetime munger$where: 'parts' is for the multi-output form (needs "
3533 . "'into'); use 'part' for a single column"
3534 85 ▶ if defined $spec->{parts};
Branch: 1 branch
BranchTrueFalseTotal
if defined $spec->{"parts"} 1 84 85
3535  
3536 84 my ( $parse, $getter_for ) = _datetime_engine( $spec->{format}, $where );
3537 84 ▶ my $get = $getter_for->( defined $spec->{part} ? $spec->{part} : 'epoch' );
Branch: 1 branch
BranchTrueFalseTotal
defined $spec->{'part'} ? : 84 0 84
3538  
3539 # One-slot memo: event streams repeat the same stamp within a second
3540 # constantly, so the previous input usually answers the next call with a
3541 # string compare. A parse failure leaves the memo untouched.
3542 84 my ( $memo_in, $memo_out );
3543 251 ▶ return sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
3544 251 my ($v) = @_;
3545 251 ▶ return $memo_out
Branch: 1 branch
BranchTrueFalseTotal
if defined $v and defined $memo_in and $v eq $memo_in 42 209 251
Condition100%6/6
defined $v and defined $memo_in and $v eq $memo_in
!ll&&!rl&&r
10510442
defined $v and defined $memo_in
!ll&&!rl&&r
1104146
MC/DC100%3/3
defined $v and defined $memo_in and $v eq $memo_in
defined $v defined $memo_in $v eq $memo_in
Truth table100%4/4
A and B and C
A= defined $vB= defined $memo_inC= $v eq $memo_in
ABCresult
0XX0
10X0
1100
1111
3546 if defined $v && defined $memo_in && $v eq $memo_in;
3547 209 my $out = $get->( $parse->($v) );
3548 185 ( $memo_in, $memo_out ) = ( $v, $out );
3549 185 return $out;
3550 84 };
3551 } ## end sub _build_datetime
3552  
3553 # Multi-output datetime: parse once, emit one number per part, in 'parts' order
3554 # (which lines up with the caller's 'into'). Returns ($list_returning_code,
3555 # $arity) so compile() can check the arity against 'into'. Memoized like the
3556 # scalar form, caching the whole output list per input stamp.
3557 7 ▶sub _build_datetime_multi {
Subroutine _build_datetime_multi: called CC=3 SCAR=11.1
3558 7 my ( $spec, $where ) = @_;
3559  
3560 7 my $parts = $spec->{parts};
3561 7 ▶ croak "datetime munger$where: 'parts' must be a non-empty arrayref"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $parts eq "ARRAY" and @$parts 0 7 7
Condition33%1/3
ref $parts eq "ARRAY" and @$parts
!ll&&!rl&&r
007
MC/DC0%0/2
ref $parts eq "ARRAY" and @$parts
ref $parts eq "ARRAY" @$parts
Truth table33%1/3
A and B
A= ref $parts eq "ARRAY"B= @$parts
ABresult
0X0
100
111
3562 unless ref $parts eq 'ARRAY' && @$parts;
3563  
3564 7 my ( $parse, $getter_for ) = _datetime_engine( $spec->{format}, $where );
3565 7 my @get = map { $getter_for->($_) } @$parts;
3566  
3567 7 my ( $memo_in, @memo_out );
3568 7 ▶ my $code = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
3569 7 my ($v) = @_;
3570 return @memo_out
3571 7 ▶ if defined $v && defined $memo_in && $v eq $memo_in;
Branch: 1 branch
BranchTrueFalseTotal
if defined $v and defined $memo_in and $v eq $memo_in 2 5 7
Condition83%5/6
defined $v and defined $memo_in and $v eq $memo_in
!ll&&!rl&&r
412
defined $v and defined $memo_in
!ll&&!rl&&r
043
MC/DC66%2/3
defined $v and defined $memo_in and $v eq $memo_in
defined $v defined $memo_in $v eq $memo_in
Truth table75%3/4
A and B and C
A= defined $vB= defined $memo_inC= $v eq $memo_in
ABCresult
0XX0
10X0
1100
1111
3572 5 my $t = $parse->($v);
3573 5 my @out = map { $_->($t) } @get;
3574 5 ( $memo_in, @memo_out ) = ( $v, @out );
3575 5 return @out;
3576 7 };
3577 7 return ( $code, scalar @$parts );
3578 } ## end sub _build_datetime_multi
3579  
3580 =head2 hash
3581  
3582 { munger => 'hash', buckets => 1024 }
3583 { munger => 'hash', buckets => 1024, seed => 7 }
3584 { munger => 'hash' } # raw 32-bit FNV-1a value
3585  
3586 Feature hashing for high-cardinality categoricals you do not want to (or cannot)
3587 enumerate with C<enum>. The input is stringified and run through 32-bit FNV-1a;
3588 with C<buckets> the result is reduced modulo that many buckets (C<[0, buckets)>),
3589 otherwise the full 32-bit hash is returned. An optional C<seed> lets you decorrelate
3590 two hashed columns.
3591  
3592 This is the one munger that is XS-accelerated: FNV-1a is a per-byte loop with a
3593 32-bit modular multiply, which is slow in pure Perl and (on a 32-bit perl) fussy
3594 to get exactly right. C<$Algorithm::ToNumberMunger::HAVE_XS>
3595 reports whether the compiled path is in use; a pure-Perl fallback (exact on a
3596 64-bit perl) is used otherwise, and both produce identical values.
3597  
3598 =cut
3599  
3600 5 ▶sub _build_hash {
Subroutine _build_hash: called CC=6 SCAR=18.0
3601 5 my ( $spec, $where ) = @_;
3602  
3603 5 my $buckets = $spec->{buckets};
3604 5 ▶ croak "hash munger$where: 'buckets' must be a positive integer"
Branch: 1 branch
BranchTrueFalseTotal
if defined $buckets and not $buckets =~ /\A[1-9][0-9]*\z/ 1 4 5
Condition100%3/3
defined $buckets and not $buckets =~ /\A[1-9][0-9]*\z/
!ll&&!rl&&r
131
MC/DC100%2/2
defined $buckets and not $buckets =~ /\A[1-9][0-9]*\z/
defined $buckets not $buckets =~ /\A[1-9][0-9]*\z/
Truth table100%3/3
A and not(B)
A= defined $bucketsB= not $buckets =~ /\A[1-9][0-9]*\z/
ABresult
0X0
100
111
3605 if defined $buckets && $buckets !~ /\A[1-9][0-9]*\z/;
3606  
3607 4 ▶ my $seed = defined $spec->{seed} ? $spec->{seed} : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $spec->{'seed'} ? : 2 2 4
3608 4 ▶ croak "hash munger$where: 'seed' must be a non-negative integer"
Branch: 1 branch
BranchTrueFalseTotal
unless $seed =~ /\A[0-9]+\z/ 0 4 4
3609 if $seed !~ /\A[0-9]+\z/;
3610  
3611 4 ▶ my $fn = $HAVE_XS ? \&_fnv1a_xs : \&_fnv1a_pp;
Branch: 1 branch
BranchTrueFalseTotal
$HAVE_XS ? : 4 0 4
3612 7 ▶ return sub {
Subroutine __ANON__: called CC=3 SCAR=11.1
3613 7 my ($v) = @_;
3614 7 ▶ my $h = $fn->( defined $v ? "$v" : '', $seed );
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 7 0 7
3615 7 ▶ return defined $buckets ? $h % $buckets : $h;
Branch: 1 branch
BranchTrueFalseTotal
defined $buckets ? : 4 3 7
3616 4 };
3617 } ## end sub _build_hash
3618  
3619 # Pure-Perl 32-bit FNV-1a, used only when the XS did not build. On a 64-bit
3620 # perl the intermediate h*16777619 (< 2**57) stays an exact integer, so the
3621 # masked result matches the C version bit for bit. The string is always
3622 # utf8-encoded first so a value hashes as its UTF-8 bytes no matter the internal
3623 # flag -- the same well-defined bytes SvPVutf8 hands the XS.
3624 0 ▶sub _fnv1a_pp {
Subroutine _fnv1a_pp: not called CC=2 SCAR=17.9
3625 0 my ( $str, $seed ) = @_;
3626 0 utf8::encode($str);
3627 0 my $h = ( 2166136261 ^ ( $seed & 0xFFFFFFFF ) ) & 0xFFFFFFFF;
3628 0 for my $c ( unpack 'C*', $str ) {
3629 0 $h ^= $c;
3630 0 $h = ( $h * 16777619 ) & 0xFFFFFFFF;
3631 }
3632 0 return $h;
3633 } ## end sub _fnv1a_pp
3634  
3635 =head2 chain
3636  
3637 # Shannon entropy of just the TLD: lowercase, keep the last dot-label
3638 { munger => 'chain',
3639 steps => [ { op => 'lc' }, { op => 'split', on => '.', index => -1 } ],
3640 then => { munger => 'entropy' } }
3641  
3642 # a hex request id buried in a token like 'req-0x2F'
3643 { munger => 'chain',
3644 steps => [ { op => 'capture', pattern => 'req-(0x[0-9a-fA-F]+)' } ],
3645 then => { munger => 'num', base => 16 } }
3646  
3647 Run the input through a list of string pre-transforms (C<steps>, applied in
3648 order), then hand the result to a terminal munger (C<then>) for the actual
3649 number. Every string munger above scores the I<whole> value; C<chain> is how a
3650 feature targets a I<piece> of it -- the entropy of the TLD alone, the length
3651 of the first path segment, an enum over a normalized token -- without asking
3652 the writer's caller to pre-slice its input. Each step is a hashref with an
3653 C<op>:
3654  
3655 =over 4
3656  
3657 =item * C<lc> / C<uc> - case-fold the value.
3658  
3659 =item * C<trim> - strip leading and trailing whitespace.
3660  
3661 =item * C<split> - split on the literal separator C<on> and keep piece
3662 C<index> (0-based; negative counts from the end, so C<-1> is a hostname's last
3663 label). An index past either end yields the empty string.
3664  
3665 =item * C<capture> - match the regex C<pattern> and keep capture group
3666 C<group> (default C<1>). No match, or a group that did not participate, yields
3667 the empty string. A true C<ignore_case> matches case-insensitively; the
3668 L</match> trust note applies here too.
3669  
3670 =item * C<replace> - replace every match of the regex C<pattern> with the
3671 literal string C<with> (default: delete the matches). C<ignore_case> as above.
3672  
3673 =back
3674  
3675 C<then> is a full munger spec and may be any built-in that takes one value --
3676 including another C<chain>. All step parameters and the terminal spec are
3677 validated at build time. An undef input enters the chain as the empty string;
3678 whether an empty result is acceptable is the terminal's call (C<entropy> and
3679 C<length> score it C<0>, C<num> croaks).
3680  
3681 The multi-output form works too: put C<into> on the B<chain> and the C<parts>
3682 on the terminal, e.g. C<trim> a sloppy timestamp before a L</datetime>
3683 C<sin>/C<cos> expansion.
3684  
3685 =cut
3686  
3687 # op => step builder; each validates its slice of the step spec at build time
3688 # and returns a string-to-string closure. Steps only ever see a defined string
3689 # (the chain entry point turns undef into '').
3690 my %CHAIN_OPS = (
3691 5 ▶ lc => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
3692 4 ▶ return sub { return lc $_[0] }
Subroutine __ANON__: called CC=1 SCAR=0.0
3693 5 },
3694 1 ▶ uc => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
3695 1 ▶ return sub { return uc $_[0] }
Subroutine __ANON__: called CC=1 SCAR=0.0
3696 1 },
3697 3 ▶ trim => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
3698 3 ▶ return sub { my ($s) = @_; $s =~ s/\A\s+//; $s =~ s/\s+\z//; return $s };
Subroutine __ANON__: called CC=1 SCAR=0.0
3699 },
3700 5 ▶ split => sub {
Subroutine __ANON__: called CC=5 SCAR=16.2
3701 5 my ( $step, $where ) = @_;
3702 5 my $on = $step->{on};
3703 5 ▶ croak "chain munger$where: split step requires a non-empty 'on' string"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $on and length $on 1 4 5
Condition66%2/3
defined $on and length $on
!ll&&!rl&&r
104
MC/DC50%1/2
defined $on and length $on
defined $on length $on
Truth table66%2/3
A and B
A= defined $onB= length $on
ABresult
0X0
100
111
3704 unless defined $on && length $on;
3705 4 ▶ my $idx = defined $step->{index} ? $step->{index} : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $step->{'index'} ? : 4 0 4
3706 4 ▶ croak "chain munger$where: split 'index' must be an integer"
Branch: 1 branch
BranchTrueFalseTotal
unless $idx =~ /\A-?[0-9]+\z/ 0 4 4
3707 unless $idx =~ /\A-?[0-9]+\z/;
3708 # limit -1 keeps trailing empty pieces, so 'a.' really has two labels
3709 # and index -1 is the empty last one, not 'a'.
3710 6 ▶ return sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
3711 6 my @p = split /\Q$on\E/, $_[0], -1;
3712 6 ▶ return ( $idx > $#p || $idx < -@p ) ? '' : $p[$idx];
Branch: 1 branch
BranchTrueFalseTotal
$idx > $#p || $idx < -@p ? : 2 4 6
Condition100%3/3
$idx > $#p or $idx < -@p
l!l&&r!l&&!r
114
MC/DC100%2/2
$idx > $#p or $idx < -@p
$idx > $#p $idx < -@p
Truth table100%3/3
A or B
A= $idx > $#pB= $idx < -@p
ABresult
1X1
011
000
3713 4 };
3714 },
3715 3 ▶ capture => sub {
Subroutine __ANON__: called CC=7 SCAR=20.1
3716 3 my ( $step, $where ) = @_;
3717 3 my $pat = $step->{pattern};
3718 3 ▶ croak "chain munger$where: capture step requires a non-empty 'pattern'"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pat and length $pat 0 3 3
Condition33%1/3
defined $pat and length $pat
!ll&&!rl&&r
003
MC/DC0%0/2
defined $pat and length $pat
defined $pat length $pat
Truth table33%1/3
A and B
A= defined $patB= length $pat
ABresult
0X0
100
111
3719 unless defined $pat && length $pat;
3720 3 ▶ my $re = eval { $step->{ignore_case} ? qr/$pat/i : qr/$pat/ };
Branch: 1 branch
BranchTrueFalseTotal
$step->{'ignore_case'} ? : 1 2 3
3721 3 ▶ croak "chain munger$where: cannot compile pattern '$pat': $@"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $re 1 2 3
3722 unless defined $re;
3723 2 ▶ my $group = defined $step->{group} ? $step->{group} : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $step->{'group'} ? : 0 2 2
3724 2 ▶ croak "chain munger$where: capture 'group' must be a positive integer"
Branch: 1 branch
BranchTrueFalseTotal
unless $group =~ /\A[1-9][0-9]*\z/ 0 2 2
3725 unless $group =~ /\A[1-9][0-9]*\z/;
3726 # @-/@+ rather than a list-context match: a pattern with no capture
3727 # groups returns (1) in list context, which would masquerade as a
3728 # captured '1'; $#+ says how many groups the pattern really has.
3729 2 ▶ return sub {
Subroutine __ANON__: called CC=4 SCAR=14.1
3730 2 my ($s) = @_;
3731 2 ▶ return '' unless $s =~ $re;
Branch: 1 branch
BranchTrueFalseTotal
unless $s =~ /$re/ 0 2 2
3732 2 ▶ return '' unless $group <= $#+ && defined $-[$group];
Branch: 1 branch
BranchTrueFalseTotal
unless $group <= $#+ and defined $-[$group] 1 1 2
Condition66%2/3
$group <= $#+ and defined $-[$group]
!ll&&!rl&&r
101
MC/DC50%1/2
$group <= $#+ and defined $-[$group]
$group <= $#+ defined $-[$group]
Truth table66%2/3
A and B
A= $group <= $#+B= defined $-[$group]
ABresult
0X0
100
111
3733 1 return substr( $s, $-[$group], $+[$group] - $-[$group] );
3734 2 };
3735 },
3736 2 ▶ replace => sub {
Subroutine __ANON__: called CC=6 SCAR=18.6
3737 2 my ( $step, $where ) = @_;
3738 2 my $pat = $step->{pattern};
3739 2 ▶ croak "chain munger$where: replace step requires a non-empty 'pattern'"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pat and length $pat 0 2 2
Condition33%1/3
defined $pat and length $pat
!ll&&!rl&&r
002
MC/DC0%0/2
defined $pat and length $pat
defined $pat length $pat
Truth table33%1/3
A and B
A= defined $patB= length $pat
ABresult
0X0
100
111
3740 unless defined $pat && length $pat;
3741 2 ▶ my $re = eval { $step->{ignore_case} ? qr/$pat/i : qr/$pat/ };
Branch: 1 branch
BranchTrueFalseTotal
$step->{'ignore_case'} ? : 0 2 2
3742 2 ▶ croak "chain munger$where: cannot compile pattern '$pat': $@"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $re 0 2 2
3743 unless defined $re;
3744 2 ▶ my $with = defined $step->{with} ? $step->{with} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $step->{'with'} ? : 1 1 2
3745 2 ▶ return sub { my ($s) = @_; $s =~ s/$re/$with/g; return $s };
Subroutine __ANON__: called CC=1 SCAR=0.0
3746 },
3747 6 );
3748  
3749 # Compile the 'steps' list into string-to-string closures; shared by the
3750 # scalar and multi-output chain builders.
3751 18 ▶sub _chain_steps {
Subroutine _chain_steps: called CC=8 SCAR=21.3
3752 18 my ( $spec, $where ) = @_;
3753  
3754 18 my $steps = $spec->{steps};
3755 18 ▶ croak "chain munger$where requires a non-empty 'steps' arrayref"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $steps eq "ARRAY" and @$steps 1 17 18
Condition66%2/3
ref $steps eq "ARRAY" and @$steps
!ll&&!rl&&r
1017
MC/DC50%1/2
ref $steps eq "ARRAY" and @$steps
ref $steps eq "ARRAY" @$steps
Truth table66%2/3
A and B
A= ref $steps eq "ARRAY"B= @$steps
ABresult
0X0
100
111
3756 unless ref $steps eq 'ARRAY' && @$steps;
3757  
3758 17 my @ops;
3759 17 for my $i ( 0 .. $#$steps ) {
3760 20 my $step = $steps->[$i];
3761 20 ▶ croak "chain munger$where: step[$i] must be a hashref"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $step eq "HASH" 0 20 20
3762 unless ref $step eq 'HASH';
3763 20 my $op = $step->{op};
3764 20 ▶ croak "chain munger$where: step[$i] has no 'op'"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $op and length $op 0 20 20
Condition33%1/3
defined $op and length $op
!ll&&!rl&&r
0020
MC/DC0%0/2
defined $op and length $op
defined $op length $op
Truth table33%1/3
A and B
A= defined $opB= length $op
ABresult
0X0
100
111
3765 unless defined $op && length $op;
3766 20 ▶ my $mk = $CHAIN_OPS{$op}
Branch: 1 branch
BranchTrueFalseTotal
my $mk = $CHAIN_OPS{$op} or croak("chain munger${where}: step[$i] has unknown op '${op}' (known: " . join(", ", sort(keys %CHAIN_OPS)) . ')') 19 1 20
3767 or croak "chain munger$where: step[$i] has unknown op '$op' (known: "
3768 . join( ', ', sort keys %CHAIN_OPS ) . ')';
3769 19 push @ops, $mk->( $step, $where );
3770 } ## end for my $i ( 0 .. $#$steps )
3771 14 return \@ops;
3772 } ## end sub _chain_steps
3773  
3774 # Validate and unpack the terminal spec; shared like _chain_steps.
3775 14 ▶sub _chain_terminal_spec {
Subroutine _chain_terminal_spec: called CC=4 SCAR=14.3
3776 14 my ( $spec, $where ) = @_;
3777 14 my $then = $spec->{then};
3778 14 ▶ croak "chain munger$where requires a 'then' hashref -- the terminal munger that produces the number"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $then eq "HASH" 1 13 14
3779 unless ref $then eq 'HASH';
3780 13 my $name = $then->{munger};
3781 13 ▶ croak "chain munger$where: 'then' has no 'munger' name"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 0 13 13
Condition33%1/3
defined $name and length $name
!ll&&!rl&&r
0013
MC/DC0%0/2
defined $name and length $name
defined $name length $name
Truth table33%1/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
3782 unless defined $name && length $name;
3783 13 return ( $then, $name );
3784 } ## end sub _chain_terminal_spec
3785  
3786 16 ▶sub _build_chain {
Subroutine _build_chain: called CC=2 SCAR=6.9
3787 16 my ( $spec, $where ) = @_;
3788  
3789 16 my $ops = _chain_steps( $spec, $where );
3790 12 my ( $then, $name ) = _chain_terminal_spec( $spec, $where );
3791 11 ▶ my $builder = $BUILDERS{$name}
Branch: 1 branch
BranchTrueFalseTotal
my $builder = $BUILDERS{$name} or croak("chain munger${where}: unknown terminal munger '${name}' (known: " . join(", ", sort(keys %BUILDERS)) . ')') 10 1 11
3792 or croak "chain munger$where: unknown terminal munger '$name' (known: "
3793 . join( ', ', sort keys %BUILDERS ) . ')';
3794 10 my $term = $builder->( $then, "$where (chain terminal)" );
3795  
3796 11 ▶ return sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
3797 11 ▶ my $s = defined $_[0] ? "$_[0]" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] ? : 10 1 11
3798 11 $s = $_->($s) for @$ops;
3799 11 return $term->($s);
3800 9 };
3801 } ## end sub _build_chain
3802  
3803 # Multi-output chain: the same pre-transforms, but the terminal is one of the
3804 # multi-output ('into') mungers. Returns ($list_returning_code, $arity) like
3805 # every multi builder; the arity is the terminal's.
3806 2 ▶sub _build_chain_multi {
Subroutine _build_chain_multi: called CC=2 SCAR=6.9
3807 2 my ( $spec, $where ) = @_;
3808  
3809 2 my $ops = _chain_steps( $spec, $where );
3810 2 my ( $then, $name ) = _chain_terminal_spec( $spec, $where );
3811 2 ▶ my $builder = $MULTI_BUILDERS{$name}
Branch: 1 branch
BranchTrueFalseTotal
my $builder = $MULTI_BUILDERS{$name} or croak("chain munger${where}: terminal munger '${name}' does not support " . q[multiple outputs ('into'); only these do: ] . join(", ", sort(keys %MULTI_BUILDERS))) 1 1 2
3812 or croak "chain munger$where: terminal munger '$name' does not support "
3813 . "multiple outputs ('into'); only these do: "
3814 . join( ', ', sort keys %MULTI_BUILDERS );
3815 1 my ( $term, $arity ) = $builder->( $then, "$where (chain terminal)" );
3816  
3817 1 ▶ my $code = sub {
Subroutine __ANON__: called CC=3 SCAR=11.2
3818 1 ▶ my $s = defined $_[0] ? "$_[0]" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] ? : 1 0 1
3819 1 $s = $_->($s) for @$ops;
3820 1 return $term->($s);
3821 1 };
3822 1 return ( $code, $arity );
3823 } ## end sub _build_chain_multi
3824  
3825 =head2 eps
3826  
3827 { munger => 'eps', prefix => 'http-req:', from => 'src_ip' }
3828 { munger => 'eps', prefix => 'dns-nxd:', from => 'src_ip',
3829 read => 'rate', mark => 0 }
3830 # multi-output: one daemon round trip fills several columns
3831 { munger => 'eps', prefix => 'http-req:', from => 'src_ip',
3832 parts => [ 'rate', 'count' ], into => [ 'req_rate', 'req_count' ] }
3833  
3834 Per-entity sliding-window event rates via the C<iqbi-damiq> daemon shipped with
3835 L<Algorithm::EventsPerSecond> (see
3836 L<Algorithm::EventsPerSecond::Sukkal>). The input value becomes a meter B<key>
3837 (after C<prefix> is prepended); by default the munger B<marks> one event against
3838 that key and returns the key's current events-per-second, using the daemon's
3839 C<MARKRATE> command -- mark and query in a single command with a single reply.
3840 This is the munger behind rate columns like a per-source request rate: every
3841 event marks its source's meter and stores the rate the meter now reads.
3842  
3843 Unlike every other munger this one consults external state -- but the state
3844 lives in the daemon, not here, so the munger itself remains a stateless client
3845 and rows stay reproducible I<given> the daemon. Because the daemon is shared,
3846 multiple writer processes marking the same keys see one B<global> rate, which an
3847 in-process meter could never give.
3848  
3849 Spec keys:
3850  
3851 =over 4
3852  
3853 =item * C<socket> - unix socket path of the daemon. Defaults to
3854 C<$Algorithm::ToNumberMunger::EPS_SOCKET>
3855 (C</var/run/iqbi-damiq.sock>).
3856  
3857 =item * C<prefix> - string prepended to the input to form the key, namespacing
3858 this column's meters (two columns keyed on the same field need different
3859 prefixes or they share meters). No whitespace/control characters. Default C<''>.
3860  
3861 =item * C<mark> - whether to mark the key (default C<1>). Marking rides
3862 C<MARKRATE>: with C<< read => 'rate' >> that one command is the whole exchange;
3863 with C<count>/C<total> the read is pipelined after it (the C<MARKRATE> rate
3864 reply is discarded), so a marking failure still comes back as an ordinary
3865 first reply. With C<< mark => 0 >> the munger only reads, for columns whose
3866 marking is done elsewhere -- e.g. an NXDOMAIN rate is I<marked> by the pipeline
3867 only on NXDOMAIN responses but I<read> on every row.
3868  
3869 =item * C<read> - what to read: C<rate> (events/sec over the daemon's window,
3870 default), C<count> (events inside the window), or C<total> (lifetime).
3871  
3872 =item * C<parts> + C<into> - multi-output form (see L</compile>): read several
3873 of C<rate>/C<count>/C<total> for the one key in a single round trip, filling one
3874 column each. When marking, the C<MARKRATE> reply itself serves the first C<rate>
3875 part, so C<< parts => ['rate', 'count'] >> costs exactly two commands.
3876  
3877 =item * C<on_error> - C<'die'> (default) croaks the write when the daemon is
3878 unreachable or replies C<ERR>; a number is returned instead as a quiet fallback.
3879 Note C<0> is indistinguishable from a genuinely idle key, so quiet fallback
3880 biases the column -- loud is the default on purpose.
3881  
3882 =item * C<timeout> - per-operation socket timeout in seconds (default 5,
3883 best-effort via C<SO_RCVTIMEO>/C<SO_SNDTIMEO>), so a wedged daemon cannot hang a
3884 writer forever.
3885  
3886 =back
3887  
3888 Semantics worth knowing: a marked read B<includes the event just marked>; keys
3889 have whitespace/control bytes replaced with C<_> to satisfy the daemon's key
3890 rules; connections are made lazily on first use and kept open (reconnecting
3891 transparently after a fork or an error), so compiling a plan -- including the
3892 eager validation in C<write_info> -- needs no running daemon. Each eps column
3893 costs one unix-socket round trip per row; the multi-output form exists so
3894 rate+count of the same key costs one round trip, not two.
3895  
3896 =cut
3897  
3898 # Default socket path of the iqbi-damiq daemon.
3899 6 our $EPS_SOCKET = '/var/run/iqbi-damiq.sock';
3900  
3901 # Persistent daemon connections, keyed by socket path, shared by every eps
3902 # munger in the process. Entries record the pid that opened them so a forked
3903 # writer transparently reopens instead of sharing a socket with its parent.
3904 # Connections are made lazily on first use -- never at munger build time, so a
3905 # plan can compile (eager validation) with no daemon running.
3906 6 my %EPS_CONN;
3907  
3908 0 ▶sub _eps_conn {
Subroutine _eps_conn: not called CC=4 SCAR=30.0
3909 0 my ( $path, $timeout ) = @_;
3910 0 my $c = $EPS_CONN{$path};
3911 0 ▶ return $c->{fh} if $c && $c->{pid} == $$;
Branch: 1 branch
BranchTrueFalseTotal
if $c and $c->{"pid"} == $$ 0 0 0
Condition0%0/3
$c and $c->{"pid"} == $$
!ll&&!rl&&r
000
MC/DC0%0/2
$c and $c->{"pid"} == $$
$c $c->{"pid"} == $$
Truth table0%0/3
A and B
A= $cB= $c->{"pid"} == $$
ABresult
0X0
100
111
3912  
3913 0 require Socket;
3914 0 require IO::Socket::UNIX;
3915 0 ▶ my $fh = IO::Socket::UNIX->new(
Branch: 1 branch
BranchTrueFalseTotal
my $fh = "IO::Socket::UNIX"->new("Type", Socket::SOCK_STREAM(), "Peer", $path) or die "cannot connect to iqbi-damiq at ${path}: $!\n" 0 0 0
3916 Type => Socket::SOCK_STREAM(),
3917 Peer => $path,
3918 ) or die "cannot connect to iqbi-damiq at $path: $!\n";
3919  
3920 # Best-effort read/write timeouts so a wedged daemon cannot hang a writer.
3921 0 eval {
3922 0 my $tv = pack( 'l!l!', $timeout, 0 );
3923 0 setsockopt( $fh, Socket::SOL_SOCKET(), Socket::SO_RCVTIMEO(), $tv );
3924 0 setsockopt( $fh, Socket::SOL_SOCKET(), Socket::SO_SNDTIMEO(), $tv );
3925 };
3926  
3927 0 $EPS_CONN{$path} = { fh => $fh, pid => $$ };
3928 0 return $fh;
3929 } ## end sub _eps_conn
3930  
3931 # One pipelined transaction: send $cmd (possibly several lines) and read
3932 # $nreplies "OK n" lines, one per command sent. The munger only ever sends
3933 # commands that reply exactly once -- MARKRATE (which marks AND returns the
3934 # rate in one go), RATE, COUNT, TOTAL; never a bare MARK, whose reply-only-on-
3935 # error behavior would let a failure desynchronize the reply stream. Dies on
3936 # ERR, EOF, or timeout; the caller still drops the cached connection on error
3937 # as belt and braces.
3938 0 ▶sub _eps_txn {
Subroutine _eps_txn: not called CC=5 SCAR=34.0
3939 0 my ( $path, $timeout, $cmd, $nreplies ) = @_;
3940 0 my $fh = _eps_conn( $path, $timeout );
3941 0 ▶ print {$fh} $cmd or die "write to iqbi-damiq failed: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
print {$fh;} $cmd or die "write to iqbi-damiq failed: $!\n" 0 0 0
3942 0 my @out;
3943 0 for ( 1 .. $nreplies ) {
3944 0 my $reply = <$fh>;
3945 0 ▶ die "iqbi-damiq closed the connection (or timed out)\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $reply 0 0 0
3946 unless defined $reply;
3947 0 ▶ $reply =~ /\AOK (\S+)/
Branch: 1 branch
BranchTrueFalseTotal
$reply =~ /\AOK (\S+)/ or die "iqbi-damiq replied: $reply" 0 0 0
3948 or die "iqbi-damiq replied: $reply";
3949 0 push @out, $1 + 0;
3950 }
3951 0 return @out;
3952 } ## end sub _eps_txn
3953  
3954 # Validate the spec keys shared by the scalar and multi-output eps builders.
3955 0 ▶sub _eps_spec {
Subroutine _eps_spec: not called CC=13 SCAR=52.0
3956 0 my ( $spec, $where ) = @_;
3957  
3958 0 ▶ my $socket = defined $spec->{socket} ? $spec->{socket} : $EPS_SOCKET;
Branch: 1 branch
BranchTrueFalseTotal
defined $spec->{'socket'} ? : 0 0 0
3959 0 ▶ croak "eps munger$where: 'socket' must be a non-empty path"
Branch: 1 branch
BranchTrueFalseTotal
unless length $socket 0 0 0
3960 unless length $socket;
3961  
3962 0 ▶ my $prefix = defined $spec->{prefix} ? $spec->{prefix} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $spec->{'prefix'} ? : 0 0 0
3963 0 ▶ croak "eps munger$where: 'prefix' may not contain whitespace or control " . 'characters'
Branch: 1 branch
BranchTrueFalseTotal
if $prefix =~ /[\s[:cntrl:]]/ 0 0 0
3964 if $prefix =~ /[\s[:cntrl:]]/;
3965  
3966 0 ▶ my $mark = exists $spec->{mark} ? ( $spec->{mark} ? 1 : 0 ) : 1;
Branch: 2 branches
BranchTrueFalseTotal
exists $spec->{'mark'} ? : 0 0 0
$spec->{'mark'} ? : 0 0 0
3967  
3968 0 ▶ my $timeout = defined $spec->{timeout} ? $spec->{timeout} : 5;
Branch: 1 branch
BranchTrueFalseTotal
defined $spec->{'timeout'} ? : 0 0 0
3969 0 ▶ croak "eps munger$where: 'timeout' must be a positive number"
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($timeout) and $timeout > 0 0 0 0
Condition0%0/3
&looks_like_number($timeout) and $timeout > 0
!ll&&!rl&&r
000
MC/DC0%0/2
&looks_like_number($timeout) and $timeout > 0
&looks_like_number($timeout) $timeout > 0
Truth table0%0/3
A and B
A= &looks_like_number($timeout)B= $timeout > 0
ABresult
0X0
100
111
3970 unless looks_like_number($timeout) && $timeout > 0;
3971  
3972 0 ▶ my $on_error = defined $spec->{on_error} ? $spec->{on_error} : 'die';
Branch: 1 branch
BranchTrueFalseTotal
defined $spec->{'on_error'} ? : 0 0 0
3973 0 ▶ croak "eps munger$where: 'on_error' must be 'die' or a number"
Branch: 1 branch
BranchTrueFalseTotal
unless $on_error eq "die" or &looks_like_number($on_error) 0 0 0
Condition0%0/3
$on_error eq "die" or &looks_like_number($on_error)
l!l&&r!l&&!r
000
MC/DC0%0/2
$on_error eq "die" or &looks_like_number($on_error)
$on_error eq "die" &looks_like_number($on_error)
Truth table0%0/3
A or B
A= $on_error eq "die"B= &looks_like_number($on_error)
ABresult
1X1
011
000
3974 unless $on_error eq 'die' || looks_like_number($on_error);
3975  
3976 0 return ( $socket, $prefix, $mark, $timeout, $on_error );
3977 } ## end sub _eps_spec
3978  
3979 6 my %EPS_READ = map { $_ => 1 } qw(rate count total);
3980  
3981 0 ▶sub _build_eps {
Subroutine _build_eps: not called CC=6 SCAR=37.4
3982 0 my ( $spec, $where ) = @_;
3983  
3984 croak "eps munger$where: 'parts' is for the multi-output form (needs " . "'into'); use 'read' for a single column"
3985 0 ▶ if defined $spec->{parts};
Branch: 1 branch
BranchTrueFalseTotal
if defined $spec->{"parts"} 0 0 0
3986  
3987 0 my ( $socket, $prefix, $mark, $timeout, $on_error ) = _eps_spec( $spec, $where );
3988  
3989 0 ▶ my $read = defined $spec->{read} ? $spec->{read} : 'rate';
Branch: 1 branch
BranchTrueFalseTotal
defined $spec->{'read'} ? : 0 0 0
3990 croak "eps munger$where: unknown read '$read' (known: " . join( ', ', sort keys %EPS_READ ) . ')'
3991 0 ▶ unless $EPS_READ{$read};
Branch: 1 branch
BranchTrueFalseTotal
unless $EPS_READ{$read} 0 0 0
3992  
3993 # Command plan, fixed at build time. The common case -- mark and read the
3994 # rate -- is the daemon's single MARKRATE command. mark+count/total rides
3995 # MARKRATE too (its rate reply is discarded) so marking failures come back
3996 # as an ordinary first reply instead of a bare MARK's error-only surprise.
3997 my @cmds
3998 0 ▶ = !$mark ? ( uc $read )
Branch: 2 branches
BranchTrueFalseTotal
!$mark ? : 0 0 0
$read eq 'rate' ? : 0 0 0
3999 : $read eq 'rate' ? ('MARKRATE')
4000 : ( 'MARKRATE', uc $read );
4001  
4002 0 ▶ return sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
4003 0 my ($v) = @_;
4004 0 ▶ my $key = $prefix . ( defined $v ? "$v" : '' );
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 0 0 0
4005 0 $key =~ s/[\s[:cntrl:]]/_/g;
4006 0 my @replies = eval {
4007 0 ▶ die "empty key\n" unless length $key;
Branch: 1 branch
BranchTrueFalseTotal
unless length $key 0 0 0
4008 0 _eps_txn( $socket, $timeout, join( '', map { "$_ $key\n" } @cmds ), scalar @cmds );
4009 };
4010 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
4011 0 my $err = $@;
4012 0 delete $EPS_CONN{$socket}; # reconnect fresh next call
4013 0 ▶ croak "eps munger$where: $err" if $on_error eq 'die';
Branch: 1 branch
BranchTrueFalseTotal
if $on_error eq "die" 0 0 0
4014 0 return $on_error + 0;
4015 }
4016 0 return $replies[-1]; # the requested read is always the last reply
4017 0 }; ## end sub
4018 } ## end sub _build_eps
4019  
4020 # Multi-output eps: one key, several reads (rate/count/total), one round trip.
4021 # Returns ($list_returning_code, $arity) for compile()'s 'into' check.
4022 0 ▶sub _build_eps_multi {
Subroutine _build_eps_multi: not called CC=12 SCAR=50.5
4023 0 my ( $spec, $where ) = @_;
4024  
4025 0 my $parts = $spec->{parts};
4026 0 ▶ croak "eps munger$where: 'parts' must be a non-empty arrayref"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $parts eq "ARRAY" and @$parts 0 0 0
Condition0%0/3
ref $parts eq "ARRAY" and @$parts
!ll&&!rl&&r
000
MC/DC0%0/2
ref $parts eq "ARRAY" and @$parts
ref $parts eq "ARRAY" @$parts
Truth table0%0/3
A and B
A= ref $parts eq "ARRAY"B= @$parts
ABresult
0X0
100
111
4027 unless ref $parts eq 'ARRAY' && @$parts;
4028 0 for my $p (@$parts) {
4029 croak "eps munger$where: unknown part '"
4030 . ( defined $p ? $p : 'undef' )
4031 . "' (known: "
4032 . join( ', ', sort keys %EPS_READ ) . ')'
4033 0 ▶ unless defined $p && $EPS_READ{$p};
Branch: 2 branches
BranchTrueFalseTotal
unless defined $p and $EPS_READ{$p} 0 0 0
defined $p ? : 0 0 0
Condition0%0/3
defined $p and $EPS_READ{$p}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $p and $EPS_READ{$p}
defined $p $EPS_READ{$p}
Truth table0%0/3
A and B
A= defined $pB= $EPS_READ{$p}
ABresult
0X0
100
111
4034 }
4035  
4036 0 my ( $socket, $prefix, $mark, $timeout, $on_error ) = _eps_spec( $spec, $where );
4037  
4038 # Command plan, fixed at build time. When marking, the mark is a MARKRATE
4039 # whose own reply serves the first 'rate' part for free; the remaining
4040 # parts become one read command each. @take maps each part to the reply
4041 # index that answers it, so the output stays in 'parts' order.
4042 0 my ( @cmds, @take );
4043 0 my $rate_served = 0;
4044 0 ▶ push @cmds, 'MARKRATE' if $mark;
Branch: 1 branch
BranchTrueFalseTotal
if $mark 0 0 0
4045 0 for my $i ( 0 .. $#$parts ) {
4046 0 ▶ if ( $mark && !$rate_served && $parts->[$i] eq 'rate' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mark and not $rate_served and $parts->[$i] eq "rate") 0 0 0
Condition0%0/6
$mark and not $rate_served and $parts->[$i] eq "rate"
!ll&&!rl&&r
000
$mark and not $rate_served
!ll&&!rl&&r
000
MC/DC0%0/3
$mark and not $rate_served and $parts->[$i] eq "rate"
$mark not $rate_served $parts->[$i] eq "rate"
Truth table0%0/4
A and not(B) and C
A= $markB= not $rate_servedC= $parts->[$i] eq "rate"
ABCresult
0XX0
10X0
1100
1111
4047 0 $take[$i] = 0; # MARKRATE's reply is the rate
4048 0 $rate_served = 1;
4049 0 next;
4050 }
4051 0 push @cmds, uc $parts->[$i];
4052 0 $take[$i] = $#cmds;
4053 }
4054 0 my $n = @$parts;
4055 0 my $nreplies = @cmds;
4056  
4057 0 ▶ my $code = sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
4058 0 my ($v) = @_;
4059 0 ▶ my $key = $prefix . ( defined $v ? "$v" : '' );
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 0 0 0
4060 0 $key =~ s/[\s[:cntrl:]]/_/g;
4061 0 my @replies = eval {
4062 0 ▶ die "empty key\n" unless length $key;
Branch: 1 branch
BranchTrueFalseTotal
unless length $key 0 0 0
4063 0 _eps_txn( $socket, $timeout, join( '', map { "$_ $key\n" } @cmds ), $nreplies );
4064 };
4065 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
4066 0 my $err = $@;
4067 0 delete $EPS_CONN{$socket};
4068 0 ▶ croak "eps munger$where: $err" if $on_error eq 'die';
Branch: 1 branch
BranchTrueFalseTotal
if $on_error eq "die" 0 0 0
4069 0 return ( $on_error + 0 ) x $n;
4070 }
4071 0 return @replies[@take];
4072 0 }; ## end $code = sub
4073 0 return ( $code, $n );
4074 } ## end sub _build_eps_multi
4075  
4076 # A compiled munging plan for one set, produced by Mungers->compile. It turns an
4077 # input record into a fully-numeric row in tags order; the Writer then only has
4078 # to validate and append. Kept in its own package so the assembly logic is
4079 # testable without a Writer or the filesystem.
4080 package Algorithm::ToNumberMunger::Plan;
4081  
4082 6 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4083 6 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4084 6 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
4085  
4086 0 ▶sub tags { return $_[0]->{tags} }
Subroutine tags: not called CC=1 SCAR=6.9
4087  
4088 # Assemble a row from a name-keyed record. Scalar/raw columns read their own tag
4089 # (or the munger's 'from'); expanding mungers read one source and fill several
4090 # columns; combining mungers read several sources and fill one. This is the only
4091 # form that supports expanders and combiners.
4092 19 ▶sub apply_named {
Subroutine apply_named: called CC=12 SCAR=25.0
4093 19 my ( $self, $hash ) = @_;
4094 19 ▶ croak 'apply_named requires a hashref' unless ref $hash eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $hash eq "HASH" 0 19 19
4095  
4096 19 my @row;
4097 19 for my $s ( @{ $self->{scalar} } ) {
4098 croak "missing value for '$s->{from}'"
4099 12 ▶ unless exists $hash->{ $s->{from} };
Branch: 1 branch
BranchTrueFalseTotal
unless exists $$hash{$s->{"from"}} 1 11 12
4100 11 my $v = $hash->{ $s->{from} };
4101 11 ▶ $row[ $self->{pos}{ $s->{tag} } ] = $s->{code} ? $s->{code}->($v) : $v;
Branch: 1 branch
BranchTrueFalseTotal
$s->{'code'} ? : 5 6 11
4102 }
4103  
4104 18 for my $e ( @{ $self->{expand} } ) {
4105 croak "missing value for '$e->{from}'"
4106 8 ▶ unless exists $hash->{ $e->{from} };
Branch: 1 branch
BranchTrueFalseTotal
unless exists $$hash{$e->{"from"}} 1 7 8
4107 7 my @vals = $e->{code}->( $hash->{ $e->{from} } );
4108 0 croak "expanding munger for [@{ $e->{into} }] returned "
4109 . scalar(@vals)
4110 . ' value(s), expected '
4111 0 . scalar( @{ $e->{into} } )
4112 7 ▶ unless @vals == @{ $e->{into} };
Branch: 1 branch
BranchTrueFalseTotal
unless @vals == @{$e->{"into"};} 0 7 7
4113 7 for my $i ( 0 .. $#{ $e->{into} } ) {
4114 14 $row[ $self->{pos}{ $e->{into}[$i] } ] = $vals[$i];
4115 }
4116 } ## end for my $e ( @{ $self->{expand} } )
4117  
4118 17 for my $c ( @{ $self->{combine} } ) {
4119 14 my @vals;
4120 14 for my $f ( @{ $c->{from} } ) {
4121 croak "missing value for '$f'"
4122 31 ▶ unless exists $hash->{$f};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $hash->{$f} 1 30 31
4123 30 push @vals, $hash->{$f};
4124 }
4125 13 $row[ $self->{pos}{ $c->{tag} } ] = $c->{code}->(@vals);
4126 }
4127  
4128 15 return \@row;
4129 } ## end sub apply_named
4130  
4131 # Assemble a row from an already-ordered positional row, applying scalar mungers
4132 # in place. Expanding and combining mungers cannot be expressed positionally
4133 # (there is no named source), so a set that has any is a hard error here -- use
4134 # apply_named.
4135 5 ▶sub apply_positional {
Subroutine apply_positional: called CC=7 SCAR=19.5
4136 5 my ( $self, $row ) = @_;
4137 5 ▶ croak 'apply_positional requires an arrayref row' unless ref $row eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "ARRAY" 0 5 5
4138 croak 'positional write is unsupported for a set with expanding mungers; ' . 'use write_named'
4139 5 ▶ if @{ $self->{expand} };
Branch: 1 branch
BranchTrueFalseTotal
if @{$self->{"expand"};} 1 4 5
4140 croak 'positional write is unsupported for a set with multi-input mungers; ' . 'use write_named'
4141 4 ▶ if @{ $self->{combine} };
Branch: 1 branch
BranchTrueFalseTotal
if @{$self->{"combine"};} 1 3 4
4142 1 croak 'row has ' . scalar(@$row) . ' fields but info.json declares ' . scalar( @{ $self->{tags} } )
4143 3 ▶ unless @$row == @{ $self->{tags} };
Branch: 1 branch
BranchTrueFalseTotal
unless @$row == @{$self->{"tags"};} 1 2 3
4144  
4145 2 my @out = @$row;
4146 2 for my $s ( @{ $self->{scalar} } ) {
4147 4 ▶ next unless $s->{code};
Branch: 1 branch
BranchTrueFalseTotal
unless $s->{"code"} 3 1 4
4148 1 my $i = $self->{pos}{ $s->{tag} };
4149 1 $out[$i] = $s->{code}->( $out[$i] );
4150 }
4151 2 return \@out;
4152 } ## end sub apply_positional
4153  
4154 =head1 AUTHOR
4155  
4156 Zane C. Bowers-Hadley, C<< <vvelox at vvelox.net> >>
4157  
4158 =head1 LICENSE AND COPYRIGHT
4159  
4160 This software is Copyright (c) 2026 by Zane C. Bowers-Hadley.
4161  
4162 This is free software, licensed under:
4163  
4164 The GNU Lesser General Public License, Version 2.1, February 1999
4165  
4166 =cut
4167  
4168 6 1; # End of Algorithm::ToNumberMunger
↑ Summary lib/Algorithm/ToNumberMunger.xs »