HistoryStoreManager.js 12 KB

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