diff --git a/js-peer/package-lock.json b/js-peer/package-lock.json index 21c1bcc1..0dc8f474 100644 --- a/js-peer/package-lock.json +++ b/js-peer/package-lock.json @@ -17,6 +17,7 @@ "@libp2p/circuit-relay-v2": "^1.0.22", "@libp2p/identify": "^2.0.0", "@libp2p/interface-pubsub": "^4.0.1", + "@libp2p/logger": "^4.0.10", "@libp2p/pubsub-peer-discovery": "^10.0.2", "@libp2p/webrtc": "^4.0.31", "@libp2p/websockets": "^8.0.22", diff --git a/js-peer/package.json b/js-peer/package.json index a5384b3c..4e072555 100644 --- a/js-peer/package.json +++ b/js-peer/package.json @@ -18,6 +18,7 @@ "@libp2p/circuit-relay-v2": "^1.0.22", "@libp2p/identify": "^2.0.0", "@libp2p/interface-pubsub": "^4.0.1", + "@libp2p/logger": "^4.0.10", "@libp2p/pubsub-peer-discovery": "^10.0.2", "@libp2p/webrtc": "^4.0.31", "@libp2p/websockets": "^8.0.22", diff --git a/js-peer/src/components/chat.tsx b/js-peer/src/components/chat.tsx index 9a217c04..584a8723 100644 --- a/js-peer/src/components/chat.tsx +++ b/js-peer/src/components/chat.tsx @@ -1,18 +1,12 @@ import { useLibp2pContext } from '@/context/ctx' import React, { useCallback, useEffect, useRef, useState } from 'react' -import type { Message } from '@libp2p/interface' import { CHAT_FILE_TOPIC, CHAT_TOPIC, FILE_EXCHANGE_PROTOCOL } from '@/lib/constants' -import { createIcon } from '@download/blockies' import { ChatFile, ChatMessage, useChatContext } from '../context/chat-ctx' import { v4 as uuidv4 } from 'uuid' -import { pipe } from 'it-pipe' -import map from 'it-map' -import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string' -import { toString as uint8ArrayToString } from 'uint8arrays/to-string' -import * as lp from 'it-length-prefixed' import { MessageComponent } from './message' +import { forComponent } from '@/lib/logger' -interface MessageProps extends ChatMessage {} +const log = forComponent('chat') export default function ChatContainer() { const { libp2p } = useLibp2pContext() @@ -23,13 +17,13 @@ export default function ChatContainer() { const sendMessage = useCallback(async () => { if (input === '') return - console.log( + log( `peers in gossip for topic ${CHAT_TOPIC}:`, libp2p.services.pubsub.getSubscribers(CHAT_TOPIC).toString(), ) const res = await libp2p.services.pubsub.publish(CHAT_TOPIC, new TextEncoder().encode(input)) - console.log( + log( 'sent message to: ', res.recipients.map((peerId) => peerId.toString()), ) @@ -55,13 +49,13 @@ export default function ChatContainer() { } setFiles(files.set(file.id, file)) - console.log( + log( `peers in gossip for topic ${CHAT_FILE_TOPIC}:`, libp2p.services.pubsub.getSubscribers(CHAT_FILE_TOPIC).toString(), ) const res = await libp2p.services.pubsub.publish(CHAT_FILE_TOPIC, new TextEncoder().encode(file.id)) - console.log( + log( 'sent file to: ', res.recipients.map((peerId) => peerId.toString()), ) diff --git a/js-peer/src/context/chat-ctx.tsx b/js-peer/src/context/chat-ctx.tsx index 4375cc5d..b98dab7d 100644 --- a/js-peer/src/context/chat-ctx.tsx +++ b/js-peer/src/context/chat-ctx.tsx @@ -7,6 +7,9 @@ import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string' import { pipe } from 'it-pipe' import map from 'it-map' import * as lp from 'it-length-prefixed' +import { forComponent } from '@/lib/logger'; + +const log = forComponent('chat-context') export interface ChatMessage { @@ -68,7 +71,7 @@ export const ChatProvider = ({ children }: any) => { const chatMessageCB = (evt: CustomEvent, topic: string, data: Uint8Array) => { const msg = new TextDecoder().decode(data) - console.log(`${topic}: ${msg}`) + log(`${topic}: ${msg}`) // Append signed messages, otherwise discard if (evt.detail.type === 'signed') { @@ -98,7 +101,7 @@ export const ChatProvider = ({ children }: any) => { async function(source) { for await (const data of source) { const body: Uint8Array = data.subarray() - console.log(`request_response: response received: size:${body.length}`) + log(`chat file message request_response: response received: size:${body.length}`) const msg: ChatMessage = { msg: newChatFileMessage(fileId, body), diff --git a/js-peer/src/lib/libp2p.ts b/js-peer/src/lib/libp2p.ts index 2e93fff6..edef0318 100644 --- a/js-peer/src/lib/libp2p.ts +++ b/js-peer/src/lib/libp2p.ts @@ -19,15 +19,18 @@ import { circuitRelayTransport } from '@libp2p/circuit-relay-v2' import { pubsubPeerDiscovery } from '@libp2p/pubsub-peer-discovery' import { BOOTSTRAP_PEER_IDS, CHAT_FILE_TOPIC, CHAT_TOPIC, PUBSUB_PEER_DISCOVERY } from './constants' import first from 'it-first' +import { forComponent } from './logger' + +const log = forComponent('libp2p') export async function startLibp2p() { // enable verbose logging in browser console to view debug logs - localStorage.debug = 'libp2p*,-libp2p:connection-manager*,-*:trace' + localStorage.debug = 'ui*,libp2p*,-libp2p:connection-manager*,-*:trace' const delegatedClient = createDelegatedRoutingV1HttpApiClient('https://delegated-ipfs.dev') const { bootstrapAddrs, relayListenAddrs } = await getBootstrapMultiaddrs(delegatedClient) + log('starting libp2p with bootstrapAddrs %o and relayListenAddrs: %o', bootstrapAddrs, relayListenAddrs) - console.log('starting libp2p') const libp2p = await createLibp2p({ addresses: { listen: [ @@ -97,7 +100,7 @@ export async function startLibp2p() { libp2p.addEventListener('self:peer:update', ({ detail: { peer } }) => { const multiaddrs = peer.addresses.map(({ multiaddr }) => multiaddr) - console.log(`changed multiaddrs: peer ${peer.id.toString()} multiaddrs: ${multiaddrs}`) + log(`changed multiaddrs: peer ${peer.id.toString()} multiaddrs: ${multiaddrs}`) }) // 👇 explicitly dialling peers discovered via pubsub is only necessary @@ -106,7 +109,7 @@ export async function startLibp2p() { // const { multiaddrs, id } = event.detail // if (libp2p.getConnections(id)?.length > 0) { - // console.log(`Already connected to peer %s. Will not try dialling`, id) + // log(`Already connected to peer %s. Will not try dialling`, id) // return // } @@ -131,24 +134,24 @@ export async function msgIdFnStrictNoSign(msg: Message): Promise { async function dialWebRTCMaddrs(libp2p: Libp2p, multiaddrs: Multiaddr[]): Promise { // Filter webrtc (browser-to-browser) multiaddrs const webRTCMadrs = multiaddrs.filter((maddr) => maddr.protoNames().includes('webrtc')) - console.log(`peer:discovery with maddrs: %o`, webRTCMadrs) + log(`dialling WebRTC multiaddrs: %o`, webRTCMadrs) for (const addr of webRTCMadrs) { try { - console.log(`woot attempting to dial webrtc multiaddr: %o`, addr) + log(`attempting to dial webrtc multiaddr: %o`, addr) await libp2p.dial(addr) return // if we succeed dialing the peer, no need to try another address } catch (error) { - console.error(`woot failed to dial webrtc multiaddr: %o`, addr) + log.error(`failed to dial webrtc multiaddr: %o`, addr) } } } export const connectToMultiaddr = (libp2p: Libp2p) => async (multiaddr: Multiaddr) => { - console.log(`dialling: ${multiaddr.toString()}`) + log(`dialling: %a`, multiaddr) try { const conn = await libp2p.dial(multiaddr) - console.info('connected to', conn.remotePeer, 'on', conn.remoteAddr) + log('connected to %p on %a', conn.remotePeer, conn.remoteAddr) return conn } catch (e) { console.error(e) diff --git a/js-peer/src/lib/logger.ts b/js-peer/src/lib/logger.ts new file mode 100644 index 00000000..cafa6054 --- /dev/null +++ b/js-peer/src/lib/logger.ts @@ -0,0 +1,5 @@ +import { prefixLogger } from '@libp2p/logger' + +const prefix = `ui` + +export const { forComponent } = prefixLogger(prefix) diff --git a/js-peer/src/pages/index.tsx b/js-peer/src/pages/index.tsx index 74212d5b..b354bebf 100644 --- a/js-peer/src/pages/index.tsx +++ b/js-peer/src/pages/index.tsx @@ -53,8 +53,7 @@ export default function Home() { } setDialling(true) try { - const connection = await connectToMultiaddr(libp2p)(multiaddr(maddr)) - console.log('connection established: ', connection) + await connectToMultiaddr(libp2p)(multiaddr(maddr)) } catch (e: any) { setErr(e?.message ?? 'Error connecting') } finally {