FlatFile.pm 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. package Trog::Data::FlatFile;
  2. use v5.36;
  3. use re '/aa';
  4. use Carp qw{confess};
  5. use Fcntl qw{LOCK_EX SEEK_SET};
  6. use JSON::MaybeXS;
  7. use File::Slurper;
  8. use File::Copy;
  9. use Path::Tiny();
  10. use Capture::Tiny qw{capture_merged};
  11. use lib 'lib';
  12. use Trog::SQLite::TagIndex;
  13. use parent qw{Trog::DataModule};
  14. our $datastore = 'data/files';
  15. sub lang { 'Perl Regex in Quotemeta' }
  16. sub help { 'https://perldoc.perl.org/functions/quotemeta.html' }
  17. =head1 Trog::Data::FlatFile
  18. This data model has multiple drawbacks, but is "good enough" for most low-content and few editor applications.
  19. You can only post once per second due to it storing each post as a file named after the timestamp.
  20. =cut
  21. our $parser = JSON::MaybeXS->new( utf8 => 1 );
  22. # Initialize the list of posts by tag for all known tags.
  23. # This is because the list won't ever change between HUPs
  24. our @tags = Trog::SQLite::TagIndex::tags();
  25. our %posts_by_tag;
  26. sub read ( $self, $query = {} ) {
  27. $query->{limit} //= 25;
  28. #Optimize direct ID
  29. my @index;
  30. if ( $query->{id} ) {
  31. @index = ("$datastore/$query->{id}");
  32. }
  33. else {
  34. # Remove tags which we don't care about and sort to keep memoized memory usage down
  35. @{ $query->{tags} } = sort grep {
  36. my $t = $_;
  37. grep { $t eq $_ } @tags
  38. } @{ $query->{tags} };
  39. my $tagkey = join( '&', @{ $query->{tags} } );
  40. # Check against memoizer
  41. $posts_by_tag{$tagkey} //= [];
  42. @index = @{ $posts_by_tag{$tagkey} } if @{ $posts_by_tag{$tagkey} };
  43. if ( !@index && -f 'data/posts.db' ) { ## no critic (ProhibitFiletest_f) -- use the tag index, else fall back to _index()
  44. @index = map { "$datastore/$_" } Trog::SQLite::TagIndex::posts_for_tags( @{ $query->{tags} } );
  45. $posts_by_tag{$tagkey} = \@index;
  46. }
  47. @index = $self->_index() unless @index;
  48. }
  49. my @items;
  50. foreach my $item (@index) {
  51. my $slurped = eval { File::Slurper::read_text($item) };
  52. if ( !$slurped ) {
  53. print "Failed to Read $item:\n$@\n";
  54. next;
  55. }
  56. my $parsed;
  57. capture_merged {
  58. $parsed = eval { $parser->decode($slurped) }
  59. };
  60. if ( !$parsed ) {
  61. # Try and read it in binary in case it was encoded incorrectly the first time
  62. $slurped = eval { File::Slurper::read_binary($item) };
  63. $parsed = eval { $parser->decode($slurped) };
  64. if ( !$parsed ) {
  65. print "JSON Decode error on $item:\n$@\n";
  66. next;
  67. }
  68. }
  69. #XXX this imposes an inefficiency in itself, get() will filter uselessly again here
  70. my @filtered = $query->{raw} ? @$parsed : $self->filter( $query, @$parsed );
  71. push( @items, @filtered ) if @filtered;
  72. next if $query->{limit} == 0; # 0 = unlimited
  73. last if scalar(@items) == $query->{limit};
  74. }
  75. return \@items;
  76. }
  77. sub _index ($self) {
  78. confess "Can't find datastore in $datastore !" unless -d $datastore;
  79. opendir( my $dh, $datastore ) or confess;
  80. my @index = grep { -f } map { "$datastore/$_" } readdir $dh; ## no critic (ProhibitFiletest_f) -- listing names, nothing is opened
  81. closedir $dh;
  82. return sort { $b cmp $a } @index;
  83. }
  84. sub routes ($self) {
  85. return Trog::SQLite::TagIndex::routes();
  86. }
  87. sub aliases ($self) {
  88. return Trog::SQLite::TagIndex::aliases();
  89. }
  90. sub write ( $self, $data ) {
  91. foreach my $post (@$data) {
  92. my $file = "$datastore/$post->{id}";
  93. my $update = [$post];
  94. mkdir $datastore;
  95. # One locked handle for the whole read-modify-write. This used to be a
  96. # -f, then a separate read, then a separate truncating open; two workers
  97. # saving the same post could both read the existing revisions and then
  98. # each write back only their own, silently dropping the post's history.
  99. # '+>>' creates the file if it is not there, and never truncates.
  100. open( my $fh, '+>>', $file ) or confess "Could not open $file: $!";
  101. flock( $fh, LOCK_EX ) or confess "Could not lock $file: $!";
  102. seek( $fh, 0, SEEK_SET ) or confess "Could not rewind $file: $!";
  103. my $slurped = do { local $/; <$fh> };
  104. $update = [ ( @{ $parser->decode($slurped) }, $post ) ] if length( $slurped // '' );
  105. seek( $fh, 0, SEEK_SET ) or confess "Could not rewind $file: $!";
  106. truncate( $fh, 0 ) or confess "Could not truncate $file: $!";
  107. print {$fh} $parser->encode($update);
  108. close $fh;
  109. Trog::SQLite::TagIndex::add_post( $post, $self );
  110. }
  111. }
  112. sub count ($self) {
  113. my @index = $self->_index();
  114. return scalar(@index);
  115. }
  116. sub delete ( $self, @posts ) {
  117. foreach my $update (@posts) {
  118. unlink "$datastore/$update->{id}" or confess;
  119. Trog::SQLite::TagIndex::remove_post($update);
  120. }
  121. return 0;
  122. }
  123. sub tags ($self) {
  124. return Trog::SQLite::TagIndex::tags();
  125. }
  126. 1;