@@ -222,28 +222,30 @@ export class StreamsWriterV2<T = any> implements StreamsWriter {
222222 }
223223
224224 private async initializeServerStream ( ) : Promise < void > {
225- this . log ( "[S2MetadataStream] Waiting for buffer task to complete" ) ;
226- // Wait for buffer task and all flushes to complete
227- await this . bufferReaderTask ;
228-
229- this . log (
230- `[S2MetadataStream] Buffer task complete, performing final flush (${ this . pendingFlushes . length } pending chunks)`
231- ) ;
232- // Final flush
233- await this . flush ( ) ;
234-
235- this . log ( `[S2MetadataStream] Waiting for ${ this . flushPromises . length } flush promises` ) ;
236- // Wait for all pending flushes
237- await Promise . all ( this . flushPromises ) ;
238-
239- this . log ( "[S2MetadataStream] All flushes complete, cleaning up" ) ;
240- // Clean up
241- if ( this . flushInterval ) {
242- clearInterval ( this . flushInterval ) ;
243- this . flushInterval = null ;
225+ try {
226+ this . log ( "[S2MetadataStream] Waiting for buffer task to complete" ) ;
227+ // Wait for buffer task and all flushes to complete
228+ await this . bufferReaderTask ;
229+
230+ this . log (
231+ `[S2MetadataStream] Buffer task complete, performing final flush (${ this . pendingFlushes . length } pending chunks)`
232+ ) ;
233+ // Final flush
234+ await this . flush ( ) ;
235+
236+ this . log ( `[S2MetadataStream] Waiting for ${ this . flushPromises . length } flush promises` ) ;
237+ // Wait for all pending flushes
238+ await Promise . all ( this . flushPromises ) ;
239+
240+ this . log ( "[S2MetadataStream] Stream completed successfully" ) ;
241+ } finally {
242+ // Clean up interval to prevent timer leak
243+ this . log ( "[S2MetadataStream] Cleaning up flush interval" ) ;
244+ if ( this . flushInterval ) {
245+ clearInterval ( this . flushInterval ) ;
246+ this . flushInterval = null ;
247+ }
244248 }
245-
246- this . log ( "[S2MetadataStream] Stream completed successfully" ) ;
247249 }
248250
249251 public async wait ( ) : Promise < void > {
0 commit comments