@@ -136,6 +136,12 @@ export class YSocketIO {
136
136
* @readonly
137
137
*/
138
138
namespacePersistentMap = new Map ( )
139
+ /**
140
+ * @type {Map<string, () => void> }
141
+ * @private
142
+ * @readonly
143
+ */
144
+ awaitingPersistMap = new Map ( )
139
145
140
146
/**
141
147
* YSocketIO constructor.
@@ -156,16 +162,20 @@ export class YSocketIO {
156
162
*
157
163
* It also starts socket connection listeners.
158
164
* @param {import('../storage.js').AbstractStorage } store
159
- * @param {{ redisPrefix?: string, redisUrl?: string }= } opts
165
+ * @param {{ redisPrefix?: string, redisUrl?: string, persistWorker?: import('worker_threads').Worker }= } opts
160
166
* @public
161
167
*/
162
- async initialize ( store , { redisUrl, redisPrefix = 'y' } = { } ) {
168
+ async initialize ( store , { redisUrl, redisPrefix = 'y' , persistWorker } = { } ) {
163
169
const [ client , subscriber ] = await promise . all ( [
164
170
api . createApiClient ( store , { redisUrl, redisPrefix } ) ,
165
171
createSubscriber ( store , { redisUrl, redisPrefix } )
166
172
] )
167
173
this . client = client
168
174
this . subscriber = subscriber
175
+ if ( persistWorker ) {
176
+ this . client . persistWorker = persistWorker
177
+ this . registerPersistWorkerResolve ( )
178
+ }
169
179
170
180
this . nsp = this . io . of ( / ^ \/ y j s \| .* $ / )
171
181
@@ -475,7 +485,24 @@ export class YSocketIO {
475
485
assert ( this . client )
476
486
const doc = this . debouncedPersistDocMap . get ( namespace )
477
487
if ( ! doc ) return
478
- await this . client . store . persistDoc ( namespace , 'index' , doc )
488
+ if ( this . client . persistWorker ) {
489
+ /** @type {Promise<void> } */
490
+ const promise = new Promise ( ( res ) => {
491
+ assert ( this . client ?. persistWorker )
492
+ this . awaitingPersistMap . set ( namespace , res )
493
+
494
+ const docState = Y . encodeStateAsUpdateV2 ( doc )
495
+ const buf = new Uint8Array ( new SharedArrayBuffer ( docState . length ) )
496
+ buf . set ( docState )
497
+ this . client . persistWorker . postMessage ( {
498
+ room : namespace ,
499
+ docstate : buf
500
+ } )
501
+ } )
502
+ await promise
503
+ } else {
504
+ await this . client . store . persistDoc ( namespace , 'index' , doc )
505
+ }
479
506
await this . client . trimRoomStream ( namespace , 'index' , true )
480
507
this . debouncedPersistDocMap . delete ( namespace )
481
508
this . debouncedPersistMap . delete ( namespace )
@@ -569,4 +596,11 @@ export class YSocketIO {
569
596
console . error ( e )
570
597
}
571
598
}
599
+
600
+ registerPersistWorkerResolve ( ) {
601
+ if ( ! this . client ?. persistWorker ) return
602
+ this . client . persistWorker . on ( 'message' , ( { event, room } ) => {
603
+ if ( event === 'persisted' ) this . awaitingPersistMap . get ( room ) ?. ( )
604
+ } )
605
+ }
572
606
}
0 commit comments