MongoDB.pm

filter: Statementstmt 31.0% 32 / 103 Branchbran 0.0% 0 / 20 Conditioncond 0.0% 0 / 9 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 32.0% 8 / 25 Podpod 0.0% 0 / 8 totaltotal 23.3% 40 / 171 CC 15 SCAR 19.4
CC
15
Cov
24%
store
20.0
BUILD
12.0
fetch
12.0
CRAP 7.0
↑ Summary MongoDB/t/CHIDriverTests.pm »
1 package CHI::Driver::MongoDB;
2 # vim:syntax=perl:tabstop=4:number:noexpandtab:
3 1 $CHI::Driver::MongoDB::VERSION = '0.0100';
4 # ABSTRACT: MongoDB driver for CHI
5  
6 1 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use MongoDB;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use BSON;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use BSON::Types qw( bson_bytes bson_time );
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use URI::Escape::XS;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 1 extends 'CHI::Driver';
17  
18 1 has 'mongodb' => (
19 is => 'ro',
20 lazy => 1,
21 init_arg => undef,
22 builder => '_build_mongodb',
23 );
24  
25 has 'mongodb_options' => (
26 is => 'rw',
27 0 ▶ default => sub { {} },
Subroutine __ANON__: not called CC=1 SCAR=6.9
28 1 );
29  
30 has 'connection_uri' => (
31 is => 'ro',
32 lazy => 1,
33 0 ▶ default => sub { 'mongodb://127.0.0.1:27017' },
Subroutine __ANON__: not called CC=1 SCAR=6.9
34 1 );
35  
36 has 'db_name' => (
37 is => 'ro',
38 lazy => 1,
39 0 ▶ default => sub {'_CHI_'},
Subroutine __ANON__: not called CC=1 SCAR=6.9
40 1 );
41  
42 1 has '_coll' => (
43 is => 'rw',
44 lazy => 1,
45 predicate => 1,
46 init_arg => undef,
47 builder => '_build_coll',
48 clearer => 1,
49 );
50  
51  
52 sub BUILD {
53 0 ▶ my ( $self, $params ) = @_;
Subroutine BUILD: not called CC=3 SCAR=24.8
Pod undocumented
54 0 foreach my $param (qw/ mongodb_options connection_uri db_name /) {
55 0 ▶ if ( exists $params->{$param} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params->{$param}) 0 0 0
56 0 delete $params->{$param};
57 }
58 }
59  
60 my %options = (
61 0 %{ $self->mongodb_options() },
62 0 %{ $self->non_common_constructor_params($params) },
63 );
64 0 $self->mongodb_options( \%options );
65 }
66  
67  
68 sub _build_mongodb {
69 0 ▶ my $self = shift;
Subroutine _build_mongodb: not called CC=1 SCAR=6.9
70  
71 0 my %opts = %{ $self->mongodb_options() };
72 0 my $uri = $self->connection_uri;
73  
74 0 return MongoDB->connect( $uri, \%opts );
75 }
76  
77  
78 sub _build_coll {
79 0 ▶ my $self = shift;
Subroutine _build_coll: not called CC=2 SCAR=17.9
80  
81 0 my $ns = sprintf( "%s.%s", $self->db_name, encodeURIComponent( $self->namespace ) );
82  
83 0 my $coll = $self->mongodb->get_namespace($ns);
84  
85 0 ▶ if ( $self->expires_on_backend ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->expires_on_backend) 0 0 0
86 0 $coll->indexes->create_one( [ expireAt => 1 ], { expireAfterSeconds => 0 } );
87 }
88  
89 0 return $coll;
90 }
91  
92  
93 sub fetch {
94 0 ▶ my ( $self, $key ) = @_;
Subroutine fetch: not called CC=3 SCAR=24.8
Pod undocumented
95  
96 0 $key = encodeURIComponent($key);
97 0 my $doc = $self->_coll->find_id( $key, { payload => 1 } );
98  
99 0 ▶ return "" . $doc->{'payload'} if defined($doc) and ref($doc) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if defined $doc and ref $doc eq "HASH" 0 0 0
Condition0%0/3
defined $doc and ref $doc eq "HASH"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $doc and ref $doc eq "HASH"
defined $doc ref $doc eq "HASH"
Truth table0%0/3
A and B
A= defined $docB= ref $doc eq "HASH"
ABresult
0X0
100
111
100 0 return undef;
101 }
102  
103  
104 sub fetch_multi_hashref {
105 0 ▶ my ( $self, $keys ) = @_;
Subroutine fetch_multi_hashref: not called CC=2 SCAR=17.9
Pod undocumented
106  
107 0 my @esc = map { encodeURIComponent($_) } @{$keys};
108 0 my $qresult = $self->_coll->find(
109 { _id => { '$in' => \@esc } },
110 {
111 batchSize => 100,
112 projection => {
113 _id => 1,
114 payload => 1
115 }
116 }
117 )->result;
118  
119 0 my %ret = ();
120 0 ▶ while ( my @batch = $qresult->batch ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@batch) = $qresult->batch) 0 0 0
121 0 map { my $k = decodeURIComponent( $_->{'_id'} ); $ret{$k} = "" . $_->{'payload'} } @batch;
122 }
123  
124 0 return \%ret;
125 }
126  
127  
128 sub store {
129 0 ▶ my ( $self, $key, $data, $expires_in ) = @_;
Subroutine store: not called CC=4 SCAR=30.0
Pod undocumented
130  
131 0 $key = encodeURIComponent($key);
132 0 my $doc = {
133 _id => $key,
134 payload => bson_bytes($data),
135 };
136 0 ▶ if ( defined $expires_in ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $expires_in) 0 0 0
137 0 $doc->{'expireAt'} = bson_time( time() + $expires_in );
138 }
139 0 my $result = $self->_coll->update_one( { _id => $key }, { '$set' => $doc }, { upsert => 1 } );
140  
141 0 ▶ warn "update_one() operation failed: unexpected result"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $result eq "MongoDB::UnacknowledgedResult" or ref $result eq "MongoDB::UpdateResult" 0 0 0
Condition0%0/3
ref $result eq "MongoDB::UnacknowledgedResult" or ref $result eq "MongoDB::UpdateResult"
l!l&&r!l&&!r
000
MC/DC0%0/2
ref $result eq "MongoDB::UnacknowledgedResult" or ref $result eq "MongoDB::UpdateResult"
ref $result eq "MongoDB::UnacknowledgedResult" ref $result eq "MongoDB::UpdateResult"
Truth table0%0/3
A or B
A= ref $result eq "MongoDB::UnacknowledgedResult"B= ref $result eq "MongoDB::UpdateResult"
ABresult
1X1
011
000
142 unless ref($result) eq 'MongoDB::UnacknowledgedResult'
143 or ref($result) eq 'MongoDB::UpdateResult';
144 try {
145 0 ▶ $result->assert if $result->acknowledged;
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if $result->acknowledged 0 0 0
146 }
147 catch {
148 0 ▶ warn "update_one() operation failed: deletion not asserted";
Subroutine __ANON__: not called CC=1 SCAR=6.9
149 0 };
150  
151 0 return undef;
152 } ## end sub store
153  
154 # TODO
155 #sub store_multi {
156 # my ( $self, $key_data, $options ) = @_;
157 #}
158  
159  
160 sub remove {
161 0 ▶ my ( $self, $key ) = @_;
Subroutine remove: not called CC=3 SCAR=24.8
Pod undocumented
162  
163 0 $key = encodeURIComponent($key);
164 0 my $result = $self->_coll->delete_one( { _id => $key } );
165  
166 0 ▶ warn "delete_one() operation failed: unexpected result"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $result eq "MongoDB::UnacknowledgedResult" or ref $result eq "MongoDB::DeleteResult" 0 0 0
Condition0%0/3
ref $result eq "MongoDB::UnacknowledgedResult" or ref $result eq "MongoDB::DeleteResult"
l!l&&r!l&&!r
000
MC/DC0%0/2
ref $result eq "MongoDB::UnacknowledgedResult" or ref $result eq "MongoDB::DeleteResult"
ref $result eq "MongoDB::UnacknowledgedResult" ref $result eq "MongoDB::DeleteResult"
Truth table0%0/3
A or B
A= ref $result eq "MongoDB::UnacknowledgedResult"B= ref $result eq "MongoDB::DeleteResult"
ABresult
1X1
011
000
167 unless ref($result) eq 'MongoDB::UnacknowledgedResult'
168 or ref($result) eq 'MongoDB::DeleteResult';
169 try {
170 0 ▶ $result->assert if $result->acknowledged;
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if $result->acknowledged 0 0 0
171 }
172 catch {
173 0 ▶ warn "delete_one() operation failed: deletion not asserted";
Subroutine __ANON__: not called CC=1 SCAR=6.9
174 0 };
175  
176 0 return undef;
177 }
178  
179  
180 sub clear {
181 0 ▶ my ($self) = @_;
Subroutine clear: not called CC=1 SCAR=6.9
Pod undocumented
182  
183 0 my $coll = $self->_coll;
184 0 $self->_clear_coll;
185 0 $coll->drop;
186  
187 0 return undef;
188 }
189  
190  
191 sub get_keys {
192 0 ▶ my ($self) = @_;
Subroutine get_keys: not called CC=2 SCAR=17.9
Pod undocumented
193  
194 0 my @allKeys = ();
195 0 my $qresult = $self->_coll->find(
196 {},
197 {
198 batchSize => 100,
199 projection => { _id => 1 }
200 }
201 )->result;
202 0 ▶ while ( my @batch = $qresult->batch ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@batch) = $qresult->batch) 0 0 0
203 0 push @allKeys, map { decodeURIComponent( $_->{'_id'} ) } @batch;
204 }
205 0 return @allKeys;
206 }
207  
208  
209 sub get_namespaces {
210 0 ▶ my $self = shift;
Subroutine get_namespaces: not called CC=1 SCAR=6.9
Pod undocumented
211 0 return $self->mongodb->get_database( $self->db_name )->collection_names;
212 }
213  
214 1 1;
215  
216 __END__
217  
218 =pod
219  
220 =encoding utf-8
221  
222 =head1 NAME
223  
224 CHI::Driver::MongoDB - MongoDB driver for CHI
225  
226 =head1 VERSION
227  
228 version 0.0100
229  
230 =head1 SYNOPSIS
231  
232 use CHI;
233
234 my $cache = CHI->new (
235 driver => 'MongoDB',
236 namespace => 'foo',
237 # optional, default: _CHI_
238 db_name => '...',
239 # optional, default: mongodb://127.0.0.1:27017
240 connection_uri => '...',
241 # optional
242 mongodb_options => { ... },
243 );
244  
245 =head1 DESCRIPTION
246  
247 Driver to use L<MongoDB> as storage back end for L<CHI>.
248  
249 L<CHI> C<namespace>s are translated to L<MongoDB> collections, so you
250 can use the same database name for all CHI instances (or simply use
251 the default and omit the parameter).
252  
253 The driver supports the C<expires_on_backend> option, but be aware that
254 the expiration actually happens within a short but unspecified time
255 frame B<after> the exact expiration timeout (cf. L</"FAILING TESTS">).
256  
257 By default the MongoDB server is expected to be available on localhost,
258 port 27017. Pass the C<connection_uri> param to override this.
259 For testing purposes, set the C<MONGODB_CONNECTION_URI> environment
260 variable.
261  
262 =head1 WARNING
263  
264 Because of the not fully understood test failures this module is
265 still considered to be a B<beta release>.
266  
267 On the other hand I have never received any reports - which either
268 means that nobody uses it or that it does work as intended ;-)
269  
270 Please open a bug report on L<https://rt.perl.org/> or send me a
271 mail if you encounter any problems.
272  
273 =head1 CONSTRUCTOR OPTIONS
274  
275 =over 4
276  
277 =item C<connection_uri>: String
278  
279 Where the MongoDB server is listening. By default,
280 C<mongodb://127.0.0.1:27017> is used.
281  
282 See L<MongoDB::MongoClient/"CONNECTION-STRING-URI"> for details.
283  
284 =item C<db_name>: String
285  
286 The database name inside MongoDB. Defaults to C<_CHI_>.
287 The name is arbitrary but should of course not clash with your other
288 databases.
289  
290 =item C<mongodb_options>: HASHREF
291  
292 Arbitrary options which are passed to the constructor of the underlying
293 L<MongoDB::MongoClient> object.
294  
295 =back
296  
297 =head1 FAILING TESTS
298  
299 Currently, you should expect four failing tests from the CHI test suite:
300 94, 205-206, 904.
301  
302 =over 4
303  
304 =item B<94>: C<Failed test 'threw Regexp ((?^:discard timeout .* reached))'>
305  
306 I do not know yet, why the test functions succeeds while it is supposed
307 to C<die>.
308  
309 =item B<205>: C<Failed test 'cannot get_object(key0) after expire'>
310  
311 =item B<206>: C<Failed test 'cannot get_object(key1) after expire'>
312  
313 MongoDB uses a dedicated thread to remove documents whose lifetime has
314 expired. It checks the stored documents periodically but that means
315 there is a short period of time between the moment a document expires
316 and the moment it is actually removed.
317 This should be no problem for our caching purposes but is the reason
318 why these tests fail.
319  
320 =item B<904> C<Failed test 'test_serializers died (Insecure dependency in eval while running with -T switch...>
321  
322 No idea yet what is wrong here.
323  
324 =back
325  
326 Fixing the second and third failing test may not be possible at all,
327 but I haven't yet found a way to disable indiviual tests.
328  
329 Other than these four, 944 subtests succeed while 67 are skipped.
330  
331 I have seen test runs where for some unknown reason a large number of
332 tests fail. I do not know why that happens. The MongoDB database is
333 dropped and recreated on every run of the test suite.
334 On simply re-running the whole test usually only the four tests shown
335 above fail.
336  
337 =head1 TODO
338  
339 In no particular order:
340  
341 =over 4
342  
343 =item Allow passing in a preconfigured L<MongoDB> object.
344  
345 =item Allow using L<Mango> instead of L<MongoDB>.
346  
347 =item Implement C<store_multi ( $key_data, $options )> method.
348  
349 =item Implement LRU discard policy.
350  
351 =item Implement support for size awareness in the back end.
352  
353 B<Caveat>: As of version 3.2 MongoDB supports collections that either
354 have a finite size (in bytes or in number of stored documents) or
355 support the automatic expiration handling but not both!
356  
357 =back
358  
359 =head1 SEE ALSO
360  
361 L<CHI>, L<CHI::Driver::Development>, L<MongoDB>
362  
363 =head1 AUTHOR
364  
365 Heiko Jansen <hjansen@cpan.org>
366  
367 =head1 COPYRIGHT AND LICENSE
368  
369 This software is copyright (c) 2018 by Heiko Jansen.
370  
371 This is free software; you can redistribute it and/or modify it under
372 the same terms as the Perl 5 programming language system itself.
373  
374 =cut
↑ Summary MongoDB/t/CHIDriverTests.pm »