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