optimized_cache.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. osc.cache.Clear()
  109. }
  110. // GetStats returns cache statistics
  111. func (osc *OptimizedSearchCache) GetStats() *CacheStats {
  112. metrics := osc.cache.Metrics
  113. return &CacheStats{
  114. Size: int(metrics.KeysAdded() - metrics.KeysEvicted()),
  115. Capacity: int(osc.cache.MaxCost()),
  116. HitCount: int64(metrics.Hits()),
  117. MissCount: int64(metrics.Misses()),
  118. HitRate: metrics.Ratio(),
  119. Evictions: int64(metrics.KeysEvicted()),
  120. Additions: int64(metrics.KeysAdded()),
  121. Updates: int64(metrics.KeysUpdated()),
  122. Cost: int64(metrics.CostAdded() - metrics.CostEvicted()),
  123. }
  124. }
  125. // CacheStats provides detailed cache statistics
  126. type CacheStats struct {
  127. Size int `json:"size"` // Current number of items
  128. Capacity int `json:"capacity"` // Maximum capacity
  129. HitCount int64 `json:"hit_count"` // Number of cache hits
  130. MissCount int64 `json:"miss_count"` // Number of cache misses
  131. HitRate float64 `json:"hit_rate"` // Cache hit rate (0.0 to 1.0)
  132. Evictions int64 `json:"evictions"` // Number of evicted items
  133. Additions int64 `json:"additions"` // Number of items added
  134. Updates int64 `json:"updates"` // Number of items updated
  135. Cost int64 `json:"cost"` // Current cost
  136. }
  137. // WarmupCache pre-loads frequently used queries into cache
  138. func (osc *OptimizedSearchCache) WarmupCache(queries []WarmupQuery) {
  139. for _, query := range queries {
  140. // Pre-generate keys to warm up the cache
  141. key := osc.GenerateOptimizedKey(query.Request)
  142. if query.Result != nil {
  143. osc.cache.Set(key, query.Result, 1) // Use cost of 1 for warmup
  144. }
  145. }
  146. // Wait for cache operations to complete
  147. osc.cache.Wait()
  148. }
  149. // WarmupQuery represents a query and result pair for cache warmup
  150. type WarmupQuery struct {
  151. Request *SearchRequest `json:"request"`
  152. Result *SearchResult `json:"result"`
  153. }
  154. // Close closes the cache and frees resources
  155. func (osc *OptimizedSearchCache) Close() {
  156. osc.cache.Close()
  157. }
  158. // FastKeyGenerator provides even faster key generation for hot paths
  159. type FastKeyGenerator struct {
  160. buffer []byte
  161. }
  162. // NewFastKeyGenerator creates a key generator with pre-allocated buffer
  163. func NewFastKeyGenerator() *FastKeyGenerator {
  164. return &FastKeyGenerator{
  165. buffer: make([]byte, 0, 256), // Pre-allocate 256 bytes
  166. }
  167. }
  168. // GenerateKey generates a key using pre-allocated buffer
  169. func (fkg *FastKeyGenerator) GenerateKey(req *SearchRequest) string {
  170. fkg.buffer = fkg.buffer[:0] // Reset buffer
  171. // Build key using buffer to avoid allocations
  172. fkg.buffer = append(fkg.buffer, "q:"...)
  173. fkg.buffer = append(fkg.buffer, req.Query...)
  174. fkg.buffer = append(fkg.buffer, "|l:"...)
  175. fkg.buffer = strconv.AppendInt(fkg.buffer, int64(req.Limit), 10)
  176. fkg.buffer = append(fkg.buffer, "|o:"...)
  177. fkg.buffer = strconv.AppendInt(fkg.buffer, int64(req.Offset), 10)
  178. fkg.buffer = append(fkg.buffer, "|s:"...)
  179. fkg.buffer = append(fkg.buffer, req.SortBy...)
  180. fkg.buffer = append(fkg.buffer, "|so:"...)
  181. fkg.buffer = append(fkg.buffer, req.SortOrder...)
  182. // Add timestamps if present
  183. if req.StartTime != nil {
  184. fkg.buffer = append(fkg.buffer, "|st:"...)
  185. fkg.buffer = strconv.AppendInt(fkg.buffer, *req.StartTime, 10)
  186. }
  187. if req.EndTime != nil {
  188. fkg.buffer = append(fkg.buffer, "|et:"...)
  189. fkg.buffer = strconv.AppendInt(fkg.buffer, *req.EndTime, 10)
  190. }
  191. // Add arrays (simplified)
  192. if len(req.StatusCodes) > 0 {
  193. fkg.buffer = append(fkg.buffer, "|sc:"...)
  194. for i, code := range req.StatusCodes {
  195. if i > 0 {
  196. fkg.buffer = append(fkg.buffer, ',')
  197. }
  198. fkg.buffer = strconv.AppendInt(fkg.buffer, int64(code), 10)
  199. }
  200. }
  201. // Convert to string (this still allocates, but fewer allocations overall)
  202. return string(fkg.buffer)
  203. }
  204. // CacheMiddleware provides middleware functionality for caching
  205. type CacheMiddleware struct {
  206. cache *OptimizedSearchCache
  207. keyGen *FastKeyGenerator
  208. enabled bool
  209. defaultTTL time.Duration
  210. }
  211. // NewCacheMiddleware creates a new cache middleware
  212. func NewCacheMiddleware(cache *OptimizedSearchCache, defaultTTL time.Duration) *CacheMiddleware {
  213. return &CacheMiddleware{
  214. cache: cache,
  215. keyGen: NewFastKeyGenerator(),
  216. enabled: true,
  217. defaultTTL: defaultTTL,
  218. }
  219. }
  220. // Enable enables caching
  221. func (cm *CacheMiddleware) Enable() {
  222. cm.enabled = true
  223. }
  224. // Disable disables caching
  225. func (cm *CacheMiddleware) Disable() {
  226. cm.enabled = false
  227. }
  228. // IsEnabled returns whether caching is enabled
  229. func (cm *CacheMiddleware) IsEnabled() bool {
  230. return cm.enabled
  231. }
  232. // GetOrSet attempts to get from cache, or executes the provided function and caches the result
  233. func (cm *CacheMiddleware) GetOrSet(req *SearchRequest, fn func() (*SearchResult, error)) (*SearchResult, error) {
  234. if !cm.enabled {
  235. return fn()
  236. }
  237. // Try cache first
  238. if cached := cm.cache.Get(req); cached != nil {
  239. return cached, nil
  240. }
  241. // Execute function
  242. result, err := fn()
  243. if err != nil {
  244. return nil, err
  245. }
  246. // Cache successful result
  247. if result != nil {
  248. cm.cache.Put(req, result, cm.defaultTTL)
  249. }
  250. return result, nil
  251. }