-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileCache.cpp
More file actions
101 lines (76 loc) · 2.19 KB
/
Copy pathFileCache.cpp
File metadata and controls
101 lines (76 loc) · 2.19 KB
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
#include "FileCache.h"
#include "FileSystem.h"
#include "MimeTypes.h"
#include "Compression.h"
#include "ETag.h"
#include "LastModified.h"
#include "Logger.h"
#include "RequestInspector.h"
#include <iostream>
using namespace std;
unordered_map<string, FileCache::CacheEntry>
FileCache::cache;
std::mutex FileCache::mutex;
FileCache::CacheEntry
FileCache::get(const string& path)
{
lock_guard<std::mutex> lock(FileCache::mutex);
time_t currentModified =
FileSystem::getLastWriteTime(path);
auto it = cache.find(path);
// ------------------------------
// CACHE HIT
// ------------------------------
if(it != cache.end())
{
if(it->second.modifiedTime == currentModified)
{
RequestInspector::current().setMetadataCache("HIT");
RequestInspector::current().setFileCache("HIT", "File already loaded in memory");
return it->second;
}
RequestInspector::current().setMetadataCache("REFRESH");
RequestInspector::current().setFileCache("REFRESH", "File modified on disk");
}
else
{
RequestInspector::current().setMetadataCache("MISS");
RequestInspector::current().setFileCache("MISS", "First time loading file");
}
// ------------------------------
// Build new cache entry
// ------------------------------
CacheEntry entry;
entry.body =
FileSystem::readFile(path);
if(entry.body.empty())
{
return entry;
}
entry.modifiedTime = currentModified;
entry.fileSize =
FileSystem::getFileSize(path);
entry.mimeType =
MimeTypes::get(path);
entry.etag =
ETag::generate(path);
entry.lastModified =
LastModified::generate(path);
bool compressible =
entry.mimeType.find("text/") == 0
|| entry.mimeType == "application/javascript"
|| entry.mimeType == "application/json"
|| entry.mimeType == "image/svg+xml";
if(compressible)
{
entry.gzipBody =
Compression::gzip(entry.body);
}
cache[path] = entry;
return entry;
}
void FileCache::clear()
{
lock_guard<std::mutex> lock(FileCache::mutex);
cache.clear();
}