model.js 28 KB

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