bcosca / fatfree

A powerful yet easy-to-use PHP micro-framework designed to help you build dynamic and robust Web applications - fast!
2.66k stars 446 forks source link

Mongo mapper and concurrency #986

Open jonathan-roy opened 7 years ago

jonathan-roy commented 7 years ago

Due to the way the active record pattern is implemented in the Mongo mapper, some data can be lost in the following situation:

Around the same time, clients 'A' and 'B' executes the same script that loads the exact same document from the Mongo DB, modifies it then saves the document back to DB.

-> updates done by either client 'A' or client 'B' (actually the first one who finishes) will be lost.

Maybe this could be solved by updating only the modified properties instead of the whole document? Or maybe a 'lock' feature could be added in the mapper (eventually in the same way as 'select for update' works)?

ikkez commented 7 years ago

Are you sure that this is caused by mongo and is not an issue of "loading a record to a form in a frontend and having 2 users, who work on the same document and save this at different times" which then lead to you race condition issue? I think you should take care of this in your business application code. I doubt that the framework can guess what data is correct.

xfra35 commented 7 years ago

But shouldn't the mapper update only the modified fields, such as what is performed in the SQL mapper?

With the current implementation, if A and B load data at the same time and update different fields, the latest update will overwrite all the fields written by the first update. E.g:

10:00 A and B load user John Doe, age=20, city=Berlin
10:05 A sets age=21
10:10 B sets city=Warsow

At the end, John Doe's age is 20 again because B has overwritten all the fields instead of just one.

jonathan-roy commented 7 years ago

Yes it was not clear in my initial post, as xfra35 said the problem only concerns when different fields of the same object are modified by differents users. I also think that this should be solved by the mapper by updating only the modified fields.

ikkez commented 7 years ago

alright. well looking at the docs about updating mongo documents it looks like this should be possible. We could probably add the same changed mechanics from the sql mapper here, to determine what fields to update. I'm just completely out of time atm.

jonathan-roy commented 6 years ago

Any news on this issue?