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 # for systems lacking Linux::Inotify2 or IO::KQueue, just emulates
5 # enough of Linux::Inotify2
6 package PublicInbox::FakeInotify;
9 use parent qw(Exporter);
10 use Time::HiRes qw(stat);
11 use PublicInbox::DS qw(add_timer);
12 sub IN_MODIFY () { 0x02 } # match Linux inotify
13 # my $IN_MOVED_TO = 0x80;
14 # my $IN_CREATE = 0x100;
15 sub MOVED_TO_OR_CREATE () { 0x80 | 0x100 }
16 sub IN_DELETE () { 0x00000200 }
18 our @EXPORT_OK = qw(fill_dirlist on_dir_change);
20 my $poll_intvl = 2; # same as Filesys::Notify::Simple
22 sub new { bless { watch => {}, dirlist => {} }, __PACKAGE__ }
24 sub fill_dirlist ($$$) {
25 my ($self, $path, $dh) = @_;
26 my $dirlist = $self->{dirlist}->{$path} = {};
27 while (defined(my $n = readdir($dh))) {
28 $dirlist->{$n} = undef if $n !~ /\A\.\.?\z/;
32 # behaves like Linux::Inotify2->watch
34 my ($self, $path, $mask) = @_;
35 my @st = stat($path) or return;
36 my $k = "$path\0$mask";
37 $self->{watch}->{$k} = $st[10]; # 10 - ctime
38 if ($mask & IN_DELETE) {
39 opendir(my $dh, $path) or return;
40 fill_dirlist($self, $path, $dh);
42 bless [ $self->{watch}, $k ], 'PublicInbox::FakeInotify::Watch';
45 # also used by KQNotify since it kevent requires readdir on st_nlink
47 sub on_dir_change ($$$$;$) {
48 my ($events, $dh, $path, $old_ctime, $dirlist) = @_;
49 my $oldlist = $dirlist->{$path};
50 my $newlist = $oldlist ? {} : undef;
51 while (defined(my $base = readdir($dh))) {
52 next if $base =~ /\A\.\.?\z/;
53 my $full = "$path/$base";
55 if (@st && $st[10] > $old_ctime) {
57 bless(\$full, 'PublicInbox::FakeInotify::Event')
60 # ignore ENOENT due to race
61 warn "unhandled stat($full) error: $!\n" if !$!{ENOENT};
63 $newlist->{$base} = undef;
67 delete @$oldlist{keys %$newlist};
68 $dirlist->{$path} = $newlist;
70 bless \"$path/$_", 'PublicInbox::FakeInotify::GoneEvent'
74 # behaves like non-blocking Linux::Inotify2->read
77 my $watch = $self->{watch} or return ();
80 for my $x (keys %$watch) {
81 my ($path, $mask) = split(/\0/, $x, 2);
82 my @now = stat($path) or next;
83 my $old_ctime = $watch->{$x};
84 $watch->{$x} = $now[10];
85 next if $old_ctime == $now[10];
86 if ($mask & IN_MODIFY) {
88 bless(\$path, 'PublicInbox::FakeInotify::Event')
89 } elsif ($mask & (MOVED_TO_OR_CREATE | IN_DELETE)) {
90 if (opendir(my $dh, $path)) {
91 on_dir_change($events, $dh, $path, $old_ctime,
93 } elsif ($!{ENOENT}) {
96 warn "W: opendir $path: $!\n";
100 delete @$watch{@watch_gone};
106 $obj->event_step; # PublicInbox::InboxIdle::event_step
107 add_timer($poll_intvl, \&poll_once, $obj);
110 package PublicInbox::FakeInotify::Watch;
115 delete $self->[0]->{$self->[1]};
120 (split(/\0/, $self->[1], 2))[0];
123 package PublicInbox::FakeInotify::Event;
126 sub fullname { ${$_[0]} }
130 package PublicInbox::FakeInotify::GoneEvent;
132 our @ISA = qw(PublicInbox::FakeInotify::Event);