blib/lib/File/FStore/File.pm untested

filter: Statementstmt 0.0% 0 / 416 Branchbran 0.0% 0 / 178 Conditioncond 0.0% 0 / 160 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 40 Podpod 0.0% 0 / 28 totaltotal 0.0% 0 / 822 CC 90 SCAR 60.4
CC
90
Cov
0%
update
1332.0
sync_with_db
240.0
get
90.0
CRAP 417.8
1 # Copyright (c) 2025 Philipp Schafft
2  
3 # licensed under Artistic License 2.0 (see LICENSE file)
4  
5 # ABSTRACT: Module for interacting with file stores
6  
7  
8 package File::FStore::File;
9  
10 use v5.10;
11 use strict;
12 use warnings;
13  
14 use Carp;
15 use Fcntl qw(SEEK_SET S_IWUSR S_IWGRP S_IWOTH);
16 use File::Spec;
17  
18 use Data::Identifier;
19 use Data::Identifier::Generate;
20  
21 use File::FStore;
22  
23 use parent qw(File::FStore::Base Data::Identifier::Interface::Known);
24  
25 use constant {
26 WRITE_BITS => S_IWUSR|S_IWGRP|S_IWOTH,
27 RE_ISE => qr<^(?:[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}|[1-3](?:\.(?:0|[1-9][0-9]*))+|[a-zA-Z][a-zA-Z0-9\+\.\-]+:.*)$>,
28 };
29  
30 our $VERSION = v0.06;
31  
32 my @_xattr_hashes = qw(sha-1-160 sha-2-256 sha-3-512);
33  
34 my %_valid_properties = (
35 size => qr<^(?:0|[1-9][0-9]*)$>,
36 inode => qr<>, # any
37 mediasubtype => qr<^(?:application|audio|example|font|haptics|image|message|model|multipart|text|video)/[0-9a-zA-Z][0-9a-zA-Z\!\#\$\&\-\^_\.\+]{0,126}$>,
38 contentise => RE_ISE,
39 inodeise => RE_ISE,
40 );
41  
42 my %_exts = (
43 'image/jpeg' => 'jpg',
44 'image/png' => 'png',
45 'image/gif' => 'gif',
46 'image/vnd.microsoft.icon' => 'ico',
47 'audio/flac' => 'flac',
48 'application/pdf' => 'pdf',
49 'application/zip' => 'zip',
50 'text/plain' => 'txt',
51 );
52  
53 my %_db_tags = (
54 # well known tags:
55 final_file_size => Data::Identifier->new(uuid => '1cd4a6c6-0d7c-48d1-81e7-4e8d41fdb45d'),
56 final_file_encoding => Data::Identifier->new(uuid => '448c50a8-c847-4bc7-856e-0db5fea8f23b'),
57 final_file_hash => Data::Identifier->new(uuid => '79385945-0963-44aa-880a-bca4a42e9002'),
58 also_has_role => Data::Identifier->new(uuid => 'd2750351-aed7-4ade-aa80-c32436cc6030'),
59 also_has_state => Data::Identifier->new(uuid => '4c426c3c-900e-4350-8443-e2149869fbc9'),
60 has_final_state => Data::Identifier->new(uuid => '54d30193-2000-4d8a-8c28-3fa5af4cad6b'),
61 specific_proto_file_state => Data::Identifier->new(uuid => '63da70a8-78a4-51b0-8b87-86872b474a5d'),
62 );
63  
64  
65 sub dbname {
66 my ($self) = @_;
67 return $self->{dbname} //= do {
68 my $sth = $self->_prepare('SELECT filename FROM file WHERE id = ?');
69 my $res;
70  
71 $sth->execute($self->{dbid});
72 $res = $sth->fetchall_arrayref;
73  
74 $res->[0][0] // croak 'Database error';
75 };
76 }
77  
78  
79 sub filename {
80 my ($self) = @_;
81 return $self->{filename} //= do {
82 $self->store->_file(qw(v2 store), $self->dbname);
83 };
84 }
85  
86  
87 sub open {
88 my ($self) = @_;
89 my $fh = $self->_open;
90  
91 $self->stat;
92 $self->_detach_fh;
93  
94 return $fh;
95 }
96  
97  
98 sub link_out {
99 my ($self, $filename) = @_;
100 link($self->filename, $filename) or croak $!;
101 }
102  
103  
104 sub symlink_out {
105 my ($self, $filename) = @_;
106 symlink($self->filename, $filename) or croak $!;
107 }
108  
109  
110 sub update {
111 my ($self, %opts) = @_;
112 my File::FStore $store = $self->store;
113 my $no_digests = delete($opts{no_digests});
114 my $on_pre_set = delete($opts{on_pre_set});
115 my $on_post_set = delete($opts{on_post_set});
116 my $inode;
117 my $properties;
118 my $digests;
119  
120 croak 'Stray options passed' if scalar keys %opts;
121  
122 $store->_init_link_style;
123  
124 $store->in_transaction(rw => sub {
125 my $fh = $self->_open;
126  
127 delete $self->{stat}; #clear stat cache.
128  
129 $inode = $self->as('File::Information::Inode');
130  
131 # Perform a verify via File::Information
132 unless ($no_digests) {
133 my $verify_result = $inode->verify;
134 unless ($verify_result->has_passed || $verify_result->has_no_data || $verify_result->has_insufficient_data) {
135 croak sprintf('File (%s) is in bad state: %s', $self->dbname, $verify_result->status);
136 }
137 }
138  
139 # Perform a verify with our own data.
140 {
141 my $data = $self->get;
142 my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
143 $atime,$mtime,$ctime,$blksize,$blocks) = $self->stat;
144  
145 $properties = $data->{properties} //= {};
146 $digests = $data->{digests} //= {};
147  
148 $properties->{size} //= $size;
149 croak 'Size missmatch' if $properties->{size} != $size;
150 $properties->{inode} //= $ino;
151 croak 'inode missmatch' if $properties->{inode} != $ino;
152  
153 # Load some basic properties, first the final values, than the current ones.
154 foreach my $lifecycle (qw(final current)) {
155 if (defined(my $v = $inode->get('size', lifecycle => $lifecycle, default => undef))) {
156 $properties->{size} //= $v;
157 croak 'Size missmatch' if $properties->{size} != $v;
158 }
159  
160 if (defined(my $v = $inode->get('mediatype', lifecycle => $lifecycle, default => undef, as => 'mediatype'))) {
161 $properties->{mediasubtype} //= $v;
162 croak sprintf('Media subtype missmatch on (%s): "%s" vs. "%s"', $self->dbname, $properties->{mediasubtype}, $v) if $properties->{mediasubtype} ne $v;
163 }
164  
165 if (defined(my $v = $inode->get('inodeise', lifecycle => $lifecycle, default => undef, as => 'mediatype'))) {
166 $properties->{inodeise} //= $v;
167 # XXX: We ignore missmatches here. This can be for a number of reasons. Such as switches between different sources of the value.
168 # TODO: A better policy should be implemented later on.
169 }
170  
171 if (defined(my $v = $inode->get('st_ino', lifecycle => $lifecycle, default => undef))) {
172 $properties->{inode} //= $v;
173 croak 'inode missmatch' if $properties->{inode} != $v;
174 }
175 }
176  
177 # First load all known final ones.
178 foreach my $digest (@{$self->_used_digests}) {
179 if (defined(my $v = $inode->digest($digest, lifecycle => 'final', default => undef))) {
180 $digests->{$digest} //= $v;
181 croak 'Digest missmatch for '.$digest if $digests->{$digest} ne $v;
182 }
183 }
184  
185 # Then test against the current ones.
186 unless ($no_digests) {
187 foreach my $digest (@{$self->_used_digests}) {
188 if (defined(my $v = $inode->digest($digest, default => undef))) {
189 $digests->{$digest} //= $v;
190 croak 'Digest missmatch for '.$digest if $digests->{$digest} ne $v;
191 }
192 }
193 }
194  
195 if (defined(my $contentise = eval {$self->_calculate_contentise($data)->uuid})) {
196 $properties->{contentise} //= $contentise;
197 croak 'Content ISE missmatch' if $properties->{contentise} ne $contentise;
198 }
199  
200 $on_pre_set->($self) if defined $on_pre_set;
201 $self->set($data);
202 }
203  
204 # Create symlinks:
205 if ((my $link_style = $store->setting('link_style')) ne 'none') {
206 state $up = File::Spec->updir;
207 my $dbname = $self->dbname;
208 my $level = $link_style =~ /^([0-9]+)-level$/ ? int($1): 1;
209 my $filename = File::Spec->catfile(( map {$up} 0 .. $level), 'store', $dbname);
210  
211 foreach my $fn ($self->_linknames($digests, $link_style)) {
212 next if -l $fn;
213 symlink($filename, $fn) or croak $!;
214 }
215 }
216  
217 if (defined(my $handle = File::FStore::File::_DUMMY_FOR_XATTR->new($fh))) {
218 if (defined($properties->{size}) && !defined($handle->getfattr('utag.final.file.size'))) {
219 $handle->setfattr('utag.final.file.size' => $properties->{size});
220 }
221  
222 if (defined($properties->{mediasubtype}) && !defined($handle->getfattr('mime_type'))) {
223 $handle->setfattr('mime_type' => $properties->{mediasubtype});
224 }
225  
226 if (defined($properties->{mediasubtype}) && !defined($handle->getfattr('utag.final.file.encoding'))) {
227 my $v = Data::Identifier::Generate->generic(
228 namespace => '50d7c533-2d9b-4208-b560-bcbbf75ce3f9',
229 input => $properties->{mediasubtype},
230 )->uuid;
231 $handle->setfattr('utag.final.file.encoding' => $v);
232 }
233  
234 if (!defined($handle->getfattr('utag.write-mode'))) {
235 $handle->setfattr('utag.write-mode' => '7b177183-083c-4387-abd3-8793eb647373');
236 }
237  
238 if (!defined($handle->getfattr('utag.final-mode'))) {
239 $handle->setfattr('utag.final-mode' => 'f418cdb9-64a7-4f15-9a18-63f7755c5b47');
240 }
241  
242 if (defined(my $size = $properties->{size}) && !defined($handle->getfattr('utag.final.file.hash'))) {
243 my @el;
244 my $v = '';
245  
246 foreach my $algo (@_xattr_hashes) {
247 push(@el, sprintf(' %s bytes 0-%u/%u %s', $algo, $size - 1, $size, $digests->{$algo} // next));
248 }
249  
250 for (my $i = 0; $i < scalar(@el); $i++) {
251 $v .= ' ' if $i;
252 $v .= $i == $#el ? 'v0' : 'v0m';
253 $v .= $el[$i];
254 }
255  
256 $handle->setfattr('utag.final.file.hash' => $v) if length $v;
257 }
258 }
259  
260 # Try to alter the file mode to make the file read only.
261 {
262 my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
263 $atime,$mtime,$ctime,$blksize,$blocks) = $self->stat;
264  
265 if (defined($mode) && ($mode & WRITE_BITS)) {
266 my $n = $mode & (07777 ^ WRITE_BITS);
267 eval { chmod($n, $fh) }; # we don't care if it fails.
268 }
269 }
270  
271 $on_post_set->($self) if defined $on_post_set;
272 });
273 }
274  
275  
276 sub stat {
277 my ($self) = @_;
278  
279 $self->{stat} //= do {
280 my @s;
281  
282 if (defined $self->{fh}) {
283 @s = stat($self->{fh});
284 } else {
285 @s = stat($self->filename);
286 }
287  
288 croak 'File missing on filesystem, store is corruped: '.$self->dbname unless scalar(@s);
289  
290 \@s;
291 };
292  
293 return @{$self->{stat}};
294 }
295  
296  
297 sub get {
298 my ($self, $domain, $key) = @_;
299 if (defined($domain)) {
300 if (defined($key)) {
301 my $sth;
302 my $res;
303  
304 if ($domain eq 'properties') {
305 $sth = $self->_prepare('SELECT value FROM file_properties WHERE file = ? AND key = ?');
306 } elsif ($domain eq 'digests') {
307 $sth = $self->_prepare('SELECT hash FROM file_hash WHERE file = ? AND algo = ?');
308 }
309  
310 croak 'Invalid domain: '.$domain unless defined $sth;
311  
312 $sth->execute($self->{dbid}, $key);
313 $res = $sth->fetchall_arrayref;
314  
315 return $res->[0][0] // croak 'No value for domain '.$domain.' key '.$key;
316 } else {
317 my $sth;
318 my %res;
319  
320 if ($domain eq 'properties') {
321 $sth = $self->_prepare('SELECT key,value FROM file_properties WHERE file = ?');
322 } elsif ($domain eq 'digests') {
323 $sth = $self->_prepare('SELECT algo,hash FROM file_hash WHERE file = ?');
324 }
325  
326 croak 'Invalid domain: '.$domain unless defined $sth;
327  
328 $sth->execute($self->{dbid});
329  
330 while (my $row = $sth->fetchrow_arrayref) {
331 $res{$row->[0]} = $row->[1];
332 }
333  
334 return \%res;
335 }
336 } else {
337 return {map {$_ => $self->get($_)} qw(properties digests)};
338 }
339 }
340  
341  
342 sub set {
343 my ($self, $domain, $key, $value) = @_;
344 my $dbid = $self->{dbid};
345 my $data;
346  
347 croak 'No data given' unless defined $domain;
348  
349 # get things in standard format:
350 if (defined($key)) {
351 if (defined($value)) {
352 $data = {$domain => {$key => $value}};
353 } else {
354 $data = {$domain => $key};
355 }
356 } else {
357 $data = $domain;
358 }
359  
360 $self->store->in_transaction(rw => sub {
361 foreach my $cdomain (keys %{$data}) {
362 my $d = $data->{$cdomain};
363 my $sth;
364 my $valids;
365  
366 if ($cdomain eq 'properties') {
367 $sth = $self->_prepare('INSERT INTO file_properties (file,key,value) SELECT ?, ?, ? WHERE NOT EXISTS (SELECT TRUE FROM file_properties WHERE file = ? AND key = ? AND value = ?)');
368 $valids = \%_valid_properties;
369 } elsif ($cdomain eq 'digests') {
370 $sth = $self->_prepare('INSERT INTO file_hash (file,algo,hash) SELECT ?, ?, ? WHERE NOT EXISTS (SELECT TRUE FROM file_hash WHERE file = ? AND algo = ? AND hash = ?)');
371 $valids = $self->_valid_digests;
372 }
373  
374 croak 'Invalid domain: '.$domain unless defined $sth;
375  
376 foreach my $key (keys %{$d}) {
377 croak 'Invalid key '.$key.' for domain '.$cdomain unless defined $valids->{$key};
378 croak 'Invalid value for key '.$key.' for domain '.$cdomain unless $d->{$key} =~ $valids->{$key};
379 $sth->execute($dbid, $key, $d->{$key}, $dbid, $key, $d->{$key});
380 }
381 }
382 });
383 }
384  
385  
386 sub delete {
387 my ($self) = @_;
388 my $store = $self->store;
389 my $dbid = $self->{dbid} or croak 'Call on invalid object';
390  
391 $store->in_transaction(rw => sub {
392 my $filename = $self->filename;
393 my @linknames = $self->_linknames(undef, 'all');
394 my $sth;
395  
396 unlink($filename) or croak 'Cannot unlink file: '.$!;
397 unlink($_) foreach @linknames;
398  
399 $sth = $self->_prepare('DELETE FROM file_hash WHERE file = ?');
400 $sth->execute($dbid);
401 $sth = $self->_prepare('DELETE FROM file_properties WHERE file = ?');
402 $sth->execute($dbid);
403 $sth = $self->_prepare('DELETE FROM file WHERE id = ?');
404 $sth->execute($dbid);
405 });
406  
407 %{$self} = ();
408 }
409  
410  
411 sub sync_with_db {
412 my ($self, %opts) = @_;
413 my $db = $opts{db} // $self->db;
414 my $fii_inode = $self->as('File::Information::Inode');
415 $db->in_transaction(rw => sub {
416 my $data = $self->get;
417 my %ids = (
418 contentise => $self->contentise(as => 'Data::Identifier'),
419 inodeise => $fii_inode->get('inodeise', as => 'Data::Identifier', default => undef),
420 proto => (defined($opts{proto}) ? $opts{proto}->Data::Identifier::as('Data::Identifier') : undef),
421  
422 # Related values:
423  
424 encoding => (defined($data->{properties}{mediasubtype}) ? Data::Identifier::Generate->generic(
425 namespace => '50d7c533-2d9b-4208-b560-bcbbf75ce3f9',
426 input => $data->{properties}{mediasubtype},
427 ): undef),
428  
429 %_db_tags,
430 );
431 my %tags = map {$_ => scalar(eval {$ids{$_}->as('Data::TagDB::Tag', %opts{autocreate}, db => $db)})} grep {defined $ids{$_}} keys %ids;
432  
433 if (defined(my $tag = $tags{contentise})) {
434 my $size = $data->{properties}{size};
435  
436 if (defined($tags{also_has_role}) && defined($tags{specific_proto_file_state})) {
437 $db->create_relation(tag => $tag, relation => $tags{also_has_role}, related => $tags{specific_proto_file_state});
438 }
439  
440 if (defined($size) && defined($tags{final_file_size})) {
441 $db->create_metadata(tag => $tag, relation => $tags{final_file_size}, data_raw => $size);
442 }
443  
444 if (defined($tags{encoding}) && defined($tags{final_file_encoding})) {
445 $db->create_relation(tag => $tag, relation => $tags{final_file_encoding}, related => $tags{encoding});
446 }
447  
448 if (defined($tags{final_file_hash}) && defined($size) && $size > 0) {
449 foreach my $digest (keys %{$data->{digests}}) {
450 my $v = sprintf('v0 %s bytes 0-%u/%u %s', $digest, $size - 1, $size, $data->{digests}{$digest} // next);
451 $db->create_metadata(tag => $tag, relation => $tags{final_file_hash}, data_raw => $v);
452 }
453 }
454 }
455  
456 if (defined(my $proto = $tags{proto})) {
457 if (defined(my $tag = $tags{contentise})) {
458 if (defined(my $relation = $opts{final_of_proto} ? $tags{has_final_state} : $tags{also_has_state})) {
459 $db->create_relation(tag => $proto, relation => $relation, related => $tag);
460 }
461 }
462 }
463  
464 if (defined(my $inode = $tags{inodeise})) {
465 if (defined(my $tag = $tags{contentise})) {
466 if (defined($tags{has_final_state})) {
467 $db->create_relation(tag => $inode, relation => $tags{has_final_state}, related => $tag);
468 }
469 }
470 }
471 });
472 }
473  
474  
475 # --- Overrides for Data::URIID::Base ---
476 sub contentise {
477 my ($self, @args) = @_;
478  
479 $self->{contentise} //= eval {Data::Identifier->new(ise => $self->get(properties => 'contentise'))};
480 $self->{contentise} //= $self->_calculate_contentise;
481  
482 return $self->SUPER::contentise(@args);
483 }
484  
485 sub as {
486 my ($self, $as, %opts) = @_;
487  
488 if ($as eq 'File::Information::Inode' || $as eq 'File::Information::Base') {
489 if (defined $opts{fii}) {
490 return $opts{fii}->for_handle($self->_open);
491 } else {
492 return $self->{fii_inode} //= $self->fii->for_handle($self->_open);
493 }
494 } elsif ($as eq 'File::Information::Link') {
495 if (defined $opts{fii}) {
496 return $opts{fii}->for_link($self->filename);
497 } else {
498 return $self->{fii_inode} //= $self->fii->for_link($self->filename);
499 }
500 }
501  
502 return $self->SUPER::as($as, %opts);
503 }
504  
505  
506 # --- Overrides for Data::Identifier::Interface::Known ---
507 sub _known_provider {
508 my ($pkg, $class, %opts) = @_;
509 state $classes = {
510 properties => [[keys %_valid_properties], not_identifiers => 1],
511 digests => [[keys %File::FStore::_valid_digests], not_identifiers => 1],
512 link_styles => [[keys %File::FStore::_valid_link_styles], not_identifiers => 1],
513 store_styles => [[keys %File::FStore::_valid_store_styles], not_identifiers => 1],
514 domains => [[qw(properties digests)], not_identifiers => 1],
515 other_tags => [[values %_db_tags], rawtype => 'Data::Identifier'],
516 };
517 croak 'Unsupported options passed' if scalar(keys %opts);
518 $class =~ tr/-/_/;
519 return @{$classes->{$class}} if defined $classes->{$class};
520 return ([map {@{$_->[0]}} values %{$classes}], not_identifiers => 1) if $class eq ':all';
521 croak 'Unsupported class';
522 }
523  
524  
525  
526 # ---- Private helpers ----
527 sub _valid_digests {
528 return state $digests = {map {$_ => qr/^[0-9a-f]{$File::FStore::_valid_digests{$_}}$/} keys %File::FStore::_valid_digests};
529 }
530  
531 sub _new {
532 my ($pkg, %opts) = @_;
533 my $self = bless \%opts, $pkg;
534  
535 croak 'No store is given' unless defined $self->{store};
536 croak 'No dbid is given' unless defined $self->{dbid};
537  
538 return $self;
539 }
540  
541 sub _prepare {
542 my ($self, $q) = @_;
543 my $dbh = $self->{dbh} //= $self->store->{dbh};
544 return $dbh->prepare($q);
545 }
546  
547 sub _open {
548 my ($self, %opts) = @_;
549 my $fh;
550  
551 $self->{fh} = $opts{fh} if defined $opts{fh};
552  
553 $fh = $self->{fh} //= do {
554 CORE::open(my $in, '<', $self->filename) or croak $!;
555 $in;
556 };
557  
558 seek($fh, 0, SEEK_SET) or croak $!;
559  
560 return $fh;
561 }
562  
563 sub _detach_fh {
564 my ($self) = @_;
565 $self->{fh} = undef;
566 }
567  
568 sub _used_digests {
569 my ($self) = @_;
570 return $self->{used_digests} //= $self->store->_used_digests;
571 }
572  
573 sub _calculate_contentise {
574 my ($self, $data) = @_;
575 my $sha_1_160 = eval { $self->get(digests => 'sha-1-160') };
576 my $sha_3_512 = eval { $self->get(digests => 'sha-3-512') };
577 my $size = eval { $self->get(properties => 'size') };
578  
579 if (defined $data) {
580 $data->{digests} //= {};
581 $data->{properties} //= {};
582 $sha_1_160 //= $data->{digests}{'sha-1-160'};
583 $sha_3_512 //= $data->{digests}{'sha-3-512'};
584 $size //= $data->{properties}{size};
585 }
586  
587 if (defined($sha_1_160) && defined($sha_3_512) && defined($size)) {
588 my $digest = sprintf('v0m sha-1-160 bytes 0-%u/%u %s v0 sha-3-512 bytes 0-%u/%u %s',
589 $size - 1, $size, $sha_1_160,
590 $size - 1, $size, $sha_3_512,
591 );
592  
593 return Data::Identifier::Generate->generic(
594 namespace => '66d488c0-3b19-4e6c-856f-79edf2484f37',
595 input => $digest,
596 );
597 }
598 return undef;
599 }
600  
601 sub _ext {
602 my ($self) = @_;
603  
604 return $self->{ext} if exists $self->{ext};
605  
606 {
607 my $mediasubtype = eval {$self->get(properties => 'mediasubtype')} // 'x.x/x.x';
608 return $self->{ext} = $_exts{$mediasubtype} if defined $_exts{$mediasubtype};
609 }
610  
611 {
612 my $dbname = $self->dbname;
613 if ($dbname =~ /\.([a-z0-9]{1,4})$/) {
614 my $ext = $1;
615  
616 if ($dbname =~ /\.(tar\.(?:gz|bz2|xz|lz|zst))$/) {
617 $ext = $1;
618 }
619  
620 return $self->{ext} = $ext;
621 }
622 }
623  
624 return $self->{ext} = undef;
625 }
626  
627 sub _linknames {
628 my ($self, $digests, $link_style) = @_;
629 my File::FStore $store = $self->store;
630 my $ext = $self->_ext;
631 my @res;
632  
633 $ext = '.'.$ext if defined $ext;
634  
635 $digests //= $self->get('digests');
636 $link_style //= $store->setting('link_style');
637  
638 foreach my $digest (keys %{$digests}) {
639 my $v = $digests->{$digest} // next;
640  
641 $v .= $ext if defined $ext;
642  
643 if ($link_style eq '1-level' || $link_style eq 'all') {
644 push(@res, $store->_file(v2 => by => $digest => $v));
645 }
646 if ($link_style eq '2-level' || $link_style eq 'all') {
647 push(@res, $store->_file(v2 => by => $digest => substr($v, 0, 2) => $v));
648 }
649 }
650  
651 return @res;
652 }
653  
654 # Bad workaround for File::ExtAttr
655 package File::FStore::File::_DUMMY_FOR_XATTR {
656  
657 sub new {
658 my ($pkg, $fh) = @_;
659 return undef unless eval {require File::ExtAttr; File::ExtAttr->import; 1;};
660 return bless \$fh;
661 }
662 sub isa {
663 my ($self, $pkg) = @_;
664 return 1 if $pkg eq 'IO::Handle';
665 return $self->SUPER::isa($pkg);
666 }
667 sub fileno {
668 my ($self) = @_;
669 return ${$self}->fileno;
670 }
671 sub getfattr {
672 my ($self, $key) = @_;
673 return eval { $self->File::ExtAttr::getfattr($key, { namespace => 'user' }) };
674 }
675 sub setfattr {
676 my ($self, $key, $value) = @_;
677 return eval { $self->File::ExtAttr::setfattr($key => $value, { namespace => 'user' }) };
678 }
679 }
680  
681  
682 1;
683  
684 __END__
685  
686 =pod
687  
688 =encoding UTF-8
689  
690 =head1 NAME
691  
692 File::FStore::File - Module for interacting with file stores
693  
694 =head1 VERSION
695  
696 version v0.06
697  
698 =head1 SYNOPSIS
699  
700 use File::FStore;
701  
702 my File::FStore $store = File::FStore->new(path => '...');
703  
704 my File::FStore::File $file = $store->query(...);
705  
706 This package provides access to file level values.
707  
708 This package inherits from L<File::FStore::Base>, and L<Data::Identifier::Interface::Known>.
709  
710 =head1 METHODS
711  
712 =head2 dbname
713  
714 my $dbname = $file->dbname;
715  
716 This returns the name of the file relative to the store's data directory.
717  
718 B<Note:>
719 This method is generally not very useful for most applications.
720  
721 See also:
722 L</filename>,
723 L</open>.
724  
725 =head2 filename
726  
727 my $filename = $file->filename;
728  
729 This returns the filename within the store.
730 The filename is returned in a format that is suitable to be passed to operating system functions.
731  
732 B<Note:>
733 When possible L</open> should be preferred.
734  
735 See also:
736 L</open>.
737  
738 =head2 open
739  
740 my $fh = $file->open;
741  
742 $fh->binmode; # allow binary data.
743  
744 Opens the file and returns a filehandle.
745 The file is opened read-only (as all files in the store are read-only to begin with).
746  
747 B<Note:>
748 This module doesn't set the handle to binary mode similar to L<perlfunc/open>.
749 See L<perlfunc/binmode> for details.
750  
751 See also:
752 L</filename>.
753  
754 =head2 link_out
755  
756 $file->link_out($filename);
757  
758 Creates an hardlink to this file as C<$filename>.
759 C<die>s on any error.
760  
761 See also:
762 L<perlfunc/link>.
763  
764 =head2 symlink_out
765  
766 $file->symlink_out($filename);
767  
768 Creates an symlink to this file as C<$filename>.
769 C<die>s on any error.
770  
771 See also:
772 L<perlfunc/symlink>.
773  
774 =head2 update
775  
776 $file->update;
777 # or:
778 $file->update(%opts);
779  
780 Updates the file in the database. Also performs a verify of the file as part of the update.
781  
782 The following (all optional) options are supported:
783  
784 =over
785  
786 =item C<no_digests>
787  
788 This will try to skip digest calculation.
789  
790 =item C<on_pre_set>
791  
792 A callback that is called before any data is set (see L</set>) on this file.
793 C<$file> is passed as first argument.
794  
795 =item C<on_post_set>
796  
797 A callback that is called after all data is set (see L</set>) on this file.
798 C<$file> is passed as first argument.
799  
800 =back
801  
802 =head2 stat
803  
804 my @res = $file->stat;
805  
806 This method performs the same task and returns the same values as L<perlfunc/stat>.
807 In contrast however it C<die>s if the request cannot be performed. This however can only happen if the store is corruped.
808  
809 The value is cached. Therefore some attributes (mostly C<atime>) might be out of sync.
810 However those attributes are unreliable to begin with, hence the cache doesn't really make this worse.
811  
812 B<Note:>
813 If you plan to perform an L</open> on this file call that first and then this method.
814 This will improve performance and reduce the chance of race conditions.
815  
816 =head2 get
817  
818 my $value = $file->get($domain => $key);
819 # or:
820 my $hashref = $file->get($domain);
821 # or:
822 my $hashhashref = $file->get;
823  
824 Returns information about the file.
825 If a C<$domain> and C<$key> is given the value is returned as scalar.
826 If only a C<$domain> is given all values for that domain are returned as a hashref.
827 If no parameters are given a hashref with the domains as keys and the hashrefs of the per-domain values is returned.
828  
829 If a value is unknown this method C<die>s.
830  
831 The following domains are supported:
832  
833 =over
834  
835 =item C<properties>
836  
837 This domain contains flat properties of the file sich as it's size.
838  
839 See L</PROPERTIES>.
840  
841 =item C<digests>
842  
843 This domain contains digests for the file as known. Those are the I<final> digests.
844 If the file does not match the those values at this point it is corruped.
845  
846 The key is the digest name in universal tag (utag) format (e.g. C<sha-3-224>).
847  
848 =back
849  
850 =head2 set
851  
852 $file->set($domain => $key => $value);
853 # or:
854 $file->set($domain => {$key => $value});
855 # or:
856 $file->set({$domain => {$key => $value}});
857  
858 This sets a value on the file.
859 The value is checked against already known values.
860 If a value is set for a key that already holds a value this method C<die>s if the values missmatch.
861  
862 This method takes a domain-key-value triplet, or a domain and a hashref with multiple values, or
863 a single hashref with the domain(s) as keys and hashrefs with key-value pairs as values.
864  
865 See also:
866 L</get>.
867  
868 =head2 delete
869  
870 $file->delete;
871  
872 Removes the given file from the store.
873 This also unlinks all links within the store.
874  
875 If there is no hardlink outside the store to the given file it is
876 fully removed from the filesystem.
877  
878 B<Note:>
879 After this call B<no> future calls are allowed on this handle
880 or any other handle referencing the same file.
881  
882 =head2 sync_with_db
883  
884 $file->sync_with_db;
885 # or:
886 $file->sync_with_db(%opts);
887  
888 Syncs the file with the database.
889 It may read data from, and write data to the database related to this file.
890  
891 B<Note:>
892 This method calls L<Data::TagDB/in_transaction> with type C<rw>.
893  
894 It mainly operates on three tags:
895  
896 =over
897  
898 =item content
899  
900 The content tag is the tag that represents the state of this file (size, digests, ...)
901 (but not the filesystem object or other objects).
902  
903 See also L</contentise>.
904  
905 =item inode
906  
907 The inode tag represents the actual file on the filesystem.
908 This is the tag file system browsing software will use.
909  
910 The inode tag has the content tag as it's final state.
911  
912 See also L<File::Information::Base/inodeise>.
913  
914 =item proto
915  
916 The proto tag represents the work independent on the filesystem.
917 This is often used by software that implement some kind of catalogue.
918  
919 The proto tag has the content tag as a state, maybe as it's final state.
920  
921 =back
922  
923 The following (all optional) options are supported:
924  
925 =over
926  
927 =item C<autocreate>
928  
929 Whether tags should be automatically created if not yet part of the database.
930  
931 Defaults to false.
932  
933 See also L<Data::Identifier/as>.
934  
935 =item C<db>
936  
937 The database object to use.
938  
939 Defaults to the value returned by L</db>.
940  
941 =item C<final_of_proto>
942  
943 Whether this file is the final state of the proto tag (true value) or
944 just one of it's states (false value).
945  
946 Defaults to false.
947  
948 =item C<proto>
949  
950 The tag to be used as proto tag (if any).
951 This may be anything that L<Data::Identifier/as> will accept.
952  
953 Defaults to C<undef>.
954  
955 =back
956  
957 =head2 known
958  
959 my @list = File::FStore::File->known($class [, %opts ] );
960 # or:
961 my @list = $file->known($class [, %opts ] );
962  
963 (since v0.05)
964  
965 Lists known objects. See L<Data::Identifier::Interface::Known/known> for details.
966  
967 The following classes are defined:
968  
969 =over
970  
971 =item C<domains>
972  
973 The list of domains this module supports.
974  
975 =item C<properties>
976  
977 The list of keys for the C<properties> domain this module knows.
978  
979 =item C<digests>
980  
981 The list of keys for the C<domains> domain this module knows.
982 Note that actual support of those digests depend on installed modules and is not reflected by this list.
983  
984 =item C<link_styles>
985  
986 The list of supported link styles. See L<File::FStore/new>.
987  
988 =item C<store_styles>
989  
990 The list of supported store styles. See L<File::FStore/new>.
991  
992 =item C<other-tags>
993  
994 A list of other tags this module knows about.
995 This list is hardly useful for most operations.
996 However it can be used to prime a database.
997  
998 =back
999  
1000 =head1 PROPERTIES
1001  
1002 The following properties are known.
1003  
1004 =head2 size
1005  
1006 The file size in bytes.
1007  
1008 =head2 inode
1009  
1010 The inode number. The value is specific to the filesystem the file is on.
1011  
1012 =head2 mediasubtype
1013  
1014 The media subtype of the file.
1015  
1016 B<Warning:>
1017 This property is commonly very missunderstood.
1018 It is best to not set this manually and let the store maintain the value.
1019 Setting this value is acceptable when importing data from another store or from a L<File::Information::Base> object.
1020  
1021 B<Note:>
1022 Only values listed at L<https://www.iana.org/assignments/media-types/media-types.xhtml> are valid.
1023 Any value not listed by IANA is invalid.
1024  
1025 =head2 contentise
1026  
1027 The content ISE (identifier) value.
1028 This value is mainly maintained internally, however may be set early as a mean to verify the file integrity.
1029 For reading the value there is a special method L</contentise>.
1030  
1031 =head2 inodeise
1032  
1033 The inode ISE (identifier) value.
1034 This value represents the inode on the file system.
1035 It is mainly maintained internally, but used by and imported from external sources
1036 such as tagpool.
1037 The value is stable for the inode's lifetime.
1038 It may be different or the same if the inode number is reused.
1039 It is stable since when the inode was created and also doesn't change when the inode is written to (in contrast to L</contenise>.
1040  
1041 See also:
1042 L<File::Information::Base/get>.
1043  
1044 =head1 AUTHOR
1045  
1046 Philipp Schafft <lion@cpan.org>
1047  
1048 =head1 COPYRIGHT AND LICENSE
1049  
1050 This software is Copyright (c) 2025 by Philipp Schafft <lion@cpan.org>.
1051  
1052 This is free software, licensed under:
1053  
1054 The Artistic License 2.0 (GPL Compatible)
1055  
1056 =cut