Skip to content

About

An Ash extension for explicit idempotency and one-time nonce semantics

Topics

Resources

Contributing

Security policy

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

ash_onetime

ash_onetime is an Ash extension for explicit keyed-effect semantics. It separates replay-safe idempotency from collision-rejecting one-time nonces and uses PostgreSQL as the authoritative admissions store.

What it does

Every protected action declares one strategy and a nonempty scope. PostgreSQL admits exactly once per key under the declared scope; the unique constraint — not application code — decides concurrent races. There is no admission pre-read.

  • :idempotency — execute the effect once per key, store the classified response, and replay it verbatim on retries within the retention boundary. A conflicting fingerprint (same key, different request) is terminal and never re-executes. The effect, the admission claim, and the encoded response commit or roll back together in the action's transaction.
  • :one_time_nonce — authenticate a single opportunity and reject every collision. The spend lives and dies with the action transaction by default; a retry must bear a fresh proof.
  • commit: :independent (nonce, opt-in, RFC 9449 §11.1) — the DPoP replay fence. The nonce claim commits in its own transaction before the action body runs, so a downstream failure cannot make the proof reusable. A reused proof is rejected with :nonce_already_used for the retention window. Default-off; existing nonce consumers are byte-for-byte unchanged.
  • Operation holds (idempotency, opt-in) — retain a completed claim while the caller's operation stays open, then release it in the settling transaction. Unreleased holds remain forever by design; monitor the held backlog and the doctor. See Idempotency.
  • Context boundaries (v1.8.0, opt-in) — the second admission shape: a resource that declares context_boundary is backed by an append-only fact table, and AshOnetime.Boundary.append_if/5 admits an append only when no fact matching the query moved past the cutoff the caller read. Writers of one context serialize on tenant-scoped advisory locks per tag (so overlapping contexts cannot deadlock and disjoint ones never block); a changed context answers {:error, {:context_changed, max_seq}}. It enforces "nothing relevant changed since I looked" rules across records without designing a lock row per rule. See Context boundaries.

Optional, non-admitting surfaces: a response cache, a Plug, Oban workers for cleanup and forward partition creation, and an external-effect execute/recover protocol for peers that need to observe or reverse a side effect — serialized by a pre-peer claim lock so concurrent same-key retries cannot overlap at the peer (v1.4.0, ADR-0010).

Hosts that already own one authoritative Ecto transaction can use the public AshOnetime.Transaction boundary instead of wrapping an Ash action. It reserves idempotency and nonce authority inside the caller's existing READ COMMITTED transaction, so the claim, the host effect, and the exact replay bytes commit or roll back together. Logical partitions isolate tenants or authority planes without importing the host's actor types. See Transaction-owned admission.

When to use this vs. hand-rolled idempotency

Use ash_onetime when you need a correct admission layer for effectful Ash actions and do not want to re-derive the failure modes a hand-rolled table-plus-flag approach ships with.

  • The correctness guarantee: a PostgreSQL-authoritative, once-per-key local effect and typed replay within the declared retention boundary. The effect, the admission claim, and the encoded response commit or roll back together in the action's existing transaction; there is no admission pre-read, so the unique constraint — not application code — decides concurrent races. A conflicting fingerprint is terminal and never re-executes.
  • What it replaces: the bespoke idempotency-key table, the "did this already run?" pre-check that races under concurrency, the stored-response schema you have to version and re-encode, the fingerprint binding you have to remember to update, and the silent double-execution that lands when you forget. Each of these is a class of bug this library was built to make impossible at the boundary.
  • When NOT to use it: read-only or non-transactional actions (the library rejects them), resources without AshPostgres (PostgreSQL is the authoritative store; there is no fallback), and workloads that need end-to-end exactly-once delivery rather than once-per-key local admission (delivery is a separate concern — see External effects). If you have no effectful action to protect, there is nothing to admit.

Quick start

defmodule MyApp.Charge do
  use Ash.Resource,
    domain: MyApp.Domain,
    data_layer: AshPostgres.DataLayer,
    extensions: [AshOnetime.Resource]

  postgres do
    table "charges"
    repo MyApp.Repo
  end

  attributes do
    uuid_primary_key :id
    attribute :account_id, :uuid, allow_nil?: false, public?: true
    attribute :amount, :integer, allow_nil?: false, public?: true
  end

  actions do
    defaults [:read]

    create :charge do
      transaction? true
      argument :idempotency_key, :string, allow_nil?: false
      accept [:account_id, :amount]
    end

    # A DPoP-protected redemption: the proof's spend survives a downstream failure.
    action :redeem, :integer do
      transaction? true
      argument :value, :integer, allow_nil?: false
      argument :proof, :string, allow_nil?: false
      run MyApp.Redeem
    end
  end

  onetime do
    protect :charge do
      strategy :idempotency
      scope([{:static, "charge"}, {:attribute, :account_id}])
      key({:client, :idempotency_key})
      fingerprint(attributes: [:account_id, :amount])
      response(MyApp.ChargeCodec, fields: [:id, :account_id, :amount], classify: MyApp.Classifier)
      retention({24, :hour})
    end

    protect :redeem do
      strategy :one_time_nonce
      scope([{:static, "redeem"}])
      key({:verified, :proof, MyApp.ProofVerifier})
      window(max_age: {5, :minute}, clock_skew: {30, :second})
      commit :independent   # RFC 9449 §11.1 replay fence (omit for the default :with_action)
    end
  end
end

Install with mix ash_onetime.install (Igniter-powered) — it wires the repo, generates the migration, and sets up the schema. See the Getting started guide for the full walkthrough.

Try it

Runnable Livebook notebooks — one per concern — walk through each strategy against a real PostgreSQL. Open them in Livebook, set DATABASE_URL, and run every cell.

See Security model for the authority and fail-closed contract, and Recipes for end-to-end payment, webhook, redemption, and transactional-outbox patterns.

Status

This guide targets v2.0.0. Context boundaries admit an append only when nothing matching changed since read. Partition pruning checks emptiness as the table owner; existing installs must generate and apply the maintenance upgrade migrations (see Upgrading). Fact tables are opt-in with --fact-tables.

Every protected action declares :idempotency or :one_time_nonce and a nonempty scope; neither has a fallback.

Compatibility

  • Elixir ~> 1.20 (developed and tested on 1.20.5; this requirement admits later 1.x releases and excludes 2.0 or newer)
  • Erlang/OTP 28 or 29
  • Ash >= 3.37.2 and < 4.0.0
  • AshPostgres ~> 2.15 and >= 2.15.2, AshSql ~> 0.8 and >= 0.8.6
  • Optional Mint ~> 1.10 and >= 1.10.2 when the host carries the installer HTTP closure
  • PostgreSQL 17 and 18. Work and qualification run the whole suite on the checked PostgreSQL 18 platform engine and the pinned upstream PostgreSQL 17 compatibility image. The generated maintenance SQL uses PostgreSQL 17's MAINTAIN privilege checks and revocations.

The security floors follow ADR 0004. Ash 3.37.2 and AshPostgres 2.15.2 include the required authorization and tenant-isolation fixes. AshSql 0.8.6 fixes query-cache security; the affected 0.8.4 and 0.8.5 releases are retired. Mint 1.10.2 fixes HTTP/2 memory exhaustion and HTTP/1 response smuggling. Optional integrations remain excluded from this package's runtime applications.

Development

Push a work branch to run Work on GitHub's hosted Ubuntu runners. Every database job starts the checked platform PostgreSQL engine through the shared action, including its dedicated logical server when needed. Compile, tests, format, docs and type checks run there; agents never run them on a workstation. The engine startup and environment contract are documented in CONTRIBUTING.md.

See CONTRIBUTING.md for the complete gate battery and usage-rules.md for non-negotiable integration boundaries. The Getting started guide covers installing the package and protecting your first action.

Handling results at the call boundary

A protected action's failure carries a typed :code that survives the Ash pipeline, and its success carries a replayed-vs-fresh signal. Both are observable after Ash.create/2 / Ash.run_action/2 returns:

case Ash.create(changeset) do
  {:ok, record} ->
    # 201 on fresh execution (replayed? == false), 200 + Idempotent-Replayed on retry (true).
    status = if AshOnetime.replayed?(record), do: 200, else: 201

  {:error, error} ->
    # The typed code reaches the caller — map it to HTTP.
    case AshOnetime.Error.code(error) do
      :nonce_already_used -> {:conflict, "nonce was already used"}
      :key_reused_with_different_request -> {:conflict, "key reused with a different request"}
      :request_in_progress -> {:conflict, "request is already processing"}
      nil -> {:internal_server_error, "unexpected error"}
    end
end

AshOnetime.replayed?/1 is tri-state: true (tracked replay), false (tracked fresh), or nil (untracked execution, primitive-return action, or unprotected — see Replay). The full code→HTTP table is in Errors.

Guides

License

MIT. See the repository LICENSE file.

About

An Ash extension for explicit idempotency and one-time nonce semantics

Topics

Resources

Contributing

Security policy

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages