Skip to content
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

feat: add proper logger #144

Merged
merged 2 commits into from
May 8, 2024
Merged
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
1 change: 1 addition & 0 deletions js-peer/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions js-peer/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
18 changes: 6 additions & 12 deletions js-peer/src/components/chat.tsx
Original file line number Diff line number Diff line change
@@ -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()
Expand All @@ -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()),
)
Expand All @@ -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()),
)
Expand Down
7 changes: 5 additions & 2 deletions js-peer/src/context/chat-ctx.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -68,7 +71,7 @@ export const ChatProvider = ({ children }: any) => {

const chatMessageCB = (evt: CustomEvent<Message>, 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') {
Expand Down Expand Up @@ -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),
Expand Down
21 changes: 12 additions & 9 deletions js-peer/src/lib/libp2p.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: [
Expand Down Expand Up @@ -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
Expand All @@ -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
// }

Expand All @@ -131,24 +134,24 @@ export async function msgIdFnStrictNoSign(msg: Message): Promise<Uint8Array> {
async function dialWebRTCMaddrs(libp2p: Libp2p, multiaddrs: Multiaddr[]): Promise<void> {
// 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)
Expand Down
5 changes: 5 additions & 0 deletions js-peer/src/lib/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { prefixLogger } from '@libp2p/logger'

const prefix = `ui`

export const { forComponent } = prefixLogger(prefix)
3 changes: 1 addition & 2 deletions js-peer/src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading