HistoryStoreManager.js 17 KB

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