macula_did_cache (macula v0.20.5)

View Source

DID Parsing Cache Module.

Provides high-performance caching for parsed DID (Decentralized Identifier) results using persistent_term for fast reads. This avoids repeated parsing of DIDs during authorization checks.

Usage

Parse and cache a DID (or get from cache):

{ok, Parsed} = macula_did_cache:get_or_parse(DID).

Returns a map with method, identity, parts, and depth.

Invalidate a specific DID from cache:

ok = macula_did_cache:invalidate(DID).

Clear entire cache:

ok = macula_did_cache:clear().

Performance

persistent_term provides O(1) lookups with zero garbage collection impact, making it ideal for frequently-accessed, rarely-changed data like parsed DIDs.

Note: persistent_term:put/2 triggers a global GC, so this cache is optimized for read-heavy workloads where DIDs are parsed once and looked up many times.

Cache Key Format

Keys are stored as {macula_did_cache, DID} tuples to avoid namespace conflicts.

Summary

Functions

Get the current number of cached DIDs.

Clear all cached DIDs.

Get parsed DID from cache, or parse and cache if not present.

Invalidate (remove) a specific DID from the cache.

Types

did/0

-type did() :: binary().

parsed_did/0

-type parsed_did() :: #{binary() => binary() | [binary()] | integer()}.

Functions

cache_size()

-spec cache_size() -> non_neg_integer().

Get the current number of cached DIDs.

Useful for monitoring and debugging.

clear()

-spec clear() -> ok.

Clear all cached DIDs.

Warning: This triggers a global GC for each erased term. Use sparingly.

get_or_parse(DID)

-spec get_or_parse(DID :: did()) -> {ok, parsed_did()} | {error, invalid_did}.

Get parsed DID from cache, or parse and cache if not present.

This is the main entry point for cached DID parsing. If the DID has been parsed before, returns the cached result. Otherwise, parses the DID, caches the result, and returns it.

Returns {ok, ParsedDID} on success, {error, invalid_did} if parsing fails.

invalidate(DID)

-spec invalidate(DID :: did()) -> ok.

Invalidate (remove) a specific DID from the cache.

Use this when a DID's parsing result may have changed (rare in practice, as DIDs are typically immutable identifiers).