httpRealtime.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import type { JsonValue } from '@shared/types'
  2. import { SSEParser } from '@shared/sse'
  3. import { apiRequest, ApiError, setApiCsrfToken } from './client'
  4. import { createId } from '@/utils/id'
  5. export class HTTPRPCError extends Error {
  6. constructor(message: string, readonly code?: string | number, readonly data?: JsonValue) { super(message) }
  7. }
  8. export class HTTPRealtimeChannel {
  9. private id = ''
  10. private cursor = ''
  11. private stopped = false
  12. private abort?: AbortController
  13. private ready = false
  14. constructor(readonly onFrame: (frame: string) => Promise<unknown>, readonly onFailure: (error: Error) => void) {}
  15. static async requireSupport(): Promise<string[]> {
  16. let value: { protocolVersion: number; csrfToken?: string; features?: string[] }
  17. try { value = await apiRequest('/api/realtime/capabilities') }
  18. catch (e) {
  19. if (e instanceof ApiError && [404, 405, 410].includes(e.status)) throw new ApiError('此服务端不支持 HTTP+SSE,请升级 15300 服务', 409, 'HTTP_SSE_REQUIRED')
  20. throw e
  21. }
  22. if (value.protocolVersion !== 1) throw new ApiError('不支持的实时协议版本', 409, 'UNSUPPORTED_REALTIME_PROTOCOL')
  23. if (value.csrfToken) setApiCsrfToken(value.csrfToken)
  24. return value.features ?? []
  25. }
  26. async open(channel: 'chat' | 'groups', anchor?: { epoch: string; cursor: number }): Promise<void> {
  27. const created = await apiRequest<{ id: string }>('/api/realtime/channels', { method: 'POST', body: { channel, ...anchor } })
  28. this.id = created.id
  29. if (this.stopped) { this.close(); return }
  30. await new Promise<void>((resolve, reject) => {
  31. const timer = window.setTimeout(() => { this.abort?.abort(); reject(new ApiError('实时事件握手超时', 0, 'REALTIME_READY_TIMEOUT')) }, 20_000)
  32. void this.readLoop(() => { window.clearTimeout(timer); this.ready = true; resolve() }).catch(error => {
  33. window.clearTimeout(timer)
  34. if (!this.ready) reject(error)
  35. if (!this.stopped) this.onFailure(error instanceof Error ? error : new Error(String(error)))
  36. })
  37. })
  38. }
  39. private async readLoop(onReady: () => void): Promise<void> {
  40. let attempt = 0
  41. while (!this.stopped) {
  42. this.abort = new AbortController()
  43. let reader: ReadableStreamDefaultReader<Uint8Array> | undefined
  44. let watchdog: number | undefined
  45. try {
  46. const headers: Record<string, string> = { Accept: 'text/event-stream' }
  47. if (this.cursor) headers['Last-Event-ID'] = this.cursor
  48. const response = await fetch(`/api/realtime/channels/${this.id}/events`, { credentials: 'same-origin', headers, signal: this.abort.signal, cache: 'no-store' })
  49. if ([401, 403, 404, 409, 428].includes(response.status)) throw new ApiError('实时连接需要重新同步', response.status, 'REALTIME_RESET_REQUIRED')
  50. if (!response.ok) throw new Error(`SSE HTTP ${response.status}`)
  51. if (!response.headers.get('content-type')?.startsWith('text/event-stream') || !response.body) throw new ApiError('无效的事件流响应', 502, 'INVALID_EVENT_STREAM')
  52. reader = response.body.getReader()
  53. const parser = new SSEParser(), decoder = new TextDecoder()
  54. while (!this.stopped) {
  55. window.clearTimeout(watchdog)
  56. watchdog = window.setTimeout(() => this.abort?.abort(), 45_000)
  57. const { value, done } = await reader.read()
  58. if (done) throw new Error('SSE disconnected')
  59. attempt = 0
  60. for (const entry of parser.feed(decoder.decode(value, { stream: true }))) {
  61. if (entry.event === 'reset') throw new ApiError('事件需要重新同步', 409, 'REALTIME_RESET_REQUIRED')
  62. if (entry.event === 'ready') continue
  63. if (entry.event !== 'frame') continue
  64. if (entry.id && entry.id === this.cursor) continue
  65. await this.onFrame(entry.data)
  66. if (entry.id) this.cursor = entry.id
  67. const frame = JSON.parse(entry.data)
  68. if (frame.type === 'group.ready' || frame.params?.type === 'gateway.ready') onReady()
  69. }
  70. }
  71. } catch (error) {
  72. if (this.stopped) return
  73. if (error instanceof ApiError) throw error
  74. } finally { window.clearTimeout(watchdog); await reader?.cancel().catch(() => {}); reader?.releaseLock() }
  75. await new Promise(r => window.setTimeout(r, Math.min(15_000, 500 * 2 ** Math.min(attempt++, 5))))
  76. }
  77. }
  78. async request(method: string, params: Record<string, JsonValue>, timeoutMs: number, requestId = createId('http-rpc')): Promise<JsonValue> {
  79. if (!this.ready || this.stopped) throw new ApiError('事件通道尚未就绪', 0, 'REALTIME_NOT_READY')
  80. type Receipt = { state: string; response?: { result?: JsonValue; error?: { message?: string; code?: string | number; data?: JsonValue } } }
  81. let receipt: Receipt
  82. try {
  83. receipt = await apiRequest(`/api/realtime/channels/${this.id}/commands`, {
  84. method: 'POST', headers: { 'Idempotency-Key': requestId }, body: { jsonrpc: '2.0', method, params }, timeoutMs,
  85. })
  86. } catch (error) {
  87. if (error instanceof ApiError && error.status >= 400 && error.status < 500) throw error
  88. try { receipt = await apiRequest(`/api/realtime/commands/${encodeURIComponent(requestId)}`) }
  89. catch { throw new ApiError('提交结果未知,请同步历史确认', 0, 'SUBMISSION_UNCERTAIN') }
  90. }
  91. if (receipt.state === 'unknown' || receipt.state === 'pending') throw new ApiError('提交结果未知,请同步历史确认', 0, 'SUBMISSION_UNCERTAIN')
  92. if (receipt.response?.error) throw new HTTPRPCError(receipt.response.error.message ?? '上游拒绝请求', receipt.response.error.code, receipt.response.error.data)
  93. if (receipt.state !== 'confirmed') throw new ApiError('无效的命令回执', 502, 'INVALID_RECEIPT')
  94. return receipt.response?.result ?? null
  95. }
  96. close(): void {
  97. this.stopped = true; this.abort?.abort()
  98. if (this.id) { const id = this.id; this.id = ''; void apiRequest(`/api/realtime/channels/${id}`, { method: 'DELETE' }).catch(() => {}) }
  99. }
  100. }