# erni27/imcache architecture

> Architecture diagram of the GitHub repository erni27/imcache, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-04-24). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/erni27/imcache
- Repository: https://github.com/erni27/imcache

## Overview

##### Project type and purpose
- imcache is a Go‐based, zero-dependency, generic in-memory cache library intended for embedding in Go applications rather than a standalone service or web app.
- It provides core caching features: expiration (absolute and sliding), eviction policies (LRU, LFU, random), max-entries limits, optional background cleaning, sharding, and eviction callbacks.

##### File structure
- Top‐level Go source files:
- imcache.go       – the main Cache struct and methods
- imcache_test.go  – unit tests for Cache
- imcache_benchmark_test.go – performance benchmarks
- cleaner.go       – implementation of the background Cleaner
- eviction.go      – eviction policy logic and callbacks
- expiration.go    – expiration tracking and utilities
- hasher.go        – Hasher64 interface and default implementations
- option.go        – functional option definitions and parsing
- cleaner.go, eviction.go, expiration.go, hasher.go follow a modular package structure
- go.mod declares dependencies (none external)
- CI, coverage, and linting configs (.github, .codecov.yaml)

##### README for additional insights
- Explains Cache vs. Sharded, functional options for configuration, and example usage.
- Highlights concurrency safety, shards for parallelism, and extension points (custom Hasher, eviction callback).

##### Components
a. Core Cache component
- In-memory store (Go map[K]entry[V])
- Mutex lock for concurrency
- Entry metadata: value, expiration timestamp, usage counters (for LFU), last access (for LRU/sliding)
- Methods: Set, Get, Peek, Delete, Clear, Close
b. Sharded Cache
- Composed of N Cache shards
- Hasher64 to map keys → shard index (keyHash % N)
- Exposes same API as Cache but forwards calls to the appropriate shard
c. Cleaner
- Background goroutine per Cache (activated via WithCleanerOption)
- Periodically scans and removes expired entries
d. Eviction subsystem
- Triggered when maxEntries is set or on access
- EvictionPolicy interface: LRU, LFU, Random strategies
- EvictionCallback: user-provided hook invoked asynchronously on evictions
e. Option parsing
- Functional Option pattern (WithExpiration, WithMaxEntriesLimit, etc.)
- Options applied at creation (New or NewSharded) and per-entry (Set)

##### Relationships and interactions
- User code → calls Cache or Sharded methods
- Cache uses map + mutex internally
- On Set/Get/Delete:
- Check expiration (expiration.go)
- Possibly trigger eviction (eviction.go)
- Invoke eviction callback (eviction.go → user callback)
- Update LRU/LFU metadata
- Cleaner → periodically invokes Cache.purgeExpired()
- Sharded → dispatches each API call to a specific shard based on hasher.go
- Option handling (option.go) → configures Cache/Sharded at construction time

##### Architectural patterns and design principles
- Functional Options pattern for high configurability without explosion of constructors
- Composition over inheritance: Sharded wraps multiple Cache instances
- Pluggable strategies via interfaces (EvictionPolicy, Hasher64)
- Concurrency safety via per-shard mutexes and goroutine isolation (Cleaner, callback)
- Single responsibility: each .go file focuses on a single concern (expiration, eviction, etc.)

2. Inside Cache<K,V>:
- “expiration.go” and “eviction.go” modules to the map.
6. For Sharded<K,V>:
- Core modules (Cache, Sharded, map): blue
- Concurrency (mutex, Cleaner, callbacks): green
- Extension (options, policies, hasher): orange

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% User
    User["User Code"]:::external

    %% Core Modules
    subgraph "Core Modules" 
        direction TB
        Cache["Cache<K,V>"]:::core
        MapStore["map[K]entry\n🔒 Mutex"]:::core
        Expiration["Expiration Module"]:::core
        EvictionSub["Eviction Subsystem"]:::core
        Policies["EvictionPolicy\nLRU / LFU / Random"]:::extension
        Callback["EvictionCallback"]:::concurrency
    end

    %% Sharded
    subgraph "Sharded Cache" 
        direction TB
        Sharded["Sharded<K,V>"]:::core
        Hasher["Hasher64"]:::extension
    end

    %% Cleaner
    Cleaner["Cleaner\n(purgeExpired)"]:::concurrency

    %% Options
    Options["Functional Options Parser"]:::extension

    %% Tests & CI
    subgraph "Tests & CI"
        direction TB
        UnitTests["Unit Tests"]:::test
        BenchTests["Benchmark Tests"]:::test
        CI["CI (GitHub Actions)"]:::infra
        Coverage["Codecov Config"]:::infra
    end

    %% Flows
    User -->|"calls Set/Get/Delete"| Cache
    User -->|"calls Set/Get/Delete"| Sharded
    Sharded -->|"select shard via Hasher"| Hasher
    Hasher -->|"keyHash % N"| Cache
    Cache -->|reads/writes| MapStore
    Cache -->|"check expirations"| Expiration
    Cache -->|"trigger eviction"| EvictionSub
    Expiration -->|tracks| MapStore
    EvictionSub -->|implements| Policies
    EvictionSub -->|"async invoke"| Callback
    Cleaner -->|periodic purge| Cache
    Options -->|configure| Cache
    Options -->|configure| Sharded

    %% Tests & CI flows
    UnitTests -->|test Cache/Sharded| Cache
    BenchTests -->|benchmark| Cache
    CI -->|runs tests| UnitTests
    CI -->|runs benchmarks| BenchTests
    CI -->|uploads| Coverage

    %% Click Events
    click Cache "https://github.com/erni27/imcache/blob/master/imcache.go"
    click Sharded "https://github.com/erni27/imcache/blob/master/imcache.go"
    click Cleaner "https://github.com/erni27/imcache/blob/master/cleaner.go"
    click EvictionSub "https://github.com/erni27/imcache/blob/master/eviction.go"
    click Expiration "https://github.com/erni27/imcache/blob/master/expiration.go"
    click Hasher "https://github.com/erni27/imcache/blob/master/hasher.go"
    click Options "https://github.com/erni27/imcache/blob/master/option.go"
    click UnitTests "https://github.com/erni27/imcache/blob/master/imcache_test.go"
    click BenchTests "https://github.com/erni27/imcache/blob/master/imcache_benchmark_test.go"
    click CI "https://github.com/erni27/imcache/blob/master/.github/workflows/ci.yaml"
    click Coverage "https://github.com/erni27/imcache/blob/master/.codecov.yaml"

    %% Styles
    classDef core fill:#cfe2f3,stroke:#2b70c9,color:#0b3d91
    classDef extension fill:#ffe5b4,stroke:#e69500,color:#993d00
    classDef concurrency fill:#d4edda,stroke:#2a7f34,color:#1a4f1a
    classDef external fill:#f0f0f0,stroke:#999,color:#333
    classDef test fill:#e2e3e5,stroke:#6c757d,color:#343a40
    classDef infra fill:#fff3cd,stroke:#856404,color:#665c00
```
