@voltro/kv 0.90.0 → 0.91.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,11 @@
1
- import "./connectionScripts.js";
2
- import { decodeCacheAtomicCommand as e, isCacheAtomicRead as t } from "./cacheAtomicProtocol.js";
3
- import { CACHE_ATOMIC_SCRIPT as n } from "./cacheAtomicScript.js";
4
- import { isHotReadOperation as r } from "./hotOperations.js";
5
- import { applyHotOperations as i, compareHotMembers as a } from "./hotState.js";
6
- import { HotError as o } from "./hot-contract.js";
1
+ import { HotError as e } from "./hot-contract.js";
2
+ import { applyHotOperations as t, compareHotMembers as n } from "./hotState.js";
7
3
  import "./hotRedisScript.js";
8
- import { applyCacheAtomicCommand as s } from "./cacheAtomicState.js";
4
+ import { isHotReadOperation as r } from "./hotOperations.js";
5
+ import { CACHE_ATOMIC_SCRIPT as i } from "./cacheAtomicScript.js";
6
+ import { applyCacheAtomicCommand as a } from "./cacheAtomicState.js";
7
+ import { decodeCacheAtomicCommand as o, isCacheAtomicRead as s } from "./cacheAtomicProtocol.js";
8
+ import "./connectionScripts.js";
9
9
  // src/connectionMemory.ts
10
10
  var c = (c = Date.now) => {
11
11
  let l = /* @__PURE__ */ new Map(), u = /* @__PURE__ */ new Map(), d = /* @__PURE__ */ new Map(), f = /* @__PURE__ */ new Set(), p = !1, m = () => {
@@ -19,7 +19,7 @@ var c = (c = Date.now) => {
19
19
  ...l.keys(),
20
20
  ...u.keys(),
21
21
  ...d.keys()
22
- ])].filter(g).sort(a), y = (e, t) => {
22
+ ])].filter(g).sort(n), y = (e, t) => {
23
23
  let n = "^";
24
24
  for (let t = 0; t < e.length; t++) {
25
25
  let r = e[t];
@@ -43,16 +43,16 @@ var c = (c = Date.now) => {
43
43
  get: (e) => S.get(e),
44
44
  exists: (e) => S.exists(e),
45
45
  zrange: (e) => S.zrange(e),
46
- eval: async (i, a, ...o) => {
47
- if (b(), i === n) {
48
- let n = e(JSON.parse(String(o[a])));
49
- if (!t(n)) throw Error("Memory read-only Lua refuses mutations");
50
- return S.eval(i, a, ...o);
46
+ eval: async (e, t, ...n) => {
47
+ if (b(), e === i) {
48
+ let r = o(JSON.parse(String(n[t])));
49
+ if (!s(r)) throw Error("Memory read-only Lua refuses mutations");
50
+ return S.eval(e, t, ...n);
51
51
  }
52
- if (i !== "\nlocal ops = cjson.decode(ARGV[1])\nlocal tm = redis.call('TIME')\nlocal now = tonumber(tm[1]) * 1000 + math.floor(tonumber(tm[2]) / 1000)\nlocal out = {}\nlocal function fail(op, reason)\n return cjson.encode({ failure = { operation = op.op, key = op.key, reason = reason } })\nend\nlocal function ttl(k, o)\n if o and o.ttlMs then redis.call('PEXPIRE', k, string.format('%.0f', o.ttlMs)) end\nend\nlocal function numberString(k, prefix)\n local raw = redis.call('GET', k)\n if not raw then return nil end\n if string.sub(raw, 1, 2) ~= prefix then error('WRONGTYPE') end\n return string.sub(raw, 3)\nend\nlocal function run(o, k)\n local op = o.op\n local expected\n if string.sub(op, 1, 1) == 'z' then expected = 'zset'\n elseif string.sub(op, 1, 1) == 'h' then expected = 'hash'\n elseif op == 'sadd' or op == 'srem' or op == 'smembers' or op == 'sismember' then expected = 'set' end\n if expected then\n local actual = redis.call('TYPE', k).ok\n if actual ~= 'none' and actual ~= expected then error('WRONGTYPE') end\n end\n if op == 'zadd' then\n local pending = {}\n local mode = o.options and o.options.mode or 'set'\n for _, m in ipairs(o.members) do\n local old\n if mode ~= 'set' then old = pending[m.member] or tonumber(redis.call('ZSCORE', k, m.member)) end\n local score = m.score\n if old then\n if mode == 'max' then score = math.max(old, score)\n elseif mode == 'min' then score = math.min(old, score)\n elseif mode == 'incr' then score = old + score end\n end\n if score == math.huge or score == -math.huge or score ~= score then error('HOT_INVALID') end\n pending[m.member] = score\n end\n -- RESP-family Lua bridges differ in number-to-argument precision.\n for member, score in pairs(pending) do redis.call('ZADD', k, string.format('%.17g', score), member) end\n ttl(k, o.options); return cjson.null\n elseif op == 'zrem' then\n local count = 0\n for _, member in ipairs(o.members) do count = count + redis.call('ZREM', k, member) end\n return count\n elseif op == 'zrank' then\n local cmd = o.order == 'desc' and 'ZREVRANK' or 'ZRANK'\n return redis.call(cmd, k, o.member) or cjson.null\n elseif op == 'zscore' then\n return tonumber(redis.call('ZSCORE', k, o.member)) or cjson.null\n elseif op == 'zcard' then return redis.call('ZCARD', k)\n elseif op == 'zrange' then\n local raw\n local limit = o.options and o.options.limit\n if limit == 0 then return {} end\n if o.range.byRank then\n local cmd = o.order == 'desc' and 'ZREVRANGE' or 'ZRANGE'\n local lo, hi = o.range.byRank[1], o.range.byRank[2]\n if limit then\n local count = redis.call('ZCARD', k)\n if lo < 0 then lo = count + lo end\n if hi < 0 then hi = count + hi end\n lo = math.max(0, lo)\n hi = math.min(hi, lo + limit - 1)\n if hi < lo then return {} end\n end\n raw = redis.call(cmd, k, string.format('%.0f', lo), string.format('%.0f', hi), 'WITHSCORES')\n else\n local cmd = o.order == 'desc' and 'ZREVRANGEBYSCORE' or 'ZRANGEBYSCORE'\n local lo, hi = o.range.byScore[1], o.range.byScore[2]\n if lo > hi then return {} end\n if o.order == 'desc' then lo, hi = hi, lo end\n if limit then raw = redis.call(cmd, k, string.format('%.17g', lo), string.format('%.17g', hi), 'WITHSCORES', 'LIMIT', 0, limit)\n else raw = redis.call(cmd, k, string.format('%.17g', lo), string.format('%.17g', hi), 'WITHSCORES') end\n end\n local result = {}\n for i = 1, #raw / 2 do\n local score = raw[i * 2]\n if type(score) == 'number' then score = string.format('%.17g', score) end\n table.insert(result, { member = raw[i * 2 - 1], score = score })\n end\n return result\n elseif op == 'zremRange' then\n local pair = o.range.byRank or o.range.byScore\n local cmd = o.range.byRank and 'ZREMRANGEBYRANK' or 'ZREMRANGEBYSCORE'\n local format = o.range.byRank and '%.0f' or '%.17g'\n return redis.call(cmd, k, string.format(format, pair[1]), string.format(format, pair[2]))\n elseif op == 'incrBy' then\n local value = tonumber(numberString(k, 'c:')) or 0\n value = value + o.delta\n if math.abs(value) > 9007199254740991 then error('HOT_INVALID') end\n if o.options and o.options.max and value > o.options.max then error('HOT_LIMIT') end\n redis.call('SET', k, 'c:' .. string.format('%.0f', value), 'KEEPTTL')\n ttl(k, o.options); return value\n elseif op == 'tokenBucket' then\n local raw = numberString(k, 'b:')\n local old = raw and cjson.decode(raw) or { tokens = o.config.capacity, updatedAt = now }\n local available = math.min(o.config.capacity, tonumber(old.tokens) + math.max(0, now - tonumber(old.updatedAt)) * o.config.refillPerSec / 1000)\n local allowed = available >= o.cost\n local remaining = available\n if allowed then remaining = remaining - o.cost end\n local retry = allowed and 0 or math.ceil((o.cost - available) / o.config.refillPerSec * 1000)\n local life = math.max(1, math.ceil(o.config.capacity / o.config.refillPerSec * 1000))\n redis.call('SET', k, 'b:' .. cjson.encode({ tokens = string.format('%.17g', remaining), updatedAt = string.format('%.0f', math.max(now, tonumber(old.updatedAt))) }), 'PX', string.format('%.0f', life))\n return { allowed = allowed, remaining = string.format('%.17g', remaining), retryAfterMs = string.format('%.0f', retry) }\n elseif op == 'rateLimit' then\n local raw = numberString(k, 'r:')\n local s = raw and cjson.decode(raw) or nil\n local cfg = o.config\n local at = o.nowMs or now\n local limit, windowMs, capacity = cfg.limit, cfg.windowMs, cfg.burst\n local allowed, remaining, resetAt, retryAfter\n local state\n if cfg.algorithm == 'fixed-window' then\n local start = s and s.kind == 'fixed' and tonumber(s.windowStart) or at\n local count = s and s.kind == 'fixed' and tonumber(s.count) or 0\n if at - start >= windowMs then start = at; count = 0 end\n resetAt = start + windowMs\n allowed = count < limit\n if allowed then count = count + 1 end\n remaining = allowed and limit - count or 0\n retryAfter = allowed and 0 or resetAt - at\n state = { kind = 'fixed', windowStart = start, count = count }\n elseif cfg.algorithm == 'sliding-window' then\n local start = s and s.kind == 'sliding' and tonumber(s.currStart) or at\n local current = s and s.kind == 'sliding' and tonumber(s.currCount) or 0\n local previous = s and s.kind == 'sliding' and tonumber(s.prevCount) or 0\n local elapsed = math.floor((at - start) / windowMs)\n if elapsed >= 2 then previous = 0; current = 0; start = at\n elseif elapsed == 1 then previous = current; current = 0; start = start + windowMs end\n local weight = (windowMs - (at - start)) / windowMs\n local estimate = previous * weight + current\n resetAt = start + windowMs\n allowed = estimate < limit\n if allowed then current = current + 1 end\n remaining = allowed and math.max(0, math.floor(limit - estimate - 1)) or 0\n retryAfter = allowed and 0 or resetAt - at\n state = { kind = 'sliding', currStart = start, currCount = current, prevCount = previous }\n else\n local tokens = s and s.kind == 'token' and tonumber(s.tokens) or capacity\n local last = s and s.kind == 'token' and tonumber(s.lastRefill) or at\n local refill = limit / windowMs\n tokens = math.min(capacity, tokens + (at - last) * refill)\n allowed = tokens >= 1\n if allowed then tokens = tokens - 1 end\n retryAfter = allowed and 0 or math.ceil((1 - tokens) / refill)\n remaining = allowed and math.floor(tokens) or 0\n resetAt = at + (allowed and math.ceil((capacity - tokens) / refill) or retryAfter)\n state = { kind = 'token', tokens = tokens, lastRefill = at }\n end\n for field, value in pairs(state) do\n if type(value) == 'number' then state[field] = string.format('%.17g', value) end\n end\n redis.call('SET', k, 'r:' .. cjson.encode(state), 'PX', string.format('%.0f', math.ceil(math.max(windowMs * 2, 60000) + 1000)))\n return { allowed = allowed, remaining = string.format('%.17g', remaining), resetAtMs = string.format('%.17g', resetAt), retryAfterMs = string.format('%.17g', retryAfter) }\n elseif op == 'hset' then\n for f, v in pairs(o.fields) do redis.call('HSET', k, f, v) end\n ttl(k, o.options); return cjson.null\n elseif op == 'hget' then return redis.call('HGET', k, o.field) or cjson.null\n elseif op == 'hgetAll' then\n local raw = redis.call('HGETALL', k)\n local fields = {}\n for i = 1, #raw, 2 do fields[raw[i]] = raw[i + 1] end\n return fields\n elseif op == 'hdel' then\n local count = 0\n for _, field in ipairs(o.fields) do count = count + redis.call('HDEL', k, field) end\n return count\n elseif op == 'sadd' or op == 'srem' then\n local count = 0\n for _, member in ipairs(o.members) do count = count + redis.call(op == 'sadd' and 'SADD' or 'SREM', k, member) end\n if op == 'sadd' then ttl(k, o.options) end\n return count\n elseif op == 'smembers' then\n local members = redis.call('SMEMBERS', k); table.sort(members); return members\n elseif op == 'sismember' then return redis.call('SISMEMBER', k, o.member) == 1\n elseif op == 'setNx' then return redis.call('SET', k, 'l:' .. o.value, 'NX', 'PX', string.format('%.0f', o.ttlMs)) ~= false\n elseif op == 'compareDelete' or op == 'compareExpire' then\n local value = numberString(k, 'l:')\n if value == nil or value ~= o.value then return false end\n if op == 'compareDelete' then return redis.call('DEL', k) == 1 end\n return redis.call('PEXPIRE', k, string.format('%.0f', o.ttlMs)) == 1\n elseif op == 'expire' then redis.call('PEXPIRE', k, string.format('%.0f', o.ttlMs)); return cjson.null\n elseif op == 'delete' then return redis.call('DEL', k) == 1 end\n error('HOT_INVALID')\nend\nfor i, op in ipairs(ops) do\n local ok, result = pcall(run, op, KEYS[i])\n if not ok then\n local reason = 'unavailable'\n if string.find(result, 'WRONGTYPE', 1, true) then reason = 'wrongType'\n elseif string.find(result, 'HOT_LIMIT', 1, true) then reason = 'limit'\n elseif string.find(result, 'HOT_INVALID', 1, true) then reason = 'invalid' end\n return fail(op, reason)\n end\n -- Redis cjson numbers have only 14 significant digits. Use strings on\n -- known numeric result slots so safe integers and fractional scores survive.\n if type(result) == 'number' then result = string.format('%.17g', result) end\n table.insert(out, { value = result })\nend\nreturn cjson.encode({ results = out })\n") throw Error("Memory read-only Lua requires a framework read script");
53
- let s = JSON.parse(String(o[a]));
54
- if (!Array.isArray(s) || !s.every((e) => r(e))) throw Error("Memory read-only Lua refuses mutations");
55
- return S.eval(i, a, ...o);
52
+ if (e !== "\nlocal ops = cjson.decode(ARGV[1])\nlocal tm = redis.call('TIME')\nlocal now = tonumber(tm[1]) * 1000 + math.floor(tonumber(tm[2]) / 1000)\nlocal out = {}\nlocal function fail(op, reason)\n return cjson.encode({ failure = { operation = op.op, key = op.key, reason = reason } })\nend\nlocal function ttl(k, o)\n if o and o.ttlMs then redis.call('PEXPIRE', k, string.format('%.0f', o.ttlMs)) end\nend\nlocal function numberString(k, prefix)\n local raw = redis.call('GET', k)\n if not raw then return nil end\n if string.sub(raw, 1, 2) ~= prefix then error('WRONGTYPE') end\n return string.sub(raw, 3)\nend\nlocal function run(o, k)\n local op = o.op\n local expected\n if string.sub(op, 1, 1) == 'z' then expected = 'zset'\n elseif string.sub(op, 1, 1) == 'h' then expected = 'hash'\n elseif op == 'sadd' or op == 'srem' or op == 'smembers' or op == 'sismember' then expected = 'set' end\n if expected then\n local actual = redis.call('TYPE', k).ok\n if actual ~= 'none' and actual ~= expected then error('WRONGTYPE') end\n end\n if op == 'zadd' then\n local pending = {}\n local mode = o.options and o.options.mode or 'set'\n for _, m in ipairs(o.members) do\n local old\n if mode ~= 'set' then old = pending[m.member] or tonumber(redis.call('ZSCORE', k, m.member)) end\n local score = m.score\n if old then\n if mode == 'max' then score = math.max(old, score)\n elseif mode == 'min' then score = math.min(old, score)\n elseif mode == 'incr' then score = old + score end\n end\n if score == math.huge or score == -math.huge or score ~= score then error('HOT_INVALID') end\n pending[m.member] = score\n end\n -- RESP-family Lua bridges differ in number-to-argument precision.\n for member, score in pairs(pending) do redis.call('ZADD', k, string.format('%.17g', score), member) end\n ttl(k, o.options); return cjson.null\n elseif op == 'zrem' then\n local count = 0\n for _, member in ipairs(o.members) do count = count + redis.call('ZREM', k, member) end\n return count\n elseif op == 'zrank' then\n local cmd = o.order == 'desc' and 'ZREVRANK' or 'ZRANK'\n return redis.call(cmd, k, o.member) or cjson.null\n elseif op == 'zscore' then\n return tonumber(redis.call('ZSCORE', k, o.member)) or cjson.null\n elseif op == 'zcard' then return redis.call('ZCARD', k)\n elseif op == 'zrange' then\n local raw\n local limit = o.options and o.options.limit\n if limit == 0 then return {} end\n if o.range.byRank then\n local cmd = o.order == 'desc' and 'ZREVRANGE' or 'ZRANGE'\n local lo, hi = o.range.byRank[1], o.range.byRank[2]\n if limit then\n local count = redis.call('ZCARD', k)\n if lo < 0 then lo = count + lo end\n if hi < 0 then hi = count + hi end\n lo = math.max(0, lo)\n hi = math.min(hi, lo + limit - 1)\n if hi < lo then return {} end\n end\n raw = redis.call(cmd, k, string.format('%.0f', lo), string.format('%.0f', hi), 'WITHSCORES')\n else\n local cmd = o.order == 'desc' and 'ZREVRANGEBYSCORE' or 'ZRANGEBYSCORE'\n local lo, hi = o.range.byScore[1], o.range.byScore[2]\n if lo > hi then return {} end\n if o.order == 'desc' then lo, hi = hi, lo end\n if limit then raw = redis.call(cmd, k, string.format('%.17g', lo), string.format('%.17g', hi), 'WITHSCORES', 'LIMIT', 0, limit)\n else raw = redis.call(cmd, k, string.format('%.17g', lo), string.format('%.17g', hi), 'WITHSCORES') end\n end\n local result = {}\n for i = 1, #raw / 2 do\n local score = raw[i * 2]\n if type(score) == 'number' then score = string.format('%.17g', score) end\n table.insert(result, { member = raw[i * 2 - 1], score = score })\n end\n return result\n elseif op == 'zremRange' then\n local pair = o.range.byRank or o.range.byScore\n local cmd = o.range.byRank and 'ZREMRANGEBYRANK' or 'ZREMRANGEBYSCORE'\n local format = o.range.byRank and '%.0f' or '%.17g'\n return redis.call(cmd, k, string.format(format, pair[1]), string.format(format, pair[2]))\n elseif op == 'incrBy' then\n local value = tonumber(numberString(k, 'c:')) or 0\n value = value + o.delta\n if math.abs(value) > 9007199254740991 then error('HOT_INVALID') end\n if o.options and o.options.max and value > o.options.max then error('HOT_LIMIT') end\n redis.call('SET', k, 'c:' .. string.format('%.0f', value), 'KEEPTTL')\n ttl(k, o.options); return value\n elseif op == 'tokenBucket' then\n local raw = numberString(k, 'b:')\n local old = raw and cjson.decode(raw) or { tokens = o.config.capacity, updatedAt = now }\n local available = math.min(o.config.capacity, tonumber(old.tokens) + math.max(0, now - tonumber(old.updatedAt)) * o.config.refillPerSec / 1000)\n local allowed = available >= o.cost\n local remaining = available\n if allowed then remaining = remaining - o.cost end\n local retry = allowed and 0 or math.ceil((o.cost - available) / o.config.refillPerSec * 1000)\n local life = math.max(1, math.ceil(o.config.capacity / o.config.refillPerSec * 1000))\n redis.call('SET', k, 'b:' .. cjson.encode({ tokens = string.format('%.17g', remaining), updatedAt = string.format('%.0f', math.max(now, tonumber(old.updatedAt))) }), 'PX', string.format('%.0f', life))\n return { allowed = allowed, remaining = string.format('%.17g', remaining), retryAfterMs = string.format('%.0f', retry) }\n elseif op == 'rateLimit' then\n local raw = numberString(k, 'r:')\n local s = raw and cjson.decode(raw) or nil\n local cfg = o.config\n local at = o.nowMs or now\n local limit, windowMs, capacity = cfg.limit, cfg.windowMs, cfg.burst\n local allowed, remaining, resetAt, retryAfter\n local state\n if cfg.algorithm == 'fixed-window' then\n local start = s and s.kind == 'fixed' and tonumber(s.windowStart) or at\n local count = s and s.kind == 'fixed' and tonumber(s.count) or 0\n if at - start >= windowMs then start = at; count = 0 end\n resetAt = start + windowMs\n allowed = count < limit\n if allowed then count = count + 1 end\n remaining = allowed and limit - count or 0\n retryAfter = allowed and 0 or resetAt - at\n state = { kind = 'fixed', windowStart = start, count = count }\n elseif cfg.algorithm == 'sliding-window' then\n local start = s and s.kind == 'sliding' and tonumber(s.currStart) or at\n local current = s and s.kind == 'sliding' and tonumber(s.currCount) or 0\n local previous = s and s.kind == 'sliding' and tonumber(s.prevCount) or 0\n local elapsed = math.floor((at - start) / windowMs)\n if elapsed >= 2 then previous = 0; current = 0; start = at\n elseif elapsed == 1 then previous = current; current = 0; start = start + windowMs end\n local weight = (windowMs - (at - start)) / windowMs\n local estimate = previous * weight + current\n resetAt = start + windowMs\n allowed = estimate < limit\n if allowed then current = current + 1 end\n remaining = allowed and math.max(0, math.floor(limit - estimate - 1)) or 0\n retryAfter = allowed and 0 or resetAt - at\n state = { kind = 'sliding', currStart = start, currCount = current, prevCount = previous }\n else\n local tokens = s and s.kind == 'token' and tonumber(s.tokens) or capacity\n local last = s and s.kind == 'token' and tonumber(s.lastRefill) or at\n local refill = limit / windowMs\n tokens = math.min(capacity, tokens + (at - last) * refill)\n allowed = tokens >= 1\n if allowed then tokens = tokens - 1 end\n retryAfter = allowed and 0 or math.ceil((1 - tokens) / refill)\n remaining = allowed and math.floor(tokens) or 0\n resetAt = at + (allowed and math.ceil((capacity - tokens) / refill) or retryAfter)\n state = { kind = 'token', tokens = tokens, lastRefill = at }\n end\n for field, value in pairs(state) do\n if type(value) == 'number' then state[field] = string.format('%.17g', value) end\n end\n redis.call('SET', k, 'r:' .. cjson.encode(state), 'PX', string.format('%.0f', math.ceil(math.max(windowMs * 2, 60000) + 1000)))\n return { allowed = allowed, remaining = string.format('%.17g', remaining), resetAtMs = string.format('%.17g', resetAt), retryAfterMs = string.format('%.17g', retryAfter) }\n elseif op == 'hset' then\n for f, v in pairs(o.fields) do redis.call('HSET', k, f, v) end\n ttl(k, o.options); return cjson.null\n elseif op == 'hget' then return redis.call('HGET', k, o.field) or cjson.null\n elseif op == 'hgetAll' then\n local raw = redis.call('HGETALL', k)\n local fields = {}\n for i = 1, #raw, 2 do fields[raw[i]] = raw[i + 1] end\n return fields\n elseif op == 'hdel' then\n local count = 0\n for _, field in ipairs(o.fields) do count = count + redis.call('HDEL', k, field) end\n return count\n elseif op == 'sadd' or op == 'srem' then\n local count = 0\n for _, member in ipairs(o.members) do count = count + redis.call(op == 'sadd' and 'SADD' or 'SREM', k, member) end\n if op == 'sadd' then ttl(k, o.options) end\n return count\n elseif op == 'smembers' then\n local members = redis.call('SMEMBERS', k); table.sort(members); return members\n elseif op == 'sismember' then return redis.call('SISMEMBER', k, o.member) == 1\n elseif op == 'setNx' then return redis.call('SET', k, 'l:' .. o.value, 'NX', 'PX', string.format('%.0f', o.ttlMs)) ~= false\n elseif op == 'compareDelete' or op == 'compareExpire' then\n local value = numberString(k, 'l:')\n if value == nil or value ~= o.value then return false end\n if op == 'compareDelete' then return redis.call('DEL', k) == 1 end\n return redis.call('PEXPIRE', k, string.format('%.0f', o.ttlMs)) == 1\n elseif op == 'expire' then redis.call('PEXPIRE', k, string.format('%.0f', o.ttlMs)); return cjson.null\n elseif op == 'delete' then return redis.call('DEL', k) == 1 end\n error('HOT_INVALID')\nend\nfor i, op in ipairs(ops) do\n local ok, result = pcall(run, op, KEYS[i])\n if not ok then\n local reason = 'unavailable'\n if string.find(result, 'WRONGTYPE', 1, true) then reason = 'wrongType'\n elseif string.find(result, 'HOT_LIMIT', 1, true) then reason = 'limit'\n elseif string.find(result, 'HOT_INVALID', 1, true) then reason = 'invalid' end\n return fail(op, reason)\n end\n -- Redis cjson numbers have only 14 significant digits. Use strings on\n -- known numeric result slots so safe integers and fractional scores survive.\n if type(result) == 'number' then result = string.format('%.17g', result) end\n table.insert(out, { value = result })\nend\nreturn cjson.encode({ results = out })\n") throw Error("Memory read-only Lua requires a framework read script");
53
+ let a = JSON.parse(String(n[t]));
54
+ if (!Array.isArray(a) || !a.every((e) => r(e))) throw Error("Memory read-only Lua refuses mutations");
55
+ return S.eval(e, t, ...n);
56
56
  }
57
57
  },
58
58
  crossNode: !1,
@@ -70,7 +70,7 @@ var c = (c = Date.now) => {
70
70
  exists: async (e) => (b(), +!!g(e)),
71
71
  zrange: async (e) => {
72
72
  if (b(), h(e), l.has(e) || d.has(e)) throw Error("Memory key is not a tag sorted set");
73
- return [...u.get(e)?.values.entries() ?? []].sort((e, t) => e[1] - t[1] || a(e[0], t[0])).map(([e]) => e);
73
+ return [...u.get(e)?.values.entries() ?? []].sort((e, t) => e[1] - t[1] || n(e[0], t[0])).map(([e]) => e);
74
74
  },
75
75
  scan: async (e, t, n) => {
76
76
  if (b(), e !== "0") throw Error("Memory SCAN requires its terminal cursor 0");
@@ -80,16 +80,16 @@ var c = (c = Date.now) => {
80
80
  keys: v().filter((e) => y(t, e))
81
81
  };
82
82
  },
83
- eval: async (e, t, ...r) => {
84
- if (b(), !Number.isSafeInteger(t) || t < 0 || t > r.length) throw Error("Memory EVAL requires a valid key count");
85
- if (e === n) {
86
- if (r.length !== t + 1 && r.length !== t + 2) throw Error("Invalid atomic cache arguments");
87
- let e = c(), n = (t) => (h(t, e), l.has(t) ? "string" : u.has(t) ? "zset" : d.has(t) ? "other" : "none");
88
- return s({
83
+ eval: async (r, o, ...s) => {
84
+ if (b(), !Number.isSafeInteger(o) || o < 0 || o > s.length) throw Error("Memory EVAL requires a valid key count");
85
+ if (r === i) {
86
+ if (s.length !== o + 1 && s.length !== o + 2) throw Error("Invalid atomic cache arguments");
87
+ let e = c(), t = (t) => (h(t, e), l.has(t) ? "string" : u.has(t) ? "zset" : d.has(t) ? "other" : "none");
88
+ return a({
89
89
  now: e,
90
- kind: n,
90
+ kind: t,
91
91
  get: (e) => {
92
- if (!["none", "string"].includes(n(e))) throw Error("Invalid cache string state");
92
+ if (!["none", "string"].includes(t(e))) throw Error("Invalid cache string state");
93
93
  return l.get(e)?.value ?? null;
94
94
  },
95
95
  set: (t, n, r) => {
@@ -99,10 +99,10 @@ var c = (c = Date.now) => {
99
99
  }), u.delete(t), d.delete(t);
100
100
  },
101
101
  remove: (e) => {
102
- let t = n(e) === "none" ? 0 : 1;
103
- return l.delete(e), u.delete(e), d.delete(e), t;
102
+ let n = t(e) === "none" ? 0 : 1;
103
+ return l.delete(e), u.delete(e), d.delete(e), n;
104
104
  },
105
- members: (e) => (n(e), [...u.get(e)?.values ?? []].map(([e, t]) => ({
105
+ members: (e) => (t(e), [...u.get(e)?.values ?? []].map(([e, t]) => ({
106
106
  member: e,
107
107
  score: t
108
108
  }))),
@@ -124,39 +124,39 @@ var c = (c = Date.now) => {
124
124
  ...l.keys(),
125
125
  ...u.keys(),
126
126
  ...d.keys()
127
- ])].filter((e) => n(e) !== "none").sort(a)
128
- }, r.slice(0, t).map(String), JSON.parse(String(r[t])), r.length === t + 2 ? JSON.parse(String(r[t + 1])) : {});
127
+ ])].filter((e) => t(e) !== "none").sort(n)
128
+ }, s.slice(0, o).map(String), JSON.parse(String(s[o])), s.length === o + 2 ? JSON.parse(String(s[o + 1])) : {});
129
129
  }
130
- if (e === "return redis.call('PUBLISH', ARGV[1], ARGV[2])") {
131
- if (t !== 0 || r.length !== 2) throw Error("Invalid publication arguments");
132
- let e = String(r[0]), n = String(r[1]), i = 0;
133
- for (let t of [...f]) t.channels.has(e) && (i++, t.deliver(e, n));
134
- return i;
130
+ if (r === "return redis.call('PUBLISH', ARGV[1], ARGV[2])") {
131
+ if (o !== 0 || s.length !== 2) throw Error("Invalid publication arguments");
132
+ let e = String(s[0]), t = String(s[1]), n = 0;
133
+ for (let r of [...f]) r.channels.has(e) && (n++, r.deliver(e, t));
134
+ return n;
135
135
  }
136
- if (e === "\nlocal ops = cjson.decode(ARGV[1])\nlocal tm = redis.call('TIME')\nlocal now = tonumber(tm[1]) * 1000 + math.floor(tonumber(tm[2]) / 1000)\nlocal out = {}\nlocal function fail(op, reason)\n return cjson.encode({ failure = { operation = op.op, key = op.key, reason = reason } })\nend\nlocal function ttl(k, o)\n if o and o.ttlMs then redis.call('PEXPIRE', k, string.format('%.0f', o.ttlMs)) end\nend\nlocal function numberString(k, prefix)\n local raw = redis.call('GET', k)\n if not raw then return nil end\n if string.sub(raw, 1, 2) ~= prefix then error('WRONGTYPE') end\n return string.sub(raw, 3)\nend\nlocal function run(o, k)\n local op = o.op\n local expected\n if string.sub(op, 1, 1) == 'z' then expected = 'zset'\n elseif string.sub(op, 1, 1) == 'h' then expected = 'hash'\n elseif op == 'sadd' or op == 'srem' or op == 'smembers' or op == 'sismember' then expected = 'set' end\n if expected then\n local actual = redis.call('TYPE', k).ok\n if actual ~= 'none' and actual ~= expected then error('WRONGTYPE') end\n end\n if op == 'zadd' then\n local pending = {}\n local mode = o.options and o.options.mode or 'set'\n for _, m in ipairs(o.members) do\n local old\n if mode ~= 'set' then old = pending[m.member] or tonumber(redis.call('ZSCORE', k, m.member)) end\n local score = m.score\n if old then\n if mode == 'max' then score = math.max(old, score)\n elseif mode == 'min' then score = math.min(old, score)\n elseif mode == 'incr' then score = old + score end\n end\n if score == math.huge or score == -math.huge or score ~= score then error('HOT_INVALID') end\n pending[m.member] = score\n end\n -- RESP-family Lua bridges differ in number-to-argument precision.\n for member, score in pairs(pending) do redis.call('ZADD', k, string.format('%.17g', score), member) end\n ttl(k, o.options); return cjson.null\n elseif op == 'zrem' then\n local count = 0\n for _, member in ipairs(o.members) do count = count + redis.call('ZREM', k, member) end\n return count\n elseif op == 'zrank' then\n local cmd = o.order == 'desc' and 'ZREVRANK' or 'ZRANK'\n return redis.call(cmd, k, o.member) or cjson.null\n elseif op == 'zscore' then\n return tonumber(redis.call('ZSCORE', k, o.member)) or cjson.null\n elseif op == 'zcard' then return redis.call('ZCARD', k)\n elseif op == 'zrange' then\n local raw\n local limit = o.options and o.options.limit\n if limit == 0 then return {} end\n if o.range.byRank then\n local cmd = o.order == 'desc' and 'ZREVRANGE' or 'ZRANGE'\n local lo, hi = o.range.byRank[1], o.range.byRank[2]\n if limit then\n local count = redis.call('ZCARD', k)\n if lo < 0 then lo = count + lo end\n if hi < 0 then hi = count + hi end\n lo = math.max(0, lo)\n hi = math.min(hi, lo + limit - 1)\n if hi < lo then return {} end\n end\n raw = redis.call(cmd, k, string.format('%.0f', lo), string.format('%.0f', hi), 'WITHSCORES')\n else\n local cmd = o.order == 'desc' and 'ZREVRANGEBYSCORE' or 'ZRANGEBYSCORE'\n local lo, hi = o.range.byScore[1], o.range.byScore[2]\n if lo > hi then return {} end\n if o.order == 'desc' then lo, hi = hi, lo end\n if limit then raw = redis.call(cmd, k, string.format('%.17g', lo), string.format('%.17g', hi), 'WITHSCORES', 'LIMIT', 0, limit)\n else raw = redis.call(cmd, k, string.format('%.17g', lo), string.format('%.17g', hi), 'WITHSCORES') end\n end\n local result = {}\n for i = 1, #raw / 2 do\n local score = raw[i * 2]\n if type(score) == 'number' then score = string.format('%.17g', score) end\n table.insert(result, { member = raw[i * 2 - 1], score = score })\n end\n return result\n elseif op == 'zremRange' then\n local pair = o.range.byRank or o.range.byScore\n local cmd = o.range.byRank and 'ZREMRANGEBYRANK' or 'ZREMRANGEBYSCORE'\n local format = o.range.byRank and '%.0f' or '%.17g'\n return redis.call(cmd, k, string.format(format, pair[1]), string.format(format, pair[2]))\n elseif op == 'incrBy' then\n local value = tonumber(numberString(k, 'c:')) or 0\n value = value + o.delta\n if math.abs(value) > 9007199254740991 then error('HOT_INVALID') end\n if o.options and o.options.max and value > o.options.max then error('HOT_LIMIT') end\n redis.call('SET', k, 'c:' .. string.format('%.0f', value), 'KEEPTTL')\n ttl(k, o.options); return value\n elseif op == 'tokenBucket' then\n local raw = numberString(k, 'b:')\n local old = raw and cjson.decode(raw) or { tokens = o.config.capacity, updatedAt = now }\n local available = math.min(o.config.capacity, tonumber(old.tokens) + math.max(0, now - tonumber(old.updatedAt)) * o.config.refillPerSec / 1000)\n local allowed = available >= o.cost\n local remaining = available\n if allowed then remaining = remaining - o.cost end\n local retry = allowed and 0 or math.ceil((o.cost - available) / o.config.refillPerSec * 1000)\n local life = math.max(1, math.ceil(o.config.capacity / o.config.refillPerSec * 1000))\n redis.call('SET', k, 'b:' .. cjson.encode({ tokens = string.format('%.17g', remaining), updatedAt = string.format('%.0f', math.max(now, tonumber(old.updatedAt))) }), 'PX', string.format('%.0f', life))\n return { allowed = allowed, remaining = string.format('%.17g', remaining), retryAfterMs = string.format('%.0f', retry) }\n elseif op == 'rateLimit' then\n local raw = numberString(k, 'r:')\n local s = raw and cjson.decode(raw) or nil\n local cfg = o.config\n local at = o.nowMs or now\n local limit, windowMs, capacity = cfg.limit, cfg.windowMs, cfg.burst\n local allowed, remaining, resetAt, retryAfter\n local state\n if cfg.algorithm == 'fixed-window' then\n local start = s and s.kind == 'fixed' and tonumber(s.windowStart) or at\n local count = s and s.kind == 'fixed' and tonumber(s.count) or 0\n if at - start >= windowMs then start = at; count = 0 end\n resetAt = start + windowMs\n allowed = count < limit\n if allowed then count = count + 1 end\n remaining = allowed and limit - count or 0\n retryAfter = allowed and 0 or resetAt - at\n state = { kind = 'fixed', windowStart = start, count = count }\n elseif cfg.algorithm == 'sliding-window' then\n local start = s and s.kind == 'sliding' and tonumber(s.currStart) or at\n local current = s and s.kind == 'sliding' and tonumber(s.currCount) or 0\n local previous = s and s.kind == 'sliding' and tonumber(s.prevCount) or 0\n local elapsed = math.floor((at - start) / windowMs)\n if elapsed >= 2 then previous = 0; current = 0; start = at\n elseif elapsed == 1 then previous = current; current = 0; start = start + windowMs end\n local weight = (windowMs - (at - start)) / windowMs\n local estimate = previous * weight + current\n resetAt = start + windowMs\n allowed = estimate < limit\n if allowed then current = current + 1 end\n remaining = allowed and math.max(0, math.floor(limit - estimate - 1)) or 0\n retryAfter = allowed and 0 or resetAt - at\n state = { kind = 'sliding', currStart = start, currCount = current, prevCount = previous }\n else\n local tokens = s and s.kind == 'token' and tonumber(s.tokens) or capacity\n local last = s and s.kind == 'token' and tonumber(s.lastRefill) or at\n local refill = limit / windowMs\n tokens = math.min(capacity, tokens + (at - last) * refill)\n allowed = tokens >= 1\n if allowed then tokens = tokens - 1 end\n retryAfter = allowed and 0 or math.ceil((1 - tokens) / refill)\n remaining = allowed and math.floor(tokens) or 0\n resetAt = at + (allowed and math.ceil((capacity - tokens) / refill) or retryAfter)\n state = { kind = 'token', tokens = tokens, lastRefill = at }\n end\n for field, value in pairs(state) do\n if type(value) == 'number' then state[field] = string.format('%.17g', value) end\n end\n redis.call('SET', k, 'r:' .. cjson.encode(state), 'PX', string.format('%.0f', math.ceil(math.max(windowMs * 2, 60000) + 1000)))\n return { allowed = allowed, remaining = string.format('%.17g', remaining), resetAtMs = string.format('%.17g', resetAt), retryAfterMs = string.format('%.17g', retryAfter) }\n elseif op == 'hset' then\n for f, v in pairs(o.fields) do redis.call('HSET', k, f, v) end\n ttl(k, o.options); return cjson.null\n elseif op == 'hget' then return redis.call('HGET', k, o.field) or cjson.null\n elseif op == 'hgetAll' then\n local raw = redis.call('HGETALL', k)\n local fields = {}\n for i = 1, #raw, 2 do fields[raw[i]] = raw[i + 1] end\n return fields\n elseif op == 'hdel' then\n local count = 0\n for _, field in ipairs(o.fields) do count = count + redis.call('HDEL', k, field) end\n return count\n elseif op == 'sadd' or op == 'srem' then\n local count = 0\n for _, member in ipairs(o.members) do count = count + redis.call(op == 'sadd' and 'SADD' or 'SREM', k, member) end\n if op == 'sadd' then ttl(k, o.options) end\n return count\n elseif op == 'smembers' then\n local members = redis.call('SMEMBERS', k); table.sort(members); return members\n elseif op == 'sismember' then return redis.call('SISMEMBER', k, o.member) == 1\n elseif op == 'setNx' then return redis.call('SET', k, 'l:' .. o.value, 'NX', 'PX', string.format('%.0f', o.ttlMs)) ~= false\n elseif op == 'compareDelete' or op == 'compareExpire' then\n local value = numberString(k, 'l:')\n if value == nil or value ~= o.value then return false end\n if op == 'compareDelete' then return redis.call('DEL', k) == 1 end\n return redis.call('PEXPIRE', k, string.format('%.0f', o.ttlMs)) == 1\n elseif op == 'expire' then redis.call('PEXPIRE', k, string.format('%.0f', o.ttlMs)); return cjson.null\n elseif op == 'delete' then return redis.call('DEL', k) == 1 end\n error('HOT_INVALID')\nend\nfor i, op in ipairs(ops) do\n local ok, result = pcall(run, op, KEYS[i])\n if not ok then\n local reason = 'unavailable'\n if string.find(result, 'WRONGTYPE', 1, true) then reason = 'wrongType'\n elseif string.find(result, 'HOT_LIMIT', 1, true) then reason = 'limit'\n elseif string.find(result, 'HOT_INVALID', 1, true) then reason = 'invalid' end\n return fail(op, reason)\n end\n -- Redis cjson numbers have only 14 significant digits. Use strings on\n -- known numeric result slots so safe integers and fractional scores survive.\n if type(result) == 'number' then result = string.format('%.17g', result) end\n table.insert(out, { value = result })\nend\nreturn cjson.encode({ results = out })\n") {
137
- let e = JSON.parse(String(r[t]));
138
- if (!Array.isArray(e) || e.length !== t || r.length !== t + 1) throw Error("Invalid HotStore batch");
136
+ if (r === "\nlocal ops = cjson.decode(ARGV[1])\nlocal tm = redis.call('TIME')\nlocal now = tonumber(tm[1]) * 1000 + math.floor(tonumber(tm[2]) / 1000)\nlocal out = {}\nlocal function fail(op, reason)\n return cjson.encode({ failure = { operation = op.op, key = op.key, reason = reason } })\nend\nlocal function ttl(k, o)\n if o and o.ttlMs then redis.call('PEXPIRE', k, string.format('%.0f', o.ttlMs)) end\nend\nlocal function numberString(k, prefix)\n local raw = redis.call('GET', k)\n if not raw then return nil end\n if string.sub(raw, 1, 2) ~= prefix then error('WRONGTYPE') end\n return string.sub(raw, 3)\nend\nlocal function run(o, k)\n local op = o.op\n local expected\n if string.sub(op, 1, 1) == 'z' then expected = 'zset'\n elseif string.sub(op, 1, 1) == 'h' then expected = 'hash'\n elseif op == 'sadd' or op == 'srem' or op == 'smembers' or op == 'sismember' then expected = 'set' end\n if expected then\n local actual = redis.call('TYPE', k).ok\n if actual ~= 'none' and actual ~= expected then error('WRONGTYPE') end\n end\n if op == 'zadd' then\n local pending = {}\n local mode = o.options and o.options.mode or 'set'\n for _, m in ipairs(o.members) do\n local old\n if mode ~= 'set' then old = pending[m.member] or tonumber(redis.call('ZSCORE', k, m.member)) end\n local score = m.score\n if old then\n if mode == 'max' then score = math.max(old, score)\n elseif mode == 'min' then score = math.min(old, score)\n elseif mode == 'incr' then score = old + score end\n end\n if score == math.huge or score == -math.huge or score ~= score then error('HOT_INVALID') end\n pending[m.member] = score\n end\n -- RESP-family Lua bridges differ in number-to-argument precision.\n for member, score in pairs(pending) do redis.call('ZADD', k, string.format('%.17g', score), member) end\n ttl(k, o.options); return cjson.null\n elseif op == 'zrem' then\n local count = 0\n for _, member in ipairs(o.members) do count = count + redis.call('ZREM', k, member) end\n return count\n elseif op == 'zrank' then\n local cmd = o.order == 'desc' and 'ZREVRANK' or 'ZRANK'\n return redis.call(cmd, k, o.member) or cjson.null\n elseif op == 'zscore' then\n return tonumber(redis.call('ZSCORE', k, o.member)) or cjson.null\n elseif op == 'zcard' then return redis.call('ZCARD', k)\n elseif op == 'zrange' then\n local raw\n local limit = o.options and o.options.limit\n if limit == 0 then return {} end\n if o.range.byRank then\n local cmd = o.order == 'desc' and 'ZREVRANGE' or 'ZRANGE'\n local lo, hi = o.range.byRank[1], o.range.byRank[2]\n if limit then\n local count = redis.call('ZCARD', k)\n if lo < 0 then lo = count + lo end\n if hi < 0 then hi = count + hi end\n lo = math.max(0, lo)\n hi = math.min(hi, lo + limit - 1)\n if hi < lo then return {} end\n end\n raw = redis.call(cmd, k, string.format('%.0f', lo), string.format('%.0f', hi), 'WITHSCORES')\n else\n local cmd = o.order == 'desc' and 'ZREVRANGEBYSCORE' or 'ZRANGEBYSCORE'\n local lo, hi = o.range.byScore[1], o.range.byScore[2]\n if lo > hi then return {} end\n if o.order == 'desc' then lo, hi = hi, lo end\n if limit then raw = redis.call(cmd, k, string.format('%.17g', lo), string.format('%.17g', hi), 'WITHSCORES', 'LIMIT', 0, limit)\n else raw = redis.call(cmd, k, string.format('%.17g', lo), string.format('%.17g', hi), 'WITHSCORES') end\n end\n local result = {}\n for i = 1, #raw / 2 do\n local score = raw[i * 2]\n if type(score) == 'number' then score = string.format('%.17g', score) end\n table.insert(result, { member = raw[i * 2 - 1], score = score })\n end\n return result\n elseif op == 'zremRange' then\n local pair = o.range.byRank or o.range.byScore\n local cmd = o.range.byRank and 'ZREMRANGEBYRANK' or 'ZREMRANGEBYSCORE'\n local format = o.range.byRank and '%.0f' or '%.17g'\n return redis.call(cmd, k, string.format(format, pair[1]), string.format(format, pair[2]))\n elseif op == 'incrBy' then\n local value = tonumber(numberString(k, 'c:')) or 0\n value = value + o.delta\n if math.abs(value) > 9007199254740991 then error('HOT_INVALID') end\n if o.options and o.options.max and value > o.options.max then error('HOT_LIMIT') end\n redis.call('SET', k, 'c:' .. string.format('%.0f', value), 'KEEPTTL')\n ttl(k, o.options); return value\n elseif op == 'tokenBucket' then\n local raw = numberString(k, 'b:')\n local old = raw and cjson.decode(raw) or { tokens = o.config.capacity, updatedAt = now }\n local available = math.min(o.config.capacity, tonumber(old.tokens) + math.max(0, now - tonumber(old.updatedAt)) * o.config.refillPerSec / 1000)\n local allowed = available >= o.cost\n local remaining = available\n if allowed then remaining = remaining - o.cost end\n local retry = allowed and 0 or math.ceil((o.cost - available) / o.config.refillPerSec * 1000)\n local life = math.max(1, math.ceil(o.config.capacity / o.config.refillPerSec * 1000))\n redis.call('SET', k, 'b:' .. cjson.encode({ tokens = string.format('%.17g', remaining), updatedAt = string.format('%.0f', math.max(now, tonumber(old.updatedAt))) }), 'PX', string.format('%.0f', life))\n return { allowed = allowed, remaining = string.format('%.17g', remaining), retryAfterMs = string.format('%.0f', retry) }\n elseif op == 'rateLimit' then\n local raw = numberString(k, 'r:')\n local s = raw and cjson.decode(raw) or nil\n local cfg = o.config\n local at = o.nowMs or now\n local limit, windowMs, capacity = cfg.limit, cfg.windowMs, cfg.burst\n local allowed, remaining, resetAt, retryAfter\n local state\n if cfg.algorithm == 'fixed-window' then\n local start = s and s.kind == 'fixed' and tonumber(s.windowStart) or at\n local count = s and s.kind == 'fixed' and tonumber(s.count) or 0\n if at - start >= windowMs then start = at; count = 0 end\n resetAt = start + windowMs\n allowed = count < limit\n if allowed then count = count + 1 end\n remaining = allowed and limit - count or 0\n retryAfter = allowed and 0 or resetAt - at\n state = { kind = 'fixed', windowStart = start, count = count }\n elseif cfg.algorithm == 'sliding-window' then\n local start = s and s.kind == 'sliding' and tonumber(s.currStart) or at\n local current = s and s.kind == 'sliding' and tonumber(s.currCount) or 0\n local previous = s and s.kind == 'sliding' and tonumber(s.prevCount) or 0\n local elapsed = math.floor((at - start) / windowMs)\n if elapsed >= 2 then previous = 0; current = 0; start = at\n elseif elapsed == 1 then previous = current; current = 0; start = start + windowMs end\n local weight = (windowMs - (at - start)) / windowMs\n local estimate = previous * weight + current\n resetAt = start + windowMs\n allowed = estimate < limit\n if allowed then current = current + 1 end\n remaining = allowed and math.max(0, math.floor(limit - estimate - 1)) or 0\n retryAfter = allowed and 0 or resetAt - at\n state = { kind = 'sliding', currStart = start, currCount = current, prevCount = previous }\n else\n local tokens = s and s.kind == 'token' and tonumber(s.tokens) or capacity\n local last = s and s.kind == 'token' and tonumber(s.lastRefill) or at\n local refill = limit / windowMs\n tokens = math.min(capacity, tokens + (at - last) * refill)\n allowed = tokens >= 1\n if allowed then tokens = tokens - 1 end\n retryAfter = allowed and 0 or math.ceil((1 - tokens) / refill)\n remaining = allowed and math.floor(tokens) or 0\n resetAt = at + (allowed and math.ceil((capacity - tokens) / refill) or retryAfter)\n state = { kind = 'token', tokens = tokens, lastRefill = at }\n end\n for field, value in pairs(state) do\n if type(value) == 'number' then state[field] = string.format('%.17g', value) end\n end\n redis.call('SET', k, 'r:' .. cjson.encode(state), 'PX', string.format('%.0f', math.ceil(math.max(windowMs * 2, 60000) + 1000)))\n return { allowed = allowed, remaining = string.format('%.17g', remaining), resetAtMs = string.format('%.17g', resetAt), retryAfterMs = string.format('%.17g', retryAfter) }\n elseif op == 'hset' then\n for f, v in pairs(o.fields) do redis.call('HSET', k, f, v) end\n ttl(k, o.options); return cjson.null\n elseif op == 'hget' then return redis.call('HGET', k, o.field) or cjson.null\n elseif op == 'hgetAll' then\n local raw = redis.call('HGETALL', k)\n local fields = {}\n for i = 1, #raw, 2 do fields[raw[i]] = raw[i + 1] end\n return fields\n elseif op == 'hdel' then\n local count = 0\n for _, field in ipairs(o.fields) do count = count + redis.call('HDEL', k, field) end\n return count\n elseif op == 'sadd' or op == 'srem' then\n local count = 0\n for _, member in ipairs(o.members) do count = count + redis.call(op == 'sadd' and 'SADD' or 'SREM', k, member) end\n if op == 'sadd' then ttl(k, o.options) end\n return count\n elseif op == 'smembers' then\n local members = redis.call('SMEMBERS', k); table.sort(members); return members\n elseif op == 'sismember' then return redis.call('SISMEMBER', k, o.member) == 1\n elseif op == 'setNx' then return redis.call('SET', k, 'l:' .. o.value, 'NX', 'PX', string.format('%.0f', o.ttlMs)) ~= false\n elseif op == 'compareDelete' or op == 'compareExpire' then\n local value = numberString(k, 'l:')\n if value == nil or value ~= o.value then return false end\n if op == 'compareDelete' then return redis.call('DEL', k) == 1 end\n return redis.call('PEXPIRE', k, string.format('%.0f', o.ttlMs)) == 1\n elseif op == 'expire' then redis.call('PEXPIRE', k, string.format('%.0f', o.ttlMs)); return cjson.null\n elseif op == 'delete' then return redis.call('DEL', k) == 1 end\n error('HOT_INVALID')\nend\nfor i, op in ipairs(ops) do\n local ok, result = pcall(run, op, KEYS[i])\n if not ok then\n local reason = 'unavailable'\n if string.find(result, 'WRONGTYPE', 1, true) then reason = 'wrongType'\n elseif string.find(result, 'HOT_LIMIT', 1, true) then reason = 'limit'\n elseif string.find(result, 'HOT_INVALID', 1, true) then reason = 'invalid' end\n return fail(op, reason)\n end\n -- Redis cjson numbers have only 14 significant digits. Use strings on\n -- known numeric result slots so safe integers and fractional scores survive.\n if type(result) == 'number' then result = string.format('%.17g', result) end\n table.insert(out, { value = result })\nend\nreturn cjson.encode({ results = out })\n") {
137
+ let n = JSON.parse(String(s[o]));
138
+ if (!Array.isArray(n) || n.length !== o || s.length !== o + 1) throw Error("Invalid HotStore batch");
139
139
  try {
140
- let t = e.map((e, t) => {
141
- let n = String(r[t]);
142
- if (h(n), l.has(n) || u.has(n)) throw new o({
143
- operation: e.op,
144
- key: e.key,
140
+ let r = n.map((t, n) => {
141
+ let r = String(s[n]);
142
+ if (h(r), l.has(r) || u.has(r)) throw new e({
143
+ operation: t.op,
144
+ key: t.key,
145
145
  reason: "wrongType"
146
146
  });
147
147
  return {
148
- ...e,
149
- key: n
148
+ ...t,
149
+ key: r
150
150
  };
151
- }), n = i(d, t, c());
152
- return JSON.stringify({ results: n.map((e) => ({ value: e })) });
153
- } catch (n) {
154
- if (!(n instanceof o)) throw n;
155
- let i = r.slice(0, t).findIndex((e) => e === n.key);
151
+ }), i = t(d, r, c());
152
+ return JSON.stringify({ results: i.map((e) => ({ value: e })) });
153
+ } catch (t) {
154
+ if (!(t instanceof e)) throw t;
155
+ let r = s.slice(0, o).findIndex((e) => e === t.key);
156
156
  return JSON.stringify({ failure: {
157
- operation: n.operation,
158
- key: i < 0 ? n.key : e[i].key,
159
- reason: n.reason
157
+ operation: t.operation,
158
+ key: r < 0 ? t.key : n[r].key,
159
+ reason: t.reason
160
160
  } });
161
161
  }
162
162
  }
@@ -1,6 +1,6 @@
1
- import { KvError as e } from "./errors.js";
2
- import { missingDriver as t } from "./driverModule.js";
3
- import { assertNatsSubject as n } from "./connectionNatsSubjects.js";
1
+ import { assertNatsSubject as e } from "./connectionNatsSubjects.js";
2
+ import { KvError as t } from "./errors.js";
3
+ import { missingDriver as n } from "./driverModule.js";
4
4
  import { Effect as r } from "effect";
5
5
  // src/connectionNats.ts
6
6
  var i = new TextEncoder(), a = new TextDecoder(), o = 5e3, s = 1e3, c = async (e, t) => {
@@ -14,14 +14,14 @@ var i = new TextEncoder(), a = new TextDecoder(), o = 5e3, s = 1e3, c = async (e
14
14
  } finally {
15
15
  n !== void 0 && clearTimeout(n);
16
16
  }
17
- }, l = (e) => {
18
- let t = /* @__PURE__ */ new Set(), r = /* @__PURE__ */ new Set(), l = /* @__PURE__ */ new Set(), u = /* @__PURE__ */ new Map(), d = !0, f = !1, p, m = (e) => {
17
+ }, l = (t) => {
18
+ let n = /* @__PURE__ */ new Set(), r = /* @__PURE__ */ new Set(), l = /* @__PURE__ */ new Set(), u = /* @__PURE__ */ new Map(), d = !0, f = !1, p, m = (e) => {
19
19
  for (let t of r) try {
20
20
  t(e);
21
21
  } catch {}
22
22
  }, h = () => {
23
23
  !f && d && (d = !1, m({ kind: "disconnected" }));
24
- }, g = e.status()[Symbol.asyncIterator](), _ = (async () => {
24
+ }, g = t.status()[Symbol.asyncIterator](), _ = (async () => {
25
25
  try {
26
26
  for (;;) {
27
27
  let e = await g.next();
@@ -41,17 +41,17 @@ var i = new TextEncoder(), a = new TextDecoder(), o = 5e3, s = 1e3, c = async (e
41
41
  t !== void 0 && (t.released = !0, u.delete(e), t.subscription.unsubscribe(), await t.done);
42
42
  };
43
43
  return {
44
- publish: async (t, r) => {
45
- n(t), v(), e.publish(t, i.encode(r));
44
+ publish: async (n, r) => {
45
+ e(n), v(), t.publish(n, i.encode(r));
46
46
  },
47
47
  flush: async () => {
48
- v(), await c(e.flush(), o);
48
+ v(), await c(t.flush(), o);
49
49
  },
50
50
  subscribe: async (r) => {
51
- n(r), v();
51
+ e(r), v();
52
52
  let i = u.get(r);
53
53
  if (i !== void 0) return i.ready;
54
- let s = e.subscribe(r), d = {
54
+ let s = t.subscribe(r), d = {
55
55
  subscription: s,
56
56
  released: !1,
57
57
  done: Promise.resolve(),
@@ -61,9 +61,9 @@ var i = new TextEncoder(), a = new TextDecoder(), o = 5e3, s = 1e3, c = async (e
61
61
  try {
62
62
  for await (let e of s) {
63
63
  if (f || d.released) continue;
64
- let n = a.decode(e.data);
65
- for (let e of t) try {
66
- e(r, n);
64
+ let t = a.decode(e.data);
65
+ for (let e of n) try {
66
+ e(r, t);
67
67
  } catch {}
68
68
  }
69
69
  } finally {
@@ -73,7 +73,7 @@ var i = new TextEncoder(), a = new TextDecoder(), o = 5e3, s = 1e3, c = async (e
73
73
  d.released || h();
74
74
  }), l.add(d.done), d.done.then(() => {
75
75
  l.delete(d.done);
76
- }), d.ready = c(e.flush(), o).then(() => {
76
+ }), d.ready = c(t.flush(), o).then(() => {
77
77
  if (v(), d.released) throw Error("NATS subscription is closed");
78
78
  }).catch(async (e) => {
79
79
  throw u.get(r) === d && await y(r), e;
@@ -82,8 +82,8 @@ var i = new TextEncoder(), a = new TextDecoder(), o = 5e3, s = 1e3, c = async (e
82
82
  unsubscribe: y,
83
83
  onMessage: (e) => {
84
84
  if (f) throw Error("NATS transport is closed");
85
- return t.add(e), () => {
86
- t.delete(e);
85
+ return n.add(e), () => {
86
+ n.delete(e);
87
87
  };
88
88
  },
89
89
  onTransportEvent: (e) => {
@@ -93,7 +93,7 @@ var i = new TextEncoder(), a = new TextDecoder(), o = 5e3, s = 1e3, c = async (e
93
93
  };
94
94
  },
95
95
  close: () => p ??= (async () => {
96
- f = !0, t.clear(), r.clear();
96
+ f = !0, n.clear(), r.clear();
97
97
  for (let e of u.values()) {
98
98
  e.released = !0;
99
99
  try {
@@ -102,40 +102,40 @@ var i = new TextEncoder(), a = new TextDecoder(), o = 5e3, s = 1e3, c = async (e
102
102
  }
103
103
  u.clear();
104
104
  try {
105
- await c(e.drain(), s);
105
+ await c(t.drain(), s);
106
106
  } catch {} finally {
107
- await e.close(), await g.return?.(), await Promise.all([...l]), await _;
107
+ await t.close(), await g.return?.(), await Promise.all([...l]), await _;
108
108
  }
109
109
  })()
110
110
  };
111
- }, u = (n) => r.callback((i) => {
111
+ }, u = (e) => r.callback((i) => {
112
112
  let a = !1, s, c = (async () => {
113
- let e = await (await import("@nats-io/transport-node").catch(t("@nats-io/transport-node", "A NATS connection"))).connect({
114
- servers: n.url.split(",").map((e) => e.trim()),
113
+ let t = await (await import("@nats-io/transport-node").catch(n("@nats-io/transport-node", "A NATS connection"))).connect({
114
+ servers: e.url.split(",").map((e) => e.trim()),
115
115
  maxReconnectAttempts: -1,
116
116
  waitOnFirstConnect: !0,
117
117
  reconnectTimeWait: 2e3,
118
118
  timeout: o,
119
- ...n.tls === "required" ? { tls: {} } : {},
120
- ...n.token === void 0 ? {} : { token: n.token },
121
- ...n.user === void 0 ? {} : { user: n.user },
122
- ...n.pass === void 0 ? {} : { pass: n.pass },
119
+ ...e.tls === "required" ? { tls: {} } : {},
120
+ ...e.token === void 0 ? {} : { token: e.token },
121
+ ...e.user === void 0 ? {} : { user: e.user },
122
+ ...e.pass === void 0 ? {} : { pass: e.pass },
123
123
  reconnectToServer: () => {
124
124
  if (a) throw Error("NATS acquisition cancelled");
125
125
  return null;
126
126
  }
127
127
  });
128
- if (a) await e.close();
128
+ if (a) await t.close();
129
129
  else {
130
130
  try {
131
- s = l(e);
132
- } catch (t) {
133
- throw await e.close(), t;
131
+ s = l(t);
132
+ } catch (e) {
133
+ throw await t.close(), e;
134
134
  }
135
135
  i(r.succeed(s));
136
136
  }
137
137
  })().catch(() => {
138
- a || i(r.fail(new e({
138
+ a || i(r.fail(new t({
139
139
  operation: "connect",
140
140
  key: "",
141
141
  cause: "NATS driver could not be opened"