]> Sergey Matveev's repositories - public-inbox.git/blobdiff - lib/PublicInbox/IMAPTracker.pm
rewrite Linux nodatacow use in pure Perl w/o system
[public-inbox.git] / lib / PublicInbox / IMAPTracker.pm
index 0bbabe07faef6c76f1bc4bcd94c75eabbfd8d1ab..4efa8a7e7e38b774ee09709b1de027d7c4cd8b79 100644 (file)
@@ -1,7 +1,8 @@
-# Copyright (C) 2018-2020 all contributors <meta@public-inbox.org>
+# Copyright (C) all contributors <meta@public-inbox.org>
 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
 package PublicInbox::IMAPTracker;
 use strict;
+use parent qw(PublicInbox::Lock);
 use DBI;
 use DBD::SQLite;
 use PublicInbox::Config;
@@ -28,7 +29,12 @@ sub dbh_new ($) {
                sqlite_use_immediate_transaction => 1,
        });
        $dbh->{sqlite_unicode} = 1;
-       $dbh->do('PRAGMA journal_mode = TRUNCATE');
+
+       # TRUNCATE reduces I/O compared to the default (DELETE).
+       # Allow and preserve user-overridden WAL, but don't force it.
+       my $jm = $dbh->selectrow_array('PRAGMA journal_mode');
+       $dbh->do('PRAGMA journal_mode = TRUNCATE') if $jm ne 'wal';
+
        create_tables($dbh);
        $dbh;
 }
@@ -43,19 +49,23 @@ SELECT uid_validity, uid FROM imap_last WHERE url = ?
 }
 
 sub update_last ($$$) {
-       my ($self, $validity, $last) = @_;
+       my ($self, $validity, $last_uid) = @_;
+       return unless defined $last_uid;
        my $sth = $self->{dbh}->prepare_cached(<<'');
 INSERT OR REPLACE INTO imap_last (url, uid_validity, uid)
 VALUES (?, ?, ?)
 
-       $sth->execute($self->{url}, $validity, $last);
+       $self->lock_acquire;
+       my $rv = $sth->execute($self->{url}, $validity, $last_uid);
+       $self->lock_release;
+       $rv;
 }
 
 sub new {
        my ($class, $url) = @_;
 
        # original name for compatibility with old setups:
-       my $dbname = PublicInbox::Config->config_dir() . "/imap.sqlite3";
+       my $dbname = PublicInbox::Config->config_dir() . '/imap.sqlite3';
 
        # use the new XDG-compliant name for new setups:
        if (!-f $dbname) {
@@ -65,11 +75,17 @@ sub new {
        }
        if (!-f $dbname) {
                require File::Path;
-               require File::Basename;
-               File::Path::mkpath(File::Basename::dirname($dbname));
+               require PublicInbox::Syscall;
+               my ($dir) = ($dbname =~ m!(.*?/)[^/]+\z!);
+               File::Path::mkpath($dir);
+               PublicInbox::Syscall::nodatacow_dir($dir);
+               open my $fh, '+>>', $dbname or die "failed to open $dbname: $!";
        }
-
-       bless { url => $url, dbh => dbh_new($dbname) }, $class;
+       my $self = bless { lock_path => "$dbname.lock", url => $url }, $class;
+       $self->lock_acquire;
+       $self->{dbh} = dbh_new($dbname);
+       $self->lock_release;
+       $self;
 }
 
 1;