Improve latency of both process.stdout and asciinema stdout writes.

This commit is contained in:
Mario Zechner 2025-06-24 17:47:16 +02:00
parent f339e69f9a
commit 45f217e143
2 changed files with 28 additions and 14 deletions

View file

@ -159,17 +159,19 @@ export class AsciinemaWriter {
const eventJson = JSON.stringify(eventArray);
this.writeStream.write(eventJson + '\n');
// Force immediate disk write to trigger file watchers
// Force immediate disk write to trigger file watchers asynchronously
if (this.fd !== null) {
try {
/*fs.fsync(this.fd, (err) => {
if (err) {
logger.error(`Failed to fsync asciinema file: ${err.message}`);
}
});*/
fs.fsyncSync(this.fd);
} catch (_e) {
// Ignore sync errors
// Use setImmediate to avoid blocking the event loop
if (this.fd !== null) {
try {
fs.fsync(this.fd, (err) => {
if (err) {
// Ignore sync errors
}
});
} catch (_e) {
// Ignore sync errors
}
}
}
}

View file

@ -334,7 +334,7 @@ export class PtyManager extends EventEmitter {
const { ptyProcess, asciinemaWriter } = session;
// Handle PTY data output
ptyProcess?.onData((data: string) => {
ptyProcess?.onData(async (data: string) => {
try {
// Check for bell character (ASCII 7) - filter out OSC sequences
if (data.includes('\x07')) {
@ -366,13 +366,25 @@ export class PtyManager extends EventEmitter {
}
}
// Write to asciinema file (now async, non-blocking)
asciinemaWriter?.writeOutput(Buffer.from(data, 'utf8'));
// Execute both writes in parallel
const promises: Promise<void>[] = [];
// Forward to stdout if requested (for fwd.ts) with batching
// Write to asciinema file
promises.push(
Promise.resolve().then(() => {
asciinemaWriter?.writeOutput(Buffer.from(data, 'utf8'));
})
);
// Forward to stdout if requested
if (forwardToStdout) {
process.stdout.write(data);
}
// Wait for both operations to complete
if (promises.length > 0) {
await Promise.all(promises);
}
} catch (error) {
logger.error(`Failed to write PTY data for session ${session.id}:`, error);
}