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); const eventJson = JSON.stringify(eventArray);
this.writeStream.write(eventJson + '\n'); 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) { if (this.fd !== null) {
try { // Use setImmediate to avoid blocking the event loop
/*fs.fsync(this.fd, (err) => { if (this.fd !== null) {
if (err) { try {
logger.error(`Failed to fsync asciinema file: ${err.message}`); fs.fsync(this.fd, (err) => {
} if (err) {
});*/ // Ignore sync errors
fs.fsyncSync(this.fd); }
} catch (_e) { });
// Ignore sync errors } catch (_e) {
// Ignore sync errors
}
} }
} }
} }

View file

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