Debian Codegraph @

extensions/VisualEditor/lib/ve/src/dm/ve.dm.SurfaceSynchronizer.js

raw symbols SCIP
1 /*!
2 * VisualEditor DataModel SurfaceSynchronizer class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /* global io */
8
9 /**
10 * DataModel surface synchronizer.
11 *
12 * @class
13 * @mixes OO.EventEmitter
14 * @mixes ve.dm.RebaseClient
15 *
16 * @constructor
17 * @param {ve.dm.Surface} surface Surface model to synchronize
18 * @param {string} documentId Document ID
19 * @param {Object} [config] Configuration options
20 * @param {string} [config.server] IO server
21 * @param {string} [config.defaultName] Default username
22 */
23 ve.dm.SurfaceSynchronizer = function VeDmSurfaceSynchronizer( surface, documentId, config ) {
24 config = config || {};
25
26 // Mixin constructors
27 OO.EventEmitter.call( this );
28 ve.dm.RebaseClient.call( this );
29
30 // Properties
31 this.surface = surface;
32 this.doc = surface.documentModel;
33 this.store = this.doc.getStore();
34 this.authors = {};
35 this.authorSelections = {};
36 this.documentId = documentId;
37
38 // Whether the document has been initialized
39 this.initialized = false;
40 // Whether we are currently synchronizing the model
41 this.applying = false;
42 this.token = null;
43 this.serverId = null;
44 this.loadSessionKey();
45 this.paused = false;
46
47 // SocketIO events
48 let conn;
49 if ( config.peerConnection ) {
50 conn = {
51 peerConnection: config.peerConnection,
52 handlers: new Map(),
53 on: function ( type, handler ) {
54 if ( !this.handlers.has( type ) ) {
55 this.handlers.set( type, [] );
56 }
57 this.handlers.get( type ).push( handler );
58 },
59 send: function ( type, data ) {
60 this.peerConnection.send( { type: type, data: ve.collab.serialize( data ) } );
61 },
62 disconnect: function () {
63 this.peerConnection.close();
64 }
65 };
66 conn.peerConnection.on( 'data', ( data ) => {
67 const type = data.type;
68 if ( typeof type !== 'string' ) {
69 throw new Error( 'Expected .type in <' + data + '>' );
70 }
71 ( conn.handlers.get( type ) || [] ).forEach( ( handler ) => {
72 handler( data.data );
73 } );
74 } );
75 } else {
76 const path = ( config.server || '' );
77 const options = {
78 query: {
79 docName: this.documentId,
80 authorId: this.getAuthorId() || '',
81 token: this.token || ''
82 },
83 transports: [ 'websocket' ]
84 };
85 conn = {
86 socket: io( path, options ),
87 on: function ( type, handler ) {
88 this.socket.on( type, handler );
89 },
90 send: function ( type, data ) {
91 this.socket.emit( type, data );
92 },
93 disconnect: function () {
94 this.socket.disconnect();
95 }
96 };
97 }
98 this.conn = conn;
99 this.conn.on( 'registered', this.onRegistered.bind( this ) );
100 this.conn.on( 'initDoc', this.onInitDoc.bind( this ) );
101 this.conn.on( 'newChange', this.onNewChange.bind( this ) );
102 this.conn.on( 'authorChange', this.onAuthorChange.bind( this ) );
103 this.conn.on( 'authorDisconnect', this.onAuthorDisconnect.bind( this ) );
104
105 const authorData = ve.init.platform.sessionStorage.getObject( 've-collab-author' );
106 if ( authorData ) {
107 this.changeAuthor( authorData );
108 } else if ( config.defaultName ) {
109 this.changeAuthor( { name: config.defaultName } );
110 }
111
112 // Events
113 this.surface.connect( this, {
114 history: 'onSurfaceHistory',
115 select: 'onSurfaceSelect'
116 } );
117
118 this.submitChangeThrottled = ve.debounce( ve.throttle( this.submitChange.bind( this ), 250 ), 0 );
119 };
120
121 /* Inheritance */
122
123 OO.mixinClass( ve.dm.SurfaceSynchronizer, OO.EventEmitter );
124 OO.mixinClass( ve.dm.SurfaceSynchronizer, ve.dm.RebaseClient );
125
126 /* Events */
127
128 /**
129 * @event ve.dm.SurfaceSynchronizer#authorSelect
130 * @param {number} authorId The author whose selection has changed
131 */
132
133 /**
134 * @event ve.dm.SurfaceSynchronizer#authorChange
135 * @param {number} authorId The author whose data has changed
136 */
137
138 /**
139 * @event ve.dm.SurfaceSynchronizer#wrongDoc
140 */
141
142 /**
143 * @event ve.dm.SurfaceSynchronizer#initDoc
144 * @param {Error} error Error, if there was a problem initializing the document
145 */
146
147 /**
148 * @event ve.dm.SurfaceSynchronizer#disconnect
149 */
150
151 /**
152 * The synchronizer is paused or resumes
153 *
154 * @event ve.dm.SurfaceSynchronizer#pause
155 */
156
157 /* Methods */
158
159 /**
160 * Destroy the synchronizer
161 */
162 ve.dm.SurfaceSynchronizer.prototype.destroy = function () {
163 this.conn.disconnect();
164 this.doc.disconnect( this );
165 this.surface.disconnect( this );
166 this.initialized = false;
167 };
168
169 /**
170 * Pause sending/receiving changes
171 *
172 * @fires ve.dm.SurfaceSynchronizer#pause
173 */
174 ve.dm.SurfaceSynchronizer.prototype.pauseChanges = function () {
175 if ( this.paused ) {
176 return;
177 }
178 this.paused = true;
179 this.queuedChanges = [];
180 this.emit( 'pause' );
181 };
182
183 /**
184 * Resume sending/receiving changes
185 *
186 * @fires ve.dm.SurfaceSynchronizer#pause
187 */
188 ve.dm.SurfaceSynchronizer.prototype.resumeChanges = function () {
189 if ( !this.paused ) {
190 return;
191 }
192 this.applying = true;
193 try {
194 // Don't cache length, as it's not inconceivable acceptChange could
195 // cause another change to arrive in some weird setup
196 for ( let i = 0; i < this.queuedChanges.length; i++ ) {
197 this.acceptChange( this.queuedChanges[ i ] );
198 }
199 } finally {
200 this.applying = false;
201 }
202 this.paused = false;
203 // Schedule submission of unsent local changes, if any
204 this.submitChangeThrottled();
205 this.emit( 'pause' );
206 };
207
208 /**
209 * @inheritdoc
210 */
211 ve.dm.SurfaceSynchronizer.prototype.getChangeSince = function ( start, toSubmit ) {
212 const change = this.doc.getChangeSince( start ),
213 selection = this.surface.getSelection();
214 if ( !selection.equals( this.lastSubmittedSelection ) ) {
215 change.selections[ this.getAuthorId() ] = selection;
216 if ( toSubmit ) {
217 this.lastSubmittedSelection = selection;
218 }
219 }
220 return change;
221 };
222
223 /**
224 * @inheritdoc
225 */
226 ve.dm.SurfaceSynchronizer.prototype.submitChange = function () {
227 // Prevent submission before initialization is complete
228 if ( !this.initialized ) {
229 return;
230 }
231 // Parent method
232 ve.dm.RebaseClient.prototype.submitChange.apply( this, arguments );
233 };
234
235 /**
236 * @inheritdoc
237 */
238 ve.dm.SurfaceSynchronizer.prototype.sendChange = function ( backtrack, change ) {
239 this.conn.send( 'submitChange', {
240 backtrack: this.backtrack,
241 // Serialize (don't rely on the transport to perform implicit serialization)
242 change: change.serialize()
243 } );
244 };
245
246 /**
247 * @inheritdoc
248 */
249 ve.dm.SurfaceSynchronizer.prototype.applyChange = function ( change ) {
250 // Author selections are superseded by change.selections, so no need to translate them
251 for ( let authorId in change.selections ) {
252 authorId = +authorId;
253 delete this.authorSelections[ authorId ];
254 }
255 change.applyTo( this.surface );
256 // HACK: After applyTo(), the selections are wrong and applying them could crash.
257 // The only reason this doesn't happen is because everything that tries to do that uses setTimeout().
258 // Translate the selections that aren't going to be overwritten by change.selections
259 this.applyNewSelections( this.authorSelections, change );
260 // Apply the overwrites from change.selections
261 this.applyNewSelections( change.selections );
262 };
263
264 /**
265 * @inheritdoc
266 */
267 ve.dm.SurfaceSynchronizer.prototype.unapplyChange = function ( change ) {
268 change.unapplyTo( this.surface );
269 // Translate all selections for what we just unapplied
270 // HACK: After unapplyTo(), the selections are wrong and applying them could crash.
271 // The only reason this doesn't happen is because everything that tries to do that uses setTimeout().
272 this.applyNewSelections( this.authorSelections, change.reversed() );
273 };
274
275 /**
276 * @inheritdoc
277 */
278 ve.dm.SurfaceSynchronizer.prototype.addToHistory = function ( change ) {
279 change.addToHistory( this.doc );
280 };
281
282 /**
283 * @inheritdoc
284 */
285 ve.dm.SurfaceSynchronizer.prototype.removeFromHistory = function ( change ) {
286 change.removeFromHistory( this.doc );
287 };
288
289 /**
290 * @inheritdoc
291 */
292 ve.dm.SurfaceSynchronizer.prototype.logEvent = function ( event ) {
293 if ( !this.initialized ) {
294 // Do not log before initialization is complete; this prevents us from logging the entire
295 // document history during initialization
296 return;
297 }
298 this.conn.send( 'logEvent', ve.extendObject( { sendTimestamp: Date.now() }, event ) );
299 };
300
301 /**
302 * Respond to transactions happening on the document. Ignores transactions applied by
303 * SurfaceSynchronizer itself.
304 */
305 ve.dm.SurfaceSynchronizer.prototype.onSurfaceHistory = function () {
306 if ( this.applying || !this.initialized || this.paused ) {
307 // Ignore our own synchronization or initialization transactions
308 return;
309 }
310 const change = this.getChangeSince( this.sentLength, true );
311 const authorId = this.authorId;
312 // HACK annotate transactions with authorship information
313 // This relies on being able to access the transaction object by reference;
314 // we should probably set the author deeper in dm.Surface or dm.Document instead.
315 change.transactions.forEach( ( tx ) => {
316 tx.authorId = authorId;
317 } );
318 // TODO deal with staged transactions somehow
319 this.applyNewSelections( this.authorSelections, change );
320 this.submitChangeThrottled();
321 };
322
323 /**
324 * Respond to selection changes.
325 */
326 ve.dm.SurfaceSynchronizer.prototype.onSurfaceSelect = function () {
327 if ( this.paused ) {
328 return;
329 }
330 this.submitChangeThrottled();
331 };
332
333 /**
334 * Translate incoming selections by change, then apply them and fire authorSelect
335 *
336 * @param {Object} newSelections Each author (key) maps to a new incoming ve.dm.Selection
337 * @param {ve.dm.Change|ve.dm.Transaction} [changeOrTx] Object to translate over, if any
338 * @fires ve.dm.SurfaceSynchronizer#authorSelect
339 */
340 ve.dm.SurfaceSynchronizer.prototype.applyNewSelections = function ( newSelections, changeOrTx ) {
341 const change = changeOrTx instanceof ve.dm.Change ? changeOrTx : null,
342 tx = changeOrTx instanceof ve.dm.Transaction ? changeOrTx : null;
343 for ( let authorId in newSelections ) {
344 authorId = +authorId;
345 if ( authorId === this.authorId ) {
346 continue;
347 }
348 let translatedSelection;
349 if ( change ) {
350 translatedSelection = newSelections[ authorId ].translateByChange( change, authorId );
351 } else if ( tx ) {
352 translatedSelection = newSelections[ authorId ].translateByTransactionWithAuthor( tx, authorId );
353 } else {
354 translatedSelection = newSelections[ authorId ];
355 }
356 if ( !translatedSelection.equals( this.authorSelections[ authorId ] ) ) {
357 // This works correctly even if newSelections === this.authorSelections
358 this.authorSelections[ authorId ] = translatedSelection;
359 this.emit( 'authorSelect', authorId );
360 }
361 }
362 };
363
364 /**
365 * Get author data object
366 *
367 * @param {number} [authorId] Author ID, defaults to current author
368 * @return {Object} Author object, containing 'name' and 'color'
369 */
370 ve.dm.SurfaceSynchronizer.prototype.getAuthorData = function ( authorId ) {
371 if ( authorId === undefined ) {
372 authorId = this.getAuthorId();
373 }
374 return this.authors[ authorId ];
375 };
376
377 ve.dm.SurfaceSynchronizer.prototype.onAuthorChange = function ( data ) {
378 this.authors[ data.authorId ] = data.authorData;
379 this.emit( 'authorChange', data.authorId );
380
381 if ( data.authorId === this.getAuthorId() ) {
382 ve.init.platform.sessionStorage.setObject( 've-collab-author', data.authorData );
383 }
384 };
385
386 ve.dm.SurfaceSynchronizer.prototype.changeAuthor = function ( data ) {
387 this.conn.send( 'changeAuthor', ve.extendObject( {}, this.getAuthorData( this.getAuthorId() ), data ) );
388 };
389
390 ve.dm.SurfaceSynchronizer.prototype.onAuthorDisconnect = function ( authorId ) {
391 delete this.authors[ authorId ];
392 delete this.authorSelections[ authorId ];
393 this.emit( 'authorDisconnect', authorId );
394 };
395
396 /**
397 * Respond to a "registered" event from the server
398 *
399 * @param {Object} data
400 * @param {number} data.authorId The author ID allocated by the server
401 * @param {string} data.token
402 * @fires ve.dm.SurfaceSynchronizer#wrongDoc
403 */
404 ve.dm.SurfaceSynchronizer.prototype.onRegistered = function ( data ) {
405 if ( this.serverId && this.serverId !== data.serverId ) {
406 this.conn.disconnect();
407 this.emit( 'wrongDoc' );
408 return;
409 }
410 this.serverId = data.serverId;
411 this.setAuthorId( data.authorId );
412 this.surface.setAuthorId( this.authorId );
413 this.token = data.token;
414 this.saveSessionKey();
415 };
416
417 ve.dm.SurfaceSynchronizer.prototype.saveSessionKey = function () {
418 ve.init.platform.sessionStorage.setObject( 'visualeditor-session-key', {
419 serverId: this.serverId,
420 docName: this.documentId,
421 authorId: this.getAuthorId(),
422 token: this.token
423 } );
424 };
425
426 ve.dm.SurfaceSynchronizer.prototype.loadSessionKey = function () {
427 const data = ve.init.platform.sessionStorage.getObject( 'visualeditor-session-key' );
428 if ( data && data.docName === this.documentId ) {
429 this.serverId = data.serverId;
430 this.setAuthorId( data.authorId );
431 this.token = data.token;
432 }
433 };
434
435 /**
436 * Respond to an initDoc event from the server, catching us up on the prior history of the document.
437 *
438 * @param {Object} data
439 * @param {Object} data.history Serialized change representing the server's history
440 * @param {Object} data.authors Object mapping author IDs to author data objects (name/color)
441 * @fires ve.dm.SurfaceSynchronizer#initDoc
442 */
443 ve.dm.SurfaceSynchronizer.prototype.onInitDoc = function ( data ) {
444 if ( this.initialized ) {
445 // Ignore attempt to initialize a second time
446 return;
447 }
448 for ( const authorId in data.authors ) {
449 this.onAuthorChange( {
450 authorId: +authorId,
451 authorData: data.authors[ authorId ]
452 } );
453 }
454 try {
455 const history = ve.dm.Change.static.deserialize( data.history );
456 this.acceptChange( history );
457 } catch ( e ) {
458 this.conn.disconnect();
459 this.emit( 'initDoc', e );
460 return;
461 }
462 this.emit( 'initDoc' );
463
464 // Mark ourselves as initialized and retry any prevented submissions
465 this.initialized = true;
466 this.submitChangeThrottled();
467 };
468
469 /**
470 * Respond to a newChange event from the server, signalling a newly committed change
471 *
472 * If the commited change is by another author, then:
473 * - Rebase uncommitted changes over the committed change
474 * - If there is a rebase rejection, then apply its inverse to the document
475 * - Apply the rebase-transposed committed change to the document
476 * - Rewrite history to have the committed change followed by rebased uncommitted changes
477 *
478 * If the committed change is by the local author, then it is already applied to the document
479 * and at the correct point in the history: just move the commit pointer.
480 *
481 * @param {Object} serializedChange Serialized ve.dm.Change that the server has applied
482 */
483 ve.dm.SurfaceSynchronizer.prototype.onNewChange = function ( serializedChange ) {
484 const change = ve.dm.Change.static.deserialize( serializedChange );
485 if ( this.paused ) {
486 this.queuedChanges.push( change );
487 return;
488 }
489 // Make sure we don't attempt to submit any of the transactions we commit while manipulating
490 // the state of the document
491 this.applying = true;
492 try {
493 this.acceptChange( change );
494 } finally {
495 this.applying = false;
496 }
497 // Schedule submission of unsent local changes, if any
498 this.submitChangeThrottled();
499 };
500
501 ve.dm.SurfaceSynchronizer.prototype.onDisconnect = function () {
502 this.initialized = false;
503 this.emit( 'disconnect' );
504 };