HistoryStoreManager.js 14 KB

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