blib/lib/Algorithm/Classifier/IsolationForest/App/Command/streamc.pm

filter: Statementstmt 91.7% 156 / 170 Branchbran 74.5% 76 / 102 Conditioncond 66.6% 16 / 24 MC/DCmcdc 33.3% 5 / 15 Subroutinesub 89.4% 17 / 19 Podpod 100% 5 / 5 totaltotal 82.0% 275 / 335 CC 62 SCAR 26.0
CC
62
Cov
84%
validate
29.3
_stream
15.6
execute
9.3
CRAP 13.4
« blib/lib/Algorithm/Classifier/IsolationForest/App/Command/set_voting.pm ↑ Summary blib/lib/Algorithm/Classifier/IsolationForest/App/Command/info.pm »
1 package Algorithm::Classifier::IsolationForest::App::Command::streamc;
2  
3 86 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 86 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 86 ▶use Algorithm::Classifier::IsolationForest::App -command;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 86 ▶use File::Slurp qw(write_file);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 86 ▶use File::Spec ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 86 ▶use Scalar::Util qw(looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 86 ▶use IO::Socket::UNIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 86 ▶use IO::Select ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 # JSON::MaybeXS codec and the connected socket, set up in execute.
13 86 my $JSON;
14 my $SOCK;
15 86 my $TIMEOUT;
16 86 my $READ_BUF = '';
17  
18 23 ▶sub opt_spec {
Subroutine opt_spec: called CC=1 SCAR=0.0
Pod documented
19 return (
20 [
21 23 'set=s',
22 'Named streamd instance to talk to; the socket becomes <set>.sock under the run dir, '
23 . 'exactly as streamd resolves it. Must match /\A[A-Za-z0-9+\-@_]+\z/.'
24 ],
25 [
26 'socket=s',
27 'Unix domain socket streamd listens on; default /var/run/iforest_streamd/streamd.sock. With '
28 . '--set this is instead the base run dir (default /var/run/iforest_streamd) holding <set>.sock.',
29 { 'completion' => 'files' }
30 ],
31 [ 'timeout=i', 'Seconds to wait for each reply from the daemon.', { 'default' => 30 } ],
32  
33 # stream mode
34 [
35 'i=s',
36 'Input to stream through the daemon, one row per line; - reads stdin.',
37 { 'completion' => 'files' }
38 ],
39 [ 'o=s', 'Output the results to this file instead of printing.', { 'completion' => 'files' } ],
40 [ 'w', 'If the file specified via -o exists, over write it.' ],
41 [ 'd', 'Include the input data in the output (CSV input only).' ],
42 [
43 'mode=s',
44 "What each row does: 'prequential' (score against the model as it stood, then learn -- the "
45 . "default), 'learn' (learn only, no output), or 'score' (score only, nothing learned).",
46 { 'default' => 'prequential' }
47 ],
48 [
49 'jsonl',
50 'Input lines are JSON rows instead of CSV: an array is positional, an object is a tagged row '
51 . '(full munger plan, raw values may contain anything JSON can). Output is the daemon\'s '
52 . 'reply JSON lines verbatim, one per request (--batch 1 for one per row).'
53 ],
54 [
55 'batch=i',
56 'Rows per request message. Bigger amortises round trips; 1 gives per-row latency for '
57 . 'tail -F style pipelines.',
58 { 'default' => 256 }
59 ],
60  
61 # command mode
62 [ 'ping', 'Check the daemon is alive; exits 0 on pong.' ],
63 [ 'stats', 'Print the daemon stats (seen, window, threshold, connections, set, ...).' ],
64 [ 'save', 'Ask the daemon to save the model now; prints the file name.' ],
65 [ 'relearn-threshold', 'Ask the daemon to relearn the contamination decision threshold.' ],
66 [ 'json', 'Command mode: print the raw JSON reply instead of the text rendering.' ],
67 );
68 } ## end sub opt_spec
69  
70 0 ▶sub abstract { 'Client for iforest streamd: stream rows through it or send it commands' }
Subroutine abstract: not called CC=1 SCAR=6.9
Pod documented
71  
72 0 ▶sub description {
Subroutine description: not called CC=1 SCAR=6.9
Pod documented
73 0 'Talks to a running `iforest streamd` daemon over its Unix socket,
74 speaking the same one-JSON-document-per-line protocol.
75  
76 Stream mode (-i) feeds rows through the daemon and prints one result
77 per row, in order. Input is CSV by default (positional rows, matching
78 `iforest stream`; fields are sent as numbers when they look like
79 numbers and as raw strings otherwise, so munged columns pass through
80 untouched) and the output is `$score,$label` lines, with -d prepending
81 the input columns. With --jsonl each input line is instead a JSON row
82 -- an array for positional data, an object for a tagged row through
83 the full munger plan -- and the output is the daemon\'s reply JSON
84 lines verbatim. Rows are sent in --batch sized messages, lockstep;
85 each request is tagged with its starting input line number, so a bad
86 row dies naming the input line (rows earlier in that message were
87 already applied by the daemon -- prequential learning is not
88 transactional). All row validation is the daemon\'s: only it knows
89 whether the model munges.
90  
91 Command mode sends exactly one of --ping, --stats, --save, or
92 --relearn-threshold and renders the reply as text (--json for the raw
93 reply). The exit code is 0 on ok and non-zero on error, connect
94 failure, or timeout, so `iforest streamc --set web --ping` works
95 directly in health checks.
96  
97 --set/--socket resolve the socket path exactly as streamd does, so the
98 same flags reach the same daemon.
99 ';
100 } ## end sub description
101  
102 23 ▶sub validate {
Subroutine validate: called CC=20 SCAR=33.8
Pod documented
103 23 my ( $self, $opt, $args ) = @_;
104  
105 23 ▶ if ( defined( $opt->{'set'} ) && $opt->{'set'} !~ /\A[A-Za-z0-9+\-@_]+\z/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"set"} and not $opt->{"set"} =~ /\A[A-Za-z0-9+\-@_]+\z/) 1 22 23
Condition100%3/3
defined $opt->{"set"} and not $opt->{"set"} =~ /\A[A-Za-z0-9+\-@_]+\z/
!ll&&!rl&&r
1211
MC/DC100%2/2
defined $opt->{"set"} and not $opt->{"set"} =~ /\A[A-Za-z0-9+\-@_]+\z/
defined $opt->{"set"} not $opt->{"set"} =~ /\A[A-Za-z0-9+\-@_]+\z/
Truth table100%3/3
A and not(B)
A= defined $opt->{"set"}B= not $opt->{"set"} =~ /\A[A-Za-z0-9+\-@_]+\z/
ABresult
0X0
100
111
106 $self->usage_error( '--set, "'
107 1 . $opt->{'set'}
108 . '", must match /\A[A-Za-z0-9+\-@_]+\z/ (letters, digits, and + - @ _ only)' );
109 }
110  
111 22 my @cmds = grep { $opt->{$_} } qw(ping stats save relearn_threshold);
112 22 ▶ if ( defined( $opt->{'i'} ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $opt->{'i'}) { } 10 12 22
elsif (scalar @cmds != 1) { } 2 10 12
113 10 ▶ if ( scalar @cmds ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @cmds) 0 10 10
114 0 $self->usage_error('-i may not be combined with --ping/--stats/--save/--relearn-threshold');
115 }
116 } elsif ( scalar @cmds != 1 ) {
117 2 $self->usage_error(
118 'need either -i (stream mode) or exactly one of --ping, --stats, --save, --relearn-threshold');
119 }
120  
121 20 ▶ if ( defined( $opt->{'i'} ) && $opt->{'i'} ne '-' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"i"} and $opt->{"i"} ne "-") 10 10 20
Condition66%2/3
defined $opt->{"i"} and $opt->{"i"} ne "-"
!ll&&!rl&&r
10010
MC/DC50%1/2
defined $opt->{"i"} and $opt->{"i"} ne "-"
defined $opt->{"i"} $opt->{"i"} ne "-"
Truth table66%2/3
A and B
A= defined $opt->{"i"}B= $opt->{"i"} ne "-"
ABresult
0X0
100
111
122 10 ▶ if ( !-f $opt->{'i'} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not -f $opt->{'i'}) { } 0 10 10
elsif (not -r $opt->{'i'}) { } 0 10 10
123 0 $self->usage_error( '-i, "' . $opt->{'i'} . '", is not a file or does not exist' );
124 } elsif ( !-r $opt->{'i'} ) {
125 0 $self->usage_error( '-i, "' . $opt->{'i'} . '", is not readable' );
126 }
127 }
128  
129 20 ▶ if ( defined( $opt->{'o'} ) && !$opt->{'w'} && -e $opt->{'o'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"o"} and not $opt->{"w"} and -e $opt->{"o"}) 0 20 20
Condition66%4/6
defined $opt->{"o"} and not $opt->{"w"} and -e $opt->{"o"}
!ll&&!rl&&r
1910
defined $opt->{"o"} and not $opt->{"w"}
!ll&&!rl&&r
1901
MC/DC0%0/3
defined $opt->{"o"} and not $opt->{"w"} and -e $opt->{"o"}
defined $opt->{"o"} not $opt->{"w"} -e $opt->{"o"}
Truth table50%2/4
A and not(B) and C
A= defined $opt->{"o"}B= not $opt->{"w"}C= -e $opt->{"o"}
ABCresult
0XX0
10X0
1100
1111
130 0 $self->usage_error( '-o, "' . $opt->{'o'} . '", already exists and -w is not specified' );
131 }
132  
133 20 ▶ if ( $opt->{'mode'} !~ /\A(?:prequential|learn|score)\z/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opt->{"mode"} =~ /\A(?:prequential|learn|score)\z/) 0 20 20
134 0 $self->usage_error( '--mode, "' . $opt->{'mode'} . '", must be prequential, learn, or score' );
135 }
136  
137 20 ▶ if ( $opt->{'d'} && $opt->{'jsonl'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{"d"} and $opt->{"jsonl"}) 1 19 20
Condition100%3/3
$opt->{"d"} and $opt->{"jsonl"}
!ll&&!rl&&r
1811
MC/DC100%2/2
$opt->{"d"} and $opt->{"jsonl"}
$opt->{"d"} $opt->{"jsonl"}
Truth table100%3/3
A and B
A= $opt->{"d"}B= $opt->{"jsonl"}
ABresult
0X0
100
111
138 1 $self->usage_error('-d only applies to CSV input; --jsonl replies are already self-describing');
139 }
140  
141 19 ▶ if ( $opt->{'json'} && defined( $opt->{'i'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{"json"} and defined $opt->{"i"}) 0 19 19
Condition66%2/3
$opt->{"json"} and defined $opt->{"i"}
!ll&&!rl&&r
1810
MC/DC0%0/2
$opt->{"json"} and defined $opt->{"i"}
$opt->{"json"} defined $opt->{"i"}
Truth table66%2/3
A and B
A= $opt->{"json"}B= defined $opt->{"i"}
ABresult
0X0
100
111
142 0 $self->usage_error('--json only applies to command mode');
143 }
144  
145 19 ▶ if ( $opt->{'batch'} < 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{"batch"} < 1) 0 19 19
146 0 $self->usage_error( '--batch, "' . $opt->{'batch'} . '", must be >= 1' );
147 }
148  
149 19 ▶ if ( $opt->{'timeout'} < 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{"timeout"} < 1) 0 19 19
150 0 $self->usage_error( '--timeout, "' . $opt->{'timeout'} . '", must be >= 1' );
151 }
152  
153 19 return 1;
154 } ## end sub validate
155  
156 19 ▶sub execute {
Subroutine execute: called CC=9 SCAR=22.3
Pod documented
157 19 my ( $self, $opt, $args ) = @_;
158  
159 # Lazily required for the same reason streamd does it: App::Cmd loads
160 # every command module up front, and the rest of the CLI should work
161 # on a box without JSON::MaybeXS.
162 19 ▶ eval { require JSON::MaybeXS; 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require JSON::MaybeXS; 1 } } or die 'iforest streamc requires JSON::MaybeXS for its wire protocol; install it: ' . $@ 19 0 19
163 or die( 'iforest streamc requires JSON::MaybeXS for its wire protocol; install it: ' . $@ );
164 19 $JSON = JSON::MaybeXS->new( utf8 => 1, canonical => 1 );
165 19 $TIMEOUT = $opt->{'timeout'};
166  
167 # Resolve the socket exactly as streamd does (keep in sync with it):
168 # without a set the flag is the socket file; with one it is the base
169 # run dir holding <set>.sock.
170 19 my $socket;
171 19 ▶ if ( defined $opt->{'set'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{'set'}) { } 18 1 19
172 18 ▶ my $run = defined $opt->{'socket'} ? $opt->{'socket'} : '/var/run/iforest_streamd';
Branch: 1 branch
BranchTrueFalseTotal
defined $opt->{'socket'} ? : 18 0 18
173 18 $socket = File::Spec->catfile( $run, $opt->{'set'} . '.sock' );
174 } else {
175 1 ▶ $socket = defined $opt->{'socket'} ? $opt->{'socket'} : '/var/run/iforest_streamd/streamd.sock';
Branch: 1 branch
BranchTrueFalseTotal
defined $opt->{'socket'} ? : 1 0 1
176 }
177 19 ▶ die( '--socket, "'
Branch: 1 branch
BranchTrueFalseTotal
if length $socket > 100 0 19 19
178 . $socket
179 . '", is '
180 . length($socket)
181 . ' bytes; Unix socket paths are limited to ~104 bytes -- use a shorter path'
182 . "\n" )
183 if length($socket) > 100;
184  
185 $SOCK = IO::Socket::UNIX->new( Peer => $socket )
186 or die( 'failed to connect to "'
187 . $socket . '": '
188 . $!
189 . ' -- is streamd running'
190 19 ▶ . ( defined $opt->{'set'} ? ' with --set ' . $opt->{'set'} : '' ) . '?'
Branch: 2 branches
BranchTrueFalseTotal
$SOCK = "IO::Socket::UNIX"->new("Peer", $socket) or die 'failed to connect to "' . $socket . '": ' . $! . ' -- is streamd running' . (defined $opt->{"set"} ? ' with --set ' . $opt->{"set"} : "") . '?' . "\n" 18 1 19
defined $opt->{'set'} ? : 0 1 1
191 . "\n" );
192 18 $SOCK->autoflush(1);
193  
194 # A daemon dropping us mid-write should surface as the read-side
195 # "no reply" error, not a silent SIGPIPE death.
196 18 local $SIG{PIPE} = 'IGNORE';
197  
198 18 ▶ return _command( $self, $opt ) if !defined $opt->{'i'};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $opt->{"i"} 9 9 18
199 9 return _stream( $self, $opt );
200 } ## end sub execute
201  
202 #-------------------------------------------------------------------------------
203 # wire helpers
204 #-------------------------------------------------------------------------------
205  
206 # Send one request and wait for its reply. The protocol is strictly one
207 # reply per request on a single connection, so this can block on the
208 # answer instead of correlating tags.
209 #
210 # Args:
211 # $msg :: the request as a hashref, ready to encode -- a row/rows
212 # message or a cmd message.
213 #
214 # Returns: the hashref _read_reply returns, holding the raw reply line and
215 # its decoded form. Dies when the daemon says nothing within --timeout
216 # seconds or closes the connection first.
217 #
218 # Example:
219 # my $got = _request( { cmd => 'stats' } );
220 # $got->{reply}{ok}{seen};
221 20 ▶sub _request {
Subroutine _request: called CC=2 SCAR=7.0
222 20 my ($msg) = @_;
223 20 print {$SOCK} $JSON->encode($msg) . "\n";
224 20 my $reply = _read_reply();
225 20 ▶ die( 'no reply from the daemon within ' . $TIMEOUT . 's (or it closed the connection)' . "\n" )
Branch: 1 branch
BranchTrueFalseTotal
unless defined $reply 0 20 20
226 unless defined $reply;
227 20 return $reply;
228 }
229  
230 # Read one newline-terminated reply, waiting no longer than --timeout in
231 # total. Whatever arrives past the newline stays in the module's read
232 # buffer for the next call, so a reply split across reads -- or two
233 # arriving in one -- both work.
234 #
235 # Args: none. Reads the module's $SOCK, $READ_BUF and $TIMEOUT.
236 #
237 # Returns: a hashref of raw (the reply line as it came, for --json
238 # passthrough) and reply (the decoded hashref), or undef when the deadline
239 # passes or the daemon closes the connection. Dies when a line arrives
240 # but does not parse as JSON.
241 #
242 # Example:
243 # my $got = _read_reply();
244 # print $got->{raw} . "\n" if $opt->{'json'};
245 20 ▶sub _read_reply {
Subroutine _read_reply: called CC=6 SCAR=18.4
246 20 my $deadline = time + $TIMEOUT;
247 20 my $sel = IO::Select->new($SOCK);
248 20 ▶ while ( $READ_BUF !~ /\n/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($READ_BUF =~ /\n/) 20 20 40
249 20 my $left = $deadline - time;
250 20 ▶ return undef if $left <= 0 || !$sel->can_read($left);
Branch: 1 branch
BranchTrueFalseTotal
if $left <= 0 or not $sel->can_read($left) 0 20 20
Condition33%1/3
$left <= 0 or not $sel->can_read($left)
l!l&&r!l&&!r
0020
MC/DC0%0/2
$left <= 0 or not $sel->can_read($left)
$left <= 0 not $sel->can_read($left)
Truth table33%1/3
A or not(B)
A= $left <= 0B= not $sel->can_read($left)
ABresult
1X1
011
000
251 20 my $got = sysread( $SOCK, my $chunk, 65536 );
252 20 ▶ return undef unless $got;
Branch: 1 branch
BranchTrueFalseTotal
unless $got 0 20 20
253 20 $READ_BUF .= $chunk;
254 }
255 20 $READ_BUF =~ s/\A([^\n]*)\n//;
256 20 my $line = $1;
257 20 my $reply = eval { $JSON->decode($line) };
258 20 ▶ die( 'daemon sent an unparseable reply: ' . $@ ) if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 20 20
259 20 return { raw => $line, reply => $reply };
260 } ## end sub _read_reply
261  
262 #-------------------------------------------------------------------------------
263 # command mode
264 #-------------------------------------------------------------------------------
265  
266 # The one-shot control path: send the single command the user asked for,
267 # print its answer, and exit. execute dispatches here instead of _stream
268 # when any of --ping/--stats/--save/--relearn-threshold is present.
269 #
270 # Args:
271 # $opt :: the parsed command options hashref. Exactly one of ping,
272 # stats, save or relearn_threshold is set; validate has already
273 # enforced that.
274 #
275 # Returns: 1. Prints the raw reply line under --json, a two-column table
276 # for a hash answer, and the bare value otherwise. Dies naming the
277 # daemon's message when it replies with an error, which is what gives
278 # --ping its usable exit code.
279 #
280 # Example:
281 # $self->_command($opt);
282 # # seen 48210
283 # # window 2048
284 9 ▶sub _command {
Subroutine _command: called CC=7 SCAR=19.5
285 9 my ( $self, $opt ) = @_;
286  
287 9 my ($which) = grep { $opt->{$_} } qw(ping stats save relearn_threshold);
288 9 ( my $cmd = $which ) =~ tr/_/-/;
289  
290 9 my $got = _request( { cmd => $cmd } );
291 9 my $reply = $got->{reply};
292 9 ▶ die( 'daemon error: ' . $reply->{error} . "\n" ) if defined $reply->{error};
Branch: 1 branch
BranchTrueFalseTotal
if defined $reply->{"error"} 1 8 9
293  
294 8 ▶ if ( $opt->{'json'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{"json"}) 1 7 8
295 1 print $got->{raw} . "\n";
296 1 return 1;
297 }
298  
299 7 my $ok = $reply->{ok};
300 7 ▶ if ( ref $ok eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $ok eq 'HASH') { } 5 2 7
301 5 for my $k ( sort keys %$ok ) {
302 29 ▶ printf " %-20s %s\n", $k, ( defined $ok->{$k} ? $ok->{$k} : '(unset)' );
Branch: 1 branch
BranchTrueFalseTotal
defined $ok->{$k} ? : 28 1 29
303 }
304 } else {
305 2 ▶ print( ( defined $ok ? $ok : 'ok' ) . "\n" );
Branch: 1 branch
BranchTrueFalseTotal
defined $ok ? : 2 0 2
306 }
307 7 return 1;
308 } ## end sub _command
309  
310 #-------------------------------------------------------------------------------
311 # stream mode
312 #-------------------------------------------------------------------------------
313  
314 # The data path: read rows from -i, send them to the daemon in batches of
315 # --batch, and emit what comes back. Errors from either side are reported
316 # against the input line that caused them, which is why the batch's
317 # starting line number travels along as the message tag.
318 #
319 # Input is positional CSV by default -- numeric-looking fields become JSON
320 # numbers, everything else stays a string for the daemon's munger plan --
321 # or one JSON row per line under --jsonl, which is what unlocks tagged
322 # rows and the full munger plan from a shell pipeline.
323 #
324 # Args:
325 # $opt :: the parsed command options hashref. i (a path or '-' for
326 # stdin), mode, batch, jsonl, d, json and o all steer this.
327 #
328 # Returns: 1. Output goes to stdout as it arrives, or accumulates and is
329 # written atomically to -o at the end -- so -o is unsuitable for an
330 # endless stdin. Nothing is printed in learn mode. Dies naming the input
331 # line on a ragged CSV row, an unparseable JSON row, or a daemon error.
332 #
333 # Example:
334 # $self->_stream($opt);
335 # # 0.41,0
336 # # 0.12,0
337 9 ▶sub _stream {
Subroutine _stream: called CC=15 SCAR=27.5
338 9 my ( $self, $opt ) = @_;
339  
340 9 my $in_fh;
341 9 ▶ if ( $opt->{'i'} eq '-' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{'i'} eq '-') { } 0 9 9
342 0 $in_fh = \*STDIN;
343 } else {
344 9 ▶ open( $in_fh, '<', $opt->{'i'} ) or die( 'failed to open -i, "' . $opt->{'i'} . '": ' . $! . "\n" );
Branch: 1 branch
BranchTrueFalseTotal
open $in_fh, "<", $opt->{"i"} or die 'failed to open -i, "' . $opt->{"i"} . '": ' . $! . "\n" 9 0 9
345 }
346  
347 # -o accumulates and writes atomically at the end (matching `iforest
348 # stream`), so it is unsuitable for an endless stdin; without it,
349 # results print as replies arrive.
350 9 my $results = '';
351 27 ▶ my $emit = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
352 27 ▶ if ( defined $opt->{'o'} ) { $results .= $_[0] . "\n" }
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{'o'}) { } 5 22 27
353 22 else { print $_[0] . "\n" }
354 9 };
355  
356 9 my $expected_cols;
357 my @rows; # decoded rows for the pending request
358 9 my @raw; # matching raw input lines, for -d
359 9 my $batch_start = 1; # input line number of $rows[0]
360 9 my $line_int = 0;
361  
362 12 ▶ my $flush = sub {
Subroutine __ANON__: called CC=8 SCAR=20.8
363 12 ▶ return unless @rows;
Branch: 1 branch
BranchTrueFalseTotal
unless @rows 1 11 12
364 11 my $got = _request( { rows => [@rows], mode => $opt->{'mode'}, tag => $batch_start } );
365 11 my $reply = $got->{reply};
366 11 ▶ if ( defined $reply->{error} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $reply->{"error"}) 1 10 11
367 1 my $line = $batch_start;
368 1 my $err = $reply->{error};
369 # Batch errors come back as "row N: ..." with N relative to
370 # the message; map it back to the input line.
371 1 ▶ if ( $err =~ s/\Arow (\d+): // ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err =~ s/\Arow (\d+): //) 1 0 1
372 1 $line = $batch_start + $1;
373 }
374 1 die( 'line ' . $line . ' of input: ' . $err . "\n" );
375 } ## end if ( defined $reply->{error} )
376 10 ▶ if ( $opt->{'mode'} ne 'learn' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{"mode"} ne "learn") 9 1 10
377 9 ▶ if ( $opt->{'jsonl'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{'jsonl'}) { } 2 7 9
378 2 $emit->( $got->{raw} );
379 } else {
380 7 my $pairs = $reply->{scores};
381 7 for my $i ( 0 .. $#$pairs ) {
382 25 ▶ my $prefix = $opt->{'d'} ? $raw[$i] . ',' : '';
Branch: 1 branch
BranchTrueFalseTotal
$opt->{'d'} ? : 5 20 25
383 25 $emit->( $prefix . $pairs->[$i][0] . ',' . $pairs->[$i][1] );
384 }
385 }
386 } ## end if ( $opt->{'mode'} ne 'learn' )
387 10 @rows = ();
388 10 @raw = ();
389 10 $batch_start = $line_int + 1;
390 9 }; ## end $flush = sub
391  
392 9 ▶ while ( my $line = <$in_fh> ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $in_fh)) 92 8 100
393 92 $line_int++;
394 92 chomp $line;
395 92 ▶ if ( $line =~ /^\s*$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^\s*$/) 0 92 92
396 0 $flush->(); # keep line-number accounting exact across blanks
397 0 $batch_start = $line_int + 1;
398 0 next;
399 }
400  
401 92 ▶ if ( $opt->{'jsonl'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{'jsonl'}) { } 4 88 92
402 4 my $row = eval { $JSON->decode($line) };
403 4 ▶ die( 'line ' . $line_int . ' of -i did not parse as JSON: ' . $@ ) if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 4 4
404 4 ▶ die( 'line ' . $line_int . ' of -i must be a JSON array (positional) or object (tagged)' . "\n" )
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "ARRAY" or ref $row eq "HASH" 0 4 4
Condition33%1/3
ref $row eq "ARRAY" or ref $row eq "HASH"
l!l&&r!l&&!r
040
MC/DC0%0/2
ref $row eq "ARRAY" or ref $row eq "HASH"
ref $row eq "ARRAY" ref $row eq "HASH"
Truth table33%1/3
A or B
A= ref $row eq "ARRAY"B= ref $row eq "HASH"
ABresult
1X1
011
000
405 unless ref $row eq 'ARRAY' || ref $row eq 'HASH';
406 4 push @rows, $row;
407 } else {
408 88 my @fields = split( /,/, $line, -1 );
409 88 ▶ if ( !defined $expected_cols ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $expected_cols) { } 7 81 88
elsif (scalar @fields != $expected_cols) { } 1 80 81
410 7 $expected_cols = scalar @fields;
411 7 ▶ die( 'Line ' . $line_int . ' of input has no columns' ) if $expected_cols < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $expected_cols < 1 0 7 7
412 } elsif ( scalar @fields != $expected_cols ) {
413 1 die( 'Line '
414 . $line_int
415 . ' of input has '
416 . scalar(@fields)
417 . ' columns but expected '
418 . $expected_cols );
419 }
420  
421 # Numeric-looking fields travel as JSON numbers, everything
422 # else as strings for the daemon's munger plan to handle; the
423 # daemon owns validation either way.
424 87 ▶ push @rows, [ map { looks_like_number($_) ? 0 + $_ : $_ } @fields ];
Branch: 1 branch
BranchTrueFalseTotal
&looks_like_number($_) ? : 174 0 174
425 87 push @raw, $line;
426 } ## end else [ if ( $opt->{'jsonl'} ) ]
427  
428 91 ▶ $flush->() if scalar @rows >= $opt->{'batch'};
Branch: 1 branch
BranchTrueFalseTotal
if scalar @rows >= $opt->{"batch"} 4 87 91
429 } ## end while ( my $line = <$in_fh> )
430 8 $flush->();
431  
432 7 ▶ if ( defined $opt->{'o'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"o"}) 1 6 7
433 1 write_file( $opt->{'o'}, { 'atomic' => 1 }, $results );
434 }
435 7 return 1;
436 } ## end sub _stream
437  
438 =head1 NAME
439  
440 Algorithm::Classifier::IsolationForest::App::Command::streamc - Client for iforest streamd: stream rows through it or send it commands
441  
442 =head1 DESCRIPTION
443  
444 The client half of C<iforest streamd>, so neither hand-rolled JSON nor a
445 socket tool is needed to talk to a daemon.
446  
447 In stream mode it reads rows from C<-i> and sends them in batches of
448 C<--batch>, printing C<$score,$label> lines as replies arrive. Input is
449 positional CSV by default -- numeric-looking fields travel as JSON
450 numbers, everything else as strings for the daemon's munger plan -- or
451 one JSON row per line under C<--jsonl>, which is what unlocks tagged rows
452 and the full munger plan from a shell pipeline.
453  
454 In command mode -- C<--ping>, C<--stats>, C<--save> or
455 C<--relearn-threshold> -- it sends the one command and prints the answer.
456 C<--ping> is driven by its exit code, so it works as a health check.
457  
458 Errors from either side name the input line that caused them.
459  
460 Run it as C<iforest streamc>; C<iforest help streamc> lists every option.
461  
462 =head1 METHODS
463  
464 L<App::Cmd> calls these while dispatching the subcommand. Nothing else
465 should.
466  
467 =head2 opt_spec
468  
469 Returns this command's option specifications, as the list of arrayrefs
470 L<Getopt::Long::Descriptive> expects.
471  
472 =head2 abstract
473  
474 Returns the one-line summary C<iforest commands> prints beside the
475 command name.
476  
477 =head2 description
478  
479 Returns the long help text C<iforest help streamc> prints under the option
480 list.
481  
482 =head2 validate
483  
484 Checks the parsed options before anything is read or written, so a
485 mistake costs nothing.
486  
487 Checks that C<--set> is a usable instance name, that C<-i> is not
488 combined with a command switch, that C<-i> and C<-o> are usable, that
489 C<--mode> names a valid mode, that C<-d> and C<--json> are only used
490 where they apply, and that C<--batch> and C<--timeout> are positive.
491  
492 Takes the parsed options hashref and the arrayref of remaining
493 arguments. Calls C<usage_error>, which prints the usage and exits, on
494 the first problem it finds, and returns 1 when everything checks out.
495  
496 =head2 execute
497  
498 Connects to the daemon's socket and runs either the command or the
499 stream, depending on which switches were given.
500  
501 Takes the parsed options hashref and the arrayref of remaining
502 arguments, and returns 1.
503  
504 =cut
505  
506 86 return 1;
« blib/lib/Algorithm/Classifier/IsolationForest/App/Command/set_voting.pm ↑ Summary blib/lib/Algorithm/Classifier/IsolationForest/App/Command/info.pm »