NoNoncense.MachineId.Strategy.SqlLease (NoNoncense v2.2.0)

Copy Markdown View Source

Strategy to acquire a machine ID lease from a SQL database (Postgres or MySQL), coordinating uniqueness across nodes through a single table.

Each machine ID (0..511) is a row in the table. A node claims an expired row using a random token and renews it periodically. The strategy protects ID reuse between nodes against clock skew by recording the lease holder's local expiry and requiring the successor's local clock to pass that cutoff. Requires a table with one pre-populated row per possible machine ID - see the migration below.

Configure the strategy when starting NoNoncense.MachineId and add it after your Repo:

children = [
  ...
  MyApp.Repo,
  {NoNoncense.MachineId,
   strategy: NoNoncense.MachineId.Strategy.SqlLease,
   strategy_opts: [repo: MyApp.Repo],
   instances: [[base_key: System.fetch_env!("BASE_KEY")]]}
]

Options

  • :repo (required) - the Ecto.Repo to run queries against
  • :table - the table leases are stored in (default "no_noncense_leases")

Migration

Use migrate/1 to create and populate the table in an Ecto migration. To use a custom table, pass :table_name to migrate/1 and the same name as :table in strategy_opts.

defmodule MyApp.Repo.Migrations.NoNoncenseLeases do
  use Ecto.Migration

  def change, do: NoNoncense.MachineId.Strategy.SqlLease.migrate()
end

Note that the migration has to run before you can configure NoNoncense.MachineId with this strategy. Without the migration, the strategy can't acquire a machine ID and will prevent the application from starting.

Summary

Functions

Convenience helper for creating the leases table in an Ecto migration.

Types

migrate_opt()

@type migrate_opt() :: {:table_name, String.t()}

opt()

@type opt() :: {:table, String.t()} | {:repo, module()}

Functions

migrate(opts \\ [])

@spec migrate([migrate_opt()]) :: term()

Convenience helper for creating the leases table in an Ecto migration.

Creates "no_noncense_leases" with id, token, expires_at, and lock_version columns, and populates all 512 IDs.

Options

  • :table_name - override the table name; pass the same name as :table to the strategy