RedisManager.js 20 KB

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