Skip to content

Commit 4517cd5

Browse files
committed
fix: worker emit back persist event
1 parent 03178fb commit 4517cd5

File tree

2 files changed

+20
-10
lines changed

2 files changed

+20
-10
lines changed

src/persist-worker-thread.js

+2
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,13 @@ export class PersistWorkerThread {
2525
* @param {{ room: string, docstate: SharedArrayBuffer }} props
2626
*/
2727
persist = async ({ room, docstate }) => {
28+
this.log(`persisting ${room} in worker`)
2829
const state = new Uint8Array(docstate)
2930
const doc = new Y.Doc()
3031
Y.applyUpdateV2(doc, state)
3132
await this.store?.persistDoc(room, 'index', doc)
3233
doc.destroy()
34+
parentPort?.postMessage({ event: 'persisted', room })
3335
}
3436
}
3537

src/y-socket-io/y-socket-io.js

+18-10
Original file line numberDiff line numberDiff line change
@@ -478,16 +478,17 @@ export class YSocketIO {
478478
async debouncedPersist (namespace, doc) {
479479
this.debouncedPersistDocMap.set(namespace, doc)
480480
if (this.debouncedPersistMap.has(namespace)) return
481-
this.debouncedPersistMap.set(
482-
namespace,
483-
setTimeout(
484-
async () => {
481+
const timeout = setTimeout(
482+
async () => {
483+
try {
485484
assert(this.client)
486485
const doc = this.debouncedPersistDocMap.get(namespace)
486+
logSocketIO(`trying to persist ${namespace}`)
487487
if (!doc) return
488+
/** @type {Promise<void> | null} */
489+
let workerPromise = null
488490
if (this.client.persistWorker) {
489-
/** @type {Promise<void>} */
490-
const promise = new Promise((resolve) => {
491+
workerPromise = new Promise((resolve) => {
491492
assert(this.client?.persistWorker)
492493
this.awaitingPersistMap.set(namespace, resolve)
493494

@@ -499,17 +500,24 @@ export class YSocketIO {
499500
docstate: buf
500501
})
501502
})
502-
await promise
503+
if (workerPromise) {
504+
await workerPromise
505+
}
503506
} else {
504507
await this.client.store.persistDoc(namespace, 'index', doc)
505508
}
506509
await this.client.trimRoomStream(namespace, 'index', true)
510+
} catch (e) {
511+
console.error(e)
512+
} finally {
507513
this.debouncedPersistDocMap.delete(namespace)
508514
this.debouncedPersistMap.delete(namespace)
509-
},
510-
PERSIST_INTERVAL + (Math.random() - 0.5) * PERSIST_INTERVAL
511-
)
515+
}
516+
},
517+
PERSIST_INTERVAL + (Math.random() - 0.5) * PERSIST_INTERVAL
512518
)
519+
520+
this.debouncedPersistMap.set(namespace, timeout)
513521
}
514522

515523
/**

0 commit comments

Comments
 (0)