]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/DirIdle.pm
dir_idle: detect files which are gone
[public-inbox.git] / lib / PublicInbox / DirIdle.pm
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>
3
4 # Used by public-inbox-watch for Maildir (and possibly MH in the future)
5 package PublicInbox::DirIdle;
6 use strict;
7 use parent 'PublicInbox::DS';
8 use PublicInbox::Syscall qw(EPOLLIN EPOLLET);
9 use PublicInbox::In2Tie;
10
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         $ino_cls = 'Linux::Inotify2';
17 # Perl 5.22+ is needed for fileno(DIRHANDLE) support:
18 } elsif ($^V ge v5.22 && eval { require PublicInbox::KQNotify }) {
19         $MAIL_IN = PublicInbox::KQNotify::MOVED_TO_OR_CREATE();
20         $MAIL_GONE = PublicInbox::KQNotify::NOTE_DELETE();
21         $ino_cls = 'PublicInbox::KQNotify';
22 } else {
23         require PublicInbox::FakeInotify;
24         $MAIL_IN = PublicInbox::FakeInotify::MOVED_TO_OR_CREATE();
25         $MAIL_GONE = PublicInbox::FakeInotify::IN_DELETE();
26 }
27
28 sub new {
29         my ($class, $dirs, $cb, $gone) = @_;
30         my $self = bless { cb => $cb }, $class;
31         my $inot;
32         if ($ino_cls) {
33                 $inot = $ino_cls->new or die "E: $ino_cls->new: $!";
34                 my $io = PublicInbox::In2Tie::io($inot);
35                 $self->SUPER::new($io, EPOLLIN | EPOLLET);
36         } else {
37                 require PublicInbox::FakeInotify;
38                 $inot = PublicInbox::FakeInotify->new; # starts timer
39         }
40
41         # Linux::Inotify2->watch or similar
42         my $fl = $MAIL_IN;
43         $fl |= $MAIL_GONE if $gone;
44         $inot->watch($_, $fl) for @$dirs;
45         $self->{inot} = $inot;
46         PublicInbox::FakeInotify::poll_once($self) if !$ino_cls;
47         $self;
48 }
49
50 sub event_step {
51         my ($self) = @_;
52         my $cb = $self->{cb};
53         local $PublicInbox::DS::in_loop = 0; # waitpid() synchronously
54         eval {
55                 my @events = $self->{inot}->read; # Linux::Inotify2->read
56                 $cb->($_) for @events;
57         };
58         warn "$self->{inot}->read err: $@\n" if $@;
59 }
60
61 1;