@pluv/persistence-redis 0.0.0-experimental-20250527040415

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Shoubhit Dash
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,18 @@
1
+ ## `@pluv/persistence-redis`
2
+
3
+ > Crdt storage persistence for [@pluv/io](https://www.npmjs.com/package/@pluv/io) rooms on distributed systems. Available for [Node.js](https://nodejs.org/) only.
4
+
5
+ **👉 See full documentation on [pluv.io](https://pluv.io/docs/introduction). 👈**
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ # npm
11
+ npm install @pluv/persistence-redis ioredis
12
+
13
+ # yarn
14
+ yarn add @pluv/persistence-redis ioredis
15
+
16
+ # pnpm
17
+ pnpm add @pluv/persistence-redis ioredis
18
+ ```
@@ -0,0 +1,29 @@
1
+ import { AbstractPersistence } from '@pluv/io';
2
+ import { JsonObject } from '@pluv/types';
3
+ import { Cluster, Redis } from 'ioredis';
4
+
5
+ type RedisClient = Cluster | Redis;
6
+ interface PersistenceRedisOptions {
7
+ client: RedisClient;
8
+ }
9
+ declare class PersistenceRedis extends AbstractPersistence {
10
+ private _client;
11
+ private _initialized;
12
+ constructor(options: PersistenceRedisOptions);
13
+ addUser(room: string, connectionId: string, user: JsonObject | null): Promise<void>;
14
+ deleteStorageState(room: string): Promise<void>;
15
+ deleteUser(room: string, connectionId: string): Promise<void>;
16
+ deleteUsers(room: string): Promise<void>;
17
+ getStorageState(room: string): Promise<string | null>;
18
+ setStorageState(room: string, state: string): Promise<void>;
19
+ getUser(room: string, connectionId: string): Promise<JsonObject | null>;
20
+ getUsers(room: string): Promise<Map<[connectionId: string][0], JsonObject | null>>;
21
+ getUsersSize(room: string): Promise<number>;
22
+ initialize(roomContext: {}): typeof this;
23
+ private _getClusterKey;
24
+ private _getRoomStorageKey;
25
+ private _getRoomUsersKey;
26
+ private _getRoomUsersUserKey;
27
+ }
28
+
29
+ export { PersistenceRedis, type RedisClient };
@@ -0,0 +1,29 @@
1
+ import { AbstractPersistence } from '@pluv/io';
2
+ import { JsonObject } from '@pluv/types';
3
+ import { Cluster, Redis } from 'ioredis';
4
+
5
+ type RedisClient = Cluster | Redis;
6
+ interface PersistenceRedisOptions {
7
+ client: RedisClient;
8
+ }
9
+ declare class PersistenceRedis extends AbstractPersistence {
10
+ private _client;
11
+ private _initialized;
12
+ constructor(options: PersistenceRedisOptions);
13
+ addUser(room: string, connectionId: string, user: JsonObject | null): Promise<void>;
14
+ deleteStorageState(room: string): Promise<void>;
15
+ deleteUser(room: string, connectionId: string): Promise<void>;
16
+ deleteUsers(room: string): Promise<void>;
17
+ getStorageState(room: string): Promise<string | null>;
18
+ setStorageState(room: string, state: string): Promise<void>;
19
+ getUser(room: string, connectionId: string): Promise<JsonObject | null>;
20
+ getUsers(room: string): Promise<Map<[connectionId: string][0], JsonObject | null>>;
21
+ getUsersSize(room: string): Promise<number>;
22
+ initialize(roomContext: {}): typeof this;
23
+ private _getClusterKey;
24
+ private _getRoomStorageKey;
25
+ private _getRoomUsersKey;
26
+ private _getRoomUsersUserKey;
27
+ }
28
+
29
+ export { PersistenceRedis, type RedisClient };
package/dist/index.js ADDED
@@ -0,0 +1,189 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __spreadValues = (a, b) => {
10
+ for (var prop in b || (b = {}))
11
+ if (__hasOwnProp.call(b, prop))
12
+ __defNormalProp(a, prop, b[prop]);
13
+ if (__getOwnPropSymbols)
14
+ for (var prop of __getOwnPropSymbols(b)) {
15
+ if (__propIsEnum.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ }
18
+ return a;
19
+ };
20
+ var __export = (target, all) => {
21
+ for (var name in all)
22
+ __defProp(target, name, { get: all[name], enumerable: true });
23
+ };
24
+ var __copyProps = (to, from, except, desc) => {
25
+ if (from && typeof from === "object" || typeof from === "function") {
26
+ for (let key of __getOwnPropNames(from))
27
+ if (!__hasOwnProp.call(to, key) && key !== except)
28
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
29
+ }
30
+ return to;
31
+ };
32
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
33
+ var __async = (__this, __arguments, generator) => {
34
+ return new Promise((resolve, reject) => {
35
+ var fulfilled = (value) => {
36
+ try {
37
+ step(generator.next(value));
38
+ } catch (e) {
39
+ reject(e);
40
+ }
41
+ };
42
+ var rejected = (value) => {
43
+ try {
44
+ step(generator.throw(value));
45
+ } catch (e) {
46
+ reject(e);
47
+ }
48
+ };
49
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
50
+ step((generator = generator.apply(__this, __arguments)).next());
51
+ });
52
+ };
53
+
54
+ // src/index.ts
55
+ var index_exports = {};
56
+ __export(index_exports, {
57
+ PersistenceRedis: () => PersistenceRedis
58
+ });
59
+ module.exports = __toCommonJS(index_exports);
60
+
61
+ // src/PersistenceRedis.ts
62
+ var import_io = require("@pluv/io");
63
+
64
+ // src/utils/partitionByLength.ts
65
+ var partitionByLength = (arr, length) => {
66
+ if (!arr.length) return [];
67
+ const head = arr.slice(0, length);
68
+ const tail = arr.slice(length);
69
+ return [head, ...partitionByLength(tail, length)];
70
+ };
71
+
72
+ // src/PersistenceRedis.ts
73
+ var DELIMITER = ":::";
74
+ var HASH_TAG = "{PluvPersistenceRedis}";
75
+ var GET_USERS_CONCURRENCY = 4;
76
+ var PersistenceRedis = class _PersistenceRedis extends import_io.AbstractPersistence {
77
+ constructor(options) {
78
+ super();
79
+ this._initialized = null;
80
+ const { client } = options;
81
+ this._client = client;
82
+ this._initialized = options._initialized;
83
+ }
84
+ addUser(room, connectionId, user) {
85
+ return __async(this, null, function* () {
86
+ if (!this._initialized) return;
87
+ yield this._initialized;
88
+ yield this._client.multi().sadd(this._getRoomUsersKey(room), connectionId).set(this._getRoomUsersUserKey(room, connectionId), JSON.stringify(user)).exec();
89
+ });
90
+ }
91
+ deleteStorageState(room) {
92
+ return __async(this, null, function* () {
93
+ if (!this._initialized) return;
94
+ yield this._initialized;
95
+ yield this._client.del(this._getRoomStorageKey(room));
96
+ });
97
+ }
98
+ deleteUser(room, connectionId) {
99
+ return __async(this, null, function* () {
100
+ if (!this._initialized) return;
101
+ yield this._initialized;
102
+ const size = yield this.getUsersSize(room);
103
+ let multi = this._client.multi().srem(this._getRoomUsersKey(room), connectionId).del(this._getRoomUsersUserKey(room, connectionId));
104
+ if (size === 1) {
105
+ multi = multi.del(this._getRoomStorageKey(room)).del(this._getRoomUsersKey(room));
106
+ }
107
+ yield multi.exec();
108
+ });
109
+ }
110
+ deleteUsers(room) {
111
+ return __async(this, null, function* () {
112
+ if (!this._initialized) return;
113
+ yield this._initialized;
114
+ const members = yield this._client.smembers(this._getRoomUsersKey(room));
115
+ yield members.reduce(
116
+ (commands, connectionId) => {
117
+ return commands.del(this._getRoomUsersUserKey(room, connectionId));
118
+ },
119
+ this._client.multi().del(this._getRoomUsersKey(room))
120
+ ).exec();
121
+ });
122
+ }
123
+ getStorageState(room) {
124
+ return __async(this, null, function* () {
125
+ if (!this._initialized) return null;
126
+ yield this._initialized;
127
+ return yield this._client.get(this._getRoomStorageKey(room));
128
+ });
129
+ }
130
+ setStorageState(room, state) {
131
+ return __async(this, null, function* () {
132
+ if (!this._initialized) return;
133
+ yield this._initialized;
134
+ yield this._client.set(this._getRoomStorageKey(room), state);
135
+ });
136
+ }
137
+ getUser(room, connectionId) {
138
+ return __async(this, null, function* () {
139
+ if (!this._initialized) return null;
140
+ yield this._initialized;
141
+ const data = yield this._client.get(this._getRoomUsersUserKey(room, connectionId));
142
+ return !data ? null : JSON.parse(data);
143
+ });
144
+ }
145
+ getUsers(room) {
146
+ return __async(this, null, function* () {
147
+ if (!this._initialized) return /* @__PURE__ */ new Map();
148
+ yield this._initialized;
149
+ const members = yield this._client.smembers(this._getRoomUsersKey(room));
150
+ const partitions = partitionByLength(members, GET_USERS_CONCURRENCY);
151
+ return yield partitions.reduce((promise, partition) => __async(this, null, function* () {
152
+ const map = yield promise;
153
+ const promises = partition.map((connectionId) => __async(this, null, function* () {
154
+ map.set(connectionId, yield this.getUser(room, connectionId));
155
+ }));
156
+ yield Promise.all(promises);
157
+ return map;
158
+ }), Promise.resolve(/* @__PURE__ */ new Map()));
159
+ });
160
+ }
161
+ getUsersSize(room) {
162
+ return __async(this, null, function* () {
163
+ if (!this._initialized) return 0;
164
+ yield this._initialized;
165
+ return yield this._client.scard(this._getRoomUsersKey(room));
166
+ });
167
+ }
168
+ initialize(roomContext) {
169
+ return new _PersistenceRedis(__spreadValues({
170
+ client: this._client
171
+ }, { _initialized: Promise.resolve(true) }));
172
+ }
173
+ _getClusterKey(key) {
174
+ return `${HASH_TAG}${key}`;
175
+ }
176
+ _getRoomStorageKey(room) {
177
+ return this._getClusterKey(`room_storage${DELIMITER}${room}`);
178
+ }
179
+ _getRoomUsersKey(room) {
180
+ return this._getClusterKey(`room_users${DELIMITER}${room}`);
181
+ }
182
+ _getRoomUsersUserKey(room, connectionId) {
183
+ return this._getClusterKey(`${this._getRoomUsersKey(room)}${DELIMITER}${connectionId}`);
184
+ }
185
+ };
186
+ // Annotate the CommonJS export names for ESM import in node:
187
+ 0 && (module.exports = {
188
+ PersistenceRedis
189
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,165 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
4
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __spreadValues = (a, b) => {
7
+ for (var prop in b || (b = {}))
8
+ if (__hasOwnProp.call(b, prop))
9
+ __defNormalProp(a, prop, b[prop]);
10
+ if (__getOwnPropSymbols)
11
+ for (var prop of __getOwnPropSymbols(b)) {
12
+ if (__propIsEnum.call(b, prop))
13
+ __defNormalProp(a, prop, b[prop]);
14
+ }
15
+ return a;
16
+ };
17
+ var __async = (__this, __arguments, generator) => {
18
+ return new Promise((resolve, reject) => {
19
+ var fulfilled = (value) => {
20
+ try {
21
+ step(generator.next(value));
22
+ } catch (e) {
23
+ reject(e);
24
+ }
25
+ };
26
+ var rejected = (value) => {
27
+ try {
28
+ step(generator.throw(value));
29
+ } catch (e) {
30
+ reject(e);
31
+ }
32
+ };
33
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
34
+ step((generator = generator.apply(__this, __arguments)).next());
35
+ });
36
+ };
37
+
38
+ // src/PersistenceRedis.ts
39
+ import { AbstractPersistence } from "@pluv/io";
40
+
41
+ // src/utils/partitionByLength.ts
42
+ var partitionByLength = (arr, length) => {
43
+ if (!arr.length) return [];
44
+ const head = arr.slice(0, length);
45
+ const tail = arr.slice(length);
46
+ return [head, ...partitionByLength(tail, length)];
47
+ };
48
+
49
+ // src/PersistenceRedis.ts
50
+ var DELIMITER = ":::";
51
+ var HASH_TAG = "{PluvPersistenceRedis}";
52
+ var GET_USERS_CONCURRENCY = 4;
53
+ var PersistenceRedis = class _PersistenceRedis extends AbstractPersistence {
54
+ constructor(options) {
55
+ super();
56
+ this._initialized = null;
57
+ const { client } = options;
58
+ this._client = client;
59
+ this._initialized = options._initialized;
60
+ }
61
+ addUser(room, connectionId, user) {
62
+ return __async(this, null, function* () {
63
+ if (!this._initialized) return;
64
+ yield this._initialized;
65
+ yield this._client.multi().sadd(this._getRoomUsersKey(room), connectionId).set(this._getRoomUsersUserKey(room, connectionId), JSON.stringify(user)).exec();
66
+ });
67
+ }
68
+ deleteStorageState(room) {
69
+ return __async(this, null, function* () {
70
+ if (!this._initialized) return;
71
+ yield this._initialized;
72
+ yield this._client.del(this._getRoomStorageKey(room));
73
+ });
74
+ }
75
+ deleteUser(room, connectionId) {
76
+ return __async(this, null, function* () {
77
+ if (!this._initialized) return;
78
+ yield this._initialized;
79
+ const size = yield this.getUsersSize(room);
80
+ let multi = this._client.multi().srem(this._getRoomUsersKey(room), connectionId).del(this._getRoomUsersUserKey(room, connectionId));
81
+ if (size === 1) {
82
+ multi = multi.del(this._getRoomStorageKey(room)).del(this._getRoomUsersKey(room));
83
+ }
84
+ yield multi.exec();
85
+ });
86
+ }
87
+ deleteUsers(room) {
88
+ return __async(this, null, function* () {
89
+ if (!this._initialized) return;
90
+ yield this._initialized;
91
+ const members = yield this._client.smembers(this._getRoomUsersKey(room));
92
+ yield members.reduce(
93
+ (commands, connectionId) => {
94
+ return commands.del(this._getRoomUsersUserKey(room, connectionId));
95
+ },
96
+ this._client.multi().del(this._getRoomUsersKey(room))
97
+ ).exec();
98
+ });
99
+ }
100
+ getStorageState(room) {
101
+ return __async(this, null, function* () {
102
+ if (!this._initialized) return null;
103
+ yield this._initialized;
104
+ return yield this._client.get(this._getRoomStorageKey(room));
105
+ });
106
+ }
107
+ setStorageState(room, state) {
108
+ return __async(this, null, function* () {
109
+ if (!this._initialized) return;
110
+ yield this._initialized;
111
+ yield this._client.set(this._getRoomStorageKey(room), state);
112
+ });
113
+ }
114
+ getUser(room, connectionId) {
115
+ return __async(this, null, function* () {
116
+ if (!this._initialized) return null;
117
+ yield this._initialized;
118
+ const data = yield this._client.get(this._getRoomUsersUserKey(room, connectionId));
119
+ return !data ? null : JSON.parse(data);
120
+ });
121
+ }
122
+ getUsers(room) {
123
+ return __async(this, null, function* () {
124
+ if (!this._initialized) return /* @__PURE__ */ new Map();
125
+ yield this._initialized;
126
+ const members = yield this._client.smembers(this._getRoomUsersKey(room));
127
+ const partitions = partitionByLength(members, GET_USERS_CONCURRENCY);
128
+ return yield partitions.reduce((promise, partition) => __async(this, null, function* () {
129
+ const map = yield promise;
130
+ const promises = partition.map((connectionId) => __async(this, null, function* () {
131
+ map.set(connectionId, yield this.getUser(room, connectionId));
132
+ }));
133
+ yield Promise.all(promises);
134
+ return map;
135
+ }), Promise.resolve(/* @__PURE__ */ new Map()));
136
+ });
137
+ }
138
+ getUsersSize(room) {
139
+ return __async(this, null, function* () {
140
+ if (!this._initialized) return 0;
141
+ yield this._initialized;
142
+ return yield this._client.scard(this._getRoomUsersKey(room));
143
+ });
144
+ }
145
+ initialize(roomContext) {
146
+ return new _PersistenceRedis(__spreadValues({
147
+ client: this._client
148
+ }, { _initialized: Promise.resolve(true) }));
149
+ }
150
+ _getClusterKey(key) {
151
+ return `${HASH_TAG}${key}`;
152
+ }
153
+ _getRoomStorageKey(room) {
154
+ return this._getClusterKey(`room_storage${DELIMITER}${room}`);
155
+ }
156
+ _getRoomUsersKey(room) {
157
+ return this._getClusterKey(`room_users${DELIMITER}${room}`);
158
+ }
159
+ _getRoomUsersUserKey(room, connectionId) {
160
+ return this._getClusterKey(`${this._getRoomUsersKey(room)}${DELIMITER}${connectionId}`);
161
+ }
162
+ };
163
+ export {
164
+ PersistenceRedis
165
+ };
@@ -0,0 +1,4 @@
1
+ import { config } from "eslint-config-pluv/base";
2
+
3
+ /** @type {import("eslint").Linter.Config} */
4
+ export default config;
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@pluv/persistence-redis",
3
+ "version": "0.0.0-experimental-20250527040415",
4
+ "description": "@pluv/io crdt storage persistence for node.js",
5
+ "author": "leedavidcs",
6
+ "license": "MIT",
7
+ "homepage": "https://github.com/pluv-io/pluv",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/pluv-io/pluv.git",
11
+ "directory": "packages/persistence-redis"
12
+ },
13
+ "main": "./dist/index.js",
14
+ "module": "./dist/index.mjs",
15
+ "types": "./dist/index.d.ts",
16
+ "publishConfig": {
17
+ "access": "public"
18
+ },
19
+ "dependencies": {
20
+ "@types/node": "^22.15.21",
21
+ "@pluv/io": "^0.0.0-experimental-20250527040415",
22
+ "@pluv/types": "^0.0.0-experimental-20250527040415"
23
+ },
24
+ "peerDependencies": {
25
+ "ioredis": "^5.0.0"
26
+ },
27
+ "devDependencies": {
28
+ "eslint": "^9.27.0",
29
+ "ioredis": "^5.6.1",
30
+ "tsup": "^8.5.0",
31
+ "typescript": "^5.8.3",
32
+ "eslint-config-pluv": "^0.0.0-experimental-20250527040415",
33
+ "@pluv/tsconfig": "^0.0.0-experimental-20250527040415"
34
+ },
35
+ "scripts": {
36
+ "build": "tsup src/index.ts --format esm,cjs --dts",
37
+ "dev": "tsup src/index.ts --format esm,cjs --watch --dts",
38
+ "lint": "eslint \"src/**/*.ts*\" --fix --max-warnings 0",
39
+ "clean": "rm -rf .turbo && rm -rf node_modules && rm -rf dist"
40
+ }
41
+ }
@@ -0,0 +1,169 @@
1
+ import { AbstractPersistence } from "@pluv/io";
2
+ import type { JsonObject } from "@pluv/types";
3
+ import type { Cluster, Redis } from "ioredis";
4
+ import { partitionByLength } from "./utils";
5
+
6
+ const DELIMITER = ":::";
7
+ const HASH_TAG = "{PluvPersistenceRedis}";
8
+
9
+ const GET_USERS_CONCURRENCY = 4;
10
+
11
+ export type RedisClient = Cluster | Redis;
12
+
13
+ export interface PersistenceRedisOptions {
14
+ client: RedisClient;
15
+ }
16
+
17
+ export class PersistenceRedis extends AbstractPersistence {
18
+ private _client: RedisClient;
19
+ private _initialized: Promise<true> | null = null;
20
+
21
+ constructor(options: PersistenceRedisOptions) {
22
+ super();
23
+
24
+ const { client } = options;
25
+
26
+ this._client = client;
27
+ this._initialized = (options as any)._initialized;
28
+ }
29
+
30
+ public async addUser(
31
+ room: string,
32
+ connectionId: string,
33
+ user: JsonObject | null,
34
+ ): Promise<void> {
35
+ if (!this._initialized) return;
36
+
37
+ await this._initialized;
38
+
39
+ await this._client
40
+ .multi()
41
+ .sadd(this._getRoomUsersKey(room), connectionId)
42
+ .set(this._getRoomUsersUserKey(room, connectionId), JSON.stringify(user))
43
+ .exec();
44
+ }
45
+
46
+ public async deleteStorageState(room: string): Promise<void> {
47
+ if (!this._initialized) return;
48
+
49
+ await this._initialized;
50
+
51
+ await this._client.del(this._getRoomStorageKey(room));
52
+ }
53
+
54
+ public async deleteUser(room: string, connectionId: string): Promise<void> {
55
+ if (!this._initialized) return;
56
+
57
+ await this._initialized;
58
+
59
+ const size = await this.getUsersSize(room);
60
+
61
+ let multi = this._client
62
+ .multi()
63
+ .srem(this._getRoomUsersKey(room), connectionId)
64
+ .del(this._getRoomUsersUserKey(room, connectionId));
65
+
66
+ if (size === 1) {
67
+ multi = multi.del(this._getRoomStorageKey(room)).del(this._getRoomUsersKey(room));
68
+ }
69
+
70
+ await multi.exec();
71
+ }
72
+
73
+ public async deleteUsers(room: string): Promise<void> {
74
+ if (!this._initialized) return;
75
+
76
+ await this._initialized;
77
+
78
+ const members = await this._client.smembers(this._getRoomUsersKey(room));
79
+
80
+ await members
81
+ .reduce(
82
+ (commands, connectionId) => {
83
+ return commands.del(this._getRoomUsersUserKey(room, connectionId));
84
+ },
85
+ this._client.multi().del(this._getRoomUsersKey(room)),
86
+ )
87
+ .exec();
88
+ }
89
+
90
+ public async getStorageState(room: string): Promise<string | null> {
91
+ if (!this._initialized) return null;
92
+
93
+ await this._initialized;
94
+
95
+ return await this._client.get(this._getRoomStorageKey(room));
96
+ }
97
+
98
+ public async setStorageState(room: string, state: string): Promise<void> {
99
+ if (!this._initialized) return;
100
+
101
+ await this._initialized;
102
+
103
+ await this._client.set(this._getRoomStorageKey(room), state);
104
+ }
105
+
106
+ public async getUser(room: string, connectionId: string): Promise<JsonObject | null> {
107
+ if (!this._initialized) return null;
108
+
109
+ await this._initialized;
110
+
111
+ const data = await this._client.get(this._getRoomUsersUserKey(room, connectionId));
112
+
113
+ return !data ? null : JSON.parse(data);
114
+ }
115
+
116
+ public async getUsers(
117
+ room: string,
118
+ ): Promise<Map<[connectionId: string][0], JsonObject | null>> {
119
+ if (!this._initialized) return new Map();
120
+
121
+ await this._initialized;
122
+
123
+ const members = await this._client.smembers(this._getRoomUsersKey(room));
124
+ const partitions = partitionByLength(members, GET_USERS_CONCURRENCY);
125
+
126
+ return await partitions.reduce(async (promise, partition) => {
127
+ const map = await promise;
128
+
129
+ const promises = partition.map(async (connectionId) => {
130
+ map.set(connectionId, await this.getUser(room, connectionId));
131
+ });
132
+
133
+ await Promise.all(promises);
134
+
135
+ return map;
136
+ }, Promise.resolve(new Map<string, JsonObject | null>()));
137
+ }
138
+
139
+ public async getUsersSize(room: string): Promise<number> {
140
+ if (!this._initialized) return 0;
141
+
142
+ await this._initialized;
143
+
144
+ return await this._client.scard(this._getRoomUsersKey(room));
145
+ }
146
+
147
+ public initialize(roomContext: {}): typeof this {
148
+ return new PersistenceRedis({
149
+ client: this._client,
150
+ ...{ _initialized: Promise.resolve(true as const) },
151
+ }) as typeof this;
152
+ }
153
+
154
+ private _getClusterKey(key: string): string {
155
+ return `${HASH_TAG}${key}`;
156
+ }
157
+
158
+ private _getRoomStorageKey(room: string): string {
159
+ return this._getClusterKey(`room_storage${DELIMITER}${room}`);
160
+ }
161
+
162
+ private _getRoomUsersKey(room: string): string {
163
+ return this._getClusterKey(`room_users${DELIMITER}${room}`);
164
+ }
165
+
166
+ private _getRoomUsersUserKey(room: string, connectionId: string): string {
167
+ return this._getClusterKey(`${this._getRoomUsersKey(room)}${DELIMITER}${connectionId}`);
168
+ }
169
+ }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export type { RedisClient } from "./PersistenceRedis";
2
+ export { PersistenceRedis } from "./PersistenceRedis";
@@ -0,0 +1 @@
1
+ export { partitionByLength } from "./partitionByLength";
@@ -0,0 +1,11 @@
1
+ export const partitionByLength = <T>(
2
+ arr: readonly T[] | T[],
3
+ length: number,
4
+ ): readonly (readonly T[])[] => {
5
+ if (!arr.length) return [];
6
+
7
+ const head = arr.slice(0, length);
8
+ const tail = arr.slice(length);
9
+
10
+ return [head, ...partitionByLength(tail, length)];
11
+ };