RedisManager.js 25 KB

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