blib/lib/EV/Nats/ObjectStore.pm

filter: Statementstmt 93.7% 194 / 207 Branchbran 71.8% 79 / 110 Conditioncond 61.3% 46 / 75 MC/DCmcdc 33.3% 14 / 42 Subroutinesub 86.2% 44 / 51 Podpod 41.6% 10 / 24 totaltotal 76.0% 387 / 509 CC 84 SCAR 18.3
CC
84
Cov
81%
create_bucket
30.0
__ANON__
12.0
__ANON__
11.0
CRAP 6.2
« blib/lib/EV/Nats/JetStream.pm ↑ Summary blib/lib/EV/Nats.pm »
1 package EV::Nats::ObjectStore;
2 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 4 our $VERSION = '0.09';
5 4 ▶use Digest::SHA qw(sha256 sha256_hex);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 4 ▶use JSON::PP ();
Subroutine BEGIN: called CC=1 SCAR=0.0
7 4 ▶use MIME::Base64 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 4 ▶use EV::Nats::JetStream;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 4 my $CHUNK_SIZE = 128 * 1024;
11 4 my $PUT_WINDOW = 16; # chunks in flight; each one's timeout runs from its own send
12 4 my @NUID_CHARS = ('A'..'Z', 'a'..'z', '0'..'9');
13  
14 25 ▶sub new {
Subroutine new: called CC=8 SCAR=21.2
Pod documented
15 25 my ($class, %opts) = @_;
16 25 ▶ my $js = delete $opts{js} || die "js (JetStream) required";
Condition50%1/2
delete $opts{'js'} || die('js (JetStream) required')
l!l
250
MC/DC0%0/1
delete $opts{'js'} || die('js (JetStream) required')
delete $opts{'js'}
Truth table50%1/2
A
A= delete $opts{'js'}
Aresult
11
00
17 25 ▶ my $bucket = delete $opts{bucket} || die "bucket name required";
Condition50%1/2
delete $opts{'bucket'} || die('bucket name required')
l!l
250
MC/DC0%0/1
delete $opts{'bucket'} || die('bucket name required')
delete $opts{'bucket'}
Truth table50%1/2
A
A= delete $opts{'bucket'}
Aresult
11
00
18 25 ▶ die "invalid ObjectStore bucket name '$bucket'"
Branch: 1 branch
BranchTrueFalseTotal
unless $bucket =~ /\A[a-zA-Z0-9_-]+\z/ 1 24 25
19 unless $bucket =~ /\A[a-zA-Z0-9_-]+\z/;
20 24 my $timeout = delete $opts{timeout};
21 24 ▶ my $chunk_size = delete $opts{chunk_size} || $CHUNK_SIZE;
Condition66%2/3
delete $opts{'chunk_size'} || $CHUNK_SIZE
l!l&&r!l&&!r
6180
MC/DC0%0/2
delete $opts{'chunk_size'} || $CHUNK_SIZE
delete $opts{'chunk_size'} $CHUNK_SIZE
Truth table66%2/3
A || B
A= delete $opts{'chunk_size'}B= $CHUNK_SIZE
ABresult
1X1
011
000
22 24 ▶ die "invalid chunk_size '$chunk_size'"
Branch: 1 branch
BranchTrueFalseTotal
unless $chunk_size =~ /\A\d+\z/ and $chunk_size > 0 1 23 24
Condition66%2/3
$chunk_size =~ /\A\d+\z/ and $chunk_size > 0
!ll&&!rl&&r
1023
MC/DC50%1/2
$chunk_size =~ /\A\d+\z/ and $chunk_size > 0
$chunk_size =~ /\A\d+\z/ $chunk_size > 0
Truth table66%2/3
A and B
A= $chunk_size =~ /\A\d+\z/B= $chunk_size > 0
ABresult
0X0
100
111
23 unless $chunk_size =~ /\A\d+\z/ && $chunk_size > 0;
24 23 warn "EV::Nats::ObjectStore::new: unknown option '$_'" for keys %opts;
25 23 bless {
26 js => $js->with_timeout($timeout),
27 bucket => $bucket,
28 stream => "OBJ_$bucket",
29 chunk_prefix => "\$O.$bucket.C.",
30 meta_prefix => "\$O.$bucket.M.",
31 chunk_size => $chunk_size,
32 }, $class;
33 }
34  
35 0 ▶sub create_bucket {
Subroutine create_bucket: not called CC=5 SCAR=34.0
Pod documented
36 0 my ($self, $opts, $cb) = @_;
37 0 ▶ $opts //= {};
Condition0%0/2
$opts //= {}
l!l
00
MC/DC0%0/1
$opts //= {}
$opts
Truth table0%0/2
A
A= $opts
Aresult
11
00
38 my $config = {
39 name => $self->{stream},
40 subjects => [ $self->{chunk_prefix} . '>', $self->{meta_prefix} . '>' ],
41 retention => 'limits',
42 ($opts->{max_bytes} ? (max_bytes => 0 + $opts->{max_bytes}) : ()),
43 ($opts->{max_age} ? (max_age => 0 + $opts->{max_age}) : ()),
44 0 ▶ ($opts->{replicas} ? (num_replicas => 0 + $opts->{replicas}) : ()),
Branch: 3 branches
BranchTrueFalseTotal
$opts->{'max_bytes'} ? : 0 0 0
$opts->{'max_age'} ? : 0 0 0
$opts->{'replicas'} ? : 0 0 0
45 discard => 'new',
46 allow_rollup_hdrs => JSON::PP::true(),
47 allow_direct => JSON::PP::true(),
48 };
49 0 ▶ $self->{js}->create_bucket_stream($config, sub { $cb->(@_[0, 1]) });
Subroutine __ANON__: not called CC=1 SCAR=6.9
50 }
51  
52 0 ▶sub delete_bucket {
Subroutine delete_bucket: not called CC=1 SCAR=6.9
Pod documented
53 0 my ($self, $cb) = @_;
54 0 ▶ $self->{js}->stream_delete($self->{stream}, sub { $cb->(@_[0, 1]) });
Subroutine __ANON__: not called CC=1 SCAR=6.9
55 }
56  
57 # Survives a dead connection: a sync croak (not connected, nothing
58 # queued) skips the purge and runs $cb now.
59 11 ▶sub purge_best_effort {
Subroutine purge_best_effort: called CC=2 SCAR=6.9
Pod undocumented
60 11 my ($self, $filter, $cb) = @_;
61 11 my $ok = eval {
62 $self->{js}->json_api('STREAM.PURGE.' . $self->{stream},
63 11 { filter => $filter }, $cb);
64 10 1;
65 };
66 11 ▶ $cb->() unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 1 10 11
67 }
68  
69 21 ▶sub purge_each {
Subroutine purge_each: called CC=2 SCAR=6.9
Pod undocumented
70 21 my ($self, $done, @filters) = @_;
71 21 ▶ return $done->() unless @filters;
Branch: 1 branch
BranchTrueFalseTotal
unless @filters 15 6 21
72 6 my $filter = shift @filters;
73 6 ▶ $self->purge_best_effort($filter, sub { $self->purge_each($done, @filters) });
Subroutine __ANON__: called CC=1 SCAR=0.0
74 }
75  
76 18 ▶sub put {
Subroutine put: called CC=5 SCAR=16.2
Pod documented
77 18 my ($self, $name, $data, $cb) = @_;
78 # the chunks, the size and the digest must all see the same bytes
79 18 ▶ utf8::downgrade($data, 1) or die "ObjectStore put: wide character in data\n";
Branch: 1 branch
BranchTrueFalseTotal
utf8::downgrade($data, 1) or die "ObjectStore put: wide character in data\n" 17 1 18
80 17 my $nats = $self->{js}{nats};
81 # fail here rather than in a chunk publish; before the first INFO
82 # max_payload is only the default
83 17 ▶ if ($nats->is_connected) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nats->is_connected) 2 15 17
84 2 my $max = $nats->max_payload;
85 die "chunk_size ($self->{chunk_size}) exceeds max_payload ($max)"
86 2 ▶ if $max > 0 && $self->{chunk_size} > $max;
Branch: 1 branch
BranchTrueFalseTotal
if $max > 0 and $self->{"chunk_size"} > $max 1 1 2
Condition66%2/3
$max > 0 and $self->{"chunk_size"} > $max
!ll&&!rl&&r
011
MC/DC50%1/2
$max > 0 and $self->{"chunk_size"} > $max
$max > 0 $self->{"chunk_size"} > $max
Truth table66%2/3
A and B
A= $max > 0B= $self->{"chunk_size"} > $max
ABresult
0X0
100
111
87 }
88 # the previous object's chunks and legacy meta go once the new meta is stored
89 16 ▶ $self->raw_meta($name, sub {
Subroutine __ANON__: called CC=3 SCAR=11.1
90 16 my ($old_meta, $old_subj, $old_gone, $err) = @_;
91 16 ▶ return $cb->(undef, $err) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 16 16
92  
93 16 my $nuid = nuid();
94 16 my $size = length $data;
95 16 my $cs = $self->{chunk_size};
96 16 ▶ my $chunks = $size ? int(($size + $cs - 1) / $cs) : 1;
Branch: 1 branch
BranchTrueFalseTotal
$size ? : 16 0 16
97 16 my $chunk_subj = $self->{chunk_prefix} . $nuid;
98  
99 16 ▶ my $store_meta = sub {
Subroutine __ANON__: called CC=3 SCAR=11.1
100 16 my ($failed) = @_;
101 return $self->purge_best_effort($chunk_subj,
102 16 ▶ sub { $cb->(undef, "$failed chunk(s) failed to publish") }) if $failed;
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
if $failed 3 13 16
103 my $meta = JSON::PP::encode_json({
104 name => meta_name($name),
105 size => $size,
106 chunks => $chunks,
107 nuid => $nuid,
108 # ADR-20: padded base64url of the raw SHA-256, as nats.go writes it
109 digest => 'SHA-256=' . b64url(sha256($data)),
110 bucket => $self->{bucket},
111 13 });
112 12 ▶ my $on_meta = sub {
Subroutine __ANON__: called CC=9 SCAR=22.7
113 12 my ($ack, $err) = @_;
114 1 ▶ return $self->purge_best_effort($chunk_subj, sub { $cb->(undef, $err) })
Subroutine __ANON__: called CC=1 SCAR=0.0
115 12 ▶ if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 1 11 12
116 11 my @stale;
117 push @stale, $self->{chunk_prefix} . $old_meta->{nuid}
118 if $old_meta && !$old_gone && length($old_meta->{nuid} // '')
119 11 ▶ && $old_meta->{nuid} ne $nuid;
Branch: 1 branch
BranchTrueFalseTotal
if $old_meta and not $old_gone and length($old_meta->{"nuid"} // "") and $old_meta->{"nuid"} ne $nuid 1 10 11
Condition63%7/11
$old_meta and not $old_gone and length($old_meta->{"nuid"} // "") and $old_meta->{"nuid"} ne $nuid
!ll&&!rl&&r
1001
$old_meta and not $old_gone and length($old_meta->{"nuid"} // "")
!ll&&!rl&&r
1001
$old_meta and not $old_gone
!ll&&!rl&&r
1001
$old_meta->{"nuid"} // ""
l!l
10
MC/DC25%1/4
$old_meta and not $old_gone and length($old_meta->{"nuid"} // "") and $old_meta->{"nuid"} ne $nuid
$old_meta not $old_gone $old_meta->{"nuid"} $old_meta->{"nuid"} ne $nuid
Truth table40%2/5
A and not(B) and C and D
A= $old_metaB= not $old_goneC= $old_meta->{"nuid"}D= $old_meta->{"nuid"} ne $nuid
ABCDresult
0XXX0
10XX0
110X0
11100
11111
120 11 my $legacy = $self->{meta_prefix} . encode_name_legacy($name);
121 11 ▶ push @stale, $legacy if $old_subj && $old_subj eq $legacy;
Branch: 1 branch
BranchTrueFalseTotal
if $old_subj and $old_subj eq $legacy 0 11 11
Condition66%2/3
$old_subj and $old_subj eq $legacy
!ll&&!rl&&r
1010
MC/DC0%0/2
$old_subj and $old_subj eq $legacy
$old_subj $old_subj eq $legacy
Truth table66%2/3
A and B
A= $old_subjB= $old_subj eq $legacy
ABresult
0X0
100
111
122 11 ▶ $self->purge_each(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
123 11 $cb->({ name => $name, size => $size, chunks => $chunks, seq => $ack->{seq} }, undef);
124 11 }, @stale);
125 13 };
126 # the rollup keeps exactly one message on the meta subject
127 eval {
128 13 $self->{js}->js_publish_h($self->{meta_prefix} . encode_name($name),
129 "NATS/1.0\r\nNats-Rollup: sub\r\n\r\n", $meta, $on_meta);
130 12 1;
131 13 ▶ } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->{"js"}->js_publish_h($self->{"meta_prefix"} . encode_name($name), "NATS/1.0\r\nNats-Rollup: sub\r\n\r\n", $meta, $on_meta); 1 } } or do { my $err = $@; $self->purge_best_effort($chunk_subj, sub { &$cb(undef, $err); } ) } 12 1 13
132 1 my $err = $@;
133 1 ▶ $self->purge_best_effort($chunk_subj, sub { $cb->(undef, $err) });
Subroutine __ANON__: called CC=1 SCAR=0.0
134 };
135 16 };
136 16 $self->put_chunks({ data => $data, subj => $chunk_subj, chunks => $chunks,
137 sent => 0, acked => 0, failed => 0, done => $store_meta });
138 16 });
139 }
140  
141 # a failure stops further sends; done fires once every sent chunk is answered
142 84 ▶sub put_chunks {
Subroutine put_chunks: called CC=9 SCAR=22.0
Pod undocumented
143 84 my ($self, $st) = @_;
144 84 my $cs = $self->{chunk_size};
145 84 ▶ while ($st->{sent} < $st->{chunks} && !$st->{failed}
Branch: 1 branch
BranchTrueFalseTotal
if ($st->{"sent"} < $st->{"chunks"} and not $st->{"failed"} and $st->{"sent"} - $st->{"acked"} < $PUT_WINDOW) 69 84 153
Condition100%6/6
$st->{"sent"} < $st->{"chunks"} and not $st->{"failed"} and $st->{"sent"} - $st->{"acked"} < $PUT_WINDOW
!ll&&!rl&&r
602469
$st->{"sent"} < $st->{"chunks"} and not $st->{"failed"}
!ll&&!rl&&r
58293
MC/DC100%3/3
$st->{"sent"} < $st->{"chunks"} and not $st->{"failed"} and $st->{"sent"} - $st->{"acked"} < $PUT_WINDOW
$st->{"sent"} < $st->{"chunks"} not $st->{"failed"} $st->{"sent"} - $st->{"acked"} < $PUT_WINDOW
Truth table100%4/4
A and not(B) and C
A= $st->{"sent"} < $st->{"chunks"}B= not $st->{"failed"}C= $st->{"sent"} - $st->{"acked"} < $PUT_WINDOW
ABCresult
0XX0
10X0
1100
1111
146 && $st->{sent} - $st->{acked} < $PUT_WINDOW) {
147 69 my $chunk = substr $st->{data}, $st->{sent}++ * $cs, $cs;
148 69 ▶ next if eval {
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { $self->{"js"}->js_publish($st->{"subj"}, $chunk, sub { ++$st->{"failed"} if $_[1]; ++$st->{"acked"}; $self->put_chunks($st); } ); 1 } } 68 1 69
149 68 ▶ $self->{js}->js_publish($st->{subj}, $chunk, sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
150 68 ▶ $st->{failed}++ if $_[1];
Branch: 1 branch
BranchTrueFalseTotal
if $_[1] 11 57 68
151 68 $st->{acked}++;
152 68 $self->put_chunks($st);
153 69 });
154 68 1;
155 };
156 1 $st->{failed}++;
157 1 $st->{acked}++;
158 }
159 return unless $st->{acked} == $st->{sent}
160 84 ▶ && ($st->{sent} == $st->{chunks} || $st->{failed});
Branch: 1 branch
BranchTrueFalseTotal
unless $st->{"acked"} == $st->{"sent"} and $st->{"sent"} == $st->{"chunks"} || $st->{"failed"} 68 16 84
Condition66%4/6
$st->{"acked"} == $st->{"sent"} and $st->{"sent"} == $st->{"chunks"} || $st->{"failed"}
!ll&&!rl&&r
68016
$st->{"sent"} == $st->{"chunks"} or $st->{"failed"}
l!l&&r!l&&!r
1510
MC/DC33%1/3
$st->{"acked"} == $st->{"sent"} and $st->{"sent"} == $st->{"chunks"} || $st->{"failed"}
$st->{"acked"} == $st->{"sent"} $st->{"sent"} == $st->{"chunks"} $st->{"failed"}
Truth table75%3/4
A and B or C
A= $st->{"acked"} == $st->{"sent"}B= $st->{"sent"} == $st->{"chunks"}C= $st->{"failed"}
ABCresult
0XX0
1000
11X1
1011
161 16 ▶ my $done = delete $st->{done} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $done = delete $st->{"done"} or return 16 0 16
162 16 $done->($st->{failed});
163 }
164  
165 11 ▶sub get {
Subroutine get: called CC=1 SCAR=0.0
Pod documented
166 11 my ($self, $name, $cb) = @_;
167 11 ▶ $self->raw_meta($name, sub {
Subroutine __ANON__: called CC=5 SCAR=16.2
168 11 my ($meta, undef, $gone, $err) = @_;
169 11 ▶ return $cb->(undef, $err) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 11 11
170 # a missing or deleted object is a clean miss, as in KV::get
171 11 ▶ return $cb->(undef, undef) if !$meta || $gone;
Branch: 1 branch
BranchTrueFalseTotal
if not $meta or $gone 4 7 11
Condition100%3/3
not $meta or $gone
l!l&&r!l&&!r
137
MC/DC100%2/2
not $meta or $gone
not $meta $gone
Truth table100%3/3
not(A) or B
A= not $metaB= $gone
ABresult
1X1
011
000
172 7 ▶ return $cb->('', undef, $meta) unless $meta->{chunks};
Branch: 1 branch
BranchTrueFalseTotal
unless $meta->{"chunks"} 0 7 7
173 7 $self->fetch_chunks($meta, 1, [], $cb);
174 11 });
175 }
176  
177 # next_by_subj answers the first match at or after seq. A replica that has
178 # not caught up misses a chunk the leader has: ask the leader before failing.
179 7 ▶sub fetch_chunks {
Subroutine fetch_chunks: called CC=1 SCAR=0.4
Pod undocumented
180 7 my ($self, $meta, $seq, $chunks, $cb, $leader) = @_;
181 $self->{js}->get_msg($self->{stream},
182 7 ▶ { next_by_subj => $self->{chunk_prefix} . $meta->{nuid}, seq => $seq }, sub {
Subroutine __ANON__: called CC=8 SCAR=24.0
183 7 my ($msg, $err) = @_;
184 7 ▶ return $cb->(undef, "chunk fetch error: $err", $meta) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 7 7
185 7 ▶ return $self->fetch_chunks($meta, $seq, $chunks, $cb, 1) if !$msg && !$leader;
Branch: 1 branch
BranchTrueFalseTotal
unless $msg or $leader 0 7 7
Condition33%1/3
$msg or $leader
l!l&&r!l&&!r
700
MC/DC0%0/2
$msg or $leader
$msg $leader
Truth table33%1/3
A or B
A= $msgB= $leader
ABresult
1X1
011
000
186 7 ▶ return $cb->(undef, "missing chunk message", $meta) unless $msg;
Branch: 1 branch
BranchTrueFalseTotal
unless $msg 0 7 7
187 7 push @$chunks, $msg->{data};
188 return $self->fetch_chunks($meta, ($msg->{seq} || $seq) + 1, $chunks, $cb)
189 7 ▶ if @$chunks < $meta->{chunks};
Branch: 1 branch
BranchTrueFalseTotal
if @$chunks < $meta->{"chunks"} 0 7 7
Condition0%0/3
$msg->{'seq'} || $seq
l!l&&r!l&&!r
000
MC/DC0%0/2
$msg->{'seq'} || $seq
$msg->{'seq'} $seq
Truth table0%0/3
A || B
A= $msg->{'seq'}B= $seq
ABresult
1X1
011
000
190 7 my $data = join '', @$chunks;
191 7 ▶ return $cb->(undef, "digest mismatch", $meta) unless digest_ok($meta->{digest}, $data);
Branch: 1 branch
BranchTrueFalseTotal
unless digest_ok($meta->{"digest"}, $data) 1 6 7
192 6 $cb->($data, undef, $meta);
193 7 }, $leader);
194 }
195  
196 # hex and unpadded base64url digests come from older writers
197 7 ▶sub digest_ok {
Subroutine digest_ok: called CC=4 SCAR=14.2
Pod undocumented
198 7 my ($digest, $data) = @_;
199 7 ▶ return 1 unless $digest && $digest =~ /^SHA-256=(.+)\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $digest and $digest =~ /^SHA-256=(.+)\z/ 0 7 7
Condition33%1/3
$digest and $digest =~ /^SHA-256=(.+)\z/
!ll&&!rl&&r
007
MC/DC0%0/2
$digest and $digest =~ /^SHA-256=(.+)\z/
$digest $digest =~ /^SHA-256=(.+)\z/
Truth table33%1/3
A and B
A= $digestB= $digest =~ /^SHA-256=(.+)\z/
ABresult
0X0
100
111
200 7 my $stored = $1;
201 7 ▶ return sha256_hex($data) eq $stored if $stored =~ /\A[0-9a-f]{64}\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $stored =~ /\A[0-9a-f]{64}\z/ 1 6 7
202 6 (my $s = $stored) =~ s/=+\z//;
203 6 (my $g = b64url(sha256($data))) =~ s/=+\z//;
204 6 return $g eq $s;
205 }
206  
207 6 ▶sub delete {
Subroutine delete: called CC=2 SCAR=7.1
Pod documented
208 6 my ($self, $name, $cb) = @_;
209 6 ▶ $cb //= sub {};
Subroutine __ANON__: not called CC=1 SCAR=1.2
Condition33%1/3
$cb //= sub { }
l!l&&r!l&&!r
600
MC/DC0%0/2
$cb //= sub { }
$cb sub { }
Truth table33%1/3
A //= B
A= $cbB= sub { }
ABresult
1X1
011
000
210 # nats.go marks a delete with the full metadata carrying "deleted":true
211 # under a rollup, not with an empty KV-Operation tombstone
212 6 ▶ $self->raw_meta($name, sub {
Subroutine __ANON__: called CC=4 SCAR=14.0
213 6 my ($meta, $found_subj, $gone, $err) = @_;
214 6 ▶ return $cb->(undef, $err) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 6 6
215 # nothing live: success, and no spurious marker
216 6 ▶ return $cb->(1, undef) if !$meta || $gone;
Branch: 1 branch
BranchTrueFalseTotal
if not $meta or $gone 2 4 6
Condition100%3/3
not $meta or $gone
l!l&&r!l&&!r
114
MC/DC100%2/2
not $meta or $gone
not $meta $gone
Truth table100%3/3
not(A) or B
A= not $metaB= $gone
ABresult
1X1
011
000
217 my $marker = JSON::PP::encode_json({
218 name => meta_name($name),
219 bucket => $self->{bucket},
220 4 nuid => '',
221 size => 0,
222 chunks => 0,
223 digest => '',
224 deleted => JSON::PP::true(),
225 });
226 4 my $legacy = $self->{meta_prefix} . encode_name_legacy($name);
227 # marked first, as nats.go does, so a failed purge cannot leave it readable
228 $self->{js}->js_publish_h($self->{meta_prefix} . encode_name($name),
229 4 ▶ "NATS/1.0\r\nNats-Rollup: sub\r\n\r\n", $marker, sub {
Subroutine __ANON__: called CC=6 SCAR=18.6
230 4 my (undef, $perr) = @_;
231 4 ▶ return $cb->(undef, $perr) if $perr;
Branch: 1 branch
BranchTrueFalseTotal
if $perr 0 4 4
232 4 my @cleanup;
233 4 ▶ push @cleanup, $self->{chunk_prefix} . $meta->{nuid} if length($meta->{nuid} // '');
Branch: 1 branch
BranchTrueFalseTotal
if length($meta->{"nuid"} // "") 4 0 4
Condition50%1/2
$meta->{"nuid"} // ""
l!l
40
MC/DC0%0/1
$meta->{"nuid"} // ""
$meta->{"nuid"}
Truth table50%1/2
A
A= $meta->{"nuid"}
Aresult
11
00
234 # a live legacy meta would resurface through the dual read and list()
235 4 ▶ push @cleanup, $legacy if $found_subj && $found_subj eq $legacy;
Branch: 1 branch
BranchTrueFalseTotal
if $found_subj and $found_subj eq $legacy 1 3 4
Condition66%2/3
$found_subj and $found_subj eq $legacy
!ll&&!rl&&r
031
MC/DC50%1/2
$found_subj and $found_subj eq $legacy
$found_subj $found_subj eq $legacy
Truth table66%2/3
A and B
A= $found_subjB= $found_subj eq $legacy
ABresult
0X0
100
111
236 4 ▶ $self->purge_each(sub { $cb->(1, undef) }, @cleanup);
Subroutine __ANON__: called CC=1 SCAR=0.0
237 4 });
238 6 });
239 }
240  
241 4 ▶sub info {
Subroutine info: called CC=1 SCAR=0.0
Pod documented
242 4 my ($self, $name, $cb) = @_;
243 4 ▶ $self->raw_meta($name, sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
244 4 my ($meta, undef, $gone, $err) = @_;
245 4 ▶ return $cb->(undef, $err) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 1 3 4
246 3 ▶ $cb->($meta && !$gone ? $meta : undef, undef);
Branch: 1 branch
BranchTrueFalseTotal
$meta && !$gone ? : 1 2 3
Condition66%2/3
$meta and not $gone
!ll&&!rl&&r
021
MC/DC50%1/2
$meta and not $gone
$meta not $gone
Truth table66%2/3
A and not(B)
A= $metaB= not $gone
ABresult
0X0
100
111
247 4 });
248 }
249  
250 1 ▶sub list {
Subroutine list: called CC=1 SCAR=0.0
Pod documented
251 1 my ($self, $cb) = @_;
252 1 ▶ $self->{js}->subjects_under($self->{stream}, $self->{meta_prefix}, sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
253 1 my ($tokens, $err) = @_;
254 1 ▶ return $cb->(undef, $err) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 1 1
255 1 $cb->([ map { decode_name_best($_) } @$tokens ], undef);
256 1 });
257 }
258  
259 0 ▶sub status {
Subroutine status: not called CC=1 SCAR=6.9
Pod documented
260 0 my ($self, $cb) = @_;
261 0 ▶ $self->{js}->stream_info($self->{stream}, sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
262 0 my ($info, $err) = @_;
263 0 ▶ return $cb->(undef, $err) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 0 0
264 $cb->({
265 bucket => $self->{bucket},
266 bytes => $info->{state}{bytes},
267 0 ▶ sealed => $info->{config}{sealed} ? 1 : 0,
Branch: 1 branch
BranchTrueFalseTotal
$info->{'config'}{'sealed'} ? : 0 0 0
268 }, undef);
269 0 });
270 }
271  
272 # ($meta, $found_subject, $is_gone, $err) -> $cb. The base64url subject is
273 # read first, then the legacy %XX one. $is_gone covers a KV-Operation
274 # tombstone and a "deleted":true meta; $meta still comes back when gone,
275 # so delete() can read its nuid.
276 37 ▶sub raw_meta {
Subroutine raw_meta: called CC=2 SCAR=7.0
Pod undocumented
277 37 my ($self, $name, $cb) = @_;
278 37 my @try = ($self->{meta_prefix} . encode_name($name));
279 37 my $legacy = $self->{meta_prefix} . encode_name_legacy($name);
280 37 ▶ push @try, $legacy if $legacy ne $try[0];
Branch: 1 branch
BranchTrueFalseTotal
if $legacy ne $try[0] 37 0 37
281 37 $self->meta_at($cb, @try);
282 }
283  
284 74 ▶sub meta_at {
Subroutine meta_at: called CC=2 SCAR=7.0
Pod undocumented
285 74 my ($self, $cb, $subj, @rest) = @_;
286 74 ▶ return $cb->(undef, undef, 0, undef) unless defined $subj;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $subj 17 57 74
287 57 ▶ $self->{js}->get_msg($self->{stream}, { last_by_subj => $subj }, sub {
Subroutine __ANON__: called CC=9 SCAR=22.5
288 57 my ($msg, $err) = @_;
289 57 ▶ return $cb->(undef, undef, 0, $err) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 1 56 57
290 56 ▶ return $self->meta_at($cb, @rest) unless $msg;
Branch: 1 branch
BranchTrueFalseTotal
unless $msg 37 19 56
291 19 my ($meta, $derr);
292 # a tombstone's payload is empty
293 19 ▶ if (length($msg->{data} // '')) {
Branch: 1 branch
BranchTrueFalseTotal
if (length($msg->{"data"} // "")) 19 0 19
Condition50%1/2
$msg->{"data"} // ""
l!l
190
MC/DC0%0/1
$msg->{"data"} // ""
$msg->{"data"}
Truth table50%1/2
A
A= $msg->{"data"}
Aresult
11
00
294 19 ($meta, $derr) = EV::Nats::JetStream::decode_json_or_error($msg->{data});
295 19 ▶ return $cb->(undef, $subj, 0, "invalid metadata: $derr") if $derr;
Branch: 1 branch
BranchTrueFalseTotal
if $derr 0 19 19
296 }
297 19 ▶ my $gone = EV::Nats::JetStream::msg_is_tombstone($msg) || ($meta && $meta->{deleted}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
EV::Nats::JetStream::msg_is_tombstone($msg) || $meta && $meta->{'deleted'} ? : 6 13 19
Condition66%4/6
EV::Nats::JetStream::msg_is_tombstone($msg) or $meta and $meta->{"deleted"}
l!l&&r!l&&!r
0613
$meta and $meta->{"deleted"}
!ll&&!rl&&r
0136
MC/DC33%1/3
EV::Nats::JetStream::msg_is_tombstone($msg) or $meta and $meta->{"deleted"}
EV::Nats::JetStream::msg_is_tombstone($msg) $meta $meta->{"deleted"}
Truth table50%2/4
A or B and C
A= EV::Nats::JetStream::msg_is_tombstone($msg)B= $metaC= $meta->{"deleted"}
ABCresult
1XX1
0111
00X0
0100
298 19 $cb->($meta, $subj, $gone, undef);
299 57 }, 1); # put and delete act on it: a replica's lagging copy would mislead them
300 }
301  
302 # concurrent writers' chunk subjects must never collide
303 16 ▶sub nuid {
Subroutine nuid: called CC=3 SCAR=11.2
Pod documented
304 16 my $bytes = '';
305 16 ▶ if (open my $fh, '<:raw', '/dev/urandom') {
Branch: 1 branch
BranchTrueFalseTotal
if (open my $fh, "<:raw", "/dev/urandom") 16 0 16
306 16 read $fh, $bytes, 22;
307 }
308 16 ▶ $bytes .= chr int rand 256 while length $bytes < 22;
Branch: 1 branch
BranchTrueFalseTotal
length $bytes < 22 and do { $bytes .= chr(int rand 256) } 0 16 16
309 16 return join '', map { $NUID_CHARS[ord($_) % @NUID_CHARS] } split //, $bytes;
310 }
311  
312 # padded base64url of bytes, as Go's URLEncoding
313 82 ▶sub b64url {
Subroutine b64url: called CC=1 SCAR=0.0
Pod undocumented
314 82 (my $e = MIME::Base64::encode_base64($_[0], '')) =~ tr{+/}{-_};
315 82 return $e;
316 }
317  
318 # padded or unpadded base64url to a UTF-8-decoded string
319 4 ▶sub b64url_dec {
Subroutine b64url_dec: called CC=1 SCAR=0.0
Pod undocumented
320 4 my $s = shift;
321 4 $s =~ tr{-_}{+/};
322 4 my $b = MIME::Base64::decode_base64($s);
323 4 utf8::decode($b);
324 4 return $b;
325 }
326  
327 # ADR-20 names are padded base64url of the name's bytes (a character string
328 # as UTF-8); *_legacy is the older %XX form
329 63 ▶sub encode_name {
Subroutine encode_name: called CC=2 SCAR=6.9
Pod undocumented
330 63 my $n = shift;
331 63 ▶ utf8::encode($n) if utf8::is_utf8($n);
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($n) 1 62 63
332 63 return b64url($n);
333 }
334  
335 # the metadata's name is text: UTF-8 bytes are decoded so it names the same
336 # subject for every client, not encoded a second time by the JSON encoder
337 18 ▶sub meta_name {
Subroutine meta_name: called CC=3 SCAR=11.0
Pod undocumented
338 18 my $n = shift;
339 18 ▶ return $n if utf8::is_utf8($n);
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($n) 0 18 18
340 18 my $text = $n;
341 18 ▶ return utf8::decode($text) ? $text : $n;
Branch: 1 branch
BranchTrueFalseTotal
utf8::decode($text) ? : 17 1 18
342 }
343 53 ▶sub encode_name_legacy { my $n = $_[0]; $n =~ s/([^A-Za-z0-9._-])/sprintf("%%%02X", ord($1))/ge; $n }
Subroutine encode_name_legacy: called CC=1 SCAR=0.0
Pod undocumented
344 2 ▶sub decode_name_legacy { my $n = $_[0]; $n =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/ge; $n }
Subroutine decode_name_legacy: called CC=1 SCAR=0.0
Pod undocumented
345  
346 # the base64url form wins when re-encoding round-trips
347 4 ▶sub decode_name_best {
Subroutine decode_name_best: called CC=2 SCAR=6.9
Pod undocumented
348 4 my $tok = shift;
349 4 my $dec = b64url_dec($tok);
350 4 ▶ return $dec if encode_name($dec) eq $tok;
Branch: 1 branch
BranchTrueFalseTotal
if encode_name($dec) eq $tok 3 1 4
351 1 return decode_name_legacy($tok);
352 }
353  
354 4 1;
355  
356 =head1 NAME
357  
358 EV::Nats::ObjectStore - Chunked object store on top of NATS JetStream
359  
360 =head1 SYNOPSIS
361  
362 use EV;
363 use EV::Nats;
364 use EV::Nats::JetStream;
365 use EV::Nats::ObjectStore;
366  
367 my $nats = EV::Nats->new(host => '127.0.0.1');
368 my $js = EV::Nats::JetStream->new(nats => $nats);
369 my $os = EV::Nats::ObjectStore->new(js => $js, bucket => 'files');
370 my $pdf_data = '...'; # your file bytes here
371  
372 $os->create_bucket({}, sub {
373 $os->put('report.pdf', $pdf_data, sub {
374 my ($info, $err) = @_;
375 print "stored: $info->{size} bytes in $info->{chunks} chunks\n";
376 $os->get('report.pdf', sub {
377 my ($data, $err, $meta) = @_;
378 print "got $meta->{size} bytes back\n";
379 });
380 });
381 });
382  
383 EV::run;
384  
385 =head1 DESCRIPTION
386  
387 An object-store bucket is a JetStream stream named C<OBJ_E<lt>bucketE<gt>>
388 with two subject groups:
389  
390 =over
391  
392 =item * C<$O.E<lt>bucketE<gt>.C.E<lt>nuidE<gt>> - opaque chunks for one
393 object (one chunk per stream message; the nuid is generated per object).
394  
395 =item * C<$O.E<lt>bucketE<gt>.M.E<lt>encoded-nameE<gt>> - last-write-wins
396 metadata describing an object (name, size, chunk count, SHA-256 digest).
397  
398 =back
399  
400 C<put> chunks the input, publishes each chunk via C<js_publish> for
401 durability, then writes a metadata entry. C<get> fetches the metadata,
402 reads the chunks back with Direct Get (C<STREAM.MSG.GET> for a bucket
403 without C<allow_direct>), and verifies the digest.
404  
405 =head1 METHODS
406  
407 All callbacks fire on the L<EV> loop, not synchronously.
408  
409 =head2 new
410  
411 new(js => $js, bucket => $name, [chunk_size => $bytes], [timeout => $ms])
412  
413 Default C<chunk_size> is 128 KiB. C<timeout> defaults to the timeout
414 of C<$js>. The bucket name must match C<[a-zA-Z0-9_-]+> and
415 C<chunk_size> must be a positive integer; both are validated up
416 front. C<chunk_size> must also not exceed the server's
417 C<max_payload> (checked on L</put> once connected).
418  
419 =head2 create_bucket
420  
421 create_bucket(\%opts, $cb)
422  
423 Provision the underlying stream. Recognised C<\%opts>:
424  
425 =over
426  
427 =item * C<max_bytes> - bucket-wide storage cap.
428  
429 =item * C<max_age> - per-message TTL in nanoseconds.
430  
431 =item * C<replicas> - cluster replication factor.
432  
433 =back
434  
435 Callback: C<($info, $err)>.
436  
437 =head2 delete_bucket
438  
439 delete_bucket($cb)
440  
441 Tear down the underlying stream. Callback: C<($info, $err)>.
442  
443 =head2 put
444  
445 put($name, $data, $cb)
446  
447 Store C<$data> under C<$name>, automatically chunked. Each chunk is
448 published with JetStream ack; the metadata entry is written last
449 (with a C<Nats-Rollup: sub> header, so the meta subject holds exactly
450 one message) so a partial upload doesn't surface a half-stored object.
451 Overwriting an existing name purges the previous object's chunks after
452 the new metadata is acknowledged. Callback: C<($info, $err)> where
453 C<$info> is C<{ name, size, chunks, seq }>.
454  
455 =head2 get
456  
457 get($name, $cb)
458  
459 Retrieve a previously-stored object. Callback: C<($data, $err, $meta)>.
460 C<$data> is C<undef> if the object does not exist or has been deleted
461 (both the old C<KV-Operation> tombstone and the nats.go
462 C<"deleted":true> marker are recognised). On digest mismatch, C<$data>
463 is C<undef> and C<$err> is C<"digest mismatch">.
464  
465 =head2 delete
466  
467 delete($name, [$cb])
468  
469 Publishes a C<"deleted":true> metadata marker with a C<Nats-Rollup:
470 sub> header (the nats.go form; the PubAck doubles as the flush fence),
471 then best-effort purges the object's chunks under
472 C<$O.E<lt>bucketE<gt>.C.E<lt>nuidE<gt>>. Marking is done first, so a
473 purge hiccup cannot leave a "deleted" object still readable. Idempotent:
474 deleting a missing or already-deleted object is a no-op success and
475 writes no marker. Callback: C<($ok, $err)>.
476  
477 =head2 info
478  
479 info($name, $cb)
480  
481 Fetch only the metadata entry for an object, without downloading
482 chunks. Callback: C<(\%meta, $err)>; C<\%meta> is C<undef> if the
483 object does not exist or was deleted (the deletion marker is
484 recognised). This is the recommended way to filter live objects out
485 of a L</list> result.
486  
487 =head2 list
488  
489 list($cb)
490  
491 List object names in the bucket. Callback: C<(\@names, $err)>.
492 Deleted entries still appear in the listing -- filtering them would
493 cost a per-name metadata round-trip, so call C<info> to filter.
494  
495 =head2 status
496  
497 status($cb)
498  
499 Returns a snapshot hashref:
500  
501 { bucket => $name, bytes => $n, sealed => 0|1 }
502  
503 C<sealed> reflects the stream's C<config.sealed> flag.
504  
505 Callback: C<(\%status, $err)>.
506  
507 =head1 SEE ALSO
508  
509 L<EV::Nats>, L<EV::Nats::JetStream>, L<EV::Nats::KV>,
510 L<NATS Object Store|https://docs.nats.io/using-nats/developer/develop_jetstream/object>.
511  
512 =cut
« blib/lib/EV/Nats/JetStream.pm ↑ Summary blib/lib/EV/Nats.pm »