serviceWorker.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  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. // Keep in sync with PdfJsMetrics.
  6. const VERSION = 2
  7. const CLEAR_CACHE_REQUEST_MATCHER = /^\/project\/[0-9a-f]{24}\/output$/
  8. const COMPILE_REQUEST_MATCHER = /^\/project\/[0-9a-f]{24}\/compile$/
  9. const PDF_REQUEST_MATCHER =
  10. /^(\/zone\/.)?(\/project\/[0-9a-f]{24}\/.*\/output.pdf)$/
  11. const PDF_JS_CHUNK_SIZE = 128 * 1024
  12. const MAX_SUBREQUEST_COUNT = 4
  13. const MAX_SUBREQUEST_BYTES = 4 * PDF_JS_CHUNK_SIZE
  14. const INCREMENTAL_CACHE_SIZE = 1000
  15. // Each compile request defines a context (essentially the specific pdf file for
  16. // that compile), requests for that pdf file can use the hashes in the compile
  17. // response, which are stored in the context.
  18. const CLIENT_CONTEXT = new Map()
  19. /**
  20. * @param {string} clientId
  21. */
  22. function getClientContext(clientId) {
  23. let clientContext = CLIENT_CONTEXT.get(clientId)
  24. if (!clientContext) {
  25. const cached = new Set()
  26. const pdfs = new Map()
  27. const metrics = {
  28. version: VERSION,
  29. id: uuid(),
  30. epoch: Date.now(),
  31. failedCount: 0,
  32. tooLargeOverheadCount: 0,
  33. tooManyRequestsCount: 0,
  34. cachedCount: 0,
  35. cachedBytes: 0,
  36. fetchedCount: 0,
  37. fetchedBytes: 0,
  38. requestedCount: 0,
  39. requestedBytes: 0,
  40. compileCount: 0,
  41. }
  42. clientContext = { pdfs, metrics, cached }
  43. CLIENT_CONTEXT.set(clientId, clientContext)
  44. // clean up old client maps
  45. expirePdfContexts()
  46. }
  47. return clientContext
  48. }
  49. /**
  50. * @param {string} clientId
  51. * @param {string} path
  52. * @param {Object} pdfContext
  53. */
  54. function registerPdfContext(clientId, path, pdfContext) {
  55. const clientContext = getClientContext(clientId)
  56. const { pdfs, metrics, cached, clsiServerId } = clientContext
  57. pdfContext.metrics = metrics
  58. pdfContext.cached = cached
  59. if (pdfContext.clsiServerId !== clsiServerId) {
  60. // VM changed, this invalidates all browser caches.
  61. clientContext.clsiServerId = pdfContext.clsiServerId
  62. cached.clear()
  63. }
  64. // we only need to keep the last 3 contexts
  65. for (const key of pdfs.keys()) {
  66. if (pdfs.size < 3) {
  67. break
  68. }
  69. pdfs.delete(key) // the map keys are returned in insertion order, so we are deleting the oldest entry here
  70. }
  71. pdfs.set(path, pdfContext)
  72. }
  73. /**
  74. * @param {string} clientId
  75. * @param {string} path
  76. */
  77. function getPdfContext(clientId, path) {
  78. const { pdfs } = getClientContext(clientId)
  79. return pdfs.get(path)
  80. }
  81. function expirePdfContexts() {
  82. // discard client maps for clients that are no longer connected
  83. const currentClientSet = new Set()
  84. self.clients.matchAll().then(function (clientList) {
  85. clientList.forEach(client => {
  86. currentClientSet.add(client.id)
  87. })
  88. CLIENT_CONTEXT.forEach((map, clientId) => {
  89. if (!currentClientSet.has(clientId)) {
  90. CLIENT_CONTEXT.delete(clientId)
  91. }
  92. })
  93. })
  94. }
  95. /**
  96. *
  97. * @param {Object} metrics
  98. * @param {number} size
  99. * @param {number} cachedCount
  100. * @param {number} cachedBytes
  101. * @param {number} fetchedCount
  102. * @param {number} fetchedBytes
  103. */
  104. function trackDownloadStats(
  105. metrics,
  106. { size, cachedCount, cachedBytes, fetchedCount, fetchedBytes }
  107. ) {
  108. metrics.cachedCount += cachedCount
  109. metrics.cachedBytes += cachedBytes
  110. metrics.fetchedCount += fetchedCount
  111. metrics.fetchedBytes += fetchedBytes
  112. metrics.requestedCount++
  113. metrics.requestedBytes += size
  114. }
  115. /**
  116. * @param {Object} metrics
  117. * @param {boolean} sizeDiffers
  118. * @param {boolean} mismatch
  119. * @param {boolean} success
  120. */
  121. function trackChunkVerify(metrics, { sizeDiffers, mismatch, success }) {
  122. if (sizeDiffers) {
  123. metrics.chunkVerifySizeDiffers |= 0
  124. metrics.chunkVerifySizeDiffers += 1
  125. }
  126. if (mismatch) {
  127. metrics.chunkVerifyMismatch |= 0
  128. metrics.chunkVerifyMismatch += 1
  129. }
  130. if (success) {
  131. metrics.chunkVerifySuccess |= 0
  132. metrics.chunkVerifySuccess += 1
  133. }
  134. }
  135. /**
  136. * @param {Array} chunks
  137. */
  138. function countBytes(chunks) {
  139. return chunks.reduce((totalBytes, chunk) => {
  140. return totalBytes + (chunk.end - chunk.start)
  141. }, 0)
  142. }
  143. /**
  144. * @param {FetchEvent} event
  145. */
  146. function onFetch(event) {
  147. const url = new URL(event.request.url)
  148. const path = url.pathname
  149. if (path.match(COMPILE_REQUEST_MATCHER)) {
  150. return processCompileRequest(event)
  151. }
  152. const match = path.match(PDF_REQUEST_MATCHER)
  153. if (match) {
  154. const ctx = getPdfContext(event.clientId, match[2])
  155. if (ctx) {
  156. return processPdfRequest(event, ctx)
  157. }
  158. }
  159. if (
  160. event.request.method === 'DELETE' &&
  161. path.match(CLEAR_CACHE_REQUEST_MATCHER)
  162. ) {
  163. return processClearCacheRequest(event)
  164. }
  165. // other request, ignore
  166. }
  167. /**
  168. * @param {FetchEvent} event
  169. */
  170. function processClearCacheRequest(event) {
  171. CLIENT_CONTEXT.delete(event.clientId)
  172. // use default request proxy.
  173. }
  174. /**
  175. * @param {FetchEvent} event
  176. */
  177. function processCompileRequest(event) {
  178. event.respondWith(
  179. fetch(event.request).then(response => {
  180. if (response.status !== 200) return response
  181. return response.json().then(body => {
  182. handleCompileResponse(event, response, body)
  183. // Send the service workers metrics to the frontend.
  184. const { metrics } = getClientContext(event.clientId)
  185. metrics.compileCount++
  186. body.serviceWorkerMetrics = metrics
  187. return new Response(JSON.stringify(body), response)
  188. })
  189. })
  190. )
  191. }
  192. /**
  193. * @param {Request} request
  194. * @param {Object} file
  195. * @return {Response}
  196. */
  197. function handleProbeRequest(request, file) {
  198. // PDF.js starts the pdf download with a probe request that has no
  199. // range headers on it.
  200. // Upon seeing the response headers, it decides whether to upgrade the
  201. // transport to chunked requests or keep reading the response body.
  202. // For small PDFs (2*chunkSize = 2*128kB) it just sends one request.
  203. // We will fetch all the ranges in bulk and emit them.
  204. // For large PDFs it sends this probe request, aborts that request before
  205. // reading any data and then sends multiple range requests.
  206. // It would be wasteful to action this probe request with all the ranges
  207. // that are available in the PDF and serve the full PDF content to
  208. // PDF.js for the probe request.
  209. // We are emitting a dummy response to the probe request instead.
  210. // It triggers the chunked transfer and subsequent fewer ranges need to be
  211. // requested -- only those of visible pages in the pdf viewer.
  212. // https://github.com/mozilla/pdf.js/blob/6fd899dc443425747098935207096328e7b55eb2/src/display/network_utils.js#L43-L47
  213. const pdfJSWillUseChunkedTransfer = file.size > 2 * PDF_JS_CHUNK_SIZE
  214. const isRangeRequest = request.headers.has('Range')
  215. if (!isRangeRequest && pdfJSWillUseChunkedTransfer) {
  216. const headers = new Headers()
  217. headers.set('Accept-Ranges', 'bytes')
  218. headers.set('Content-Length', file.size)
  219. headers.set('Content-Type', 'application/pdf')
  220. return new Response('', {
  221. headers,
  222. status: 200,
  223. statusText: 'OK',
  224. })
  225. }
  226. }
  227. /**
  228. *
  229. * @param {FetchEvent} event
  230. * @param {Object} file
  231. * @param {string} clsiServerId
  232. * @param {string} compileGroup
  233. * @param {Date} pdfCreatedAt
  234. * @param {Object} metrics
  235. * @param {Set} cached
  236. */
  237. function processPdfRequest(
  238. event,
  239. { file, clsiServerId, compileGroup, pdfCreatedAt, metrics, cached }
  240. ) {
  241. const response = handleProbeRequest(event.request, file)
  242. if (response) {
  243. return event.respondWith(response)
  244. }
  245. const verifyChunks = event.request.url.includes('verify_chunks=true')
  246. const rangeHeader =
  247. event.request.headers.get('Range') || `bytes=0-${file.size - 1}`
  248. const [start, last] = rangeHeader
  249. .slice('bytes='.length)
  250. .split('-')
  251. .map(i => parseInt(i, 10))
  252. const end = last + 1
  253. // Check that handling the range request won't trigger excessive subrequests,
  254. // (to avoid unwanted latency compared to the original request).
  255. const { chunks, newChunks } = cutRequestAmplification(
  256. getMatchingChunks(file.ranges, start, end),
  257. cached,
  258. metrics
  259. )
  260. const dynamicChunks = getInterleavingDynamicChunks(chunks, start, end)
  261. const chunksSize = countBytes(newChunks)
  262. const size = end - start
  263. if (chunks.length === 0 && dynamicChunks.length === 1) {
  264. // fall back to the original range request when no chunks are cached.
  265. trackDownloadStats(metrics, {
  266. size,
  267. cachedCount: 0,
  268. cachedBytes: 0,
  269. fetchedCount: 1,
  270. fetchedBytes: size,
  271. })
  272. return
  273. }
  274. if (
  275. chunksSize > MAX_SUBREQUEST_BYTES &&
  276. !(dynamicChunks.length === 0 && newChunks.length <= 1)
  277. ) {
  278. // fall back to the original range request when a very large amount of
  279. // object data would be requested, unless it is the only object in the
  280. // request or everything is already cached.
  281. metrics.tooLargeOverheadCount++
  282. trackDownloadStats(metrics, {
  283. size,
  284. cachedCount: 0,
  285. cachedBytes: 0,
  286. fetchedCount: 1,
  287. fetchedBytes: size,
  288. })
  289. return
  290. }
  291. // URL prefix is /project/:id/user/:id/build/... or /project/:id/build/...
  292. // for authenticated and unauthenticated users respectively.
  293. const perUserPrefix = file.url.slice(0, file.url.indexOf('/build/'))
  294. const byteRanges = dynamicChunks
  295. .map(chunk => `${chunk.start}-${chunk.end - 1}`)
  296. .join(',')
  297. const coalescedDynamicChunks = []
  298. switch (dynamicChunks.length) {
  299. case 0:
  300. break
  301. case 1:
  302. coalescedDynamicChunks.push({
  303. chunk: dynamicChunks[0],
  304. url: event.request.url,
  305. init: { headers: { Range: `bytes=${byteRanges}` } },
  306. })
  307. break
  308. default:
  309. coalescedDynamicChunks.push({
  310. chunk: dynamicChunks,
  311. url: event.request.url,
  312. init: { headers: { Range: `bytes=${byteRanges}` } },
  313. })
  314. }
  315. const requests = chunks
  316. .map(chunk => {
  317. const path = `${perUserPrefix}/content/${file.contentId}/${chunk.hash}`
  318. const url = new URL(path, event.request.url)
  319. if (clsiServerId) {
  320. url.searchParams.set('clsiserverid', clsiServerId)
  321. }
  322. if (compileGroup) {
  323. url.searchParams.set('compileGroup', compileGroup)
  324. }
  325. return { chunk, url: url.toString() }
  326. })
  327. .concat(coalescedDynamicChunks)
  328. let cachedCount = 0
  329. let cachedBytes = 0
  330. let fetchedCount = 0
  331. let fetchedBytes = 0
  332. const reAssembledBlob = new Uint8Array(size)
  333. event.respondWith(
  334. Promise.all(
  335. requests.map(({ chunk, url, init }) =>
  336. fetch(url, init)
  337. .then(response => {
  338. if (!(response.status === 206 || response.status === 200)) {
  339. throw new OError(
  340. 'non successful response status: ' + response.status
  341. )
  342. }
  343. const boundary = getMultipartBoundary(response)
  344. if (Array.isArray(chunk) && !boundary) {
  345. throw new OError('missing boundary on multipart request', {
  346. headers: Object.fromEntries(response.headers.entries()),
  347. chunk,
  348. })
  349. }
  350. const blobFetchDate = getServerTime(response)
  351. const blobSize = getResponseSize(response)
  352. if (blobFetchDate && blobSize) {
  353. const chunkSize =
  354. Math.min(end, chunk.end) - Math.max(start, chunk.start)
  355. // Example: 2MB PDF, 1MB image, 128KB PDF.js chunk.
  356. // | pdf.js chunk |
  357. // | A BIG IMAGE BLOB |
  358. // | THE FULL PDF |
  359. if (blobFetchDate < pdfCreatedAt) {
  360. cachedCount++
  361. cachedBytes += chunkSize
  362. // Roll the position of the hash in the Map.
  363. cached.delete(chunk.hash)
  364. cached.add(chunk.hash)
  365. } else {
  366. // Blobs are fetched in bulk.
  367. fetchedCount++
  368. fetchedBytes += blobSize
  369. }
  370. }
  371. return response
  372. .blob()
  373. .then(blob => blob.arrayBuffer())
  374. .then(arraybuffer => {
  375. return {
  376. boundary,
  377. chunk,
  378. data: backFillObjectContext(chunk, arraybuffer),
  379. }
  380. })
  381. })
  382. .catch(error => {
  383. throw OError.tag(error, 'cannot fetch chunk', { url })
  384. })
  385. )
  386. )
  387. .then(rawResponses => {
  388. const responses = []
  389. for (const response of rawResponses) {
  390. if (response.boundary) {
  391. responses.push(
  392. ...getMultiPartResponses(response, file, metrics, verifyChunks)
  393. )
  394. } else {
  395. responses.push(response)
  396. }
  397. }
  398. responses.forEach(({ chunk, data }) => {
  399. // overlap:
  400. // | REQUESTED_RANGE |
  401. // | CHUNK |
  402. const offsetStart = Math.max(start - chunk.start, 0)
  403. // overlap:
  404. // | REQUESTED_RANGE |
  405. // | CHUNK |
  406. const offsetEnd = Math.max(chunk.end - end, 0)
  407. if (offsetStart > 0 || offsetEnd > 0) {
  408. // compute index positions for slice to handle case where offsetEnd=0
  409. const chunkSize = chunk.end - chunk.start
  410. data = data.subarray(offsetStart, chunkSize - offsetEnd)
  411. }
  412. const insertPosition = Math.max(chunk.start - start, 0)
  413. reAssembledBlob.set(data, insertPosition)
  414. })
  415. let verifyProcess = Promise.resolve(reAssembledBlob)
  416. if (verifyChunks) {
  417. verifyProcess = fetch(event.request)
  418. .then(response => response.arrayBuffer())
  419. .then(arrayBuffer => {
  420. const fullBlob = new Uint8Array(arrayBuffer)
  421. const stats = {}
  422. if (reAssembledBlob.byteLength !== fullBlob.byteLength) {
  423. stats.sizeDiffers = true
  424. } else if (
  425. !reAssembledBlob.every((v, idx) => v === fullBlob[idx])
  426. ) {
  427. stats.mismatch = true
  428. } else {
  429. stats.success = true
  430. }
  431. trackChunkVerify(metrics, stats)
  432. if (stats.success === true) {
  433. return reAssembledBlob
  434. } else {
  435. return fullBlob
  436. }
  437. })
  438. }
  439. return verifyProcess.then(blob => {
  440. trackDownloadStats(metrics, {
  441. size,
  442. cachedCount,
  443. cachedBytes,
  444. fetchedCount,
  445. fetchedBytes,
  446. })
  447. return new Response(blob, {
  448. status: 206,
  449. headers: {
  450. 'Accept-Ranges': 'bytes',
  451. 'Content-Length': size,
  452. 'Content-Range': `bytes ${start}-${last}/${file.size}`,
  453. 'Content-Type': 'application/pdf',
  454. },
  455. })
  456. })
  457. })
  458. .catch(error => {
  459. fetchedBytes += size
  460. metrics.failedCount++
  461. trackDownloadStats(metrics, {
  462. size,
  463. cachedCount: 0,
  464. cachedBytes: 0,
  465. fetchedCount,
  466. fetchedBytes,
  467. })
  468. reportError(event, OError.tag(error, 'failed to compose pdf response'))
  469. return fetch(event.request)
  470. })
  471. )
  472. }
  473. /**
  474. *
  475. * @param {Response} response
  476. */
  477. function getServerTime(response) {
  478. const raw = response.headers.get('Date')
  479. if (!raw) return new Date()
  480. return new Date(raw)
  481. }
  482. /**
  483. *
  484. * @param {Response} response
  485. */
  486. function getResponseSize(response) {
  487. const raw = response.headers.get('Content-Length')
  488. if (!raw) return 0
  489. return parseInt(raw, 10)
  490. }
  491. /**
  492. *
  493. * @param {Response} response
  494. */
  495. function getMultipartBoundary(response) {
  496. const raw = response.headers.get('Content-Type')
  497. if (!raw.includes('multipart/byteranges')) return ''
  498. const idx = raw.indexOf('boundary=')
  499. if (idx === -1) return ''
  500. return raw.slice(idx + 'boundary='.length)
  501. }
  502. /**
  503. * @param {Object} response
  504. * @param {Object} file
  505. * @param {Object} metrics
  506. * @param {boolean} verifyChunks
  507. */
  508. function getMultiPartResponses(response, file, metrics, verifyChunks) {
  509. const { chunk: chunks, data, boundary } = response
  510. const responses = []
  511. let offsetStart = 0
  512. for (const chunk of chunks) {
  513. const header = `\r\n--${boundary}\r\nContent-Type: application/pdf\r\nContent-Range: bytes ${
  514. chunk.start
  515. }-${chunk.end - 1}/${file.size}\r\n\r\n`
  516. const headerSize = header.length
  517. // Verify header content. A proxy might have tampered with it.
  518. const headerRaw = ENCODER.encode(header)
  519. if (
  520. !data
  521. .subarray(offsetStart, offsetStart + headerSize)
  522. .every((v, idx) => v === headerRaw[idx])
  523. ) {
  524. metrics.headerVerifyFailure |= 0
  525. metrics.headerVerifyFailure++
  526. throw new OError('multipart response header does not match', {
  527. actual: new TextDecoder().decode(
  528. data.subarray(offsetStart, offsetStart + headerSize)
  529. ),
  530. expected: header,
  531. })
  532. }
  533. offsetStart += headerSize
  534. const chunkSize = chunk.end - chunk.start
  535. responses.push({
  536. chunk,
  537. data: data.subarray(offsetStart, offsetStart + chunkSize),
  538. })
  539. offsetStart += chunkSize
  540. }
  541. return responses
  542. }
  543. /**
  544. * @param {FetchEvent} event
  545. * @param {Response} response
  546. * @param {Object} body
  547. */
  548. function handleCompileResponse(event, response, body) {
  549. if (!body || body.status !== 'success') return
  550. const pdfCreatedAt = getServerTime(response)
  551. for (const file of body.outputFiles) {
  552. if (file.path !== 'output.pdf') continue // not the pdf used for rendering
  553. if (file.ranges) {
  554. file.ranges.forEach(backFillEdgeBounds)
  555. const { clsiServerId, compileGroup } = body
  556. registerPdfContext(event.clientId, file.url, {
  557. pdfCreatedAt,
  558. file,
  559. clsiServerId,
  560. compileGroup,
  561. })
  562. }
  563. break
  564. }
  565. }
  566. const ENCODER = new TextEncoder()
  567. function backFillEdgeBounds(chunk) {
  568. if (chunk.objectId) {
  569. chunk.objectId = ENCODER.encode(chunk.objectId)
  570. chunk.start -= chunk.objectId.byteLength
  571. }
  572. return chunk
  573. }
  574. /**
  575. * @param chunk
  576. * @param {ArrayBuffer} arrayBuffer
  577. * @return {Uint8Array}
  578. */
  579. function backFillObjectContext(chunk, arrayBuffer) {
  580. if (!chunk.objectId) {
  581. // This is a dynamic chunk
  582. return new Uint8Array(arrayBuffer)
  583. }
  584. const { start, end, objectId } = chunk
  585. const header = Uint8Array.from(objectId)
  586. const fullBuffer = new Uint8Array(end - start)
  587. fullBuffer.set(header, 0)
  588. fullBuffer.set(new Uint8Array(arrayBuffer), objectId.length)
  589. return fullBuffer
  590. }
  591. /**
  592. * @param {Array} chunks
  593. * @param {number} start
  594. * @param {number} end
  595. * @returns {Array}
  596. */
  597. function getMatchingChunks(chunks, start, end) {
  598. const matchingChunks = []
  599. for (const chunk of chunks) {
  600. if (chunk.end <= start) {
  601. // no overlap:
  602. // | REQUESTED_RANGE |
  603. // | CHUNK |
  604. continue
  605. }
  606. if (chunk.start >= end) {
  607. // no overlap:
  608. // | REQUESTED_RANGE |
  609. // | CHUNK |
  610. break
  611. }
  612. matchingChunks.push(chunk)
  613. }
  614. return matchingChunks
  615. }
  616. /**
  617. * @param {Array} potentialChunks
  618. * @param {Set} cached
  619. * @param {Object} metrics
  620. */
  621. function cutRequestAmplification(potentialChunks, cached, metrics) {
  622. const chunks = []
  623. const newChunks = []
  624. let tooManyRequests = false
  625. for (const chunk of potentialChunks) {
  626. if (cached.has(chunk.hash)) {
  627. chunks.push(chunk)
  628. continue
  629. }
  630. if (newChunks.length < MAX_SUBREQUEST_COUNT) {
  631. chunks.push(chunk)
  632. newChunks.push(chunk)
  633. } else {
  634. tooManyRequests = true
  635. }
  636. }
  637. if (tooManyRequests) {
  638. metrics.tooManyRequestsCount++
  639. }
  640. if (cached.size > INCREMENTAL_CACHE_SIZE) {
  641. for (const key of cached) {
  642. if (cached.size < INCREMENTAL_CACHE_SIZE) {
  643. break
  644. }
  645. // Map keys are stored in insertion order.
  646. // We re-insert keys on cache hit, 'cached' is a cheap LRU.
  647. cached.delete(key)
  648. }
  649. }
  650. return { chunks, newChunks }
  651. }
  652. /**
  653. * @param {Array} chunks
  654. * @param {number} start
  655. * @param {number} end
  656. * @returns {Array}
  657. */
  658. function getInterleavingDynamicChunks(chunks, start, end) {
  659. const dynamicChunks = []
  660. for (const chunk of chunks) {
  661. if (start < chunk.start) {
  662. dynamicChunks.push({ start, end: chunk.start })
  663. }
  664. start = chunk.end
  665. }
  666. if (start < end) {
  667. dynamicChunks.push({ start, end })
  668. }
  669. return dynamicChunks
  670. }
  671. /**
  672. * @param {FetchEvent} event
  673. */
  674. function onFetchWithErrorHandling(event) {
  675. try {
  676. onFetch(event)
  677. } catch (error) {
  678. reportError(event, OError.tag(error, 'low level error in onFetch'))
  679. }
  680. }
  681. // allow fetch event listener to be removed if necessary
  682. const controller = new AbortController()
  683. // listen to all network requests
  684. self.addEventListener('fetch', onFetchWithErrorHandling, {
  685. signal: controller.signal,
  686. })
  687. // complete setup ASAP
  688. self.addEventListener('install', event => {
  689. event.waitUntil(self.skipWaiting())
  690. })
  691. self.addEventListener('activate', event => {
  692. event.waitUntil(self.clients.claim())
  693. })
  694. self.addEventListener('message', event => {
  695. if (event.data && event.data.type === 'disable') {
  696. controller.abort() // removes the fetch event listener
  697. }
  698. })
  699. /**
  700. *
  701. * @param {FetchEvent} event
  702. * @param {Error} error
  703. */
  704. function reportError(event, error) {
  705. self.clients
  706. .get(event.clientId)
  707. .then(client => {
  708. if (!client) {
  709. // The client disconnected.
  710. return
  711. }
  712. client.postMessage(
  713. JSON.stringify({
  714. extra: { url: event.request.url, info: OError.getFullInfo(error) },
  715. error: {
  716. name: error.name,
  717. message: error.message,
  718. stack: OError.getFullStack(error),
  719. },
  720. })
  721. )
  722. })
  723. .catch(() => {})
  724. }