model.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  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) =>
  308. o.cacheHit('getSnapshot')
  309. )
  310. return callback(null, docs[docName])
  311. }
  312. // We're a memory store. If we don't have it, nobody does.
  313. if (!db) {
  314. return callback('Document does not exist')
  315. }
  316. const callbacks = awaitingGetSnapshot[docName]
  317. // The document is being loaded already. Add ourselves as a callback.
  318. if (callbacks) {
  319. return callbacks.push(callback)
  320. }
  321. __guardMethod__(options.stats, 'cacheMiss', (o1) =>
  322. o1.cacheMiss('getSnapshot')
  323. )
  324. // The document isn't loaded and isn't being loaded. Load it.
  325. awaitingGetSnapshot[docName] = [callback]
  326. return db.getSnapshot(docName, function (error, data, dbMeta) {
  327. if (error) {
  328. return add(docName, error)
  329. }
  330. const type = types[data.type]
  331. if (!type) {
  332. console.warn(`Type '${data.type}' missing`)
  333. return callback('Type not found')
  334. }
  335. data.type = type
  336. const committedVersion = data.v
  337. // The server can close without saving the most recent document snapshot.
  338. // In this case, there are extra ops which need to be applied before
  339. // returning the snapshot.
  340. return getOpsInternal(docName, data.v, null, function (error, ops) {
  341. if (error) {
  342. return callback(error)
  343. }
  344. if (ops.length > 0) {
  345. console.log(`Catchup ${docName} ${data.v} -> ${data.v + ops.length}`)
  346. try {
  347. for (const op of Array.from(ops)) {
  348. data.snapshot = type.apply(data.snapshot, op.op)
  349. data.v++
  350. }
  351. } catch (e) {
  352. // This should never happen - it indicates that whats in the
  353. // database is invalid.
  354. console.error(`Op data invalid for ${docName}: ${e.stack}`)
  355. return callback('Op data invalid')
  356. }
  357. }
  358. model.emit('load', docName, data)
  359. return add(docName, error, data, committedVersion, ops, dbMeta)
  360. })
  361. })
  362. }
  363. // This makes sure the cache contains a document. If the doc cache doesn't contain
  364. // a document, it is loaded from the database and stored.
  365. //
  366. // Documents are stored so long as either:
  367. // - They have been accessed within the past #{PERIOD}
  368. // - At least one client has the document open
  369. var refreshReapingTimeout = function (docName) {
  370. const doc = docs[docName]
  371. if (!doc) {
  372. return
  373. }
  374. // I want to let the clients list be updated before this is called.
  375. return process.nextTick(function () {
  376. // This is an awkward way to find out the number of clients on a document. If this
  377. // causes performance issues, add a numClients field to the document.
  378. //
  379. // The first check is because its possible that between refreshReapingTimeout being called and this
  380. // event being fired, someone called delete() on the document and hence the doc is something else now.
  381. if (
  382. doc === docs[docName] &&
  383. doc.eventEmitter.listeners('op').length === 0 &&
  384. (db || options.forceReaping) &&
  385. doc.opQueue.busy === false
  386. ) {
  387. let reapTimer
  388. clearTimeout(doc.reapTimer)
  389. return (doc.reapTimer = reapTimer = setTimeout(
  390. () =>
  391. tryWriteSnapshot(docName, function () {
  392. // If the reaping timeout has been refreshed while we're writing the snapshot, or if we're
  393. // in the middle of applying an operation, don't reap.
  394. if (
  395. docs[docName].reapTimer === reapTimer &&
  396. doc.opQueue.busy === false
  397. ) {
  398. return delete docs[docName]
  399. }
  400. }),
  401. options.reapTime
  402. ))
  403. }
  404. })
  405. }
  406. var tryWriteSnapshot = function (docName, callback) {
  407. if (!db) {
  408. return typeof callback === 'function' ? callback() : undefined
  409. }
  410. const doc = docs[docName]
  411. // The doc is closed
  412. if (!doc) {
  413. return typeof callback === 'function' ? callback() : undefined
  414. }
  415. // The document is already saved.
  416. if (doc.committedVersion === doc.v) {
  417. return typeof callback === 'function' ? callback() : undefined
  418. }
  419. if (doc.snapshotWriteLock) {
  420. return typeof callback === 'function'
  421. ? callback('Another snapshot write is in progress')
  422. : undefined
  423. }
  424. doc.snapshotWriteLock = true
  425. __guardMethod__(options.stats, 'writeSnapshot', (o) => o.writeSnapshot())
  426. const writeSnapshot =
  427. (db != null ? db.writeSnapshot : undefined) ||
  428. ((docName, docData, dbMeta, callback) => callback())
  429. const data = {
  430. v: doc.v,
  431. meta: doc.meta,
  432. snapshot: doc.snapshot,
  433. // The database doesn't know about object types.
  434. type: doc.type.name
  435. }
  436. // Commit snapshot.
  437. return writeSnapshot(docName, data, doc.dbMeta, function (error, dbMeta) {
  438. doc.snapshotWriteLock = false
  439. // We have to use data.v here because the version in the doc could
  440. // have been updated between the call to writeSnapshot() and now.
  441. doc.committedVersion = data.v
  442. doc.dbMeta = dbMeta
  443. return typeof callback === 'function' ? callback(error) : undefined
  444. })
  445. }
  446. // *** Model interface methods
  447. // Create a new document.
  448. //
  449. // data should be {snapshot, type, [meta]}. The version of a new document is 0.
  450. this.create = function (docName, type, meta, callback) {
  451. if (typeof meta === 'function') {
  452. ;[meta, callback] = Array.from([{}, meta])
  453. }
  454. if (docName.match(/\//)) {
  455. return typeof callback === 'function'
  456. ? callback('Invalid document name')
  457. : undefined
  458. }
  459. if (docs[docName]) {
  460. return typeof callback === 'function'
  461. ? callback('Document already exists')
  462. : undefined
  463. }
  464. if (typeof type === 'string') {
  465. type = types[type]
  466. }
  467. if (!type) {
  468. return typeof callback === 'function'
  469. ? callback('Type not found')
  470. : undefined
  471. }
  472. const data = {
  473. snapshot: type.create(),
  474. type: type.name,
  475. meta: meta || {},
  476. v: 0
  477. }
  478. const done = function (error, dbMeta) {
  479. // dbMeta can be used to cache extra state needed by the database to access the document, like an ID or something.
  480. if (error) {
  481. return typeof callback === 'function' ? callback(error) : undefined
  482. }
  483. // From here on we'll store the object version of the type name.
  484. data.type = type
  485. add(docName, null, data, 0, [], dbMeta)
  486. model.emit('create', docName, data)
  487. return typeof callback === 'function' ? callback() : undefined
  488. }
  489. if (db) {
  490. return db.create(docName, data, done)
  491. } else {
  492. return done()
  493. }
  494. }
  495. // Perminantly deletes the specified document.
  496. // If listeners are attached, they are removed.
  497. //
  498. // The callback is called with (error) if there was an error. If error is null / undefined, the
  499. // document was deleted.
  500. //
  501. // WARNING: This isn't well supported throughout the code. (Eg, streaming clients aren't told about the
  502. // deletion. Subsequent op submissions will fail).
  503. this.delete = function (docName, callback) {
  504. const doc = docs[docName]
  505. if (doc) {
  506. clearTimeout(doc.reapTimer)
  507. delete docs[docName]
  508. }
  509. const done = function (error) {
  510. if (!error) {
  511. model.emit('delete', docName)
  512. }
  513. return typeof callback === 'function' ? callback(error) : undefined
  514. }
  515. if (db) {
  516. return db.delete(docName, doc != null ? doc.dbMeta : undefined, done)
  517. } else {
  518. return done(!doc ? 'Document does not exist' : undefined)
  519. }
  520. }
  521. // This gets all operations from [start...end]. (That is, its not inclusive.)
  522. //
  523. // end can be null. This means 'get me all ops from start'.
  524. //
  525. // Each op returned is in the form {op:o, meta:m, v:version}.
  526. //
  527. // Callback is called with (error, [ops])
  528. //
  529. // If the document does not exist, getOps doesn't necessarily return an error. This is because
  530. // its awkward to figure out whether or not the document exists for things
  531. // like the redis database backend. I guess its a bit gross having this inconsistant
  532. // with the other DB calls, but its certainly convenient.
  533. //
  534. // Use getVersion() to determine if a document actually exists, if thats what you're
  535. // after.
  536. this.getOps = getOps = function (docName, start, end, callback) {
  537. // getOps will only use the op cache if its there. It won't fill the op cache in.
  538. if (!(start >= 0)) {
  539. throw new Error('start must be 0+')
  540. }
  541. if (typeof end === 'function') {
  542. ;[end, callback] = Array.from([null, end])
  543. }
  544. const ops = docs[docName] != null ? docs[docName].ops : undefined
  545. if (ops) {
  546. const version = docs[docName].v
  547. // Ops contains an array of ops. The last op in the list is the last op applied
  548. if (end == null) {
  549. end = version
  550. }
  551. start = Math.min(start, end)
  552. if (start === end) {
  553. return callback(null, [])
  554. }
  555. // Base is the version number of the oldest op we have cached
  556. const base = version - ops.length
  557. // If the database is null, we'll trim to the ops we do have and hope thats enough.
  558. if (start >= base || db === null) {
  559. refreshReapingTimeout(docName)
  560. if (options.stats != null) {
  561. options.stats.cacheHit('getOps')
  562. }
  563. return callback(null, ops.slice(start - base, end - base))
  564. }
  565. }
  566. if (options.stats != null) {
  567. options.stats.cacheMiss('getOps')
  568. }
  569. return getOpsInternal(docName, start, end, callback)
  570. }
  571. // Gets the snapshot data for the specified document.
  572. // getSnapshot(docName, callback)
  573. // Callback is called with (error, {v: <version>, type: <type>, snapshot: <snapshot>, meta: <meta>})
  574. this.getSnapshot = (docName, callback) =>
  575. load(docName, (error, doc) =>
  576. callback(
  577. error,
  578. doc
  579. ? { v: doc.v, type: doc.type, snapshot: doc.snapshot, meta: doc.meta }
  580. : undefined
  581. )
  582. )
  583. // Gets the latest version # of the document.
  584. // getVersion(docName, callback)
  585. // callback is called with (error, version).
  586. this.getVersion = (docName, callback) =>
  587. load(docName, (error, doc) =>
  588. callback(error, doc != null ? doc.v : undefined)
  589. )
  590. // Apply an op to the specified document.
  591. // The callback is passed (error, applied version #)
  592. // opData = {op:op, v:v, meta:metadata}
  593. //
  594. // Ops are queued before being applied so that the following code applies op C before op B:
  595. // model.applyOp 'doc', OPA, -> model.applyOp 'doc', OPB
  596. // model.applyOp 'doc', OPC
  597. this.applyOp = (
  598. docName,
  599. opData,
  600. callback // All the logic for this is in makeOpQueue, above.
  601. ) =>
  602. load(docName, function (error, doc) {
  603. if (error) {
  604. return callback(error)
  605. }
  606. return process.nextTick(() =>
  607. doc.opQueue(opData, function (error, newVersion) {
  608. refreshReapingTimeout(docName)
  609. return typeof callback === 'function'
  610. ? callback(error, newVersion)
  611. : undefined
  612. })
  613. )
  614. })
  615. // TODO: store (some) metadata in DB
  616. // TODO: op and meta should be combineable in the op that gets sent
  617. this.applyMetaOp = function (docName, metaOpData, callback) {
  618. const { path, value } = metaOpData.meta
  619. if (!isArray(path)) {
  620. return typeof callback === 'function'
  621. ? callback('path should be an array')
  622. : undefined
  623. }
  624. return load(docName, function (error, doc) {
  625. if (error != null) {
  626. return typeof callback === 'function' ? callback(error) : undefined
  627. } else {
  628. let applied = false
  629. switch (path[0]) {
  630. case 'shout':
  631. doc.eventEmitter.emit('op', metaOpData)
  632. applied = true
  633. break
  634. }
  635. if (applied) {
  636. model.emit('applyMetaOp', docName, path, value)
  637. }
  638. return typeof callback === 'function'
  639. ? callback(null, doc.v)
  640. : undefined
  641. }
  642. })
  643. }
  644. // Listen to all ops from the specified version. If version is in the past, all
  645. // ops since that version are sent immediately to the listener.
  646. //
  647. // The callback is called once the listener is attached, but before any ops have been passed
  648. // to the listener.
  649. //
  650. // This will _not_ edit the document metadata.
  651. //
  652. // If there are any listeners, we don't purge the document from the cache. But be aware, this behaviour
  653. // might change in a future version.
  654. //
  655. // version is the document version at which the document is opened. It can be left out if you want to open
  656. // the document at the most recent version.
  657. //
  658. // listener is called with (opData) each time an op is applied.
  659. //
  660. // callback(error, openedVersion)
  661. this.listen = function (docName, version, listener, callback) {
  662. if (typeof version === 'function') {
  663. ;[version, listener, callback] = Array.from([null, version, listener])
  664. }
  665. return load(docName, function (error, doc) {
  666. if (error) {
  667. return typeof callback === 'function' ? callback(error) : undefined
  668. }
  669. clearTimeout(doc.reapTimer)
  670. if (version != null) {
  671. return getOps(docName, version, null, function (error, data) {
  672. if (error) {
  673. return typeof callback === 'function' ? callback(error) : undefined
  674. }
  675. doc.eventEmitter.on('op', listener)
  676. if (typeof callback === 'function') {
  677. callback(null, version)
  678. }
  679. return (() => {
  680. const result = []
  681. for (const op of Array.from(data)) {
  682. var needle
  683. listener(op)
  684. // The listener may well remove itself during the catchup phase. If this happens, break early.
  685. // This is done in a quite inefficient way. (O(n) where n = #listeners on doc)
  686. if (
  687. ((needle = listener),
  688. !Array.from(doc.eventEmitter.listeners('op')).includes(needle))
  689. ) {
  690. break
  691. } else {
  692. result.push(undefined)
  693. }
  694. }
  695. return result
  696. })()
  697. })
  698. } else {
  699. // Version is null / undefined. Just add the listener.
  700. doc.eventEmitter.on('op', listener)
  701. return typeof callback === 'function'
  702. ? callback(null, doc.v)
  703. : undefined
  704. }
  705. })
  706. }
  707. // Remove a listener for a particular document.
  708. //
  709. // removeListener(docName, listener)
  710. //
  711. // This is synchronous.
  712. this.removeListener = function (docName, listener) {
  713. // The document should already be loaded.
  714. const doc = docs[docName]
  715. if (!doc) {
  716. throw new Error('removeListener called but document not loaded')
  717. }
  718. doc.eventEmitter.removeListener('op', listener)
  719. return refreshReapingTimeout(docName)
  720. }
  721. // Flush saves all snapshot data to the database. I'm not sure whether or not this is actually needed -
  722. // sharejs will happily replay uncommitted ops when documents are re-opened anyway.
  723. this.flush = function (callback) {
  724. if (!db) {
  725. return typeof callback === 'function' ? callback() : undefined
  726. }
  727. let pendingWrites = 0
  728. for (const docName in docs) {
  729. const doc = docs[docName]
  730. if (doc.committedVersion < doc.v) {
  731. pendingWrites++
  732. // I'm hoping writeSnapshot will always happen in another thread.
  733. tryWriteSnapshot(docName, () =>
  734. process.nextTick(function () {
  735. pendingWrites--
  736. if (pendingWrites === 0) {
  737. return typeof callback === 'function' ? callback() : undefined
  738. }
  739. })
  740. )
  741. }
  742. }
  743. // If nothing was queued, terminate immediately.
  744. if (pendingWrites === 0) {
  745. return typeof callback === 'function' ? callback() : undefined
  746. }
  747. }
  748. // Close the database connection. This is needed so nodejs can shut down cleanly.
  749. this.closeDb = function () {
  750. __guardMethod__(db, 'close', (o) => o.close())
  751. return (db = null)
  752. }
  753. }
  754. // Model inherits from EventEmitter.
  755. Model.prototype = new EventEmitter()
  756. function __guardMethod__(obj, methodName, transform) {
  757. if (
  758. typeof obj !== 'undefined' &&
  759. obj !== null &&
  760. typeof obj[methodName] === 'function'
  761. ) {
  762. return transform(obj, methodName)
  763. } else {
  764. return undefined
  765. }
  766. }