@sonamu-kit/websocket-redis-adapter 0.0.0-stage → 0.13.0

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.
@@ -0,0 +1,23 @@
1
+ export type LuaScript = {
2
+ name: string;
3
+ source: string;
4
+ sha: string;
5
+ };
6
+ /**
7
+ * 세션 하나의 상태를 메모리 snapshot으로 맞춘다(upsert/삭제).
8
+ * Redis에 남아 있던 이전 JSON의 기여분을 빼고 새 JSON의 기여분을 더하므로, 이전 쓰기가 유실됐어도 count가 세션 상태와 어긋나지 않는다.
9
+ * KEYS: sessions, rooms, users, namespaces / ARGV: sessionId, presence JSON(빈 문자열이면 삭제), keyTtlMs
10
+ */
11
+ export declare const APPLY_SESSION_SCRIPT: LuaScript;
12
+ /**
13
+ * 노드 키 4개를 지우고 메모리 snapshot으로 다시 쓴다. 쓰기 실패나 failover 뒤의 불일치(고스트 엔트리 포함)를 한 번에 정리한다.
14
+ * KEYS: sessions, rooms, users, namespaces / ARGV: keyTtlMs, (sessionId, presence JSON) 반복
15
+ */
16
+ export declare const REBUILD_NODE_SCRIPT: LuaScript;
17
+ /**
18
+ * 한 노드에서 audience 조건에 맞는 활성 세션 수를 센다. 세션 목록은 읽지 않고 count 해시만 읽는다.
19
+ * namespace가 없거나 빈 문자열인 조건은 core와 같이 모든 namespace로 보고, 그 노드의 namespaces 해시 필드(활성 namespace 목록)로 펼친다.
20
+ * KEYS: rooms, users, namespaces / ARGV: 조건 JSON 배열 [{ k: "all" | "room" | "user", ns?, id? }]
21
+ */
22
+ export declare const COUNT_AUDIENCE_SCRIPT: LuaScript;
23
+ //# sourceMappingURL=scripts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scripts.d.ts","sourceRoot":"","sources":["../src/scripts.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,SAAS,GAAG;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,EAAE,MAAM,CAAC;CACb,CAAC;AAwDF;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,WAoChC,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,mBAAmB,WAyB/B,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,WAmDjC,CAAC"}
@@ -0,0 +1,180 @@
1
+ import { createHash } from "node:crypto";
2
+ // src/scripts.ts
3
+ function defineScript(name, source) {
4
+ return {
5
+ name,
6
+ source,
7
+ sha: createHash("sha1").update(source).digest("hex")
8
+ };
9
+ }
10
+ /**
11
+ * 세션 presence JSON에서 count 해시 기여분을 계산하는 공통 Lua 함수.
12
+ * - 비활성 세션은 아무 count에도 기여하지 않는다.
13
+ * - room/user 필드는 `<namespace 바이트 길이>:<namespace>:<id>` 형식이라 구분자가 namespace에 들어 있어도 모호하지 않다.
14
+ * countAudience 스크립트의 fieldOf()와 같은 형식을 유지해야 한다.
15
+ * - user id는 JS에서 타입 태그를 붙인 문자열(`n:1`, `s:1`)이라 1과 "1"이 다른 필드가 된다.
16
+ * - 키 이름은 항상 KEYS에서만 가져온다(호출자 keyPrefix와 Cluster slot 규칙을 지키기 위해).
17
+ */
18
+ const CONTRIBUTIONS_LUA = `
19
+ local function fieldOf(namespace, id)
20
+ return string.len(namespace) .. ':' .. namespace .. ':' .. id
21
+ end
22
+
23
+ local function addContributions(deltas, keys, json, delta)
24
+ if not json or json == '' then
25
+ return
26
+ end
27
+ local ok, session = pcall(cjson.decode, json)
28
+ if not ok or type(session) ~= 'table' or session.active ~= true or type(session.namespace) ~= 'string' then
29
+ return
30
+ end
31
+ local namespace = session.namespace
32
+ local contributions = { { keys.namespaces, namespace } }
33
+ if type(session.rooms) == 'table' then
34
+ for _, roomId in ipairs(session.rooms) do
35
+ if type(roomId) == 'string' then
36
+ table.insert(contributions, { keys.rooms, fieldOf(namespace, roomId) })
37
+ end
38
+ end
39
+ end
40
+ if type(session.userId) == 'string' then
41
+ table.insert(contributions, { keys.users, fieldOf(namespace, session.userId) })
42
+ end
43
+ for _, contribution in ipairs(contributions) do
44
+ local key = contribution[1]
45
+ local field = contribution[2]
46
+ local byKey = deltas[key]
47
+ if not byKey then
48
+ byKey = {}
49
+ deltas[key] = byKey
50
+ end
51
+ byKey[field] = (byKey[field] or 0) + delta
52
+ end
53
+ end
54
+ `;
55
+ const NODE_KEYS_LUA = `
56
+ local keys = { sessions = KEYS[1], rooms = KEYS[2], users = KEYS[3], namespaces = KEYS[4] }
57
+ `;
58
+ /**
59
+ * 세션 하나의 상태를 메모리 snapshot으로 맞춘다(upsert/삭제).
60
+ * Redis에 남아 있던 이전 JSON의 기여분을 빼고 새 JSON의 기여분을 더하므로, 이전 쓰기가 유실됐어도 count가 세션 상태와 어긋나지 않는다.
61
+ * KEYS: sessions, rooms, users, namespaces / ARGV: sessionId, presence JSON(빈 문자열이면 삭제), keyTtlMs
62
+ */
63
+ const APPLY_SESSION_SCRIPT = defineScript("applySession", `${CONTRIBUTIONS_LUA}${NODE_KEYS_LUA}
64
+ local sessionId = ARGV[1]
65
+ local nextJson = ARGV[2]
66
+ local ttl = tonumber(ARGV[3])
67
+
68
+ local deltas = {}
69
+ local previous = redis.call('HGET', keys.sessions, sessionId)
70
+ if previous then
71
+ addContributions(deltas, keys, previous, -1)
72
+ end
73
+ addContributions(deltas, keys, nextJson, 1)
74
+
75
+ for key, fields in pairs(deltas) do
76
+ for field, delta in pairs(fields) do
77
+ if delta ~= 0 then
78
+ local count = redis.call('HINCRBY', key, field, delta)
79
+ if count <= 0 then
80
+ redis.call('HDEL', key, field)
81
+ end
82
+ end
83
+ end
84
+ end
85
+
86
+ if nextJson ~= '' then
87
+ redis.call('HSET', keys.sessions, sessionId, nextJson)
88
+ elseif previous then
89
+ redis.call('HDEL', keys.sessions, sessionId)
90
+ end
91
+
92
+ for index = 1, 4 do
93
+ redis.call('PEXPIRE', KEYS[index], ttl)
94
+ end
95
+ return 1
96
+ `);
97
+ /**
98
+ * 노드 키 4개를 지우고 메모리 snapshot으로 다시 쓴다. 쓰기 실패나 failover 뒤의 불일치(고스트 엔트리 포함)를 한 번에 정리한다.
99
+ * KEYS: sessions, rooms, users, namespaces / ARGV: keyTtlMs, (sessionId, presence JSON) 반복
100
+ */
101
+ const REBUILD_NODE_SCRIPT = defineScript("rebuildNode", `${CONTRIBUTIONS_LUA}${NODE_KEYS_LUA}
102
+ local ttl = tonumber(ARGV[1])
103
+ redis.call('DEL', KEYS[1], KEYS[2], KEYS[3], KEYS[4])
104
+
105
+ local deltas = {}
106
+ for index = 2, #ARGV, 2 do
107
+ redis.call('HSET', keys.sessions, ARGV[index], ARGV[index + 1])
108
+ addContributions(deltas, keys, ARGV[index + 1], 1)
109
+ end
110
+
111
+ for key, fields in pairs(deltas) do
112
+ for field, count in pairs(fields) do
113
+ if count > 0 then
114
+ redis.call('HSET', key, field, count)
115
+ end
116
+ end
117
+ end
118
+
119
+ for index = 1, 4 do
120
+ redis.call('PEXPIRE', KEYS[index], ttl)
121
+ end
122
+ return 1
123
+ `);
124
+ /**
125
+ * 한 노드에서 audience 조건에 맞는 활성 세션 수를 센다. 세션 목록은 읽지 않고 count 해시만 읽는다.
126
+ * namespace가 없거나 빈 문자열인 조건은 core와 같이 모든 namespace로 보고, 그 노드의 namespaces 해시 필드(활성 namespace 목록)로 펼친다.
127
+ * KEYS: rooms, users, namespaces / ARGV: 조건 JSON 배열 [{ k: "all" | "room" | "user", ns?, id? }]
128
+ */
129
+ const COUNT_AUDIENCE_SCRIPT = defineScript("countAudience", `
130
+ local roomsKey = KEYS[1]
131
+ local usersKey = KEYS[2]
132
+ local namespacesKey = KEYS[3]
133
+ local leaves = cjson.decode(ARGV[1])
134
+
135
+ local function fieldOf(namespace, id)
136
+ return string.len(namespace) .. ':' .. namespace .. ':' .. id
137
+ end
138
+
139
+ local function countOf(key, field)
140
+ return tonumber(redis.call('HGET', key, field)) or 0
141
+ end
142
+
143
+ local activeNamespaces = nil
144
+ local function namespaces()
145
+ if activeNamespaces == nil then
146
+ activeNamespaces = redis.call('HKEYS', namespacesKey)
147
+ end
148
+ return activeNamespaces
149
+ end
150
+
151
+ local total = 0
152
+ for _, leaf in ipairs(leaves) do
153
+ local namespace = leaf.ns
154
+ if leaf.k == 'all' then
155
+ if type(namespace) == 'string' and namespace ~= '' then
156
+ total = total + countOf(namespacesKey, namespace)
157
+ else
158
+ for _, name in ipairs(namespaces()) do
159
+ total = total + countOf(namespacesKey, name)
160
+ end
161
+ end
162
+ else
163
+ local key = roomsKey
164
+ if leaf.k == 'user' then
165
+ key = usersKey
166
+ end
167
+ if type(namespace) == 'string' and namespace ~= '' then
168
+ total = total + countOf(key, fieldOf(namespace, leaf.id))
169
+ else
170
+ for _, name in ipairs(namespaces()) do
171
+ total = total + countOf(key, fieldOf(name, leaf.id))
172
+ end
173
+ end
174
+ end
175
+ end
176
+ return total
177
+ `);
178
+ export { APPLY_SESSION_SCRIPT, COUNT_AUDIENCE_SCRIPT, REBUILD_NODE_SCRIPT };
179
+
180
+ //# sourceMappingURL=scripts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scripts.js","names":[],"sources":["../src/scripts.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\n\nexport type LuaScript = {\n name: string;\n source: string;\n sha: string;\n};\n\nfunction defineScript(name: string, source: string): LuaScript {\n return { name, source, sha: createHash(\"sha1\").update(source).digest(\"hex\") };\n}\n\n/**\n * 세션 presence JSON에서 count 해시 기여분을 계산하는 공통 Lua 함수.\n * - 비활성 세션은 아무 count에도 기여하지 않는다.\n * - room/user 필드는 `<namespace 바이트 길이>:<namespace>:<id>` 형식이라 구분자가 namespace에 들어 있어도 모호하지 않다.\n * countAudience 스크립트의 fieldOf()와 같은 형식을 유지해야 한다.\n * - user id는 JS에서 타입 태그를 붙인 문자열(`n:1`, `s:1`)이라 1과 \"1\"이 다른 필드가 된다.\n * - 키 이름은 항상 KEYS에서만 가져온다(호출자 keyPrefix와 Cluster slot 규칙을 지키기 위해).\n */\nconst CONTRIBUTIONS_LUA = `\nlocal function fieldOf(namespace, id)\n return string.len(namespace) .. ':' .. namespace .. ':' .. id\nend\n\nlocal function addContributions(deltas, keys, json, delta)\n if not json or json == '' then\n return\n end\n local ok, session = pcall(cjson.decode, json)\n if not ok or type(session) ~= 'table' or session.active ~= true or type(session.namespace) ~= 'string' then\n return\n end\n local namespace = session.namespace\n local contributions = { { keys.namespaces, namespace } }\n if type(session.rooms) == 'table' then\n for _, roomId in ipairs(session.rooms) do\n if type(roomId) == 'string' then\n table.insert(contributions, { keys.rooms, fieldOf(namespace, roomId) })\n end\n end\n end\n if type(session.userId) == 'string' then\n table.insert(contributions, { keys.users, fieldOf(namespace, session.userId) })\n end\n for _, contribution in ipairs(contributions) do\n local key = contribution[1]\n local field = contribution[2]\n local byKey = deltas[key]\n if not byKey then\n byKey = {}\n deltas[key] = byKey\n end\n byKey[field] = (byKey[field] or 0) + delta\n end\nend\n`;\n\nconst NODE_KEYS_LUA = `\nlocal keys = { sessions = KEYS[1], rooms = KEYS[2], users = KEYS[3], namespaces = KEYS[4] }\n`;\n\n/**\n * 세션 하나의 상태를 메모리 snapshot으로 맞춘다(upsert/삭제).\n * Redis에 남아 있던 이전 JSON의 기여분을 빼고 새 JSON의 기여분을 더하므로, 이전 쓰기가 유실됐어도 count가 세션 상태와 어긋나지 않는다.\n * KEYS: sessions, rooms, users, namespaces / ARGV: sessionId, presence JSON(빈 문자열이면 삭제), keyTtlMs\n */\nexport const APPLY_SESSION_SCRIPT = defineScript(\n \"applySession\",\n `${CONTRIBUTIONS_LUA}${NODE_KEYS_LUA}\nlocal sessionId = ARGV[1]\nlocal nextJson = ARGV[2]\nlocal ttl = tonumber(ARGV[3])\n\nlocal deltas = {}\nlocal previous = redis.call('HGET', keys.sessions, sessionId)\nif previous then\n addContributions(deltas, keys, previous, -1)\nend\naddContributions(deltas, keys, nextJson, 1)\n\nfor key, fields in pairs(deltas) do\n for field, delta in pairs(fields) do\n if delta ~= 0 then\n local count = redis.call('HINCRBY', key, field, delta)\n if count <= 0 then\n redis.call('HDEL', key, field)\n end\n end\n end\nend\n\nif nextJson ~= '' then\n redis.call('HSET', keys.sessions, sessionId, nextJson)\nelseif previous then\n redis.call('HDEL', keys.sessions, sessionId)\nend\n\nfor index = 1, 4 do\n redis.call('PEXPIRE', KEYS[index], ttl)\nend\nreturn 1\n`,\n);\n\n/**\n * 노드 키 4개를 지우고 메모리 snapshot으로 다시 쓴다. 쓰기 실패나 failover 뒤의 불일치(고스트 엔트리 포함)를 한 번에 정리한다.\n * KEYS: sessions, rooms, users, namespaces / ARGV: keyTtlMs, (sessionId, presence JSON) 반복\n */\nexport const REBUILD_NODE_SCRIPT = defineScript(\n \"rebuildNode\",\n `${CONTRIBUTIONS_LUA}${NODE_KEYS_LUA}\nlocal ttl = tonumber(ARGV[1])\nredis.call('DEL', KEYS[1], KEYS[2], KEYS[3], KEYS[4])\n\nlocal deltas = {}\nfor index = 2, #ARGV, 2 do\n redis.call('HSET', keys.sessions, ARGV[index], ARGV[index + 1])\n addContributions(deltas, keys, ARGV[index + 1], 1)\nend\n\nfor key, fields in pairs(deltas) do\n for field, count in pairs(fields) do\n if count > 0 then\n redis.call('HSET', key, field, count)\n end\n end\nend\n\nfor index = 1, 4 do\n redis.call('PEXPIRE', KEYS[index], ttl)\nend\nreturn 1\n`,\n);\n\n/**\n * 한 노드에서 audience 조건에 맞는 활성 세션 수를 센다. 세션 목록은 읽지 않고 count 해시만 읽는다.\n * namespace가 없거나 빈 문자열인 조건은 core와 같이 모든 namespace로 보고, 그 노드의 namespaces 해시 필드(활성 namespace 목록)로 펼친다.\n * KEYS: rooms, users, namespaces / ARGV: 조건 JSON 배열 [{ k: \"all\" | \"room\" | \"user\", ns?, id? }]\n */\nexport const COUNT_AUDIENCE_SCRIPT = defineScript(\n \"countAudience\",\n `\nlocal roomsKey = KEYS[1]\nlocal usersKey = KEYS[2]\nlocal namespacesKey = KEYS[3]\nlocal leaves = cjson.decode(ARGV[1])\n\nlocal function fieldOf(namespace, id)\n return string.len(namespace) .. ':' .. namespace .. ':' .. id\nend\n\nlocal function countOf(key, field)\n return tonumber(redis.call('HGET', key, field)) or 0\nend\n\nlocal activeNamespaces = nil\nlocal function namespaces()\n if activeNamespaces == nil then\n activeNamespaces = redis.call('HKEYS', namespacesKey)\n end\n return activeNamespaces\nend\n\nlocal total = 0\nfor _, leaf in ipairs(leaves) do\n local namespace = leaf.ns\n if leaf.k == 'all' then\n if type(namespace) == 'string' and namespace ~= '' then\n total = total + countOf(namespacesKey, namespace)\n else\n for _, name in ipairs(namespaces()) do\n total = total + countOf(namespacesKey, name)\n end\n end\n else\n local key = roomsKey\n if leaf.k == 'user' then\n key = usersKey\n end\n if type(namespace) == 'string' and namespace ~= '' then\n total = total + countOf(key, fieldOf(namespace, leaf.id))\n else\n for _, name in ipairs(namespaces()) do\n total = total + countOf(key, fieldOf(name, leaf.id))\n end\n end\n end\nend\nreturn total\n`,\n);\n"],"mappings":";;AAQA,SAAS,aAAa,MAAc,QAA2B;CAC7D,OAAO;EAAE;EAAM;EAAQ,KAAK,WAAW,MAAM,CAAC,CAAC,OAAO,MAAM,CAAC,CAAC,OAAO,KAAK;CAAE;AAC9E;;;;;;;;;AAUA,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsC1B,MAAM,gBAAgB;;;;;;;;AAStB,MAAa,uBAAuB,aAClC,gBACA,GAAG,oBAAoB,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkCvC;;;;;AAMA,MAAa,sBAAsB,aACjC,eACA,GAAG,oBAAoB,cAAc;;;;;;;;;;;;;;;;;;;;;;CAuBvC;;;;;;AAOA,MAAa,wBAAwB,aACnC,iBACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiDF"}
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@sonamu-kit/websocket-redis-adapter",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.13.0",
4
+ "description": "Redis presence store and cluster bus for Sonamu multi-node WebSocket delivery",
5
+ "license": "MIT",
6
+ "author": "CartaNova <dev@cartanova.ai>",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/cartanova-ai/sonamu.git",
10
+ "directory": "modules/websocket-redis-adapter"
11
+ },
12
+ "files": [
13
+ "dist"
14
+ ],
15
+ "type": "module",
16
+ "main": "./dist/index.js",
17
+ "exports": {
18
+ ".": {
19
+ "import": "./dist/index.js",
20
+ "types": "./dist/index.d.ts",
21
+ "development": "./src/index.ts"
22
+ }
23
+ },
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "dependencies": {
28
+ "zod": "^4.6.7"
29
+ },
30
+ "devDependencies": {
31
+ "@types/node": "26.6.5",
32
+ "oxfmt": "^0.74.0",
33
+ "oxlint": "1.89.0",
34
+ "redis": "^6.3.0",
35
+ "sonamu": "0.13.0",
36
+ "testcontainers": "^12.0.0",
37
+ "tsdown": "^0.23.1",
38
+ "typescript": "7.1.0-dev.20260831.1",
39
+ "vitest": "^5.0.5"
40
+ },
41
+ "peerDependencies": {
42
+ "redis": "^6.3.0",
43
+ "sonamu": ">=0.12.0"
44
+ },
45
+ "engines": {
46
+ "node": ">=22.0.0"
47
+ },
48
+ "scripts": {
49
+ "build": "tsdown && tsc --emitDeclarationOnly",
50
+ "typecheck": "pnpm run check:type",
51
+ "check": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json && tsc -p tsconfig.tools.json && oxlint src tests && oxfmt --check src tests *.json *.ts",
52
+ "check:type": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json && tsc -p tsconfig.tools.json",
53
+ "check:format": "oxfmt src tests *.json *.ts",
54
+ "test": "vitest run --passWithNoTests",
55
+ "test:watch": "vitest watch"
56
+ }
6
57
  }