Ensure events are delivered in order

This commit is contained in:
Kevin Sawicki & Nathan Sobo 2013-06-25 17:02:34 -07:00 committed by Nathan Sobo
parent b5aa0b900c
commit 7fe356b649
2 changed files with 28 additions and 4 deletions

View File

@ -1,6 +1,5 @@
require 'atom'
require 'window'
_ = require 'underscore'
{createPeer, connectDocument} = require './session-utils'
{createSite, Document} = require 'telepath'

View File

@ -7,14 +7,39 @@ module.exports =
new Peer(id, host: 'ec2-54-218-51-127.us-west-2.compute.amazonaws.com', port: 8080)
connectDocument: (doc, connection) ->
nextOutputEventId = 1
outputListener = (event) ->
console.log 'sending event', event
event.id = nextOutputEventId++
console.log 'sending event', event.id, event
connection.send(event)
doc.outputEvents.on('changed', outputListener)
connection.on 'data', (event) ->
console.log 'receiving event', event
queuedEvents = []
nextInputEventId = 1
handleInputEvent = (event) ->
console.log 'received event', event.id, event
doc.handleInputEvent(event)
nextInputEventId = event.id + 1
flushQueuedEvents = ->
loop
eventHandled = false
for event, index in queuedEvents when event.id is nextInputEventId
handleInputEvent(event)
queuedEvents.splice(index, 1)
eventHandled = true
break
break unless eventHandled
connection.on 'data', (event) ->
if event.id is nextInputEventId
handleInputEvent(event)
flushQueuedEvents()
else
console.log 'enqueing event', event.id, event
queuedEvents.push(event)
connection.on 'close', ->
doc.outputEvents.removeListener('changed', outputListener)
connection.on 'error', (error) ->
console.error 'connection error', error.stack ? error