RedisManager.js 20 KB

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