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