Skip to content

Commit

Permalink
feat: queue up ydoc sync task
Browse files Browse the repository at this point in the history
  • Loading branch information
galaxian85 committed Jan 17, 2025
1 parent e342bde commit eb99a03
Showing 1 changed file with 45 additions and 10 deletions.
55 changes: 45 additions & 10 deletions src/y-socket-io/y-socket-io.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,12 @@ export class YSocketIO {
*/
namespaceMap = new Map()

/**
* @type {Promise<void>[]}
* @private
*/
syncQueue = []

/**
* YSocketIO constructor.
* @constructor
Expand Down Expand Up @@ -157,16 +163,26 @@ export class YSocketIO {
this.initAwarenessListeners(socket)
this.initSocketListeners(socket)

const doc = await this.client.getDoc(namespace, 'index')

if (
api.isSmallerRedisId(doc.redisLastId, socket.user.initialRedisSubId)
) {
// our subscription is newer than the content that we received from the api
// need to renew subscription id and make sure that we catch the latest content.
this.subscriber.ensureSubId(stream, doc.redisLastId)
}
this.startSynchronization(socket, doc)
/**
* @type {Promise<void>}
*/
const task = new Promise((resolve) => {
assert(this.client)
this.client.getDoc(namespace, 'index').then((doc) => {
assert(socket.user)
assert(this.subscriber)
if (
api.isSmallerRedisId(doc.redisLastId, socket.user.initialRedisSubId)
) {
// our subscription is newer than the content that we received from the api
// need to renew subscription id and make sure that we catch the latest content.
this.subscriber.ensureSubId(stream, doc.redisLastId)
}
this.startSynchronization(socket, doc)
resolve()
})
})
this.queueUpSyncTask(task)
})

return { client, subscriber }
Expand Down Expand Up @@ -336,6 +352,25 @@ export class YSocketIO {
}
}

/**
* @private
* @param {Promise<void>} task
*/
queueUpSyncTask (task) {
const len = this.syncQueue.push(task)
if (len === 1) this.consumeSyncQueue()
}

/**
* @private
*/
async consumeSyncQueue () {
if (this.syncQueue.length === 0) return
const task = this.syncQueue.shift()
await task
this.consumeSyncQueue()
}

/**
* @param {Namespace} namespace
*/
Expand Down

0 comments on commit eb99a03

Please sign in to comment.