DynamoDB/20120810.pm untested

filter: Statementstmt 0.0% 0 / 252 Branchbran 0.0% 0 / 46 Conditioncond 0.0% 0 / 19 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 36 Podpod 0.0% 0 / 25 totaltotal 0.0% 0 / 378 CC 24 SCAR 28.8
CC
24
Cov
0%
type_for_value
72.0
scan
30.0
validate_table_name
30.0
CRAP 17.8
1 package WebService::Amazon::DynamoDB::20120810;
2 $WebService::Amazon::DynamoDB::20120810::VERSION = '0.003';
3 use strict;
4 use warnings;
5  
6 use parent qw(WebService::Amazon::DynamoDB);
7  
8 =head1 NAME
9  
10 WebService::Amazon::DynamoDB::20120810 - interact with DynamoDB using API version 20120810
11  
12 =head1 VERSION
13  
14 version 0.003
15  
16 =head1 DESCRIPTION
17  
18 =cut
19  
20 use Future;
21 use Future::Utils qw(try_repeat);
22 use POSIX qw(strftime);
23 use JSON::MaybeXS;
24 use Scalar::Util qw(reftype);
25 use B qw(svref_2object);
26 use HTTP::Request;
27  
28 use WebService::Amazon::Signature;
29  
30 =head2 new
31  
32 Instantiates the API object.
33  
34 Expects the following named parameters:
35  
36 =over 4
37  
38 =item * implementation - the object which provides a Future-returning C<request> method,
39 see L<WebService::Amazon::DynamoDB::NaHTTP> for example.
40  
41 =item * uri - the base URI for constructing requests
42  
43 =item * security - 'iam' or 'key'
44  
45 =item * access_key - the access key for signing requests (only for security=key)
46  
47 =item * secret_key - the secret key for signing requests (only for security=key)
48  
49 =item * role - the role to use for requests (only for security=iam, usually autodetected from EC2 instance metadata)
50  
51 =item * algorithm - which signing algorithm to use, default AWS4-HMAC-SHA256
52  
53 =back
54  
55 =cut
56  
57 sub new {
58 my $class = shift;
59 bless { @_ }, $class
60 }
61  
62 sub implementation { shift->{implementation} }
63 sub host { shift->{host} }
64 sub port { shift->{port} }
65 sub algorithm { 'AWS4-HMAC-SHA256' }
66 sub access_key { shift->{access_key} }
67 sub secret_key { shift->{secret_key} }
68 sub api_version { '20120810' }
69 sub json { shift->{json} //= JSON::MaybeXS->new }
70  
71 =head2 security_token
72  
73 =cut
74  
75 sub security_token { shift->{security_token} }
76  
77  
78 =head2 create_table
79  
80 Creates a new table. It may take some time before the table is marked
81 as active - use L</wait_for_table> to poll until the status changes.
82  
83 Named parameters:
84  
85 =over 4
86  
87 =item * table - the table name
88  
89 =item * read_capacity - expected read capacity units (optional, default 5)
90  
91 =item * write_capacity - expected write capacity units (optional, default 5)
92  
93 =item * fields - an arrayref specifying the fields, in pairs of (name, type),
94 where type is N for numeric, S for string, SS for string sequence, B for binary
95 etc.
96  
97 =item * primary - the primary keys as an arrayref of pairs indicating (name, type),
98 default type is hash so ['pkey'] would create a single HASH primary key
99  
100 =back
101  
102 =cut
103  
104 sub create_table {
105 my $self = shift;
106 my %args = @_;
107 my %payload = (
108 TableName => $args{table},
109 ProvisionedThroughput => {
110 ReadCapacityUnits => $args{read_capacity} || 5,
111 WriteCapacityUnits => $args{write_capacity} || 5,
112 }
113 );
114 my @fields = @{$args{fields}};
115 my %field;
116 while(my ($k, $type) = splice @fields, 0, 2) {
117 $field{$k} = $type;
118 push @{$payload{AttributeDefinitions} }, {
119 AttributeName => $k,
120 AttributeType => $type || 'S',
121 }
122 }
123 my @primary = @{$args{primary} || []};
124 while(my ($k, $type) = splice @primary, 0, 2) {
125 die "Unknown field $k" unless exists $field{$k};
126 push @{$payload{KeySchema} }, {
127 AttributeName => $k,
128 KeyType => $type || 'HASH',
129 }
130 }
131 $self->make_request(
132 target => 'CreateTable',
133 payload => \%payload,
134 )->then(sub {
135 $self->_request(shift)
136 })
137 }
138  
139 =head2 describe_table
140  
141 Describes the given table.
142  
143 Takes a single named parameter:
144  
145 =over 4
146  
147 =item * table - the table name
148  
149 =back
150  
151 and returns the table spec.
152  
153 =cut
154  
155 sub describe_table {
156 my $self = shift;
157 my %args = @_;
158 my %payload = (
159 TableName => $args{table},
160 );
161 $self->make_request(
162 target => 'DescribeTable',
163 payload => \%payload,
164 )->then(sub {
165 $self->_request(shift)->transform(
166 # Sadly not the same key as used in DeleteTable
167 done => sub { my $content = shift; $self->json->decode($content)->{Table}; }
168 );
169 })
170 }
171  
172 =head2 delete_table
173  
174 Delete a table entirely.
175  
176 Takes a single named parameter:
177  
178 =over 4
179  
180 =item * table - the table name
181  
182 =back
183  
184 =cut
185  
186 sub delete_table {
187 my $self = shift;
188 my %args = @_;
189 my %payload = (
190 TableName => $args{table},
191 );
192 $self->make_request(
193 target => 'DeleteTable',
194 payload => \%payload,
195 )->then(sub {
196 $self->_request(shift)->transform(
197 # Sadly not the same key as used in DescribeTable
198 done => sub { my $content = shift; $self->json->decode($content)->{TableDescription} }
199 )
200 })
201 }
202  
203 =head2 wait_for_table
204  
205 Waits for the given table to be marked as active.
206  
207 Takes a single named parameter:
208  
209 =over 4
210  
211 =item * table - the table name
212  
213 =back
214  
215 =cut
216  
217 sub wait_for_table {
218 my $self = shift;
219 my %args = @_;
220 try_repeat {
221 $self->describe_table(%args)
222 } until => sub {
223 my $f = shift;
224 my $status = $f->get->{TableStatus};
225 # warn "status: " . $status;
226 $status eq 'ACTIVE'
227 };
228 }
229  
230 =head2 each_table
231  
232 Run code for all current tables.
233  
234 Takes a coderef as the first parameter, will call this for each table found.
235  
236 =cut
237  
238 sub each_table {
239 my $self = shift;
240 my $code = shift;
241 my %args = @_;
242 my %payload;
243 my $last_table;
244 try_repeat {
245 $payload{ExclusiveStartTableName} = $args{start} if defined $args{start};
246 $payload{Limit} = $args{limit} if defined $args{limit};
247 $self->make_request(
248 target => 'ListTables',
249 payload => \%payload,
250 )->then(sub {
251 $self->_request(shift)
252 })->on_done(sub {
253 my $rslt = shift;
254 my $data = $self->json->decode($rslt);
255 for my $tbl (@{$data->{TableNames}}) {
256 $code->($tbl);
257 }
258 $last_table = $data->{LastEvaluatedTableName};
259 $args{start} = $last_table;
260 });
261 } while => sub {
262 # warn "Checking @_ => $last_table\n";
263 defined $last_table
264 };
265 }
266  
267 =head2 list_tables
268  
269 Returns a L<Future> which will resolve with a list of all tables.
270  
271 Takes no parameters.
272  
273 $ddb->list_tables->on_done(sub {
274 my @tbl = @_;
275 print "Table: $_\n" for @tbl;
276 });
277  
278 =cut
279  
280 sub list_tables {
281 my $self = shift;
282 my @tbl;
283 $self->each_table(sub {
284 push @tbl, shift
285 })->transform(
286 done => sub { @tbl }
287 );
288 }
289  
290 =head2 put_item
291  
292 Writes a single item to the table.
293  
294 Takes the following named parameters:
295  
296 =over 4
297  
298 =item * table - the table name
299  
300 =item * fields - the field spec, as a { key => value } hashref
301  
302 =back
303  
304 =cut
305  
306 sub put_item {
307 my $self = shift;
308 my %args = @_;
309  
310 my %payload = (
311 TableName => $args{table},
312 ReturnConsumedCapacity => $args{capacity} ? 'TOTAL' : 'NONE',
313 );
314 foreach my $k (keys %{$args{fields}}) {
315 my $v = $args{fields}{$k};
316 $payload{Item}{$k} = { type_for_value($v) => $v };
317 }
318  
319 $self->make_request(
320 target => 'PutItem',
321 payload => \%payload,
322 )->then(sub {
323 $self->_request(shift)->transform(
324 # Sadly not the same key as used in DeleteTable
325 done => sub { $self->json->decode(shift)->{Table}; }
326 );
327 })
328 }
329  
330 =head2 update_item
331  
332 Updates a single item in the table.
333  
334 Takes the following named parameters:
335  
336 =over 4
337  
338 =item * table - the table name
339  
340 =item * item - the item to update, as a{ key => value } hashref
341  
342 =item * fields - the field spec, as a { key => value } hashref
343  
344 =back
345  
346 =cut
347  
348 sub update_item {
349 my $self = shift;
350 my %args = @_;
351  
352 my %payload = (
353 TableName => $args{table},
354 ReturnConsumedCapacity => $args{capacity} ? 'TOTAL' : 'NONE',
355 );
356 foreach my $k (keys %{$args{item}}) {
357 my $v = $args{item}{$k};
358 $payload{Key}{$k} = { type_for_value($v) => $v };
359 }
360 foreach my $k (keys %{$args{fields}}) {
361 my $v = $args{fields}{$k};
362 $payload{AttributeUpdates}{$k} = {
363 Action => $args{action} || 'PUT',
364 Value => { type_for_value($v) => $v }
365 };
366 }
367  
368 my $req = $self->make_request(
369 target => 'UpdateItem',
370 payload => \%payload,
371 )->then(sub {
372 $self->_request(shift)->transform(
373 done => sub { $self->json->decode(shift) }
374 );
375 })
376 }
377  
378 =head2 delete_item
379  
380 Deletes a single item from the table.
381  
382 Takes the following named parameters:
383  
384 =over 4
385  
386 =item * table - the table name
387  
388 =item * item - the item to delete, as a { key => value } hashref
389  
390 =back
391  
392 =cut
393  
394 sub delete_item {
395 my $self = shift;
396 my %args = @_;
397  
398 my %payload = (
399 TableName => $args{table},
400 ReturnConsumedCapacity => $args{capacity} ? 'TOTAL' : 'NONE',
401 );
402 foreach my $k (keys %{$args{item}}) {
403 my $v = $args{item}{$k};
404 $payload{Key}{$k} = { type_for_value($v) => $v };
405 }
406  
407 my $req = $self->make_request(
408 target => 'DeleteItem',
409 payload => \%payload,
410 )->then(sub {
411 $self->_request(shift)->transform(
412 done => sub { $self->json->decode(shift) }
413 );
414 })
415 }
416  
417 =head2 batch_get_item
418  
419 Retrieve a batch of items from one or more tables.
420  
421 Takes a coderef which will be called for each found item, followed by
422 these named parameters:
423  
424 =over 4
425  
426 =item * items - the search spec, as { table => { attribute => 'value', ... }, ... }
427  
428 =back
429  
430 =cut
431  
432 sub batch_get_item {
433 my $self = shift;
434 my $code = shift;
435 my %args = @_;
436 my %payload = (
437 ReturnConsumedCapacity => $args{capacity} ? 'TOTAL' : 'NONE',
438 );
439 for my $tbl (keys %{$args{items}}) {
440 my $item = $args{items}{$tbl};
441 my @keys = @{$item->{keys}};
442 $payload{RequestItems}{$tbl}{Keys} = [];
443 while(my ($k, $v) = splice @keys, 0, 2) {
444 push @{$payload{RequestItems}{$tbl}{Keys}}, {
445 $k => {
446 type_for_value($v) => $v
447 }
448 };
449 }
450 }
451  
452 my $finished = 0;
453 try_repeat {
454 my $req = $self->make_request(
455 target => 'BatchGetItem',
456 payload => \%payload,
457 )->then(sub {
458 $self->_request(shift)
459 })->on_done(sub {
460 my $rslt = shift;
461 my $data = $self->json->decode($rslt);
462 my @resp = %{$data->{Responses}};
463 # { Something => [ { Name => { S => 'text' } } ] }
464 while(my ($k, $v) = splice @resp, 0, 2) {
465 for my $entry (@$v) {
466 $code->($k => {
467 map {; $_ => values %{$entry->{$_}} } keys %$entry
468 });
469 }
470 }
471 $args{RequestItems} = $data->{UnprocessedKeys};
472 $finished = 1 unless keys %{$data->{UnprocessedKeys}};
473 });
474 } until => sub { $finished };
475 }
476  
477 =head2 scan
478  
479 Scan a table for values with an optional filter expression.
480  
481 =cut
482  
483 sub scan {
484 my $self = shift;
485 my $code = shift;
486 my %args = @_;
487 my %payload = (
488 TableName => $args{table},
489 ReturnConsumedCapacity => $args{capacity} ? 'TOTAL' : 'NONE',
490 );
491 $payload{AttributesToGet} = $args{fields};
492 $payload{Limit} = $args{limit} if exists $args{limit};
493 my %filter;
494 for my $f (@{$args{filter}}) {
495 $filter{$f->{field}} = {
496 AttributeValueList => [ {
497 type_for_value($f->{value}) => $f->{value},
498 } ],
499 ComparisonOperator => $f->{compare} || 'EQ',
500 }
501 }
502 $payload{ScanFilter} = \%filter if %filter;
503 my $finished = 0;
504 my $count = 0;
505 try_repeat {
506 $self->make_request(
507 target => 'Scan',
508 payload => \%payload,
509 )->then(sub {
510 $self->_request(shift)
511 })->on_done(sub {
512 my $rslt = shift;
513 my $data = $self->json->decode($rslt);
514 for my $entry (@{$data->{Items}}) {
515 $code->({
516 map {; $_ => values %{$entry->{$_}} } keys %$entry
517 });
518 }
519 $count += $data->{Count};
520 $args{ExclusiveStartKey} = $data->{LastEvaluatedKey};
521 $finished = 1 unless keys %{$data->{LastEvaluatedKey}};
522 });
523 } until => sub { $finished };
524 }
525  
526 =head1 METHODS - Internal
527  
528 The following methods are intended for internal use and are documented
529 purely for completeness - for normal operations see L</METHODS> instead.
530  
531 =cut
532  
533 sub scope {
534 my $self = shift;
535 join '/', strftime('%Y%m%d', gmtime), $self->region, qw(dynamodb aws4_request)
536 }
537  
538 sub region { shift->{region} //= 'us-west-1' }
539  
540 =head1 FUNCTIONS - Internal
541  
542 =head2 type_for_value
543  
544 Returns an appropriate type (N, S, SS etc.) for the given
545 value.
546  
547 Rules are similar to L<JSON> - if you want numeric, numify (0+$value),
548 otherwise you'll get a string.
549  
550 =cut
551  
552 sub type_for_value {
553 my $v = shift;
554 if(my $ref = reftype($v)) {
555 # An array maps to a sequence
556 if($ref eq 'ARRAY') {
557 my $flags = B::svref_2object(\$v)->FLAGS;
558 # Any refs mean we're sending binary data
559 return 'BS' if grep ref($_), @$v;
560 # Any stringified values => string data
561 return 'SS' if grep $_ & B::SVp_POK, map B::svref_2object(\$_)->FLAGS, @$v;
562 # Everything numeric? Send as a number
563 return 'NS' if @$v == grep $_ & (B::SVp_IOK | B::SVp_NOK), map B::svref_2object(\$_)->FLAGS, @$v;
564 # Default is a string sequence
565 return 'SS';
566 } else {
567 return 'B';
568 }
569 } else {
570 my $flags = B::svref_2object(\$v)->FLAGS;
571 return 'S' if $flags & B::SVp_POK;
572 return 'N' if $flags & (B::SVp_IOK | B::SVp_NOK);
573 return 'S';
574 }
575 }
576  
577 sub validate_table_name {
578 my ($self, $name) = @_;
579 die 'Table name is undefined' unless defined $name;
580 die 'Name too short' if length($name) < 3;
581 die 'Name too long' if length($name) > 255;
582 die 'Invalid characters in name' if $name =~ /[^a-zA-Z0-9_.-]/;
583 return 1;
584 }
585  
586 1;
587  
588 __END__