HistoryStoreManager.js 12 KB

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