Debian Codegraph @

node/@xterm/xterm/src/common/input/WriteBuffer.ts

raw
1
2 /**
3 * Copyright (c) 2019 The xterm.js authors. All rights reserved.
4 * @license MIT
5 */
6
7 import { Disposable } from 'vs/base/common/lifecycle';
8 import { Emitter } from 'vs/base/common/event';
9
10 declare const setTimeout: (handler: () => void, timeout?: number) => void;
11
12 /**
13 * Safety watermark to avoid memory exhaustion and browser engine crash on fast data input.
14 * Enable flow control to avoid this limit and make sure that your backend correctly
15 * propagates this to the underlying pty. (see docs for further instructions)
16 * Since this limit is meant as a safety parachute to prevent browser crashs,
17 * it is set to a very high number. Typically xterm.js gets unresponsive with
18 * a 100 times lower number (>500 kB).
19 */
20 const DISCARD_WATERMARK = 50000000; // ~50 MB
21
22 /**
23 * The max number of ms to spend on writes before allowing the renderer to
24 * catch up with a 0ms setTimeout. A value of < 33 to keep us close to
25 * 30fps, and a value of < 16 to try to run at 60fps. Of course, the real FPS
26 * depends on the time it takes for the renderer to draw the frame.
27 */
28 const WRITE_TIMEOUT_MS = 12;
29
30 /**
31 * Threshold of max held chunks in the write buffer, that were already processed.
32 * This is a tradeoff between extensive write buffer shifts (bad runtime) and high
33 * memory consumption by data thats not used anymore.
34 */
35 const WRITE_BUFFER_LENGTH_THRESHOLD = 50;
36
37 export class WriteBuffer extends Disposable {
38 private _writeBuffer: (string | Uint8Array)[] = [];
39 private _callbacks: ((() => void) | undefined)[] = [];
40 private _pendingData = 0;
41 private _bufferOffset = 0;
42 private _isSyncWriting = false;
43 private _syncCalls = 0;
44 private _didUserInput = false;
45
46 private readonly _onWriteParsed = this._register(new Emitter<void>());
47 public readonly onWriteParsed = this._onWriteParsed.event;
48
49 constructor(private _action: (data: string | Uint8Array, promiseResult?: boolean) => void | Promise<boolean>) {
50 super();
51 }
52
53 public handleUserInput(): void {
54 this._didUserInput = true;
55 }
56
57 /**
58 * @deprecated Unreliable, to be removed soon.
59 */
60 public writeSync(data: string | Uint8Array, maxSubsequentCalls?: number): void {
61 // stop writeSync recursions with maxSubsequentCalls argument
62 // This is dangerous to use as it will lose the current data chunk
63 // and return immediately.
64 if (maxSubsequentCalls !== undefined && this._syncCalls > maxSubsequentCalls) {
65 // comment next line if a whole loop block should only contain x `writeSync` calls
66 // (total flat vs. deep nested limit)
67 this._syncCalls = 0;
68 return;
69 }
70 // append chunk to buffer
71 this._pendingData += data.length;
72 this._writeBuffer.push(data);
73 this._callbacks.push(undefined);
74
75 // increase recursion counter
76 this._syncCalls++;
77 // exit early if another writeSync loop is active
78 if (this._isSyncWriting) {
79 return;
80 }
81 this._isSyncWriting = true;
82
83 // force sync processing on pending data chunks to avoid in-band data scrambling
84 // does the same as innerWrite but without event loop
85 // we have to do it here as single loop steps to not corrupt loop subject
86 // by another writeSync call triggered from _action
87 let chunk: string | Uint8Array | undefined;
88 while (chunk = this._writeBuffer.shift()) {
89 this._action(chunk);
90 const cb = this._callbacks.shift();
91 if (cb) cb();
92 }
93 // reset to avoid reprocessing of chunks with scheduled innerWrite call
94 // stopping scheduled innerWrite by offset > length condition
95 this._pendingData = 0;
96 this._bufferOffset = 0x7FFFFFFF;
97
98 // allow another writeSync to loop
99 this._isSyncWriting = false;
100 this._syncCalls = 0;
101 }
102
103 public write(data: string | Uint8Array, callback?: () => void): void {
104 if (this._pendingData > DISCARD_WATERMARK) {
105 throw new Error('write data discarded, use flow control to avoid losing data');
106 }
107
108 // schedule chunk processing for next event loop run
109 if (!this._writeBuffer.length) {
110 this._bufferOffset = 0;
111
112 // If this is the first write call after the user has done some input,
113 // parse it immediately to minimize input latency,
114 // otherwise schedule for the next event
115 if (this._didUserInput) {
116 this._didUserInput = false;
117 this._pendingData += data.length;
118 this._writeBuffer.push(data);
119 this._callbacks.push(callback);
120 this._innerWrite();
121 return;
122 }
123
124 setTimeout(() => this._innerWrite());
125 }
126
127 this._pendingData += data.length;
128 this._writeBuffer.push(data);
129 this._callbacks.push(callback);
130 }
131
132 /**
133 * Inner write call, that enters the sliced chunk processing by timing.
134 *
135 * `lastTime` indicates, when the last _innerWrite call had started.
136 * It is used to aggregate async handler execution under a timeout constraint
137 * effectively lowering the redrawing needs, schematically:
138 *
139 * macroTask _innerWrite:
140 * if (performance.now() - (lastTime | 0) < WRITE_TIMEOUT_MS):
141 * schedule microTask _innerWrite(lastTime)
142 * else:
143 * schedule macroTask _innerWrite(0)
144 *
145 * overall execution order on task queues:
146 *
147 * macrotasks: [...] --> _innerWrite(0) --> [...] --> screenUpdate --> [...]
148 * m t: |
149 * i a: [...]
150 * c s: |
151 * r k: while < timeout:
152 * o s: _innerWrite(timeout)
153 *
154 * `promiseResult` depicts the promise resolve value of an async handler.
155 * This value gets carried forward through all saved stack states of the
156 * paused parser for proper continuation.
157 *
158 * Note, for pure sync code `lastTime` and `promiseResult` have no meaning.
159 */
160 protected _innerWrite(lastTime: number = 0, promiseResult: boolean = true): void {
161 const startTime = lastTime || performance.now();
162 while (this._writeBuffer.length > this._bufferOffset) {
163 const data = this._writeBuffer[this._bufferOffset];
164 const result = this._action(data, promiseResult);
165 if (result) {
166 /**
167 * If we get a promise as return value, we re-schedule the continuation
168 * as thenable on the promise and exit right away.
169 *
170 * The exit here means, that we block input processing at the current active chunk,
171 * the exact execution position within the chunk is preserved by the saved
172 * stack content in InputHandler and EscapeSequenceParser.
173 *
174 * Resuming happens automatically from that saved stack state.
175 * Also the resolved promise value is passed along the callstack to
176 * `EscapeSequenceParser.parse` to correctly resume the stopped handler loop.
177 *
178 * Exceptions on async handlers will be logged to console async, but do not interrupt
179 * the input processing (continues with next handler at the current input position).
180 */
181
182 /**
183 * If a promise takes long to resolve, we should schedule continuation behind setTimeout.
184 * This might already be too late, if our .then enters really late (executor + prev thens
185 * took very long). This cannot be solved here for the handler itself (it is the handlers
186 * responsibility to slice hard work), but we can at least schedule a screen update as we
187 * gain control.
188 */
189 const continuation: (r: boolean) => void = (r: boolean) => performance.now() - startTime >= WRITE_TIMEOUT_MS
190 ? setTimeout(() => this._innerWrite(0, r))
191 : this._innerWrite(startTime, r);
192
193 /**
194 * Optimization considerations:
195 * The continuation above favors FPS over throughput by eval'ing `startTime` on resolve.
196 * This might schedule too many screen updates with bad throughput drops (in case a slow
197 * resolving handler sliced its work properly behind setTimeout calls). We cannot spot
198 * this condition here, also the renderer has no way to spot nonsense updates either.
199 * FIXME: A proper fix for this would track the FPS at the renderer entry level separately.
200 *
201 * If favoring of FPS shows bad throughtput impact, use the following instead. It favors
202 * throughput by eval'ing `startTime` upfront pulling at least one more chunk into the
203 * current microtask queue (executed before setTimeout).
204 */
205 // const continuation: (r: boolean) => void = performance.now() - startTime >=
206 // WRITE_TIMEOUT_MS
207 // ? r => setTimeout(() => this._innerWrite(0, r))
208 // : r => this._innerWrite(startTime, r);
209
210 // Handle exceptions synchronously to current band position, idea:
211 // 1. spawn a single microtask which we allow to throw hard
212 // 2. spawn a promise immediately resolving to `true`
213 // (executed on the same queue, thus properly aligned before continuation happens)
214 result.catch(err => {
215 queueMicrotask(() => {throw err;});
216 return Promise.resolve(false);
217 }).then(continuation);
218 return;
219 }
220
221 const cb = this._callbacks[this._bufferOffset];
222 if (cb) cb();
223 this._bufferOffset++;
224 this._pendingData -= data.length;
225
226 if (performance.now() - startTime >= WRITE_TIMEOUT_MS) {
227 break;
228 }
229 }
230 if (this._writeBuffer.length > this._bufferOffset) {
231 // Allow renderer to catch up before processing the next batch
232 // trim already processed chunks if we are above threshold
233 if (this._bufferOffset > WRITE_BUFFER_LENGTH_THRESHOLD) {
234 this._writeBuffer = this._writeBuffer.slice(this._bufferOffset);
235 this._callbacks = this._callbacks.slice(this._bufferOffset);
236 this._bufferOffset = 0;
237 }
238 setTimeout(() => this._innerWrite());
239 } else {
240 this._writeBuffer.length = 0;
241 this._callbacks.length = 0;
242 this._pendingData = 0;
243 this._bufferOffset = 0;
244 }
245 this._onWriteParsed.fire();
246 }
247 }