RedisManager.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. /* eslint-disable
  2. camelcase,
  3. */
  4. // TODO: This file was created by bulk-decaffeinate.
  5. // Fix any style issues and re-enable lint.
  6. /*
  7. * decaffeinate suggestions:
  8. * DS101: Remove unnecessary use of Array.from
  9. * DS102: Remove unnecessary code created because of implicit returns
  10. * DS103: Rewrite code to no longer use __guard__
  11. * DS201: Simplify complex destructure assignments
  12. * DS207: Consider shorter variations of null checks
  13. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  14. */
  15. let RedisManager
  16. const Settings = require('@overleaf/settings')
  17. const rclient = require('@overleaf/redis-wrapper').createClient(
  18. Settings.redis.documentupdater
  19. )
  20. const logger = require('@overleaf/logger')
  21. const metrics = require('./Metrics')
  22. const Errors = require('./Errors')
  23. const crypto = require('crypto')
  24. const async = require('async')
  25. const ProjectHistoryRedisManager = require('./ProjectHistoryRedisManager')
  26. const { docIsTooLarge } = require('./Limits')
  27. // Sometimes Redis calls take an unexpectedly long time. We have to be
  28. // quick with Redis calls because we're holding a lock that expires
  29. // after 30 seconds. We can't let any errors in the rest of the stack
  30. // hold us up, and need to bail out quickly if there is a problem.
  31. const MAX_REDIS_REQUEST_LENGTH = 5000 // 5 seconds
  32. // Make times easy to read
  33. const minutes = 60 // seconds for Redis expire
  34. const logHashErrors =
  35. Settings.documentupdater != null
  36. ? Settings.documentupdater.logHashErrors
  37. : undefined
  38. const logHashReadErrors = logHashErrors != null ? logHashErrors.read : undefined
  39. const MEGABYTES = 1024 * 1024
  40. const MAX_RANGES_SIZE = 3 * MEGABYTES
  41. const keys = Settings.redis.documentupdater.key_schema
  42. const historyKeys = Settings.redis.history.key_schema // note: this is track changes, not project-history
  43. module.exports = RedisManager = {
  44. rclient,
  45. putDocInMemory(
  46. project_id,
  47. doc_id,
  48. docLines,
  49. version,
  50. ranges,
  51. pathname,
  52. projectHistoryId,
  53. _callback
  54. ) {
  55. const timer = new metrics.Timer('redis.put-doc')
  56. const callback = function (error) {
  57. timer.done()
  58. return _callback(error)
  59. }
  60. const docLinesArray = docLines
  61. docLines = JSON.stringify(docLines)
  62. if (docLines.indexOf('\u0000') !== -1) {
  63. const error = new Error('null bytes found in doc lines')
  64. // this check was added to catch memory corruption in JSON.stringify.
  65. // It sometimes returned null bytes at the end of the string.
  66. logger.error({ err: error, doc_id, docLines }, error.message)
  67. return callback(error)
  68. }
  69. // Do an optimised size check on the docLines using the serialised
  70. // length as an upper bound
  71. const sizeBound = docLines.length
  72. if (docIsTooLarge(sizeBound, docLinesArray, Settings.max_doc_length)) {
  73. const docSize = docLines.length
  74. const err = new Error('blocking doc insert into redis: doc is too large')
  75. logger.error({ project_id, doc_id, err, docSize }, err.message)
  76. return callback(err)
  77. }
  78. const docHash = RedisManager._computeHash(docLines)
  79. // record bytes sent to redis
  80. metrics.summary('redis.docLines', docLines.length, { status: 'set' })
  81. logger.debug(
  82. { project_id, doc_id, version, docHash, pathname, projectHistoryId },
  83. 'putting doc in redis'
  84. )
  85. return RedisManager._serializeRanges(ranges, function (error, ranges) {
  86. if (error != null) {
  87. logger.error({ err: error, doc_id, project_id }, error.message)
  88. return callback(error)
  89. }
  90. // update docsInProject set before writing doc contents
  91. rclient.sadd(keys.docsInProject({ project_id }), doc_id, error => {
  92. if (error) return callback(error)
  93. rclient.mset(
  94. {
  95. [keys.docLines({ doc_id })]: docLines,
  96. [keys.projectKey({ doc_id })]: project_id,
  97. [keys.docVersion({ doc_id })]: version,
  98. [keys.docHash({ doc_id })]: docHash,
  99. [keys.ranges({ doc_id })]: ranges,
  100. [keys.pathname({ doc_id })]: pathname,
  101. [keys.projectHistoryId({ doc_id })]: projectHistoryId,
  102. },
  103. callback
  104. )
  105. })
  106. })
  107. },
  108. removeDocFromMemory(project_id, doc_id, _callback) {
  109. logger.debug({ project_id, doc_id }, 'removing doc from redis')
  110. const callback = function (err) {
  111. if (err != null) {
  112. logger.err({ project_id, doc_id, err }, 'error removing doc from redis')
  113. return _callback(err)
  114. } else {
  115. logger.debug({ project_id, doc_id }, 'removed doc from redis')
  116. return _callback()
  117. }
  118. }
  119. let multi = rclient.multi()
  120. multi.strlen(keys.docLines({ doc_id }))
  121. multi.del(
  122. keys.docLines({ doc_id }),
  123. keys.projectKey({ doc_id }),
  124. keys.docVersion({ doc_id }),
  125. keys.docHash({ doc_id }),
  126. keys.ranges({ doc_id }),
  127. keys.pathname({ doc_id }),
  128. keys.projectHistoryId({ doc_id }),
  129. keys.projectHistoryType({ doc_id }),
  130. keys.unflushedTime({ doc_id }),
  131. keys.lastUpdatedAt({ doc_id }),
  132. keys.lastUpdatedBy({ doc_id })
  133. )
  134. return multi.exec(function (error, response) {
  135. if (error != null) {
  136. return callback(error)
  137. }
  138. const length = response != null ? response[0] : undefined
  139. if (length > 0) {
  140. // record bytes freed in redis
  141. metrics.summary('redis.docLines', length, { status: 'del' })
  142. }
  143. multi = rclient.multi()
  144. multi.srem(keys.docsInProject({ project_id }), doc_id)
  145. multi.del(keys.projectState({ project_id }))
  146. return multi.exec(callback)
  147. })
  148. },
  149. checkOrSetProjectState(project_id, newState, callback) {
  150. if (callback == null) {
  151. callback = function () {}
  152. }
  153. const multi = rclient.multi()
  154. multi.getset(keys.projectState({ project_id }), newState)
  155. multi.expire(keys.projectState({ project_id }), 30 * minutes)
  156. return multi.exec(function (error, response) {
  157. if (error != null) {
  158. return callback(error)
  159. }
  160. logger.debug(
  161. { project_id, newState, oldState: response[0] },
  162. 'checking project state'
  163. )
  164. return callback(null, response[0] !== newState)
  165. })
  166. },
  167. clearProjectState(project_id, callback) {
  168. if (callback == null) {
  169. callback = function () {}
  170. }
  171. return rclient.del(keys.projectState({ project_id }), callback)
  172. },
  173. getDoc(project_id, doc_id, callback) {
  174. if (callback == null) {
  175. callback = function () {}
  176. }
  177. const timer = new metrics.Timer('redis.get-doc')
  178. const collectKeys = [
  179. keys.docLines({ doc_id }),
  180. keys.docVersion({ doc_id }),
  181. keys.docHash({ doc_id }),
  182. keys.projectKey({ doc_id }),
  183. keys.ranges({ doc_id }),
  184. keys.pathname({ doc_id }),
  185. keys.projectHistoryId({ doc_id }),
  186. keys.unflushedTime({ doc_id }),
  187. keys.lastUpdatedAt({ doc_id }),
  188. keys.lastUpdatedBy({ doc_id }),
  189. ]
  190. rclient.mget(...collectKeys, (error, ...rest) => {
  191. let [
  192. docLines,
  193. version,
  194. storedHash,
  195. doc_project_id,
  196. ranges,
  197. pathname,
  198. projectHistoryId,
  199. unflushedTime,
  200. lastUpdatedAt,
  201. lastUpdatedBy,
  202. ] = Array.from(rest[0])
  203. const timeSpan = timer.done()
  204. if (error != null) {
  205. return callback(error)
  206. }
  207. // check if request took too long and bail out. only do this for
  208. // get, because it is the first call in each update, so if this
  209. // passes we'll assume others have a reasonable chance to succeed.
  210. if (timeSpan > MAX_REDIS_REQUEST_LENGTH) {
  211. error = new Error('redis getDoc exceeded timeout')
  212. return callback(error)
  213. }
  214. // record bytes loaded from redis
  215. if (docLines != null) {
  216. metrics.summary('redis.docLines', docLines.length, { status: 'get' })
  217. }
  218. // check sha1 hash value if present
  219. if (docLines != null && storedHash != null) {
  220. const computedHash = RedisManager._computeHash(docLines)
  221. if (logHashReadErrors && computedHash !== storedHash) {
  222. logger.error(
  223. {
  224. project_id,
  225. doc_id,
  226. doc_project_id,
  227. computedHash,
  228. storedHash,
  229. docLines,
  230. },
  231. 'hash mismatch on retrieved document'
  232. )
  233. }
  234. }
  235. try {
  236. docLines = JSON.parse(docLines)
  237. ranges = RedisManager._deserializeRanges(ranges)
  238. } catch (e) {
  239. return callback(e)
  240. }
  241. version = parseInt(version || 0, 10)
  242. // check doc is in requested project
  243. if (doc_project_id != null && doc_project_id !== project_id) {
  244. logger.error(
  245. { project_id, doc_id, doc_project_id },
  246. 'doc not in project'
  247. )
  248. return callback(new Errors.NotFoundError('document not found'))
  249. }
  250. if (projectHistoryId != null) {
  251. projectHistoryId = parseInt(projectHistoryId)
  252. }
  253. callback(
  254. null,
  255. docLines,
  256. version,
  257. ranges,
  258. pathname,
  259. projectHistoryId,
  260. unflushedTime,
  261. lastUpdatedAt,
  262. lastUpdatedBy
  263. )
  264. })
  265. },
  266. getDocVersion(doc_id, callback) {
  267. if (callback == null) {
  268. callback = function () {}
  269. }
  270. return rclient.mget(
  271. keys.docVersion({ doc_id }),
  272. keys.projectHistoryType({ doc_id }),
  273. function (error, result) {
  274. if (error != null) {
  275. return callback(error)
  276. }
  277. let [version, projectHistoryType] = Array.from(result || [])
  278. version = parseInt(version, 10)
  279. return callback(null, version, projectHistoryType)
  280. }
  281. )
  282. },
  283. getDocLines(doc_id, callback) {
  284. if (callback == null) {
  285. callback = function () {}
  286. }
  287. return rclient.get(keys.docLines({ doc_id }), function (error, docLines) {
  288. if (error != null) {
  289. return callback(error)
  290. }
  291. return callback(null, docLines)
  292. })
  293. },
  294. getPreviousDocOps(doc_id, start, end, callback) {
  295. if (callback == null) {
  296. callback = function () {}
  297. }
  298. const timer = new metrics.Timer('redis.get-prev-docops')
  299. return rclient.llen(keys.docOps({ doc_id }), function (error, length) {
  300. if (error != null) {
  301. return callback(error)
  302. }
  303. return rclient.get(
  304. keys.docVersion({ doc_id }),
  305. function (error, version) {
  306. if (error != null) {
  307. return callback(error)
  308. }
  309. version = parseInt(version, 10)
  310. const first_version_in_redis = version - length
  311. if (start < first_version_in_redis || end > version) {
  312. error = new Errors.OpRangeNotAvailableError(
  313. 'doc ops range is not loaded in redis'
  314. )
  315. logger.debug(
  316. { err: error, doc_id, length, version, start, end },
  317. 'doc ops range is not loaded in redis'
  318. )
  319. return callback(error)
  320. }
  321. start = start - first_version_in_redis
  322. if (end > -1) {
  323. end = end - first_version_in_redis
  324. }
  325. if (isNaN(start) || isNaN(end)) {
  326. error = new Error('inconsistent version or lengths')
  327. logger.error(
  328. { err: error, doc_id, length, version, start, end },
  329. 'inconsistent version or length'
  330. )
  331. return callback(error)
  332. }
  333. return rclient.lrange(
  334. keys.docOps({ doc_id }),
  335. start,
  336. end,
  337. function (error, jsonOps) {
  338. let ops
  339. if (error != null) {
  340. return callback(error)
  341. }
  342. try {
  343. ops = jsonOps.map(jsonOp => JSON.parse(jsonOp))
  344. } catch (e) {
  345. return callback(e)
  346. }
  347. const timeSpan = timer.done()
  348. if (timeSpan > MAX_REDIS_REQUEST_LENGTH) {
  349. error = new Error('redis getPreviousDocOps exceeded timeout')
  350. return callback(error)
  351. }
  352. return callback(null, ops)
  353. }
  354. )
  355. }
  356. )
  357. })
  358. },
  359. getHistoryType(doc_id, callback) {
  360. if (callback == null) {
  361. callback = function () {}
  362. }
  363. return rclient.get(
  364. keys.projectHistoryType({ doc_id }),
  365. function (error, projectHistoryType) {
  366. if (error != null) {
  367. return callback(error)
  368. }
  369. return callback(null, projectHistoryType)
  370. }
  371. )
  372. },
  373. setHistoryType(doc_id, projectHistoryType, callback) {
  374. if (callback == null) {
  375. callback = function () {}
  376. }
  377. return rclient.set(
  378. keys.projectHistoryType({ doc_id }),
  379. projectHistoryType,
  380. callback
  381. )
  382. },
  383. DOC_OPS_TTL: 60 * minutes,
  384. DOC_OPS_MAX_LENGTH: 100,
  385. updateDocument(
  386. project_id,
  387. doc_id,
  388. docLines,
  389. newVersion,
  390. appliedOps,
  391. ranges,
  392. updateMeta,
  393. callback
  394. ) {
  395. if (appliedOps == null) {
  396. appliedOps = []
  397. }
  398. if (callback == null) {
  399. callback = function () {}
  400. }
  401. return RedisManager.getDocVersion(
  402. doc_id,
  403. function (error, currentVersion, projectHistoryType) {
  404. if (error != null) {
  405. return callback(error)
  406. }
  407. if (currentVersion + appliedOps.length !== newVersion) {
  408. error = new Error(`Version mismatch. '${doc_id}' is corrupted.`)
  409. logger.error(
  410. {
  411. err: error,
  412. doc_id,
  413. currentVersion,
  414. newVersion,
  415. opsLength: appliedOps.length,
  416. },
  417. 'version mismatch'
  418. )
  419. return callback(error)
  420. }
  421. const jsonOps = appliedOps.map(op => JSON.stringify(op))
  422. for (const op of Array.from(jsonOps)) {
  423. if (op.indexOf('\u0000') !== -1) {
  424. error = new Error('null bytes found in jsonOps')
  425. // this check was added to catch memory corruption in JSON.stringify
  426. logger.error({ err: error, doc_id, jsonOps }, error.message)
  427. return callback(error)
  428. }
  429. }
  430. const newDocLines = JSON.stringify(docLines)
  431. if (newDocLines.indexOf('\u0000') !== -1) {
  432. error = new Error('null bytes found in doc lines')
  433. // this check was added to catch memory corruption in JSON.stringify
  434. logger.error({ err: error, doc_id, newDocLines }, error.message)
  435. return callback(error)
  436. }
  437. // Do an optimised size check on the docLines using the serialised
  438. // length as an upper bound
  439. const sizeBound = newDocLines.length
  440. if (docIsTooLarge(sizeBound, docLines, Settings.max_doc_length)) {
  441. const err = new Error('blocking doc update: doc is too large')
  442. const docSize = newDocLines.length
  443. logger.error({ project_id, doc_id, err, docSize }, err.message)
  444. return callback(err)
  445. }
  446. const newHash = RedisManager._computeHash(newDocLines)
  447. const opVersions = appliedOps.map(op => (op != null ? op.v : undefined))
  448. logger.debug(
  449. {
  450. doc_id,
  451. version: newVersion,
  452. hash: newHash,
  453. op_versions: opVersions,
  454. },
  455. 'updating doc in redis'
  456. )
  457. // record bytes sent to redis in update
  458. metrics.summary('redis.docLines', newDocLines.length, {
  459. status: 'update',
  460. })
  461. return RedisManager._serializeRanges(ranges, function (error, ranges) {
  462. if (error != null) {
  463. logger.error({ err: error, doc_id }, error.message)
  464. return callback(error)
  465. }
  466. if (ranges != null && ranges.indexOf('\u0000') !== -1) {
  467. error = new Error('null bytes found in ranges')
  468. // this check was added to catch memory corruption in JSON.stringify
  469. logger.error({ err: error, doc_id, ranges }, error.message)
  470. return callback(error)
  471. }
  472. const multi = rclient.multi()
  473. multi.mset({
  474. [keys.docLines({ doc_id })]: newDocLines,
  475. [keys.docVersion({ doc_id })]: newVersion,
  476. [keys.docHash({ doc_id })]: newHash,
  477. [keys.ranges({ doc_id })]: ranges,
  478. [keys.lastUpdatedAt({ doc_id })]: Date.now(),
  479. [keys.lastUpdatedBy({ doc_id })]: updateMeta && updateMeta.user_id,
  480. })
  481. multi.ltrim(
  482. keys.docOps({ doc_id }),
  483. -RedisManager.DOC_OPS_MAX_LENGTH,
  484. -1
  485. ) // index 3
  486. // push the ops last so we can get the lengths at fixed index position 7
  487. if (jsonOps.length > 0) {
  488. multi.rpush(keys.docOps({ doc_id }), ...Array.from(jsonOps)) // index 5
  489. // expire must come after rpush since before it will be a no-op if the list is empty
  490. multi.expire(keys.docOps({ doc_id }), RedisManager.DOC_OPS_TTL) // index 6
  491. if (projectHistoryType === 'project-history') {
  492. metrics.inc('history-queue', 1, { status: 'skip-track-changes' })
  493. logger.debug(
  494. { doc_id },
  495. 'skipping push of uncompressed ops for project using project-history'
  496. )
  497. } else {
  498. // project is using old track-changes history service
  499. metrics.inc('history-queue', 1, { status: 'track-changes' })
  500. multi.rpush(
  501. historyKeys.uncompressedHistoryOps({ doc_id }),
  502. ...Array.from(jsonOps)
  503. ) // index 7
  504. }
  505. // Set the unflushed timestamp to the current time if the doc
  506. // hasn't been modified before (the content in mongo has been
  507. // valid up to this point). Otherwise leave it alone ("NX" flag).
  508. multi.set(keys.unflushedTime({ doc_id }), Date.now(), 'NX')
  509. }
  510. return multi.exec(function (error, result) {
  511. let docUpdateCount
  512. if (error != null) {
  513. return callback(error)
  514. }
  515. if (projectHistoryType === 'project-history') {
  516. docUpdateCount = undefined // only using project history, don't bother with track-changes
  517. } else {
  518. // project is using old track-changes history service
  519. docUpdateCount = result[4]
  520. }
  521. if (
  522. jsonOps.length > 0 &&
  523. __guard__(
  524. Settings.apis != null
  525. ? Settings.apis.project_history
  526. : undefined,
  527. x => x.enabled
  528. )
  529. ) {
  530. metrics.inc('history-queue', 1, { status: 'project-history' })
  531. return ProjectHistoryRedisManager.queueOps(
  532. project_id,
  533. ...Array.from(jsonOps),
  534. (error, projectUpdateCount) => {
  535. if (error) {
  536. // The full project history can re-sync a project in case
  537. // updates went missing.
  538. // Just record the error here and acknowledge the write-op.
  539. metrics.inc('history-queue-error')
  540. }
  541. callback(null, docUpdateCount, projectUpdateCount)
  542. }
  543. )
  544. } else {
  545. return callback(null, docUpdateCount)
  546. }
  547. })
  548. })
  549. }
  550. )
  551. },
  552. renameDoc(project_id, doc_id, user_id, update, projectHistoryId, callback) {
  553. if (callback == null) {
  554. callback = function () {}
  555. }
  556. return RedisManager.getDoc(
  557. project_id,
  558. doc_id,
  559. function (error, lines, version) {
  560. if (error != null) {
  561. return callback(error)
  562. }
  563. if (lines != null && version != null) {
  564. return rclient.set(
  565. keys.pathname({ doc_id }),
  566. update.newPathname,
  567. callback
  568. )
  569. } else {
  570. return callback()
  571. }
  572. }
  573. )
  574. },
  575. clearUnflushedTime(doc_id, callback) {
  576. if (callback == null) {
  577. callback = function () {}
  578. }
  579. return rclient.del(keys.unflushedTime({ doc_id }), callback)
  580. },
  581. getDocIdsInProject(project_id, callback) {
  582. if (callback == null) {
  583. callback = function () {}
  584. }
  585. return rclient.smembers(keys.docsInProject({ project_id }), callback)
  586. },
  587. getDocTimestamps(doc_ids, callback) {
  588. // get lastupdatedat timestamps for an array of doc_ids
  589. if (callback == null) {
  590. callback = function () {}
  591. }
  592. return async.mapSeries(
  593. doc_ids,
  594. (doc_id, cb) => rclient.get(keys.lastUpdatedAt({ doc_id }), cb),
  595. callback
  596. )
  597. },
  598. queueFlushAndDeleteProject(project_id, callback) {
  599. // store the project id in a sorted set ordered by time with a random offset to smooth out spikes
  600. const SMOOTHING_OFFSET =
  601. Settings.smoothingOffset > 0
  602. ? Math.round(Settings.smoothingOffset * Math.random())
  603. : 0
  604. return rclient.zadd(
  605. keys.flushAndDeleteQueue(),
  606. Date.now() + SMOOTHING_OFFSET,
  607. project_id,
  608. callback
  609. )
  610. },
  611. getNextProjectToFlushAndDelete(cutoffTime, callback) {
  612. // find the oldest queued flush that is before the cutoff time
  613. if (callback == null) {
  614. callback = function () {}
  615. }
  616. return rclient.zrangebyscore(
  617. keys.flushAndDeleteQueue(),
  618. 0,
  619. cutoffTime,
  620. 'WITHSCORES',
  621. 'LIMIT',
  622. 0,
  623. 1,
  624. function (err, reply) {
  625. if (err != null) {
  626. return callback(err)
  627. }
  628. if (!(reply != null ? reply.length : undefined)) {
  629. return callback()
  630. } // return if no projects ready to be processed
  631. // pop the oldest entry (get and remove in a multi)
  632. const multi = rclient.multi()
  633. // Poor man's version of ZPOPMIN, which is only available in Redis 5.
  634. multi.zrange(keys.flushAndDeleteQueue(), 0, 0, 'WITHSCORES')
  635. multi.zremrangebyrank(keys.flushAndDeleteQueue(), 0, 0)
  636. multi.zcard(keys.flushAndDeleteQueue()) // the total length of the queue (for metrics)
  637. return multi.exec(function (err, reply) {
  638. if (err != null) {
  639. return callback(err)
  640. }
  641. if (!(reply != null ? reply.length : undefined)) {
  642. return callback()
  643. }
  644. const [key, timestamp] = Array.from(reply[0])
  645. const queueLength = reply[2]
  646. return callback(null, key, timestamp, queueLength)
  647. })
  648. }
  649. )
  650. },
  651. _serializeRanges(ranges, callback) {
  652. if (callback == null) {
  653. callback = function () {}
  654. }
  655. let jsonRanges = JSON.stringify(ranges)
  656. if (jsonRanges != null && jsonRanges.length > MAX_RANGES_SIZE) {
  657. return callback(new Error('ranges are too large'))
  658. }
  659. if (jsonRanges === '{}') {
  660. // Most doc will have empty ranges so don't fill redis with lots of '{}' keys
  661. jsonRanges = null
  662. }
  663. return callback(null, jsonRanges)
  664. },
  665. _deserializeRanges(ranges) {
  666. if (ranges == null || ranges === '') {
  667. return {}
  668. } else {
  669. return JSON.parse(ranges)
  670. }
  671. },
  672. _computeHash(docLines) {
  673. // use sha1 checksum of doclines to detect data corruption.
  674. //
  675. // note: must specify 'utf8' encoding explicitly, as the default is
  676. // binary in node < v5
  677. return crypto.createHash('sha1').update(docLines, 'utf8').digest('hex')
  678. },
  679. }
  680. function __guard__(value, transform) {
  681. return typeof value !== 'undefined' && value !== null
  682. ? transform(value)
  683. : undefined
  684. }