11import { 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' ;
39import { randomUUID } from 'node:crypto' ;
410import ms , { type StringValue } from 'ms' ;
511import { getCacheProvider } from './cache-plugin' ;
@@ -90,6 +96,7 @@ function useCache<R extends any[], F extends AsyncFunction<R>>(
9096 }
9197
9298 const memo = ( async ( ...args ) => {
99+ const analytics = getCommandKit ( ) ?. analytics ;
93100 const keyHash = await stableHash ( {
94101 fnId : metadata . id ,
95102 buildId : metadata . buildId ,
@@ -126,12 +133,28 @@ function useCache<R extends any[], F extends AsyncFunction<R>>(
126133 storedFn . lastAccess = Date . now ( ) ;
127134 }
128135
136+ const start = performance . now ( ) ;
129137 const cached = await provider . get ( effectiveKey ) ;
138+ const end = performance . now ( ) - start ;
139+
130140 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+
131152 return cached . value ;
132153 }
133154
155+ const rawStart = performance . now ( ) ;
134156 const result = await fn ( ...args ) ;
157+ const rawEnd = performance . now ( ) - rawStart ;
135158
136159 if ( result != null ) {
137160 const ttl = context . params . ttl ;
@@ -148,6 +171,21 @@ function useCache<R extends any[], F extends AsyncFunction<R>>(
148171 } ) ;
149172 }
150173
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+
151189 return result ;
152190 } ,
153191 ) ;
@@ -232,6 +270,14 @@ export async function revalidateTag(tag: string): Promise<void> {
232270
233271 // Batch delete operations for better performance
234272 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+ ) ;
235281}
236282
237283/**
0 commit comments