Skip to content

fix failing api calls due to inactive service worker #731

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

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions apps/wallet/src/data/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import { createTRPCProxyClient } from '@trpc/client'
import { initTRPC } from '@trpc/server'
import superjson from 'superjson'
import { createChromeHandler } from 'trpc-chrome/adapter'
import { chromeLink } from 'trpc-chrome/link'
import { z } from 'zod'

import * as bitcoin from './bitcoin/bitcoin'
import { chromeLinkWithRetries } from './chromeLink'
import * as ethereum from './ethereum/ethereum'
import { getKeystore } from './keystore'
import * as solana from './solana/solana'
Expand Down Expand Up @@ -601,10 +601,8 @@ export async function createAPI() {
}

export function createAPIClient() {
const port = chrome.runtime.connect()

return createTRPCProxyClient<APIRouter>({
links: [chromeLink({ port })],
links: [chromeLinkWithRetries()],
transformer: superjson,
})
}
121 changes: 121 additions & 0 deletions apps/wallet/src/data/chromeLink.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import { chromeLink } from 'trpc-chrome/link'

import type { TRPCLink } from '@trpc/client'
import type { AnyRouter } from '@trpc/server'
import type { ChromeLinkOptions } from 'trpc-chrome/link'

const MAX_RETRIES = 3
const RETRY_DELAY = 100

export function chromeLinkWithRetries<TRouter extends AnyRouter>(
options: Omit<ChromeLinkOptions, 'port'> = {},
): TRPCLink<TRouter> {
const { ...chromeLinkOptions } = options

let port: chrome.runtime.Port | null = null
let currentLink: TRPCLink<TRouter> | null = null

const createPort = () => {
if (port) {
try {
port.disconnect()
// eslint-disable-next-line no-empty
} catch {}
}

port = chrome.runtime.connect()
port.onDisconnect.addListener(() => {
port = null
currentLink = null
})

currentLink = chromeLink({ ...chromeLinkOptions, port })

return port
}

const checkConnection = () => {
if (!port || !currentLink) {
createPort()
} else {
try {
port.postMessage({ type: 'ping' })
if (chrome.runtime.lastError) {
createPort()
}
} catch {
createPort()
}
}
}

// @ts-expect-error - Custom observable missing pipe method but functionally compatible
return runtime => {
return ctx => {
let retryCount = 0

const retryOperation = async (): Promise<unknown> => {
try {
checkConnection()

if (!currentLink) {
throw new Error('Failed to establish connection')
}

const result = await new Promise((resolve, reject) => {
currentLink!(runtime)(ctx).subscribe({
next(value) {
resolve(value)
},
error(err) {
reject(err)
},
})
})

return result
} catch (error) {
const isConnectionError =
error instanceof Error &&
(error.message.includes('Attempting to use a disconnected port') ||
error.message.includes('Could not establish connection') ||
error.message.includes('Extension context invalidated') ||
chrome.runtime.lastError !== undefined)

if (isConnectionError && retryCount < MAX_RETRIES) {
retryCount++

port = null
currentLink = null
await new Promise(resolve =>
setTimeout(resolve, RETRY_DELAY * retryCount),
)

return retryOperation()
}

throw error
}
}

return {
subscribe(observer) {
retryOperation()
.then(value => {
observer.next?.(
value as Parameters<NonNullable<typeof observer.next>>[0],
)
observer.complete?.()
})
.catch(err => {
observer.error?.(err)
})

return {
unsubscribe: () => {},
}
},
}
}
}
}
Loading