RedisManager.js 23 KB

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