HistoryStoreManager.js 16 KB

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