par_filecache.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. // FILECACHE :: https://github.com/prideout/par
  2. // Simple file-based LRU cache for blobs with content-addressable names.
  3. //
  4. // Each cached item is stored on disk as "{PREFIX}{NAME}", where {PREFIX}
  5. // is passed in when initializing the cache. You'll probably want to specify
  6. // a folder path for your prefix, including the trailing slash.
  7. //
  8. // Each item is divided into a payload (arbitrary size) and an optional header
  9. // (fixed size). The structure of the payload and header are completely up to
  10. // you. The list of items is stored in a text file at "{PREFIX}table", which
  11. // contains a list of names, timestamps, and byte counts. This table is loaded
  12. // only once, but is saved every time the client fetches a blob from the cache,
  13. // so that the most-recently-accessed timestamps are always up to date, even
  14. // when your application doesn't close gracefully.
  15. //
  16. // The MIT License
  17. // Copyright (c) 2015 Philip Rideout
  18. // -----------------------------------------------------------------------------
  19. // BEGIN PUBLIC API
  20. // -----------------------------------------------------------------------------
  21. #ifndef PAR_FILECACHE_H
  22. #define PAR_FILECACHE_H
  23. #ifdef __cplusplus
  24. extern "C" {
  25. #endif
  26. #include <stdint.h>
  27. #include <stdbool.h>
  28. // Initialize the filecache using the given prefix (usually a folder path with
  29. // a trailing slash) and the given maximum byte count. If items already exist
  30. // in the cache when this is called, they are not evicted. Cached items are
  31. // meant to persist from run to run.
  32. void par_filecache_init(char const* prefix, int maxsize);
  33. // Save a blob to the cache using the given unique name. If adding the blob
  34. // would cause the cache to exceed maxsize, the least-recently-used item is
  35. // evicted at this time.
  36. void par_filecache_save(char const* name, uint8_t const* payload,
  37. int payloadsize, uint8_t const* header, int headersize);
  38. // Check if the given blob is in the cache; if not, return 0. If so, return 1
  39. // and allocate new memory for payload. The caller should free the payload.
  40. // The header is preallocated so the caller needs to know its size beforehand.
  41. bool par_filecache_load(char const* name, uint8_t** payload, int* payloadsize,
  42. uint8_t* header, int headersize);
  43. // Remove all items from the cache.
  44. void par_filecache_evict_all();
  45. // Set this to zero if you wish to avoid LZ4 compression. I recommend using
  46. // it though, because it's very fast and it's a two-file library.
  47. #ifndef ENABLE_LZ4
  48. #define ENABLE_LZ4 0
  49. #endif
  50. #ifndef PAR_FILECACHE_VERBOSE
  51. #define PAR_FILECACHE_VERBOSE 0
  52. #endif
  53. #ifndef PAR_PI
  54. #define PAR_PI (3.14159265359)
  55. #define PAR_MIN(a, b) (a > b ? b : a)
  56. #define PAR_MAX(a, b) (a > b ? a : b)
  57. #define PAR_CLAMP(v, lo, hi) PAR_MAX(lo, PAR_MIN(hi, v))
  58. #define PAR_SWAP(T, A, B) { T tmp = B; B = A; A = tmp; }
  59. #define PAR_SQR(a) ((a) * (a))
  60. #endif
  61. #ifndef PAR_MALLOC
  62. #define PAR_MALLOC(T, N) ((T*) malloc(N * sizeof(T)))
  63. #define PAR_CALLOC(T, N) ((T*) calloc(N * sizeof(T), 1))
  64. #define PAR_REALLOC(T, BUF, N) ((T*) realloc(BUF, sizeof(T) * (N)))
  65. #define PAR_FREE(BUF) free(BUF)
  66. #endif
  67. #ifdef __cplusplus
  68. }
  69. #endif
  70. // -----------------------------------------------------------------------------
  71. // END PUBLIC API
  72. // -----------------------------------------------------------------------------
  73. #ifdef PAR_FILECACHE_IMPLEMENTATION
  74. #include <limits.h>
  75. #include <string.h>
  76. #include <assert.h>
  77. #include <stdio.h>
  78. #include <fcntl.h>
  79. #include <unistd.h>
  80. #include <stdlib.h>
  81. #include <stdint.h>
  82. #include <libgen.h>
  83. #include <time.h>
  84. #include <sys/stat.h>
  85. #ifndef PATH_MAX
  86. #define PATH_MAX 4096
  87. #endif
  88. #if ENABLE_LZ4
  89. #include "lz4.h"
  90. #endif
  91. static char * _par_strdup(char const* s)
  92. {
  93. if (s) {
  94. size_t l = strlen(s);
  95. char *s2 = (char*) malloc(l + 1);
  96. if (s2) {
  97. strcpy(s2, s);
  98. }
  99. return s2;
  100. }
  101. return 0;
  102. }
  103. #define PAR_MAX_ENTRIES 64
  104. typedef struct {
  105. time_t last_used_timestamp;
  106. uint64_t hashed_name;
  107. char const* name;
  108. int nbytes;
  109. } filecache_entry_t;
  110. typedef struct {
  111. filecache_entry_t entries[PAR_MAX_ENTRIES];
  112. int nentries;
  113. int totalbytes;
  114. } filecache_table_t;
  115. static void _update_table(char const* item_name, int item_size);
  116. static void _append_table(char const* item_name, int item_size);
  117. static void _read_or_create_tablefile();
  118. static void _save_tablefile();
  119. static void _evict_lru();
  120. static uint64_t _hash(char const* name);
  121. static char _fileprefix[PATH_MAX] = "./_cache.";
  122. static char _tablepath[PATH_MAX] = "./_cache.table";
  123. static int _maxtotalbytes = 1024 * 1024 * 16;
  124. static filecache_table_t* _table = 0;
  125. void par_filecache_init(char const* prefix, int maxsize)
  126. {
  127. size_t len = strlen(prefix);
  128. assert(len + 1 < PATH_MAX && "Cache prefix is too long");
  129. strncpy(_fileprefix, prefix, len + 1);
  130. strcpy(_tablepath, _fileprefix);
  131. strcat(_tablepath, "table");
  132. _maxtotalbytes = maxsize;
  133. }
  134. #if IOS_EXAMPLE
  135. NSString* getPrefix()
  136. {
  137. NSString* cachesFolder = [NSSearchPathForDirectoriesInDomains(
  138. NSCachesDirectory, NSUserDomainMask, YES) firstObject];
  139. NSError* error = nil;
  140. if (![[NSFileManager defaultManager] createDirectoryAtPath : cachesFolder
  141. withIntermediateDirectories : YES
  142. attributes : nil
  143. error : &error]) {
  144. NSLog(@ "MGMPlatformGetCachesFolder error: %@", error);
  145. return nil;
  146. }
  147. return [cachesFolder stringByAppendingString : @ "/_cache."];
  148. }
  149. #endif
  150. static bool par_filecache__read(void* dest, int nbytes, FILE* file)
  151. {
  152. int consumed = (int) fread(dest, nbytes, 1, file);
  153. return consumed == 1;
  154. }
  155. bool par_filecache_load(char const* name, uint8_t** payload, int* payloadsize,
  156. uint8_t* header, int headersize)
  157. {
  158. char qualified[PATH_MAX];
  159. size_t len = strlen(name);
  160. if (len == 0) {
  161. return false;
  162. }
  163. assert(len + strlen(_fileprefix) < PATH_MAX);
  164. strcpy(qualified, _fileprefix);
  165. strcat(qualified, name);
  166. if (access(qualified, F_OK) == -1) {
  167. return false;
  168. }
  169. FILE* cachefile = fopen(qualified, "rb");
  170. assert(cachefile && "Unable to open cache file for reading");
  171. fseek(cachefile, 0, SEEK_END);
  172. long fsize = ftell(cachefile);
  173. fseek(cachefile, 0, SEEK_SET);
  174. if (headersize > 0 && !par_filecache__read(header, headersize, cachefile)) {
  175. return false;
  176. }
  177. int32_t dnbytes;
  178. #if ENABLE_LZ4
  179. long cnbytes = fsize - headersize - sizeof(dnbytes);
  180. if (!par_filecache__read(&dnbytes, sizeof(dnbytes), cachefile)) {
  181. return false;
  182. }
  183. #else
  184. long cnbytes = fsize - headersize;
  185. dnbytes = (int32_t) cnbytes;
  186. #endif
  187. char* cbuff = (char*) malloc(cnbytes);
  188. if (!par_filecache__read(cbuff, (int) cnbytes, cachefile)) {
  189. return false;
  190. }
  191. #if ENABLE_LZ4
  192. char* dbuff = (char*) malloc(dnbytes);
  193. LZ4_decompress_safe(cbuff, dbuff, (int) cnbytes, dnbytes);
  194. free(cbuff);
  195. #else
  196. char* dbuff = cbuff;
  197. #endif
  198. fclose(cachefile);
  199. *payload = (uint8_t*) dbuff;
  200. *payloadsize = dnbytes;
  201. _update_table(name, (int) cnbytes);
  202. return true;
  203. }
  204. void par_filecache_save(char const* name, uint8_t const* payload,
  205. int payloadsize, uint8_t const* header, int headersize)
  206. {
  207. char qualified[PATH_MAX];
  208. size_t len = strlen(name);
  209. if (len == 0) {
  210. return;
  211. }
  212. assert(len + strlen(_fileprefix) < PATH_MAX);
  213. strcpy(qualified, _fileprefix);
  214. strcat(qualified, name);
  215. FILE* cachefile = fopen(qualified, "wb");
  216. assert(cachefile && "Unable to open cache file for writing");
  217. if (headersize > 0) {
  218. fwrite(header, 1, headersize, cachefile);
  219. }
  220. int csize = 0;
  221. if (payloadsize > 0) {
  222. #if ENABLE_LZ4
  223. int32_t nbytes = payloadsize;
  224. fwrite(&nbytes, 1, sizeof(nbytes), cachefile);
  225. int maxsize = LZ4_compressBound(nbytes);
  226. char* dst = (char*) malloc(maxsize);
  227. char const* src = (char const*) payload;
  228. assert(nbytes < LZ4_MAX_INPUT_SIZE);
  229. csize = LZ4_compress_default(src, dst, nbytes, maxsize);
  230. fwrite(dst, 1, csize, cachefile);
  231. free(dst);
  232. #else
  233. csize = payloadsize;
  234. int actual = (int) fwrite(payload, 1, csize, cachefile);
  235. if (actual < csize) {
  236. fclose(cachefile);
  237. remove(qualified);
  238. printf("Unable to save %s to cache (%d bytes)\n", name, csize);
  239. return;
  240. }
  241. #endif
  242. }
  243. fclose(cachefile);
  244. _update_table(name, csize + headersize);
  245. }
  246. void par_filecache_evict_all()
  247. {
  248. #if PAR_FILECACHE_VERBOSE
  249. printf("Evicting all.\n");
  250. #endif
  251. char qualified[PATH_MAX];
  252. if (!_table) {
  253. _read_or_create_tablefile();
  254. }
  255. filecache_entry_t* entry = _table->entries;
  256. for (int i = 0; i < _table->nentries; i++, entry++) {
  257. strcpy(qualified, _fileprefix);
  258. strcat(qualified, entry->name);
  259. #if PAR_FILECACHE_VERBOSE
  260. printf("Evicting %s\n", qualified);
  261. #endif
  262. remove(qualified);
  263. }
  264. _table->nentries = 0;
  265. _table->totalbytes = 0;
  266. remove(_tablepath);
  267. }
  268. // Adds the given item to the table and evicts the LRU items if the total cache
  269. // size exceeds the specified maxsize.
  270. static void _append_table(char const* item_name, int item_size)
  271. {
  272. time_t now = time(0);
  273. if (!_table) {
  274. _read_or_create_tablefile();
  275. }
  276. uint64_t hashed_name = _hash(item_name);
  277. int total = _table->totalbytes + item_size;
  278. while (_table->nentries >= PAR_MAX_ENTRIES || total > _maxtotalbytes) {
  279. assert(_table->nentries > 0 && "Cache size is too small.");
  280. _evict_lru();
  281. total = _table->totalbytes + item_size;
  282. }
  283. _table->totalbytes = total;
  284. filecache_entry_t* entry = &_table->entries[_table->nentries++];
  285. entry->last_used_timestamp = now;
  286. entry->hashed_name = hashed_name;
  287. entry->name = _par_strdup(item_name);
  288. entry->nbytes = item_size;
  289. _save_tablefile();
  290. }
  291. // Updates the timestamp associated with the given item.
  292. static void _update_table(char const* item_name, int item_size)
  293. {
  294. time_t now = time(0);
  295. if (!_table) {
  296. _read_or_create_tablefile();
  297. }
  298. uint64_t hashed_name = _hash(item_name);
  299. filecache_entry_t* entry = _table->entries;
  300. int i;
  301. for (i = 0; i < _table->nentries; i++, entry++) {
  302. if (entry->hashed_name == hashed_name) {
  303. break;
  304. }
  305. }
  306. if (i >= _table->nentries) {
  307. _append_table(item_name, item_size);
  308. return;
  309. }
  310. entry->last_used_timestamp = now;
  311. _save_tablefile();
  312. }
  313. static void _read_or_create_tablefile()
  314. {
  315. _table = (filecache_table_t*) calloc(sizeof(filecache_table_t), 1);
  316. FILE* fhandle = fopen(_tablepath, "r");
  317. if (!fhandle) {
  318. fhandle = fopen(_tablepath, "w");
  319. if (!fhandle) {
  320. mkdir(dirname(_tablepath), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
  321. fhandle = fopen(_tablepath, "w");
  322. }
  323. assert(fhandle && "Unable to create filecache info file.");
  324. } else {
  325. filecache_entry_t entry;
  326. char name[PATH_MAX];
  327. while (1) {
  328. int nargs = fscanf(fhandle, "%ld %d %s", &entry.last_used_timestamp,
  329. &entry.nbytes, name);
  330. if (nargs != 3) {
  331. break;
  332. }
  333. entry.name = _par_strdup(name);
  334. entry.hashed_name = _hash(entry.name);
  335. _table->entries[_table->nentries++] = entry;
  336. _table->totalbytes += entry.nbytes;
  337. }
  338. }
  339. fclose(fhandle);
  340. }
  341. static void _save_tablefile()
  342. {
  343. FILE* fhandle = fopen(_tablepath, "w");
  344. assert(fhandle && "Unable to create filecache info file.");
  345. filecache_entry_t* entry = _table->entries;
  346. for (int i = 0; i < _table->nentries; i++, entry++) {
  347. fprintf(fhandle, "%ld %d %s\n", entry->last_used_timestamp,
  348. entry->nbytes, entry->name);
  349. }
  350. fclose(fhandle);
  351. }
  352. static void _evict_lru()
  353. {
  354. const uint64_t never_evict = _hash("version");
  355. int oldest_index = -1;
  356. time_t oldest_time = LONG_MAX;
  357. filecache_entry_t* entry = _table->entries;
  358. for (int i = 0; i < _table->nentries; i++, entry++) {
  359. if (entry->hashed_name == never_evict) {
  360. continue;
  361. }
  362. if (entry->last_used_timestamp < oldest_time) {
  363. oldest_time = entry->last_used_timestamp;
  364. oldest_index = i;
  365. }
  366. }
  367. if (oldest_index > -1) {
  368. entry = _table->entries + oldest_index;
  369. char qualified[PATH_MAX];
  370. size_t len = strlen(entry->name);
  371. assert(len + strlen(_fileprefix) < PATH_MAX);
  372. strcpy(qualified, _fileprefix);
  373. strcat(qualified, entry->name);
  374. #if PAR_FILECACHE_VERBOSE
  375. printf("Evicting %s\n", entry->name);
  376. #endif
  377. remove(qualified);
  378. _table->totalbytes -= entry->nbytes;
  379. if (_table->nentries-- > 1) {
  380. *entry = _table->entries[_table->nentries];
  381. }
  382. }
  383. }
  384. // https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function
  385. static uint64_t _hash(char const* name)
  386. {
  387. const uint64_t OFFSET = 14695981039346656037ull;
  388. const uint64_t PRIME = 1099511628211ull;
  389. const unsigned char* str = (const unsigned char*) name;
  390. uint64_t hval = OFFSET;
  391. while (*str) {
  392. hval *= PRIME;
  393. hval ^= (uint64_t) *(str++);
  394. }
  395. return hval;
  396. }
  397. #undef PAR_MAX_ENTRIES
  398. #endif // PAR_FILECACHE_IMPLEMENTATION
  399. #endif // PAR_FILECACHE_H