ExLine.ChannelAccessToken.Cache (ExLine v0.1.0)

Copy Markdown View Source

A GenServer that caches a channel access token and refreshes it before it expires.

ExLine is a library and owns no processes — you add this to your application's supervision tree, one child per channel you want to keep a warm token for:

children = [
  {ExLine.ChannelAccessToken.Cache,
   name: :my_channel,
   issue: fn ->
     ExLine.Api.ChannelAccessToken.issue_stateless(
       ExLine.Client.transport(),
       System.fetch_env!("LINE_CHANNEL_ID"),
       System.fetch_env!("LINE_CHANNEL_SECRET")
     )
   end}
]

Supervisor.start_link(children, strategy: :one_for_one)

Then build clients from the cached token wherever you send messages:

{:ok, token} = ExLine.ChannelAccessToken.Cache.token(:my_channel)
client = ExLine.Client.new(access_token: token)
ExLine.Api.Messaging.push(client, user_id, ExLine.Message.text("hi"))

The :issue function is any zero-arity function returning the same shape as the ExLine.Api.ChannelAccessToken issue functions ({:ok, %{"access_token" => ..., "expires_in" => ...}} | {:error, _}); for v2.1 tokens, have it sign an assertion with ExLine.ChannelAccessToken.Assertion.sign/1 and call issue_jwt/2.

Options

  • :issue (required) — zero-arity issue function (see above).
  • :name — process name to register under (e.g. an atom or {:via, ...} tuple).
  • :refresh_before — refresh this many seconds before expires_in (default 600).
  • :retry_after — seconds to wait before retrying a failed issue (default 30).

Summary

Functions

Returns a specification to start this module under a supervisor.

Starts the cache. See the module doc for options.

Returns the currently cached token, or {:error, :unavailable} if the first issue has not yet succeeded.

Types

t()

@type t() :: GenServer.server()

Functions

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

start_link(opts)

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

Starts the cache. See the module doc for options.

token(server)

@spec token(t()) :: {:ok, String.t()} | {:error, :unavailable}

Returns the currently cached token, or {:error, :unavailable} if the first issue has not yet succeeded.