RedisManager.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  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('node: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. if (docLines != null && !Array.isArray(docLines)) {
  308. return callback(
  309. new Errors.ProjectMigratedToHistoryOTError(
  310. 'refusing to process doc that was migrated to history-ot'
  311. )
  312. )
  313. }
  314. version = parseInt(version || 0, 10)
  315. // check doc is in requested project
  316. if (docProjectId != null && docProjectId !== projectId) {
  317. logger.error(
  318. { projectId, docId, docProjectId },
  319. 'doc not in project'
  320. )
  321. return callback(new Errors.NotFoundError('document not found'))
  322. }
  323. if (docLines && version && !pathname) {
  324. metrics.inc('pathname', 1, {
  325. path: 'RedisManager.getDoc',
  326. status: pathname === '' ? 'zero-length' : 'undefined',
  327. })
  328. }
  329. callback(
  330. null,
  331. docLines,
  332. version,
  333. ranges,
  334. pathname,
  335. projectHistoryId,
  336. unflushedTime,
  337. lastUpdatedAt,
  338. lastUpdatedBy,
  339. historyRangesSupport,
  340. resolvedCommentIds
  341. )
  342. }
  343. )
  344. })
  345. })
  346. },
  347. getDocVersion(docId, callback) {
  348. rclient.mget(keys.docVersion({ doc_id: docId }), (error, result) => {
  349. if (error) {
  350. return callback(error)
  351. }
  352. let [version] = result || []
  353. version = parseInt(version, 10)
  354. callback(null, version)
  355. })
  356. },
  357. getDocLines(docId, callback) {
  358. rclient.get(keys.docLines({ doc_id: docId }), (error, docLines) => {
  359. if (error) {
  360. return callback(error)
  361. }
  362. callback(null, docLines)
  363. })
  364. },
  365. getPreviousDocOps(docId, start, end, callback) {
  366. const timer = new metrics.Timer('redis.get-prev-docops')
  367. rclient.llen(keys.docOps({ doc_id: docId }), (error, length) => {
  368. if (error) {
  369. return callback(error)
  370. }
  371. rclient.get(keys.docVersion({ doc_id: docId }), (error, version) => {
  372. if (error) {
  373. return callback(error)
  374. }
  375. version = parseInt(version, 10)
  376. const firstVersionInRedis = version - length
  377. if (start < firstVersionInRedis || end > version) {
  378. error = new Errors.OpRangeNotAvailableError(
  379. 'doc ops range is not loaded in redis',
  380. { firstVersionInRedis, version, ttlInS: RedisManager.DOC_OPS_TTL }
  381. )
  382. logger.debug(
  383. { err: error, docId, length, version, start, end },
  384. 'doc ops range is not loaded in redis'
  385. )
  386. return callback(error)
  387. }
  388. start = start - firstVersionInRedis
  389. if (end > -1) {
  390. end = end - firstVersionInRedis
  391. }
  392. if (isNaN(start) || isNaN(end)) {
  393. error = new Error('inconsistent version or lengths')
  394. logger.error(
  395. { err: error, docId, length, version, start, end },
  396. 'inconsistent version or length'
  397. )
  398. return callback(error)
  399. }
  400. rclient.lrange(
  401. keys.docOps({ doc_id: docId }),
  402. start,
  403. end,
  404. (error, jsonOps) => {
  405. let ops
  406. if (error) {
  407. return callback(error)
  408. }
  409. try {
  410. ops = jsonOps.map(jsonOp => JSON.parse(jsonOp))
  411. } catch (e) {
  412. return callback(e)
  413. }
  414. const timeSpan = timer.done()
  415. if (timeSpan > MAX_REDIS_REQUEST_LENGTH) {
  416. error = new Error('redis getPreviousDocOps exceeded timeout')
  417. return callback(error)
  418. }
  419. callback(null, ops)
  420. }
  421. )
  422. })
  423. })
  424. },
  425. DOC_OPS_TTL: 60 * minutes,
  426. DOC_OPS_MAX_LENGTH: 100,
  427. updateDocument(
  428. projectId,
  429. docId,
  430. docLines,
  431. newVersion,
  432. appliedOps,
  433. ranges,
  434. updateMeta,
  435. callback
  436. ) {
  437. if (appliedOps == null) {
  438. appliedOps = []
  439. }
  440. RedisManager.getDocVersion(docId, (error, currentVersion) => {
  441. if (error) {
  442. return callback(error)
  443. }
  444. if (currentVersion + appliedOps.length !== newVersion) {
  445. error = new Error(`Version mismatch. '${docId}' is corrupted.`)
  446. logger.error(
  447. {
  448. err: error,
  449. docId,
  450. currentVersion,
  451. newVersion,
  452. opsLength: appliedOps.length,
  453. },
  454. 'version mismatch'
  455. )
  456. return callback(error)
  457. }
  458. const jsonOps = appliedOps.map(op => JSON.stringify(op))
  459. for (const op of jsonOps) {
  460. if (op.indexOf('\u0000') !== -1) {
  461. error = new Error('null bytes found in jsonOps')
  462. // this check was added to catch memory corruption in JSON.stringify
  463. logger.error({ err: error, docId, jsonOps }, error.message)
  464. return callback(error)
  465. }
  466. }
  467. const newDocLines = JSON.stringify(docLines)
  468. if (newDocLines.indexOf('\u0000') !== -1) {
  469. error = new Error('null bytes found in doc lines')
  470. // this check was added to catch memory corruption in JSON.stringify
  471. logger.error({ err: error, docId, newDocLines }, error.message)
  472. return callback(error)
  473. }
  474. // Do an optimised size check on the docLines using the serialised
  475. // length as an upper bound
  476. const sizeBound = newDocLines.length
  477. if (docIsTooLarge(sizeBound, docLines, Settings.max_doc_length)) {
  478. const err = new Error('blocking doc update: doc is too large')
  479. const docSize = newDocLines.length
  480. logger.error({ projectId, docId, err, docSize }, err.message)
  481. return callback(err)
  482. }
  483. const newHash = RedisManager._computeHash(newDocLines)
  484. const opVersions = appliedOps.map(op => op?.v)
  485. logger.debug(
  486. {
  487. docId,
  488. version: newVersion,
  489. hash: newHash,
  490. opVersions,
  491. },
  492. 'updating doc in redis'
  493. )
  494. // record bytes sent to redis in update
  495. metrics.summary('redis.docLines', newDocLines.length, {
  496. status: 'update',
  497. })
  498. RedisManager._serializeRanges(ranges, (error, ranges) => {
  499. if (error) {
  500. logger.error({ err: error, docId }, error.message)
  501. return callback(error)
  502. }
  503. if (ranges && ranges.indexOf('\u0000') !== -1) {
  504. error = new Error('null bytes found in ranges')
  505. // this check was added to catch memory corruption in JSON.stringify
  506. logger.error({ err: error, docId, ranges }, error.message)
  507. return callback(error)
  508. }
  509. // Make sure that this MULTI operation only operates on doc
  510. // specific keys, i.e. keys that have the doc id in curly braces.
  511. // The curly braces identify a hash key for Redis and ensures that
  512. // the MULTI's operations are all done on the same node in a
  513. // cluster environment.
  514. const multi = rclient.multi()
  515. multi.mset({
  516. [keys.docLines({ doc_id: docId })]: newDocLines,
  517. [keys.docVersion({ doc_id: docId })]: newVersion,
  518. [keys.docHash({ doc_id: docId })]: newHash,
  519. [keys.ranges({ doc_id: docId })]: ranges,
  520. [keys.lastUpdatedAt({ doc_id: docId })]: Date.now(),
  521. [keys.lastUpdatedBy({ doc_id: docId })]:
  522. updateMeta && updateMeta.user_id,
  523. })
  524. multi.ltrim(
  525. keys.docOps({ doc_id: docId }),
  526. -RedisManager.DOC_OPS_MAX_LENGTH,
  527. -1
  528. ) // index 3
  529. // push the ops last so we can get the lengths at fixed index position 7
  530. if (jsonOps.length > 0) {
  531. multi.rpush(keys.docOps({ doc_id: docId }), ...jsonOps) // index 5
  532. // expire must come after rpush since before it will be a no-op if the list is empty
  533. multi.expire(keys.docOps({ doc_id: docId }), RedisManager.DOC_OPS_TTL) // index 6
  534. }
  535. // Set the unflushed timestamp to the current time if not set ("NX" flag).
  536. multi.set(keys.unflushedTime({ doc_id: docId }), Date.now(), 'NX')
  537. multi.exec((error, result) => {
  538. if (error) {
  539. return callback(error)
  540. }
  541. callback()
  542. })
  543. })
  544. })
  545. },
  546. renameDoc(projectId, docId, userId, update, projectHistoryId, callback) {
  547. RedisManager.getDoc(projectId, docId, (error, lines, version) => {
  548. if (error) {
  549. return callback(error)
  550. }
  551. if (lines != null && version != null) {
  552. if (!update.newPathname) {
  553. logger.warn(
  554. { projectId, docId, update },
  555. 'missing pathname in RedisManager.renameDoc'
  556. )
  557. metrics.inc('pathname', 1, {
  558. path: 'RedisManager.renameDoc',
  559. status: update.newPathname === '' ? 'zero-length' : 'undefined',
  560. })
  561. }
  562. rclient.set(
  563. keys.pathname({ doc_id: docId }),
  564. update.newPathname,
  565. callback
  566. )
  567. } else {
  568. callback()
  569. }
  570. })
  571. },
  572. clearUnflushedTime(docId, callback) {
  573. rclient.del(keys.unflushedTime({ doc_id: docId }), callback)
  574. },
  575. updateCommentState(docId, commentId, resolved, callback) {
  576. if (resolved) {
  577. rclient.sadd(
  578. keys.resolvedCommentIds({ doc_id: docId }),
  579. commentId,
  580. callback
  581. )
  582. } else {
  583. rclient.srem(
  584. keys.resolvedCommentIds({ doc_id: docId }),
  585. commentId,
  586. callback
  587. )
  588. }
  589. },
  590. getDocIdsInProject(projectId, callback) {
  591. rclient.smembers(keys.docsInProject({ project_id: projectId }), callback)
  592. },
  593. /**
  594. * Get lastupdatedat timestamps for an array of docIds
  595. */
  596. getDocTimestamps(docIds, callback) {
  597. async.mapSeries(
  598. docIds,
  599. (docId, cb) => rclient.get(keys.lastUpdatedAt({ doc_id: docId }), cb),
  600. callback
  601. )
  602. },
  603. /**
  604. * Store the project id in a sorted set ordered by time with a random offset
  605. * to smooth out spikes
  606. */
  607. queueFlushAndDeleteProject(projectId, callback) {
  608. const SMOOTHING_OFFSET =
  609. Settings.smoothingOffset > 0
  610. ? Math.round(Settings.smoothingOffset * Math.random())
  611. : 0
  612. rclient.zadd(
  613. keys.flushAndDeleteQueue(),
  614. Date.now() + SMOOTHING_OFFSET,
  615. projectId,
  616. callback
  617. )
  618. },
  619. /**
  620. * Find the oldest queued flush that is before the cutoff time
  621. */
  622. getNextProjectToFlushAndDelete(cutoffTime, callback) {
  623. rclient.zrangebyscore(
  624. keys.flushAndDeleteQueue(),
  625. 0,
  626. cutoffTime,
  627. 'WITHSCORES',
  628. 'LIMIT',
  629. 0,
  630. 1,
  631. (err, reply) => {
  632. if (err) {
  633. return callback(err)
  634. }
  635. // return if no projects ready to be processed
  636. if (!reply || reply.length === 0) {
  637. return callback()
  638. }
  639. // pop the oldest entry (get and remove in a multi)
  640. const multi = rclient.multi()
  641. // Poor man's version of ZPOPMIN, which is only available in Redis 5.
  642. multi.zrange(keys.flushAndDeleteQueue(), 0, 0, 'WITHSCORES')
  643. multi.zremrangebyrank(keys.flushAndDeleteQueue(), 0, 0)
  644. multi.zcard(keys.flushAndDeleteQueue()) // the total length of the queue (for metrics)
  645. multi.exec((err, reply) => {
  646. if (err) {
  647. return callback(err)
  648. }
  649. if (!reply || reply.length === 0) {
  650. return callback()
  651. }
  652. const [key, timestamp] = reply[0]
  653. const queueLength = reply[2]
  654. callback(null, key, timestamp, queueLength)
  655. })
  656. }
  657. )
  658. },
  659. setHistoryRangesSupportFlag(docId, historyRangesSupport, callback) {
  660. if (historyRangesSupport) {
  661. rclient.sadd(keys.historyRangesSupport(), docId, callback)
  662. } else {
  663. rclient.srem(keys.historyRangesSupport(), docId, callback)
  664. }
  665. },
  666. blockProject(projectId, callback) {
  667. // Make sure that this MULTI operation only operates on project
  668. // specific keys, i.e. keys that have the project id in curly braces.
  669. // The curly braces identify a hash key for Redis and ensures that
  670. // the MULTI's operations are all done on the same node in a
  671. // cluster environment.
  672. const multi = rclient.multi()
  673. multi.setex(
  674. keys.projectBlock({ project_id: projectId }),
  675. PROJECT_BLOCK_TTL_SECS,
  676. '1'
  677. )
  678. multi.scard(keys.docsInProject({ project_id: projectId }))
  679. multi.exec((err, reply) => {
  680. if (err) {
  681. return callback(err)
  682. }
  683. const docsInProject = reply[1]
  684. if (docsInProject > 0) {
  685. // Too late to lock the project
  686. rclient.del(keys.projectBlock({ project_id: projectId }), err => {
  687. if (err) {
  688. return callback(err)
  689. }
  690. callback(null, false)
  691. })
  692. } else {
  693. callback(null, true)
  694. }
  695. })
  696. },
  697. unblockProject(projectId, callback) {
  698. rclient.del(keys.projectBlock({ project_id: projectId }), (err, reply) => {
  699. if (err) {
  700. return callback(err)
  701. }
  702. const wasBlocked = reply === 1
  703. callback(null, wasBlocked)
  704. })
  705. },
  706. _serializeRanges(ranges, callback) {
  707. let jsonRanges = JSON.stringify(ranges)
  708. if (jsonRanges && jsonRanges.length > MAX_RANGES_SIZE) {
  709. return callback(new Error('ranges are too large'))
  710. }
  711. if (jsonRanges === '{}') {
  712. // Most doc will have empty ranges so don't fill redis with lots of '{}' keys
  713. jsonRanges = null
  714. }
  715. callback(null, jsonRanges)
  716. },
  717. _deserializeRanges(ranges) {
  718. if (ranges == null || ranges === '') {
  719. return {}
  720. } else {
  721. return JSON.parse(ranges)
  722. }
  723. },
  724. _computeHash(docLines) {
  725. // use sha1 checksum of doclines to detect data corruption.
  726. //
  727. // note: must specify 'utf8' encoding explicitly, as the default is
  728. // binary in node < v5
  729. return crypto.createHash('sha1').update(docLines, 'utf8').digest('hex')
  730. },
  731. }
  732. module.exports = RedisManager
  733. module.exports.promises = promisifyAll(RedisManager, {
  734. without: ['_deserializeRanges', '_computeHash'],
  735. multiResult: {
  736. getDoc: [
  737. 'lines',
  738. 'version',
  739. 'ranges',
  740. 'pathname',
  741. 'projectHistoryId',
  742. 'unflushedTime',
  743. 'lastUpdatedAt',
  744. 'lastUpdatedBy',
  745. 'historyRangesSupport',
  746. 'resolvedCommentIds',
  747. ],
  748. getNextProjectToFlushAndDelete: [
  749. 'projectId',
  750. 'flushTimestamp',
  751. 'queueLength',
  752. ],
  753. },
  754. })