Skip to content

No handler registered in 'background' error, but background handler still being found and invoked #69

@VnUgE

Description

@VnUgE

So, I recently ran into a fun new issue I am having a hard time debugging. I recently switched up from using "hard-coded" message handlers to generating them dynamically at runtime. Not a single issue passing messages until that change. (Ill explain)

webex-err-image

The background onMessage handler for that messageId is correctly registered and is actually being called despite that error in the foreground code.

Error conditions

  • Only If one or more contexts are open such as options + popup (works fine if only one is open)
  • Only if an onMessage handler actually yields asynchronously such as network request or setTimeout in a promise
  • It happens if the promise is accepted or rejected.
  • The last context to open fails; if the options page is open, async popup requests will fail

I was having issues tracing with the debugger from the background side (couldn't repro), however I could trace with console messages to determine that the functions were still getting called despite the error and failure. However the sendMessage console error appears after the method is called, but before the promise resolves.

Example Source Code

import { runtime } from "webextension-polyfill";
import { onMessage, sendMessage } from 'webext-bridge/background'
import { BridgeMessage, RuntimeContext, isInternalEndpoint } from "webext-bridge";
import { JsonObject } from "type-fest";
import { cloneDeep } from "lodash";
import { debugLog } from "@vnuge/vnlib.browser";
export interface BgRuntime<T> {
    readonly state: T;
    readonly onInstalled: (callback: () => Promise<void>) => void;
    readonly onConnected: (callback: () => Promise<void>) => void;
}
export type ApiExport = {
    [key: string]: Function
};
export type IFeatureApi<T> = (bgApi?: BgRuntime<T>) => ApiExport
export type SendMessageHandler = <T extends JsonObject | JsonObject[]>(action: string, data: any) => Promise<T>
export type VarArgsFunction<T> = (...args: any[]) => T
export interface IFeatureExport<TState, TFeature extends ApiExport> {
    background: (bgApi: BgRuntime<TState>) => TFeature
    foreground: () => TFeature
}
export interface IForegroundUnwrapper {
    use: <T extends ApiExport>(api:() => IFeatureExport<any, T>) => T
}
export interface IBackgroundWrapper<TState> {
    register: <T extends ApiExport>(features: (() => IFeatureExport<TState, T>)[]) => void
}
export const useBackgroundFeatures = <TState>(state: TState): IBackgroundWrapper<TState> => {
    const rt = { state,
        onConnected: runtime.onConnect.addListener,
        onInstalled: runtime.onInstalled.addListener,
    }   as BgRuntime<TState>
    return{
        register: <TFeature extends ApiExport>(features:(() => IFeatureExport<TState, TFeature>)[]) => {
            for (const feature of features) {
                const f = feature().background(rt)
                for (const externFuncName in f) {
                    const func = f[externFuncName] as Function
                    const onMessageFuncName = `${feature.name}-${externFuncName}`
                    onMessage(onMessageFuncName, async (msg: BridgeMessage<any>) => {
                        try {
                            if (!isInternalEndpoint(msg.sender)) {
                                throw new Error(`Unauthorized external call to ${onMessageFuncName}`)
                            }
                            const result = func(...msg.data)
                            // ---> Foreground error is raised here if pending promise is awaited
                            const data = await result;
                            return { ...data }
                        }
                        catch (e: any) {
                            return { bridgeMessageException: JSON.stringify(e),}
                        }
                    });
  }}}}
}
export const useForegoundFeatures = (sendMessage: SendMessageHandler): IForegroundUnwrapper => {
    return{
        use: <T extends ApiExport>(feature:() => IFeatureExport<any, T>): T => {
            const api = feature().foreground()
            const proxied : T = {} as T
            for(const funcName in api){
                //Create proxy for each method
                proxied[funcName] = (async (...args:any) => {
                    const result = await sendMessage(`${feature.name}-${funcName}`, cloneDeep(args)) as any
                    if(result.bridgeMessageException){
                        const err = JSON.parse(result.bridgeMessageException)
                        if(result.errResponse){
                            err.response = JSON.parse(result.errResponse)
                        }
                        throw err
                    }
                    return result;
                }) as any
            }
            return proxied;
   }}
}
const exampleFeature = () : IFeatureExport<any, {exampleMethod:() => Promise<void>}> => ({
    foreground: () => ({
        exampleMethod: () => Promise.resolve() //stub method never actually called 
    }),
    background: (state:any) => ({
        exampleMethod: () => new Promise((resolve) => setTimeout(resolve, 0)) //actual background method called
    })
})
//In background main.ts
const { register } = useBackgroundFeatures({})
register([ exampleFeature ])

//In foreground
const { use } = useForegoundFeatures(sendMessage)
const { exampleMethod } = use(exampleFeature)
await exampleMethod() //Mapped directly to background handler

Each script, popup/options/conent-script pass the correct sendMessage function to the useForegoundFeatures method. The senMessage function uses the default context argument (tried explicitly setting 'background' and doesnt change).

Extra steps I have taken

  • Confirmed that the offending methods are correctly returning pending promises
  • Confirmed the issue still exists after a release build (not just during debugging)
  • Tried loading in FireFox on another machine, not using the debug remote-control
  • Rewrite using promises instead of async/await syntax
  • Confirmed no other messages are being handled when this happens

After debugging, it seems fairly obvious that a promise is not being properly awaited, I just need to figure out where, and why it would cause that type of exception. Big apologies if this a bonehead mistake, I have just been pulling my hair out all weekend and was hoping someone might be able to help. I have not pushed these latest changes to my repo yet (I wanted to debug first) but I can create a buggy branch if it would help seeing the entire project.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions