model.coffee 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. # The model of all the ops. Responsible for applying & transforming remote deltas
  2. # and managing the storage layer.
  3. #
  4. # Actual storage is handled by the database wrappers in db/*, wrapped by DocCache
  5. {EventEmitter} = require 'events'
  6. queue = require './syncqueue'
  7. types = require '../types'
  8. isArray = (o) -> Object.prototype.toString.call(o) == '[object Array]'
  9. # This constructor creates a new Model object. There will be one model object
  10. # per server context.
  11. #
  12. # The model object is responsible for a lot of things:
  13. #
  14. # - It manages the interactions with the database
  15. # - It maintains (in memory) a set of all active documents
  16. # - It calls out to the OT functions when necessary
  17. #
  18. # The model is an event emitter. It emits the following events:
  19. #
  20. # create(docName, data): A document has been created with the specified name & data
  21. module.exports = Model = (db, options) ->
  22. # db can be null if the user doesn't want persistance.
  23. return new Model(db, options) if !(this instanceof Model)
  24. model = this
  25. options ?= {}
  26. # This is a cache of 'live' documents.
  27. #
  28. # The cache is a map from docName -> {
  29. # ops:[{op, meta}]
  30. # snapshot
  31. # type
  32. # v
  33. # meta
  34. # eventEmitter
  35. # reapTimer
  36. # committedVersion: v
  37. # snapshotWriteLock: bool to make sure writeSnapshot isn't re-entrant
  38. # dbMeta: database specific data
  39. # opQueue: syncQueue for processing ops
  40. # }
  41. #
  42. # The ops list contains the document's last options.numCachedOps ops. (Or all
  43. # of them if we're using a memory store).
  44. #
  45. # Documents are stored in this set so long as the document has been accessed in
  46. # the last few seconds (options.reapTime) OR at least one client has the document
  47. # open. I don't know if I should keep open (but not being edited) documents live -
  48. # maybe if a client has a document open but the document isn't being edited, I should
  49. # flush it from the cache.
  50. #
  51. # In any case, the API to model is designed such that if we want to change that later
  52. # it should be pretty easy to do so without any external-to-the-model code changes.
  53. docs = {}
  54. # This is a map from docName -> [callback]. It is used when a document hasn't been
  55. # cached and multiple getSnapshot() / getVersion() requests come in. All requests
  56. # are added to the callback list and called when db.getSnapshot() returns.
  57. #
  58. # callback(error, snapshot data)
  59. awaitingGetSnapshot = {}
  60. # The time that documents which no clients have open will stay in the cache.
  61. # Should be > 0.
  62. options.reapTime ?= 3000
  63. # The number of operations the cache holds before reusing the space
  64. options.numCachedOps ?= 10
  65. # This option forces documents to be reaped, even when there's no database backend.
  66. # This is useful when you don't care about persistance and don't want to gradually
  67. # fill memory.
  68. #
  69. # You might want to set reapTime to a day or something.
  70. options.forceReaping ?= false
  71. # Until I come up with a better strategy, we'll save a copy of the document snapshot
  72. # to the database every ~20 submitted ops.
  73. options.opsBeforeCommit ?= 20
  74. # It takes some processing time to transform client ops. The server will punt ops back to the
  75. # client to transform if they're too old.
  76. options.maximumAge ?= 40
  77. # **** Cache API methods
  78. # Its important that all ops are applied in order. This helper method creates the op submission queue
  79. # for a single document. This contains the logic for transforming & applying ops.
  80. makeOpQueue = (docName, doc) -> queue (opData, callback) ->
  81. return callback 'Version missing' unless opData.v >= 0
  82. return callback 'Op at future version' if opData.v > doc.v
  83. # Punt the transforming work back to the client if the op is too old.
  84. return callback 'Op too old' if opData.v + options.maximumAge < doc.v
  85. opData.meta ||= {}
  86. opData.meta.ts = Date.now()
  87. # We'll need to transform the op to the current version of the document. This
  88. # calls the callback immediately if opVersion == doc.v.
  89. getOps docName, opData.v, doc.v, (error, ops) ->
  90. return callback error if error
  91. unless doc.v - opData.v == ops.length
  92. # This should never happen. It indicates that we didn't get all the ops we
  93. # asked for. Its important that the submitted op is correctly transformed.
  94. console.error "Could not get old ops in model for document #{docName}"
  95. console.error "Expected ops #{opData.v} to #{doc.v} and got #{ops.length} ops"
  96. return callback 'Internal error'
  97. if ops.length > 0
  98. try
  99. # If there's enough ops, it might be worth spinning this out into a webworker thread.
  100. for oldOp in ops
  101. # Dup detection works by sending the id(s) the op has been submitted with previously.
  102. # If the id matches, we reject it. The client can also detect the op has been submitted
  103. # already if it sees its own previous id in the ops it sees when it does catchup.
  104. if oldOp.meta.source and opData.dupIfSource and oldOp.meta.source in opData.dupIfSource
  105. return callback 'Op already submitted'
  106. opData.op = doc.type.transform opData.op, oldOp.op, 'left'
  107. opData.v++
  108. catch error
  109. console.error error.stack
  110. return callback error.message
  111. try
  112. snapshot = doc.type.apply doc.snapshot, opData.op
  113. catch error
  114. console.error error.stack
  115. return callback error.message
  116. # The op data should be at the current version, and the new document data should be at
  117. # the next version.
  118. #
  119. # This should never happen in practice, but its a nice little check to make sure everything
  120. # is hunky-dory.
  121. unless opData.v == doc.v
  122. # This should never happen.
  123. console.error "Version mismatch detected in model. File a ticket - this is a bug."
  124. console.error "Expecting #{opData.v} == #{doc.v}"
  125. return callback 'Internal error'
  126. #newDocData = {snapshot, type:type.name, v:opVersion + 1, meta:docData.meta}
  127. writeOp = db?.writeOp or (docName, newOpData, callback) -> callback()
  128. writeOp docName, opData, (error) ->
  129. if error
  130. # The user should probably know about this.
  131. console.warn "Error writing ops to database: #{error}"
  132. return callback error
  133. options.stats?.writeOp?()
  134. # This is needed when we emit the 'change' event, below.
  135. oldSnapshot = doc.snapshot
  136. # All the heavy lifting is now done. Finally, we'll update the cache with the new data
  137. # and (maybe!) save a new document snapshot to the database.
  138. doc.v = opData.v + 1
  139. doc.snapshot = snapshot
  140. doc.ops.push opData
  141. doc.ops.shift() if db and doc.ops.length > options.numCachedOps
  142. model.emit 'applyOp', docName, opData, snapshot, oldSnapshot
  143. doc.eventEmitter.emit 'op', opData, snapshot, oldSnapshot
  144. # The callback is called with the version of the document at which the op was applied.
  145. # This is the op.v after transformation, and its doc.v - 1.
  146. callback null, opData.v
  147. # I need a decent strategy here for deciding whether or not to save the snapshot.
  148. #
  149. # The 'right' strategy looks something like "Store the snapshot whenever the snapshot
  150. # is smaller than the accumulated op data". For now, I'll just store it every 20
  151. # ops or something. (Configurable with doc.committedVersion)
  152. if !doc.snapshotWriteLock and doc.committedVersion + options.opsBeforeCommit <= doc.v
  153. tryWriteSnapshot docName, (error) ->
  154. console.warn "Error writing snapshot #{error}. This is nonfatal" if error
  155. # Add the data for the given docName to the cache. The named document shouldn't already
  156. # exist in the doc set.
  157. #
  158. # Returns the new doc.
  159. add = (docName, error, data, committedVersion, ops, dbMeta) ->
  160. callbacks = awaitingGetSnapshot[docName]
  161. delete awaitingGetSnapshot[docName]
  162. if error
  163. callback error for callback in callbacks if callbacks
  164. else
  165. doc = docs[docName] =
  166. snapshot: data.snapshot
  167. v: data.v
  168. type: data.type
  169. meta: data.meta
  170. # Cache of ops
  171. ops: ops or []
  172. eventEmitter: new EventEmitter
  173. # Timer before the document will be invalidated from the cache (if the document has no
  174. # listeners)
  175. reapTimer: null
  176. # Version of the snapshot thats in the database
  177. committedVersion: committedVersion ? data.v
  178. snapshotWriteLock: false
  179. dbMeta: dbMeta
  180. doc.opQueue = makeOpQueue docName, doc
  181. refreshReapingTimeout docName
  182. model.emit 'add', docName, data
  183. callback null, doc for callback in callbacks if callbacks
  184. doc
  185. # This is a little helper wrapper around db.getOps. It does two things:
  186. #
  187. # - If there's no database set, it returns an error to the callback
  188. # - It adds version numbers to each op returned from the database
  189. # (These can be inferred from context so the DB doesn't store them, but its useful to have them).
  190. getOpsInternal = (docName, start, end, callback) ->
  191. return callback? 'Document does not exist' unless db
  192. db.getOps docName, start, end, (error, ops) ->
  193. return callback? error if error
  194. v = start
  195. op.v = v++ for op in ops
  196. callback? null, ops
  197. # Load the named document into the cache. This function is re-entrant.
  198. #
  199. # The callback is called with (error, doc)
  200. load = (docName, callback) ->
  201. if docs[docName]
  202. # The document is already loaded. Return immediately.
  203. options.stats?.cacheHit? 'getSnapshot'
  204. return callback null, docs[docName]
  205. # We're a memory store. If we don't have it, nobody does.
  206. return callback 'Document does not exist' unless db
  207. callbacks = awaitingGetSnapshot[docName]
  208. # The document is being loaded already. Add ourselves as a callback.
  209. return callbacks.push callback if callbacks
  210. options.stats?.cacheMiss? 'getSnapshot'
  211. # The document isn't loaded and isn't being loaded. Load it.
  212. awaitingGetSnapshot[docName] = [callback]
  213. db.getSnapshot docName, (error, data, dbMeta) ->
  214. return add docName, error if error
  215. type = types[data.type]
  216. unless type
  217. console.warn "Type '#{data.type}' missing"
  218. return callback "Type not found"
  219. data.type = type
  220. committedVersion = data.v
  221. # The server can close without saving the most recent document snapshot.
  222. # In this case, there are extra ops which need to be applied before
  223. # returning the snapshot.
  224. getOpsInternal docName, data.v, null, (error, ops) ->
  225. return callback error if error
  226. if ops.length > 0
  227. console.log "Catchup #{docName} #{data.v} -> #{data.v + ops.length}"
  228. try
  229. for op in ops
  230. data.snapshot = type.apply data.snapshot, op.op
  231. data.v++
  232. catch e
  233. # This should never happen - it indicates that whats in the
  234. # database is invalid.
  235. console.error "Op data invalid for #{docName}: #{e.stack}"
  236. return callback 'Op data invalid'
  237. model.emit 'load', docName, data
  238. add docName, error, data, committedVersion, ops, dbMeta
  239. # This makes sure the cache contains a document. If the doc cache doesn't contain
  240. # a document, it is loaded from the database and stored.
  241. #
  242. # Documents are stored so long as either:
  243. # - They have been accessed within the past #{PERIOD}
  244. # - At least one client has the document open
  245. refreshReapingTimeout = (docName) ->
  246. doc = docs[docName]
  247. return unless doc
  248. # I want to let the clients list be updated before this is called.
  249. process.nextTick ->
  250. # This is an awkward way to find out the number of clients on a document. If this
  251. # causes performance issues, add a numClients field to the document.
  252. #
  253. # The first check is because its possible that between refreshReapingTimeout being called and this
  254. # event being fired, someone called delete() on the document and hence the doc is something else now.
  255. if doc == docs[docName] and
  256. doc.eventEmitter.listeners('op').length == 0 and
  257. (db or options.forceReaping) and
  258. doc.opQueue.busy is false
  259. clearTimeout doc.reapTimer
  260. doc.reapTimer = reapTimer = setTimeout ->
  261. tryWriteSnapshot docName, ->
  262. # If the reaping timeout has been refreshed while we're writing the snapshot, or if we're
  263. # in the middle of applying an operation, don't reap.
  264. delete docs[docName] if docs[docName].reapTimer is reapTimer and doc.opQueue.busy is false
  265. , options.reapTime
  266. tryWriteSnapshot = (docName, callback) ->
  267. return callback?() unless db
  268. doc = docs[docName]
  269. # The doc is closed
  270. return callback?() unless doc
  271. # The document is already saved.
  272. return callback?() if doc.committedVersion is doc.v
  273. return callback? 'Another snapshot write is in progress' if doc.snapshotWriteLock
  274. doc.snapshotWriteLock = true
  275. options.stats?.writeSnapshot?()
  276. writeSnapshot = db?.writeSnapshot or (docName, docData, dbMeta, callback) -> callback()
  277. data =
  278. v: doc.v
  279. meta: doc.meta
  280. snapshot: doc.snapshot
  281. # The database doesn't know about object types.
  282. type: doc.type.name
  283. # Commit snapshot.
  284. writeSnapshot docName, data, doc.dbMeta, (error, dbMeta) ->
  285. doc.snapshotWriteLock = false
  286. # We have to use data.v here because the version in the doc could
  287. # have been updated between the call to writeSnapshot() and now.
  288. doc.committedVersion = data.v
  289. doc.dbMeta = dbMeta
  290. callback? error
  291. # *** Model interface methods
  292. # Create a new document.
  293. #
  294. # data should be {snapshot, type, [meta]}. The version of a new document is 0.
  295. @create = (docName, type, meta, callback) ->
  296. [meta, callback] = [{}, meta] if typeof meta is 'function'
  297. return callback? 'Invalid document name' if docName.match /\//
  298. return callback? 'Document already exists' if docs[docName]
  299. type = types[type] if typeof type == 'string'
  300. return callback? 'Type not found' unless type
  301. data =
  302. snapshot:type.create()
  303. type:type.name
  304. meta:meta or {}
  305. v:0
  306. done = (error, dbMeta) ->
  307. # dbMeta can be used to cache extra state needed by the database to access the document, like an ID or something.
  308. return callback? error if error
  309. # From here on we'll store the object version of the type name.
  310. data.type = type
  311. add docName, null, data, 0, [], dbMeta
  312. model.emit 'create', docName, data
  313. callback?()
  314. if db
  315. db.create docName, data, done
  316. else
  317. done()
  318. # Perminantly deletes the specified document.
  319. # If listeners are attached, they are removed.
  320. #
  321. # The callback is called with (error) if there was an error. If error is null / undefined, the
  322. # document was deleted.
  323. #
  324. # WARNING: This isn't well supported throughout the code. (Eg, streaming clients aren't told about the
  325. # deletion. Subsequent op submissions will fail).
  326. @delete = (docName, callback) ->
  327. doc = docs[docName]
  328. if doc
  329. clearTimeout doc.reapTimer
  330. delete docs[docName]
  331. done = (error) ->
  332. model.emit 'delete', docName unless error
  333. callback? error
  334. if db
  335. db.delete docName, doc?.dbMeta, done
  336. else
  337. done (if !doc then 'Document does not exist')
  338. # This gets all operations from [start...end]. (That is, its not inclusive.)
  339. #
  340. # end can be null. This means 'get me all ops from start'.
  341. #
  342. # Each op returned is in the form {op:o, meta:m, v:version}.
  343. #
  344. # Callback is called with (error, [ops])
  345. #
  346. # If the document does not exist, getOps doesn't necessarily return an error. This is because
  347. # its awkward to figure out whether or not the document exists for things
  348. # like the redis database backend. I guess its a bit gross having this inconsistant
  349. # with the other DB calls, but its certainly convenient.
  350. #
  351. # Use getVersion() to determine if a document actually exists, if thats what you're
  352. # after.
  353. @getOps = getOps = (docName, start, end, callback) ->
  354. # getOps will only use the op cache if its there. It won't fill the op cache in.
  355. throw new Error 'start must be 0+' unless start >= 0
  356. [end, callback] = [null, end] if typeof end is 'function'
  357. ops = docs[docName]?.ops
  358. if ops
  359. version = docs[docName].v
  360. # Ops contains an array of ops. The last op in the list is the last op applied
  361. end ?= version
  362. start = Math.min start, end
  363. return callback null, [] if start == end
  364. # Base is the version number of the oldest op we have cached
  365. base = version - ops.length
  366. # If the database is null, we'll trim to the ops we do have and hope thats enough.
  367. if start >= base or db is null
  368. refreshReapingTimeout docName
  369. options.stats?.cacheHit 'getOps'
  370. return callback null, ops[(start - base)...(end - base)]
  371. options.stats?.cacheMiss 'getOps'
  372. getOpsInternal docName, start, end, callback
  373. # Gets the snapshot data for the specified document.
  374. # getSnapshot(docName, callback)
  375. # Callback is called with (error, {v: <version>, type: <type>, snapshot: <snapshot>, meta: <meta>})
  376. @getSnapshot = (docName, callback) ->
  377. load docName, (error, doc) ->
  378. callback error, if doc then {v:doc.v, type:doc.type, snapshot:doc.snapshot, meta:doc.meta}
  379. # Gets the latest version # of the document.
  380. # getVersion(docName, callback)
  381. # callback is called with (error, version).
  382. @getVersion = (docName, callback) ->
  383. load docName, (error, doc) -> callback error, doc?.v
  384. # Apply an op to the specified document.
  385. # The callback is passed (error, applied version #)
  386. # opData = {op:op, v:v, meta:metadata}
  387. #
  388. # Ops are queued before being applied so that the following code applies op C before op B:
  389. # model.applyOp 'doc', OPA, -> model.applyOp 'doc', OPB
  390. # model.applyOp 'doc', OPC
  391. @applyOp = (docName, opData, callback) ->
  392. # All the logic for this is in makeOpQueue, above.
  393. load docName, (error, doc) ->
  394. return callback error if error
  395. process.nextTick -> doc.opQueue opData, (error, newVersion) ->
  396. refreshReapingTimeout docName
  397. callback? error, newVersion
  398. # TODO: store (some) metadata in DB
  399. # TODO: op and meta should be combineable in the op that gets sent
  400. @applyMetaOp = (docName, metaOpData, callback) ->
  401. {path, value} = metaOpData.meta
  402. return callback? "path should be an array" unless isArray path
  403. load docName, (error, doc) ->
  404. if error?
  405. callback? error
  406. else
  407. applied = false
  408. switch path[0]
  409. when 'shout'
  410. doc.eventEmitter.emit 'op', metaOpData
  411. applied = true
  412. model.emit 'applyMetaOp', docName, path, value if applied
  413. callback? null, doc.v
  414. # Listen to all ops from the specified version. If version is in the past, all
  415. # ops since that version are sent immediately to the listener.
  416. #
  417. # The callback is called once the listener is attached, but before any ops have been passed
  418. # to the listener.
  419. #
  420. # This will _not_ edit the document metadata.
  421. #
  422. # If there are any listeners, we don't purge the document from the cache. But be aware, this behaviour
  423. # might change in a future version.
  424. #
  425. # version is the document version at which the document is opened. It can be left out if you want to open
  426. # the document at the most recent version.
  427. #
  428. # listener is called with (opData) each time an op is applied.
  429. #
  430. # callback(error, openedVersion)
  431. @listen = (docName, version, listener, callback) ->
  432. [version, listener, callback] = [null, version, listener] if typeof version is 'function'
  433. load docName, (error, doc) ->
  434. return callback? error if error
  435. clearTimeout doc.reapTimer
  436. if version?
  437. getOps docName, version, null, (error, data) ->
  438. return callback? error if error
  439. doc.eventEmitter.on 'op', listener
  440. callback? null, version
  441. for op in data
  442. listener op
  443. # The listener may well remove itself during the catchup phase. If this happens, break early.
  444. # This is done in a quite inefficient way. (O(n) where n = #listeners on doc)
  445. break unless listener in doc.eventEmitter.listeners 'op'
  446. else # Version is null / undefined. Just add the listener.
  447. doc.eventEmitter.on 'op', listener
  448. callback? null, doc.v
  449. # Remove a listener for a particular document.
  450. #
  451. # removeListener(docName, listener)
  452. #
  453. # This is synchronous.
  454. @removeListener = (docName, listener) ->
  455. # The document should already be loaded.
  456. doc = docs[docName]
  457. throw new Error 'removeListener called but document not loaded' unless doc
  458. doc.eventEmitter.removeListener 'op', listener
  459. refreshReapingTimeout docName
  460. # Flush saves all snapshot data to the database. I'm not sure whether or not this is actually needed -
  461. # sharejs will happily replay uncommitted ops when documents are re-opened anyway.
  462. @flush = (callback) ->
  463. return callback?() unless db
  464. pendingWrites = 0
  465. for docName, doc of docs
  466. if doc.committedVersion < doc.v
  467. pendingWrites++
  468. # I'm hoping writeSnapshot will always happen in another thread.
  469. tryWriteSnapshot docName, ->
  470. process.nextTick ->
  471. pendingWrites--
  472. callback?() if pendingWrites is 0
  473. # If nothing was queued, terminate immediately.
  474. callback?() if pendingWrites is 0
  475. # Close the database connection. This is needed so nodejs can shut down cleanly.
  476. @closeDb = ->
  477. db?.close?()
  478. db = null
  479. return
  480. # Model inherits from EventEmitter.
  481. Model:: = new EventEmitter