If the autosave file is damaged in any way (suppose that turning off the power when the file is in the middle of saving will do this?), The user will lose his job. How can I prevent such situations and do my best to ensure that the autosave document is in a consistent state?
To prevent data loss due to a partially recorded autosave file, do not overwrite the autosave file. Instead, write to a new file each time, and then rename it as soon as the file is securely written.
Not to forget that the autosave file was not written correctly:
- Note the exceptions that were reset when the autosave file is written and closed in the event of a disk error, a complete file system, etc.
- Keep the current checksum of the file when it is written, and write it at the end of the file. Then, when you download the autosave file, check that the checksum exists and is correct.
If the check state contains several files, make sure that you write the files in a known order (without overwriting!) And write the checksum to the autosave file after all other files have been safely closed. You might want to create a directory for each checkpoint.
FOLLOW UP
No. I am not saying that renaming always succeeds. However, it is atomic — it either succeeds (and completes), or the file system does not change. So if you do this:
- write "file.new" and close,
- delete a file" ,
- rename the file "file.new" to "file"
then, provided that the first step is successful, you are guaranteed to receive the last “file” on disk. And just add a few steps so that you have a backup of the “file” at any time. (If the 3rd step is unsuccessful, you will remain with the file “file.new” and no “file.” This can be restored manually or automatically by the application the next time you start.)
Also, I'm not saying that records always succeed, or that applications do not crash, or that power never goes out. And the point of the checksum is to allow you to detect cases when this happened, and the autosave file is incomplete.
Finally, it’s nice to have two autosaves if your application gets into a state where its data structures are mixed up and the last autosave as a result is pointless. (The checksum will not protect against this.) Be careful when autosaving when the application crashes for the same reason.
source share