HistoryStoreManager.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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.apis.history_v1.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. logger.debug({ fileHash }, 'created blob for file')
  305. callback(null, { file: fileHash })
  306. }
  307. )
  308. })
  309. .catch(err => {
  310. if (err instanceof RequestFailedError && err.response.status === 404) {
  311. logger.warn(
  312. { projectId, historyId, filestoreURL },
  313. 'File contents not found in filestore. Storing in history as an empty file'
  314. )
  315. const emptyStream = new StringStream()
  316. LocalFileWriter.bufferOnDisk(
  317. emptyStream,
  318. filestoreURL,
  319. `project-${projectId}-file-${fileId}`,
  320. (fsPath, cb) => {
  321. _createBlob(historyId, fsPath, cb)
  322. },
  323. (err, fileHash) => {
  324. if (err) {
  325. return callback(err)
  326. }
  327. logger.debug({ fileHash }, 'created empty blob for file')
  328. callback(null, { file: fileHash })
  329. }
  330. )
  331. emptyStream.push(null) // send an EOF signal
  332. } else {
  333. callback(OError.tag(err, 'error from filestore', { filestoreURL }))
  334. }
  335. })
  336. } else {
  337. const error = new OError('invalid update for blob creation')
  338. callback(error)
  339. }
  340. }
  341. function _createBlob(historyId, fsPath, _callback) {
  342. const callback = _.once(_callback)
  343. HashManager._getBlobHash(fsPath, (error, hash, byteLength) => {
  344. if (error) {
  345. return callback(OError.tag(error))
  346. }
  347. const outStream = fs.createReadStream(fsPath)
  348. logger.debug(
  349. { fsPath, historyId, hash, byteLength },
  350. 'sending blob to history service'
  351. )
  352. const url = `${Settings.overleaf.history.host}/projects/${historyId}/blobs/${hash}`
  353. fetchNothing(url, {
  354. method: 'PUT',
  355. body: outStream,
  356. headers: { 'Content-Length': byteLength }, // add the content length to work around problems with chunked encoding in node 18
  357. ...getHistoryFetchOptions(),
  358. })
  359. .then(res => {
  360. callback(null, hash)
  361. })
  362. .catch(err => {
  363. callback(OError.tag(err))
  364. })
  365. })
  366. }
  367. export function initializeProject(historyId, callback) {
  368. _requestHistoryService(
  369. {
  370. method: 'POST',
  371. path: 'projects',
  372. json: historyId == null ? true : { projectId: historyId },
  373. },
  374. (error, project) => {
  375. if (error) {
  376. return callback(OError.tag(error))
  377. }
  378. const id = project.projectId
  379. if (id == null) {
  380. error = new OError('history store did not return a project id', id)
  381. return callback(error)
  382. }
  383. callback(null, id)
  384. }
  385. )
  386. }
  387. export function deleteProject(projectId, callback) {
  388. _requestHistoryService(
  389. { method: 'DELETE', path: `projects/${projectId}` },
  390. callback
  391. )
  392. }
  393. const getProjectBlobAsync = promisify(getProjectBlob)
  394. class BlobStore {
  395. constructor(projectId) {
  396. this.projectId = projectId
  397. }
  398. async getString(hash) {
  399. return await getProjectBlobAsync(this.projectId, hash)
  400. }
  401. async getObject(hash) {
  402. const string = await this.getString(hash)
  403. return JSON.parse(string)
  404. }
  405. }
  406. export function getBlobStore(projectId) {
  407. return new BlobStore(projectId)
  408. }
  409. function _requestOptions(options) {
  410. const requestOptions = {
  411. method: options.method || 'GET',
  412. url: `${Settings.overleaf.history.host}/${options.path}`,
  413. timeout: HTTP_REQUEST_TIMEOUT,
  414. auth: {
  415. user: Settings.overleaf.history.user,
  416. pass: Settings.overleaf.history.pass,
  417. sendImmediately: true,
  418. },
  419. }
  420. if (options.json != null) {
  421. requestOptions.json = options.json
  422. }
  423. if (options.body != null) {
  424. requestOptions.body = options.body
  425. }
  426. if (options.qs != null) {
  427. requestOptions.qs = options.qs
  428. }
  429. return requestOptions
  430. }
  431. /**
  432. * @return {RequestInit}
  433. */
  434. function getHistoryFetchOptions() {
  435. return {
  436. signal: AbortSignal.timeout(HTTP_REQUEST_TIMEOUT),
  437. basicAuth: {
  438. user: Settings.overleaf.history.user,
  439. password: Settings.overleaf.history.pass,
  440. },
  441. }
  442. }
  443. function _requestHistoryService(options, callback) {
  444. const requestOptions = _requestOptions(options)
  445. request(requestOptions, (error, res, body) => {
  446. if (error) {
  447. return callback(OError.tag(error))
  448. }
  449. if (res.statusCode >= 200 && res.statusCode < 300) {
  450. callback(null, body)
  451. } else {
  452. error = new OError(
  453. `history store a non-success status code: ${res.statusCode}`
  454. )
  455. error.statusCode = res.statusCode
  456. error.body = body
  457. logger.warn({ err: error }, error.message)
  458. callback(error)
  459. }
  460. })
  461. }
  462. export const promises = {
  463. getMostRecentChunk: promisify(getMostRecentChunk),
  464. getChunkAtVersion: promisify(getChunkAtVersion),
  465. getMostRecentVersion: promisify(getMostRecentVersion),
  466. getProjectBlob: promisify(getProjectBlob),
  467. getProjectBlobStream: promisify(getProjectBlobStream),
  468. sendChanges: promisify(sendChanges),
  469. createBlobForUpdate: promisify(createBlobForUpdate),
  470. initializeProject: promisify(initializeProject),
  471. deleteProject: promisify(deleteProject),
  472. }