HistoryUpgradeHelper.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. const { ReadPreference, ObjectId } = require('mongodb')
  2. const { db } = require('../../../../app/src/infrastructure/mongodb')
  3. const Settings = require('@overleaf/settings')
  4. const ProjectHistoryHandler = require('../../../../app/src/Features/Project/ProjectHistoryHandler')
  5. const HistoryManager = require('../../../../app/src/Features/History/HistoryManager')
  6. const ProjectHistoryController = require('./ProjectHistoryController')
  7. const ProjectEntityHandler = require('../../../../app/src/Features/Project/ProjectEntityHandler')
  8. const ProjectEntityUpdateHandler = require('../../../../app/src/Features/Project/ProjectEntityUpdateHandler')
  9. const DocumentUpdaterHandler = require('../../../../app/src/Features/DocumentUpdater/DocumentUpdaterHandler')
  10. // Timestamp of when 'Enable history for SL in background' release
  11. const ID_WHEN_FULL_PROJECT_HISTORY_ENABLED =
  12. Settings.apis.project_history?.idWhenFullProjectHistoryEnabled // was '5a8d8a370000000000000000'
  13. const DATETIME_WHEN_FULL_PROJECT_HISTORY_ENABLED =
  14. ID_WHEN_FULL_PROJECT_HISTORY_ENABLED
  15. ? new ObjectId(ID_WHEN_FULL_PROJECT_HISTORY_ENABLED).getTimestamp()
  16. : null
  17. async function countProjects(query = {}) {
  18. const count = await db.projects.countDocuments(query)
  19. return count
  20. }
  21. async function countDocHistory(query = {}) {
  22. const count = await db.docHistory.countDocuments(query)
  23. return count
  24. }
  25. async function findProjects(query = {}, projection = {}) {
  26. const projects = await db.projects.find(query).project(projection).toArray()
  27. return projects
  28. }
  29. async function determineProjectHistoryType(project) {
  30. if (project.overleaf && project.overleaf.history) {
  31. if (project.overleaf.history.upgradeFailed) {
  32. return 'UpgradeFailed'
  33. }
  34. if (project.overleaf.history.conversionFailed) {
  35. return 'ConversionFailed'
  36. }
  37. }
  38. if (
  39. project.overleaf &&
  40. project.overleaf.history &&
  41. project.overleaf.history.id
  42. ) {
  43. if (project.overleaf.history.display) {
  44. // v2: full project history, do nothing
  45. return 'V2'
  46. } else {
  47. if (projectCreatedAfterFullProjectHistoryEnabled(project)) {
  48. // IF project initialised after full project history enabled for all projects
  49. // THEN project history should contain all information we need, without intervention
  50. return 'V1WithoutConversion'
  51. } else {
  52. // ELSE SL history may predate full project history
  53. // THEN delete full project history and convert their SL history to full project history
  54. // --
  55. // TODO: how to verify this, can get rough start date of SL history, but not full project history
  56. const preserveHistory = await shouldPreserveHistory(project)
  57. const anyDocHistory = await anyDocHistoryExists(project)
  58. const anyDocHistoryIndex = await anyDocHistoryIndexExists(project)
  59. if (preserveHistory) {
  60. if (anyDocHistory || anyDocHistoryIndex) {
  61. // if SL history exists that we need to preserve, then we must convert
  62. return 'V1WithConversion'
  63. } else {
  64. // otherwise just upgrade without conversion
  65. return 'V1WithoutConversion'
  66. }
  67. } else {
  68. // if preserveHistory false, then max 7 days of SL history
  69. // but v1 already record to both histories, so safe to upgrade
  70. return 'V1WithoutConversion'
  71. }
  72. }
  73. }
  74. } else {
  75. const preserveHistory = await shouldPreserveHistory(project)
  76. const anyDocHistory = await anyDocHistoryExists(project)
  77. const anyDocHistoryIndex = await anyDocHistoryIndexExists(project)
  78. if (anyDocHistory || anyDocHistoryIndex) {
  79. // IF there is SL history ->
  80. if (preserveHistory) {
  81. // that needs to be preserved:
  82. // THEN initialise full project history and convert SL history to full project history
  83. return 'NoneWithConversion'
  84. } else {
  85. return 'NoneWithTemporaryHistory'
  86. }
  87. } else {
  88. // ELSE there is not any SL history ->
  89. // THEN initialise full project history and sync with current content
  90. return 'NoneWithoutConversion'
  91. }
  92. }
  93. }
  94. async function upgradeProject(project, options) {
  95. const historyType = await determineProjectHistoryType(project)
  96. if (historyType === 'V2') {
  97. return { historyType, upgraded: true }
  98. }
  99. const upgradeFn = getUpgradeFunctionForType(historyType)
  100. if (!upgradeFn) {
  101. return { error: 'unsupported history type' }
  102. }
  103. if (options.forceClean) {
  104. try {
  105. const projectId = project._id
  106. // delete any existing history stored in the mongo backend
  107. await HistoryManager.promises.deleteProject(projectId, projectId)
  108. } catch (err) {
  109. // failed to delete existing history, but we can try to continue
  110. }
  111. }
  112. const result = await upgradeFn(project, options)
  113. result.historyType = historyType
  114. return result
  115. }
  116. // Do upgrades/conversion:
  117. function getUpgradeFunctionForType(historyType) {
  118. return UpgradeFunctionMapping[historyType]
  119. }
  120. const UpgradeFunctionMapping = {
  121. NoneWithoutConversion: doUpgradeForNoneWithoutConversion,
  122. UpgradeFailed: doUpgradeForNoneWithoutConversion,
  123. ConversionFailed: doUpgradeForNoneWithConversion,
  124. V1WithoutConversion: doUpgradeForV1WithoutConversion,
  125. V1WithConversion: doUpgradeForV1WithConversion,
  126. NoneWithConversion: doUpgradeForNoneWithConversion,
  127. NoneWithTemporaryHistory: doUpgradeForNoneWithConversion,
  128. }
  129. async function doUpgradeForV1WithoutConversion(project) {
  130. await db.projects.updateOne(
  131. { _id: project._id },
  132. {
  133. $set: {
  134. 'overleaf.history.display': true,
  135. 'overleaf.history.upgradedAt': new Date(),
  136. 'overleaf.history.upgradeReason': `v1-without-sl-history`,
  137. },
  138. }
  139. )
  140. return { upgraded: true }
  141. }
  142. async function doUpgradeForV1WithConversion(project) {
  143. const result = {}
  144. const projectId = project._id
  145. // migrateProjectHistory expects project id as a string
  146. const projectIdString = project._id.toString()
  147. try {
  148. // We treat these essentially as None projects, the V1 history is irrelevant,
  149. // so we will delete it, and do a conversion as if we're a None project
  150. await ProjectHistoryController.deleteProjectHistory(projectIdString)
  151. await ProjectHistoryController.migrateProjectHistory(projectIdString)
  152. } catch (err) {
  153. // if migrateProjectHistory fails, it cleans up by deleting
  154. // the history and unsetting the history id
  155. // therefore a failed project will still look like a 'None with conversion' project
  156. result.error = err
  157. await db.projects.updateOne(
  158. { _id: projectId },
  159. {
  160. $set: {
  161. 'overleaf.history.conversionFailed': true,
  162. },
  163. }
  164. )
  165. return result
  166. }
  167. await db.projects.updateOne(
  168. { _id: projectId },
  169. {
  170. $set: {
  171. 'overleaf.history.upgradeReason': `v1-with-conversion`,
  172. },
  173. $unset: {
  174. 'overleaf.history.upgradeFailed': true,
  175. 'overleaf.history.conversionFailed': true,
  176. },
  177. }
  178. )
  179. result.upgraded = true
  180. return result
  181. }
  182. async function doUpgradeForNoneWithoutConversion(project) {
  183. const result = {}
  184. const projectId = project._id
  185. try {
  186. // Logic originally from ProjectHistoryHandler.ensureHistoryExistsForProject
  187. // However sends a force resync project to project history instead
  188. // of a resync request to doc-updater
  189. let historyId = await ProjectHistoryHandler.promises.getHistoryId(projectId)
  190. if (historyId == null) {
  191. historyId = await HistoryManager.promises.initializeProject(projectId)
  192. if (historyId != null) {
  193. await ProjectHistoryHandler.promises.setHistoryId(projectId, historyId)
  194. }
  195. }
  196. // tell document updater to clear the docs, they will be reloaded with any new history id
  197. await DocumentUpdaterHandler.promises.flushProjectToMongoAndDelete(
  198. projectId
  199. )
  200. // now resync the project
  201. await HistoryManager.promises.resyncProject(projectId, {
  202. force: true,
  203. origin: { kind: 'history-migration' },
  204. })
  205. await HistoryManager.promises.flushProject(projectId)
  206. } catch (err) {
  207. result.error = err
  208. await db.projects.updateOne(
  209. { _id: project._id },
  210. {
  211. $set: {
  212. 'overleaf.history.upgradeFailed': true,
  213. },
  214. }
  215. )
  216. return result
  217. }
  218. await db.projects.updateOne(
  219. { _id: project._id },
  220. {
  221. $set: {
  222. 'overleaf.history.display': true,
  223. 'overleaf.history.upgradedAt': new Date(),
  224. 'overleaf.history.upgradeReason': `none-without-conversion`,
  225. },
  226. }
  227. )
  228. result.upgraded = true
  229. return result
  230. }
  231. async function doUpgradeForNoneWithConversion(project, options = {}) {
  232. const result = {}
  233. const projectId = project._id
  234. // migrateProjectHistory expects project id as a string
  235. const projectIdString = project._id.toString()
  236. try {
  237. if (options.convertLargeDocsToFile) {
  238. result.convertedDocCount = await convertLargeDocsToFile(
  239. projectId,
  240. options.userId
  241. )
  242. }
  243. await ProjectHistoryController.migrateProjectHistory(
  244. projectIdString,
  245. options.migrationOptions
  246. )
  247. } catch (err) {
  248. // if migrateProjectHistory fails, it cleans up by deleting
  249. // the history and unsetting the history id
  250. // therefore a failed project will still look like a 'None with conversion' project
  251. result.error = err
  252. // We set a failed flag so future runs of the script don't automatically retry
  253. await db.projects.updateOne(
  254. { _id: projectId },
  255. {
  256. $set: {
  257. 'overleaf.history.conversionFailed': true,
  258. },
  259. }
  260. )
  261. return result
  262. }
  263. await db.projects.updateOne(
  264. { _id: projectId },
  265. {
  266. $set: {
  267. 'overleaf.history.upgradeReason':
  268. `none-with-conversion` + options.reason ? `/${options.reason}` : ``,
  269. },
  270. $unset: {
  271. 'overleaf.history.upgradeFailed': true,
  272. 'overleaf.history.conversionFailed': true,
  273. },
  274. }
  275. )
  276. result.upgraded = true
  277. return result
  278. }
  279. // Util
  280. function projectCreatedAfterFullProjectHistoryEnabled(project) {
  281. if (DATETIME_WHEN_FULL_PROJECT_HISTORY_ENABLED == null) {
  282. return false
  283. } else {
  284. return (
  285. project._id.getTimestamp() >= DATETIME_WHEN_FULL_PROJECT_HISTORY_ENABLED
  286. )
  287. }
  288. }
  289. async function shouldPreserveHistory(project) {
  290. return await db.projectHistoryMetaData.findOne(
  291. {
  292. $and: [
  293. { project_id: { $eq: project._id } },
  294. { preserveHistory: { $eq: true } },
  295. ],
  296. },
  297. { readPreference: ReadPreference.SECONDARY }
  298. )
  299. }
  300. async function anyDocHistoryExists(project) {
  301. return await db.docHistory.findOne(
  302. { project_id: { $eq: project._id } },
  303. {
  304. projection: { _id: 1 },
  305. readPreference: ReadPreference.SECONDARY,
  306. }
  307. )
  308. }
  309. async function anyDocHistoryIndexExists(project) {
  310. return await db.docHistoryIndex.findOne(
  311. { project_id: { $eq: project._id } },
  312. {
  313. projection: { _id: 1 },
  314. readPreference: ReadPreference.SECONDARY,
  315. }
  316. )
  317. }
  318. async function convertLargeDocsToFile(projectId, userId) {
  319. const docs = await ProjectEntityHandler.promises.getAllDocs(projectId)
  320. let convertedDocCount = 0
  321. for (const doc of Object.values(docs)) {
  322. const sizeBound = JSON.stringify(doc.lines)
  323. if (docIsTooLarge(sizeBound, doc.lines, Settings.max_doc_length)) {
  324. await ProjectEntityUpdateHandler.promises.convertDocToFile(
  325. projectId,
  326. doc._id,
  327. userId,
  328. null
  329. )
  330. convertedDocCount++
  331. }
  332. }
  333. return convertedDocCount
  334. }
  335. // check whether the total size of the document in characters exceeds the
  336. // maxDocLength.
  337. //
  338. // Copied from document-updater:
  339. // https://github.com/overleaf/internal/blob/74adfbebda5f3c2c37d9937f0db5c4106ecde492/services/document-updater/app/js/Limits.js#L18
  340. function docIsTooLarge(estimatedSize, lines, maxDocLength) {
  341. if (estimatedSize <= maxDocLength) {
  342. return false // definitely under the limit, no need to calculate the total size
  343. }
  344. // calculate the total size, bailing out early if the size limit is reached
  345. let size = 0
  346. for (const line of lines) {
  347. size += line.length + 1 // include the newline
  348. if (size > maxDocLength) return true
  349. }
  350. // since we didn't hit the limit in the loop, the document is within the allowed length
  351. return false
  352. }
  353. module.exports = {
  354. countProjects,
  355. countDocHistory,
  356. findProjects,
  357. determineProjectHistoryType,
  358. getUpgradeFunctionForType,
  359. upgradeProject,
  360. convertLargeDocsToFile,
  361. anyDocHistoryExists,
  362. anyDocHistoryIndexExists,
  363. doUpgradeForNoneWithConversion,
  364. }