Skip to content

Commit

Permalink
fix: use separate logger for ui/sw (#217)
Browse files Browse the repository at this point in the history
* chore: use prefixLogger

* chore: use new logger in sw.ts

* fix: use separate logger for ui/sw

* chore: fix self-reviewed issues

* chore: shorten debug log prefix
  • Loading branch information
SgtPooki authored Apr 24, 2024
1 parent 80774f5 commit a96837b
Show file tree
Hide file tree
Showing 9 changed files with 82 additions and 62 deletions.
10 changes: 6 additions & 4 deletions src/context/service-worker-context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@
*/
import React, { createContext, useEffect, useState } from 'preact/compat'
import { getRedirectUrl, isDeregisterRequest } from '../lib/deregister-request.js'
import { error, trace } from '../lib/logger.js'
import { uiLogger } from '../lib/logger.js'
import { findOriginIsolationRedirect } from '../lib/path-or-subdomain.js'
import { registerServiceWorker } from '../service-worker-utils.js'

const log = uiLogger.forComponent('service-worker-context')

export const ServiceWorkerContext = createContext({
isServiceWorkerRegistered: false
})
Expand All @@ -39,13 +41,13 @@ export const ServiceWorkerProvider = ({ children }): React.JSX.Element => {
}
async function doWork (): Promise<void> {
if (isDeregisterRequest(window.location.href)) {
trace('UI: deregistering service worker')
log.trace('deregistering service worker')
const registration = await navigator.serviceWorker.getRegistration()
if (registration != null) {
await registration.unregister()
window.location.replace(getRedirectUrl(window.location.href).href)
} else {
error('UI: service worker not registered, cannot deregister')
log.error('service worker not registered, cannot deregister')
}
}
const registration = await navigator.serviceWorker.getRegistration()
Expand All @@ -57,7 +59,7 @@ export const ServiceWorkerProvider = ({ children }): React.JSX.Element => {
await registerServiceWorker()
setIsServiceWorkerRegistered(true)
} catch (err) {
error('error registering service worker', err)
log.error('error registering service worker', err)
}
}
}
Expand Down
9 changes: 6 additions & 3 deletions src/lib/channel.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { error } from './logger.js'
import type { ChannelActions } from './common.js'
import type { ComponentLogger, Logger } from '@libp2p/logger'

export enum ChannelUsers {
SW = 'SW',
Expand Down Expand Up @@ -34,11 +34,14 @@ export interface ChannelMessage<Source extends ChannelUserValues, Data = Record<
export class HeliaServiceWorkerCommsChannel<S extends ChannelUserValues = 'EMITTER_ONLY'> {
channel: BroadcastChannel
debug = false
constructor (public source: S, private readonly channelName = 'helia:sw') {
log: Logger
channelName = 'helia:sw'
constructor (public source: S, logger: ComponentLogger) {
this.log = logger.forComponent('comms-channel')
// NOTE: We're supposed to close the channel when we're done with it, but we're not doing that anywhere yet.
this.channel = new BroadcastChannel(this.channelName)
this.channel.onmessageerror = (e) => {
error('onmessageerror', e)
this.log.error('onmessageerror', e)
}
}

Expand Down
5 changes: 3 additions & 2 deletions src/lib/config-db.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import debugLib from 'debug'
import { GenericIDB, type BaseDbConfig } from './generic-db.js'
import { LOCAL_STORAGE_KEYS } from './local-storage.js'
import { log } from './logger.js'
import type { ComponentLogger } from '@libp2p/logger'

export interface ConfigDb extends BaseDbConfig {
gateways: string[]
Expand Down Expand Up @@ -32,7 +32,8 @@ export async function loadConfigFromLocalStorage (): Promise<void> {
}
}

export async function setConfig (config: ConfigDb): Promise<void> {
export async function setConfig (config: ConfigDb, logger: ComponentLogger): Promise<void> {
const log = logger.forComponent('set-config')
debugLib.enable(config.debug ?? '') // set debug level first.
log('config-debug: setting config %O for domain %s', config, window.location.origin)

Expand Down
4 changes: 1 addition & 3 deletions src/lib/deregister-request.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import { trace } from './logger.js'

// things are wonky with hash routes for deregistering.
export function isDeregisterRequest (url: string): boolean {
const urlObj = new URL(url)
const result = urlObj.search.includes('ipfs-sw-deregister')
trace('isDeregisterRequest: ', url, result)

return result
}

Expand Down
16 changes: 11 additions & 5 deletions src/lib/logger.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import { logger } from '@libp2p/logger'
import { prefixLogger, type ComponentLogger } from '@libp2p/logger'

const logObj = logger('helia:service-worker-gateway')
const host = globalThis.location.host.replace(':', '_')

export const log = logObj
export const error = logObj.error
export const trace = logObj.trace
const swLogPrefix = `helia:sw-gateway:sw:${host}`
const uiLogPrefix = `helia:sw-gateway:ui:${host}`

export const swLogger = prefixLogger(swLogPrefix)
export const uiLogger = prefixLogger(uiLogPrefix)

export const getUiComponentLogger = (component: string): ComponentLogger => {
return prefixLogger(`${uiLogPrefix}:${component}`)
}
14 changes: 8 additions & 6 deletions src/pages/config.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@ import { ServiceWorkerProvider } from '../context/service-worker-context.jsx'
import { HeliaServiceWorkerCommsChannel } from '../lib/channel.js'
import { getConfig, loadConfigFromLocalStorage } from '../lib/config-db.js'
import { LOCAL_STORAGE_KEYS } from '../lib/local-storage.js'
import { trace } from '../lib/logger.js'
import { getUiComponentLogger, uiLogger } from '../lib/logger.js'

const channel = new HeliaServiceWorkerCommsChannel('WINDOW')
const uiComponentLogger = getUiComponentLogger('config-page')
const log = uiLogger.forComponent('config-page')
const channel = new HeliaServiceWorkerCommsChannel('WINDOW', uiComponentLogger)

const urlValidationFn = (value: string): Error | null => {
try {
Expand Down Expand Up @@ -49,14 +51,14 @@ 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()
trace('config-page: postMessage config to origin ', config, targetOrigin)
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
*/
window.parent?.postMessage({ source: 'helia-sw-config-iframe', target: 'PARENT', action: 'RELOAD_CONFIG', config }, {
targetOrigin
})
trace('config-page: RELOAD_CONFIG sent to parent window')
log.trace('config-page: RELOAD_CONFIG sent to parent window')
}, [])

useEffect(() => {
Expand All @@ -69,11 +71,11 @@ function ConfigPage (): React.JSX.Element | null {
const saveConfig = useCallback(async () => {
try {
await loadConfigFromLocalStorage()
trace('config-page: sending RELOAD_CONFIG to service worker')
log.trace('config-page: sending RELOAD_CONFIG to service worker')
// update the BASE_URL service worker
await channel.messageAndWaitForResponse('SW', { target: 'SW', action: 'RELOAD_CONFIG' })
// base_domain service worker is updated
trace('config-page: RELOAD_CONFIG_SUCCESS for %s', window.location.origin)
log.trace('config-page: RELOAD_CONFIG_SUCCESS for %s', window.location.origin)
// update the <subdomain>.<namespace>.BASE_URL service worker
await postFromIframeToParentSw()
if (!isLoadedInIframe) {
Expand Down
15 changes: 9 additions & 6 deletions src/pages/redirect-page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,12 @@ import { HeliaServiceWorkerCommsChannel } from '../lib/channel.js'
import { setConfig, type ConfigDb } from '../lib/config-db.js'
import { getSubdomainParts } from '../lib/get-subdomain-parts.js'
import { isConfigPage } from '../lib/is-config-page.js'
import { error, trace } from '../lib/logger.js'
import { getUiComponentLogger, uiLogger } from '../lib/logger.js'
import { translateIpfsRedirectUrl } from '../lib/translate-ipfs-redirect-url.js'

const uiComponentLogger = getUiComponentLogger('redirect-page')
const log = uiLogger.forComponent('redirect-page')

const ConfigIframe = (): React.JSX.Element => {
const { parentDomain } = getSubdomainParts(window.location.href)
let iframeSrc
Expand All @@ -27,7 +30,7 @@ const ConfigIframe = (): React.JSX.Element => {
)
}

const channel = new HeliaServiceWorkerCommsChannel('WINDOW')
const channel = new HeliaServiceWorkerCommsChannel('WINDOW', uiComponentLogger)

function RedirectPage ({ showConfigIframe = true }: { showConfigIframe?: boolean }): React.JSX.Element {
const [isAutoReloadEnabled, setIsAutoReloadEnabled] = useState(false)
Expand All @@ -41,14 +44,14 @@ function RedirectPage ({ showConfigIframe = true }: { showConfigIframe?: boolean

async function doWork (config: ConfigDb): Promise<void> {
try {
await setConfig(config)
await setConfig(config, uiComponentLogger)
// TODO: show spinner / disable buttons while waiting for response
await channel.messageAndWaitForResponse('SW', { target: 'SW', action: 'RELOAD_CONFIG' })
trace('redirect-page: RELOAD_CONFIG_SUCCESS on %s', window.location.origin)
log.trace('redirect-page: RELOAD_CONFIG_SUCCESS on %s', window.location.origin)
// try to preload the content
// await fetch(window.location.href, { method: 'GET' })
} catch (err) {
error('redirect-page: error setting config on subdomain', err)
log.error('redirect-page: error setting config on subdomain', err)
}

if (config.autoReload) {
Expand All @@ -57,7 +60,7 @@ function RedirectPage ({ showConfigIframe = true }: { showConfigIframe?: boolean
}
const listener = (event: MessageEvent): void => {
if (event.data?.source === 'helia-sw-config-iframe') {
trace('redirect-page: received RELOAD_CONFIG message from iframe', event.data)
log.trace('redirect-page: received RELOAD_CONFIG message from iframe', event.data)
const config = event.data?.config
if (config != null) {
void doWork(config as ConfigDb)
Expand Down
6 changes: 5 additions & 1 deletion src/service-worker-utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { log } from './lib/logger.js'
import { uiLogger } from './lib/logger.js'

/**
* This function is always and only used from the UI
*/
export async function registerServiceWorker (): Promise<ServiceWorkerRegistration> {
const log = uiLogger.forComponent('register-service-worker')
const swRegistration = await navigator.serviceWorker.register(new URL(/* webpackChunkName: "sw" */'sw.js', import.meta.url))
return new Promise((resolve, reject) => {
swRegistration.addEventListener('updatefound', () => {
Expand Down
Loading

0 comments on commit a96837b

Please sign in to comment.