]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/InboxIdle.pm
inboxidle: new class to detect inbox changes
[public-inbox.git] / lib / PublicInbox / InboxIdle.pm
1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 package PublicInbox::InboxIdle;
5 use strict;
6 use base qw(PublicInbox::DS);
7 use fields qw(pi_config inot);
8 use Symbol qw(gensym);
9 use PublicInbox::Syscall qw(EPOLLIN EPOLLET);
10 my $IN_CLOSE = 0x08 | 0x10; # match Linux inotify
11 my $ino_cls;
12 if ($^O eq 'linux' && eval { require Linux::Inotify2; 1 }) {
13         $IN_CLOSE = Linux::Inotify2::IN_CLOSE();
14         $ino_cls = 'Linux::Inotify2';
15 } elsif (eval { require PublicInbox::KQNotify }) {
16         $IN_CLOSE = PublicInbox::KQNotify::IN_CLOSE();
17         $ino_cls = 'PublicInbox::KQNotify';
18 }
19 require PublicInbox::In2Tie if $ino_cls;
20
21 sub in2_arm ($$) { # PublicInbox::Config::each_inbox callback
22         my ($ibx, $inot) = @_;
23         my $path = "$ibx->{inboxdir}/";
24         $path .= $ibx->version >= 2 ? 'inbox.lock' : 'ssoma.lock';
25         $inot->watch($path, $IN_CLOSE, sub { $ibx->on_unlock });
26         # TODO: detect deleted packs (and possibly other files)
27 }
28
29 sub new {
30         my ($class, $pi_config) = @_;
31         my $self = fields::new($class);
32         my $inot;
33         if ($ino_cls) {
34                 $inot = $ino_cls->new or die "E: $ino_cls->new: $!";
35                 my $sock = gensym;
36                 tie *$sock, 'PublicInbox::In2Tie', $inot;
37                 $inot->blocking(0);
38                 $inot->on_overflow(undef); # broadcasts everything on overflow
39                 $self->SUPER::new($sock, EPOLLIN | EPOLLET);
40         } else {
41                 require PublicInbox::FakeInotify;
42                 $inot = PublicInbox::FakeInotify->new;
43         }
44         $self->{inot} = $inot;
45         $pi_config->each_inbox(\&in2_arm, $inot);
46         $self;
47 }
48
49 sub event_step {
50         my ($self) = @_;
51         eval { $self->{inot}->poll }; # Linux::Inotify2::poll
52         warn "$self->{inot}->poll err: $@\n" if $@;
53 }
54
55 1;