juicycleff / casbin-mongodb-adapter

Pure MongoDB adapter for Casbin
MIT License
9 stars 14 forks source link

savePolicy behavior #4

Closed fchristl closed 4 years ago

fchristl commented 4 years ago

I am working on a project that deals with a larger amount of permissions. There is a REST service to manage permissions/roles. Each time a permission or role has been changed, I called await enforcer.savePolicy();.

Now I realized that savePolicy effectively drops the entire casbin mongo collection and re-creates it with the new policy data. When calling it in concurrent scenarios (e.g. I have two concurrent requests to add a permission), that results in the following situation:

  1. The first permission is created,
  2. savePolicy is called and drops the collection,
  3. the second permission is created,
  4. savePolicy is called and drops the collection,
  5. At the end, only the second permission is in the collection.

In other scenarios (I cannot quite reproduce when exactly), step 4 throws an error (ns not found) as it apparently tries to perform operations on the now-dropped collection.

I solved this in my application now by waiting for all write operations to finish, and only then call savePolicy.

Is this something that could be implemented in the adapter itself? Alternatively, would this behavior be something worth mentioning in the documentation?

Update: The problem only occured once we moved to a replica set rather than a single Mongo instance.

hsluoyz commented 4 years ago

You should enable AutoSave: https://casbin.org/docs/en/adapters#autosave

fchristl commented 4 years ago

Oops. Thank you very much!