optimized_cache.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. package searcher
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "encoding/json"
  6. "fmt"
  7. "strconv"
  8. "time"
  9. "github.com/dgraph-io/ristretto/v2"
  10. "github.com/0xJacky/Nginx-UI/internal/nginx_log/utils"
  11. )
  12. // OptimizedSearchCache provides high-performance caching using Ristretto
  13. type OptimizedSearchCache struct {
  14. cache *ristretto.Cache[string, *SearchResult]
  15. }
  16. // NewOptimizedSearchCache creates a new optimized cache with Ristretto
  17. func NewOptimizedSearchCache(maxSize int64) *OptimizedSearchCache {
  18. cache, err := ristretto.NewCache(&ristretto.Config[string, *SearchResult]{
  19. NumCounters: maxSize * 10, // Number of keys to track frequency of (10x cache size)
  20. MaxCost: maxSize, // Maximum cost of cache (number of items)
  21. BufferItems: 64, // Number of keys per Get buffer
  22. Metrics: true, // Enable metrics collection
  23. })
  24. if err != nil {
  25. panic(fmt.Sprintf("failed to create cache: %v", err))
  26. }
  27. return &OptimizedSearchCache{
  28. cache: cache,
  29. }
  30. }
  31. // GenerateOptimizedKey generates an efficient cache key for a search request
  32. func (osc *OptimizedSearchCache) GenerateOptimizedKey(req *SearchRequest) string {
  33. // Create a unique key based on all search parameters
  34. keyData := struct {
  35. Query string `json:"query"`
  36. Limit int `json:"limit"`
  37. Offset int `json:"offset"`
  38. SortBy string `json:"sort_by"`
  39. SortOrder string `json:"sort_order"`
  40. StartTime *int64 `json:"start_time"`
  41. EndTime *int64 `json:"end_time"`
  42. IPAddresses []string `json:"ip_addresses"`
  43. StatusCodes []int `json:"status_codes"`
  44. Methods []string `json:"methods"`
  45. MinBytes *int64 `json:"min_bytes"`
  46. MaxBytes *int64 `json:"max_bytes"`
  47. }{
  48. Query: req.Query,
  49. Limit: req.Limit,
  50. Offset: req.Offset,
  51. SortBy: req.SortBy,
  52. SortOrder: req.SortOrder,
  53. StartTime: req.StartTime,
  54. EndTime: req.EndTime,
  55. IPAddresses: req.IPAddresses,
  56. StatusCodes: req.StatusCodes,
  57. Methods: req.Methods,
  58. MinBytes: req.MinBytes,
  59. MaxBytes: req.MaxBytes,
  60. }
  61. // Convert to JSON and hash for consistent key generation
  62. jsonData, err := json.Marshal(keyData)
  63. if err != nil {
  64. // Fallback to efficient string building if JSON marshal fails
  65. keyBuf := make([]byte, 0, len(req.Query)+len(req.SortBy)+len(req.SortOrder)+32)
  66. keyBuf = append(keyBuf, "q:"...)
  67. keyBuf = append(keyBuf, req.Query...)
  68. keyBuf = append(keyBuf, "|l:"...)
  69. keyBuf = utils.AppendInt(keyBuf, req.Limit)
  70. keyBuf = append(keyBuf, "|o:"...)
  71. keyBuf = utils.AppendInt(keyBuf, req.Offset)
  72. keyBuf = append(keyBuf, "|s:"...)
  73. keyBuf = append(keyBuf, req.SortBy...)
  74. keyBuf = append(keyBuf, "|so:"...)
  75. keyBuf = append(keyBuf, req.SortOrder...)
  76. return utils.BytesToStringUnsafe(keyBuf)
  77. }
  78. // Use MD5 hash for compact key representation
  79. hash := md5.Sum(jsonData)
  80. return hex.EncodeToString(hash[:])
  81. }
  82. // Get retrieves a search result from cache
  83. func (osc *OptimizedSearchCache) Get(req *SearchRequest) *SearchResult {
  84. key := osc.GenerateOptimizedKey(req)
  85. if result, found := osc.cache.Get(key); found {
  86. // Mark result as from cache
  87. cachedResult := *result // Create a copy
  88. cachedResult.FromCache = true
  89. return &cachedResult
  90. }
  91. return nil
  92. }
  93. // Put stores a search result in cache with automatic cost calculation
  94. func (osc *OptimizedSearchCache) Put(req *SearchRequest, result *SearchResult, ttl time.Duration) {
  95. key := osc.GenerateOptimizedKey(req)
  96. // Calculate cost based on result size (number of hits + base cost)
  97. cost := int64(1 + len(result.Hits)/10) // Base cost of 1 plus hits/10
  98. if cost < 1 {
  99. cost = 1
  100. }
  101. // Set with TTL
  102. osc.cache.SetWithTTL(key, result, cost, ttl)
  103. // Wait for the value to pass through buffers to ensure it's cached
  104. osc.cache.Wait()
  105. }
  106. // Clear clears all cached entries
  107. func (osc *OptimizedSearchCache) Clear() {
  108. if osc != nil && osc.cache != nil {
  109. osc.cache.Clear()
  110. }
  111. }
  112. // GetStats returns cache statistics
  113. func (osc *OptimizedSearchCache) GetStats() *CacheStats {
  114. metrics := osc.cache.Metrics
  115. return &CacheStats{
  116. Size: int(metrics.KeysAdded() - metrics.KeysEvicted()),
  117. Capacity: int(osc.cache.MaxCost()),
  118. HitCount: int64(metrics.Hits()),
  119. MissCount: int64(metrics.Misses()),
  120. HitRate: metrics.Ratio(),
  121. Evictions: int64(metrics.KeysEvicted()),
  122. Additions: int64(metrics.KeysAdded()),
  123. Updates: int64(metrics.KeysUpdated()),
  124. Cost: int64(metrics.CostAdded() - metrics.CostEvicted()),
  125. }
  126. }
  127. // CacheStats provides detailed cache statistics
  128. type CacheStats struct {
  129. Size int `json:"size"` // Current number of items
  130. Capacity int `json:"capacity"` // Maximum capacity
  131. HitCount int64 `json:"hit_count"` // Number of cache hits
  132. MissCount int64 `json:"miss_count"` // Number of cache misses
  133. HitRate float64 `json:"hit_rate"` // Cache hit rate (0.0 to 1.0)
  134. Evictions int64 `json:"evictions"` // Number of evicted items
  135. Additions int64 `json:"additions"` // Number of items added
  136. Updates int64 `json:"updates"` // Number of items updated
  137. Cost int64 `json:"cost"` // Current cost
  138. }
  139. // WarmupCache pre-loads frequently used queries into cache
  140. func (osc *OptimizedSearchCache) WarmupCache(queries []WarmupQuery) {
  141. for _, query := range queries {
  142. // Pre-generate keys to warm up the cache
  143. key := osc.GenerateOptimizedKey(query.Request)
  144. if query.Result != nil {
  145. osc.cache.Set(key, query.Result, 1) // Use cost of 1 for warmup
  146. }
  147. }
  148. // Wait for cache operations to complete
  149. osc.cache.Wait()
  150. }
  151. // WarmupQuery represents a query and result pair for cache warmup
  152. type WarmupQuery struct {
  153. Request *SearchRequest `json:"request"`
  154. Result *SearchResult `json:"result"`
  155. }
  156. // Close closes the cache and frees resources
  157. func (osc *OptimizedSearchCache) Close() {
  158. osc.cache.Close()
  159. }
  160. // FastKeyGenerator provides even faster key generation for hot paths
  161. type FastKeyGenerator struct {
  162. buffer []byte
  163. }
  164. // NewFastKeyGenerator creates a key generator with pre-allocated buffer
  165. func NewFastKeyGenerator() *FastKeyGenerator {
  166. return &FastKeyGenerator{
  167. buffer: make([]byte, 0, 256), // Pre-allocate 256 bytes
  168. }
  169. }
  170. // GenerateKey generates a key using pre-allocated buffer
  171. func (fkg *FastKeyGenerator) GenerateKey(req *SearchRequest) string {
  172. fkg.buffer = fkg.buffer[:0] // Reset buffer
  173. // Build key using buffer to avoid allocations
  174. fkg.buffer = append(fkg.buffer, "q:"...)
  175. fkg.buffer = append(fkg.buffer, req.Query...)
  176. fkg.buffer = append(fkg.buffer, "|l:"...)
  177. fkg.buffer = strconv.AppendInt(fkg.buffer, int64(req.Limit), 10)
  178. fkg.buffer = append(fkg.buffer, "|o:"...)
  179. fkg.buffer = strconv.AppendInt(fkg.buffer, int64(req.Offset), 10)
  180. fkg.buffer = append(fkg.buffer, "|s:"...)
  181. fkg.buffer = append(fkg.buffer, req.SortBy...)
  182. fkg.buffer = append(fkg.buffer, "|so:"...)
  183. fkg.buffer = append(fkg.buffer, req.SortOrder...)
  184. // Add timestamps if present
  185. if req.StartTime != nil {
  186. fkg.buffer = append(fkg.buffer, "|st:"...)
  187. fkg.buffer = strconv.AppendInt(fkg.buffer, *req.StartTime, 10)
  188. }
  189. if req.EndTime != nil {
  190. fkg.buffer = append(fkg.buffer, "|et:"...)
  191. fkg.buffer = strconv.AppendInt(fkg.buffer, *req.EndTime, 10)
  192. }
  193. // Add arrays (simplified)
  194. if len(req.StatusCodes) > 0 {
  195. fkg.buffer = append(fkg.buffer, "|sc:"...)
  196. for i, code := range req.StatusCodes {
  197. if i > 0 {
  198. fkg.buffer = append(fkg.buffer, ',')
  199. }
  200. fkg.buffer = strconv.AppendInt(fkg.buffer, int64(code), 10)
  201. }
  202. }
  203. // Convert to string (this still allocates, but fewer allocations overall)
  204. return string(fkg.buffer)
  205. }
  206. // CacheMiddleware provides middleware functionality for caching
  207. type CacheMiddleware struct {
  208. cache *OptimizedSearchCache
  209. keyGen *FastKeyGenerator
  210. enabled bool
  211. defaultTTL time.Duration
  212. }
  213. // NewCacheMiddleware creates a new cache middleware
  214. func NewCacheMiddleware(cache *OptimizedSearchCache, defaultTTL time.Duration) *CacheMiddleware {
  215. return &CacheMiddleware{
  216. cache: cache,
  217. keyGen: NewFastKeyGenerator(),
  218. enabled: true,
  219. defaultTTL: defaultTTL,
  220. }
  221. }
  222. // Enable enables caching
  223. func (cm *CacheMiddleware) Enable() {
  224. cm.enabled = true
  225. }
  226. // Disable disables caching
  227. func (cm *CacheMiddleware) Disable() {
  228. cm.enabled = false
  229. }
  230. // IsEnabled returns whether caching is enabled
  231. func (cm *CacheMiddleware) IsEnabled() bool {
  232. return cm.enabled
  233. }
  234. // GetOrSet attempts to get from cache, or executes the provided function and caches the result
  235. func (cm *CacheMiddleware) GetOrSet(req *SearchRequest, fn func() (*SearchResult, error)) (*SearchResult, error) {
  236. if !cm.enabled {
  237. return fn()
  238. }
  239. // Try cache first
  240. if cached := cm.cache.Get(req); cached != nil {
  241. return cached, nil
  242. }
  243. // Execute function
  244. result, err := fn()
  245. if err != nil {
  246. return nil, err
  247. }
  248. // Cache successful result
  249. if result != nil {
  250. cm.cache.Put(req, result, cm.defaultTTL)
  251. }
  252. return result, nil
  253. }