model.js 28 KB

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