RedisManager.js 25 KB

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