model.coffee 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  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. if options.maxDocLength? and doc.snapshot.length > options.maxDocLength
  117. return callback "Update takes doc over max doc size"
  118. # The op data should be at the current version, and the new document data should be at
  119. # the next version.
  120. #
  121. # This should never happen in practice, but its a nice little check to make sure everything
  122. # is hunky-dory.
  123. unless opData.v == doc.v
  124. # This should never happen.
  125. console.error "Version mismatch detected in model. File a ticket - this is a bug."
  126. console.error "Expecting #{opData.v} == #{doc.v}"
  127. return callback 'Internal error'
  128. #newDocData = {snapshot, type:type.name, v:opVersion + 1, meta:docData.meta}
  129. writeOp = db?.writeOp or (docName, newOpData, callback) -> callback()
  130. writeOp docName, opData, (error) ->
  131. if error
  132. # The user should probably know about this.
  133. console.warn "Error writing ops to database: #{error}"
  134. return callback error
  135. options.stats?.writeOp?()
  136. # This is needed when we emit the 'change' event, below.
  137. oldSnapshot = doc.snapshot
  138. # All the heavy lifting is now done. Finally, we'll update the cache with the new data
  139. # and (maybe!) save a new document snapshot to the database.
  140. doc.v = opData.v + 1
  141. doc.snapshot = snapshot
  142. doc.ops.push opData
  143. doc.ops.shift() if db and doc.ops.length > options.numCachedOps
  144. model.emit 'applyOp', docName, opData, snapshot, oldSnapshot
  145. doc.eventEmitter.emit 'op', opData, snapshot, oldSnapshot
  146. # The callback is called with the version of the document at which the op was applied.
  147. # This is the op.v after transformation, and its doc.v - 1.
  148. callback null, opData.v
  149. # I need a decent strategy here for deciding whether or not to save the snapshot.
  150. #
  151. # The 'right' strategy looks something like "Store the snapshot whenever the snapshot
  152. # is smaller than the accumulated op data". For now, I'll just store it every 20
  153. # ops or something. (Configurable with doc.committedVersion)
  154. if !doc.snapshotWriteLock and doc.committedVersion + options.opsBeforeCommit <= doc.v
  155. tryWriteSnapshot docName, (error) ->
  156. console.warn "Error writing snapshot #{error}. This is nonfatal" if error
  157. # Add the data for the given docName to the cache. The named document shouldn't already
  158. # exist in the doc set.
  159. #
  160. # Returns the new doc.
  161. add = (docName, error, data, committedVersion, ops, dbMeta) ->
  162. callbacks = awaitingGetSnapshot[docName]
  163. delete awaitingGetSnapshot[docName]
  164. if error
  165. callback error for callback in callbacks if callbacks
  166. else
  167. doc = docs[docName] =
  168. snapshot: data.snapshot
  169. v: data.v
  170. type: data.type
  171. meta: data.meta
  172. # Cache of ops
  173. ops: ops or []
  174. eventEmitter: new EventEmitter
  175. # Timer before the document will be invalidated from the cache (if the document has no
  176. # listeners)
  177. reapTimer: null
  178. # Version of the snapshot thats in the database
  179. committedVersion: committedVersion ? data.v
  180. snapshotWriteLock: false
  181. dbMeta: dbMeta
  182. doc.opQueue = makeOpQueue docName, doc
  183. refreshReapingTimeout docName
  184. model.emit 'add', docName, data
  185. callback null, doc for callback in callbacks if callbacks
  186. doc
  187. # This is a little helper wrapper around db.getOps. It does two things:
  188. #
  189. # - If there's no database set, it returns an error to the callback
  190. # - It adds version numbers to each op returned from the database
  191. # (These can be inferred from context so the DB doesn't store them, but its useful to have them).
  192. getOpsInternal = (docName, start, end, callback) ->
  193. return callback? 'Document does not exist' unless db
  194. db.getOps docName, start, end, (error, ops) ->
  195. return callback? error if error
  196. v = start
  197. op.v = v++ for op in ops
  198. callback? null, ops
  199. # Load the named document into the cache. This function is re-entrant.
  200. #
  201. # The callback is called with (error, doc)
  202. load = (docName, callback) ->
  203. if docs[docName]
  204. # The document is already loaded. Return immediately.
  205. options.stats?.cacheHit? 'getSnapshot'
  206. return callback null, docs[docName]
  207. # We're a memory store. If we don't have it, nobody does.
  208. return callback 'Document does not exist' unless db
  209. callbacks = awaitingGetSnapshot[docName]
  210. # The document is being loaded already. Add ourselves as a callback.
  211. return callbacks.push callback if callbacks
  212. options.stats?.cacheMiss? 'getSnapshot'
  213. # The document isn't loaded and isn't being loaded. Load it.
  214. awaitingGetSnapshot[docName] = [callback]
  215. db.getSnapshot docName, (error, data, dbMeta) ->
  216. return add docName, error if error
  217. type = types[data.type]
  218. unless type
  219. console.warn "Type '#{data.type}' missing"
  220. return callback "Type not found"
  221. data.type = type
  222. committedVersion = data.v
  223. # The server can close without saving the most recent document snapshot.
  224. # In this case, there are extra ops which need to be applied before
  225. # returning the snapshot.
  226. getOpsInternal docName, data.v, null, (error, ops) ->
  227. return callback error if error
  228. if ops.length > 0
  229. console.log "Catchup #{docName} #{data.v} -> #{data.v + ops.length}"
  230. try
  231. for op in ops
  232. data.snapshot = type.apply data.snapshot, op.op
  233. data.v++
  234. catch e
  235. # This should never happen - it indicates that whats in the
  236. # database is invalid.
  237. console.error "Op data invalid for #{docName}: #{e.stack}"
  238. return callback 'Op data invalid'
  239. model.emit 'load', docName, data
  240. add docName, error, data, committedVersion, ops, dbMeta
  241. # This makes sure the cache contains a document. If the doc cache doesn't contain
  242. # a document, it is loaded from the database and stored.
  243. #
  244. # Documents are stored so long as either:
  245. # - They have been accessed within the past #{PERIOD}
  246. # - At least one client has the document open
  247. refreshReapingTimeout = (docName) ->
  248. doc = docs[docName]
  249. return unless doc
  250. # I want to let the clients list be updated before this is called.
  251. process.nextTick ->
  252. # This is an awkward way to find out the number of clients on a document. If this
  253. # causes performance issues, add a numClients field to the document.
  254. #
  255. # The first check is because its possible that between refreshReapingTimeout being called and this
  256. # event being fired, someone called delete() on the document and hence the doc is something else now.
  257. if doc == docs[docName] and
  258. doc.eventEmitter.listeners('op').length == 0 and
  259. (db or options.forceReaping) and
  260. doc.opQueue.busy is false
  261. clearTimeout doc.reapTimer
  262. doc.reapTimer = reapTimer = setTimeout ->
  263. tryWriteSnapshot docName, ->
  264. # If the reaping timeout has been refreshed while we're writing the snapshot, or if we're
  265. # in the middle of applying an operation, don't reap.
  266. delete docs[docName] if docs[docName].reapTimer is reapTimer and doc.opQueue.busy is false
  267. , options.reapTime
  268. tryWriteSnapshot = (docName, callback) ->
  269. return callback?() unless db
  270. doc = docs[docName]
  271. # The doc is closed
  272. return callback?() unless doc
  273. # The document is already saved.
  274. return callback?() if doc.committedVersion is doc.v
  275. return callback? 'Another snapshot write is in progress' if doc.snapshotWriteLock
  276. doc.snapshotWriteLock = true
  277. options.stats?.writeSnapshot?()
  278. writeSnapshot = db?.writeSnapshot or (docName, docData, dbMeta, callback) -> callback()
  279. data =
  280. v: doc.v
  281. meta: doc.meta
  282. snapshot: doc.snapshot
  283. # The database doesn't know about object types.
  284. type: doc.type.name
  285. # Commit snapshot.
  286. writeSnapshot docName, data, doc.dbMeta, (error, dbMeta) ->
  287. doc.snapshotWriteLock = false
  288. # We have to use data.v here because the version in the doc could
  289. # have been updated between the call to writeSnapshot() and now.
  290. doc.committedVersion = data.v
  291. doc.dbMeta = dbMeta
  292. callback? error
  293. # *** Model interface methods
  294. # Create a new document.
  295. #
  296. # data should be {snapshot, type, [meta]}. The version of a new document is 0.
  297. @create = (docName, type, meta, callback) ->
  298. [meta, callback] = [{}, meta] if typeof meta is 'function'
  299. return callback? 'Invalid document name' if docName.match /\//
  300. return callback? 'Document already exists' if docs[docName]
  301. type = types[type] if typeof type == 'string'
  302. return callback? 'Type not found' unless type
  303. data =
  304. snapshot:type.create()
  305. type:type.name
  306. meta:meta or {}
  307. v:0
  308. done = (error, dbMeta) ->
  309. # dbMeta can be used to cache extra state needed by the database to access the document, like an ID or something.
  310. return callback? error if error
  311. # From here on we'll store the object version of the type name.
  312. data.type = type
  313. add docName, null, data, 0, [], dbMeta
  314. model.emit 'create', docName, data
  315. callback?()
  316. if db
  317. db.create docName, data, done
  318. else
  319. done()
  320. # Perminantly deletes the specified document.
  321. # If listeners are attached, they are removed.
  322. #
  323. # The callback is called with (error) if there was an error. If error is null / undefined, the
  324. # document was deleted.
  325. #
  326. # WARNING: This isn't well supported throughout the code. (Eg, streaming clients aren't told about the
  327. # deletion. Subsequent op submissions will fail).
  328. @delete = (docName, callback) ->
  329. doc = docs[docName]
  330. if doc
  331. clearTimeout doc.reapTimer
  332. delete docs[docName]
  333. done = (error) ->
  334. model.emit 'delete', docName unless error
  335. callback? error
  336. if db
  337. db.delete docName, doc?.dbMeta, done
  338. else
  339. done (if !doc then 'Document does not exist')
  340. # This gets all operations from [start...end]. (That is, its not inclusive.)
  341. #
  342. # end can be null. This means 'get me all ops from start'.
  343. #
  344. # Each op returned is in the form {op:o, meta:m, v:version}.
  345. #
  346. # Callback is called with (error, [ops])
  347. #
  348. # If the document does not exist, getOps doesn't necessarily return an error. This is because
  349. # its awkward to figure out whether or not the document exists for things
  350. # like the redis database backend. I guess its a bit gross having this inconsistant
  351. # with the other DB calls, but its certainly convenient.
  352. #
  353. # Use getVersion() to determine if a document actually exists, if thats what you're
  354. # after.
  355. @getOps = getOps = (docName, start, end, callback) ->
  356. # getOps will only use the op cache if its there. It won't fill the op cache in.
  357. throw new Error 'start must be 0+' unless start >= 0
  358. [end, callback] = [null, end] if typeof end is 'function'
  359. ops = docs[docName]?.ops
  360. if ops
  361. version = docs[docName].v
  362. # Ops contains an array of ops. The last op in the list is the last op applied
  363. end ?= version
  364. start = Math.min start, end
  365. return callback null, [] if start == end
  366. # Base is the version number of the oldest op we have cached
  367. base = version - ops.length
  368. # If the database is null, we'll trim to the ops we do have and hope thats enough.
  369. if start >= base or db is null
  370. refreshReapingTimeout docName
  371. options.stats?.cacheHit 'getOps'
  372. return callback null, ops[(start - base)...(end - base)]
  373. options.stats?.cacheMiss 'getOps'
  374. getOpsInternal docName, start, end, callback
  375. # Gets the snapshot data for the specified document.
  376. # getSnapshot(docName, callback)
  377. # Callback is called with (error, {v: <version>, type: <type>, snapshot: <snapshot>, meta: <meta>})
  378. @getSnapshot = (docName, callback) ->
  379. load docName, (error, doc) ->
  380. callback error, if doc then {v:doc.v, type:doc.type, snapshot:doc.snapshot, meta:doc.meta}
  381. # Gets the latest version # of the document.
  382. # getVersion(docName, callback)
  383. # callback is called with (error, version).
  384. @getVersion = (docName, callback) ->
  385. load docName, (error, doc) -> callback error, doc?.v
  386. # Apply an op to the specified document.
  387. # The callback is passed (error, applied version #)
  388. # opData = {op:op, v:v, meta:metadata}
  389. #
  390. # Ops are queued before being applied so that the following code applies op C before op B:
  391. # model.applyOp 'doc', OPA, -> model.applyOp 'doc', OPB
  392. # model.applyOp 'doc', OPC
  393. @applyOp = (docName, opData, callback) ->
  394. # All the logic for this is in makeOpQueue, above.
  395. load docName, (error, doc) ->
  396. return callback error if error
  397. process.nextTick -> doc.opQueue opData, (error, newVersion) ->
  398. refreshReapingTimeout docName
  399. callback? error, newVersion
  400. # TODO: store (some) metadata in DB
  401. # TODO: op and meta should be combineable in the op that gets sent
  402. @applyMetaOp = (docName, metaOpData, callback) ->
  403. {path, value} = metaOpData.meta
  404. return callback? "path should be an array" unless isArray path
  405. load docName, (error, doc) ->
  406. if error?
  407. callback? error
  408. else
  409. applied = false
  410. switch path[0]
  411. when 'shout'
  412. doc.eventEmitter.emit 'op', metaOpData
  413. applied = true
  414. model.emit 'applyMetaOp', docName, path, value if applied
  415. callback? null, doc.v
  416. # Listen to all ops from the specified version. If version is in the past, all
  417. # ops since that version are sent immediately to the listener.
  418. #
  419. # The callback is called once the listener is attached, but before any ops have been passed
  420. # to the listener.
  421. #
  422. # This will _not_ edit the document metadata.
  423. #
  424. # If there are any listeners, we don't purge the document from the cache. But be aware, this behaviour
  425. # might change in a future version.
  426. #
  427. # version is the document version at which the document is opened. It can be left out if you want to open
  428. # the document at the most recent version.
  429. #
  430. # listener is called with (opData) each time an op is applied.
  431. #
  432. # callback(error, openedVersion)
  433. @listen = (docName, version, listener, callback) ->
  434. [version, listener, callback] = [null, version, listener] if typeof version is 'function'
  435. load docName, (error, doc) ->
  436. return callback? error if error
  437. clearTimeout doc.reapTimer
  438. if version?
  439. getOps docName, version, null, (error, data) ->
  440. return callback? error if error
  441. doc.eventEmitter.on 'op', listener
  442. callback? null, version
  443. for op in data
  444. listener op
  445. # The listener may well remove itself during the catchup phase. If this happens, break early.
  446. # This is done in a quite inefficient way. (O(n) where n = #listeners on doc)
  447. break unless listener in doc.eventEmitter.listeners 'op'
  448. else # Version is null / undefined. Just add the listener.
  449. doc.eventEmitter.on 'op', listener
  450. callback? null, doc.v
  451. # Remove a listener for a particular document.
  452. #
  453. # removeListener(docName, listener)
  454. #
  455. # This is synchronous.
  456. @removeListener = (docName, listener) ->
  457. # The document should already be loaded.
  458. doc = docs[docName]
  459. throw new Error 'removeListener called but document not loaded' unless doc
  460. doc.eventEmitter.removeListener 'op', listener
  461. refreshReapingTimeout docName
  462. # Flush saves all snapshot data to the database. I'm not sure whether or not this is actually needed -
  463. # sharejs will happily replay uncommitted ops when documents are re-opened anyway.
  464. @flush = (callback) ->
  465. return callback?() unless db
  466. pendingWrites = 0
  467. for docName, doc of docs
  468. if doc.committedVersion < doc.v
  469. pendingWrites++
  470. # I'm hoping writeSnapshot will always happen in another thread.
  471. tryWriteSnapshot docName, ->
  472. process.nextTick ->
  473. pendingWrites--
  474. callback?() if pendingWrites is 0
  475. # If nothing was queued, terminate immediately.
  476. callback?() if pendingWrites is 0
  477. # Close the database connection. This is needed so nodejs can shut down cleanly.
  478. @closeDb = ->
  479. db?.close?()
  480. db = null
  481. return
  482. # Model inherits from EventEmitter.
  483. Model:: = new EventEmitter