Skip to content

Commit cdfe413

Browse files
committed
remove offscreen cache
1 parent 8bf13db commit cdfe413

9 files changed

Lines changed: 31 additions & 143 deletions

File tree

src/background/color-scheme.js

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
import {kDark, kStyleViaXhr, STATE_DB} from '@/js/consts';
1+
import {kDark, kStyleViaXhr} from '@/js/consts';
22
import {CLIENT} from '@/js/port';
33
import * as prefs from '@/js/prefs';
44
import {debounce, isCssDarkScheme} from '@/js/util';
55
import {broadcastExtension} from './broadcast';
6-
import {bgBusy, bgInit, bgPreInit} from './common';
6+
import {bgBusy, bgPreInit} from './common';
77
import {stateDB} from './db';
8-
import offscreen, {offscreenCache} from './offscreen';
8+
import offscreen from './offscreen';
99

1010
const changeListeners = new Set();
1111
const kSTATE = 'schemeSwitcher.enabled';
@@ -35,10 +35,7 @@ let prefState;
3535
chrome.alarms.onAlarm.addListener(onAlarm);
3636

3737
if (__.MV3) {
38-
bgPreInit.push(offscreenCache.then(v => {
39-
if (v && (v = v[STATE_DB])) setSystemDark(v.get(kDark));
40-
else bgInit.push(refreshSystemDark);
41-
}));
38+
bgPreInit.push(stateDB.get(kDark).then(setSystemDark));
4239
prefs.subscribe([kSTATE, kStyleViaXhr], (key, val, init) => {
4340
if (init && key !== kStyleViaXhr) // only process the last one on init
4441
return;

src/background/db.js

Lines changed: 11 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,10 @@
11
import {CACHE_DB, DB, STATE_DB} from '@/js/consts';
22
import {API} from '@/js/msg-api';
3-
import {CLIENT} from '@/js/port';
4-
import {STORAGE_KEY, subscribe} from '@/js/prefs';
3+
import {STORAGE_KEY} from '@/js/prefs';
54
import {chromeLocal} from '@/js/storage-util';
65
import {CHROME} from '@/js/ua';
76
import {deepMerge} from '@/js/util';
87
import ChromeStorageDB from './db-chrome-storage';
9-
import offscreen, {offscreenCache} from './offscreen';
10-
import {offloadCache} from './style-manager/util';
118

129
/*
1310
Initialize a database. There are some problems using IndexedDB in Firefox:
@@ -19,15 +16,13 @@ import {offloadCache} from './style-manager/util';
1916
let exec = __.BUILD === 'chrome' || CHROME
2017
? dbExecIndexedDB
2118
: tryUsingIndexedDB;
22-
const cachedClient = new WeakSet();
2319
const FALLBACK = 'dbInChromeStorage';
2420
const REASON = FALLBACK + 'Reason';
2521
const DRAFTS_DB = 'drafts';
2622
const CACHING = {
2723
[DRAFTS_DB]: cachedExec,
28-
[STORAGE_KEY]: __.MV3 ? cachedExecOffscreen : cachedExec,
24+
[STORAGE_KEY]: cachedExec,
2925
};
30-
const CACHING2 = {};
3126
const DATA_KEY = {};
3227
const STORES = {};
3328
const VERSIONS = {};
@@ -37,9 +32,6 @@ const databases = {};
3732
const proxyHandler = {
3833
get: ({dbName}, cmd) => (CACHING[dbName] || exec).bind(null, dbName, cmd),
3934
};
40-
const getAll = (range, map) => range instanceof IDBKeyRange
41-
? [...map.keys()].filter(range.includes, range).map(map.get, map)
42-
: [...map.values()];
4335
/**
4436
* @param {string} dbName
4537
* @param {object} [cfg]
@@ -66,75 +58,22 @@ export const draftsDb = getDbProxy(DRAFTS_DB);
6658
export const prefsDb = getDbProxy(STORAGE_KEY);
6759
export const stateDB = __.MV3 && getDbProxy(STATE_DB, {store: 'kv'});
6860

69-
if (__.MV3) {
70-
const toggleOffscreenCache = val => {
71-
CACHING[CACHE_DB] = CACHING[DB] = CACHING[STATE_DB] = val
72-
? cachedExecOffscreen
73-
: cachedExec;
74-
if (!val && offscreen[CLIENT])
75-
offscreen.dbCache(null);
76-
};
77-
toggleOffscreenCache(true);
78-
CACHING2[STORAGE_KEY] = CACHING2[STATE_DB] = cachedExec;
79-
subscribe('keepAliveCache', (key, val) => toggleOffscreenCache(val), true);
80-
}
81-
8261
Object.assign(API, /** @namespace API */ {
8362
draftsDb,
8463
prefsDb,
8564
});
8665

8766
async function cachedExec(dbName, cmd, a, b) {
88-
const old = dataCache[dbName];
89-
const hub = old || (dataCache[dbName] = new Map());
90-
const res = cmd === 'get' && hub.has(a)
91-
? hub.get(a)
92-
: old && (
93-
cmd === 'getAll' ? getAll(a, hub)
94-
: cmd === 'getMany' && a.map(hub.get, hub)
95-
) || await exec(...arguments);
96-
switch (cmd) {
97-
case 'put':
98-
cmd = DATA_KEY[dbName];
99-
hub.set(cmd ? a[cmd] : b, deepMerge(a));
100-
break;
101-
case 'putMany':
102-
cmd = DATA_KEY[dbName];
103-
for (b of a) hub.set(b[cmd], deepMerge(b));
104-
break;
105-
case 'deleteMany':
106-
a.forEach(hub.delete, hub);
107-
break;
108-
case 'delete':
109-
case 'clear':
110-
hub[cmd](a);
111-
break;
112-
}
113-
return res && typeof res === 'object' ? deepMerge(res) : res;
114-
}
115-
116-
async function cachedExecOffscreen(dbName, cmd, a, b) {
117-
let res, client, isRead;
118-
if ((isRead = cmd.startsWith('get'))
119-
&& offscreenCache
120-
&& await offscreenCache
121-
&& (res = offscreenCache[dbName])) {
122-
return cmd === 'get' ? res.get(a)
123-
: cmd === 'getMany' ? a.map(res.get, res)
124-
: getAll(a, res);
125-
}
126-
if ((client = offscreen[CLIENT]) && !cachedClient.has(client)) {
127-
cachedClient.add(client);
128-
if (!offscreenCache) {
129-
offloadCache(dataCache);
130-
client = null;
131-
}
67+
const hub = dataCache[dbName] ??= {};
68+
const res = cmd === 'get' && a in hub ? hub[a] : await exec(...arguments);
69+
if (cmd === 'get') {
70+
hub[a] = deepMerge(res);
71+
} else if (cmd === 'put') {
72+
const key = DATA_KEY[dbName];
73+
hub[key ? a[key] : b] = deepMerge(a);
74+
} else if (cmd === 'delete') {
75+
delete hub[a];
13276
}
133-
if (client && !isRead)
134-
offscreen.dbCache(dbName, cmd, a, b, DATA_KEY[dbName]);
135-
res = await (CACHING2[dbName] || exec)(dbName, cmd, a, b);
136-
if (client && isRead)
137-
offscreen.dbCache(dbName, 'res:' + cmd, res, a, DATA_KEY[dbName]);
13877
return res;
13978
}
14079

src/background/index.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import {setSystemDark} from './color-scheme';
1414
import {bgBusy, bgInit, bgPreInit, dataHub} from './common';
1515
import reinjectContentScripts from './content-scripts';
1616
import initContextMenus from './context-menus';
17-
import {draftsDb, prefsDb, stateDB} from './db';
17+
import {cacheDB, draftsDb, prefsDb, stateDB} from './db';
1818
import download from './download';
1919
import {refreshIconsWhenReady, updateIconBadge} from './icon-manager';
2020
import prefsApi from './prefs-api';
@@ -85,6 +85,7 @@ chrome.runtime.onInstalled.addListener(({reason, previousVersion}) => {
8585
}
8686
if (__.MV3) {
8787
(bgPreInit.length ? bgPreInit : []).push(
88+
cacheDB.clear(),
8889
stateDB.clear(),
8990
DNR.getDynamicRules().then(rules => updateDynamicRules(undefined, getRuleIds(rules))),
9091
DNR.getSessionRules().then(rules => updateSessionRules(undefined, getRuleIds(rules))),

src/background/offscreen.js

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
1-
import {CLIENT, createPortProxy} from '@/js/port';
1+
import {createPortProxy} from '@/js/port';
22
import {ownRoot} from '@/js/urls';
3-
import {bgBusy} from './common';
43
import {getWindowClients} from './util';
54

65
const FILENAME = 'offscreen.html';
@@ -14,12 +13,6 @@ const offscreen = createPortProxy(() => (
1413
});
1514
export default offscreen;
1615

17-
export let offscreenCache = __.MV3 && (async () => {
18-
bgBusy.then(() => (offscreenCache = null));
19-
offscreenCache = (offscreen[CLIENT] = await findOffscreenClient()) &&
20-
await offscreen.getData();
21-
return offscreenCache;
22-
})();
2316
let creating;
2417

2518
async function findOffscreenClient() {

src/background/style-manager/cache.js

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -131,10 +131,12 @@ function del(items) {
131131
cacheDB.deleteMany(items);
132132
}
133133

134-
export function getCacheSkeletons(arr = cache.values(), toDel = []) {
134+
/** @return {void} */
135+
function flush() {
135136
const bare = [];
137+
let toDel;
136138
nextEntry:
137-
for (const val of arr) {
139+
for (const val of toWrite) {
138140
const {d, url, maybeMatch, sections} = val;
139141
/** @type {MatchCache.IndexMap} */
140142
const indexes = {};
@@ -146,7 +148,7 @@ export function getCacheSkeletons(arr = cache.values(), toDel = []) {
146148
const sec = sections[styleId];
147149
const idx = sec && (Array.isArray(sec) ? sec : sec.idx);
148150
if (!idx) {
149-
toDel.push(val);
151+
(toDel ??= []).push(val);
150152
continue nextEntry;
151153
}
152154
indexes[styleId] = idx;
@@ -158,15 +160,8 @@ export function getCacheSkeletons(arr = cache.values(), toDel = []) {
158160
res.url = url;
159161
bare.push(res);
160162
}
161-
return bare;
162-
}
163-
164-
/** @return {void} */
165-
function flush() {
166-
const toDel = [];
167-
const res = getCacheSkeletons(toWrite, toDel);
168-
if (toDel[0]) del(toDel);
169-
cacheDB.putMany(res);
163+
if (toDel) del(toDel);
164+
cacheDB.putMany(bare);
170165
toWrite.clear();
171166
timer = null;
172167
}

src/background/style-manager/util.js

Lines changed: 1 addition & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
1-
import {CACHE_DB, DB, UCD} from '@/js/consts';
1+
import {UCD} from '@/js/consts';
22
import * as URLS from '@/js/urls';
33
import {deepEqual, isEmptyObj, mapObj} from '@/js/util';
44
import {broadcast} from '../broadcast';
55
import broadcastInjectorConfig from '../broadcast-injector-config';
66
import {uuidIndex} from '../common';
77
import {prefsDb} from '../db';
8-
import offscreen from '../offscreen';
98
import * as syncMan from '../sync-manager';
10-
import {getCacheSkeletons} from './cache';
119
import {buildCacheForStyle} from './cache-builder';
1210

1311
/** @type {StyleDataMap} */
@@ -70,18 +68,6 @@ export function *iterStyles() {
7068
for (const v of dataMap.values()) yield v.style;
7169
}
7270

73-
export function offloadCache(dbCache) {
74-
const res = {...dbCache};
75-
const styleMap = res[DB] = new Map();
76-
const cacheMap = res[CACHE_DB] = new Map();
77-
for (const {style} of dataMap.values())
78-
styleMap.set(style.id, style);
79-
for (const v of getCacheSkeletons())
80-
cacheMap.set(v.url, v);
81-
__.DEBUGLOG('Offloading cache...');
82-
return offscreen.dbCache(res);
83-
}
84-
8571
export async function setOrderImpl(data, {
8672
broadcast: broadcastAllowed,
8773
calc = true,

src/background/style-via-webrequest.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import * as colorScheme from './color-scheme';
99
import {bgBusy, bgPreInit, dataHub, onUnload} from './common';
1010
import {stateDB} from './db';
1111
import {webNavigation} from './navigation-manager';
12-
import offscreen, {offscreenCache} from './offscreen';
12+
import offscreen from './offscreen';
1313
import makePopupData from './popup-data';
1414
import {getSectionsByUrl} from './style-manager';
1515
import * as styleCache from './style-manager/cache';
@@ -47,7 +47,6 @@ let curXHR = false;
4747
if (__.MV3) {
4848
toggle(); // register listeners synchronously so they wake up the SW next time it dies
4949
bgPreInit.push((async () => {
50-
await offscreenCache;
5150
ruleIds = await stateDB.get(kRuleIds) || {};
5251
for (const id in ruleIds) ruleIdKeys[ruleIds[id]] = +id;
5352
})());

src/background/tab-manager.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,8 +89,10 @@ bgInit.push(async () => {
8989
cache.set(id, data);
9090
}
9191
}
92-
if (__.MV3)
93-
stateDB.deleteMany([...dbMap.keys()].filter(k => !cache.has(k)));
92+
if (__.MV3) {
93+
const toDel = [...dbMap.keys()].filter(k => !cache.has(k));
94+
if (toDel.length) stateDB.deleteMany(toDel);
95+
}
9496
});
9597

9698
bgBusy.then(() => {

src/offscreen/index.js

Lines changed: 0 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -2,37 +2,13 @@ import {API} from '@/js/msg-api';
22
import {COMMANDS} from '@/js/port';
33
import {fetchWebDAV, isCssDarkScheme, mapObj} from '@/js/util';
44

5-
let dbCache;
65
let webdavInstance;
76

87
/** @namespace OffscreenAPI */
98
Object.assign(COMMANDS, {
109
isDark: isCssDarkScheme,
1110
createObjectURL: URL.createObjectURL,
1211
revokeObjectURL: URL.revokeObjectURL,
13-
dbCache(dbName, cmd, a, b, dataKey) {
14-
if (typeof dbName === 'object' /* includes `null` */) {
15-
dbCache = dbName;
16-
return;
17-
}
18-
const map = (dbCache ??= {})[dbName] ??= new Map();
19-
if (cmd === 'put' || cmd === 'res:get')
20-
map.set(b, a);
21-
else if (cmd === 'delete' || cmd === 'clear')
22-
map[cmd](a);
23-
else if (cmd === 'deleteMany')
24-
a.forEach(map.delete, map);
25-
else if (cmd === 'putMany' || cmd === 'res:getAll')
26-
for (b of a) map.set(b[dataKey], b);
27-
else if (cmd === 'res:getMany')
28-
for (let i = 0; i < a.length; i++)
29-
map.set(b[i], a[i]);
30-
else return cmd === 'get' ? map.get(a)
31-
: cmd === 'getAll' ? [...map.values()]
32-
: cmd === 'getMany' ? a.map(map.get, map)
33-
: undefined;
34-
},
35-
getData: () => dbCache,
3612
webdav: (cmd, ...args) => webdavInstance[cmd](...args),
3713
webdavInit: async cfg => {
3814
if (!webdavInstance) await loadScript(__.JS + 'webdav.js');

0 commit comments

Comments
 (0)