How projectdiscovery/gcache works
Project type and purpose
• This is a Go‐based, in‐process cache library (gcache) providing multiple eviction strategies (Simple, LRU, LFU, ARC), optional expiration, loader functions, and event hooks. It is intended to be embedded in other Go applications to provide thread‐safe, in‐memory caching.
File structure
• Top‐level “.go” files (arc.go, lru.go, lfu.go, simple.go) each implement a CacheStrategy.
• cache.go defines the Cache interface and the core cache manager / builder.
• singleflight.go implements a request‐coalescing loader.
• stats.go, clock.go, utils.go support expiration, statistics, and misc helpers.
• internal/list implements a doubly‐linked list for LRU/ARC.
• tests validate each component; examples/ shows usage.
README for additional insights
• Describes how to choose and build caches with different strategies, expiration, loader functions, and event handlers.
• Emphasizes concurrency safety, loader guarantees, and event hooks.
a. Main components
• Client Code
• Cache.Builder & Cache Interface
• Core Cache Manager (cache.go)
• Eviction Strategy Modules (simple, LRU, LFU, ARC)
• Storage Layer (map + internal/list for ordering)
• Singleflight Loader (singleflight.go)
• Expiration & Clock (clock.go)
• Event Handlers (Evicted, Added, Purge hooks)
• Utility & Stats (stats.go, utils.go)
b. Relationships & Interactions
• Client calls Builder → selects Strategy → Build() → returns a Cache instance.
• Client invokes Cache.Set/Get methods on Cache instance.
• Cache.Get:
• Checks map; if miss and loader configured, delegates to singleflight to call user LoaderFunc → writes to storage.
• Checks expiration via Clock.
• Updates ordering/list in strategy.
• Fires event handlers.
• Cache.Set:
• Inserts into map + list.
• If capacity exceeded, calls chosen strategy’s evict method → removes entries → triggers EvictedFunc.
• Strategy modules depend on internal/list and utils.
• Stats module observes hits, misses, evictions.
c. Architectural patterns & design principles
• Strategy Pattern: simple, LRU, LFU, ARC algorithms interchangeable.
• Builder Pattern: chaining configuration before instantiation.
• Singleflight: request coalescing pattern to avoid thundering‐herd on loader.
• Event callback hooks for extensibility.
• Separation of concerns: core cache manager vs eviction logic vs storage vs utilities.
d. Key technologies & libraries
• Pure Go (no external dependencies).
• internal/list for doubly linked list.
• sync.RWMutex for concurrency safety.
• time package for expiration.
• internal singleflight logic (modeled after golang.org/x/sync/singleflight).
Essential elements
• Event handlers (EvictedFunc, AddedFunc, PurgeVisitorFunc)
Summary
• How the Strategy pattern and Builder pattern work together, how singleflight coalesces loads, and how hooks extend behavior.