FlatFile.pm 5.7 KB

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