]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SolverGit.pm
qspawn: improve error reporting and handling
[public-inbox.git] / lib / PublicInbox / SolverGit.pm
1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # "Solve" blobs which don't exist in git code repositories by
5 # searching inboxes for post-image blobs.
6
7 # this emits a lot of debugging/tracing information which may be
8 # publicly viewed over HTTP(S).  Be careful not to expose
9 # local filesystem layouts in the process.
10 package PublicInbox::SolverGit;
11 use strict;
12 use v5.10.1;
13 use File::Temp 0.19 (); # 0.19 for ->newdir
14 use Fcntl qw(SEEK_SET);
15 use PublicInbox::Git qw(git_unquote git_quote);
16 use PublicInbox::MsgIter qw(msg_part_text);
17 use PublicInbox::Qspawn;
18 use PublicInbox::Tmpfile;
19 use PublicInbox::GitAsyncCat;
20 use PublicInbox::Eml;
21 use URI::Escape qw(uri_escape_utf8);
22
23 # POSIX requires _POSIX_ARG_MAX >= 4096, and xargs is required to
24 # subtract 2048 bytes.  We also don't factor in environment variable
25 # headroom into this.
26 use POSIX qw(sysconf _SC_ARG_MAX);
27 my $ARG_SIZE_MAX = (sysconf(_SC_ARG_MAX) || 4096) - 2048;
28 my $OID_MIN = 7;
29
30 # By default, "git format-patch" generates filenames with a four-digit
31 # prefix, so that means 9999 patch series are OK, right? :>
32 # Maybe we can make this configurable, main concern is disk space overhead
33 # for uncompressed patch fragments.  Aside from space, public-inbox-httpd
34 # is otherwise unaffected by having many patches, here, as it can share
35 # work fairly.  Other PSGI servers may have trouble, though.
36 my $MAX_PATCH = 9999;
37
38 my $LF = qr!\r?\n!;
39 my $ANY = qr![^\r\n]+!;
40 my $MODE = '100644|120000|100755';
41 my $FN = qr!(?:("?[^/\n]+/[^\r\n]+)|/dev/null)!;
42 my %BAD_COMPONENT = ('' => 1, '.' => 1, '..' => 1);
43
44 # di = diff info / a hashref with information about a diff ($di):
45 # {
46 #       oid_a => abbreviated pre-image oid,
47 #       oid_b => abbreviated post-image oid,
48 #       tmp => anonymous file handle with the diff,
49 #       hdr_lines => string of various header lines for mode information
50 #       mode_a => original mode of oid_a (string, not integer),
51 #       ibx => PublicInbox::Inbox object containing the diff
52 #       smsg => PublicInbox::Smsg object containing diff
53 #       path_a => pre-image path
54 #       path_b => post-image path
55 #       n => numeric path of the patch (relative to worktree)
56 # }
57
58 sub dbg ($$) {
59         print { $_[0]->{out} } $_[1], "\n" or ERR($_[0], "print(dbg): $!");
60 }
61
62 sub done ($$) {
63         my ($self, $res) = @_;
64         my $ucb = delete($self->{user_cb}) or return;
65         $ucb->($res, $self->{uarg});
66 }
67
68 sub ERR ($$) {
69         my ($self, $err) = @_;
70         print { $self->{out} } $err, "\n";
71         eval { done($self, $err) };
72         die $err;
73 }
74
75 # look for existing objects already in git repos, returns arrayref
76 # if found, number of remaining git coderepos to try if not.
77 sub solve_existing ($$) {
78         my ($self, $want) = @_;
79         my $try = $want->{try_gits} //= [ @{$self->{gits}} ]; # array copy
80         my $git = shift @$try or die 'BUG {try_gits} empty';
81         my $oid_b = $want->{oid_b};
82         my ($oid_full, $type, $size) = $git->check($oid_b);
83
84         # other than {oid_b, try_gits, try_ibxs}
85         my $have_hints = scalar keys %$want > 3;
86         if (defined($type) && (!$have_hints || $type eq 'blob')) {
87                 delete $want->{try_gits};
88                 return [ $git, $oid_full, $type, int($size) ]; # done, success
89         }
90
91         # TODO: deal with 40-char "abbreviations" with future SHA-256 git
92         return scalar(@$try) if length($oid_b) >= 40;
93
94         # parse stderr of "git cat-file --batch-check"
95         my $err = $git->last_check_err;
96         my (@oids) = ($err =~ /\b([a-f0-9]{40,})\s+blob\b/g);
97         return scalar(@$try) unless scalar(@oids);
98
99         # TODO: do something with the ambiguous array?
100         # push @ambiguous, [ $git, @oids ];
101
102         dbg($self, "`$oid_b' ambiguous in " .
103                         join("\n\t", $git->pub_urls($self->{psgi_env}))
104                         . "\n" .
105                         join('', map { "$_ blob\n" } @oids));
106         scalar(@$try);
107 }
108
109 sub extract_diff ($$) {
110         my ($p, $arg) = @_;
111         my ($self, $want, $smsg) = @$arg;
112         my ($part) = @$p; # ignore $depth and @idx;
113         my $ct = $part->content_type || 'text/plain';
114         my $post = $want->{oid_b};
115         my $pre = $want->{oid_a};
116         if (!defined($pre) || $pre !~ /\A[a-f0-9]+\z/) {
117                 $pre = '[a-f0-9]{7}'; # for RE below
118         }
119
120         # Email::MIME::Encodings forces QP to be CRLF upon decoding,
121         # change it back to LF:
122         my $cte = $part->header('Content-Transfer-Encoding') || '';
123         my ($s, undef) = msg_part_text($part, $ct);
124         defined $s or return;
125         delete $part->{bdy};
126         if ($cte =~ /\bquoted-printable\b/i && $part->crlf eq "\n") {
127                 $s =~ s/\r\n/\n/sg;
128         }
129         $s =~ m!( # $1 start header lines we save for debugging:
130
131                 # everything before ^index is optional, but we don't
132                 # want to match ^(old|copy|rename|deleted|...) unless
133                 # we match /^diff --git/ first:
134                 (?: # begin optional stuff:
135
136                 # try to get the pre-and-post filenames as $2 and $3
137                 (?:^diff\x20--git\x20$FN\x20$FN$LF)
138
139                 (?:^(?: # pass all this to git-apply:
140                         # old mode $4
141                         (?:old\x20mode\x20($MODE))
142                         |
143                         # new mode (possibly new file) ($5)
144                         (?:new\x20(?:file\x20)?mode\x20($MODE))
145                         |
146                         (?:(?:copy|rename|deleted|
147                                 dissimilarity|similarity)$ANY)
148                 )$LF)*
149
150                 )? # end of optional stuff, everything below is required
151
152                 # match the pre and post-image OIDs as $6 $7
153                 ^index\x20(${pre}[a-f0-9]*)\.\.(${post}[a-f0-9]*)
154                         # mode if unchanged $8
155                         (?:\x20(100644|120000|100755))?$LF
156         ) # end of header lines ($1)
157         ( # $9 is the patch body
158                 # "--- a/foo.c" sets pre-filename ($10) in case
159                 # $2 is missing
160                 (?:^---\x20$FN$LF)
161
162                 # "+++ b/foo.c" sets post-filename ($11) in case
163                 # $3 is missing
164                 (?:^\+{3}\x20$FN$LF)
165
166                 # the meat of the diff, including "^\\No newline ..."
167                 # We also allow for totally blank lines w/o leading spaces,
168                 # because git-apply(1) handles that case, too
169                 (?:^(?:[\@\+\x20\-\\][^\n]*|)$LF)+
170         )!smx or return;
171         undef $s; # free memory
172
173         my $di = {
174                 hdr_lines => $1,
175                 oid_a => $6,
176                 oid_b => $7,
177                 mode_a => $5 // $8 // $4, # new (file) // unchanged // old
178         };
179         my $path_a = $2 // $10;
180         my $path_b = $3 // $11;
181         my $patch = $9;
182
183         # don't care for leading 'a/' and 'b/'
184         my (undef, @a) = split(m{/}, git_unquote($path_a)) if defined($path_a);
185         my (undef, @b) = split(m{/}, git_unquote($path_b));
186
187         # get rid of path-traversal attempts and junk patches:
188         # it's junk at best, an attack attempt at worse:
189         foreach (@a, @b) { return if $BAD_COMPONENT{$_} }
190
191         $di->{path_a} = join('/', @a) if @a;
192         $di->{path_b} = join('/', @b);
193
194         my $path = ++$self->{tot};
195         $di->{n} = $path;
196         open(my $tmp, '>:utf8', $self->{tmp}->dirname . "/$path") or
197                 die "open(tmp): $!";
198         print $tmp $di->{hdr_lines}, $patch or die "print(tmp): $!";
199         close $tmp or die "close(tmp): $!";
200
201         # for debugging/diagnostics:
202         $di->{ibx} = $want->{cur_ibx};
203         $di->{smsg} = $smsg;
204
205         push @{$self->{tmp_diffs}}, $di;
206 }
207
208 sub path_searchable ($) { defined($_[0]) && $_[0] =~ m!\A[\w/\. \-]+\z! }
209
210 # ".." appears in path names, which confuses Xapian into treating
211 # it as a range query.  So we split on ".." since Xapian breaks
212 # on punctuation anyways:
213 sub filename_query ($) {
214         join('', map { qq( dfn:"$_") } split(/\.\./, $_[0]));
215 }
216
217 sub find_smsgs ($$$) {
218         my ($self, $ibx, $want) = @_;
219         my $srch = $ibx->isrch or return;
220
221         my $post = $want->{oid_b} or die 'BUG: no {oid_b}';
222         $post =~ /\A[a-f0-9]+\z/ or die "BUG: oid_b not hex: $post";
223
224         my $q = "dfpost:$post";
225         my $pre = $want->{oid_a};
226         if (defined $pre && $pre =~ /\A[a-f0-9]+\z/) {
227                 $q .= " dfpre:$pre";
228         }
229
230         my $path_b = $want->{path_b};
231         if (path_searchable($path_b)) {
232                 $q .= filename_query($path_b);
233
234                 my $path_a = $want->{path_a};
235                 if (path_searchable($path_a) && $path_a ne $path_b) {
236                         $q .= filename_query($path_a);
237                 }
238         }
239         my $mset = $srch->mset($q, { relevance => 1 });
240         $mset->size ? $srch->mset_to_smsg($ibx, $mset) : undef;
241 }
242
243 sub update_index_result ($$) {
244         my ($bref, $self) = @_;
245         my ($qsp_err, $msg) = delete @$self{qw(-qsp_err -msg)};
246         ERR($self, "git update-index error:$qsp_err") if $qsp_err;
247         dbg($self, $msg);
248         next_step($self); # onto do_git_apply
249 }
250
251 sub prepare_index ($) {
252         my ($self) = @_;
253         my $patches = $self->{patches};
254         $self->{nr} = 0;
255
256         my $di = $patches->[0] or die 'no patches';
257         my $oid_a = $di->{oid_a} or die '{oid_a} unset';
258         my $existing = $self->{found}->{$oid_a};
259
260         # no index creation for added files
261         $oid_a =~ /\A0+\z/ and return next_step($self);
262
263         die "BUG: $oid_a not found" unless $existing;
264
265         my $oid_full = $existing->[1];
266         my $path_a = $di->{path_a} or die "BUG: path_a missing for $oid_full";
267         my $mode_a = $di->{mode_a} // '100644';
268
269         my $in = tmpfile("update-index.$oid_full") or die "tmpfile: $!";
270         print $in "$mode_a $oid_full\t$path_a\0" or die "print: $!";
271         $in->flush or die "flush: $!";
272         sysseek($in, 0, SEEK_SET) or die "seek: $!";
273
274         dbg($self, 'preparing index');
275         my $rdr = { 0 => $in };
276         my $cmd = [ qw(git update-index -z --index-info) ];
277         my $qsp = PublicInbox::Qspawn->new($cmd, $self->{git_env}, $rdr);
278         $path_a = git_quote($path_a);
279         $qsp->{qsp_err} = \($self->{-qsp_err} = '');
280         $self->{-msg} = "index prepared:\n$mode_a $oid_full\t$path_a";
281         $qsp->psgi_qx($self->{psgi_env}, undef, \&update_index_result, $self);
282 }
283
284 # pure Perl "git init"
285 sub do_git_init ($) {
286         my ($self) = @_;
287         my $dir = $self->{tmp}->dirname;
288         my $git_dir = "$dir/git";
289
290         foreach ('', qw(objects refs objects/info refs/heads)) {
291                 mkdir("$git_dir/$_") or die "mkdir $_: $!";
292         }
293         open my $fh, '>', "$git_dir/config" or die "open git/config: $!";
294         my $first = $self->{gits}->[0];
295         my $fmt = $first->object_format;
296         my $v = defined($$fmt) ? 1 : 0;
297         print $fh <<EOF or die "print git/config $!";
298 [core]
299         repositoryFormatVersion = $v
300         filemode = true
301         bare = false
302         logAllRefUpdates = false
303 EOF
304         print $fh <<EOM if defined($$fmt);
305 [extensions]
306         objectformat = $$fmt
307 EOM
308         close $fh or die "close git/config: $!";
309
310         open $fh, '>', "$git_dir/HEAD" or die "open git/HEAD: $!";
311         print $fh "ref: refs/heads/master\n" or die "print git/HEAD: $!";
312         close $fh or die "close git/HEAD: $!";
313
314         my $f = 'objects/info/alternates';
315         open $fh, '>', "$git_dir/$f" or die "open: $f: $!";
316         foreach my $git (@{$self->{gits}}) {
317                 print $fh $git->git_path('objects'),"\n" or die "print $f: $!";
318         }
319         close $fh or die "close: $f: $!";
320         my $tmp_git = $self->{tmp_git} = PublicInbox::Git->new($git_dir);
321         $tmp_git->{-tmp} = $self->{tmp};
322         $self->{git_env} = {
323                 GIT_DIR => $git_dir,
324                 GIT_INDEX_FILE => "$git_dir/index",
325                 GIT_TEST_FSYNC => 0, # undocumented git env
326         };
327         prepare_index($self);
328 }
329
330 sub do_finish ($) {
331         my ($self) = @_;
332         my ($found, $oid_want) = @$self{qw(found oid_want)};
333         if (my $exists = $found->{$oid_want}) {
334                 return done($self, $exists);
335         }
336
337         # let git disambiguate if oid_want was too short,
338         # but long enough to be unambiguous:
339         my $tmp_git = $self->{tmp_git};
340         if (my @res = $tmp_git->check($oid_want)) {
341                 return done($self, $found->{$res[0]});
342         }
343         if (my $err = $tmp_git->last_check_err) {
344                 dbg($self, $err);
345         }
346         done($self, undef);
347 }
348
349 sub event_step ($) {
350         my ($self) = @_;
351         eval {
352                 # step 1: resolve blobs to patches in the todo queue
353                 if (my $want = pop @{$self->{todo}}) {
354                         # this populates {patches} and {todo}
355                         resolve_patch($self, $want);
356
357                 # step 2: then we instantiate a working tree once
358                 # the todo queue is finally empty:
359                 } elsif (!defined($self->{tmp_git})) {
360                         do_git_init($self);
361
362                 # step 3: apply each patch in the stack
363                 } elsif (scalar @{$self->{patches}}) {
364                         do_git_apply($self);
365
366                 # step 4: execute the user-supplied callback with
367                 # our result: (which may be undef)
368                 # Other steps may call user_cb to terminate prematurely
369                 # on error
370                 } elsif (exists $self->{user_cb}) {
371                         do_finish($self);
372                 } else {
373                         die 'about to call user_cb twice'; # Oops :x
374                 }
375         }; # eval
376         my $err = $@;
377         if ($err) {
378                 $err =~ s/^\s*Exception:\s*//; # bad word to show users :P
379                 dbg($self, "E: $err");
380                 eval { done($self, $err) };
381         }
382 }
383
384 sub next_step ($) {
385         my ($self) = @_;
386         # if outside of public-inbox-httpd, caller is expected to be
387         # looping event_step, anyways
388         my $async = $self->{psgi_env}->{'pi-httpd.async'} or return;
389         # PublicInbox::HTTPD::Async->new
390         $async->(undef, undef, $self);
391 }
392
393 sub mark_found ($$$) {
394         my ($self, $oid, $found_info) = @_;
395         my $found = $self->{found};
396         $found->{$oid} = $found_info;
397         my $oid_cur = $found_info->[1];
398         while ($oid_cur ne $oid && length($oid_cur) > $OID_MIN) {
399                 $found->{$oid_cur} = $found_info;
400                 chop($oid_cur);
401         }
402 }
403
404 sub parse_ls_files ($$) {
405         my ($self, $bref) = @_;
406         my ($qsp_err, $di) = delete @$self{qw(-qsp_err -cur_di)};
407         die "git ls-files error:$qsp_err" if $qsp_err;
408
409         my ($line, @extra) = split(/\0/, $$bref);
410         scalar(@extra) and die "BUG: extra files in index: <",
411                                 join('> <', @extra), ">";
412
413         my ($info, $file) = split(/\t/, $line, 2);
414         my ($mode_b, $oid_b_full, $stage) = split(/ /, $info);
415         if ($file ne $di->{path_b}) {
416                 die
417 "BUG: index mismatch: file=$file != path_b=$di->{path_b}";
418         }
419
420         my $tmp_git = $self->{tmp_git} or die 'no git working tree';
421         my (undef, undef, $size) = $tmp_git->check($oid_b_full);
422         defined($size) or die "check $oid_b_full failed";
423
424         dbg($self, "index at:\n$mode_b $oid_b_full\t$file");
425         my $created = [ $tmp_git, $oid_b_full, 'blob', $size, $di ];
426         mark_found($self, $di->{oid_b}, $created);
427         next_step($self); # onto the next patch
428 }
429
430 sub ls_files_result {
431         my ($bref, $self) = @_;
432         eval { parse_ls_files($self, $bref) };
433         ERR($self, $@) if $@;
434 }
435
436 sub oids_same_ish ($$) {
437         (index($_[0], $_[1]) == 0) || (index($_[1], $_[0]) == 0);
438 }
439
440 sub skip_identical ($$$) {
441         my ($self, $patches, $cur_oid_b) = @_;
442         while (my $nxt = $patches->[0]) {
443                 if (oids_same_ish($cur_oid_b, $nxt->{oid_b})) {
444                         dbg($self, 'skipping '.di_url($self, $nxt).
445                                 " for $cur_oid_b");
446                         shift @$patches;
447                 } else {
448                         return;
449                 }
450         }
451 }
452
453 sub apply_result ($$) {
454         my ($bref, $self) = @_;
455         my ($qsp_err, $di) = delete @$self{qw(-qsp_err -cur_di)};
456         dbg($self, $$bref);
457         my $patches = $self->{patches};
458         if ($qsp_err) {
459                 my $msg = "git apply error:$qsp_err";
460                 my $nxt = $patches->[0];
461                 if ($nxt && oids_same_ish($nxt->{oid_b}, $di->{oid_b})) {
462                         dbg($self, $msg);
463                         dbg($self, 'trying '.di_url($self, $nxt));
464                         return do_git_apply($self);
465                 } else {
466                         ERR($self, $msg);
467                 }
468         } else {
469                 skip_identical($self, $patches, $di->{oid_b});
470         }
471
472         my @cmd = qw(git ls-files -s -z);
473         my $qsp = PublicInbox::Qspawn->new(\@cmd, $self->{git_env});
474         $self->{-cur_di} = $di;
475         $qsp->{qsp_err} = \($self->{-qsp_err} = '');
476         $qsp->psgi_qx($self->{psgi_env}, undef, \&ls_files_result, $self);
477 }
478
479 sub do_git_apply ($) {
480         my ($self) = @_;
481         my $dn = $self->{tmp}->dirname;
482         my $patches = $self->{patches};
483
484         # we need --ignore-whitespace because some patches are CRLF
485         my @cmd = (qw(git apply --cached --ignore-whitespace
486                         --unidiff-zero --whitespace=warn --verbose));
487         my $len = length(join(' ', @cmd));
488         my $total = $self->{tot};
489         my $di; # keep track of the last one for "git ls-files"
490         my $prv_oid_b;
491
492         do {
493                 my $i = ++$self->{nr};
494                 $di = shift @$patches;
495                 dbg($self, "\napplying [$i/$total] " . di_url($self, $di) .
496                         "\n" . $di->{hdr_lines});
497                 my $path = $di->{n};
498                 $len += length($path) + 1;
499                 push @cmd, $path;
500                 $prv_oid_b = $di->{oid_b};
501         } while (@$patches && $len < $ARG_SIZE_MAX &&
502                  !oids_same_ish($patches->[0]->{oid_b}, $prv_oid_b));
503
504         my $opt = { 2 => 1, -C => $dn, quiet => 1 };
505         my $qsp = PublicInbox::Qspawn->new(\@cmd, $self->{git_env}, $opt);
506         $self->{-cur_di} = $di;
507         $qsp->{qsp_err} = \($self->{-qsp_err} = '');
508         $qsp->psgi_qx($self->{psgi_env}, undef, \&apply_result, $self);
509 }
510
511 sub di_url ($$) {
512         my ($self, $di) = @_;
513         # note: we don't pass the PSGI env unconditionally, here,
514         # different inboxes can have different HTTP_HOST on the same instance.
515         my $ibx = $di->{ibx};
516         my $env = $self->{psgi_env} if $ibx eq $self->{inboxes}->[0];
517         my $url = $ibx->base_url($env);
518         my $mid = $di->{smsg}->{mid};
519         defined($url) ? "$url$mid/" : "<$mid>";
520 }
521
522 sub retry_current {
523         my ($self, $want) = @_;
524         push @{$self->{todo}}, $want;
525         next_step($self); # retry solve_existing
526 }
527
528 sub try_harder ($$) {
529         my ($self, $want) = @_;
530
531         # do we have more inboxes to try?
532         return retry_current($self, $want) if scalar @{$want->{try_ibxs}};
533
534         my $cur_want = $want->{oid_b};
535         if (length($cur_want) > $OID_MIN) { # maybe a shorter OID will work
536                 delete $want->{try_ibxs}; # drop empty arrayref
537                 chop($cur_want);
538                 dbg($self, "retrying $want->{oid_b} as $cur_want");
539                 $want->{oid_b} = $cur_want;
540                 return retry_current($self, $want); # retry with shorter abbrev
541         }
542
543         dbg($self, "could not find $cur_want");
544         eval { done($self, undef) };
545         die "E: $@" if $@;
546 }
547
548 sub extract_diffs_done {
549         my ($self, $want) = @_;
550
551         delete $want->{try_smsgs};
552         delete $want->{cur_ibx};
553
554         my $diffs = delete $self->{tmp_diffs};
555         if (scalar @$diffs) {
556                 unshift @{$self->{patches}}, @$diffs;
557                 dbg($self, "found $want->{oid_b} in " .  join(" ||\n\t",
558                         map { di_url($self, $_) } @$diffs));
559
560                 # good, we can find a path to the oid we $want, now
561                 # lets see if we need to apply more patches:
562                 my $di = $diffs->[0];
563                 my $src = $di->{oid_a};
564
565                 unless ($src =~ /\A0+\z/) {
566                         # we have to solve it using another oid, fine:
567                         my $job = { oid_b => $src, path_b => $di->{path_a} };
568                         push @{$self->{todo}}, $job;
569                 }
570                 return next_step($self); # onto the next todo item
571         }
572         try_harder($self, $want);
573 }
574
575 sub extract_diff_async {
576         my ($bref, $oid, $type, $size, $x) = @_;
577         my ($self, $want, $smsg) = @$x;
578         if (defined($oid)) {
579                 $smsg->{blob} eq $oid or
580                                 ERR($self, "BUG: $smsg->{blob} != $oid");
581                 PublicInbox::Eml->new($bref)->each_part(\&extract_diff, $x, 1);
582         }
583
584         scalar(@{$want->{try_smsgs}}) ? retry_current($self, $want)
585                                         : extract_diffs_done($self, $want);
586 }
587
588 sub resolve_patch ($$) {
589         my ($self, $want) = @_;
590
591         my $cur_want = $want->{oid_b};
592         if (scalar(@{$self->{patches}}) > $MAX_PATCH) {
593                 die "Aborting, too many steps to $self->{oid_want}";
594         }
595
596         if (my $msgs = $want->{try_smsgs}) {
597                 my $smsg = shift @$msgs;
598                 if ($self->{psgi_env}->{'pi-httpd.async'}) {
599                         return ibx_async_cat($want->{cur_ibx}, $smsg->{blob},
600                                                 \&extract_diff_async,
601                                                 [$self, $want, $smsg]);
602                 } else {
603                         if (my $eml = $want->{cur_ibx}->smsg_eml($smsg)) {
604                                 $eml->each_part(\&extract_diff,
605                                                 [ $self, $want, $smsg ], 1);
606                         }
607                 }
608
609                 return scalar(@$msgs) ? retry_current($self, $want)
610                                         : extract_diffs_done($self, $want);
611         }
612
613         # see if we can find the blob in an existing git repo:
614         if (!$want->{try_ibxs} && $self->{seen_oid}->{$cur_want}++) {
615                 die "Loop detected solving $cur_want\n";
616         }
617         $want->{try_ibxs} //= [ @{$self->{inboxes}} ]; # array copy
618         my $existing = solve_existing($self, $want);
619         if (ref $existing) {
620                 my ($found_git, undef, $type, undef) = @$existing;
621                 dbg($self, "found $cur_want in " .
622                         join(" ||\n\t",
623                                 $found_git->pub_urls($self->{psgi_env})));
624
625                 if ($cur_want eq $self->{oid_want} || $type ne 'blob') {
626                         eval { done($self, $existing) };
627                         die "E: $@" if $@;
628                         return;
629                 }
630                 mark_found($self, $cur_want, $existing);
631                 return next_step($self); # onto patch application
632         } elsif ($existing > 0) {
633                 return retry_current($self, $want);
634         } else { # $existing == 0: we may retry if inbox scan (below) fails
635                 delete $want->{try_gits};
636         }
637
638         # scan through inboxes to look for emails which results in
639         # the oid we want:
640         my $ibx = shift(@{$want->{try_ibxs}}) or die 'BUG: {try_ibxs} empty';
641         if (my $msgs = find_smsgs($self, $ibx, $want)) {
642                 $want->{try_smsgs} = $msgs;
643                 $want->{cur_ibx} = $ibx;
644                 $self->{tmp_diffs} = [];
645                 return retry_current($self, $want);
646         }
647         try_harder($self, $want);
648 }
649
650 # this API is designed to avoid creating self-referential structures;
651 # so user_cb never references the SolverGit object
652 sub new {
653         my ($class, $ibx, $user_cb, $uarg) = @_;
654
655         bless {
656                 gits => $ibx->{-repo_objs},
657                 user_cb => $user_cb,
658                 uarg => $uarg,
659                 # -cur_di, -qsp_err, -msg => temp fields for Qspawn callbacks
660
661                 # TODO: config option for searching related inboxes
662                 inboxes => [ $ibx ],
663         }, $class;
664 }
665
666 # recreate $oid_want using $hints
667 # hints keys: path_a, path_b, oid_a (note: `oid_b' is NOT a hint)
668 # Calls {user_cb} with: [ ::Git object, oid_full, type, size, di (diff_info) ]
669 # with found object, or undef if nothing was found
670 # Calls {user_cb} with a string error on fatal errors
671 sub solve ($$$$$) {
672         my ($self, $env, $out, $oid_want, $hints) = @_;
673
674         # should we even get here? Probably not, but somebody
675         # could be manually typing URLs:
676         return done($self, undef) if $oid_want =~ /\A0+\z/;
677
678         $self->{oid_want} = $oid_want;
679         $self->{out} = $out;
680         $self->{seen_oid} = {};
681         $self->{tot} = 0;
682         $self->{psgi_env} = $env;
683         $self->{todo} = [ { %$hints, oid_b => $oid_want } ];
684         $self->{patches} = []; # [ $di, $di, ... ]
685         $self->{found} = {}; # { abbr => [ ::Git, oid, type, size, $di ] }
686         $self->{tmp} = File::Temp->newdir("solver.$oid_want-XXXX", TMPDIR => 1);
687
688         dbg($self, "solving $oid_want ...");
689         if (my $async = $env->{'pi-httpd.async'}) {
690                 # PublicInbox::HTTPD::Async->new
691                 $async->(undef, undef, $self);
692         } else {
693                 event_step($self) while $self->{user_cb};
694         }
695 }
696
697 1;