@colyseus/core 0.18.16 → 0.18.18
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/build/MatchMaker.cjs +93 -10
- package/build/MatchMaker.cjs.map +3 -3
- package/build/MatchMaker.d.ts +20 -1
- package/build/MatchMaker.mjs +93 -11
- package/build/MatchMaker.mjs.map +3 -3
- package/build/Room.cjs +69 -68
- package/build/Room.cjs.map +2 -2
- package/build/Room.mjs +69 -68
- package/build/Room.mjs.map +2 -2
- package/build/matchmaker/LocalDriver/LocalDriver.cjs +14 -1
- package/build/matchmaker/LocalDriver/LocalDriver.cjs.map +2 -2
- package/build/matchmaker/LocalDriver/LocalDriver.d.ts +2 -0
- package/build/matchmaker/LocalDriver/LocalDriver.mjs +14 -1
- package/build/matchmaker/LocalDriver/LocalDriver.mjs.map +2 -2
- package/build/matchmaker/driver.cjs.map +1 -1
- package/build/matchmaker/driver.d.ts +11 -0
- package/build/matchmaker/driver.mjs.map +1 -1
- package/build/presence/LocalPresence.cjs +2 -0
- package/build/presence/LocalPresence.cjs.map +2 -2
- package/build/presence/LocalPresence.mjs +2 -0
- package/build/presence/LocalPresence.mjs.map +2 -2
- package/build/utils/DevMode.cjs +3 -0
- package/build/utils/DevMode.cjs.map +2 -2
- package/build/utils/DevMode.mjs +4 -1
- package/build/utils/DevMode.mjs.map +2 -2
- package/build/utils/Utils.cjs +6 -0
- package/build/utils/Utils.cjs.map +2 -2
- package/build/utils/Utils.d.ts +2 -0
- package/build/utils/Utils.mjs +4 -0
- package/build/utils/Utils.mjs.map +2 -2
- package/package.json +3 -3
- package/src/MatchMaker.ts +174 -16
- package/src/Room.ts +72 -30
- package/src/matchmaker/LocalDriver/LocalDriver.ts +15 -7
- package/src/matchmaker/driver.ts +12 -0
- package/src/presence/LocalPresence.ts +2 -0
- package/src/utils/DevMode.ts +4 -1
- package/src/utils/Utils.ts +6 -0
|
@@ -29,9 +29,11 @@ var import_Query = require("./Query.cjs");
|
|
|
29
29
|
var LocalDriver = class {
|
|
30
30
|
constructor() {
|
|
31
31
|
this.rooms = [];
|
|
32
|
+
// the roomIds in `rooms`: keeps has() and insert() O(1) however many rooms there are
|
|
33
|
+
this.roomIds = /* @__PURE__ */ new Set();
|
|
32
34
|
}
|
|
33
35
|
has(roomId) {
|
|
34
|
-
return this.
|
|
36
|
+
return this.roomIds.has(roomId);
|
|
35
37
|
}
|
|
36
38
|
query(conditions, sortOptions) {
|
|
37
39
|
const query = new import_Query.Query(this.rooms, conditions);
|
|
@@ -83,10 +85,19 @@ var LocalDriver = class {
|
|
|
83
85
|
}
|
|
84
86
|
return true;
|
|
85
87
|
}
|
|
88
|
+
async insert(room) {
|
|
89
|
+
if (this.has(room.roomId)) {
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
this.roomIds.add(room.roomId);
|
|
93
|
+
this.rooms.push(room);
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
86
96
|
persist(room, create = false) {
|
|
87
97
|
if (!create) {
|
|
88
98
|
return false;
|
|
89
99
|
}
|
|
100
|
+
this.roomIds.add(room.roomId);
|
|
90
101
|
this.rooms.push(room);
|
|
91
102
|
return true;
|
|
92
103
|
}
|
|
@@ -94,12 +105,14 @@ var LocalDriver = class {
|
|
|
94
105
|
const roomIndex = this.rooms.findIndex((room) => room.roomId === roomId);
|
|
95
106
|
if (roomIndex !== -1) {
|
|
96
107
|
this.rooms.splice(roomIndex, 1);
|
|
108
|
+
this.roomIds.delete(roomId);
|
|
97
109
|
return true;
|
|
98
110
|
}
|
|
99
111
|
return false;
|
|
100
112
|
}
|
|
101
113
|
clear() {
|
|
102
114
|
this.rooms = [];
|
|
115
|
+
this.roomIds.clear();
|
|
103
116
|
}
|
|
104
117
|
shutdown() {
|
|
105
118
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/matchmaker/LocalDriver/LocalDriver.ts"],
|
|
4
|
-
"sourcesContent": ["import { debugMatchMaking } from '../../Debug.ts';\nimport type { IRoomCache, SortOptions, MatchMakerDriver } from '../driver.ts';\nimport { Query } from './Query.ts';\n\n// re-export\nexport type { IRoomCache, SortOptions, MatchMakerDriver };\n\nexport class LocalDriver implements MatchMakerDriver {\n public rooms: IRoomCache[] = [];\n\n public has(roomId: string) {\n return this.
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAiC;AAEjC,mBAAsB;AAKf,IAAM,cAAN,MAA8C;AAAA,EAA9C;AACL,SAAO,QAAsB,CAAC;AAAA;AAAA,
|
|
4
|
+
"sourcesContent": ["import { debugMatchMaking } from '../../Debug.ts';\nimport type { IRoomCache, SortOptions, MatchMakerDriver } from '../driver.ts';\nimport { Query } from './Query.ts';\n\n// re-export\nexport type { IRoomCache, SortOptions, MatchMakerDriver };\n\nexport class LocalDriver implements MatchMakerDriver {\n public rooms: IRoomCache[] = [];\n\n // the roomIds in `rooms`: keeps has() and insert() O(1) however many rooms there are\n private roomIds = new Set<string>();\n\n public has(roomId: string) {\n return this.roomIds.has(roomId);\n }\n\n public query(conditions: Partial<IRoomCache>, sortOptions?: SortOptions) {\n const query = new Query<IRoomCache>(this.rooms, conditions);\n\n if (sortOptions) {\n query.sort(sortOptions);\n }\n\n return query.filter(conditions);\n }\n\n public cleanup(processId: string) {\n const cachedRooms = this.query({ processId });\n debugMatchMaking(\"removing stale rooms by processId %s (%s rooms found)\", processId, cachedRooms.length);\n\n cachedRooms.forEach((room) => this.remove(room.roomId));\n return Promise.resolve();\n }\n\n public findOne(conditions: Partial<IRoomCache>, sortOptions?: SortOptions) {\n const query = new Query<IRoomCache>(this.rooms, conditions);\n\n if (sortOptions) {\n query.sort(sortOptions);\n }\n\n return query as unknown as Promise<IRoomCache>;\n }\n\n public async findByIds(roomIds: string[]): Promise<Map<string, IRoomCache>> {\n const result = new Map<string, IRoomCache>();\n if (roomIds.length === 0) { return result; }\n const wanted = new Set(roomIds);\n for (const room of this.rooms) {\n if (wanted.has(room.roomId)) { result.set(room.roomId, room); }\n }\n return result;\n }\n\n public update(room: IRoomCache, operations: Partial<{ $set: Partial<IRoomCache>, $inc: Partial<IRoomCache> }>) {\n if (operations.$set) {\n for (const field in operations.$set) {\n if (operations.$set.hasOwnProperty(field)) {\n room[field] = operations.$set[field];\n }\n }\n }\n\n if (operations.$inc) {\n for (const field in operations.$inc) {\n if (operations.$inc.hasOwnProperty(field)) {\n room[field] += operations.$inc[field];\n }\n }\n }\n\n return true;\n }\n\n public async insert(room: IRoomCache) {\n if (this.has(room.roomId)) { return false; }\n\n this.roomIds.add(room.roomId);\n this.rooms.push(room);\n return true;\n }\n\n public persist(room: IRoomCache, create: boolean = false) {\n if (!create) { return false; }\n\n this.roomIds.add(room.roomId);\n this.rooms.push(room);\n\n return true;\n }\n\n public remove(roomId: string) {\n const roomIndex = this.rooms.findIndex((room) => room.roomId === roomId);\n if (roomIndex !== -1) {\n this.rooms.splice(roomIndex, 1);\n this.roomIds.delete(roomId);\n return true;\n }\n return false;\n }\n\n public clear() {\n this.rooms = [];\n this.roomIds.clear();\n }\n\n public shutdown() {\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAiC;AAEjC,mBAAsB;AAKf,IAAM,cAAN,MAA8C;AAAA,EAA9C;AACL,SAAO,QAAsB,CAAC;AAG9B;AAAA,SAAQ,UAAU,oBAAI,IAAY;AAAA;AAAA,EAE3B,IAAI,QAAgB;AACzB,WAAO,KAAK,QAAQ,IAAI,MAAM;AAAA,EAChC;AAAA,EAEO,MAAM,YAAiC,aAA2B;AACvE,UAAM,QAAQ,IAAI,mBAAkB,KAAK,OAAO,UAAU;AAE1D,QAAI,aAAa;AACf,YAAM,KAAK,WAAW;AAAA,IACxB;AAEA,WAAO,MAAM,OAAO,UAAU;AAAA,EAChC;AA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AAM;AAC5B,SAAK,MAAM,KAAK,IAAI;AACpB,WAAO;AAAA,EACT;AAAA,EAEO,QAAQ,MAAkB,SAAkB,OAAO;AACxD,QAAI,CAAC,QAAQ;AAAE,aAAO;AAAA,IAAO;AAE7B,SAAK,QAAQ,IAAI,KAAK,MAAM;AAC5B,SAAK,MAAM,KAAK,IAAI;AAEpB,WAAO;AAAA,EACT;AAAA,EAEO,OAAO,QAAgB;AAC5B,UAAM,YAAY,KAAK,MAAM,UAAU,CAAC,SAAS,KAAK,WAAW,MAAM;AACvE,QAAI,cAAc,IAAI;AACpB,WAAK,MAAM,OAAO,WAAW,CAAC;AAC9B,WAAK,QAAQ,OAAO,MAAM;AAC1B,aAAO;AAAA,IACT;AACA,WAAO;AAAA,EACT;AAAA,EAEO,QAAQ;AACb,SAAK,QAAQ,CAAC;AACd,SAAK,QAAQ,MAAM;AAAA,EACrB;AAAA,EAEO,WAAW;AAAA,EAClB;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -2,6 +2,7 @@ import type { IRoomCache, SortOptions, MatchMakerDriver } from '../driver.ts';
|
|
|
2
2
|
export type { IRoomCache, SortOptions, MatchMakerDriver };
|
|
3
3
|
export declare class LocalDriver implements MatchMakerDriver {
|
|
4
4
|
rooms: IRoomCache[];
|
|
5
|
+
private roomIds;
|
|
5
6
|
has(roomId: string): boolean;
|
|
6
7
|
query(conditions: Partial<IRoomCache>, sortOptions?: SortOptions): IRoomCache<any>[];
|
|
7
8
|
cleanup(processId: string): Promise<void>;
|
|
@@ -11,6 +12,7 @@ export declare class LocalDriver implements MatchMakerDriver {
|
|
|
11
12
|
$set: Partial<IRoomCache>;
|
|
12
13
|
$inc: Partial<IRoomCache>;
|
|
13
14
|
}>): boolean;
|
|
15
|
+
insert(room: IRoomCache): Promise<boolean>;
|
|
14
16
|
persist(room: IRoomCache, create?: boolean): boolean;
|
|
15
17
|
remove(roomId: string): boolean;
|
|
16
18
|
clear(): void;
|
|
@@ -4,9 +4,11 @@ import { Query } from "./Query.mjs";
|
|
|
4
4
|
var LocalDriver = class {
|
|
5
5
|
constructor() {
|
|
6
6
|
this.rooms = [];
|
|
7
|
+
// the roomIds in `rooms`: keeps has() and insert() O(1) however many rooms there are
|
|
8
|
+
this.roomIds = /* @__PURE__ */ new Set();
|
|
7
9
|
}
|
|
8
10
|
has(roomId) {
|
|
9
|
-
return this.
|
|
11
|
+
return this.roomIds.has(roomId);
|
|
10
12
|
}
|
|
11
13
|
query(conditions, sortOptions) {
|
|
12
14
|
const query = new Query(this.rooms, conditions);
|
|
@@ -58,10 +60,19 @@ var LocalDriver = class {
|
|
|
58
60
|
}
|
|
59
61
|
return true;
|
|
60
62
|
}
|
|
63
|
+
async insert(room) {
|
|
64
|
+
if (this.has(room.roomId)) {
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
this.roomIds.add(room.roomId);
|
|
68
|
+
this.rooms.push(room);
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
61
71
|
persist(room, create = false) {
|
|
62
72
|
if (!create) {
|
|
63
73
|
return false;
|
|
64
74
|
}
|
|
75
|
+
this.roomIds.add(room.roomId);
|
|
65
76
|
this.rooms.push(room);
|
|
66
77
|
return true;
|
|
67
78
|
}
|
|
@@ -69,12 +80,14 @@ var LocalDriver = class {
|
|
|
69
80
|
const roomIndex = this.rooms.findIndex((room) => room.roomId === roomId);
|
|
70
81
|
if (roomIndex !== -1) {
|
|
71
82
|
this.rooms.splice(roomIndex, 1);
|
|
83
|
+
this.roomIds.delete(roomId);
|
|
72
84
|
return true;
|
|
73
85
|
}
|
|
74
86
|
return false;
|
|
75
87
|
}
|
|
76
88
|
clear() {
|
|
77
89
|
this.rooms = [];
|
|
90
|
+
this.roomIds.clear();
|
|
78
91
|
}
|
|
79
92
|
shutdown() {
|
|
80
93
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/matchmaker/LocalDriver/LocalDriver.ts"],
|
|
4
|
-
"sourcesContent": ["import { debugMatchMaking } from '../../Debug.ts';\nimport type { IRoomCache, SortOptions, MatchMakerDriver } from '../driver.ts';\nimport { Query } from './Query.ts';\n\n// re-export\nexport type { IRoomCache, SortOptions, MatchMakerDriver };\n\nexport class LocalDriver implements MatchMakerDriver {\n public rooms: IRoomCache[] = [];\n\n public has(roomId: string) {\n return this.
|
|
5
|
-
"mappings": ";AAAA,SAAS,wBAAwB;AAEjC,SAAS,aAAa;AAKf,IAAM,cAAN,MAA8C;AAAA,EAA9C;AACL,SAAO,QAAsB,CAAC;AAAA;AAAA,
|
|
4
|
+
"sourcesContent": ["import { debugMatchMaking } from '../../Debug.ts';\nimport type { IRoomCache, SortOptions, MatchMakerDriver } from '../driver.ts';\nimport { Query } from './Query.ts';\n\n// re-export\nexport type { IRoomCache, SortOptions, MatchMakerDriver };\n\nexport class LocalDriver implements MatchMakerDriver {\n public rooms: IRoomCache[] = [];\n\n // the roomIds in `rooms`: keeps has() and insert() O(1) however many rooms there are\n private roomIds = new Set<string>();\n\n public has(roomId: string) {\n return this.roomIds.has(roomId);\n }\n\n public query(conditions: Partial<IRoomCache>, sortOptions?: SortOptions) {\n const query = new Query<IRoomCache>(this.rooms, conditions);\n\n if (sortOptions) {\n query.sort(sortOptions);\n }\n\n return query.filter(conditions);\n }\n\n public cleanup(processId: string) {\n const cachedRooms = this.query({ processId });\n debugMatchMaking(\"removing stale rooms by processId %s (%s rooms found)\", processId, cachedRooms.length);\n\n cachedRooms.forEach((room) => this.remove(room.roomId));\n return Promise.resolve();\n }\n\n public findOne(conditions: Partial<IRoomCache>, sortOptions?: SortOptions) {\n const query = new Query<IRoomCache>(this.rooms, conditions);\n\n if (sortOptions) {\n query.sort(sortOptions);\n }\n\n return query as unknown as Promise<IRoomCache>;\n }\n\n public async findByIds(roomIds: string[]): Promise<Map<string, IRoomCache>> {\n const result = new Map<string, IRoomCache>();\n if (roomIds.length === 0) { return result; }\n const wanted = new Set(roomIds);\n for (const room of this.rooms) {\n if (wanted.has(room.roomId)) { result.set(room.roomId, room); }\n }\n return result;\n }\n\n public update(room: IRoomCache, operations: Partial<{ $set: Partial<IRoomCache>, $inc: Partial<IRoomCache> }>) {\n if (operations.$set) {\n for (const field in operations.$set) {\n if (operations.$set.hasOwnProperty(field)) {\n room[field] = operations.$set[field];\n }\n }\n }\n\n if (operations.$inc) {\n for (const field in operations.$inc) {\n if (operations.$inc.hasOwnProperty(field)) {\n room[field] += operations.$inc[field];\n }\n }\n }\n\n return true;\n }\n\n public async insert(room: IRoomCache) {\n if (this.has(room.roomId)) { return false; }\n\n this.roomIds.add(room.roomId);\n this.rooms.push(room);\n return true;\n }\n\n public persist(room: IRoomCache, create: boolean = false) {\n if (!create) { return false; }\n\n this.roomIds.add(room.roomId);\n this.rooms.push(room);\n\n return true;\n }\n\n public remove(roomId: string) {\n const roomIndex = this.rooms.findIndex((room) => room.roomId === roomId);\n if (roomIndex !== -1) {\n this.rooms.splice(roomIndex, 1);\n this.roomIds.delete(roomId);\n return true;\n }\n return false;\n }\n\n public clear() {\n this.rooms = [];\n this.roomIds.clear();\n }\n\n public shutdown() {\n }\n}\n"],
|
|
5
|
+
"mappings": ";AAAA,SAAS,wBAAwB;AAEjC,SAAS,aAAa;AAKf,IAAM,cAAN,MAA8C;AAAA,EAA9C;AACL,SAAO,QAAsB,CAAC;AAG9B;AAAA,SAAQ,UAAU,oBAAI,IAAY;AAAA;AAAA,EAE3B,IAAI,QAAgB;AACzB,WAAO,KAAK,QAAQ,IAAI,MAAM;AAAA,EAChC;AAAA,EAEO,MAAM,YAAiC,aAA2B;AACvE,UAAM,QAAQ,IAAI,MAAkB,KAAK,OAAO,UAAU;AAE1D,QAAI,aAAa;AACf,YAAM,KAAK,WAAW;AAAA,IACxB;AAEA,WAAO,MAAM,OAAO,UAAU;AAAA,EAChC;AAAA,EAEO,QAAQ,WAAmB;AAChC,UAAM,cAAc,KAAK,MAAM,EAAE,UAAU,CAA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QAAQ,MAAkB,SAAkB,OAAO;AACxD,QAAI,CAAC,QAAQ;AAAE,aAAO;AAAA,IAAO;AAE7B,SAAK,QAAQ,IAAI,KAAK,MAAM;AAC5B,SAAK,MAAM,KAAK,IAAI;AAEpB,WAAO;AAAA,EACT;AAAA,EAEO,OAAO,QAAgB;AAC5B,UAAM,YAAY,KAAK,MAAM,UAAU,CAAC,SAAS,KAAK,WAAW,MAAM;AACvE,QAAI,cAAc,IAAI;AACpB,WAAK,MAAM,OAAO,WAAW,CAAC;AAC9B,WAAK,QAAQ,OAAO,MAAM;AAC1B,aAAO;AAAA,IACT;AACA,WAAO;AAAA,EACT;AAAA,EAEO,QAAQ;AACb,SAAK,QAAQ,CAAC;AACd,SAAK,QAAQ,MAAM;AAAA,EACrB;AAAA,EAEO,WAAW;AAAA,EAClB;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/matchmaker/driver.ts"],
|
|
4
|
-
"sourcesContent": ["import type { Room } from \"@colyseus/core\";\n\n/**\n * Sort options for room queries.\n */\nexport interface SortOptions {\n [fieldName: string]: 1 | -1 | 'asc' | 'desc' | 'ascending' | 'descending';\n}\n\n/**\n * Built-in room cache fields that can be used for sorting.\n */\nexport type IRoomCacheSortByKeys = 'clients' | 'maxClients' | 'createdAt';\n\n/**\n * Built-in room cache fields that can be used for filtering.\n */\nexport type IRoomCacheFilterByKeys = 'clients' | 'maxClients' | 'processId';\n\n/**\n * Extract metadata type from Room type\n */\nexport type ExtractRoomCacheMetadata<RoomType extends Room> = RoomType['~metadata'];\n\n/**\n * Generates a unique lock ID based on filter options.\n */\nexport function getLockId(filterOptions: any) {\n return Object.keys(filterOptions).map((key) => `${key}:${filterOptions[key]}`).join(\"-\");\n}\n\n/**\n * Initialize a room cache which contains CRUD operations for room listings.\n *\n * @internal\n * @param initialValues - Predefined room properties.\n * @returns RoomData - New room cache.\n */\nexport function initializeRoomCache(initialValues: Partial<IRoomCache> = {}): IRoomCache {\n return {\n clients: 0,\n maxClients: Infinity,\n locked: false,\n private: false,\n metadata: undefined,\n createdAt: (initialValues && initialValues.createdAt) ? new Date(initialValues.createdAt) : new Date(),\n unlisted: false,\n ...initialValues,\n } as IRoomCache;\n}\n\nexport interface IRoomCache<Metadata = any> {\n /**\n * Room name.\n */\n name: string;\n\n /**\n * Unique identifier for the room.\n */\n roomId: string;\n\n /**\n * Process id where the room is running.\n */\n processId: string;\n\n /**\n * Number of clients connected to this room.\n */\n clients: number;\n\n /**\n * Maximum number of clients allowed to join the room.\n */\n maxClients: number;\n\n /**\n * Indicates if the room is locked (i.e. join requests are rejected).\n */\n locked?: boolean;\n\n /**\n * Indicates if the room is private\n * Private rooms can't be joined via `join()` or `joinOrCreate()`.\n */\n private?: boolean;\n\n /**\n * Public address of the server.\n */\n publicAddress?: string;\n\n /**\n * Do not show this room in lobby listing.\n */\n unlisted?: boolean;\n\n /**\n * Metadata associated with the room.\n */\n metadata?: Metadata;\n\n /**\n * When the room was created.\n */\n createdAt?: Date;\n}\n\nexport interface MatchMakerDriver {\n /**\n * Check if a room exists in room cache.\n *\n * @param roomId - The room id.\n *\n * @returns Promise<boolean> | boolean - A promise or a boolean value indicating if the room exists.\n */\n has(roomId: string): Promise<boolean> | boolean;\n\n /**\n * Query rooms in room cache for given conditions.\n *\n * @param conditions - Filtering conditions.\n *\n * @returns Promise<IRoomCache[]> | IRoomCache[] - A promise or an object contaning room metadata list.\n */\n query<T extends Room = any>(\n conditions: Partial<IRoomCache & ExtractRoomCacheMetadata<T>>,\n sortOptions?: SortOptions\n ): Promise<Array<IRoomCache<ExtractRoomCacheMetadata<T>>>> | Array<IRoomCache<ExtractRoomCacheMetadata<T>>>;\n\n /**\n * Clean up rooms in room cache by process id.\n * @param processId - The process id.\n */\n cleanup?(processId: string): Promise<void>;\n\n /**\n * Query for a room in room cache for given conditions.\n *\n * @param conditions - Filtering conditions.\n *\n * @returns `IRoomCache` - An object contaning filtered room metadata.\n */\n findOne<T extends Room = any>(\n conditions: Partial<IRoomCache & ExtractRoomCacheMetadata<T>>,\n sortOptions?: SortOptions\n ): Promise<IRoomCache<ExtractRoomCacheMetadata<T>>>;\n\n /**\n * Batch-resolve room caches by roomId in a single backend round\n * trip. Missing roomIds are absent from the returned map. Used by\n * hot paths (per-join uniqueness check, by-user reverse-index\n * lookups) where K serial `findOne` calls would multiply round\n * trips needlessly.\n *\n * @param roomIds - Room ids to look up.\n *\n * @returns Map keyed by roomId of the rooms that were found.\n */\n findByIds(roomIds: string[]): Promise<Map<string, IRoomCache>>;\n\n /**\n * Remove a room from room cache.\n *\n * @param roomId - The room id.\n */\n remove(roomId: string): Promise<boolean> | boolean;\n\n /**\n * Update a room in room cache.\n *\n * @param IRoomCache - The room to update.\n * @param operations - The operations to update the room.\n */\n update(\n room: IRoomCache,\n operations: Partial<{ $set: Partial<IRoomCache>, $inc: Partial<IRoomCache> }>\n ): Promise<boolean> | boolean;\n\n /**\n * Persist a room in room cache.\n *\n * @param room - The room to persist.\n * @param create - If true, create a new record. If false (default), update existing record.\n */\n persist(room: IRoomCache, create?: boolean): Promise<boolean> | boolean;\n\n /**\n * Empty the room cache. Used for testing purposes only.\n * May be asynchronous \u2014 callers must await it.\n * @internal Do not call this method yourself.\n */\n clear(): void | Promise<void>;\n\n /**\n * Boot the room cache medium (if available).\n */\n boot?(): Promise<void>;\n\n /**\n * Dispose the connection of the room cache medium.\n * May be asynchronous \u2014 callers must await it.\n */\n shutdown(): void | Promise<void>;\n}\n"],
|
|
4
|
+
"sourcesContent": ["import type { Room } from \"@colyseus/core\";\n\n/**\n * Sort options for room queries.\n */\nexport interface SortOptions {\n [fieldName: string]: 1 | -1 | 'asc' | 'desc' | 'ascending' | 'descending';\n}\n\n/**\n * Built-in room cache fields that can be used for sorting.\n */\nexport type IRoomCacheSortByKeys = 'clients' | 'maxClients' | 'createdAt';\n\n/**\n * Built-in room cache fields that can be used for filtering.\n */\nexport type IRoomCacheFilterByKeys = 'clients' | 'maxClients' | 'processId';\n\n/**\n * Extract metadata type from Room type\n */\nexport type ExtractRoomCacheMetadata<RoomType extends Room> = RoomType['~metadata'];\n\n/**\n * Generates a unique lock ID based on filter options.\n */\nexport function getLockId(filterOptions: any) {\n return Object.keys(filterOptions).map((key) => `${key}:${filterOptions[key]}`).join(\"-\");\n}\n\n/**\n * Initialize a room cache which contains CRUD operations for room listings.\n *\n * @internal\n * @param initialValues - Predefined room properties.\n * @returns RoomData - New room cache.\n */\nexport function initializeRoomCache(initialValues: Partial<IRoomCache> = {}): IRoomCache {\n return {\n clients: 0,\n maxClients: Infinity,\n locked: false,\n private: false,\n metadata: undefined,\n createdAt: (initialValues && initialValues.createdAt) ? new Date(initialValues.createdAt) : new Date(),\n unlisted: false,\n ...initialValues,\n } as IRoomCache;\n}\n\nexport interface IRoomCache<Metadata = any> {\n /**\n * Room name.\n */\n name: string;\n\n /**\n * Unique identifier for the room.\n */\n roomId: string;\n\n /**\n * Process id where the room is running.\n */\n processId: string;\n\n /**\n * Number of clients connected to this room.\n */\n clients: number;\n\n /**\n * Maximum number of clients allowed to join the room.\n */\n maxClients: number;\n\n /**\n * Indicates if the room is locked (i.e. join requests are rejected).\n */\n locked?: boolean;\n\n /**\n * Indicates if the room is private\n * Private rooms can't be joined via `join()` or `joinOrCreate()`.\n */\n private?: boolean;\n\n /**\n * Public address of the server.\n */\n publicAddress?: string;\n\n /**\n * Do not show this room in lobby listing.\n */\n unlisted?: boolean;\n\n /**\n * Metadata associated with the room.\n */\n metadata?: Metadata;\n\n /**\n * When the room was created.\n */\n createdAt?: Date;\n}\n\nexport interface MatchMakerDriver {\n /**\n * Check if a room exists in room cache.\n *\n * @param roomId - The room id.\n *\n * @returns Promise<boolean> | boolean - A promise or a boolean value indicating if the room exists.\n */\n has(roomId: string): Promise<boolean> | boolean;\n\n /**\n * Query rooms in room cache for given conditions.\n *\n * @param conditions - Filtering conditions.\n *\n * @returns Promise<IRoomCache[]> | IRoomCache[] - A promise or an object contaning room metadata list.\n */\n query<T extends Room = any>(\n conditions: Partial<IRoomCache & ExtractRoomCacheMetadata<T>>,\n sortOptions?: SortOptions\n ): Promise<Array<IRoomCache<ExtractRoomCacheMetadata<T>>>> | Array<IRoomCache<ExtractRoomCacheMetadata<T>>>;\n\n /**\n * Clean up rooms in room cache by process id.\n * @param processId - The process id.\n */\n cleanup?(processId: string): Promise<void>;\n\n /**\n * Query for a room in room cache for given conditions.\n *\n * @param conditions - Filtering conditions.\n *\n * @returns `IRoomCache` - An object contaning filtered room metadata.\n */\n findOne<T extends Room = any>(\n conditions: Partial<IRoomCache & ExtractRoomCacheMetadata<T>>,\n sortOptions?: SortOptions\n ): Promise<IRoomCache<ExtractRoomCacheMetadata<T>>>;\n\n /**\n * Batch-resolve room caches by roomId in a single backend round\n * trip. Missing roomIds are absent from the returned map. Used by\n * hot paths (per-join uniqueness check, by-user reverse-index\n * lookups) where K serial `findOne` calls would multiply round\n * trips needlessly.\n *\n * @param roomIds - Room ids to look up.\n *\n * @returns Map keyed by roomId of the rooms that were found.\n */\n findByIds(roomIds: string[]): Promise<Map<string, IRoomCache>>;\n\n /**\n * Remove a room from room cache.\n *\n * @param roomId - The room id.\n */\n remove(roomId: string): Promise<boolean> | boolean;\n\n /**\n * Update a room in room cache.\n *\n * @param IRoomCache - The room to update.\n * @param operations - The operations to update the room.\n */\n update(\n room: IRoomCache,\n operations: Partial<{ $set: Partial<IRoomCache>, $inc: Partial<IRoomCache> }>\n ): Promise<boolean> | boolean;\n\n /**\n * Persist a room in room cache.\n *\n * @param room - The room to persist.\n * @param create - If true, create a new record. If false (default), update existing record.\n */\n persist(room: IRoomCache, create?: boolean): Promise<boolean> | boolean;\n\n /**\n * Record a room, unless its `roomId` is already recorded. Must be atomic, and\n * must return false rather than throwing when the `roomId` is taken.\n *\n * Matchmaking uses this to settle which process owns a room when one create\n * request is answered twice. Drivers that don't implement it fall back to\n * `persist(room, true)`, where the second write silently wins.\n *\n * TODO: required on 1.0, replacing `persist()`'s `create` flag.\n */\n insert?(room: IRoomCache): Promise<boolean>;\n\n /**\n * Empty the room cache. Used for testing purposes only.\n * May be asynchronous \u2014 callers must await it.\n * @internal Do not call this method yourself.\n */\n clear(): void | Promise<void>;\n\n /**\n * Boot the room cache medium (if available).\n */\n boot?(): Promise<void>;\n\n /**\n * Dispose the connection of the room cache medium.\n * May be asynchronous \u2014 callers must await it.\n */\n shutdown(): void | Promise<void>;\n}\n"],
|
|
5
5
|
"mappings": ";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA2BO,SAAS,UAAU,eAAoB;AAC5C,SAAO,OAAO,KAAK,aAAa,EAAE,IAAI,CAAC,QAAQ,GAAG,GAAG,IAAI,cAAc,GAAG,CAAC,EAAE,EAAE,KAAK,GAAG;AACzF;AASO,SAAS,oBAAoB,gBAAqC,CAAC,GAAe;AACvF,SAAO;AAAA,IACL,SAAS;AAAA,IACT,YAAY;AAAA,IACZ,QAAQ;AAAA,IACR,SAAS;AAAA,IACT,UAAU;AAAA,IACV,WAAY,iBAAiB,cAAc,YAAa,IAAI,KAAK,cAAc,SAAS,IAAI,oBAAI,KAAK;AAAA,IACrG,UAAU;AAAA,IACV,GAAG;AAAA,EACL;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -141,6 +141,17 @@ export interface MatchMakerDriver {
|
|
|
141
141
|
* @param create - If true, create a new record. If false (default), update existing record.
|
|
142
142
|
*/
|
|
143
143
|
persist(room: IRoomCache, create?: boolean): Promise<boolean> | boolean;
|
|
144
|
+
/**
|
|
145
|
+
* Record a room, unless its `roomId` is already recorded. Must be atomic, and
|
|
146
|
+
* must return false rather than throwing when the `roomId` is taken.
|
|
147
|
+
*
|
|
148
|
+
* Matchmaking uses this to settle which process owns a room when one create
|
|
149
|
+
* request is answered twice. Drivers that don't implement it fall back to
|
|
150
|
+
* `persist(room, true)`, where the second write silently wins.
|
|
151
|
+
*
|
|
152
|
+
* TODO: required on 1.0, replacing `persist()`'s `create` flag.
|
|
153
|
+
*/
|
|
154
|
+
insert?(room: IRoomCache): Promise<boolean>;
|
|
144
155
|
/**
|
|
145
156
|
* Empty the room cache. Used for testing purposes only.
|
|
146
157
|
* May be asynchronous — callers must await it.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/matchmaker/driver.ts"],
|
|
4
|
-
"sourcesContent": ["import type { Room } from \"@colyseus/core\";\n\n/**\n * Sort options for room queries.\n */\nexport interface SortOptions {\n [fieldName: string]: 1 | -1 | 'asc' | 'desc' | 'ascending' | 'descending';\n}\n\n/**\n * Built-in room cache fields that can be used for sorting.\n */\nexport type IRoomCacheSortByKeys = 'clients' | 'maxClients' | 'createdAt';\n\n/**\n * Built-in room cache fields that can be used for filtering.\n */\nexport type IRoomCacheFilterByKeys = 'clients' | 'maxClients' | 'processId';\n\n/**\n * Extract metadata type from Room type\n */\nexport type ExtractRoomCacheMetadata<RoomType extends Room> = RoomType['~metadata'];\n\n/**\n * Generates a unique lock ID based on filter options.\n */\nexport function getLockId(filterOptions: any) {\n return Object.keys(filterOptions).map((key) => `${key}:${filterOptions[key]}`).join(\"-\");\n}\n\n/**\n * Initialize a room cache which contains CRUD operations for room listings.\n *\n * @internal\n * @param initialValues - Predefined room properties.\n * @returns RoomData - New room cache.\n */\nexport function initializeRoomCache(initialValues: Partial<IRoomCache> = {}): IRoomCache {\n return {\n clients: 0,\n maxClients: Infinity,\n locked: false,\n private: false,\n metadata: undefined,\n createdAt: (initialValues && initialValues.createdAt) ? new Date(initialValues.createdAt) : new Date(),\n unlisted: false,\n ...initialValues,\n } as IRoomCache;\n}\n\nexport interface IRoomCache<Metadata = any> {\n /**\n * Room name.\n */\n name: string;\n\n /**\n * Unique identifier for the room.\n */\n roomId: string;\n\n /**\n * Process id where the room is running.\n */\n processId: string;\n\n /**\n * Number of clients connected to this room.\n */\n clients: number;\n\n /**\n * Maximum number of clients allowed to join the room.\n */\n maxClients: number;\n\n /**\n * Indicates if the room is locked (i.e. join requests are rejected).\n */\n locked?: boolean;\n\n /**\n * Indicates if the room is private\n * Private rooms can't be joined via `join()` or `joinOrCreate()`.\n */\n private?: boolean;\n\n /**\n * Public address of the server.\n */\n publicAddress?: string;\n\n /**\n * Do not show this room in lobby listing.\n */\n unlisted?: boolean;\n\n /**\n * Metadata associated with the room.\n */\n metadata?: Metadata;\n\n /**\n * When the room was created.\n */\n createdAt?: Date;\n}\n\nexport interface MatchMakerDriver {\n /**\n * Check if a room exists in room cache.\n *\n * @param roomId - The room id.\n *\n * @returns Promise<boolean> | boolean - A promise or a boolean value indicating if the room exists.\n */\n has(roomId: string): Promise<boolean> | boolean;\n\n /**\n * Query rooms in room cache for given conditions.\n *\n * @param conditions - Filtering conditions.\n *\n * @returns Promise<IRoomCache[]> | IRoomCache[] - A promise or an object contaning room metadata list.\n */\n query<T extends Room = any>(\n conditions: Partial<IRoomCache & ExtractRoomCacheMetadata<T>>,\n sortOptions?: SortOptions\n ): Promise<Array<IRoomCache<ExtractRoomCacheMetadata<T>>>> | Array<IRoomCache<ExtractRoomCacheMetadata<T>>>;\n\n /**\n * Clean up rooms in room cache by process id.\n * @param processId - The process id.\n */\n cleanup?(processId: string): Promise<void>;\n\n /**\n * Query for a room in room cache for given conditions.\n *\n * @param conditions - Filtering conditions.\n *\n * @returns `IRoomCache` - An object contaning filtered room metadata.\n */\n findOne<T extends Room = any>(\n conditions: Partial<IRoomCache & ExtractRoomCacheMetadata<T>>,\n sortOptions?: SortOptions\n ): Promise<IRoomCache<ExtractRoomCacheMetadata<T>>>;\n\n /**\n * Batch-resolve room caches by roomId in a single backend round\n * trip. Missing roomIds are absent from the returned map. Used by\n * hot paths (per-join uniqueness check, by-user reverse-index\n * lookups) where K serial `findOne` calls would multiply round\n * trips needlessly.\n *\n * @param roomIds - Room ids to look up.\n *\n * @returns Map keyed by roomId of the rooms that were found.\n */\n findByIds(roomIds: string[]): Promise<Map<string, IRoomCache>>;\n\n /**\n * Remove a room from room cache.\n *\n * @param roomId - The room id.\n */\n remove(roomId: string): Promise<boolean> | boolean;\n\n /**\n * Update a room in room cache.\n *\n * @param IRoomCache - The room to update.\n * @param operations - The operations to update the room.\n */\n update(\n room: IRoomCache,\n operations: Partial<{ $set: Partial<IRoomCache>, $inc: Partial<IRoomCache> }>\n ): Promise<boolean> | boolean;\n\n /**\n * Persist a room in room cache.\n *\n * @param room - The room to persist.\n * @param create - If true, create a new record. If false (default), update existing record.\n */\n persist(room: IRoomCache, create?: boolean): Promise<boolean> | boolean;\n\n /**\n * Empty the room cache. Used for testing purposes only.\n * May be asynchronous \u2014 callers must await it.\n * @internal Do not call this method yourself.\n */\n clear(): void | Promise<void>;\n\n /**\n * Boot the room cache medium (if available).\n */\n boot?(): Promise<void>;\n\n /**\n * Dispose the connection of the room cache medium.\n * May be asynchronous \u2014 callers must await it.\n */\n shutdown(): void | Promise<void>;\n}\n"],
|
|
4
|
+
"sourcesContent": ["import type { Room } from \"@colyseus/core\";\n\n/**\n * Sort options for room queries.\n */\nexport interface SortOptions {\n [fieldName: string]: 1 | -1 | 'asc' | 'desc' | 'ascending' | 'descending';\n}\n\n/**\n * Built-in room cache fields that can be used for sorting.\n */\nexport type IRoomCacheSortByKeys = 'clients' | 'maxClients' | 'createdAt';\n\n/**\n * Built-in room cache fields that can be used for filtering.\n */\nexport type IRoomCacheFilterByKeys = 'clients' | 'maxClients' | 'processId';\n\n/**\n * Extract metadata type from Room type\n */\nexport type ExtractRoomCacheMetadata<RoomType extends Room> = RoomType['~metadata'];\n\n/**\n * Generates a unique lock ID based on filter options.\n */\nexport function getLockId(filterOptions: any) {\n return Object.keys(filterOptions).map((key) => `${key}:${filterOptions[key]}`).join(\"-\");\n}\n\n/**\n * Initialize a room cache which contains CRUD operations for room listings.\n *\n * @internal\n * @param initialValues - Predefined room properties.\n * @returns RoomData - New room cache.\n */\nexport function initializeRoomCache(initialValues: Partial<IRoomCache> = {}): IRoomCache {\n return {\n clients: 0,\n maxClients: Infinity,\n locked: false,\n private: false,\n metadata: undefined,\n createdAt: (initialValues && initialValues.createdAt) ? new Date(initialValues.createdAt) : new Date(),\n unlisted: false,\n ...initialValues,\n } as IRoomCache;\n}\n\nexport interface IRoomCache<Metadata = any> {\n /**\n * Room name.\n */\n name: string;\n\n /**\n * Unique identifier for the room.\n */\n roomId: string;\n\n /**\n * Process id where the room is running.\n */\n processId: string;\n\n /**\n * Number of clients connected to this room.\n */\n clients: number;\n\n /**\n * Maximum number of clients allowed to join the room.\n */\n maxClients: number;\n\n /**\n * Indicates if the room is locked (i.e. join requests are rejected).\n */\n locked?: boolean;\n\n /**\n * Indicates if the room is private\n * Private rooms can't be joined via `join()` or `joinOrCreate()`.\n */\n private?: boolean;\n\n /**\n * Public address of the server.\n */\n publicAddress?: string;\n\n /**\n * Do not show this room in lobby listing.\n */\n unlisted?: boolean;\n\n /**\n * Metadata associated with the room.\n */\n metadata?: Metadata;\n\n /**\n * When the room was created.\n */\n createdAt?: Date;\n}\n\nexport interface MatchMakerDriver {\n /**\n * Check if a room exists in room cache.\n *\n * @param roomId - The room id.\n *\n * @returns Promise<boolean> | boolean - A promise or a boolean value indicating if the room exists.\n */\n has(roomId: string): Promise<boolean> | boolean;\n\n /**\n * Query rooms in room cache for given conditions.\n *\n * @param conditions - Filtering conditions.\n *\n * @returns Promise<IRoomCache[]> | IRoomCache[] - A promise or an object contaning room metadata list.\n */\n query<T extends Room = any>(\n conditions: Partial<IRoomCache & ExtractRoomCacheMetadata<T>>,\n sortOptions?: SortOptions\n ): Promise<Array<IRoomCache<ExtractRoomCacheMetadata<T>>>> | Array<IRoomCache<ExtractRoomCacheMetadata<T>>>;\n\n /**\n * Clean up rooms in room cache by process id.\n * @param processId - The process id.\n */\n cleanup?(processId: string): Promise<void>;\n\n /**\n * Query for a room in room cache for given conditions.\n *\n * @param conditions - Filtering conditions.\n *\n * @returns `IRoomCache` - An object contaning filtered room metadata.\n */\n findOne<T extends Room = any>(\n conditions: Partial<IRoomCache & ExtractRoomCacheMetadata<T>>,\n sortOptions?: SortOptions\n ): Promise<IRoomCache<ExtractRoomCacheMetadata<T>>>;\n\n /**\n * Batch-resolve room caches by roomId in a single backend round\n * trip. Missing roomIds are absent from the returned map. Used by\n * hot paths (per-join uniqueness check, by-user reverse-index\n * lookups) where K serial `findOne` calls would multiply round\n * trips needlessly.\n *\n * @param roomIds - Room ids to look up.\n *\n * @returns Map keyed by roomId of the rooms that were found.\n */\n findByIds(roomIds: string[]): Promise<Map<string, IRoomCache>>;\n\n /**\n * Remove a room from room cache.\n *\n * @param roomId - The room id.\n */\n remove(roomId: string): Promise<boolean> | boolean;\n\n /**\n * Update a room in room cache.\n *\n * @param IRoomCache - The room to update.\n * @param operations - The operations to update the room.\n */\n update(\n room: IRoomCache,\n operations: Partial<{ $set: Partial<IRoomCache>, $inc: Partial<IRoomCache> }>\n ): Promise<boolean> | boolean;\n\n /**\n * Persist a room in room cache.\n *\n * @param room - The room to persist.\n * @param create - If true, create a new record. If false (default), update existing record.\n */\n persist(room: IRoomCache, create?: boolean): Promise<boolean> | boolean;\n\n /**\n * Record a room, unless its `roomId` is already recorded. Must be atomic, and\n * must return false rather than throwing when the `roomId` is taken.\n *\n * Matchmaking uses this to settle which process owns a room when one create\n * request is answered twice. Drivers that don't implement it fall back to\n * `persist(room, true)`, where the second write silently wins.\n *\n * TODO: required on 1.0, replacing `persist()`'s `create` flag.\n */\n insert?(room: IRoomCache): Promise<boolean>;\n\n /**\n * Empty the room cache. Used for testing purposes only.\n * May be asynchronous \u2014 callers must await it.\n * @internal Do not call this method yourself.\n */\n clear(): void | Promise<void>;\n\n /**\n * Boot the room cache medium (if available).\n */\n boot?(): Promise<void>;\n\n /**\n * Dispose the connection of the room cache medium.\n * May be asynchronous \u2014 callers must await it.\n */\n shutdown(): void | Promise<void>;\n}\n"],
|
|
5
5
|
"mappings": ";AA2BO,SAAS,UAAU,eAAoB;AAC5C,SAAO,OAAO,KAAK,aAAa,EAAE,IAAI,CAAC,QAAQ,GAAG,GAAG,IAAI,cAAc,GAAG,CAAC,EAAE,EAAE,KAAK,GAAG;AACzF;AASO,SAAS,oBAAoB,gBAAqC,CAAC,GAAe;AACvF,SAAO;AAAA,IACL,SAAS;AAAA,IACT,YAAY;AAAA,IACZ,QAAQ;AAAA,IACR,SAAS;AAAA,IACT,UAAU;AAAA,IACV,WAAY,iBAAiB,cAAc,YAAa,IAAI,KAAK,cAAc,SAAS,IAAI,oBAAI,KAAK;AAAA,IACrG,UAAU;AAAA,IACV,GAAG;AAAA,EACL;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/presence/LocalPresence.ts"],
|
|
4
|
-
"sourcesContent": ["\nimport { EventEmitter } from 'events';\nimport { spliceOne } from '../utils/Utils.ts';\nimport type { Presence } from './Presence.ts';\n\nimport { hasDevModeCache, isDevMode, getDevModeCache, writeDevModeCache } from '../utils/DevMode.ts';\n\ntype Callback = (...args: any[]) => void;\n\nexport class LocalPresence implements Presence {\n public subscriptions: EventEmitter = new EventEmitter();\n\n // null-proto: keys are caller-controlled, must never resolve through Object.prototype\n public data: {[roomName: string]: string[]} = Object.create(null);\n public hash: {[roomName: string]: {[key: string]: string}} = Object.create(null);\n\n public keys: {[name: string]: string | number} = Object.create(null);\n\n private timeouts: {[name: string]: NodeJS.Timeout} = Object.create(null);\n\n constructor() {\n //\n // reload from local cache on devMode\n //\n if (\n isDevMode &&\n hasDevModeCache()\n ) {\n const cache = getDevModeCache();\n if (cache.data) { this.data = cache.data; }\n if (cache.hash) { this.hash = cache.hash; }\n if (cache.keys) { this.keys = cache.keys; }\n }\n }\n\n public subscribe(topic: string, callback: (...args: any[]) => void) {\n this.subscriptions.on(topic, callback);\n return Promise.resolve(this);\n }\n\n public unsubscribe(topic: string, callback?: Callback) {\n if (callback) {\n this.subscriptions.removeListener(topic, callback);\n\n } else {\n this.subscriptions.removeAllListeners(topic);\n }\n\n return this;\n }\n\n public publish(topic: string, data: any) {\n this.subscriptions.emit(topic, data);\n return this;\n }\n\n public async channels (pattern?: string) {\n let eventNames = this.subscriptions.eventNames() as string[];\n if (pattern) {\n //\n // This is a limited glob pattern to regexp implementation.\n // If needed, we can use a full implementation like picomatch: https://github.com/micromatch/picomatch/\n //\n const regexp = new RegExp(\n pattern.\n replaceAll(\".\", \"\\\\.\").\n replaceAll(\"$\", \"\\\\$\").\n replaceAll(\"*\", \".*\").\n replaceAll(\"?\", \".\"),\n \"i\"\n );\n eventNames = eventNames.filter((eventName) => regexp.test(eventName));\n }\n return eventNames;\n }\n\n public async exists(key: string): Promise<boolean> {\n return (\n this.keys[key] !== undefined ||\n this.data[key] !== undefined ||\n this.hash[key] !== undefined\n );\n }\n\n public set(key: string, value: string) {\n this.keys[key] = value;\n }\n\n public setex(key: string, value: string, seconds: number) {\n this.keys[key] = value;\n this.expire(key, seconds);\n }\n\n public expire(key: string, seconds: number) {\n // ensure previous timeout is clear before setting another one.\n if (this.timeouts[key]) {\n clearTimeout(this.timeouts[key]);\n }\n this.timeouts[key] = setTimeout(() => {\n delete this.keys[key];\n delete this.timeouts[key];\n }, seconds * 1000);\n }\n\n public get(key: string) {\n return this.keys[key];\n }\n\n public del(key: string) {\n delete this.keys[key];\n delete this.data[key];\n delete this.hash[key];\n }\n\n public sadd(key: string, value: any) {\n if (!this.data[key]) {\n this.data[key] = [];\n }\n\n if (this.data[key].indexOf(value) === -1) {\n this.data[key].push(value);\n }\n }\n\n public async smembers(key: string): Promise<string[]> {\n return this.data[key] || [];\n }\n\n public async sismember(key: string, field: string) {\n return this.data[key] && this.data[key].includes(field) ? 1 : 0;\n }\n\n public srem(key: string, value: any) {\n if (this.data[key]) {\n spliceOne(this.data[key], this.data[key].indexOf(value));\n }\n }\n\n public scard(key: string) {\n return (this.data[key] || []).length;\n }\n\n public async sinter(...keys: string[]) {\n const intersection: {[value: string]: number} = Object.create(null);\n\n for (let i = 0, l = keys.length; i < l; i++) {\n (await this.smembers(keys[i])).forEach((member) => {\n if (!intersection[member]) {\n intersection[member] = 0;\n }\n\n intersection[member]++;\n });\n }\n\n return Object.keys(intersection).reduce((prev, curr) => {\n if (intersection[curr] > 1) {\n prev.push(curr);\n }\n return prev;\n }, []);\n }\n\n public hset(key: string, field: string, value: string) {\n if (!this.hash[key]) { this.hash[key] = Object.create(null); }\n this.hash[key][field] = value;\n return Promise.resolve(true);\n }\n\n public hincrby(key: string, field: string, incrBy: number) {\n if (!this.hash[key]) { this.hash[key] = Object.create(null); }\n let value = Number(this.hash[key][field] || '0');\n value += incrBy;\n this.hash[key][field] = value.toString();\n return Promise.resolve(value);\n }\n\n public hincrbyex(key: string, field: string, incrBy: number, expireInSeconds: number) {\n if (!this.hash[key]) { this.hash[key] = Object.create(null); }\n let value = Number(this.hash[key][field] || '0');\n value += incrBy;\n this.hash[key][field] = value.toString();\n\n //\n // FIXME: delete only hash[key][field]\n // (we can't use \"HEXPIRE\" in Redis because it's only available since Redis version 7.4.0+)\n //\n if (this.timeouts[key]) {\n clearTimeout(this.timeouts[key]);\n }\n this.timeouts[key] = setTimeout(() => {\n delete this.hash[key];\n delete this.timeouts[key];\n }, expireInSeconds * 1000);\n\n return Promise.resolve(value);\n }\n\n public async hget(key: string, field: string) {\n return (typeof(this.hash[key]) === 'object')\n ? this.hash[key][field] ?? null\n : null;\n }\n\n public async hgetall(key: string) {\n return { ...this.hash[key] }; // fresh plain object, like redis\n }\n\n public hdel(key: string, field: any) {\n const success = this.hash?.[key]?.[field] !== undefined;\n if (success) {\n delete this.hash[key][field];\n }\n return Promise.resolve(success);\n }\n\n public async hlen(key: string) {\n return this.hash[key] && Object.keys(this.hash[key]).length || 0;\n }\n\n public async incr(key: string) {\n if (!this.keys[key]) {\n this.keys[key] = 0;\n }\n (this.keys[key] as number)++;\n return Promise.resolve(this.keys[key] as number);\n }\n\n public async decr(key: string) {\n if (!this.keys[key]) {\n this.keys[key] = 0;\n }\n (this.keys[key] as number)--;\n return Promise.resolve(this.keys[key] as number);\n }\n\n public llen(key: string) {\n return Promise.resolve((this.data[key] && this.data[key].length) || 0);\n }\n\n public rpush(key: string, ...values: string[]): Promise<number> {\n if (!this.data[key]) { this.data[key] = []; }\n\n let lastLength: number = 0;\n\n values.forEach(value => {\n lastLength = this.data[key].push(value);\n });\n\n return Promise.resolve(lastLength);\n }\n\n public lpush(key: string, ...values: string[]): Promise<number> {\n if (!this.data[key]) { this.data[key] = []; }\n\n let lastLength: number = 0;\n\n values.forEach(value => {\n lastLength = this.data[key].unshift(value);\n });\n\n return Promise.resolve(lastLength);\n }\n\n public lpop(key: string): Promise<string> {\n return Promise.resolve(Array.isArray(this.data[key])\n ? this.data[key].shift()\n : null);\n }\n\n public rpop(key: string): Promise<string | null> {\n return Promise.resolve(this.data[key].pop());\n }\n\n public brpop(...args: [...keys: string[], timeoutInSeconds: number]): Promise<[string, string] | null> {\n const keys = args.slice(0, -1) as string[];\n const timeoutInSeconds = args[args.length - 1] as number;\n\n const getFirstPopulated = (): [string, string] | null => {\n const keyWithValue = keys.find(key => this.data[key] && this.data[key].length > 0);\n if (keyWithValue) {\n return [keyWithValue, this.data[keyWithValue].pop()];\n } else {\n return null;\n }\n }\n\n const firstPopulated = getFirstPopulated();\n\n if (firstPopulated) {\n // return first populated key + item\n return Promise.resolve(firstPopulated);\n\n } else {\n // 8 retries per second\n const maxRetries = timeoutInSeconds * 8;\n\n let tries = 0;\n return new Promise((resolve) => {\n const interval = setInterval(() => {\n tries++;\n\n const firstPopulated = getFirstPopulated();\n if (firstPopulated) {\n clearInterval(interval);\n return resolve(firstPopulated);\n\n } else if (tries >= maxRetries) {\n clearInterval(interval);\n return resolve(null);\n }\n\n }, (timeoutInSeconds * 1000) / maxRetries);\n });\n }\n }\n\n public setMaxListeners(number: number) {\n this.subscriptions.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AAgB,MAAM;AAAA,EAC3C;AAAA,EAEO,WAAW;AAChB,QAAI,0BAAW;AACb,4CAAkB;AAAA,QAChB,MAAM,KAAK;AAAA,QACX,MAAM,KAAK;AAAA,QACX,MAAM,KAAK;AAAA,MACb,CAAC;AAAA,IACH;AAAA,EACF;AAEJ;",
|
|
4
|
+
"sourcesContent": ["\nimport { EventEmitter } from 'events';\nimport { spliceOne } from '../utils/Utils.ts';\nimport type { Presence } from './Presence.ts';\n\nimport { hasDevModeCache, isDevMode, getDevModeCache, writeDevModeCache } from '../utils/DevMode.ts';\n\ntype Callback = (...args: any[]) => void;\n\nexport class LocalPresence implements Presence {\n public subscriptions: EventEmitter = new EventEmitter();\n\n // null-proto: keys are caller-controlled, must never resolve through Object.prototype\n public data: {[roomName: string]: string[]} = Object.create(null);\n public hash: {[roomName: string]: {[key: string]: string}} = Object.create(null);\n\n public keys: {[name: string]: string | number} = Object.create(null);\n\n private timeouts: {[name: string]: NodeJS.Timeout} = Object.create(null);\n\n constructor() {\n //\n // reload from local cache on devMode\n //\n if (\n isDevMode &&\n hasDevModeCache()\n ) {\n const cache = getDevModeCache();\n if (cache.data) { this.data = cache.data; }\n if (cache.hash) { this.hash = cache.hash; }\n if (cache.keys) { this.keys = cache.keys; }\n }\n }\n\n public subscribe(topic: string, callback: (...args: any[]) => void) {\n this.subscriptions.on(topic, callback);\n return Promise.resolve(this);\n }\n\n public unsubscribe(topic: string, callback?: Callback) {\n if (callback) {\n this.subscriptions.removeListener(topic, callback);\n\n } else {\n this.subscriptions.removeAllListeners(topic);\n }\n\n return this;\n }\n\n public publish(topic: string, data: any) {\n this.subscriptions.emit(topic, data);\n return this;\n }\n\n public async channels (pattern?: string) {\n let eventNames = this.subscriptions.eventNames() as string[];\n if (pattern) {\n //\n // This is a limited glob pattern to regexp implementation.\n // If needed, we can use a full implementation like picomatch: https://github.com/micromatch/picomatch/\n //\n const regexp = new RegExp(\n pattern.\n replaceAll(\".\", \"\\\\.\").\n replaceAll(\"$\", \"\\\\$\").\n replaceAll(\"*\", \".*\").\n replaceAll(\"?\", \".\"),\n \"i\"\n );\n eventNames = eventNames.filter((eventName) => regexp.test(eventName));\n }\n return eventNames;\n }\n\n public async exists(key: string): Promise<boolean> {\n return (\n this.keys[key] !== undefined ||\n this.data[key] !== undefined ||\n this.hash[key] !== undefined\n );\n }\n\n public set(key: string, value: string) {\n this.keys[key] = value;\n }\n\n public setex(key: string, value: string, seconds: number) {\n this.keys[key] = value;\n this.expire(key, seconds);\n }\n\n public expire(key: string, seconds: number) {\n // ensure previous timeout is clear before setting another one.\n if (this.timeouts[key]) {\n clearTimeout(this.timeouts[key]);\n }\n this.timeouts[key] = setTimeout(() => {\n delete this.keys[key];\n delete this.timeouts[key];\n }, seconds * 1000);\n }\n\n public get(key: string) {\n return this.keys[key];\n }\n\n public del(key: string) {\n clearTimeout(this.timeouts[key]); // a pending expiry would wipe whatever is set next\n delete this.timeouts[key];\n delete this.keys[key];\n delete this.data[key];\n delete this.hash[key];\n }\n\n public sadd(key: string, value: any) {\n if (!this.data[key]) {\n this.data[key] = [];\n }\n\n if (this.data[key].indexOf(value) === -1) {\n this.data[key].push(value);\n }\n }\n\n public async smembers(key: string): Promise<string[]> {\n return this.data[key] || [];\n }\n\n public async sismember(key: string, field: string) {\n return this.data[key] && this.data[key].includes(field) ? 1 : 0;\n }\n\n public srem(key: string, value: any) {\n if (this.data[key]) {\n spliceOne(this.data[key], this.data[key].indexOf(value));\n }\n }\n\n public scard(key: string) {\n return (this.data[key] || []).length;\n }\n\n public async sinter(...keys: string[]) {\n const intersection: {[value: string]: number} = Object.create(null);\n\n for (let i = 0, l = keys.length; i < l; i++) {\n (await this.smembers(keys[i])).forEach((member) => {\n if (!intersection[member]) {\n intersection[member] = 0;\n }\n\n intersection[member]++;\n });\n }\n\n return Object.keys(intersection).reduce((prev, curr) => {\n if (intersection[curr] > 1) {\n prev.push(curr);\n }\n return prev;\n }, []);\n }\n\n public hset(key: string, field: string, value: string) {\n if (!this.hash[key]) { this.hash[key] = Object.create(null); }\n this.hash[key][field] = value;\n return Promise.resolve(true);\n }\n\n public hincrby(key: string, field: string, incrBy: number) {\n if (!this.hash[key]) { this.hash[key] = Object.create(null); }\n let value = Number(this.hash[key][field] || '0');\n value += incrBy;\n this.hash[key][field] = value.toString();\n return Promise.resolve(value);\n }\n\n public hincrbyex(key: string, field: string, incrBy: number, expireInSeconds: number) {\n if (!this.hash[key]) { this.hash[key] = Object.create(null); }\n let value = Number(this.hash[key][field] || '0');\n value += incrBy;\n this.hash[key][field] = value.toString();\n\n //\n // FIXME: delete only hash[key][field]\n // (we can't use \"HEXPIRE\" in Redis because it's only available since Redis version 7.4.0+)\n //\n if (this.timeouts[key]) {\n clearTimeout(this.timeouts[key]);\n }\n this.timeouts[key] = setTimeout(() => {\n delete this.hash[key];\n delete this.timeouts[key];\n }, expireInSeconds * 1000);\n\n return Promise.resolve(value);\n }\n\n public async hget(key: string, field: string) {\n return (typeof(this.hash[key]) === 'object')\n ? this.hash[key][field] ?? null\n : null;\n }\n\n public async hgetall(key: string) {\n return { ...this.hash[key] }; // fresh plain object, like redis\n }\n\n public hdel(key: string, field: any) {\n const success = this.hash?.[key]?.[field] !== undefined;\n if (success) {\n delete this.hash[key][field];\n }\n return Promise.resolve(success);\n }\n\n public async hlen(key: string) {\n return this.hash[key] && Object.keys(this.hash[key]).length || 0;\n }\n\n public async incr(key: string) {\n if (!this.keys[key]) {\n this.keys[key] = 0;\n }\n (this.keys[key] as number)++;\n return Promise.resolve(this.keys[key] as number);\n }\n\n public async decr(key: string) {\n if (!this.keys[key]) {\n this.keys[key] = 0;\n }\n (this.keys[key] as number)--;\n return Promise.resolve(this.keys[key] as number);\n }\n\n public llen(key: string) {\n return Promise.resolve((this.data[key] && this.data[key].length) || 0);\n }\n\n public rpush(key: string, ...values: string[]): Promise<number> {\n if (!this.data[key]) { this.data[key] = []; }\n\n let lastLength: number = 0;\n\n values.forEach(value => {\n lastLength = this.data[key].push(value);\n });\n\n return Promise.resolve(lastLength);\n }\n\n public lpush(key: string, ...values: string[]): Promise<number> {\n if (!this.data[key]) { this.data[key] = []; }\n\n let lastLength: number = 0;\n\n values.forEach(value => {\n lastLength = this.data[key].unshift(value);\n });\n\n return Promise.resolve(lastLength);\n }\n\n public lpop(key: string): Promise<string> {\n return Promise.resolve(Array.isArray(this.data[key])\n ? this.data[key].shift()\n : null);\n }\n\n public rpop(key: string): Promise<string | null> {\n return Promise.resolve(this.data[key].pop());\n }\n\n public brpop(...args: [...keys: string[], timeoutInSeconds: number]): Promise<[string, string] | null> {\n const keys = args.slice(0, -1) as string[];\n const timeoutInSeconds = args[args.length - 1] as number;\n\n const getFirstPopulated = (): [string, string] | null => {\n const keyWithValue = keys.find(key => this.data[key] && this.data[key].length > 0);\n if (keyWithValue) {\n return [keyWithValue, this.data[keyWithValue].pop()];\n } else {\n return null;\n }\n }\n\n const firstPopulated = getFirstPopulated();\n\n if (firstPopulated) {\n // return first populated key + item\n return Promise.resolve(firstPopulated);\n\n } else {\n // 8 retries per second\n const maxRetries = timeoutInSeconds * 8;\n\n let tries = 0;\n return new Promise((resolve) => {\n const interval = setInterval(() => {\n tries++;\n\n const firstPopulated = getFirstPopulated();\n if (firstPopulated) {\n clearInterval(interval);\n return resolve(firstPopulated);\n\n } else if (tries >= maxRetries) {\n clearInterval(interval);\n return resolve(null);\n }\n\n }, (timeoutInSeconds * 1000) / maxRetries);\n });\n }\n }\n\n public setMaxListeners(number: number) {\n this.subscriptions.setMaxListeners(number);\n }\n\n public shutdown() {\n if (isDevMode) {\n writeDevModeCache({\n data: this.data,\n hash: this.hash,\n keys: this.keys\n });\n }\n }\n\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,oBAA6B;AAC7B,mBAA0B;AAG1B,qBAA+E;AAIxE,IAAM,gBAAN,MAAwC;AAAA,EAW3C,cAAc;AAVd,SAAO,gBAA8B,IAAI,2BA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
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/presence/LocalPresence.ts"],
|
|
4
|
-
"sourcesContent": ["\nimport { EventEmitter } from 'events';\nimport { spliceOne } from '../utils/Utils.ts';\nimport type { Presence } from './Presence.ts';\n\nimport { hasDevModeCache, isDevMode, getDevModeCache, writeDevModeCache } from '../utils/DevMode.ts';\n\ntype Callback = (...args: any[]) => void;\n\nexport class LocalPresence implements Presence {\n public subscriptions: EventEmitter = new EventEmitter();\n\n // null-proto: keys are caller-controlled, must never resolve through Object.prototype\n public data: {[roomName: string]: string[]} = Object.create(null);\n public hash: {[roomName: string]: {[key: string]: string}} = Object.create(null);\n\n public keys: {[name: string]: string | number} = Object.create(null);\n\n private timeouts: {[name: string]: NodeJS.Timeout} = Object.create(null);\n\n constructor() {\n //\n // reload from local cache on devMode\n //\n if (\n isDevMode &&\n hasDevModeCache()\n ) {\n const cache = getDevModeCache();\n if (cache.data) { this.data = cache.data; }\n if (cache.hash) { this.hash = cache.hash; }\n if (cache.keys) { this.keys = cache.keys; }\n }\n }\n\n public subscribe(topic: string, callback: (...args: any[]) => void) {\n this.subscriptions.on(topic, callback);\n return Promise.resolve(this);\n }\n\n public unsubscribe(topic: string, callback?: Callback) {\n if (callback) {\n this.subscriptions.removeListener(topic, callback);\n\n } else {\n this.subscriptions.removeAllListeners(topic);\n }\n\n return this;\n }\n\n public publish(topic: string, data: any) {\n this.subscriptions.emit(topic, data);\n return this;\n }\n\n public async channels (pattern?: string) {\n let eventNames = this.subscriptions.eventNames() as string[];\n if (pattern) {\n //\n // This is a limited glob pattern to regexp implementation.\n // If needed, we can use a full implementation like picomatch: https://github.com/micromatch/picomatch/\n //\n const regexp = new RegExp(\n pattern.\n replaceAll(\".\", \"\\\\.\").\n replaceAll(\"$\", \"\\\\$\").\n replaceAll(\"*\", \".*\").\n replaceAll(\"?\", \".\"),\n \"i\"\n );\n eventNames = eventNames.filter((eventName) => regexp.test(eventName));\n }\n return eventNames;\n }\n\n public async exists(key: string): Promise<boolean> {\n return (\n this.keys[key] !== undefined ||\n this.data[key] !== undefined ||\n this.hash[key] !== undefined\n );\n }\n\n public set(key: string, value: string) {\n this.keys[key] = value;\n }\n\n public setex(key: string, value: string, seconds: number) {\n this.keys[key] = value;\n this.expire(key, seconds);\n }\n\n public expire(key: string, seconds: number) {\n // ensure previous timeout is clear before setting another one.\n if (this.timeouts[key]) {\n clearTimeout(this.timeouts[key]);\n }\n this.timeouts[key] = setTimeout(() => {\n delete this.keys[key];\n delete this.timeouts[key];\n }, seconds * 1000);\n }\n\n public get(key: string) {\n return this.keys[key];\n }\n\n public del(key: string) {\n delete this.keys[key];\n delete this.data[key];\n delete this.hash[key];\n }\n\n public sadd(key: string, value: any) {\n if (!this.data[key]) {\n this.data[key] = [];\n }\n\n if (this.data[key].indexOf(value) === -1) {\n this.data[key].push(value);\n }\n }\n\n public async smembers(key: string): Promise<string[]> {\n return this.data[key] || [];\n }\n\n public async sismember(key: string, field: string) {\n return this.data[key] && this.data[key].includes(field) ? 1 : 0;\n }\n\n public srem(key: string, value: any) {\n if (this.data[key]) {\n spliceOne(this.data[key], this.data[key].indexOf(value));\n }\n }\n\n public scard(key: string) {\n return (this.data[key] || []).length;\n }\n\n public async sinter(...keys: string[]) {\n const intersection: {[value: string]: number} = Object.create(null);\n\n for (let i = 0, l = keys.length; i < l; i++) {\n (await this.smembers(keys[i])).forEach((member) => {\n if (!intersection[member]) {\n intersection[member] = 0;\n }\n\n intersection[member]++;\n });\n }\n\n return Object.keys(intersection).reduce((prev, curr) => {\n if (intersection[curr] > 1) {\n prev.push(curr);\n }\n return prev;\n }, []);\n }\n\n public hset(key: string, field: string, value: string) {\n if (!this.hash[key]) { this.hash[key] = Object.create(null); }\n this.hash[key][field] = value;\n return Promise.resolve(true);\n }\n\n public hincrby(key: string, field: string, incrBy: number) {\n if (!this.hash[key]) { this.hash[key] = Object.create(null); }\n let value = Number(this.hash[key][field] || '0');\n value += incrBy;\n this.hash[key][field] = value.toString();\n return Promise.resolve(value);\n }\n\n public hincrbyex(key: string, field: string, incrBy: number, expireInSeconds: number) {\n if (!this.hash[key]) { this.hash[key] = Object.create(null); }\n let value = Number(this.hash[key][field] || '0');\n value += incrBy;\n this.hash[key][field] = value.toString();\n\n //\n // FIXME: delete only hash[key][field]\n // (we can't use \"HEXPIRE\" in Redis because it's only available since Redis version 7.4.0+)\n //\n if (this.timeouts[key]) {\n clearTimeout(this.timeouts[key]);\n }\n this.timeouts[key] = setTimeout(() => {\n delete this.hash[key];\n delete this.timeouts[key];\n }, expireInSeconds * 1000);\n\n return Promise.resolve(value);\n }\n\n public async hget(key: string, field: string) {\n return (typeof(this.hash[key]) === 'object')\n ? this.hash[key][field] ?? null\n : null;\n }\n\n public async hgetall(key: string) {\n return { ...this.hash[key] }; // fresh plain object, like redis\n }\n\n public hdel(key: string, field: any) {\n const success = this.hash?.[key]?.[field] !== undefined;\n if (success) {\n delete this.hash[key][field];\n }\n return Promise.resolve(success);\n }\n\n public async hlen(key: string) {\n return this.hash[key] && Object.keys(this.hash[key]).length || 0;\n }\n\n public async incr(key: string) {\n if (!this.keys[key]) {\n this.keys[key] = 0;\n }\n (this.keys[key] as number)++;\n return Promise.resolve(this.keys[key] as number);\n }\n\n public async decr(key: string) {\n if (!this.keys[key]) {\n this.keys[key] = 0;\n }\n (this.keys[key] as number)--;\n return Promise.resolve(this.keys[key] as number);\n }\n\n public llen(key: string) {\n return Promise.resolve((this.data[key] && this.data[key].length) || 0);\n }\n\n public rpush(key: string, ...values: string[]): Promise<number> {\n if (!this.data[key]) { this.data[key] = []; }\n\n let lastLength: number = 0;\n\n values.forEach(value => {\n lastLength = this.data[key].push(value);\n });\n\n return Promise.resolve(lastLength);\n }\n\n public lpush(key: string, ...values: string[]): Promise<number> {\n if (!this.data[key]) { this.data[key] = []; }\n\n let lastLength: number = 0;\n\n values.forEach(value => {\n lastLength = this.data[key].unshift(value);\n });\n\n return Promise.resolve(lastLength);\n }\n\n public lpop(key: string): Promise<string> {\n return Promise.resolve(Array.isArray(this.data[key])\n ? this.data[key].shift()\n : null);\n }\n\n public rpop(key: string): Promise<string | null> {\n return Promise.resolve(this.data[key].pop());\n }\n\n public brpop(...args: [...keys: string[], timeoutInSeconds: number]): Promise<[string, string] | null> {\n const keys = args.slice(0, -1) as string[];\n const timeoutInSeconds = args[args.length - 1] as number;\n\n const getFirstPopulated = (): [string, string] | null => {\n const keyWithValue = keys.find(key => this.data[key] && this.data[key].length > 0);\n if (keyWithValue) {\n return [keyWithValue, this.data[keyWithValue].pop()];\n } else {\n return null;\n }\n }\n\n const firstPopulated = getFirstPopulated();\n\n if (firstPopulated) {\n // return first populated key + item\n return Promise.resolve(firstPopulated);\n\n } else {\n // 8 retries per second\n const maxRetries = timeoutInSeconds * 8;\n\n let tries = 0;\n return new Promise((resolve) => {\n const interval = setInterval(() => {\n tries++;\n\n const firstPopulated = getFirstPopulated();\n if (firstPopulated) {\n clearInterval(interval);\n return resolve(firstPopulated);\n\n } else if (tries >= maxRetries) {\n clearInterval(interval);\n return resolve(null);\n }\n\n }, (timeoutInSeconds * 1000) / maxRetries);\n });\n }\n }\n\n public setMaxListeners(number: number) {\n this.subscriptions.setMaxListeners(number);\n }\n\n public shutdown() {\n if (isDevMode) {\n writeDevModeCache({\n data: this.data,\n hash: this.hash,\n keys: this.keys\n });\n }\n }\n\n}\n"],
|
|
5
|
-
"mappings": ";AACA,SAAS,oBAAoB;AAC7B,SAAS,iBAAiB;AAG1B,SAAS,iBAAiB,WAAW,iBAAiB,yBAAyB;AAIxE,IAAM,gBAAN,MAAwC;AAAA,EAW3C,cAAc;AAVd,SAAO,gBAA8B,IAAI,aAAa;AAGtD;AAAA,SAAO,OAAuC,uBAAO,OAAO,IAAI;AAChE,SAAO,OAAsD,uBAAO,OAAO,IAAI;AAE/E,SAAO,OAA0C,uBAAO,OAAO,IAAI;AAEnE,SAAQ,WAA6C,uBAAO,OAAO,IA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M,eAAe,KAAK,KAAK,SAAO,KAAK,KAAK,GAAG,KAAK,KAAK,KAAK,GAAG,EAAE,SAAS,CAAC;AACjF,UAAI,cAAc;AAChB,eAAO,CAAC,cAAc,KAAK,KAAK,YAAY,EAAE,IAAI,CAAC;AAAA,MACrD,OAAO;AACL,eAAO;AAAA,MACT;AAAA,IACF;AAEA,UAAM,iBAAiB,kBAAkB;AAEzC,QAAI,gBAAgB;AAElB,aAAO,QAAQ,QAAQ,cAAc;AAAA,IAEvC,OAAO;AAEL,YAAM,aAAa,mBAAmB;AAEtC,UAAI,QAAQ;AACZ,aAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,cAAM,WAAW,YAAY,MAAM;AACjC;AAEA,gBAAMA,kBAAiB,kBAAkB;AACzC,cAAIA,iBAAgB;AAClB,0BAAc,QAAQ;AACtB,mBAAO,QAAQA,eAAc;AAAA,UAE/B,WAAW,SAAS,YAAY;AAC9B,0BAAc,QAAQ;AACtB,mBAAO,QAAQ,IAAI;AAAA,UACrB;AAAA,QAEF,GAAI,mBAAmB,MAAQ,UAAU;AAAA,MAC3C,CAAC;AAAA,IACH;AAAA,EACF;AAAA,EAEO,gBAAgB,QAAgB;AACrC,SAAK,cAAc,gBAAgB,MAAM;AAAA,EAC3C;AAAA,EAEO,WAAW;AAChB,QAAI,WAAW;AACb,wBAAkB;AAAA,QAChB,MAAM,KAAK;AAAA,QACX,MAAM,KAAK;AAAA,QACX,MAAM,KAAK;AAAA,MACb,CAAC;AAAA,IACH;AAAA,EACF;AAEJ;",
|
|
4
|
+
"sourcesContent": ["\nimport { EventEmitter } from 'events';\nimport { spliceOne } from '../utils/Utils.ts';\nimport type { Presence } from './Presence.ts';\n\nimport { hasDevModeCache, isDevMode, getDevModeCache, writeDevModeCache } from '../utils/DevMode.ts';\n\ntype Callback = (...args: any[]) => void;\n\nexport class LocalPresence implements Presence {\n public subscriptions: EventEmitter = new EventEmitter();\n\n // null-proto: keys are caller-controlled, must never resolve through Object.prototype\n public data: {[roomName: string]: string[]} = Object.create(null);\n public hash: {[roomName: string]: {[key: string]: string}} = Object.create(null);\n\n public keys: {[name: string]: string | number} = Object.create(null);\n\n private timeouts: {[name: string]: NodeJS.Timeout} = Object.create(null);\n\n constructor() {\n //\n // reload from local cache on devMode\n //\n if (\n isDevMode &&\n hasDevModeCache()\n ) {\n const cache = getDevModeCache();\n if (cache.data) { this.data = cache.data; }\n if (cache.hash) { this.hash = cache.hash; }\n if (cache.keys) { this.keys = cache.keys; }\n }\n }\n\n public subscribe(topic: string, callback: (...args: any[]) => void) {\n this.subscriptions.on(topic, callback);\n return Promise.resolve(this);\n }\n\n public unsubscribe(topic: string, callback?: Callback) {\n if (callback) {\n this.subscriptions.removeListener(topic, callback);\n\n } else {\n this.subscriptions.removeAllListeners(topic);\n }\n\n return this;\n }\n\n public publish(topic: string, data: any) {\n this.subscriptions.emit(topic, data);\n return this;\n }\n\n public async channels (pattern?: string) {\n let eventNames = this.subscriptions.eventNames() as string[];\n if (pattern) {\n //\n // This is a limited glob pattern to regexp implementation.\n // If needed, we can use a full implementation like picomatch: https://github.com/micromatch/picomatch/\n //\n const regexp = new RegExp(\n pattern.\n replaceAll(\".\", \"\\\\.\").\n replaceAll(\"$\", \"\\\\$\").\n replaceAll(\"*\", \".*\").\n replaceAll(\"?\", \".\"),\n \"i\"\n );\n eventNames = eventNames.filter((eventName) => regexp.test(eventName));\n }\n return eventNames;\n }\n\n public async exists(key: string): Promise<boolean> {\n return (\n this.keys[key] !== undefined ||\n this.data[key] !== undefined ||\n this.hash[key] !== undefined\n );\n }\n\n public set(key: string, value: string) {\n this.keys[key] = value;\n }\n\n public setex(key: string, value: string, seconds: number) {\n this.keys[key] = value;\n this.expire(key, seconds);\n }\n\n public expire(key: string, seconds: number) {\n // ensure previous timeout is clear before setting another one.\n if (this.timeouts[key]) {\n clearTimeout(this.timeouts[key]);\n }\n this.timeouts[key] = setTimeout(() => {\n delete this.keys[key];\n delete this.timeouts[key];\n }, seconds * 1000);\n }\n\n public get(key: string) {\n return this.keys[key];\n }\n\n public del(key: string) {\n clearTimeout(this.timeouts[key]); // a pending expiry would wipe whatever is set next\n delete this.timeouts[key];\n delete this.keys[key];\n delete this.data[key];\n delete this.hash[key];\n }\n\n public sadd(key: string, value: any) {\n if (!this.data[key]) {\n this.data[key] = [];\n }\n\n if (this.data[key].indexOf(value) === -1) {\n this.data[key].push(value);\n }\n }\n\n public async smembers(key: string): Promise<string[]> {\n return this.data[key] || [];\n }\n\n public async sismember(key: string, field: string) {\n return this.data[key] && this.data[key].includes(field) ? 1 : 0;\n }\n\n public srem(key: string, value: any) {\n if (this.data[key]) {\n spliceOne(this.data[key], this.data[key].indexOf(value));\n }\n }\n\n public scard(key: string) {\n return (this.data[key] || []).length;\n }\n\n public async sinter(...keys: string[]) {\n const intersection: {[value: string]: number} = Object.create(null);\n\n for (let i = 0, l = keys.length; i < l; i++) {\n (await this.smembers(keys[i])).forEach((member) => {\n if (!intersection[member]) {\n intersection[member] = 0;\n }\n\n intersection[member]++;\n });\n }\n\n return Object.keys(intersection).reduce((prev, curr) => {\n if (intersection[curr] > 1) {\n prev.push(curr);\n }\n return prev;\n }, []);\n }\n\n public hset(key: string, field: string, value: string) {\n if (!this.hash[key]) { this.hash[key] = Object.create(null); }\n this.hash[key][field] = value;\n return Promise.resolve(true);\n }\n\n public hincrby(key: string, field: string, incrBy: number) {\n if (!this.hash[key]) { this.hash[key] = Object.create(null); }\n let value = Number(this.hash[key][field] || '0');\n value += incrBy;\n this.hash[key][field] = value.toString();\n return Promise.resolve(value);\n }\n\n public hincrbyex(key: string, field: string, incrBy: number, expireInSeconds: number) {\n if (!this.hash[key]) { this.hash[key] = Object.create(null); }\n let value = Number(this.hash[key][field] || '0');\n value += incrBy;\n this.hash[key][field] = value.toString();\n\n //\n // FIXME: delete only hash[key][field]\n // (we can't use \"HEXPIRE\" in Redis because it's only available since Redis version 7.4.0+)\n //\n if (this.timeouts[key]) {\n clearTimeout(this.timeouts[key]);\n }\n this.timeouts[key] = setTimeout(() => {\n delete this.hash[key];\n delete this.timeouts[key];\n }, expireInSeconds * 1000);\n\n return Promise.resolve(value);\n }\n\n public async hget(key: string, field: string) {\n return (typeof(this.hash[key]) === 'object')\n ? this.hash[key][field] ?? null\n : null;\n }\n\n public async hgetall(key: string) {\n return { ...this.hash[key] }; // fresh plain object, like redis\n }\n\n public hdel(key: string, field: any) {\n const success = this.hash?.[key]?.[field] !== undefined;\n if (success) {\n delete this.hash[key][field];\n }\n return Promise.resolve(success);\n }\n\n public async hlen(key: string) {\n return this.hash[key] && Object.keys(this.hash[key]).length || 0;\n }\n\n public async incr(key: string) {\n if (!this.keys[key]) {\n this.keys[key] = 0;\n }\n (this.keys[key] as number)++;\n return Promise.resolve(this.keys[key] as number);\n }\n\n public async decr(key: string) {\n if (!this.keys[key]) {\n this.keys[key] = 0;\n }\n (this.keys[key] as number)--;\n return Promise.resolve(this.keys[key] as number);\n }\n\n public llen(key: string) {\n return Promise.resolve((this.data[key] && this.data[key].length) || 0);\n }\n\n public rpush(key: string, ...values: string[]): Promise<number> {\n if (!this.data[key]) { this.data[key] = []; }\n\n let lastLength: number = 0;\n\n values.forEach(value => {\n lastLength = this.data[key].push(value);\n });\n\n return Promise.resolve(lastLength);\n }\n\n public lpush(key: string, ...values: string[]): Promise<number> {\n if (!this.data[key]) { this.data[key] = []; }\n\n let lastLength: number = 0;\n\n values.forEach(value => {\n lastLength = this.data[key].unshift(value);\n });\n\n return Promise.resolve(lastLength);\n }\n\n public lpop(key: string): Promise<string> {\n return Promise.resolve(Array.isArray(this.data[key])\n ? this.data[key].shift()\n : null);\n }\n\n public rpop(key: string): Promise<string | null> {\n return Promise.resolve(this.data[key].pop());\n }\n\n public brpop(...args: [...keys: string[], timeoutInSeconds: number]): Promise<[string, string] | null> {\n const keys = args.slice(0, -1) as string[];\n const timeoutInSeconds = args[args.length - 1] as number;\n\n const getFirstPopulated = (): [string, string] | null => {\n const keyWithValue = keys.find(key => this.data[key] && this.data[key].length > 0);\n if (keyWithValue) {\n return [keyWithValue, this.data[keyWithValue].pop()];\n } else {\n return null;\n }\n }\n\n const firstPopulated = getFirstPopulated();\n\n if (firstPopulated) {\n // return first populated key + item\n return Promise.resolve(firstPopulated);\n\n } else {\n // 8 retries per second\n const maxRetries = timeoutInSeconds * 8;\n\n let tries = 0;\n return new Promise((resolve) => {\n const interval = setInterval(() => {\n tries++;\n\n const firstPopulated = getFirstPopulated();\n if (firstPopulated) {\n clearInterval(interval);\n return resolve(firstPopulated);\n\n } else if (tries >= maxRetries) {\n clearInterval(interval);\n return resolve(null);\n }\n\n }, (timeoutInSeconds * 1000) / maxRetries);\n });\n }\n }\n\n public setMaxListeners(number: number) {\n this.subscriptions.setMaxListeners(number);\n }\n\n public shutdown() {\n if (isDevMode) {\n writeDevModeCache({\n data: this.data,\n hash: this.hash,\n keys: this.keys\n });\n }\n }\n\n}\n"],
|
|
5
|
+
"mappings": ";AACA,SAAS,oBAAoB;AAC7B,SAAS,iBAAiB;AAG1B,SAAS,iBAAiB,WAAW,iBAAiB,yBAAyB;AAIxE,IAAM,gBAAN,MAAwC;AAAA,EAW3C,cAAc;AAVd,SAAO,gBAA8B,IAAI,aAAa;AAGtD;AAAA,SAAO,OAAuC,uBAAO,OAAO,IAAI;AAChE,SAAO,OAAsD,uBAAO,OAAO,IAAI;AAE/E,SAAO,OAA0C,uBAAO,OAAO,IAAI;AAEnE,SAAQ,WAA6C,uBAAO,OAAO,IAAI;AAMrE,QACE,aACA,gBAAgB,GAChB;AACA,YAAM,QAAQ,gBAAgB;AAC9B,UAAI,MAAM,MAAM;AAAE,aAAK,OAAO,MAAM;AAAA,MAAM;AAC1C,UAAI,MAAM,MAAM;AAAE,aAAK,OAAO,MAAM;AAAA,MAAM;AAC1C,UAAI,MAAM,MAAM;AAAE,aAAK,OAAO,MAAM;AAAA,MAAM;AAAA,IAC5C;AAAA,EACF;AAAA,EAEO,UAAU,OAAe,UAAoC;AAChE,SAAK,cAAc,GAAG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I,gBAAgB;AAElB,aAAO,QAAQ,QAAQ,cAAc;AAAA,IAEvC,OAAO;AAEL,YAAM,aAAa,mBAAmB;AAEtC,UAAI,QAAQ;AACZ,aAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,cAAM,WAAW,YAAY,MAAM;AACjC;AAEA,gBAAMA,kBAAiB,kBAAkB;AACzC,cAAIA,iBAAgB;AAClB,0BAAc,QAAQ;AACtB,mBAAO,QAAQA,eAAc;AAAA,UAE/B,WAAW,SAAS,YAAY;AAC9B,0BAAc,QAAQ;AACtB,mBAAO,QAAQ,IAAI;AAAA,UACrB;AAAA,QAEF,GAAI,mBAAmB,MAAQ,UAAU;AAAA,MAC3C,CAAC;AAAA,IACH;AAAA,EACF;AAAA,EAEO,gBAAgB,QAAgB;AACrC,SAAK,cAAc,gBAAgB,MAAM;AAAA,EAC3C;AAAA,EAEO,WAAW;AAChB,QAAI,WAAW;AACb,wBAAkB;AAAA,QAChB,MAAM,KAAK;AAAA,QACX,MAAM,KAAK;AAAA,QACX,MAAM,KAAK;AAAA,MACb,CAAC;AAAA,IACH;AAAA,EACF;AAEJ;",
|
|
6
6
|
"names": ["firstPopulated"]
|
|
7
7
|
}
|
package/build/utils/DevMode.cjs
CHANGED
|
@@ -75,6 +75,9 @@ async function reloadFromCache() {
|
|
|
75
75
|
recreatedRoomListing = await (0, import_MatchMaker.handleCreateRoom)(roomHistory.roomName, roomHistory.clientOptions, roomId);
|
|
76
76
|
recreatedRoom = (0, import_MatchMaker.getLocalRoomById)(recreatedRoomListing.roomId);
|
|
77
77
|
} catch (e) {
|
|
78
|
+
if (import_MatchMaker.state === import_MatchMaker.MatchMakerState.SHUTTING_DOWN) {
|
|
79
|
+
break;
|
|
80
|
+
}
|
|
78
81
|
(0, import_Debug.debugAndPrintError)(`\u274C couldn't restore room '${roomId}':
|
|
79
82
|
${e.stack}`);
|
|
80
83
|
await import_MatchMaker.presence.hdel(getRoomRestoreListKey(), roomId);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/DevMode.ts"],
|
|
4
|
-
"sourcesContent": ["import fs from 'fs';\nimport path from 'path';\nimport { type Schema, MapSchema, ArraySchema, SetSchema, CollectionSchema, $childType, $changes } from '@colyseus/schema';\nimport { logger } from '../Logger.ts';\nimport { debugAndPrintError, debugDevMode } from '../Debug.ts';\nimport { getLocalRoomById, handleCreateRoom, presence, remoteRoomCall } from '../MatchMaker.ts';\nimport type { Room } from '../Room.ts';\n\nconst DEVMODE_CACHE_FILE_PATH = path.resolve(\".devmode.json\");\n\nexport let isDevMode: boolean = false;\n\nexport function hasDevModeCache() {\n return fs.existsSync(DEVMODE_CACHE_FILE_PATH);\n}\n\n// presence dictionaries are keyed by caller-controlled strings: rebuild them null-proto\nconst nullProto = (_: string, value: any) =>\n (value && typeof value === 'object' && !Array.isArray(value))\n ? Object.assign(Object.create(null), value)\n : value;\n\nexport function getDevModeCache() {\n return JSON.parse(fs.readFileSync(DEVMODE_CACHE_FILE_PATH, 'utf8'), nullProto) || {};\n}\n\nexport function writeDevModeCache(cache: any) {\n fs.writeFileSync(DEVMODE_CACHE_FILE_PATH, JSON.stringify(cache, null, 2), 'utf8');\n}\n\nexport function setDevMode(bool: boolean) {\n isDevMode = bool;\n}\n\nexport async function reloadFromCache() {\n const roomHistoryList = Object.entries(await presence.hgetall(getRoomRestoreListKey()));\n debugDevMode(\"rooms to restore: %i\", roomHistoryList.length);\n\n for (const [roomId, value] of roomHistoryList) {\n let roomHistory: any;\n let recreatedRoom: Room;\n let recreatedRoomListing: any;\n\n try {\n roomHistory = JSON.parse(value);\n debugDevMode(\"restoring room %s (%s)\", roomHistory.roomName, roomId);\n\n recreatedRoomListing = await handleCreateRoom(roomHistory.roomName, roomHistory.clientOptions, roomId);\n recreatedRoom = getLocalRoomById(recreatedRoomListing.roomId);\n\n } catch (e: any) {\n // unrestorable entry (e.g. room type renamed/removed) \u2014 drop it\n // instead of wedging the boot\n debugAndPrintError(`\u274C couldn't restore room '${roomId}':\\n${e.stack}`);\n await presence.hdel(getRoomRestoreListKey(), roomId);\n continue;\n }\n\n // Restore previous state\n if (roomHistory.hasOwnProperty(\"state\")) {\n try {\n const rawState = JSON.parse(roomHistory.state);\n logger.debug(`\uD83D\uDCCB room '${roomId}' state =>`, rawState);\n\n (recreatedRoom.state as Schema).restore(rawState);\n\n // Restore the encoder's nextUniqueId so refIds increase\n // monotonically across HMR cycles. Without this, restore()\n // always produces the same refIds (0,1,2,3...) and onJoin()\n // always assigns the same next refIds (4,5...), causing the\n // client decoder to reuse stale instances on the 2nd+ cycle.\n if (roomHistory.nextRefId !== undefined) {\n const encoderRoot = recreatedRoom.state[$changes]?.root;\n if (encoderRoot && roomHistory.nextRefId > encoderRoot['nextUniqueId']) {\n encoderRoot['nextUniqueId'] = roomHistory.nextRefId;\n }\n }\n } catch (e: any) {\n debugAndPrintError(`\u274C couldn't restore room '${roomId}' state:\\n${e.stack}`);\n }\n }\n\n // Reserve seats for clients from cached history.\n // Skip entries without a reconnectionToken \u2014 these are stale\n // seats from allowReconnection() where the client already left\n // (e.g. page refresh). Restoring them would block room disposal.\n if (roomHistory.clients) {\n for (const clientData of roomHistory.clients) {\n const { sessionId, reconnectionToken } = clientData;\n if (!reconnectionToken) { continue; }\n // TODO: need to restore each client's StateView as well\n await remoteRoomCall(recreatedRoomListing.roomId, '_reserveSeat', [sessionId, {}, {}, recreatedRoom.seatReservationTimeout, false, reconnectionToken]);\n }\n }\n\n // call `onRestoreRoom` with custom 'cache'd property.\n recreatedRoom.onRestoreRoom?.(roomHistory[\"cache\"]);\n\n logger.debug(`\uD83D\uDD04 room '${roomId}' has been restored with ${roomHistory.clients?.length || 0} reserved seats: ${roomHistory.clients?.map((c: any) => c.sessionId).join(\", \")}`);\n }\n\n if (roomHistoryList.length > 0) {\n logger.debug(\"\u2705\", roomHistoryList.length, \"room(s) have been restored.\");\n }\n}\n\nexport async function cacheRoomHistory(rooms: { [roomId: string]: Room }) {\n for (const room of Object.values(rooms)) {\n const roomHistoryResult = await presence.hget(getRoomRestoreListKey(), room.roomId);\n if (roomHistoryResult) {\n try {\n const roomHistory = JSON.parse(roomHistoryResult);\n\n // custom cache method\n roomHistory[\"cache\"] = room.onCacheRoom?.();\n\n // encode state\n debugDevMode(\"caching room %s (%s)\", room.roomName, room.roomId);\n\n if (room.state) {\n roomHistory[\"state\"] = JSON.stringify(room.state);\n\n // Cache the encoder's nextUniqueId so it can be restored.\n // This ensures refIds increase monotonically across HMR cycles,\n // preventing the client decoder from reusing stale refs that\n // happen to have the same refId as newly created instances.\n const encoderRoot = room.state[$changes]?.root;\n if (encoderRoot) {\n roomHistory[\"nextRefId\"] = encoderRoot['nextUniqueId'];\n }\n }\n\n // cache active clients with their reconnection tokens\n // TODO: need to cache each client's StateView as well\n const activeClients = room.clients.map((client) => ({\n sessionId: client.sessionId,\n reconnectionToken: client.reconnectionToken,\n }));\n\n // collect active client sessionIds to avoid duplicates\n const activeSessionIds = new Set(activeClients.map((c) => c.sessionId));\n\n // also cache reserved seats (they don't have reconnectionTokens yet)\n // filter out reserved seats that are already active clients (from devMode reconnection)\n const reservedSeats = Object.keys(room['_reservedSeats'])\n .filter((sessionId) => !activeSessionIds.has(sessionId))\n .map((sessionId) => ({\n sessionId,\n reconnectionToken: undefined,\n }));\n\n roomHistory[\"clients\"] = activeClients.concat(reservedSeats);\n\n await presence.hset(getRoomRestoreListKey(), room.roomId, JSON.stringify(roomHistory));\n\n // Rewrite updated room history\n logger.debug(`\uD83D\uDCBE caching room '${room.roomId}' (clients: ${room.clients.length}, has state: ${roomHistory[\"state\"] !== undefined ? \"yes\" : \"no\"})`);\n\n } catch (e: any) {\n debugAndPrintError(`\u274C couldn't cache room '${room.roomId}', due to:\\n${e.stack}`);\n }\n }\n }\n}\n\nexport function getRoomRestoreListKey() {\n return 'roomhistory';\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAAe;AACf,kBAAiB;AACjB,oBAAuG;AACvG,oBAAuB;AACvB,mBAAiD;AACjD,
|
|
4
|
+
"sourcesContent": ["import fs from 'fs';\nimport path from 'path';\nimport { type Schema, MapSchema, ArraySchema, SetSchema, CollectionSchema, $childType, $changes } from '@colyseus/schema';\nimport { logger } from '../Logger.ts';\nimport { debugAndPrintError, debugDevMode } from '../Debug.ts';\nimport { getLocalRoomById, handleCreateRoom, MatchMakerState, presence, remoteRoomCall, state } from '../MatchMaker.ts';\nimport type { Room } from '../Room.ts';\n\nconst DEVMODE_CACHE_FILE_PATH = path.resolve(\".devmode.json\");\n\nexport let isDevMode: boolean = false;\n\nexport function hasDevModeCache() {\n return fs.existsSync(DEVMODE_CACHE_FILE_PATH);\n}\n\n// presence dictionaries are keyed by caller-controlled strings: rebuild them null-proto\nconst nullProto = (_: string, value: any) =>\n (value && typeof value === 'object' && !Array.isArray(value))\n ? Object.assign(Object.create(null), value)\n : value;\n\nexport function getDevModeCache() {\n return JSON.parse(fs.readFileSync(DEVMODE_CACHE_FILE_PATH, 'utf8'), nullProto) || {};\n}\n\nexport function writeDevModeCache(cache: any) {\n fs.writeFileSync(DEVMODE_CACHE_FILE_PATH, JSON.stringify(cache, null, 2), 'utf8');\n}\n\nexport function setDevMode(bool: boolean) {\n isDevMode = bool;\n}\n\nexport async function reloadFromCache() {\n const roomHistoryList = Object.entries(await presence.hgetall(getRoomRestoreListKey()));\n debugDevMode(\"rooms to restore: %i\", roomHistoryList.length);\n\n for (const [roomId, value] of roomHistoryList) {\n let roomHistory: any;\n let recreatedRoom: Room;\n let recreatedRoomListing: any;\n\n try {\n roomHistory = JSON.parse(value);\n debugDevMode(\"restoring room %s (%s)\", roomHistory.roomName, roomId);\n\n recreatedRoomListing = await handleCreateRoom(roomHistory.roomName, roomHistory.clientOptions, roomId);\n recreatedRoom = getLocalRoomById(recreatedRoomListing.roomId);\n\n } catch (e: any) {\n // shutdown interrupted the restore: keep the remaining entries for the next boot\n if (state === MatchMakerState.SHUTTING_DOWN) { break; }\n\n // unrestorable entry (e.g. room type renamed/removed) \u2014 drop it\n // instead of wedging the boot\n debugAndPrintError(`\u274C couldn't restore room '${roomId}':\\n${e.stack}`);\n await presence.hdel(getRoomRestoreListKey(), roomId);\n continue;\n }\n\n // Restore previous state\n if (roomHistory.hasOwnProperty(\"state\")) {\n try {\n const rawState = JSON.parse(roomHistory.state);\n logger.debug(`\uD83D\uDCCB room '${roomId}' state =>`, rawState);\n\n (recreatedRoom.state as Schema).restore(rawState);\n\n // Restore the encoder's nextUniqueId so refIds increase\n // monotonically across HMR cycles. Without this, restore()\n // always produces the same refIds (0,1,2,3...) and onJoin()\n // always assigns the same next refIds (4,5...), causing the\n // client decoder to reuse stale instances on the 2nd+ cycle.\n if (roomHistory.nextRefId !== undefined) {\n const encoderRoot = recreatedRoom.state[$changes]?.root;\n if (encoderRoot && roomHistory.nextRefId > encoderRoot['nextUniqueId']) {\n encoderRoot['nextUniqueId'] = roomHistory.nextRefId;\n }\n }\n } catch (e: any) {\n debugAndPrintError(`\u274C couldn't restore room '${roomId}' state:\\n${e.stack}`);\n }\n }\n\n // Reserve seats for clients from cached history.\n // Skip entries without a reconnectionToken \u2014 these are stale\n // seats from allowReconnection() where the client already left\n // (e.g. page refresh). Restoring them would block room disposal.\n if (roomHistory.clients) {\n for (const clientData of roomHistory.clients) {\n const { sessionId, reconnectionToken } = clientData;\n if (!reconnectionToken) { continue; }\n // TODO: need to restore each client's StateView as well\n await remoteRoomCall(recreatedRoomListing.roomId, '_reserveSeat', [sessionId, {}, {}, recreatedRoom.seatReservationTimeout, false, reconnectionToken]);\n }\n }\n\n // call `onRestoreRoom` with custom 'cache'd property.\n recreatedRoom.onRestoreRoom?.(roomHistory[\"cache\"]);\n\n logger.debug(`\uD83D\uDD04 room '${roomId}' has been restored with ${roomHistory.clients?.length || 0} reserved seats: ${roomHistory.clients?.map((c: any) => c.sessionId).join(\", \")}`);\n }\n\n if (roomHistoryList.length > 0) {\n logger.debug(\"\u2705\", roomHistoryList.length, \"room(s) have been restored.\");\n }\n}\n\nexport async function cacheRoomHistory(rooms: { [roomId: string]: Room }) {\n for (const room of Object.values(rooms)) {\n const roomHistoryResult = await presence.hget(getRoomRestoreListKey(), room.roomId);\n if (roomHistoryResult) {\n try {\n const roomHistory = JSON.parse(roomHistoryResult);\n\n // custom cache method\n roomHistory[\"cache\"] = room.onCacheRoom?.();\n\n // encode state\n debugDevMode(\"caching room %s (%s)\", room.roomName, room.roomId);\n\n if (room.state) {\n roomHistory[\"state\"] = JSON.stringify(room.state);\n\n // Cache the encoder's nextUniqueId so it can be restored.\n // This ensures refIds increase monotonically across HMR cycles,\n // preventing the client decoder from reusing stale refs that\n // happen to have the same refId as newly created instances.\n const encoderRoot = room.state[$changes]?.root;\n if (encoderRoot) {\n roomHistory[\"nextRefId\"] = encoderRoot['nextUniqueId'];\n }\n }\n\n // cache active clients with their reconnection tokens\n // TODO: need to cache each client's StateView as well\n const activeClients = room.clients.map((client) => ({\n sessionId: client.sessionId,\n reconnectionToken: client.reconnectionToken,\n }));\n\n // collect active client sessionIds to avoid duplicates\n const activeSessionIds = new Set(activeClients.map((c) => c.sessionId));\n\n // also cache reserved seats (they don't have reconnectionTokens yet)\n // filter out reserved seats that are already active clients (from devMode reconnection)\n const reservedSeats = Object.keys(room['_reservedSeats'])\n .filter((sessionId) => !activeSessionIds.has(sessionId))\n .map((sessionId) => ({\n sessionId,\n reconnectionToken: undefined,\n }));\n\n roomHistory[\"clients\"] = activeClients.concat(reservedSeats);\n\n await presence.hset(getRoomRestoreListKey(), room.roomId, JSON.stringify(roomHistory));\n\n // Rewrite updated room history\n logger.debug(`\uD83D\uDCBE caching room '${room.roomId}' (clients: ${room.clients.length}, has state: ${roomHistory[\"state\"] !== undefined ? \"yes\" : \"no\"})`);\n\n } catch (e: any) {\n debugAnd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AAE;AAAA,MAClF;AAAA,IACF;AAAA,EACF;AACF;AAEO,SAAS,wBAAwB;AACtC,SAAO;AACT;",
|
|
6
6
|
"names": ["path", "fs"]
|
|
7
7
|
}
|
package/build/utils/DevMode.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import path from "path";
|
|
|
4
4
|
import { $changes } from "@colyseus/schema";
|
|
5
5
|
import { logger } from "../Logger.mjs";
|
|
6
6
|
import { debugAndPrintError, debugDevMode } from "../Debug.mjs";
|
|
7
|
-
import { getLocalRoomById, handleCreateRoom, presence, remoteRoomCall } from "../MatchMaker.mjs";
|
|
7
|
+
import { getLocalRoomById, handleCreateRoom, MatchMakerState, presence, remoteRoomCall, state } from "../MatchMaker.mjs";
|
|
8
8
|
var DEVMODE_CACHE_FILE_PATH = path.resolve(".devmode.json");
|
|
9
9
|
var isDevMode = false;
|
|
10
10
|
function hasDevModeCache() {
|
|
@@ -33,6 +33,9 @@ async function reloadFromCache() {
|
|
|
33
33
|
recreatedRoomListing = await handleCreateRoom(roomHistory.roomName, roomHistory.clientOptions, roomId);
|
|
34
34
|
recreatedRoom = getLocalRoomById(recreatedRoomListing.roomId);
|
|
35
35
|
} catch (e) {
|
|
36
|
+
if (state === MatchMakerState.SHUTTING_DOWN) {
|
|
37
|
+
break;
|
|
38
|
+
}
|
|
36
39
|
debugAndPrintError(`\u274C couldn't restore room '${roomId}':
|
|
37
40
|
${e.stack}`);
|
|
38
41
|
await presence.hdel(getRoomRestoreListKey(), roomId);
|