HistoryStoreManager.js 16 KB

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