connection.coffee 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. # A Connection wraps a persistant BC connection to a sharejs server.
  2. #
  3. # This class implements the client side of the protocol defined here:
  4. # https://github.com/josephg/ShareJS/wiki/Wire-Protocol
  5. #
  6. # The equivalent server code is in src/server/browserchannel.coffee.
  7. #
  8. # This file is a bit of a mess. I'm dreadfully sorry about that. It passes all the tests,
  9. # so I have hope that its *correct* even if its not clean.
  10. #
  11. # Most of Connection exists to support the open() method, which creates a new document
  12. # reference.
  13. if WEB?
  14. types = exports.types
  15. throw new Error 'Must load browserchannel before this library' unless window.BCSocket
  16. {BCSocket} = window
  17. else
  18. types = require '../types'
  19. {BCSocket} = require 'browserchannel'
  20. Doc = require('./doc').Doc
  21. class Connection
  22. constructor: (host) ->
  23. # Map of docname -> doc
  24. @docs = {}
  25. # States:
  26. # - 'connecting': The connection is being established
  27. # - 'handshaking': The connection has been established, but we don't have the auth ID yet
  28. # - 'ok': We have connected and recieved our client ID. Ready for data.
  29. # - 'disconnected': The connection is closed, but it will not reconnect automatically.
  30. # - 'stopped': The connection is closed, and will not reconnect.
  31. @state = 'connecting'
  32. @socket = new BCSocket host, reconnect:true
  33. @socket.onmessage = (msg) =>
  34. if msg.auth is null
  35. # Auth failed.
  36. @lastError = msg.error # 'forbidden'
  37. @disconnect()
  38. return @emit 'connect failed', msg.error
  39. else if msg.auth
  40. # Our very own client id.
  41. @id = msg.auth
  42. @setState 'ok'
  43. return
  44. docName = msg.doc
  45. if docName isnt undefined
  46. @lastReceivedDoc = docName
  47. else
  48. msg.doc = docName = @lastReceivedDoc
  49. if @docs[docName]
  50. @docs[docName]._onMessage msg
  51. else
  52. console?.error 'Unhandled message', msg
  53. @connected = false
  54. @socket.onclose = (reason) =>
  55. #console.warn 'onclose', reason
  56. @setState 'disconnected', reason
  57. if reason in ['Closed', 'Stopped by server']
  58. @setState 'stopped', @lastError or reason
  59. @socket.onerror = (e) =>
  60. #console.warn 'onerror', e
  61. @emit 'error', e
  62. @socket.onopen = =>
  63. #console.warn 'onopen'
  64. @lastError = @lastReceivedDoc = @lastSentDoc = null
  65. @setState 'handshaking'
  66. @socket.onconnecting = =>
  67. #console.warn 'connecting'
  68. @setState 'connecting'
  69. setState: (state, data) ->
  70. return if @state is state
  71. @state = state
  72. delete @id if state is 'disconnected'
  73. @emit state, data
  74. # Documents could just subscribe to the state change events, but there's less state to
  75. # clean up when you close a document if I just notify the doucments directly.
  76. for docName, doc of @docs
  77. doc._connectionStateChanged state, data
  78. send: (data) ->
  79. docName = data.doc
  80. if docName is @lastSentDoc
  81. delete data.doc
  82. else
  83. @lastSentDoc = docName
  84. #console.warn 'c->s', data
  85. @socket.send data
  86. disconnect: ->
  87. # This will call @socket.onclose(), which in turn will emit the 'disconnected' event.
  88. #console.warn 'calling close on the socket'
  89. @socket.close()
  90. # *** Doc management
  91. makeDoc: (name, data, callback) ->
  92. throw new Error("Doc #{name} already open") if @docs[name]
  93. doc = new Doc(@, name, data)
  94. @docs[name] = doc
  95. doc.open (error) =>
  96. delete @docs[name] if error
  97. callback error, (doc unless error)
  98. # Open a document that already exists
  99. # callback(error, doc)
  100. openExisting: (docName, callback) ->
  101. return callback 'connection closed' if @state is 'stopped'
  102. return callback null, @docs[docName] if @docs[docName]
  103. doc = @makeDoc docName, {}, callback
  104. # Open a document. It will be created if it doesn't already exist.
  105. # Callback is passed a document or an error
  106. # type is either a type name (eg 'text' or 'simple') or the actual type object.
  107. # Types must be supported by the server.
  108. # callback(error, doc)
  109. open: (docName, type, callback) ->
  110. return callback 'connection closed' if @state is 'stopped'
  111. if typeof type is 'function'
  112. callback = type
  113. type = 'text'
  114. callback ||= ->
  115. type = types[type] if typeof type is 'string'
  116. throw new Error "OT code for document type missing" unless type
  117. throw new Error 'Server-generated random doc names are not currently supported' unless docName?
  118. if @docs[docName]
  119. doc = @docs[docName]
  120. if doc.type == type
  121. callback null, doc
  122. else
  123. callback 'Type mismatch', doc
  124. return
  125. @makeDoc docName, {create:true, type:type.name}, callback
  126. # Not currently working.
  127. # create: (type, callback) ->
  128. # open null, type, callback
  129. # Make connections event emitters.
  130. unless WEB?
  131. MicroEvent = require './microevent'
  132. MicroEvent.mixin Connection
  133. exports.Connection = Connection