-
Notifications
You must be signed in to change notification settings - Fork 5
/
lua.go
92 lines (77 loc) · 2.26 KB
/
lua.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package redis
const (
cmdCAS = "cas"
cmdCAD = "cad"
)
func luaScript() string {
return luaScriptStr
}
const luaScriptStr = `
-- This lua script implements CAS based commands using lua and redis commands.
if #KEYS > 0 then error('No Keys should be provided') end
if #ARGV <= 0 then error('ARGV should be provided') end
local command_name = assert(table.remove(ARGV, 1), 'Must provide a command')
local decode = function(val)
return cjson.decode(val)
end
local encode = function(val)
return cjson.encode(val)
end
local exists = function(key)
return redis.call('exists', key) == 1
end
local get = function(key)
return redis.call('get', key)
end
local setex = function(key, val, ex)
if ex == "0" then
return redis.call('set', key, val)
end
return redis.call('set', key, val, 'ex', ex)
end
local del = function(key)
return redis.call('del', key)
end
-- cas is compare-and-swap function which compare the old value's signature
-- if they are the same, then swap with new val
-- noted that $old and $new are json formatted strings
-- and key is keyed with 'lastIndex'
local lastIndex = "LastIndex"
local cas = function(key, old, new, ttl)
if not exists(key) then
error("redis: key is not found")
end
local decodedOrig = decode(get(key))
local decodedOld = decode(old)
if decodedOrig[lastIndex] == decodedOld[lastIndex] then
setex(key, new, ttl)
return "OK"
else
error("redis: value has been changed")
end
end
-- cad is compare-and-del function which compare the old value's signature
-- if they are the same, then the key will be deleted
-- noted that $old is a json formatted string
-- and key is keyed with 'lastIndex'
local cad = function(key, old)
if not exists(key) then
error("redis: key is not found")
end
local decodedOrig = decode(get(key))
local decodedOld = decode(old)
if decodedOrig[lastIndex] == decodedOld[lastIndex] then
del(key)
return "OK"
else
error("redis: value has been changed")
end
end
-- Launcher exposes interfaces which be called by passing the arguments.
local Launcher = {
cas = cas,
cad = cad
}
local command = assert(Launcher[command_name], 'Unknown command ' .. command_name)
return command(unpack(ARGV))
`