handling service worker waiting phase

This commit is contained in:
Sebastian 2022-05-06 17:29:42 -03:00
parent 9641299d6c
commit 37690dd22c
No known key found for this signature in database
GPG Key ID: BE4FF68352439FC1
7 changed files with 86 additions and 77 deletions

View File

@ -445,8 +445,8 @@ async function downloadExchangeKeysInfo(
codecForExchangeKeysJson(), codecForExchangeKeysJson(),
); );
logger.info("received /keys response"); logger.trace("received /keys response");
logger.info(`${j2s(exchangeKeysJsonUnchecked)}`); logger.trace(`${j2s(exchangeKeysJsonUnchecked)}`);
if (exchangeKeysJsonUnchecked.denoms.length === 0) { if (exchangeKeysJsonUnchecked.denoms.length === 0) {
throw TalerError.fromDetail( throw TalerError.fromDetail(

View File

@ -54,6 +54,6 @@
"default_popup": "static/popup.html" "default_popup": "static/popup.html"
}, },
"background": { "background": {
"service_worker": "dist/background.js" "service_worker": "service_worker.js"
} }
} }

View File

@ -32,8 +32,8 @@ zipfile="taler-wallet-webextension-${vers_manifest}.zip"
TEMP_DIR=$(mktemp -d) TEMP_DIR=$(mktemp -d)
jq '. | .name = "GNU Taler Wallet" ' manifest-v3.json > $TEMP_DIR/manifest.json jq '. | .name = "GNU Taler Wallet" ' manifest-v3.json > $TEMP_DIR/manifest.json
cp -r dist static $TEMP_DIR cp -r dist static service_worker.js $TEMP_DIR
(cd $TEMP_DIR && zip -q -r "$zipfile" dist static manifest.json) (cd $TEMP_DIR && zip -q -r "$zipfile" dist static manifest.json service_worker.js)
mkdir -p extension/v3 mkdir -p extension/v3
mv "$TEMP_DIR/$zipfile" ./extension/v3/ mv "$TEMP_DIR/$zipfile" ./extension/v3/
rm -rf $TEMP_DIR rm -rf $TEMP_DIR

View File

@ -9,7 +9,7 @@
"private": false, "private": false,
"scripts": { "scripts": {
"clean": "rimraf dist lib tsconfig.tsbuildinfo", "clean": "rimraf dist lib tsconfig.tsbuildinfo",
"test": "mocha --enable-source-maps 'dist/**/*.test.js'", "test": "pnpm compile && mocha --enable-source-maps 'dist/**/*.test.js'",
"test:coverage": "nyc pnpm test", "test:coverage": "nyc pnpm test",
"compile": "tsc && ./build-fast-with-linaria.mjs", "compile": "tsc && ./build-fast-with-linaria.mjs",
"dev": "./dev.mjs", "dev": "./dev.mjs",

View File

@ -0,0 +1,11 @@
/* eslint-disable no-undef */
/**
* Wrapper to catch any initialization error and show it in the logs
*/
try {
importScripts("dist/background.js");
self.skipWaiting();
console.log("SERVICE WORKER init: ok");
} catch (e) {
console.error("SERVICE WORKER failed:", e);
}

View File

@ -117,7 +117,7 @@ export async function removeHostPermissions(): Promise<boolean> {
if ("webRequest" in chrome) { if ("webRequest" in chrome) {
chrome.webRequest.handlerBehaviorChanged(() => { chrome.webRequest.handlerBehaviorChanged(() => {
if (chrome.runtime.lastError) { if (chrome.runtime.lastError) {
console.error(JSON.stringify(chrome.runtime.lastError)); logger.error(JSON.stringify(chrome.runtime.lastError));
} }
}); });
} }
@ -138,7 +138,6 @@ export async function removeHostPermissions(): Promise<boolean> {
} }
function addPermissionsListener(callback: (p: Permissions, lastError?: string) => void): void { function addPermissionsListener(callback: (p: Permissions, lastError?: string) => void): void {
console.log("addPermissionListener is not supported for Firefox");
chrome.permissions.onAdded.addListener((perm: Permissions) => { chrome.permissions.onAdded.addListener((perm: Permissions) => {
const lastError = chrome.runtime.lastError?.message; const lastError = chrome.runtime.lastError?.message;
callback(perm, lastError) callback(perm, lastError)
@ -182,7 +181,7 @@ function openWalletURIFromPopup(talerUri: string): void {
url = chrome.runtime.getURL(`static/wallet.html#/cta/refund?talerRefundUri=${talerUri}`); url = chrome.runtime.getURL(`static/wallet.html#/cta/refund?talerRefundUri=${talerUri}`);
break; break;
default: default:
console.warn( logger.warn(
"Response with HTTP 402 has Taler header, but header value is not a taler:// URI.", "Response with HTTP 402 has Taler header, but header value is not a taler:// URI.",
); );
return; return;
@ -211,6 +210,7 @@ function openWalletPageFromPopup(page: string): void {
async function sendMessageToWalletBackground(operation: string, payload: any): Promise<any> { async function sendMessageToWalletBackground(operation: string, payload: any): Promise<any> {
return new Promise<any>((resolve, reject) => { return new Promise<any>((resolve, reject) => {
logger.trace("send operation to the wallet background", operation)
chrome.runtime.sendMessage({ operation, payload, id: "(none)" }, (resp) => { chrome.runtime.sendMessage({ operation, payload, id: "(none)" }, (resp) => {
if (chrome.runtime.lastError) { if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError.message) reject(chrome.runtime.lastError.message)
@ -245,7 +245,7 @@ function sendMessageToAllChannels(message: MessageFromBackend): void {
try { try {
notif.postMessage(message); notif.postMessage(message);
} catch (e) { } catch (e) {
console.error(e); logger.error("error posting a message", e);
} }
} }
} }
@ -275,7 +275,7 @@ function registerReloadOnNewVersion(): void {
// Explicitly unload the extension page as soon as an update is available, // Explicitly unload the extension page as soon as an update is available,
// so the update gets installed as soon as possible. // so the update gets installed as soon as possible.
chrome.runtime.onUpdateAvailable.addListener((details) => { chrome.runtime.onUpdateAvailable.addListener((details) => {
console.log("update available:", details); logger.info("update available:", details);
chrome.runtime.reload(); chrome.runtime.reload();
}); });
@ -286,7 +286,7 @@ function redirectTabToWalletPage(
page: string, page: string,
): void { ): void {
const url = chrome.runtime.getURL(`/static/wallet.html#${page}`); const url = chrome.runtime.getURL(`/static/wallet.html#${page}`);
console.log("redirecting tabId: ", tabId, " to: ", url); logger.trace("redirecting tabId: ", tabId, " to: ", url);
chrome.tabs.update(tabId, { url }); chrome.tabs.update(tabId, { url });
} }
@ -301,13 +301,13 @@ function getWalletVersion(): WalletVersion {
} }
function registerTalerHeaderListener(callback: (tabId: number, url: string) => void): void { function registerTalerHeaderListener(callback: (tabId: number, url: string) => void): void {
console.log("setting up header listener"); logger.trace("setting up header listener");
function headerListener( function headerListener(
details: chrome.webRequest.WebResponseHeadersDetails, details: chrome.webRequest.WebResponseHeadersDetails,
): void { ): void {
if (chrome.runtime.lastError) { if (chrome.runtime.lastError) {
console.error(JSON.stringify(chrome.runtime.lastError)); logger.error(JSON.stringify(chrome.runtime.lastError));
return; return;
} }
if ( if (
@ -350,7 +350,7 @@ function registerTalerHeaderListener(callback: (tabId: number, url: string) => v
//notify the browser about this change, this operation is expensive //notify the browser about this change, this operation is expensive
chrome?.webRequest?.handlerBehaviorChanged(() => { chrome?.webRequest?.handlerBehaviorChanged(() => {
if (chrome.runtime.lastError) { if (chrome.runtime.lastError) {
console.error(JSON.stringify(chrome.runtime.lastError)); logger.error(JSON.stringify(chrome.runtime.lastError));
} }
}); });
}); });
@ -473,7 +473,6 @@ async function registerIconChangeOnTalerContent(): Promise<void> {
logger.info("tab updated", tabId, info); logger.info("tab updated", tabId, info);
if (info.status !== "complete") return; if (info.status !== "complete") return;
const uri = await findTalerUriInTab(tabId); const uri = await findTalerUriInTab(tabId);
console.log("urio", uri)
if (uri) { if (uri) {
setAlertedIcon() setAlertedIcon()
} else { } else {
@ -483,9 +482,7 @@ async function registerIconChangeOnTalerContent(): Promise<void> {
}); });
chrome.tabs.onActivated.addListener(async ({ tabId }: chrome.tabs.TabActiveInfo) => { chrome.tabs.onActivated.addListener(async ({ tabId }: chrome.tabs.TabActiveInfo) => {
if (tabId < 0) return; if (tabId < 0) return;
logger.info("tab activated", tabId);
const uri = await findTalerUriInTab(tabId); const uri = await findTalerUriInTab(tabId);
console.log("urio", uri)
if (uri) { if (uri) {
setAlertedIcon() setAlertedIcon()
} else { } else {
@ -565,7 +562,7 @@ async function findTalerUriInTab(tabId: number): Promise<string | undefined> {
}, },
(result) => { (result) => {
if (chrome.runtime.lastError) { if (chrome.runtime.lastError) {
console.error(JSON.stringify(chrome.runtime.lastError)); logger.error(JSON.stringify(chrome.runtime.lastError));
resolve(undefined); resolve(undefined);
return; return;
} }

View File

@ -121,69 +121,70 @@ async function dispatch(
}; };
}; };
switch (req.operation) { try {
case "wxGetDiagnostics": { switch (req.operation) {
r = wrapResponse(await getDiagnostics()); case "wxGetDiagnostics": {
break; r = wrapResponse(await getDiagnostics());
} break;
case "reset-db": { }
await deleteTalerDatabase(indexedDB as any); case "reset-db": {
r = wrapResponse(await reinitWallet()); await deleteTalerDatabase(indexedDB as any);
break; r = wrapResponse(await reinitWallet());
} break;
case "run-gc": { }
logger.info("gc") case "run-gc": {
const dump = await exportDb(currentDatabase!.idbHandle()); logger.info("gc")
await deleteTalerDatabase(indexedDB as any); const dump = await exportDb(currentDatabase!.idbHandle());
logger.info("cleaned") await deleteTalerDatabase(indexedDB as any);
await reinitWallet(); logger.info("cleaned")
logger.info("init") await reinitWallet();
await importDb(currentDatabase!.idbHandle(), dump) logger.info("init")
logger.info("imported") await importDb(currentDatabase!.idbHandle(), dump)
r = wrapResponse({ result: true }); logger.info("imported")
break; r = wrapResponse({ result: true });
} break;
case "containsHeaderListener": { }
const res = await platform.containsTalerHeaderListener(); case "containsHeaderListener": {
r = wrapResponse({ newValue: res }); const res = await platform.containsTalerHeaderListener();
break; r = wrapResponse({ newValue: res });
} break;
case "toggleHeaderListener": { }
const newVal = req.payload.value; case "toggleHeaderListener": {
logger.trace("new extended permissions value", newVal); const newVal = req.payload.value;
if (newVal) { logger.trace("new extended permissions value", newVal);
platform.registerTalerHeaderListener(parseTalerUriAndRedirect); if (newVal) {
r = wrapResponse({ newValue: true }); platform.registerTalerHeaderListener(parseTalerUriAndRedirect);
} else { r = wrapResponse({ newValue: true });
const rem = await platform.getPermissionsApi().removeHostPermissions(); } else {
logger.trace("permissions removed:", rem); const rem = await platform.getPermissionsApi().removeHostPermissions();
r = wrapResponse({ newVal: false }); logger.trace("permissions removed:", rem);
} r = wrapResponse({ newVal: false });
break; }
} break;
default: { }
const w = currentWallet; default: {
if (!w) { const w = currentWallet;
r = { if (!w) {
type: "error", r = {
id: req.id, type: "error",
operation: req.operation, id: req.id,
error: makeErrorDetail( operation: req.operation,
TalerErrorCode.WALLET_CORE_NOT_AVAILABLE, error: makeErrorDetail(
{}, TalerErrorCode.WALLET_CORE_NOT_AVAILABLE,
"wallet core not available", {},
), "wallet core not available",
}; ),
};
break;
}
r = await w.handleCoreApiRequest(req.operation, req.id, req.payload);
break; break;
} }
r = await w.handleCoreApiRequest(req.operation, req.id, req.payload);
break;
} }
}
try {
sendResponse(r); sendResponse(r);
} catch (e) { } catch (e) {
logger.error(`Error sending operation: ${req.operation}`, e)
// might fail if tab disconnected // might fail if tab disconnected
} }
} }
@ -231,7 +232,7 @@ async function reinitWallet(): Promise<void> {
}); });
platform.keepAlive(() => { platform.keepAlive(() => {
wallet.runTaskLoop().catch((e) => { return wallet.runTaskLoop().catch((e) => {
logger.error("error during wallet task loop", e); logger.error("error during wallet task loop", e);
}); });
}) })