File: cache.cpp

package info (click to toggle)
bibledit-cloud 5.1.036-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 250,636 kB
  • sloc: xml: 915,934; ansic: 261,349; cpp: 92,628; javascript: 32,542; sh: 4,915; makefile: 586; php: 69
file content (464 lines) | stat: -rw-r--r-- 13,714 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
/*
Copyright (©) 2003-2025 Teus Benschop.

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/


#include <database/cache.h>
#include <filter/url.h>
#include <filter/string.h>
#include <filter/date.h>
#include <filter/shell.h>
#include <database/sqlite.h>
#include <database/logs.h>
#include <database/logic.h>
#include <database/config/general.h>


// Databases resilience:
// They contain cached data.
// Rarely written to.
// Often read from.


namespace database::cache::sql {


constexpr auto max_book {100};

static std::string filename (std::string resource, int book)
{
  // Name of the database for this resource.
  resource = filter_url_clean_filename (resource);
  std::string book_fragment;
  if (book) {
    book_fragment = "_" + std::to_string (book);
  }
  return fragment () + resource + book_fragment;
}


std::string fragment ()
{
  return "cache_resource_";
}


std::string path (const std::string& resource, int book)
{
  return filter_url_create_path ({database_logic_databases (), filename (filter_url_urlencode (resource), book) + database::sqlite::suffix ()});
}


void create (const std::string& resource, int book)
{
  SqliteDatabase sql (filename (resource, book));
  
  sql.add ("CREATE TABLE IF NOT EXISTS cache (chapter integer, verse integer, value text);");
  sql.execute ();
  
  sql.clear ();
  
  sql.add ("CREATE TABLE IF NOT EXISTS ready (ready boolean);");
  sql.execute ();
}


void remove (const std::string& resource)
{
  for (int book = 0; book < max_book; book++) {
    remove (resource, book);
  }
}


void remove (const std::string& resource, int book)
{
  const std::string file = database::sqlite::get_file (filename (resource, book));
  if (file_or_dir_exists (file)) {
    filter_url_unlink (file);
  }
}


// Returns true if the cache for the $resource exists.
bool exists (const std::string& resource)
{
  for (int book = 0; book < max_book; book++) {
    if (exists (resource, book))
      return true;
  }
  return false;
}


// Returns true if the cache for the $resource $book exists.
bool exists (const std::string& resource, int book)
{
  const std::string file = database::sqlite::get_file (filename (resource, book));
  return file_or_dir_exists (file);
}


// Returns true if a cached value for $resource/book/chapter/verse exists.
bool exists (const std::string& resource, int book, int chapter, int verse)
{
  // If the the book-based cache exists, check existence from there.
  if (exists (resource, book)) {
    SqliteDatabase sql = SqliteDatabase (filename (resource, book));
    sql.add ("SELECT count(*) FROM cache WHERE chapter = ");
    sql.add (chapter);
    sql.add ("AND verse = ");
    sql.add (verse);
    sql.add (";");
    std::vector <std::string> result = sql.query () ["count(*)"];
    int count = 0;
    if (!result.empty ()) 
      count = filter::strings::convert_to_int (result.at(0));
    return (count > 0);
  }
  // Else if the previous cache layout exists, check that.
  if (exists (resource, 0)) {
    SqliteDatabase sql = SqliteDatabase (filename (resource, 0));
    sql.add ("SELECT count(*) FROM cache WHERE book =");
    sql.add (book);
    sql.add ("AND chapter = ");
    sql.add (chapter);
    sql.add ("AND verse = ");
    sql.add (verse);
    sql.add (";");
    std::vector <std::string> result = sql.query () ["count(*)"];
    int count = 0;
    if (!result.empty ()) 
      count = filter::strings::convert_to_int (result [0]);
    return (count > 0);
  }
  // Nothing exists.
  return false;
}


// Caches a value.
void cache (const std::string& resource, int book, int chapter, int verse, const std::string& value)
{
  SqliteDatabase sql (filename (resource, book));
  
  sql.clear ();
  sql.add ("DELETE FROM cache WHERE chapter = ");
  sql.add (chapter);
  sql.add ("AND verse = ");
  sql.add (verse);
  sql.add (";");
  sql.execute ();
  
  sql.clear ();
  sql.add ("INSERT INTO cache VALUES (");
  sql.add (chapter);
  sql.add (",");
  sql.add (verse);
  sql.add (",");
  sql.add (value);
  sql.add (");");
  sql.execute ();
}


// Retrieves a cached value.
std::string retrieve (const std::string& resource, const int book, const int chapter, const int verse)
{
  // If the the book-based cache exists, retrieve it from there.
  if (exists (resource, book)) {
    SqliteDatabase sql = SqliteDatabase (filename (resource, book));
    sql.add ("SELECT value FROM cache WHERE chapter = ");
    sql.add (chapter);
    sql.add ("AND verse = ");
    sql.add (verse);
    sql.add (";");
    const std::vector <std::string> result = sql.query () ["value"];
    if (result.empty ())
      return std::string();
    return result.at(0);
  }
  // Else if the previous cache layout exists, retrieve it from there.
  if (exists (resource, 0)) {
    SqliteDatabase sql = SqliteDatabase (filename (resource, 0));
    sql.add ("SELECT value FROM cache WHERE book =");
    sql.add (book);
    sql.add ("AND chapter = ");
    sql.add (chapter);
    sql.add ("AND verse = ");
    sql.add (verse);
    sql.add (";");
    const std::vector <std::string> result = sql.query () ["value"];
    if (result.empty ())
      return std::string();
    return result.at(0);
  }
  return std::string();
}


// Returns how many element are in cache $resource.
int count (const std::string& resource)
{
  int count = 0;
  // Book 0 is for the old layout. Book 1++ is for the new layout.
  for (int book = 0; book < max_book; book++) {
    if (exists (resource, book)) {
      count ++;
    }
  }
  return count;
}


// Return true if the database has loaded all its expected content.
bool ready (const std::string& resource, const int book)
{
  SqliteDatabase sql (filename (resource, book));
  sql.add ("SELECT ready FROM ready;");
  const std::vector <std::string> result = sql.query () ["ready"];
  if (!result.empty()) {
    const auto ready = result.at(0);
    return filter::strings::convert_to_bool (ready);
  }
  return false;
}


// Sets the 'ready' flag in the database.
void ready (const std::string& resource, const int book, const bool ready)
{
  SqliteDatabase sql (filename (resource, book));
  
  sql.clear ();
  sql.add ("DELETE FROM ready;");
  sql.execute ();
  
  sql.clear ();
  sql.add ("INSERT INTO ready VALUES (");
  sql.add (ready);
  sql.add (");");
  sql.execute ();
}


int size (const std::string& resource, const int book)
{
  const std::string file = database::sqlite::get_file (filename (resource, book));
  return filter_url_filesize (file);
}


} // namespace.


namespace database::cache::file {


static std::string full_path (std::string file)
{
  return filter_url_create_root_path ({database_logic_databases (), "cache", file});
}


// The purpose of splitting the file up into paths is
// to avoid that the cache folder would contain too many files
// and so would become slow.
static std::string split_file (std::string file)
{
  if (file.size () > 9) file.insert (9, "/");
  if (file.size () > 18) file.insert (18, "/");
  if (file.size () > 27) file.insert (27, "/");
  file.append (".txt");
  return file;
}


bool exists (std::string schema)
{
  schema = filter_url_clean_filename (schema);
  schema = database::cache::file::split_file (schema);
  schema = database::cache::file::full_path (schema);
  return file_or_dir_exists (schema);
}


void put (std::string schema, const std::string& contents)
{
  schema = filter_url_clean_filename (schema);
  schema = split_file (schema);
  schema = full_path (schema);
  const std::string path = filter_url_dirname (schema);
  if (!file_or_dir_exists (path)) 
    filter_url_mkdir (path);
  filter_url_file_put_contents (schema, contents);
}


std::string get (std::string schema)
{
  schema = filter_url_clean_filename (schema);
  schema = database::cache::file::split_file (schema);
  schema = database::cache::file::full_path (schema);
  return filter_url_file_get_contents (schema);
}


void remove (std::string schema)
{
  schema = filter_url_clean_filename (schema);
  schema = split_file (schema);
  schema = full_path (schema);
  filter_url_unlink (schema);
}


// Deletes expired cached items.
void trim (bool clear)
{
  if (clear)
    Database_Logs::log ("Clearing cache");
  
  // The directory that contains the file-based cache files.
  std::string path = database::cache::file::full_path ("");
  
  // Get the free space on the file system that contains the cache.
  std::string output, error;
  filter::shell::run (path, filter::shell::get_executable(filter::shell::Executable::df), {"."}, &output, &error);
  if (!error.empty ())
    Database_Logs::log (error);
  int percentage_disk_in_use {0};
  {
    const std::vector<std::string> bits = filter::strings::explode(output, ' ');
    for (const auto& bit : bits) {
      if (bit.find ("%") != std::string::npos) {
        percentage_disk_in_use = filter::strings::convert_to_int(bit);
        // If a real percentage was found, other than 0, then skip the remainder.
        // On macOS the first percentage found is %iused, so will be skipped.
        if (percentage_disk_in_use != 0)
          break;
      }
    }
  }
  Database_Logs::log ("Disk space in use is " + std::to_string(percentage_disk_in_use) + "%");
  
  // There have been instances that the cache takes up 4, 5, or 6 Gbytes in the Cloud.
  // If the cache is left untrimmed, the size can be even larger.
  // This leads to errors when the disk runs out of space.
  // Therefore it's good to remove cached files older than a couple of hours
  // in cases where disk space is tight.
  // Two hours.
  std::string minutes = "+120";
  // One day.
  if (percentage_disk_in_use < 70)
    minutes = "+1440";
  // One week.
  if (percentage_disk_in_use < 50)
    minutes = "+10080";
  
  // Handle clearing the cache immediately.
  if (clear)
    minutes = "+0";
  
  // Remove files that have not been modified for x minutes.
  // It uses a Linux shell command.
  // This can be done because it runs on the server only.
  // It used to do "cd /path/to/cache; find /path/to/cache ...".
  // This could remove the folder "cache" too.
  // After this folder was removed, no caching could take place anymore.
  // https://github.com/bibledit/cloud/issues/366
  // This was not visible on macOS, but it was visible on Linux.
  // The fix is to do "cd /path/to/cache; find . ...".
  output.clear ();
  error.clear ();
  filter::shell::run (path, filter::shell::get_executable(filter::shell::Executable::find), {".", "-amin", minutes, "-delete"}, &output, &error);
  if (!output.empty ()) Database_Logs::log (output);
  if (!error.empty ()) Database_Logs::log (error);
  
  // Remove empty directories.
  output.clear ();
  error.clear ();
  filter::shell::run (path, filter::shell::get_executable(filter::shell::Executable::find), {".", "-type", "d", "-empty", "-delete"}, &output, &error);
  if (!output.empty ()) Database_Logs::log (output);
  if (!error.empty ()) Database_Logs::log (error);
  
  // The directory that contains the database-based cache files.
  path = filter_url_create_root_path ({database_logic_databases ()});
  
  // The number of days to keep cached data depends on the percentage of the disk in use.
  // There have been instances that the cache takes up 4, 5, or 6 Gbytes in the Cloud.
  // This can be even more.
  // This may lead to errors when the disk runs out of space.
  // Therefore it's good to limit caches more if the space is tight.
  // By default keep the resources cache for 30 days.
  std::string days = "+30";
  // If keeping the resources cache for an extended period of time, keep it for a full year.
  if (database::config::general::get_keep_resources_cache_for_long())
    days = "+365";
  // If free disk space is tighter, keep the caches for a shorter period.
  if (percentage_disk_in_use > 80)
    days = "+14";
  if (percentage_disk_in_use > 85)
    days = "+7";
  if (percentage_disk_in_use > 90)
    days = "+1";
  
  // Handle clearing the cache immediately.
  if (clear)
    days = "0";
  
  Database_Logs::log ("Will remove resource caches not accessed for " + days + " days");
  
  // Remove database-based cached files that have not been modified for x days.
  output.clear ();
  error.clear ();
  filter::shell::run (path, filter::shell::get_executable(filter::shell::Executable::find), {path, "-name", database::cache::sql::fragment () + "*", "-atime", days, "-delete"}, &output, &error);
  if (!output.empty ()) Database_Logs::log (output);
  if (!error.empty ()) Database_Logs::log (error);
  
  if (clear)
    Database_Logs::log ("Ready clearing  cache");
}


} // namespace.


namespace database::cache {


// This returns true if the $html can be cached.
bool can_cache (const std::string& error, const std::string& html)
{
  // Normally if everything is fine, then caching is possible.
  bool cache = true;
  
  // Do not cache the data in an error situation.
  if (!error.empty()) cache = false;
  
  // Do not cache the data if Cloudflare does any kind of protection.
  // https://github.com/bibledit/cloud/issues/693.
  if (html.find ("Cloudflare") != std::string::npos) cache = false;
  
  return cache;
}


} // namespace.