RedisManager.js 20 KB

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