FlatFile.pm 7.4 KB

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