]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/DirIdle.pm
89cce305f872816d4048558859d5954b2b4c00cc
[public-inbox.git] / lib / PublicInbox / DirIdle.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 # 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, $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         $ino_cls = 'Linux::Inotify2';
16 } elsif (eval { require PublicInbox::KQNotify }) {
17         $MAIL_IN = PublicInbox::KQNotify::MOVED_TO_OR_CREATE();
18         $ino_cls = 'PublicInbox::KQNotify';
19 } else {
20         require PublicInbox::FakeInotify;
21         $MAIL_IN = PublicInbox::FakeInotify::MOVED_TO_OR_CREATE();
22 }
23
24 sub new {
25         my ($class, $dirs, $cb) = @_;
26         my $self = bless { cb => $cb }, $class;
27         my $inot;
28         if ($ino_cls) {
29                 $inot = $ino_cls->new or die "E: $ino_cls->new: $!";
30                 my $io = PublicInbox::In2Tie::io($inot);
31                 $self->SUPER::new($io, EPOLLIN | EPOLLET);
32         } else {
33                 require PublicInbox::FakeInotify;
34                 $inot = PublicInbox::FakeInotify->new; # starts timer
35         }
36
37         # Linux::Inotify2->watch or similar
38         $inot->watch($_, $MAIL_IN) for @$dirs;
39         $self->{inot} = $inot;
40         PublicInbox::FakeInotify::poll_once($self) if !$ino_cls;
41         $self;
42 }
43
44 sub event_step {
45         my ($self) = @_;
46         my $cb = $self->{cb};
47         eval {
48                 my @events = $self->{inot}->read; # Linux::Inotify2->read
49                 $cb->($_) for @events;
50         };
51         warn "$self->{inot}->read err: $@\n" if $@;
52 }
53
54 1;