DetoxifySh.Cache (DetoxifySh v0.1.0)

Copy Markdown

Keeps recent results in memory, so analyzing the same text again neither calls the API nor is charged (the API charges for its own cache hits).

A cache is a process owning an ETS table. The :detoxify_sh application starts one, named DetoxifySh.Cache, which every client uses unless told otherwise, so caching works with no setup. To size one differently, or to keep one part of an application's results apart, start your own under your supervisor and name it in DetoxifySh.new/1:

children = [
  {DetoxifySh.Cache, name: MyApp.DetoxifyCache, max_size: 5_000}
]

DetoxifySh.new(cache: MyApp.DetoxifyCache)

The default cache takes the same options from config :detoxify_sh, cache: [...]; config :detoxify_sh, cache: false does not start it.

Options:

  • :name - required: the process's and the ETS table's name.
  • :max_size - how many results to keep; the least recently used goes first. Default 1,000; 0 keeps none.
  • :max_age - how long a result is kept after it was fetched, in milliseconds, however often it is read. Default six hours; :infinity keeps it until it is pushed out.

Lookups read the table directly from the calling process, so concurrent callers do not queue behind each other; only storing a result, and noting that one was read, go through the process.

Summary

Functions

Returns a specification to start this module under a supervisor.

Forgets every result.

The value kept for key, or :miss. A cache that is not running is a miss, so a client keeps working without one.

Keeps value for key. Does nothing if the cache is not running.

How many results the cache holds, expired ones included until they are noticed.

Starts a cache. See the module documentation for the options.

Functions

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

clear(cache)

@spec clear(atom()) :: :ok

Forgets every result.

get(cache, key)

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

The value kept for key, or :miss. A cache that is not running is a miss, so a client keeps working without one.

put(cache, key, value)

@spec put(atom(), term(), term()) :: :ok

Keeps value for key. Does nothing if the cache is not running.

size(cache)

@spec size(atom()) :: non_neg_integer()

How many results the cache holds, expired ones included until they are noticed.

start_link(options)

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

Starts a cache. See the module documentation for the options.