Stored.pm

filter: Statementstmt 100% 69 / 69 Branchbran 50.0% 4 / 8 Conditioncond 50.0% 1 / 2 MC/DCmcdc 0.0% 0 / 1 Subroutinesub 100% 23 / 23 Podpod 28.5% 2 / 7 totaltotal 90.0% 99 / 110 CC 6 SCAR 3.7
CC
6
Cov
94%
advance
3.1
_build_report_every
2.1
_build_progress
2.1
CRAP 1.4
« Stored/Storage.pm ↑ Summary Stored/Storage/Memory.pm »
1 package Time::Progress::Stored;
2 1 $Time::Progress::Stored::VERSION = '1.002';
3 1 ▶use v5.10;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use true;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use autobox::Core;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 =head1 NAME
9  
10 Time::Progress::Stored - Report progress + store and retrieve the current status
11  
12 =head1 DESCRIPTION
13  
14 This module helps if you have a long running process which reports
15 progress, but you need to actually display the progress to the user in
16 a different process.
17  
18 Typically this is a long running web request in the web server or in a
19 job queue worker, while the web browser periodically sends Ajax
20 requests to get updated on the current progress status to show using a
21 progress bar.
22  
23 Time::Progress::Stored stores the progress report as the worker
24 performs its job, and retrieves it from elsewhere where the report is
25 needed.
26  
27 The report is a hashref with the following details:
28  
29 | id | "progress-1454518121172" |
30 | max | 262 |
31 | current | 2 |
32 | activity | "Importing Users" |
33 | elapsed_seconds | "1" |
34 | elapsed_time | " 0:01" |
35 | finish_time | "Wed Feb 3 16:50:54 2016" |
36 | percent | 0.8 |
37 | percent_string | " 0.8%" |
38 | remaining_seconds | "130" |
39 | remaining_time | " 2:10" |
40 | is_done | 0 |
41  
42 =head1 SYNOPSIS
43  
44 ### In the worker process
45  
46 my $progess_id = ...; # Probably comes from the client
47 my $max = @items * 2; # Let's say two passes over @items
48  
49 my $redis = Redis->new( ... );
50 my $progress = Time::Progress::Stored->new({
51 max => $max,
52 progress_id => $progress_id,
53 storage => Progress::Stored::Storage::Redis->new({ redis => $redis }),
54 });
55  
56 # Do the work
57 for my $item (@items) {
58 # Do stuff
59 $progress->advance("Doing the first thing");
60 }
61 for my $item (@items) {
62 # Do other stuff
63 $progress->advance("Doing other stuff with $item->{name}");
64 }
65  
66 $progress->done();
67  
68  
69 ### HTTP endpoint, e.g. a Mojo controller for /progress/:progress_id
70  
71 sub get {
72 my $self = shift;
73 my $progress_id = $self->param("progress_id");
74  
75 my $storage = Time::Progress::Stored::Storage::Redis->new({
76 redis => $self->redis,
77 });
78 my $response_json = $storage->retrieve($progress_id)
79 or return $self->render(status => 404, json => {});
80  
81 return $self->render(json => { progress => $response_json });
82 }
83  
84  
85 =head2 Synopsis breakdown
86  
87 =head3 Worker
88  
89 As the long running piece of work comes in, start the progress
90 reporting.
91  
92 Create the $progress object with a storage to store the progress
93 reports. Initialize it with the number of actions you want to perform.
94  
95 For each time something is done, call $progress->advance(). This might
96 update the actual report.
97  
98 By default only about 100 steps will be reported (each percent
99 progressed). You can increase this by specifying the attribute
100 "report_every", e.g. to report every single time something happens,
101 set it to 1 (this might slow things down though).
102  
103 "advance" can optionally be called with an activity description
104 string, indicating what's happening right now. This can be large scale
105 steps, or include details about this specific action being performed.
106  
107 At the end, call $progress->done, just to make sure the reporting
108 knows it has reached the end. This will set is_done: 1 in the report.
109  
110  
111 =head3 HTTP endpoint
112  
113 The client should send requests to the endpoint periodically to get
114 the current progress report. The request contains the progress id, and
115 it's simply fetched and returned as a JSON payload.
116  
117 See above for the contents of the payload.
118  
119  
120 =head3 Client making a request to a long running web request
121  
122 This is for when the long running process is running as one web
123 request.
124  
125 A web page would typically provide a progress id while making the
126 initial Ajax request to kick off the long running process.
127  
128 The client then sends Ajax requests to the HTTP endpoint (using the
129 id) every second to get updates on the progress. It does this until
130 the long running progress has responded.
131  
132 If you look at the report payload you'll see there is a variety of
133 information to provide user feedback, e.g. percent done, time left,
134 what's going on etc.
135  
136  
137 =head3 Client making a request to a asynchronous worker process
138  
139 This is for when the long running process is running as a background
140 process, e.g. in a job queue.
141  
142 A web page would typically kick off the long running process. Instead
143 of the client passing in a progress id, the $progress object defaults
144 to a unique id (or you can just make one up yourself), and the HTTP
145 endpoint can report $progress->progress_id back to the client in the
146 response.
147  
148 The client then sends Ajax requests to the HTTP endpoint (using the
149 id) every second to get updates on the progress. It does this until
150 the progress report "is_done" is set to 1.
151  
152  
153 =head2 Storage backends
154  
155 Time::Progress::Stored can use various backends to store the
156 status.
157  
158 Current backends are Redis and Memory. Memory is mainly for testing
159 and not very useful for real life scenarios.
160  
161 The backends are tiny and it would be simple to write another backend
162 for e.g. a file, or using one of the Cache or CHI modules. Patches
163 more than welcome.
164  
165  
166  
167 =head2 Pitfalls
168  
169 If you're testing with a single threaded test server like Morbo, the
170 web browser's Ajax requests won't be processed until the long running
171 process has finished, so you'll never see the progress until it's all
172 done.
173  
174 =cut
175  
176 1 ▶use Types::Standard qw/ Int Bool Str /;
Subroutine BEGIN: called CC=1 SCAR=0.0
177 1 ▶use List::AllUtils qw/ min /;
Subroutine BEGIN: called CC=1 SCAR=0.0
178 1 ▶use Time::Progress;
Subroutine BEGIN: called CC=1 SCAR=0.0
179  
180 1 ▶use Time::Progress::Stored::Storage::Memory;
Subroutine BEGIN: called CC=1 SCAR=0.0
181  
182  
183 =head1 ATTRIBUTES
184  
185 =head2 max
186  
187 The number of times you're planning to call ->advance().
188  
189 =cut
190  
191 1 has max => (
192 is => "ro",
193 isa => Int,
194 required => 1,
195 );
196  
197 =head2 storage
198  
199 A Storage object to store reports in.
200  
201 Default: Time::Progress::Stored::Storage::Memory, but that's probably
202 only useful for testing.
203  
204 =cut
205  
206 has storage => (
207 is => "lazy",
208 1 ▶ isa => sub { shift->isa("Time::Progress::Stored::Storage") },
Subroutine __ANON__: called CC=1 SCAR=0.0
209 1 );
210 1 ▶sub _build_storage {
Subroutine _build_storage: called CC=1 SCAR=0.0
211 1 my $self = shift;
212 1 Time::Progress::Stored::Storage::Memory->new();
213 }
214  
215 =head2 progress_id
216  
217 The id to identify this progress report with. Either set by the
218 client, or defaulted to a unique URL-param safe value you can return
219 to the client.
220  
221 =cut
222  
223 1 has progress_id => ( is => "lazy" );
224 1 ▶sub _build_progress_id { "progress-" . time() . "-" . int(rand(10_000)) }
Subroutine _build_progress_id: called CC=1 SCAR=0.0
225  
226 =head2 report_every
227  
228 Number of calls to ->advance() for every time a new progress report is
229 generated and stored.
230  
231 Default: a value that results in a report for every percent of
232 progress.
233  
234 =cut
235  
236 1 has report_every => ( is => "lazy" );
237 1 ▶sub _build_report_every {
Subroutine _build_report_every: called CC=2 SCAR=7.2
238 1 my $self = shift;
239 1 ▶ int($self->max / 100) || 1;
Branch: 1 branch
BranchTrueFalseTotal
int $self->max / 100 or 1 0 1 1
240 }
241  
242 =head2 current
243  
244 The current iteration. You could in theory set this yourself, but it's
245 recommended to call ->advance().
246  
247 =cut
248  
249 1 has current => (
250 is => "rw",
251 isa => Int,
252 lazy => 1,
253 builder => "_build_current",
254 );
255 1 ▶sub _build_current { 0 }
Subroutine _build_current: called CC=1 SCAR=0.0
256 42 ▶sub inc_current {
Subroutine inc_current: called CC=1 SCAR=0.0
Pod undocumented
257 42 my $self = shift;
258 42 $self->current( $self->current + 1 );
259 }
260  
261 1 has is_done => (
262 is => "rw",
263 isa => Bool,
264 lazy => 1,
265 builder => "_build_is_done",
266 );
267 1 ▶sub _build_is_done { 0 }
Subroutine _build_is_done: called CC=1 SCAR=0.0
268  
269 =head2 current_activity
270  
271 Same as ->current, but for the current activity.
272  
273 =cut
274  
275 1 has current_activity => (
276 is => "rw",
277 isa => Str,
278 lazy => 1,
279 builder => "_build_current_activity",
280 );
281 1 ▶sub _build_current_activity { "" }
Subroutine _build_current_activity: called CC=1 SCAR=0.0
282  
283  
284  
285  
286 1 has progress => ( is => "lazy" );
287 1 ▶sub _build_progress {
Subroutine _build_progress: called CC=2 SCAR=7.2
288 1 my $self = shift;
289 1 ▶ Time::Progress->new( max => $self->max // 1 )
Condition50%1/2
$self->max // 1
l!l
10
MC/DC0%0/1
$self->max // 1
$self->max
Truth table50%1/2
A
A= $self->max
Aresult
11
00
290 }
291  
292  
293  
294 =head1 METHODS
295  
296 =cut
297  
298 1 ▶sub BUILD {
Subroutine BUILD: called CC=1 SCAR=0.0
Pod undocumented
299 1 my $self = shift;
300 # There should always be a report available to fetch
301 1 $self->write_report();
302 }
303  
304 =head2 advance($activity?)
305  
306 Advance the progress one iteration. Optionally set the current
307 $activity.
308  
309 =cut
310  
311 42 ▶sub advance {
Subroutine advance: called CC=3 SCAR=11.3
Pod documented
312 42 my $self = shift;
313 42 my ($activity) = @_;
314 42 ▶ defined($activity) and $self->current_activity( $activity );
Branch: 1 branch
BranchTrueFalseTotal
defined $activity and $self->current_activity($activity) 0 42 42
315 42 $self->inc_current;
316 42 ▶ $self->current % $self->report_every or $self->write_report();
Branch: 1 branch
BranchTrueFalseTotal
$self->current % $self->report_every or $self->write_report 0 42 42
317 }
318  
319 =head2 done()
320  
321 Mark the progress as being completed, and set the is_done key in the
322 report.
323  
324 =cut
325  
326 1 ▶sub done {
Subroutine done: called CC=1 SCAR=0.0
Pod documented
327 1 my $self = shift;
328 1 $self->current( $self->max );
329 1 $self->is_done(1);
330 1 $self->write_report();
331 }
332  
333 44 ▶sub write_report {
Subroutine write_report: called CC=1 SCAR=0.0
Pod undocumented
334 44 my $self = shift;
335 44 $self->storage->store( $self->progress_id, $self->report );
336 }
337  
338 44 ▶sub report {
Subroutine report: called CC=1 SCAR=0.0
Pod undocumented
339 44 my $self = shift;
340  
341 # Avoid going beyond max, since that results in a "n/a"
342 44 my $current = min($self->current, $self->max);
343  
344 44 state $progress_template = join("\t", qw/ %p %l %L %e %E %f /);
345 44 my $report_string = $self->progress->report( $progress_template, $current );
346 my (
347 44 $percent_string, $elapsed_seconds, $elapsed_time,
348 $remaining_seconds, $remaining_time, $finish_time,
349 ) = split(/\t/, $report_string);
350 44 my $percent = $self->percent_from_string($percent_string);
351  
352 return {
353 44 id => $self->progress_id,
354 activity => $self->current_activity,
355 max => $self->max,
356 current => $current,
357 percent_string => $percent_string,
358 percent => $percent,
359 elapsed_seconds => $elapsed_seconds,
360 elapsed_time => $elapsed_time,
361 remaining_seconds => $remaining_seconds,
362 remaining_time => $remaining_time,
363 finish_time => $finish_time,
364 is_done => $self->is_done,
365 };
366 }
367  
368 44 ▶sub percent_from_string {
Subroutine percent_from_string: called CC=2 SCAR=7.0
Pod undocumented
369 44 my $self = shift;
370 44 my ($percent_string) = @_;
371 44 ▶ $percent_string =~ /([\d.]+)/ or return 0;
Branch: 1 branch
BranchTrueFalseTotal
$percent_string =~ /([\d.]+)/ or return 0 44 0 44
372 44 return $1 + 0;
373 }
374  
375  
376 =head1 DEVELOPMENT
377  
378 =head2 Author
379  
380 Johan Lindstrom, C<< <johanl [AT] cpan.org> >>
381  
382  
383 =head2 Contributors
384  
385  
386  
387 =head2 Source code
388  
389 L<https://github.com/jplindstrom/p5-Time-Progress-Stored>
390  
391  
392 =head2 Bug reports
393  
394 Please report any bugs or feature requests on GitHub:
395  
396 L<https://github.com/jplindstrom/p5-Time-Progress-Stored/issues>.
397  
398  
399 =head2 Caveats
400  
401  
402 =head1 COPYRIGHT & LICENSE
403  
404 Copyright 2016- Broadbean Technologies, All Rights Reserved.
405  
406 This program is free software; you can redistribute it and/or modify it
407 under the same terms as Perl itself.
408  
409  
410 =head1 ACKNOWLEDGEMENTS
411  
412 Thanks to Broadbean for providing time to open source this during one
413 of the regular Hack-days.
414  
415 This module uses the excellent L<Time::Progress> module, which you
416 should be using if you just need a progress bar in a command line
417 script.
418  
419 =cut
« Stored/Storage.pm ↑ Summary Stored/Storage/Memory.pm »