forked from codesandbox/codesandbox-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.ts
More file actions
208 lines (173 loc) · 4.69 KB
/
cache.ts
File metadata and controls
208 lines (173 loc) · 4.69 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
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
// Responsible for consuming and syncing with the server/local cache
import localforage from 'localforage';
import _debug from '@codesandbox/common/lib/utils/debug';
import Manager from './manager';
import { SCRIPT_VERSION } from '..';
const debug = _debug('cs:compiler:cache');
const host = process.env.CODESANDBOX_HOST;
const MAX_CACHE_SIZE = 1024 * 1024 * 7;
let APICacheUsed = false;
try {
localforage.config({
name: 'CodeSandboxApp',
storeName: 'sandboxes', // Should be alphanumeric, with underscores.
description:
'Cached transpilations of the sandboxes, for faster initialization time.',
});
// Prewarm store
localforage.keys();
} catch (e) {
console.warn('Problems initializing IndexedDB store.');
console.warn(e);
}
function shouldSaveOnlineCache(firstRun: boolean, changes: number) {
if (!firstRun || changes > 0) {
return false;
}
if (!(window as any).__SANDBOX_DATA__) {
return true;
}
return false;
}
export function clearIndexedDBCache() {
return localforage.clear();
}
export async function saveCache(
sandboxId: string,
managerModuleToTranspile: any,
manager: Manager,
changes: number,
firstRun: boolean
) {
if (!sandboxId) {
return Promise.resolve(false);
}
const managerState = {
...(await manager.serialize({
entryPath: managerModuleToTranspile
? managerModuleToTranspile.path
: null,
optimizeForSize: true,
})),
};
try {
if (process.env.NODE_ENV === 'development') {
debug(
'Saving cache of ' +
(JSON.stringify(managerState).length / 1024).toFixed(2) +
'kb to indexedDB'
);
}
await localforage.setItem(manager.id, managerState);
} catch (e) {
if (process.env.NODE_ENV === 'development') {
console.error(e);
}
manager.clearCache();
}
if (shouldSaveOnlineCache(firstRun, changes) && SCRIPT_VERSION) {
const stringifiedManagerState = JSON.stringify(managerState);
if (stringifiedManagerState.length > MAX_CACHE_SIZE) {
return Promise.resolve(false);
}
debug(
'Saving cache of ' +
(stringifiedManagerState.length / 1024).toFixed(2) +
'kb to CodeSandbox API'
);
return window
.fetch(`${host}/api/v1/sandboxes/${sandboxId}/cache`, {
method: 'POST',
body: JSON.stringify({
version: SCRIPT_VERSION,
data: stringifiedManagerState,
}),
headers: {
'Content-Type': 'application/json',
},
})
.then(x => x.json())
.catch(e => {
if (process.env.NODE_ENV === 'development') {
console.error('Something went wrong while saving cache.');
console.error(e);
}
});
}
return Promise.resolve(false);
}
export function deleteAPICache(sandboxId: string): Promise<any> {
if (APICacheUsed) {
debug('Deleting cache of API');
return window
.fetch(`${host}/api/v1/sandboxes/${sandboxId}/cache`, {
method: 'DELETE',
body: JSON.stringify({
version: SCRIPT_VERSION,
}),
headers: {
'Content-Type': 'application/json',
},
})
.then(x => x.json())
.catch(e => {
console.error('Something went wrong while deleting cache.');
console.error(e);
});
}
return Promise.resolve(false);
}
function findCacheToUse(cache1, cache2) {
if (!cache1 && !cache2) {
return null;
}
if (cache1 && !cache2) {
return cache1;
}
if (cache2 && !cache1) {
return cache2;
}
return cache2.timestamp > cache1.timestamp ? cache2 : cache1;
}
export function ignoreNextCache() {
try {
localStorage.setItem('ignoreCache', 'true');
} catch (e) {
console.warn(e);
}
}
export async function consumeCache(manager: Manager) {
try {
const shouldIgnoreCache =
localStorage.getItem('ignoreCache') ||
localStorage.getItem('ignoreCacheDev');
if (shouldIgnoreCache) {
localStorage.removeItem('ignoreCache');
return false;
}
const cacheData = (window as any).__SANDBOX_DATA__;
const localData = await localforage.getItem(manager.id);
const cache = findCacheToUse(cacheData && cacheData.data, localData);
if (cache) {
const version = SCRIPT_VERSION;
if (cache.version === version) {
if (cache === localData) {
APICacheUsed = false;
} else {
APICacheUsed = true;
}
debug(
`Loading cache from ${cache === localData ? 'localStorage' : 'API'}`,
cache
);
await manager.load(cache);
return true;
}
}
return false;
} catch (e) {
console.warn('Problems consuming cache');
console.warn(e);
return false;
}
}