Diff

util/pubsub.lua @ 6439:d58ad8bd244b

util.pubsub: Add support for limiting the number of item in a node (default to 20)
author Kim Alvefur <zash@zash.se>
date Sun, 28 Sep 2014 01:50:00 +0200
parent 6437:3f1f11dfdf10
child 6442:0f4025abbe8f
child 6515:c9a72c64c3e2
line wrap: on
line diff
--- a/util/pubsub.lua	Sun Sep 28 01:46:17 2014 +0200
+++ b/util/pubsub.lua	Sun Sep 28 01:50:00 2014 +0200
@@ -12,6 +12,7 @@
 	capabilities = {};
 } };
 local default_node_config = { __index = {
+	["pubsub#max_items"] = "20";
 } };
 
 function new(config)
@@ -262,6 +263,14 @@
 	end
 end
 
+local function trim_items(data, max)
+	max = tonumber(max);
+	if not max or #data <= max then return end
+	repeat
+		data[t_remove(data, 1)] = nil;
+	until #data <= max
+end
+
 function service:publish(node, actor, id, item)
 	-- Access checking
 	if not self:may(node, actor, "publish") then
@@ -283,6 +292,7 @@
 	remove_item_by_id(node_data, id);
 	node_data[#node_data + 1] = id;
 	node_data[id] = item;
+	trim_items(node_data, node_obj.config["pubsub#max_items"]);
 	self.events.fire_event("item-published", { node = node, actor = actor, id = id, item = item });
 	self.config.broadcaster("items", node, node_obj.subscribers, item);
 	return true;
@@ -427,6 +437,7 @@
 	for k,v in pairs(new_config) do
 		node_obj.config[k] = v;
 	end
+	trim_items(self.data[node], node_obj.config["pubsub#max_items"]);
 
 	return true;
 end