blib/lib/CSV/HistoryPlayer.pm

filter: Statementstmt 100% 95 / 95 Branchbran 95.0% 19 / 20 Conditioncond 83.3% 5 / 6 MC/DCmcdc 75.0% 3 / 4 Subroutinesub 100% 17 / 17 Podpod 100% 2 / 2 totaltotal 97.9% 141 / 144 CC 16 SCAR 12.7
CC
16
Cov
98%
_build_files
7.0
__ANON__
6.0
__ANON__
3.0
CRAP 3.6
↑ Summary
1 package CSV::HistoryPlayer;
2  
3 2 ▶use List::MoreUtils qw(uniq);
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use Path::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use Text::CSV;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 2 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 2 our $VERSION = '0.03';
13  
14 =head1 NAME
15  
16 =encoding utf8
17  
18 CSV::HistoryPlayer - Plays scattered CSV files with historic data
19  
20 =head1 STATUS
21  
22 =begin HTML
23  
24 <p>
25 <a href="https://travis-ci.org/binary-com/perl-CSV-HistoryPlayer"><img src="https://travis-ci.org/binary-com/perl-CSV-HistoryPlayer.svg" /></a>
26 </p>
27  
28 =end HTML
29  
30  
31 =head1 SYNOPSYS
32  
33 use CSV::HistoryPlayer;
34  
35 my $player = CSV::HistoryPlayer->(root_dir => 'path/to/directory');
36 while (my $data = $player->poll) {
37 my ($file, $row) = @$data;
38 print "event occured at ", $row->[0], "\n";
39 }
40  
41 =head1 DESCRIPTION
42  
43 Let's assume you have many of CSV-files, each one has some events
44 written in it (in the B<first> column in form of unix timestamp) and
45 filenames also have encoded date of the events within, i.e.
46  
47 ├── income
48 │   ├── 2015-02-10.csv
49 │   └── 2015-02-12.csv
50 └── outcome
51 ├── 2015-02-11.csv
52 └── 2015-02-12.csv
53  
54 Let's assume, that the files have content like:
55  
56 income/2015-02-10.csv: 1455106611, 10, "got pocket money from Mom"
57 income/2015-02-12.csv: 1455301001, 15, "got pocket money from Dad"
58 outcome/2015-02-11.csv: 1455203801, 10, "bought Immortal CD (black metal)"
59 outcome/2015-02-12.csv: 1455307400, 10, "bought Obsidian Gate CD (black metal)"
60  
61 Now, you would to replay all transactions. That's easy
62  
63 use CSV::HistoryPlayer;
64  
65 my $player = CSV::HistoryPlayer->(root_dir => 'path/to/directory');
66 while (my $data = $player->poll) {
67 my ($file, $row) = @$data;
68 my ($when, $how_much, $description) = @$row;
69 my $sign = $file =~ /income/ ? '+' : '-';
70 print $sign, " ", $how_much, '$: ', $description, "\n";
71 }
72  
73 # +10$: got pocket money from Mom
74 # -10$: bought Immortal CD (black metal)
75 # +15$: got pocket money from Dad
76 # -10$: bought Obsidian Gate CD (black metal)
77  
78 I.e. the L<CSV::HistoryPlayer> virtually unites scattered CSV files,
79 and allows to read evens from them in historically correct order.
80  
81  
82 =head1 ATTRIBUTES
83  
84 =over 2
85  
86 =item * C<root_dir>
87  
88 The root directory, where the csv files should be searched from.
89 This attribute is B<mandatory>.
90  
91 =item * C<dir_filter>
92  
93 The closure, which allows to filter out unneeded directories,
94 in the file scan phase to do not include csv-files within
95  
96 my $player = CSV::HistoryPlayer->(
97 ...,
98 # if returns true, than dir will be scanned for csv-files
99 dir_filter => sub { $_[0] =~ /income/ },
100 );
101  
102 By default, all found directories are allowed to be scanned
103 for CSV-files.
104  
105 =item * C<files_mapper>
106  
107 The closure, which allows to do custom sort and filtering of found
108 CSV-files in historical order.
109  
110 By default CSV-files are lexically sorted and not filtered.
111  
112 For example, if there are files C<3-Jan-16.csv>, C<4-Jan-16.csv>,
113 ..., they can be sorted with L<Date::Utility>
114  
115 files_maper => sub {
116 my $orig_files = shift;
117 my @files =
118 map { $_->{file} }
119 sort { $a->{epoch} <=> $b->{epoch} }
120 map {
121 my $date = /(.*\/)(.+)/ ? $2 : die("wrong filename in $_");
122 {
123 file => $_,
124 epoch => Date::Utility->new($date)->epoch,
125 }
126 } @$orig_files;
127 return \@files;
128 }
129  
130  
131 =item * C<files>
132  
133 Returns historically sorted list of found CSV-files; each item in
134 the list is L<Path::Tiny> instance.
135  
136 =back
137  
138 =head1 METHODS
139  
140 =over 2
141  
142 =item * C<peek>
143  
144 Returns the reference to the current pointer in the i<virtual> CSV-file
145 and the actual file.
146  
147 Initially it points to the earliest row of the historically first file.
148 If there are many concurrent files, than the earliest row of them is returned.
149  
150 If end of i<virtual> CSV-file is reached, then C<undef> is returned
151  
152 my $data = $player->peak;
153 if ($data) {
154 my ($file, $row) = @$data;
155 }
156  
157 =item * C<poll>
158  
159 The same as C<peak> method, but after return of the current row in
160 the i<virtual> CSV-file, it moves the pointer to the next row.
161 Designed to serve as iterator,
162  
163 while (my $data = $player->poll) {
164 my ($file, $row) = @$data;
165 }
166  
167 =back
168  
169 =head1 ASSUMPTIONS
170  
171 =over 2
172  
173 =item * Same filenames for the same timeframe
174  
175 CSV-files aggregate events on some time-frame (i.e. one day, one hour,
176 one week etc.). The L<CSV::HistoryPlayer> does not sort content of
177 files due to performance reasons. Than means, if you have files, organized
178 like:
179  
180 event-a/date_1.csv
181 event-b/date_2.csv
182  
183 and C<date_1> and C<date_2> intersects, then they should have exactly
184 the same name, e.g.:
185  
186 event-a/3-Jan-16.csv
187 event-b/3-Jan-16.csv
188  
189 to be replayed correctly.
190  
191  
192 =item * unix timestamp is the first column in CSV-files
193  
194 =item * CSV-files are opened with the defaults of L<Text::CSV>
195  
196 =back
197  
198 =head1 SEE ALSO
199  
200 L<Text::CSV>, L<Higher-Order Perl|http://hop.perl.plover.com>
201  
202 =head1 SOURCE CODE
203  
204 L<GitHub|https://github.com/binary-com/perl-CSV-HistoryPlayer>
205  
206  
207 =cut
208  
209 2 has 'root_dir' => (
210 is => 'ro',
211 required => 1
212 );
213  
214 has 'dir_filter' => (
215 is => 'ro',
216 5 ▶ default => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
217 26 ▶ return sub { 1 }
Subroutine __ANON__: called CC=1 SCAR=0.0
218 5 });
219  
220 has 'files_mapper' => (
221 is => 'ro',
222 5 ▶ default => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
223 5 ▶ return sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
224 5 my $files = shift;
225 5 return [sort { $a cmp $b } @$files];
226 }
227 5 });
228  
229 2 has 'files' => (is => 'lazy');
230  
231 2 has _current_data => (is => 'rw');
232  
233 2 has '_reader' => (is => 'lazy');
234  
235 6 ▶sub _build_files {
Subroutine _build_files: called CC=7 SCAR=19.5
236 6 my $self = shift;
237  
238 6 my @files;
239 6 my @dirs_queue = (path($self->root_dir));
240 6 my $dir_filter = $self->dir_filter;
241 6 ▶ while (@dirs_queue) {
Branch: 1 branch
BranchTrueFalseTotal
if (@dirs_queue) 38 6 44
242 38 my $dir = shift(@dirs_queue);
243 38 ▶ if ($dir_filter->($dir)) {
Branch: 1 branch
BranchTrueFalseTotal
if (&$dir_filter($dir)) 37 1 38
244 37 for my $c ($dir->children) {
245 50 ▶ push @dirs_queue, $c if (-d $c);
Branch: 1 branch
BranchTrueFalseTotal
if -d $c 32 18 50
246 50 ▶ push @files, $c
Branch: 1 branch
BranchTrueFalseTotal
if $c =~ /\.csv$/i and -s -r -f(_) 16 34 50
Condition66%2/3
$c =~ /\.csv$/i and -s -r -f(_)
!ll&&!rl&&r
34016
MC/DC50%1/2
$c =~ /\.csv$/i and -s -r -f(_)
$c =~ /\.csv$/i -s -r -f(_)
Truth table66%2/3
A and B
A= $c =~ /\.csv$/iB= -s -r -f(_)
ABresult
0X0
100
111
247 if ($c =~ /\.csv$/i && -s -r -f _);
248 }
249 }
250 }
251 6 my $sorted_files = $self->files_mapper->(\@files);
252 6 return $sorted_files;
253 }
254  
255 3 ▶sub _build__reader {
Subroutine _build__reader: called CC=1 SCAR=0.0
256 3 my $self = shift;
257 3 my $files = $self->files;
258 3 my $clusters = [uniq map { $_->basename } @$files];
259 3 my $cluster_idx = -1;
260 3 my @cluster_fds;
261 my @cluster_csvs;
262 3 my @cluser_files;
263  
264 6 ▶ my $open_cluster = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
265 6 my $cluster_id = $clusters->[$cluster_idx];
266 6 @cluser_files = grep { $_->basename eq $cluster_id } @$files;
267 6 @cluster_fds = ();
268 6 @cluster_csvs = ();
269 6 for my $cf (@cluser_files) {
270 9 ▶ my $csv = Text::CSV->new({binary => 1})
Branch: 1 branch
BranchTrueFalseTotal
my $csv = "Text::CSV"->new({"binary", 1}) or die 'Cannot use CSV: ' . "Text::CSV"->error_diag 9 0 9
271 or die "Cannot use CSV: " . Text::CSV->error_diag();
272 9 my $fh = $cf->filehandle("<");
273 9 push @cluster_fds, $fh;
274 9 push @cluster_csvs, $csv;
275 }
276 3 };
277  
278 3 my @lines;
279 30 ▶ my $read_line_from_cluster = sub {
Subroutine __ANON__: called CC=6 SCAR=17.9
280 REDO: {
281  
282 # make sure that we read last line from all cluster files
283 30 for my $idx (0 .. @cluster_fds - 1) {
284 44 ▶ if (!defined $lines[$idx] && !$cluster_csvs[$idx]->eof) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $lines[$idx] or $cluster_csvs[$idx]->eof) 30 14 44
Condition100%3/3
defined $lines[$idx] or $cluster_csvs[$idx]->eof
l!l&&r!l&&!r
11330
MC/DC100%2/2
defined $lines[$idx] or $cluster_csvs[$idx]->eof
defined $lines[$idx] $cluster_csvs[$idx]->eof
Truth table100%3/3
A or B
A= defined $lines[$idx]B= $cluster_csvs[$idx]->eof
ABresult
1X1
011
000
285 30 $lines[$idx] =
286 $cluster_csvs[$idx]->getline($cluster_fds[$idx]);
287 }
288 }
289  
290 # we assume that timestamp is the 1st column
291 my @ordered_idx =
292 11 sort { $lines[$a]->[0] <=> $lines[$b]->[0] }
293 30 grep { defined $lines[$_] } (0 .. @lines - 1);
294 30 ▶ if (@ordered_idx) {
Branch: 1 branch
BranchTrueFalseTotal
if (@ordered_idx) { } 21 9 30
295 21 my $idx = shift @ordered_idx;
296 21 my $line = $lines[$idx];
297 21 my $file = $cluser_files[$idx];
298 21 $self->_current_data([$file, $line]);
299 21 $lines[$idx] = undef;
300 } else {
301 9 ▶ if ($cluster_idx < @$clusters - 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cluster_idx < @$clusters - 1) 6 3 9
302 6 $open_cluster->(++$cluster_idx);
303 6 goto REDO;
304 }
305 }
306 }
307 3 };
308  
309 3 return $read_line_from_cluster;
310 }
311  
312 3 ▶sub peek {
Subroutine peek: called CC=2 SCAR=6.9
Pod documented
313 3 my $self = shift;
314 3 ▶ return $self->_current_data if $self->_current_data;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_current_data 1 2 3
315 2 $self->_reader->();
316 2 return $self->_current_data;
317  
318 }
319  
320 24 ▶sub poll {
Subroutine poll: called CC=2 SCAR=6.9
Pod documented
321 24 my $self = shift;
322 24 my $result = $self->_current_data;
323 24 ▶ if (!$result) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($result) 22 2 24
324 22 $self->_reader->();
325 22 $result = $self->_current_data;
326 }
327 24 $self->_current_data(undef);
328 24 return $result;
329 }
330  
331 =head1 AUTHOR
332  
333 binary.com, C<< <perl at binary.com> >>
334  
335 =head1 BUGS
336  
337 Please report any bugs or feature requests to
338 L<https://github.com/binary-com/perl-CSV-HistoryPlayer/issues>.
339  
340 =head1 LICENSE AND COPYRIGHT
341  
342 Copyright (C) 2016 binary.com
343  
344 This program is free software; you can redistribute it and/or modify it
345 under the terms of the the Artistic License (2.0). You may obtain a
346 copy of the full license at:
347  
348 L<http://www.perlfoundation.org/artistic_license_2_0>
349  
350 Any use, modification, and distribution of the Standard or Modified
351 Versions is governed by this Artistic License. By using, modifying or
352 distributing the Package, you accept this license. Do not use, modify,
353 or distribute the Package, if you do not accept this license.
354  
355 If your Modified Version has been derived from a Modified Version made
356 by someone other than you, you are nevertheless required to ensure that
357 your Modified Version complies with the requirements of this license.
358  
359 This license does not grant you the right to use any trademark, service
360 mark, tradename, or logo of the Copyright Holder.
361  
362 This license includes the non-exclusive, worldwide, free-of-charge
363 patent license to make, have made, use, offer to sell, sell, import and
364 otherwise transfer the Package with respect to any patent claims
365 licensable by the Copyright Holder that are necessarily infringed by the
366 Package. If you institute patent litigation (including a cross-claim or
367 counterclaim) against any party alleging that the Package constitutes
368 direct or contributory patent infringement, then this Artistic License
369 to you shall terminate on the date that such litigation is filed.
370  
371 Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER
372 AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
373 THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
374 PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY
375 YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR
376 CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR
377 CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE,
378 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
379  
380 =cut
381  
382 2 1;
↑ Summary