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