MCPcopy Index your code
hub / github.com/editablejs/editable / setupWSConnection

Function setupWSConnection

packages/yjs-websocket/src/server/utils.ts:288–359  ·  view source on GitHub ↗
(
  conn: WebSocket.WebSocket,
  req: http.IncomingMessage,
  options?: SetupWSConnectionOptions,
)

Source from the content-addressed store, hash-verified

286}
287
288export const setupWSConnection = (
289 conn: WebSocket.WebSocket,
290 req: http.IncomingMessage,
291 options?: SetupWSConnectionOptions,
292) => {
293 const {
294 docName = req.url!.slice(1).split('?')[0],
295 gc = true,
296 initialValue,
297 pingTimeout = 30000,
298 callback,
299 } = options ?? {}
300 conn.binaryType = 'arraybuffer'
301 // get doc, initialize if it does not exist yet
302 const doc = getYDoc(docName, gc, initialValue, callback)
303 doc.conns.set(conn, new Set())
304 doc.on('subDocLoaded', subDoc => {
305 const encoder = encoding.createEncoder()
306 encoding.writeVarUint(encoder, messageSubDocSync)
307 encoding.writeVarString(encoder, subDoc.guid)
308 syncProtocol.writeSyncStep1(encoder, subDoc)
309 send(doc, conn, encoding.toUint8Array(encoder))
310 })
311 // listen and reply to events
312 conn.on('message', (message: ArrayBuffer) => messageListener(conn, doc, new Uint8Array(message)))
313
314 // Check if connection is still alive
315 let pongReceived = true
316 const pingInterval = setInterval(() => {
317 if (!pongReceived) {
318 if (doc.conns.has(conn)) {
319 closeConn(doc, conn)
320 }
321 clearInterval(pingInterval)
322 } else if (doc.conns.has(conn)) {
323 pongReceived = false
324 try {
325 conn.ping()
326 } catch (e) {
327 closeConn(doc, conn)
328 clearInterval(pingInterval)
329 }
330 }
331 }, pingTimeout)
332 conn.on('close', () => {
333 closeConn(doc, conn)
334 clearInterval(pingInterval)
335 })
336 conn.on('pong', () => {
337 pongReceived = true
338 })
339 // put the following in a variables in a block so the interval handlers don't keep in in
340 // scope
341 {
342 // send sync step 1
343 const encoder = encoding.createEncoder()
344 encoding.writeVarUint(encoder, messageSync)
345 encoding.writeAny(encoder, {})

Callers 1

start.tsFile · 0.90

Calls 6

getYDocFunction · 0.85
sendFunction · 0.85
messageListenerFunction · 0.85
closeConnFunction · 0.85
onMethod · 0.80
getStatesMethod · 0.80

Tested by

no test coverage detected