model.js 28 KB

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