FlatFile.pm 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. # Enough for the page that was asked for, not one page's worth. get()
  88. # paginates *after* this, so stopping at limit meant it had nothing left
  89. # to slice for page two and every page but the first came back empty --
  90. # offset pagination simply did not work on this model.
  91. #
  92. # >= rather than ==, because a file holds every version of its post and
  93. # one of them can push @items past the mark in a single step, which the
  94. # equality test would then never match.
  95. my $needed = $query->{limit} * ( $query->{page} || 1 );
  96. last if scalar(@items) >= $needed;
  97. }
  98. return \@items;
  99. }
  100. sub _index ($self) {
  101. confess "Can't find datastore in $datastore !" unless -d $datastore;
  102. opendir( my $dh, $datastore ) or confess;
  103. my @index = grep { -f } map { "$datastore/$_" } readdir $dh; ## no critic (ProhibitFiletest_f) -- listing names, nothing is opened
  104. closedir $dh;
  105. return sort { $b cmp $a } @index;
  106. }
  107. sub routes ($self) {
  108. return Trog::SQLite::TagIndex::routes();
  109. }
  110. sub aliases ($self) {
  111. return Trog::SQLite::TagIndex::aliases();
  112. }
  113. sub write ( $self, $data ) {
  114. # The lock and the scratch file both live beside the datastore rather than
  115. # in it: _index() scans $datastore with readdir, and would otherwise hand
  116. # either of them to the JSON parser as though it were a post.
  117. my $spool = File::Basename::dirname($datastore);
  118. foreach my $post (@$data) {
  119. # Or the write lands on the datastore directory itself: "$datastore/"
  120. # is a directory, rename() onto it fails, and the error names File::
  121. # Slurper rather than the post that had no id. add() will not produce
  122. # one, but nothing else guarantees a caller went through add().
  123. confess "Cannot write a post with no id" unless length( $post->{id} // '' );
  124. my $file = "$datastore/$post->{id}";
  125. File::Path::make_path($datastore);
  126. # Two separate races here, needing two separate answers.
  127. #
  128. # The lock is what stops a lost update. Without it two workers saving
  129. # the same post both read the existing N revisions and each write back
  130. # N+1, so one save vanishes: at three workers by 25 saves, about 30 of
  131. # 75 revisions survived. With it, all 75. It has to be taken on a
  132. # path that never gets renamed, hence a lockfile rather than the post.
  133. open( my $lock, '>>', "$spool/.write.lock" ) or confess "Could not open $spool/.write.lock: $!";
  134. flock( $lock, LOCK_EX ) or confess "Could not lock $spool/.write.lock: $!";
  135. my $slurped = eval { File::Slurper::read_binary($file) };
  136. my $update = length( $slurped // '' ) ? [ ( @{ $parser->decode($slurped) }, $post ) ] : [$post];
  137. # The rename is what stops a torn read. Every reader here takes no
  138. # lock, so writing in place lets one catch a half-written file: a few
  139. # hundred unparseable reads per hundred thousand, against none once the
  140. # write lands by rename. PERMS because File::Temp would otherwise
  141. # create a new post 0600, where a plain open honoured the umask.
  142. local $File::Slurper::Temp::FILE_TEMP_DIR = $spool;
  143. local $File::Slurper::Temp::FILE_TEMP_PERMS = oct('666') & ~umask;
  144. File::Slurper::Temp::write_binary( $file, $parser->encode($update) );
  145. close $lock;
  146. Trog::SQLite::TagIndex::add_post( $post, $self );
  147. }
  148. }
  149. sub count ($self) {
  150. my @index = $self->_index();
  151. return scalar(@index);
  152. }
  153. sub delete ( $self, @posts ) {
  154. foreach my $update (@posts) {
  155. unlink "$datastore/$update->{id}" or confess;
  156. Trog::SQLite::TagIndex::remove_post($update);
  157. }
  158. return 0;
  159. }
  160. sub tags ($self) {
  161. return Trog::SQLite::TagIndex::tags();
  162. }
  163. 1;