RedisManager.js 26 KB

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