MCPcopy Create free account
hub / github.com/colbymchenry/codegraph / subscribe

Method subscribe

src/ui-server/api/events.ts:187–247  ·  view source on GitHub ↗

* Attach one browser to the stream. * * Returns `true` in every case — the response is answered here, streaming or * not — so it slots into the API's `switch` like any other endpoint.

(req: IncomingMessage, res: ServerResponse, method: string)

Source from the content-addressed store, hash-verified

185 * not — so it slots into the API's `switch` like any other endpoint.
186 */
187 subscribe(req: IncomingMessage, res: ServerResponse, method: string): true {
188 if (this.closed) {
189 // The server is shutting down. Answer, do not attach: a client that got a
190 // stream here would hold the socket open against `close()`.
191 res.writeHead(503, {
192 'Content-Type': 'application/json; charset=utf-8',
193 'Cache-Control': 'no-store',
194 });
195 res.end(method === 'HEAD' ? undefined : JSON.stringify({ error: 'Shutting down.', code: 'internal' }));
196 return true;
197 }
198
199 res.writeHead(200, {
200 'Content-Type': 'text/event-stream; charset=utf-8',
201 'Cache-Control': 'no-store',
202 // Node would otherwise chunk small writes; an event that sits in a buffer
203 // is an event that did not happen.
204 Connection: 'keep-alive',
205 'X-Accel-Buffering': 'no',
206 });
207
208 if (method === 'HEAD') {
209 res.end();
210 return true;
211 }
212
213 // No keep-alive timeout on this socket: the server sets one globally so
214 // Ctrl-C does not wait on browser connections, and it would close a healthy
215 // stream between heartbeats.
216 res.socket?.setTimeout(0);
217 res.socket?.setNoDelay(true);
218
219 this.ensureWatching();
220
221 const client: Client = {
222 res,
223 heartbeat: setInterval(() => {
224 // A comment frame. Not an event, so no client handler ever sees it —
225 // it exists to notice a socket the other end has already dropped.
226 if (!res.writableEnded) res.write(': ping\n\n');
227 }, HEARTBEAT_MS),
228 };
229 // `unref` so a live stream never keeps the process alive on its own.
230 client.heartbeat.unref?.();
231 this.clients.add(client);
232
233 const drop = (): void => this.drop(client);
234 res.on('close', drop);
235 res.on('error', drop);
236 req.on('aborted', drop);
237
238 this.send(client, {
239 type: 'hello',
240 index: this.revision,
241 watching: { source: this.sourceUp, index: this.indexUp },
242 degraded: this.degraded,
243 heartbeatMs: HEARTBEAT_MS,
244 at: Date.now(),

Callers 2

handlerFunction · 0.80
mountPanelFunction · 0.80

Calls 5

ensureWatchingMethod · 0.95
sendMethod · 0.95
writeMethod · 0.65
onMethod · 0.65
addMethod · 0.45

Tested by 1

mountPanelFunction · 0.64