Last active
April 19, 2017 20:55
-
-
Save noogen/58812a3645da61b43423 to your computer and use it in GitHub Desktop.
Redis track a user event
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local utcDate = KEYS[1] -- because redis does not have os.time, we require a utc date expecting yyyy-mm-dd hh-mm-ss | |
local userId = KEYS[2] -- a username/email/unique identifier | |
local eventName = KEYS[3] -- event name to track | |
local siteId = KEYS[4] -- site id | |
local appPrefix = ARGV[1] | |
if not utcDate then | |
return "error: utcDate/keys[1] is required" | |
end | |
if not userId then | |
return "error: userId/keys[2] is required" | |
end | |
if not eventName then | |
return "error: eventName/keys[3] is required" | |
end | |
if not appPrefix then | |
appPrefix = "trak" | |
end | |
local d = {} | |
local i = 0 | |
local ukey = appPrefix .. "::users::" .. userId | |
local uid = redis.call("GET", ukey) | |
for word in string.gmatch(utcDate, "(%d+)") do | |
i = i+1 | |
d[i] = word | |
end | |
if not uid then | |
uid = redis.call("INCR", appPrefix .. "::identity::users") | |
redis.call("SET", ukey, uid) | |
end | |
local key1 = (appPrefix .. "::" .. eventName .. "::" .. string.format("%d-%d-%d-%d-%d", d[1], d[2], d[3], d[4], d[5])) | |
redis.call("SETBIT", key1, uid, 1) -- minute | |
redis.call("SETBIT", string.sub(key1, 1, -3), uid, 1) -- hour | |
redis.call("SETBIT", string.sub(key1, 1, -6), uid, 1) -- day | |
redis.call("SETBIT", string.sub(key1, 1, -9), uid, 1) -- month | |
redis.call("SETBIT", string.sub(key1, 1, -12), uid, 1) -- yyyy | |
if siteId then | |
key1 = (appPrefix .. "::site::" .. siteid .. "::" .. eventName .. "::" .. string.format("%d-%d-%d-%d-%d", d[1], d[2], d[3], d[4], d[5])) | |
redis.call("SETBIT", key1, uid, 1) -- minute | |
redis.call("SETBIT", string.sub(key1, 1, -3), uid, 1) -- hour | |
redis.call("SETBIT", string.sub(key1, 1, -6), uid, 1) -- day | |
redis.call("SETBIT", string.sub(key1, 1, -9), uid, 1) -- month | |
redis.call("SETBIT", string.sub(key1, 1, -12), uid, 1) -- yyyy | |
end | |
return uid .. "" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment