ProjectEntityMongoUpdateHandler.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. /* NOTE: this file is an async/await version of
  2. * ProjectEntityMongoUpdateHandler.js. It's temporarily separate from the
  3. * callback-style version so that we can test it in production for some code
  4. * paths only.
  5. */
  6. const { callbackify } = require('util')
  7. const { callbackifyMultiResult } = require('../../util/promises')
  8. const _ = require('underscore')
  9. const logger = require('logger-sharelatex')
  10. const path = require('path')
  11. const { ObjectId } = require('mongodb')
  12. const Settings = require('settings-sharelatex')
  13. const OError = require('@overleaf/o-error')
  14. const CooldownManager = require('../Cooldown/CooldownManager')
  15. const Errors = require('../Errors/Errors')
  16. const { Folder } = require('../../models/Folder')
  17. const LockManager = require('../../infrastructure/LockManager')
  18. const { Project } = require('../../models/Project')
  19. const ProjectEntityHandler = require('./ProjectEntityHandler')
  20. const ProjectGetter = require('./ProjectGetter')
  21. const ProjectLocator = require('./ProjectLocator')
  22. const FolderStructureBuilder = require('./FolderStructureBuilder')
  23. const SafePath = require('./SafePath')
  24. const LOCK_NAMESPACE = 'mongoTransaction'
  25. const ENTITY_TYPE_TO_MONGO_PATH_SEGMENT = {
  26. doc: 'docs',
  27. docs: 'docs',
  28. file: 'fileRefs',
  29. files: 'fileRefs',
  30. fileRefs: 'fileRefs',
  31. folder: 'folders',
  32. folders: 'folders'
  33. }
  34. module.exports = {
  35. LOCK_NAMESPACE,
  36. addDoc: callbackifyMultiResult(wrapWithLock(addDoc), ['result', 'project']),
  37. addFile: callbackifyMultiResult(wrapWithLock(addFile), ['result', 'project']),
  38. addFolder: callbackifyMultiResult(wrapWithLock(addFolder), [
  39. 'folder',
  40. 'parentFolderId'
  41. ]),
  42. replaceFileWithNew: callbackifyMultiResult(wrapWithLock(replaceFileWithNew), [
  43. 'oldFileRef',
  44. 'project',
  45. 'path',
  46. 'newProject'
  47. ]),
  48. mkdirp: callbackifyMultiResult(wrapWithLock(mkdirp), [
  49. 'newFolders',
  50. 'folder'
  51. ]),
  52. moveEntity: callbackifyMultiResult(wrapWithLock(moveEntity), [
  53. 'project',
  54. 'startPath',
  55. 'endPath',
  56. 'rev',
  57. 'changes'
  58. ]),
  59. deleteEntity: callbackifyMultiResult(wrapWithLock(deleteEntity), [
  60. 'entity',
  61. 'path',
  62. 'projectBeforeDeletion',
  63. 'newProject'
  64. ]),
  65. renameEntity: callbackifyMultiResult(wrapWithLock(renameEntity), [
  66. 'project',
  67. 'startPath',
  68. 'endPath',
  69. 'rev',
  70. 'changes'
  71. ]),
  72. createNewFolderStructure: callbackify(wrapWithLock(createNewFolderStructure)),
  73. _insertDeletedDocReference: callbackify(_insertDeletedDocReference),
  74. _insertDeletedFileReference: callbackify(_insertDeletedFileReference),
  75. _putElement: callbackifyMultiResult(_putElement, ['result', 'project']),
  76. _confirmFolder,
  77. promises: {
  78. addDoc: wrapWithLock(addDoc),
  79. addFile: wrapWithLock(addFile),
  80. addFolder: wrapWithLock(addFolder),
  81. replaceFileWithNew: wrapWithLock(replaceFileWithNew),
  82. mkdirp: wrapWithLock(mkdirp),
  83. moveEntity: wrapWithLock(moveEntity),
  84. deleteEntity: wrapWithLock(deleteEntity),
  85. renameEntity: wrapWithLock(renameEntity),
  86. createNewFolderStructure: wrapWithLock(createNewFolderStructure),
  87. _insertDeletedDocReference,
  88. _insertDeletedFileReference,
  89. _putElement
  90. }
  91. }
  92. function wrapWithLock(methodWithoutLock) {
  93. // This lock is used whenever we read or write to an existing project's
  94. // structure. Some operations to project structure cannot be done atomically
  95. // in mongo, this lock is used to prevent reading the structure between two
  96. // parts of a staged update.
  97. async function methodWithLock(projectId, ...rest) {
  98. return LockManager.promises.runWithLock(LOCK_NAMESPACE, projectId, () =>
  99. methodWithoutLock(projectId, ...rest)
  100. )
  101. }
  102. return methodWithLock
  103. }
  104. async function addDoc(projectId, folderId, doc) {
  105. const project = await ProjectGetter.promises.getProjectWithoutLock(
  106. projectId,
  107. {
  108. rootFolder: true,
  109. name: true,
  110. overleaf: true
  111. }
  112. )
  113. folderId = _confirmFolder(project, folderId)
  114. const { result, project: newProject } = await _putElement(
  115. project,
  116. folderId,
  117. doc,
  118. 'doc'
  119. )
  120. return { result, project: newProject }
  121. }
  122. async function addFile(projectId, folderId, fileRef) {
  123. const project = await ProjectGetter.promises.getProjectWithoutLock(
  124. projectId,
  125. { rootFolder: true, name: true, overleaf: true }
  126. )
  127. folderId = _confirmFolder(project, folderId)
  128. const { result, project: newProject } = await _putElement(
  129. project,
  130. folderId,
  131. fileRef,
  132. 'file'
  133. )
  134. return { result, project: newProject }
  135. }
  136. async function addFolder(projectId, parentFolderId, folderName) {
  137. const project = await ProjectGetter.promises.getProjectWithoutLock(
  138. projectId,
  139. { rootFolder: true, name: true, overleaf: true }
  140. )
  141. parentFolderId = _confirmFolder(project, parentFolderId)
  142. const folder = new Folder({ name: folderName })
  143. await _putElement(project, parentFolderId, folder, 'folder')
  144. return { folder, parentFolderId }
  145. }
  146. async function replaceFileWithNew(projectId, fileId, newFileRef) {
  147. const project = await ProjectGetter.promises.getProjectWithoutLock(
  148. projectId,
  149. { rootFolder: true, name: true, overleaf: true }
  150. )
  151. const { element: fileRef, path } = await ProjectLocator.promises.findElement({
  152. project,
  153. element_id: fileId,
  154. type: 'file'
  155. })
  156. await _insertDeletedFileReference(projectId, fileRef)
  157. const newProject = await Project.findOneAndUpdate(
  158. { _id: project._id },
  159. {
  160. $set: {
  161. [`${path.mongo}._id`]: newFileRef._id,
  162. [`${path.mongo}.created`]: new Date(),
  163. [`${path.mongo}.linkedFileData`]: newFileRef.linkedFileData,
  164. [`${path.mongo}.hash`]: newFileRef.hash
  165. },
  166. $inc: {
  167. version: 1,
  168. [`${path.mongo}.rev`]: 1
  169. }
  170. },
  171. { new: true }
  172. ).exec()
  173. // Note: Mongoose uses new:true to return the modified document
  174. // https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate
  175. // but Mongo uses returnNewDocument:true instead
  176. // https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/
  177. // We are using Mongoose here, but if we ever switch to a direct mongo call
  178. // the next line will need to be updated.
  179. return { oldFileRef: fileRef, project, path, newProject }
  180. }
  181. async function mkdirp(projectId, path, options = {}) {
  182. // defaults to case insensitive paths, use options {exactCaseMatch:true}
  183. // to make matching case-sensitive
  184. let folders = path.split('/')
  185. folders = _.select(folders, folder => folder.length !== 0)
  186. const project = await ProjectGetter.promises.getProjectWithOnlyFolders(
  187. projectId
  188. )
  189. if (path === '/') {
  190. return { newFolders: [], folder: project.rootFolder[0] }
  191. }
  192. const newFolders = []
  193. let builtUpPath = ''
  194. let lastFolder = null
  195. for (const folderName of folders) {
  196. builtUpPath += `/${folderName}`
  197. try {
  198. const {
  199. element: foundFolder
  200. } = await ProjectLocator.promises.findElementByPath({
  201. project,
  202. path: builtUpPath,
  203. exactCaseMatch: options.exactCaseMatch
  204. })
  205. lastFolder = foundFolder
  206. } catch (err) {
  207. // Folder couldn't be found. Create it.
  208. const parentFolderId = lastFolder && lastFolder._id
  209. const {
  210. folder: newFolder,
  211. parentFolderId: newParentFolderId
  212. } = await addFolder(projectId, parentFolderId, folderName)
  213. newFolder.parentFolder_id = newParentFolderId
  214. lastFolder = newFolder
  215. newFolders.push(newFolder)
  216. }
  217. }
  218. return { folder: lastFolder, newFolders }
  219. }
  220. async function moveEntity(projectId, entityId, destFolderId, entityType) {
  221. const project = await ProjectGetter.promises.getProjectWithoutLock(
  222. projectId,
  223. { rootFolder: true, name: true, overleaf: true }
  224. )
  225. const {
  226. element: entity,
  227. path: entityPath
  228. } = await ProjectLocator.promises.findElement({
  229. project,
  230. element_id: entityId,
  231. type: entityType
  232. })
  233. // Prevent top-level docs/files with reserved names (to match v1 behaviour)
  234. if (_blockedFilename(entityPath, entityType)) {
  235. throw new Errors.InvalidNameError('blocked element name')
  236. }
  237. await _checkValidMove(project, entityType, entity, entityPath, destFolderId)
  238. const {
  239. docs: oldDocs,
  240. files: oldFiles
  241. } = await ProjectEntityHandler.promises.getAllEntitiesFromProject(project)
  242. // For safety, insert the entity in the destination
  243. // location first, and then remove the original. If
  244. // there is an error the entity may appear twice. This
  245. // will cause some breakage but is better than being
  246. // lost, which is what happens if this is done in the
  247. // opposite order.
  248. const { result } = await _putElement(
  249. project,
  250. destFolderId,
  251. entity,
  252. entityType
  253. )
  254. // Note: putElement always pushes onto the end of an
  255. // array so it will never change an existing mongo
  256. // path. Therefore it is safe to remove an element
  257. // from the project with an existing path after
  258. // calling putElement. But we must be sure that we
  259. // have not moved a folder subfolder of itself (which
  260. // is done by _checkValidMove above) because that
  261. // would lead to it being deleted.
  262. const newProject = await _removeElementFromMongoArray(
  263. Project,
  264. projectId,
  265. entityPath.mongo,
  266. entityId
  267. )
  268. const {
  269. docs: newDocs,
  270. files: newFiles
  271. } = await ProjectEntityHandler.promises.getAllEntitiesFromProject(newProject)
  272. const startPath = entityPath.fileSystem
  273. const endPath = result.path.fileSystem
  274. const changes = {
  275. oldDocs,
  276. newDocs,
  277. oldFiles,
  278. newFiles,
  279. newProject
  280. }
  281. // check that no files have been lost (or duplicated)
  282. if (
  283. oldFiles.length !== newFiles.length ||
  284. oldDocs.length !== newDocs.length
  285. ) {
  286. logger.warn(
  287. {
  288. projectId,
  289. oldDocs: oldDocs.length,
  290. newDocs: newDocs.length,
  291. oldFiles: oldFiles.length,
  292. newFiles: newFiles.length,
  293. origProject: project,
  294. newProject
  295. },
  296. "project corrupted moving files - shouldn't happen"
  297. )
  298. throw new Error('unexpected change in project structure')
  299. }
  300. return { project, startPath, endPath, rev: entity.rev, changes }
  301. }
  302. async function deleteEntity(projectId, entityId, entityType, callback) {
  303. const project = await ProjectGetter.promises.getProjectWithoutLock(
  304. projectId,
  305. { name: true, rootFolder: true, overleaf: true, rootDoc_id: true }
  306. )
  307. const deleteRootDoc =
  308. project.rootDoc_id &&
  309. entityId &&
  310. project.rootDoc_id.toString() === entityId.toString()
  311. const { element: entity, path } = await ProjectLocator.promises.findElement({
  312. project,
  313. element_id: entityId,
  314. type: entityType
  315. })
  316. const newProject = await _removeElementFromMongoArray(
  317. Project,
  318. projectId,
  319. path.mongo,
  320. entityId,
  321. deleteRootDoc
  322. )
  323. return { entity, path, projectBeforeDeletion: project, newProject }
  324. }
  325. async function renameEntity(
  326. projectId,
  327. entityId,
  328. entityType,
  329. newName,
  330. callback
  331. ) {
  332. const project = await ProjectGetter.promises.getProjectWithoutLock(
  333. projectId,
  334. { rootFolder: true, name: true, overleaf: true }
  335. )
  336. const {
  337. element: entity,
  338. path: entPath,
  339. folder: parentFolder
  340. } = await ProjectLocator.promises.findElement({
  341. project,
  342. element_id: entityId,
  343. type: entityType
  344. })
  345. const startPath = entPath.fileSystem
  346. const endPath = path.join(path.dirname(entPath.fileSystem), newName)
  347. // Prevent top-level docs/files with reserved names (to match v1 behaviour)
  348. if (_blockedFilename({ fileSystem: endPath }, entityType)) {
  349. throw new Errors.InvalidNameError('blocked element name')
  350. }
  351. // check if the new name already exists in the current folder
  352. _checkValidElementName(parentFolder, newName)
  353. const {
  354. docs: oldDocs,
  355. files: oldFiles
  356. } = await ProjectEntityHandler.promises.getAllEntitiesFromProject(project)
  357. // we need to increment the project version number for any structure change
  358. const newProject = await Project.findOneAndUpdate(
  359. { _id: projectId },
  360. { $set: { [`${entPath.mongo}.name`]: newName }, $inc: { version: 1 } },
  361. { new: true }
  362. ).exec()
  363. const {
  364. docs: newDocs,
  365. files: newFiles
  366. } = await ProjectEntityHandler.promises.getAllEntitiesFromProject(newProject)
  367. return {
  368. project,
  369. startPath,
  370. endPath,
  371. rev: entity.rev,
  372. changes: { oldDocs, newDocs, oldFiles, newFiles, newProject }
  373. }
  374. }
  375. async function _insertDeletedDocReference(projectId, doc) {
  376. await Project.updateOne(
  377. { _id: projectId },
  378. {
  379. $push: {
  380. deletedDocs: { _id: doc._id, name: doc.name, deletedAt: new Date() }
  381. }
  382. }
  383. ).exec()
  384. }
  385. async function _insertDeletedFileReference(projectId, fileRef) {
  386. await Project.updateOne(
  387. { _id: projectId },
  388. {
  389. $push: {
  390. deletedFiles: {
  391. _id: fileRef._id,
  392. name: fileRef.name,
  393. linkedFileData: fileRef.linkedFileData,
  394. hash: fileRef.hash,
  395. deletedAt: new Date()
  396. }
  397. }
  398. }
  399. ).exec()
  400. }
  401. async function _removeElementFromMongoArray(
  402. model,
  403. modelId,
  404. path,
  405. elementId,
  406. deleteRootDoc = false
  407. ) {
  408. const nonArrayPath = path.slice(0, path.lastIndexOf('.'))
  409. const options = { new: true }
  410. const query = { _id: modelId }
  411. const update = {
  412. $pull: { [nonArrayPath]: { _id: elementId } },
  413. $inc: { version: 1 }
  414. }
  415. if (deleteRootDoc) {
  416. update.$unset = { rootDoc_id: 1 }
  417. }
  418. return model.findOneAndUpdate(query, update, options).exec()
  419. }
  420. function _countElements(project) {
  421. function countFolder(folder) {
  422. if (folder == null) {
  423. return 0
  424. }
  425. let total = 0
  426. if (folder.folders) {
  427. total += folder.folders.length
  428. for (const subfolder of folder.folders) {
  429. total += countFolder(subfolder)
  430. }
  431. }
  432. if (folder.docs) {
  433. total += folder.docs.length
  434. }
  435. if (folder.fileRefs) {
  436. total += folder.fileRefs.length
  437. }
  438. return total
  439. }
  440. return countFolder(project.rootFolder[0])
  441. }
  442. async function _putElement(project, folderId, element, type) {
  443. if (element == null || element._id == null) {
  444. logger.warn(
  445. { projectId: project._id, folderId, element, type },
  446. 'failed trying to insert element as it was null'
  447. )
  448. throw new Error('no element passed to be inserted')
  449. }
  450. const pathSegment = _getMongoPathSegmentFromType(type)
  451. // original check path.resolve("/", element.name) isnt "/#{element.name}" or element.name.match("/")
  452. // check if name is allowed
  453. if (!SafePath.isCleanFilename(element.name)) {
  454. logger.warn(
  455. { projectId: project._id, folderId, element, type },
  456. 'failed trying to insert element as name was invalid'
  457. )
  458. throw new Errors.InvalidNameError('invalid element name')
  459. }
  460. if (folderId == null) {
  461. folderId = project.rootFolder[0]._id
  462. }
  463. if (_countElements(project) > Settings.maxEntitiesPerProject) {
  464. logger.warn(
  465. { projectId: project._id },
  466. 'project too big, stopping insertions'
  467. )
  468. CooldownManager.putProjectOnCooldown(project._id)
  469. throw new Error('project_has_to_many_files')
  470. }
  471. const { element: folder, path } = await ProjectLocator.promises.findElement({
  472. project,
  473. element_id: folderId,
  474. type: 'folder'
  475. })
  476. const newPath = {
  477. fileSystem: `${path.fileSystem}/${element.name}`,
  478. mongo: path.mongo
  479. }
  480. // check if the path would be too long
  481. if (!SafePath.isAllowedLength(newPath.fileSystem)) {
  482. throw new Errors.InvalidNameError('path too long')
  483. }
  484. // Prevent top-level docs/files with reserved names (to match v1 behaviour)
  485. if (_blockedFilename(newPath, type)) {
  486. throw new Errors.InvalidNameError('blocked element name')
  487. }
  488. _checkValidElementName(folder, element.name)
  489. element._id = ObjectId(element._id.toString())
  490. const mongoPath = `${path.mongo}.${pathSegment}`
  491. const newProject = await Project.findOneAndUpdate(
  492. { _id: project._id },
  493. { $push: { [mongoPath]: element }, $inc: { version: 1 } },
  494. { new: true }
  495. ).exec()
  496. return { result: { path: newPath }, project: newProject }
  497. }
  498. function _blockedFilename(entityPath, entityType) {
  499. // check if name would be blocked in v1
  500. // javascript reserved names are forbidden for docs and files
  501. // at the top-level (but folders with reserved names are allowed).
  502. const isFolder = entityType === 'folder'
  503. const dir = path.dirname(entityPath.fileSystem)
  504. const file = path.basename(entityPath.fileSystem)
  505. const isTopLevel = dir === '/'
  506. if (isTopLevel && !isFolder && SafePath.isBlockedFilename(file)) {
  507. return true
  508. } else {
  509. return false
  510. }
  511. }
  512. function _getMongoPathSegmentFromType(type) {
  513. const pathSegment = ENTITY_TYPE_TO_MONGO_PATH_SEGMENT[type]
  514. if (pathSegment == null) {
  515. throw new Error(`Unknown entity type: ${type}`)
  516. }
  517. return pathSegment
  518. }
  519. /**
  520. * Check if the name is already taken by a doc, file or folder. If so, return an
  521. * error "file already exists".
  522. */
  523. function _checkValidElementName(folder, name) {
  524. if (folder == null) {
  525. return
  526. }
  527. const elements = []
  528. .concat(folder.docs || [])
  529. .concat(folder.fileRefs || [])
  530. .concat(folder.folders || [])
  531. for (const element of elements) {
  532. if (element.name === name) {
  533. throw new Errors.InvalidNameError('file already exists')
  534. }
  535. }
  536. }
  537. function _confirmFolder(project, folderId) {
  538. if (folderId == null) {
  539. return project.rootFolder[0]._id
  540. } else {
  541. return folderId
  542. }
  543. }
  544. async function _checkValidMove(
  545. project,
  546. entityType,
  547. entity,
  548. entityPath,
  549. destFolderId
  550. ) {
  551. const {
  552. element: destEntity,
  553. path: destFolderPath
  554. } = await ProjectLocator.promises.findElement({
  555. project,
  556. element_id: destFolderId,
  557. type: 'folder'
  558. })
  559. // check if there is already a doc/file/folder with the same name
  560. // in the destination folder
  561. _checkValidElementName(destEntity, entity.name)
  562. if (/folder/.test(entityType)) {
  563. const isNestedFolder =
  564. destFolderPath.fileSystem.slice(0, entityPath.fileSystem.length) ===
  565. entityPath.fileSystem
  566. if (isNestedFolder) {
  567. throw new Errors.InvalidNameError(
  568. 'destination folder is a child folder of me'
  569. )
  570. }
  571. }
  572. }
  573. async function createNewFolderStructure(projectId, docUploads, fileUploads) {
  574. try {
  575. const rootFolder = FolderStructureBuilder.buildFolderStructure(
  576. docUploads,
  577. fileUploads
  578. )
  579. const result = await Project.updateOne(
  580. {
  581. _id: projectId,
  582. 'rootFolder.0.folders.0': { $exists: false },
  583. 'rootFolder.0.docs.0': { $exists: false },
  584. 'rootFolder.0.files.0': { $exists: false }
  585. },
  586. {
  587. $set: { rootFolder: [rootFolder] },
  588. $inc: { version: 1 }
  589. }
  590. ).exec()
  591. if (result.n !== 1) {
  592. throw new OError({
  593. message: 'project not found or folder structure already exists',
  594. info: { projectId }
  595. })
  596. }
  597. } catch (err) {
  598. throw new OError({
  599. message: 'failed to create folder structure',
  600. info: { projectId }
  601. }).withCause(err)
  602. }
  603. }