All the tests now pass with the broken out classes
[dbsrgits/DBM-Deep.git] / lib / DBM / Deep / Engine / Sector / Reference.pm
1 package DBM::Deep::Engine::Sector::Reference;
2
3 use 5.006_000;
4
5 use strict;
6 use warnings FATAL => 'all';
7
8 use base qw( DBM::Deep::Engine::Sector::Data );
9
10 my $STALE_SIZE = 2;
11
12 # Please refer to the pack() documentation for further information
13 my %StP = (
14     1 => 'C', # Unsigned char value (no order needed as it's just one byte)
15     2 => 'n', # Unsigned short in "network" (big-endian) order
16     4 => 'N', # Unsigned long in "network" (big-endian) order
17     8 => 'Q', # Usigned quad (no order specified, presumably machine-dependent)
18 );
19
20 sub _init {
21     my $self = shift;
22
23     my $e = $self->engine;
24
25     unless ( $self->offset ) {
26         my $classname = Scalar::Util::blessed( delete $self->{data} );
27         my $leftover = $self->size - $self->base_size - 3 * $e->byte_size;
28
29         my $class_offset = 0;
30         if ( defined $classname ) {
31             my $class_sector = DBM::Deep::Engine::Sector::Scalar->new({
32                 engine => $e,
33                 data   => $classname,
34             });
35             $class_offset = $class_sector->offset;
36         }
37
38         $self->{offset} = $e->_request_data_sector( $self->size );
39         $e->storage->print_at( $self->offset, $self->type ); # Sector type
40         # Skip staleness counter
41         $e->storage->print_at( $self->offset + $self->base_size,
42             pack( $StP{$e->byte_size}, 0 ),             # Index/BList loc
43             pack( $StP{$e->byte_size}, $class_offset ), # Classname loc
44             pack( $StP{$e->byte_size}, 1 ),             # Initial refcount
45             chr(0) x $leftover,                         # Zero-fill the rest
46         );
47     }
48     else {
49         $self->{type} = $e->storage->read_at( $self->offset, 1 );
50     }
51
52     $self->{staleness} = unpack(
53         $StP{$STALE_SIZE},
54         $e->storage->read_at( $self->offset + $e->SIG_SIZE, $STALE_SIZE ),
55     );
56
57     return;
58 }
59
60 sub staleness { $_[0]{staleness} }
61
62 sub get_data_location_for {
63     my $self = shift;
64     my ($args) = @_;
65
66     # Assume that the head is not allowed unless otherwise specified.
67     $args->{allow_head} = 0 unless exists $args->{allow_head};
68
69     # Assume we don't create a new blist location unless otherwise specified.
70     $args->{create} = 0 unless exists $args->{create};
71
72     my $blist = $self->get_bucket_list({
73         key_md5 => $args->{key_md5},
74         key => $args->{key},
75         create  => $args->{create},
76     });
77     return unless $blist && $blist->{found};
78
79     # At this point, $blist knows where the md5 is. What it -doesn't- know yet
80     # is whether or not this transaction has this key. That's part of the next
81     # function call.
82     my $location = $blist->get_data_location_for({
83         allow_head => $args->{allow_head},
84     }) or return;
85
86     return $location;
87 }
88
89 sub get_data_for {
90     my $self = shift;
91     my ($args) = @_;
92
93     my $location = $self->get_data_location_for( $args )
94         or return;
95
96     return $self->engine->_load_sector( $location );
97 }
98
99 sub write_data {
100     my $self = shift;
101     my ($args) = @_;
102
103     my $blist = $self->get_bucket_list({
104         key_md5 => $args->{key_md5},
105         key => $args->{key},
106         create  => 1,
107     }) or DBM::Deep->_throw_error( "How did write_data fail (no blist)?!" );
108
109     # Handle any transactional bookkeeping.
110     if ( $self->engine->trans_id ) {
111         if ( ! $blist->has_md5 ) {
112             $blist->mark_deleted({
113                 trans_id => 0,
114             });
115         }
116     }
117     else {
118         my @trans_ids = $self->engine->get_running_txn_ids;
119         if ( $blist->has_md5 ) {
120             if ( @trans_ids ) {
121                 my $old_value = $blist->get_data_for;
122                 foreach my $other_trans_id ( @trans_ids ) {
123                     next if $blist->get_data_location_for({
124                         trans_id   => $other_trans_id,
125                         allow_head => 0,
126                     });
127                     $blist->write_md5({
128                         trans_id => $other_trans_id,
129                         key      => $args->{key},
130                         key_md5  => $args->{key_md5},
131                         value    => $old_value->clone,
132                     });
133                 }
134             }
135         }
136         else {
137             if ( @trans_ids ) {
138                 foreach my $other_trans_id ( @trans_ids ) {
139                     #XXX This doesn't seem to possible to ever happen . . .
140                     next if $blist->get_data_location_for({ trans_id => $other_trans_id, allow_head => 0 });
141                     $blist->mark_deleted({
142                         trans_id => $other_trans_id,
143                     });
144                 }
145             }
146         }
147     }
148
149     #XXX Is this safe to do transactionally?
150     # Free the place we're about to write to.
151     if ( $blist->get_data_location_for({ allow_head => 0 }) ) {
152         $blist->get_data_for({ allow_head => 0 })->free;
153     }
154
155     $blist->write_md5({
156         key      => $args->{key},
157         key_md5  => $args->{key_md5},
158         value    => $args->{value},
159     });
160 }
161
162 sub delete_key {
163     my $self = shift;
164     my ($args) = @_;
165
166     # XXX What should happen if this fails?
167     my $blist = $self->get_bucket_list({
168         key_md5 => $args->{key_md5},
169     }) or DBM::Deep->_throw_error( "How did delete_key fail (no blist)?!" );
170
171     # Save the location so that we can free the data
172     my $location = $blist->get_data_location_for({
173         allow_head => 0,
174     });
175     my $old_value = $location && $self->engine->_load_sector( $location );
176
177     my @trans_ids = $self->engine->get_running_txn_ids;
178
179     # If we're the HEAD and there are running txns, then we need to clone this value to the other
180     # transactions to preserve Isolation.
181     if ( $self->engine->trans_id == 0 ) {
182         if ( @trans_ids ) {
183             foreach my $other_trans_id ( @trans_ids ) {
184                 next if $blist->get_data_location_for({ trans_id => $other_trans_id, allow_head => 0 });
185                 $blist->write_md5({
186                     trans_id => $other_trans_id,
187                     key      => $args->{key},
188                     key_md5  => $args->{key_md5},
189                     value    => $old_value->clone,
190                 });
191             }
192         }
193     }
194
195     my $data;
196     if ( @trans_ids ) {
197         $blist->mark_deleted( $args );
198
199         if ( $old_value ) {
200             $data = $old_value->data({ export => 1 });
201             $old_value->free;
202         }
203     }
204     else {
205         $data = $blist->delete_md5( $args );
206     }
207
208     return $data;
209 }
210
211 sub get_blist_loc {
212     my $self = shift;
213
214     my $e = $self->engine;
215     my $blist_loc = $e->storage->read_at( $self->offset + $self->base_size, $e->byte_size );
216     return unpack( $StP{$e->byte_size}, $blist_loc );
217 }
218
219 sub get_bucket_list {
220     my $self = shift;
221     my ($args) = @_;
222     $args ||= {};
223
224     # XXX Add in check here for recycling?
225
226     my $engine = $self->engine;
227
228     my $blist_loc = $self->get_blist_loc;
229
230     # There's no index or blist yet
231     unless ( $blist_loc ) {
232         return unless $args->{create};
233
234         my $blist = DBM::Deep::Engine::Sector::BucketList->new({
235             engine  => $engine,
236             key_md5 => $args->{key_md5},
237         });
238
239         $engine->storage->print_at( $self->offset + $self->base_size,
240             pack( $StP{$engine->byte_size}, $blist->offset ),
241         );
242
243         return $blist;
244     }
245
246     my $sector = $engine->_load_sector( $blist_loc )
247         or DBM::Deep->_throw_error( "Cannot read sector at $blist_loc in get_bucket_list()" );
248     my $i = 0;
249     my $last_sector = undef;
250     while ( $sector->isa( 'DBM::Deep::Engine::Sector::Index' ) ) {
251         $blist_loc = $sector->get_entry( ord( substr( $args->{key_md5}, $i++, 1 ) ) );
252         $last_sector = $sector;
253         if ( $blist_loc ) {
254             $sector = $engine->_load_sector( $blist_loc )
255                 or DBM::Deep->_throw_error( "Cannot read sector at $blist_loc in get_bucket_list()" );
256         }
257         else {
258             $sector = undef;
259             last;
260         }
261     }
262
263     # This means we went through the Index sector(s) and found an empty slot
264     unless ( $sector ) {
265         return unless $args->{create};
266
267         DBM::Deep->_throw_error( "No last_sector when attempting to build a new entry" )
268             unless $last_sector;
269
270         my $blist = DBM::Deep::Engine::Sector::BucketList->new({
271             engine  => $engine,
272             key_md5 => $args->{key_md5},
273         });
274
275         $last_sector->set_entry( ord( substr( $args->{key_md5}, $i - 1, 1 ) ) => $blist->offset );
276
277         return $blist;
278     }
279
280     $sector->find_md5( $args->{key_md5} );
281
282     # See whether or not we need to reindex the bucketlist
283     # Yes, the double-braces are there for a reason. if() doesn't create a redo-able block,
284     # so we have to create a bare block within the if() for redo-purposes. Patch and idea
285     # submitted by sprout@cpan.org. -RobK, 2008-01-09
286     if ( !$sector->has_md5 && $args->{create} && $sector->{idx} == -1 ) {{
287         my $redo;
288
289         my $new_index = DBM::Deep::Engine::Sector::Index->new({
290             engine => $engine,
291         });
292
293         my %blist_cache;
294         #XXX q.v. the comments for this function.
295         foreach my $entry ( $sector->chopped_up ) {
296             my ($spot, $md5) = @{$entry};
297             my $idx = ord( substr( $md5, $i, 1 ) );
298
299             # XXX This is inefficient
300             my $blist = $blist_cache{$idx}
301                 ||= DBM::Deep::Engine::Sector::BucketList->new({
302                     engine => $engine,
303                 });
304
305             $new_index->set_entry( $idx => $blist->offset );
306
307             my $new_spot = $blist->write_at_next_open( $md5 );
308             $engine->reindex_entry( $spot => $new_spot );
309         }
310
311         # Handle the new item separately.
312         {
313             my $idx = ord( substr( $args->{key_md5}, $i, 1 ) );
314
315             # If all the previous blist's items have been thrown into one
316             # blist and the new item belongs in there too, we need
317             # another index.
318             if ( keys %blist_cache == 1 and each %blist_cache == $idx ) {
319                 ++$i, ++$redo;
320             } else {
321                 my $blist = $blist_cache{$idx}
322                     ||= DBM::Deep::Engine::Sector::BucketList->new({
323                         engine => $engine,
324                     });
325     
326                 $new_index->set_entry( $idx => $blist->offset );
327     
328                 #XXX THIS IS HACKY!
329                 $blist->find_md5( $args->{key_md5} );
330                 $blist->write_md5({
331                     key     => $args->{key},
332                     key_md5 => $args->{key_md5},
333                     value   => DBM::Deep::Engine::Sector::Null->new({
334                         engine => $engine,
335                         data   => undef,
336                     }),
337                 });
338             }
339 #            my $blist = $blist_cache{$idx}
340 #                ||= DBM::Deep::Engine::Sector::BucketList->new({
341 #                    engine => $engine,
342 #                });
343 #
344 #            $new_index->set_entry( $idx => $blist->offset );
345 #
346 #            #XXX THIS IS HACKY!
347 #            $blist->find_md5( $args->{key_md5} );
348 #            $blist->write_md5({
349 #                key     => $args->{key},
350 #                key_md5 => $args->{key_md5},
351 #                value   => DBM::Deep::Engine::Sector::Null->new({
352 #                    engine => $engine,
353 #                    data   => undef,
354 #                }),
355 #            });
356         }
357
358         if ( $last_sector ) {
359             $last_sector->set_entry(
360                 ord( substr( $args->{key_md5}, $i - 1, 1 ) ),
361                 $new_index->offset,
362             );
363         } else {
364             $engine->storage->print_at( $self->offset + $self->base_size,
365                 pack( $StP{$engine->byte_size}, $new_index->offset ),
366             );
367         }
368
369         $sector->clear;
370         $sector->free;
371
372         if ( $redo ) {
373             (undef, $sector) = %blist_cache;
374             $last_sector = $new_index;
375             redo;
376         }
377
378         $sector = $blist_cache{ ord( substr( $args->{key_md5}, $i, 1 ) ) };
379         $sector->find_md5( $args->{key_md5} );
380     }}
381
382     return $sector;
383 }
384
385 sub get_class_offset {
386     my $self = shift;
387
388     my $e = $self->engine;
389     return unpack(
390         $StP{$e->byte_size},
391         $e->storage->read_at(
392             $self->offset + $self->base_size + 1 * $e->byte_size, $e->byte_size,
393         ),
394     );
395 }
396
397 sub get_classname {
398     my $self = shift;
399
400     my $class_offset = $self->get_class_offset;
401
402     return unless $class_offset;
403
404     return $self->engine->_load_sector( $class_offset )->data;
405 }
406
407 sub data {
408     my $self = shift;
409     my ($args) = @_;
410     $args ||= {};
411
412     my $obj;
413     unless ( $obj = $self->engine->cache->{ $self->offset } ) {
414         $obj = DBM::Deep->new({
415             type        => $self->type,
416             base_offset => $self->offset,
417             staleness   => $self->staleness,
418             storage     => $self->engine->storage,
419             engine      => $self->engine,
420         });
421
422         if ( $self->engine->storage->{autobless} ) {
423             my $classname = $self->get_classname;
424             if ( defined $classname ) {
425                 bless $obj, $classname;
426             }
427         }
428
429         $self->engine->cache->{$self->offset} = $obj;
430     }
431
432     # We're not exporting, so just return.
433     unless ( $args->{export} ) {
434         return $obj;
435     }
436
437     # We shouldn't export if this is still referred to.
438     if ( $self->get_refcount > 1 ) {
439         return $obj;
440     }
441
442     return $obj->export;
443 }
444
445 sub free {
446     my $self = shift;
447
448     # We're not ready to be removed yet.
449     if ( $self->decrement_refcount > 0 ) {
450         return;
451     }
452
453     # Rebless the object into DBM::Deep::Null.
454     eval { %{ $self->engine->cache->{ $self->offset } } = (); };
455     eval { @{ $self->engine->cache->{ $self->offset } } = (); };
456     bless $self->engine->cache->{ $self->offset }, 'DBM::Deep::Null';
457     delete $self->engine->cache->{ $self->offset };
458
459     my $blist_loc = $self->get_blist_loc;
460     $self->engine->_load_sector( $blist_loc )->free if $blist_loc;
461
462     my $class_loc = $self->get_class_offset;
463     $self->engine->_load_sector( $class_loc )->free if $class_loc;
464
465     $self->SUPER::free();
466 }
467
468 sub increment_refcount {
469     my $self = shift;
470
471     my $refcount = $self->get_refcount;
472
473     $refcount++;
474
475     $self->write_refcount( $refcount );
476
477     return $refcount;
478 }
479
480 sub decrement_refcount {
481     my $self = shift;
482
483     my $refcount = $self->get_refcount;
484
485     $refcount--;
486
487     $self->write_refcount( $refcount );
488
489     return $refcount;
490 }
491
492 sub get_refcount {
493     my $self = shift;
494
495     my $e = $self->engine;
496     return unpack(
497         $StP{$e->byte_size},
498         $e->storage->read_at(
499             $self->offset + $self->base_size + 2 * $e->byte_size, $e->byte_size,
500         ),
501     );
502 }
503
504 sub write_refcount {
505     my $self = shift;
506     my ($num) = @_;
507
508     my $e = $self->engine;
509     $e->storage->print_at(
510         $self->offset + $self->base_size + 2 * $e->byte_size,
511         pack( $StP{$e->byte_size}, $num ),
512     );
513 }
514
515 1;
516 __END__