1 package DBM::Deep::Engine;
7 our $VERSION = q(0.99_03);
12 # * Every method in here assumes that the storage has been appropriately
13 # safeguarded. This can be anything from flock() to some sort of manual
14 # mutex. But, it's the caller's responsability to make sure that this has
17 # Setup file and tag signatures. These should never change.
18 sub SIG_FILE () { 'DPDB' }
19 sub SIG_HEADER () { 'h' }
20 sub SIG_INTERNAL () { 'i' }
21 sub SIG_HASH () { 'H' }
22 sub SIG_ARRAY () { 'A' }
23 sub SIG_NULL () { 'N' }
24 sub SIG_DATA () { 'D' }
25 sub SIG_INDEX () { 'I' }
26 sub SIG_BLIST () { 'B' }
27 sub SIG_FREE () { 'F' }
28 sub SIG_KEYS () { 'K' }
30 sub STALE_SIZE () { 1 }
32 # Please refer to the pack() documentation for further information
34 1 => 'C', # Unsigned char value (no order specified, presumably ASCII)
35 2 => 'n', # Unsigned short in "network" (big-endian) order
36 4 => 'N', # Unsigned long in "network" (big-endian) order
37 8 => 'Q', # Usigned quad (no order specified, presumably machine-dependent)
40 ################################################################################
50 hash_size => 16, # In bytes
51 hash_chars => 256, # Number of chars the algorithm uses per byte
53 num_txns => 2, # HEAD plus 1 additional transaction for importing
54 trans_id => 0, # Default to the HEAD
56 entries => {}, # This is the list of entries for transactions
60 if ( defined $args->{pack_size} ) {
61 if ( lc $args->{pack_size} eq 'small' ) {
62 $args->{byte_size} = 2;
64 elsif ( lc $args->{pack_size} eq 'medium' ) {
65 $args->{byte_size} = 4;
67 elsif ( lc $args->{pack_size} eq 'large' ) {
68 $args->{byte_size} = 8;
71 DBM::Deep->_throw_error( "Unknown pack_size value: '$args->{pack_size}'" );
75 # Grab the parameters we want to use
76 foreach my $param ( keys %$self ) {
77 next unless exists $args->{$param};
78 $self->{$param} = $args->{$param};
82 # Number of buckets per blist before another level of indexing is
83 # done. Increase this value for slightly greater speed, but larger database
84 # files. DO NOT decrease this value below 16, due to risk of recursive
87 if ( $self->{max_buckets} < 16 ) {
88 warn "Floor of max_buckets is 16. Setting it to 16 from '$self->{max_buckets}'\n";
89 $self->{max_buckets} = 16;
92 if ( !$self->{digest} ) {
94 $self->{digest} = \&Digest::MD5::md5;
100 ################################################################################
104 my ($obj, $key) = @_;
106 # This will be a Reference sector
107 my $sector = $self->_load_sector( $obj->_base_offset )
110 if ( $sector->staleness != $obj->_staleness ) {
114 my $key_md5 = $self->_apply_digest( $key );
116 my $value_sector = $sector->get_data_for({
121 unless ( $value_sector ) {
122 $value_sector = DBM::Deep::Engine::Sector::Null->new({
127 $sector->write_data({
130 value => $value_sector,
134 return $value_sector->data;
141 # This will be a Reference sector
142 my $sector = $self->_load_sector( $obj->_base_offset )
143 or DBM::Deep->_throw_error( "How did get_classname fail (no sector for '$obj')?!" );
145 if ( $sector->staleness != $obj->_staleness ) {
149 return $sector->get_classname;
154 my ($obj, $key) = @_;
156 # This will be a Reference sector
157 my $sector = $self->_load_sector( $obj->_base_offset )
160 if ( $sector->staleness != $obj->_staleness ) {
164 my $data = $sector->get_data_for({
165 key_md5 => $self->_apply_digest( $key ),
169 # exists() returns 1 or '' for true/false.
170 return $data ? 1 : '';
175 my ($obj, $key) = @_;
177 my $sector = $self->_load_sector( $obj->_base_offset )
180 if ( $sector->staleness != $obj->_staleness ) {
184 return $sector->delete_key({
185 key_md5 => $self->_apply_digest( $key ),
192 my ($obj, $key, $value) = @_;
194 my $r = Scalar::Util::reftype( $value ) || '';
197 last if $r eq 'HASH';
198 last if $r eq 'ARRAY';
200 DBM::Deep->_throw_error(
201 "Storage of references of type '$r' is not supported."
206 if ( !defined $value ) {
207 $class = 'DBM::Deep::Engine::Sector::Null';
209 elsif ( $r eq 'ARRAY' || $r eq 'HASH' ) {
210 if ( $r eq 'ARRAY' && tied(@$value) ) {
211 DBM::Deep->_throw_error( "Cannot store something that is tied." );
213 if ( $r eq 'HASH' && tied(%$value) ) {
214 DBM::Deep->_throw_error( "Cannot store something that is tied." );
216 $class = 'DBM::Deep::Engine::Sector::Reference';
217 $type = substr( $r, 0, 1 );
220 $class = 'DBM::Deep::Engine::Sector::Scalar';
223 # This will be a Reference sector
224 my $sector = $self->_load_sector( $obj->_base_offset )
225 or DBM::Deep->_throw_error( "Cannot write to a deleted spot in DBM::Deep." );
227 if ( $sector->staleness != $obj->_staleness ) {
228 DBM::Deep->_throw_error( "Cannot write to a deleted spot in DBM::Deep.n" );
231 # Create this after loading the reference sector in case something bad happens.
232 # This way, we won't allocate value sector(s) needlessly.
233 my $value_sector = $class->new({
239 $sector->write_data({
241 key_md5 => $self->_apply_digest( $key ),
242 value => $value_sector,
245 # This code is to make sure we write all the values in the $value to the disk
246 # and to make sure all changes to $value after the assignment are reflected
247 # on disk. This may be counter-intuitive at first, but it is correct dwimmery.
248 # NOTE - simply tying $value won't perform a STORE on each value. Hence, the
249 # copy to a temp value.
250 if ( $r eq 'ARRAY' ) {
252 tie @$value, 'DBM::Deep', {
253 base_offset => $value_sector->offset,
254 staleness => $value_sector->staleness,
255 storage => $self->storage,
259 bless $value, 'DBM::Deep::Array' unless Scalar::Util::blessed( $value );
261 elsif ( $r eq 'HASH' ) {
263 tie %$value, 'DBM::Deep', {
264 base_offset => $value_sector->offset,
265 staleness => $value_sector->staleness,
266 storage => $self->storage,
271 bless $value, 'DBM::Deep::Hash' unless Scalar::Util::blessed( $value );
277 # XXX Add staleness here
280 my ($obj, $prev_key) = @_;
282 # XXX Need to add logic about resetting the iterator if any key in the reference has changed
283 unless ( $prev_key ) {
284 $obj->{iterator} = DBM::Deep::Iterator->new({
285 base_offset => $obj->_base_offset,
290 return $obj->{iterator}->get_next_key( $obj );
293 ################################################################################
299 # We're opening the file.
300 unless ( $obj->_base_offset ) {
301 my $bytes_read = $self->_read_file_header;
303 # Creating a new file
304 unless ( $bytes_read ) {
305 $self->_write_file_header;
307 # 1) Create Array/Hash entry
308 my $initial_reference = DBM::Deep::Engine::Sector::Reference->new({
312 $obj->{base_offset} = $initial_reference->offset;
313 $obj->{staleness} = $initial_reference->staleness;
315 $self->storage->flush;
317 # Reading from an existing file
319 $obj->{base_offset} = $bytes_read;
320 my $initial_reference = DBM::Deep::Engine::Sector::Reference->new({
322 offset => $obj->_base_offset,
324 unless ( $initial_reference ) {
325 DBM::Deep->_throw_error("Corrupted file, no master index record");
328 unless ($obj->_type eq $initial_reference->type) {
329 DBM::Deep->_throw_error("File type mismatch");
332 $obj->{staleness} = $initial_reference->staleness;
343 if ( $self->trans_id ) {
344 DBM::Deep->_throw_error( "Cannot begin_work within an active transaction" );
347 my @slots = $self->read_txn_slots;
348 for my $i ( 1 .. @slots ) {
351 $self->set_trans_id( $i );
354 $self->write_txn_slots( @slots );
356 if ( !$self->trans_id ) {
357 DBM::Deep->_throw_error( "Cannot begin_work - no available transactions" );
367 if ( !$self->trans_id ) {
368 DBM::Deep->_throw_error( "Cannot rollback without an active transaction" );
371 # Each entry is the file location for a bucket that has a modification for
372 # this transaction. The entries need to be expunged.
373 foreach my $entry (@{ $self->get_entries } ) {
374 # Remove the entry here
375 my $read_loc = $entry
378 + $self->trans_id * ( $self->byte_size + 4 );
380 my $data_loc = $self->storage->read_at( $read_loc, $self->byte_size );
381 $data_loc = unpack( $StP{$self->byte_size}, $data_loc );
382 $self->storage->print_at( $read_loc, pack( $StP{$self->byte_size}, 0 ) );
384 if ( $data_loc > 1 ) {
385 $self->_load_sector( $data_loc )->free;
389 $self->clear_entries;
391 my @slots = $self->read_txn_slots;
392 $slots[$self->trans_id] = 0;
393 $self->write_txn_slots( @slots );
394 $self->inc_txn_staleness_counter( $self->trans_id );
395 $self->set_trans_id( 0 );
404 if ( !$self->trans_id ) {
405 DBM::Deep->_throw_error( "Cannot commit without an active transaction" );
408 foreach my $entry (@{ $self->get_entries } ) {
409 # Overwrite the entry in head with the entry in trans_id
414 my $head_loc = $self->storage->read_at( $base, $self->byte_size );
415 $head_loc = unpack( $StP{$self->byte_size}, $head_loc );
416 my $trans_loc = $self->storage->read_at(
417 $base + $self->trans_id * ( $self->byte_size + 4 ), $self->byte_size,
420 $self->storage->print_at( $base, $trans_loc );
421 $self->storage->print_at(
422 $base + $self->trans_id * ( $self->byte_size + 4 ),
423 pack( $StP{$self->byte_size} . ' N', (0) x 2 ),
426 if ( $head_loc > 1 ) {
427 $self->_load_sector( $head_loc )->free;
431 $self->clear_entries;
433 my @slots = $self->read_txn_slots;
434 $slots[$self->trans_id] = 0;
435 $self->write_txn_slots( @slots );
436 $self->inc_txn_staleness_counter( $self->trans_id );
437 $self->set_trans_id( 0 );
444 return split '', unpack( 'b32',
445 $self->storage->read_at(
451 sub write_txn_slots {
453 $self->storage->print_at( $self->trans_loc,
454 pack( 'b32', join('', @_) ),
458 sub get_running_txn_ids {
460 my @transactions = $self->read_txn_slots;
461 my @trans_ids = grep { $transactions[$_] } 0 .. $#transactions;
464 sub get_txn_staleness_counter {
468 # Hardcode staleness of 0 for the HEAD
469 return 0 unless $trans_id;
472 $self->storage->read_at(
473 $self->trans_loc + 4 * $trans_id,
480 sub inc_txn_staleness_counter {
484 # Hardcode staleness of 0 for the HEAD
485 return unless $trans_id;
487 $self->storage->print_at(
488 $self->trans_loc + 4 * $trans_id,
489 pack( 'N', $self->get_txn_staleness_counter( $trans_id ) + 1 ),
495 return [ keys %{ $self->{entries}{$self->trans_id} ||= {} } ];
500 my ($trans_id, $loc) = @_;
502 $self->{entries}{$trans_id} ||= {};
503 $self->{entries}{$trans_id}{$loc} = undef;
506 # If the buckets are being relocated because of a reindexing, the entries
507 # mechanism needs to be made aware of it.
510 my ($old_loc, $new_loc) = @_;
513 while ( my ($trans_id, $locs) = each %{ $self->{entries} } ) {
514 foreach my $orig_loc ( keys %{ $locs } ) {
515 if ( $orig_loc == $old_loc ) {
516 delete $locs->{orig_loc};
517 $locs->{$new_loc} = undef;
526 delete $self->{entries}{$self->trans_id};
529 ################################################################################
532 my $header_fixed = length( SIG_FILE ) + 1 + 4 + 4;
534 sub _write_file_header {
537 my $header_var = 1 + 1 + 1 + 4 + 4 * $self->num_txns + 3 * $self->byte_size;
539 my $loc = $self->storage->request_space( $header_fixed + $header_var );
541 $self->storage->print_at( $loc,
544 pack('N', 1), # header version - at this point, we're at 9 bytes
545 pack('N', $header_var), # header size
546 # --- Above is $header_fixed. Below is $header_var
547 pack('C', $self->byte_size),
548 pack('C', $self->max_buckets),
549 pack('C', $self->num_txns),
550 pack('N', 0 ), # Transaction activeness bitfield
551 pack('N' . $self->num_txns, 0 x $self->num_txns ), # Transaction staleness counters
552 pack($StP{$self->byte_size}, 0), # Start of free chain (blist size)
553 pack($StP{$self->byte_size}, 0), # Start of free chain (data size)
554 pack($StP{$self->byte_size}, 0), # Start of free chain (index size)
557 $self->set_trans_loc( $header_fixed + 3 );
558 $self->set_chains_loc( $header_fixed + 3 + 4 + 4 * $self->num_txns );
563 sub _read_file_header {
566 my $buffer = $self->storage->read_at( 0, $header_fixed );
567 return unless length($buffer);
569 my ($file_signature, $sig_header, $header_version, $size) = unpack(
573 unless ( $file_signature eq SIG_FILE ) {
574 $self->storage->close;
575 DBM::Deep->_throw_error( "Signature not found -- file is not a Deep DB" );
578 unless ( $sig_header eq SIG_HEADER ) {
579 $self->storage->close;
580 DBM::Deep->_throw_error( "Old file version found." );
583 my $buffer2 = $self->storage->read_at( undef, $size );
584 my @values = unpack( 'C C C', $buffer2 );
586 if ( @values != 3 || grep { !defined } @values ) {
587 $self->storage->close;
588 DBM::Deep->_throw_error("Corrupted file - bad header");
591 $self->set_trans_loc( $header_fixed + scalar(@values) );
592 $self->set_chains_loc( $header_fixed + scalar(@values) + 4 + 4 * $self->num_txns );
594 #XXX Add warnings if values weren't set right
595 @{$self}{qw(byte_size max_buckets num_txns)} = @values;
597 my $header_var = scalar(@values) + 4 + 4 * $self->num_txns + 3 * $self->byte_size;
598 unless ( $size == $header_var ) {
599 $self->storage->close;
600 DBM::Deep->_throw_error( "Unexpected size found ($size <-> $header_var)." );
603 return length($buffer) + length($buffer2);
611 # Add a catch for offset of 0 or 1
612 return if $offset <= 1;
614 my $type = $self->storage->read_at( $offset, 1 );
615 return if $type eq chr(0);
617 if ( $type eq $self->SIG_ARRAY || $type eq $self->SIG_HASH ) {
618 return DBM::Deep::Engine::Sector::Reference->new({
624 # XXX Don't we need key_md5 here?
625 elsif ( $type eq $self->SIG_BLIST ) {
626 return DBM::Deep::Engine::Sector::BucketList->new({
632 elsif ( $type eq $self->SIG_INDEX ) {
633 return DBM::Deep::Engine::Sector::Index->new({
639 elsif ( $type eq $self->SIG_NULL ) {
640 return DBM::Deep::Engine::Sector::Null->new({
646 elsif ( $type eq $self->SIG_DATA ) {
647 return DBM::Deep::Engine::Sector::Scalar->new({
653 # This was deleted from under us, so just return and let the caller figure it out.
654 elsif ( $type eq $self->SIG_FREE ) {
658 DBM::Deep->_throw_error( "'$offset': Don't know what to do with type '$type'" );
663 return $self->{digest}->(@_);
666 sub _add_free_blist_sector { shift->_add_free_sector( 0, @_ ) }
667 sub _add_free_data_sector { shift->_add_free_sector( 1, @_ ) }
668 sub _add_free_index_sector { shift->_add_free_sector( 2, @_ ) }
670 sub _add_free_sector {
672 my ($multiple, $offset, $size) = @_;
674 my $chains_offset = $multiple * $self->byte_size;
676 my $storage = $self->storage;
678 # Increment staleness.
679 # XXX Can this increment+modulo be done by "&= 0x1" ?
680 my $staleness = unpack( $StP{STALE_SIZE()}, $storage->read_at( $offset + SIG_SIZE, STALE_SIZE ) );
681 $staleness = ($staleness + 1 ) % ( 2 ** ( 8 * STALE_SIZE ) );
682 $storage->print_at( $offset + SIG_SIZE, pack( $StP{STALE_SIZE()}, $staleness ) );
684 my $old_head = $storage->read_at( $self->chains_loc + $chains_offset, $self->byte_size );
686 $storage->print_at( $self->chains_loc + $chains_offset,
687 pack( $StP{$self->byte_size}, $offset ),
690 # Record the old head in the new sector after the signature and staleness counter
691 $storage->print_at( $offset + SIG_SIZE + STALE_SIZE, $old_head );
694 sub _request_blist_sector { shift->_request_sector( 0, @_ ) }
695 sub _request_data_sector { shift->_request_sector( 1, @_ ) }
696 sub _request_index_sector { shift->_request_sector( 2, @_ ) }
698 sub _request_sector {
700 my ($multiple, $size) = @_;
702 my $chains_offset = $multiple * $self->byte_size;
704 my $old_head = $self->storage->read_at( $self->chains_loc + $chains_offset, $self->byte_size );
705 my $loc = unpack( $StP{$self->byte_size}, $old_head );
707 # We don't have any free sectors of the right size, so allocate a new one.
709 my $offset = $self->storage->request_space( $size );
711 # Zero out the new sector. This also guarantees correct increases
713 $self->storage->print_at( $offset, chr(0) x $size );
718 # Read the new head after the signature and the staleness counter
719 my $new_head = $self->storage->read_at( $loc + SIG_SIZE + STALE_SIZE, $self->byte_size );
720 $self->storage->print_at( $self->chains_loc + $chains_offset, $new_head );
721 $self->storage->print_at(
722 $loc + SIG_SIZE + STALE_SIZE,
723 pack( $StP{$self->byte_size}, 0 ),
729 ################################################################################
731 sub storage { $_[0]{storage} }
732 sub byte_size { $_[0]{byte_size} }
733 sub hash_size { $_[0]{hash_size} }
734 sub hash_chars { $_[0]{hash_chars} }
735 sub num_txns { $_[0]{num_txns} }
736 sub max_buckets { $_[0]{max_buckets} }
737 sub blank_md5 { chr(0) x $_[0]->hash_size }
739 sub trans_id { $_[0]{trans_id} }
740 sub set_trans_id { $_[0]{trans_id} = $_[1] }
742 sub trans_loc { $_[0]{trans_loc} }
743 sub set_trans_loc { $_[0]{trans_loc} = $_[1] }
745 sub chains_loc { $_[0]{chains_loc} }
746 sub set_chains_loc { $_[0]{chains_loc} = $_[1] }
748 ################################################################################
750 package DBM::Deep::Iterator;
758 engine => $args->{engine},
759 base_offset => $args->{base_offset},
762 Scalar::Util::weaken( $self->{engine} );
767 sub reset { $_[0]{breadcrumbs} = [] }
769 sub get_sector_iterator {
773 my $sector = $self->{engine}->_load_sector( $loc )
776 if ( $sector->isa( 'DBM::Deep::Engine::Sector::Index' ) ) {
777 return DBM::Deep::Iterator::Index->new({
782 elsif ( $sector->isa( 'DBM::Deep::Engine::Sector::BucketList' ) ) {
783 return DBM::Deep::Iterator::BucketList->new({
789 DBM::Deep->_throw_error( "get_sector_iterator(): Why did $loc make a $sector?" );
796 my $crumbs = $self->{breadcrumbs};
797 my $e = $self->{engine};
799 unless ( @$crumbs ) {
800 # This will be a Reference sector
801 my $sector = $e->_load_sector( $self->{base_offset} )
802 # If no sector is found, thist must have been deleted from under us.
805 if ( $sector->staleness != $obj->_staleness ) {
809 my $loc = $sector->get_blist_loc
812 push @$crumbs, $self->get_sector_iterator( $loc );
817 unless ( @$crumbs ) {
822 my $iterator = $crumbs->[-1];
824 # This level is done.
825 if ( $iterator->at_end ) {
830 if ( $iterator->isa( 'DBM::Deep::Iterator::Index' ) ) {
831 # If we don't have any more, it will be caught at the
833 if ( my $next = $iterator->get_next_iterator ) {
834 push @$crumbs, $next;
839 unless ( $iterator->isa( 'DBM::Deep::Iterator::BucketList' ) ) {
840 DBM::Deep->_throw_error(
841 "Should have a bucketlist iterator here - instead have $iterator"
845 # At this point, we have a BucketList iterator
846 my $key = $iterator->get_next_key;
847 if ( defined $key ) {
850 #XXX else { $iterator->set_to_end() } ?
852 # We hit the end of the bucketlist iterator, so redo
856 DBM::Deep->_throw_error( "get_next_key(): How did we get here?" );
859 package DBM::Deep::Iterator::Index;
862 my $self = bless $_[1] => $_[0];
863 $self->{curr_index} = 0;
869 return $self->{curr_index} >= $self->{iterator}{engine}->hash_chars;
872 sub get_next_iterator {
877 return if $self->at_end;
878 $loc = $self->{sector}->get_entry( $self->{curr_index}++ );
881 return $self->{iterator}->get_sector_iterator( $loc );
884 package DBM::Deep::Iterator::BucketList;
887 my $self = bless $_[1] => $_[0];
888 $self->{curr_index} = 0;
894 return $self->{curr_index} >= $self->{iterator}{engine}->max_buckets;
900 return if $self->at_end;
902 my $idx = $self->{curr_index}++;
904 my $data_loc = $self->{sector}->get_data_location_for({
909 #XXX Do we want to add corruption checks here?
910 return $self->{sector}->get_key_for( $idx )->data;
913 package DBM::Deep::Engine::Sector;
916 my $self = bless $_[1], $_[0];
917 Scalar::Util::weaken( $self->{engine} );
923 #sub clone { DBM::Deep->_throw_error( "Must be implemented in the child class" ); }
925 sub engine { $_[0]{engine} }
926 sub offset { $_[0]{offset} }
927 sub type { $_[0]{type} }
931 return $self->engine->SIG_SIZE + $self->engine->STALE_SIZE;
937 my $e = $self->engine;
939 $e->storage->print_at( $self->offset, $e->SIG_FREE );
940 # Skip staleness counter
941 $e->storage->print_at( $self->offset + $self->base_size,
942 chr(0) x ($self->size - $self->base_size),
945 my $free_meth = $self->free_meth;
946 $e->$free_meth( $self->offset, $self->size );
951 package DBM::Deep::Engine::Sector::Data;
953 our @ISA = qw( DBM::Deep::Engine::Sector );
956 sub size { return 256 }
957 sub free_meth { return '_add_free_data_sector' }
961 return ref($self)->new({
962 engine => $self->engine,
968 package DBM::Deep::Engine::Sector::Scalar;
970 our @ISA = qw( DBM::Deep::Engine::Sector::Data );
975 my $chain_loc = $self->chain_loc;
977 $self->SUPER::free();
980 $self->engine->_load_sector( $chain_loc )->free;
986 sub type { $_[0]{engine}->SIG_DATA }
990 my $engine = $self->engine;
992 unless ( $self->offset ) {
993 my $data_section = $self->size - $self->base_size - 1 * $engine->byte_size - 1;
995 $self->{offset} = $engine->_request_data_sector( $self->size );
997 my $data = delete $self->{data};
998 my $dlen = length $data;
1000 my $curr_offset = $self->offset;
1001 while ( $continue ) {
1003 my $next_offset = 0;
1005 my ($leftover, $this_len, $chunk);
1006 if ( $dlen > $data_section ) {
1008 $this_len = $data_section;
1009 $chunk = substr( $data, 0, $this_len );
1011 $dlen -= $data_section;
1012 $next_offset = $engine->_request_data_sector( $self->size );
1013 $data = substr( $data, $this_len );
1016 $leftover = $data_section - $dlen;
1023 $engine->storage->print_at( $curr_offset, $self->type ); # Sector type
1025 $engine->storage->print_at( $curr_offset + $self->base_size,
1026 pack( $StP{$engine->byte_size}, $next_offset ), # Chain loc
1027 pack( $StP{1}, $this_len ), # Data length
1028 $chunk, # Data to be stored in this sector
1029 chr(0) x $leftover, # Zero-fill the rest
1032 $curr_offset = $next_offset;
1042 my $buffer = $self->engine->storage->read_at(
1043 $self->offset + $self->base_size + $self->engine->byte_size, 1
1046 return unpack( $StP{1}, $buffer );
1052 $StP{$self->engine->byte_size},
1053 $self->engine->storage->read_at(
1054 $self->offset + $self->base_size,
1055 $self->engine->byte_size,
1065 my $chain_loc = $self->chain_loc;
1067 $data .= $self->engine->storage->read_at(
1068 $self->offset + $self->base_size + $self->engine->byte_size + 1, $self->data_length,
1071 last unless $chain_loc;
1073 $self = $self->engine->_load_sector( $chain_loc );
1079 package DBM::Deep::Engine::Sector::Null;
1081 our @ISA = qw( DBM::Deep::Engine::Sector::Data );
1083 sub type { $_[0]{engine}->SIG_NULL }
1084 sub data_length { 0 }
1090 my $engine = $self->engine;
1092 unless ( $self->offset ) {
1093 my $leftover = $self->size - $self->base_size - 1 * $engine->byte_size - 1;
1095 $self->{offset} = $engine->_request_data_sector( $self->size );
1096 $engine->storage->print_at( $self->offset, $self->type ); # Sector type
1097 # Skip staleness counter
1098 $engine->storage->print_at( $self->offset + $self->base_size,
1099 pack( $StP{$engine->byte_size}, 0 ), # Chain loc
1100 pack( $StP{1}, $self->data_length ), # Data length
1101 chr(0) x $leftover, # Zero-fill the rest
1108 package DBM::Deep::Engine::Sector::Reference;
1110 our @ISA = qw( DBM::Deep::Engine::Sector::Data );
1115 my $e = $self->engine;
1117 unless ( $self->offset ) {
1118 my $classname = Scalar::Util::blessed( delete $self->{data} );
1119 my $leftover = $self->size - $self->base_size - 2 * $e->byte_size;
1121 my $class_offset = 0;
1122 if ( defined $classname ) {
1123 my $class_sector = DBM::Deep::Engine::Sector::Scalar->new({
1127 $class_offset = $class_sector->offset;
1130 $self->{offset} = $e->_request_data_sector( $self->size );
1131 $e->storage->print_at( $self->offset, $self->type ); # Sector type
1132 # Skip staleness counter
1133 $e->storage->print_at( $self->offset + $self->base_size,
1134 pack( $StP{$e->byte_size}, 0 ), # Index/BList loc
1135 pack( $StP{$e->byte_size}, $class_offset ), # Classname loc
1136 chr(0) x $leftover, # Zero-fill the rest
1140 $self->{type} = $e->storage->read_at( $self->offset, 1 );
1143 $self->{staleness} = unpack(
1144 $StP{$e->STALE_SIZE},
1145 $e->storage->read_at( $self->offset + $e->SIG_SIZE, $e->STALE_SIZE ),
1154 my $blist_loc = $self->get_blist_loc;
1155 $self->engine->_load_sector( $blist_loc )->free if $blist_loc;
1157 my $class_loc = $self->get_class_offset;
1158 $self->engine->_load_sector( $class_loc )->free if $class_loc;
1160 $self->SUPER::free();
1163 sub staleness { $_[0]{staleness} }
1169 # Assume that the head is not allowed unless otherwise specified.
1170 $args->{allow_head} = 0 unless exists $args->{allow_head};
1172 # Assume we don't create a new blist location unless otherwise specified.
1173 $args->{create} = 0 unless exists $args->{create};
1175 my $blist = $self->get_bucket_list({
1176 key_md5 => $args->{key_md5},
1177 key => $args->{key},
1178 create => $args->{create},
1180 return unless $blist && $blist->{found};
1182 # At this point, $blist knows where the md5 is. What it -doesn't- know yet
1183 # is whether or not this transaction has this key. That's part of the next
1185 my $location = $blist->get_data_location_for({
1186 allow_head => $args->{allow_head},
1189 return $self->engine->_load_sector( $location );
1196 my $blist = $self->get_bucket_list({
1197 key_md5 => $args->{key_md5},
1198 key => $args->{key},
1200 }) or DBM::Deep->_throw_error( "How did write_data fail (no blist)?!" );
1202 # Handle any transactional bookkeeping.
1203 if ( $self->engine->trans_id ) {
1204 if ( ! $blist->has_md5 ) {
1205 $blist->mark_deleted({
1211 my @trans_ids = $self->engine->get_running_txn_ids;
1212 if ( $blist->has_md5 ) {
1214 my $old_value = $blist->get_data_for;
1215 foreach my $other_trans_id ( @trans_ids ) {
1216 next if $blist->get_data_location_for({
1217 trans_id => $other_trans_id,
1221 trans_id => $other_trans_id,
1222 key => $args->{key},
1223 key_md5 => $args->{key_md5},
1224 value => $old_value->clone,
1231 foreach my $other_trans_id ( @trans_ids ) {
1232 #XXX This doesn't seem to possible to ever happen . . .
1233 next if $blist->get_data_location_for({ trans_id => $other_trans_id, allow_head => 0 });
1234 $blist->mark_deleted({
1235 trans_id => $other_trans_id,
1242 #XXX Is this safe to do transactionally?
1243 # Free the place we're about to write to.
1244 if ( $blist->get_data_location_for({ allow_head => 0 }) ) {
1245 $blist->get_data_for({ allow_head => 0 })->free;
1249 key => $args->{key},
1250 key_md5 => $args->{key_md5},
1251 value => $args->{value},
1259 # XXX What should happen if this fails?
1260 my $blist = $self->get_bucket_list({
1261 key_md5 => $args->{key_md5},
1262 }) or DBM::Deep->_throw_error( "How did delete_key fail (no blist)?!" );
1264 # Save the location so that we can free the data
1265 my $location = $blist->get_data_location_for({
1268 my $old_value = $location && $self->engine->_load_sector( $location );
1270 my @trans_ids = $self->engine->get_running_txn_ids;
1272 if ( $self->engine->trans_id == 0 ) {
1274 foreach my $other_trans_id ( @trans_ids ) {
1275 next if $blist->get_data_location_for({ trans_id => $other_trans_id, allow_head => 0 });
1277 trans_id => $other_trans_id,
1278 key => $args->{key},
1279 key_md5 => $args->{key_md5},
1280 value => $old_value->clone,
1288 $blist->mark_deleted( $args );
1291 $data = $old_value->data;
1296 $data = $blist->delete_md5( $args );
1305 my $e = $self->engine;
1306 my $blist_loc = $e->storage->read_at( $self->offset + $self->base_size, $e->byte_size );
1307 return unpack( $StP{$e->byte_size}, $blist_loc );
1310 sub get_bucket_list {
1315 # XXX Add in check here for recycling?
1317 my $engine = $self->engine;
1319 my $blist_loc = $self->get_blist_loc;
1321 # There's no index or blist yet
1322 unless ( $blist_loc ) {
1323 return unless $args->{create};
1325 my $blist = DBM::Deep::Engine::Sector::BucketList->new({
1327 key_md5 => $args->{key_md5},
1330 $engine->storage->print_at( $self->offset + $self->base_size,
1331 pack( $StP{$engine->byte_size}, $blist->offset ),
1337 my $sector = $engine->_load_sector( $blist_loc )
1338 or DBM::Deep->_throw_error( "Cannot read sector at $blist_loc in get_bucket_list()" );
1340 my $last_sector = undef;
1341 while ( $sector->isa( 'DBM::Deep::Engine::Sector::Index' ) ) {
1342 $blist_loc = $sector->get_entry( ord( substr( $args->{key_md5}, $i++, 1 ) ) );
1343 $last_sector = $sector;
1345 $sector = $engine->_load_sector( $blist_loc )
1346 or DBM::Deep->_throw_error( "Cannot read sector at $blist_loc in get_bucket_list()" );
1354 # This means we went through the Index sector(s) and found an empty slot
1355 unless ( $sector ) {
1356 return unless $args->{create};
1358 DBM::Deep->_throw_error( "No last_sector when attempting to build a new entry" )
1359 unless $last_sector;
1361 my $blist = DBM::Deep::Engine::Sector::BucketList->new({
1363 key_md5 => $args->{key_md5},
1366 $last_sector->set_entry( ord( substr( $args->{key_md5}, $i - 1, 1 ) ) => $blist->offset );
1371 $sector->find_md5( $args->{key_md5} );
1373 # See whether or not we need to reindex the bucketlist
1374 if ( !$sector->has_md5 && $args->{create} && $sector->{idx} == -1 ) {
1375 my $new_index = DBM::Deep::Engine::Sector::Index->new({
1380 #XXX q.v. the comments for this function.
1381 foreach my $entry ( $sector->chopped_up ) {
1382 my ($spot, $md5) = @{$entry};
1383 my $idx = ord( substr( $md5, $i, 1 ) );
1385 # XXX This is inefficient
1386 my $blist = $blist_cache{$idx}
1387 ||= DBM::Deep::Engine::Sector::BucketList->new({
1391 $new_index->set_entry( $idx => $blist->offset );
1393 my $new_spot = $blist->write_at_next_open( $md5 );
1394 $engine->reindex_entry( $spot => $new_spot );
1397 # Handle the new item separately.
1399 my $idx = ord( substr( $args->{key_md5}, $i, 1 ) );
1400 my $blist = $blist_cache{$idx}
1401 ||= DBM::Deep::Engine::Sector::BucketList->new({
1405 $new_index->set_entry( $idx => $blist->offset );
1408 $blist->find_md5( $args->{key_md5} );
1410 key => $args->{key},
1411 key_md5 => $args->{key_md5},
1412 value => DBM::Deep::Engine::Sector::Null->new({
1419 if ( $last_sector ) {
1420 $last_sector->set_entry(
1421 ord( substr( $args->{key_md5}, $i - 1, 1 ) ),
1425 $engine->storage->print_at( $self->offset + $self->base_size,
1426 pack( $StP{$engine->byte_size}, $new_index->offset ),
1432 $sector = $blist_cache{ ord( substr( $args->{key_md5}, $i, 1 ) ) };
1433 $sector->find_md5( $args->{key_md5} );
1439 sub get_class_offset {
1442 my $e = $self->engine;
1444 $StP{$e->byte_size},
1445 $e->storage->read_at(
1446 $self->offset + $self->base_size + 1 * $e->byte_size, $e->byte_size,
1454 my $class_offset = $self->get_class_offset;
1456 return unless $class_offset;
1458 return $self->engine->_load_sector( $class_offset )->data;
1461 #XXX Add singleton handling here
1465 my $new_obj = DBM::Deep->new({
1466 type => $self->type,
1467 base_offset => $self->offset,
1468 staleness => $self->staleness,
1469 storage => $self->engine->storage,
1470 engine => $self->engine,
1473 if ( $self->engine->storage->{autobless} ) {
1474 my $classname = $self->get_classname;
1475 if ( defined $classname ) {
1476 bless $new_obj, $classname;
1483 package DBM::Deep::Engine::Sector::BucketList;
1485 our @ISA = qw( DBM::Deep::Engine::Sector );
1490 my $engine = $self->engine;
1492 unless ( $self->offset ) {
1493 my $leftover = $self->size - $self->base_size;
1495 $self->{offset} = $engine->_request_blist_sector( $self->size );
1496 $engine->storage->print_at( $self->offset, $engine->SIG_BLIST ); # Sector type
1497 # Skip staleness counter
1498 $engine->storage->print_at( $self->offset + $self->base_size,
1499 chr(0) x $leftover, # Zero-fill the data
1503 if ( $self->{key_md5} ) {
1512 unless ( $self->{size} ) {
1513 my $e = $self->engine;
1514 # Base + numbuckets * bucketsize
1515 $self->{size} = $self->base_size + $e->max_buckets * $self->bucket_size;
1517 return $self->{size};
1520 sub free_meth { return '_add_free_blist_sector' }
1524 unless ( $self->{bucket_size} ) {
1525 my $e = $self->engine;
1526 # Key + head (location) + transactions (location + staleness-counter)
1527 my $location_size = $e->byte_size + $e->num_txns * ( $e->byte_size + 4 );
1528 $self->{bucket_size} = $e->hash_size + $location_size;
1530 return $self->{bucket_size};
1533 # XXX This is such a poor hack. I need to rethink this code.
1537 my $e = $self->engine;
1540 foreach my $idx ( 0 .. $e->max_buckets - 1 ) {
1541 my $spot = $self->offset + $self->base_size + $idx * $self->bucket_size;
1542 my $md5 = $e->storage->read_at( $spot, $e->hash_size );
1544 #XXX If we're chopping, why would we ever have the blank_md5?
1545 last if $md5 eq $e->blank_md5;
1547 my $rest = $e->storage->read_at( undef, $self->bucket_size - $e->hash_size );
1548 push @buckets, [ $spot, $md5 . $rest ];
1554 sub write_at_next_open {
1558 #XXX This is such a hack!
1559 $self->{_next_open} = 0 unless exists $self->{_next_open};
1561 my $spot = $self->offset + $self->base_size + $self->{_next_open}++ * $self->bucket_size;
1562 $self->engine->storage->print_at( $spot, $entry );
1569 unless ( exists $self->{found} ) {
1572 return $self->{found};
1578 $self->{found} = undef;
1582 $self->{key_md5} = shift;
1585 # If we don't have an MD5, then what are we supposed to do?
1586 unless ( exists $self->{key_md5} ) {
1587 DBM::Deep->_throw_error( "Cannot find_md5 without a key_md5 set" );
1590 my $e = $self->engine;
1591 foreach my $idx ( 0 .. $e->max_buckets - 1 ) {
1592 my $potential = $e->storage->read_at(
1593 $self->offset + $self->base_size + $idx * $self->bucket_size, $e->hash_size,
1596 if ( $potential eq $e->blank_md5 ) {
1597 $self->{idx} = $idx;
1601 if ( $potential eq $self->{key_md5} ) {
1603 $self->{idx} = $idx;
1615 DBM::Deep->_throw_error( "write_md5: no key" ) unless exists $args->{key};
1616 DBM::Deep->_throw_error( "write_md5: no key_md5" ) unless exists $args->{key_md5};
1617 DBM::Deep->_throw_error( "write_md5: no value" ) unless exists $args->{value};
1619 my $engine = $self->engine;
1621 $args->{trans_id} = $engine->trans_id unless exists $args->{trans_id};
1623 my $spot = $self->offset + $self->base_size + $self->{idx} * $self->bucket_size;
1624 $engine->add_entry( $args->{trans_id}, $spot );
1626 unless ($self->{found}) {
1627 my $key_sector = DBM::Deep::Engine::Sector::Scalar->new({
1629 data => $args->{key},
1632 $engine->storage->print_at( $spot,
1634 pack( $StP{$engine->byte_size}, $key_sector->offset ),
1639 + $engine->hash_size
1640 + $engine->byte_size
1641 + $args->{trans_id} * ( $engine->byte_size + 4 );
1643 $engine->storage->print_at( $loc,
1644 pack( $StP{$engine->byte_size}, $args->{value}->offset ),
1645 pack( 'N', $engine->get_txn_staleness_counter( $args->{trans_id} ) ),
1654 my $engine = $self->engine;
1656 $args->{trans_id} = $engine->trans_id unless exists $args->{trans_id};
1658 my $spot = $self->offset + $self->base_size + $self->{idx} * $self->bucket_size;
1659 $engine->add_entry( $args->{trans_id}, $spot );
1662 + $engine->hash_size
1663 + $engine->byte_size
1664 + $args->{trans_id} * ( $engine->byte_size + 4 );
1666 $engine->storage->print_at( $loc,
1667 pack( $StP{$engine->byte_size}, 1 ), # 1 is the marker for deleted
1668 pack( 'N', $engine->get_txn_staleness_counter( $args->{trans_id} ) ),
1676 my $engine = $self->engine;
1677 return undef unless $self->{found};
1679 # Save the location so that we can free the data
1680 my $location = $self->get_data_location_for({
1683 my $key_sector = $self->get_key_for;
1685 my $spot = $self->offset + $self->base_size + $self->{idx} * $self->bucket_size;
1686 $engine->storage->print_at( $spot,
1687 $engine->storage->read_at(
1688 $spot + $self->bucket_size,
1689 $self->bucket_size * ( $engine->max_buckets - $self->{idx} - 1 ),
1691 chr(0) x $self->bucket_size,
1696 my $data_sector = $self->engine->_load_sector( $location );
1697 my $data = $data_sector->data;
1703 sub get_data_location_for {
1708 $args->{allow_head} = 0 unless exists $args->{allow_head};
1709 $args->{trans_id} = $self->engine->trans_id unless exists $args->{trans_id};
1710 $args->{idx} = $self->{idx} unless exists $args->{idx};
1712 my $e = $self->engine;
1714 my $spot = $self->offset + $self->base_size
1715 + $args->{idx} * $self->bucket_size
1718 + $args->{trans_id} * ( $e->byte_size + 4 );
1720 my $buffer = $e->storage->read_at(
1724 my ($loc, $staleness) = unpack( $StP{$e->byte_size} . ' N', $buffer );
1726 # We have found an entry that is old, so get rid of it
1727 if ( $staleness != (my $s = $e->get_txn_staleness_counter( $args->{trans_id} ) ) ) {
1728 $e->storage->print_at(
1730 pack( $StP{$e->byte_size} . ' N', (0) x 2 ),
1735 # If we're in a transaction and we never wrote to this location, try the
1737 if ( $args->{trans_id} && !$loc && $args->{allow_head} ) {
1738 return $self->get_data_location_for({
1741 idx => $args->{idx},
1744 return $loc <= 1 ? 0 : $loc;
1752 return unless $self->{found};
1753 my $location = $self->get_data_location_for({
1754 allow_head => $args->{allow_head},
1756 return $self->engine->_load_sector( $location );
1762 $idx = $self->{idx} unless defined $idx;
1764 if ( $idx >= $self->engine->max_buckets ) {
1765 DBM::Deep->_throw_error( "get_key_for(): Attempting to retrieve $idx" );
1768 my $location = $self->engine->storage->read_at(
1769 $self->offset + $self->base_size + $idx * $self->bucket_size + $self->engine->hash_size,
1770 $self->engine->byte_size,
1772 $location = unpack( $StP{$self->engine->byte_size}, $location );
1773 DBM::Deep->_throw_error( "get_key_for: No location?" ) unless $location;
1775 return $self->engine->_load_sector( $location );
1778 package DBM::Deep::Engine::Sector::Index;
1780 our @ISA = qw( DBM::Deep::Engine::Sector );
1785 my $engine = $self->engine;
1787 unless ( $self->offset ) {
1788 my $leftover = $self->size - $self->base_size;
1790 $self->{offset} = $engine->_request_index_sector( $self->size );
1791 $engine->storage->print_at( $self->offset, $engine->SIG_INDEX ); # Sector type
1792 # Skip staleness counter
1793 $engine->storage->print_at( $self->offset + $self->base_size,
1794 chr(0) x $leftover, # Zero-fill the rest
1803 unless ( $self->{size} ) {
1804 my $e = $self->engine;
1805 $self->{size} = $self->base_size + $e->byte_size * $e->hash_chars;
1807 return $self->{size};
1810 sub free_meth { return '_add_free_index_sector' }
1814 my $e = $self->engine;
1816 for my $i ( 0 .. $e->hash_chars - 1 ) {
1817 my $l = $self->get_entry( $i ) or next;
1818 $e->_load_sector( $l )->free;
1821 $self->SUPER::free();
1827 return $self->offset + $self->base_size + $idx * $self->engine->byte_size;
1834 my $e = $self->engine;
1836 DBM::Deep->_throw_error( "get_entry: Out of range ($idx)" )
1837 if $idx < 0 || $idx >= $e->hash_chars;
1840 $StP{$e->byte_size},
1841 $e->storage->read_at( $self->_loc_for( $idx ), $e->byte_size ),
1847 my ($idx, $loc) = @_;
1849 my $e = $self->engine;
1851 DBM::Deep->_throw_error( "set_entry: Out of range ($idx)" )
1852 if $idx < 0 || $idx >= $e->hash_chars;
1854 $self->engine->storage->print_at(
1855 $self->_loc_for( $idx ),
1856 pack( $StP{$e->byte_size}, $loc ),