Skip to content
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
4 changes: 1 addition & 3 deletions examples/serving-websites-from-web-browsers/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { noise } from '@chainsafe/libp2p-noise'
import { yamux } from '@chainsafe/libp2p-yamux'
import { circuitRelayTransport } from '@libp2p/circuit-relay-v2'
import { devToolsMetrics } from '@libp2p/devtools-metrics'
import { http } from '@libp2p/http'
import { nodeServer } from '@libp2p/http-server'
import { createServer } from '@libp2p/http-server/node'
Expand Down Expand Up @@ -91,8 +90,7 @@ const libp2p = await createLibp2p({
server: nodeServer(server)
}),
ping: ping()
},
metrics: devToolsMetrics()
}
})

// update listening addresses
Expand Down
1 change: 0 additions & 1 deletion examples/serving-websites-from-web-browsers/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
"@chainsafe/libp2p-noise": "^16.1.3",
"@chainsafe/libp2p-yamux": "^7.0.1",
"@libp2p/circuit-relay-v2": "^3.2.14",
"@libp2p/devtools-metrics": "^1.2.17",
"@libp2p/http": "^1.0.0",
"@libp2p/http-server": "^1.0.0",
"@libp2p/identify": "^3.0.32",
Expand Down
191 changes: 101 additions & 90 deletions packages/http-utils/src/stream-to-socket.ts
Original file line number Diff line number Diff line change
@@ -1,115 +1,123 @@
import { Duplex } from 'node:stream'
import { byteStream } from 'it-byte-stream'
import type { Connection, Stream } from '@libp2p/interface'
import type { ByteStream } from 'it-byte-stream'
import type { Socket, SocketConnectOpts, AddressInfo, SocketReadyState } from 'node:net'

const MAX_TIMEOUT = 2_147_483_647

class Libp2pSocket extends Duplex {
export class Libp2pSocket extends Duplex {
public readonly autoSelectFamilyAttemptedAddresses = []
public readonly connecting = false
public readonly pending = false
public readonly remoteAddress: string
public remoteAddress: string
public bytesRead: number
public bytesWritten: number
public timeout = MAX_TIMEOUT
public allowHalfOpen: boolean

private readonly stream: Stream
#stream?: Stream
#bytes?: ByteStream<Stream>

constructor (stream: Stream, connection: Connection) {
const bytes = byteStream(stream)
constructor () {
super()

super({
write: (chunk, encoding, cb) => {
this.stream.log('write %d bytes', chunk.byteLength)
this.bytesRead = 0
this.bytesWritten = 0
this.allowHalfOpen = true
this.remoteAddress = ''
}

this.bytesWritten += chunk.byteLength
bytes.write(chunk)
.then(() => {
cb()
}, err => {
cb(err)
setStream (stream: Stream, connection: Connection): void {
this.#bytes = byteStream(stream)
this.#stream = stream
this.remoteAddress = connection.remoteAddr.toString()
}

_write (chunk: Uint8Array, encoding: string, cb: (err?: Error) => void): void {
this.#stream?.log('write %d bytes', chunk.byteLength)

this.bytesWritten += chunk.byteLength
this.#bytes?.write(chunk)
.then(() => {
cb()
}, err => {
cb(err)
})
}

_read (size: number): void {
this.#stream?.log('asked to read %d bytes', size)

void Promise.resolve().then(async () => {
try {
while (true) {
const chunk = await this.#bytes?.read({
signal: AbortSignal.timeout(this.timeout)
})
},
read: (size) => {
this.stream.log('asked to read %d bytes', size)

void Promise.resolve().then(async () => {
try {
while (true) {
const chunk = await bytes.read({
signal: AbortSignal.timeout(this.timeout)
})

if (chunk == null) {
this.stream.log('socket readable end closed')
this.push(null)
return
}

this.bytesRead += chunk.byteLength

this.stream.log('socket read %d bytes', chunk.byteLength)
const more = this.push(chunk.subarray())

if (!more) {
break
}
}
} catch (err: any) {
this.destroy(err)

if (chunk == null) {
this.#stream?.log('socket readable end closed')
this.push(null)
return
}
})
},
destroy: (err, cb) => {
this.stream.log('destroy with %d bytes buffered - %e', this.bufferSize, err)

if (err != null) {
bytes.unwrap().abort(err)
cb()
} else {
bytes.unwrap().close()
.then(() => {
cb()
})
.catch(err => {
stream.abort(err)
cb(err)
})
}
},
final: (cb) => {
this.stream.log('final')
this.bytesRead += chunk.byteLength

bytes.unwrap().closeWrite()
.then(() => {
cb()
})
.catch(err => {
bytes.unwrap().abort(err)
cb(err)
})
this.#stream?.log('socket read %d bytes', chunk.byteLength)
const more = this.push(chunk.subarray())

if (!more) {
break
}
}
} catch (err: any) {
this.destroy(err)
}
})
}

this.stream = stream
this.remoteAddress = connection.remoteAddr.toString()
this.bytesRead = 0
this.bytesWritten = 0
this.allowHalfOpen = true
_destroy (err: Error, cb: (err?: Error) => void): void {
this.#stream?.log('destroy with %d bytes buffered - %e', this.bufferSize, err)

if (err != null) {
this.#bytes?.unwrap().abort(err)
cb()
} else {
this.#bytes?.unwrap().close()
.then(() => {
cb()
})
.catch(err => {
this.#stream?.abort(err)
cb(err)
})
}
}

_final (cb: (err?: Error) => void): void {
this.#stream?.log('final')

this.#bytes?.unwrap().closeWrite()
.then(() => {
cb()
})
.catch(err => {
this.#bytes?.unwrap().abort(err)
cb(err)
})
}

public get readyState (): SocketReadyState {
if (this.stream.status === 'closed') {
if (this.#stream?.status === 'closed') {
return 'closed'
}

if (this.stream.writeStatus === 'closed' || this.stream.writeStatus === 'closing') {
if (this.#stream?.writeStatus === 'closed' || this.#stream?.writeStatus === 'closing') {
return 'readOnly'
}

if (this.stream.readStatus === 'closed' || this.stream.readStatus === 'closing') {
if (this.#stream?.readStatus === 'closed' || this.#stream?.readStatus === 'closing') {
return 'writeOnly'
}

Expand All @@ -121,7 +129,7 @@ class Libp2pSocket extends Duplex {
}

destroySoon (): void {
this.stream.log('destroySoon with %d bytes buffered', this.bufferSize)
this.#stream?.log('destroySoon with %d bytes buffered', this.bufferSize)
this.destroy()
}

Expand All @@ -130,24 +138,24 @@ class Libp2pSocket extends Duplex {
connect (port: number, connectionListener?: () => void): this
connect (path: string, connectionListener?: () => void): this
connect (...args: any[]): this {
this.stream.log('connect %o', args)
this.#stream?.log('connect %o', args)
return this
}

setEncoding (encoding?: BufferEncoding): this {
this.stream.log('setEncoding %s', encoding)
this.#stream?.log('setEncoding %s', encoding)
return this
}

resetAndDestroy (): this {
this.stream.log('resetAndDestroy')
this.stream.abort(new Error('Libp2pSocket.resetAndDestroy'))
this.#stream?.log('resetAndDestroy')
this.#stream?.abort(new Error('Libp2pSocket.resetAndDestroy'))

return this
}

setTimeout (timeout: number, callback?: () => void): this {
this.stream.log('setTimeout %d', timeout)
this.#stream?.log('setTimeout %d', timeout)

if (callback != null) {
this.addListener('timeout', callback)
Expand All @@ -159,31 +167,31 @@ class Libp2pSocket extends Duplex {
}

setNoDelay (noDelay?: boolean): this {
this.stream.log('setNoDelay %b', noDelay)
this.#stream?.log('setNoDelay %b', noDelay)

return this
}

setKeepAlive (enable?: boolean, initialDelay?: number): this {
this.stream.log('setKeepAlive %b %d', enable, initialDelay)
this.#stream?.log('setKeepAlive %b %d', enable, initialDelay)

return this
}

address (): AddressInfo | Record<string, any> {
this.stream.log('address')
this.#stream?.log('address')

return {}
}

unref (): this {
this.stream.log('unref')
this.#stream?.log('unref')

return this
}

ref (): this {
this.stream.log('ref')
this.#stream?.log('ref')

return this
}
Expand All @@ -196,5 +204,8 @@ class Libp2pSocket extends Duplex {
}

export function streamToSocket (stream: Stream, connection: Connection): Socket {
return new Libp2pSocket(stream, connection)
const socket = new Libp2pSocket()
socket.setStream(stream, connection)

return socket
}
Loading
Loading