@Quatermass
Or basically, having a small battery alongside the Raspi. Theoretically, it could be pretty simple to create:
Battery, that gives exact 4.7V.
Custom commands to Raspi to trigger shutdown process, once the voltage drops below 4.75V (IE, when the main power line shuts down and the voltage drops from normal 5-5.1V to the battery voltage).
And Battery would charge up in every time you use/start Raspi for some time, or could be charged separately in short time.