Skip to content

Commit

Permalink
fix: multiple bugs (#220)
Browse files Browse the repository at this point in the history
* Revert "feat: migrate to preact/compat (#190)"

This reverts commit 8c98f57.

* fix: duplicate body processing in errorPageResponse

* fix: match css + js sw assets

* fix: sw sometimes uses empty gateways+routers config

* fix: getConfig is more robust and receives logger
  • Loading branch information
SgtPooki authored Apr 24, 2024
1 parent 4443174 commit 75aa0b8
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 22 deletions.
39 changes: 31 additions & 8 deletions src/lib/config-db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,16 +45,39 @@ export async function setConfig (config: ConfigDb, logger: ComponentLogger): Pro
configDb.close()
}

export async function getConfig (): Promise<ConfigDb> {
await configDb.open()
const defaultGateways = ['https://trustless-gateway.link']
const defaultRouters = ['https://delegated-ipfs.dev']
export async function getConfig (logger: ComponentLogger): Promise<ConfigDb> {
const log = logger.forComponent('get-config')
let gateways: string[] = defaultGateways
let routers: string[] = defaultRouters
let autoReload = false
let debug = ''

const gateways = await configDb.get('gateways') ?? ['https://trustless-gateway.link']
const routers = await configDb.get('routers') ?? ['https://delegated-ipfs.dev']
const autoReload = await configDb.get('autoReload') ?? false
const debug = await configDb.get('debug') ?? ''
configDb.close()
debugLib.enable(debug)
try {
await configDb.open()

gateways = await configDb.get('gateways')

routers = await configDb.get('routers')

autoReload = await configDb.get('autoReload') ?? false
debug = await configDb.get('debug') ?? ''
configDb.close()
debugLib.enable(debug)
} catch (err) {
log('error loading config from db', err)
}

if (gateways == null || gateways.length === 0) {
gateways = [...defaultGateways]
}

if (routers == null || routers.length === 0) {
routers = [...defaultRouters]
}

// always return the config, even if we failed to load it.
return {
gateways,
routers,
Expand Down
2 changes: 1 addition & 1 deletion src/pages/config.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ function ConfigPage (): React.JSX.Element | null {
}
// we get the iframe origin from a query parameter called 'origin', if this is loaded in an iframe
const targetOrigin = decodeURIComponent(window.location.hash.split('@origin=')[1])
const config = await getConfig()
const config = await getConfig(uiComponentLogger)
log.trace('config-page: postMessage config to origin ', config, targetOrigin)
/**
* The reload page in the parent window is listening for this message, and then it passes a RELOAD_CONFIG message to the service worker
Expand Down
25 changes: 12 additions & 13 deletions src/sw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ self.addEventListener('activate', (event) => {
switch (action) {
case 'RELOAD_CONFIG':
void updateVerifiedFetch().then(async () => {
channel.postMessage<any>({ action: 'RELOAD_CONFIG_SUCCESS', data: { config: await getConfig() } })
channel.postMessage<any>({ action: 'RELOAD_CONFIG_SUCCESS', data: { config: await getConfig(swLogger) } })
log.trace('RELOAD_CONFIG_SUCCESS for %s', self.location.origin)
})
break
Expand Down Expand Up @@ -174,12 +174,14 @@ self.addEventListener('fetch', (event) => {
const request = event.request
const urlString = request.url
const url = new URL(urlString)
log('incoming request url: %s:', event.request.url)
log('request range header value: "%s"', event.request.headers.get('range'))
log.trace('incoming request url: %s:', event.request.url)

event.waitUntil(requestRouting(event, url).then(async (shouldHandle) => {
if (shouldHandle) {
log.trace('handling request for %s', url)
event.respondWith(getResponseFromCacheOrFetch(event))
} else {
log.trace('not handling request for %s', url)
}
}))
})
Expand Down Expand Up @@ -221,12 +223,12 @@ async function requestRouting (event: FetchEvent, url: URL): Promise<boolean> {
}

async function getVerifiedFetch (): Promise<VerifiedFetch> {
const config = await getConfig()
const config = await getConfig(swLogger)
log(`config-debug: got config for sw location ${self.location.origin}`, config)

const verifiedFetch = await createVerifiedFetch({
gateways: config.gateways ?? ['https://trustless-gateway.link'],
routers: config.routers ?? ['https://delegated-ipfs.dev'],
gateways: config.gateways,
routers: config.routers,
dnsResolvers: {
'.': dnsJsonOverHttps('https://delegated-ipfs.dev/dns-query')
}
Expand Down Expand Up @@ -283,7 +285,7 @@ function isAggregateError (err: unknown): err is AggregateError {
}

function isSwAssetRequest (event: FetchEvent): boolean {
const isActualSwAsset = /^.+\/(?:ipfs-sw-).+\.js$/.test(event.request.url)
const isActualSwAsset = /^.+\/(?:ipfs-sw-).+$/.test(event.request.url)
return isActualSwAsset
}

Expand Down Expand Up @@ -513,7 +515,6 @@ async function fetchHandler ({ path, request, event }: FetchHandlerArg): Promise
async function errorPageResponse (fetchResponse: Response): Promise<Response> {
const responseContentType = fetchResponse.headers.get('Content-Type')
let json: Record<string, any> | null = null
let text: string | null = null
const responseBodyAsText: string | null = await fetchResponse.text()

if (responseContentType != null) {
Expand All @@ -524,14 +525,12 @@ async function errorPageResponse (fetchResponse: Response): Promise<Response> {
try {
json = JSON.parse(responseBodyAsText)
} catch (e) {
text = responseBodyAsText
json = { error: { message: `${fetchResponse.statusText}: ${text}`, stack: null } }
log.error('error parsing json for error page response', e)
}
}
}
if (json == null) {
text = await fetchResponse.text()
json = { error: { message: `${fetchResponse.statusText}: ${text}`, stack: null } }
json = { error: { message: `${fetchResponse.statusText}: ${responseBodyAsText}`, stack: null } }
}

const responseDetails = getResponseDetails(fetchResponse, responseBodyAsText)
Expand Down Expand Up @@ -573,7 +572,7 @@ async function getServiceWorkerDetails (): Promise<ServiceWorkerDetails> {
const state = registration.installing?.state ?? registration.waiting?.state ?? registration.active?.state ?? 'unknown'

return {
config: await getConfig(),
config: await getConfig(swLogger),
// TODO: implement https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy
crossOriginIsolated: self.crossOriginIsolated,
installTime: (new Date(firstInstallTime)).toUTCString(),
Expand Down

0 comments on commit 75aa0b8

Please sign in to comment.