KiokuDB/Backend/CouchDB.pm

filter: Statementstmt 25.0% 51 / 204 Branchbran 0.0% 0 / 70 Conditioncond 0.0% 0 / 28 MC/DCmcdc 0.0% 0 / 17 Subroutinesub 52.0% 13 / 25 Podpod 0.0% 0 / 9 totaltotal 18.1% 64 / 353 CC 58 SCAR 54.9
CC
58
Cov
17%
get_from_storage
455.1
commit_entries
417.9
find_meta
56.0
CRAP 242.8
↑ Summary KiokuX/CouchDB/Role/View.pm »
1 #!/usr/bin/perl
2  
3 package KiokuDB::Backend::CouchDB;
4 1 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use Moose::Util::TypeConstraints;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use Data::Stream::Bulk::Util qw(bulk);
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 1 ▶use AnyEvent::CouchDB;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use Carp 'confess';
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use List::MoreUtils qw{ any };
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use Time::HiRes qw/gettimeofday tv_interval/;
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 1 ▶use KiokuDB::Backend::CouchDB::Exceptions;
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 1 ▶use namespace::clean -except => 'meta';
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 1 our $VERSION = '0.16';
19  
20 # TODO Read revision numbers into rev field and use for later conflict resolution
21  
22 1 with qw(
23 KiokuDB::Backend
24 KiokuDB::Backend::Serialize::JSPON
25 KiokuDB::Backend::Role::UnicodeSafe
26 KiokuDB::Backend::Role::Clear
27 KiokuDB::Backend::Role::Scan
28 KiokuDB::Backend::Role::Query::Simple::Linear
29 KiokuDB::Backend::Role::TXN::Memory
30 KiokuDB::Backend::Role::Concurrency::POSIX
31 );
32  
33 # TODO Remove TXN::Memory or ensure that it works as it should
34  
35 1 has create => (
36 isa => "Bool",
37 is => "ro",
38 default => 0,
39 );
40  
41 1 has conflicts => (
42 is => 'rw',
43 isa => enum([qw{ overwrite confess ignore throw }]),
44 default => 'throw'
45 );
46
47  
48 0 ▶sub BUILD {
Subroutine BUILD: not called CC=5 SCAR=34.0
Pod undocumented
49 0 my $self = shift;
50  
51 0 ▶ if ( $self->create ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->create) 0 0 0
52 0 my $e = do {local $@; eval { $self->db->create->recv }; $@ };
53  
54 # Throw errors except if its because the database already exists
55 0 ▶ if ( $e ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($e) 0 0 0
56 0 ▶ if ( my($error) = grep { exists $_->{error} } @$e ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my($error) = grep({exists $_->{"error"};} @$e)) 0 0 0
57 0 ▶ if( $error->{error} ne 'file_exists' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($error->{"error"} ne "file_exists") 0 0 0
58 0 die "$error->{error}: $error->{reason}";
59 }
60 }
61 }
62 }
63 }
64  
65 1 has db => (
66 isa => "AnyEvent::CouchDB::Database",
67 is => "ro",
68 handles => [qw(document)],
69 );
70  
71 1 has '+id_field' => ( default => "_id" );
72 1 has '+class_field' => ( default => "class" );
73 1 has '+class_meta_field' => ( default => "class_meta" );
74 1 has '+deleted_field' => ( default => "_deleted" );
75  
76 1 our @couch_meta_fields = qw{ _rev _attachments _conflicts };
77  
78  
79 0 ▶sub delete {
Subroutine delete: not called CC=4 SCAR=30.0
Pod undocumented
80 0 my ( $self, @ids_or_entries ) = @_;
81
82 0 my $db = $self->db;
83
84 0 warn "Remove: ", join(', ', @ids_or_entries);
85
86 0 for(@ids_or_entries) {
87 0 ▶ if(blessed($_)) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($_)) { } 0 0 0
88 0 my $meta = $self->find_meta($_);
89 $db->remove_doc({
90 _id => $_->id,
91 0 ▶ ($meta->{_rev} ? (_rev => $meta->{_rev}) : ())
Branch: 1 branch
BranchTrueFalseTotal
$meta->{'_rev'} ? : 0 0 0
92 });
93 } else {
94 0 $db->remove_doc({_id => $_});
95 }
96 }
97
98 0 return;
99 }
100  
101 0 ▶sub new_from_dsn_params {
Subroutine new_from_dsn_params: not called CC=2 SCAR=17.9
Pod undocumented
102 0 my ( $self, %args ) = @_;
103  
104 my $db = exists $args{db}
105 ? couch($args{uri})->db($args{db})
106 0 ▶ : couchdb($args{uri});
Branch: 1 branch
BranchTrueFalseTotal
exists $args{'db'} ? : 0 0 0
107
108 0 $self->new(%args, db => $db);
109 }
110  
111 # Collect metadata for a given entry
112 0 ▶sub find_meta {
Subroutine find_meta: not called CC=7 SCAR=40.3
Pod undocumented
113 0 my ( $self, $entry ) = @_;
114 0 my $meta;
115  
116 0 my $prev = $entry;
117 # Go backwards in history to collect metadata
118 # TODO Consider whether this should be necessary - why not store this in every entry?
119 0 ▶ while($prev and any {not exists $meta->{$_}} @couch_meta_fields) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
if ($prev and &any(sub { not exists $meta->{$_}; } , @KiokuDB::Backend::CouchDB::couch_meta_fields)) 0 0 0
Condition0%0/3
$prev and &any(sub { not exists $meta->{$_}; } , @KiokuDB::Backend::CouchDB::couch_meta_fields)
!ll&&!rl&&r
000
MC/DC0%0/2
$prev and &any(sub { not exists $meta->{$_}; } , @KiokuDB::Backend::CouchDB::couch_meta_fields)
$prev &any(sub { not exists $meta->{$_}; } , @KiokuDB::Backend::CouchDB::couch_meta_fields)
Truth table0%0/3
A and B
A= $prevB= &any(sub { not exists $meta->{$_}; } , @KiokuDB::Backend::CouchDB::couch_meta_fields)
ABresult
0X0
100
111
120 0 ▶ if(my $backend_data = $prev->backend_data) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $backend_data = $prev->backend_data) 0 0 0
121 0 for(@couch_meta_fields) {
122 $meta->{$_} = $backend_data->{$_}
123 0 ▶ if $backend_data->{$_} and not exists $meta->{$_};
Branch: 1 branch
BranchTrueFalseTotal
if $backend_data->{$_} and not exists $meta->{$_} 0 0 0
Condition0%0/3
$backend_data->{$_} and not exists $meta->{$_}
!ll&&!rl&&r
000
MC/DC0%0/2
$backend_data->{$_} and not exists $meta->{$_}
$backend_data->{$_} not exists $meta->{$_}
Truth table0%0/3
A and not(B)
A= $backend_data->{$_}B= not exists $meta->{$_}
ABresult
0X0
100
111
124 }
125 }
126 0 $prev = $prev->prev;
127 }
128
129 0 return $meta;
130 }
131  
132 0 ▶sub commit_entries {
Subroutine commit_entries: not called CC=21 SCAR=60.4
Pod undocumented
133 0 my ( $self, @entries ) = @_;
134
135 0 my @docs;
136 0 my $db = $self->db;
137
138 0 my $start = [ gettimeofday ];
139  
140 0 foreach my $entry ( @entries ) {
141
142 0 my $meta = $self->find_meta($entry);
143
144 0 my $collapsed = $self->collapse_jspon($entry);
145  
146 0 for(@couch_meta_fields) {
147 $collapsed->{$_} = $meta->{$_}
148 0 ▶ if $meta->{$_}
Branch: 1 branch
BranchTrueFalseTotal
if $meta->{$_} 0 0 0
149 }
150
151 0 push @docs, $collapsed;
152  
153 0 $entry->backend_data($collapsed);
154  
155 }
156  
157 # TODO couchdb <= 0.8 (possibly 0.9 too) will return a hash ref here, which will fail. Detect and handle.
158 0 my $data = $self->db->bulk_docs(\@docs)->recv;
159  
160 0 ▶ if ( my @errors = grep { exists $_->{error} } @$data ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@errors) = grep({exists $_->{"error"};} @$data)) 0 0 0
161  
162 0 ▶ if($self->conflicts eq 'confess') {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->conflicts eq 'confess') { } 0 0 0
elsif ($self->conflicts eq 'overwrite' or $self->conflicts eq 'throw') { } 0 0 0
163 1 ▶ no warnings 'uninitialized';
Subroutine BEGIN: called CC=1 SCAR=0.0
164 0 confess "Errors in update: " . join(", ", map { "$_->{error} (on ID $_->{id} ($_->{rev}, $_->{error}, $_->{reason}))" } @errors);
165 ▶ } elsif($self->conflicts eq 'overwrite' or $self->conflicts eq 'throw') {
Condition0%0/3
$self->conflicts eq "overwrite" or $self->conflicts eq "throw"
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->conflicts eq "overwrite" or $self->conflicts eq "throw"
$self->conflicts eq "overwrite" $self->conflicts eq "throw"
Truth table0%0/3
A or B
A= $self->conflicts eq "overwrite"B= $self->conflicts eq "throw"
ABresult
1X1
011
000
166 0 my %conflicts;
167 my @conflicts;
168 0 my @other_errors;
169 0 for(@errors) {
170 0 ▶ if($_->{error} eq 'conflict') {
Branch: 1 branch
BranchTrueFalseTotal
if ($_->{'error'} eq 'conflict') { } 0 0 0
171 0 push @conflicts, $_->{id};
172 } else {
173 0 push @other_errors, $_;
174 }
175 }
176 0 ▶ if(@other_errors) {
Branch: 1 branch
BranchTrueFalseTotal
if (@other_errors) 0 0 0
177 0 confess "Errors in update: " . join(", ", map { "$_->{error} (on ID $_->{id} ($_->{rev}))" } @other_errors);
178 }
179
180 # Updating resulted in conflicts that we handle by overwriting the change
181 0 my $old_docs = $db->open_docs([@conflicts], {conflicts => 'true'})->recv;
182 0 ▶ if(exists $old_docs->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $old_docs->{"error"}) 0 0 0
183 0 confess "Updating ids ", join(', ', @conflicts), " failed during conflict resolution: $old_docs->{error}.";
184 }
185 0 my @old_docs = @{$old_docs->{rows}};
186  
187 0 ▶ if($self->conflicts eq 'overwrite') {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->conflicts eq 'overwrite') { } 0 0 0
188 0 my @re_update_docs;
189 0 foreach my $old_doc (@old_docs) {
190 0 my($new_doc) = grep {$old_doc->{doc}{_id} eq $_->{_id}} @docs;
191 0 $new_doc->{_rev} = $old_doc->{doc}{_rev};
192 0 push @re_update_docs, $new_doc;
193 }
194 # Handle errors that has arised when trying the second update
195 0 ▶ if(@errors = grep { exists $_->{error} } @{$self->db->bulk_docs(\@re_update_docs)->recv}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@errors = grep({exists $_->{"error"};} @{$self->db->bulk_docs(\@re_update_docs)->recv;})) 0 0 0
196 confess "Updating ids ", join(', ', @conflicts), " failed during conflict resolution: ",
197 0 join(', ', map { $_->{error} . ' on ' . $_->{id} } @errors);
198 }
199 } else { # throw
200 0 my $conflicts = [];
201 0 my %docs;
202 0 for(@docs) {
203 0 $docs{$_->{_id}} = $_;
204 }
205 0 ▶ for(my $i=0; $i < @conflicts; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @conflicts) 0 0 0
206 push @$conflicts, {
207 new => $docs{$conflicts[$i]}->{data},
208 old => $old_docs[$i]->{doc}{data}
209 0 };
210 }
211 0 KiokuDB::Backend::CouchDB::Exception::Conflicts->throw(
212 conflicts => $conflicts,
213 error => 'Conflict while storing objects'
214 );
215 }
216 }
217 # $self->conflicts eq 'ignore' here, so don't do anything
218 }
219  
220 0 foreach my $rev ( map { $_->{rev} } @$data ) {
221 0 ( shift @docs )->{_rev} = $rev;
222 }
223  
224 0 ▶ if ($ENV{KIOKU_COUCH_TRACE}){
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{"KIOKU_COUCH_TRACE"}) 0 0 0
225 0 my $end = [ gettimeofday ];
226 0 warn "[KIOKU COUCH TRACE] KiokuDB::Backend::CouchDB::commit_entries() [", tv_interval($start, $end),"s]:\n";
227 0 ▶ warn "[KIOKU COUCH TRACE] ".$_->id.', ['.($_->class || '')."]\n" for @entries;
Condition0%0/2
$_->class || ''
l!l
00
MC/DC0%0/1
$_->class || ''
$_->class
Truth table0%0/2
A
A= $_->class
Aresult
11
00
228 }
229 }
230  
231 0 ▶sub get_from_storage {
Subroutine get_from_storage: not called CC=23 SCAR=61.2
Pod undocumented
232 0 my ( $self, @ids ) = @_;
233  
234 0 my @result;
235  
236 0 my $error_count = 0;
237 0 my $max_errors = 2;
238 0 my $retry_delay = 5;
239 0 my $data;
240 my $error;
241 0 my $start = [ gettimeofday ];
242 0 ▶ while(not $data and $error_count <= $max_errors) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $data and $error_count <= $max_errors) 0 0 0
Condition0%0/3
not $data and $error_count <= $max_errors
!ll&&!rl&&r
000
MC/DC0%0/2
not $data and $error_count <= $max_errors
not $data $error_count <= $max_errors
Truth table0%0/3
not(A) and B
A= not $dataB= $error_count <= $max_errors
ABresult
0X0
100
111
243 0 $error = undef;
244 0 ▶ try { $data = $self->db->open_docs(\@ids)->recv }
Subroutine __ANON__: not called CC=1 SCAR=6.9
245 0 ▶ catch { $error_count++; $error = $_ };
Subroutine __ANON__: not called CC=1 SCAR=6.9
246
247 # Always retry immediately after first failed connect, then apply delay
248 0 ▶ sleep $retry_delay if $error_count > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $error_count > 1 0 0 0
249
250 0 ▶ if(not $error and not $data) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($error or $data) 0 0 0
Condition0%0/3
$error or $data
l!l&&r!l&&!r
000
MC/DC0%0/2
$error or $data
$error $data
Truth table0%0/3
A or B
A= $errorB= $data
ABresult
1X1
011
000
251 0 die "Call to CouchDB returned false ($data)";
252 }
253 }
254 0 ▶ die $error->[0]{Reason} if ref $error eq 'ARRAY' and ref $error->[0] eq 'HASH' and $error->[0]{Reason};
Branch: 1 branch
BranchTrueFalseTotal
if ref $error eq "ARRAY" and ref $error->[0] eq "HASH" and $error->[0]{"Reason"} 0 0 0
Condition0%0/6
ref $error eq "ARRAY" and ref $error->[0] eq "HASH" and $error->[0]{"Reason"}
!ll&&!rl&&r
000
ref $error eq "ARRAY" and ref $error->[0] eq "HASH"
!ll&&!rl&&r
000
MC/DC0%0/3
ref $error eq "ARRAY" and ref $error->[0] eq "HASH" and $error->[0]{"Reason"}
ref $error eq "ARRAY" ref $error->[0] eq "HASH" $error->[0]{"Reason"}
Truth table0%0/4
A and B and C
A= ref $error eq "ARRAY"B= ref $error->[0] eq "HASH"C= $error->[0]{"Reason"}
ABCresult
0XX0
10X0
1100
1111
255 0 ▶ die $error if $error;
Branch: 1 branch
BranchTrueFalseTotal
if $error 0 0 0
256  
257 die('Invalid response from CouchDB (rows missing or not array)', $data)
258 0 ▶ unless $data->{rows} and ref $data->{rows} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless $data->{"rows"} and ref $data->{"rows"} eq "ARRAY" 0 0 0
Condition0%0/3
$data->{"rows"} and ref $data->{"rows"} eq "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/2
$data->{"rows"} and ref $data->{"rows"} eq "ARRAY"
$data->{"rows"} ref $data->{"rows"} eq "ARRAY"
Truth table0%0/3
A and B
A= $data->{"rows"}B= ref $data->{"rows"} eq "ARRAY"
ABresult
0X0
100
111
259  
260 0 my @deleted;
261 my @not_found;
262 0 my @unknown;
263 0 my @errors;
264 0 my @docs;
265 0 for(@{ $data->{rows} }) {
266 0 ▶ if($_->{doc} ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($_->{'doc'}) { } 0 0 0
elsif ($_->{'value'}{'deleted'}) { } 0 0 0
elsif (my $error = $_->{'error'}) { } 0 0 0
267 # TODO We may have to check if $_->{doc} has a valid value and treat as error otherwise
268 0 push @docs, $_->{doc};
269 } elsif($_->{value}{deleted}) {
270 0 push @deleted, $_;
271 } elsif(my $error = $_->{error}) {
272 0 ▶ if($error eq 'not_found') {
Branch: 1 branch
BranchTrueFalseTotal
if ($error eq 'not_found') { } 0 0 0
273 0 push @not_found, $_;
274 } else {
275 0 push @errors, $_;
276 }
277 } else {
278 0 push @unknown, $_;
279 }
280 }
281 0 ▶ if(@errors) {
Branch: 1 branch
BranchTrueFalseTotal
if (@errors) 0 0 0
282 1 ▶ use Data::Dump 'pp';
Subroutine BEGIN: called CC=1 SCAR=0.0
283 0 die 'Error on fetch from CouchDB.', pp @errors;
284 }
285 0 ▶ if(@unknown) {
Branch: 1 branch
BranchTrueFalseTotal
if (@unknown) 0 0 0
286 1 ▶ use Data::Dump 'pp';
Subroutine BEGIN: called CC=1 SCAR=0.0
287 0 die 'Unknown response from CouchDB.', pp @unknown;
288 }
289  
290 # TODO What to do with deleted entries?
291 # TODO What to do with entries not found?
292
293 0 ▶ if ($ENV{KIOKU_COUCH_TRACE}){
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{"KIOKU_COUCH_TRACE"}) 0 0 0
294 0 my $end = [ gettimeofday ];
295 0 warn "[KIOKU COUCH TRACE] KiokuDB::Backend::CouchDB::get_from_storage() [", tv_interval($start, $end),"s]:\n";
296 0 ▶ warn "[KIOKU COUCH TRACE] ".$_->{_id}.', ['.($_->{class} || '')."]\n" for @docs;
Condition0%0/2
$_->{'class'} || ''
l!l
00
MC/DC0%0/1
$_->{'class'} || ''
$_->{'class'}
Truth table0%0/2
A
A= $_->{'class'}
Aresult
11
00
297 0 warn "[KIOKU COUCH TRACE] (not found) ".$_->{key}."\n" for @not_found;
298 }
299
300 0 return map { $self->deserialize($_) } @docs;
301 }
302  
303 0 ▶sub deserialize {
Subroutine deserialize: not called CC=1 SCAR=6.9
Pod undocumented
304 0 my ( $self, $doc ) = @_;
305  
306 0 my %doc = %{ $doc };
307  
308 0 return $self->expand_jspon(\%doc, backend_data => $doc );
309 }
310  
311 0 ▶sub clear {
Subroutine clear: not called CC=1 SCAR=6.9
Pod undocumented
312 0 my $self = shift;
313  
314 # FIXME TXN
315  
316 0 $self->db->drop->recv;
317 0 $self->db->create->recv;
318 }
319  
320 0 ▶sub all_entries {
Subroutine all_entries: not called CC=2 SCAR=17.9
Pod undocumented
321 0 my ( $self, %args ) = @_;
322  
323 # FIXME pagination
324 0 my @ids = map { $_->{id} } @{ $self->db->all_docs->recv->{rows} };
325  
326 0 ▶ if ( my $l = $args{live_objects} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $l = $args{'live_objects'}) { } 0 0 0
327 0 my %entries;
328 0 @entries{@ids} = $l->ids_to_entries(@ids);
329  
330 0 my @missing = grep { not $entries{$_} } @ids;
331  
332 0 @entries{@missing} = $self->get(@missing);
333  
334 0 return bulk(values %entries);
335 } else {
336 0 return bulk($self->get(@ids));
337 }
338 }
339  
340 1 __PACKAGE__->meta->make_immutable;
341  
342 1 1;
343  
344 __END__
↑ Summary KiokuX/CouchDB/Role/View.pm »