This repository has been archived by the owner on Jun 26, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
watchdog.js
506 lines (440 loc) · 14.6 KB
/
watchdog.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
/**
* @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
/**
* @module watchdog/watchdog
*/
/* globals console, window */
import mix from '@ckeditor/ckeditor5-utils/src/mix';
import ObservableMixin from '@ckeditor/ckeditor5-utils/src/observablemixin';
import { throttle, cloneDeepWith, isElement } from 'lodash-es';
import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
import areConnectedThroughProperties from '@ckeditor/ckeditor5-utils/src/areconnectedthroughproperties';
/**
* A watchdog for CKEditor 5 editors.
*
* See the {@glink features/watchdog Watchdog feature guide} to learn the rationale behind it and
* how to use it.
*/
export default class Watchdog {
/**
* @param {module:watchdog/watchdog~WatchdogConfig} [config] The watchdog plugin configuration.
*/
constructor( config = {} ) {
/**
* An array of crashes saved as an object with the following properties:
*
* * `message`: `String`,
* * `stack`: `String`,
* * `date`: `Number`,
* * `filename`: `String | undefined`,
* * `lineno`: `Number | undefined`,
* * `colno`: `Number | undefined`,
*
* @public
* @readonly
* @type {Array.<Object>}
*/
this.crashes = [];
/**
* Specifies the state of the editor handled by the watchdog. The state can be one of the following values:
*
* * `initializing` - before the first initialization, and after crashes, before the editor is ready,
* * `ready` - a state when a user can interact with the editor,
* * `crashed` - a state when an error occurs - it quickly changes to `initializing` or `crashedPermanently`
* depending on how many and how frequency errors have been caught recently,
* * `crashedPermanently` - a state when the watchdog stops reacting to errors and keeps the editor crashed,
* * `destroyed` - a state when the editor is manually destroyed by the user after calling `watchdog.destroy()`
*
* @public
* @observable
* @member {'initializing'|'ready'|'crashed'|'crashedPermanently'|'destroyed'} #state
*/
this.set( 'state', 'initializing' );
/**
* @private
* @type {Number}
* @see module:watchdog/watchdog~WatchdogConfig
*/
this._crashNumberLimit = typeof config.crashNumberLimit === 'number' ? config.crashNumberLimit : 3;
/**
* Returns the result of `Date.now()` call. It can be overridden in tests to mock time as the popular
* approaches like `sinon.useFakeTimers()` does not work well with error handling.
*
* @protected
*/
this._now = Date.now;
/**
* @private
* @type {Number}
* @see module:watchdog/watchdog~WatchdogConfig
*/
this._minimumNonErrorTimePeriod = typeof config.minimumNonErrorTimePeriod === 'number' ? config.minimumNonErrorTimePeriod : 5000;
/**
* Checks if the event error comes from the editor that is handled by the watchdog (by checking the error context)
* and restarts the editor.
*
* @private
* @type {Function}
*/
this._boundErrorHandler = evt => {
// `evt.error` is exposed by EventError while `evt.reason` is available in PromiseRejectionEvent.
if ( evt.reason ) {
// Note that evt.reason might be everything that is in the promise rejection.
if ( evt.reason instanceof Error ) {
this._handleError( evt.reason, evt );
}
} else {
this._handleError( evt.error, evt );
}
};
/**
* Throttled save method. The `save()` method is called the specified `saveInterval` after `throttledSave()` is called,
* unless a new action happens in the meantime.
*
* @private
* @type {Function}
*/
this._throttledSave = throttle(
this._save.bind( this ),
typeof config.saveInterval === 'number' ? config.saveInterval : 5000
);
/**
* The current editor instance.
*
* @private
* @type {module:core/editor/editor~Editor}
*/
this._editor = null;
/**
* The editor creation method.
*
* @private
* @member {Function} #_creator
* @see #setCreator
*/
/**
* The editor destruction method.
*
* @private
* @member {Function} #_destructor
* @see #setDestructor
*/
this._destructor = editor => editor.destroy();
/**
* The latest saved editor data represented as a root name -> root data object.
*
* @private
* @member {Object.<String,String>} #_data
*/
/**
* The last document version.
*
* @private
* @member {Number} #_lastDocumentVersion
*/
/**
* The editor source element or data.
*
* @private
* @member {HTMLElement|String|Object.<String|String>} #_elementOrData
*/
/**
* The editor configuration.
*
* @private
* @member {Object|undefined} #_config
*/
}
/**
* The current editor instance.
*
* @readonly
* @type {module:core/editor/editor~Editor}
*/
get editor() {
return this._editor;
}
/**
* Sets the function that is responsible for the editor creation.
* It expects a function that should return a promise.
*
* watchdog.setCreator( ( element, config ) => ClassicEditor.create( element, config ) );
*
* @param {Function} creator
*/
setCreator( creator ) {
this._creator = creator;
}
/**
* Sets the function that is responsible for the editor destruction.
* Overrides the default destruction function, which destroys only the editor instance.
* It expects a function that should return a promise or `undefined`.
*
* watchdog.setDestructor( editor => {
* // Do something before the editor is destroyed.
*
* return editor
* .destroy()
* .then( () => {
* // Do something after the editor is destroyed.
* } );
* } );
*
* @param {Function} destructor
*/
setDestructor( destructor ) {
this._destructor = destructor;
}
/**
* Creates a watched editor instance using the creator passed to the {@link #setCreator `setCreator()`} method or
* the {@link module:watchdog/watchdog~Watchdog.for `Watchdog.for()`} helper.
*
* @param {HTMLElement|String|Object.<String|String>} elementOrData
* @param {module:core/editor/editorconfig~EditorConfig} [config]
*
* @returns {Promise}
*/
create( elementOrData, config ) {
if ( !this._creator ) {
/**
* The watchdog's editor creator is not defined. Define it by using
* {@link module:watchdog/watchdog~Watchdog#setCreator `Watchdog#setCreator()`} or
* the {@link module:watchdog/watchdog~Watchdog.for `Watchdog.for()`} helper.
*
* @error watchdog-creator-not-defined
*/
throw new CKEditorError(
'watchdog-creator-not-defined: The watchdog\'s editor creator is not defined.',
null
);
}
this._elementOrData = elementOrData;
// Clone configuration because it might be shared within multiple watchdog instances. Otherwise,
// when an error occurs in one of these editors, the watchdog will restart all of them.
this._config = cloneDeepWith( config, value => {
// Leave DOM references.
return isElement( value ) ? value : undefined;
} );
return Promise.resolve()
.then( () => this._creator( elementOrData, this._config ) )
.then( editor => {
this._editor = editor;
window.addEventListener( 'error', this._boundErrorHandler );
window.addEventListener( 'unhandledrejection', this._boundErrorHandler );
this.listenTo( editor.model.document, 'change:data', this._throttledSave );
this._lastDocumentVersion = editor.model.document.version;
this._data = this._getData();
this.state = 'ready';
} );
}
/**
* Destroys the current editor instance by using the destructor passed to the {@link #setDestructor `setDestructor()`} method
* and sets state to `destroyed`.
*
* @returns {Promise}
*/
destroy() {
this.state = 'destroyed';
return this._destroy();
}
/**
* Destroys the current editor instance by using the destructor passed to the {@link #setDestructor `setDestructor()`} method.
*
* @private
*/
_destroy() {
window.removeEventListener( 'error', this._boundErrorHandler );
window.removeEventListener( 'unhandledrejection', this._boundErrorHandler );
this.stopListening( this._editor.model.document, 'change:data', this._throttledSave );
// Save data if there is a remaining editor data change.
this._throttledSave.flush();
return Promise.resolve()
.then( () => this._destructor( this._editor ) )
.then( () => {
this._editor = null;
} );
}
/**
* Saves the editor data, so it can be restored after the crash even if the data cannot be fetched at
* the moment of the crash.
*
* @private
*/
_save() {
const version = this._editor.model.document.version;
// Change may not produce an operation, so the document's version
// can be the same after that change.
if ( version === this._lastDocumentVersion ) {
return;
}
try {
this._data = this._getData();
this._lastDocumentVersion = version;
} catch ( err ) {
console.error(
err,
'An error happened during restoring editor data. ' +
'Editor will be restored from the previously saved data.'
);
}
}
/**
* Returns the editor data.
*
* @private
* @returns {Object<String,String>}
*/
_getData() {
const data = {};
for ( const rootName of this._editor.model.document.getRootNames() ) {
data[ rootName ] = this._editor.data.get( { rootName } );
}
return data;
}
/**
* Checks if the error comes from the editor that is handled by the watchdog (by checking the error context) and
* restarts the editor. It reacts to {@link module:utils/ckeditorerror~CKEditorError `CKEditorError` errors} only.
*
* @private
* @fires error
* @param {Error} error Error.
* @param {ErrorEvent|PromiseRejectionEvent} evt Error event.
*/
_handleError( error, evt ) {
// @if CK_DEBUG // if ( error.is && error.is( 'CKEditorError' ) && error.context === undefined ) {
// @if CK_DEBUG // console.warn( 'The error is missing its context and Watchdog cannot restart the proper editor.' );
// @if CK_DEBUG // }
if ( this._shouldReactToError( error ) ) {
this.crashes.push( {
message: error.message,
stack: error.stack,
// `evt.filename`, `evt.lineno` and `evt.colno` are available only in ErrorEvent events
filename: evt.filename,
lineno: evt.lineno,
colno: evt.colno,
date: this._now()
} );
this.fire( 'error', { error } );
this.state = 'crashed';
if ( this._shouldRestartEditor() ) {
this._restart();
} else {
this.state = 'crashedPermanently';
}
}
}
/**
* Checks whether the error should be handled.
*
* @private
* @param {Error} error Error
*/
_shouldReactToError( error ) {
return (
error.is &&
error.is( 'CKEditorError' ) &&
error.context !== undefined &&
// In some cases the editor should not be restarted - e.g. in case of the editor initialization.
// That's why the `null` was introduced as a correct error context which does cause restarting.
error.context !== null &&
// Do not react to errors if the watchdog is in states other than `ready`.
this.state === 'ready' &&
this._isErrorComingFromThisEditor( error )
);
}
/**
* Checks if the editor should be restared or if it should be marked as crashed.
*/
_shouldRestartEditor() {
if ( this.crashes.length <= this._crashNumberLimit ) {
return true;
}
const lastErrorTime = this.crashes[ this.crashes.length - 1 ].date;
const firstMeaningfulErrorTime = this.crashes[ this.crashes.length - 1 - this._crashNumberLimit ].date;
const averageNonErrorTimePeriod = ( lastErrorTime - firstMeaningfulErrorTime ) / this._crashNumberLimit;
return averageNonErrorTimePeriod > this._minimumNonErrorTimePeriod;
}
/**
* Restarts the editor instance. This method is called whenever an editor error occurs. It fires the `restart` event and changes
* the state to `initializing`.
*
* @private
* @fires restart
* @returns {Promise}
*/
_restart() {
this.state = 'initializing';
return Promise.resolve()
.then( () => this._destroy() )
.catch( err => console.error( 'An error happened during the editor destructing.', err ) )
.then( () => {
if ( typeof this._elementOrData === 'string' ) {
return this.create( this._data, this._config );
}
const updatedConfig = Object.assign( {}, this._config, {
initialData: this._data
} );
return this.create( this._elementOrData, updatedConfig );
} )
.then( () => {
this.fire( 'restart' );
} );
}
/**
* Traverses both structures to find out whether the error context is connected
* with the current editor.
*
* @private
* @param {module:utils/ckeditorerror~CKEditorError} error
*/
_isErrorComingFromThisEditor( error ) {
return areConnectedThroughProperties( this._editor, error.context );
}
/**
* A shorthand method for creating an instance of the watchdog. For the full usage, see the
* {@link ~Watchdog `Watchdog` class description}.
*
* Usage:
*
* const watchdog = Watchdog.for( ClassicEditor );
*
* watchdog.create( elementOrData, config );
*
* @param {*} Editor The editor class.
* @param {module:watchdog/watchdog~WatchdogConfig} [watchdogConfig] The watchdog plugin configuration.
*/
static for( Editor, watchdogConfig ) {
const watchdog = new Watchdog( watchdogConfig );
watchdog.setCreator( ( elementOrData, config ) => Editor.create( elementOrData, config ) );
return watchdog;
}
/**
* Fired when a new {@link module:utils/ckeditorerror~CKEditorError `CKEditorError`} error connected to the watchdog editor occurs
* and the watchdog will react to it.
*
* @event error
*/
/**
* Fired after the watchdog restarts the error in case of a crash.
*
* @event restart
*/
}
mix( Watchdog, ObservableMixin );
/**
* The watchdog plugin configuration.
*
* @typedef {Object} WatchdogConfig
*
* @property {Number} [crashNumberLimit=3] A threshold specifying the number of editor crashes
* when the watchdog stops restarting the editor in case of errors.
* After this limit is reached and the time between last errors is shorter than `minimumNonErrorTimePeriod`
* the watchdog changes its state to `crashedPermanently` and it stops restarting the editor. This prevents an infinite restart loop.
* @property {Number} [minimumNonErrorTimePeriod=5000] An average amount of milliseconds between last editor errors
* (defaults to 5000). When the period of time between errors is lower than that and the `crashNumberLimit` is also reached
* the watchdog changes its state to `crashedPermanently` and it stops restarting the editor. This prevents an infinite restart loop.
* @property {Number} [saveInterval=5000] A minimum number of milliseconds between saving editor data internally, (defaults to 5000).
* Note that for large documents this might have an impact on the editor performance.
*/