Debian Codegraph @

extensions/VisualEditor/lib/ve/src/ve.Filibuster.js

raw symbols SCIP
1 /*!
2 * Extremely detailed logging of function calls and state changes
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * A scrupulous event logger that logs state at every function call, and
9 * shortlists potentially significant observations for strict scrutiny.
10 *
11 * Functions are wrapped to log entry/exit. This creates a comprehensive log of
12 * every watched function call (typically thousands per keystroke), together
13 * with the corresponding call stack.
14 *
15 * Observer callbacks can be registered to watch certain global values (e.g.
16 * the DOM/DM content and selection). These at every watched function
17 * entry/exit, and when there is a change (typically a few times per keystroke),
18 * an observation is logged. Each observation shows the state change and call
19 * stack, and has a log number that points into the full call log.
20 *
21 * Function wrapping generally takes place after object initialization.
22 * That means property lookups that have already happened (e.g. through
23 * .bind or setTimeout in a constructor) will not pass through the wrapper.
24 *
25 * This code is inspired by United States v. Carolene Products Company, 304
26 * U.S. 144 (1938), Footnote Four.
27 *
28 * @class ve.Filibuster
29 */
30
31 /**
32 * @constructor
33 * @param {string[]} eventNames List of event names to listen to
34 */
35 ve.Filibuster = function VeFilibuster() {
36 this.count = 0;
37 this.states = {};
38 this.observers = {};
39 // Tree of call frames
40 this.callTree = { children: [] };
41 // Current call frame
42 this.frame = this.callTree;
43 // Path (index offsets) to current call frame
44 this.callPath = [];
45 // Index offset tree: {
46 // changes: {enter: xxx, exit: xxx }
47 // children: { index offset tree }
48 // }
49 this.observationTree = { children: {} };
50 this.active = false;
51 this.startTime = null;
52 };
53
54 OO.initClass( ve.Filibuster );
55
56 /**
57 * Clears logs, without detaching observers
58 */
59 ve.Filibuster.prototype.clearLogs = function () {
60 this.count = 0;
61 for ( const name in this.states ) {
62 delete this.states[ name ];
63 }
64 this.observationTree.children = {};
65 this.callTree.children.length = 0;
66 this.frame = this.callTree;
67 this.callPath.length = 0;
68 };
69
70 /**
71 * Attaches an observer callback. The callback returns a value representing the current state,
72 * which must be a string (this ensures state values are immutable, comparable with strict
73 * equality and easily dumpable).
74 *
75 * The observer will be called before and after every function call. An observation is logged
76 * every time there is a difference between the current return value and the previous one.
77 *
78 * @param {string} name The name of the observer, for display in the logs.
79 * @param {Function} callback The callback; must return a string
80 * @return {ve.Filibuster}
81 * @chainable
82 */
83 ve.Filibuster.prototype.setObserver = function ( name, callback ) {
84 this.observers[ name ] = callback;
85 return this;
86 };
87
88 /**
89 * Calls each observer, logging an observation if a change is detected. Called at the start
90 * and end of every monitored function call.
91 *
92 * @param {string} action The function call phase: call|return|throw
93 */
94 ve.Filibuster.prototype.observe = function ( action ) {
95 const changes = {};
96
97 for ( const name in this.observers ) {
98 const callback = this.observers[ name ];
99 const oldState = this.states[ name ];
100 let newState;
101 try {
102 newState = callback();
103 } catch ( ex ) {
104 newState = 'Error: ' + ex;
105 }
106 if ( typeof newState !== 'string' ) {
107 // Be strict about the allowed types, to ensure immutability
108 ve.error( 'Illegal state:', newState );
109 throw new Error( 'Illegal state: ' + newState );
110 }
111
112 if ( this.states[ name ] !== newState ) {
113 if ( Object.prototype.hasOwnProperty.call( this.states, name ) ) {
114 // State change: write observation
115 changes[ name ] = {
116 oldState: oldState,
117 newState: newState
118 };
119 }
120 this.states[ name ] = newState;
121 }
122 }
123
124 // Save any changes into observations tree
125 if ( Object.keys( changes ).length > 0 ) {
126 // Navigate along tree branch, creating as necessary
127 let ptr = this.observationTree;
128 for ( let j = 0, jLen = this.callPath.length; j < jLen; j++ ) {
129 const offset = this.callPath[ j ];
130 if ( !ptr.children ) {
131 ptr.children = {};
132 }
133 if ( !ptr.children[ offset ] ) {
134 ptr.children[ offset ] = {};
135 }
136 ptr = ptr.children[ offset ];
137 }
138 if ( !ptr.changes ) {
139 ptr.changes = {};
140 }
141 if ( action === 'call' ) {
142 ptr.changes.enter = changes;
143 } else {
144 ptr.changes.exit = changes;
145 }
146 }
147 };
148
149 /**
150 * Log a function call. Called at the start and end of every monitored function call.
151 *
152 * @param {string} funcName The name of the function
153 * @param {string} action The function call phase: call|return|throw
154 * @param {Array} [args] The call arguments (if action === 'call')
155 * @param {any} [returned] The return value (if action === 'return')
156 */
157 ve.Filibuster.prototype.log = function ( funcName, action, args, returned ) {
158 if ( !this.active ) {
159 return;
160 }
161 const time = ve.now() - this.startTime;
162 if ( action === 'call' ) {
163 // Descend down the call tree (adding a new frame)
164 // Store arguments as a cloned plain object, to avoid anachronistic changes and
165 // for easy display.
166 const parentFrame = this.frame;
167 if ( !parentFrame.children ) {
168 parentFrame.children = [];
169 }
170 this.callPath.push( parentFrame.children.length );
171 this.frame = {
172 count: this.count++,
173 funcName: funcName,
174 args: this.constructor.static.clonePlain( args ),
175 // returned: xxx,
176 // thrown: xxx
177 start: time,
178 // end: xxx,
179 // children: xxx,
180 parent: parentFrame
181 };
182 parentFrame.children.push( this.frame );
183 }
184
185 this.observe( action, time );
186
187 if ( action === 'return' || action === 'throw' ) {
188 // Check funcName, store values, ascend call tree
189 if ( this.frame.funcName === undefined ) {
190 throw new Error(
191 'No call logged, but leaving "' + funcName + '" (' + action + ')'
192 );
193 }
194 if ( this.frame.funcName !== funcName ) {
195 throw new Error(
196 'Logged call to "' + this.frame.funcName + '"' +
197 ' but leaving "' + funcName + '" (' + action + ')'
198 );
199 }
200 this.frame.end = time;
201 if ( action === 'return' ) {
202 this.frame.returned = this.constructor.static.clonePlain( returned );
203 } else if ( action === 'throw' ) {
204 this.frame.thrown = true;
205 }
206
207 this.frame = this.frame.parent;
208 this.callPath.pop();
209 }
210 };
211
212 /**
213 * Replace a reference to a function with a wrapper that performs logging.
214 *
215 * Note that the same function can be referenced multiple times; each reference would
216 * need wrapping separately.
217 *
218 * @param {Object} container The container with the function as a property
219 * @param {string} klassName The name of the container, for display in the logs
220 * @param {string} fnName The property name of the function in the container
221 * @return {ve.Filibuster}
222 * @chainable
223 */
224 ve.Filibuster.prototype.wrapFunction = function ( container, klassName, fnName ) {
225 const filibuster = this,
226 fullName = ( klassName || 'unknown' ) + '.' + fnName;
227 const fn = container[ fnName ];
228 const wrapper = function () {
229 let returnVal,
230 fnReturned = false;
231 filibuster.log( fullName, 'call', Array.prototype.slice.call( arguments ), undefined );
232 try {
233 returnVal = fn.apply( this, arguments );
234 fnReturned = true;
235 filibuster.log( fullName, 'return', undefined, returnVal );
236 return returnVal;
237 } finally {
238 if ( !fnReturned ) {
239 // Can't easily get the error without affecting the call stack
240 filibuster.log( fullName, 'throw', undefined, undefined );
241 }
242 }
243 };
244 wrapper.wrappedFunction = fn;
245 container[ fnName ] = wrapper;
246 return this;
247 };
248
249 /**
250 * Wrap the functions in a class with wrappers that perform logging.
251 *
252 * @param {Object} klass The class with the function as a property
253 * @param {Function[]} [nowrapList] Functions that should not be wrapped
254 * @return {ve.Filibuster}
255 * @chainable
256 */
257 ve.Filibuster.prototype.wrapClass = function ( klass, nowrapList ) {
258 const container = klass.prototype;
259 const fnNames = Object.getOwnPropertyNames( container );
260 for ( let i = 0, len = fnNames.length; i < len; i++ ) {
261 const fnName = fnNames[ i ];
262 if ( fnName === 'prototype' || fnName === 'constructor' ) {
263 continue;
264 }
265 const fn = container[ fnName ];
266 if ( typeof fn !== 'function' || fn.wrappedFunction ) {
267 continue;
268 }
269 if ( nowrapList && nowrapList.indexOf( fn ) !== -1 ) {
270 continue;
271 }
272 this.wrapFunction( container, klass.name, fnName );
273 }
274 return this;
275 };
276
277 /**
278 * Recursively wrap the functions in a namespace with wrappers that perform logging.
279 *
280 * @param {Object} ns The namespace whose functions should be wrapped
281 * @param {string} nsName The name of the namespace, for display in logs
282 * @param {Function[]} [nowrapList] Functions that should not be wrapped
283 * @return {ve.Filibuster}
284 * @chainable
285 */
286 ve.Filibuster.prototype.wrapNamespace = function ( ns, nsName, nowrapList ) {
287 const propNames = Object.getOwnPropertyNames( ns );
288 for ( let i = 0, len = propNames.length; i < len; i++ ) {
289 const propName = propNames[ i ];
290 const prop = ns[ propName ];
291 if ( nowrapList && nowrapList.indexOf( prop ) !== -1 ) {
292 continue;
293 }
294 const isConstructor = (
295 typeof prop === 'function' &&
296 !ve.isEmptyObject( prop.prototype )
297 );
298 if ( isConstructor ) {
299 this.wrapClass( prop, nowrapList );
300 } else if ( typeof prop === 'function' ) {
301 this.wrapFunction( ns, nsName, propName );
302 } else if ( $.isPlainObject( prop ) ) {
303 // Might be a namespace; recurse
304 this.wrapNamespace( prop, nsName + '.' + propName, nowrapList );
305 }
306 }
307 return this;
308 };
309
310 /**
311 * Start logging
312 */
313 ve.Filibuster.prototype.start = function () {
314 this.active = true;
315 this.startTime = ve.now();
316 };
317
318 /**
319 * Stop logging
320 */
321 ve.Filibuster.prototype.stop = function () {
322 this.active = false;
323 };
324
325 /**
326 * Get an HTML representation of part of the call tree, opened at each observation
327 *
328 * In general, building HTML fragments like this is ugly; but this turns out to give
329 * better performance if the HTML representation is really large.
330 *
331 * @param {number[]} [branchPath] Path to the part of the tree to represent
332 * @return {string} HTML representation
333 */
334 ve.Filibuster.prototype.getObservationsHtml = function ( branchPath ) {
335 function showArgs( args ) {
336 return '<b>(</b>' + ve.escapeHtml( args.map( ( arg ) => JSON.stringify( arg ) ).join( ', ' ) ) + '<b>)</b>';
337 }
338
339 function showVal( val ) {
340 return ve.escapeHtml( JSON.stringify( val ) );
341 }
342
343 function showChanges( changes, phase ) {
344 return (
345 ( phase === 'enter' ? '<hr>' : '' ) +
346 '<div class="ve-filibuster-changes">' +
347 Object.keys( changes ).map( ( name ) => (
348 '<b>' + ve.escapeHtml( name + ' old' ) + '</b><br>' +
349 ve.escapeHtml( changes[ name ].oldState ) + '<br>' +
350 '<b>' + ve.escapeHtml( name + ' new' ) + '</b><br>' +
351 ve.escapeHtml( changes[ name ].newState )
352 ) ).join( '<br>' ) +
353 '</div>' +
354 ( phase === 'exit' ? '<hr>' : '' )
355 );
356 }
357
358 function showCallOpen( frame ) {
359 return (
360 '<b>' + frame.count + '</b> ' +
361 '(' + frame.start.toFixed( 2 ) + 'ms-' + frame.end.toFixed( 2 ) + 'ms) ' +
362 '<b>' + ve.escapeHtml( frame.funcName ) + '</b>' +
363 showArgs( frame.args )
364 );
365 }
366
367 function showCallClose( frame ) {
368 return (
369 '<b>exit ' + ve.escapeHtml( frame.funcName ) + '</b>' +
370 '--->' +
371 ( frame.thrown ? 'thrown' : showVal( frame.returned ) )
372 );
373 }
374
375 function showCallSkip( frame ) {
376 return (
377 '<b>' + frame.count + '</b> ' +
378 '(' + frame.start.toFixed( 2 ) + 'ms-' + frame.end.toFixed( 2 ) + 'ms) ' +
379 '<b>' + ve.escapeHtml( frame.funcName ) + '</b>' +
380 showArgs( frame.args ) +
381 '<span />' +
382 '--->' +
383 ( frame.thrown ? 'thrown' : showVal( frame.returned ) )
384 );
385 }
386
387 function getFragments( frames, observations, path ) {
388 const html = [];
389 html.push( '<ul>' );
390 for ( let j = 0, jLen = frames.length; j < jLen; j++ ) {
391 const frame = frames[ j ];
392 const observation = observations[ j ];
393 if ( observation && observation.changes && observation.changes.enter ) {
394 html.push( showChanges( observation.changes.enter, 'enter' ) );
395 }
396 const expanded = observation && observation.children;
397 const expandable = !expanded && frame.children && frame.children.length > 0;
398 html.push( '<li class="ve-filibuster-frame' );
399 if ( expandable ) {
400 html.push( ' ve-filibuster-frame-expandable' );
401 }
402 html.push(
403 '" data-ve-filibuster-frame="' +
404 ve.escapeHtml( JSON.stringify( path.concat( j ) ) ) + '">'
405 );
406 if ( expanded ) {
407 html.push( showCallOpen( frame ) );
408 html.push.apply( html, getFragments(
409 frame.children || [],
410 observation.children,
411 path.concat( j )
412 ) );
413 html.push( showCallClose( frame ) );
414 } else {
415 html.push( showCallSkip( frame ) );
416 }
417 html.push( '</li>' );
418 if ( observation && observation.changes && observation.changes.exit ) {
419 html.push( showChanges( observation.changes.exit, 'exit' ) );
420 }
421 }
422 html.push( '</ul>' );
423 return html;
424 }
425
426 let callTree = this.callTree;
427 let observationTree = this.observationTree;
428 // Walk to the specified part of the tree
429 if ( !branchPath ) {
430 branchPath = [];
431 }
432 for ( let i = 0, iLen = branchPath.length; i < iLen; i++ ) {
433 callTree = callTree.children[ branchPath[ i ] ];
434 if ( observationTree && observationTree.children ) {
435 observationTree = observationTree.children[ branchPath[ i ] ];
436 } else {
437 // No observations on this branch
438 observationTree = undefined;
439 }
440 }
441
442 return getFragments(
443 callTree.children || [],
444 ( observationTree && observationTree.children ) || {},
445 branchPath
446 ).join( '' );
447 };
448
449 /* Static methods */
450
451 /**
452 * Get a plain-old-data deep clone of val.
453 *
454 * The resulting value is easily dumpable, and will not change if val changes.
455 *
456 * @param {Object|string|number|undefined|null} val Value to analyze
457 * @param {Set} [seen] Seen objects, for recursion detection
458 * @return {Object|string|number|null} Plain old data object
459 */
460 ve.Filibuster.static.clonePlain = function ( val, seen ) {
461 if ( seen === undefined ) {
462 seen = new Set();
463 }
464 if ( Array.isArray( val ) ) {
465 if ( seen.has( val ) ) {
466 return '…';
467 }
468 seen.add( val );
469 return val.map( ( x ) => this.clonePlain( x, seen ) );
470 } else if ( typeof val === 'function' ) {
471 return '(function ' + val.name + ')';
472 } else if ( typeof val === 'undefined' ) {
473 return '(undefined)';
474 } else if ( val === null ) {
475 return null;
476 } else if ( val === window ) {
477 return '(window)';
478 } else if ( typeof val !== 'object' ) {
479 return val;
480 } else if ( val.constructor === ve.Range ) {
481 return { 've.Range': [ val.from, val.to ] };
482 } else if ( val.constructor === ve.dm.Transaction ) {
483 return { 've.dm.Transaction': val.operations.map( ( op ) => this.clonePlain( op ) ) };
484 } else if ( val instanceof ve.dm.Selection ) {
485 return { 've.dm.Selection': val.getDescription() };
486 } else if ( val.constructor === ve.dm.AnnotationSet ) {
487 return {
488 've.dm.AnnotationSet': val.getStore()
489 .values( val.getHashes() )
490 .map( ( annotation ) => annotation.name )
491 };
492 } else if ( val.constructor !== Object ) {
493 // Not a plain old object
494 return '(' + ( val.constructor.name || 'unknown' ) + ')';
495 } else {
496 if ( seen.has( val ) ) {
497 return '…';
498 }
499 seen.add( val );
500 const plainVal = {};
501 Object.getOwnPropertyNames( val ).forEach( ( k ) => {
502 plainVal[ k ] = this.clonePlain( val[ k ], seen );
503 } );
504 return plainVal;
505 }
506 };