serviceWorker.js 17 KB

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