Migrated setup_fh -> setup and moved lots of POD into the base class
[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     # This can return nothing if we are deleting an entry in a hashref that was
167     # auto-vivified as part of the delete process. For example:
168     #     my $x = {};
169     #     delete $x->{foo}{bar};
170     my $blist = $self->get_bucket_list({
171         key_md5 => $args->{key_md5},
172     }) or return;
173
174     # Save the location so that we can free the data
175     my $location = $blist->get_data_location_for({
176         allow_head => 0,
177     });
178     my $old_value = $location && $self->engine->_load_sector( $location );
179
180     my @trans_ids = $self->engine->get_running_txn_ids;
181
182     # If we're the HEAD and there are running txns, then we need to clone this value to the other
183     # transactions to preserve Isolation.
184     if ( $self->engine->trans_id == 0 ) {
185         if ( @trans_ids ) {
186             foreach my $other_trans_id ( @trans_ids ) {
187                 next if $blist->get_data_location_for({ trans_id => $other_trans_id, allow_head => 0 });
188                 $blist->write_md5({
189                     trans_id => $other_trans_id,
190                     key      => $args->{key},
191                     key_md5  => $args->{key_md5},
192                     value    => $old_value->clone,
193                 });
194             }
195         }
196     }
197
198     my $data;
199     if ( @trans_ids ) {
200         $blist->mark_deleted( $args );
201
202         if ( $old_value ) {
203             $data = $old_value->data({ export => 1 });
204             $old_value->free;
205         }
206     }
207     else {
208         $data = $blist->delete_md5( $args );
209     }
210
211     return $data;
212 }
213
214 sub get_blist_loc {
215     my $self = shift;
216
217     my $e = $self->engine;
218     my $blist_loc = $e->storage->read_at( $self->offset + $self->base_size, $e->byte_size );
219     return unpack( $StP{$e->byte_size}, $blist_loc );
220 }
221
222 sub get_bucket_list {
223     my $self = shift;
224     my ($args) = @_;
225     $args ||= {};
226
227     # XXX Add in check here for recycling?
228
229     my $engine = $self->engine;
230
231     my $blist_loc = $self->get_blist_loc;
232
233     # There's no index or blist yet
234     unless ( $blist_loc ) {
235         return unless $args->{create};
236
237         my $blist = DBM::Deep::Engine::Sector::BucketList->new({
238             engine  => $engine,
239             key_md5 => $args->{key_md5},
240         });
241
242         $engine->storage->print_at( $self->offset + $self->base_size,
243             pack( $StP{$engine->byte_size}, $blist->offset ),
244         );
245
246         return $blist;
247     }
248
249     my $sector = $engine->_load_sector( $blist_loc )
250         or DBM::Deep->_throw_error( "Cannot read sector at $blist_loc in get_bucket_list()" );
251     my $i = 0;
252     my $last_sector = undef;
253     while ( $sector->isa( 'DBM::Deep::Engine::Sector::Index' ) ) {
254         $blist_loc = $sector->get_entry( ord( substr( $args->{key_md5}, $i++, 1 ) ) );
255         $last_sector = $sector;
256         if ( $blist_loc ) {
257             $sector = $engine->_load_sector( $blist_loc )
258                 or DBM::Deep->_throw_error( "Cannot read sector at $blist_loc in get_bucket_list()" );
259         }
260         else {
261             $sector = undef;
262             last;
263         }
264     }
265
266     # This means we went through the Index sector(s) and found an empty slot
267     unless ( $sector ) {
268         return unless $args->{create};
269
270         DBM::Deep->_throw_error( "No last_sector when attempting to build a new entry" )
271             unless $last_sector;
272
273         my $blist = DBM::Deep::Engine::Sector::BucketList->new({
274             engine  => $engine,
275             key_md5 => $args->{key_md5},
276         });
277
278         $last_sector->set_entry( ord( substr( $args->{key_md5}, $i - 1, 1 ) ) => $blist->offset );
279
280         return $blist;
281     }
282
283     $sector->find_md5( $args->{key_md5} );
284
285     # See whether or not we need to reindex the bucketlist
286     # Yes, the double-braces are there for a reason. if() doesn't create a redo-able block,
287     # so we have to create a bare block within the if() for redo-purposes. Patch and idea
288     # submitted by sprout@cpan.org. -RobK, 2008-01-09
289     if ( !$sector->has_md5 && $args->{create} && $sector->{idx} == -1 ) {{
290         my $redo;
291
292         my $new_index = DBM::Deep::Engine::Sector::Index->new({
293             engine => $engine,
294         });
295
296         my %blist_cache;
297         #XXX q.v. the comments for this function.
298         foreach my $entry ( $sector->chopped_up ) {
299             my ($spot, $md5) = @{$entry};
300             my $idx = ord( substr( $md5, $i, 1 ) );
301
302             # XXX This is inefficient
303             my $blist = $blist_cache{$idx}
304                 ||= DBM::Deep::Engine::Sector::BucketList->new({
305                     engine => $engine,
306                 });
307
308             $new_index->set_entry( $idx => $blist->offset );
309
310             my $new_spot = $blist->write_at_next_open( $md5 );
311             $engine->reindex_entry( $spot => $new_spot );
312         }
313
314         # Handle the new item separately.
315         {
316             my $idx = ord( substr( $args->{key_md5}, $i, 1 ) );
317
318             # If all the previous blist's items have been thrown into one
319             # blist and the new item belongs in there too, we need
320             # another index.
321             if ( keys %blist_cache == 1 and each %blist_cache == $idx ) {
322                 ++$i, ++$redo;
323             } else {
324                 my $blist = $blist_cache{$idx}
325                     ||= DBM::Deep::Engine::Sector::BucketList->new({
326                         engine => $engine,
327                     });
328     
329                 $new_index->set_entry( $idx => $blist->offset );
330     
331                 #XXX THIS IS HACKY!
332                 $blist->find_md5( $args->{key_md5} );
333                 $blist->write_md5({
334                     key     => $args->{key},
335                     key_md5 => $args->{key_md5},
336                     value   => DBM::Deep::Engine::Sector::Null->new({
337                         engine => $engine,
338                         data   => undef,
339                     }),
340                 });
341             }
342 #            my $blist = $blist_cache{$idx}
343 #                ||= DBM::Deep::Engine::Sector::BucketList->new({
344 #                    engine => $engine,
345 #                });
346 #
347 #            $new_index->set_entry( $idx => $blist->offset );
348 #
349 #            #XXX THIS IS HACKY!
350 #            $blist->find_md5( $args->{key_md5} );
351 #            $blist->write_md5({
352 #                key     => $args->{key},
353 #                key_md5 => $args->{key_md5},
354 #                value   => DBM::Deep::Engine::Sector::Null->new({
355 #                    engine => $engine,
356 #                    data   => undef,
357 #                }),
358 #            });
359         }
360
361         if ( $last_sector ) {
362             $last_sector->set_entry(
363                 ord( substr( $args->{key_md5}, $i - 1, 1 ) ),
364                 $new_index->offset,
365             );
366         } else {
367             $engine->storage->print_at( $self->offset + $self->base_size,
368                 pack( $StP{$engine->byte_size}, $new_index->offset ),
369             );
370         }
371
372         $sector->clear;
373         $sector->free;
374
375         if ( $redo ) {
376             (undef, $sector) = %blist_cache;
377             $last_sector = $new_index;
378             redo;
379         }
380
381         $sector = $blist_cache{ ord( substr( $args->{key_md5}, $i, 1 ) ) };
382         $sector->find_md5( $args->{key_md5} );
383     }}
384
385     return $sector;
386 }
387
388 sub get_class_offset {
389     my $self = shift;
390
391     my $e = $self->engine;
392     return unpack(
393         $StP{$e->byte_size},
394         $e->storage->read_at(
395             $self->offset + $self->base_size + 1 * $e->byte_size, $e->byte_size,
396         ),
397     );
398 }
399
400 sub get_classname {
401     my $self = shift;
402
403     my $class_offset = $self->get_class_offset;
404
405     return unless $class_offset;
406
407     return $self->engine->_load_sector( $class_offset )->data;
408 }
409
410 sub data {
411     my $self = shift;
412     my ($args) = @_;
413     $args ||= {};
414
415     my $obj;
416     unless ( $obj = $self->engine->cache->{ $self->offset } ) {
417         $obj = DBM::Deep->new({
418             type        => $self->type,
419             base_offset => $self->offset,
420             staleness   => $self->staleness,
421             storage     => $self->engine->storage,
422             engine      => $self->engine,
423         });
424
425         if ( $self->engine->storage->{autobless} ) {
426             my $classname = $self->get_classname;
427             if ( defined $classname ) {
428                 bless $obj, $classname;
429             }
430         }
431
432         $self->engine->cache->{$self->offset} = $obj;
433     }
434
435     # We're not exporting, so just return.
436     unless ( $args->{export} ) {
437         return $obj;
438     }
439
440     # We shouldn't export if this is still referred to.
441     if ( $self->get_refcount > 1 ) {
442         return $obj;
443     }
444
445     return $obj->export;
446 }
447
448 sub free {
449     my $self = shift;
450
451     # We're not ready to be removed yet.
452     if ( $self->decrement_refcount > 0 ) {
453         return;
454     }
455
456     # Rebless the object into DBM::Deep::Null.
457     eval { %{ $self->engine->cache->{ $self->offset } } = (); };
458     eval { @{ $self->engine->cache->{ $self->offset } } = (); };
459     bless $self->engine->cache->{ $self->offset }, 'DBM::Deep::Null';
460     delete $self->engine->cache->{ $self->offset };
461
462     my $blist_loc = $self->get_blist_loc;
463     $self->engine->_load_sector( $blist_loc )->free if $blist_loc;
464
465     my $class_loc = $self->get_class_offset;
466     $self->engine->_load_sector( $class_loc )->free if $class_loc;
467
468     $self->SUPER::free();
469 }
470
471 sub increment_refcount {
472     my $self = shift;
473
474     my $refcount = $self->get_refcount;
475
476     $refcount++;
477
478     $self->write_refcount( $refcount );
479
480     return $refcount;
481 }
482
483 sub decrement_refcount {
484     my $self = shift;
485
486     my $refcount = $self->get_refcount;
487
488     $refcount--;
489
490     $self->write_refcount( $refcount );
491
492     return $refcount;
493 }
494
495 sub get_refcount {
496     my $self = shift;
497
498     my $e = $self->engine;
499     return unpack(
500         $StP{$e->byte_size},
501         $e->storage->read_at(
502             $self->offset + $self->base_size + 2 * $e->byte_size, $e->byte_size,
503         ),
504     );
505 }
506
507 sub write_refcount {
508     my $self = shift;
509     my ($num) = @_;
510
511     my $e = $self->engine;
512     $e->storage->print_at(
513         $self->offset + $self->base_size + 2 * $e->byte_size,
514         pack( $StP{$e->byte_size}, $num ),
515     );
516 }
517
518 1;
519 __END__