DynamoDB.pm untested

filter: Statementstmt 0.0% 0 / 109 Branchbran 0.0% 0 / 22 Conditioncond 0.0% 0 / 22 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 18 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 182 SCAR 50.5
CC
12
Cov
0%
new
72.0
cached_iam_credentials
12.0
make_request
6.0
CRAP 156.0
1 package WebService::Amazon::DynamoDB;
2 # ABSTRACT: Abstract API support for Amazon DynamoDB
3 use strict;
4 use warnings;
5  
6 our $VERSION = '0.004';
7  
8 =head1 NAME
9  
10 WebService::Amazon::DynamoDB - support for the AWS DynamoDB API
11  
12 =head1 VERSION
13  
14 version 0.004
15  
16 =head1 SYNOPSIS
17  
18 # Using access key
19 my $ddb = WebService::Amazon::DynamoDB->new(
20 version => '20120810',
21 access_key => 'access_key',
22 secret_key => 'secret_key',
23 uri => 'http://localhost:8000',
24 );
25 $ddb->batch_get_item(
26 sub {
27 my $tbl = shift;
28 my $data = shift;
29 warn "Batch get: $tbl had " . join(',', %$data) . "\n";
30 },
31 items => {
32 $table_name => {
33 keys => [
34 name => 'some test name here',
35 ],
36 fields => [qw(name age)],
37 }
38 },
39 )->get;
40  
41 # Using the IAM role from the current EC2 instance
42 my $ddb = WebService::Amazon::DynamoDB->new(
43 security => 'iam',
44 );
45 ...
46  
47 # Using a specific IAM role
48 my $ddb = WebService::Amazon::DynamoDB->new(
49 security => 'iam',
50 iam_role => 'role_name',
51 );
52  
53 =head1 BEFORE YOU START
54  
55 B<NOTE>: I'd recommend looking at the L<Amazon::DynamoDB> module first.
56 It is a fork of this one with better features, more comprehensive tests,
57 and overall it's maintained much more actively.
58  
59 =head1 DESCRIPTION
60  
61 Provides a L<Future>-based API for Amazon's DynamoDB REST API.
62 See L<WebService::Amazon::DynamoDB::20120810> for available methods.
63  
64 Current implementations for issuing the HTTP requests:
65  
66 =over 4
67  
68 =item * L<WebService::Async::UserAgent::NaHTTP> - use L<Net::Async::HTTP>
69 for applications based on L<IO::Async> (this gives nonblocking behaviour)
70  
71 =item * L<WebService::Async::UserAgent::LWP> - use L<LWP::UserAgent> (will
72 block, timeouts are unlikely to work)
73  
74 =item * L<WebService::Async::UserAgent::MojoUA> - use L<Mojo::UserAgent>,
75 should be suitable for integration into a L<Mojolicious> application (could
76 be adapted for nonblocking, although the current version does not do this).
77  
78 =back
79  
80 Only the L<Net::Async::HTTP> implementation has had any significant testing or use.
81  
82 =cut
83  
84 use WebService::Amazon::IAM::Client;
85  
86 use WebService::Amazon::DynamoDB::20120810;
87 use Module::Load;
88 use POSIX qw(strftime);
89  
90 use Log::Any qw($log);
91  
92 =head1 METHODS
93  
94 =cut
95  
96 sub new {
97 my $class = shift;
98 my %args = @_;
99 $args{implementation} //= 'WebService::Async::UserAgent::NaHTTP';
100 unless(ref $args{implementation}) {
101 $log->debugf("Loading module for HTTP implementation [%s]", $args{implementation});
102 Module::Load::load($args{implementation});
103 $log->debugf("Instantiating [%s]", $args{implementation});
104 $args{implementation} = $args{implementation}->new(
105 (exists $args{loop} ? (loop => delete $args{loop}) : ())
106 );
107 }
108 my $version = delete $args{version} || '20120810';
109 my $pkg = __PACKAGE__ . '::' . $version;
110 $log->debugf("Look for ->new in [%s]", $pkg);
111 if(my $code = $pkg->can('new')) {
112 $class = $pkg if $class eq __PACKAGE__;
113 $args{security} ||= 'key';
114 $args{region} ||= 'us-west-1';
115 $args{iam_role} = Future->done($args{iam_role}) if exists $args{iam_role} && !ref $args{iam_role};
116 if(exists $args{host} or exists $args{port}) {
117 $args{uri} = URI->new('http://' . $args{host} . ':' . $args{port});
118 } else {
119 $args{uri} ||= 'https://dynamodb.' . $args{region} . '.amazonaws.com/';
120 $args{uri} = URI->new($args{uri}) unless ref $args{uri};
121 }
122 return $code->($class, %args)
123 }
124 die "No support for version $version";
125 }
126  
127 sub security { shift->{security} }
128  
129 sub uri { shift->{uri} }
130  
131 sub api_version { ... }
132  
133 =head2 make_request
134  
135 Generates an L<HTTP::Request>.
136  
137 =cut
138  
139 sub make_request {
140 my $self = shift;
141 my %args = @_;
142 my $target = $args{target};
143 my $js = JSON::MaybeXS->new;
144 my $req = HTTP::Request->new(
145 POST => $self->uri
146 );
147 $req->header( host => $self->uri->host );
148 my $http_date = strftime('%a, %d %b %Y %H:%M:%S %Z', localtime);
149 $req->protocol('HTTP/1.1');
150 $req->header( 'Date' => $http_date );
151 $req->header( 'x-amz-date' => strftime('%Y%m%dT%H%M%SZ', gmtime) );
152 $req->header( 'x-amz-target', 'DynamoDB_'. $self->api_version. '.'. $target );
153 $req->header( 'content-type' => 'application/x-amz-json-1.0' );
154 my $payload = $js->encode($args{payload});
155 $req->content($payload);
156 $req->header( 'Content-Length' => length($payload));
157 $self->credentials->then(sub {
158 my ($creds) = @_;
159 # Don't show these by default
160 # $log->debugf("Using [%s] for credentials", $creds);
161 my $token = delete $creds->{token};
162 my $amz = WebService::Amazon::Signature->new(
163 version => 4,
164 algorithm => $self->algorithm,
165 scope => $self->scope,
166 %$creds,
167 );
168 $amz->from_http_request($req);
169 $req->header(Authorization => $amz->calculate_signature);
170 $req->header('X-Amz-Security-Token' => $token) if defined $token;
171 Future->done($req)
172 })
173 }
174  
175 sub credentials {
176 my ($self) = @_;
177 if($self->security eq 'key') {
178 $log->debugf("Using key-based security");
179 # We don't bother caching the hashref, since we'd need to be passing
180 # a copy anyway (caller may change the values)
181 return Future->done({
182 access_key => $self->access_key,
183 secret_key => $self->secret_key,
184 })
185 }
186  
187 return $self->cached_iam_credentials->else(sub {
188 $log->debug("No cached credentials (or already expired)");
189 $self->find_iam_role->then(sub {
190 my ($role) = @_;
191 $log->debugf("Found role [%s]", $role);
192 $self->retrieve_iam_credentials(
193 $role
194 )
195 })
196 });
197 }
198  
199 sub cached_iam_credentials {
200 my ($self) = @_;
201 return Future->fail('no cached credentials') unless exists $self->{cached_iam_credentials};
202  
203 # Assume expired if we're within 5 seconds
204 return Future->fail('cached credentials expire') if $self->{cached_iam_credentials}{expire_at} <= time - 5;
205  
206 # Shallow copy, so we're not affected if the caller changes the values
207 return Future->done({
208 %{ $self->{cached_iam_credentials}{details} }
209 })
210 }
211  
212 sub find_iam_role {
213 my ($self) = @_;
214 $self->{iam_role} //= $self->iam->active_roles
215 }
216  
217 sub retrieve_iam_credentials {
218 my ($self, $role) = @_;
219 $self->iam->credentials_for_role($role)->then(sub {
220 my ($creds, $expiry) = @_;
221 $log->debugf("New credentials received, will expire in %s seconds", strftime '%H:%M:%S', gmtime($expiry - time));
222 $self->{cached_iam_credentials} = {
223 expire_at => $expiry,
224 details => $creds
225 };
226 # Shallow copy, so we're not affected if the caller changes the values
227 Future->done({ %$creds })
228 })
229 }
230  
231 sub _request {
232 my $self = shift;
233 my $req = shift;
234 # Don't show requests by default
235 # $log->debugf("Issuing request [%s]", $req->as_string("\n"));
236 $self->implementation->request($req)
237 }
238  
239 sub iam {
240 $_[0]->{iam} //= WebService::Amazon::IAM::Client->new(
241 ua => $_[0]->implementation,
242 )
243 }
244  
245 1;
246  
247 __END__