added caching to map results
All checks were successful
Run Integration Tests / test (push) Successful in 19s

This commit is contained in:
partisan 2024-12-05 19:47:53 +01:00
parent f2d9a37e87
commit 7498f4128a
3 changed files with 77 additions and 4 deletions

View file

@ -62,6 +62,23 @@ type ForumSearchResult struct {
ThumbnailSrc string `json:"thumbnailSrc,omitempty"`
}
// GeocodeCachedItem represents a geocoding result stored in the cache.
type GeocodeCachedItem struct {
Latitude string
Longitude string
Found bool
StoredTime time.Time
}
// GeocodeCache is a thread-safe map for caching geocoding results.
type GeocodeCache struct {
mu sync.Mutex
results map[string]GeocodeCachedItem
expiration time.Duration
}
var geocodeCache *GeocodeCache
// CacheKey represents the key used to store search results in the cache.
type CacheKey struct {
Query string
@ -95,6 +112,15 @@ func NewResultsCache() *ResultsCache {
}
}
// NewGeocodeCache creates a new GeocodeCache with a specified expiration duration.
func NewGeocodeCache() *GeocodeCache {
printDebug("Initializing geocode cache with expiration: %s", config.RamCache.Duration)
return &GeocodeCache{
results: make(map[string]GeocodeCachedItem),
expiration: config.RamCache.Duration,
}
}
// Get retrieves the results for a given key from the cache.
func (rc *ResultsCache) Get(key CacheKey) ([]SearchResult, bool) {
rc.mu.Lock()
@ -151,6 +177,38 @@ func (rc *ResultsCache) currentMemoryUsage() uint64 {
return v.Used // Used memory in bytes
}
// Get retrieves the geocoding result for a given query from the cache.
func (gc *GeocodeCache) Get(query string) (latitude, longitude string, found bool, exists bool) {
gc.mu.Lock()
defer gc.mu.Unlock()
item, exists := gc.results[query]
if !exists {
return "", "", false, false
}
// Check if the item has expired
if time.Since(item.StoredTime) > gc.expiration {
delete(gc.results, query)
printDebug("Geocode cache expired for query: %s", query)
return "", "", false, false
}
return item.Latitude, item.Longitude, item.Found, true
}
func (gc *GeocodeCache) Set(query, latitude, longitude string, found bool) {
gc.mu.Lock()
defer gc.mu.Unlock()
gc.results[query] = GeocodeCachedItem{
Latitude: latitude,
Longitude: longitude,
Found: found,
StoredTime: time.Now(),
}
}
func (rc *ResultsCache) cleanOldestItems() {
rc.mu.Lock()
defer rc.mu.Unlock()