sonamu 0.13.8 → 0.13.10

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.
Files changed (46) hide show
  1. package/dist/database/base-model.d.ts +5 -8
  2. package/dist/database/base-model.d.ts.map +1 -1
  3. package/dist/database/base-model.js +56 -24
  4. package/dist/database/puri.d.ts +1 -2
  5. package/dist/database/puri.d.ts.map +1 -1
  6. package/dist/database/puri.js +65 -58
  7. package/dist/entity/entity.d.ts +13 -1
  8. package/dist/entity/entity.d.ts.map +1 -1
  9. package/dist/entity/entity.js +42 -4
  10. package/dist/stream/__tests__/ws-test-helpers.d.ts +2 -1
  11. package/dist/stream/__tests__/ws-test-helpers.d.ts.map +1 -1
  12. package/dist/stream/__tests__/ws-test-helpers.js +5 -1
  13. package/dist/stream/ws-cluster-bus.d.ts +21 -3
  14. package/dist/stream/ws-cluster-bus.d.ts.map +1 -1
  15. package/dist/stream/ws-cluster-bus.js +1 -1
  16. package/dist/stream/ws-delivery.d.ts +11 -0
  17. package/dist/stream/ws-delivery.d.ts.map +1 -1
  18. package/dist/stream/ws-delivery.js +95 -4
  19. package/dist/stream/ws-presence-index.d.ts +2 -0
  20. package/dist/stream/ws-presence-index.d.ts.map +1 -1
  21. package/dist/stream/ws-presence-index.js +9 -3
  22. package/dist/stream/ws-presence-store.d.ts +2 -0
  23. package/dist/stream/ws-presence-store.d.ts.map +1 -1
  24. package/dist/stream/ws-presence-store.js +4 -1
  25. package/dist/stream/ws-registry.d.ts +12 -0
  26. package/dist/stream/ws-registry.d.ts.map +1 -1
  27. package/dist/stream/ws-registry.js +49 -3
  28. package/dist/stream/ws.d.ts +2 -1
  29. package/dist/stream/ws.d.ts.map +1 -1
  30. package/dist/stream/ws.js +4 -1
  31. package/package.json +1 -1
  32. package/src/database/__tests__/puri-hydration.test.ts +113 -76
  33. package/src/database/base-model.ts +75 -43
  34. package/src/database/puri.ts +84 -106
  35. package/src/entity/__tests__/entity-subset-query.test.ts +118 -0
  36. package/src/entity/entity.ts +64 -3
  37. package/src/stream/__tests__/ws-contracts.test.ts +1 -0
  38. package/src/stream/__tests__/ws-leave-user.test.ts +293 -0
  39. package/src/stream/__tests__/ws-multinode.test.ts +3 -1
  40. package/src/stream/__tests__/ws-test-helpers.ts +6 -0
  41. package/src/stream/ws-cluster-bus.ts +26 -3
  42. package/src/stream/ws-delivery.ts +117 -6
  43. package/src/stream/ws-presence-index.ts +10 -1
  44. package/src/stream/ws-presence-store.ts +6 -0
  45. package/src/stream/ws-registry.ts +78 -2
  46. package/src/stream/ws.ts +9 -0
@@ -43,6 +43,7 @@ function createEnvelope(input: {
43
43
  frames: Record<string, string>;
44
44
  }): WebSocketClusterEnvelope {
45
45
  return {
46
+ kind: "publish",
46
47
  id: input.id,
47
48
  sourceNodeId: input.sourceNodeId ?? "node-b",
48
49
  targetNodeIds: input.targetNodeIds ?? ["node-a"],
@@ -0,0 +1,293 @@
1
+ import { afterEach, describe, expect, it } from "vitest";
2
+ import { z } from "zod";
3
+
4
+ import { createWebSocketRuntime, type WebSocketRuntime } from "../ws";
5
+ import {
6
+ type WebSocketClusterEnvelopeHandler,
7
+ type WebSocketClusterSubscribeOptions,
8
+ type WebSocketClusterLeaveUserEnvelope,
9
+ type WebSocketClusterPublishEnvelope,
10
+ } from "../ws-cluster-bus";
11
+ import { InMemoryWebSocketPresenceStore } from "../ws-presence-store";
12
+ import {
13
+ asWebSocket,
14
+ createDeferred,
15
+ FakeWebSocket,
16
+ flushAsync,
17
+ InProcessClusterNetwork,
18
+ isSettled,
19
+ RecordingClusterBus,
20
+ ScriptedPresenceStore,
21
+ } from "./ws-test-helpers";
22
+
23
+ const outEvents = z.object({ message: z.object({ text: z.string() }) });
24
+ const runtimes: WebSocketRuntime[] = [];
25
+
26
+ function createRuntime(options: Parameters<typeof createWebSocketRuntime>[0] = {}) {
27
+ const runtime = createWebSocketRuntime({ telemetry: true, ...options });
28
+ runtime.registerRoute("/chat", { outEvents });
29
+ runtimes.push(runtime);
30
+ return runtime;
31
+ }
32
+
33
+ async function connect(
34
+ runtime: WebSocketRuntime,
35
+ userId: number | string,
36
+ namespace = "chat",
37
+ active = true,
38
+ ) {
39
+ const socket = new FakeWebSocket();
40
+ const connection = await runtime.registerConnection(asWebSocket(socket), {
41
+ routeKey: "/chat",
42
+ namespace,
43
+ active,
44
+ heartbeat: 0,
45
+ outEvents,
46
+ inEvents: z.object({}),
47
+ });
48
+ await connection.setUserId(userId);
49
+ await connection.join("room");
50
+ return { socket, connection };
51
+ }
52
+
53
+ afterEach(async () => {
54
+ await Promise.all(runtimes.splice(0).map((runtime) => runtime.shutdown()));
55
+ });
56
+
57
+ describe("사용자 방 퇴장", () => {
58
+ it("여러 세션을 동기로 퇴장시키되 다른 방과 사용자 및 namespace를 보존한다", async () => {
59
+ const runtime = createRuntime();
60
+ const first = await connect(runtime, 1);
61
+ const second = await connect(runtime, 1);
62
+ const admin = await connect(runtime, 1, "admin");
63
+ const stringUser = await connect(runtime, "1");
64
+ const other = await connect(runtime, 2);
65
+ const inactive = await connect(runtime, 1, "chat", false);
66
+ await first.connection.join("other");
67
+ const result = runtime.leaveUser(1, "room", "chat");
68
+ for (const member of [first, second, inactive]) {
69
+ expect(runtime.registry.getConnection(member.connection.id)?.rooms.has("room")).toBe(false);
70
+ }
71
+ expect(runtime.registry.getConnection(first.connection.id)?.rooms.has("other")).toBe(true);
72
+ for (const member of [admin, stringUser, other]) {
73
+ expect(runtime.registry.getConnection(member.connection.id)?.rooms.has("room")).toBe(true);
74
+ }
75
+ await expect(result).resolves.toEqual({
76
+ localLeftCount: 3,
77
+ targetNodeCount: 0,
78
+ partial: false,
79
+ });
80
+ await expect(runtime.leaveUser(1, "room")).resolves.toEqual({
81
+ localLeftCount: 1,
82
+ targetNodeCount: 0,
83
+ partial: false,
84
+ });
85
+ await expect(runtime.leaveUser("missing", "room")).resolves.toEqual({
86
+ localLeftCount: 0,
87
+ targetNodeCount: 0,
88
+ partial: false,
89
+ });
90
+ expect(runtime.registry.getConnection(stringUser.connection.id)?.rooms.has("room")).toBe(true);
91
+ });
92
+
93
+ it("store 반영을 기다리고 실패하면 로컬 변경을 유지하며 partial을 반환한다", async () => {
94
+ const store = new ScriptedPresenceStore();
95
+ const runtime = createRuntime({ presenceStore: store });
96
+ const member = await connect(runtime, 1);
97
+ const gate = createDeferred();
98
+ store.next("leave", () => gate.promise);
99
+ const pending = runtime.leaveUser(1, "room");
100
+ expect(runtime.registry.getConnection(member.connection.id)?.rooms.has("room")).toBe(false);
101
+ expect(await isSettled(pending)).toBe(false);
102
+ gate.reject(new Error("store"));
103
+ await expect(pending).resolves.toMatchObject({ localLeftCount: 1, partial: true });
104
+ });
105
+
106
+ it("세 노드의 제어 메시지가 뒤따르는 방 publish보다 먼저 전달된다", async () => {
107
+ const store = new InMemoryWebSocketPresenceStore();
108
+ const scripted = new ScriptedPresenceStore(store);
109
+ const network = new InProcessClusterNetwork();
110
+ const [a, b, c] = ["a", "b", "c"].map((nodeId) =>
111
+ createRuntime({
112
+ nodeId,
113
+ presenceStore: nodeId === "a" ? scripted : store,
114
+ clusterBus: network.bus(nodeId),
115
+ }),
116
+ );
117
+ const targetB = await connect(b, 1);
118
+ const targetC = await connect(c, 1);
119
+ const otherB = await connect(b, "1");
120
+ const otherC = await connect(c, 2);
121
+ await flushAsync();
122
+ // 노드 조회를 방 publish가 큐에 들어간 뒤에야 끝내, 제어 메시지가 큐를 우회하면 순서가 뒤집히게 한다
123
+ const routeGate = createDeferred();
124
+ scripted.next("getLiveNodeIds", () => routeGate.promise);
125
+ const leaving = a.leaveUser(1, "room");
126
+ const publishing = a.publishToRoom("room", "message", { text: "after" });
127
+ routeGate.resolve();
128
+ await expect(leaving).resolves.toEqual({
129
+ localLeftCount: 0,
130
+ targetNodeCount: 2,
131
+ partial: false,
132
+ });
133
+ await publishing;
134
+ await flushAsync(10);
135
+ expect(network.published.map((envelope) => envelope.kind)).toEqual(["leaveUser", "publish"]);
136
+ expect(targetB.socket.sentMessages).toEqual([]);
137
+ expect(targetC.socket.sentMessages).toEqual([]);
138
+ expect(otherB.socket.sentMessages).toHaveLength(1);
139
+ expect(otherC.socket.sentMessages).toHaveLength(1);
140
+ await expect(a.registry.getRoomMemberCount("room")).resolves.toEqual({
141
+ count: 2,
142
+ partial: false,
143
+ });
144
+ });
145
+
146
+ it("사용자 replica가 지연돼도 모든 live 노드에 퇴장을 전달한다", async () => {
147
+ const shared = new InMemoryWebSocketPresenceStore();
148
+ const delayed = new ScriptedPresenceStore(shared);
149
+ const network = new InProcessClusterNetwork();
150
+ const a = createRuntime({ nodeId: "a", presenceStore: shared, clusterBus: network.bus("a") });
151
+ const b = createRuntime({ nodeId: "b", presenceStore: delayed, clusterBus: network.bus("b") });
152
+ const member = await connect(b, "before");
153
+ const gate = createDeferred();
154
+ delayed.next("setUserId", () => gate.promise);
155
+ const binding = member.connection.setUserId(1);
156
+ expect(shared.resolveRoute({ type: "user", userId: 1 }, "a").remoteNodeIds).toEqual([]);
157
+ await expect(a.leaveUser(1, "room")).resolves.toMatchObject({
158
+ targetNodeCount: 1,
159
+ partial: false,
160
+ });
161
+ await flushAsync();
162
+ expect(b.registry.getConnection(member.connection.id)?.rooms.has("room")).toBe(false);
163
+ gate.resolve();
164
+ await binding;
165
+ await flushAsync();
166
+ expect(shared.getRoomMemberCount("room")).toBe(0);
167
+ });
168
+
169
+ it("구독 거절 사유는 원문 payload 없이 telemetry에 기록한다", async () => {
170
+ class RejectionBus extends RecordingClusterBus {
171
+ override subscribe(
172
+ handler: WebSocketClusterEnvelopeHandler,
173
+ options?: WebSocketClusterSubscribeOptions,
174
+ ) {
175
+ options?.onRejected?.({ reason: "invalidEnvelope", raw: "sensitive".repeat(100) });
176
+ return super.subscribe(handler);
177
+ }
178
+ }
179
+ const runtime = createRuntime({ clusterBus: new RejectionBus() });
180
+ await flushAsync();
181
+ const event = runtime.telemetryController
182
+ .getEventStore()
183
+ ?.query({ name: "ws.cluster.envelope.rejected" })[0];
184
+ expect(event?.detail).toEqual({ reason: "invalidEnvelope" });
185
+ expect(event?.level).toBe("warn");
186
+ });
187
+
188
+ it("노드 조회 실패와 publish 거절을 partial로 반환하고 시도한 노드 수를 보존한다", async () => {
189
+ const store = new ScriptedPresenceStore();
190
+ const bus = new RecordingClusterBus();
191
+ const runtime = createRuntime({ nodeId: "a", presenceStore: store, clusterBus: bus });
192
+ store.next("getLiveNodeIds", () => {
193
+ throw new Error("route");
194
+ });
195
+ await expect(runtime.leaveUser(1, "room")).resolves.toEqual({
196
+ localLeftCount: 0,
197
+ targetNodeCount: 0,
198
+ partial: true,
199
+ });
200
+ await store.register({
201
+ sessionId: "remote",
202
+ nodeId: "b",
203
+ namespace: "chat",
204
+ active: true,
205
+ connectedAt: new Date(),
206
+ });
207
+ bus.publish = () => Promise.reject(new Error("publish"));
208
+ await expect(runtime.leaveUser(1, "room")).resolves.toEqual({
209
+ localLeftCount: 0,
210
+ targetNodeCount: 1,
211
+ partial: true,
212
+ });
213
+ expect(
214
+ runtime.telemetryController
215
+ .getEventStore()
216
+ ?.query({ name: "ws.cluster.control.failed" })
217
+ .map((event) => event.detail?.stage),
218
+ ).toEqual(["route", "publish"]);
219
+ });
220
+
221
+ it("선택적 노드 조회가 없는 store는 사용자 라우팅으로 대체한다", async () => {
222
+ const store = new ScriptedPresenceStore();
223
+ Object.defineProperty(store, "getLiveNodeIds", { value: undefined });
224
+ const runtime = createRuntime({ presenceStore: store });
225
+ await runtime.leaveUser(1, "room", "chat");
226
+ expect(store.callsOf("resolveRoute")).toHaveLength(1);
227
+ store.next("resolveRoute", () => Promise.reject(new Error("route")));
228
+ await expect(runtime.leaveUser(1, "room")).resolves.toMatchObject({ partial: true });
229
+ });
230
+
231
+ it("알 수 없는 kind의 envelope은 publish로 처리하지 않고 거절한다", async () => {
232
+ const bus = new RecordingClusterBus();
233
+ const runtime = createRuntime({ nodeId: "a", clusterBus: bus });
234
+ await connect(runtime, 1);
235
+ const base: WebSocketClusterPublishEnvelope = {
236
+ kind: "publish",
237
+ id: "x",
238
+ sourceNodeId: "b",
239
+ targetNodeIds: ["a"],
240
+ audience: { type: "room", roomId: "room" },
241
+ event: "message",
242
+ frames: {},
243
+ emittedAt: 0,
244
+ };
245
+ // SAFETY: 미래 버전 wire payload의 알 수 없는 kind를 재현한다
246
+ const future = { ...base, kind: "future" } as WebSocketClusterPublishEnvelope;
247
+ await expect(bus.emit(future)).resolves.toBeUndefined();
248
+ const store = runtime.telemetryController.getEventStore();
249
+ const rejected = store?.query({ name: "ws.cluster.envelope.rejected" });
250
+ expect(rejected).toHaveLength(1);
251
+ expect(rejected?.[0].detail).toEqual({ reason: "unknownKind" });
252
+ expect(store?.query({ name: "ws.cluster.envelope.received" })).toHaveLength(0);
253
+ });
254
+
255
+ it("제어 메시지도 자기 노드와 대상 불일치를 무시하고 kind 없는 기존 publish를 수신한다", async () => {
256
+ const bus = new RecordingClusterBus();
257
+ const runtime = createRuntime({ nodeId: "a", clusterBus: bus });
258
+ const target = await connect(runtime, 1);
259
+ const control: WebSocketClusterLeaveUserEnvelope = {
260
+ kind: "leaveUser",
261
+ id: "control",
262
+ sourceNodeId: "a",
263
+ targetNodeIds: ["a"],
264
+ userId: 1,
265
+ roomId: "room",
266
+ emittedAt: 0,
267
+ };
268
+ await bus.emit(control);
269
+ await bus.emit({ ...control, sourceNodeId: "b", targetNodeIds: ["c"] });
270
+ expect(runtime.registry.getConnection(target.connection.id)?.rooms.has("room")).toBe(true);
271
+ const publish: WebSocketClusterPublishEnvelope = {
272
+ kind: "publish",
273
+ id: "legacy",
274
+ sourceNodeId: "b",
275
+ targetNodeIds: ["a"],
276
+ audience: { type: "room", roomId: "room" },
277
+ event: "message",
278
+ frames: { "/chat": '{"event":"message","data":{"text":"legacy"}}' },
279
+ emittedAt: 0,
280
+ };
281
+ const { kind: _kind, ...legacy } = publish;
282
+ // SAFETY: publish 필드는 위에서 구성했고 구버전 wire payload의 누락된 kind만 재현한다
283
+ await bus.emit(legacy as WebSocketClusterPublishEnvelope);
284
+ await flushAsync();
285
+ expect(target.socket.sentMessages).toHaveLength(1);
286
+ await bus.emit({ ...control, sourceNodeId: "b" });
287
+ expect(runtime.registry.getConnection(target.connection.id)?.rooms.has("room")).toBe(false);
288
+ expect(
289
+ runtime.telemetryController.getEventStore()?.query({ name: "ws.cluster.control.received" })[0]
290
+ .detail?.localLeftCount,
291
+ ).toBe(1);
292
+ });
293
+ });
@@ -114,7 +114,9 @@ describe("WebSocket 멀티 노드 전달", () => {
114
114
  expect(b2.socket.sentMessages).toEqual([]);
115
115
  expect(network.published).toHaveLength(1);
116
116
  expect(network.published[0].targetNodeIds).toEqual(["node-b"]);
117
- expect(network.published[0].frames["/chat"]).toBe(a1.socket.sentMessages[0]);
117
+ expect(network.published[0].kind === "publish" && network.published[0].frames["/chat"]).toBe(
118
+ a1.socket.sentMessages[0],
119
+ );
118
120
  expect(nodeB.store.calls.slice(nodeBCallsBefore)).toEqual([]);
119
121
  expect(nodeA.store.callsOf("resolveRoute")).toEqual(["resolveRoute:node-a:room"]);
120
122
  });
@@ -138,6 +138,7 @@ type ScriptedMethod =
138
138
  | "clearUserId"
139
139
  | "join"
140
140
  | "leave"
141
+ | "getLiveNodeIds"
141
142
  | "resolveRoute"
142
143
  | "getRoomMemberCount"
143
144
  | "shutdown";
@@ -225,6 +226,11 @@ export class ScriptedPresenceStore {
225
226
  return this.run("resolveRoute", () => this.inner.resolveRoute(audience, nodeId));
226
227
  }
227
228
 
229
+ getLiveNodeIds(): string[] | Promise<string[]> {
230
+ this.calls.push("getLiveNodeIds");
231
+ return this.run("getLiveNodeIds", () => this.inner.getLiveNodeIds());
232
+ }
233
+
228
234
  getRoomMemberCount(roomId: WebSocketRoomId, namespace?: string): number | Promise<number> {
229
235
  this.calls.push(`getRoomMemberCount:${roomId}`);
230
236
  return this.run("getRoomMemberCount", () => this.inner.getRoomMemberCount(roomId, namespace));
@@ -1,11 +1,12 @@
1
1
  import { type WebSocketAudience } from "./ws-audience";
2
- import { type MaybePromise } from "./ws-core";
2
+ import { type WebSocketUserId, type MaybePromise } from "./ws-core";
3
3
 
4
4
  /**
5
5
  * 노드 간 publish envelope. 원본 data 대신 발행 노드가 route별로 한 번 검증·인코딩한 frame을 싣는다.
6
6
  * 수신 노드는 자기 메모리로 audience를 해석하고, 각 연결의 route frame을 재검증 없이 그대로 보낸다.
7
7
  */
8
- export type WebSocketClusterEnvelope = {
8
+ export type WebSocketClusterPublishEnvelope = {
9
+ kind: "publish";
9
10
  id: string;
10
11
  sourceNodeId: string;
11
12
  targetNodeIds: string[];
@@ -16,6 +17,25 @@ export type WebSocketClusterEnvelope = {
16
17
  emittedAt: number;
17
18
  };
18
19
 
20
+ export type WebSocketClusterLeaveUserEnvelope = {
21
+ kind: "leaveUser";
22
+ id: string;
23
+ sourceNodeId: string;
24
+ targetNodeIds: string[];
25
+ userId: WebSocketUserId;
26
+ roomId: string;
27
+ namespace?: string;
28
+ emittedAt: number;
29
+ };
30
+
31
+ export type WebSocketClusterEnvelope =
32
+ | WebSocketClusterPublishEnvelope
33
+ | WebSocketClusterLeaveUserEnvelope;
34
+
35
+ export type WebSocketClusterSubscribeOptions = {
36
+ onRejected?: (info: { reason: string; raw?: string }) => void;
37
+ };
38
+
19
39
  export type WebSocketClusterEnvelopeHandler = (
20
40
  envelope: WebSocketClusterEnvelope,
21
41
  ) => void | Promise<void>;
@@ -25,7 +45,10 @@ export interface WebSocketClusterBus {
25
45
  readonly nodeId?: string;
26
46
  publish(envelope: WebSocketClusterEnvelope): void | Promise<void>;
27
47
  // 구독 완료를 promise로 알릴 수 있다. 반환한 해제 함수는 runtime shutdown에서 한 번 호출된다
28
- subscribe(handler: WebSocketClusterEnvelopeHandler): MaybePromise<() => void>;
48
+ subscribe(
49
+ handler: WebSocketClusterEnvelopeHandler,
50
+ options?: WebSocketClusterSubscribeOptions,
51
+ ): MaybePromise<() => void>;
29
52
  shutdown(): void | Promise<void>;
30
53
  }
31
54
 
@@ -6,7 +6,7 @@ import { runtimeTypeOf } from "../runtime-type";
6
6
  import { type WebSocketAudience } from "./ws-audience";
7
7
  import { type WebSocketAudienceResolver } from "./ws-audience-resolver";
8
8
  import { type WebSocketClusterBus, type WebSocketClusterEnvelope } from "./ws-cluster-bus";
9
- import { type WebSocketFrameConnection } from "./ws-core";
9
+ import { type WebSocketUserId, type WebSocketFrameConnection } from "./ws-core";
10
10
  import { encodeWebSocketFrame, type WebSocketFrameEncoding } from "./ws-frame";
11
11
  import { type WebSocketLocalConnectionStore } from "./ws-local-connection-store";
12
12
  import {
@@ -53,6 +53,15 @@ export class WebSocketDeliveryEngine {
53
53
  localConnections: WebSocketLocalConnectionStore;
54
54
  // registry 메모리 기준으로 audience에 속한 로컬 활성 세션 ID를 반환한다
55
55
  resolveLocalSessionIds: (audience: WebSocketAudience) => string[];
56
+ leaveLocalUser: (
57
+ userId: WebSocketUserId,
58
+ roomId: string,
59
+ namespace?: string,
60
+ ) => {
61
+ localLeftCount: number;
62
+ completion: Promise<boolean>;
63
+ };
64
+ resolveControlNodeIds: (userId: WebSocketUserId, namespace?: string) => Promise<string[]>;
56
65
  audienceResolver: WebSocketAudienceResolver;
57
66
  clusterBus: WebSocketClusterBus;
58
67
  telemetryController?: WebSocketTelemetryController;
@@ -161,6 +170,59 @@ export class WebSocketDeliveryEngine {
161
170
  }
162
171
  }
163
172
 
173
+ publishLeaveUser(
174
+ userId: WebSocketUserId,
175
+ roomId: string,
176
+ namespace?: string,
177
+ ): Promise<{ targetNodeCount: number; partial: boolean }> {
178
+ const routing = Promise.resolve()
179
+ .then(() => this.options.resolveControlNodeIds(userId, namespace))
180
+ .catch((cause: unknown) => {
181
+ this.emitControlFailed("route", cause);
182
+ return undefined;
183
+ });
184
+ const task = this.publishQueue.then(async () => {
185
+ const targetNodeIds = await routing;
186
+ if (!targetNodeIds) {
187
+ return { targetNodeCount: 0, partial: true };
188
+ }
189
+ if (targetNodeIds.length === 0) {
190
+ return { targetNodeCount: 0, partial: false };
191
+ }
192
+ try {
193
+ await this.options.clusterBus.publish({
194
+ kind: "leaveUser",
195
+ id: randomUUID(),
196
+ sourceNodeId: this.options.nodeId,
197
+ targetNodeIds,
198
+ userId,
199
+ roomId,
200
+ namespace,
201
+ emittedAt: Date.now(),
202
+ });
203
+ this.telemetry.emit({
204
+ name: "ws.cluster.control.published",
205
+ level: "debug",
206
+ detail: { userId, roomId, namespace, targetNodeCount: targetNodeIds.length },
207
+ });
208
+ return { targetNodeCount: targetNodeIds.length, partial: false };
209
+ } catch (cause) {
210
+ this.emitControlFailed("publish", cause);
211
+ return { targetNodeCount: targetNodeIds.length, partial: true };
212
+ }
213
+ });
214
+ this.publishQueue = task.then(() => undefined);
215
+ return task;
216
+ }
217
+
218
+ private emitControlFailed(stage: "route" | "publish", cause: unknown): void {
219
+ this.telemetry.emit({
220
+ name: "ws.cluster.control.failed",
221
+ level: "warn",
222
+ detail: { stage, errorType: describeError(cause) },
223
+ });
224
+ }
225
+
164
226
  // 진행 중인 publish(원격 포함)와 구독 시도가 모두 끝나면 resolve한다
165
227
  async drainPublishes(): Promise<void> {
166
228
  await Promise.all([this.publishQueue, this.subscription]);
@@ -210,9 +272,20 @@ export class WebSocketDeliveryEngine {
210
272
  private subscribe(): Promise<Unsubscribe | undefined> {
211
273
  return Promise.resolve()
212
274
  .then(() =>
213
- this.options.clusterBus.subscribe((envelope) => {
214
- this.handleClusterEnvelope(envelope);
215
- }),
275
+ this.options.clusterBus.subscribe(
276
+ (envelope) => {
277
+ this.handleClusterEnvelope(envelope);
278
+ },
279
+ {
280
+ onRejected: ({ reason }) => {
281
+ this.telemetry.emit({
282
+ name: "ws.cluster.envelope.rejected",
283
+ level: "warn",
284
+ detail: { reason },
285
+ });
286
+ },
287
+ },
288
+ ),
216
289
  )
217
290
  .then(
218
291
  (unsubscribe) => unsubscribe,
@@ -265,6 +338,7 @@ export class WebSocketDeliveryEngine {
265
338
  }
266
339
 
267
340
  const envelope: WebSocketClusterEnvelope = {
341
+ kind: "publish",
268
342
  id: randomUUID(),
269
343
  sourceNodeId: this.options.nodeId,
270
344
  targetNodeIds: remoteNodeIds,
@@ -317,11 +391,25 @@ export class WebSocketDeliveryEngine {
317
391
  return;
318
392
  }
319
393
 
394
+ // 구독자가 모르는 kind는 publish로 오인하지 않고 거절한다. kind가 없으면 구버전 publish다
395
+ const kind: unknown = envelope.kind;
396
+ if (kind !== undefined && kind !== "publish" && kind !== "leaveUser") {
397
+ this.telemetry.emit({
398
+ name: "ws.cluster.envelope.rejected",
399
+ level: "warn",
400
+ detail: { reason: "unknownKind" },
401
+ });
402
+ return;
403
+ }
404
+
320
405
  if (envelope.sourceNodeId === this.options.nodeId) {
321
406
  this.telemetry.emit({
322
407
  name: "ws.cluster.envelope.ignored",
323
408
  level: "debug",
324
- detail: { reason: "selfSource", event: envelope.event },
409
+ detail: {
410
+ reason: "selfSource",
411
+ event: envelope.kind === "leaveUser" ? undefined : envelope.event,
412
+ },
325
413
  });
326
414
  return;
327
415
  }
@@ -333,7 +421,30 @@ export class WebSocketDeliveryEngine {
333
421
  this.telemetry.emit({
334
422
  name: "ws.cluster.envelope.ignored",
335
423
  level: "debug",
336
- detail: { reason: "targetMismatch", event: envelope.event },
424
+ detail: {
425
+ reason: "targetMismatch",
426
+ event: envelope.kind === "leaveUser" ? undefined : envelope.event,
427
+ },
428
+ });
429
+ return;
430
+ }
431
+
432
+ if (envelope.kind === "leaveUser") {
433
+ const local = this.options.leaveLocalUser(
434
+ envelope.userId,
435
+ envelope.roomId,
436
+ envelope.namespace,
437
+ );
438
+ this.telemetry.emit({
439
+ name: "ws.cluster.control.received",
440
+ level: "debug",
441
+ detail: {
442
+ userId: envelope.userId,
443
+ roomId: envelope.roomId,
444
+ namespace: envelope.namespace,
445
+ sourceNodeId: envelope.sourceNodeId,
446
+ localLeftCount: local.localLeftCount,
447
+ },
337
448
  });
338
449
  return;
339
450
  }
@@ -132,6 +132,14 @@ export class WebSocketPresenceIndex {
132
132
  return this.getBoundSessions(this.rooms, roomId, namespace).length;
133
133
  }
134
134
 
135
+ getLiveNodeIds(): string[] {
136
+ return [...new Set([...this.sessions.values()].map((session) => session.nodeId))];
137
+ }
138
+
139
+ getUserSessions(userId: WebSocketUserId, namespace?: string): WebSocketSessionPresence[] {
140
+ return this.getBoundSessions(this.users, userId, namespace, true).map(copyPresence);
141
+ }
142
+
135
143
  getStats(): WebSocketRegistryStats {
136
144
  const byNamespace: Record<string, number> = {};
137
145
  let totalConnections = 0;
@@ -199,6 +207,7 @@ export class WebSocketPresenceIndex {
199
207
  index: BindingIndex<Id>,
200
208
  id: Id,
201
209
  namespace?: string,
210
+ includeInactive = false,
202
211
  ): PresenceRecord[] {
203
212
  // namespace가 없으면(빈 문자열 포함) 모든 namespace의 바인딩을 본다
204
213
  const namespaces = namespace ? [index.get(namespace)] : [...index.values()];
@@ -213,7 +222,7 @@ export class WebSocketPresenceIndex {
213
222
  seen.add(sessionId);
214
223
 
215
224
  const record = this.sessions.get(sessionId);
216
- if (record?.active) {
225
+ if (record && (record.active || includeInactive)) {
217
226
  records.push(record);
218
227
  }
219
228
  }
@@ -48,6 +48,8 @@ export interface WebSocketPresenceStore {
48
48
  resolveRoute(audience: WebSocketAudience, nodeId: string): MaybePromise<WebSocketRoutingPlan>;
49
49
  // 클러스터 전체의 활성 방 인원수
50
50
  getRoomMemberCount(roomId: WebSocketRoomId, namespace?: string): MaybePromise<number>;
51
+ // 사용자 제어 메시지는 해당 사용자의 replica 유무와 무관하게 모든 live 노드에 전송한다
52
+ getLiveNodeIds?(): MaybePromise<string[]>;
51
53
  shutdown?(): MaybePromise<void>;
52
54
  }
53
55
 
@@ -100,6 +102,10 @@ export class InMemoryWebSocketPresenceStore implements WebSocketPresenceStore {
100
102
  return { localSessionIds, remoteNodeIds: [...remoteNodeIds] };
101
103
  }
102
104
 
105
+ getLiveNodeIds(): string[] {
106
+ return this.index.getLiveNodeIds();
107
+ }
108
+
103
109
  getRoomMemberCount(roomId: WebSocketRoomId, namespace?: string): number {
104
110
  return this.index.getRoomMemberCount(roomId, namespace);
105
111
  }