Lavash.Rx.Cache (Lavash v0.3.0-rc.1)

Copy Markdown View Source

Module-scoped node-global cache for compiled rx() ASTs.

User-supplied ASTs (the :ast field of %Lavash.Rx{}, action run function ASTs, etc.) are stored in the Spark DSL state in quoted form. Re-evaluating them via Code.eval_quoted/3 on every fire is the slow path: it re-parses, re-expands, and re-evaluates each call.

This module caches the compiled function in :persistent_term keyed by {Lavash.Rx.Cache, module, kind, identifier} so the eval cost is paid once per module load instead of once per fire.

The Lavash compile transformers wire erase/2 into @after_compile so a hot recompile in dev drops all cached entries for the affected module.

Summary

Functions

Compile an action run lambda AST (with Phoenix.Component.assign/3 imported) into a callable function. Cached under {Lavash.Rx.Cache, module, :run_fun, ast_hash}.

Compile a %Lavash.Rx{} AST into fn state -> ... end and cache it under {Lavash.Rx.Cache, module, :rx, ast_hash}.

Drops all cached entries for module. Wired into Lavash modules' @after_compile so dev recompiles rebuild the cache from the new AST instead of returning stale fns.

Returns a cached function compiled from the given AST.

Functions

compile_run_fun(module, fun_ast)

@spec compile_run_fun(module(), Macro.t()) :: (map() -> map())

Compile an action run lambda AST (with Phoenix.Component.assign/3 imported) into a callable function. Cached under {Lavash.Rx.Cache, module, :run_fun, ast_hash}.

compile_rx(module, ast)

@spec compile_rx(module(), Macro.t()) :: (map() -> term())

Compile a %Lavash.Rx{} AST into fn state -> ... end and cache it under {Lavash.Rx.Cache, module, :rx, ast_hash}.

erase(env, bytecode)

@spec erase(Macro.Env.t(), binary() | nil) :: :ok

Drops all cached entries for module. Wired into Lavash modules' @after_compile so dev recompiles rebuild the cache from the new AST instead of returning stale fns.

Matches the @after_compile callback signature (env, bytecode).

get_or_compile(key, compile)

@spec get_or_compile(term(), (-> (term() -> term()))) :: (term() -> term())

Returns a cached function compiled from the given AST.

On the first call for a key, runs compile.() to produce the function and stashes it. Subsequent calls return the cached function directly.

compile is a thunk to defer the work until the cache misses; callers should not pay eval cost on the hit path.