RedisManager.js 24 KB

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