]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/TestCommon.pm
c2d07e5943622115d47e7816f1cd4abc0a5ce6a0
[public-inbox.git] / lib / PublicInbox / TestCommon.pm
1 # Copyright (C) 2015-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # internal APIs used only for tests
5 package PublicInbox::TestCommon;
6 use strict;
7 use parent qw(Exporter);
8 use v5.10.1;
9 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD :seek);
10 use POSIX qw(dup2);
11 use IO::Socket::INET;
12 use File::Spec;
13 our @EXPORT;
14 BEGIN {
15         @EXPORT = qw(tmpdir tcp_server tcp_connect require_git require_mods
16                 run_script start_script key2sub xsys xsys_e xqx eml_load tick
17                 have_xapian_compact json_utf8 setup_public_inboxes create_inbox
18                 tcp_host_port test_lei lei lei_ok $lei_out $lei_err $lei_opt);
19         require Test::More;
20         my @methods = grep(!/\W/, @Test::More::EXPORT);
21         eval(join('', map { "*$_=\\&Test::More::$_;" } @methods));
22         die $@ if $@;
23         push @EXPORT, @methods;
24 }
25
26 sub eml_load ($) {
27         my ($path, $cb) = @_;
28         open(my $fh, '<', $path) or die "open $path: $!";
29         require PublicInbox::Eml;
30         PublicInbox::Eml->new(\(do { local $/; <$fh> }));
31 }
32
33 sub tmpdir (;$) {
34         my ($base) = @_;
35         require File::Temp;
36         unless (defined $base) {
37                 ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
38         }
39         my $tmpdir = File::Temp->newdir("pi-$base-$$-XXXXXX", TMPDIR => 1);
40         ($tmpdir->dirname, $tmpdir);
41 }
42
43 sub tcp_server () {
44         my %opt = (
45                 ReuseAddr => 1,
46                 Proto => 'tcp',
47                 Type => Socket::SOCK_STREAM(),
48                 Listen => 1024,
49                 Blocking => 0,
50         );
51         eval {
52                 die 'IPv4-only' if $ENV{TEST_IPV4_ONLY};
53                 require IO::Socket::INET6;
54                 IO::Socket::INET6->new(%opt, LocalAddr => '[::1]')
55         } || eval {
56                 die 'IPv6-only' if $ENV{TEST_IPV6_ONLY};
57                 IO::Socket::INET->new(%opt, LocalAddr => '127.0.0.1')
58         } || BAIL_OUT "failed to create TCP server: $! ($@)";
59 }
60
61 sub tcp_host_port ($) {
62         my ($s) = @_;
63         my ($h, $p) = ($s->sockhost, $s->sockport);
64         my $ipv4 = $s->sockdomain == Socket::AF_INET();
65         if (wantarray) {
66                 $ipv4 ? ($h, $p) : ("[$h]", $p);
67         } else {
68                 $ipv4 ? "$h:$p" : "[$h]:$p";
69         }
70 }
71
72 sub tcp_connect {
73         my ($dest, %opt) = @_;
74         my $addr = tcp_host_port($dest);
75         my $s = ref($dest)->new(
76                 Proto => 'tcp',
77                 Type => Socket::SOCK_STREAM(),
78                 PeerAddr => $addr,
79                 %opt,
80         ) or BAIL_OUT "failed to connect to $addr: $!";
81         $s->autoflush(1);
82         $s;
83 }
84
85 sub require_git ($;$) {
86         my ($req, $maybe) = @_;
87         my ($req_maj, $req_min, $req_sub) = split(/\./, $req);
88         my ($cur_maj, $cur_min, $cur_sub) = (xqx([qw(git --version)])
89                         =~ /version (\d+)\.(\d+)(?:\.(\d+))?/);
90
91         my $req_int = ($req_maj << 24) | ($req_min << 16) | ($req_sub // 0);
92         my $cur_int = ($cur_maj << 24) | ($cur_min << 16) | ($cur_sub // 0);
93         if ($cur_int < $req_int) {
94                 return 0 if $maybe;
95                 plan skip_all =>
96                         "git $req+ required, have $cur_maj.$cur_min.$cur_sub";
97         }
98         1;
99 }
100
101 sub require_mods {
102         my @mods = @_;
103         my $maybe = pop @mods if $mods[-1] =~ /\A[0-9]+\z/;
104         my @need;
105         while (my $mod = shift(@mods)) {
106                 if ($mod eq 'json') {
107                         $mod = 'Cpanel::JSON::XS||JSON::MaybeXS||'.
108                                 'JSON||JSON::PP'
109                 }
110                 if ($mod eq 'Search::Xapian') {
111                         if (eval { require PublicInbox::Search } &&
112                                 PublicInbox::Search::load_xapian()) {
113                                 next;
114                         }
115                 } elsif ($mod eq 'Search::Xapian::WritableDatabase') {
116                         if (eval { require PublicInbox::SearchIdx } &&
117                                 PublicInbox::SearchIdx::load_xapian_writable()){
118                                         next;
119                         }
120                 } elsif (index($mod, '||') >= 0) { # "Foo||Bar"
121                         my $ok;
122                         for my $m (split(/\Q||\E/, $mod)) {
123                                 eval "require $m";
124                                 next if $@;
125                                 $ok = $m;
126                                 last;
127                         }
128                         next if $ok;
129                 } else {
130                         eval "require $mod";
131                 }
132                 if ($@) {
133                         push @need, $mod;
134                 } elsif ($mod eq 'IO::Socket::SSL' &&
135                         # old versions of IO::Socket::SSL aren't supported
136                         # by libnet, at least:
137                         # https://rt.cpan.org/Ticket/Display.html?id=100529
138                                 !eval{ IO::Socket::SSL->VERSION(2.007); 1 }) {
139                         push @need, $@;
140                 }
141         }
142         return unless @need;
143         my $m = join(', ', @need)." missing for $0";
144         skip($m, $maybe) if $maybe;
145         plan(skip_all => $m)
146 }
147
148 sub key2script ($) {
149         my ($key) = @_;
150         return $key if ($key eq 'git' || index($key, '/') >= 0);
151         # n.b. we may have scripts which don't start with "public-inbox" in
152         # the future:
153         $key =~ s/\A([-\.])/public-inbox$1/;
154         'blib/script/'.$key;
155 }
156
157 my @io_mode = ([ *STDIN{IO}, '+<&' ], [ *STDOUT{IO}, '+>&' ],
158                 [ *STDERR{IO}, '+>&' ]);
159
160 sub _prepare_redirects ($) {
161         my ($fhref) = @_;
162         my $orig_io = [];
163         for (my $fd = 0; $fd <= $#io_mode; $fd++) {
164                 my $fh = $fhref->[$fd] or next;
165                 my ($oldfh, $mode) = @{$io_mode[$fd]};
166                 open my $orig, $mode, $oldfh or die "$oldfh $mode stash: $!";
167                 $orig_io->[$fd] = $orig;
168                 open $oldfh, $mode, $fh or die "$oldfh $mode redirect: $!";
169         }
170         $orig_io;
171 }
172
173 sub _undo_redirects ($) {
174         my ($orig_io) = @_;
175         for (my $fd = 0; $fd <= $#io_mode; $fd++) {
176                 my $fh = $orig_io->[$fd] or next;
177                 my ($oldfh, $mode) = @{$io_mode[$fd]};
178                 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
179         }
180 }
181
182 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows choosing between
183 # three ways to spawn our own short-lived Perl scripts for testing:
184 #
185 # 0 - (fork|vfork) + execve, the most realistic but slowest
186 # 1 - (not currently implemented)
187 # 2 - preloading and running in current process (slightly faster than 1)
188 #
189 # 2 is not compatible with scripts which use "exit" (which we'll try to
190 # avoid in the future).
191 # The default is 2.
192 our $run_script_exit_code;
193 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
194 sub run_script_exit {
195         $run_script_exit_code = $_[0] // 0;
196         die RUN_SCRIPT_EXIT;
197 }
198
199 our %cached_scripts;
200 sub key2sub ($) {
201         my ($key) = @_;
202         $cached_scripts{$key} //= do {
203                 my $f = key2script($key);
204                 open my $fh, '<', $f or die "open $f: $!";
205                 my $str = do { local $/; <$fh> };
206                 my $pkg = (split(m!/!, $f))[-1];
207                 $pkg =~ s/([a-z])([a-z0-9]+)(\.t)?\z/\U$1\E$2/;
208                 $pkg .= "_T" if $3;
209                 $pkg =~ tr/-.//d;
210                 $pkg = "PublicInbox::TestScript::$pkg";
211                 eval <<EOF;
212 package $pkg;
213 use strict;
214 use subs qw(exit);
215
216 *exit = \\&PublicInbox::TestCommon::run_script_exit;
217 sub main {
218 # the below "line" directive is a magic comment, see perlsyn(1) manpage
219 # line 1 "$f"
220 $str
221         0;
222 }
223 1;
224 EOF
225                 $pkg->can('main');
226         }
227 }
228
229 sub _run_sub ($$$) {
230         my ($sub, $key, $argv) = @_;
231         local @ARGV = @$argv;
232         $run_script_exit_code = undef;
233         my $exit_code = eval { $sub->(@$argv) };
234         if ($@ eq RUN_SCRIPT_EXIT) {
235                 $@ = '';
236                 $exit_code = $run_script_exit_code;
237                 $? = ($exit_code << 8);
238         } elsif (defined($exit_code)) {
239                 $? = ($exit_code << 8);
240         } elsif ($@) { # mimic die() behavior when uncaught
241                 warn "E: eval-ed $key: $@\n";
242                 $? = ($! << 8) if $!;
243                 $? = (255 << 8) if $? == 0;
244         } else {
245                 die "BUG: eval-ed $key: no exit code or \$@\n";
246         }
247 }
248
249 sub run_script ($;$$) {
250         my ($cmd, $env, $opt) = @_;
251         my ($key, @argv) = @$cmd;
252         my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
253         my $sub = $run_mode == 0 ? undef : key2sub($key);
254         my $fhref = [];
255         my $spawn_opt = {};
256         for my $fd (0..2) {
257                 my $redir = $opt->{$fd};
258                 my $ref = ref($redir);
259                 if ($ref eq 'SCALAR') {
260                         open my $fh, '+>', undef or die "open: $!";
261                         $fhref->[$fd] = $fh;
262                         $spawn_opt->{$fd} = $fh;
263                         next if $fd > 0;
264                         $fh->autoflush(1);
265                         print $fh $$redir or die "print: $!";
266                         seek($fh, 0, SEEK_SET) or die "seek: $!";
267                 } elsif ($ref eq 'GLOB') {
268                         $spawn_opt->{$fd} = $fhref->[$fd] = $redir;
269                 } elsif ($ref) {
270                         die "unable to deal with $ref $redir";
271                 }
272         }
273         if ($key =~ /-(index|convert|extindex|convert|xcpdb)\z/) {
274                 unshift @argv, '--no-fsync';
275         }
276         if ($run_mode == 0) {
277                 # spawn an independent new process, like real-world use cases:
278                 require PublicInbox::Spawn;
279                 my $cmd = [ key2script($key), @argv ];
280                 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
281                 if (defined $pid) {
282                         my $r = waitpid($pid, 0) // die "waitpid: $!";
283                         $r == $pid or die "waitpid: expected $pid, got $r";
284                 }
285         } else { # localize and run everything in the same process:
286                 # note: "local *STDIN = *STDIN;" and so forth did not work in
287                 # old versions of perl
288                 local %ENV = $env ? (%ENV, %$env) : %ENV;
289                 local %SIG = %SIG;
290                 local $0 = join(' ', @$cmd);
291                 my $orig_io = _prepare_redirects($fhref);
292                 _run_sub($sub, $key, \@argv);
293                 _undo_redirects($orig_io);
294                 select STDOUT;
295         }
296
297         # slurp the redirects back into user-supplied strings
298         for my $fd (1..2) {
299                 my $fh = $fhref->[$fd] or next;
300                 seek($fh, 0, SEEK_SET) or die "seek: $!";
301                 my $redir = $opt->{$fd};
302                 local $/;
303                 $$redir = <$fh>;
304         }
305         $? == 0;
306 }
307
308 sub tick (;$) {
309         my $tick = shift // 0.1;
310         select undef, undef, undef, $tick;
311         1;
312 }
313
314 sub wait_for_tail ($;$) {
315         my ($tail_pid, $want) = @_;
316         my $wait = 2;
317         if ($^O eq 'linux') { # GNU tail may use inotify
318                 state $tail_has_inotify;
319                 return tick if $want < 0 && $tail_has_inotify;
320                 my $end = time + $wait;
321                 my @ino;
322                 do {
323                         @ino = grep {
324                                 readlink($_) =~ /\binotify\b/
325                         } glob("/proc/$tail_pid/fd/*");
326                 } while (!@ino && time <= $end and tick);
327                 return if !@ino;
328                 $tail_has_inotify = 1;
329                 $ino[0] =~ s!/fd/!/fdinfo/!;
330                 my @info;
331                 do {
332                         if (open my $fh, '<', $ino[0]) {
333                                 local $/ = "\n";
334                                 @info = grep(/^inotify wd:/, <$fh>);
335                         }
336                 } while (scalar(@info) < $want && time <= $end and tick);
337         } else {
338                 sleep($wait);
339         }
340 }
341
342 # like system() built-in, but uses spawn() for env/rdr + vfork
343 sub xsys {
344         my ($cmd, $env, $rdr) = @_;
345         if (ref($cmd)) {
346                 $rdr ||= {};
347         } else {
348                 $cmd = [ @_ ];
349                 $env = undef;
350                 $rdr = {};
351         }
352         run_script($cmd, $env, { %$rdr, run_mode => 0 });
353         $? >> 8
354 }
355
356 sub xsys_e { # like "/bin/sh -e"
357         xsys(@_) == 0 or
358                 BAIL_OUT (ref $_[0] ? "@{$_[0]}" : "@_"). " failed \$?=$?"
359 }
360
361 # like `backtick` or qx{} op, but uses spawn() for env/rdr + vfork
362 sub xqx {
363         my ($cmd, $env, $rdr) = @_;
364         $rdr //= {};
365         run_script($cmd, $env, { %$rdr, run_mode => 0, 1 => \(my $out) });
366         wantarray ? split(/^/m, $out) : $out;
367 }
368
369 sub start_script {
370         my ($cmd, $env, $opt) = @_;
371         my ($key, @argv) = @$cmd;
372         my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 2;
373         my $sub = $run_mode == 0 ? undef : key2sub($key);
374         my $tail_pid;
375         if (my $tail_cmd = $ENV{TAIL}) {
376                 my @paths;
377                 for (@argv) {
378                         next unless /\A--std(?:err|out)=(.+)\z/;
379                         push @paths, $1;
380                 }
381                 if ($opt) {
382                         for (1, 2) {
383                                 my $f = $opt->{$_} or next;
384                                 if (!ref($f)) {
385                                         push @paths, $f;
386                                 } elsif (ref($f) eq 'GLOB' && $^O eq 'linux') {
387                                         my $fd = fileno($f);
388                                         my $f = readlink "/proc/$$/fd/$fd";
389                                         push @paths, $f if -e $f;
390                                 }
391                         }
392                 }
393                 if (@paths) {
394                         $tail_pid = fork // die "fork: $!";
395                         if ($tail_pid == 0) {
396                                 # make sure files exist, first
397                                 open my $fh, '>>', $_ for @paths;
398                                 open(STDOUT, '>&STDERR') or die "1>&2: $!";
399                                 exec(split(' ', $tail_cmd), @paths);
400                                 die "$tail_cmd failed: $!";
401                         }
402                         wait_for_tail($tail_pid, scalar @paths);
403                 }
404         }
405         my $pid = fork // die "fork: $!\n";
406         if ($pid == 0) {
407                 eval { PublicInbox::DS->Reset };
408                 # pretend to be systemd (cf. sd_listen_fds(3))
409                 # 3 == SD_LISTEN_FDS_START
410                 my $fd;
411                 for ($fd = 0; 1; $fd++) {
412                         my $s = $opt->{$fd};
413                         last if $fd >= 3 && !defined($s);
414                         next unless $s;
415                         my $fl = fcntl($s, F_GETFD, 0);
416                         if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
417                                 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
418                         }
419                         fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
420                         dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
421                 }
422                 %ENV = (%ENV, %$env) if $env;
423                 my $fds = $fd - 3;
424                 if ($fds > 0) {
425                         $ENV{LISTEN_PID} = $$;
426                         $ENV{LISTEN_FDS} = $fds;
427                 }
428                 $0 = join(' ', @$cmd);
429                 if ($sub) {
430                         eval { PublicInbox::DS->Reset };
431                         _run_sub($sub, $key, \@argv);
432                         POSIX::_exit($? >> 8);
433                 } else {
434                         exec(key2script($key), @argv);
435                         die "FAIL: ",join(' ', $key, @argv), ": $!\n";
436                 }
437         }
438         PublicInboxTestProcess->new($pid, $tail_pid);
439 }
440
441 sub have_xapian_compact () {
442         require PublicInbox::Spawn;
443         # $ENV{XAPIAN_COMPACT} is used by PublicInbox/Xapcmd.pm, too
444         PublicInbox::Spawn::which($ENV{XAPIAN_COMPACT} || 'xapian-compact');
445 }
446
447 our ($err_skip, $lei_opt, $lei_out, $lei_err);
448 # favor lei() or lei_ok() over $lei for new code
449 sub lei (@) {
450         my ($cmd, $env, $xopt) = @_;
451         $lei_out = $lei_err = '';
452         if (!ref($cmd)) {
453                 ($env, $xopt) = grep { (!defined) || ref } @_;
454                 $cmd = [ grep { defined && !ref } @_ ];
455         }
456         my $res = run_script(['lei', @$cmd], $env, $xopt // $lei_opt);
457         $err_skip and
458                 $lei_err = join('', grep(!/$err_skip/, split(/^/m, $lei_err)));
459         $res;
460 };
461
462 sub lei_ok (@) {
463         my $msg = ref($_[-1]) eq 'SCALAR' ? pop(@_) : undef;
464         my $tmpdir = quotemeta(File::Spec->tmpdir);
465         # filter out anything that looks like a path name for consistent logs
466         my @msg = ref($_[0]) eq 'ARRAY' ? @{$_[0]} : @_;
467         for (@msg) {
468                 s!\A([a-z0-9]+://)[^/]+/!$1\$HOST_PORT/! ||
469                         s!$tmpdir\b/(?:[^/]+/)?!\$TMPDIR/!;
470         }
471         ok(lei(@_), "lei @msg". ($msg ? " ($$msg)" : '')) or diag $lei_err;
472 }
473
474 sub json_utf8 () {
475         state $x = ref(PublicInbox::Config->json)->new->utf8->canonical;
476 }
477
478 sub test_lei {
479 SKIP: {
480         my ($cb) = pop @_;
481         my $test_opt = shift // {};
482         require_git(2.6, 1) or skip('git 2.6+ required for lei test', 2);
483         require_mods(qw(json DBD::SQLite Search::Xapian), 2);
484         require PublicInbox::Config;
485         local %ENV = %ENV;
486         delete $ENV{XDG_DATA_HOME};
487         delete $ENV{XDG_CONFIG_HOME};
488         $ENV{GIT_COMMITTER_EMAIL} = 'lei@example.com';
489         $ENV{GIT_COMMITTER_NAME} = 'lei user';
490         my (undef, $fn, $lineno) = caller(0);
491         my $t = "$fn:$lineno";
492         require PublicInbox::Spawn;
493         state $lei_daemon = PublicInbox::Spawn->can('send_cmd4') ||
494                                 eval { require Socket::MsgHdr; 1 };
495         # XXX fix and move this inside daemon-only before 1.7 release
496         skip <<'EOM', 1 unless $lei_daemon;
497 Socket::MsgHdr missing or Inline::C is unconfigured/missing
498 EOM
499         $lei_opt = { 1 => \$lei_out, 2 => \$lei_err };
500         my ($daemon_pid, $for_destroy);
501         my $tmpdir = $test_opt->{tmpdir};
502         ($tmpdir, $for_destroy) = tmpdir unless $tmpdir;
503         SKIP: {
504                 skip 'TEST_LEI_ONESHOT set', 1 if $ENV{TEST_LEI_ONESHOT};
505                 my $home = "$tmpdir/lei-daemon";
506                 mkdir($home, 0700) or BAIL_OUT "mkdir: $!";
507                 local $ENV{HOME} = $home;
508                 my $xrd = "$home/xdg_run";
509                 mkdir($xrd, 0700) or BAIL_OUT "mkdir: $!";
510                 local $ENV{XDG_RUNTIME_DIR} = $xrd;
511                 $cb->();
512                 lei_ok(qw(daemon-pid), \"daemon-pid after $t");
513                 chomp($daemon_pid = $lei_out);
514                 if ($daemon_pid) {
515                         ok(kill(0, $daemon_pid), "daemon running after $t");
516                         lei_ok(qw(daemon-kill), \"daemon-kill after $t");
517                 } else {
518                         fail("daemon not running after $t");
519                 }
520         }; # SKIP for lei_daemon
521         unless ($test_opt->{daemon_only}) {
522                 $ENV{TEST_LEI_DAEMON_ONLY} and
523                         skip 'TEST_LEI_DAEMON_ONLY set', 1;
524                 require_ok 'PublicInbox::LEI';
525                 my $home = "$tmpdir/lei-oneshot";
526                 mkdir($home, 0700) or BAIL_OUT "mkdir: $!";
527                 local $ENV{HOME} = $home;
528                 # force sun_path[108] overflow:
529                 my $xrd = "$home/1shot-test".('.sun_path' x 108);
530                 local $err_skip = qr!\Q$xrd!; # for lei() filtering
531                 local $ENV{XDG_RUNTIME_DIR} = $xrd;
532                 $cb->();
533         }
534         if ($daemon_pid) {
535                 for (0..10) {
536                         kill(0, $daemon_pid) or last;
537                         tick;
538                 }
539                 ok(!kill(0, $daemon_pid), "$t daemon stopped after oneshot");
540         }
541 }; # SKIP if missing git 2.6+ || Xapian || SQLite || json
542 } # /test_lei
543
544 # returns the pathname to a ~/.public-inbox/config in scalar context,
545 # ($test_home, $pi_config_pathname) in list context
546 sub setup_public_inboxes () {
547         my $test_home = "t/home2";
548         my $pi_config = "$test_home/.public-inbox/config";
549         my $stamp = "$test_home/setup-stamp";
550         my @ret = ($test_home, $pi_config);
551         return @ret if -f $stamp;
552
553         require PublicInbox::Lock;
554         my $lk = bless { lock_path => "$test_home/setup.lock" },
555                         'PublicInbox::Lock';
556         my $end = $lk->lock_for_scope;
557         return @ret if -f $stamp;
558
559         local $ENV{PI_CONFIG} = $pi_config;
560         for my $V (1, 2) {
561                 run_script([qw(-init --skip-docdata), "-V$V",
562                                 '--newsgroup', "t.v$V", "t$V",
563                                 "$test_home/t$V", "http://example.com/t$V",
564                                 "t$V\@example.com" ]) or BAIL_OUT "init v$V";
565         }
566         require PublicInbox::Config;
567         require PublicInbox::InboxWritable;
568         my $cfg = PublicInbox::Config->new;
569         my $seen = 0;
570         $cfg->each_inbox(sub {
571                 my ($ibx) = @_;
572                 $ibx->{-no_fsync} = 1;
573                 my $im = PublicInbox::InboxWritable->new($ibx)->importer(0);
574                 my $V = $ibx->version;
575                 my @eml = (glob('t/*.eml'), 't/data/0001.patch');
576                 for (@eml) {
577                         next if $_ eq 't/psgi_v2-old.eml'; # dup mid
578                         $im->add(eml_load($_)) or BAIL_OUT "v$V add $_";
579                         $seen++;
580                 }
581                 $im->done;
582         });
583         $seen or BAIL_OUT 'no imports';
584         open my $fh, '>', $stamp or BAIL_OUT "open $stamp: $!";
585         @ret;
586 }
587
588 sub create_inbox ($$;@) {
589         my $ident = shift;
590         my $cb = pop;
591         my %opt = @_;
592         require PublicInbox::Lock;
593         require PublicInbox::InboxWritable;
594         my ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
595         my $dir = "t/data-gen/$base.$ident";
596         my $new = !-d $dir;
597         if ($new) {
598                 mkdir $dir; # may race
599                 -d $dir or BAIL_OUT "$dir could not be created: $!";
600         }
601         my $lk = bless { lock_path => "$dir/creat.lock" }, 'PublicInbox::Lock';
602         $opt{inboxdir} = File::Spec->rel2abs($dir);
603         $opt{name} //= $ident;
604         my $scope = $lk->lock_for_scope;
605         my $pre_cb = delete $opt{pre_cb};
606         $pre_cb->($dir) if $pre_cb && $new;
607         $opt{-no_fsync} = 1;
608         my $no_gc = delete $opt{-no_gc};
609         my $tmpdir = delete $opt{tmpdir};
610         my $addr = $opt{address} // [];
611         $opt{-primary_address} //= $addr->[0] // "$ident\@example.com";
612         my $parallel = delete($opt{importer_parallel}) // 0;
613         my $creat_opt = { nproc => delete($opt{nproc}) // 1 };
614         my $ibx = PublicInbox::InboxWritable->new({ %opt }, $creat_opt);
615         if (!-f "$dir/creat.stamp") {
616                 my $im = $ibx->importer($parallel);
617                 $cb->($im, $ibx);
618                 $im->done if $im;
619                 unless ($no_gc) {
620                         my @to_gc = $ibx->version == 1 ? ($ibx->{inboxdir}) :
621                                         glob("$ibx->{inboxdir}/git/*.git");
622                         for my $dir (@to_gc) {
623                                 xsys_e([ qw(git gc -q) ], { GIT_DIR => $dir });
624                         }
625                 }
626                 open my $s, '>', "$dir/creat.stamp" or
627                         BAIL_OUT "error creating $dir/creat.stamp: $!";
628         }
629         if ($tmpdir) {
630                 undef $ibx;
631                 xsys([qw(/bin/cp -Rp), $dir, $tmpdir]) == 0 or
632                         BAIL_OUT "cp $dir $tmpdir";
633                 $opt{inboxdir} = $tmpdir;
634                 $ibx = PublicInbox::InboxWritable->new(\%opt);
635         }
636         $ibx;
637 }
638
639 package PublicInboxTestProcess;
640 use strict;
641
642 # prevent new threads from inheriting these objects
643 sub CLONE_SKIP { 1 }
644
645 sub new {
646         my ($klass, $pid, $tail_pid) = @_;
647         bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
648 }
649
650 sub kill {
651         my ($self, $sig) = @_;
652         CORE::kill($sig // 'TERM', $self->{pid});
653 }
654
655 sub join {
656         my ($self, $sig) = @_;
657         my $pid = delete $self->{pid} or return;
658         CORE::kill($sig, $pid) if defined $sig;
659         my $ret = waitpid($pid, 0) // die "waitpid($pid): $!";
660         $ret == $pid or die "waitpid($pid) != $ret";
661 }
662
663 sub DESTROY {
664         my ($self) = @_;
665         return if $self->{owner} != $$;
666         if (my $tail_pid = delete $self->{tail_pid}) {
667                 PublicInbox::TestCommon::wait_for_tail($tail_pid, -1);
668                 CORE::kill('TERM', $tail_pid);
669         }
670         $self->join('TERM');
671 }
672
673 package PublicInbox::TestCommon::InboxWakeup;
674 use strict;
675 sub on_inbox_unlock { ${$_[0]}->($_[1]) }
676
677 1;