sonamu 0.11.16 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (322) hide show
  1. package/dist/_virtual/_rolldown/runtime.js +1 -2
  2. package/dist/ai/agents/agent.js +2 -3
  3. package/dist/ai/agents/index.js +1 -2
  4. package/dist/ai/index.js +1 -2
  5. package/dist/ai/providers/rtzr/api.js +1 -2
  6. package/dist/ai/providers/rtzr/error.js +2 -3
  7. package/dist/ai/providers/rtzr/model.js +1 -2
  8. package/dist/ai/providers/rtzr/options.js +1 -2
  9. package/dist/ai/providers/rtzr/provider.js +1 -2
  10. package/dist/ai/providers/rtzr/utils.js +1 -2
  11. package/dist/api/base-frame.js +4 -4
  12. package/dist/api/caster.d.ts +1 -1
  13. package/dist/api/caster.d.ts.map +1 -1
  14. package/dist/api/caster.js +9 -9
  15. package/dist/api/code-converters.js +6 -5
  16. package/dist/api/config.d.ts +1 -1
  17. package/dist/api/config.d.ts.map +1 -1
  18. package/dist/api/config.js +2 -3
  19. package/dist/api/context.d.ts +2 -3
  20. package/dist/api/context.d.ts.map +1 -1
  21. package/dist/api/context.js +2 -3
  22. package/dist/api/decorators.js +2 -3
  23. package/dist/api/http-validator.js +2 -3
  24. package/dist/api/index.js +8 -3
  25. package/dist/api/secret.js +1 -2
  26. package/dist/api/sonamu.d.ts +3 -5
  27. package/dist/api/sonamu.d.ts.map +1 -1
  28. package/dist/api/sonamu.js +30 -24
  29. package/dist/api/validator.js +1 -2
  30. package/dist/api/websocket-helpers.js +2 -3
  31. package/dist/auth/audit-log/builders.js +1 -2
  32. package/dist/auth/audit-log/client-ip.js +2 -3
  33. package/dist/auth/audit-log/events.js +1 -2
  34. package/dist/auth/audit-log/plugin.d.ts.map +1 -1
  35. package/dist/auth/audit-log/plugin.js +2 -3
  36. package/dist/auth/audit-log-ingestor.js +2 -3
  37. package/dist/auth/auth-generator.js +2 -3
  38. package/dist/auth/better-auth-entities.js +1 -2
  39. package/dist/auth/better-auth-request.js +2 -3
  40. package/dist/auth/index.js +2 -3
  41. package/dist/auth/knex-adapter.js +2 -3
  42. package/dist/auth/plugins/entity-definitions/admin.js +1 -2
  43. package/dist/auth/plugins/entity-definitions/anonymous.js +1 -2
  44. package/dist/auth/plugins/entity-definitions/api-key.js +1 -2
  45. package/dist/auth/plugins/entity-definitions/audit-log.js +1 -2
  46. package/dist/auth/plugins/entity-definitions/index.js +1 -2
  47. package/dist/auth/plugins/entity-definitions/jwt.js +1 -2
  48. package/dist/auth/plugins/entity-definitions/organization.js +1 -2
  49. package/dist/auth/plugins/entity-definitions/passkey.js +1 -2
  50. package/dist/auth/plugins/entity-definitions/phone-number.js +1 -2
  51. package/dist/auth/plugins/entity-definitions/sso.js +1 -2
  52. package/dist/auth/plugins/entity-definitions/two-factor.js +1 -2
  53. package/dist/auth/plugins/entity-definitions/username.js +1 -2
  54. package/dist/auth/plugins/wrappers/admin.d.ts +33 -32
  55. package/dist/auth/plugins/wrappers/admin.d.ts.map +1 -1
  56. package/dist/auth/plugins/wrappers/admin.js +2 -3
  57. package/dist/auth/plugins/wrappers/anonymous.js +2 -3
  58. package/dist/auth/plugins/wrappers/api-key.js +2 -3
  59. package/dist/auth/plugins/wrappers/jwt.js +2 -3
  60. package/dist/auth/plugins/wrappers/organization.js +2 -3
  61. package/dist/auth/plugins/wrappers/passkey.js +2 -3
  62. package/dist/auth/plugins/wrappers/phone-number.d.ts +43 -1
  63. package/dist/auth/plugins/wrappers/phone-number.d.ts.map +1 -1
  64. package/dist/auth/plugins/wrappers/phone-number.js +2 -3
  65. package/dist/auth/plugins/wrappers/sso.d.ts +138 -187
  66. package/dist/auth/plugins/wrappers/sso.d.ts.map +1 -1
  67. package/dist/auth/plugins/wrappers/sso.js +1 -2
  68. package/dist/auth/plugins/wrappers/two-factor.d.ts +51 -10
  69. package/dist/auth/plugins/wrappers/two-factor.d.ts.map +1 -1
  70. package/dist/auth/plugins/wrappers/two-factor.js +2 -3
  71. package/dist/auth/plugins/wrappers/username.d.ts +39 -5
  72. package/dist/auth/plugins/wrappers/username.d.ts.map +1 -1
  73. package/dist/auth/plugins/wrappers/username.js +2 -3
  74. package/dist/bin/build-config.js +5 -5
  75. package/dist/bin/compiler-policy.js +2 -3
  76. package/dist/bin/fixture.js +7 -5
  77. package/dist/bin/hmr-hook-register.js +1 -2
  78. package/dist/bin/migrate-targets.js +2 -3
  79. package/dist/bin/test-command.js +2 -3
  80. package/dist/bin/ts-loader-register.js +2 -3
  81. package/dist/bin/ts-loader-registration.js +2 -3
  82. package/dist/bin/typecheck-web.js +2 -3
  83. package/dist/cache/cache-manager.js +1 -2
  84. package/dist/cache/decorator.js +2 -3
  85. package/dist/cache/drivers.js +1 -2
  86. package/dist/cache/index.js +2 -3
  87. package/dist/cache-control/cache-control.js +1 -2
  88. package/dist/code-formatting/index.js +2 -3
  89. package/dist/code-formatting/oxfmt.js +2 -3
  90. package/dist/code-formatting/oxlint.js +2 -3
  91. package/dist/compress/compress.js +1 -2
  92. package/dist/compress/index.js +2 -2
  93. package/dist/compress/types.d.ts +1 -1
  94. package/dist/compress/types.d.ts.map +1 -1
  95. package/dist/cone/cone-generator.js +2 -3
  96. package/dist/database/_batch_update.js +1 -2
  97. package/dist/database/base-model.js +4 -4
  98. package/dist/database/db.js +4 -4
  99. package/dist/database/knex.js +2 -3
  100. package/dist/database/puri-wrapper.js +2 -3
  101. package/dist/database/puri.js +23 -22
  102. package/dist/database/puri.types.js +1 -2
  103. package/dist/database/transaction-context.js +1 -2
  104. package/dist/database/upsert-builder.js +2 -3
  105. package/dist/dict/en.js +2 -3
  106. package/dist/dict/index.js +3 -3
  107. package/dist/dict/ko.js +2 -3
  108. package/dist/dict/rc-keys.js +1 -2
  109. package/dist/dict/sd.js +2 -3
  110. package/dist/dict/sonamu-dictionary.js +7 -6
  111. package/dist/dict/utils.js +2 -3
  112. package/dist/entity/entity-manager.d.ts +66 -66
  113. package/dist/entity/entity-manager.js +4 -4
  114. package/dist/entity/entity-template-cone.js +2 -3
  115. package/dist/entity/entity.js +21 -18
  116. package/dist/env.js +1 -2
  117. package/dist/exceptions/error-handler.d.ts.map +1 -1
  118. package/dist/exceptions/error-handler.js +2 -3
  119. package/dist/exceptions/so-exceptions.js +2 -3
  120. package/dist/filter/index.js +3 -2
  121. package/dist/filter/types.js +1 -2
  122. package/dist/filter/utils.js +7 -6
  123. package/dist/index.d.ts +1 -0
  124. package/dist/index.d.ts.map +1 -1
  125. package/dist/index.js +42 -6
  126. package/dist/logger/category.js +2 -3
  127. package/dist/logger/configure.js +5 -5
  128. package/dist/migration/code-generation.js +23 -16
  129. package/dist/migration/index-where-predicate.js +2 -3
  130. package/dist/migration/migration-set.js +2 -3
  131. package/dist/migration/migrator.js +2 -3
  132. package/dist/migration/postgresql-schema-reader.js +6 -9
  133. package/dist/migration/slack-confirm.js +2 -3
  134. package/dist/naite/naite-reporter.js +2 -3
  135. package/dist/naite/naite.js +10 -8
  136. package/dist/runtime-type.js +2 -3
  137. package/dist/ssr/hmr-opt-out.js +1 -2
  138. package/dist/ssr/index.js +7 -4
  139. package/dist/ssr/registry.js +1 -2
  140. package/dist/ssr/renderer.js +2 -3
  141. package/dist/storage/base-file.js +1 -2
  142. package/dist/storage/buffered-file.js +2 -3
  143. package/dist/storage/drivers.js +1 -2
  144. package/dist/storage/index.js +2 -3
  145. package/dist/storage/s3-driver.js +1 -2
  146. package/dist/storage/storage-manager.js +2 -3
  147. package/dist/storage/uploaded-file.js +2 -3
  148. package/dist/stream/__tests__/ws-test-helpers.d.ts +108 -0
  149. package/dist/stream/__tests__/ws-test-helpers.d.ts.map +1 -0
  150. package/dist/stream/__tests__/ws-test-helpers.js +259 -0
  151. package/dist/stream/index.d.ts +1 -0
  152. package/dist/stream/index.d.ts.map +1 -1
  153. package/dist/stream/index.js +15 -4
  154. package/dist/stream/sse.js +1 -2
  155. package/dist/stream/ws-audience-resolver.d.ts +8 -5
  156. package/dist/stream/ws-audience-resolver.d.ts.map +1 -1
  157. package/dist/stream/ws-audience-resolver.js +17 -15
  158. package/dist/stream/ws-audience.js +1 -2
  159. package/dist/stream/ws-cluster-bus.d.ts +9 -4
  160. package/dist/stream/ws-cluster-bus.d.ts.map +1 -1
  161. package/dist/stream/ws-cluster-bus.js +2 -3
  162. package/dist/stream/ws-core.d.ts +10 -0
  163. package/dist/stream/ws-core.d.ts.map +1 -1
  164. package/dist/stream/ws-delivery.d.ts +30 -4
  165. package/dist/stream/ws-delivery.d.ts.map +1 -1
  166. package/dist/stream/ws-delivery.js +200 -54
  167. package/dist/stream/ws-frame.d.ts +15 -0
  168. package/dist/stream/ws-frame.d.ts.map +1 -0
  169. package/dist/stream/ws-frame.js +28 -0
  170. package/dist/stream/ws-local-connection-store.d.ts +4 -4
  171. package/dist/stream/ws-local-connection-store.d.ts.map +1 -1
  172. package/dist/stream/ws-local-connection-store.js +3 -4
  173. package/dist/stream/ws-presence-index.d.ts +36 -0
  174. package/dist/stream/ws-presence-index.d.ts.map +1 -0
  175. package/dist/stream/ws-presence-index.js +176 -0
  176. package/dist/stream/ws-presence-store.d.ts +39 -39
  177. package/dist/stream/ws-presence-store.d.ts.map +1 -1
  178. package/dist/stream/ws-presence-store.js +23 -154
  179. package/dist/stream/ws-registry.d.ts +45 -17
  180. package/dist/stream/ws-registry.d.ts.map +1 -1
  181. package/dist/stream/ws-registry.js +170 -62
  182. package/dist/stream/ws-session-id.d.ts +14 -0
  183. package/dist/stream/ws-session-id.d.ts.map +1 -0
  184. package/dist/stream/ws-session-id.js +36 -0
  185. package/dist/stream/ws-telemetry-memory.js +3 -4
  186. package/dist/stream/ws-telemetry-trace.js +1 -2
  187. package/dist/stream/ws-telemetry.js +2 -3
  188. package/dist/stream/ws.d.ts +20 -10
  189. package/dist/stream/ws.d.ts.map +1 -1
  190. package/dist/stream/ws.js +60 -38
  191. package/dist/syncer/api-parser.js +2 -3
  192. package/dist/syncer/checksum.js +4 -4
  193. package/dist/syncer/code-generator.js +4 -4
  194. package/dist/syncer/entity-operations.js +2 -3
  195. package/dist/syncer/event-batcher.js +1 -2
  196. package/dist/syncer/file-copy.js +2 -3
  197. package/dist/syncer/file-patterns.js +2 -3
  198. package/dist/syncer/file-tracking.js +2 -3
  199. package/dist/syncer/filesystem-dependencies.js +1 -2
  200. package/dist/syncer/index.js +8 -2
  201. package/dist/syncer/module-loader.js +8 -6
  202. package/dist/syncer/syncer-actions.js +8 -7
  203. package/dist/syncer/syncer.js +13 -8
  204. package/dist/syncer/watcher.js +2 -3
  205. package/dist/tasks/decorator.js +1 -2
  206. package/dist/tasks/step-wrapper.js +2 -3
  207. package/dist/tasks/workflow-manager.js +2 -3
  208. package/dist/template/entity-converter.js +17 -16
  209. package/dist/template/helpers.js +2 -3
  210. package/dist/template/implementations/entity.template.js +2 -3
  211. package/dist/template/implementations/entry-server.template.js +2 -3
  212. package/dist/template/implementations/generated.template.js +2 -3
  213. package/dist/template/implementations/generated_http.template.js +6 -6
  214. package/dist/template/implementations/generated_sso.template.js +2 -3
  215. package/dist/template/implementations/http_validators.template.js +2 -3
  216. package/dist/template/implementations/init_types.template.js +2 -3
  217. package/dist/template/implementations/model.template.js +4 -4
  218. package/dist/template/implementations/model_test.template.js +2 -3
  219. package/dist/template/implementations/queries.template.js +2 -3
  220. package/dist/template/implementations/sd.template.js +2 -3
  221. package/dist/template/implementations/services.template.js +2 -3
  222. package/dist/template/implementations/view_form.template.js +12 -9
  223. package/dist/template/implementations/view_id_all_select.template.js +2 -3
  224. package/dist/template/implementations/view_list.template.d.ts.map +1 -1
  225. package/dist/template/implementations/view_list.template.js +19 -17
  226. package/dist/template/implementations/view_search_input.template.js +2 -3
  227. package/dist/template/index.js +9 -3
  228. package/dist/template/template-manager.js +2 -3
  229. package/dist/template/template-types.js +1 -2
  230. package/dist/template/template.js +2 -3
  231. package/dist/template/zod-converter.js +54 -47
  232. package/dist/testing/_relation-graph.js +2 -3
  233. package/dist/testing/bootstrap.js +2 -3
  234. package/dist/testing/data-explorer.js +2 -3
  235. package/dist/testing/dev-test-routes.js +2 -3
  236. package/dist/testing/dev-vitest-manager.js +15 -12
  237. package/dist/testing/faker-mappings.js +1 -2
  238. package/dist/testing/filesystem.js +2 -3
  239. package/dist/testing/fixture-generator.js +2 -3
  240. package/dist/testing/fixture-loader.js +1 -2
  241. package/dist/testing/fixture-manager.js +12 -9
  242. package/dist/testing/global-setup.js +5 -5
  243. package/dist/testing/index.js +6 -3
  244. package/dist/testing/naite-vitest-reporter.js +1 -2
  245. package/dist/testing/parallel-db-manager.js +2 -3
  246. package/dist/testing/vitest-helpers.js +2 -3
  247. package/dist/tooling/__tests__/helpers/sonamu-test-root.js +2 -3
  248. package/dist/tooling/cdd-service.js +1 -2
  249. package/dist/tooling/cli-tooling.js +1 -2
  250. package/dist/tooling/fixture-service.js +1 -2
  251. package/dist/tooling/index.js +1 -2
  252. package/dist/tooling/test-run-client.js +2 -3
  253. package/dist/tsdown.api.config.js +1 -2
  254. package/dist/types/types.js +2 -3
  255. package/dist/ui/ai-api.d.ts.map +1 -1
  256. package/dist/ui/ai-api.js +4 -5
  257. package/dist/ui/ai-client.d.ts +2 -2
  258. package/dist/ui/ai-client.d.ts.map +1 -1
  259. package/dist/ui/ai-client.js +9 -8
  260. package/dist/ui/api.d.ts.map +1 -1
  261. package/dist/ui/api.js +11 -8
  262. package/dist/ui/async-route.js +1 -2
  263. package/dist/ui/cdd-service.js +22 -21
  264. package/dist/ui/migrations-api.js +6 -5
  265. package/dist/ui-web/assets/index-QDMyy31K.js +180 -0
  266. package/dist/ui-web/assets/index-dV7akMFB.css +1 -0
  267. package/dist/ui-web/index.html +2 -2
  268. package/dist/utils/async-utils.js +1 -2
  269. package/dist/utils/class-name.js +1 -2
  270. package/dist/utils/console-util.js +1 -2
  271. package/dist/utils/controller.js +2 -3
  272. package/dist/utils/esm-utils.js +1 -2
  273. package/dist/utils/fs-utils.js +2 -3
  274. package/dist/utils/lodash-able.js +1 -2
  275. package/dist/utils/model.js +1 -2
  276. package/dist/utils/object-utils.js +2 -3
  277. package/dist/utils/path-utils.js +2 -3
  278. package/dist/utils/process-utils.js +2 -3
  279. package/dist/utils/runtime-value.js +1 -2
  280. package/dist/utils/sql-parser.js +2 -3
  281. package/dist/utils/type-utils.js +8 -8
  282. package/dist/utils/utils.js +2 -3
  283. package/dist/utils/zod-error.js +2 -3
  284. package/dist/vector/chunking.js +1 -2
  285. package/dist/vector/config.js +1 -2
  286. package/dist/vector/embedding.js +4 -4
  287. package/package.json +63 -63
  288. package/src/ai/agents/agent.ts +1 -1
  289. package/src/api/__tests__/sonamu.plugins.test.ts +11 -1
  290. package/src/api/__tests__/sonamu.websocket-routes.test.ts +234 -0
  291. package/src/api/__tests__/sonamu.websocket.test.ts +241 -24
  292. package/src/api/config.ts +1 -1
  293. package/src/api/context.ts +2 -8
  294. package/src/api/sonamu.ts +46 -28
  295. package/src/auth/audit-log/plugin.ts +2 -0
  296. package/src/compress/types.ts +1 -1
  297. package/src/exceptions/error-handler.ts +3 -2
  298. package/src/index.ts +1 -0
  299. package/src/stream/__tests__/ws-contracts.test.ts +483 -265
  300. package/src/stream/__tests__/ws-multinode.test.ts +326 -0
  301. package/src/stream/__tests__/ws-registry-async.test.ts +855 -0
  302. package/src/stream/__tests__/ws-test-helpers.ts +360 -0
  303. package/src/stream/__tests__/ws.test.ts +342 -145
  304. package/src/stream/index.ts +1 -0
  305. package/src/stream/ws-audience-resolver.ts +21 -19
  306. package/src/stream/ws-cluster-bus.ts +12 -4
  307. package/src/stream/ws-core.ts +14 -0
  308. package/src/stream/ws-delivery.ts +321 -97
  309. package/src/stream/ws-frame.ts +39 -0
  310. package/src/stream/ws-local-connection-store.ts +10 -9
  311. package/src/stream/ws-presence-index.ts +273 -0
  312. package/src/stream/ws-presence-store.ts +64 -284
  313. package/src/stream/ws-registry.ts +272 -85
  314. package/src/stream/ws-session-id.ts +39 -0
  315. package/src/stream/ws.ts +91 -50
  316. package/src/template/implementations/model.template.ts +3 -3
  317. package/src/template/implementations/view_list.template.ts +12 -13
  318. package/src/ui/ai-api.ts +4 -2
  319. package/src/ui/ai-client.ts +2 -2
  320. package/src/ui/api.ts +58 -62
  321. package/dist/ui-web/assets/index-BMdIyKXS.css +0 -1
  322. package/dist/ui-web/assets/index-LpE8u19O.js +0 -178
@@ -0,0 +1,39 @@
1
+ import { type z } from "zod";
2
+
3
+ export type WebSocketFrameEncoding =
4
+ | { status: "encoded"; frame: string }
5
+ | { status: "unknownEvent" }
6
+ | { status: "invalidPayload" };
7
+
8
+ /**
9
+ * outEvents 스키마로 payload를 검증하고 `{event, data}` frame 문자열로 인코딩한다.
10
+ * 같은 스키마로 인코딩한 frame은 로컬·원격 수신자 모두에게 같은 바이트로 전달된다.
11
+ */
12
+ export function encodeWebSocketFrame<Data>(
13
+ outEvents: z.ZodObject,
14
+ event: string,
15
+ data: Data,
16
+ ): WebSocketFrameEncoding {
17
+ const schema = getEventSchema(outEvents, event);
18
+ if (!schema) {
19
+ return { status: "unknownEvent" };
20
+ }
21
+
22
+ const parsed = schema.safeParse(data);
23
+ if (!parsed.success) {
24
+ return { status: "invalidPayload" };
25
+ }
26
+
27
+ return {
28
+ status: "encoded",
29
+ frame: JSON.stringify({
30
+ event,
31
+ data: parsed.data,
32
+ }),
33
+ };
34
+ }
35
+
36
+ function getEventSchema(outEvents: z.ZodObject, event: string): z.ZodType | undefined {
37
+ const eventSchemas: Record<string, z.ZodType> = outEvents["shape"];
38
+ return Object.hasOwn(eventSchemas, event) ? eventSchemas[event] : undefined;
39
+ }
@@ -1,14 +1,14 @@
1
1
  import { isFunctionValue } from "../utils/runtime-value";
2
- import { type ManagedWebSocketConnection } from "./ws-core";
2
+ import { type WebSocketFrameConnection } from "./ws-core";
3
3
  import {
4
4
  type WebSocketTelemetryConnectionSnapshot,
5
5
  type TelemetryInspectableConnection,
6
6
  } from "./ws-telemetry";
7
7
 
8
8
  export class WebSocketLocalConnectionStore {
9
- private readonly connections = new Map<string, ManagedWebSocketConnection>();
9
+ private readonly connections = new Map<string, WebSocketFrameConnection>();
10
10
 
11
- register(connection: ManagedWebSocketConnection): void {
11
+ register(connection: WebSocketFrameConnection): void {
12
12
  this.connections.set(connection.id, connection);
13
13
  }
14
14
 
@@ -16,12 +16,12 @@ export class WebSocketLocalConnectionStore {
16
16
  this.connections.delete(connectionId);
17
17
  }
18
18
 
19
- getConnection(connectionId: string): ManagedWebSocketConnection | undefined {
19
+ getConnection(connectionId: string): WebSocketFrameConnection | undefined {
20
20
  return this.connections.get(connectionId);
21
21
  }
22
22
 
23
- getConnections(connectionIds: string[]): ManagedWebSocketConnection[] {
24
- const targets: ManagedWebSocketConnection[] = [];
23
+ getConnections(connectionIds: string[]): WebSocketFrameConnection[] {
24
+ const targets: WebSocketFrameConnection[] = [];
25
25
  const seen = new Set<string>();
26
26
 
27
27
  for (const connectionId of connectionIds) {
@@ -63,14 +63,15 @@ export class WebSocketLocalConnectionStore {
63
63
  }
64
64
 
65
65
  closeAll(code?: number, reason?: string): void {
66
- for (const connection of this.connections.values()) {
66
+ // close 도중 unregister가 Map을 바꾸므로 복사본을 순회한다
67
+ for (const connection of Array.from(this.connections.values())) {
67
68
  connection.close(code, reason);
68
69
  }
69
70
  }
70
71
  }
71
72
 
72
73
  function isTelemetryInspectableConnection(
73
- connection: ManagedWebSocketConnection,
74
- ): connection is ManagedWebSocketConnection & TelemetryInspectableConnection {
74
+ connection: WebSocketFrameConnection,
75
+ ): connection is WebSocketFrameConnection & TelemetryInspectableConnection {
75
76
  return "getTelemetrySnapshot" in connection && isFunctionValue(connection.getTelemetrySnapshot);
76
77
  }
@@ -0,0 +1,273 @@
1
+ import { type WebSocketAudience } from "./ws-audience";
2
+ import { type WebSocketRegistryStats, type WebSocketRoomId, type WebSocketUserId } from "./ws-core";
3
+ import {
4
+ type WebSocketPresenceRegistration,
5
+ type WebSocketSessionPresence,
6
+ } from "./ws-presence-store";
7
+
8
+ type PresenceRecord = WebSocketSessionPresence;
9
+ // namespace → 바인딩 id → 세션 ID 집합. userId는 Map 키로 그대로 써서 1과 "1"을 구분한다
10
+ type BindingIndex<Id> = Map<string, Map<Id, Set<string>>>;
11
+
12
+ /**
13
+ * 동기 presence 인덱스. registry의 노드 로컬 메모리와 in-memory store가 함께 쓴다.
14
+ * 외부로 내보내는 presence는 항상 복사본이다.
15
+ */
16
+ export class WebSocketPresenceIndex {
17
+ private readonly sessions = new Map<string, PresenceRecord>();
18
+ private readonly rooms: BindingIndex<WebSocketRoomId> = new Map();
19
+ private readonly users: BindingIndex<WebSocketUserId> = new Map();
20
+
21
+ has(sessionId: string): boolean {
22
+ return this.sessions.has(sessionId);
23
+ }
24
+
25
+ register(input: WebSocketPresenceRegistration): void {
26
+ // 같은 세션을 다시 등록하면 이전 바인딩을 먼저 정리해 고아 바인딩이 남지 않게 한다
27
+ this.unregister(input.sessionId);
28
+ this.sessions.set(input.sessionId, {
29
+ sessionId: input.sessionId,
30
+ nodeId: input.nodeId,
31
+ namespace: input.namespace,
32
+ active: input.active,
33
+ rooms: new Set(),
34
+ connectedAt: new Date(input.connectedAt.getTime()),
35
+ lastSeenAt: new Date(input.connectedAt.getTime()),
36
+ });
37
+ }
38
+
39
+ activate(sessionId: string): void {
40
+ const record = this.sessions.get(sessionId);
41
+ if (record) {
42
+ record.active = true;
43
+ }
44
+ }
45
+
46
+ unregister(sessionId: string): WebSocketSessionPresence | undefined {
47
+ const record = this.sessions.get(sessionId);
48
+ if (!record) {
49
+ return undefined;
50
+ }
51
+
52
+ if (record.userId !== undefined) {
53
+ removeBinding(this.users, record.namespace, record.userId, sessionId);
54
+ }
55
+ for (const roomId of record.rooms) {
56
+ removeBinding(this.rooms, record.namespace, roomId, sessionId);
57
+ }
58
+ this.sessions.delete(sessionId);
59
+ return copyPresence(record);
60
+ }
61
+
62
+ touch(sessionId: string): void {
63
+ const record = this.sessions.get(sessionId);
64
+ if (record) {
65
+ record.lastSeenAt = new Date();
66
+ }
67
+ }
68
+
69
+ setUserId(sessionId: string, userId: WebSocketUserId): void {
70
+ const record = this.sessions.get(sessionId);
71
+ if (!record) {
72
+ return;
73
+ }
74
+
75
+ if (record.userId !== undefined) {
76
+ removeBinding(this.users, record.namespace, record.userId, sessionId);
77
+ }
78
+ record.userId = userId;
79
+ addBinding(this.users, record.namespace, userId, sessionId);
80
+ }
81
+
82
+ clearUserId(sessionId: string): void {
83
+ const record = this.sessions.get(sessionId);
84
+ if (!record || record.userId === undefined) {
85
+ return;
86
+ }
87
+
88
+ removeBinding(this.users, record.namespace, record.userId, sessionId);
89
+ delete record.userId;
90
+ }
91
+
92
+ join(sessionId: string, roomId: WebSocketRoomId): void {
93
+ const record = this.sessions.get(sessionId);
94
+ if (!record) {
95
+ return;
96
+ }
97
+
98
+ record.rooms.add(roomId);
99
+ addBinding(this.rooms, record.namespace, roomId, sessionId);
100
+ }
101
+
102
+ leave(sessionId: string, roomId: WebSocketRoomId): void {
103
+ const record = this.sessions.get(sessionId);
104
+ if (!record) {
105
+ return;
106
+ }
107
+
108
+ record.rooms.delete(roomId);
109
+ removeBinding(this.rooms, record.namespace, roomId, sessionId);
110
+ }
111
+
112
+ getConnection(sessionId: string): WebSocketSessionPresence | undefined {
113
+ const record = this.sessions.get(sessionId);
114
+ return record ? copyPresence(record) : undefined;
115
+ }
116
+
117
+ getConnectionCount(namespace?: string): number {
118
+ let count = 0;
119
+ for (const record of this.sessions.values()) {
120
+ if (record.active && matchesNamespace(record, namespace)) {
121
+ count += 1;
122
+ }
123
+ }
124
+ return count;
125
+ }
126
+
127
+ getRoomMembers(roomId: WebSocketRoomId, namespace?: string): WebSocketSessionPresence[] {
128
+ return this.getBoundSessions(this.rooms, roomId, namespace).map(copyPresence);
129
+ }
130
+
131
+ getRoomMemberCount(roomId: WebSocketRoomId, namespace?: string): number {
132
+ return this.getBoundSessions(this.rooms, roomId, namespace).length;
133
+ }
134
+
135
+ getStats(): WebSocketRegistryStats {
136
+ const byNamespace: Record<string, number> = {};
137
+ let totalConnections = 0;
138
+
139
+ for (const record of this.sessions.values()) {
140
+ if (!record.active) {
141
+ continue;
142
+ }
143
+ byNamespace[record.namespace] = (byNamespace[record.namespace] ?? 0) + 1;
144
+ totalConnections += 1;
145
+ }
146
+
147
+ let totalRooms = 0;
148
+ for (const bindings of this.rooms.values()) {
149
+ totalRooms += bindings.size;
150
+ }
151
+
152
+ return { totalConnections, totalRooms, byNamespace };
153
+ }
154
+
155
+ /**
156
+ * audience에 해당하는 활성 세션을 중복 없이 반환한다. 반환값은 내부 상태를 노출하지 않도록 ID와 노드 ID만 담는다.
157
+ */
158
+ queryAudience(audience: WebSocketAudience): Array<{ sessionId: string; nodeId: string }> {
159
+ const seen = new Set<string>();
160
+ const results: Array<{ sessionId: string; nodeId: string }> = [];
161
+
162
+ for (const record of this.collectAudience(audience)) {
163
+ if (seen.has(record.sessionId)) {
164
+ continue;
165
+ }
166
+ seen.add(record.sessionId);
167
+ results.push({ sessionId: record.sessionId, nodeId: record.nodeId });
168
+ }
169
+
170
+ return results;
171
+ }
172
+
173
+ private collectAudience(audience: WebSocketAudience): PresenceRecord[] {
174
+ switch (audience.type) {
175
+ case "all":
176
+ return [...this.sessions.values()].filter(
177
+ (record) => record.active && matchesNamespace(record, audience.namespace),
178
+ );
179
+ case "room":
180
+ return this.getBoundSessions(this.rooms, audience.roomId, audience.namespace);
181
+ case "user":
182
+ return this.getBoundSessions(this.users, audience.userId, audience.namespace);
183
+ case "connections": {
184
+ const records: PresenceRecord[] = [];
185
+ for (const sessionId of audience.connectionIds) {
186
+ const record = this.sessions.get(sessionId);
187
+ if (record?.active && matchesNamespace(record, audience.namespace)) {
188
+ records.push(record);
189
+ }
190
+ }
191
+ return records;
192
+ }
193
+ case "union":
194
+ return audience.audiences.flatMap((item) => this.collectAudience(item));
195
+ }
196
+ }
197
+
198
+ private getBoundSessions<Id>(
199
+ index: BindingIndex<Id>,
200
+ id: Id,
201
+ namespace?: string,
202
+ ): PresenceRecord[] {
203
+ // namespace가 없으면(빈 문자열 포함) 모든 namespace의 바인딩을 본다
204
+ const namespaces = namespace ? [index.get(namespace)] : [...index.values()];
205
+ const seen = new Set<string>();
206
+ const records: PresenceRecord[] = [];
207
+
208
+ for (const bindings of namespaces) {
209
+ for (const sessionId of bindings?.get(id) ?? []) {
210
+ if (seen.has(sessionId)) {
211
+ continue;
212
+ }
213
+ seen.add(sessionId);
214
+
215
+ const record = this.sessions.get(sessionId);
216
+ if (record?.active) {
217
+ records.push(record);
218
+ }
219
+ }
220
+ }
221
+
222
+ return records;
223
+ }
224
+ }
225
+
226
+ function matchesNamespace(record: PresenceRecord, namespace: string | undefined): boolean {
227
+ return namespace === undefined || namespace === "" || record.namespace === namespace;
228
+ }
229
+
230
+ function copyPresence(record: PresenceRecord): WebSocketSessionPresence {
231
+ const copy: WebSocketSessionPresence = {
232
+ sessionId: record.sessionId,
233
+ nodeId: record.nodeId,
234
+ namespace: record.namespace,
235
+ active: record.active,
236
+ rooms: new Set(record.rooms),
237
+ connectedAt: new Date(record.connectedAt.getTime()),
238
+ lastSeenAt: new Date(record.lastSeenAt.getTime()),
239
+ };
240
+ if (record.userId !== undefined) {
241
+ copy.userId = record.userId;
242
+ }
243
+ return copy;
244
+ }
245
+
246
+ function addBinding<Id>(index: BindingIndex<Id>, namespace: string, id: Id, sessionId: string) {
247
+ const bindings = index.get(namespace) ?? new Map<Id, Set<string>>();
248
+ const members = bindings.get(id) ?? new Set<string>();
249
+ members.add(sessionId);
250
+ bindings.set(id, members);
251
+ index.set(namespace, bindings);
252
+ }
253
+
254
+ function removeBinding<Id>(
255
+ index: BindingIndex<Id>,
256
+ namespace: string,
257
+ id: Id,
258
+ sessionId: string,
259
+ ): void {
260
+ const bindings = index.get(namespace);
261
+ const members = bindings?.get(id);
262
+ if (!bindings || !members) {
263
+ return;
264
+ }
265
+
266
+ members.delete(sessionId);
267
+ if (members.size === 0) {
268
+ bindings.delete(id);
269
+ }
270
+ if (bindings.size === 0) {
271
+ index.delete(namespace);
272
+ }
273
+ }