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 # implements the small subset of Linux::Inotify2 functionality we use
5 # using IO::KQueue on *BSD systems.
6 package PublicInbox::KQNotify;
9 use PublicInbox::DSKQXS; # wraps IO::KQueue for fork-safe DESTROY
10 use PublicInbox::FakeInotify;
11 use Time::HiRes qw(stat);
13 # NOTE_EXTEND detects rename(2), NOTE_WRITE detects link(2)
14 sub MOVED_TO_OR_CREATE () { NOTE_EXTEND|NOTE_WRITE }
18 bless { dskq => PublicInbox::DSKQXS->new, watch => {} }, $class;
22 my ($self, $path, $mask) = @_;
25 opendir($fh, $path) or return;
27 $watch = bless [ $fh, $path, $st[10] ],
28 'PublicInbox::KQNotify::Watchdir';
30 open($fh, '<', $path) or return;
31 $watch = bless [ $fh, $path ],
32 'PublicInbox::KQNotify::Watch';
34 my $ident = fileno($fh);
35 $self->{dskq}->{kq}->EV_SET($ident, # ident
36 EVFILT_VNODE, # filter
37 EV_ADD | EV_CLEAR, # flags
40 if ($mask == NOTE_WRITE || $mask == MOVED_TO_OR_CREATE) {
41 $self->{watch}->{$ident} = $watch;
43 die "TODO Not implemented: $mask";
48 # emulate Linux::Inotify::fileno
49 sub fileno { ${$_[0]->{dskq}->{kq}} }
51 # noop for Linux::Inotify2 compatibility. Unlike inotify,
52 # kqueue doesn't seem to overflow since it's limited by the number of
53 # open FDs the process has
56 # noop for Linux::Inotify2 compatibility, we use `0' timeout for ->kevent
59 # behave like Linux::Inotify2->read
62 my @kevents = $self->{dskq}->{kq}->kevent(0);
64 for my $kev (@kevents) {
65 my $ident = $kev->[KQ_IDENT];
66 my $mask = $kev->[KQ_FFLAGS];
67 my ($dh, $path, $old_ctime) = @{$self->{watch}->{$ident}};
68 if (!defined($old_ctime)) {
70 bless(\$path, 'PublicInbox::FakeInotify::Event')
71 } elsif ($mask & MOVED_TO_OR_CREATE) {
72 my @new_st = stat($path) or next;
73 $self->{watch}->{$ident}->[3] = $new_st[10]; # ctime
75 PublicInbox::FakeInotify::on_new_files($events, $dh,
82 package PublicInbox::KQNotify::Watch;
85 sub name { $_[0]->[1] }
87 sub cancel { close $_[0]->[0] or die "close: $!" }
89 package PublicInbox::KQNotify::Watchdir;
92 sub name { $_[0]->[1] }
94 sub cancel { closedir $_[0]->[0] or die "closedir: $!" }