model.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  1. /* eslint-disable
  2. no-console,
  3. no-return-assign,
  4. */
  5. // TODO: This file was created by bulk-decaffeinate.
  6. // Fix any style issues and re-enable lint.
  7. /*
  8. * decaffeinate suggestions:
  9. * DS101: Remove unnecessary use of Array.from
  10. * DS102: Remove unnecessary code created because of implicit returns
  11. * DS103: Rewrite code to no longer use __guard__
  12. * DS104: Avoid inline assignments
  13. * DS204: Change includes calls to have a more natural evaluation order
  14. * DS205: Consider reworking code to avoid use of IIFEs
  15. * DS207: Consider shorter variations of null checks
  16. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  17. */
  18. // The model of all the ops. Responsible for applying & transforming remote deltas
  19. // and managing the storage layer.
  20. //
  21. // Actual storage is handled by the database wrappers in db/*, wrapped by DocCache
  22. let Model
  23. const { EventEmitter } = require('events')
  24. const queue = require('./syncqueue')
  25. const types = require('../types')
  26. const Profiler = require('../../Profiler')
  27. const isArray = o => Object.prototype.toString.call(o) === '[object Array]'
  28. // This constructor creates a new Model object. There will be one model object
  29. // per server context.
  30. //
  31. // The model object is responsible for a lot of things:
  32. //
  33. // - It manages the interactions with the database
  34. // - It maintains (in memory) a set of all active documents
  35. // - It calls out to the OT functions when necessary
  36. //
  37. // The model is an event emitter. It emits the following events:
  38. //
  39. // create(docName, data): A document has been created with the specified name & data
  40. module.exports = Model = function (db, options) {
  41. // db can be null if the user doesn't want persistance.
  42. let getOps
  43. if (!(this instanceof Model)) {
  44. return new Model(db, options)
  45. }
  46. const model = this
  47. if (options == null) {
  48. options = {}
  49. }
  50. // This is a cache of 'live' documents.
  51. //
  52. // The cache is a map from docName -> {
  53. // ops:[{op, meta}]
  54. // snapshot
  55. // type
  56. // v
  57. // meta
  58. // eventEmitter
  59. // reapTimer
  60. // committedVersion: v
  61. // snapshotWriteLock: bool to make sure writeSnapshot isn't re-entrant
  62. // dbMeta: database specific data
  63. // opQueue: syncQueue for processing ops
  64. // }
  65. //
  66. // The ops list contains the document's last options.numCachedOps ops. (Or all
  67. // of them if we're using a memory store).
  68. //
  69. // Documents are stored in this set so long as the document has been accessed in
  70. // the last few seconds (options.reapTime) OR at least one client has the document
  71. // open. I don't know if I should keep open (but not being edited) documents live -
  72. // maybe if a client has a document open but the document isn't being edited, I should
  73. // flush it from the cache.
  74. //
  75. // In any case, the API to model is designed such that if we want to change that later
  76. // it should be pretty easy to do so without any external-to-the-model code changes.
  77. const docs = {}
  78. // This is a map from docName -> [callback]. It is used when a document hasn't been
  79. // cached and multiple getSnapshot() / getVersion() requests come in. All requests
  80. // are added to the callback list and called when db.getSnapshot() returns.
  81. //
  82. // callback(error, snapshot data)
  83. const awaitingGetSnapshot = {}
  84. // The time that documents which no clients have open will stay in the cache.
  85. // Should be > 0.
  86. if (options.reapTime == null) {
  87. options.reapTime = 3000
  88. }
  89. // The number of operations the cache holds before reusing the space
  90. if (options.numCachedOps == null) {
  91. options.numCachedOps = 10
  92. }
  93. // This option forces documents to be reaped, even when there's no database backend.
  94. // This is useful when you don't care about persistance and don't want to gradually
  95. // fill memory.
  96. //
  97. // You might want to set reapTime to a day or something.
  98. if (options.forceReaping == null) {
  99. options.forceReaping = false
  100. }
  101. // Until I come up with a better strategy, we'll save a copy of the document snapshot
  102. // to the database every ~20 submitted ops.
  103. if (options.opsBeforeCommit == null) {
  104. options.opsBeforeCommit = 20
  105. }
  106. // It takes some processing time to transform client ops. The server will punt ops back to the
  107. // client to transform if they're too old.
  108. if (options.maximumAge == null) {
  109. options.maximumAge = 40
  110. }
  111. // **** Cache API methods
  112. // Its important that all ops are applied in order. This helper method creates the op submission queue
  113. // for a single document. This contains the logic for transforming & applying ops.
  114. const makeOpQueue = (docName, doc) =>
  115. queue(function (opData, callback) {
  116. if (!(opData.v >= 0)) {
  117. return callback('Version missing')
  118. }
  119. if (opData.v > doc.v) {
  120. return callback('Op at future version')
  121. }
  122. // Punt the transforming work back to the client if the op is too old.
  123. if (opData.v + options.maximumAge < doc.v) {
  124. return callback('Op too old')
  125. }
  126. if (!opData.meta) {
  127. opData.meta = {}
  128. }
  129. opData.meta.ts = Date.now()
  130. // We'll need to transform the op to the current version of the document. This
  131. // calls the callback immediately if opVersion == doc.v.
  132. return getOps(docName, opData.v, doc.v, function (error, ops) {
  133. let snapshot
  134. if (error) {
  135. return callback(error)
  136. }
  137. if (doc.v - opData.v !== ops.length) {
  138. // This should never happen. It indicates that we didn't get all the ops we
  139. // asked for. Its important that the submitted op is correctly transformed.
  140. console.error(
  141. `Could not get old ops in model for document ${docName}`
  142. )
  143. console.error(
  144. `Expected ops ${opData.v} to ${doc.v} and got ${ops.length} ops`
  145. )
  146. return callback('Internal error')
  147. }
  148. if (ops.length > 0) {
  149. try {
  150. const profile = new Profiler('model.transform')
  151. // If there's enough ops, it might be worth spinning this out into a webworker thread.
  152. for (const oldOp of Array.from(ops)) {
  153. // Dup detection works by sending the id(s) the op has been submitted with previously.
  154. // If the id matches, we reject it. The client can also detect the op has been submitted
  155. // already if it sees its own previous id in the ops it sees when it does catchup.
  156. if (
  157. oldOp.meta.source &&
  158. opData.dupIfSource &&
  159. Array.from(opData.dupIfSource).includes(oldOp.meta.source)
  160. ) {
  161. return callback('Op already submitted')
  162. }
  163. opData.op = doc.type.transform(opData.op, oldOp.op, 'left')
  164. opData.v++
  165. }
  166. profile.log('transform', { sync: true }).end()
  167. } catch (error1) {
  168. error = error1
  169. return callback(error.message)
  170. }
  171. }
  172. try {
  173. const profile = new Profiler('model.apply')
  174. snapshot = doc.type.apply(doc.snapshot, opData.op)
  175. profile.log('model.apply', { sync: true }).end()
  176. } catch (error2) {
  177. error = error2
  178. return callback(error.message)
  179. }
  180. if (
  181. options.maxDocLength != null &&
  182. doc.snapshot.length > options.maxDocLength
  183. ) {
  184. return callback('Update takes doc over max doc size')
  185. }
  186. // The op data should be at the current version, and the new document data should be at
  187. // the next version.
  188. //
  189. // This should never happen in practice, but its a nice little check to make sure everything
  190. // is hunky-dory.
  191. if (opData.v !== doc.v) {
  192. // This should never happen.
  193. console.error(
  194. 'Version mismatch detected in model. File a ticket - this is a bug.'
  195. )
  196. console.error(`Expecting ${opData.v} == ${doc.v}`)
  197. return callback('Internal error')
  198. }
  199. // newDocData = {snapshot, type:type.name, v:opVersion + 1, meta:docData.meta}
  200. const writeOp =
  201. (db != null ? db.writeOp : undefined) ||
  202. ((docName, newOpData, callback) => callback())
  203. return writeOp(docName, opData, function (error) {
  204. if (error) {
  205. // The user should probably know about this.
  206. console.warn(`Error writing ops to database: ${error}`)
  207. return callback(error)
  208. }
  209. __guardMethod__(options.stats, 'writeOp', o => o.writeOp())
  210. // This is needed when we emit the 'change' event, below.
  211. const oldSnapshot = doc.snapshot
  212. // All the heavy lifting is now done. Finally, we'll update the cache with the new data
  213. // and (maybe!) save a new document snapshot to the database.
  214. doc.v = opData.v + 1
  215. doc.snapshot = snapshot
  216. doc.ops.push(opData)
  217. if (db && doc.ops.length > options.numCachedOps) {
  218. doc.ops.shift()
  219. }
  220. model.emit('applyOp', docName, opData, snapshot, oldSnapshot)
  221. doc.eventEmitter.emit('op', opData, snapshot, oldSnapshot)
  222. // The callback is called with the version of the document at which the op was applied.
  223. // This is the op.v after transformation, and its doc.v - 1.
  224. callback(null, opData.v)
  225. // I need a decent strategy here for deciding whether or not to save the snapshot.
  226. //
  227. // The 'right' strategy looks something like "Store the snapshot whenever the snapshot
  228. // is smaller than the accumulated op data". For now, I'll just store it every 20
  229. // ops or something. (Configurable with doc.committedVersion)
  230. if (
  231. !doc.snapshotWriteLock &&
  232. doc.committedVersion + options.opsBeforeCommit <= doc.v
  233. ) {
  234. return tryWriteSnapshot(docName, function (error) {
  235. if (error) {
  236. return console.warn(
  237. `Error writing snapshot ${error}. This is nonfatal`
  238. )
  239. }
  240. })
  241. }
  242. })
  243. })
  244. })
  245. // Add the data for the given docName to the cache. The named document shouldn't already
  246. // exist in the doc set.
  247. //
  248. // Returns the new doc.
  249. const add = function (docName, error, data, committedVersion, ops, dbMeta) {
  250. let callback, doc
  251. const callbacks = awaitingGetSnapshot[docName]
  252. delete awaitingGetSnapshot[docName]
  253. if (error) {
  254. if (callbacks) {
  255. for (callback of Array.from(callbacks)) {
  256. callback(error)
  257. }
  258. }
  259. } else {
  260. doc = docs[docName] = {
  261. snapshot: data.snapshot,
  262. v: data.v,
  263. type: data.type,
  264. meta: data.meta,
  265. // Cache of ops
  266. ops: ops || [],
  267. eventEmitter: new EventEmitter(),
  268. // Timer before the document will be invalidated from the cache (if the document has no
  269. // listeners)
  270. reapTimer: null,
  271. // Version of the snapshot thats in the database
  272. committedVersion: committedVersion != null ? committedVersion : data.v,
  273. snapshotWriteLock: false,
  274. dbMeta,
  275. }
  276. doc.opQueue = makeOpQueue(docName, doc)
  277. refreshReapingTimeout(docName)
  278. model.emit('add', docName, data)
  279. if (callbacks) {
  280. for (callback of Array.from(callbacks)) {
  281. callback(null, doc)
  282. }
  283. }
  284. }
  285. return doc
  286. }
  287. // This is a little helper wrapper around db.getOps. It does two things:
  288. //
  289. // - If there's no database set, it returns an error to the callback
  290. // - It adds version numbers to each op returned from the database
  291. // (These can be inferred from context so the DB doesn't store them, but its useful to have them).
  292. const getOpsInternal = function (docName, start, end, callback) {
  293. if (!db) {
  294. return typeof callback === 'function'
  295. ? callback('Document does not exist')
  296. : undefined
  297. }
  298. return db.getOps(docName, start, end, function (error, ops) {
  299. if (error) {
  300. return typeof callback === 'function' ? callback(error) : undefined
  301. }
  302. let v = start
  303. for (const op of Array.from(ops)) {
  304. op.v = v++
  305. }
  306. return typeof callback === 'function' ? callback(null, ops) : undefined
  307. })
  308. }
  309. // Load the named document into the cache. This function is re-entrant.
  310. //
  311. // The callback is called with (error, doc)
  312. const load = function (docName, callback) {
  313. if (docs[docName]) {
  314. // The document is already loaded. Return immediately.
  315. __guardMethod__(options.stats, 'cacheHit', o => o.cacheHit('getSnapshot'))
  316. return callback(null, docs[docName])
  317. }
  318. // We're a memory store. If we don't have it, nobody does.
  319. if (!db) {
  320. return callback('Document does not exist')
  321. }
  322. const callbacks = awaitingGetSnapshot[docName]
  323. // The document is being loaded already. Add ourselves as a callback.
  324. if (callbacks) {
  325. return callbacks.push(callback)
  326. }
  327. __guardMethod__(options.stats, 'cacheMiss', o1 =>
  328. o1.cacheMiss('getSnapshot')
  329. )
  330. // The document isn't loaded and isn't being loaded. Load it.
  331. awaitingGetSnapshot[docName] = [callback]
  332. return db.getSnapshot(docName, function (error, data, dbMeta) {
  333. if (error) {
  334. return add(docName, error)
  335. }
  336. const type = types[data.type]
  337. if (!type) {
  338. console.warn(`Type '${data.type}' missing`)
  339. return callback('Type not found')
  340. }
  341. data.type = type
  342. const committedVersion = data.v
  343. // The server can close without saving the most recent document snapshot.
  344. // In this case, there are extra ops which need to be applied before
  345. // returning the snapshot.
  346. return getOpsInternal(docName, data.v, null, function (error, ops) {
  347. if (error) {
  348. return callback(error)
  349. }
  350. if (ops.length > 0) {
  351. console.log(`Catchup ${docName} ${data.v} -> ${data.v + ops.length}`)
  352. try {
  353. for (const op of Array.from(ops)) {
  354. data.snapshot = type.apply(data.snapshot, op.op)
  355. data.v++
  356. }
  357. } catch (e) {
  358. // This should never happen - it indicates that whats in the
  359. // database is invalid.
  360. console.error(`Op data invalid for ${docName}: ${e.stack}`)
  361. return callback('Op data invalid')
  362. }
  363. }
  364. model.emit('load', docName, data)
  365. return add(docName, error, data, committedVersion, ops, dbMeta)
  366. })
  367. })
  368. }
  369. // This makes sure the cache contains a document. If the doc cache doesn't contain
  370. // a document, it is loaded from the database and stored.
  371. //
  372. // Documents are stored so long as either:
  373. // - They have been accessed within the past #{PERIOD}
  374. // - At least one client has the document open
  375. var refreshReapingTimeout = function (docName) {
  376. const doc = docs[docName]
  377. if (!doc) {
  378. return
  379. }
  380. // I want to let the clients list be updated before this is called.
  381. return process.nextTick(function () {
  382. // This is an awkward way to find out the number of clients on a document. If this
  383. // causes performance issues, add a numClients field to the document.
  384. //
  385. // The first check is because its possible that between refreshReapingTimeout being called and this
  386. // event being fired, someone called delete() on the document and hence the doc is something else now.
  387. if (
  388. doc === docs[docName] &&
  389. doc.eventEmitter.listeners('op').length === 0 &&
  390. (db || options.forceReaping) &&
  391. doc.opQueue.busy === false
  392. ) {
  393. let reapTimer
  394. clearTimeout(doc.reapTimer)
  395. return (doc.reapTimer = reapTimer =
  396. setTimeout(
  397. () =>
  398. tryWriteSnapshot(docName, function () {
  399. // If the reaping timeout has been refreshed while we're writing the snapshot, or if we're
  400. // in the middle of applying an operation, don't reap.
  401. if (
  402. docs[docName].reapTimer === reapTimer &&
  403. doc.opQueue.busy === false
  404. ) {
  405. return delete docs[docName]
  406. }
  407. }),
  408. options.reapTime
  409. ))
  410. }
  411. })
  412. }
  413. var tryWriteSnapshot = function (docName, callback) {
  414. if (!db) {
  415. return typeof callback === 'function' ? callback() : undefined
  416. }
  417. const doc = docs[docName]
  418. // The doc is closed
  419. if (!doc) {
  420. return typeof callback === 'function' ? callback() : undefined
  421. }
  422. // The document is already saved.
  423. if (doc.committedVersion === doc.v) {
  424. return typeof callback === 'function' ? callback() : undefined
  425. }
  426. if (doc.snapshotWriteLock) {
  427. return typeof callback === 'function'
  428. ? callback('Another snapshot write is in progress')
  429. : undefined
  430. }
  431. doc.snapshotWriteLock = true
  432. __guardMethod__(options.stats, 'writeSnapshot', o => o.writeSnapshot())
  433. const writeSnapshot =
  434. (db != null ? db.writeSnapshot : undefined) ||
  435. ((docName, docData, dbMeta, callback) => callback())
  436. const data = {
  437. v: doc.v,
  438. meta: doc.meta,
  439. snapshot: doc.snapshot,
  440. // The database doesn't know about object types.
  441. type: doc.type.name,
  442. }
  443. // Commit snapshot.
  444. return writeSnapshot(docName, data, doc.dbMeta, function (error, dbMeta) {
  445. doc.snapshotWriteLock = false
  446. // We have to use data.v here because the version in the doc could
  447. // have been updated between the call to writeSnapshot() and now.
  448. doc.committedVersion = data.v
  449. doc.dbMeta = dbMeta
  450. return typeof callback === 'function' ? callback(error) : undefined
  451. })
  452. }
  453. // *** Model interface methods
  454. // Create a new document.
  455. //
  456. // data should be {snapshot, type, [meta]}. The version of a new document is 0.
  457. this.create = function (docName, type, meta, callback) {
  458. if (typeof meta === 'function') {
  459. ;[meta, callback] = Array.from([{}, meta])
  460. }
  461. if (docName.match(/\//)) {
  462. return typeof callback === 'function'
  463. ? callback('Invalid document name')
  464. : undefined
  465. }
  466. if (docs[docName]) {
  467. return typeof callback === 'function'
  468. ? callback('Document already exists')
  469. : undefined
  470. }
  471. if (typeof type === 'string') {
  472. type = types[type]
  473. }
  474. if (!type) {
  475. return typeof callback === 'function'
  476. ? callback('Type not found')
  477. : undefined
  478. }
  479. const data = {
  480. snapshot: type.create(),
  481. type: type.name,
  482. meta: meta || {},
  483. v: 0,
  484. }
  485. const done = function (error, dbMeta) {
  486. // dbMeta can be used to cache extra state needed by the database to access the document, like an ID or something.
  487. if (error) {
  488. return typeof callback === 'function' ? callback(error) : undefined
  489. }
  490. // From here on we'll store the object version of the type name.
  491. data.type = type
  492. add(docName, null, data, 0, [], dbMeta)
  493. model.emit('create', docName, data)
  494. return typeof callback === 'function' ? callback() : undefined
  495. }
  496. if (db) {
  497. return db.create(docName, data, done)
  498. } else {
  499. return done()
  500. }
  501. }
  502. // Perminantly deletes the specified document.
  503. // If listeners are attached, they are removed.
  504. //
  505. // The callback is called with (error) if there was an error. If error is null / undefined, the
  506. // document was deleted.
  507. //
  508. // WARNING: This isn't well supported throughout the code. (Eg, streaming clients aren't told about the
  509. // deletion. Subsequent op submissions will fail).
  510. this.delete = function (docName, callback) {
  511. const doc = docs[docName]
  512. if (doc) {
  513. clearTimeout(doc.reapTimer)
  514. delete docs[docName]
  515. }
  516. const done = function (error) {
  517. if (!error) {
  518. model.emit('delete', docName)
  519. }
  520. return typeof callback === 'function' ? callback(error) : undefined
  521. }
  522. if (db) {
  523. return db.delete(docName, doc != null ? doc.dbMeta : undefined, done)
  524. } else {
  525. return done(!doc ? 'Document does not exist' : undefined)
  526. }
  527. }
  528. // This gets all operations from [start...end]. (That is, its not inclusive.)
  529. //
  530. // end can be null. This means 'get me all ops from start'.
  531. //
  532. // Each op returned is in the form {op:o, meta:m, v:version}.
  533. //
  534. // Callback is called with (error, [ops])
  535. //
  536. // If the document does not exist, getOps doesn't necessarily return an error. This is because
  537. // its awkward to figure out whether or not the document exists for things
  538. // like the redis database backend. I guess its a bit gross having this inconsistant
  539. // with the other DB calls, but its certainly convenient.
  540. //
  541. // Use getVersion() to determine if a document actually exists, if thats what you're
  542. // after.
  543. this.getOps = getOps = function (docName, start, end, callback) {
  544. // getOps will only use the op cache if its there. It won't fill the op cache in.
  545. if (!(start >= 0)) {
  546. throw new Error('start must be 0+')
  547. }
  548. if (typeof end === 'function') {
  549. ;[end, callback] = Array.from([null, end])
  550. }
  551. const ops = docs[docName] != null ? docs[docName].ops : undefined
  552. if (ops) {
  553. const version = docs[docName].v
  554. // Ops contains an array of ops. The last op in the list is the last op applied
  555. if (end == null) {
  556. end = version
  557. }
  558. start = Math.min(start, end)
  559. if (start === end) {
  560. return callback(null, [])
  561. }
  562. // Base is the version number of the oldest op we have cached
  563. const base = version - ops.length
  564. // If the database is null, we'll trim to the ops we do have and hope thats enough.
  565. if (start >= base || db === null) {
  566. refreshReapingTimeout(docName)
  567. if (options.stats != null) {
  568. options.stats.cacheHit('getOps')
  569. }
  570. return callback(null, ops.slice(start - base, end - base))
  571. }
  572. }
  573. if (options.stats != null) {
  574. options.stats.cacheMiss('getOps')
  575. }
  576. return getOpsInternal(docName, start, end, callback)
  577. }
  578. // Gets the snapshot data for the specified document.
  579. // getSnapshot(docName, callback)
  580. // Callback is called with (error, {v: <version>, type: <type>, snapshot: <snapshot>, meta: <meta>})
  581. this.getSnapshot = (docName, callback) =>
  582. load(docName, (error, doc) =>
  583. callback(
  584. error,
  585. doc
  586. ? { v: doc.v, type: doc.type, snapshot: doc.snapshot, meta: doc.meta }
  587. : undefined
  588. )
  589. )
  590. // Gets the latest version # of the document.
  591. // getVersion(docName, callback)
  592. // callback is called with (error, version).
  593. this.getVersion = (docName, callback) =>
  594. load(docName, (error, doc) =>
  595. callback(error, doc != null ? doc.v : undefined)
  596. )
  597. // Apply an op to the specified document.
  598. // The callback is passed (error, applied version #)
  599. // opData = {op:op, v:v, meta:metadata}
  600. //
  601. // Ops are queued before being applied so that the following code applies op C before op B:
  602. // model.applyOp 'doc', OPA, -> model.applyOp 'doc', OPB
  603. // model.applyOp 'doc', OPC
  604. this.applyOp = (
  605. docName,
  606. opData,
  607. callback // All the logic for this is in makeOpQueue, above.
  608. ) =>
  609. load(docName, function (error, doc) {
  610. if (error) {
  611. return callback(error)
  612. }
  613. return process.nextTick(() =>
  614. doc.opQueue(opData, function (error, newVersion) {
  615. refreshReapingTimeout(docName)
  616. return typeof callback === 'function'
  617. ? callback(error, newVersion)
  618. : undefined
  619. })
  620. )
  621. })
  622. // TODO: store (some) metadata in DB
  623. // TODO: op and meta should be combineable in the op that gets sent
  624. this.applyMetaOp = function (docName, metaOpData, callback) {
  625. const { path, value } = metaOpData.meta
  626. if (!isArray(path)) {
  627. return typeof callback === 'function'
  628. ? callback('path should be an array')
  629. : undefined
  630. }
  631. return load(docName, function (error, doc) {
  632. if (error != null) {
  633. return typeof callback === 'function' ? callback(error) : undefined
  634. } else {
  635. let applied = false
  636. switch (path[0]) {
  637. case 'shout':
  638. doc.eventEmitter.emit('op', metaOpData)
  639. applied = true
  640. break
  641. }
  642. if (applied) {
  643. model.emit('applyMetaOp', docName, path, value)
  644. }
  645. return typeof callback === 'function'
  646. ? callback(null, doc.v)
  647. : undefined
  648. }
  649. })
  650. }
  651. // Listen to all ops from the specified version. If version is in the past, all
  652. // ops since that version are sent immediately to the listener.
  653. //
  654. // The callback is called once the listener is attached, but before any ops have been passed
  655. // to the listener.
  656. //
  657. // This will _not_ edit the document metadata.
  658. //
  659. // If there are any listeners, we don't purge the document from the cache. But be aware, this behaviour
  660. // might change in a future version.
  661. //
  662. // version is the document version at which the document is opened. It can be left out if you want to open
  663. // the document at the most recent version.
  664. //
  665. // listener is called with (opData) each time an op is applied.
  666. //
  667. // callback(error, openedVersion)
  668. this.listen = function (docName, version, listener, callback) {
  669. if (typeof version === 'function') {
  670. ;[version, listener, callback] = Array.from([null, version, listener])
  671. }
  672. return load(docName, function (error, doc) {
  673. if (error) {
  674. return typeof callback === 'function' ? callback(error) : undefined
  675. }
  676. clearTimeout(doc.reapTimer)
  677. if (version != null) {
  678. return getOps(docName, version, null, function (error, data) {
  679. if (error) {
  680. return typeof callback === 'function' ? callback(error) : undefined
  681. }
  682. doc.eventEmitter.on('op', listener)
  683. if (typeof callback === 'function') {
  684. callback(null, version)
  685. }
  686. return (() => {
  687. const result = []
  688. for (const op of Array.from(data)) {
  689. var needle
  690. listener(op)
  691. // The listener may well remove itself during the catchup phase. If this happens, break early.
  692. // This is done in a quite inefficient way. (O(n) where n = #listeners on doc)
  693. if (
  694. ((needle = listener),
  695. !Array.from(doc.eventEmitter.listeners('op')).includes(needle))
  696. ) {
  697. break
  698. } else {
  699. result.push(undefined)
  700. }
  701. }
  702. return result
  703. })()
  704. })
  705. } else {
  706. // Version is null / undefined. Just add the listener.
  707. doc.eventEmitter.on('op', listener)
  708. return typeof callback === 'function'
  709. ? callback(null, doc.v)
  710. : undefined
  711. }
  712. })
  713. }
  714. // Remove a listener for a particular document.
  715. //
  716. // removeListener(docName, listener)
  717. //
  718. // This is synchronous.
  719. this.removeListener = function (docName, listener) {
  720. // The document should already be loaded.
  721. const doc = docs[docName]
  722. if (!doc) {
  723. throw new Error('removeListener called but document not loaded')
  724. }
  725. doc.eventEmitter.removeListener('op', listener)
  726. return refreshReapingTimeout(docName)
  727. }
  728. // Flush saves all snapshot data to the database. I'm not sure whether or not this is actually needed -
  729. // sharejs will happily replay uncommitted ops when documents are re-opened anyway.
  730. this.flush = function (callback) {
  731. if (!db) {
  732. return typeof callback === 'function' ? callback() : undefined
  733. }
  734. let pendingWrites = 0
  735. for (const docName in docs) {
  736. const doc = docs[docName]
  737. if (doc.committedVersion < doc.v) {
  738. pendingWrites++
  739. // I'm hoping writeSnapshot will always happen in another thread.
  740. tryWriteSnapshot(docName, () =>
  741. process.nextTick(function () {
  742. pendingWrites--
  743. if (pendingWrites === 0) {
  744. return typeof callback === 'function' ? callback() : undefined
  745. }
  746. })
  747. )
  748. }
  749. }
  750. // If nothing was queued, terminate immediately.
  751. if (pendingWrites === 0) {
  752. return typeof callback === 'function' ? callback() : undefined
  753. }
  754. }
  755. // Close the database connection. This is needed so nodejs can shut down cleanly.
  756. this.closeDb = function () {
  757. __guardMethod__(db, 'close', o => o.close())
  758. return (db = null)
  759. }
  760. }
  761. // Model inherits from EventEmitter.
  762. Model.prototype = new EventEmitter()
  763. function __guardMethod__(obj, methodName, transform) {
  764. if (
  765. typeof obj !== 'undefined' &&
  766. obj !== null &&
  767. typeof obj[methodName] === 'function'
  768. ) {
  769. return transform(obj, methodName)
  770. } else {
  771. return undefined
  772. }
  773. }