]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Import.pm
search: improve reindexing behavior
[public-inbox.git] / lib / PublicInbox / Import.pm
1 # Copyright (C) 2016 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 #
4 # git fast-import-based ssoma-mda MDA replacement
5 # This is only ever run by public-inbox-mda and public-inbox-learn,
6 # not the WWW or NNTP code which only requires read-only access.
7 package PublicInbox::Import;
8 use strict;
9 use warnings;
10 use Fcntl qw(:flock :DEFAULT);
11 use PublicInbox::Spawn qw(spawn);
12 use PublicInbox::MID qw(mid_mime mid2path);
13
14 sub new {
15         my ($class, $git, $name, $email) = @_;
16         bless {
17                 git => $git,
18                 ident => "$name <$email>",
19                 mark => 1,
20                 ref => 'refs/heads/master',
21         }, $class
22 }
23
24 # idempotent start function
25 sub gfi_start {
26         my ($self) = @_;
27
28         return ($self->{in}, $self->{out}) if $self->{pid};
29
30         my ($in_r, $in_w, $out_r, $out_w);
31         pipe($in_r, $in_w) or die "pipe failed: $!";
32         pipe($out_r, $out_w) or die "pipe failed: $!";
33         my $git = $self->{git};
34         my $git_dir = $git->{git_dir};
35         my $lockpath = "$git_dir/ssoma.lock";
36         sysopen(my $lockfh, $lockpath, O_WRONLY|O_CREAT) or
37                 die "failed to open lock $lockpath: $!";
38
39         # wait for other processes to be done
40         flock($lockfh, LOCK_EX) or die "lock failed: $!\n";
41         local $/ = "\n";
42         chomp($self->{tip} = $git->qx(qw(rev-parse --revs-only), $self->{ref}));
43
44         my @cmd = ('git', "--git-dir=$git_dir", qw(fast-import
45                         --quiet --done --date-format=rfc2822));
46         my $rdr = { 0 => fileno($out_r), 1 => fileno($in_w) };
47         my $pid = spawn(\@cmd, undef, $rdr);
48         die "spawn fast-import failed: $!" unless defined $pid;
49         $out_w->autoflush(1);
50         $self->{in} = $in_r;
51         $self->{out} = $out_w;
52         $self->{lockfh} = $lockfh;
53         $self->{pid} = $pid;
54         $self->{nchg} = 0;
55         ($in_r, $out_w);
56 }
57
58 sub wfail () { die "write to fast-import failed: $!" }
59
60 sub now2822 () {
61         my @t = gmtime(time);
62         my $day = qw(Sun Mon Tue Wed Thu Fri Sat)[$t[6]];
63         my $mon = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)[$t[4]];
64
65         sprintf('%s, %2d %s %d %02d:%02d:%02d +0000',
66                 $day, $t[3], $mon, $t[5] + 1900, $t[2], $t[1], $t[0]);
67 }
68
69 sub norm_body ($) {
70         my ($mime) = @_;
71         my $b = $mime->body_raw;
72         $b =~ s/(\r?\n)+\z//s;
73         $b
74 }
75
76 # returns undef on non-existent
77 # ('MISMATCH', msg) on mismatch
78 # (:MARK, msg) on success
79 sub remove {
80         my ($self, $mime) = @_; # mime = Email::MIME
81
82         my $mid = mid_mime($mime);
83         my $path = mid2path($mid);
84
85         my ($r, $w) = $self->gfi_start;
86         my $tip = $self->{tip};
87         return ('MISSING', undef) if $tip eq '';
88
89         print $w "ls $tip $path\n" or wfail;
90         local $/ = "\n";
91         my $check = <$r>;
92         defined $check or die "EOF from fast-import / ls: $!";
93         return ('MISSING', undef) if $check =~ /\Amissing /;
94         $check =~ m!\A100644 blob ([a-f0-9]{40})\t!s or die "not blob: $check";
95         my $blob = $1;
96         print $w "cat-blob $blob\n" or wfail;
97         $check = <$r>;
98         defined $check or die "EOF from fast-import / cat-blob: $!";
99         $check =~ /\A[a-f0-9]{40} blob (\d+)\n\z/ or
100                                 die "unexpected cat-blob response: $check";
101         my $left = $1;
102         my $offset = 0;
103         my $buf = '';
104         my $n;
105         while ($left > 0) {
106                 $n = read($r, $buf, $left, $offset);
107                 defined($n) or die "read cat-blob failed: $!";
108                 $n == 0 and die 'fast-export (cat-blob) died';
109                 $left -= $n;
110                 $offset += $n;
111         }
112         $n = read($r, my $lf, 1);
113         defined($n) or die "read final byte of cat-blob failed: $!";
114         die "bad read on final byte: <$lf>" if $lf ne "\n";
115         my $cur = Email::MIME->new($buf);
116         my $cur_s = $cur->header('Subject');
117         $cur_s = '' unless defined $cur_s;
118         my $cur_m = $mime->header('Subject');
119         $cur_m = '' unless defined $cur_m;
120         if ($cur_s ne $cur_m || norm_body($cur) ne norm_body($mime)) {
121                 return ('MISMATCH', $cur);
122         }
123
124         my $ref = $self->{ref};
125         my $commit = $self->{mark}++;
126         my $parent = $tip =~ /\A:/ ? $tip : undef;
127         unless ($parent) {
128                 print $w "reset $ref\n" or wfail;
129         }
130         my $ident = $self->{ident};
131         my $now = now2822();
132         print $w "commit $ref\nmark :$commit\n",
133                 "author $ident $now\n",
134                 "committer $ident $now\n",
135                 "data 3\nrm\n\n",
136                 'from ', ($parent ? $parent : $tip), "\n" or wfail;
137         print $w "D $path\n\n" or wfail;
138         $self->{nchg}++;
139         (($self->{tip} = ":$commit"), $cur);
140 }
141
142 # returns undef on duplicate
143 sub add {
144         my ($self, $mime, $check_cb) = @_; # mime = Email::MIME
145
146         my $from = $mime->header('From');
147         my ($email) = ($from =~ /([^<\s]+\@[^>\s]+)/g);
148         my $name = $from;
149         $name =~ s/\s*\S+\@\S+\s*\z//;
150         # git gets confused with:
151         #  "'A U Thor <u@example.com>' via foo" <foo@example.com>
152         # ref:
153         # <CAD0k6qSUYANxbjjbE4jTW4EeVwOYgBD=bXkSu=akiYC_CB7Ffw@mail.gmail.com>
154         $name =~ tr/<>// and $name = $email;
155
156         my $date = $mime->header('Date');
157         my $subject = $mime->header('Subject');
158         $subject = '(no subject)' unless defined $subject;
159         my $mid = mid_mime($mime);
160         my $path = mid2path($mid);
161
162         my ($r, $w) = $self->gfi_start;
163         my $tip = $self->{tip};
164         if ($tip ne '') {
165                 print $w "ls $tip $path\n" or wfail;
166                 local $/ = "\n";
167                 my $check = <$r>;
168                 defined $check or die "EOF from fast-import: $!";
169                 return unless $check =~ /\Amissing /;
170         }
171
172         # kill potentially confusing/misleading headers
173         $mime->header_set($_) for qw(bytes lines content-length status);
174         if ($check_cb) {
175                 $mime = $check_cb->($mime) or return;
176         }
177
178         $mime = $mime->as_string;
179         my $blob = $self->{mark}++;
180         print $w "blob\nmark :$blob\ndata ", length($mime), "\n" or wfail;
181         print $w $mime, "\n" or wfail;
182         my $ref = $self->{ref};
183         my $commit = $self->{mark}++;
184         my $parent = $tip =~ /\A:/ ? $tip : undef;
185
186         unless ($parent) {
187                 print $w "reset $ref\n" or wfail;
188         }
189
190         # quiet down wide character warnings:
191         binmode $w, ':utf8' or die "binmode :utf8 failed: $!";
192         print $w "commit $ref\nmark :$commit\n",
193                 "author $name <$email> $date\n",
194                 "committer $self->{ident} ", now2822(), "\n",
195                 "data ", (bytes::length($subject) + 1), "\n",
196                 $subject, "\n\n" or wfail;
197         binmode $w, ':raw' or die "binmode :raw failed: $!";
198
199         if ($tip ne '') {
200                 print $w 'from ', ($parent ? $parent : $tip), "\n" or wfail;
201         }
202         print $w "M 100644 :$blob $path\n\n" or wfail;
203         $self->{nchg}++;
204         $self->{tip} = ":$commit";
205 }
206
207 sub done {
208         my ($self) = @_;
209         my $w = delete $self->{out} or return;
210         my $r = delete $self->{in} or die 'BUG: missing {in} when done';
211         print $w "done\n" or wfail;
212         my $pid = delete $self->{pid} or die 'BUG: missing {pid} when done';
213         waitpid($pid, 0) == $pid or die 'fast-import did not finish';
214         $? == 0 or die "fast-import failed: $?";
215         my $nchg = delete $self->{nchg};
216
217         # for compatibility with existing ssoma installations
218         # we can probably remove this entirely by 2020
219         my $git_dir = $self->{git}->{git_dir};
220         # XXX: change the following scope to: if (-e $index) # in 2018 or so..
221         my @cmd = ('git', "--git-dir=$git_dir");
222         if ($nchg && !$ENV{FAST}) {
223                 my $index = "$git_dir/ssoma.index";
224                 my $env = { GIT_INDEX_FILE => $index };
225                 my @rt = (@cmd, qw(read-tree -m -v -i), $self->{ref});
226                 $pid = spawn(\@rt, $env, undef);
227                 defined $pid or die "spawn read-tree failed: $!";
228                 waitpid($pid, 0) == $pid or die 'read-tree did not finish';
229                 $? == 0 or die "failed to update $git_dir/ssoma.index: $?\n";
230         }
231         if ($nchg) {
232                 $pid = spawn([@cmd, 'update-server-info'], undef, undef);
233                 defined $pid or die "spawn update-server-info failed: $!\n";
234                 waitpid($pid, 0) == $pid or
235                         die 'update-server-info did not finish';
236                 $? == 0 or die "failed to update-server-info: $?\n";
237
238                 eval {
239                         require PublicInbox::SearchIdx;
240                         my $s = PublicInbox::SearchIdx->new($git_dir, 2);
241                         $s->index_sync({ ref => $self->{ref} });
242                 };
243         }
244
245         my $lockfh = delete $self->{lockfh} or die "BUG: not locked: $!";
246         flock($lockfh, LOCK_UN) or die "unlock failed: $!";
247         close $lockfh or die "close lock failed: $!";
248 }
249
250 1;
251 __END__
252 =pod
253
254 =head1 NAME
255
256 PublicInbox::Import - message importer for public-inbox
257
258 =head1 VERSION
259
260 version 1.0
261
262 =head1 SYNOPSYS
263
264         use Email::MIME;
265         use PublicInbox::Git;
266         use PublicInbox::Import;
267
268         chomp(my $git_dir = `git rev-parse --git-dir`);
269         $git_dir or die "GIT_DIR= must be specified\n";
270         my $git = PublicInbox::Git->new($git_dir);
271         my @committer = ('inbox', 'inbox@example.org');
272         my $im = PublicInbox::Import->new($git, @committer);
273
274         # to add a message:
275         my $message = "From: <u\@example.org>\n".
276                 "Subject: test message \n" .
277                 "Date: Thu, 01 Jan 1970 00:00:00 +0000\n" .
278                 "Message-ID: <m\@example.org>\n".
279                 "\ntest message";
280         my $parsed = Email::MIME->new($message);
281         my $ret = $im->add($parsed);
282         if (!defined $ret) {
283                 warn "duplicate: ",
284                         $parsed->header_obj->header_raw('Message-ID'), "\n";
285         } else {
286                 print "imported at mark $ret\n";
287         }
288         $im->done;
289
290         # to remove a message
291         my $junk = Email::MIME->new($message);
292         my ($mark, $orig) = $im->remove($junk);
293         if ($mark eq 'MISSING') {
294                 print "not found\n";
295         } elsif ($mark eq 'MISMATCH') {
296                 print "Message exists but does not match\n\n",
297                         $orig->as_string, "\n",;
298         } else {
299                 print "removed at mark $mark\n\n",
300                         $orig->as_string, "\n";
301         }
302         $im->done;
303
304 =head1 DESCRIPTION
305
306 An importer and remover for public-inboxes which takes L<Email::MIME>
307 messages as input and stores them in a ssoma repository as
308 documented in L<https://ssoma.public-inbox.org/ssoma_repository.txt>,
309 except it does not allow duplicate Message-IDs.
310
311 It requires L<git(1)> and L<git-fast-import(1)> to be installed.
312
313 =head1 METHODS
314
315 =cut
316
317 =head2 new
318
319         my $im = PublicInbox::Import->new($git, @committer);
320
321 Initialize a new PublicInbox::Import object.
322
323 =head2 add
324
325         my $parsed = Email::MIME->new($message);
326         $im->add($parsed);
327
328 Adds a message to to the git repository.  This will acquire
329 C<$GIT_DIR/ssoma.lock> and start L<git-fast-import(1)> if necessary.
330
331 Messages added will not be visible to other processes until L</done>
332 is called, but L</remove> may be called on them.
333
334 =head2 remove
335
336         my $junk = Email::MIME->new($message);
337         my ($code, $orig) = $im->remove($junk);
338
339 Removes a message from the repository.  On success, it returns
340 a ':'-prefixed numeric code representing the git-fast-import
341 mark and the original messages as an Email::MIME object.
342 If the message could not be found, the code is "MISSING"
343 and the original message is undef.  If there is a mismatch where
344 the "Message-ID" is matched but the subject and body do not match,
345 the returned code is "MISMATCH" and the conflicting message
346 is returned as orig.
347
348 =head2 done
349
350 Finalizes the L<git-fast-import(1)> and unlocks the repository.
351 Calling this is required to finalize changes to a repository.
352
353 =head1 SEE ALSO
354
355 L<Email::MIME>
356
357 =head1 CONTACT
358
359 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
360
361 The mail archives are hosted at L<https://public-inbox.org/meta/>
362
363 =head1 COPYRIGHT
364
365 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
366
367 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>
368
369 =cut