FlatFile.pm 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. package Trog::Data::FlatFile;
  2. use v5.36;
  3. use re '/aa';
  4. use Carp qw{confess};
  5. use Fcntl qw{LOCK_EX};
  6. use File::Basename ();
  7. use File::Path ();
  8. use JSON::MaybeXS;
  9. use File::Slurper;
  10. use File::Slurper::Temp();
  11. use File::Copy;
  12. use Path::Tiny();
  13. use Capture::Tiny qw{capture_merged};
  14. use lib 'lib';
  15. use Trog::Log qw{:all};
  16. use Trog::SQLite::TagIndex;
  17. use parent qw{Trog::DataModule};
  18. our $datastore = 'data/files';
  19. sub lang { 'Perl Regex in Quotemeta' }
  20. sub help { 'https://perldoc.perl.org/functions/quotemeta.html' }
  21. =head1 Trog::Data::FlatFile
  22. This data model has multiple drawbacks, but is "good enough" for most low-content and few editor applications.
  23. You can only post once per second due to it storing each post as a file named after the timestamp.
  24. =cut
  25. our $parser = JSON::MaybeXS->new( utf8 => 1 );
  26. # Initialize the list of posts by tag for all known tags.
  27. # This is because the list won't ever change between HUPs
  28. our @tags = Trog::SQLite::TagIndex::tags();
  29. our %posts_by_tag;
  30. sub read ( $self, $query = {} ) {
  31. $query->{limit} //= 25;
  32. #Optimize direct ID
  33. my @index;
  34. if ( $query->{id} ) {
  35. # Only when it's actually there. A miss here is the ordinary answer to
  36. # "is there a post with this id", which is what add() asks before every
  37. # single insert to decide between version 0 and a bump -- naming the
  38. # file regardless meant every new post reported itself as a failed read.
  39. # The other branch gets its paths from _index(), which greps -f, so this
  40. # is the only way a path that isn't there can reach the loop below.
  41. my $path = "$datastore/$query->{id}";
  42. @index = ($path) if -f $path; ## no critic (ProhibitFiletest_f) -- a missing post is a miss, not an error
  43. }
  44. else {
  45. # Remove tags which we don't care about and sort to keep memoized memory usage down
  46. @{ $query->{tags} } = sort grep {
  47. my $t = $_;
  48. grep { $t eq $_ } @tags
  49. } @{ $query->{tags} };
  50. my $tagkey = join( '&', @{ $query->{tags} } );
  51. # Check against memoizer
  52. $posts_by_tag{$tagkey} //= [];
  53. @index = @{ $posts_by_tag{$tagkey} } if @{ $posts_by_tag{$tagkey} };
  54. if ( !@index && -f 'data/posts.db' ) { ## no critic (ProhibitFiletest_f) -- use the tag index, else fall back to _index()
  55. @index = map { "$datastore/$_" } Trog::SQLite::TagIndex::posts_for_tags( @{ $query->{tags} } );
  56. $posts_by_tag{$tagkey} = \@index;
  57. }
  58. @index = $self->_index() unless @index;
  59. }
  60. my @items;
  61. foreach my $item (@index) {
  62. # Checked with defined() rather than truthiness so that an empty file
  63. # falls through to the JSON parser, which will say what is actually
  64. # wrong with it rather than blaming the read.
  65. my $slurped = eval { File::Slurper::read_text($item) };
  66. if ( !defined $slurped ) {
  67. WARN("Could not read post '$item': $@");
  68. next;
  69. }
  70. my $parsed;
  71. capture_merged {
  72. $parsed = eval { $parser->decode($slurped) }
  73. };
  74. if ( !$parsed ) {
  75. # Try and read it in binary in case it was encoded incorrectly the first time
  76. $slurped = eval { File::Slurper::read_binary($item) };
  77. $parsed = eval { $parser->decode($slurped) };
  78. if ( !$parsed ) {
  79. WARN("Could not decode post '$item': $@");
  80. next;
  81. }
  82. }
  83. #XXX this imposes an inefficiency in itself, get() will filter uselessly again here
  84. my @filtered = $query->{raw} ? @$parsed : $self->filter( $query, @$parsed );
  85. push( @items, @filtered ) if @filtered;
  86. next if $query->{limit} == 0; # 0 = unlimited
  87. last if scalar(@items) == $query->{limit};
  88. }
  89. return \@items;
  90. }
  91. sub _index ($self) {
  92. confess "Can't find datastore in $datastore !" unless -d $datastore;
  93. opendir( my $dh, $datastore ) or confess;
  94. my @index = grep { -f } map { "$datastore/$_" } readdir $dh; ## no critic (ProhibitFiletest_f) -- listing names, nothing is opened
  95. closedir $dh;
  96. return sort { $b cmp $a } @index;
  97. }
  98. sub routes ($self) {
  99. return Trog::SQLite::TagIndex::routes();
  100. }
  101. sub aliases ($self) {
  102. return Trog::SQLite::TagIndex::aliases();
  103. }
  104. sub write ( $self, $data ) {
  105. # The lock and the scratch file both live beside the datastore rather than
  106. # in it: _index() scans $datastore with readdir, and would otherwise hand
  107. # either of them to the JSON parser as though it were a post.
  108. my $spool = File::Basename::dirname($datastore);
  109. foreach my $post (@$data) {
  110. my $file = "$datastore/$post->{id}";
  111. File::Path::make_path($datastore);
  112. # Two separate races here, needing two separate answers.
  113. #
  114. # The lock is what stops a lost update. Without it two workers saving
  115. # the same post both read the existing N revisions and each write back
  116. # N+1, so one save vanishes: at three workers by 25 saves, about 30 of
  117. # 75 revisions survived. With it, all 75. It has to be taken on a
  118. # path that never gets renamed, hence a lockfile rather than the post.
  119. open( my $lock, '>>', "$spool/.write.lock" ) or confess "Could not open $spool/.write.lock: $!";
  120. flock( $lock, LOCK_EX ) or confess "Could not lock $spool/.write.lock: $!";
  121. my $slurped = eval { File::Slurper::read_binary($file) };
  122. my $update = length( $slurped // '' ) ? [ ( @{ $parser->decode($slurped) }, $post ) ] : [$post];
  123. # The rename is what stops a torn read. Every reader here takes no
  124. # lock, so writing in place lets one catch a half-written file: a few
  125. # hundred unparseable reads per hundred thousand, against none once the
  126. # write lands by rename. PERMS because File::Temp would otherwise
  127. # create a new post 0600, where a plain open honoured the umask.
  128. local $File::Slurper::Temp::FILE_TEMP_DIR = $spool;
  129. local $File::Slurper::Temp::FILE_TEMP_PERMS = oct('666') & ~umask;
  130. File::Slurper::Temp::write_binary( $file, $parser->encode($update) );
  131. close $lock;
  132. Trog::SQLite::TagIndex::add_post( $post, $self );
  133. }
  134. }
  135. sub count ($self) {
  136. my @index = $self->_index();
  137. return scalar(@index);
  138. }
  139. sub delete ( $self, @posts ) {
  140. foreach my $update (@posts) {
  141. unlink "$datastore/$update->{id}" or confess;
  142. Trog::SQLite::TagIndex::remove_post($update);
  143. }
  144. return 0;
  145. }
  146. sub tags ($self) {
  147. return Trog::SQLite::TagIndex::tags();
  148. }
  149. 1;