/
caching.js
236 lines (201 loc) 路 6.06 KB
/
caching.js
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
// @flow
export type SimpleCacheConfigurator = SimpleCacheConfiguratorFn &
SimpleCacheConfiguratorObj;
type SimpleCacheConfiguratorFn = {
(boolean): void,
<T>(handler: () => T): T,
};
type SimpleCacheConfiguratorObj = {
forever: () => void,
never: () => void,
using: <T>(handler: () => T) => T,
invalidate: <T>(handler: () => T) => T,
};
type CacheEntry<ResultT, SideChannel> = Array<{
value: ResultT,
valid: SideChannel => boolean,
}>;
export type { CacheConfigurator };
/**
* Given a function with a single argument, cache its results based on its argument and how it
* configures its caching behavior. Cached values are stored strongly.
*/
export function makeStrongCache<ArgT, ResultT, SideChannel>(
handler: (ArgT, CacheConfigurator<SideChannel>) => ResultT,
): (ArgT, SideChannel) => ResultT {
return makeCachedFunction(new Map(), handler);
}
/**
* Given a function with a single argument, cache its results based on its argument and how it
* configures its caching behavior. Cached values are stored weakly and the function argument must be
* an object type.
*/
export function makeWeakCache<
ArgT: {} | Array<*> | $ReadOnlyArray<*>,
ResultT,
SideChannel,
>(
handler: (ArgT, CacheConfigurator<SideChannel>) => ResultT,
): (ArgT, SideChannel) => ResultT {
// $FlowIssue https://github.com/facebook/flow/issues/4528
return makeCachedFunction(new WeakMap(), handler);
}
type CacheMap<ArgT, ResultT, SideChannel> =
| Map<ArgT, CacheEntry<ResultT, SideChannel>>
| WeakMap<ArgT, CacheEntry<ResultT, SideChannel>>;
function makeCachedFunction<
ArgT,
ResultT,
SideChannel,
// $FlowIssue https://github.com/facebook/flow/issues/4528
Cache: CacheMap<ArgT, ResultT, SideChannel>,
>(
callCache: Cache,
handler: (ArgT, CacheConfigurator<SideChannel>) => ResultT,
): (ArgT, SideChannel) => ResultT {
return function cachedFunction(arg, data) {
let cachedValue: CacheEntry<ResultT, SideChannel> | void = callCache.get(
arg,
);
if (cachedValue) {
for (const { value, valid } of cachedValue) {
if (valid(data)) return value;
}
}
const cache = new CacheConfigurator(data);
const value = handler(arg, cache);
if (!cache.configured()) cache.forever();
cache.deactivate();
switch (cache.mode()) {
case "forever":
cachedValue = [{ value, valid: () => true }];
callCache.set(arg, cachedValue);
break;
case "invalidate":
cachedValue = [{ value, valid: cache.validator() }];
callCache.set(arg, cachedValue);
break;
case "valid":
if (cachedValue) {
cachedValue.push({ value, valid: cache.validator() });
} else {
cachedValue = [{ value, valid: cache.validator() }];
callCache.set(arg, cachedValue);
}
}
return value;
};
}
class CacheConfigurator<SideChannel = void> {
_active: boolean = true;
_never: boolean = false;
_forever: boolean = false;
_invalidate: boolean = false;
_configured: boolean = false;
_pairs: Array<[mixed, (SideChannel) => mixed]> = [];
_data: SideChannel;
constructor(data: SideChannel) {
this._data = data;
}
simple() {
return makeSimpleConfigurator(this);
}
mode() {
if (this._never) return "never";
if (this._forever) return "forever";
if (this._invalidate) return "invalidate";
return "valid";
}
forever() {
if (!this._active) {
throw new Error("Cannot change caching after evaluation has completed.");
}
if (this._never) {
throw new Error("Caching has already been configured with .never()");
}
this._forever = true;
this._configured = true;
}
never() {
if (!this._active) {
throw new Error("Cannot change caching after evaluation has completed.");
}
if (this._forever) {
throw new Error("Caching has already been configured with .forever()");
}
this._never = true;
this._configured = true;
}
using<T>(handler: SideChannel => T): T {
if (!this._active) {
throw new Error("Cannot change caching after evaluation has completed.");
}
if (this._never || this._forever) {
throw new Error(
"Caching has already been configured with .never or .forever()",
);
}
this._configured = true;
const key = handler(this._data);
this._pairs.push([key, handler]);
return key;
}
invalidate<T>(handler: SideChannel => T): T {
if (!this._active) {
throw new Error("Cannot change caching after evaluation has completed.");
}
if (this._never || this._forever) {
throw new Error(
"Caching has already been configured with .never or .forever()",
);
}
this._invalidate = true;
this._configured = true;
const key = handler(this._data);
this._pairs.push([key, handler]);
return key;
}
validator(): SideChannel => boolean {
const pairs = this._pairs;
return (data: SideChannel) => pairs.every(([key, fn]) => key === fn(data));
}
deactivate() {
this._active = false;
}
configured() {
return this._configured;
}
}
function makeSimpleConfigurator(
cache: CacheConfigurator<any>,
): SimpleCacheConfigurator {
function cacheFn(val) {
if (typeof val === "boolean") {
if (val) cache.forever();
else cache.never();
return;
}
return cache.using(() => assertSimpleType(val()));
}
cacheFn.forever = () => cache.forever();
cacheFn.never = () => cache.never();
cacheFn.using = cb => cache.using(() => assertSimpleType(cb()));
cacheFn.invalidate = cb => cache.invalidate(() => assertSimpleType(cb()));
return (cacheFn: any);
}
// Types are limited here so that in the future these values can be used
// as part of Babel's caching logic.
type SimpleType = string | boolean | number | null | void;
export function assertSimpleType(value: mixed): SimpleType {
if (
value != null &&
typeof value !== "string" &&
typeof value !== "boolean" &&
typeof value !== "number"
) {
throw new Error(
"Cache keys must be either string, boolean, number, null, or undefined.",
);
}
return value;
}