Skip to content
Merged
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
35 changes: 25 additions & 10 deletions packages/utils/src/stream-to-ma-conn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,28 @@ export function streamToMaConnection (props: StreamProperties): MultiaddrConnect
const { sink, source } = stream
const log = logger.forComponent('libp2p:stream:converter')

let closedRead = false
let closedWrite = false

const mapSource = (async function * () {
for await (const list of source) {
if (list instanceof Uint8Array) {
yield list
} else {
yield * list
try {
for await (const list of source) {
if (list instanceof Uint8Array) {
yield list
} else {
yield * list
}
}
} finally {
closedRead = true
close()
}
}())

const maConn: MultiaddrConnection = {
async sink (source) {
try {
await sink(source)
close()
} catch (err: any) {
// If aborted we can safely ignore
if (err.type !== 'aborted') {
Expand All @@ -41,23 +48,31 @@ export function streamToMaConnection (props: StreamProperties): MultiaddrConnect
// destroyed. There's nothing to do here except log the error & return.
log(err)
}
} finally {
closedWrite = true
close()
}
},
source: mapSource,
remoteAddr,
timeline: { open: Date.now(), close: undefined },
async close (options?: AbortOptions) {
close()
close(true)
await stream.close(options)
},
abort (err: Error): void {
close()
close(true)
stream.abort(err)
}
}

function close (): void {
if (maConn.timeline.close == null) {
function close (force?: boolean): void {
if (force === true) {
closedRead = true
closedWrite = true
}

if (closedRead && closedWrite && maConn.timeline.close == null) {
maConn.timeline.close = Date.now()
}
}
Expand Down