@comake/skl-js-engine 1.4.3 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,64 @@
1
+ import crypto from 'crypto';
2
+ import type { ReadCacheOperation } from '../SklEngineOptions';
3
+
4
+ export interface BuildReadCacheKeyInput {
5
+ operation: ReadCacheOperation;
6
+ args: readonly unknown[];
7
+ endpointUrl?: string;
8
+ namespace?: string;
9
+ keyHint?: string;
10
+ }
11
+
12
+ function stableStringify(value: unknown): string {
13
+ if (value === null) return 'null';
14
+
15
+ const valueType = typeof value;
16
+ if (valueType === 'number' || valueType === 'boolean') return String(value);
17
+ if (valueType === 'string') return JSON.stringify(value);
18
+ if (valueType !== 'object') {
19
+ const serializedPrimitive = JSON.stringify(value);
20
+ return serializedPrimitive ?? String(value);
21
+ }
22
+
23
+ if (Array.isArray(value)) {
24
+ return `[${value.map(stableStringify).join(',')}]`;
25
+ }
26
+
27
+ const objectValue = value as Record<string, unknown>;
28
+ // eslint-disable-next-line @typescript-eslint/require-array-sort-compare
29
+ const keys = Object.keys(objectValue).sort();
30
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${stableStringify(objectValue[key])}`).join(',')}}`;
31
+ }
32
+
33
+ export function buildReadCacheKey(input: BuildReadCacheKeyInput): string {
34
+ const keyParts = {
35
+ namespace: input.namespace ?? '',
36
+ endpointUrl: input.endpointUrl ?? '',
37
+ operation: input.operation,
38
+ keyHint: input.keyHint ?? '',
39
+ args: input.args
40
+ };
41
+ return crypto.createHash('sha256').update(stableStringify(keyParts)).digest('hex');
42
+ }
43
+
44
+ export class ReadCacheSingleflight {
45
+ private readonly inflight = new Map<string, Promise<unknown>>();
46
+
47
+ public async do<T>(key: string, fn: () => Promise<T>): Promise<T> {
48
+ const existing = this.inflight.get(key) as Promise<T> | undefined;
49
+ if (existing) {
50
+ return existing;
51
+ }
52
+
53
+ const promise = (async(): Promise<T> => {
54
+ try {
55
+ return await fn();
56
+ } finally {
57
+ this.inflight.delete(key);
58
+ }
59
+ })();
60
+
61
+ this.inflight.set(key, promise as Promise<unknown>);
62
+ return promise;
63
+ }
64
+ }