HistoryStoreManager.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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. const url = `${Settings.overleaf.history.host}/projects/${historyId}/blobs/${hash}`
  236. fetchNothing(url, {
  237. method: 'HEAD',
  238. ...getHistoryFetchOptions(),
  239. })
  240. .then(res => {
  241. callback(null, true)
  242. })
  243. .catch(err => {
  244. if (err instanceof RequestFailedError) {
  245. return callback(null, false)
  246. }
  247. callback(OError.tag(err), false)
  248. })
  249. }
  250. function _rewriteFilestoreUrl(url, projectId, callback) {
  251. if (!url) {
  252. return { fileId: null, filestoreURL: null }
  253. }
  254. // Rewrite the filestore url to point to the location in the local
  255. // settings for this service (this avoids problems with cross-
  256. // datacentre requests when running filestore in multiple locations).
  257. const { pathname: fileStorePath } = new URL(url)
  258. const urlMatch = /^\/project\/([0-9a-f]{24})\/file\/([0-9a-f]{24})$/.exec(
  259. fileStorePath
  260. )
  261. if (urlMatch == null) {
  262. return callback(new OError('invalid file for blob creation'))
  263. }
  264. if (urlMatch[1] !== projectId) {
  265. return callback(new OError('invalid project for blob creation'))
  266. }
  267. const fileId = urlMatch[2]
  268. const filestoreURL = `${Settings.apis.filestore.url}/project/${projectId}/file/${fileId}`
  269. return { filestoreURL, fileId }
  270. }
  271. export function createBlobForUpdate(projectId, historyId, update, callback) {
  272. callback = _.once(callback)
  273. if (update.doc != null && update.docLines != null) {
  274. let ranges
  275. try {
  276. ranges = HistoryBlobTranslator.createRangeBlobDataFromUpdate(update)
  277. } catch (error) {
  278. return callback(error)
  279. }
  280. createBlobFromString(
  281. historyId,
  282. update.docLines,
  283. `project-${projectId}-doc-${update.doc}`,
  284. (err, fileHash) => {
  285. if (err) {
  286. return callback(err)
  287. }
  288. if (ranges) {
  289. createBlobFromString(
  290. historyId,
  291. JSON.stringify(ranges),
  292. `project-${projectId}-doc-${update.doc}-ranges`,
  293. (err, rangesHash) => {
  294. if (err) {
  295. return callback(err)
  296. }
  297. logger.debug(
  298. { fileHash, rangesHash },
  299. 'created blobs for both ranges and content'
  300. )
  301. return callback(null, { file: fileHash, ranges: rangesHash })
  302. }
  303. )
  304. } else {
  305. logger.debug({ fileHash }, 'created blob for content')
  306. return callback(null, { file: fileHash })
  307. }
  308. }
  309. )
  310. } else if (
  311. update.file != null &&
  312. (update.url != null || update.createdBlob)
  313. ) {
  314. const { fileId, filestoreURL } = _rewriteFilestoreUrl(
  315. update.url,
  316. projectId,
  317. callback
  318. )
  319. _checkBlobExists(historyId, update.hash, (err, blobExists) => {
  320. if (err) {
  321. logger.warn(
  322. { err, projectId, fileId, update },
  323. 'error checking whether blob exists, reading from filestore'
  324. )
  325. } else if (update.createdBlob && blobExists) {
  326. logger.debug(
  327. { projectId, fileId, update },
  328. 'Skipping blob creation as it has already been created'
  329. )
  330. return callback(null, { file: update.hash })
  331. } else if (update.createdBlob) {
  332. logger.warn(
  333. { projectId, fileId, update },
  334. 'created blob does not exist, reading from filestore'
  335. )
  336. }
  337. if (!filestoreURL) {
  338. return callback(
  339. new OError('no filestore URL provided and blob was not created')
  340. )
  341. }
  342. fetchStream(filestoreURL, {
  343. signal: AbortSignal.timeout(HTTP_REQUEST_TIMEOUT),
  344. })
  345. .then(stream => {
  346. LocalFileWriter.bufferOnDisk(
  347. stream,
  348. filestoreURL,
  349. `project-${projectId}-file-${fileId}`,
  350. (fsPath, cb) => {
  351. _createBlob(historyId, fsPath, cb)
  352. },
  353. (err, fileHash) => {
  354. if (err) {
  355. return callback(err)
  356. }
  357. if (update.hash && update.hash !== fileHash) {
  358. logger.warn(
  359. { projectId, fileId, webHash: update.hash, fileHash },
  360. 'hash mismatch between web and project-history'
  361. )
  362. }
  363. logger.debug({ fileHash }, 'created blob for file')
  364. callback(null, { file: fileHash })
  365. }
  366. )
  367. })
  368. .catch(err => {
  369. if (
  370. err instanceof RequestFailedError &&
  371. err.response.status === 404
  372. ) {
  373. logger.warn(
  374. { projectId, historyId, filestoreURL },
  375. 'File contents not found in filestore. Storing in history as an empty file'
  376. )
  377. const emptyStream = new StringStream()
  378. LocalFileWriter.bufferOnDisk(
  379. emptyStream,
  380. filestoreURL,
  381. `project-${projectId}-file-${fileId}`,
  382. (fsPath, cb) => {
  383. _createBlob(historyId, fsPath, cb)
  384. },
  385. (err, fileHash) => {
  386. if (err) {
  387. return callback(err)
  388. }
  389. logger.debug({ fileHash }, 'created empty blob for file')
  390. callback(null, { file: fileHash })
  391. }
  392. )
  393. emptyStream.push(null) // send an EOF signal
  394. } else {
  395. callback(OError.tag(err, 'error from filestore', { filestoreURL }))
  396. }
  397. })
  398. })
  399. } else {
  400. const error = new OError('invalid update for blob creation')
  401. callback(error)
  402. }
  403. }
  404. function _createBlob(historyId, fsPath, _callback) {
  405. const callback = _.once(_callback)
  406. HashManager._getBlobHash(fsPath, (error, hash, byteLength) => {
  407. if (error) {
  408. return callback(OError.tag(error))
  409. }
  410. const outStream = fs.createReadStream(fsPath)
  411. logger.debug(
  412. { fsPath, historyId, hash, byteLength },
  413. 'sending blob to history service'
  414. )
  415. const url = `${Settings.overleaf.history.host}/projects/${historyId}/blobs/${hash}`
  416. fetchNothing(url, {
  417. method: 'PUT',
  418. body: outStream,
  419. headers: { 'Content-Length': byteLength }, // add the content length to work around problems with chunked encoding in node 18
  420. ...getHistoryFetchOptions(),
  421. })
  422. .then(res => {
  423. callback(null, hash)
  424. })
  425. .catch(err => {
  426. callback(OError.tag(err))
  427. })
  428. })
  429. }
  430. export function initializeProject(historyId, callback) {
  431. _requestHistoryService(
  432. {
  433. method: 'POST',
  434. path: 'projects',
  435. json: historyId == null ? true : { projectId: historyId },
  436. },
  437. (error, project) => {
  438. if (error) {
  439. return callback(OError.tag(error))
  440. }
  441. const id = project.projectId
  442. if (id == null) {
  443. error = new OError('history store did not return a project id', id)
  444. return callback(error)
  445. }
  446. callback(null, id)
  447. }
  448. )
  449. }
  450. export function deleteProject(projectId, callback) {
  451. _requestHistoryService(
  452. { method: 'DELETE', path: `projects/${projectId}` },
  453. callback
  454. )
  455. }
  456. const getProjectBlobAsync = promisify(getProjectBlob)
  457. class BlobStore {
  458. constructor(projectId) {
  459. this.projectId = projectId
  460. }
  461. async getString(hash) {
  462. return await getProjectBlobAsync(this.projectId, hash)
  463. }
  464. async getObject(hash) {
  465. const string = await this.getString(hash)
  466. return JSON.parse(string)
  467. }
  468. }
  469. export function getBlobStore(projectId) {
  470. return new BlobStore(projectId)
  471. }
  472. function _requestOptions(options) {
  473. const requestOptions = {
  474. method: options.method || 'GET',
  475. url: `${Settings.overleaf.history.host}/${options.path}`,
  476. timeout: HTTP_REQUEST_TIMEOUT,
  477. auth: {
  478. user: Settings.overleaf.history.user,
  479. pass: Settings.overleaf.history.pass,
  480. sendImmediately: true,
  481. },
  482. }
  483. if (options.json != null) {
  484. requestOptions.json = options.json
  485. }
  486. if (options.body != null) {
  487. requestOptions.body = options.body
  488. }
  489. if (options.qs != null) {
  490. requestOptions.qs = options.qs
  491. }
  492. return requestOptions
  493. }
  494. /**
  495. * @return {RequestInit}
  496. */
  497. function getHistoryFetchOptions() {
  498. return {
  499. signal: AbortSignal.timeout(HTTP_REQUEST_TIMEOUT),
  500. basicAuth: {
  501. user: Settings.overleaf.history.user,
  502. password: Settings.overleaf.history.pass,
  503. },
  504. }
  505. }
  506. function _requestHistoryService(options, callback) {
  507. const requestOptions = _requestOptions(options)
  508. request(requestOptions, (error, res, body) => {
  509. if (error) {
  510. return callback(OError.tag(error))
  511. }
  512. if (res.statusCode >= 200 && res.statusCode < 300) {
  513. callback(null, body)
  514. } else {
  515. error = new OError(
  516. `history store a non-success status code: ${res.statusCode}`
  517. )
  518. error.statusCode = res.statusCode
  519. error.body = body
  520. logger.warn({ err: error }, error.message)
  521. callback(error)
  522. }
  523. })
  524. }
  525. export const promises = {
  526. getMostRecentChunk: promisify(getMostRecentChunk),
  527. getChunkAtVersion: promisify(getChunkAtVersion),
  528. getMostRecentVersion: promisify(getMostRecentVersion),
  529. getProjectBlob: promisify(getProjectBlob),
  530. getProjectBlobStream: promisify(getProjectBlobStream),
  531. sendChanges: promisify(sendChanges),
  532. createBlobForUpdate: promisify(createBlobForUpdate),
  533. initializeProject: promisify(initializeProject),
  534. deleteProject: promisify(deleteProject),
  535. }