3
0
mirror of https://github.com/pragma-/pbot.git synced 2024-11-26 13:59:47 +01:00

DualIndexHashObject can now enqueue saves to prevent repeated-save thrashing

This commit is contained in:
Pragmatic Software 2020-05-14 16:57:34 -07:00
parent a91c2cd71e
commit 506ebf13c6
2 changed files with 34 additions and 12 deletions

View File

@ -36,6 +36,7 @@ sub initialize {
my ($self, %conf) = @_; my ($self, %conf) = @_;
$self->{name} = $conf{name} // 'Dual Index hash object'; $self->{name} = $conf{name} // 'Dual Index hash object';
$self->{filename} = $conf{filename} // Carp::carp("Missing filename to DualIndexHashObject, will not be able to save to or load from file."); $self->{filename} = $conf{filename} // Carp::carp("Missing filename to DualIndexHashObject, will not be able to save to or load from file.");
$self->{save_queue_timeout} = $conf{save_queue_timeout} // 0;
$self->{hash} = {}; $self->{hash} = {};
} }
@ -107,20 +108,34 @@ sub save {
return; return;
} }
$self->{pbot}->{logger}->log("Saving $self->{name} to $filename\n"); my $subref = sub {
$self->{pbot}->{logger}->log("Saving $self->{name} to $filename\n");
if (not $self->get_data('$metadata$', '$metadata$', 'update_version')) { if (not $self->get_data('$metadata$', '$metadata$', 'update_version')) {
$self->add('$metadata$', '$metadata$', { update_version => PBot::VERSION::BUILD_REVISION }); $self->add('$metadata$', '$metadata$', { update_version => PBot::VERSION::BUILD_REVISION });
}
$self->set('$metadata$', '$metadata$', 'name', $self->{name}, 1);
my $json = JSON->new;
my $json_text = $json->pretty->canonical->utf8->encode($self->{hash});
open(FILE, "> $filename") or die "Couldn't open $filename: $!\n";
print FILE "$json_text\n";
close FILE;
};
if ($self->{save_queue_timeout}) {
# enqueue the save to prevent save-thrashing
$self->{pbot}->{timer}->replace_subref_or_enqueue_event(
$subref,
$self->{save_queue_timeout},
"save $self->{name}",
);
} else {
# execute it right now
$subref->();
} }
$self->set('$metadata$', '$metadata$', 'name', $self->{name}, 1);
my $json = JSON->new;
my $json_text = $json->pretty->canonical->utf8->encode($self->{hash});
open(FILE, "> $filename") or die "Couldn't open $filename: $!\n";
print FILE "$json_text\n";
close FILE;
} }
sub clear { sub clear {

View File

@ -258,6 +258,13 @@ sub initialize {
# give botowner all capabilities # give botowner all capabilities
$self->{capabilities}->rebuild_botowner_capabilities(); $self->{capabilities}->rebuild_botowner_capabilities();
# flush all pending save events to disk at exit
$self->{atexit}->register(sub {
$self->{pbot}->{timer}->execute_and_dequeue_event('save *');
return;
}
);
} }
sub random_nick { sub random_nick {