model.js 28 KB

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