HistoryStoreManager.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. import { promisify } from 'node:util'
  2. import fs from 'node:fs'
  3. import request from 'request'
  4. import stream from 'node:stream'
  5. import logger from '@overleaf/logger'
  6. import _ from 'lodash'
  7. import { URL } from 'node:url'
  8. import OError from '@overleaf/o-error'
  9. import Settings from '@overleaf/settings'
  10. import {
  11. fetchStream,
  12. fetchNothing,
  13. RequestFailedError,
  14. } from '@overleaf/fetch-utils'
  15. import * as Versions from './Versions.js'
  16. import * as Errors from './Errors.js'
  17. import * as LocalFileWriter from './LocalFileWriter.js'
  18. import * as HashManager from './HashManager.js'
  19. import * as HistoryBlobTranslator from './HistoryBlobTranslator.js'
  20. const HTTP_REQUEST_TIMEOUT = Settings.overleaf.history.requestTimeout
  21. /**
  22. * Container for functions that need to be mocked in tests
  23. *
  24. * TODO: Rewrite tests in terms of exported functions only
  25. */
  26. export const _mocks = {}
  27. class StringStream extends stream.Readable {
  28. _read() {}
  29. }
  30. _mocks.getMostRecentChunk = (projectId, historyId, callback) => {
  31. const path = `projects/${historyId}/latest/history`
  32. logger.debug({ projectId, historyId }, 'getting chunk from history service')
  33. _requestChunk({ path, json: true }, callback)
  34. }
  35. /**
  36. * @param {Callback} callback
  37. */
  38. export function getMostRecentChunk(projectId, historyId, callback) {
  39. _mocks.getMostRecentChunk(projectId, historyId, callback)
  40. }
  41. /**
  42. * @param {Callback} callback
  43. */
  44. export function getChunkAtVersion(projectId, historyId, version, callback) {
  45. const path = `projects/${historyId}/versions/${version}/history`
  46. logger.debug(
  47. { projectId, historyId, version },
  48. 'getting chunk from history service for version'
  49. )
  50. _requestChunk({ path, json: true }, callback)
  51. }
  52. export function getMostRecentVersion(projectId, historyId, callback) {
  53. getMostRecentChunk(projectId, historyId, (error, chunk) => {
  54. if (error) {
  55. return callback(OError.tag(error))
  56. }
  57. const mostRecentVersion =
  58. chunk.chunk.startVersion + (chunk.chunk.history.changes || []).length
  59. const lastChange = _.last(
  60. _.sortBy(chunk.chunk.history.changes || [], x => x.timestamp)
  61. )
  62. // find the latest project and doc versions in the chunk
  63. _getLatestProjectVersion(projectId, chunk, (err1, projectVersion) =>
  64. _getLatestV2DocVersions(projectId, chunk, (err2, v2DocVersions) => {
  65. // return the project and doc versions
  66. const projectStructureAndDocVersions = {
  67. project: projectVersion,
  68. docs: v2DocVersions,
  69. }
  70. callback(
  71. err1 || err2,
  72. mostRecentVersion,
  73. projectStructureAndDocVersions,
  74. lastChange
  75. )
  76. })
  77. )
  78. })
  79. }
  80. function _requestChunk(options, callback) {
  81. _requestHistoryService(options, (err, chunk) => {
  82. if (err) {
  83. return callback(OError.tag(err))
  84. }
  85. if (
  86. chunk == null ||
  87. chunk.chunk == null ||
  88. chunk.chunk.startVersion == null
  89. ) {
  90. return callback(new OError('unexpected response'))
  91. }
  92. callback(null, chunk)
  93. })
  94. }
  95. function _getLatestProjectVersion(projectId, chunk, callback) {
  96. // find the initial project version
  97. let projectVersion =
  98. chunk.chunk.history.snapshot && chunk.chunk.history.snapshot.projectVersion
  99. // keep track of any errors
  100. let error = null
  101. // iterate over the changes in chunk to find the most recent project version
  102. for (const change of chunk.chunk.history.changes || []) {
  103. if (change.projectVersion != null) {
  104. if (
  105. projectVersion != null &&
  106. Versions.lt(change.projectVersion, projectVersion)
  107. ) {
  108. logger.warn(
  109. { projectId, chunk, projectVersion, change },
  110. 'project structure version out of order in chunk'
  111. )
  112. if (!error) {
  113. error = new Errors.OpsOutOfOrderError(
  114. 'project structure version out of order'
  115. )
  116. }
  117. } else {
  118. projectVersion = change.projectVersion
  119. }
  120. }
  121. }
  122. callback(error, projectVersion)
  123. }
  124. function _getLatestV2DocVersions(projectId, chunk, callback) {
  125. // find the initial doc versions (indexed by docId as this is immutable)
  126. const v2DocVersions =
  127. (chunk.chunk.history.snapshot &&
  128. chunk.chunk.history.snapshot.v2DocVersions) ||
  129. {}
  130. // keep track of any errors
  131. let error = null
  132. // iterate over the changes in the chunk to find the most recent doc versions
  133. for (const change of chunk.chunk.history.changes || []) {
  134. if (change.v2DocVersions != null) {
  135. for (const docId in change.v2DocVersions) {
  136. const docInfo = change.v2DocVersions[docId]
  137. const { v } = docInfo
  138. if (
  139. v2DocVersions[docId] &&
  140. v2DocVersions[docId].v != null &&
  141. Versions.lt(v, v2DocVersions[docId].v)
  142. ) {
  143. logger.warn(
  144. {
  145. projectId,
  146. docId,
  147. changeVersion: docInfo,
  148. previousVersion: v2DocVersions[docId],
  149. },
  150. 'doc version out of order in chunk'
  151. )
  152. if (!error) {
  153. error = new Errors.OpsOutOfOrderError('doc version out of order')
  154. }
  155. } else {
  156. v2DocVersions[docId] = docInfo
  157. }
  158. }
  159. }
  160. }
  161. callback(error, v2DocVersions)
  162. }
  163. export function getProjectBlob(historyId, blobHash, callback) {
  164. logger.debug({ historyId, blobHash }, 'getting blob from history service')
  165. _requestHistoryService(
  166. { path: `projects/${historyId}/blobs/${blobHash}` },
  167. callback
  168. )
  169. }
  170. /**
  171. * @param {Callback} callback
  172. */
  173. export function getProjectBlobStream(historyId, blobHash, callback) {
  174. const url = `${Settings.overleaf.history.host}/projects/${historyId}/blobs/${blobHash}`
  175. logger.debug(
  176. { historyId, blobHash },
  177. 'getting blob stream from history service'
  178. )
  179. fetchStream(url, getHistoryFetchOptions())
  180. .then(stream => {
  181. callback(null, stream)
  182. })
  183. .catch(err => callback(OError.tag(err)))
  184. }
  185. export function sendChanges(
  186. projectId,
  187. historyId,
  188. changes,
  189. endVersion,
  190. callback
  191. ) {
  192. logger.debug(
  193. { projectId, historyId, endVersion },
  194. 'sending changes to history service'
  195. )
  196. _requestHistoryService(
  197. {
  198. path: `projects/${historyId}/legacy_changes`,
  199. qs: { end_version: endVersion },
  200. method: 'POST',
  201. json: changes,
  202. },
  203. error => {
  204. if (error) {
  205. OError.tag(error, 'failed to send changes to v1', {
  206. projectId,
  207. historyId,
  208. endVersion,
  209. errorCode: error.code,
  210. statusCode: error.statusCode,
  211. body: error.body,
  212. })
  213. logger.warn(error)
  214. return callback(error)
  215. }
  216. callback()
  217. }
  218. )
  219. }
  220. function createBlobFromString(historyId, data, fileId, callback) {
  221. const stringStream = new StringStream()
  222. stringStream.push(data)
  223. stringStream.push(null)
  224. LocalFileWriter.bufferOnDisk(
  225. stringStream,
  226. '',
  227. fileId,
  228. (fsPath, cb) => {
  229. _createBlob(historyId, fsPath, cb)
  230. },
  231. callback
  232. )
  233. }
  234. function _checkBlobExists(historyId, hash, callback) {
  235. if (!hash) return callback(null, false)
  236. const url = `${Settings.overleaf.history.host}/projects/${historyId}/blobs/${hash}`
  237. fetchNothing(url, {
  238. method: 'HEAD',
  239. ...getHistoryFetchOptions(),
  240. })
  241. .then(res => {
  242. callback(null, true)
  243. })
  244. .catch(err => {
  245. if (err instanceof RequestFailedError && err.response.status === 404) {
  246. return callback(null, false)
  247. }
  248. callback(OError.tag(err), false)
  249. })
  250. }
  251. function _rewriteFilestoreUrl(url, projectId, callback) {
  252. if (!url) {
  253. return { fileId: null, filestoreURL: null }
  254. }
  255. // Rewrite the filestore url to point to the location in the local
  256. // settings for this service (this avoids problems with cross-
  257. // datacentre requests when running filestore in multiple locations).
  258. const { pathname: fileStorePath } = new URL(url)
  259. const urlMatch = /^\/project\/([0-9a-f]{24})\/file\/([0-9a-f]{24})$/.exec(
  260. fileStorePath
  261. )
  262. if (urlMatch == null) {
  263. return callback(new OError('invalid file for blob creation'))
  264. }
  265. if (urlMatch[1] !== projectId) {
  266. return callback(new OError('invalid project for blob creation'))
  267. }
  268. const fileId = urlMatch[2]
  269. const filestoreURL = `${Settings.apis.filestore.url}/project/${projectId}/file/${fileId}`
  270. return { filestoreURL, fileId }
  271. }
  272. export function createBlobForUpdate(projectId, historyId, update, callback) {
  273. callback = _.once(callback)
  274. if (update.doc != null && update.docLines != null) {
  275. let ranges
  276. try {
  277. ranges = HistoryBlobTranslator.createRangeBlobDataFromUpdate(update)
  278. } catch (error) {
  279. return callback(error)
  280. }
  281. createBlobFromString(
  282. historyId,
  283. update.docLines,
  284. `project-${projectId}-doc-${update.doc}`,
  285. (err, fileHash) => {
  286. if (err) {
  287. return callback(err)
  288. }
  289. if (ranges) {
  290. createBlobFromString(
  291. historyId,
  292. JSON.stringify(ranges),
  293. `project-${projectId}-doc-${update.doc}-ranges`,
  294. (err, rangesHash) => {
  295. if (err) {
  296. return callback(err)
  297. }
  298. logger.debug(
  299. { fileHash, rangesHash },
  300. 'created blobs for both ranges and content'
  301. )
  302. return callback(null, { file: fileHash, ranges: rangesHash })
  303. }
  304. )
  305. } else {
  306. logger.debug({ fileHash }, 'created blob for content')
  307. return callback(null, { file: fileHash })
  308. }
  309. }
  310. )
  311. } else if (
  312. update.file != null &&
  313. (update.url != null || update.createdBlob)
  314. ) {
  315. const { fileId, filestoreURL } = _rewriteFilestoreUrl(
  316. update.url,
  317. projectId,
  318. callback
  319. )
  320. _checkBlobExists(historyId, update.hash, (err, blobExists) => {
  321. if (err) {
  322. return callback(
  323. new OError(
  324. 'error checking whether blob exists',
  325. { projectId, historyId, update },
  326. err
  327. )
  328. )
  329. } else if (blobExists) {
  330. logger.debug(
  331. { projectId, fileId, update },
  332. 'Skipping blob creation as it has already been created'
  333. )
  334. return callback(null, { file: update.hash })
  335. } else if (update.createdBlob) {
  336. logger.warn(
  337. { projectId, fileId, update },
  338. 'created blob does not exist, reading from filestore'
  339. )
  340. }
  341. if (!filestoreURL) {
  342. return callback(
  343. new OError('no filestore URL provided and blob was not created')
  344. )
  345. }
  346. if (!Settings.apis.filestore.enabled) {
  347. return callback(new OError('blocking filestore read', { update }))
  348. }
  349. fetchStream(filestoreURL, {
  350. signal: AbortSignal.timeout(HTTP_REQUEST_TIMEOUT),
  351. })
  352. .then(stream => {
  353. LocalFileWriter.bufferOnDisk(
  354. stream,
  355. filestoreURL,
  356. `project-${projectId}-file-${fileId}`,
  357. (fsPath, cb) => {
  358. _createBlob(historyId, fsPath, cb)
  359. },
  360. (err, fileHash) => {
  361. if (err) {
  362. return callback(err)
  363. }
  364. if (update.hash && update.hash !== fileHash) {
  365. logger.warn(
  366. { projectId, fileId, webHash: update.hash, fileHash },
  367. 'hash mismatch between web and project-history'
  368. )
  369. }
  370. logger.debug({ fileHash }, 'created blob for file')
  371. callback(null, { file: fileHash })
  372. }
  373. )
  374. })
  375. .catch(err => {
  376. if (
  377. err instanceof RequestFailedError &&
  378. err.response.status === 404
  379. ) {
  380. logger.warn(
  381. { projectId, historyId, filestoreURL },
  382. 'File contents not found in filestore. Storing in history as an empty file'
  383. )
  384. const emptyStream = new StringStream()
  385. LocalFileWriter.bufferOnDisk(
  386. emptyStream,
  387. filestoreURL,
  388. `project-${projectId}-file-${fileId}`,
  389. (fsPath, cb) => {
  390. _createBlob(historyId, fsPath, cb)
  391. },
  392. (err, fileHash) => {
  393. if (err) {
  394. return callback(err)
  395. }
  396. logger.debug({ fileHash }, 'created empty blob for file')
  397. callback(null, { file: fileHash })
  398. }
  399. )
  400. emptyStream.push(null) // send an EOF signal
  401. } else {
  402. callback(OError.tag(err, 'error from filestore', { filestoreURL }))
  403. }
  404. })
  405. })
  406. } else {
  407. const error = new OError('invalid update for blob creation')
  408. callback(error)
  409. }
  410. }
  411. function _createBlob(historyId, fsPath, _callback) {
  412. const callback = _.once(_callback)
  413. HashManager._getBlobHash(fsPath, (error, hash, byteLength) => {
  414. if (error) {
  415. return callback(OError.tag(error))
  416. }
  417. const outStream = fs.createReadStream(fsPath)
  418. logger.debug(
  419. { fsPath, historyId, hash, byteLength },
  420. 'sending blob to history service'
  421. )
  422. const url = `${Settings.overleaf.history.host}/projects/${historyId}/blobs/${hash}`
  423. fetchNothing(url, {
  424. method: 'PUT',
  425. body: outStream,
  426. headers: { 'Content-Length': byteLength }, // add the content length to work around problems with chunked encoding in node 18
  427. ...getHistoryFetchOptions(),
  428. })
  429. .then(res => {
  430. callback(null, hash)
  431. })
  432. .catch(err => {
  433. callback(OError.tag(err))
  434. })
  435. })
  436. }
  437. export function initializeProject(historyId, callback) {
  438. _requestHistoryService(
  439. {
  440. method: 'POST',
  441. path: 'projects',
  442. json: historyId == null ? true : { projectId: historyId },
  443. },
  444. (error, project) => {
  445. if (error) {
  446. return callback(OError.tag(error))
  447. }
  448. const id = project.projectId
  449. if (id == null) {
  450. error = new OError('history store did not return a project id', id)
  451. return callback(error)
  452. }
  453. callback(null, id)
  454. }
  455. )
  456. }
  457. export function deleteProject(projectId, callback) {
  458. _requestHistoryService(
  459. { method: 'DELETE', path: `projects/${projectId}` },
  460. callback
  461. )
  462. }
  463. const getProjectBlobAsync = promisify(getProjectBlob)
  464. class BlobStore {
  465. constructor(projectId) {
  466. this.projectId = projectId
  467. }
  468. async getString(hash) {
  469. return await getProjectBlobAsync(this.projectId, hash)
  470. }
  471. async getObject(hash) {
  472. const string = await this.getString(hash)
  473. return JSON.parse(string)
  474. }
  475. }
  476. export function getBlobStore(projectId) {
  477. return new BlobStore(projectId)
  478. }
  479. function _requestOptions(options) {
  480. const requestOptions = {
  481. method: options.method || 'GET',
  482. url: `${Settings.overleaf.history.host}/${options.path}`,
  483. timeout: HTTP_REQUEST_TIMEOUT,
  484. auth: {
  485. user: Settings.overleaf.history.user,
  486. pass: Settings.overleaf.history.pass,
  487. sendImmediately: true,
  488. },
  489. }
  490. if (options.json != null) {
  491. requestOptions.json = options.json
  492. }
  493. if (options.body != null) {
  494. requestOptions.body = options.body
  495. }
  496. if (options.qs != null) {
  497. requestOptions.qs = options.qs
  498. }
  499. return requestOptions
  500. }
  501. /**
  502. * @return {RequestInit}
  503. */
  504. function getHistoryFetchOptions() {
  505. return {
  506. signal: AbortSignal.timeout(HTTP_REQUEST_TIMEOUT),
  507. basicAuth: {
  508. user: Settings.overleaf.history.user,
  509. password: Settings.overleaf.history.pass,
  510. },
  511. }
  512. }
  513. function _requestHistoryService(options, callback) {
  514. const requestOptions = _requestOptions(options)
  515. request(requestOptions, (error, res, body) => {
  516. if (error) {
  517. return callback(OError.tag(error))
  518. }
  519. if (res.statusCode >= 200 && res.statusCode < 300) {
  520. callback(null, body)
  521. } else {
  522. const { method, url, qs } = requestOptions
  523. error = new OError(
  524. `history store a non-success status code: ${res.statusCode}`,
  525. { method, url, qs, statusCode: res.statusCode }
  526. )
  527. logger.warn({ err: error }, error.message)
  528. callback(error)
  529. }
  530. })
  531. }
  532. export const promises = {
  533. getMostRecentChunk: promisify(getMostRecentChunk),
  534. getChunkAtVersion: promisify(getChunkAtVersion),
  535. getMostRecentVersion: promisify(getMostRecentVersion),
  536. getProjectBlob: promisify(getProjectBlob),
  537. getProjectBlobStream: promisify(getProjectBlobStream),
  538. sendChanges: promisify(sendChanges),
  539. createBlobForUpdate: promisify(createBlobForUpdate),
  540. initializeProject: promisify(initializeProject),
  541. deleteProject: promisify(deleteProject),
  542. }