RedisManager.js 20 KB

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