This is an automated email from the ASF dual-hosted git repository.
hsluoyz pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/casbin-ex.git
The following commit(s) were added to refs/heads/master by this push:
new eb5fff7 feat: prevent EnforcerServer crash on duplicate casbin_rule
insert (#64)
eb5fff7 is described below
commit eb5fff7850aa9f7be42364eac2fe038f7a72afce
Author: Pratik Khadloya <[email protected]>
AuthorDate: Tue Jun 16 20:29:00 2026 +0530
feat: prevent EnforcerServer crash on duplicate casbin_rule insert (#64)
---
lib/casbin/persist/ecto_adapter.ex | 10 ++++++++--
1 file changed, 8 insertions(+), 2 deletions(-)
diff --git a/lib/casbin/persist/ecto_adapter.ex
b/lib/casbin/persist/ecto_adapter.ex
index 3b4d8a0..7d3edac 100644
--- a/lib/casbin/persist/ecto_adapter.ex
+++ b/lib/casbin/persist/ecto_adapter.ex
@@ -302,7 +302,11 @@ defmodule Casbin.Persist.EctoAdapter do
repo = Casbin.Persist.EctoAdapter.get_repo(adapter)
changeset = CasbinRule.create_changeset(policy)
- case repo.insert(changeset) do
+ # on_conflict: :nothing prevents Ecto.ConstraintError when a duplicate
rule is
+ # inserted concurrently (e.g., two nodes racing, or memory/DB state
diverging after
+ # an EnforcerServer restart). Without this, the bare insert raises and
crashes the
+ # EnforcerServer GenServer — a critical process that takes time to
restart.
+ case repo.insert(changeset, on_conflict: :nothing) do
{:ok, _casbin} -> {:ok, adapter}
{:error, changeset} -> {:error, changeset.errors}
end
@@ -375,7 +379,9 @@ defmodule Casbin.Persist.EctoAdapter do
defp insert_policy(repo, adapter, policy) do
changeset = CasbinRule.create_changeset(policy)
- case repo.insert(changeset) do
+ # on_conflict: :nothing — same rationale as add_policy/2: save_policies/2
+ # truncates then re-inserts all rules; a race or restart can cause
duplicates.
+ case repo.insert(changeset, on_conflict: :nothing) do
{:ok, _casbin} -> adapter
{:error, changeset} -> {:error, changeset.errors}
end
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]