1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 package PublicInbox::InboxIdle;
6 use base qw(PublicInbox::DS);
7 use fields qw(pi_config inot pathmap);
9 use PublicInbox::Syscall qw(EPOLLIN EPOLLET);
10 my $IN_MODIFY = 0x02; # match Linux inotify
12 if ($^O eq 'linux' && eval { require Linux::Inotify2; 1 }) {
13 $IN_MODIFY = Linux::Inotify2::IN_MODIFY();
14 $ino_cls = 'Linux::Inotify2';
15 } elsif (eval { require PublicInbox::KQNotify }) {
16 $IN_MODIFY = PublicInbox::KQNotify::NOTE_WRITE();
17 $ino_cls = 'PublicInbox::KQNotify';
19 require PublicInbox::In2Tie if $ino_cls;
21 sub in2_arm ($$) { # PublicInbox::Config::each_inbox callback
22 my ($ibx, $self) = @_;
23 my $dir = abs_path($ibx->{inboxdir});
25 warn "W: $ibx->{inboxdir} not watched: $!\n";
28 my $inot = $self->{inot};
29 my $cur = $self->{pathmap}->{$dir} //= [];
31 # transfer old subscriptions to the current inbox, cancel the old watch
32 if (my $old_ibx = $cur->[0]) {
33 $ibx->{unlock_subs} and
34 die "BUG: $dir->{unlock_subs} should not exist";
35 $ibx->{unlock_subs} = $old_ibx->{unlock_subs};
40 my $lock = "$dir/".($ibx->version >= 2 ? 'inbox.lock' : 'ssoma.lock');
41 $cur->[1] = $inot->watch($lock, $IN_MODIFY, sub { $ibx->on_unlock });
43 # TODO: detect deleted packs (and possibly other files)
47 my ($self, $pi_config) = @_;
48 $pi_config->each_inbox(\&in2_arm, $self);
52 my ($class, $pi_config) = @_;
53 my $self = fields::new($class);
56 $inot = $ino_cls->new or die "E: $ino_cls->new: $!";
57 my $io = PublicInbox::In2Tie::io($inot);
58 $self->SUPER::new($io, EPOLLIN | EPOLLET);
60 require PublicInbox::FakeInotify;
61 $inot = PublicInbox::FakeInotify->new;
63 $self->{inot} = $inot;
64 $self->{pathmap} = {}; # inboxdir => [ ibx, watch1, watch2, watch3...]
65 refresh($self, $pi_config);
71 eval { $self->{inot}->poll }; # Linux::Inotify2::poll
72 warn "$self->{inot}->poll err: $@\n" if $@;
75 # for graceful shutdown in PublicInbox::Daemon,
76 # just ensure the FD gets closed ASAP and subscribers