HistoryStoreManager.js 18 KB

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