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 memory transport #2802

Merged
merged 1 commit into from
Nov 5, 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
2 changes: 1 addition & 1 deletion .release-please-manifest.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"packages/connection-encrypter-plaintext":"2.0.10","packages/connection-encrypter-tls":"2.0.10","packages/crypto":"5.0.6","packages/interface":"2.2.0","packages/interface-compliance-tests":"6.1.8","packages/interface-internal":"2.0.10","packages/kad-dht":"14.1.0","packages/keychain":"5.0.9","packages/libp2p":"2.2.1","packages/logger":"5.1.3","packages/metrics-devtools":"1.1.8","packages/metrics-prometheus":"4.2.4","packages/metrics-simple":"1.2.6","packages/multistream-select":"6.0.8","packages/peer-collections":"6.0.10","packages/peer-discovery-bootstrap":"11.0.10","packages/peer-discovery-mdns":"11.0.10","packages/peer-id":"5.0.7","packages/peer-record":"8.0.10","packages/peer-store":"11.0.10","packages/pnet":"2.0.10","packages/protocol-autonat":"2.0.10","packages/protocol-dcutr":"2.0.10","packages/protocol-echo":"2.1.1","packages/protocol-fetch":"2.0.10","packages/protocol-identify":"3.0.10","packages/protocol-perf":"4.0.10","packages/protocol-ping":"2.0.10","packages/pubsub":"10.0.10","packages/pubsub-floodsub":"10.1.8","packages/record":"4.0.4","packages/stream-multiplexer-mplex":"11.0.10","packages/transport-circuit-relay-v2":"3.1.0","packages/transport-tcp":"10.0.11","packages/transport-webrtc":"5.0.16","packages/transport-websockets":"9.0.11","packages/transport-webtransport":"5.0.16","packages/upnp-nat":"2.0.10","packages/utils":"6.1.3"}
{"packages/connection-encrypter-plaintext":"2.0.10","packages/connection-encrypter-tls":"2.0.10","packages/crypto":"5.0.6","packages/interface":"2.2.0","packages/interface-compliance-tests":"6.1.8","packages/interface-internal":"2.0.10","packages/kad-dht":"14.1.0","packages/keychain":"5.0.9","packages/libp2p":"2.2.1","packages/logger":"5.1.3","packages/metrics-devtools":"1.1.8","packages/metrics-prometheus":"4.2.4","packages/metrics-simple":"1.2.6","packages/multistream-select":"6.0.8","packages/peer-collections":"6.0.10","packages/peer-discovery-bootstrap":"11.0.10","packages/peer-discovery-mdns":"11.0.10","packages/peer-id":"5.0.7","packages/peer-record":"8.0.10","packages/peer-store":"11.0.10","packages/pnet":"2.0.10","packages/protocol-autonat":"2.0.10","packages/protocol-dcutr":"2.0.10","packages/protocol-echo":"2.1.1","packages/protocol-fetch":"2.0.10","packages/protocol-identify":"3.0.10","packages/protocol-perf":"4.0.10","packages/protocol-ping":"2.0.10","packages/pubsub":"10.0.10","packages/pubsub-floodsub":"10.1.8","packages/record":"4.0.4","packages/stream-multiplexer-mplex":"11.0.10","packages/transport-circuit-relay-v2":"3.1.0","packages/transport-memory":"0.0.0","packages/transport-tcp":"10.0.11","packages/transport-webrtc":"5.0.16","packages/transport-websockets":"9.0.11","packages/transport-webtransport":"5.0.16","packages/upnp-nat":"2.0.10","packages/utils":"6.1.3"}
1 change: 1 addition & 0 deletions .release-please.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"packages/record": {},
"packages/stream-multiplexer-mplex": {},
"packages/transport-circuit-relay-v2": {},
"packages/transport-memory": {},
"packages/transport-tcp": {},
"packages/transport-webrtc": {},
"packages/transport-websockets": {},
Expand Down
6 changes: 6 additions & 0 deletions packages/transport-memory/.aegir.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/** @type {import('aegir').PartialOptions} */
export default {
build: {
bundlesizeMax: '15KB'
}
}
4 changes: 4 additions & 0 deletions packages/transport-memory/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
This project is dual licensed under MIT and Apache-2.0.

MIT: https://www.opensource.org/licenses/mit
Apache-2.0: https://www.apache.org/licenses/license-2.0
5 changes: 5 additions & 0 deletions packages/transport-memory/LICENSE-APACHE
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
19 changes: 19 additions & 0 deletions packages/transport-memory/LICENSE-MIT
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
The MIT License (MIT)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
86 changes: 86 additions & 0 deletions packages/transport-memory/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# @libp2p/tcp

[![libp2p.io](https://img.shields.io/badge/project-libp2p-yellow.svg?style=flat-square)](http://libp2p.io/)
[![Discuss](https://img.shields.io/discourse/https/discuss.libp2p.io/posts.svg?style=flat-square)](https://discuss.libp2p.io)
[![codecov](https://img.shields.io/codecov/c/github/libp2p/js-libp2p.svg?style=flat-square)](https://codecov.io/gh/libp2p/js-libp2p)
[![CI](https://img.shields.io/github/actions/workflow/status/libp2p/js-libp2p/main.yml?branch=main\&style=flat-square)](https://github.com/libp2p/js-libp2p/actions/workflows/main.yml?query=branch%3Amain)

> A memory transport for libp2p

# About

<!--

!IMPORTANT!

Everything in this README between "# About" and "# Install" is automatically
generated and will be overwritten the next time the doc generator is run.

To make changes to this section, please update the @packageDocumentation section
of src/index.js or src/index.ts

To experiment with formatting, please run "npm run docs" from the root of this
repo and examine the changes made.

-->

A [libp2p transport](https://docs.libp2p.io/concepts/transports/overview/)
that operates in-memory only.

This is intended for testing and can only be used to connect two libp2p nodes
that are running in the same process.

## Example

```TypeScript
import { createLibp2p } from 'libp2p'
import { memory } from '@libp2p/memory'
import { multiaddr } from '@multiformats/multiaddr'

const listener = await createLibp2p({
addresses: {
listen: [
'/memory/address-a'
]
},
transports: [
memory()
]
})

const dialer = await createLibp2p({
transports: [
memory()
]
})

const ma = multiaddr('/memory/address-a')

// dial the listener, timing out after 10s
const connection = await dialer.dial(ma, {
signal: AbortSignal.timeout(10_000)
})

// use connection...
```

# Install

```console
$ npm i @libp2p/tcp
```

# API Docs

- <https://libp2p.github.io/js-libp2p/modules/_libp2p_tcp.html>

# License

Licensed under either of

- Apache 2.0, ([LICENSE-APACHE](https://github.com/libp2p/js-libp2p/blob/main/packages/transport-tcp/LICENSE-APACHE) / <http://www.apache.org/licenses/LICENSE-2.0>)
- MIT ([LICENSE-MIT](https://github.com/libp2p/js-libp2p/blob/main/packages/transport-tcp/LICENSE-MIT) / <http://opensource.org/licenses/MIT>)

# Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
75 changes: 75 additions & 0 deletions packages/transport-memory/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
{
"name": "@libp2p/memory",
"version": "0.0.0",
"description": "A memory transport for libp2p",
"license": "Apache-2.0 OR MIT",
"homepage": "https://github.com/libp2p/js-libp2p/tree/main/packages/transport-tcp#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/libp2p/js-libp2p.git"
},
"bugs": {
"url": "https://github.com/libp2p/js-libp2p/issues"
},
"publishConfig": {
"access": "public",
"provenance": true
},
"type": "module",
"types": "./dist/src/index.d.ts",
"files": [
"src",
"dist",
"!dist/test",
"!**/*.tsbuildinfo"
],
"exports": {
".": {
"types": "./dist/src/index.d.ts",
"import": "./dist/src/index.js"
}
},
"eslintConfig": {
"extends": "ipfs",
"parserOptions": {
"project": true,
"sourceType": "module"
}
},
"scripts": {
"clean": "aegir clean",
"lint": "aegir lint",
"dep-check": "aegir dep-check",
"doc-check": "aegir doc-check",
"build": "aegir build",
"test": "aegir test -t node -t electron-main",
"test:chrome": "aegir test -t browser -f ./dist/test/browser.js --cov",
"test:chrome-webworker": "aegir test -t webworker -f ./dist/test/browser.js",
"test:firefox": "aegir test -t browser -f ./dist/test/browser.js -- --browser firefox",
"test:firefox-webworker": "aegir test -t webworker -f ./dist/test/browser.js -- --browser firefox",
"test:node": "aegir test -t node --cov",
"test:electron-main": "aegir test -t electron-main"
},
"dependencies": {
"@libp2p/interface": "^2.2.0",
"@multiformats/multiaddr": "^12.2.3",
"@multiformats/multiaddr-matcher": "^1.5.0",
"@types/sinon": "^17.0.3",
"delay": "^6.0.0",
"it-map": "^3.1.1",
"it-pushable": "^3.2.3",
"nanoid": "^5.0.8",
"uint8arraylist": "^2.4.8"
},
"devDependencies": {
"@libp2p/crypto": "^5.0.6",
"@libp2p/interface-compliance-tests": "^6.1.8",
"@libp2p/logger": "^5.1.3",
"@libp2p/peer-id": "^5.0.7",
"aegir": "^44.0.1"
},
"browser": {
"./dist/src/tcp.js": "./dist/src/tcp.browser.js"
},
"sideEffects": false
}
176 changes: 176 additions & 0 deletions packages/transport-memory/src/connections.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
/**
* @packageDocumentation
*
* A [libp2p transport](https://docs.libp2p.io/concepts/transports/overview/)
* that operates in-memory only.
*
* This is intended for testing and can only be used to connect two libp2p nodes
* that are running in the same process.
*
* @example
*
* ```TypeScript
* import { createLibp2p } from 'libp2p'
* import { memory } from '@libp2p/memory'
* import { multiaddr } from '@multiformats/multiaddr'
*
* const listener = await createLibp2p({
* addresses: {
* listen: [
* '/memory/node-a'
* ]
* },
* transports: [
* memory()
* ]
* })
*
* const dialer = await createLibp2p({
* transports: [
* memory()
* ]
* })
*
* const ma = multiaddr('/memory/node-a')
*
* // dial the listener, timing out after 10s
* const connection = await dialer.dial(ma, {
* signal: AbortSignal.timeout(10_000)
* })
*
* // use connection...
* ```
*/

import { ConnectionFailedError } from '@libp2p/interface'
import { multiaddr } from '@multiformats/multiaddr'
import delay from 'delay'
import map from 'it-map'
import { pushable } from 'it-pushable'
import type { MemoryTransportComponents } from './index.js'
import type { MultiaddrConnection, PeerId } from '@libp2p/interface'
import type { Uint8ArrayList } from 'uint8arraylist'

export const connections = new Map<string, MemoryConnection>()

interface MemoryConnectionHandler {
(maConn: MultiaddrConnection): void
}

interface MemoryConnectionInit {
onConnection: MemoryConnectionHandler
address: string
}

export class MemoryConnection {
private readonly components: MemoryTransportComponents
private readonly init: MemoryConnectionInit
private readonly connections: Set<MultiaddrConnection>
private latency: number

constructor (components: MemoryTransportComponents, init: MemoryConnectionInit) {
this.components = components
this.init = init
this.connections = new Set()
this.latency = 0
}

async dial (dialingPeerId: PeerId): Promise<MultiaddrConnection> {
const dialerPushable = pushable<Uint8Array | Uint8ArrayList>()
const listenerPushable = pushable<Uint8Array | Uint8ArrayList>()
const self = this

const dialer: MultiaddrConnection = {
source: (async function * () {
yield * map(listenerPushable, async buf => {
await delay(self.latency)
return buf
})
})(),
sink: async (source) => {
for await (const buf of source) {
dialerPushable.push(buf)
}
},
close: async () => {
dialerPushable.end()
this.connections.delete(dialer)
dialer.timeline.close = Date.now()

listenerPushable.end()
this.connections.delete(listener)
listener.timeline.close = Date.now()
},
abort: (err) => {
dialerPushable.end(err)
this.connections.delete(dialer)
dialer.timeline.close = Date.now()

listenerPushable.end(err)
this.connections.delete(listener)
listener.timeline.close = Date.now()
},
timeline: {
open: Date.now()
},
remoteAddr: multiaddr(`${this.init.address}/p2p/${this.components.peerId}`),
log: this.components.logger.forComponent(`libp2p:memory:outgoing:${1}`)
}

const listener: MultiaddrConnection = {
source: (async function * () {
yield * map(dialerPushable, async buf => {
await delay(self.latency)
return buf
})
})(),
sink: async (source) => {
for await (const buf of source) {
listenerPushable.push(buf)
}
},
close: async () => {
listenerPushable.end()
this.connections.delete(listener)
listener.timeline.close = Date.now()

dialerPushable.end()
this.connections.delete(dialer)
dialer.timeline.close = Date.now()

Check warning on line 139 in packages/transport-memory/src/connections.ts

View check run for this annotation

Codecov / codecov/patch

packages/transport-memory/src/connections.ts#L133-L139

Added lines #L133 - L139 were not covered by tests
},
abort: (err) => {
listenerPushable.end(err)
this.connections.delete(listener)
listener.timeline.close = Date.now()

dialerPushable.end(err)
this.connections.delete(dialer)
dialer.timeline.close = Date.now()
},
timeline: {
open: Date.now()
},
remoteAddr: multiaddr(`${this.init.address}-outgoing/p2p/${dialingPeerId}`),
log: this.components.logger.forComponent(`libp2p:memory:outgoing:${1}`)
}

this.connections.add(dialer)
this.connections.add(listener)

await delay(this.latency)

this.init.onConnection(listener)

return dialer
}

close (): void {
[...this.connections].forEach(maConn => {
maConn.abort(new ConnectionFailedError('Memory Connection closed'))
})
}

setLatency (ms: number): void {
this.latency = ms
}
}
Loading
Loading