1 # Copyright (C) 2020-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # Used by public-inbox-watch for Maildir (and possibly MH in the future)
5 package PublicInbox::DirIdle;
7 use parent 'PublicInbox::DS';
8 use PublicInbox::Syscall qw(EPOLLIN EPOLLET);
9 use PublicInbox::In2Tie;
11 my ($MAIL_IN, $MAIL_GONE, $ino_cls);
12 if ($^O eq 'linux' && eval { require Linux::Inotify2; 1 }) {
13 $MAIL_IN = Linux::Inotify2::IN_MOVED_TO() |
14 Linux::Inotify2::IN_CREATE();
15 $MAIL_GONE = Linux::Inotify2::IN_DELETE() |
16 Linux::Inotify2::IN_DELETE_SELF() |
17 Linux::Inotify2::IN_MOVE_SELF();
18 $ino_cls = 'Linux::Inotify2';
19 # Perl 5.22+ is needed for fileno(DIRHANDLE) support:
20 } elsif ($^V ge v5.22 && eval { require PublicInbox::KQNotify }) {
21 $MAIL_IN = PublicInbox::KQNotify::MOVED_TO_OR_CREATE();
22 $MAIL_GONE = PublicInbox::KQNotify::NOTE_DELETE() |
23 PublicInbox::KQNotify::NOTE_REVOKE() |
24 PublicInbox::KQNotify::NOTE_RENAME();
25 $ino_cls = 'PublicInbox::KQNotify';
27 require PublicInbox::FakeInotify;
28 $MAIL_IN = PublicInbox::FakeInotify::MOVED_TO_OR_CREATE();
29 $MAIL_GONE = PublicInbox::FakeInotify::IN_DELETE() |
30 PublicInbox::FakeInotify::IN_DELETE_SELF() |
31 PublicInbox::FakeInotify::IN_MOVE_SELF();
35 my ($class, $dirs, $cb, $gone) = @_;
36 my $self = bless { cb => $cb }, $class;
39 $inot = $ino_cls->new or die "E: $ino_cls->new: $!";
40 my $io = PublicInbox::In2Tie::io($inot);
41 $self->SUPER::new($io, EPOLLIN | EPOLLET);
43 require PublicInbox::FakeInotify;
44 $inot = PublicInbox::FakeInotify->new; # starts timer
47 # Linux::Inotify2->watch or similar
49 $fl |= $MAIL_GONE if $gone;
50 $inot->watch($_, $fl) for @$dirs;
51 $self->{inot} = $inot;
52 PublicInbox::FakeInotify::poll_once($self) if !$ino_cls;
57 my ($self, $dirs, $gone) = @_;
58 my $fl = $MAIL_IN | ($gone ? $MAIL_GONE : 0);
61 my $w = $self->{inot}->watch($d, $fl) or next;
64 PublicInbox::FakeInotify::poll_once($self) if !$ino_cls;
69 my ($self, $dir) = @_;
70 my $inot = $self->{inot};
71 if (my $cb = $inot->can('rm_watches')) { # TODO for fake watchers
79 local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
81 my @events = $self->{inot}->read; # Linux::Inotify2->read
82 $cb->($_) for @events;
84 warn "$self->{inot}->read err: $@\n" if $@;
89 my $inot = delete $self->{inot} // return;
90 if ($inot->can('fh')) { # Linux::Inotify2 2.3+
91 close($inot->fh) or warn "CLOSE ERROR: $!";
92 } elsif ($inot->isa('Linux::Inotify2')) {
93 require PublicInbox::LI2Wrap;
94 PublicInbox::LI2Wrap::wrapclose($inot);