Skip to content

Commit da4648b

Browse files
authored
fix(app): avoid to cache shared worker requests in service worker (#1173)
Co-authored-by: Andrejs <Leitans>
1 parent 142b2e8 commit da4648b

File tree

7 files changed

+67
-50
lines changed

7 files changed

+67
-50
lines changed

src/components/loader/loader.js

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -211,18 +211,18 @@ const Bootloader = () => {
211211
function bootstrap() {
212212
if ('serviceWorker' in navigator) {
213213
console.log('Going to install service worker');
214-
// TODO: tmp disabled
215-
// window.addEventListener('load', () => {
216-
// console.log('Starting to load service worker');
217-
// navigator.serviceWorker
218-
// .register('/service-worker.js')
219-
// .then((registration) => {
220-
// console.log('service worker registered: ', registration);
221-
// })
222-
// .catch((registrationError) => {
223-
// console.log('service worker registration failed: ', registrationError);
224-
// });
225-
// });
214+
215+
window.addEventListener('load', () => {
216+
console.log('Starting to load service worker');
217+
navigator.serviceWorker
218+
.register('/service-worker.js')
219+
.then((registration) => {
220+
console.log('service worker registered: ', registration);
221+
})
222+
.catch((registrationError) => {
223+
console.log('service worker registration failed: ', registrationError);
224+
});
225+
});
226226
} else {
227227
console.log('No service worker is available');
228228
}
@@ -247,9 +247,8 @@ function bootstrap() {
247247

248248
progressData.innerHTML = `Loading: <span>${Math.round(
249249
progress * 100
250-
)}%</span>. <br/> Network speed: <span>${
251-
Math.round(e.networkSpeed * 100) / 100
252-
} kbps</span>`;
250+
)}%</span>. <br/> Network speed: <span>${Math.round(e.networkSpeed * 100) / 100
251+
} kbps</span>`;
253252

254253
// console.log(e.loaded, e.loaded / e.totalSize); // @TODO
255254
})

src/services/QueueManager/QueueManager.ts

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,43 @@
11
import {
22
BehaviorSubject,
3-
map,
4-
timeout,
5-
throwError,
6-
of,
7-
catchError,
83
EMPTY,
94
Observable,
10-
mergeMap,
5+
catchError,
116
debounceTime,
12-
merge,
13-
tap,
14-
interval,
157
filter,
8+
interval,
9+
map,
10+
merge,
11+
mergeMap,
12+
of,
13+
throwError,
14+
timeout,
1615
} from 'rxjs';
1716

1817
import * as R from 'ramda';
1918

20-
import { fetchIpfsContent } from 'src/services/ipfs/utils/utils-ipfs';
2119
import { CybIpfsNode, IpfsContentSource } from 'src/services/ipfs/types';
20+
import { fetchIpfsContent } from 'src/services/ipfs/utils/utils-ipfs';
2221
import { ParticleCid } from 'src/types/base';
2322

2423
import { promiseToObservable } from '../../utils/rxjs/helpers';
2524

2625
import type {
26+
IDeferredDbSaver,
2727
QueueItem,
28-
QueueItemResult,
28+
QueueItemAsyncResult,
2929
QueueItemCallback,
3030
QueueItemOptions,
31-
QueueStats,
31+
QueueItemResult,
3232
QueueSource,
33-
IDeferredDbSaver,
34-
QueueItemAsyncResult,
33+
QueueStats,
3534
} from './types';
3635

3736
import { QueueStrategy } from './QueueStrategy';
3837

39-
import { QueueItemTimeoutError } from './QueueItemTimeoutError';
4038
import BroadcastChannelSender from '../backend/channels/BroadcastChannelSender';
39+
import { QueueItemTimeoutError } from './QueueItemTimeoutError';
40+
import { CustomHeaders, XCybSourceValues } from './constants';
4141

4242
const QUEUE_DEBOUNCE_MS = 33;
4343
const CONNECTION_KEEPER_RETRY_MS = 5000;
@@ -70,7 +70,7 @@ const strategies = {
7070
helia: new QueueStrategy(
7171
{
7272
db: { timeout: 5000, maxConcurrentExecutions: 999 },
73-
node: { timeout: 6 * 1000, maxConcurrentExecutions: 50 }, //TODO: set to 60
73+
node: { timeout: 6 * 1000, maxConcurrentExecutions: 50 }, // TODO: set to 60
7474
gateway: { timeout: 3 * 1000, maxConcurrentExecutions: 11 },
7575
},
7676
['db', 'node', 'gateway']
@@ -168,6 +168,9 @@ class QueueManager {
168168
const res = await fetchIpfsContent(cid, source, {
169169
controller,
170170
node: this.node,
171+
headers: {
172+
[CustomHeaders.XCybSource]: XCybSourceValues.sharedWorker,
173+
},
171174
}).then((content) => {
172175
this.defferedDbSaver?.enqueueIpfsContent(content);
173176

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
/* eslint-disable import/prefer-default-export */
2+
export const CustomHeaders = {
3+
XCybSource: 'X-Cyb-Source',
4+
};
5+
6+
export enum XCybSourceValues {
7+
sharedWorker = 'shared-worker',
8+
}

src/services/ipfs/utils/utils-ipfs.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ const fetchIPFSContentFromNode = async (
101101
}
102102
default: {
103103
// Get sample of content
104-
const { value: firstChunk, done } = await node
104+
const { value: firstChunk } = await node
105105
.cat(cid, { signal, length: 2048, offset: 0 })
106106
[Symbol.asyncIterator]()
107107
.next();
@@ -154,7 +154,8 @@ const fetchIPFSContentFromNode = async (
154154
const fetchIPFSContentFromGateway = async (
155155
cid: string,
156156
node?: IpfsNode,
157-
controller?: AbortController
157+
controller?: AbortController,
158+
headers?: Record<string, string>
158159
): Promise<IPFSContentMaybe> => {
159160
// fetch META only from external node(toooo slow), TODO: fetch meta from cybernode
160161
const isExternalNode = node?.nodeType === 'external';
@@ -166,6 +167,7 @@ const fetchIPFSContentFromGateway = async (
166167
const response = await fetch(contentUrl, {
167168
method: 'GET',
168169
signal: controller?.signal,
170+
headers,
169171
});
170172

171173
if (response && response.body) {
@@ -210,14 +212,15 @@ const fetchIPFSContentFromGateway = async (
210212
type fetchContentOptions = {
211213
controller?: AbortController;
212214
node?: IpfsNode;
215+
headers?: Record<string, string>;
213216
};
214217

215218
async function fetchIpfsContent(
216219
cid: string,
217220
source: IpfsContentSource,
218221
options: fetchContentOptions
219222
): Promise<IPFSContentMaybe> {
220-
const { node, controller } = options;
223+
const { node, controller, headers } = options;
221224

222225
try {
223226
switch (source) {
@@ -226,7 +229,7 @@ async function fetchIpfsContent(
226229
case 'node':
227230
return fetchIPFSContentFromNode(cid, node, controller);
228231
case 'gateway':
229-
return fetchIPFSContentFromGateway(cid, node, controller);
232+
return fetchIPFSContentFromGateway(cid, node, controller, headers);
230233
default:
231234
return undefined;
232235
}

src/services/service-worker/service-worker.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { matchPrecache, precacheAndRoute } from 'workbox-precaching';
44
import { registerRoute } from 'workbox-routing';
55
import { CacheFirst, NetworkFirst } from 'workbox-strategies';
66
import { ExpirationPlugin } from 'workbox-expiration';
7+
import { CustomHeaders, XCybSourceValues } from '../QueueManager/constants';
78

89
declare const self: ServiceWorkerGlobalScope;
910

@@ -68,6 +69,8 @@ registerRoute(
6869
({ request }) =>
6970
request.method === 'GET' &&
7071
request.destination !== 'document' &&
72+
request.headers.get(CustomHeaders.XCybSource) !==
73+
XCybSourceValues.sharedWorker &&
7174
!(
7275
request.destination === 'image' ||
7376
request.destination === 'style' ||

webpack.config.common.js

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ const { CleanWebpackPlugin } = require('clean-webpack-plugin');
55
const HTMLWebpackPlugin = require('html-webpack-plugin');
66
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
77
const WorkerUrlPlugin = require('worker-url/plugin');
8-
const WorkboxPlugin = require('workbox-webpack-plugin');
98
const BootloaderPlugin = require('./src/components/loader/webpack-loader');
109

1110
require('dotenv').config();
@@ -117,11 +116,6 @@ const config = {
117116
// ProvidePlugin configuration
118117
cyblog: ['src/utils/logging/cyblog.ts', 'default'],
119118
}),
120-
new WorkboxPlugin.InjectManifest({
121-
swSrc: 'src/services/service-worker/service-worker.ts',
122-
swDest: 'service-worker.js',
123-
maximumFileSizeToCacheInBytes: 50 * 1024 * 1024,
124-
}),
125119
],
126120
module: {
127121
rules: [

webpack.config.prod.js

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@ const { merge } = require('webpack-merge');
22
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
33
const TerserPlugin = require('terser-webpack-plugin');
44
const CompressionWebpackPlugin = require('compression-webpack-plugin');
5+
const WorkboxPlugin = require('workbox-webpack-plugin');
56
const commonConfig = require('./webpack.config.common');
6-
const BundleInfoPlugin = require('./webpack/BundleInfoPlugin.js');
77

88
module.exports = merge(commonConfig, {
99
mode: 'production',
@@ -34,15 +34,22 @@ module.exports = merge(commonConfig, {
3434
}),
3535
...(!process.env.IPFS_DEPLOY
3636
? [
37-
new CompressionWebpackPlugin({
38-
filename: '[path][base].gz',
39-
algorithm: 'gzip',
40-
test: /\.js$|\.css$|\.html$|\.eot?.+$|\.ttf?.+$|\.woff?.+$|\.svg+$|\.wasm?.+$/,
41-
threshold: 10240,
42-
minRatio: 0.8,
43-
}),
44-
]
37+
new CompressionWebpackPlugin({
38+
filename: '[path][base].gz',
39+
algorithm: 'gzip',
40+
test: /\.js$|\.css$|\.html$|\.eot?.+$|\.ttf?.+$|\.woff?.+$|\.svg+$|\.wasm?.+$/,
41+
threshold: 10240,
42+
minRatio: 0.8,
43+
}),
44+
]
4545
: []),
4646
],
4747
},
48+
plugins: [
49+
new WorkboxPlugin.InjectManifest({
50+
swSrc: 'src/services/service-worker/service-worker.ts',
51+
swDest: 'service-worker.js',
52+
maximumFileSizeToCacheInBytes: 50 * 1024 * 1024,
53+
}),
54+
],
4855
});

0 commit comments

Comments
 (0)