FlatFile.pm 7.4 KB

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