HistoryStoreManager.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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. const HTTP_REQUEST_TIMEOUT = Settings.apis.history_v1.requestTimeout
  20. /**
  21. * Container for functions that need to be mocked in tests
  22. *
  23. * TODO: Rewrite tests in terms of exported functions only
  24. */
  25. export const _mocks = {}
  26. class StringStream extends stream.Readable {
  27. _read() {}
  28. }
  29. _mocks.getMostRecentChunk = (projectId, historyId, callback) => {
  30. const path = `projects/${historyId}/latest/history`
  31. logger.debug({ projectId, historyId }, 'getting chunk from history service')
  32. _requestChunk({ path, json: true }, callback)
  33. }
  34. /**
  35. * @param {Callback} callback
  36. */
  37. export function getMostRecentChunk(projectId, historyId, callback) {
  38. _mocks.getMostRecentChunk(projectId, historyId, callback)
  39. }
  40. /**
  41. * @param {Callback} callback
  42. */
  43. export function getChunkAtVersion(projectId, historyId, version, callback) {
  44. const path = `projects/${historyId}/versions/${version}/history`
  45. logger.debug(
  46. { projectId, historyId, version },
  47. 'getting chunk from history service for version'
  48. )
  49. _requestChunk({ path, json: true }, callback)
  50. }
  51. export function getMostRecentVersion(projectId, historyId, callback) {
  52. getMostRecentChunk(projectId, historyId, (error, chunk) => {
  53. if (error) {
  54. return callback(OError.tag(error))
  55. }
  56. const mostRecentVersion =
  57. chunk.chunk.startVersion + (chunk.chunk.history.changes || []).length
  58. const lastChange = _.last(
  59. _.sortBy(chunk.chunk.history.changes || [], x => x.timestamp)
  60. )
  61. // find the latest project and doc versions in the chunk
  62. _getLatestProjectVersion(projectId, chunk, (err1, projectVersion) =>
  63. _getLatestV2DocVersions(projectId, chunk, (err2, v2DocVersions) => {
  64. // return the project and doc versions
  65. const projectStructureAndDocVersions = {
  66. project: projectVersion,
  67. docs: v2DocVersions,
  68. }
  69. callback(
  70. err1 || err2,
  71. mostRecentVersion,
  72. projectStructureAndDocVersions,
  73. lastChange
  74. )
  75. })
  76. )
  77. })
  78. }
  79. function _requestChunk(options, callback) {
  80. _requestHistoryService(options, (err, chunk) => {
  81. if (err) {
  82. return callback(OError.tag(err))
  83. }
  84. if (
  85. chunk == null ||
  86. chunk.chunk == null ||
  87. chunk.chunk.startVersion == null
  88. ) {
  89. return callback(new OError('unexpected response'))
  90. }
  91. callback(null, chunk)
  92. })
  93. }
  94. function _getLatestProjectVersion(projectId, chunk, callback) {
  95. // find the initial project version
  96. let projectVersion =
  97. chunk.chunk.history.snapshot && chunk.chunk.history.snapshot.projectVersion
  98. // keep track of any errors
  99. let error = null
  100. // iterate over the changes in chunk to find the most recent project version
  101. for (const change of chunk.chunk.history.changes || []) {
  102. if (change.projectVersion != null) {
  103. if (
  104. projectVersion != null &&
  105. Versions.lt(change.projectVersion, projectVersion)
  106. ) {
  107. logger.warn(
  108. { projectId, chunk, projectVersion, change },
  109. 'project structure version out of order in chunk'
  110. )
  111. if (!error) {
  112. error = new Errors.OpsOutOfOrderError(
  113. 'project structure version out of order'
  114. )
  115. }
  116. } else {
  117. projectVersion = change.projectVersion
  118. }
  119. }
  120. }
  121. callback(error, projectVersion)
  122. }
  123. function _getLatestV2DocVersions(projectId, chunk, callback) {
  124. // find the initial doc versions (indexed by docId as this is immutable)
  125. const v2DocVersions =
  126. (chunk.chunk.history.snapshot &&
  127. chunk.chunk.history.snapshot.v2DocVersions) ||
  128. {}
  129. // keep track of any errors
  130. let error = null
  131. // iterate over the changes in the chunk to find the most recent doc versions
  132. for (const change of chunk.chunk.history.changes || []) {
  133. if (change.v2DocVersions != null) {
  134. for (const docId in change.v2DocVersions) {
  135. const docInfo = change.v2DocVersions[docId]
  136. const { v } = docInfo
  137. if (
  138. v2DocVersions[docId] &&
  139. v2DocVersions[docId].v != null &&
  140. Versions.lt(v, v2DocVersions[docId].v)
  141. ) {
  142. logger.warn(
  143. {
  144. projectId,
  145. docId,
  146. changeVersion: docInfo,
  147. previousVersion: v2DocVersions[docId],
  148. },
  149. 'doc version out of order in chunk'
  150. )
  151. if (!error) {
  152. error = new Errors.OpsOutOfOrderError('doc version out of order')
  153. }
  154. } else {
  155. v2DocVersions[docId] = docInfo
  156. }
  157. }
  158. }
  159. }
  160. callback(error, v2DocVersions)
  161. }
  162. export function getProjectBlob(historyId, blobHash, callback) {
  163. logger.debug({ historyId, blobHash }, 'getting blob from history service')
  164. _requestHistoryService(
  165. { path: `projects/${historyId}/blobs/${blobHash}` },
  166. callback
  167. )
  168. }
  169. /**
  170. * @param {Callback} callback
  171. */
  172. export function getProjectBlobStream(historyId, blobHash, callback) {
  173. const url = `${Settings.overleaf.history.host}/projects/${historyId}/blobs/${blobHash}`
  174. logger.debug(
  175. { historyId, blobHash },
  176. 'getting blob stream from history service'
  177. )
  178. fetchStream(url, getHistoryFetchOptions())
  179. .then(stream => {
  180. callback(null, stream)
  181. })
  182. .catch(err => callback(OError.tag(err)))
  183. }
  184. export function sendChanges(
  185. projectId,
  186. historyId,
  187. changes,
  188. endVersion,
  189. callback
  190. ) {
  191. logger.debug(
  192. { projectId, historyId, endVersion },
  193. 'sending changes to history service'
  194. )
  195. _requestHistoryService(
  196. {
  197. path: `projects/${historyId}/legacy_changes`,
  198. qs: { end_version: endVersion },
  199. method: 'POST',
  200. json: changes,
  201. },
  202. error => {
  203. if (error) {
  204. OError.tag(error, 'failed to send changes to v1', {
  205. projectId,
  206. historyId,
  207. endVersion,
  208. errorCode: error.code,
  209. statusCode: error.statusCode,
  210. body: error.body,
  211. })
  212. logger.warn(error)
  213. return callback(error)
  214. }
  215. callback()
  216. }
  217. )
  218. }
  219. export function createBlobForUpdate(projectId, historyId, update, callback) {
  220. callback = _.once(callback)
  221. if (update.doc != null && update.docLines != null) {
  222. const stringStream = new StringStream()
  223. stringStream.push(update.docLines)
  224. stringStream.push(null)
  225. LocalFileWriter.bufferOnDisk(
  226. stringStream,
  227. '',
  228. `project-${projectId}-doc-${update.doc}`,
  229. (fsPath, cb) => {
  230. _createBlob(historyId, fsPath, cb)
  231. },
  232. callback
  233. )
  234. } else if (update.file != null && update.url != null) {
  235. // Rewrite the filestore url to point to the location in the local
  236. // settings for this service (this avoids problems with cross-
  237. // datacentre requests when running filestore in multiple locations).
  238. const { pathname: fileStorePath } = new URL(update.url)
  239. const urlMatch = /^\/project\/([0-9a-f]{24})\/file\/([0-9a-f]{24})$/.exec(
  240. fileStorePath
  241. )
  242. if (urlMatch == null) {
  243. return callback(new OError('invalid file for blob creation'))
  244. }
  245. if (urlMatch[1] !== projectId) {
  246. return callback(new OError('invalid project for blob creation'))
  247. }
  248. const fileId = urlMatch[2]
  249. const filestoreURL = `${Settings.apis.filestore.url}/project/${projectId}/file/${fileId}`
  250. fetchStream(filestoreURL, {
  251. signal: AbortSignal.timeout(HTTP_REQUEST_TIMEOUT),
  252. })
  253. .then(stream => {
  254. LocalFileWriter.bufferOnDisk(
  255. stream,
  256. filestoreURL,
  257. `project-${projectId}-file-${fileId}`,
  258. (fsPath, cb) => {
  259. _createBlob(historyId, fsPath, cb)
  260. },
  261. callback
  262. )
  263. })
  264. .catch(err => {
  265. if (err instanceof RequestFailedError && err.response.status === 404) {
  266. logger.warn(
  267. { projectId, historyId, filestoreURL },
  268. 'File contents not found in filestore. Storing in history as an empty file'
  269. )
  270. const emptyStream = new StringStream()
  271. LocalFileWriter.bufferOnDisk(
  272. emptyStream,
  273. filestoreURL,
  274. `project-${projectId}-file-${fileId}`,
  275. (fsPath, cb) => {
  276. _createBlob(historyId, fsPath, cb)
  277. },
  278. callback
  279. )
  280. emptyStream.push(null) // send an EOF signal
  281. } else {
  282. callback(OError.tag(err, 'error from filestore', { filestoreURL }))
  283. }
  284. })
  285. } else {
  286. const error = new OError('invalid update for blob creation')
  287. callback(error)
  288. }
  289. }
  290. function _createBlob(historyId, fsPath, _callback) {
  291. const callback = _.once(_callback)
  292. HashManager._getBlobHash(fsPath, (error, hash, byteLength) => {
  293. if (error) {
  294. return callback(OError.tag(error))
  295. }
  296. const outStream = fs.createReadStream(fsPath)
  297. logger.debug(
  298. { fsPath, historyId, hash, byteLength },
  299. 'sending blob to history service'
  300. )
  301. const url = `${Settings.overleaf.history.host}/projects/${historyId}/blobs/${hash}`
  302. fetchNothing(url, {
  303. method: 'PUT',
  304. body: outStream,
  305. headers: { 'Content-Length': byteLength }, // add the content length to work around problems with chunked encoding in node 18
  306. ...getHistoryFetchOptions(),
  307. })
  308. .then(res => {
  309. callback(null, hash)
  310. })
  311. .catch(err => {
  312. callback(OError.tag(err))
  313. })
  314. })
  315. }
  316. export function initializeProject(historyId, callback) {
  317. _requestHistoryService(
  318. {
  319. method: 'POST',
  320. path: 'projects',
  321. json: historyId == null ? true : { projectId: historyId },
  322. },
  323. (error, project) => {
  324. if (error) {
  325. return callback(OError.tag(error))
  326. }
  327. const id = project.projectId
  328. if (id == null) {
  329. error = new OError('history store did not return a project id', id)
  330. return callback(error)
  331. }
  332. callback(null, id)
  333. }
  334. )
  335. }
  336. export function deleteProject(projectId, callback) {
  337. _requestHistoryService(
  338. { method: 'DELETE', path: `projects/${projectId}` },
  339. callback
  340. )
  341. }
  342. const getProjectBlobAsync = promisify(getProjectBlob)
  343. class BlobStore {
  344. constructor(projectId) {
  345. this.projectId = projectId
  346. }
  347. async getString(hash) {
  348. return await getProjectBlobAsync(this.projectId, hash)
  349. }
  350. async getObject(hash) {
  351. const string = await this.getString(hash)
  352. return JSON.parse(string)
  353. }
  354. }
  355. export function getBlobStore(projectId) {
  356. return new BlobStore(projectId)
  357. }
  358. function _requestOptions(options) {
  359. const requestOptions = {
  360. method: options.method || 'GET',
  361. url: `${Settings.overleaf.history.host}/${options.path}`,
  362. timeout: HTTP_REQUEST_TIMEOUT,
  363. auth: {
  364. user: Settings.overleaf.history.user,
  365. pass: Settings.overleaf.history.pass,
  366. sendImmediately: true,
  367. },
  368. }
  369. if (options.json != null) {
  370. requestOptions.json = options.json
  371. }
  372. if (options.body != null) {
  373. requestOptions.body = options.body
  374. }
  375. if (options.qs != null) {
  376. requestOptions.qs = options.qs
  377. }
  378. return requestOptions
  379. }
  380. /**
  381. * @return {RequestInit}
  382. */
  383. function getHistoryFetchOptions() {
  384. return {
  385. signal: AbortSignal.timeout(HTTP_REQUEST_TIMEOUT),
  386. basicAuth: {
  387. user: Settings.overleaf.history.user,
  388. password: Settings.overleaf.history.pass,
  389. },
  390. }
  391. }
  392. function _requestHistoryService(options, callback) {
  393. const requestOptions = _requestOptions(options)
  394. request(requestOptions, (error, res, body) => {
  395. if (error) {
  396. return callback(OError.tag(error))
  397. }
  398. if (res.statusCode >= 200 && res.statusCode < 300) {
  399. callback(null, body)
  400. } else {
  401. error = new OError(
  402. `history store a non-success status code: ${res.statusCode}`
  403. )
  404. error.statusCode = res.statusCode
  405. error.body = body
  406. logger.warn({ err: error }, error.message)
  407. callback(error)
  408. }
  409. })
  410. }
  411. export const promises = {
  412. getMostRecentChunk: promisify(getMostRecentChunk),
  413. getChunkAtVersion: promisify(getChunkAtVersion),
  414. getMostRecentVersion: promisify(getMostRecentVersion),
  415. getProjectBlob: promisify(getProjectBlob),
  416. getProjectBlobStream: promisify(getProjectBlobStream),
  417. sendChanges: promisify(sendChanges),
  418. createBlobForUpdate: promisify(createBlobForUpdate),
  419. initializeProject: promisify(initializeProject),
  420. deleteProject: promisify(deleteProject),
  421. }