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. #endif // PAR_FILECACHE_H
  71. // -----------------------------------------------------------------------------
  72. // END PUBLIC API
  73. // -----------------------------------------------------------------------------
  74. #ifdef PAR_FILECACHE_IMPLEMENTATION
  75. #include <limits.h>
  76. #include <string.h>
  77. #include <assert.h>
  78. #include <stdio.h>
  79. #include <fcntl.h>
  80. #include <unistd.h>
  81. #include <stdlib.h>
  82. #include <stdint.h>
  83. #include <libgen.h>
  84. #include <time.h>
  85. #include <sys/stat.h>
  86. #ifndef PATH_MAX
  87. #define PATH_MAX 4096
  88. #endif
  89. #if ENABLE_LZ4
  90. #include "lz4.h"
  91. #endif
  92. static char * _par_strdup(char const* s)
  93. {
  94. if (s) {
  95. size_t l = strlen(s);
  96. char *s2 = (char*) malloc(l + 1);
  97. if (s2) {
  98. strcpy(s2, s);
  99. }
  100. return s2;
  101. }
  102. return 0;
  103. }
  104. #define PAR_MAX_ENTRIES 64
  105. typedef struct {
  106. time_t last_used_timestamp;
  107. uint64_t hashed_name;
  108. char const* name;
  109. int nbytes;
  110. } filecache_entry_t;
  111. typedef struct {
  112. filecache_entry_t entries[PAR_MAX_ENTRIES];
  113. int nentries;
  114. int totalbytes;
  115. } filecache_table_t;
  116. static void _update_table(char const* item_name, int item_size);
  117. static void _append_table(char const* item_name, int item_size);
  118. static void _read_or_create_tablefile();
  119. static void _save_tablefile();
  120. static void _evict_lru();
  121. static uint64_t _hash(char const* name);
  122. static char _fileprefix[PATH_MAX] = "./_cache.";
  123. static char _tablepath[PATH_MAX] = "./_cache.table";
  124. static int _maxtotalbytes = 1024 * 1024 * 16;
  125. static filecache_table_t* _table = 0;
  126. void par_filecache_init(char const* prefix, int maxsize)
  127. {
  128. size_t len = strlen(prefix);
  129. assert(len + 1 < PATH_MAX && "Cache prefix is too long");
  130. strncpy(_fileprefix, prefix, len + 1);
  131. strcpy(_tablepath, _fileprefix);
  132. strcat(_tablepath, "table");
  133. _maxtotalbytes = maxsize;
  134. }
  135. #if IOS_EXAMPLE
  136. NSString* getPrefix()
  137. {
  138. NSString* cachesFolder = [NSSearchPathForDirectoriesInDomains(
  139. NSCachesDirectory, NSUserDomainMask, YES) firstObject];
  140. NSError* error = nil;
  141. if (![[NSFileManager defaultManager] createDirectoryAtPath : cachesFolder
  142. withIntermediateDirectories : YES
  143. attributes : nil
  144. error : &error]) {
  145. NSLog(@ "MGMPlatformGetCachesFolder error: %@", error);
  146. return nil;
  147. }
  148. return [cachesFolder stringByAppendingString : @ "/_cache."];
  149. }
  150. #endif
  151. static bool par_filecache__read(void* dest, int nbytes, FILE* file)
  152. {
  153. int consumed = (int) fread(dest, nbytes, 1, file);
  154. return consumed == 1;
  155. }
  156. bool par_filecache_load(char const* name, uint8_t** payload, int* payloadsize,
  157. uint8_t* header, int headersize)
  158. {
  159. char qualified[PATH_MAX];
  160. size_t len = strlen(name);
  161. if (len == 0) {
  162. return false;
  163. }
  164. assert(len + strlen(_fileprefix) < PATH_MAX);
  165. strcpy(qualified, _fileprefix);
  166. strcat(qualified, name);
  167. if (access(qualified, F_OK) == -1) {
  168. return false;
  169. }
  170. FILE* cachefile = fopen(qualified, "rb");
  171. assert(cachefile && "Unable to open cache file for reading");
  172. fseek(cachefile, 0, SEEK_END);
  173. long fsize = ftell(cachefile);
  174. fseek(cachefile, 0, SEEK_SET);
  175. if (headersize > 0 && !par_filecache__read(header, headersize, cachefile)) {
  176. return false;
  177. }
  178. int32_t dnbytes;
  179. #if ENABLE_LZ4
  180. long cnbytes = fsize - headersize - sizeof(dnbytes);
  181. if (!par_filecache__read(&dnbytes, sizeof(dnbytes), cachefile)) {
  182. return false;
  183. }
  184. #else
  185. long cnbytes = fsize - headersize;
  186. dnbytes = (int32_t) cnbytes;
  187. #endif
  188. char* cbuff = (char*) malloc(cnbytes);
  189. if (!par_filecache__read(cbuff, cnbytes, cachefile)) {
  190. return false;
  191. }
  192. #if ENABLE_LZ4
  193. char* dbuff = (char*) malloc(dnbytes);
  194. LZ4_decompress_safe(cbuff, dbuff, (int) cnbytes, dnbytes);
  195. free(cbuff);
  196. #else
  197. char* dbuff = cbuff;
  198. #endif
  199. fclose(cachefile);
  200. *payload = (uint8_t*) dbuff;
  201. *payloadsize = dnbytes;
  202. _update_table(name, (int) cnbytes);
  203. return true;
  204. }
  205. void par_filecache_save(char const* name, uint8_t const* payload,
  206. int payloadsize, uint8_t const* header, int headersize)
  207. {
  208. char qualified[PATH_MAX];
  209. size_t len = strlen(name);
  210. if (len == 0) {
  211. return;
  212. }
  213. assert(len + strlen(_fileprefix) < PATH_MAX);
  214. strcpy(qualified, _fileprefix);
  215. strcat(qualified, name);
  216. FILE* cachefile = fopen(qualified, "wb");
  217. assert(cachefile && "Unable to open cache file for writing");
  218. if (headersize > 0) {
  219. fwrite(header, 1, headersize, cachefile);
  220. }
  221. int csize = 0;
  222. if (payloadsize > 0) {
  223. #if ENABLE_LZ4
  224. int32_t nbytes = payloadsize;
  225. fwrite(&nbytes, 1, sizeof(nbytes), cachefile);
  226. int maxsize = LZ4_compressBound(nbytes);
  227. char* dst = (char*) malloc(maxsize);
  228. char const* src = (char const*) payload;
  229. assert(nbytes < LZ4_MAX_INPUT_SIZE);
  230. csize = LZ4_compress_default(src, dst, nbytes, maxsize);
  231. fwrite(dst, 1, csize, cachefile);
  232. free(dst);
  233. #else
  234. csize = payloadsize;
  235. int actual = (int) fwrite(payload, 1, csize, cachefile);
  236. if (actual < csize) {
  237. fclose(cachefile);
  238. remove(qualified);
  239. printf("Unable to save %s to cache (%d bytes)\n", name, csize);
  240. return;
  241. }
  242. #endif
  243. }
  244. fclose(cachefile);
  245. _update_table(name, csize + headersize);
  246. }
  247. void par_filecache_evict_all()
  248. {
  249. #if PAR_FILECACHE_VERBOSE
  250. printf("Evicting all.\n");
  251. #endif
  252. char qualified[PATH_MAX];
  253. if (!_table) {
  254. _read_or_create_tablefile();
  255. }
  256. filecache_entry_t* entry = _table->entries;
  257. for (int i = 0; i < _table->nentries; i++, entry++) {
  258. strcpy(qualified, _fileprefix);
  259. strcat(qualified, entry->name);
  260. #if PAR_FILECACHE_VERBOSE
  261. printf("Evicting %s\n", qualified);
  262. #endif
  263. remove(qualified);
  264. }
  265. _table->nentries = 0;
  266. _table->totalbytes = 0;
  267. remove(_tablepath);
  268. }
  269. // Adds the given item to the table and evicts the LRU items if the total cache
  270. // size exceeds the specified maxsize.
  271. static void _append_table(char const* item_name, int item_size)
  272. {
  273. time_t now = time(0);
  274. if (!_table) {
  275. _read_or_create_tablefile();
  276. }
  277. uint64_t hashed_name = _hash(item_name);
  278. int total = _table->totalbytes + item_size;
  279. while (_table->nentries >= PAR_MAX_ENTRIES || total > _maxtotalbytes) {
  280. assert(_table->nentries > 0 && "Cache size is too small.");
  281. _evict_lru();
  282. total = _table->totalbytes + item_size;
  283. }
  284. _table->totalbytes = total;
  285. filecache_entry_t* entry = &_table->entries[_table->nentries++];
  286. entry->last_used_timestamp = now;
  287. entry->hashed_name = hashed_name;
  288. entry->name = _par_strdup(item_name);
  289. entry->nbytes = item_size;
  290. _save_tablefile();
  291. }
  292. // Updates the timestamp associated with the given item.
  293. static void _update_table(char const* item_name, int item_size)
  294. {
  295. time_t now = time(0);
  296. if (!_table) {
  297. _read_or_create_tablefile();
  298. }
  299. uint64_t hashed_name = _hash(item_name);
  300. filecache_entry_t* entry = _table->entries;
  301. int i;
  302. for (i = 0; i < _table->nentries; i++, entry++) {
  303. if (entry->hashed_name == hashed_name) {
  304. break;
  305. }
  306. }
  307. if (i >= _table->nentries) {
  308. _append_table(item_name, item_size);
  309. return;
  310. }
  311. entry->last_used_timestamp = now;
  312. _save_tablefile();
  313. }
  314. static void _read_or_create_tablefile()
  315. {
  316. _table = (filecache_table_t*) calloc(sizeof(filecache_table_t), 1);
  317. FILE* fhandle = fopen(_tablepath, "r");
  318. if (!fhandle) {
  319. fhandle = fopen(_tablepath, "w");
  320. if (!fhandle) {
  321. mkdir(dirname(_tablepath), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
  322. fhandle = fopen(_tablepath, "w");
  323. }
  324. assert(fhandle && "Unable to create filecache info file.");
  325. } else {
  326. filecache_entry_t entry;
  327. char name[PATH_MAX];
  328. while (1) {
  329. int nargs = fscanf(fhandle, "%ld %d %s", &entry.last_used_timestamp,
  330. &entry.nbytes, name);
  331. if (nargs != 3) {
  332. break;
  333. }
  334. entry.name = _par_strdup(name);
  335. entry.hashed_name = _hash(entry.name);
  336. _table->entries[_table->nentries++] = entry;
  337. _table->totalbytes += entry.nbytes;
  338. }
  339. }
  340. fclose(fhandle);
  341. }
  342. static void _save_tablefile()
  343. {
  344. FILE* fhandle = fopen(_tablepath, "w");
  345. assert(fhandle && "Unable to create filecache info file.");
  346. filecache_entry_t* entry = _table->entries;
  347. for (int i = 0; i < _table->nentries; i++, entry++) {
  348. fprintf(fhandle, "%ld %d %s\n", entry->last_used_timestamp,
  349. entry->nbytes, entry->name);
  350. }
  351. fclose(fhandle);
  352. }
  353. static void _evict_lru()
  354. {
  355. const uint64_t never_evict = _hash("version");
  356. int oldest_index = -1;
  357. time_t oldest_time = LONG_MAX;
  358. filecache_entry_t* entry = _table->entries;
  359. for (int i = 0; i < _table->nentries; i++, entry++) {
  360. if (entry->hashed_name == never_evict) {
  361. continue;
  362. }
  363. if (entry->last_used_timestamp < oldest_time) {
  364. oldest_time = entry->last_used_timestamp;
  365. oldest_index = i;
  366. }
  367. }
  368. if (oldest_index > -1) {
  369. entry = _table->entries + oldest_index;
  370. char qualified[PATH_MAX];
  371. size_t len = strlen(entry->name);
  372. assert(len + strlen(_fileprefix) < PATH_MAX);
  373. strcpy(qualified, _fileprefix);
  374. strcat(qualified, entry->name);
  375. #if PAR_FILECACHE_VERBOSE
  376. printf("Evicting %s\n", entry->name);
  377. #endif
  378. remove(qualified);
  379. _table->totalbytes -= entry->nbytes;
  380. if (_table->nentries-- > 1) {
  381. *entry = _table->entries[_table->nentries];
  382. }
  383. }
  384. }
  385. // https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function
  386. static uint64_t _hash(char const* name)
  387. {
  388. const uint64_t OFFSET = 14695981039346656037ull;
  389. const uint64_t PRIME = 1099511628211ull;
  390. const unsigned char* str = (const unsigned char*) name;
  391. uint64_t hval = OFFSET;
  392. while (*str) {
  393. hval *= PRIME;
  394. hval ^= (uint64_t) *(str++);
  395. }
  396. return hval;
  397. }
  398. #undef PAR_MAX_ENTRIES
  399. #endif // PAR_FILECACHE_IMPLEMENTATION