File Coverage

File:blib/lib/Database/BI/Extract.pm
Coverage:100.0%

linestmtbrancondsubtimecode
1package Database::BI::Extract;
2
3
18
18
18
140486
18
199
use strict;
4
18
18
18
24
16
625
use warnings;
5
6our $VERSION = '0.025.0';
7
8
18
18
18
25
20
460
use Carp                qw(croak carp);
9
18
18
18
27
17
221
use Digest::MD5         qw(md5_hex);
10
18
18
18
30
17
243
use Encode              qw(encode_utf8);
11
18
18
18
27
17
283
use File::Path          qw(make_path remove_tree);
12
18
18
18
115
4912
195
use Mojo::File;
13
18
18
18
142
999
4997
use Readonly;
14
15# ---------------------------------------------------------------------------
16# An extract is a SQLite materialisation of one dataset, stored at:
17#   <model_dir>/extracts/<fingerprint>.db
18# or, when a cache directory is set (see new), at:
19#   <cache_dir>/database-bi-extracts/<fingerprint>.db
20#
21# The fingerprint is md5_hex(spec . "\0" . mtime . "\0" . size).
22# It is a pure cache: deleting the extracts/ directory at any time leaves
23# the application fully functional.  No file under data_dir is created.
24#
25# The web application reads an accelerated dataset's extract through get(), and
26# script/bi-extract builds one through put() (Dashboard::accelerate).  A caller
27# decides whether to build a new extract; Extract only stores and retrieves
28# bytes.
29# ---------------------------------------------------------------------------
30
31# The folder extracts are kept in under a cache directory that was set, rather
32# than in it: evict() removes every .db file it finds, and a CACHEDIR such as
33# ~/.cache holds other programs' files.
34Readonly my $CACHE_SUBDIR => 'database-bi-extracts';
35
36# new( model_dir => $dir, cache_dir => $dir, config => \%conf, home => $dir, dir => $dir ) -> $self
37#
38# Database::BI::CacheDir chooses the cache directory (Object::Configure,
39# CACHEDIR, CACHE_DIR, cache_dir in database_bi.conf); the extracts go in its
40# database-bi-extracts folder.  With none of those set they stay in
41# <model_dir>/extracts, where they always were.
42sub new {
43
75
33389
        my ($class, %args) = @_;
44
45        # dir names the folder outright, choosing nothing.
46        return bless { model_dir => $args{model_dir}, dir => $args{dir} }, $class
47
75
220
                if defined($args{dir}) && length($args{dir});
48
49
69
1139
        require Database::BI::CacheDir;
50        my $cache_dir = Database::BI::CacheDir::resolve(
51                class  => $class,
52                params => \%args,
53
69
227
                (exists($args{config}) ? (config => $args{config}, home => $args{home}) : ()),
54        );
55
56
69
136
        my $dir;
57
69
98
        if (defined $cache_dir) {
58
7
9
                $dir = Mojo::File->new($cache_dir)->child($CACHE_SUBDIR)->to_string;
59        } else {
60
62
257
                croak 'model_dir is required' unless defined $args{model_dir} && length $args{model_dir};
61
54
148
                $dir = Mojo::File->new($args{model_dir})->child('extracts')->to_string;
62        }
63
64
61
1011
        return bless { model_dir => $args{model_dir}, dir => $dir }, $class;
65}
66
67# dir( $self ) -> $path_string
68#
69# The folder the extracts are kept in.  It need not exist yet.
70sub dir {
71
44
34
        my $self = shift;
72
44
98
        return $self->{dir};
73}
74
75# _fingerprint( $spec, $mtime, $size ) -> $hex_string
76sub _fingerprint {
77
300
1734
        my ($spec, $mtime, $size) = @_;
78
300
202
        $mtime //= 0;
79
300
180
        $size  //= 0;
80
300
535
        return md5_hex(encode_utf8(join("\0", $spec, $mtime, $size)));
81}
82
83# _extract_dir( $self ) -> $path_string
84sub _extract_dir {
85
554
1043
        my $self = shift;
86
554
456
        return $self->{dir};
87}
88
89# path( $spec, $mtime, $size ) -> $path_string
90#
91# Returns the filesystem path an extract for this fingerprint would occupy.
92# Does not test for existence.
93sub path {
94
288
850
        my ($self, $spec, $mtime, $size) = @_;
95
288
196
        my $fp = _fingerprint($spec, $mtime, $size);
96
288
193
        return Mojo::File->new($self->_extract_dir)->child("$fp.db")->to_string;
97}
98
99# get( $spec, $mtime, $size ) -> $path_string | undef
100#
101# Returns the path to the cached SQLite file when the fingerprint matches and
102# the file exists on disk; returns undef on a cache miss.
103sub get {
104
45
2893
        my ($self, $spec, $mtime, $size) = @_;
105
45
92
        my $p = $self->path($spec, $mtime, $size);
106
45
615
        return -f $p ? $p : undef;
107}
108
109# put( $spec, $mtime, $size, $sqlite_bytes ) -> $path_string
110#
111# Writes $sqlite_bytes to the cache.  Creates the extracts/ directory if it
112# does not exist yet.  Returns the path written to.  Croaks on I/O failure.
113sub put {
114
242
12273
        my ($self, $spec, $mtime, $size, $bytes) = @_;
115
242
293
        croak 'sqlite_bytes are required' unless defined $bytes && length $bytes;
116
117        # A caller's $@ and $! are its own: the writes below use both on the way.
118
238
187
        local ($@, $!);
119
120
238
143
        my $dir = $self->_extract_dir;
121
238
307
        unless (-d $dir) {
122
22
22
18
1653
                eval { make_path($dir) };
123
22
533
                croak "Cannot create extract dir '$dir': $@" if $@;
124        }
125
126
235
149
        my $p = $self->path($spec, $mtime, $size);
127        # Premise 1: get() trusts any plain file at $p.  Premise 2: a write that
128        # fails half way (disk full, a killed process) leaves a short file where it
129        # wrote.  Conclusion: write beside it and rename, so $p is the whole extract
130        # or what it was before, and a failure removes its own temporary file.
131
235
1846
        my $temp = "$p.$$.tmp";
132
235
235
32
31
96
161
2534
35
        my $ok = eval { Mojo::File->new($temp)->spurt($bytes); rename $temp, $p or die "$!\n"; 1 };
133
235
10808
        my $why = $@;
134
235
150
        unless ($ok) {
135
204
200
                unlink $temp;
136
204
597
                croak "Cannot write extract '$p': $why";
137        }
138
139
31
55
        return $p;
140}
141
142# evict( $spec ) -> $count_removed
143#
144# Removes all cached extract files that begin with a fingerprint that could
145# belong to $spec.  Because the fingerprint includes mtime+size, a changed
146# file naturally produces a miss without eviction; evict() is provided for
147# explicit cache clearing.  Returns the number of files removed.
148# NOTE: because fingerprints are global md5 hashes we cannot identify which
149# belong to a spec without re-computing; this method removes ALL extracts.
150# Call it only when clearing the whole extract store is desired.
151sub evict {
152
19
1979
        my ($self, $spec) = @_;
153
19
32
        my $dir = $self->_extract_dir;
154
19
65
        return 0 unless -d $dir;
155
156
14
9
        my $count = 0;
157        # Listed rather than globbed: glob() splits its pattern on spaces and reads
158        # brackets as a class, so the name of the directory could defeat it.
159
14
25
14
16
768
24
        for my $f (grep { /\.db\z/ } @{ Mojo::File->new($dir)->list->map('to_string') }) {
160
18
271
                if (unlink $f) {
161
17
14
                        $count++;
162                }
163        }
164        # A temporary file left by a process that was killed mid-write.
165
14
8
14
30
167
20
        unlink grep { /\.tmp\z/ } @{ Mojo::File->new($dir)->list->map('to_string') };
166
14
126
        return $count;
167}
168
1691;
170