RedisManager.js 21 KB

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