mod_mam: Use a FIFO queue for scheduling archive expiry
authorKim Alvefur <zash@zash.se>
Tue, 12 Sep 2017 14:42:56 +0200
changeset 8233 154852646095
parent 8232 bf6f80f2d971
child 8234 97a094fdf101
mod_mam: Use a FIFO queue for scheduling archive expiry
plugins/mod_mam/mod_mam.lua
--- a/plugins/mod_mam/mod_mam.lua	Mon Sep 11 19:32:51 2017 +0200
+++ b/plugins/mod_mam/mod_mam.lua	Tue Sep 12 14:42:56 2017 +0200
@@ -56,6 +56,13 @@
 
 local cleanup;
 
+local function schedule_cleanup(username)
+	if cleanup and not cleanup[username] then
+		table.insert(cleanup, username);
+		cleanup[username] = true;
+	end
+end
+
 -- Handle prefs.
 module:hook("iq/self/"..xmlns_mam..":prefs", function(event)
 	local origin, stanza = event.origin, event.stanza;
@@ -97,7 +104,7 @@
 	local query = stanza.tags[1];
 	local qid = query.attr.queryid;
 
-	if cleanup then cleanup[origin.username] = true; end
+	schedule_cleanup(origin.username);
 
 	-- Search query parameters
 	local qwith, qstart, qend;
@@ -304,7 +311,7 @@
 			local id = ok;
 			clone_for_other_handlers:tag("stanza-id", { xmlns = xmlns_st_id, by = store_user.."@"..host, id = id }):up();
 			event.stanza = clone_for_other_handlers;
-			if cleanup then cleanup[store_user] = true; end
+			schedule_cleanup(store_user);
 			module:fire_event("archive-message-added", { origin = origin, stanza = clone_for_storage, for_user = store_user, id = id });
 		end
 	else
@@ -353,13 +360,13 @@
 	pcall(function ()
 		-- If this works, then we schedule cleanup for all known users on startup
 		for user in um.users(module.host) do
-			cleanup[user] = true;
+			schedule_cleanup(user);
 		end
 	end);
 
 	-- At odd intervals, delete old messages for one user
 	module:add_timer(math.random(10, 60), function()
-		local user = next(cleanup);
+		local user = table.remove(cleanup, 1);
 		if user then
 			module:log("debug", "Removing old messages for user %q", user);
 			local ok, err = archive:delete(user, { ["end"] = os.time() - cleanup_after; })