@@ -34,6 +34,7 @@ import {
3434
3535import { ReliableChannelEvent , ReliableChannelEvents } from "./events.js" ;
3636import { MissingMessageRetriever } from "./missing_message_retriever.js" ;
37+ import { RandomTimeout } from "./random_timeout.js" ;
3738import { RetryManager } from "./retry_manager.js" ;
3839import { SyncStatus } from "./sync_status.js" ;
3940
@@ -150,8 +151,7 @@ export class ReliableChannel<
150151 options ?: Partial < QueryRequestParams >
151152 ) => AsyncGenerator < Promise < T | undefined > [ ] > ;
152153
153- private readonly syncMinIntervalMs : number ;
154- private syncTimeout : ReturnType < typeof setTimeout > | undefined ;
154+ private syncRandomTimeout : RandomTimeout ;
155155 private sweepInBufInterval : ReturnType < typeof setInterval > | undefined ;
156156 private readonly sweepInBufIntervalMs : number ;
157157 private processTaskTimeout : ReturnType < typeof setTimeout > | undefined ;
@@ -205,8 +205,11 @@ export class ReliableChannel<
205205 }
206206 }
207207
208- this . syncMinIntervalMs =
209- options ?. syncMinIntervalMs ?? DEFAULT_SYNC_MIN_INTERVAL_MS ;
208+ this . syncRandomTimeout = new RandomTimeout (
209+ options ?. syncMinIntervalMs ?? DEFAULT_SYNC_MIN_INTERVAL_MS ,
210+ 2 ,
211+ this . sendSyncMessage . bind ( this )
212+ ) ;
210213
211214 this . sweepInBufIntervalMs =
212215 options ?. sweepInBufIntervalMs ?? DEFAULT_SWEEP_IN_BUF_INTERVAL_MS ;
@@ -242,7 +245,7 @@ export class ReliableChannel<
242245
243246 /**
244247 * Emit events when the channel is aware of missing message.
245- * Note that "syncd " may mean some messages are irretrievably lost.
248+ * Note that "synced " may mean some messages are irretrievably lost.
246249 * Check the emitted data for details.
247250 *
248251 * @emits [[StatusEvents]]
@@ -547,30 +550,11 @@ export class ReliableChannel<
547550 }
548551
549552 private restartSync ( multiplier : number = 1 ) : void {
550- if ( this . syncTimeout ) {
551- clearTimeout ( this . syncTimeout ) ;
552- }
553- if ( this . syncMinIntervalMs ) {
554- const timeoutMs = this . random ( ) * this . syncMinIntervalMs * multiplier ;
555-
556- this . syncTimeout = setTimeout ( ( ) => {
557- void this . sendSyncMessage ( ) ;
558- // Always restart a sync, no matter whether the message was sent.
559- // Set a multiplier so we wait a bit longer to not hog the conversation
560- void this . restartSync ( 2 ) ;
561- } , timeoutMs ) ;
562- }
553+ this . syncRandomTimeout . restart ( multiplier ) ;
563554 }
564555
565556 private stopSync ( ) : void {
566- if ( this . syncTimeout ) {
567- clearTimeout ( this . syncTimeout ) ;
568- }
569- }
570-
571- // Used to enable overriding when testing
572- private random ( ) : number {
573- return Math . random ( ) ;
557+ this . syncRandomTimeout . stop ( ) ;
574558 }
575559
576560 private safeSendEvent < T extends ReliableChannelEvent > (
0 commit comments