RedisManager.js 24 KB

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