r14213@rob-kinyons-computer (orig r8080): rkinyon | 2006-11-17 20:47:50 -0500
[dbsrgits/DBM-Deep.git] / lib / DBM / Deep / Engine.pm
CommitLineData
a20d9a3f 1package DBM::Deep::Engine;
2
2120a181 3use 5.006_000;
460b1067 4
a20d9a3f 5use strict;
6
2120a181 7our $VERSION = q(0.99_04);
86867f3a 8
359a01ac 9use Scalar::Util ();
a20d9a3f 10
21838116 11# File-wide notes:
2120a181 12# * Every method in here assumes that the storage has been appropriately
c3aafc14 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
15# been done.
21838116 16
8db25060 17# Setup file and tag signatures. These should never change.
8db25060 18sub SIG_FILE () { 'DPDB' }
460b1067 19sub SIG_HEADER () { 'h' }
8db25060 20sub SIG_INTERNAL () { 'i' }
21sub SIG_HASH () { 'H' }
22sub SIG_ARRAY () { 'A' }
8db25060 23sub SIG_NULL () { 'N' }
24sub SIG_DATA () { 'D' }
25sub SIG_INDEX () { 'I' }
26sub SIG_BLIST () { 'B' }
7b1e1aa1 27sub SIG_FREE () { 'F' }
86867f3a 28sub SIG_KEYS () { 'K' }
8db25060 29sub SIG_SIZE () { 1 }
2120a181 30sub STALE_SIZE () { 1 }
8db25060 31
2120a181 32# Please refer to the pack() documentation for further information
33my %StP = (
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)
38);
83371fe3 39
c3aafc14 40################################################################################
c3aafc14 41
612969fb 42sub new {
43 my $class = shift;
44 my ($args) = @_;
45
46 my $self = bless {
2120a181 47 byte_size => 4,
48
49 digest => undef,
50 hash_size => 16, # In bytes
51 hash_chars => 256, # Number of chars the algorithm uses per byte
612969fb 52 max_buckets => 16,
2120a181 53 num_txns => 2, # HEAD plus 1 additional transaction for importing
54 trans_id => 0, # Default to the HEAD
460b1067 55
2120a181 56 entries => {}, # This is the list of entries for transactions
83371fe3 57 storage => undef,
612969fb 58 }, $class;
59
e0098e7f 60 if ( defined $args->{pack_size} ) {
61 if ( lc $args->{pack_size} eq 'small' ) {
2120a181 62 $args->{byte_size} = 2;
e0098e7f 63 }
64 elsif ( lc $args->{pack_size} eq 'medium' ) {
2120a181 65 $args->{byte_size} = 4;
e0098e7f 66 }
67 elsif ( lc $args->{pack_size} eq 'large' ) {
2120a181 68 $args->{byte_size} = 8;
e0098e7f 69 }
70 else {
2120a181 71 DBM::Deep->_throw_error( "Unknown pack_size value: '$args->{pack_size}'" );
e0098e7f 72 }
73 }
74
fde3db1a 75 # Grab the parameters we want to use
76 foreach my $param ( keys %$self ) {
77 next unless exists $args->{$param};
3e9498a1 78 $self->{$param} = $args->{$param};
fde3db1a 79 }
80
2120a181 81 ##
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
85 # reindex overrun.
86 ##
e0098e7f 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;
90 }
91
2120a181 92 if ( !$self->{digest} ) {
93 require Digest::MD5;
94 $self->{digest} = \&Digest::MD5::md5;
95 }
96
260a80b4 97 return $self;
98}
99
2120a181 100################################################################################
460b1067 101
2120a181 102sub read_value {
c3aafc14 103 my $self = shift;
2120a181 104 my ($obj, $key) = @_;
105
106 # This will be a Reference sector
107 my $sector = $self->_load_sector( $obj->_base_offset )
108 or return;
109
110 if ( $sector->staleness != $obj->_staleness ) {
111 return;
112 }
113
114 my $key_md5 = $self->_apply_digest( $key );
115
116 my $value_sector = $sector->get_data_for({
117 key_md5 => $key_md5,
118 allow_head => 1,
119 });
120
121 unless ( $value_sector ) {
122 $value_sector = DBM::Deep::Engine::Sector::Null->new({
123 engine => $self,
124 data => undef,
125 });
126
127 $sector->write_data({
128 key_md5 => $key_md5,
129 key => $key,
130 value => $value_sector,
131 });
132 }
133
134 return $value_sector->data;
c3aafc14 135}
136
2120a181 137sub get_classname {
260a80b4 138 my $self = shift;
2120a181 139 my ($obj) = @_;
260a80b4 140
2120a181 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')?!" );
612969fb 144
2120a181 145 if ( $sector->staleness != $obj->_staleness ) {
146 return;
147 }
ea2f6d67 148
2120a181 149 return $sector->get_classname;
1bf65be7 150}
151
2120a181 152sub key_exists {
0d0f3d5d 153 my $self = shift;
2120a181 154 my ($obj, $key) = @_;
0d0f3d5d 155
2120a181 156 # This will be a Reference sector
157 my $sector = $self->_load_sector( $obj->_base_offset )
158 or return '';
0d0f3d5d 159
2120a181 160 if ( $sector->staleness != $obj->_staleness ) {
161 return '';
162 }
0d0f3d5d 163
2120a181 164 my $data = $sector->get_data_for({
165 key_md5 => $self->_apply_digest( $key ),
166 allow_head => 1,
167 });
20b7f047 168
2120a181 169 # exists() returns 1 or '' for true/false.
170 return $data ? 1 : '';
0d0f3d5d 171}
172
2120a181 173sub delete_key {
e064ccd1 174 my $self = shift;
2120a181 175 my ($obj, $key) = @_;
e064ccd1 176
2120a181 177 my $sector = $self->_load_sector( $obj->_base_offset )
178 or return;
460b1067 179
2120a181 180 if ( $sector->staleness != $obj->_staleness ) {
181 return;
182 }
183
184 return $sector->delete_key({
185 key_md5 => $self->_apply_digest( $key ),
186 allow_head => 0,
187 });
188}
189
190sub write_value {
191 my $self = shift;
192 my ($obj, $key, $value) = @_;
193
194 my $r = Scalar::Util::reftype( $value ) || '';
195 {
196 last if $r eq '';
197 last if $r eq 'HASH';
198 last if $r eq 'ARRAY';
e064ccd1 199
2120a181 200 DBM::Deep->_throw_error(
201 "Storage of references of type '$r' is not supported."
202 );
460b1067 203 }
260a80b4 204
2120a181 205 my ($class, $type);
206 if ( !defined $value ) {
207 $class = 'DBM::Deep::Engine::Sector::Null';
208 }
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." );
212 }
213 if ( $r eq 'HASH' && tied(%$value) ) {
214 DBM::Deep->_throw_error( "Cannot store something that is tied." );
215 }
216 $class = 'DBM::Deep::Engine::Sector::Reference';
217 $type = substr( $r, 0, 1 );
218 }
219 else {
220 $class = 'DBM::Deep::Engine::Sector::Scalar';
460b1067 221 }
9b2370e0 222
2120a181 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." );
15ba72cc 226
2120a181 227 if ( $sector->staleness != $obj->_staleness ) {
228 DBM::Deep->_throw_error( "Cannot write to a deleted spot in DBM::Deep.n" );
229 }
15ba72cc 230
2120a181 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({
234 engine => $self,
235 data => $value,
236 type => $type,
237 });
238
239 $sector->write_data({
240 key => $key,
241 key_md5 => $self->_apply_digest( $key ),
242 value => $value_sector,
243 });
244
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' ) {
251 my @temp = @$value;
252 tie @$value, 'DBM::Deep', {
253 base_offset => $value_sector->offset,
254 staleness => $value_sector->staleness,
255 storage => $self->storage,
256 engine => $self,
257 };
258 @$value = @temp;
259 bless $value, 'DBM::Deep::Array' unless Scalar::Util::blessed( $value );
e064ccd1 260 }
2120a181 261 elsif ( $r eq 'HASH' ) {
262 my %temp = %$value;
263 tie %$value, 'DBM::Deep', {
264 base_offset => $value_sector->offset,
265 staleness => $value_sector->staleness,
266 storage => $self->storage,
267 engine => $self,
268 };
e064ccd1 269
2120a181 270 %$value = %temp;
271 bless $value, 'DBM::Deep::Hash' unless Scalar::Util::blessed( $value );
272 }
460b1067 273
2120a181 274 return 1;
e064ccd1 275}
276
2120a181 277# XXX Add staleness here
278sub get_next_key {
460b1067 279 my $self = shift;
2120a181 280 my ($obj, $prev_key) = @_;
70b55428 281
2120a181 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,
286 engine => $self,
287 });
288 }
118ba343 289
2120a181 290 return $obj->{iterator}->get_next_key( $obj );
291}
118ba343 292
2120a181 293################################################################################
260a80b4 294
2120a181 295sub setup_fh {
296 my $self = shift;
297 my ($obj) = @_;
359a01ac 298
2120a181 299 # We're opening the file.
300 unless ( $obj->_base_offset ) {
301 my $bytes_read = $self->_read_file_header;
118ba343 302
2120a181 303 # Creating a new file
304 unless ( $bytes_read ) {
305 $self->_write_file_header;
118ba343 306
2120a181 307 # 1) Create Array/Hash entry
308 my $initial_reference = DBM::Deep::Engine::Sector::Reference->new({
309 engine => $self,
310 type => $obj->_type,
311 });
312 $obj->{base_offset} = $initial_reference->offset;
313 $obj->{staleness} = $initial_reference->staleness;
118ba343 314
2120a181 315 $self->storage->flush;
118ba343 316 }
2120a181 317 # Reading from an existing file
118ba343 318 else {
319 $obj->{base_offset} = $bytes_read;
2120a181 320 my $initial_reference = DBM::Deep::Engine::Sector::Reference->new({
321 engine => $self,
322 offset => $obj->_base_offset,
323 });
324 unless ( $initial_reference ) {
325 DBM::Deep->_throw_error("Corrupted file, no master index record");
359a01ac 326 }
118ba343 327
2120a181 328 unless ($obj->_type eq $initial_reference->type) {
329 DBM::Deep->_throw_error("File type mismatch");
118ba343 330 }
2120a181 331
332 $obj->{staleness} = $initial_reference->staleness;
118ba343 333 }
118ba343 334 }
2120a181 335
336 return 1;
337}
338
339sub begin_work {
340 my $self = shift;
341 my ($obj) = @_;
342
343 if ( $self->trans_id ) {
344 DBM::Deep->_throw_error( "Cannot begin_work within an active transaction" );
345 }
346
347 my @slots = $self->read_txn_slots;
348 for my $i ( 1 .. @slots ) {
349 next if $slots[$i];
350 $slots[$i] = 1;
351 $self->set_trans_id( $i );
352 last;
353 }
354 $self->write_txn_slots( @slots );
355
356 if ( !$self->trans_id ) {
357 DBM::Deep->_throw_error( "Cannot begin_work - no available transactions" );
358 }
359
360 return;
361}
362
363sub rollback {
364 my $self = shift;
365 my ($obj) = @_;
366
367 if ( !$self->trans_id ) {
368 DBM::Deep->_throw_error( "Cannot rollback without an active transaction" );
369 }
370
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
376 + $self->hash_size
377 + $self->byte_size
378 + $self->trans_id * ( $self->byte_size + 4 );
379
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 ) );
383
384 if ( $data_loc > 1 ) {
385 $self->_load_sector( $data_loc )->free;
386 }
260a80b4 387 }
e06824f8 388
2120a181 389 $self->clear_entries;
70b55428 390
2120a181 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 );
6fde4ed2 396
70b55428 397 return 1;
398}
399
2120a181 400sub commit {
16d1ad9b 401 my $self = shift;
2120a181 402 my ($obj) = @_;
403
404 if ( !$self->trans_id ) {
405 DBM::Deep->_throw_error( "Cannot commit without an active transaction" );
406 }
407
408 foreach my $entry (@{ $self->get_entries } ) {
409 # Overwrite the entry in head with the entry in trans_id
410 my $base = $entry
411 + $self->hash_size
412 + $self->byte_size;
413
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,
418 );
419
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 ),
424 );
425
426 if ( $head_loc > 1 ) {
427 $self->_load_sector( $head_loc )->free;
428 }
429 }
430
431 $self->clear_entries;
432
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 );
438
439 return 1;
16d1ad9b 440}
441
2120a181 442sub read_txn_slots {
d4b1166e 443 my $self = shift;
2120a181 444 return split '', unpack( 'b32',
445 $self->storage->read_at(
446 $self->trans_loc, 4,
447 )
448 );
449}
20f7b20c 450
2120a181 451sub write_txn_slots {
452 my $self = shift;
453 $self->storage->print_at( $self->trans_loc,
454 pack( 'b32', join('', @_) ),
7dcefff3 455 );
2120a181 456}
457
458sub get_running_txn_ids {
459 my $self = shift;
460 my @transactions = $self->read_txn_slots;
461 my @trans_ids = grep { $transactions[$_] } 0 .. $#transactions;
462}
463
464sub get_txn_staleness_counter {
465 my $self = shift;
466 my ($trans_id) = @_;
20f7b20c 467
2120a181 468 # Hardcode staleness of 0 for the HEAD
469 return 0 unless $trans_id;
f37c15ab 470
2120a181 471 my $x = unpack( 'N',
472 $self->storage->read_at(
473 $self->trans_loc + 4 * $trans_id,
474 4,
475 )
476 );
477 return $x;
d4b1166e 478}
479
2120a181 480sub inc_txn_staleness_counter {
d4b1166e 481 my $self = shift;
2120a181 482 my ($trans_id) = @_;
20f7b20c 483
2120a181 484 # Hardcode staleness of 0 for the HEAD
485 return unless $trans_id;
20f7b20c 486
2120a181 487 $self->storage->print_at(
488 $self->trans_loc + 4 * $trans_id,
489 pack( 'N', $self->get_txn_staleness_counter( $trans_id ) + 1 ),
86867f3a 490 );
2120a181 491}
20f7b20c 492
2120a181 493sub get_entries {
494 my $self = shift;
495 return [ keys %{ $self->{entries}{$self->trans_id} ||= {} } ];
d4b1166e 496}
497
2120a181 498sub add_entry {
ea2f6d67 499 my $self = shift;
2120a181 500 my ($trans_id, $loc) = @_;
ea2f6d67 501
2120a181 502 $self->{entries}{$trans_id} ||= {};
503 $self->{entries}{$trans_id}{$loc} = undef;
504}
ea2f6d67 505
2120a181 506# If the buckets are being relocated because of a reindexing, the entries
507# mechanism needs to be made aware of it.
508sub reindex_entry {
509 my $self = shift;
510 my ($old_loc, $new_loc) = @_;
511
512 TRANS:
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;
518 next TRANS;
519 }
520 }
ea2f6d67 521 }
ea2f6d67 522}
523
2120a181 524sub clear_entries {
d4b1166e 525 my $self = shift;
2120a181 526 delete $self->{entries}{$self->trans_id};
527}
eea0d863 528
2120a181 529################################################################################
eea0d863 530
2120a181 531{
532 my $header_fixed = length( SIG_FILE ) + 1 + 4 + 4;
533
534 sub _write_file_header {
535 my $self = shift;
536
537 my $header_var = 1 + 1 + 1 + 4 + 4 * $self->num_txns + 3 * $self->byte_size;
538
539 my $loc = $self->storage->request_space( $header_fixed + $header_var );
540
541 $self->storage->print_at( $loc,
542 SIG_FILE,
543 SIG_HEADER,
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)
eea0d863 555 );
eea0d863 556
2120a181 557 $self->set_trans_loc( $header_fixed + 3 );
558 $self->set_chains_loc( $header_fixed + 3 + 4 + 4 * $self->num_txns );
20f7b20c 559
2120a181 560 return;
c9b6d0d8 561 }
75be6413 562
2120a181 563 sub _read_file_header {
564 my $self = shift;
ea2f6d67 565
2120a181 566 my $buffer = $self->storage->read_at( 0, $header_fixed );
567 return unless length($buffer);
019404df 568
2120a181 569 my ($file_signature, $sig_header, $header_version, $size) = unpack(
570 'A4 A N N', $buffer
571 );
ea2f6d67 572
2120a181 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" );
576 }
ea2f6d67 577
2120a181 578 unless ( $sig_header eq SIG_HEADER ) {
579 $self->storage->close;
580 DBM::Deep->_throw_error( "Old file version found." );
75be6413 581 }
504185fb 582
2120a181 583 my $buffer2 = $self->storage->read_at( undef, $size );
584 my @values = unpack( 'C C C', $buffer2 );
386bab6c 585
2120a181 586 if ( @values != 3 || grep { !defined } @values ) {
587 $self->storage->close;
588 DBM::Deep->_throw_error("Corrupted file - bad header");
ea2f6d67 589 }
590
2120a181 591 $self->set_trans_loc( $header_fixed + scalar(@values) );
592 $self->set_chains_loc( $header_fixed + scalar(@values) + 4 + 4 * $self->num_txns );
c9b6d0d8 593
2120a181 594 #XXX Add warnings if values weren't set right
595 @{$self}{qw(byte_size max_buckets num_txns)} = @values;
ea2f6d67 596
2120a181 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)." );
c9b6d0d8 601 }
20f7b20c 602
2120a181 603 return length($buffer) + length($buffer2);
604 }
d5d7c51d 605}
606
2120a181 607sub _load_sector {
d5d7c51d 608 my $self = shift;
2120a181 609 my ($offset) = @_;
d5d7c51d 610
2120a181 611 # Add a catch for offset of 0 or 1
612 return if $offset <= 1;
d5d7c51d 613
2120a181 614 my $type = $self->storage->read_at( $offset, 1 );
615 return if $type eq chr(0);
d5d7c51d 616
2120a181 617 if ( $type eq $self->SIG_ARRAY || $type eq $self->SIG_HASH ) {
618 return DBM::Deep::Engine::Sector::Reference->new({
619 engine => $self,
620 type => $type,
621 offset => $offset,
622 });
f37c15ab 623 }
2120a181 624 # XXX Don't we need key_md5 here?
625 elsif ( $type eq $self->SIG_BLIST ) {
626 return DBM::Deep::Engine::Sector::BucketList->new({
627 engine => $self,
628 type => $type,
629 offset => $offset,
630 });
d5d7c51d 631 }
2120a181 632 elsif ( $type eq $self->SIG_INDEX ) {
633 return DBM::Deep::Engine::Sector::Index->new({
634 engine => $self,
635 type => $type,
636 offset => $offset,
637 });
d5d7c51d 638 }
2120a181 639 elsif ( $type eq $self->SIG_NULL ) {
640 return DBM::Deep::Engine::Sector::Null->new({
641 engine => $self,
642 type => $type,
643 offset => $offset,
644 });
d5d7c51d 645 }
2120a181 646 elsif ( $type eq $self->SIG_DATA ) {
647 return DBM::Deep::Engine::Sector::Scalar->new({
648 engine => $self,
649 type => $type,
650 offset => $offset,
651 });
9d4fa373 652 }
2120a181 653 # This was deleted from under us, so just return and let the caller figure it out.
654 elsif ( $type eq $self->SIG_FREE ) {
655 return;
20f7b20c 656 }
d4b1166e 657
2120a181 658 DBM::Deep->_throw_error( "'$offset': Don't know what to do with type '$type'" );
d4b1166e 659}
660
2120a181 661sub _apply_digest {
75be6413 662 my $self = shift;
2120a181 663 return $self->{digest}->(@_);
664}
16d1ad9b 665
2120a181 666sub _add_free_blist_sector { shift->_add_free_sector( 0, @_ ) }
667sub _add_free_data_sector { shift->_add_free_sector( 1, @_ ) }
668sub _add_free_index_sector { shift->_add_free_sector( 2, @_ ) }
75be6413 669
2120a181 670sub _add_free_sector {
671 my $self = shift;
672 my ($multiple, $offset, $size) = @_;
75be6413 673
2120a181 674 my $chains_offset = $multiple * $self->byte_size;
75be6413 675
2120a181 676 my $storage = $self->storage;
75be6413 677
2120a181 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 ) );
75be6413 683
2120a181 684 my $old_head = $storage->read_at( $self->chains_loc + $chains_offset, $self->byte_size );
75be6413 685
2120a181 686 $storage->print_at( $self->chains_loc + $chains_offset,
687 pack( $StP{$self->byte_size}, $offset ),
688 );
75be6413 689
2120a181 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 );
692}
75be6413 693
2120a181 694sub _request_blist_sector { shift->_request_sector( 0, @_ ) }
695sub _request_data_sector { shift->_request_sector( 1, @_ ) }
696sub _request_index_sector { shift->_request_sector( 2, @_ ) }
7b1e1aa1 697
2120a181 698sub _request_sector {
699 my $self = shift;
700 my ($multiple, $size) = @_;
75be6413 701
2120a181 702 my $chains_offset = $multiple * $self->byte_size;
2603d86e 703
2120a181 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 );
75be6413 706
2120a181 707 # We don't have any free sectors of the right size, so allocate a new one.
708 unless ( $loc ) {
709 my $offset = $self->storage->request_space( $size );
7b1e1aa1 710
2120a181 711 # Zero out the new sector. This also guarantees correct increases
712 # in the filesize.
713 $self->storage->print_at( $offset, chr(0) x $size );
7b1e1aa1 714
2120a181 715 return $offset;
7b1e1aa1 716 }
717
2120a181 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 ),
7b1e1aa1 724 );
75be6413 725
2120a181 726 return $loc;
75be6413 727}
728
2120a181 729################################################################################
8db25060 730
2120a181 731sub storage { $_[0]{storage} }
732sub byte_size { $_[0]{byte_size} }
733sub hash_size { $_[0]{hash_size} }
734sub hash_chars { $_[0]{hash_chars} }
735sub num_txns { $_[0]{num_txns} }
736sub max_buckets { $_[0]{max_buckets} }
737sub blank_md5 { chr(0) x $_[0]->hash_size }
8db25060 738
2120a181 739sub trans_id { $_[0]{trans_id} }
740sub set_trans_id { $_[0]{trans_id} = $_[1] }
8db25060 741
2120a181 742sub trans_loc { $_[0]{trans_loc} }
743sub set_trans_loc { $_[0]{trans_loc} = $_[1] }
744
745sub chains_loc { $_[0]{chains_loc} }
746sub set_chains_loc { $_[0]{chains_loc} = $_[1] }
747
748################################################################################
749
750package DBM::Deep::Iterator;
751
752sub new {
753 my $class = shift;
754 my ($args) = @_;
755
756 my $self = bless {
757 breadcrumbs => [],
758 engine => $args->{engine},
759 base_offset => $args->{base_offset},
760 }, $class;
761
762 Scalar::Util::weaken( $self->{engine} );
763
764 return $self;
765}
766
767sub reset { $_[0]{breadcrumbs} = [] }
768
769sub get_sector_iterator {
770 my $self = shift;
771 my ($loc) = @_;
772
773 my $sector = $self->{engine}->_load_sector( $loc )
774 or return;
775
776 if ( $sector->isa( 'DBM::Deep::Engine::Sector::Index' ) ) {
777 return DBM::Deep::Iterator::Index->new({
778 iterator => $self,
779 sector => $sector,
685e40f1 780 });
2120a181 781 }
782 elsif ( $sector->isa( 'DBM::Deep::Engine::Sector::BucketList' ) ) {
783 return DBM::Deep::Iterator::BucketList->new({
784 iterator => $self,
785 sector => $sector,
786 });
787 }
8db25060 788
2120a181 789 DBM::Deep->_throw_error( "get_sector_iterator(): Why did $loc make a $sector?" );
790}
791
792sub get_next_key {
793 my $self = shift;
794 my ($obj) = @_;
795
796 my $crumbs = $self->{breadcrumbs};
797 my $e = $self->{engine};
798
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.
803 or return;
804
805 if ( $sector->staleness != $obj->_staleness ) {
806 return;
8db25060 807 }
808
2120a181 809 my $loc = $sector->get_blist_loc
810 or return;
811
812 push @$crumbs, $self->get_sector_iterator( $loc );
8db25060 813 }
8db25060 814
2120a181 815 FIND_NEXT_KEY: {
816 # We're at the end.
817 unless ( @$crumbs ) {
818 $self->reset;
8db25060 819 return;
820 }
8db25060 821
2120a181 822 my $iterator = $crumbs->[-1];
823
824 # This level is done.
825 if ( $iterator->at_end ) {
826 pop @$crumbs;
827 redo FIND_NEXT_KEY;
828 }
829
830 if ( $iterator->isa( 'DBM::Deep::Iterator::Index' ) ) {
831 # If we don't have any more, it will be caught at the
832 # prior check.
833 if ( my $next = $iterator->get_next_iterator ) {
834 push @$crumbs, $next;
835 }
836 redo FIND_NEXT_KEY;
837 }
838
839 unless ( $iterator->isa( 'DBM::Deep::Iterator::BucketList' ) ) {
840 DBM::Deep->_throw_error(
841 "Should have a bucketlist iterator here - instead have $iterator"
842 );
843 }
844
845 # At this point, we have a BucketList iterator
846 my $key = $iterator->get_next_key;
847 if ( defined $key ) {
848 return $key;
849 }
850 #XXX else { $iterator->set_to_end() } ?
851
852 # We hit the end of the bucketlist iterator, so redo
853 redo FIND_NEXT_KEY;
8db25060 854 }
855
2120a181 856 DBM::Deep->_throw_error( "get_next_key(): How did we get here?" );
8db25060 857}
858
2120a181 859package DBM::Deep::Iterator::Index;
860
861sub new {
862 my $self = bless $_[1] => $_[0];
863 $self->{curr_index} = 0;
864 return $self;
865}
866
867sub at_end {
beac1dff 868 my $self = shift;
2120a181 869 return $self->{curr_index} >= $self->{iterator}{engine}->hash_chars;
870}
9020ee8c 871
2120a181 872sub get_next_iterator {
873 my $self = shift;
94e8af14 874
2120a181 875 my $loc;
876 while ( !$loc ) {
877 return if $self->at_end;
878 $loc = $self->{sector}->get_entry( $self->{curr_index}++ );
386bab6c 879 }
94e8af14 880
2120a181 881 return $self->{iterator}->get_sector_iterator( $loc );
882}
883
884package DBM::Deep::Iterator::BucketList;
885
886sub new {
887 my $self = bless $_[1] => $_[0];
888 $self->{curr_index} = 0;
889 return $self;
890}
891
892sub at_end {
893 my $self = shift;
894 return $self->{curr_index} >= $self->{iterator}{engine}->max_buckets;
895}
896
897sub get_next_key {
898 my $self = shift;
899
900 return if $self->at_end;
901
902 my $idx = $self->{curr_index}++;
903
904 my $data_loc = $self->{sector}->get_data_location_for({
905 allow_head => 1,
906 idx => $idx,
907 }) or return;
908
909 #XXX Do we want to add corruption checks here?
910 return $self->{sector}->get_key_for( $idx )->data;
911}
912
913package DBM::Deep::Engine::Sector;
914
915sub new {
916 my $self = bless $_[1], $_[0];
917 Scalar::Util::weaken( $self->{engine} );
918 $self->_init;
919 return $self;
920}
921
922#sub _init {}
923#sub clone { DBM::Deep->_throw_error( "Must be implemented in the child class" ); }
924
925sub engine { $_[0]{engine} }
926sub offset { $_[0]{offset} }
927sub type { $_[0]{type} }
928
929sub base_size {
930 my $self = shift;
931 return $self->engine->SIG_SIZE + $self->engine->STALE_SIZE;
932}
933
934sub free {
935 my $self = shift;
936
937 my $e = $self->engine;
938
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),
943 );
944
945 my $free_meth = $self->free_meth;
946 $e->$free_meth( $self->offset, $self->size );
947
beac1dff 948 return;
9020ee8c 949}
ab0e4957 950
2120a181 951package DBM::Deep::Engine::Sector::Data;
952
953our @ISA = qw( DBM::Deep::Engine::Sector );
954
955# This is in bytes
956sub size { return 256 }
957sub free_meth { return '_add_free_data_sector' }
958
959sub clone {
beac1dff 960 my $self = shift;
2120a181 961 return ref($self)->new({
962 engine => $self->engine,
963 data => $self->data,
964 type => $self->type,
965 });
966}
967
968package DBM::Deep::Engine::Sector::Scalar;
969
970our @ISA = qw( DBM::Deep::Engine::Sector::Data );
ab0e4957 971
2120a181 972sub free {
973 my $self = shift;
633df1fd 974
2120a181 975 my $chain_loc = $self->chain_loc;
633df1fd 976
2120a181 977 $self->SUPER::free();
633df1fd 978
2120a181 979 if ( $chain_loc ) {
980 $self->engine->_load_sector( $chain_loc )->free;
633df1fd 981 }
982
2120a181 983 return;
984}
985
986sub type { $_[0]{engine}->SIG_DATA }
987sub _init {
988 my $self = shift;
989
990 my $engine = $self->engine;
991
992 unless ( $self->offset ) {
993 my $data_section = $self->size - $self->base_size - 1 * $engine->byte_size - 1;
7a960a12 994
2120a181 995 $self->{offset} = $engine->_request_data_sector( $self->size );
7a960a12 996
2120a181 997 my $data = delete $self->{data};
998 my $dlen = length $data;
999 my $continue = 1;
1000 my $curr_offset = $self->offset;
1001 while ( $continue ) {
633df1fd 1002
2120a181 1003 my $next_offset = 0;
1004
1005 my ($leftover, $this_len, $chunk);
1006 if ( $dlen > $data_section ) {
1007 $leftover = 0;
1008 $this_len = $data_section;
1009 $chunk = substr( $data, 0, $this_len );
1010
1011 $dlen -= $data_section;
1012 $next_offset = $engine->_request_data_sector( $self->size );
1013 $data = substr( $data, $this_len );
1014 }
1015 else {
1016 $leftover = $data_section - $dlen;
1017 $this_len = $dlen;
1018 $chunk = $data;
ea2f6d67 1019
2120a181 1020 $continue = 0;
ea2f6d67 1021 }
2120a181 1022
1023 $engine->storage->print_at( $curr_offset, $self->type ); # Sector type
1024 # Skip staleness
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
1030 );
1031
1032 $curr_offset = $next_offset;
633df1fd 1033 }
1034
2120a181 1035 return;
386bab6c 1036 }
2120a181 1037}
7a960a12 1038
2120a181 1039sub data_length {
1040 my $self = shift;
7a960a12 1041
2120a181 1042 my $buffer = $self->engine->storage->read_at(
1043 $self->offset + $self->base_size + $self->engine->byte_size, 1
1044 );
633df1fd 1045
2120a181 1046 return unpack( $StP{1}, $buffer );
ab0e4957 1047}
1048
2120a181 1049sub chain_loc {
beac1dff 1050 my $self = shift;
2120a181 1051 return unpack(
1052 $StP{$self->engine->byte_size},
1053 $self->engine->storage->read_at(
1054 $self->offset + $self->base_size,
1055 $self->engine->byte_size,
1056 ),
1057 );
1058}
912d50b1 1059
2120a181 1060sub data {
1061 my $self = shift;
1062
1063 my $data;
1064 while ( 1 ) {
1065 my $chain_loc = $self->chain_loc;
1066
1067 $data .= $self->engine->storage->read_at(
1068 $self->offset + $self->base_size + $self->engine->byte_size + 1, $self->data_length,
1069 );
1070
1071 last unless $chain_loc;
1072
1073 $self = $self->engine->_load_sector( $chain_loc );
ea2f6d67 1074 }
2120a181 1075
1076 return $data;
912d50b1 1077}
1078
2120a181 1079package DBM::Deep::Engine::Sector::Null;
1080
1081our @ISA = qw( DBM::Deep::Engine::Sector::Data );
1082
1083sub type { $_[0]{engine}->SIG_NULL }
1084sub data_length { 0 }
1085sub data { return }
1086
1087sub _init {
beac1dff 1088 my $self = shift;
d0b74c17 1089
2120a181 1090 my $engine = $self->engine;
d0b74c17 1091
2120a181 1092 unless ( $self->offset ) {
1093 my $leftover = $self->size - $self->base_size - 1 * $engine->byte_size - 1;
d0b74c17 1094
2120a181 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
1102 );
d0b74c17 1103
2120a181 1104 return;
1105 }
1106}
d0b74c17 1107
2120a181 1108package DBM::Deep::Engine::Sector::Reference;
16d1ad9b 1109
2120a181 1110our @ISA = qw( DBM::Deep::Engine::Sector::Data );
d0b74c17 1111
2120a181 1112sub _init {
1113 my $self = shift;
d5d7c51d 1114
2120a181 1115 my $e = $self->engine;
d5d7c51d 1116
2120a181 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;
1120
1121 my $class_offset = 0;
1122 if ( defined $classname ) {
1123 my $class_sector = DBM::Deep::Engine::Sector::Scalar->new({
1124 engine => $e,
1125 data => $classname,
1126 });
1127 $class_offset = $class_sector->offset;
d0b74c17 1128 }
1129
2120a181 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
1137 );
1138 }
1139 else {
1140 $self->{type} = $e->storage->read_at( $self->offset, 1 );
beac1dff 1141 }
d0b74c17 1142
2120a181 1143 $self->{staleness} = unpack(
1144 $StP{$e->STALE_SIZE},
1145 $e->storage->read_at( $self->offset + $e->SIG_SIZE, $e->STALE_SIZE ),
1146 );
1147
1148 return;
6736c116 1149}
1150
2120a181 1151sub free {
d0b74c17 1152 my $self = shift;
d0b74c17 1153
2120a181 1154 my $blist_loc = $self->get_blist_loc;
1155 $self->engine->_load_sector( $blist_loc )->free if $blist_loc;
d0b74c17 1156
2120a181 1157 my $class_loc = $self->get_class_offset;
1158 $self->engine->_load_sector( $class_loc )->free if $class_loc;
d0b74c17 1159
2120a181 1160 $self->SUPER::free();
d0b74c17 1161}
1162
2120a181 1163sub staleness { $_[0]{staleness} }
1164
1165sub get_data_for {
6736c116 1166 my $self = shift;
2120a181 1167 my ($args) = @_;
d0b74c17 1168
2120a181 1169 # Assume that the head is not allowed unless otherwise specified.
1170 $args->{allow_head} = 0 unless exists $args->{allow_head};
6736c116 1171
2120a181 1172 # Assume we don't create a new blist location unless otherwise specified.
1173 $args->{create} = 0 unless exists $args->{create};
d0b74c17 1174
2120a181 1175 my $blist = $self->get_bucket_list({
1176 key_md5 => $args->{key_md5},
1177 key => $args->{key},
1178 create => $args->{create},
1179 });
1180 return unless $blist && $blist->{found};
e5fc7e69 1181
2120a181 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
1184 # function call.
1185 my $location = $blist->get_data_location_for({
1186 allow_head => $args->{allow_head},
1187 }) or return;
e5fc7e69 1188
2120a181 1189 return $self->engine->_load_sector( $location );
1190}
d0b74c17 1191
2120a181 1192sub write_data {
1193 my $self = shift;
1194 my ($args) = @_;
1195
1196 my $blist = $self->get_bucket_list({
1197 key_md5 => $args->{key_md5},
1198 key => $args->{key},
1199 create => 1,
1200 }) or DBM::Deep->_throw_error( "How did write_data fail (no blist)?!" );
1201
1202 # Handle any transactional bookkeeping.
1203 if ( $self->engine->trans_id ) {
1204 if ( ! $blist->has_md5 ) {
1205 $blist->mark_deleted({
1206 trans_id => 0,
1207 });
1208 }
42717e46 1209 }
e5fc7e69 1210 else {
2120a181 1211 my @trans_ids = $self->engine->get_running_txn_ids;
1212 if ( $blist->has_md5 ) {
1213 if ( @trans_ids ) {
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,
1218 allow_head => 0,
1219 });
1220 $blist->write_md5({
1221 trans_id => $other_trans_id,
1222 key => $args->{key},
1223 key_md5 => $args->{key_md5},
1224 value => $old_value->clone,
1225 });
1226 }
beac1dff 1227 }
2120a181 1228 }
1229 else {
1230 if ( @trans_ids ) {
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,
1236 });
ea2f6d67 1237 }
2120a181 1238 }
1239 }
1240 }
ea2f6d67 1241
2120a181 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;
1246 }
8db25060 1247
2120a181 1248 $blist->write_md5({
1249 key => $args->{key},
1250 key_md5 => $args->{key_md5},
1251 value => $args->{value},
1252 });
1253}
d0b74c17 1254
2120a181 1255sub delete_key {
1256 my $self = shift;
1257 my ($args) = @_;
86867f3a 1258
2120a181 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)?!" );
1263
1264 # Save the location so that we can free the data
1265 my $location = $blist->get_data_location_for({
1266 allow_head => 0,
1267 });
1268 my $old_value = $location && $self->engine->_load_sector( $location );
1269
1270 my @trans_ids = $self->engine->get_running_txn_ids;
1271
1272 if ( $self->engine->trans_id == 0 ) {
1273 if ( @trans_ids ) {
1274 foreach my $other_trans_id ( @trans_ids ) {
1275 next if $blist->get_data_location_for({ trans_id => $other_trans_id, allow_head => 0 });
1276 $blist->write_md5({
1277 trans_id => $other_trans_id,
1278 key => $args->{key},
1279 key_md5 => $args->{key_md5},
1280 value => $old_value->clone,
1281 });
beac1dff 1282 }
8db25060 1283 }
2120a181 1284 }
d0b74c17 1285
2120a181 1286 my $data;
1287 if ( @trans_ids ) {
1288 $blist->mark_deleted( $args );
1289
1290 if ( $old_value ) {
1291 $data = $old_value->data;
1292 $old_value->free;
1293 }
1294 }
1295 else {
1296 $data = $blist->delete_md5( $args );
42717e46 1297 }
d0b74c17 1298
2120a181 1299 return $data;
6736c116 1300}
1301
2120a181 1302sub get_blist_loc {
1303 my $self = shift;
75be6413 1304
2120a181 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 );
1308}
1309
1310sub get_bucket_list {
75be6413 1311 my $self = shift;
2120a181 1312 my ($args) = @_;
1313 $args ||= {};
1314
1315 # XXX Add in check here for recycling?
1316
1317 my $engine = $self->engine;
1318
1319 my $blist_loc = $self->get_blist_loc;
1320
1321 # There's no index or blist yet
1322 unless ( $blist_loc ) {
1323 return unless $args->{create};
1324
1325 my $blist = DBM::Deep::Engine::Sector::BucketList->new({
1326 engine => $engine,
1327 key_md5 => $args->{key_md5},
1328 });
1329
1330 $engine->storage->print_at( $self->offset + $self->base_size,
1331 pack( $StP{$engine->byte_size}, $blist->offset ),
1332 );
1333
1334 return $blist;
1335 }
1336
1337 my $sector = $engine->_load_sector( $blist_loc )
1338 or DBM::Deep->_throw_error( "Cannot read sector at $blist_loc in get_bucket_list()" );
1339 my $i = 0;
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;
1344 if ( $blist_loc ) {
1345 $sector = $engine->_load_sector( $blist_loc )
1346 or DBM::Deep->_throw_error( "Cannot read sector at $blist_loc in get_bucket_list()" );
1347 }
1348 else {
1349 $sector = undef;
1350 last;
1351 }
1352 }
1353
1354 # This means we went through the Index sector(s) and found an empty slot
1355 unless ( $sector ) {
1356 return unless $args->{create};
1357
1358 DBM::Deep->_throw_error( "No last_sector when attempting to build a new entry" )
1359 unless $last_sector;
1360
1361 my $blist = DBM::Deep::Engine::Sector::BucketList->new({
1362 engine => $engine,
1363 key_md5 => $args->{key_md5},
1364 });
1365
1366 $last_sector->set_entry( ord( substr( $args->{key_md5}, $i - 1, 1 ) ) => $blist->offset );
1367
1368 return $blist;
1369 }
75be6413 1370
2120a181 1371 $sector->find_md5( $args->{key_md5} );
1372
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({
1376 engine => $engine,
1377 });
1378
1379 my %blist_cache;
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 ) );
1384
1385 # XXX This is inefficient
1386 my $blist = $blist_cache{$idx}
1387 ||= DBM::Deep::Engine::Sector::BucketList->new({
1388 engine => $engine,
1389 });
1390
1391 $new_index->set_entry( $idx => $blist->offset );
1392
1393 my $new_spot = $blist->write_at_next_open( $md5 );
1394 $engine->reindex_entry( $spot => $new_spot );
1395 }
1396
1397 # Handle the new item separately.
1398 {
1399 my $idx = ord( substr( $args->{key_md5}, $i, 1 ) );
1400 my $blist = $blist_cache{$idx}
1401 ||= DBM::Deep::Engine::Sector::BucketList->new({
1402 engine => $engine,
1403 });
1404
1405 $new_index->set_entry( $idx => $blist->offset );
1406
1407 #XXX THIS IS HACKY!
1408 $blist->find_md5( $args->{key_md5} );
1409 $blist->write_md5({
1410 key => $args->{key},
1411 key_md5 => $args->{key_md5},
1412 value => DBM::Deep::Engine::Sector::Null->new({
1413 engine => $engine,
1414 data => undef,
1415 }),
1416 });
1417 }
1418
1419 if ( $last_sector ) {
1420 $last_sector->set_entry(
1421 ord( substr( $args->{key_md5}, $i - 1, 1 ) ),
1422 $new_index->offset,
1423 );
1424 } else {
1425 $engine->storage->print_at( $self->offset + $self->base_size,
1426 pack( $StP{$engine->byte_size}, $new_index->offset ),
1427 );
1428 }
1429
1430 $sector->free;
1431
1432 $sector = $blist_cache{ ord( substr( $args->{key_md5}, $i, 1 ) ) };
1433 $sector->find_md5( $args->{key_md5} );
1434 }
1435
1436 return $sector;
1437}
1438
1439sub get_class_offset {
1440 my $self = shift;
1441
1442 my $e = $self->engine;
ea2f6d67 1443 return unpack(
2120a181 1444 $StP{$e->byte_size},
1445 $e->storage->read_at(
1446 $self->offset + $self->base_size + 1 * $e->byte_size, $e->byte_size,
75be6413 1447 ),
1448 );
75be6413 1449}
1450
2120a181 1451sub get_classname {
d608b06e 1452 my $self = shift;
21838116 1453
2120a181 1454 my $class_offset = $self->get_class_offset;
1455
1456 return unless $class_offset;
1457
1458 return $self->engine->_load_sector( $class_offset )->data;
1459}
1460
1461#XXX Add singleton handling here
1462sub data {
1463 my $self = shift;
1464
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,
1471 });
1472
1473 if ( $self->engine->storage->{autobless} ) {
1474 my $classname = $self->get_classname;
1475 if ( defined $classname ) {
1476 bless $new_obj, $classname;
1477 }
1478 }
1479
1480 return $new_obj;
1481}
1482
1483package DBM::Deep::Engine::Sector::BucketList;
1484
1485our @ISA = qw( DBM::Deep::Engine::Sector );
1486
1487sub _init {
1488 my $self = shift;
1489
1490 my $engine = $self->engine;
1491
1492 unless ( $self->offset ) {
1493 my $leftover = $self->size - $self->base_size;
1494
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
9a187d8c 1500 );
2120a181 1501 }
d608b06e 1502
2120a181 1503 if ( $self->{key_md5} ) {
1504 $self->find_md5;
d608b06e 1505 }
1506
2120a181 1507 return $self;
d608b06e 1508}
1509
2120a181 1510sub size {
994ccd8e 1511 my $self = shift;
2120a181 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;
1516 }
1517 return $self->{size};
1518}
994ccd8e 1519
2120a181 1520sub free_meth { return '_add_free_blist_sector' }
7b1e1aa1 1521
2120a181 1522sub bucket_size {
1523 my $self = shift;
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;
1529 }
1530 return $self->{bucket_size};
1531}
7b1e1aa1 1532
2120a181 1533# XXX This is such a poor hack. I need to rethink this code.
1534sub chopped_up {
1535 my $self = shift;
1536
1537 my $e = $self->engine;
1538
1539 my @buckets;
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 );
1543
1544 #XXX If we're chopping, why would we ever have the blank_md5?
1545 last if $md5 eq $e->blank_md5;
1546
1547 my $rest = $e->storage->read_at( undef, $self->bucket_size - $e->hash_size );
1548 push @buckets, [ $spot, $md5 . $rest ];
1549 }
1550
1551 return @buckets;
994ccd8e 1552}
1553
2120a181 1554sub write_at_next_open {
1555 my $self = shift;
1556 my ($entry) = @_;
1557
1558 #XXX This is such a hack!
1559 $self->{_next_open} = 0 unless exists $self->{_next_open};
1560
1561 my $spot = $self->offset + $self->base_size + $self->{_next_open}++ * $self->bucket_size;
1562 $self->engine->storage->print_at( $spot, $entry );
1563
1564 return $spot;
e96daec8 1565}
1566
2120a181 1567sub has_md5 {
1568 my $self = shift;
1569 unless ( exists $self->{found} ) {
1570 $self->find_md5;
1571 }
1572 return $self->{found};
1573}
86867f3a 1574
2120a181 1575sub find_md5 {
1576 my $self = shift;
1577
1578 $self->{found} = undef;
1579 $self->{idx} = -1;
1580
1581 if ( @_ ) {
1582 $self->{key_md5} = shift;
1583 }
1584
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" );
1588 }
1589
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,
1594 );
1595
1596 if ( $potential eq $e->blank_md5 ) {
1597 $self->{idx} = $idx;
86867f3a 1598 return;
2120a181 1599 }
1600
1601 if ( $potential eq $self->{key_md5} ) {
1602 $self->{found} = 1;
1603 $self->{idx} = $idx;
86867f3a 1604 return;
2120a181 1605 }
86867f3a 1606 }
1607
1608 return;
1609}
1610
2120a181 1611sub write_md5 {
86867f3a 1612 my $self = shift;
2120a181 1613 my ($args) = @_;
1614
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};
86867f3a 1618
2120a181 1619 my $engine = $self->engine;
86867f3a 1620
2120a181 1621 $args->{trans_id} = $engine->trans_id unless exists $args->{trans_id};
86867f3a 1622
2120a181 1623 my $spot = $self->offset + $self->base_size + $self->{idx} * $self->bucket_size;
1624 $engine->add_entry( $args->{trans_id}, $spot );
1625
1626 unless ($self->{found}) {
1627 my $key_sector = DBM::Deep::Engine::Sector::Scalar->new({
1628 engine => $engine,
1629 data => $args->{key},
1630 });
1631
1632 $engine->storage->print_at( $spot,
1633 $args->{key_md5},
1634 pack( $StP{$engine->byte_size}, $key_sector->offset ),
1635 );
86867f3a 1636 }
1637
2120a181 1638 my $loc = $spot
1639 + $engine->hash_size
1640 + $engine->byte_size
1641 + $args->{trans_id} * ( $engine->byte_size + 4 );
1642
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} ) ),
1646 );
1647}
1648
1649sub mark_deleted {
1650 my $self = shift;
1651 my ($args) = @_;
1652 $args ||= {};
1653
1654 my $engine = $self->engine;
1655
1656 $args->{trans_id} = $engine->trans_id unless exists $args->{trans_id};
1657
1658 my $spot = $self->offset + $self->base_size + $self->{idx} * $self->bucket_size;
1659 $engine->add_entry( $args->{trans_id}, $spot );
1660
1661 my $loc = $spot
1662 + $engine->hash_size
1663 + $engine->byte_size
1664 + $args->{trans_id} * ( $engine->byte_size + 4 );
1665
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} ) ),
1669 );
1670}
1671
1672sub delete_md5 {
1673 my $self = shift;
1674 my ($args) = @_;
1675
1676 my $engine = $self->engine;
1677 return undef unless $self->{found};
1678
1679 # Save the location so that we can free the data
1680 my $location = $self->get_data_location_for({
1681 allow_head => 0,
1682 });
1683 my $key_sector = $self->get_key_for;
1684
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 ),
1690 ),
1691 chr(0) x $self->bucket_size,
1692 );
1693
1694 $key_sector->free;
1695
1696 my $data_sector = $self->engine->_load_sector( $location );
1697 my $data = $data_sector->data;
1698 $data_sector->free;
1699
1700 return $data;
1701}
1702
1703sub get_data_location_for {
1704 my $self = shift;
1705 my ($args) = @_;
1706 $args ||= {};
1707
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};
1711
1712 my $e = $self->engine;
1713
1714 my $spot = $self->offset + $self->base_size
1715 + $args->{idx} * $self->bucket_size
1716 + $e->hash_size
1717 + $e->byte_size
1718 + $args->{trans_id} * ( $e->byte_size + 4 );
1719
1720 my $buffer = $e->storage->read_at(
1721 $spot,
1722 $e->byte_size + 4,
1723 );
1724 my ($loc, $staleness) = unpack( $StP{$e->byte_size} . ' N', $buffer );
1725
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(
1729 $spot,
1730 pack( $StP{$e->byte_size} . ' N', (0) x 2 ),
1731 );
1732 $loc = 0;
86867f3a 1733 }
1734
2120a181 1735 # If we're in a transaction and we never wrote to this location, try the
1736 # HEAD instead.
1737 if ( $args->{trans_id} && !$loc && $args->{allow_head} ) {
1738 return $self->get_data_location_for({
1739 trans_id => 0,
1740 allow_head => 1,
1741 idx => $args->{idx},
1742 });
1743 }
1744 return $loc <= 1 ? 0 : $loc;
1745}
1746
1747sub get_data_for {
1748 my $self = shift;
1749 my ($args) = @_;
1750 $args ||= {};
1751
1752 return unless $self->{found};
1753 my $location = $self->get_data_location_for({
1754 allow_head => $args->{allow_head},
1755 });
1756 return $self->engine->_load_sector( $location );
1757}
1758
1759sub get_key_for {
1760 my $self = shift;
1761 my ($idx) = @_;
1762 $idx = $self->{idx} unless defined $idx;
1763
1764 if ( $idx >= $self->engine->max_buckets ) {
1765 DBM::Deep->_throw_error( "get_key_for(): Attempting to retrieve $idx" );
86867f3a 1766 }
1767
2120a181 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,
1771 );
1772 $location = unpack( $StP{$self->engine->byte_size}, $location );
1773 DBM::Deep->_throw_error( "get_key_for: No location?" ) unless $location;
1774
1775 return $self->engine->_load_sector( $location );
1776}
86867f3a 1777
2120a181 1778package DBM::Deep::Engine::Sector::Index;
1779
1780our @ISA = qw( DBM::Deep::Engine::Sector );
1781
1782sub _init {
1783 my $self = shift;
1784
1785 my $engine = $self->engine;
1786
1787 unless ( $self->offset ) {
1788 my $leftover = $self->size - $self->base_size;
1789
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
1795 );
1796 }
1797
1798 return $self;
1799}
1800
1801sub size {
1802 my $self = shift;
1803 unless ( $self->{size} ) {
1804 my $e = $self->engine;
1805 $self->{size} = $self->base_size + $e->byte_size * $e->hash_chars;
1806 }
1807 return $self->{size};
1808}
1809
1810sub free_meth { return '_add_free_index_sector' }
1811
1812sub free {
1813 my $self = shift;
1814 my $e = $self->engine;
1815
1816 for my $i ( 0 .. $e->hash_chars - 1 ) {
1817 my $l = $self->get_entry( $i ) or next;
1818 $e->_load_sector( $l )->free;
86867f3a 1819 }
1820
2120a181 1821 $self->SUPER::free();
1822}
1823
1824sub _loc_for {
1825 my $self = shift;
1826 my ($idx) = @_;
1827 return $self->offset + $self->base_size + $idx * $self->engine->byte_size;
1828}
1829
1830sub get_entry {
1831 my $self = shift;
1832 my ($idx) = @_;
1833
1834 my $e = $self->engine;
1835
1836 DBM::Deep->_throw_error( "get_entry: Out of range ($idx)" )
1837 if $idx < 0 || $idx >= $e->hash_chars;
1838
1839 return unpack(
1840 $StP{$e->byte_size},
1841 $e->storage->read_at( $self->_loc_for( $idx ), $e->byte_size ),
1842 );
1843}
1844
1845sub set_entry {
1846 my $self = shift;
1847 my ($idx, $loc) = @_;
1848
1849 my $e = $self->engine;
1850
1851 DBM::Deep->_throw_error( "set_entry: Out of range ($idx)" )
1852 if $idx < 0 || $idx >= $e->hash_chars;
1853
1854 $self->engine->storage->print_at(
1855 $self->_loc_for( $idx ),
1856 pack( $StP{$e->byte_size}, $loc ),
1857 );
86867f3a 1858}
1859
a20d9a3f 18601;
1861__END__