Nebulex.Adapter.Transaction behaviour (Nebulex v3.0.0-rc.1)

View Source

Specifies the adapter Transaction API.

Default implementation

This module also provides a default implementation which uses the Erlang library :global.

This implementation accepts the following options:

  • :keys (list of term/0) - The list of keys the transaction will lock. Since the lock ID is generated based on the key, the transaction uses a fixed lock ID if the option is not provided or is an empty list. Then, all subsequent transactions without this option (or set to an empty list) are serialized, and performance is significantly affected. For that reason, it is recommended to pass the list of keys involved in the transaction. The default value is [].

  • :nodes (list of atom/0) - The list of the nodes where to set the lock.

    The default value is [node()].

  • :retries (:infinity | non_neg_integer/0) - If the key has already been locked by another process and retries are not equal to 0, the process sleeps for a while and tries to execute the action later. When :retries attempts have been made, an exception is raised. If :retries is :infinity (the default), the function will eventually be executed (unless the lock is never released). The default value is :infinity.

Let's see an example:

MyCache.transaction fn ->
  counter = MyCache.get(:counter)
  MyCache.set(:counter, counter + 1)
end

Locking only the involved key (recommended):

MyCache.transaction(
  fn ->
    counter = MyCache.get(:counter)
    MyCache.set(:counter, counter + 1)
  end,
  [keys: [:counter]]
)

MyCache.transaction(
  fn ->
    alice = MyCache.get(:alice)
    bob = MyCache.get(:bob)
    MyCache.set(:alice, %{alice | balance: alice.balance + 100})
    MyCache.set(:bob, %{bob | balance: bob.balance + 100})
  end,
  [keys: [:alice, :bob]]
)

Summary

Callbacks

Returns {:ok, true} if the current process is inside a transaction; otherwise, {:ok, false} is returned.

Runs the given function inside a transaction.

Callbacks

in_transaction?(adapter_meta, opts)

Returns {:ok, true} if the current process is inside a transaction; otherwise, {:ok, false} is returned.

If there's an error with executing the command, {:error, reason} is returned, where reason is the cause of the error.

See Nebulex.Cache.in_transaction?/1.

transaction(adapter_meta, fun, opts)

Runs the given function inside a transaction.

If an Elixir exception occurs, the exception will bubble up from the transaction function. If the cache aborts the transaction, it returns {:error, reason}.

A successful transaction returns the value returned by the function wrapped in a tuple as {:ok, value}.

See Nebulex.Cache.transaction/2.