watchdog.js 15 KB

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