Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: await initialization before routing a msg #2364

Merged
merged 14 commits into from
May 2, 2023
Merged
18 changes: 17 additions & 1 deletion src/common/lib/utils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import browser, { Runtime } from "webextension-polyfill";
import { ABORT_PROMPT_ERROR } from "~/common/constants";
import { getPosition as getWindowPosition } from "~/common/utils/window";
import type { Invoice, OriginData, OriginDataInternal } from "~/types";
import type {
Invoice,
OriginData,
OriginDataInternal,
DeferredPromise,
} from "~/types";

const utils = {
base64ToHex: (str: string) => {
Expand Down Expand Up @@ -37,6 +42,17 @@ const utils = {
stringToUint8Array: (str: string) => {
return Uint8Array.from(str, (x) => x.charCodeAt(0));
},
deferredPromise: (): DeferredPromise => {
let resolve: DeferredPromise["resolve"];
let reject: DeferredPromise["reject"];
const promise = new Promise<void>(
(innerResolve: () => void, innerReject: () => void) => {
resolve = innerResolve;
reject = innerReject;
}
);
return { promise, resolve, reject };
},
openPage: (page: string) => {
browser.tabs.create({ url: browser.runtime.getURL(page) });
},
Expand Down
3 changes: 2 additions & 1 deletion src/extension/background-script/actions/accounts/select.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ const select = async (message: MessageAccountSelect) => {
if (account) {
if (currentState.connector) {
console.info("Unloading connector");
await currentState.connector.unload();
const connector = await currentState.connector;
await connector.unload();
}

state.setState({
Expand Down
39 changes: 28 additions & 11 deletions src/extension/background-script/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ import state from "./state";

let isFirstInstalled = false;
let isRecentlyUpdated = false;
const {
promise: isInitialized,
resolve: resolveInit,
reject: rejectInit,
} = utils.deferredPromise();

const debug = process.env.NODE_ENV === "development";

Expand Down Expand Up @@ -85,7 +90,7 @@ const handleInstalled = (details: { reason: string }) => {

// listen to calls from the content script and calls the actions through the router
// returns a promise to be handled in the content script
const routeCalls = (
const routeCalls = async (
message: {
application: string;
prompt: boolean;
Expand All @@ -101,6 +106,7 @@ const routeCalls = (
if (message.type) {
console.error("Invalid message, using type: ", message);
}
await isInitialized;
const action = message.action || message.type;
console.info(`Routing call: ${action}`);
// Potentially check for internal vs. public calls
Expand All @@ -113,7 +119,8 @@ const routeCalls = (
return r;
});
}
return call;
const result = await call;
return result;
};

browser.runtime.onMessage.addListener(debugLogger);
Expand Down Expand Up @@ -149,18 +156,28 @@ async function init() {

events.subscribe();
console.info("Events subscribed");

if (isRecentlyUpdated) {
console.info("Running any pending migrations");
await migrate();
}
console.info("Loading completed");
}

console.info("Welcome to Alby");
init().then(() => {
if (isFirstInstalled && !state.getState().getAccount()) {
utils.openUrl("welcome.html");
}
if (isRecentlyUpdated) {
migrate();
}
});
init()
.then(() => {
if (resolveInit) {
resolveInit();
}
if (isFirstInstalled && !state.getState().getAccount()) {
utils.openUrl("welcome.html");
}
})
.catch((err) => {
console.error(err);
if (rejectInit) {
rejectInit();
}
});

browser.runtime.setUninstallURL("https://getalby.com/goodbye");
36 changes: 21 additions & 15 deletions src/extension/background-script/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ interface State {
account: Account | null;
accounts: Accounts;
migrations: Migration[] | null;
connector: Connector | null;
connector: Promise<Connector> | null;
currentAccountId: string | null;
nostrPrivateKey: string | null;
nostr: Nostr | null;
Expand Down Expand Up @@ -96,19 +96,25 @@ const state = createState<State>((set, get) => ({
},
getConnector: async () => {
if (get().connector) {
return get().connector as Connector;
const connector = (await get().connector) as Connector;
return connector;
}
const currentAccountId = get().currentAccountId as string;
const account = get().accounts[currentAccountId];
const password = await get().password();
if (!password) throw new Error("Password is not set");
const config = decryptData(account.config as string, password);

const connector = new connectors[account.connector](account, config);
await connector.init();

set({ connector: connector });

// use a Promise to initialize the connector
// this makes sure we can immediatelly set the state and use the same promise for future calls
// we must make sure not two connections are initialized
const connectorPromise = (async () => {
const currentAccountId = get().currentAccountId as string;
const account = get().accounts[currentAccountId];
const password = await get().password();
if (!password) throw new Error("Password is not set");
const config = decryptData(account.config as string, password);
const connector = new connectors[account.connector](account, config);
await connector.init();
return connector;
})();
set({ connector: connectorPromise });

const connector = await connectorPromise;
return connector;
},
getNostr: async () => {
Expand Down Expand Up @@ -146,8 +152,8 @@ const state = createState<State>((set, get) => ({

browser.tabs.remove(allTabIds);

const connector = get().connector;
if (connector) {
if (get().connector) {
const connector = (await get().connector) as Connector;
await connector.unload();
}
set({ connector: null, account: null, nostr: null });
Expand Down
6 changes: 6 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -769,3 +769,9 @@ export interface Invoice {
}

export type BrowserType = "chrome" | "firefox";

export interface DeferredPromise {
promise: Promise<unknown>;
resolve?: () => void;
reject?: () => void;
}