HistoryManager.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. const { callbackify } = require('util')
  2. const { fetchJson, fetchNothing } = require('@overleaf/fetch-utils')
  3. const settings = require('@overleaf/settings')
  4. const OError = require('@overleaf/o-error')
  5. const UserGetter = require('../User/UserGetter')
  6. const ProjectGetter = require('../Project/ProjectGetter')
  7. const HistoryBackupDeletionHandler = require('./HistoryBackupDeletionHandler')
  8. async function initializeProject(projectId) {
  9. const body = await fetchJson(`${settings.apis.project_history.url}/project`, {
  10. method: 'POST',
  11. json: { historyId: projectId.toString() },
  12. })
  13. const historyId = body && body.project && body.project.id
  14. if (!historyId) {
  15. throw new OError('project-history did not provide an id', { body })
  16. }
  17. return historyId
  18. }
  19. async function flushProject(projectId) {
  20. try {
  21. await fetchNothing(
  22. `${settings.apis.project_history.url}/project/${projectId}/flush`,
  23. { method: 'POST' }
  24. )
  25. } catch (err) {
  26. throw OError.tag(err, 'failed to flush project to project history', {
  27. projectId,
  28. })
  29. }
  30. }
  31. async function deleteProjectHistory(projectId) {
  32. try {
  33. await fetchNothing(
  34. `${settings.apis.project_history.url}/project/${projectId}`,
  35. { method: 'DELETE' }
  36. )
  37. } catch (err) {
  38. throw OError.tag(err, 'failed to delete project history', {
  39. projectId,
  40. })
  41. }
  42. }
  43. async function resyncProject(projectId, options = {}) {
  44. const body = {}
  45. if (options.force) {
  46. body.force = options.force
  47. }
  48. if (options.origin) {
  49. body.origin = options.origin
  50. }
  51. if (options.historyRangesMigration) {
  52. body.historyRangesMigration = options.historyRangesMigration
  53. }
  54. try {
  55. await fetchNothing(
  56. `${settings.apis.project_history.url}/project/${projectId}/resync`,
  57. {
  58. method: 'POST',
  59. json: body,
  60. signal: AbortSignal.timeout(6 * 60 * 1000),
  61. }
  62. )
  63. } catch (err) {
  64. throw OError.tag(err, 'failed to resync project history', {
  65. projectId,
  66. })
  67. }
  68. }
  69. async function deleteProject(projectId, historyId) {
  70. const tasks = []
  71. tasks.push(_deleteProjectInProjectHistory(projectId))
  72. if (historyId != null) {
  73. tasks.push(_deleteProjectInFullProjectHistory(historyId))
  74. }
  75. await Promise.all(tasks)
  76. await HistoryBackupDeletionHandler.deleteProject(projectId)
  77. }
  78. async function _deleteProjectInProjectHistory(projectId) {
  79. try {
  80. await fetchNothing(
  81. `${settings.apis.project_history.url}/project/${projectId}`,
  82. { method: 'DELETE' }
  83. )
  84. } catch (err) {
  85. throw OError.tag(
  86. err,
  87. 'failed to clear project history in project-history',
  88. { projectId }
  89. )
  90. }
  91. }
  92. async function _deleteProjectInFullProjectHistory(historyId) {
  93. try {
  94. await fetchNothing(
  95. `${settings.apis.v1_history.url}/projects/${historyId}`,
  96. {
  97. method: 'DELETE',
  98. basicAuth: {
  99. user: settings.apis.v1_history.user,
  100. password: settings.apis.v1_history.pass,
  101. },
  102. }
  103. )
  104. } catch (err) {
  105. throw OError.tag(err, 'failed to clear project history', { historyId })
  106. }
  107. }
  108. /**
  109. * Warning: Don't use this method for large projects. It will eagerly load all
  110. * the history data and apply all operations.
  111. * @param {string} projectId
  112. * @returns Promise<object>
  113. */
  114. async function getCurrentContent(projectId) {
  115. const project = await ProjectGetter.promises.getProject(projectId, {
  116. overleaf: true,
  117. })
  118. const historyId = project?.overleaf?.history?.id
  119. if (!historyId) {
  120. throw new OError('project does not have a history id', { projectId })
  121. }
  122. try {
  123. return await fetchJson(
  124. `${settings.apis.v1_history.url}/projects/${historyId}/latest/content`,
  125. {
  126. method: 'GET',
  127. basicAuth: {
  128. user: settings.apis.v1_history.user,
  129. password: settings.apis.v1_history.pass,
  130. },
  131. }
  132. )
  133. } catch (err) {
  134. throw OError.tag(err, 'failed to load project history', { historyId })
  135. }
  136. }
  137. /**
  138. * Warning: Don't use this method for large projects. It will eagerly load all
  139. * the history data and apply all operations.
  140. * @param {string} projectId
  141. * @param {number} version
  142. *
  143. * @returns Promise<object>
  144. */
  145. async function getContentAtVersion(projectId, version) {
  146. const project = await ProjectGetter.promises.getProject(projectId, {
  147. overleaf: true,
  148. })
  149. const historyId = project?.overleaf?.history?.id
  150. if (!historyId) {
  151. throw new OError('project does not have a history id', { projectId })
  152. }
  153. try {
  154. return await fetchJson(
  155. `${settings.apis.v1_history.url}/projects/${historyId}/versions/${version}/content`,
  156. {
  157. method: 'GET',
  158. basicAuth: {
  159. user: settings.apis.v1_history.user,
  160. password: settings.apis.v1_history.pass,
  161. },
  162. }
  163. )
  164. } catch (err) {
  165. throw OError.tag(
  166. err,
  167. 'failed to load project history snapshot at version',
  168. { historyId, version }
  169. )
  170. }
  171. }
  172. async function injectUserDetails(data) {
  173. // data can be either:
  174. // {
  175. // diff: [{
  176. // i: "foo",
  177. // meta: {
  178. // users: ["user_id", v1_user_id, ...]
  179. // ...
  180. // }
  181. // }, ...]
  182. // }
  183. // or
  184. // {
  185. // updates: [{
  186. // pathnames: ["main.tex"]
  187. // meta: {
  188. // users: ["user_id", v1_user_id, ...]
  189. // ...
  190. // },
  191. // ...
  192. // }, ...]
  193. // }
  194. // Either way, the top level key points to an array of objects with a meta.users property
  195. // that we need to replace user_ids with populated user objects.
  196. // Note that some entries in the users arrays may be v1 ids returned by the v1 history
  197. // service. v1 ids will be `numbers`
  198. let userIds = new Set()
  199. let v1UserIds = new Set()
  200. const entries = Array.isArray(data.diff)
  201. ? data.diff
  202. : Array.isArray(data.updates)
  203. ? data.updates
  204. : []
  205. for (const entry of entries) {
  206. for (const user of (entry.meta && entry.meta.users) || []) {
  207. if (typeof user === 'string') {
  208. userIds.add(user)
  209. } else if (typeof user === 'number') {
  210. v1UserIds.add(user)
  211. }
  212. }
  213. }
  214. userIds = Array.from(userIds)
  215. v1UserIds = Array.from(v1UserIds)
  216. const projection = { first_name: 1, last_name: 1, email: 1 }
  217. const usersArray = await UserGetter.promises.getUsers(userIds, projection)
  218. const users = {}
  219. for (const user of usersArray) {
  220. users[user._id.toString()] = _userView(user)
  221. }
  222. projection.overleaf = 1
  223. const v1IdentifiedUsersArray = await UserGetter.promises.getUsersByV1Ids(
  224. v1UserIds,
  225. projection
  226. )
  227. for (const user of v1IdentifiedUsersArray) {
  228. users[user.overleaf.id] = _userView(user)
  229. }
  230. for (const entry of entries) {
  231. if (entry.meta != null) {
  232. entry.meta.users = ((entry.meta && entry.meta.users) || []).map(user => {
  233. if (typeof user === 'string' || typeof user === 'number') {
  234. return users[user]
  235. } else {
  236. return user
  237. }
  238. })
  239. }
  240. }
  241. return data
  242. }
  243. function _userView(user) {
  244. const { _id, first_name: firstName, last_name: lastName, email } = user
  245. return { first_name: firstName, last_name: lastName, email, id: _id }
  246. }
  247. module.exports = {
  248. initializeProject: callbackify(initializeProject),
  249. flushProject: callbackify(flushProject),
  250. resyncProject: callbackify(resyncProject),
  251. deleteProject: callbackify(deleteProject),
  252. deleteProjectHistory: callbackify(deleteProjectHistory),
  253. injectUserDetails: callbackify(injectUserDetails),
  254. getCurrentContent: callbackify(getCurrentContent),
  255. promises: {
  256. initializeProject,
  257. flushProject,
  258. resyncProject,
  259. deleteProject,
  260. injectUserDetails,
  261. deleteProjectHistory,
  262. getCurrentContent,
  263. getContentAtVersion,
  264. },
  265. }