Skip to content

Commit

Permalink
compare-and-set script housekeeping
Browse files Browse the repository at this point in the history
  • Loading branch information
ptaoussanis committed Nov 20, 2014
1 parent 0159a36 commit cad91b9
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 21 deletions.
20 changes: 20 additions & 0 deletions src/lua/cas.lua
@@ -0,0 +1,20 @@
local curr_val = redis.call('get', _:k);

if (_:old-val-?sha ~= '') then
-- Check current value's SHA1
local curr_sha = redis.sha1hex(curr_val);
if (curr_sha == _:old-val-?sha) then
redis.call('set', _:k, _:new-val);
return true; -- 1
else
return false; -- nil (was 0)
end
else
-- Check current value
if (curr_val == _:old-?val) then
redis.call('set', _:k, _:new-val);
return true; -- 1
else
return false; -- nil (was 0)
end
end
8 changes: 0 additions & 8 deletions src/lua/misc/cas_sha.lua

This file was deleted.

7 changes: 0 additions & 7 deletions src/lua/misc/cas_val.lua

This file was deleted.

13 changes: 7 additions & 6 deletions src/taoensso/carmine.clj
Expand Up @@ -245,23 +245,24 @@
(def compare-and-set
"Experimental. Workaround for this not being in Redis core,
Ref http://goo.gl/M4Phx8."
(let [script-val (encore/slurp-resource "lua/misc/cas_val.lua")
script-sha (encore/slurp-resource "lua/misc/cas_sha.lua")]
(let [script (encore/slurp-resource "lua/cas.lua")]
(fn [k old-val new-val]
(if (= old-val :redis/nx)
;; Could also do with
;; sha = redis.sha1hex(nil) = "da39a3ee5e6b4b0d3255bfef95601890afd80709"
;; != redis.sha1hex(<serialized-nil>):
(setnx k new-val)
(let [bs-old-val (protocol/coerce-bs old-val)
just-use-val? (< (count bs-old-val) 40) #_false
just-use-val? (< (count bs-old-val) 40) #_false #_true
?sha
(when-not just-use-val?
(org.apache.commons.codec.digest.DigestUtils/sha1Hex
^bytes bs-old-val))]
(if-let [sha ?sha]
(lua script-sha {:k k} {:old-val-sha sha :new-val new-val})
(lua script-val {:k k} {:old-val old-val :new-val new-val})))))))
(lua script
{:k k}
{:old-val-?sha (if-not ?sha "" ?sha)
:old-?val (if-not ?sha old-val "")
:new-val new-val}))))))

(comment
(wcar {} (del "cas-k") (compare-and-set "cas-k" :redis/nx [:foo]))
Expand Down

0 comments on commit cad91b9

Please sign in to comment.