model.js 28 KB

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