Skip to content

Commit f89658a

Browse files
committed
backup to cacheStorage on startup
1 parent 004fdf0 commit f89658a

File tree

3 files changed

+35
-21
lines changed

3 files changed

+35
-21
lines changed

src/background/db.js

Lines changed: 28 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import {API} from '@/js/msg-api';
33
import {STORAGE_KEY} from '@/js/prefs';
44
import {chromeLocal} from '@/js/storage-util';
55
import {CHROME} from '@/js/ua';
6-
import {deepMerge, sleep} from '@/js/util';
6+
import {deepMerge, sleep, sleep0} from '@/js/util';
77
import ChromeStorageDB from './db-chrome-storage';
88

99
/*
@@ -25,8 +25,8 @@ const CACHING = {
2525
};
2626
const {CompressionStream} = global;
2727
const kApplicationGzip = 'application/gzip';
28+
/** @type {ResponseInit} */
2829
const MIRROR_INIT = CompressionStream && {headers: {[kContentType]: kApplicationGzip}};
29-
const MIRROR_PREFIX = 'http://_/';
3030
/** @type {{[id: string]: Cache}} */
3131
const MIRROR = {
3232
[DB]: null,
@@ -122,9 +122,9 @@ async function tryUsingIndexedDB(...args) {
122122

123123
async function testDB() {
124124
const id = `${performance.now()}.${Math.random()}.${Date.now()}`;
125-
await dbExecIndexedDB(DB, 'put', {id});
125+
await dbExecIndexedDB.call(testDB, DB, 'put', {id});
126126
const e = await dbExecIndexedDB(DB, 'get', id);
127-
await dbExecIndexedDB(DB, 'delete', e.id); // throws if `e` or id is null
127+
await dbExecIndexedDB.call(testDB, DB, 'delete', e.id); // throws if `e` or id is null
128128
}
129129

130130
function useChromeStorage(err) {
@@ -145,7 +145,7 @@ async function dbExecIndexedDB(dbName, method, ...args) {
145145
const store = (databases[dbName] ??= await open(dbName))
146146
.transaction([storeName], mode)
147147
.objectStore(storeName);
148-
if (mode && dbName in MIRROR)
148+
if (mode && dbName in MIRROR && (__.BUILD === 'chrome' || this !== testDB))
149149
execMirror(...arguments);
150150
return method.endsWith('Many')
151151
? storeMany(store, method.slice(0, -4), ...args)
@@ -217,32 +217,39 @@ export async function execMirror(dbName, method, a, b) {
217217
const mirror = MIRROR[dbName] ??= await caches.open(dbName);
218218
switch (method) {
219219
case 'delete':
220-
return mirror.delete(MIRROR_PREFIX + a);
220+
return mirror.delete(__.MIRROR_PREFIX + a);
221221
case 'get':
222222
b = await execMirror(dbName, 'getAll', a);
223223
return b[0];
224224
case 'getAll':
225225
a = await mirror.matchAll(a);
226226
for (let i = 0; i < a.length; i++) {
227227
b = a[i];
228-
if (MIRROR_INIT && b.headers.get(kContentType) === kApplicationGzip)
228+
if (CompressionStream && b.headers.get(kContentType) === kApplicationGzip)
229229
b = new Response(b.body.pipeThrough(new DecompressionStream('gzip')));
230230
a[i] = b.text();
231231
}
232232
a = await Promise.all(a);
233233
for (let i = 0; i < a.length; i++)
234234
a[i] = JSON.parse(a[i]);
235235
return a;
236+
case 'getAllKeys':
237+
a = await mirror.keys();
238+
for (let i = 0; i < a.length; i++) {
239+
b = a[i].url.slice(__.MIRROR_PREFIX_LEN);
240+
a[i] = +b || b;
241+
}
242+
return a;
236243
case 'put':
237244
await sleep(10);
238245
if (dbName === DB && a[UCD])
239246
delete (a = {...a}).sections;
240-
b = MIRROR_PREFIX + (b ?? a.id);
247+
b = __.MIRROR_PREFIX + (b ?? a.id);
241248
a = JSON.stringify(a);
242-
if (MIRROR_INIT)
249+
if (CompressionStream) {
243250
MIRROR_INIT.headers['Content-Length'] = a.length;
244-
if (CompressionStream)
245251
a = new Response(a).body.pipeThrough(new CompressionStream('gzip'));
252+
}
246253
return mirror.put(b, new Response(a, MIRROR_INIT));
247254
case 'putMany':
248255
for (let i = 0; i < a.length; i++)
@@ -251,14 +258,19 @@ export async function execMirror(dbName, method, a, b) {
251258
}
252259

253260
export async function mirrorStorage(dataMap) {
254-
if (!await caches.has(DB)) {
255-
for (const {style} of dataMap.values())
261+
let val;
262+
let keys = new Set(await execMirror(DB, 'getAllKeys'));
263+
for (const {style} of dataMap.values()) {
264+
if (!keys.has(style.id)) {
265+
await sleep0();
256266
await execMirror(DB, 'put', style);
267+
}
257268
}
258-
if (!await caches.has(STORAGE_KEY)) {
259-
for (const key of [kInjectionOrder]) {
260-
const val = await prefsDB.get(key);
261-
if (val) await execMirror(STORAGE_KEY, 'put', val, key);
269+
keys = new Set(await execMirror(STORAGE_KEY, 'getAllKeys'));
270+
for (const key of [kInjectionOrder]) {
271+
if (!keys.has(key) && (val = await prefsDB.get(key))) {
272+
await sleep0();
273+
await execMirror(STORAGE_KEY, 'put', val, key);
262274
}
263275
}
264276
}

src/background/index.js

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -103,12 +103,8 @@ chrome.runtime.onInstalled.addListener(({reason, previousVersion}) => {
103103
.then(() => usercssMan.toggleUrlInstaller()),
104104
DNR.getSessionRules().then(rules => updateSessionRules(undefined, getRuleIds(rules))),
105105
);
106-
refreshIconsWhenReady();
107106
}
108-
(async () => {
109-
if (bgBusy) await bgBusy;
110-
mirrorStorage(dataMap);
111-
})();
107+
onStartup();
112108
});
113109

114110
if (__.MV3) {
@@ -132,6 +128,9 @@ async function onStartup() {
132128
const {date} = await draftsDB.get(id) || {};
133129
if (date < minDate) draftsDB.delete(id);
134130
}
131+
if (bgBusy)
132+
await bgBusy;
133+
mirrorStorage(dataMap);
135134
}
136135

137136
onMessage.set((m, sender) => {

webpack.config.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ const VARS = {
9292
PAGE_BG: PAGE_BG.split('/').pop(),
9393
ZIP: !!ZIP,
9494
};
95+
const MIRROR_PREFIX = 'http://_/';
9596
const DEBUG_MODE = {
9697
GENERAL: 1,
9798
PORT: 2,
@@ -492,6 +493,8 @@ module.exports = [
492493
new RawEnvPlugin({
493494
ENTRY: 'sw',
494495
IS_BG: true,
496+
MIRROR_PREFIX,
497+
MIRROR_PREFIX_LEN: MIRROR_PREFIX.length,
495498
}, {
496499
KEEP_ALIVE: 'global.keepAlive',
497500
}),

0 commit comments

Comments
 (0)