(room: string)
| 134 | } |
| 135 | |
| 136 | private async subscribe(room: string): Promise<void> { |
| 137 | return new Promise(async (resolve, reject) => { |
| 138 | try { |
| 139 | const controller = new AbortController() |
| 140 | this.controllers.set(room, controller) |
| 141 | |
| 142 | // initialize heartbeat |
| 143 | this.lastPingTimes.set(room, Date.now()) |
| 144 | |
| 145 | const stream = await fetch(`${this.redisUrl}/subscribe/${room}`, { |
| 146 | headers: { |
| 147 | Authorization: `Bearer ${this.redisToken}`, |
| 148 | accept: "text/event-stream", |
| 149 | }, |
| 150 | signal: controller.signal, |
| 151 | }) |
| 152 | |
| 153 | const reader = stream.body?.getReader() |
| 154 | const decoder = new TextDecoder() |
| 155 | let buffer = "" |
| 156 | |
| 157 | while (reader) { |
| 158 | const { done, value } = await reader.read() |
| 159 | |
| 160 | // continue execution once connection is established |
| 161 | // otherwise subscription below would be blocking |
| 162 | resolve() |
| 163 | |
| 164 | if (done) break |
| 165 | |
| 166 | const chunk = decoder.decode(value) |
| 167 | buffer += chunk |
| 168 | |
| 169 | const messages = buffer.split("\n") |
| 170 | buffer = messages.pop() || "" |
| 171 | |
| 172 | for (const message of messages) { |
| 173 | logger.info("Received message:", message) |
| 174 | if (message.startsWith("data: ")) { |
| 175 | const data = message.slice(6) |
| 176 | try { |
| 177 | // extract payload from message format: message,room,payload |
| 178 | // skip first two commas to get the start of the payload |
| 179 | const firstCommaIndex = data.indexOf(",") |
| 180 | const secondCommaIndex = data.indexOf(",", firstCommaIndex + 1) |
| 181 | |
| 182 | if (firstCommaIndex === -1 || secondCommaIndex === -1) { |
| 183 | logger.warn("Invalid message format - missing commas") |
| 184 | continue |
| 185 | } |
| 186 | |
| 187 | const payloadStr = data.slice(secondCommaIndex + 1) |
| 188 | |
| 189 | if (!payloadStr) { |
| 190 | logger.warn("Missing payload in message") |
| 191 | continue |
| 192 | } |
| 193 |
no outgoing calls
no test coverage detected