Localize.FormatCache (Localize v0.32.0)

Copy Markdown View Source

An ETS-backed cache for compiled format patterns.

Number format metadata and datetime format tokens are cached here after first compilation. The cache is hard-bounded: when inserting an entry would exceed the configured maximum, an existing entry is evicted synchronously, keeping the cache at or below the cap at all times.

The maximum number of entries defaults to 2,000 and can be overridden with:

config :localize, :format_cache_max_entries, 5_000

Trust model

The ETS table is :protected — only the cache GenServer can write to it; any process can read directly. This keeps the cache from being polluted by other libraries running in the same BEAM, and ensures the size invariant cannot be violated by a non-owner write.

Writes go through store/2, which is a GenServer.call to the owner. A miss-then-store pattern from a hot path therefore pays one gen-server round-trip per first-time format compilation; subsequent lookups are direct ETS reads with no synchronisation cost.

Summary

Functions

Returns a specification to start this module under a supervisor.

Clears all entries from the cache.

Look up a compiled format pattern by its cache key.

Returns the configured maximum number of cache entries.

Returns the current number of entries in the cache.

Store a compiled format pattern in the cache.

Functions

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

clear()

@spec clear() :: :ok

Clears all entries from the cache.

Routed through the GenServer so the operation respects the table's :protected ownership. Intended for tests and maintenance; production callers should not need this.

lookup(key)

@spec lookup(term()) :: {:ok, term()} | :miss

Look up a compiled format pattern by its cache key.

Arguments

  • key is the cache key, typically a tuple like {:localize, :number_format_meta, format_string}.

Returns

  • {:ok, value} if the key is present.

  • :miss if not cached or the table does not exist.

max_entries()

@spec max_entries() :: pos_integer()

Returns the configured maximum number of cache entries.

size()

@spec size() :: non_neg_integer()

Returns the current number of entries in the cache.

Primarily useful in tests; production callers should not need to inspect the size directly.

store(key, value)

@spec store(term(), term()) :: :ok

Store a compiled format pattern in the cache.

Routed through the cache GenServer so the size cap can be enforced synchronously. If the table doesn't exist (e.g. during a bare unit test), the call is a no-op.

Arguments

  • key is the cache key.

  • value is the compiled artifact to cache.

Returns

  • :ok.