]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/EvCleanup.pm
a9f6167dff25c9054ef83a3b81c27f76cf8d847f
[public-inbox.git] / lib / PublicInbox / EvCleanup.pm
1 # Copyright (C) 2016-2018 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # event cleanups (currently for PublicInbox::DS)
5 package PublicInbox::EvCleanup;
6 use strict;
7 use warnings;
8 use base qw(PublicInbox::DS);
9 use PublicInbox::Syscall qw(EPOLLOUT EPOLLONESHOT);
10
11 my $ENABLED;
12 sub enabled { $ENABLED }
13 sub enable { $ENABLED = 1 }
14 my $singleton;
15 my $asapq = [ [], undef ];
16 my $nextq = [ [], undef ];
17 my $laterq = [ [], undef ];
18
19 sub once_init () {
20         my $self = fields::new('PublicInbox::EvCleanup');
21         my ($r, $w);
22
23         # This is a dummy pipe which is always writable so it can always
24         # fires in the next event loop iteration.
25         pipe($r, $w) or die "pipe: $!";
26         fcntl($w, 1031, 4096) if $^O eq 'linux'; # 1031: F_SETPIPE_SZ
27         $self->SUPER::new($w, 0);
28
29         # always writable, since PublicInbox::EvCleanup::event_step
30         # never drains wbuf.  We can avoid wasting a hash slot by
31         # stuffing the read-end of the pipe into the never-to-be-touched
32         # wbuf
33         $self->{wbuf} = $r;
34         $self;
35 }
36
37 sub _run_all ($) {
38         my ($q) = @_;
39
40         my $run = $q->[0];
41         $q->[0] = [];
42         $q->[1] = undef;
43         $_->() foreach @$run;
44 }
45
46 # ensure PublicInbox::DS::ToClose processing after timers fire
47 sub _asap_close () { $asapq->[1] ||= _asap_timer() }
48
49 sub _run_asap () { _run_all($asapq) }
50 sub _run_next () {
51         _run_all($nextq);
52         _asap_close();
53 }
54
55 sub _run_later () {
56         _run_all($laterq);
57         _asap_close();
58 }
59
60 # Called by PublicInbox::DS
61 sub event_step {
62         my ($self) = @_;
63         _run_asap();
64 }
65
66 sub _asap_timer () {
67         $singleton ||= once_init();
68         $singleton->watch(EPOLLOUT|EPOLLONESHOT);
69         1;
70 }
71
72 sub asap ($) {
73         my ($cb) = @_;
74         push @{$asapq->[0]}, $cb;
75         $asapq->[1] ||= _asap_timer();
76 }
77
78 sub next_tick ($) {
79         my ($cb) = @_;
80         push @{$nextq->[0]}, $cb;
81         $nextq->[1] ||= PublicInbox::DS->AddTimer(0, *_run_next);
82 }
83
84 sub later ($) {
85         my ($cb) = @_;
86         push @{$laterq->[0]}, $cb;
87         $laterq->[1] ||= PublicInbox::DS->AddTimer(60, *_run_later);
88 }
89
90 END {
91         _run_asap();
92         _run_all($nextq);
93         _run_all($laterq);
94 }
95
96 1;