RedisManager.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  1. const Settings = require('@overleaf/settings')
  2. const RedisWrapper = require('@overleaf/redis-wrapper')
  3. const logger = require('@overleaf/logger')
  4. const OError = require('@overleaf/o-error')
  5. const { promisifyAll } = require('@overleaf/promise-utils')
  6. const metrics = require('./Metrics')
  7. const Errors = require('./Errors')
  8. const crypto = require('node:crypto')
  9. const async = require('async')
  10. const { docIsTooLarge } = require('./Limits')
  11. const rclient = RedisWrapper.createClient(Settings.redis.documentupdater)
  12. // Sometimes Redis calls take an unexpectedly long time. We have to be
  13. // quick with Redis calls because we're holding a lock that expires
  14. // after 30 seconds. We can't let any errors in the rest of the stack
  15. // hold us up, and need to bail out quickly if there is a problem.
  16. const MAX_REDIS_REQUEST_LENGTH = 5000 // 5 seconds
  17. const PROJECT_BLOCK_TTL_SECS = 30
  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 shareJSTextOT = Array.isArray(docLines)
  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 (
  57. shareJSTextOT && // editor-core has a size check in TextOperation.apply and TextOperation.applyToLength.
  58. docIsTooLarge(sizeBound, docLinesArray, Settings.max_doc_length)
  59. ) {
  60. const docSize = docLines.length
  61. const err = new Error('blocking doc insert into redis: doc is too large')
  62. logger.error({ projectId, docId, err, docSize }, err.message)
  63. return callback(err)
  64. }
  65. const docHash = RedisManager._computeHash(docLines)
  66. // record bytes sent to redis
  67. metrics.summary('redis.docLines', docLines.length, { status: 'set' })
  68. logger.debug(
  69. { projectId, docId, version, docHash, pathname, projectHistoryId },
  70. 'putting doc in redis'
  71. )
  72. RedisManager._serializeRanges(ranges, (error, ranges) => {
  73. if (error) {
  74. logger.error({ err: error, docId, projectId }, error.message)
  75. return callback(error)
  76. }
  77. // update docsInProject set before writing doc contents
  78. const multi = rclient.multi()
  79. multi.exists(keys.projectBlock({ project_id: projectId }))
  80. multi.sadd(keys.docsInProject({ project_id: projectId }), docId)
  81. multi.exec((err, reply) => {
  82. if (err) {
  83. return callback(err)
  84. }
  85. const projectBlocked = reply[0] === 1
  86. if (projectBlocked) {
  87. // We don't clean up the spurious docId added in the docsInProject
  88. // set. There is a risk that the docId was successfully added by a
  89. // concurrent process. This set is used when unloading projects. An
  90. // extra docId will not prevent the project from being uploaded, but
  91. // a missing docId means that the doc might stay in Redis forever.
  92. return callback(
  93. new OError('Project blocked from loading docs', { projectId })
  94. )
  95. }
  96. RedisManager.setHistoryRangesSupportFlag(
  97. docId,
  98. historyRangesSupport,
  99. err => {
  100. if (err) {
  101. return callback(err)
  102. }
  103. if (!pathname) {
  104. metrics.inc('pathname', 1, {
  105. path: 'RedisManager.setDoc',
  106. status: pathname === '' ? 'zero-length' : 'undefined',
  107. })
  108. }
  109. // Make sure that this MULTI operation only operates on doc
  110. // specific keys, i.e. keys that have the doc id in curly braces.
  111. // The curly braces identify a hash key for Redis and ensures that
  112. // the MULTI's operations are all done on the same node in a
  113. // cluster environment.
  114. const multi = rclient.multi()
  115. multi.mset({
  116. [keys.docLines({ doc_id: docId })]: docLines,
  117. [keys.projectKey({ doc_id: docId })]: projectId,
  118. [keys.docVersion({ doc_id: docId })]: version,
  119. [keys.docHash({ doc_id: docId })]: docHash,
  120. [keys.ranges({ doc_id: docId })]: ranges,
  121. [keys.pathname({ doc_id: docId })]: pathname,
  122. [keys.projectHistoryId({ doc_id: docId })]: projectHistoryId,
  123. })
  124. if (historyRangesSupport) {
  125. multi.del(keys.resolvedCommentIds({ doc_id: docId }))
  126. if (resolvedCommentIds.length > 0) {
  127. multi.sadd(
  128. keys.resolvedCommentIds({ doc_id: docId }),
  129. ...resolvedCommentIds
  130. )
  131. }
  132. }
  133. multi.exec(err => {
  134. if (err) {
  135. callback(
  136. OError.tag(err, 'failed to write doc to Redis in MULTI', {
  137. previousErrors: err.previousErrors.map(e => ({
  138. name: e.name,
  139. message: e.message,
  140. command: e.command,
  141. })),
  142. })
  143. )
  144. } else {
  145. callback()
  146. }
  147. })
  148. }
  149. )
  150. })
  151. })
  152. },
  153. removeDocFromMemory(projectId, docId, _callback) {
  154. logger.debug({ projectId, docId }, 'removing doc from redis')
  155. const callback = err => {
  156. if (err) {
  157. logger.err({ projectId, docId, err }, 'error removing doc from redis')
  158. _callback(err)
  159. } else {
  160. logger.debug({ projectId, docId }, 'removed doc from redis')
  161. _callback()
  162. }
  163. }
  164. // Make sure that this MULTI operation only operates on doc
  165. // specific keys, i.e. keys that have the doc id in curly braces.
  166. // The curly braces identify a hash key for Redis and ensures that
  167. // the MULTI's operations are all done on the same node in a
  168. // cluster environment.
  169. let multi = rclient.multi()
  170. multi.strlen(keys.docLines({ doc_id: docId }))
  171. multi.del(
  172. keys.docLines({ doc_id: docId }),
  173. keys.projectKey({ doc_id: docId }),
  174. keys.docVersion({ doc_id: docId }),
  175. keys.docHash({ doc_id: docId }),
  176. keys.ranges({ doc_id: docId }),
  177. keys.pathname({ doc_id: docId }),
  178. keys.projectHistoryId({ doc_id: docId }),
  179. keys.unflushedTime({ doc_id: docId }),
  180. keys.lastUpdatedAt({ doc_id: docId }),
  181. keys.lastUpdatedBy({ doc_id: docId }),
  182. keys.resolvedCommentIds({ doc_id: docId })
  183. )
  184. multi.exec((error, response) => {
  185. if (error) {
  186. return callback(error)
  187. }
  188. const length = response?.[0]
  189. if (length > 0) {
  190. // record bytes freed in redis
  191. metrics.summary('redis.docLines', length, { status: 'del' })
  192. }
  193. // Make sure that this MULTI operation only operates on project
  194. // specific keys, i.e. keys that have the project id in curly braces.
  195. // The curly braces identify a hash key for Redis and ensures that
  196. // the MULTI's operations are all done on the same node in a
  197. // cluster environment.
  198. multi = rclient.multi()
  199. multi.srem(keys.docsInProject({ project_id: projectId }), docId)
  200. multi.del(keys.projectState({ project_id: projectId }))
  201. multi.exec(err => {
  202. if (err) {
  203. return callback(err)
  204. }
  205. rclient.srem(keys.historyRangesSupport(), docId, callback)
  206. })
  207. })
  208. },
  209. checkOrSetProjectState(projectId, newState, callback) {
  210. // Make sure that this MULTI operation only operates on project
  211. // specific keys, i.e. keys that have the project id in curly braces.
  212. // The curly braces identify a hash key for Redis and ensures that
  213. // the MULTI's operations are all done on the same node in a
  214. // cluster environment.
  215. const multi = rclient.multi()
  216. multi.getset(keys.projectState({ project_id: projectId }), newState)
  217. multi.expire(keys.projectState({ project_id: projectId }), 30 * minutes)
  218. multi.exec((error, response) => {
  219. if (error) {
  220. return callback(error)
  221. }
  222. logger.debug(
  223. { projectId, newState, oldState: response[0] },
  224. 'checking project state'
  225. )
  226. callback(null, response[0] !== newState)
  227. })
  228. },
  229. clearProjectState(projectId, callback) {
  230. rclient.del(keys.projectState({ project_id: projectId }), callback)
  231. },
  232. getDoc(projectId, docId, callback) {
  233. const timer = new metrics.Timer('redis.get-doc')
  234. const collectKeys = [
  235. keys.docLines({ doc_id: docId }),
  236. keys.docVersion({ doc_id: docId }),
  237. keys.docHash({ doc_id: docId }),
  238. keys.projectKey({ doc_id: docId }),
  239. keys.ranges({ doc_id: docId }),
  240. keys.pathname({ doc_id: docId }),
  241. keys.projectHistoryId({ doc_id: docId }),
  242. keys.unflushedTime({ doc_id: docId }),
  243. keys.lastUpdatedAt({ doc_id: docId }),
  244. keys.lastUpdatedBy({ doc_id: docId }),
  245. ]
  246. rclient.mget(...collectKeys, (error, result) => {
  247. if (error) {
  248. return callback(error)
  249. }
  250. let [
  251. docLines,
  252. version,
  253. storedHash,
  254. docProjectId,
  255. ranges,
  256. pathname,
  257. projectHistoryId,
  258. unflushedTime,
  259. lastUpdatedAt,
  260. lastUpdatedBy,
  261. ] = result
  262. rclient.sismember(keys.historyRangesSupport(), docId, (error, result) => {
  263. if (error) {
  264. return callback(error)
  265. }
  266. rclient.smembers(
  267. keys.resolvedCommentIds({ doc_id: docId }),
  268. (error, resolvedCommentIds) => {
  269. if (error) {
  270. return callback(error)
  271. }
  272. const historyRangesSupport = result === 1
  273. const timeSpan = timer.done()
  274. // check if request took too long and bail out. only do this for
  275. // get, because it is the first call in each update, so if this
  276. // passes we'll assume others have a reasonable chance to succeed.
  277. if (timeSpan > MAX_REDIS_REQUEST_LENGTH) {
  278. error = new Error('redis getDoc exceeded timeout')
  279. return callback(error)
  280. }
  281. // record bytes loaded from redis
  282. if (docLines != null) {
  283. metrics.summary('redis.docLines', docLines.length, {
  284. status: 'get',
  285. })
  286. }
  287. // check sha1 hash value if present
  288. if (docLines != null && storedHash != null) {
  289. const computedHash = RedisManager._computeHash(docLines)
  290. if (logHashReadErrors && computedHash !== storedHash) {
  291. logger.error(
  292. {
  293. projectId,
  294. docId,
  295. docProjectId,
  296. computedHash,
  297. storedHash,
  298. docLines,
  299. },
  300. 'hash mismatch on retrieved document'
  301. )
  302. }
  303. }
  304. try {
  305. docLines = JSON.parse(docLines)
  306. ranges = RedisManager._deserializeRanges(ranges)
  307. } catch (e) {
  308. return callback(e)
  309. }
  310. version = parseInt(version || 0, 10)
  311. // check doc is in requested project
  312. if (docProjectId != null && docProjectId !== projectId) {
  313. logger.error(
  314. { projectId, docId, docProjectId },
  315. 'doc not in project'
  316. )
  317. return callback(new Errors.NotFoundError('document not found'))
  318. }
  319. if (docLines && version && !pathname) {
  320. metrics.inc('pathname', 1, {
  321. path: 'RedisManager.getDoc',
  322. status: pathname === '' ? 'zero-length' : 'undefined',
  323. })
  324. }
  325. callback(
  326. null,
  327. docLines,
  328. version,
  329. ranges,
  330. pathname,
  331. projectHistoryId,
  332. unflushedTime,
  333. lastUpdatedAt,
  334. lastUpdatedBy,
  335. historyRangesSupport,
  336. resolvedCommentIds
  337. )
  338. }
  339. )
  340. })
  341. })
  342. },
  343. getDocVersion(docId, callback) {
  344. rclient.mget(keys.docVersion({ doc_id: docId }), (error, result) => {
  345. if (error) {
  346. return callback(error)
  347. }
  348. let [version] = result || []
  349. version = parseInt(version, 10)
  350. callback(null, version)
  351. })
  352. },
  353. getDocLines(docId, callback) {
  354. rclient.get(keys.docLines({ doc_id: docId }), (error, docLines) => {
  355. if (error) {
  356. return callback(error)
  357. }
  358. callback(null, docLines)
  359. })
  360. },
  361. getPreviousDocOps(docId, start, end, callback) {
  362. const timer = new metrics.Timer('redis.get-prev-docops')
  363. rclient.llen(keys.docOps({ doc_id: docId }), (error, length) => {
  364. if (error) {
  365. return callback(error)
  366. }
  367. rclient.get(keys.docVersion({ doc_id: docId }), (error, version) => {
  368. if (error) {
  369. return callback(error)
  370. }
  371. version = parseInt(version, 10)
  372. const firstVersionInRedis = version - length
  373. if (start < firstVersionInRedis || end > version) {
  374. error = new Errors.OpRangeNotAvailableError(
  375. 'doc ops range is not loaded in redis',
  376. { firstVersionInRedis, version, ttlInS: RedisManager.DOC_OPS_TTL }
  377. )
  378. logger.debug(
  379. { err: error, docId, length, version, start, end },
  380. 'doc ops range is not loaded in redis'
  381. )
  382. return callback(error)
  383. }
  384. start = start - firstVersionInRedis
  385. if (end > -1) {
  386. end = end - firstVersionInRedis
  387. }
  388. if (isNaN(start) || isNaN(end)) {
  389. error = new Error('inconsistent version or lengths')
  390. logger.error(
  391. { err: error, docId, length, version, start, end },
  392. 'inconsistent version or length'
  393. )
  394. return callback(error)
  395. }
  396. rclient.lrange(
  397. keys.docOps({ doc_id: docId }),
  398. start,
  399. end,
  400. (error, jsonOps) => {
  401. let ops
  402. if (error) {
  403. return callback(error)
  404. }
  405. try {
  406. ops = jsonOps.map(jsonOp => JSON.parse(jsonOp))
  407. } catch (e) {
  408. return callback(e)
  409. }
  410. const timeSpan = timer.done()
  411. if (timeSpan > MAX_REDIS_REQUEST_LENGTH) {
  412. error = new Error('redis getPreviousDocOps exceeded timeout')
  413. return callback(error)
  414. }
  415. callback(null, ops)
  416. }
  417. )
  418. })
  419. })
  420. },
  421. DOC_OPS_TTL: 60 * minutes,
  422. DOC_OPS_MAX_LENGTH: 100,
  423. updateDocument(
  424. projectId,
  425. docId,
  426. docLines,
  427. newVersion,
  428. appliedOps,
  429. ranges,
  430. updateMeta,
  431. callback
  432. ) {
  433. if (appliedOps == null) {
  434. appliedOps = []
  435. }
  436. const shareJSTextOT = Array.isArray(docLines)
  437. RedisManager.getDocVersion(docId, (error, currentVersion) => {
  438. if (error) {
  439. return callback(error)
  440. }
  441. if (currentVersion + appliedOps.length !== newVersion) {
  442. error = new Error(`Version mismatch. '${docId}' is corrupted.`)
  443. logger.error(
  444. {
  445. err: error,
  446. docId,
  447. currentVersion,
  448. newVersion,
  449. opsLength: appliedOps.length,
  450. },
  451. 'version mismatch'
  452. )
  453. return callback(error)
  454. }
  455. const jsonOps = appliedOps.map(op => JSON.stringify(op))
  456. for (const op of jsonOps) {
  457. if (op.indexOf('\u0000') !== -1) {
  458. error = new Error('null bytes found in jsonOps')
  459. // this check was added to catch memory corruption in JSON.stringify
  460. logger.error({ err: error, docId, jsonOps }, error.message)
  461. return callback(error)
  462. }
  463. }
  464. const newDocLines = JSON.stringify(docLines)
  465. if (newDocLines.indexOf('\u0000') !== -1) {
  466. error = new Error('null bytes found in doc lines')
  467. // this check was added to catch memory corruption in JSON.stringify
  468. logger.error({ err: error, docId, newDocLines }, error.message)
  469. return callback(error)
  470. }
  471. // Do an optimised size check on the docLines using the serialised
  472. // length as an upper bound
  473. const sizeBound = newDocLines.length
  474. if (
  475. shareJSTextOT && // editor-core has a size check in TextOperation.apply and TextOperation.applyToLength.
  476. docIsTooLarge(sizeBound, docLines, Settings.max_doc_length)
  477. ) {
  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. async cleanupTestRedis() {
  732. await RedisWrapper.cleanupTestRedis(rclient)
  733. },
  734. }
  735. module.exports = RedisManager
  736. module.exports.promises = promisifyAll(RedisManager, {
  737. without: ['_deserializeRanges', '_computeHash'],
  738. multiResult: {
  739. getDoc: [
  740. 'lines',
  741. 'version',
  742. 'ranges',
  743. 'pathname',
  744. 'projectHistoryId',
  745. 'unflushedTime',
  746. 'lastUpdatedAt',
  747. 'lastUpdatedBy',
  748. 'historyRangesSupport',
  749. 'resolvedCommentIds',
  750. ],
  751. getNextProjectToFlushAndDelete: [
  752. 'projectId',
  753. 'flushTimestamp',
  754. 'queueLength',
  755. ],
  756. },
  757. })