blib/lib/Sub/Slice.pm

filter: Statementstmt 95.1% 194 / 204 Branchbran 85.4% 82 / 96 Conditioncond 77.1% 27 / 35 MC/DCmcdc 63.6% 14 / 22 Subroutinesub 97.3% 36 / 37 Podpod 90.9% 20 / 22 totaltotal 89.6% 373 / 416 CC 62 SCAR 15.9
CC
62
Cov
90%
at_stage
11.3
new
11.0
store
7.0
CRAP 4.9
↑ Summary lib/Sub/Slice/Backend/Filesystem.pm »
1 #############################################################################
2 ## Name: Sub::Slice
3 ## Purpose: Split long-running tasks into manageable chunks
4 ## Author: Simon Flack
5 ## Modified by: $Author: colinr $ on $Date: 2005/11/23 14:31:51 $
6 ## Created: 23/01/2003
7 ## RCS-ID: $Id: Slice.pm,v 1.48 2005/11/23 14:31:51 colinr Exp $
8 #############################################################################
9 package Sub::Slice;
10  
11 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 2 ▶use vars qw/ $VERSION /;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 2 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 2 $VERSION = sprintf"%d.%03d", q$Revision: 1.48 $ =~ /: (\d+)\.(\d+)/;
16  
17 26 ▶sub new {
Subroutine new: called CC=11 SCAR=24.0
Pod documented
18 26 my $class = shift;
19 26 ▶ confess "args: expecting flattened hash (even-numbered list)" if @_%2;
Branch: 1 branch
BranchTrueFalseTotal
if @_ % 2 1 25 26
20 25 my %args = @_;
21  
22 #Load backend
23 25 ▶ my $backend_name = $args{backend} || 'Filesystem';
Condition100%2/2
$args{'backend'} || 'Filesystem'
l!l
718
MC/DC100%1/1
$args{'backend'} || 'Filesystem'
$args{'backend'}
Truth table100%2/2
A
A= $args{'backend'}
Aresult
11
00
24 25 ▶ croak("Invalid Sub::Slice::Backend - $backend_name") if($backend_name =~ m|[^\w:]|);
Branch: 1 branch
BranchTrueFalseTotal
if $backend_name =~ /[^\w:]/ 1 24 25
25 24 ▶ $backend_name = "Sub::Slice::Backend::$backend_name" unless($backend_name =~ /::/); #If no namespace, assume in the Sub::Slice::Backend namespace
Branch: 1 branch
BranchTrueFalseTotal
unless $backend_name =~ /::/ 22 2 24
26 24 eval "require $backend_name";
27 24 ▶ die("Unable to load $backend_name - $@") if($@);
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 23 24
28 23 my $backend = $backend_name->new($args{storage_options});
29  
30 #Create job
31 23 my $job;
32 23 ▶ if ($args{token}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{'token'}) { } 18 5 23
33 18 my $token = $args{token};
34  
35 # Some serializers (XML::Simple?) refuse to serialize
36 # a blessed object. We can now cope with an unblessed
37 # token (though if it is blessed, we leave it as it is)
38 18 ▶ confess "illegal scalar token" unless(ref $token && UNIVERSAL::isa($token, 'HASH'));
Branch: 1 branch
BranchTrueFalseTotal
unless ref $token and UNIVERSAL::isa($token, "HASH") 2 16 18
Condition100%3/3
ref $token and UNIVERSAL::isa($token, "HASH")
!ll&&!rl&&r
1116
MC/DC100%2/2
ref $token and UNIVERSAL::isa($token, "HASH")
ref $token UNIVERSAL::isa($token, "HASH")
Truth table100%3/3
A and B
A= ref $tokenB= UNIVERSAL::isa($token, "HASH")
ABresult
0X0
100
111
39 16 $token = Sub::Slice::Token->rebless($token);
40 16 $job = $backend->load_job( $token->{id} );
41 15 TRACE($job->{token}->{pin}, $token->{pin});
42 15 ▶ die("Signature from client doesn't match the value on the server") unless($job->{token}->{pin} == $token->{pin});
Branch: 1 branch
BranchTrueFalseTotal
unless $job->{"token"}{"pin"} == $token->{"pin"} 1 14 15
43 14 $token->clean(); # remove cruft from last run
44 14 $job->{'token'} = $token;
45 14 ▶ $job->{'iterations'} = $token->{iterations} if(defined $token->{iterations});
Branch: 1 branch
BranchTrueFalseTotal
if defined $token->{"iterations"} 0 14 14
46 } else {
47 5 my $id = $backend->new_id();
48 5 $job = _create_job($id, \%args);
49 5 bless $job, $class;
50 }
51  
52 #Attach backend only for transient lifetime
53 19 $job->{'backend'} = $backend;
54 19 $job->{'this_iteration'} = 0;
55 19 return $job;
56 }
57  
58 20 ▶sub DESTROY {
Subroutine DESTROY: called CC=5 SCAR=16.1
59 20 my $self = shift;
60 20 TRACE("Sub::Slice destructor for $self");
61  
62 #Things not to persist
63 20 delete $self->{'return_value'};
64 20 my $backend = delete $self->{'backend'};
65  
66 20 my $new_eval_error;
67 {
68 # If DESTROY is being called as a result of something else dying, protect $@
69 20 local $@;
70  
71 20 my $job_id = $self->id;
72 20 ▶ if($self->is_done || $self->abort) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->is_done or $self->abort) { } 2 18 20
Condition66%2/3
$self->is_done or $self->abort
l!l&&r!l&&!r
2018
MC/DC50%1/2
$self->is_done or $self->abort
$self->is_done $self->abort
Truth table66%2/3
A or B
A= $self->is_doneB= $self->abort
ABresult
1X1
011
000
73 2 TRACE("finished job: $job_id - deleting...");
74 2 $backend->delete_job($job_id);
75 } else {
76 18 eval { $backend->save_job($self) };
77 18 ▶ if ($new_eval_error = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($new_eval_error = $@) 1 17 18
78 1 TRACE($new_eval_error);
79 1 DUMP($self)
80 }
81 18 TRACE('DONE');
82 }
83 }
84 20 ▶ $@ = $new_eval_error if $new_eval_error;
Branch: 1 branch
BranchTrueFalseTotal
if $new_eval_error 1 19 20
85 }
86  
87 193 ▶sub token {
Subroutine token: called CC=2 SCAR=6.9
Pod documented
88 193 my $self = shift;
89 193 ▶ croak("cannot set token") if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 1 192 193
90 192 return $self->{'token'};
91 }
92  
93 73 ▶sub id {
Subroutine id: called CC=2 SCAR=6.9
Pod documented
94 73 my $self = shift;
95 73 ▶ croak("cannot set id") if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 1 72 73
96 72 return $self->token->{id};
97 }
98  
99 5 ▶sub set_estimate {
Subroutine set_estimate: called CC=2 SCAR=7.2
Pod documented
100 5 my $self = shift;
101 5 ▶ defined $_[0] and $self->token()->{estimate} = shift;
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] and $self->token->{"estimate"} = shift() 5 0 5
102 }
103  
104 2 ▶sub estimate {
Subroutine estimate: called CC=2 SCAR=6.9
Pod documented
105 2 my $self = shift;
106 2 ▶ croak("use set_estimate() to change estimate") if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 1 1 2
107 1 return $self->token()->{estimate};
108 }
109  
110 2 ▶sub count {
Subroutine count: called CC=2 SCAR=6.9
Pod documented
111 2 my $self = shift;
112 2 ▶ croak("cannot set count") if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 1 1 2
113 1 return $self->token()->{count};
114 }
115  
116 51 ▶sub is_done {
Subroutine is_done: called CC=2 SCAR=6.9
Pod documented
117 51 my $self = shift;
118 51 ▶ croak("use done() to mark job as completed") if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 1 50 51
119 50 return $self->token()->{done};
120 }
121  
122 3 ▶sub done {
Subroutine done: called CC=2 SCAR=6.9
Pod documented
123 3 my $self = shift;
124 3 ▶ croak("done() doesn't take arguments") if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 1 2 3
125 2 $self->token()->{done} = 1;
126 }
127  
128 18 ▶sub abort {
Subroutine abort: called CC=2 SCAR=8.4
Pod documented
129 18 my $self = shift;
130 18 ▶ if (defined $_[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $_[0]) 0 18 18
131 0 $self->token()->{error} = shift;
132 0 $self->token()->{abort} = 1;
133 }
134 18 return $self->token()->{'abort'};
135 }
136  
137 6 ▶sub status {
Subroutine status: called CC=2 SCAR=7.1
Pod documented
138 6 my $self = shift;
139 6 ▶ defined $_[0] and $self->token()->{status} = shift;
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] and $self->token->{"status"} = shift() 6 0 6
140 6 return $self->token()->{status};
141 }
142  
143 29 ▶sub store {
Subroutine store: called CC=7 SCAR=19.5
Pod documented
144 29 my $self = shift;
145 29 ▶ while (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 29 27 56
146 29 my ($key, $value) = (shift, shift);
147 29 ▶ croak("Usage: store( KEY, [VALUE] )") unless ($key);
Branch: 1 branch
BranchTrueFalseTotal
unless $key 1 28 29
148 28 ▶ croak("Error: invalid key: $key") if ref $key;
Branch: 1 branch
BranchTrueFalseTotal
if ref $key 1 27 28
149 27 ▶ if(ref $value || !$self->{blob_threshold} || length($value) <= $self->{blob_threshold}) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value or not $self->{'blob_threshold'} or length $value <= $self->{'blob_threshold'}) { } 26 1 27
Condition83%5/6
ref $value or not $self->{"blob_threshold"} or length $value <= $self->{"blob_threshold"}
l!l&&r!l&&!r
2511
ref $value or not $self->{"blob_threshold"}
l!l&&r!l&&!r
0252
MC/DC66%2/3
ref $value or not $self->{"blob_threshold"} or length $value <= $self->{"blob_threshold"}
ref $value not $self->{"blob_threshold"} length $value <= $self->{"blob_threshold"}
Truth table75%3/4
A or not(B) or C
A= ref $valueB= not $self->{"blob_threshold"}C= length $value <= $self->{"blob_threshold"}
ABCresult
1XX1
01X1
0011
0000
150 26 $self->{'backend'}->store($self, $key, $value);
151 } else {
152 1 $self->store_blob($key, $value);
153 }
154 }
155 }
156  
157 44 ▶sub fetch {
Subroutine fetch: called CC=4 SCAR=13.9
Pod documented
158 44 my $self = shift;
159 44 my $key = shift;
160 44 ▶ croak("Usage: fetch( KEY )") unless ($key);
Branch: 1 branch
BranchTrueFalseTotal
unless $key 1 43 44
161 43 ▶ croak("Error: invalid key") if ref $key;
Branch: 1 branch
BranchTrueFalseTotal
if ref $key 1 42 43
162 42 my $d = $self->{'backend'}->fetch($self, $key);
163 42 ▶ return defined $d ? $d : $self->fetch_blob($key);
Branch: 1 branch
BranchTrueFalseTotal
defined $d ? : 41 1 42
164 }
165  
166 3 ▶sub store_blob {
Subroutine store_blob: called CC=1 SCAR=0.0
Pod documented
167 3 my $self = shift;
168 3 my ($key, $data) = @_;
169 3 $self->{'backend'}->store_blob($self, $key, $data);
170 }
171  
172 5 ▶sub fetch_blob {
Subroutine fetch_blob: called CC=1 SCAR=0.0
Pod documented
173 5 my $self = shift;
174 5 my ($key) = @_;
175 5 return $self->{'backend'}->fetch_blob($self, $key);
176 }
177  
178 52 ▶sub stage {
Subroutine stage: called CC=2 SCAR=6.9
Pod documented
179 52 my $self = shift;
180 52 ▶ croak("use next_stage() to set stage") if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 1 51 52
181 51 return $self->{'stage'};
182 }
183  
184 20 ▶sub return_value {
Subroutine return_value: called CC=4 SCAR=14.2
Pod documented
185 20 my $self = shift;
186 20 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 16 4 20
187 16 $self->{return_value} = [@_];
188 16 return @_;
189 }
190 4 my $rv = $self->{return_value};
191 4 ▶ if ($rv) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rv) { } 4 0 4
192 4 ▶ return (@$rv)[0..$#$rv] if $#$rv >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $rv->$#* >= 0 4 0 4
193 } else {
194 return ()
195 0 }
196 }
197  
198 8 ▶sub next_stage {
Subroutine next_stage: called CC=3 SCAR=11.0
Pod documented
199 8 my $self = shift;
200 8 my $stage = shift;
201 8 ▶ croak("Error: invalid stage") if (ref $stage || !defined $stage);
Branch: 1 branch
BranchTrueFalseTotal
if ref $stage or not defined $stage 2 6 8
Condition100%3/3
ref $stage or not defined $stage
l!l&&r!l&&!r
116
MC/DC100%2/2
ref $stage or not defined $stage
ref $stage not defined $stage
Truth table100%3/3
A or not(B)
A= ref $stageB= not defined $stage
ABresult
1X1
011
000
202 6 $self->{'stage'} = $stage;
203 6 $self->{'token'}->{'stage'} = $stage;
204 }
205  
206 7 ▶sub at_start ($&) {
Subroutine at_start: called CC=4 SCAR=14.3
Pod documented
207 7 my $self = shift;
208 7 my ($code) = @_;
209 7 ▶ return if $self->{'initialised'} || $self->stage();
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"initialised"} or $self->stage 5 2 7
Condition66%2/3
$self->{"initialised"} or $self->stage
l!l&&r!l&&!r
502
MC/DC50%1/2
$self->{"initialised"} or $self->stage
$self->{"initialised"} $self->stage
Truth table66%2/3
A or B
A= $self->{"initialised"}B= $self->stage
ABresult
1X1
011
000
210 2 TRACE(sprintf 'Running at_start for job %s', $self->id);
211 2 $self->{'initialised'}++;
212  
213 2 eval {$self->return_value($code->($self))};
214 2 ▶ if (my $error = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = $@) 0 2 2
215 0 $self->abort($error);
216 0 die $error;
217 }
218  
219 2 return $self->return_value;
220 }
221  
222 28 ▶sub at_stage ($$&) {
Subroutine at_stage: called CC=11 SCAR=24.3
Pod documented
223 28 my $self = shift;
224 28 my ($this_stage, $code) = @_;
225  
226 28 ▶ croak("undefined stage") unless defined $this_stage;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $this_stage 0 28 28
227  
228 28 ▶ return unless $self->{'initialised'};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"initialised"} 0 28 28
229 28 ▶ if (my $stage = $self->stage()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $stage = $self->stage) { } 26 2 28
230 26 ▶ return unless defined $this_stage && $this_stage eq $stage;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $this_stage and $this_stage eq $stage 17 9 26
Condition66%2/3
defined $this_stage and $this_stage eq $stage
!ll&&!rl&&r
0179
MC/DC50%1/2
defined $this_stage and $this_stage eq $stage
defined $this_stage $this_stage eq $stage
Truth table66%2/3
A and B
A= defined $this_stageB= $this_stage eq $stage
ABresult
0X0
100
111
231 } else {
232 2 $self->next_stage($this_stage);
233 }
234  
235 11 TRACE(sprintf'Running stage:%s for job %s', $this_stage, $self->id);
236  
237 11 while (1) {
238 23 ▶ last if ( $self->is_done() || $this_stage ne $self->stage() );
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_done or $this_stage ne $self->stage 6 17 23
Condition100%3/3
$self->is_done or $this_stage ne $self->stage
l!l&&r!l&&!r
2417
MC/DC100%2/2
$self->is_done or $this_stage ne $self->stage
$self->is_done $this_stage ne $self->stage
Truth table100%3/3
A or B
A= $self->is_doneB= $this_stage ne $self->stage
ABresult
1X1
011
000
239 17 my $iterate = $self->{'iterations'};
240 17 ▶ last if $iterate && $self->{'this_iteration'} >= $iterate;
Branch: 1 branch
BranchTrueFalseTotal
if $iterate and $self->{"this_iteration"} >= $iterate 5 12 17
Condition100%3/3
$iterate and $self->{"this_iteration"} >= $iterate
!ll&&!rl&&r
665
MC/DC100%2/2
$iterate and $self->{"this_iteration"} >= $iterate
$iterate $self->{"this_iteration"} >= $iterate
Truth table100%3/3
A and B
A= $iterateB= $self->{"this_iteration"} >= $iterate
ABresult
0X0
100
111
241 12 $self->{'this_iteration'}++;
242 12 $self->token()->{count}++;
243  
244 12 eval {$self->return_value($code->($self))}; #Trap any exceptions
245 12 ▶ if (my $error = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = $@) 0 12 12
246 0 $self->abort($error); #Record error message
247 0 die $error; #Re-throw exception
248 }
249 }
250  
251 11 return 1;
252 }
253  
254 7 ▶sub at_end ($&) {
Subroutine at_end: called CC=4 SCAR=14.4
Pod documented
255 7 my $self = shift;
256 7 my ($code) = @_;
257 7 ▶ return unless $self->{'initialised'};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"initialised"} 0 7 7
258 7 ▶ return unless $self->is_done;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->is_done 5 2 7
259 2 TRACE(sprintf 'Running at_end for job %s', $self->id);
260  
261 2 eval {$self->return_value($code->($self))};
262 2 ▶ if (my $error = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = $@) 0 2 2
263 0 $self->abort($error);
264 0 die $error;
265 }
266  
267 2 return $self->return_value;
268 }
269  
270  
271 #############################################################################
272 # Private Functions
273  
274 5 ▶sub _create_job {
Subroutine _create_job: called CC=3 SCAR=11.2
275 5 my ($id, $options) = @_;
276  
277 5 my $iterations = $options->{iterations};
278 5 ▶ $iterations = 1 unless defined $iterations;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $iterations 0 5 5
279  
280 5 my ($fh, $token, %job);
281 5 DUMP('Sub::Slice storage options', $options->{storage_options});
282 5 $job{'storage_options'} = $options->{storage_options};
283 5 ▶ $job{'storage_options'}->{path} ||= File::Spec::Functions::tmpdir();
Condition33%1/3
$job{"storage_options"}{"path"} ||= File::Spec::Functions::tmpdir()
l!l&&r!l&&!r
500
MC/DC0%0/2
$job{"storage_options"}{"path"} ||= File::Spec::Functions::tmpdir()
$job{"storage_options"}{"path"} File::Spec::Functions::tmpdir()
Truth table33%1/3
A ||= B
A= $job{"storage_options"}{"path"}B= File::Spec::Functions::tmpdir()
ABresult
1X1
011
000
284 5 $job{'iterations'} = $iterations;
285 5 $job{'token'} = Sub::Slice::Token->new($id, $options->{pin_length});
286 5 $job{'blob_threshold'} = $options->{auto_blob_threshold};
287  
288 5 return \%job;
289 }
290  
291 # Log::Trace stubs
292 71 ▶sub TRACE {}
Subroutine TRACE: called CC=1 SCAR=0.0
Pod undocumented
293 6 ▶sub DUMP {}
Subroutine DUMP: called CC=1 SCAR=0.0
Pod undocumented
294  
295 #############################################################################
296 # Sub::Slice::Token
297 #############################################################################
298 package Sub::Slice::Token;
299  
300 2 ▶use constant DEFAULT_PIN_LENGTH => 1e9;
Subroutine BEGIN: called CC=1 SCAR=0.0
301 2 ▶use vars '$AUTOLOAD';
Subroutine BEGIN: called CC=1 SCAR=0.0
302 2 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
303 2 ▶use POSIX qw(log10 ceil);
Subroutine BEGIN: called CC=1 SCAR=0.0
304  
305 16 ▶sub rebless {
Subroutine rebless: called CC=3 SCAR=11.3
306 16 my ($class, $token) = @_;
307 16 ▶ $class = ref $class || $class;
Condition33%1/3
ref $class || $class
l!l&&r!l&&!r
0160
MC/DC0%0/2
ref $class || $class
ref $class $class
Truth table33%1/3
A || B
A= ref $classB= $class
ABresult
1X1
011
000
308 16 ▶ bless $token, $class if (ref $token eq "HASH");
Branch: 1 branch
BranchTrueFalseTotal
if ref $token eq "HASH" 9 7 16
309 16 return $token;
310 }
311  
312 5 ▶sub new {
Subroutine new: called CC=2 SCAR=6.9
313 5 my $class = shift;
314 5 my ($id, $pin_length) = @_;
315 5 ▶ $pin_length = DEFAULT_PIN_LENGTH unless($pin_length);
Branch: 1 branch
BranchTrueFalseTotal
unless $pin_length 4 1 5
316  
317 5 my $self = bless {
318 id => $id,
319 estimate => 0,
320 count => 0,
321 done => 0,
322 abort => "",
323 error => "",
324 stage => "",
325 pin => $class->random_pin($pin_length),
326 }, $class;
327 5 return $self;
328 }
329  
330 5 ▶sub random_pin {
Subroutine random_pin: called CC=1 SCAR=0.0
331 5 my ($self, $pin_length) = @_;
332 5 my $figs = ceil(log10($pin_length));
333 5 return sprintf("%0${figs}d", int(rand($pin_length))); #Fixed length random number padded with zeros
334 }
335  
336 14 ▶sub clean {
Subroutine clean: called CC=2 SCAR=6.9
337 14 my $self = shift;
338 14 $self->{$_} = "" for qw( abort error status );
339 14 return $self;
340 }
341  
342 0 ▶sub DESTROY {};
Subroutine DESTROY: not called CC=1 SCAR=0.0
343  
344 20 ▶sub AUTOLOAD {
Subroutine AUTOLOAD: called CC=2 SCAR=7.4
345 20 my $self = shift;
346 20 (my $name = $AUTOLOAD) =~ s/.*://;
347 20 ▶ if (!exists $self->{$name}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not exists $self->{$name}) { } 0 20 20
348 0 croak("undefined method: $name");
349 } else {
350 20 return $self->{$name}
351 }
352 }
353  
354 2 1;
355  
356  
357 =head1 NAME
358  
359 Sub::Slice - split long-running tasks into manageable chunks
360  
361 =head1 SYNOPSIS
362  
363 # Client
364 # Assume methods in the Server:: package are magically remoted
365 my $token = Server::create_token();
366 for(1 .. MAX_ITERATIONS) {
367 Server::do_work($token);
368 last if $token->{done};
369 }
370  
371 # Server
372 # Imagine this is on a remote machine
373 package Server;
374 use Sub::Slice;
375  
376 sub create_token {
377 # create a new job:
378 my $job = new Sub::Slice(
379 backend => 'Filesystem',
380 storage_options => {
381 path => '/var/tmp/myproject/',
382 }
383 );
384 return $job->token;
385 }
386  
387 sub do_work {
388 # loading an existing job:
389 my $job = new Sub::Slice(
390 token => $token
391 backend => 'Filesystem',
392 storage_options => {
393 path => '/var/tmp/myproject/',
394 }
395 );
396  
397 at_start $job
398 sub {
399 $job->store('foo', '1');
400 $job->store('bar', { abc = > 'def' });
401 # store data, initialise
402 $job->set_estimate(10); # estimate number of steps
403 return ( $job->fetch('foo') );
404 };
405  
406 my $foo = $job->fetch('foo');
407  
408 at_stage $job "stage_one",
409 sub {
410 my $bar = $job->fetch('bar');
411 # do stuff
412 $job->next_stage('stage_two') if $some_condition;
413 };
414  
415 at_stage $job "stage_two",
416 sub {
417 # ...do more stuff...
418 # mark job as ready to be deleted
419 $job->done() if $job->count() == $job->estimate();
420 };
421  
422 return $job->return_value(); #Pass back any return value from coderefs
423 }
424  
425 =head1 DESCRIPTION
426  
427 Sub::Slice breaks up a long process into smaller chunks that can be executed
428 one at a time over a stateless protocol such as HTTP/SOAP so that progress may
429 be reported. This means that the client can display progress or cancel the
430 operation part-way through.
431  
432 It works by the client requesting a token from the server, and passing the
433 token back to the server on each iteration. The token passed to the client
434 contains status information which the client can use to determine if the job
435 has completed/failed and to display status/error messages.
436  
437 Within the routine called on each iteration, the server defines a set of
438 coderefs, one of which will be called for a given iteration. In addition the
439 server may define coderefs to be called at the start and end of the job. The
440 server may provide the client with an estimate of the number of iterations the
441 job is likely to take.
442  
443 It is possible to balance performance/usability by modifying the number of
444 iterations that will be executed before returning progress to the client.
445  
446 =head1 METHODS
447  
448 =over 4
449  
450 =item new( %options )
451  
452 Create a new job object. Valid options are:
453  
454 =over 4
455  
456 =item token
457  
458 A token for an existing job (optional)
459  
460 =item iterations
461  
462 The number of chunks to execute before saving the state and returning. Defaults to '1'.
463 This value may be overridden later on by setting the value in the token.
464 Set to 0 for unlimited.
465  
466 =item backend
467  
468 The storage backend.
469 This should either be a fully qualified package name or if no namespace is included it's assumed to be in the
470 Sub::Slice::Backend namespace (e.g. Database would be interpreted as Sub::Slice::Backend::Database).
471 Defaults to Sub::Slice::Backend::Filesystem.
472  
473 =item pin_length
474  
475 The size of the random PIN used to sign the token. Default is 1e9.
476  
477 =item random_pin ($l)
478  
479 Generates a random PIN of length $l. We do this using rand().
480 You might want to override this method if you require
481 cryptographic-quality randomness for your environment.
482  
483 =item auto_blob_threshold
484  
485 If this is set, any strings longer than this number of bytes will be stored as BLOBs automatically
486 (possibly taking advantage of a more efficient BLOB storage mechanism offered by the backend).
487 Note that this does not apply when you store references, only to strings of characters/bytes.
488  
489 =item storage_options
490  
491 A hash of configuration options for the backend storage.
492 See the POD of the backend module (default is L<Sub::Slice::Backend::Filesystem>).
493  
494 =back
495  
496 Returns an existing job object with session data for C<$token>
497  
498 =back
499  
500 =head2 METHODS DEFINING STAGES OF ITERATION
501  
502 =over 4
503  
504 =item at_start $job \&coderef
505  
506 Code to initialise the job. This isn't counted as an iteration and will only
507 run once per job.
508  
509 =item at_stage $job $stage_name, \&coderef
510  
511 Executes C<\E<amp>coderef> up-to C<iterate> times, B<if> C<$stage_name> is the
512 current stage B<and> if the number of executions in the current session is not
513 greater than C<iterate>. It is currently required that you have at least one
514 C<at_stage> defined.
515  
516 If the current stage hasn't been set with C<next_stage()>, it will implicitly be set to the first
517 C<at_stage> block that is seen.
518  
519 =item at_end $job \&coderef
520  
521 Code to run after the last iteration (unless the job is aborted before then). This isn't counted as an iteration and will only
522 run once per job. It's typically used as a "commit" stage.
523  
524 =back
525  
526 If a job dies in one of these blocks, Sub::Slice sets $job->abort($@) and rethrows the exception.
527 Note that C<at_end> may not be run if a job is aborted during one of the earlier stages.
528 See L<Sub::Slice::Manual> for an example of defensive coding to prevent resources allocated in C<at_start>
529 leaking if the job is aborted part-way through.
530  
531 =head2 ACCESSOR METHODS
532  
533 =over 4
534  
535 =item $job->token()
536  
537 Returns the token object for this job. The token object will be updated
538 automatically as stages of the sub execute. The token has the following
539 properties which the client can make use of:
540  
541 =over 4
542  
543 =item done
544  
545 Read/write boolean value. Is the job done?
546 Setting this to 1 on the client will cause iterations on the server to cease,
547 and any C<at_end> cleanup to be done.
548  
549 =item abort
550  
551 Read-only boolean value. Was the job aborted on the server?
552  
553 =item error
554  
555 Read-only. Error message if the job was aborted.
556  
557 =item count
558  
559 Read-only. Number of iterations performed so far.
560  
561 =item estimate
562  
563 Read-only. An estimate of the total number of iterations that will be performed. This may
564 not be totally accurate, depending if new work is "discovered" as the
565 iterations proceed.
566  
567 =item status
568  
569 Read-only. Status message.
570  
571 =item stage
572  
573 Read-only. The next stage that the job will run.
574  
575 =item iterations
576  
577 A write-only property the client can use to
578 control the number of iterations run on the server in the next call. This overrides the
579 default number of iterations set in the Sub::Slice constructor.
580  
581 =back
582  
583 =item $job->id()
584  
585 Returns the ID of the job (issued by the C<new_id> function in the backend).
586 This is mainly of interest if you are writing a backend and need to get the ID from a job.
587  
588 =item $job->count()
589  
590 Returns the total number of iterations that have been executed.
591  
592 =item $job->estimate()
593  
594 Returns an estimate of how many iterations are required for the job.
595  
596 =item $job->is_done()
597  
598 Returns a boolean value. Is the job done?
599  
600 =item $job->stage()
601  
602 Returns the name of the executing code block, as set by C<next_stage()>
603  
604 =item $job->fetch( $key )
605  
606 Returns the user data stored under C<$key>.
607 If no data is found against C<$key>, it automatically tries C<fetch_blob> to see if data was stored as a blob.
608  
609 =item $job->fetch_blob($key)
610  
611 Returns a lump of data stored using C<store_blob> - see the MUTATOR METHODS.
612  
613 =item $job->return_value()
614  
615 C<return_value()> returns the return value of the stage. This C<return_value()>
616 method will help you avoid mistakes like this:
617  
618 sub do_work {
619 my $job = new Sub::Slice(token => shift());
620 at_stage $job 'mystage', sub {
621 # do stuff
622 return 'abc' #only returns 1 level up
623 };
624 #nowt returned from do_work
625 }
626  
627 The caller of do_work() will not receive the return value inside the 'mystage' sub {}
628 This might be better written as :
629  
630 sub do_work {
631 my $job = new Sub::Slice(token => shift());
632 at_stage $job 'mystage', sub {
633 # do stuff
634 return 'abc' #only returns 1 level up
635 };
636 return $job->return_value(); # 'abc'
637 }
638  
639 =back
640  
641 =head2 MUTATOR METHODS THAT SET VALUES IN THE TOKEN
642  
643 =over 4
644  
645 =item $job->set_estimate( $int )
646  
647 Populates the C<estimate> field in the token with an estimate of how many
648 iterations are required for this job to complete.
649  
650 =item $job->done()
651  
652 Mark the job as completed successfully. This sets the done flag in the token.
653 Serialised object data will be removed when the object is destroyed.
654  
655 =item $job->abort( $reason )
656  
657 Mark the job as aborted. This sets the abort flag in the token.
658 The optional $reason message will be stored in the token's error string.
659 Serialised object data will be removed when the object is destroyed.
660  
661 =item $job->status( $status_text )
662  
663 Set the status field in the token. This might be useful to inform users about
664 what is about to happen in the next iteration of the job.
665  
666 =back
667  
668 =head2 OTHER MUTATOR METHODS
669  
670 =over 4
671  
672 =item $job->next_stage( $stage_name )
673  
674 Tell the C<$job> object that the next time the routine is called, it should
675 execute the block named C<$stage_name>. Unless C<next_stage> is set, the first
676 at_stage block will be executed.
677  
678 =item $job->store( $key => $value, $key2 => $value2, ... )
679  
680 Store some user data in the object. C<$value> can be a scalar containing any
681 perl data type (such as hash/array references) - it will be automatically
682 serialised.
683  
684 Note that some objects may not be suited to serialisation. For example if
685 an object is blessed into a package that is C<require>d at runtime, when it is
686 deserialised, the required package may not actually be loaded.
687  
688 There may also be issues serialising some objects like DBI database handles and
689 XML::Parser objects, although this is potentially backend-specific (Filesystem
690 uses Storable, and some objects may provide serialisation hooks).
691  
692 C<$value> is optional (if not specified, C<$value> will be set to undef).
693  
694 =item $job->store_blob($key => $blob)
695  
696 Allows large lumps of data to be stored efficiently by the back end.
697  
698 =back
699  
700 =head1 VERSION
701  
702 $Revision: 1.48 $ on $Date: 2005/11/23 14:31:51 $ by $Author: colinr $
703  
704 =head1 AUTHOR
705  
706 Simon Flack and John Alden with additions by Tim Sweetman <cpan _at_ bbc _dot_ co _dot_ uk>
707  
708 =head1 COPYRIGHT
709  
710 (c) BBC 2005. This program is free software; you can redistribute it and/or modify it under the GNU GPL.
711  
712 See the file COPYING in this distribution, or http://www.gnu.org/licenses/gpl.txt
713  
714 =cut
↑ Summary lib/Sub/Slice/Backend/Filesystem.pm »