Skip to content

Commit

Permalink
disable style cache in db
Browse files Browse the repository at this point in the history
  • Loading branch information
tophf committed Feb 12, 2025
1 parent 8366089 commit 3a2d9ba
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 118 deletions.
90 changes: 4 additions & 86 deletions src/background/style-manager/cache.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import {bgBusy} from '../common';
import {cacheDB, db as styleDB} from '../db';
import {bgMortal, bgMortalChanged} from '../tab-manager';

let onDeleted;
let timer;
Expand All @@ -12,73 +10,20 @@ const toWrite = new Set();

export default cache;

if (__.MV3) {
bgMortalChanged.add(val => {
if (val) cacheDB.putMany(Object.values(cache));
else cacheDB.clear();
});
}

/** @param {MatchCache.Entry} val
* @return {void} */
export function add(val) {
cache.set(val.url, bgMortal ? hit(val) : val);
cache.set(val.url, hit(val));
if (cache.size >= MAX) prune();
}

/** @return {void} */
export function clear() {
if (onDeleted) cache.forEach(onDeleted);
if (__.MV3 && bgMortal) cacheDB.clear();
if (timer) timer = clearTimeout(timer);
cache.clear();
}

/** @param {string} url
* @return {Promise<?MatchCache.Entry>} */
export async function loadOne(url) {
const val = await cacheDB.get(url);
if (val) {
cache.set(url, hit(val));
const styleIds = Object.keys(val.sections ??= {}).map(Number);
const styles = styleIds.length ? await styleDB.getMany(styleIds) : [];
for (const style of styles) {
if (!style || !make(val, style)) {
del([val]);
return;
}
}
}
return val;
}

/** @return {Promise<void>} */
export async function loadAll() {
for (const val of await cacheDB.getAll()) {
if (!cache.has(val.url)) {
cache.set(val.url, val);
}
}
}

/** @param {StyleDataMap} dataMap
* @return {void} */
export function hydrate(dataMap) {
const toDel = [];
for (const val of cache.values()) {
for (const id in (val.sections ??= {})) {
const data = dataMap.get(+id);
if (!data || !make(val, data.style)) {
toDel.push(val);
break;
} else {
data.appliesTo.add(val.url);
}
}
}
if (toDel[0]) del(toDel);
}

/**
* @param {MatchCache.DbEntry} entry
* @param {StyleObj} style
Expand Down Expand Up @@ -122,39 +67,12 @@ function del(items) {
cache.delete(items[i] = val.url);
onDeleted(val);
}
if (__.MV3 && bgMortal) cacheDB.deleteMany(items);
}

/** @return {void} */
function flush() {
const bare = [];
let toDel;
nextEntry:
for (const val of toWrite) {
const {d, url, sections} = val;
/** @type {MatchCache.IndexMap} */
const indexes = {};
/** @type {MatchCache.DbEntry} */
const res = {};
let styleId;
for (styleId in sections) {
/** @type {Injection.Sections | MatchCache.Index} */
const sec = sections[styleId];
const idx = sec && (Array.isArray(sec) ? sec : sec.idx);
if (!idx) {
(toDel ??= []).push(val);
continue nextEntry;
}
indexes[styleId] = idx;
}
// Adding the meaningful props first to ensure their visibility in devtools DB viewer
if (styleId) res.sections = indexes;
res.d = [d?.[1] || 0, new Date()];
res.url = url;
bare.push(res);
}
if (toDel) del(toDel);
if (__.MV3) cacheDB.putMany(bare);
for (const val of toWrite)
val.d = [val.d?.[1] || 0, new Date()];
toWrite.clear();
timer = null;
}
Expand All @@ -170,7 +88,7 @@ async function flushLater() {
* @param {T} val
* @return {T} */
export function hit(val) {
if (val && bgMortal) {
if (val) {
toWrite.add(val);
if (!timer) flushLater();
}
Expand Down
3 changes: 0 additions & 3 deletions src/background/style-manager/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {STORAGE_KEY} from '@/js/prefs';
import * as colorScheme from '../color-scheme';
import {bgBusy, bgInit, onSchemeChange} from '../common';
import {db, draftsDB, execMirror, prefsDB} from '../db';
import {bgMortal} from '../tab-manager';
import * as styleCache from './cache';
import './init';
import {fixKnownProblems} from './fixer';
Expand All @@ -16,15 +15,13 @@ bgInit.push(async () => {
let [orderFromDb, styles] = await Promise.all([
prefsDB.get(kInjectionOrder),
db.getAll(),
__.MV3 && bgMortal ? styleCache.loadAll() : [],
]);
if (!orderFromDb)
orderFromDb = await execMirror(STORAGE_KEY, 'get', kInjectionOrder);
if (!styles[0])
styles = mirrored = await execMirror(DB, 'getAll');
setOrderImpl(orderFromDb, {store: false});
initStyleMap(styles, mirrored);
styleCache.hydrate(dataMap);
__.DEBUGLOG('styleMan init done');
});

Expand Down
36 changes: 8 additions & 28 deletions src/background/style-via-webrequest.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,14 @@ import * as prefs from '@/js/prefs';
import {CHROME, FIREFOX} from '@/js/ua';
import {actionPopupUrl, ownRoot} from '@/js/urls';
import {deepEqual, isEmptyObj} from '@/js/util';
import {ignoreChromeError, ownId, toggleListener} from '@/js/util-webext';
import {ownId, toggleListener} from '@/js/util-webext';
import * as colorScheme from './color-scheme';
import {bgBusy, bgPreInit, clientDataJobs, dataHub, onUnload} from './common';
import {stateDB} from './db';
import {webNavigation} from './navigation-manager';
import offscreen from './offscreen';
import makePopupData from './popup-data';
import {getSectionsByUrl} from './style-manager';
import * as styleCache from './style-manager/cache';
import tabCache, * as tabMan from './tab-manager';

const idCSP = 'patchCsp';
Expand Down Expand Up @@ -136,32 +135,14 @@ function toggle(prefKey) {
async function prepareStyles(req) {
const {tabId, frameId, url} = req; if (tabId < 0) return;
const key = tabId + ':' + frameId;
const bgPreInitLen = __.MV3 && bgPreInit.length;
const isDark = curXHR
&& colorScheme.isSystem()
&& !tabMan.someInjectable()
&& colorScheme.refreshSystemDark();
__.DEBUGLOG('prepareStyles', key, req, {isDark});
if (!curXHR && !curCSP && !bgBusy) return;
let cached, unlock;
let lock = __.MV3 && bgPreInitLen && new Promise(resolve => (unlock = resolve));
if (__.MV3 && bgPreInitLen) { // bgPreInit in progress, let's join it
bgPreInit.push(
styleCache.loadOne(url),
frameId ? browser.tabs.get(tabId).catch(ignoreChromeError) : undefined,
isDark,
);
const all = Promise.all(bgPreInit);
if (lock) bgPreInit.push(lock); // keeps bgBusy from resolving until we're done here
[cached, req.tab] = (await all).slice(bgPreInitLen);
__.DEBUGLOG('prepareStyles cache', key, cached);
}
if (!cached && bgBusy) {
if (lock) lock = unlock(); // set to undefined
const isInit = bgBusy;
__.DEBUGLOG('prepareStyles', key, req);
if (!curXHR && !curCSP && !bgBusy)
return;
if (bgBusy)
await bgBusy;
} else if (!bgPreInitLen && isDark && __.MV3) {
await isDark;
}
if (curXHR && colorScheme.isSystem() && (isInit || !tabMan.someInjectable()))
await colorScheme.refreshSystemDark();
const oldData = toSend[key];
const data = oldData || {};
const payload = data.payload = getSectionsByUrl.call({sender: req}, url, null, kStyleViaXhr);
Expand All @@ -172,7 +153,6 @@ async function prepareStyles(req) {
await prepareStylesMV3(tabId, frameId, url, data, key, payload);
}
toSend[key] = data;
if (lock) setTimeout(unlock);
__.DEBUGLOG('prepareStyles done', key, data);
}

Expand Down
2 changes: 1 addition & 1 deletion src/background/tab-manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ const putObject = obj => stateDB.putMany(
);

export const bgMortalChanged = __.MV3 && new Set();
export let bgMortal;
let bgMortal;

bgInit.push(async () => {
const [saved, tabs] = await Promise.all([
Expand Down

0 comments on commit 3a2d9ba

Please sign in to comment.