1
1
import { AsyncLocalStorage } from 'node:async_hooks' ;
2
- import { AsyncFunction , GenericFunction } from 'commandkit' ;
2
+ import {
3
+ AsyncFunction ,
4
+ defer ,
5
+ GenericFunction ,
6
+ getCommandKit ,
7
+ } from 'commandkit' ;
8
+ import { AnalyticsEvents } from 'commandkit/analytics' ;
3
9
import { randomUUID } from 'node:crypto' ;
4
10
import ms , { type StringValue } from 'ms' ;
5
11
import { getCacheProvider } from './cache-plugin' ;
@@ -90,6 +96,7 @@ function useCache<R extends any[], F extends AsyncFunction<R>>(
90
96
}
91
97
92
98
const memo = ( async ( ...args ) => {
99
+ const analytics = getCommandKit ( ) ?. analytics ;
93
100
const keyHash = await stableHash ( {
94
101
fnId : metadata . id ,
95
102
buildId : metadata . buildId ,
@@ -126,12 +133,28 @@ function useCache<R extends any[], F extends AsyncFunction<R>>(
126
133
storedFn . lastAccess = Date . now ( ) ;
127
134
}
128
135
136
+ const start = performance . now ( ) ;
129
137
const cached = await provider . get ( effectiveKey ) ;
138
+ const end = performance . now ( ) - start ;
139
+
130
140
if ( cached && cached . value != null ) {
141
+ defer ( ( ) =>
142
+ analytics ?. track ( {
143
+ name : AnalyticsEvents . CACHE_HIT ,
144
+ id : 'commandkit' ,
145
+ data : {
146
+ time : end . toFixed ( 2 ) ,
147
+ tags : Array . from ( storedFn ?. tags ?? [ ] ) ,
148
+ } ,
149
+ } ) ,
150
+ ) ;
151
+
131
152
return cached . value ;
132
153
}
133
154
155
+ const rawStart = performance . now ( ) ;
134
156
const result = await fn ( ...args ) ;
157
+ const rawEnd = performance . now ( ) - rawStart ;
135
158
136
159
if ( result != null ) {
137
160
const ttl = context . params . ttl ;
@@ -148,6 +171,21 @@ function useCache<R extends any[], F extends AsyncFunction<R>>(
148
171
} ) ;
149
172
}
150
173
174
+ defer ( ( ) =>
175
+ analytics ?. track ( {
176
+ name : AnalyticsEvents . CACHE_MISS ,
177
+ id : 'commandkit' ,
178
+ data : {
179
+ time : rawEnd . toFixed ( 2 ) ,
180
+ tags : Array . from (
181
+ context . params . tags . size
182
+ ? context . params . tags
183
+ : ( storedFn ?. tags ?? [ ] ) ,
184
+ ) ,
185
+ } ,
186
+ } ) ,
187
+ ) ;
188
+
151
189
return result ;
152
190
} ,
153
191
) ;
@@ -232,6 +270,14 @@ export async function revalidateTag(tag: string): Promise<void> {
232
270
233
271
// Batch delete operations for better performance
234
272
await Promise . all ( entries . map ( ( entry ) => provider . delete ( entry . key ) ) ) ;
273
+
274
+ defer ( ( ) =>
275
+ getCommandKit ( ) ?. analytics ?. track ( {
276
+ name : AnalyticsEvents . CACHE_REVALIDATED ,
277
+ id : 'commandkit' ,
278
+ data : { tag } ,
279
+ } ) ,
280
+ ) ;
235
281
}
236
282
237
283
/**
0 commit comments