RedisManager.js 19 KB

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