RedisManager.js 22 KB

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