@@ -4,10 +4,21 @@ import { appendRegularFile, resolveRegularFileAppendFlags } from "../infra/fs-sa
44
55export type QueuedFileWriteResult = "queued" | "dropped" ;
66
7+ export type QueuedFileWriterDiagnostics = {
8+ pendingWrites : number ;
9+ queuedBytes : number ;
10+ activeOperation : "idle" | "mkdir" | "yield" | "file-append" ;
11+ activeWriteBytes ?: number ;
12+ maxFileBytes ?: number ;
13+ maxQueuedBytes ?: number ;
14+ yieldBeforeWrite : boolean ;
15+ } ;
16+
717export type QueuedFileWriter = {
818 filePath : string ;
919 write : ( line : string ) => unknown ;
1020 flush : ( ) => Promise < void > ;
21+ describeQueue ?: ( ) => QueuedFileWriterDiagnostics ;
1122} ;
1223
1324type QueuedFileWriterOptions = {
@@ -50,7 +61,10 @@ export function getQueuedFileWriter(
5061 const dir = path . dirname ( filePath ) ;
5162 const ready = fs . mkdir ( dir , { recursive : true , mode : 0o700 } ) . catch ( ( ) => undefined ) ;
5263 let queue : Promise < unknown > = Promise . resolve ( ) ;
64+ let pendingWrites = 0 ;
5365 let queuedBytes = 0 ;
66+ let activeOperation : QueuedFileWriterDiagnostics [ "activeOperation" ] = "idle" ;
67+ let activeWriteBytes : number | undefined ;
5468
5569 const writer : QueuedFileWriter = {
5670 filePath,
@@ -62,20 +76,45 @@ export function getQueuedFileWriter(
6276 ) {
6377 return "dropped" ;
6478 }
79+ pendingWrites += 1 ;
6580 queuedBytes += lineBytes ;
6681 queue = queue
67- . then ( ( ) => ready )
68- . then ( ( ) => ( options . yieldBeforeWrite ? waitForImmediate ( ) : undefined ) )
69- . then ( ( ) => safeAppendFile ( filePath , line , options ) )
82+ . then ( async ( ) => {
83+ activeOperation = "mkdir" ;
84+ await ready ;
85+ } )
86+ . then ( async ( ) => {
87+ if ( options . yieldBeforeWrite ) {
88+ activeOperation = "yield" ;
89+ await waitForImmediate ( ) ;
90+ }
91+ } )
92+ . then ( async ( ) => {
93+ activeOperation = "file-append" ;
94+ activeWriteBytes = lineBytes ;
95+ await safeAppendFile ( filePath , line , options ) ;
96+ } )
7097 . catch ( ( ) => undefined )
7198 . finally ( ( ) => {
99+ pendingWrites = Math . max ( 0 , pendingWrites - 1 ) ;
72100 queuedBytes = Math . max ( 0 , queuedBytes - lineBytes ) ;
101+ activeWriteBytes = undefined ;
102+ activeOperation = pendingWrites > 0 ? activeOperation : "idle" ;
73103 } ) ;
74104 return "queued" ;
75105 } ,
76106 flush : async ( ) => {
77107 await queue ;
78108 } ,
109+ describeQueue : ( ) => ( {
110+ pendingWrites,
111+ queuedBytes,
112+ activeOperation,
113+ activeWriteBytes,
114+ maxFileBytes : options . maxFileBytes ,
115+ maxQueuedBytes : options . maxQueuedBytes ,
116+ yieldBeforeWrite : options . yieldBeforeWrite === true ,
117+ } ) ,
79118 } ;
80119
81120 writers . set ( filePath , writer ) ;
0 commit comments