Add 'add' and 'replace' commands

Sun, 01 Aug 2010 12:40:45 +0100

author
Matthew Wild <mwild1@gmail.com>
date
Sun, 01 Aug 2010 12:40:45 +0100
changeset 17
5bede08f2f55
parent 16
906615e293de
child 18
d4822ae9d901

Add 'add' and 'replace' commands

mooncached.lua file | annotate | diff | comparison | revisions
util/memcache.lua file | annotate | diff | comparison | revisions
--- a/mooncached.lua	Sun Aug 01 12:23:34 2010 +0100
+++ b/mooncached.lua	Sun Aug 01 12:40:45 2010 +0100
@@ -31,7 +31,7 @@
 
 --- Command handlers
 
-function command_handlers.set(conn, params)
+local function generic_store_command(store_method, conn, params)
 	local key, flags, exptime, bytes, reply = params:match("(%S+) (%d+) (%d+) (%d+) ?(.*)$");
 	flags, exptime, bytes, reply = tonumber(flags), tonumber(exptime), tonumber(bytes), reply ~= "noreply";
 	if not (flags and exptime and bytes) then
@@ -49,10 +49,14 @@
 		received_buffer[#received_buffer+1] = data;
 		if received_count >= bytes then
 			received_buffer = table.concat(received_buffer);
-			local ok, err = cache:set(key, flags, exptime, received_buffer:sub(1,bytes));
+			local ok, err = store_method(cache, key, flags, exptime, received_buffer:sub(1,bytes));
 			if reply then
 				if ok then
-					conn:send("STORED\r\n");
+					if err == true then
+						conn:send("STORED\r\n");
+					else
+						conn:send("NOT_STORED\r\n");
+					end
 				else
 					conn:send("SERVER_ERROR "..(err or "Unknown error").."\r\n");
 				end
@@ -73,6 +77,18 @@
 	return true;
 end
 
+function command_handlers.set(conn, params)
+	return generic_store_command(cache.set, conn, params);
+end
+
+function command_handlers.add(conn, params)
+	return generic_store_command(cache.add, conn, params);
+end
+
+function command_handlers.replace(conn, params)
+	return generic_store_command(cache.replace, conn, params);
+end
+
 function command_handlers.get(conn, keys)
 	for key in keys:gmatch("%S+") do
 		local flags, data = cache:get(key);
--- a/util/memcache.lua	Sun Aug 01 12:23:34 2010 +0100
+++ b/util/memcache.lua	Sun Aug 01 12:40:45 2010 +0100
@@ -20,8 +20,23 @@
 			end
 			_expiry[key] = expires;
 		end
+		_deleted[key] = nil;
 		_data[key] = data;
-		return true;
+		return true, true;
+	end
+	
+	function cache:add(key, flags, expires, data)
+		if not(_data[key]) and (not(_deleted[key]) or _deleted[key] < now()) then
+			return self:set(key, flags, expires, data);
+		end
+		return true, false; -- No error, but data was not stored
+	end
+	
+	function cache:replace(key, flags, expires, data)
+		if _data[key] and (not(_deleted[key]) or _deleted[key] < now()) then
+			return self:set(key, flags, expires, data);
+		end
+		return true, false; -- No error, but data was not stored
 	end
 	
 	function cache:exists(key)

mercurial