blib/lib/PGXN/API/Sync.pm

filter: Statementstmt 53.1% 75 / 141 Branchbran 20.6% 12 / 58 Conditioncond 22.2% 2 / 9 MC/DCmcdc 16.6% 1 / 6 Subroutinesub 75.0% 21 / 28 Podpod 100% 8 / 8 totaltotal 47.6% 119 / 250 CC 34 SCAR 38.4
CC
34
Cov
43%
update_index
182.0
unzip
21.2
regex_for_uri_template
20.0
CRAP 46.4
« _build/lib/PGXN/Build.pm ↑ Summary blib/lib/PGXN/API/Indexer.pm »
1 package PGXN::API::Sync;
2  
3 2 ▶use v5.14;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use PGXN::API;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use PGXN::API::Indexer;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use Digest::SHA1;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 2 ▶use List::Util qw(first);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 2 ▶use File::Spec::Functions qw(catfile path rel2abs tmpdir catdir);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 2 ▶use File::Path qw(make_path);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 2 ▶use Cwd;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 2 ▶use Archive::Zip qw(:ERROR_CODES);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 2 ▶use constant WIN32 => $^O eq 'MSWin32';
Subroutine BEGIN: called CC=1 SCAR=0.0
15 2 ▶use Moose::Util::TypeConstraints;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 2 ▶use namespace::autoclean;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 2 our $VERSION = v0.21.1;
18  
19 subtype Executable => as 'Str', where {
20 2 ▶ my $exe = $_;
Subroutine __ANON__: called CC=1 SCAR=0.0
21 2 ▶ first { -f $_ && -x _ } $exe, map { catfile $_, $exe } path;
Subroutine __ANON__: called CC=2 SCAR=7.1
Branch: 1 branch
BranchTrueFalseTotal
-f $_ and -x _ 2 0 2
22 2 };
23  
24 2 has rsync_path => (is => 'rw', isa => 'Executable', default => 'rsync', required => 1);
25 2 has source => (is => 'rw', isa => 'Str', required => 1);
26 2 has verbose => (is => 'rw', isa => 'Int', default => 0);
27 has log_file => (is => 'rw', isa => 'Str', required => 1, default => sub {
28 2 ▶ catfile tmpdir, "pgxn-api-sync-$$.txt"
Subroutine __ANON__: called CC=1 SCAR=0.0
29 2 });
30 has mirror_uri_templates => (is => 'ro', isa => 'HashRef', lazy => 1, default => sub {
31 0 ▶ my $self = shift;
Subroutine __ANON__: not called CC=1 SCAR=6.9
32 0 my $api = PGXN::API->instance;
33 0 my $tmpl = $api->read_json_from(catfile $api->mirror_root, 'index.json');
34 0 return { map { $_ => URI::Template->new($tmpl->{$_}) } keys %{ $tmpl } };
35 2 });
36  
37 sub run {
38 0 ▶ my $self = shift;
Subroutine run: not called CC=1 SCAR=6.9
Pod documented
39 0 $self->run_rsync;
40 0 $self->update_index;
41 }
42  
43 sub DESTROY {
44 1 ▶ my $self = shift;
Subroutine DESTROY: called CC=1 SCAR=0.0
45 1 unlink $self->log_file;
46 1 $self->SUPER::DESTROY;
47 }
48  
49 sub run_rsync {
50 1 ▶ my $self = shift;
Subroutine run_rsync: called CC=3 SCAR=11.7
Pod documented
51  
52 # Sync the mirror.
53 1 ▶ say "Updating the mirror from ", $self->source if $self->verbose;
Branch: 1 branch
BranchTrueFalseTotal
if $self->verbose 0 1 1
54 1 ▶ system (
Branch: 1 branch
BranchTrueFalseTotal
system($self->rsync_path, ("--archive", "--compress", "--delete", "--quiet"), "--log-file-format", "%i %n", "--log-file", $self->log_file, $self->source, "PGXN::API"->instance->mirror_root) == 0 or die 1 0 1
55 $self->rsync_path,
56 qw(--archive --compress --delete --quiet),
57 '--log-file-format' => '%i %n',
58 '--log-file' => $self->log_file,
59 $self->source,
60 PGXN::API->instance->mirror_root,
61 ) == 0 or die;
62 }
63  
64 sub update_index {
65 0 ▶ my $self = shift;
Subroutine update_index: not called CC=13 SCAR=52.0
Pod documented
66 0 my $indexer = PGXN::API::Indexer->new(verbose => $self->verbose);
67  
68 0 my $meta_re = $self->regex_for_uri_template('meta');
69 0 my $mirr_re = $self->regex_for_uri_template('mirrors');
70 0 my $spec_re = $self->regex_for_uri_template('spec');
71 0 my $stat_re = $self->regex_for_uri_template('stats');
72 0 my $user_re = $self->regex_for_uri_template('user');
73 0 my $log = $self->log_file;
74  
75 0 ▶ say 'Parsing the rsync log file' if $self->verbose > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->verbose > 1 0 0 0
76 0 ▶ open my $fh, '<:encoding(UTF-8)', $log or die "Canot open $log: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:encoding(UTF-8)", $log or die "Canot open ${log}: $!\n" 0 0 0
77 0 ▶ while (my $line = <$fh>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 0 0 0
78 0 ▶ if ($line =~ $meta_re) {
Branch: 5 branches
BranchTrueFalseTotal
if ($line =~ /$meta_re/u) { } 0 0 0
elsif ($line =~ /$stat_re/u or $line =~ /$mirr_re/u) { } 0 0 0
elsif ($line =~ /$spec_re/u) { } 0 0 0
elsif ($line =~ /\s>f(?:[+]+|(?:c|.s|..t)[^ ]+)\sindex[.]json$/u) { } 0 0 0
elsif ($line =~ /$user_re/u) { } 0 0 0
79 0 ▶ if (my $params = $self->validate_distribution($1)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $params = $self->validate_distribution($1)) 0 0 0
80 0 $indexer->add_distribution($params);
81 }
82 }
83 ▶ elsif ($line =~ $stat_re || $line =~ $mirr_re) {
Condition0%0/3
$line =~ /$stat_re/u or $line =~ /$mirr_re/u
l!l&&r!l&&!r
000
MC/DC0%0/2
$line =~ /$stat_re/u or $line =~ /$mirr_re/u
$line =~ /$stat_re/u $line =~ /$mirr_re/u
Truth table0%0/3
A or B
A= $line =~ /$stat_re/uB= $line =~ /$mirr_re/u
ABresult
1X1
011
000
84 0 $indexer->copy_from_mirror($1);
85 }
86 elsif ($line =~ $spec_re) {
87 0 my $path = $1;
88 0 $indexer->copy_from_mirror($path);
89 0 $indexer->parse_from_mirror($path, 'Multimarkdown');
90 }
91 elsif ($line =~ /\s>f(?:[+]+|(?:c|.s|..t)[^ ]+)\sindex[.]json$/) {
92 # Always update the index JSON if it's mentioned.
93 0 $indexer->update_root_json;
94 }
95 elsif ($line =~ $user_re) {
96 0 $indexer->merge_user($2);
97 }
98 }
99 0 ▶ close $fh or die "Cannot close $log: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or die "Cannot close ${log}: $!\n" 0 0 0
100 0 $indexer->finalize;
101 0 ▶ say 'Sync complete' if $self->verbose;
Branch: 1 branch
BranchTrueFalseTotal
if $self->verbose 0 0 0
102 0 return $self;
103 }
104  
105 sub regex_for_uri_template {
106 0 ▶ my ($self, $name) = @_;
Subroutine regex_for_uri_template: not called CC=4 SCAR=30.0
Pod documented
107  
108 # Get the URI for the template.
109 my $uri = $self->mirror_uri_templates->{$name}->process(
110 0 map { $_ => "{$_}" } qw(dist version user extension tag stats format)
111 );
112  
113 0 my %regex_for = (
114 '{dist}' => qr{[^/]+?},
115 # https://regex101.com/r/vkijKf/
116 '{version}' => qr{(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?},
117 '{user}' => qr{([a-z]([-a-z0-9]{0,61}[a-z0-9])?)}i,
118 '{extension}' => qr{[^/]+?},
119 '{tag}' => qr{[^/]+?},
120 '{stats}' => qr{(?:dist|tag|user|extension|summary)},
121 '{format}' => qr{(?:txt|html|atom|xml)},
122 );
123  
124 # Assemble the regex corresponding to the template.
125 my $regex = join '', map {
126 0 ▶ $regex_for{$_} || quotemeta $_
Branch: 1 branch
BranchTrueFalseTotal
$regex_for{$_} or quotemeta $_ 0 0 0
127 0 ▶ } grep { defined && length } map {
Branch: 1 branch
BranchTrueFalseTotal
defined $_ and length $_ 0 0 0
128 0 split /(\{.+?\})/
129 0 ▶ } catfile grep { defined && length } $uri->path_segments;
Branch: 1 branch
BranchTrueFalseTotal
defined $_ and length $_ 0 0 0
130  
131 # Return the regex to match new or updated in rsync output lines.
132 0 return qr{\s>f(?:[+]+|(?:c|.s|..t)[^ ]+)\s($regex)$};
133  
134 # The rsync %i output format:
135 # YXcstpogz # Snow Leopard
136 # YXcstpoguax # Debian
137 # c: checkum has changed, file will be updated
138 # s: file size has changed, file will be updated
139 # t: modtime has changed, file will be updated
140 # +++++++: New item
141 }
142  
143  
144 sub validate_distribution {
145 0 ▶ my ($self, $fn) = shift->_rel_to_mirror(@_);
Subroutine validate_distribution: not called CC=4 SCAR=30.0
Pod documented
146 0 my $meta = PGXN::API->instance->read_json_from($fn);
147 0 my $zip_path = $self->download_for($meta);
148  
149 # Validate it against the SHA1 checksum.
150 0 ▶ say ' Checksumming ', $zip_path if $self->verbose;
Branch: 1 branch
BranchTrueFalseTotal
if $self->verbose 0 0 0
151 0 ▶ if ($self->digest_for($zip_path) ne $meta->{sha1}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->digest_for($zip_path) ne $meta->{"sha1"}) 0 0 0
152 0 warn "Checksum verification failed for $fn\n";
153 0 return;
154 }
155  
156 # Unpack the distribution.
157 0 ▶ my $zip = $self->unzip($zip_path, $meta) or return;
Branch: 1 branch
BranchTrueFalseTotal
my $zip = $self->unzip($zip_path, $meta) or return 0 0 0
158 0 return { meta => $meta, zip => $zip };
159 }
160  
161 sub download_for {
162 0 ▶ my ($self, $meta) = @_;
Subroutine download_for: not called CC=1 SCAR=6.9
Pod documented
163 my $zip_uri = $self->mirror_uri_templates->{download}->process(
164 dist => lc $meta->{name},
165 version => lc $meta->{version},
166 0 );
167  
168 0 my (undef, @segments) = $zip_uri->path_segments;
169 0 return catfile @segments;
170 }
171  
172 sub digest_for {
173 0 ▶ my ($self, $fn) = shift->_rel_to_mirror(@_);
Subroutine digest_for: not called CC=2 SCAR=17.9
Pod documented
174 0 ▶ open my $fh, '<:raw', $fn or die "Cannot open $fn: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $fn or die "Cannot open ${fn}: $!\n" 0 0 0
175 0 my $sha1 = Digest::SHA1->new;
176 0 $sha1->addfile($fh);
177 0 return $sha1->hexdigest;
178 }
179  
180 sub unzip {
181 2 ▶ say ' Extracting ', $_[1] if $_[0]->verbose;
Subroutine unzip: called CC=12 SCAR=30.5
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
if $_[0]->verbose 0 2 2
182 2 my ($self, $zip_path, $meta) = shift->_rel_to_mirror(@_);
183  
184 2 my $zip = Archive::Zip->new;
185 2 ▶ if ($zip->read(rel2abs $zip_path) != AZ_OK) {
Branch: 1 branch
BranchTrueFalseTotal
if ($zip->read(rel2abs($zip_path)) != 0) 0 2 2
186 0 warn "Error reading $zip_path\n";
187 0 return;
188 }
189  
190 my $dist_dir = catdir(
191 PGXN::API->instance->source_dir,
192 lc $meta->{name}
193 2 );
194 2 ▶ make_path $dist_dir unless -e $dist_dir && -d _;
Branch: 1 branch
BranchTrueFalseTotal
unless -e $dist_dir and -d _ 1 1 2
Condition66%2/3
-e $dist_dir and -d _
!ll&&!rl&&r
101
MC/DC50%1/2
-e $dist_dir and -d _
-e $dist_dir -d _
Truth table66%2/3
A and B
A= -e $dist_dirB= -d _
ABresult
0X0
100
111
195  
196 2 foreach my $member ($zip->members) {
197 29 my $fn = catfile $dist_dir, split m{/} => $member->fileName;
198 29 ▶ say " $fn\n" if $self->verbose > 2;
Branch: 1 branch
BranchTrueFalseTotal
if $self->verbose > 2 0 29 29
199  
200 29 ▶ if ($member->isSymbolicLink) {
Branch: 1 branch
BranchTrueFalseTotal
if ($member->isSymbolicLink) { } 0 29 29
201 # Delete exsting so Archive::Zip won't fail to create it.
202 0 ▶ warn "Cannot unlink $fn: $!\n" if -e $fn && !unlink $fn;
Branch: 1 branch
BranchTrueFalseTotal
if -e $fn and not unlink($fn) 0 0 0
Condition0%0/3
-e $fn and not unlink($fn)
!ll&&!rl&&r
000
MC/DC0%0/2
-e $fn and not unlink($fn)
-e $fn not unlink($fn)
Truth table0%0/3
A and not(B)
A= -e $fnB= not unlink($fn)
ABresult
0X0
100
111
203 } else {
204 # Make sure the member is readable by everyone.
205 29 ▶ $member->unixFileAttributes( $member->isDirectory ? 0755 : 0644 );
Branch: 1 branch
BranchTrueFalseTotal
$member->isDirectory ? : 12 17 29
206 }
207  
208 29 ▶ if ($member->extractToFileNamed($fn) != AZ_OK) {
Branch: 1 branch
BranchTrueFalseTotal
if ($member->extractToFileNamed($fn) != 0) 0 29 29
209 0 warn "Error extracting $fn from $zip_path\n";
210 0 next;
211 }
212 }
213  
214 2 return $zip;
215 }
216  
217 sub _rel_to_mirror {
218 2 ▶ return shift, catfile(+PGXN::API->instance->mirror_root, shift), @_;
Subroutine _rel_to_mirror: called CC=1 SCAR=0.0
219 }
220  
221 2 __PACKAGE__->meta->make_immutable(inline_destructor => 0);
222  
223 2 1;
224  
225 __END__
226  
227 =head1 Name
228  
229 PGXN::API::Sync - Sync from a PGXN mirror and update the index
230  
231 =head1 Synopsis
232  
233 use PGXN::API::Sync;
234 PGXN::API::Sync->new(
235 source => $source,
236 rsync_path => $rsync_path,
237 verbose => $verbose,
238 )->run;
239  
240 =head1 Description
241  
242 This module provides the implementation for L<pgxn_api_sync>, the command-line
243 utility for syncing to a PGXN mirror and creating the API. It syncs to the
244 specified PGXN rsync source URL, which should be a PGXN mirror server, and
245 then verifies and unpacks newly-uploaded distributions and hands them off to
246 L<PGXN::API::Indexer> to index.
247  
248 =head1 Class Interface
249  
250 =head2 Constructor
251  
252 =head3 C<new>
253  
254 my $sync = PGXN::API::Sync->new(%params);
255  
256 Creates and returns a new PGXN::API::Sync object. The supported parameters
257 are:
258  
259 =over
260  
261 =item C<rsync_path>
262  
263 Path to the rsync executable. Defaults to C<rsync>, which should work find if
264 there is an executable with that name in your path.
265  
266 =item C<source>
267  
268 An C<rsync> URL specifying the source from which to sync. The source should be
269 an C<rsync> server serving up a PGXN mirror source as created or mirrored from
270 a PGXN Manager server.
271  
272 =item C<verbose>
273  
274 An incremental integer specifying the level of verbosity to use during a sync.
275 By default, PGXN::API::Sync runs in quiet mode, where only errors are emitted
276 to C<STDERR>.
277  
278 =back
279  
280 =head1 Instance Interface
281  
282 =head2 Instance Methods
283  
284 =head3 C<run>
285  
286 $sync->run;
287  
288 Runs the sync, C<rsync>ing from the source mirror server, verifying and
289 unpacking distributions, and handing them off to the indexer for indexing.
290 This is the main method called by L<pgxn_api_sync> to just do the job.
291  
292 =head3 C<run_rsync>
293  
294 $sync->run_rsync;
295  
296 C<rsync>s from the source mirror server. Called by C<run>.
297  
298 =head3 C<update_index>
299  
300 $sync->update_index;
301  
302 Parses the log generated by the execution of C<run_rsync()> for new
303 distribution F<META.json> files and passes any found off to
304 C<validate_distribution()> and L<PGXN::API::Indexer/add_distribution> for
305 validation, unpacking, and indexing. Called internally by C<run()>.
306  
307 =head3 C<regex_for_uri_template>
308  
309 my $regex = $sync->regex_for_uri_template('download');
310  
311 Returns a regular expression that will match the path to a file in the rsync
312 logs. The regular expression is created from a named URI template as loaded
313 from the F</index.json> file synced from the mirror server. Used internally to
314 parse the paths to distribution files from the rsync logs so that they can be
315 validated, unpacked, and indexed.
316  
317 =head3 C<download_for>
318  
319 my $download = $sync->download_for($meta);
320  
321 Given the metadata loaded from a mirror server F<META.json> file, returns the
322 path to the download file for the distribution. Used internally by
323 C<validate_distribution()> to find the file to validate.
324  
325 =head3 C<validate_distribution>
326  
327 my $params = $sync->validate_distribution($path_to_dist_meta);
328  
329 Given the path to a distribution F<META.json> file, this method validates the
330 digest for the download file and unpacks it. Returns parameters suitable for
331 passing to L<PGXN::Indexer/add_distribution> for indexing.
332  
333 =head3 C<digest_for>
334  
335 my $digest = $sync->digest_for($zipfile);
336  
337 Returns the SHA-1 hex digest for a distribution file (or any file, really).
338 Called by C<validate_distribution()>.
339  
340 =head3 C<unzip>
341  
342 $sync->unzip($download, $meta);)
343  
344 Given a download file for a distribution, and the metadata loaded from the
345 C<META.json> describing the download, this method unpacks the download under
346 the F<src/> directory under the document root. Each file will be readable by
347 all users. This provides the browsable file interface for the API server to
348 serve. Called internally by C<validate_distribution()>.
349  
350 =head2 Instance Accessors
351  
352 =head3 C<rsync_path>
353  
354 my $rsync_path = $sync->rsync_path;
355 $sync->rsync_path($rsync_path);
356  
357 Get or set the path to the C<rsync> executable.
358  
359 =head3 C<source>
360  
361 my $source = $sync->source;
362 $sync->source($source);
363  
364 Get or set the source C<rsync> URL from which to sync a PGXN mirror.
365  
366 =head3 C<verbose>
367  
368 my $verbose = $sync->verbose;
369 $sync->verbose($verbose);
370  
371 Get or set an incremental verbosity. The higher the integer specified, the
372 more verbose the sync.
373  
374 =head3 C<log_file>
375  
376 my $log_file = $sync->log_file;
377 $sync->log_file($log_file);
378  
379 Get or set the path to use for the C<rsync> log file. This file will then be
380 parsed by C<update_index> for new distributions to index.
381  
382 =head3 C<mirror_uri_templates>
383  
384 my $templates = $pgxn->mirror_uri_templates;
385  
386 Returns a hash reference of the URI templates loaded from the F<index.json>
387 file in the mirror root. The keys are the names of the templates, and the
388 values are L<URI::Template> objects.
389  
390 =cut
391  
392 =head1 Author
393  
394 David E. Wheeler <david.wheeler@pgexperts.com>
395  
396 =head1 Copyright and License
397  
398 Copyright (c) 2011-2025 David E. Wheeler.
399  
400 This module is free software; you can redistribute it and/or modify it under
401 the L<PostgreSQL License|http://www.opensource.org/licenses/postgresql>.
402  
403 Permission to use, copy, modify, and distribute this software and its
404 documentation for any purpose, without fee, and without a written agreement is
405 hereby granted, provided that the above copyright notice and this paragraph
406 and the following two paragraphs appear in all copies.
407  
408 In no event shall David E. Wheeler be liable to any party for direct,
409 indirect, special, incidental, or consequential damages, including lost
410 profits, arising out of the use of this software and its documentation, even
411 if David E. Wheeler has been advised of the possibility of such damage.
412  
413 David E. Wheeler specifically disclaims any warranties, including, but not
414 limited to, the implied warranties of merchantability and fitness for a
415 particular purpose. The software provided hereunder is on an "as is" basis,
416 and David E. Wheeler has no obligations to provide maintenance, support,
417 updates, enhancements, or modifications.
418  
419 =cut
« _build/lib/PGXN/Build.pm ↑ Summary blib/lib/PGXN/API/Indexer.pm »