Debian Codegraph @

packages/babel-core/src/config/caching.ts

raw ◀ ▶
1 Debian patch touch this file
1 import gensync from "gensync";
2 import type { Handler } from "gensync";
3 import {
4 maybeAsync,
5 isAsync,
6 onFirstPause,
7 waitFor,
8 isThenable,
9 } from "../gensync-utils/async";
10 import { isIterableIterator } from "./util";
11
12 export type { CacheConfigurator };
13
14 export type SimpleCacheConfigurator = {
15 (forever: boolean): void;
16 <T>(handler: () => T): T;
17
18 forever: () => void;
19 never: () => void;
20 using: <T>(handler: () => T) => T;
21 invalidate: <T>(handler: () => T) => T;
22 };
23
24 export type CacheEntry<ResultT, SideChannel> = Array<{
25 value: ResultT;
26 valid: (channel: SideChannel) => Handler<boolean>;
27 }>;
28
29 const synchronize = <ArgsT extends unknown[], ResultT>(
30 gen: (...args: ArgsT) => Handler<ResultT>,
31 ): ((...args: ArgsT) => ResultT) => {
32 return gensync(gen).sync;
33 };
34
35 // eslint-disable-next-line require-yield
36 function* genTrue() {
37 return true;
38 }
39
40 export function makeWeakCache<ArgT extends object, ResultT, SideChannel>(
41 handler: (
42 arg: ArgT,
43 cache: CacheConfigurator<SideChannel>,
44 ) => Handler<ResultT> | ResultT,
45 ): (arg: ArgT, data: SideChannel) => Handler<ResultT> {
46 return makeCachedFunction<ArgT, ResultT, SideChannel>(WeakMap, handler);
47 }
48
49 export function makeWeakCacheSync<ArgT extends object, ResultT, SideChannel>(
50 handler: (arg: ArgT, cache?: CacheConfigurator<SideChannel>) => ResultT,
51 ): (arg: ArgT, data?: SideChannel) => ResultT {
52 return synchronize<[ArgT, SideChannel], ResultT>(
53 makeWeakCache<ArgT, ResultT, SideChannel>(handler),
54 );
55 }
56
57 export function makeStrongCache<ArgT, ResultT, SideChannel>(
58 handler: (
59 arg: ArgT,
60 cache: CacheConfigurator<SideChannel>,
61 ) => Handler<ResultT> | ResultT,
62 ): (arg: ArgT, data: SideChannel) => Handler<ResultT> {
63 return makeCachedFunction<ArgT, ResultT, SideChannel>(Map, handler);
64 }
65
66 export function makeStrongCacheSync<ArgT, ResultT, SideChannel>(
67 handler: (arg: ArgT, cache?: CacheConfigurator<SideChannel>) => ResultT,
68 ): (arg: ArgT, data?: SideChannel) => ResultT {
69 return synchronize<[ArgT, SideChannel], ResultT>(
70 makeStrongCache<ArgT, ResultT, SideChannel>(handler),
71 );
72 }
73
74 /* NOTE: Part of the logic explained in this comment is explained in the
75 * getCachedValueOrWait and setupAsyncLocks functions.
76 *
77 * > There are only two hard things in Computer Science: cache invalidation and naming things.
78 * > -- Phil Karlton
79 *
80 * I don't know if Phil was also thinking about handling a cache whose invalidation function is
81 * defined asynchronously is considered, but it is REALLY hard to do correctly.
82 *
83 * The implemented logic (only when gensync is run asynchronously) is the following:
84 * 1. If there is a valid cache associated to the current "arg" parameter,
85 * a. RETURN the cached value
86 * 3. If there is a FinishLock associated to the current "arg" parameter representing a valid cache,
87 * a. Wait for that lock to be released
88 * b. RETURN the value associated with that lock
89 * 5. Start executing the function to be cached
90 * a. If it pauses on a promise, then
91 * i. Let FinishLock be a new lock
92 * ii. Store FinishLock as associated to the current "arg" parameter
93 * iii. Wait for the function to finish executing
94 * iv. Release FinishLock
95 * v. Send the function result to anyone waiting on FinishLock
96 * 6. Store the result in the cache
97 * 7. RETURN the result
98 */
99 function makeCachedFunction<ArgT, ResultT, SideChannel>(
100 CallCache: new <Cached>() => CacheMap<ArgT, Cached, SideChannel>,
101 handler: (
102 arg: ArgT,
103 cache: CacheConfigurator<SideChannel>,
104 ) => Handler<ResultT> | ResultT,
105 ): (arg: ArgT, data: SideChannel) => Handler<ResultT> {
106 const callCacheSync = new CallCache<ResultT>();
107 const callCacheAsync = new CallCache<ResultT>();
108 const futureCache = new CallCache<Lock<ResultT>>();
109
110 return function* cachedFunction(arg: ArgT, data: SideChannel) {
111 const asyncContext = yield* isAsync();
112 const callCache = asyncContext ? callCacheAsync : callCacheSync;
113
114 const cached = yield* getCachedValueOrWait<ArgT, ResultT, SideChannel>(
115 asyncContext,
116 callCache,
117 futureCache,
118 arg,
119 data,
120 );
121 if (cached.valid) return cached.value;
122
123 const cache = new CacheConfigurator(data);
124
125 const handlerResult: Handler<ResultT> | ResultT = handler(arg, cache);
126
127 let finishLock: Lock<ResultT>;
128 let value: ResultT;
129
130 if (isIterableIterator(handlerResult)) {
131 value = yield* onFirstPause(handlerResult, () => {
132 finishLock = setupAsyncLocks(cache, futureCache, arg);
133 });
134 } else {
135 value = handlerResult;
136 }
137
138 updateFunctionCache(callCache, cache, arg, value);
139
140 if (finishLock) {
141 futureCache.delete(arg);
142 finishLock.release(value);
143 }
144
145 return value;
146 };
147 }
148
149 type CacheMap<ArgT, ResultT, SideChannel> =
150 | Map<ArgT, CacheEntry<ResultT, SideChannel>>
151 // @ts-expect-error todo(flow->ts): add `extends object` constraint to ArgT
152 | WeakMap<ArgT, CacheEntry<ResultT, SideChannel>>;
153
154 function* getCachedValue<ArgT, ResultT, SideChannel>(
155 cache: CacheMap<ArgT, ResultT, SideChannel>,
156 arg: ArgT,
157 data: SideChannel,
158 ): Handler<{ valid: true; value: ResultT } | { valid: false; value: null }> {
159 const cachedValue: CacheEntry<ResultT, SideChannel> | void = cache.get(arg);
160
161 if (cachedValue) {
162 for (const { value, valid } of cachedValue) {
163 if (yield* valid(data)) return { valid: true, value };
164 }
165 }
166
167 return { valid: false, value: null };
168 }
169
170 function* getCachedValueOrWait<ArgT, ResultT, SideChannel>(
171 asyncContext: boolean,
172 callCache: CacheMap<ArgT, ResultT, SideChannel>,
173 futureCache: CacheMap<ArgT, Lock<ResultT>, SideChannel>,
174 arg: ArgT,
175 data: SideChannel,
176 ): Handler<{ valid: true; value: ResultT } | { valid: false; value: null }> {
177 const cached = yield* getCachedValue(callCache, arg, data);
178 if (cached.valid) {
179 return cached;
180 }
181
182 if (asyncContext) {
183 const cached = yield* getCachedValue(futureCache, arg, data);
184 if (cached.valid) {
185 const value = yield* waitFor<ResultT>(cached.value.promise);
186 return { valid: true, value };
187 }
188 }
189
190 return { valid: false, value: null };
191 }
192
193 function setupAsyncLocks<ArgT, ResultT, SideChannel>(
194 config: CacheConfigurator<SideChannel>,
195 futureCache: CacheMap<ArgT, Lock<ResultT>, SideChannel>,
196 arg: ArgT,
197 ): Lock<ResultT> {
198 const finishLock = new Lock<ResultT>();
199
200 updateFunctionCache(futureCache, config, arg, finishLock);
201
202 return finishLock;
203 }
204
205 function updateFunctionCache<
206 ArgT,
207 ResultT,
208 SideChannel,
209 Cache extends CacheMap<ArgT, ResultT, SideChannel>,
210 >(
211 cache: Cache,
212 config: CacheConfigurator<SideChannel>,
213 arg: ArgT,
214 value: ResultT,
215 ) {
216 if (!config.configured()) config.forever();
217
218 let cachedValue: CacheEntry<ResultT, SideChannel> | void = cache.get(arg);
219
220 config.deactivate();
221
222 switch (config.mode()) {
223 case "forever":
224 cachedValue = [{ value, valid: genTrue }];
225 cache.set(arg, cachedValue);
226 break;
227 case "invalidate":
228 cachedValue = [{ value, valid: config.validator() }];
229 cache.set(arg, cachedValue);
230 break;
231 case "valid":
232 if (cachedValue) {
233 cachedValue.push({ value, valid: config.validator() });
234 } else {
235 cachedValue = [{ value, valid: config.validator() }];
236 cache.set(arg, cachedValue);
237 }
238 }
239 }
240
241 class CacheConfigurator<SideChannel = void> {
242 _active: boolean = true;
243 _never: boolean = false;
244 _forever: boolean = false;
245 _invalidate: boolean = false;
246
247 _configured: boolean = false;
248
249 _pairs: Array<
250 [cachedValue: unknown, handler: (data: SideChannel) => Handler<unknown>]
251 > = [];
252
253 _data: SideChannel;
254
255 constructor(data: SideChannel) {
256 this._data = data;
257 }
258
259 simple() {
260 return makeSimpleConfigurator(this);
261 }
262
263 mode() {
264 if (this._never) return "never";
265 if (this._forever) return "forever";
266 if (this._invalidate) return "invalidate";
267 return "valid";
268 }
269
270 forever() {
271 if (!this._active) {
272 throw new Error("Cannot change caching after evaluation has completed.");
273 }
274 if (this._never) {
275 throw new Error("Caching has already been configured with .never()");
276 }
277 this._forever = true;
278 this._configured = true;
279 }
280
281 never() {
282 if (!this._active) {
283 throw new Error("Cannot change caching after evaluation has completed.");
284 }
285 if (this._forever) {
286 throw new Error("Caching has already been configured with .forever()");
287 }
288 this._never = true;
289 this._configured = true;
290 }
291
292 using<T>(handler: (data: SideChannel) => T): T {
293 if (!this._active) {
294 throw new Error("Cannot change caching after evaluation has completed.");
295 }
296 if (this._never || this._forever) {
297 throw new Error(
298 "Caching has already been configured with .never or .forever()",
299 );
300 }
301 this._configured = true;
302
303 const key = handler(this._data);
304
305 const fn = maybeAsync(
306 handler,
307 `You appear to be using an async cache handler, but Babel has been called synchronously`,
308 );
309
310 if (isThenable(key)) {
311 // @ts-expect-error todo(flow->ts): improve function return type annotation
312 return key.then((key: unknown) => {
313 this._pairs.push([key, fn]);
314 return key;
315 });
316 }
317
318 this._pairs.push([key, fn]);
319 return key;
320 }
321
322 invalidate<T>(handler: (data: SideChannel) => T): T {
323 this._invalidate = true;
324 return this.using(handler);
325 }
326
327 validator(): (data: SideChannel) => Handler<boolean> {
328 const pairs = this._pairs;
329 return function* (data: SideChannel) {
330 for (const [key, fn] of pairs) {
331 if (key !== (yield* fn(data))) return false;
332 }
333 return true;
334 };
335 }
336
337 deactivate() {
338 this._active = false;
339 }
340
341 configured() {
342 return this._configured;
343 }
344 }
345
346 function makeSimpleConfigurator(
347 cache: CacheConfigurator<any>,
348 ): SimpleCacheConfigurator {
349 function cacheFn(val: any) {
350 if (typeof val === "boolean") {
351 if (val) cache.forever();
352 else cache.never();
353 return;
354 }
355
356 return cache.using(() => assertSimpleType(val()));
357 }
358 cacheFn.forever = () => cache.forever();
359 cacheFn.never = () => cache.never();
360 cacheFn.using = (cb: { (): SimpleType }) =>
361 cache.using(() => assertSimpleType(cb()));
362 cacheFn.invalidate = (cb: { (): SimpleType }) =>
363 cache.invalidate(() => assertSimpleType(cb()));
364
365 return cacheFn as any;
366 }
367
368 // Types are limited here so that in the future these values can be used
369 // as part of Babel's caching logic.
370 export type SimpleType =
371 | string
372 | boolean
373 | number
374 | null
375 | void
376 | Promise<SimpleType>;
377 export function assertSimpleType(value: unknown): SimpleType {
378 if (isThenable(value)) {
379 throw new Error(
380 `You appear to be using an async cache handler, ` +
381 `which your current version of Babel does not support. ` +
382 `We may add support for this in the future, ` +
383 `but if you're on the most recent version of @babel/core and still ` +
384 `seeing this error, then you'll need to synchronously handle your caching logic.`,
385 );
386 }
387
388 if (
389 value != null &&
390 typeof value !== "string" &&
391 typeof value !== "boolean" &&
392 typeof value !== "number"
393 ) {
394 throw new Error(
395 "Cache keys must be either string, boolean, number, null, or undefined.",
396 );
397 }
•398 // @ts-ignore Type 'unknown' is not assignable to type 'SimpleType'. This can be removed
399 // when strictNullCheck is enabled
400 return value;
401 }
402
403 class Lock<T> {
404 released: boolean = false;
405 promise: Promise<T>;
406 _resolve: (value: T) => void;
407
408 constructor() {
409 this.promise = new Promise(resolve => {
410 this._resolve = resolve;
411 });
412 }
413
414 release(value: T) {
415 this.released = true;
416 this._resolve(value);
417 }
418 }