project-snapshot.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. const DOWNLOAD_BLOBS_CONCURRENCY = 10
  6. /**
  7. * Project snapshot container with on-demand refresh
  8. */
  9. export class ProjectSnapshot {
  10. private projectId: string
  11. private snapshot: Snapshot
  12. private version: number
  13. private blobStore: SimpleBlobStore
  14. private refreshPromise: Promise<void>
  15. private initialized: boolean
  16. private refreshing: boolean
  17. private queued: boolean
  18. constructor(projectId: string) {
  19. this.projectId = projectId
  20. this.snapshot = new Snapshot()
  21. this.version = 0
  22. this.refreshPromise = Promise.resolve()
  23. this.initialized = false
  24. this.refreshing = false
  25. this.queued = false
  26. this.blobStore = new SimpleBlobStore(this.projectId)
  27. }
  28. /**
  29. * Request a refresh of the snapshot.
  30. *
  31. * When the returned promise resolves, the snapshot is guaranteed to have been
  32. * updated at least to the version of the document that was current when the
  33. * function was called.
  34. */
  35. async refresh() {
  36. if (this.queued) {
  37. // There already is a queued refresh that will run after this call.
  38. // Just wait for it to complete.
  39. await this.refreshPromise
  40. } else if (this.refreshing) {
  41. // There is a refresh running, but no queued refresh. Queue a refresh
  42. // after this one and make it the new promise to wait for.
  43. this.refreshPromise = this.queueRefresh()
  44. await this.refreshPromise
  45. } else {
  46. // There is no refresh running. Start one.
  47. this.refreshPromise = this.startRefresh()
  48. await this.refreshPromise
  49. }
  50. }
  51. /**
  52. * Get the list of paths to editable docs.
  53. */
  54. getDocPaths(): string[] {
  55. const allPaths = this.snapshot.getFilePathnames()
  56. return allPaths.filter(path => this.snapshot.getFile(path)?.isEditable())
  57. }
  58. /**
  59. * Get the list of paths to binary files.
  60. */
  61. getBinaryFilePathsWithHash(): { path: string; hash: string; size: number }[] {
  62. const allPaths = this.snapshot.getFilePathnames()
  63. const paths = []
  64. for (const path of allPaths) {
  65. const file = this.snapshot.getFile(path)
  66. if (file == null || file.isEditable()) {
  67. continue
  68. }
  69. const hash = file.getHash()
  70. const size = file.getByteLength()
  71. if (hash == null) {
  72. continue
  73. }
  74. if (size == null) {
  75. continue
  76. }
  77. paths.push({ path, hash, size })
  78. }
  79. return paths
  80. }
  81. /**
  82. * Get the doc content at the given path.
  83. */
  84. getDocContents(path: string): string | null {
  85. const file = this.snapshot.getFile(path)
  86. if (file == null) {
  87. return null
  88. }
  89. return file.getContent({ filterTrackedDeletes: true }) ?? null
  90. }
  91. async getBinaryFileContents(
  92. path: string,
  93. options?: { maxSize?: number }
  94. ): Promise<any> {
  95. const file = this.snapshot.getFile(path)
  96. const hash = file?.getHash()
  97. if (hash == null) {
  98. return null
  99. }
  100. return await this.blobStore.getString(hash, options)
  101. }
  102. getDocs(): Map<string, File> {
  103. const files = new Map()
  104. for (const path of this.snapshot.getFilePathnames()) {
  105. const file = this.snapshot.getFile(path)
  106. if (file?.isEditable()) {
  107. files.set(path, file)
  108. }
  109. }
  110. return files
  111. }
  112. /**
  113. * Immediately start a refresh
  114. */
  115. private async startRefresh() {
  116. this.refreshing = true
  117. try {
  118. if (!this.initialized) {
  119. await this.initialize()
  120. } else {
  121. await this.loadChanges()
  122. }
  123. } finally {
  124. this.refreshing = false
  125. }
  126. }
  127. /**
  128. * Queue a refresh after the currently running refresh
  129. */
  130. private async queueRefresh() {
  131. this.queued = true
  132. try {
  133. await this.refreshPromise
  134. } catch {
  135. // Ignore errors
  136. }
  137. this.queued = false
  138. await this.startRefresh()
  139. }
  140. /**
  141. * Initialize the snapshot using the project's latest chunk.
  142. *
  143. * This is run on the first refresh.
  144. */
  145. private async initialize() {
  146. await flushHistory(this.projectId)
  147. const chunk = await fetchLatestChunk(this.projectId)
  148. this.snapshot = chunk.getSnapshot()
  149. this.snapshot.applyAll(chunk.getChanges())
  150. this.version = chunk.getEndVersion()
  151. await this.loadDocs()
  152. this.initialized = true
  153. }
  154. /**
  155. * Apply changes since the last refresh.
  156. *
  157. * This is run on the second and subsequent refreshes
  158. */
  159. private async loadChanges() {
  160. await flushHistory(this.projectId)
  161. let hasMore = true
  162. while (hasMore) {
  163. const response = await fetchLatestChanges(this.projectId, this.version)
  164. const changes = response.changes
  165. this.snapshot.applyAll(changes)
  166. this.version += changes.length
  167. hasMore = response.hasMore
  168. }
  169. await this.loadDocs()
  170. }
  171. /**
  172. * Load all editable docs in the snapshot.
  173. *
  174. * This is done by converting any lazy file data into an "eager" file data. If
  175. * a doc is already loaded, the load is a no-op.
  176. */
  177. private async loadDocs() {
  178. const paths = this.getDocPaths()
  179. const limit = pLimit(DOWNLOAD_BLOBS_CONCURRENCY)
  180. await Promise.all(
  181. paths.map(path =>
  182. limit(async () => {
  183. const file = this.snapshot.getFile(path)
  184. await file?.load('eager', this.blobStore)
  185. })
  186. )
  187. )
  188. }
  189. }
  190. /**
  191. * Blob store that fetches blobs from the history service
  192. */
  193. class SimpleBlobStore {
  194. private projectId: string
  195. constructor(projectId: string) {
  196. this.projectId = projectId
  197. }
  198. async getString(
  199. hash: string,
  200. options?: { maxSize?: number }
  201. ): Promise<string> {
  202. return await fetchBlob(this.projectId, hash, options)
  203. }
  204. async getObject(hash: string) {
  205. const blob = await this.getString(hash)
  206. return JSON.parse(blob)
  207. }
  208. }
  209. async function flushHistory(projectId: string) {
  210. await postJSON(`/project/${projectId}/flush`)
  211. }
  212. async function fetchLatestChunk(projectId: string): Promise<Chunk> {
  213. const response = await getJSON<{ chunk: RawChunk }>(
  214. `/project/${projectId}/latest/history`
  215. )
  216. return Chunk.fromRaw(response.chunk)
  217. }
  218. type FetchLatestChangesResponse = {
  219. changes: Change[]
  220. hasMore: boolean
  221. }
  222. type FetchLatestChangesApiResponse =
  223. | RawChange[]
  224. | {
  225. changes: RawChange[]
  226. hasMore: boolean
  227. }
  228. async function fetchLatestChanges(
  229. projectId: string,
  230. version: number
  231. ): Promise<FetchLatestChangesResponse> {
  232. // TODO: The paginated flag is a transition flag. It can be removed after this
  233. // code has been deployed for a few weeks.
  234. const response = await getJSON<FetchLatestChangesApiResponse>(
  235. `/project/${projectId}/changes?since=${version}&paginated=true`
  236. )
  237. let changes, hasMore
  238. if (Array.isArray(response)) {
  239. // deprecated response format is a simple array of changes
  240. // TODO: Remove this branch after the transition
  241. changes = response
  242. hasMore = false
  243. } else {
  244. changes = response.changes
  245. hasMore = response.hasMore
  246. }
  247. return {
  248. changes: changes.map(Change.fromRaw).filter(change => change != null),
  249. hasMore,
  250. }
  251. }
  252. async function fetchBlob(
  253. projectId: string,
  254. hash: string,
  255. options?: { maxSize?: number }
  256. ): Promise<string> {
  257. const url = `/project/${projectId}/blob/${hash}`
  258. if (options?.maxSize) {
  259. return await fetchTextFileWithSizeLimit(url, options.maxSize)
  260. }
  261. const res = await fetch(url)
  262. if (!res.ok) {
  263. throw new FetchError('Failed to fetch blob', url, undefined, res)
  264. }
  265. return await res.text()
  266. }
  267. async function fetchTextFileWithSizeLimit(url: string, maxSize: number) {
  268. let result = ''
  269. try {
  270. const abortController = new AbortController()
  271. const response = await fetch(url, {
  272. signal: abortController.signal,
  273. })
  274. if (!response.ok) {
  275. throw new Error('Failed to fetch blob')
  276. }
  277. if (!response.body) {
  278. throw new Error('Response body is empty')
  279. }
  280. const reader = response.body.pipeThrough(new TextDecoderStream())
  281. for await (const chunk of reader) {
  282. result += chunk
  283. if (result.length > maxSize) {
  284. abortController.abort()
  285. }
  286. }
  287. } catch (error: any) {
  288. if (error?.name === 'AbortError') {
  289. // This is fine, we just return the result we have so far
  290. } else {
  291. throw error
  292. }
  293. }
  294. return result.slice(0, maxSize)
  295. }