RedisManager.js 23 KB

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