serviceWorker.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. import { v4 as uuid } from 'uuid'
  2. const OError = require('@overleaf/o-error')
  3. const COMPILE_REQUEST_MATCHER = /^\/project\/[0-9a-f]{24}\/compile$/
  4. const PDF_REQUEST_MATCHER = /^\/project\/[0-9a-f]{24}\/.*\/output.pdf$/
  5. const PDF_JS_CHUNK_SIZE = 128 * 1024
  6. const MAX_SUBREQUEST_COUNT = 8
  7. const MAX_SUBREQUEST_BYTES = 4 * PDF_JS_CHUNK_SIZE
  8. // Each compile request defines a context (essentially the specific pdf file for
  9. // that compile), requests for that pdf file can use the hashes in the compile
  10. // response, which are stored in the context.
  11. const CLIENT_CONTEXT = new Map()
  12. /**
  13. * @param {string} clientId
  14. */
  15. function getClientContext(clientId) {
  16. let clientContext = CLIENT_CONTEXT.get(clientId)
  17. if (!clientContext) {
  18. const pdfs = new Map()
  19. const metrics = {
  20. id: uuid(),
  21. epoch: Date.now(),
  22. cachedBytes: 0,
  23. fetchedBytes: 0,
  24. requestedBytes: 0,
  25. }
  26. clientContext = { pdfs, metrics }
  27. CLIENT_CONTEXT.set(clientId, clientContext)
  28. // clean up old client maps
  29. expirePdfContexts()
  30. }
  31. return clientContext
  32. }
  33. /**
  34. * @param {string} clientId
  35. * @param {string} path
  36. * @param {Object} pdfContext
  37. */
  38. function registerPdfContext(clientId, path, pdfContext) {
  39. const clientContext = getClientContext(clientId)
  40. const { pdfs, metrics } = clientContext
  41. pdfContext.metrics = metrics
  42. // we only need to keep the last 3 contexts
  43. for (const key of pdfs.keys()) {
  44. if (pdfs.size < 3) {
  45. break
  46. }
  47. pdfs.delete(key) // the map keys are returned in insertion order, so we are deleting the oldest entry here
  48. }
  49. pdfs.set(path, pdfContext)
  50. }
  51. /**
  52. * @param {string} clientId
  53. * @param {string} path
  54. */
  55. function getPdfContext(clientId, path) {
  56. const { pdfs } = getClientContext(clientId)
  57. return pdfs.get(path)
  58. }
  59. function expirePdfContexts() {
  60. // discard client maps for clients that are no longer connected
  61. const currentClientSet = new Set()
  62. self.clients.matchAll().then(function (clientList) {
  63. clientList.forEach(client => {
  64. currentClientSet.add(client.id)
  65. })
  66. CLIENT_CONTEXT.forEach((map, clientId) => {
  67. if (!currentClientSet.has(clientId)) {
  68. CLIENT_CONTEXT.delete(clientId)
  69. }
  70. })
  71. })
  72. }
  73. /**
  74. *
  75. * @param {Object} metrics
  76. * @param {number} size
  77. * @param {number} cachedBytes
  78. * @param {number} fetchedBytes
  79. */
  80. function trackDownloadStats(metrics, { size, cachedBytes, fetchedBytes }) {
  81. metrics.cachedBytes += cachedBytes
  82. metrics.fetchedBytes += fetchedBytes
  83. metrics.requestedBytes += size
  84. }
  85. /**
  86. * @param {Object} metrics
  87. * @param {boolean} sizeDiffers
  88. * @param {boolean} mismatch
  89. * @param {boolean} success
  90. */
  91. function trackChunkVerify(metrics, { sizeDiffers, mismatch, success }) {
  92. if (sizeDiffers) {
  93. metrics.chunkVerifySizeDiffers |= 0
  94. metrics.chunkVerifySizeDiffers += 1
  95. }
  96. if (mismatch) {
  97. metrics.chunkVerifyMismatch |= 0
  98. metrics.chunkVerifyMismatch += 1
  99. }
  100. if (success) {
  101. metrics.chunkVerifySuccess |= 0
  102. metrics.chunkVerifySuccess += 1
  103. }
  104. }
  105. /**
  106. * @param {Array} chunks
  107. */
  108. function countBytes(chunks) {
  109. return chunks.reduce((totalBytes, chunk) => {
  110. return totalBytes + (chunk.end - chunk.start)
  111. }, 0)
  112. }
  113. /**
  114. * @param {FetchEvent} event
  115. */
  116. function onFetch(event) {
  117. const url = new URL(event.request.url)
  118. const path = url.pathname
  119. if (path.match(COMPILE_REQUEST_MATCHER)) {
  120. return processCompileRequest(event)
  121. }
  122. if (path.match(PDF_REQUEST_MATCHER)) {
  123. const ctx = getPdfContext(event.clientId, path)
  124. if (ctx) {
  125. return processPdfRequest(event, ctx)
  126. }
  127. }
  128. // other request, ignore
  129. }
  130. /**
  131. * @param {FetchEvent} event
  132. */
  133. function processCompileRequest(event) {
  134. event.respondWith(
  135. fetch(event.request).then(response => {
  136. if (response.status !== 200) return response
  137. return response.json().then(body => {
  138. handleCompileResponse(event, response, body)
  139. // Send the service workers metrics to the frontend.
  140. const { metrics } = getClientContext(event.clientId)
  141. body.serviceWorkerMetrics = metrics
  142. return new Response(JSON.stringify(body), response)
  143. })
  144. })
  145. )
  146. }
  147. /**
  148. * @param {Request} request
  149. * @param {Object} file
  150. * @return {Response}
  151. */
  152. function handleProbeRequest(request, file) {
  153. // PDF.js starts the pdf download with a probe request that has no
  154. // range headers on it.
  155. // Upon seeing the response headers, it decides whether to upgrade the
  156. // transport to chunked requests or keep reading the response body.
  157. // For small PDFs (2*chunkSize = 2*128kB) it just sends one request.
  158. // We will fetch all the ranges in bulk and emit them.
  159. // For large PDFs it sends this probe request, aborts that request before
  160. // reading any data and then sends multiple range requests.
  161. // It would be wasteful to action this probe request with all the ranges
  162. // that are available in the PDF and serve the full PDF content to
  163. // PDF.js for the probe request.
  164. // We are emitting a dummy response to the probe request instead.
  165. // It triggers the chunked transfer and subsequent fewer ranges need to be
  166. // requested -- only those of visible pages in the pdf viewer.
  167. // https://github.com/mozilla/pdf.js/blob/6fd899dc443425747098935207096328e7b55eb2/src/display/network_utils.js#L43-L47
  168. const pdfJSWillUseChunkedTransfer = file.size > 2 * PDF_JS_CHUNK_SIZE
  169. const isRangeRequest = request.headers.has('Range')
  170. if (!isRangeRequest && pdfJSWillUseChunkedTransfer) {
  171. const headers = new Headers()
  172. headers.set('Accept-Ranges', 'bytes')
  173. headers.set('Content-Length', file.size)
  174. headers.set('Content-Type', 'application/pdf')
  175. return new Response('', {
  176. headers,
  177. status: 200,
  178. statusText: 'OK',
  179. })
  180. }
  181. }
  182. /**
  183. *
  184. * @param {FetchEvent} event
  185. * @param {Object} file
  186. * @param {string} clsiServerId
  187. * @param {string} compileGroup
  188. * @param {Date} pdfCreatedAt
  189. * @param {Object} metrics
  190. */
  191. function processPdfRequest(
  192. event,
  193. { file, clsiServerId, compileGroup, pdfCreatedAt, metrics }
  194. ) {
  195. const response = handleProbeRequest(event.request, file)
  196. if (response) {
  197. return event.respondWith(response)
  198. }
  199. const verifyChunks = event.request.url.includes('verify_chunks=true')
  200. const rangeHeader =
  201. event.request.headers.get('Range') || `bytes=0-${file.size - 1}`
  202. const [start, last] = rangeHeader
  203. .slice('bytes='.length)
  204. .split('-')
  205. .map(i => parseInt(i, 10))
  206. const end = last + 1
  207. // Check that handling the range request won't trigger excessive subrequests,
  208. // (to avoid unwanted latency compared to the original request).
  209. const chunks = getMatchingChunks(file.ranges, start, end)
  210. const dynamicChunks = getInterleavingDynamicChunks(chunks, start, end)
  211. const chunksSize = countBytes(chunks)
  212. if (chunks.length + dynamicChunks.length > MAX_SUBREQUEST_COUNT) {
  213. // fall back to the original range request when splitting the range creates
  214. // too many subrequests.
  215. return
  216. }
  217. if (
  218. chunksSize > MAX_SUBREQUEST_BYTES &&
  219. !(dynamicChunks.length === 0 && chunks.length === 1)
  220. ) {
  221. // fall back to the original range request when a very large amount of
  222. // object data would be requested, unless it is the only object in the
  223. // request.
  224. return
  225. }
  226. // URL prefix is /project/:id/user/:id/build/... or /project/:id/build/...
  227. // for authenticated and unauthenticated users respectively.
  228. const perUserPrefix = file.url.slice(0, file.url.indexOf('/build/'))
  229. const requests = chunks
  230. .map(chunk => {
  231. const path = `${perUserPrefix}/content/${file.contentId}/${chunk.hash}`
  232. const url = new URL(path, event.request.url)
  233. if (clsiServerId) {
  234. url.searchParams.set('clsiserverid', clsiServerId)
  235. }
  236. if (compileGroup) {
  237. url.searchParams.set('compileGroup', compileGroup)
  238. }
  239. return { chunk, url: url.toString() }
  240. })
  241. .concat(
  242. dynamicChunks.map(chunk => {
  243. const { start, end } = chunk
  244. return {
  245. chunk,
  246. url: event.request.url,
  247. init: { headers: { Range: `bytes=${start}-${end - 1}` } },
  248. }
  249. })
  250. )
  251. const size = end - start
  252. let cachedBytes = 0
  253. let fetchedBytes = 0
  254. const reAssembledBlob = new Uint8Array(size)
  255. event.respondWith(
  256. Promise.all(
  257. requests.map(({ chunk, url, init }) =>
  258. fetch(url, init)
  259. .then(response => {
  260. if (!(response.status === 206 || response.status === 200)) {
  261. throw new OError(
  262. 'non successful response status: ' + response.status
  263. )
  264. }
  265. const blobFetchDate = getServerTime(response)
  266. const blobSize = getResponseSize(response)
  267. if (blobFetchDate && blobSize) {
  268. const chunkSize =
  269. Math.min(end, chunk.end) - Math.max(start, chunk.start)
  270. // Example: 2MB PDF, 1MB image, 128KB PDF.js chunk.
  271. // | pdf.js chunk |
  272. // | A BIG IMAGE BLOB |
  273. // | THE FULL PDF |
  274. if (blobFetchDate < pdfCreatedAt) {
  275. cachedBytes += chunkSize
  276. } else {
  277. // Blobs are fetched in bulk.
  278. fetchedBytes += blobSize
  279. }
  280. }
  281. return response.arrayBuffer()
  282. })
  283. .then(arrayBuffer => {
  284. return {
  285. chunk,
  286. data: backFillObjectContext(chunk, arrayBuffer),
  287. }
  288. })
  289. .catch(error => {
  290. throw OError.tag(error, 'cannot fetch chunk', { url })
  291. })
  292. )
  293. )
  294. .then(responses => {
  295. responses.forEach(({ chunk, data }) => {
  296. // overlap:
  297. // | REQUESTED_RANGE |
  298. // | CHUNK |
  299. const offsetStart = Math.max(start - chunk.start, 0)
  300. // overlap:
  301. // | REQUESTED_RANGE |
  302. // | CHUNK |
  303. const offsetEnd = Math.max(chunk.end - end, 0)
  304. if (offsetStart > 0 || offsetEnd > 0) {
  305. // compute index positions for slice to handle case where offsetEnd=0
  306. const chunkSize = chunk.end - chunk.start
  307. data = data.slice(offsetStart, chunkSize - offsetEnd)
  308. }
  309. const insertPosition = Math.max(chunk.start - start, 0)
  310. reAssembledBlob.set(data, insertPosition)
  311. })
  312. let verifyProcess = Promise.resolve(reAssembledBlob)
  313. if (verifyChunks) {
  314. verifyProcess = fetch(event.request)
  315. .then(response => response.arrayBuffer())
  316. .then(arrayBuffer => {
  317. const fullBlob = new Uint8Array(arrayBuffer)
  318. const stats = {}
  319. if (reAssembledBlob.byteLength !== fullBlob.byteLength) {
  320. stats.sizeDiffers = true
  321. } else if (
  322. !reAssembledBlob.every((v, idx) => v === fullBlob[idx])
  323. ) {
  324. stats.mismatch = true
  325. } else {
  326. stats.success = true
  327. }
  328. trackChunkVerify(metrics, stats)
  329. if (stats.success === true) {
  330. return reAssembledBlob
  331. } else {
  332. return fullBlob
  333. }
  334. })
  335. }
  336. return verifyProcess.then(blob => {
  337. trackDownloadStats(metrics, { size, cachedBytes, fetchedBytes })
  338. return new Response(blob, {
  339. status: 206,
  340. headers: {
  341. 'Accept-Ranges': 'bytes',
  342. 'Content-Length': size,
  343. 'Content-Range': `bytes ${start}-${last}/${file.size}`,
  344. 'Content-Type': 'application/pdf',
  345. },
  346. })
  347. })
  348. })
  349. .catch(error => {
  350. reportError(event, OError.tag(error, 'failed to compose pdf response'))
  351. return fetch(event.request)
  352. })
  353. )
  354. }
  355. /**
  356. *
  357. * @param {Response} response
  358. */
  359. function getServerTime(response) {
  360. const raw = response.headers.get('Date')
  361. if (!raw) return new Date()
  362. return new Date(raw)
  363. }
  364. /**
  365. *
  366. * @param {Response} response
  367. */
  368. function getResponseSize(response) {
  369. const raw = response.headers.get('Content-Length')
  370. if (!raw) return 0
  371. return parseInt(raw, 10)
  372. }
  373. /**
  374. * @param {FetchEvent} event
  375. * @param {Response} response
  376. * @param {Object} body
  377. */
  378. function handleCompileResponse(event, response, body) {
  379. if (!body || body.status !== 'success') return
  380. const pdfCreatedAt = getServerTime(response)
  381. for (const file of body.outputFiles) {
  382. if (file.path !== 'output.pdf') continue // not the pdf used for rendering
  383. if (file.ranges) {
  384. file.ranges.forEach(backFillEdgeBounds)
  385. const { clsiServerId, compileGroup } = body
  386. registerPdfContext(event.clientId, file.url, {
  387. pdfCreatedAt,
  388. file,
  389. clsiServerId,
  390. compileGroup,
  391. })
  392. }
  393. break
  394. }
  395. }
  396. const ENCODER = new TextEncoder()
  397. function backFillEdgeBounds(chunk) {
  398. if (chunk.objectId) {
  399. chunk.objectId = ENCODER.encode(chunk.objectId)
  400. chunk.start -= chunk.objectId.byteLength
  401. }
  402. return chunk
  403. }
  404. /**
  405. * @param chunk
  406. * @param {ArrayBuffer} arrayBuffer
  407. * @return {Uint8Array}
  408. */
  409. function backFillObjectContext(chunk, arrayBuffer) {
  410. if (!chunk.objectId) {
  411. // This is a dynamic chunk
  412. return new Uint8Array(arrayBuffer)
  413. }
  414. const { start, end, objectId } = chunk
  415. const header = Uint8Array.from(objectId)
  416. const fullBuffer = new Uint8Array(end - start)
  417. fullBuffer.set(header, 0)
  418. fullBuffer.set(new Uint8Array(arrayBuffer), objectId.length)
  419. return fullBuffer
  420. }
  421. /**
  422. * @param {Array} chunks
  423. * @param {number} start
  424. * @param {number} end
  425. * @returns {Array}
  426. */
  427. function getMatchingChunks(chunks, start, end) {
  428. const matchingChunks = []
  429. for (const chunk of chunks) {
  430. if (chunk.end <= start) {
  431. // no overlap:
  432. // | REQUESTED_RANGE |
  433. // | CHUNK |
  434. continue
  435. }
  436. if (chunk.start >= end) {
  437. // no overlap:
  438. // | REQUESTED_RANGE |
  439. // | CHUNK |
  440. break
  441. }
  442. matchingChunks.push(chunk)
  443. }
  444. return matchingChunks
  445. }
  446. /**
  447. * @param {Array} chunks
  448. * @param {number} start
  449. * @param {number} end
  450. * @returns {Array}
  451. */
  452. function getInterleavingDynamicChunks(chunks, start, end) {
  453. const dynamicChunks = []
  454. for (const chunk of chunks) {
  455. if (start < chunk.start) {
  456. dynamicChunks.push({ start, end: chunk.start })
  457. }
  458. start = chunk.end
  459. }
  460. if (start < end) {
  461. dynamicChunks.push({ start, end })
  462. }
  463. return dynamicChunks
  464. }
  465. /**
  466. * @param {FetchEvent} event
  467. */
  468. function onFetchWithErrorHandling(event) {
  469. try {
  470. onFetch(event)
  471. } catch (error) {
  472. reportError(event, OError.tag(error, 'low level error in onFetch'))
  473. }
  474. }
  475. // listen to all network requests
  476. self.addEventListener('fetch', onFetchWithErrorHandling)
  477. // complete setup ASAP
  478. self.addEventListener('install', event => {
  479. event.waitUntil(self.skipWaiting())
  480. })
  481. self.addEventListener('activate', event => {
  482. event.waitUntil(self.clients.claim())
  483. })
  484. /**
  485. *
  486. * @param {FetchEvent} event
  487. * @param {Error} error
  488. */
  489. function reportError(event, error) {
  490. self.clients
  491. .get(event.clientId)
  492. .then(client => {
  493. if (!client) {
  494. // The client disconnected.
  495. return
  496. }
  497. client.postMessage(
  498. JSON.stringify({
  499. extra: { url: event.request.url, info: OError.getFullInfo(error) },
  500. error: {
  501. name: error.name,
  502. message: error.message,
  503. stack: OError.getFullStack(error),
  504. },
  505. })
  506. )
  507. })
  508. .catch(() => {})
  509. }