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