realtimeBroker.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. import { randomUUID } from 'node:crypto'
  2. import WebSocket from 'ws'
  3. import { HttpError } from './errors.js'
  4. import { checkedChatFrame, CHAT_MAX_PAYLOAD, GroupFrameValidator } from './realtimeProtocol.js'
  5. import { RealtimeReceipts, type CommandReceipt } from './realtimeReceipts.js'
  6. type Frame = Record<string, any>
  7. export interface RealtimeActivity { kind: 'command' | 'event' | 'group' | 'reset'; name: string; sessionId?: string; roomId?: string }
  8. export interface RealtimePrincipal {
  9. key: string
  10. upstreamKey: string
  11. instanceKey?: string
  12. paired: boolean
  13. valid(): boolean
  14. authorize?(kind: 'chat' | 'groups', method?: string): void
  15. url(channel: 'chat' | 'groups', anchor?: { epoch: string; cursor: number }): Promise<URL>
  16. observeCommand?(frame: string): void
  17. observeEvent?(frame: string): void
  18. }
  19. export interface StreamEntry { id: string; event: 'frame' | 'reset'; data: string; at: number; bytes: number }
  20. export interface RealtimeChannel {
  21. id: string; kind: 'chat' | 'groups'; principal: RealtimePrincipal
  22. seq: number; droppedThrough: number; entries: StreamEntry[]; routes: Set<string>
  23. listeners: Set<(entry: StreamEntry) => void>; touched: number; bytes: number
  24. group?: { epoch: string; cursor: number }; socket?: WebSocket
  25. }
  26. interface Route { profile: string; stored: string; runtime: string; active: boolean; seq: number; observers: Map<string, RealtimePrincipal> }
  27. interface Pending { resolve(frame: Frame): void; reject(error: Error): void; timer: ReturnType<typeof setTimeout> }
  28. interface Upstream {
  29. principal: RealtimePrincipal; socket?: WebSocket; connecting?: Promise<void>; ready?: Frame
  30. pending: Map<string, Pending>; routes: Map<string, Route>; byRuntime: Map<string, Route>
  31. tails: Map<string, Promise<unknown>>; early: Map<string, Frame[]>; earlyBytes: number
  32. retry?: ReturnType<typeof setTimeout>; attempts: number; epoch?: string; recovering: boolean
  33. lastUsed: number; ping?: ReturnType<typeof setInterval>
  34. deferred: Frame[]
  35. recovery?: Promise<void>
  36. }
  37. /** Server-owned WS transports. Downstream detach never tears down an active upstream. */
  38. export class RealtimeBroker {
  39. readonly epoch = randomUUID()
  40. readonly channels = new Map<string, RealtimeChannel>()
  41. private upstreams = new Map<string, Upstream>()
  42. private commands = new Map<string, Promise<CommandReceipt>>()
  43. private completed = new Map<string, { receipt: CommandReceipt; at: number; bytes: number }>()
  44. private receipts: RealtimeReceipts
  45. private timer: ReturnType<typeof setInterval>
  46. private closed = false
  47. constructor(home: string, readonly now = Date.now, readonly onActivity: (activity: RealtimeActivity) => void = () => {}) {
  48. this.receipts = new RealtimeReceipts(home)
  49. this.timer = setInterval(() => this.sweep(), 5_000)
  50. this.timer.unref()
  51. }
  52. async create(principal: RealtimePrincipal, kind: 'chat' | 'groups', group?: { epoch: string; cursor: number }): Promise<RealtimeChannel> {
  53. if (this.closed) throw new HttpError(503, 'Realtime broker is stopping', 'broker_stopping')
  54. principal.authorize?.(kind)
  55. if (!principal.valid()) throw new HttpError(401, 'Authentication expired', 'authentication_required')
  56. // Closed pages leave resumable channels behind. They must not consume the live-stream
  57. // quota; evict oldest detached handles under pressure, never a running upstream.
  58. let own = [...this.channels.values()].filter(c => c.principal.key === principal.key)
  59. while (own.length >= 32) {
  60. const stale = own.filter(c => !c.listeners.size).sort((a, b) => a.touched - b.touched)[0]
  61. if (!stale) break
  62. this.remove(stale); own = own.filter(c => c !== stale)
  63. }
  64. if (own.length >= 32 || this.channels.size >= 512) {
  65. throw new HttpError(429, 'Too many realtime channels', 'channel_limit')
  66. }
  67. const c: RealtimeChannel = { id: randomUUID(), kind, principal, seq: 0, droppedThrough: 0,
  68. entries: [], routes: new Set(), listeners: new Set(), touched: this.now(), bytes: 0, group }
  69. this.channels.set(c.id, c)
  70. try {
  71. if (kind === 'groups') {
  72. if (!group) throw new HttpError(400, 'Group anchor is required', 'invalid_anchor')
  73. await this.connectGroup(c)
  74. } else {
  75. const u = this.upstream(principal)
  76. await this.connect(u)
  77. this.emit(c, 'frame', u.ready!)
  78. }
  79. return c
  80. } catch (e) { this.remove(c); throw e }
  81. }
  82. get(principal: RealtimePrincipal, id: string): RealtimeChannel {
  83. const c = this.channels.get(id)
  84. if (!c || c.principal.key !== principal.key) throw new HttpError(404, 'Channel not found', 'channel_not_found')
  85. if (!principal.valid()) throw new HttpError(401, 'Authentication expired', 'authentication_required')
  86. c.touched = this.now()
  87. return c
  88. }
  89. detach(principal: RealtimePrincipal, id: string): void { this.remove(this.get(principal, id)) }
  90. release(c: RealtimeChannel): void { if (this.channels.get(c.id) === c) this.remove(c) }
  91. private remove(c: RealtimeChannel): void {
  92. this.channels.delete(c.id)
  93. c.socket?.close()
  94. for (const listener of c.listeners) {
  95. try { listener({ id: '', event: 'reset', data: '{"reason":"channel_closed"}', at: this.now(), bytes: 0 }) } catch { /* a closed consumer must not affect the upstream */ }
  96. }
  97. c.listeners.clear()
  98. }
  99. subscribe(c: RealtimeChannel, cursor: string | undefined, listener: (entry: StreamEntry) => void): () => void {
  100. if ([...this.channels.values()].filter(v => v.principal.key === c.principal.key).reduce((n, v) => n + v.listeners.size, 0) >= 8) {
  101. throw new HttpError(429, 'Too many active event streams', 'stream_limit')
  102. }
  103. this.trim(c)
  104. let seq = 0
  105. if (cursor) {
  106. const prefix = `${this.epoch}:`
  107. if (!cursor.startsWith(prefix) || !/^\d+$/.test(cursor.slice(prefix.length))) {
  108. throw new HttpError(409, 'Stream epoch changed', 'reset_required')
  109. }
  110. seq = Number(cursor.slice(prefix.length))
  111. }
  112. if (!Number.isSafeInteger(seq) || seq < c.droppedThrough || seq > c.seq) {
  113. throw new HttpError(409, 'Replay window expired', 'reset_required')
  114. }
  115. c.listeners.add(listener)
  116. for (const entry of c.entries) if (Number(entry.id.split(':').at(-1)) > seq) listener(entry)
  117. return () => { c.listeners.delete(listener); c.touched = this.now() }
  118. }
  119. receipt(p: RealtimePrincipal, id: string): CommandReceipt {
  120. if (!p.valid()) throw new HttpError(401, 'Authentication expired', 'authentication_required')
  121. const receipt = this.completed.get(`${p.key}:${id}`)?.receipt ?? this.receipts.lookup(p.key, id)
  122. if (!receipt) throw new HttpError(404, 'Receipt not found; do not automatically resubmit an attempted command', 'receipt_not_found')
  123. return receipt
  124. }
  125. command(c: RealtimeChannel, requestId: string, input: Frame): Promise<CommandReceipt> {
  126. if (this.closed) throw new HttpError(503, 'Realtime broker is stopping', 'broker_stopping')
  127. if (c.kind !== 'chat') throw new HttpError(403, 'Group event channel is read-only', 'read_only')
  128. const normalized = checkedChatFrame(Buffer.from(JSON.stringify(input)), false, c.principal.paired)
  129. const frame = JSON.parse(normalized) as Frame
  130. c.principal.authorize?.('chat', String(frame.method))
  131. delete frame.id
  132. const fingerprint = JSON.stringify(frame)
  133. if (!this.receipts.lookup(c.principal.key, requestId) && (this.commands.size >= 1024
  134. || [...this.commands.keys()].filter(k => k.startsWith(`${c.principal.key}:`)).length >= 32)) {
  135. throw new HttpError(429, 'Too many pending commands', 'command_limit')
  136. }
  137. const existing = this.receipts.reserve(c.principal.key, requestId, fingerprint)
  138. const key = `${c.principal.key}:${requestId}`
  139. if (existing) return this.commands.get(key) ?? Promise.resolve(this.completed.get(key)?.receipt ?? existing)
  140. const work = this.perform(c, frame).then(response => {
  141. const state = response.error ? 'rejected' : 'confirmed'
  142. this.receipts.finish(c.principal.key, requestId, state, response)
  143. return { requestId, state, response } as CommandReceipt
  144. }, (error: unknown) => {
  145. if (error instanceof HttpError) {
  146. const response = { error: { code: error.code, message: error.message } }
  147. this.receipts.finish(c.principal.key, requestId, 'rejected', response)
  148. return { requestId, state: 'rejected', response } as CommandReceipt
  149. }
  150. this.receipts.finish(c.principal.key, requestId, 'unknown')
  151. return { requestId, state: 'unknown' } as CommandReceipt
  152. })
  153. this.commands.set(key, work)
  154. void work.then(receipt => {
  155. this.commands.delete(key)
  156. this.completed.set(key, { receipt, at: this.now(), bytes: Buffer.byteLength(JSON.stringify(receipt)) })
  157. while (this.completed.size > 10_000 || [...this.completed.values()].reduce((n, x) => n + x.bytes, 0) > 32 * 1024 * 1024) this.completed.delete(this.completed.keys().next().value!)
  158. })
  159. return work
  160. }
  161. private async perform(c: RealtimeChannel, frame: Frame): Promise<Frame> {
  162. const u = this.upstream(c.principal)
  163. const p = frame.params as Frame
  164. const method = String(frame.method)
  165. const opening = method === 'session.create' || method === 'session.resume'
  166. if (opening && (c.routes.size >= 128 || u.routes.size >= 512)) throw new HttpError(429, 'Route capacity reached', 'route_limit')
  167. let route = p.session_id ? u.byRuntime.get(p.session_id) : undefined
  168. if (!opening && !method.startsWith('profiles.')) {
  169. if (!route && (method === 'approval.respond' || method === 'clarify.respond')) {
  170. // These RPCs use request_id rather than session_id; resolve only a pending interaction seen by this channel.
  171. const match = [...c.routes].map(k => u.routes.get(k)).find(r => r && this.interactions.get(`${u.principal.upstreamKey}:${p.request_id}`) === r.runtime)
  172. route = match
  173. }
  174. if (!route || !c.routes.has(this.routeKey(route.profile, route.stored))) throw new HttpError(403, 'Session is not subscribed', 'route_forbidden')
  175. if (['approval.respond', 'clarify.respond'].includes(method)
  176. && this.interactions.get(`${u.principal.upstreamKey}:${p.request_id}`) !== route.runtime) {
  177. throw new HttpError(403, 'Interaction does not belong to this session', 'interaction_forbidden')
  178. }
  179. }
  180. const routeKey = opening ? this.routeKey(String(p.profile), String(p.session_id ?? c.id))
  181. : route ? this.routeKey(route.profile, route.stored) : 'profiles'
  182. const execute = async () => {
  183. if (!c.principal.valid()) throw new HttpError(401, 'Authentication expired', 'authentication_required')
  184. if (method === 'session.resume') {
  185. const ownerKey = JSON.stringify([c.principal.instanceKey ?? c.principal.upstreamKey, p.profile, p.session_id])
  186. const owner = this.routeOwners.get(ownerKey)
  187. if (owner && owner !== c.principal.upstreamKey) throw new HttpError(409, 'Session is attached through another credential scope', 'session_scope_conflict')
  188. this.routeOwners.set(ownerKey, c.principal.upstreamKey)
  189. }
  190. await this.connect(u)
  191. await u.recovery
  192. if (!c.principal.valid()) throw new HttpError(401, 'Authentication expired', 'authentication_required')
  193. const previouslyActive = route?.active ?? false
  194. if (route && (method === 'prompt.submit' || method === 'session.steer')) route.active = true
  195. const activity: RealtimeActivity = { kind: 'command', name: method, sessionId: route?.stored }
  196. this.onActivity(activity)
  197. const response = await this.rpc(u, method, p, f => c.principal.observeEvent?.(JSON.stringify(f)), f => c.principal.observeCommand?.(JSON.stringify(f)))
  198. .finally(() => this.onActivity(activity))
  199. if (response.error && route && (method === 'prompt.submit' || method === 'session.steer')) route.active = previouslyActive
  200. if (!response.error && route && (method === 'prompt.submit' || method === 'session.steer')) route.active = true
  201. if ((opening || method === 'session.branch') && response.result) {
  202. const result = response.result as Frame
  203. const info = result.info ?? {}
  204. const runtime = String(result.session_id ?? '')
  205. const stored = String(result.stored_session_id ?? result.session_key ?? info.stored_session_id ?? p.session_id ?? runtime)
  206. if (!runtime || !stored) throw new Error('Invalid upstream session identity')
  207. const profile = String(p.profile ?? route?.profile ?? 'default')
  208. const key = this.routeKey(profile, stored)
  209. this.routeOwners.set(JSON.stringify([c.principal.instanceKey ?? c.principal.upstreamKey, profile, stored]), c.principal.upstreamKey)
  210. const r: Route = u.routes.get(key) ?? { profile, stored, runtime, active: false, seq: 0, observers: new Map() }
  211. u.byRuntime.delete(r.runtime)
  212. r.runtime = runtime
  213. r.active = result.running === true || info.running === true
  214. u.routes.set(key, r); u.byRuntime.set(runtime, r); c.routes.add(key)
  215. r.observers.set(c.principal.key, c.principal)
  216. for (const pending of [result.pending_approval, result.pending_clarify, result.inflight?.pending_approval, result.inflight?.pending_clarify]) {
  217. if (pending?.request_id) this.interactions.set(`${u.principal.upstreamKey}:${pending.request_id}`, runtime)
  218. }
  219. const early = u.early.get(runtime) ?? []
  220. u.early.delete(runtime)
  221. for (const e of early) { u.earlyBytes -= Buffer.byteLength(JSON.stringify(e)); this.event(u, e) }
  222. }
  223. if (method === 'session.close' && route && !response.error) {
  224. u.byRuntime.delete(route.runtime); u.routes.delete(this.routeKey(route.profile, route.stored))
  225. this.routeOwners.delete(JSON.stringify([c.principal.instanceKey ?? c.principal.upstreamKey, route.profile, route.stored]))
  226. }
  227. u.lastUsed = this.now()
  228. return response
  229. }
  230. if (['session.interrupt', 'approval.respond', 'clarify.respond', 'session.steer'].includes(method)) return execute()
  231. const work = (u.tails.get(routeKey) ?? Promise.resolve()).catch(() => {}).then(execute)
  232. u.tails.set(routeKey, work)
  233. void work.finally(() => { if (u.tails.get(routeKey) === work) u.tails.delete(routeKey) }).catch(() => {})
  234. return work
  235. }
  236. private interactions = new Map<string, string>()
  237. private routeOwners = new Map<string, string>()
  238. private routeKey(profile: string, stored: string): string { return JSON.stringify([profile, stored]) }
  239. private upstream(p: RealtimePrincipal): Upstream {
  240. let u = this.upstreams.get(p.upstreamKey)
  241. if (!u) {
  242. if (this.upstreams.size >= 64) throw new HttpError(429, 'Upstream capacity reached', 'upstream_limit')
  243. u = { principal: p, pending: new Map(), routes: new Map(), byRuntime: new Map(), tails: new Map(),
  244. early: new Map(), earlyBytes: 0, attempts: 0, recovering: false, deferred: [], lastUsed: this.now() }
  245. this.upstreams.set(p.upstreamKey, u)
  246. }
  247. return u
  248. }
  249. private connect(u: Upstream): Promise<void> {
  250. if (u.connecting) return u.connecting
  251. if (u.socket?.readyState === WebSocket.OPEN && u.ready) return Promise.resolve()
  252. u.connecting = (async () => {
  253. const url = await u.principal.url('chat')
  254. if (this.closed) throw new Error('Broker closed')
  255. await new Promise<void>((resolve, reject) => {
  256. const ws = new WebSocket(url, { headers: { Origin: `${url.protocol === 'wss:' ? 'https:' : 'http:'}//${url.host}` }, maxPayload: CHAT_MAX_PAYLOAD, handshakeTimeout: 15_000 })
  257. u.socket = ws
  258. const timeout = setTimeout(() => { reject(new Error('Upstream ready timeout')); ws.terminate() }, 20_000)
  259. let ready = false
  260. ws.on('message', (data, binary) => {
  261. if (u.socket !== ws || binary) return
  262. let f: Frame
  263. try { f = JSON.parse(data.toString()) } catch { ws.terminate(); return }
  264. if (f.method === 'event' && f.params?.type === 'gateway.ready') {
  265. clearTimeout(timeout); ready = true; u.ready = f; u.attempts = 0
  266. const epoch = f.params.payload?.replay_epoch
  267. const changed = u.epoch !== undefined && epoch !== u.epoch
  268. u.epoch = epoch
  269. if (u.routes.size) u.recovery = this.recover(u, changed).finally(() => { u.recovery = undefined })
  270. resolve()
  271. } else if (f.id !== undefined) {
  272. const pending = u.pending.get(String(f.id))
  273. if (pending) { clearTimeout(pending.timer); u.pending.delete(String(f.id)); pending.resolve(f) }
  274. } else if (f.method === 'event') this.event(u, f)
  275. })
  276. let alive = true
  277. ws.on('pong', () => { alive = true })
  278. u.ping = setInterval(() => { if (!alive) ws.terminate(); else if (ws.readyState === WebSocket.OPEN) { alive = false; ws.ping() } }, 25_000)
  279. u.ping.unref()
  280. ws.on('error', () => { if (!ready) reject(new Error('Upstream connection failed')) })
  281. ws.on('close', () => {
  282. clearTimeout(timeout); clearInterval(u.ping)
  283. if (u.socket !== ws) return
  284. u.socket = undefined; u.ready = undefined
  285. if (!ready) reject(new Error('Upstream disconnected'))
  286. for (const pending of u.pending.values()) { clearTimeout(pending.timer); pending.reject(new Error('Upstream disconnected; result unknown')) }
  287. u.pending.clear()
  288. if (!this.closed && this.upstreams.get(u.principal.upstreamKey) === u) {
  289. u.retry = setTimeout(() => { u.retry = undefined; void this.connect(u).catch(() => {}) }, Math.min(15_000, 500 * 2 ** Math.min(u.attempts++, 5)))
  290. u.retry.unref()
  291. }
  292. })
  293. })
  294. })().finally(() => { u.connecting = undefined })
  295. return u.connecting
  296. }
  297. private rpc(u: Upstream, method: string, params: Frame, observed?: (frame: Frame) => void, sent?: (frame: Frame) => void): Promise<Frame> {
  298. const id = randomUUID()
  299. if (u.socket?.readyState !== WebSocket.OPEN || u.socket.bufferedAmount > 8 * 1024 * 1024 || u.pending.size >= 128) throw new Error('Upstream unavailable or congested')
  300. const frame = { jsonrpc: '2.0', id, method, params }
  301. sent?.(frame)
  302. return new Promise((resolve, reject) => {
  303. const timer = setTimeout(() => { u.pending.delete(id); reject(new Error('Upstream command result unknown')) }, 120_000)
  304. timer.unref()
  305. u.pending.set(id, { timer, reject, resolve: response => { observed?.(response); resolve(response) } })
  306. u.socket!.send(JSON.stringify(frame), error => { if (error) { clearTimeout(timer); u.pending.delete(id); reject(error) } })
  307. })
  308. }
  309. private event(u: Upstream, f: Frame, replay = false): void {
  310. if (this.closed) return
  311. if (u.recovering && !replay) {
  312. if (u.deferred.length >= 512 || Buffer.byteLength(JSON.stringify([...u.deferred, f])) > 1024 * 1024) { u.deferred = []; this.reset(u, 'recovery_overflow') }
  313. else u.deferred.push(f)
  314. return
  315. }
  316. const p = f.params
  317. if (!p || typeof p.type !== 'string') return
  318. const sid = String(p.session_id ?? '')
  319. const r = u.byRuntime.get(sid)
  320. this.onActivity({ kind: 'event', name: p.type, sessionId: r?.stored })
  321. if (sid && !r) {
  322. const size = Buffer.byteLength(JSON.stringify(f))
  323. if (u.earlyBytes + size > 1024 * 1024) { u.early.clear(); u.earlyBytes = 0; this.reset(u, 'unmapped_event_overflow'); return }
  324. const list = u.early.get(sid) ?? []; list.push(f); u.early.set(sid, list); u.earlyBytes += size
  325. return
  326. }
  327. if (r) {
  328. if (Number.isSafeInteger(p.seq)) {
  329. if (p.seq <= r.seq) return
  330. if (r.seq > 0 && p.seq > r.seq + 1) this.reset(u, 'upstream_sequence_gap')
  331. r.seq = p.seq
  332. }
  333. if (['message.start', 'approval.request', 'clarify.request'].includes(p.type)) r.active = true
  334. if (p.type === 'message.complete') r.active = false
  335. if (p.payload?.request_id) this.interactions.set(`${u.principal.upstreamKey}:${p.payload.request_id}`, sid)
  336. while (this.interactions.size > 10_000) this.interactions.delete(this.interactions.keys().next().value!)
  337. }
  338. if (r) for (const principal of r.observers.values()) {
  339. if (principal.valid()) principal.observeEvent?.(JSON.stringify(f))
  340. }
  341. for (const c of this.channels.values()) {
  342. if (c.kind !== 'chat' || c.principal.upstreamKey !== u.principal.upstreamKey || !c.principal.valid()) continue
  343. if (r && !c.routes.has(this.routeKey(r.profile, r.stored))) continue
  344. if (!r && !['profiles.changed', 'sessions.changed', 'models.changed', 'pet.changed'].includes(p.type)) continue
  345. this.emit(c, 'frame', f)
  346. }
  347. }
  348. private async recover(u: Upstream, changed: boolean): Promise<void> {
  349. if (u.recovering) return
  350. u.recovering = true
  351. try {
  352. for (const r of u.routes.values()) {
  353. const lastSeen = r.seq
  354. const resumed = await this.rpc(u, 'session.resume', { session_id: r.stored, profile: r.profile, close_on_disconnect: false, omit_messages: true })
  355. if (typeof resumed.result?.running === 'boolean') r.active = resumed.result.running
  356. if (!resumed.result || resumed.result.session_id !== r.runtime || changed) {
  357. if (resumed.result?.session_id) { u.byRuntime.delete(r.runtime); r.runtime = resumed.result.session_id; u.byRuntime.set(r.runtime, r) }
  358. r.seq = 0; this.reset(u, 'upstream_reset'); continue
  359. }
  360. const replay = await this.rpc(u, 'session.events.since', { session_id: r.runtime, last_seen: lastSeen })
  361. if (replay.error || replay.result?.truncated || replay.result?.epoch !== u.epoch) this.reset(u, 'upstream_replay_unavailable')
  362. else for (const p of replay.result?.events ?? []) this.event(u, { jsonrpc: '2.0', method: 'event', params: p }, true)
  363. }
  364. } catch { this.reset(u, 'upstream_recovery_failed') }
  365. finally {
  366. u.recovering = false
  367. const deferred = u.deferred; u.deferred = []
  368. for (const frame of deferred) this.event(u, frame)
  369. }
  370. }
  371. private reset(u: Upstream, reason: string): void {
  372. this.onActivity({ kind: 'reset', name: reason })
  373. for (const c of this.channels.values()) if (c.kind === 'chat' && c.principal.upstreamKey === u.principal.upstreamKey) this.emit(c, 'reset', { reason })
  374. }
  375. private async connectGroup(c: RealtimeChannel): Promise<void> {
  376. const url = await c.principal.url('groups', c.group)
  377. const validator = new GroupFrameValidator(c.group!.epoch, c.group!.cursor)
  378. await new Promise<void>((resolve, reject) => {
  379. const ws = new WebSocket(url, { headers: { Origin: `${url.protocol === 'wss:' ? 'https:' : 'http:'}//${url.host}` }, maxPayload: 2 * 1024 * 1024, handshakeTimeout: 15_000 })
  380. c.socket = ws
  381. const timer = setTimeout(() => { ws.terminate(); reject(new Error('Group ready timeout')) }, 20_000)
  382. ws.on('message', (data, binary) => {
  383. try {
  384. if (!validator.accept(data, binary)) return
  385. const frame = JSON.parse(data.toString()) as Frame
  386. this.onActivity({ kind: 'group', name: String(frame.event ?? frame.type), roomId: frame.roomId })
  387. if (frame.type === 'group.ready') { clearTimeout(timer); resolve() }
  388. if (frame.type === 'group.event') c.group!.cursor = frame.cursor
  389. this.emit(c, 'frame', frame)
  390. } catch { this.emit(c, 'reset', { reason: 'group_gap' }); ws.close() }
  391. })
  392. ws.on('error', () => { clearTimeout(timer); reject(new Error('Group connection failed')) })
  393. ws.on('close', () => { clearTimeout(timer); reject(new Error('Group disconnected')); this.onActivity({ kind: 'group', name: 'group_disconnected' }); if (this.channels.has(c.id)) this.emit(c, 'reset', { reason: 'group_disconnected' }) })
  394. })
  395. }
  396. private emit(c: RealtimeChannel, event: StreamEntry['event'], value: Frame): void {
  397. const data = JSON.stringify(value)
  398. const entry: StreamEntry = { id: `${this.epoch}:${++c.seq}`, event, data, at: this.now(), bytes: Buffer.byteLength(data) }
  399. c.entries.push(entry); c.bytes += entry.bytes
  400. this.trim(c)
  401. for (const listener of [...c.listeners]) {
  402. try { listener(entry) } catch { c.listeners.delete(listener) }
  403. }
  404. }
  405. private trim(c: RealtimeChannel): void {
  406. const own = [...this.channels.values()].filter(v => v.principal.key === c.principal.key)
  407. while (own.reduce((n, v) => n + v.bytes, 0) > 8 * 1024 * 1024 || own.reduce((n, v) => n + v.entries.length, 0) > 10_000) {
  408. const oldest = own.filter(v => v.entries.length).sort((a, b) => a.entries[0]!.at - b.entries[0]!.at)[0]
  409. if (!oldest) break
  410. this.evict(oldest)
  411. }
  412. while (c.entries[0] && c.entries[0].at < this.now() - 600_000) this.evict(c)
  413. while ([...this.channels.values()].reduce((n, v) => n + v.bytes, 0) > 128 * 1024 * 1024) {
  414. const oldest = [...this.channels.values()].filter(v => v.entries.length).sort((a, b) => a.entries[0]!.at - b.entries[0]!.at)[0]
  415. if (!oldest) break
  416. this.evict(oldest)
  417. }
  418. }
  419. private evict(c: RealtimeChannel): void {
  420. const entry = c.entries.shift()!
  421. c.bytes -= entry.bytes; c.droppedThrough = Number(entry.id.split(':').at(-1))
  422. }
  423. private sweep(): void {
  424. for (const [key, item] of this.completed) if (item.at < this.now() - 600_000) this.completed.delete(key)
  425. for (const c of this.channels.values()) {
  426. if (!c.principal.valid() || (!c.listeners.size && this.now() - c.touched > 600_000)) this.remove(c)
  427. else this.trim(c)
  428. }
  429. for (const [key, u] of this.upstreams) {
  430. if (u.pending.size || u.tails.size || [...u.routes.values()].some(r => r.active)) { u.lastUsed = this.now(); continue }
  431. if ([...this.channels.values()].some(c => c.principal.upstreamKey === key)) { u.lastUsed = this.now(); continue }
  432. if (this.now() - u.lastUsed > 300_000) {
  433. this.upstreams.delete(key); clearTimeout(u.retry); clearInterval(u.ping); u.socket?.close()
  434. for (const [route, owner] of this.routeOwners) if (owner === key) this.routeOwners.delete(route)
  435. }
  436. }
  437. }
  438. close(): void {
  439. if (this.closed) return
  440. this.closed = true; clearInterval(this.timer)
  441. for (const c of [...this.channels.values()]) this.remove(c)
  442. for (const u of this.upstreams.values()) {
  443. clearTimeout(u.retry); clearInterval(u.ping)
  444. for (const p of u.pending.values()) { clearTimeout(p.timer); p.reject(new Error('Broker stopped')) }
  445. u.pending.clear(); u.socket?.terminate()
  446. }
  447. // Pending command continuations may still update their receipts in the next microtask.
  448. void Promise.allSettled(this.commands.values()).then(() => this.receipts.close())
  449. }
  450. }