ExZarr.ChunkCache (ExZarr v1.1.0)

View Source

LRU (Least Recently Used) cache for array chunks.

Provides a GenServer-based cache for recently accessed chunks to improve performance for repeated reads. The cache automatically evicts the least recently used entries when the size limit is reached.

Features

  • Thread-safe concurrent access
  • Configurable size limit
  • LRU eviction policy
  • Automatic cleanup

Configuration

Configure the cache size in your application config:

config :ex_zarr, chunk_cache_size: 1000  # Number of chunks to cache

Usage

# Cache is automatically started with ExZarr application
{:ok, pid} = ExZarr.ChunkCache.start_link(max_size: 1000)

# Put chunk in cache
:ok = ExZarr.ChunkCache.put(cache_key, chunk_data)

# Get chunk from cache
{:ok, chunk_data} = ExZarr.ChunkCache.get(cache_key)
# or
:not_found = ExZarr.ChunkCache.get(cache_key)

# Clear entire cache
:ok = ExZarr.ChunkCache.clear()

Summary

Functions

Returns a specification to start this module under a supervisor.

Clears the entire cache.

Retrieves a chunk from the cache.

Removes a specific chunk from the cache.

Stores a chunk in the cache.

Starts the chunk cache GenServer.

Returns cache statistics.

Types

cache_key()

@type cache_key() :: {String.t(), tuple()}

chunk_data()

@type chunk_data() :: binary()

Functions

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

clear(server \\ __MODULE__)

@spec clear(GenServer.server()) :: :ok

Clears the entire cache.

get(key, server \\ __MODULE__)

@spec get(cache_key(), GenServer.server()) :: {:ok, chunk_data()} | :not_found

Retrieves a chunk from the cache.

Returns {:ok, chunk_data} if found, or :not_found if not in cache. Updates the access time for LRU tracking.

invalidate(key, server \\ __MODULE__)

@spec invalidate(cache_key(), GenServer.server()) :: :ok

Removes a specific chunk from the cache.

Used when a chunk is modified to invalidate the cached copy.

put(key, data, server \\ __MODULE__)

@spec put(cache_key(), chunk_data(), GenServer.server()) :: :ok

Stores a chunk in the cache.

If the cache is full, evicts the least recently used chunk.

start_link(opts \\ [])

@spec start_link(keyword()) :: GenServer.on_start()

Starts the chunk cache GenServer.

Options

  • :max_size - Maximum number of chunks to cache (default: 1000)
  • :name - Process name (default: ExZarr.ChunkCache)

stats(server \\ __MODULE__)

@spec stats(GenServer.server()) :: map()

Returns cache statistics.

Returns a map with:

  • :size - Current number of cached chunks
  • :max_size - Maximum cache capacity
  • :hits - Number of cache hits
  • :misses - Number of cache misses
  • :hit_rate - Percentage of requests that were hits