Skip to content

Commit 74dc2c5

Browse files
committed
refactor: improve cache key generation
1 parent 821017f commit 74dc2c5

File tree

2 files changed

+20
-17
lines changed

2 files changed

+20
-17
lines changed

packages/cache/src/use-cache.ts

Lines changed: 4 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import { AnalyticsEvents } from 'commandkit/analytics';
99
import { randomUUID } from 'node:crypto';
1010
import ms, { type StringValue } from 'ms';
1111
import { getCacheProvider } from './cache-plugin';
12-
import stableHash from 'stable-hash';
12+
import { createHash } from './utils';
1313

1414
const cacheContext = new AsyncLocalStorage<CacheContext>();
1515
const fnStore = new Map<
@@ -28,13 +28,7 @@ const CACHE_FN_ID = `__cache_fn_id_${Date.now()}__${Math.random()}__`;
2828
const CACHED_FN_SYMBOL = Symbol('commandkit.cache.sentinel');
2929

3030
// WeakMap to store function metadata without preventing garbage collection
31-
const fnMetadata = new WeakMap<
32-
GenericFunction,
33-
{ id: string; buildId: string }
34-
>();
35-
36-
// Generate a stable build ID that persists across restarts
37-
const BUILD_ID = randomUUID();
31+
const fnMetadata = new WeakMap<GenericFunction, string>();
3832

3933
/**
4034
* Context for managing cache operations within an async scope
@@ -88,20 +82,13 @@ function useCache<R extends any[], F extends AsyncFunction<R>>(
8882
// Get or create function metadata
8983
let metadata = fnMetadata.get(fn);
9084
if (!metadata) {
91-
metadata = {
92-
id: randomUUID(),
93-
buildId: BUILD_ID,
94-
};
85+
metadata = randomUUID();
9586
fnMetadata.set(fn, metadata);
9687
}
9788

9889
const memo = (async (...args) => {
9990
const analytics = getCommandKit()?.analytics;
100-
const keyHash = await stableHash({
101-
fnId: metadata.id,
102-
buildId: metadata.buildId,
103-
args,
104-
});
91+
const keyHash = createHash(metadata, args);
10592

10693
const resolvedTTL =
10794
isLocal && params?.ttl != null

packages/cache/src/utils.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import stableHash from 'stable-hash';
2+
import { createHash as createHashNode } from 'node:crypto';
3+
4+
/**
5+
* @private
6+
*/
7+
export function createHash(id: string, args: any[]): string {
8+
const objectHash = stableHash({
9+
id,
10+
args,
11+
});
12+
13+
const hash = createHashNode('sha256').update(objectHash).digest('hex');
14+
15+
return hash;
16+
}

0 commit comments

Comments
 (0)