cache storage entries and batch them for write-back

This commit is contained in:
BuckarooBanzay 2023-06-19 16:14:40 +02:00 committed by Athozus
parent 984d8c34d9
commit 8c20aeba5b

View File

@ -14,22 +14,62 @@ local function populate_entry(e)
return e return e
end end
local cache = {}
-- retrieve the storage entry for the player
function mail.get_storage_entry(playername) function mail.get_storage_entry(playername)
local str = mail.storage:get_string(STORAGE_PREFIX .. playername) local key = STORAGE_PREFIX .. playername
if cache[key] then
-- use cached entry
return cache[key]
end
local str = mail.storage:get_string(key)
local entry
if str == "" then if str == "" then
-- new entry -- new entry
return populate_entry() entry = populate_entry()
else else
-- deserialize existing entry -- deserialize existing entry
local e = minetest.parse_json(str) local e = minetest.parse_json(str)
return populate_entry(e) entry = populate_entry(e)
end
end end
function mail.set_storage_entry(playername, entry) -- cache for next time
mail.storage:set_string(STORAGE_PREFIX .. playername, minetest.write_json(entry)) cache[key] = entry
return entry
end end
-- entries queued for saving
local save_queued_entries = {}
-- save the storage entry for the player
function mail.set_storage_entry(playername, entry)
local key = STORAGE_PREFIX .. playername
-- cache
cache[key] = entry
-- enqueue for writing
save_queued_entries[key] = entry
end
local function save_worker()
for key, entry in pairs(save_queued_entries) do
-- write to backend
mail.storage:set_string(key, minetest.write_json(entry))
end
-- clear queue
save_queued_entries = {}
-- save every second
minetest.after(1, save_worker)
end
-- start save-worker loop
save_worker()
-- save on shutdown
minetest.register_on_shutdown(save_worker)
-- get a mail by id from the players in- or outbox -- get a mail by id from the players in- or outbox
function mail.get_message(playername, msg_id) function mail.get_message(playername, msg_id)
local entry = mail.get_storage_entry(playername) local entry = mail.get_storage_entry(playername)