All files / server cache-utils.ts

48.88% Statements 22/45
28.35% Branches 19/67
29.41% Functions 5/17
47.61% Lines 20/42

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290                                                                              18x     18x 18x     18x   18x 18x     18x 18x     18x                     20x                                                                                                                                                                                                                                                                                                                                                       36x 18x   18x     18x     18x                                 40x   40x 1206x 1206x     40x                                  
/**
 * Cache utilities for Drizzle Cube semantic layer
 * Provides cache key generation and normalization functions
 */
 
import type { SemanticQuery, Filter, TimeDimension, SecurityContext } from './types'
 
/**
 * Configuration for cache key generation
 */
export interface CacheKeyConfig {
  /** Prefix for all cache keys */
  keyPrefix?: string
  /** Whether to include security context in cache key */
  includeSecurityContext?: boolean
  /** Custom serializer for security context */
  securityContextSerializer?: (ctx: SecurityContext) => string
}
 
/**
 * Generate a deterministic cache key from query and security context
 *
 * Key structure: {prefix}query:{queryHash}:ctx:{securityHash}
 *
 * Uses FNV-1a hash for:
 * - Speed: ~3x faster than SHA-256
 * - Simplicity: No dependencies required
 * - Sufficient collision resistance for cache keys
 *
 * @param query - The semantic query to cache
 * @param securityContext - Security context for tenant isolation
 * @param config - Cache key configuration
 * @returns Deterministic cache key string
 */
export function generateCacheKey(
  query: SemanticQuery,
  securityContext: SecurityContext,
  config: CacheKeyConfig = {}
): string {
  const prefix = config.keyPrefix ?? 'drizzle-cube:'
 
  // Create normalized query representation for consistent hashing
  const normalizedQuery = normalizeQuery(query)
  const queryHash = fnv1aHash(JSON.stringify(normalizedQuery))
 
  // Include security context in key for tenant isolation
  let key = `${prefix}query:${queryHash}`
 
  Eif (config.includeSecurityContext !== false) {
    const ctxString = config.securityContextSerializer
      ? config.securityContextSerializer(securityContext)
      : JSON.stringify(sortObject(securityContext))
    const ctxHash = fnv1aHash(ctxString)
    key += `:ctx:${ctxHash}`
  }
 
  return key
}
 
/**
 * Normalize query for consistent hashing
 * Sorts arrays and object keys to ensure same query = same hash
 *
 * @param query - The semantic query to normalize
 * @returns Normalized query with sorted arrays and keys
 */
export function normalizeQuery(query: SemanticQuery): SemanticQuery {
  return {
    measures: query.measures ? [...query.measures].sort() : undefined,
    dimensions: query.dimensions ? [...query.dimensions].sort() : undefined,
    filters: query.filters ? sortFilters(query.filters) : undefined,
    timeDimensions: query.timeDimensions
      ? sortTimeDimensions(query.timeDimensions)
      : undefined,
    limit: query.limit,
    offset: query.offset,
    order: query.order ? sortObject(query.order) : undefined,
    fillMissingDatesValue: query.fillMissingDatesValue,
    // Include funnel config in cache key for proper cache invalidation
    funnel: query.funnel ? normalizeFunnelConfig(query.funnel) : undefined,
    // Include flow config in cache key for proper cache invalidation
    flow: query.flow ? normalizeFlowConfig(query.flow) : undefined,
    // Include retention config in cache key for proper cache invalidation
    retention: query.retention ? normalizeRetentionConfig(query.retention) : undefined
  }
}
 
/**
 * Normalize funnel config for consistent hashing
 * Ensures step order and filter content create unique cache keys
 *
 * @param funnel - The funnel config to normalize
 * @returns Normalized funnel config
 */
function normalizeFunnelConfig(funnel: NonNullable<SemanticQuery['funnel']>): NonNullable<SemanticQuery['funnel']> {
  return {
    bindingKey: funnel.bindingKey,
    timeDimension: funnel.timeDimension,
    // Normalize steps - preserve order but sort filters within each step
    steps: funnel.steps.map(step => {
      const normalizedStep: typeof step = {
        name: step.name,
        filter: step.filter
          ? (Array.isArray(step.filter) ? sortFilters(step.filter) : sortFilters([step.filter])[0])
          : undefined,
        timeToConvert: step.timeToConvert
      }
      // Include cube property for multi-cube steps
      if ('cube' in step && step.cube) {
        (normalizedStep as { cube?: string }).cube = step.cube
      }
      return normalizedStep
    }),
    includeTimeMetrics: funnel.includeTimeMetrics,
    globalTimeWindow: funnel.globalTimeWindow
  }
}
 
/**
 * Normalize flow config for consistent hashing
 * Ensures all flow parameters are included in cache key
 *
 * @param flow - The flow config to normalize
 * @returns Normalized flow config
 */
function normalizeFlowConfig(flow: NonNullable<SemanticQuery['flow']>): NonNullable<SemanticQuery['flow']> {
  return {
    bindingKey: flow.bindingKey,
    timeDimension: flow.timeDimension,
    eventDimension: flow.eventDimension,
    // Normalize starting step - sort filters for consistent hashing
    startingStep: {
      name: flow.startingStep.name,
      filter: flow.startingStep.filter
        ? (Array.isArray(flow.startingStep.filter)
            ? sortFilters(flow.startingStep.filter)
            : sortFilters([flow.startingStep.filter])[0])
        : undefined
    },
    // CRITICAL: Include step counts in cache key
    stepsBefore: flow.stepsBefore,
    stepsAfter: flow.stepsAfter,
    // Include optional entity limit if present
    entityLimit: flow.entityLimit,
    // CRITICAL: Include outputMode - affects aggregation strategy (sankey vs sunburst)
    outputMode: flow.outputMode,
    // Include join strategy to keep cache keys aligned with join selection
    joinStrategy: flow.joinStrategy
  }
}
 
/**
 * Normalize retention config for consistent hashing
 * Ensures all retention parameters are included in cache key
 *
 * @param retention - The retention config to normalize
 * @returns Normalized retention config
 */
function normalizeRetentionConfig(retention: NonNullable<SemanticQuery['retention']>): NonNullable<SemanticQuery['retention']> {
  return {
    timeDimension: retention.timeDimension,
    bindingKey: retention.bindingKey,
    dateRange: retention.dateRange,
    granularity: retention.granularity,
    periods: retention.periods,
    retentionType: retention.retentionType,
    // Normalize filters for consistent hashing
    cohortFilters: retention.cohortFilters
      ? (Array.isArray(retention.cohortFilters)
          ? sortFilters(retention.cohortFilters)
          : sortFilters([retention.cohortFilters])[0])
      : undefined,
    activityFilters: retention.activityFilters
      ? (Array.isArray(retention.activityFilters)
          ? sortFilters(retention.activityFilters)
          : sortFilters([retention.activityFilters])[0])
      : undefined,
    // Include breakdown dimensions for cache key
    breakdownDimensions: retention.breakdownDimensions
  }
}
 
/**
 * Sort filters recursively for consistent hashing
 * Handles both simple filters and logical (and/or) groups
 *
 * @param filters - Array of filters to sort
 * @returns Sorted array of filters
 */
function sortFilters(filters: Filter[]): Filter[] {
  return [...filters]
    .map((f) => {
      if ('and' in f && f.and) {
        return { and: sortFilters(f.and) }
      }
      if ('or' in f && f.or) {
        return { or: sortFilters(f.or) }
      }
      // FilterCondition - sort values array if present
      const fc = f as { member: string; operator: string; values?: unknown[] }
      return {
        ...fc,
        values: fc.values ? [...fc.values].sort() : fc.values
      }
    })
    .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)))
}
 
/**
 * Sort time dimensions for consistent hashing
 *
 * @param timeDimensions - Array of time dimensions to sort
 * @returns Sorted array of time dimensions
 */
function sortTimeDimensions(timeDimensions: TimeDimension[]): TimeDimension[] {
  return [...timeDimensions]
    .map((td) => ({
      dimension: td.dimension,
      granularity: td.granularity,
      dateRange: td.dateRange,
      fillMissingDates: td.fillMissingDates,
      compareDateRange: td.compareDateRange
        ? [...td.compareDateRange].sort((a, b) => {
            const aStr = Array.isArray(a) ? a.join('-') : a
            const bStr = Array.isArray(b) ? b.join('-') : b
            return aStr.localeCompare(bStr)
          })
        : undefined
    }))
    .sort((a, b) => a.dimension.localeCompare(b.dimension))
}
 
/**
 * Recursively sort object keys for deterministic serialization
 *
 * @param obj - Object to sort
 * @returns Object with sorted keys (recursively)
 */
export function sortObject<T>(obj: T): T {
  if (obj === null || typeof obj !== 'object') return obj
  Iif (Array.isArray(obj)) return obj.map(sortObject) as T
 
  return Object.keys(obj as object)
    .sort()
    .reduce((sorted, key) => {
      ;(sorted as Record<string, unknown>)[key] = sortObject(
        (obj as Record<string, unknown>)[key]
      )
      return sorted
    }, {} as T)
}
 
/**
 * FNV-1a hash - fast, non-cryptographic hash function
 * Returns hex string for cache key readability
 *
 * Properties:
 * - O(n) time complexity
 * - Low collision rate for similar strings
 * - Deterministic across runs
 *
 * @param str - String to hash
 * @returns 8-character hex string
 */
export function fnv1aHash(str: string): string {
  let hash = 2166136261 // FNV offset basis
 
  for (let i = 0; i < str.length; i++) {
    hash ^= str.charCodeAt(i)
    hash = (hash * 16777619) >>> 0 // FNV prime, unsigned 32-bit
  }
 
  return hash.toString(16).padStart(8, '0')
}
 
/**
 * Generate invalidation pattern for a cube
 * Used when cube data changes and all related cache entries need clearing
 *
 * @param cubeName - Name of the cube to invalidate
 * @param keyPrefix - Cache key prefix
 * @returns Glob pattern for cache invalidation
 */
export function getCubeInvalidationPattern(
  cubeName: string,
  keyPrefix?: string
): string {
  return `${keyPrefix ?? 'drizzle-cube:'}*${cubeName}*`
}