project-snapshot.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. import pLimit from 'p-limit'
  2. import { Change, Chunk, Snapshot, File } from 'overleaf-editor-core'
  3. import { RawChange, RawChunk } from 'overleaf-editor-core/lib/types'
  4. import { FetchError, getJSON, postJSON } from '@/infrastructure/fetch-json'
  5. import path from 'path-browserify'
  6. const DOWNLOAD_BLOBS_CONCURRENCY = 10
  7. /**
  8. * Project snapshot container with on-demand refresh
  9. */
  10. export class ProjectSnapshot {
  11. private projectId: string
  12. private snapshot: Snapshot
  13. private version: number
  14. private blobStore: SimpleBlobStore
  15. private refreshPromise: Promise<void>
  16. private initialized: boolean
  17. private refreshing: boolean
  18. private queued: boolean
  19. constructor(projectId: string) {
  20. this.projectId = projectId
  21. this.snapshot = new Snapshot()
  22. this.version = 0
  23. this.refreshPromise = Promise.resolve()
  24. this.initialized = false
  25. this.refreshing = false
  26. this.queued = false
  27. this.blobStore = new SimpleBlobStore(this.projectId)
  28. }
  29. /**
  30. * Request a refresh of the snapshot.
  31. *
  32. * When the returned promise resolves, the snapshot is guaranteed to have been
  33. * updated at least to the version of the document that was current when the
  34. * function was called.
  35. */
  36. async refresh() {
  37. if (this.queued) {
  38. // There already is a queued refresh that will run after this call.
  39. // Just wait for it to complete.
  40. await this.refreshPromise
  41. } else if (this.refreshing) {
  42. // There is a refresh running, but no queued refresh. Queue a refresh
  43. // after this one and make it the new promise to wait for.
  44. this.refreshPromise = this.queueRefresh()
  45. await this.refreshPromise
  46. } else {
  47. // There is no refresh running. Start one.
  48. this.refreshPromise = this.startRefresh()
  49. await this.refreshPromise
  50. }
  51. }
  52. /**
  53. * Get the list of paths to editable docs.
  54. */
  55. getDocPaths(): string[] {
  56. const allPaths = this.snapshot.getFilePathnames()
  57. return allPaths.filter(path => this.snapshot.getFile(path)?.isEditable())
  58. }
  59. /**
  60. * Get the list of paths to binary files.
  61. */
  62. getBinaryFilePathsWithHash(): { path: string; hash: string; size: number }[] {
  63. const allPaths = this.snapshot.getFilePathnames()
  64. const paths = []
  65. for (const path of allPaths) {
  66. const file = this.snapshot.getFile(path)
  67. if (file == null || file.isEditable()) {
  68. continue
  69. }
  70. const hash = file.getHash()
  71. const size = file.getByteLength()
  72. if (hash == null) {
  73. continue
  74. }
  75. if (size == null) {
  76. continue
  77. }
  78. paths.push({ path, hash, size })
  79. }
  80. return paths
  81. }
  82. /**
  83. * Use an algorithm similar to Kpathsea to locate files in the project snapshot:
  84. *
  85. * 1. look for the exact path relative to the root path
  86. * 2. look for the path + extension relative to the root path
  87. * 3. look for the exact path relative to the current path
  88. * 4. look for the path + extension relative to the current path
  89. */
  90. locateFile(filePath: string, currentPath = '/', extensions = ['.tex']) {
  91. // ignore absolute paths
  92. if (filePath.startsWith('/')) {
  93. return null
  94. }
  95. const snapshotPaths = new Set(this.snapshot.getFilePathnames())
  96. const basePaths = [
  97. // relative to the root of the compile directory
  98. '/',
  99. ]
  100. if (currentPath !== '/') {
  101. // relative to the current directory
  102. basePaths.push(currentPath)
  103. }
  104. const extensionsToTest = ['', ...extensions]
  105. for (const basePath of basePaths) {
  106. for (const extension of extensionsToTest) {
  107. const pathname = path.resolve(basePath, `${filePath}${extension}`)
  108. const snapshotPath = pathname.substring(1) // remove leading slash
  109. if (snapshotPaths.has(snapshotPath)) {
  110. return snapshotPath
  111. }
  112. }
  113. }
  114. return null
  115. }
  116. /**
  117. * Get the doc content at the given path.
  118. */
  119. getDocContents(path: string): string | null {
  120. const file = this.snapshot.getFile(path)
  121. if (file == null) {
  122. return null
  123. }
  124. return file.getContent({ filterTrackedDeletes: true }) ?? null
  125. }
  126. async getBinaryFileContents(
  127. path: string,
  128. options?: { maxSize?: number }
  129. ): Promise<any> {
  130. const file = this.snapshot.getFile(path)
  131. const hash = file?.getHash()
  132. const byteLength = file?.getByteLength()
  133. if (hash == null) {
  134. return null
  135. }
  136. if (byteLength == null) {
  137. return null
  138. }
  139. let blobStoreOptions
  140. if (options?.maxSize != null && byteLength > options?.maxSize) {
  141. blobStoreOptions = { maxSize: options.maxSize }
  142. }
  143. return await this.blobStore.getString(hash, blobStoreOptions)
  144. }
  145. getDocs(): Map<string, File> {
  146. const files = new Map()
  147. for (const path of this.snapshot.getFilePathnames()) {
  148. const file = this.snapshot.getFile(path)
  149. if (file?.isEditable()) {
  150. files.set(path, file)
  151. }
  152. }
  153. return files
  154. }
  155. /**
  156. * Immediately start a refresh
  157. */
  158. private async startRefresh() {
  159. this.refreshing = true
  160. try {
  161. if (!this.initialized) {
  162. await this.initialize()
  163. } else {
  164. await this.loadChanges()
  165. }
  166. } finally {
  167. this.refreshing = false
  168. }
  169. }
  170. /**
  171. * Queue a refresh after the currently running refresh
  172. */
  173. private async queueRefresh() {
  174. this.queued = true
  175. try {
  176. await this.refreshPromise
  177. } catch {
  178. // Ignore errors
  179. }
  180. this.queued = false
  181. await this.startRefresh()
  182. }
  183. /**
  184. * Initialize the snapshot using the project's latest chunk.
  185. *
  186. * This is run on the first refresh.
  187. */
  188. private async initialize() {
  189. await flushHistory(this.projectId)
  190. const chunk = await fetchLatestChunk(this.projectId)
  191. this.snapshot = chunk.getSnapshot()
  192. this.snapshot.applyAll(chunk.getChanges())
  193. this.version = chunk.getEndVersion()
  194. await this.loadDocs()
  195. this.initialized = true
  196. }
  197. /**
  198. * Apply changes since the last refresh.
  199. *
  200. * This is run on the second and subsequent refreshes
  201. */
  202. private async loadChanges() {
  203. await flushHistory(this.projectId)
  204. let hasMore = true
  205. while (hasMore) {
  206. const response = await fetchLatestChanges(this.projectId, this.version)
  207. const changes = response.changes
  208. this.snapshot.applyAll(changes)
  209. this.version += changes.length
  210. hasMore = response.hasMore
  211. }
  212. await this.loadDocs()
  213. }
  214. /**
  215. * Load all editable docs in the snapshot.
  216. *
  217. * This is done by converting any lazy file data into an "eager" file data. If
  218. * a doc is already loaded, the load is a no-op.
  219. */
  220. private async loadDocs() {
  221. const paths = this.getDocPaths()
  222. const limit = pLimit(DOWNLOAD_BLOBS_CONCURRENCY)
  223. await Promise.all(
  224. paths.map(path =>
  225. limit(async () => {
  226. const file = this.snapshot.getFile(path)
  227. await file?.load('eager', this.blobStore)
  228. })
  229. )
  230. )
  231. }
  232. }
  233. /**
  234. * Blob store that fetches blobs from the history service
  235. */
  236. export class SimpleBlobStore {
  237. private projectId: string
  238. constructor(projectId: string) {
  239. this.projectId = projectId
  240. }
  241. async getString(
  242. hash: string,
  243. options?: { maxSize?: number }
  244. ): Promise<string> {
  245. return await fetchBlob(this.projectId, hash, options)
  246. }
  247. async getObject(hash: string) {
  248. const blob = await this.getString(hash)
  249. return JSON.parse(blob)
  250. }
  251. }
  252. async function flushHistory(projectId: string) {
  253. await postJSON(`/project/${projectId}/flush`)
  254. }
  255. export async function fetchLatestChunk(projectId: string): Promise<Chunk> {
  256. const response = await getJSON<{ chunk: RawChunk }>(
  257. `/project/${projectId}/latest/history`
  258. )
  259. return Chunk.fromRaw(response.chunk)
  260. }
  261. type FetchLatestChangesResponse = {
  262. changes: Change[]
  263. hasMore: boolean
  264. }
  265. type FetchLatestChangesApiResponse =
  266. | RawChange[]
  267. | {
  268. changes: RawChange[]
  269. hasMore: boolean
  270. }
  271. async function fetchLatestChanges(
  272. projectId: string,
  273. version: number
  274. ): Promise<FetchLatestChangesResponse> {
  275. // TODO: The paginated flag is a transition flag. It can be removed after this
  276. // code has been deployed for a few weeks.
  277. const response = await getJSON<FetchLatestChangesApiResponse>(
  278. `/project/${projectId}/changes?since=${version}&paginated=true`
  279. )
  280. let changes, hasMore
  281. if (Array.isArray(response)) {
  282. // deprecated response format is a simple array of changes
  283. // TODO: Remove this branch after the transition
  284. changes = response
  285. hasMore = false
  286. } else {
  287. changes = response.changes
  288. hasMore = response.hasMore
  289. }
  290. return {
  291. changes: changes.map(Change.fromRaw).filter(change => change != null),
  292. hasMore,
  293. }
  294. }
  295. async function fetchBlob(
  296. projectId: string,
  297. hash: string,
  298. options?: { maxSize?: number }
  299. ): Promise<string> {
  300. const url = `/project/${projectId}/blob/${hash}`
  301. let fetchOpts
  302. if (options?.maxSize === 0) {
  303. return ''
  304. }
  305. if (options?.maxSize) {
  306. fetchOpts = {
  307. headers: {
  308. Range: `bytes=0-${options.maxSize - 1}`,
  309. },
  310. }
  311. }
  312. const res = await fetch(url, fetchOpts)
  313. if (!res.ok) {
  314. throw new FetchError('Failed to fetch blob', url, undefined, res)
  315. }
  316. // Use arrayBuffer + TextDecoder rather than res.text() to preserve any
  317. // UTF-8 BOM (U+FEFF) in the blob content. The server stores blobs as-is
  318. // and includes the BOM in stringLength, so text operations are built
  319. // against a BOM-inclusive length. Response.text() strips the BOM per the
  320. // Encoding spec, making the string 1 char shorter than expected and causing
  321. // ApplyError when the operations are applied.
  322. const buffer = await res.arrayBuffer()
  323. return new TextDecoder('utf-8', { ignoreBOM: true }).decode(buffer)
  324. }