Skip to content

Commit 3345f28

Browse files
MarcoPolomaschad
andauthored
feat(@libp2p/protocol-perf): Implement perf protocol (#1604)
Co-authored-by: Marco Munizaga <[email protected]> Co-authored-by: Chad Nehemiah <[email protected]>
1 parent a1fbb7e commit 3345f28

File tree

10 files changed

+520
-0
lines changed

10 files changed

+520
-0
lines changed

packages/protocol-perf/LICENSE

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
This project is dual licensed under MIT and Apache-2.0.
2+
3+
MIT: https://www.opensource.org/licenses/mit
4+
Apache-2.0: https://www.apache.org/licenses/license-2.0

packages/protocol-perf/LICENSE-APACHE

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
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
2+
3+
http://www.apache.org/licenses/LICENSE-2.0
4+
5+
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.

packages/protocol-perf/LICENSE-MIT

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
The MIT License (MIT)
2+
3+
Permission is hereby granted, free of charge, to any person obtaining a copy
4+
of this software and associated documentation files (the "Software"), to deal
5+
in the Software without restriction, including without limitation the rights
6+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7+
copies of the Software, and to permit persons to whom the Software is
8+
furnished to do so, subject to the following conditions:
9+
10+
The above copyright notice and this permission notice shall be included in
11+
all copies or substantial portions of the Software.
12+
13+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19+
THE SOFTWARE.

packages/protocol-perf/README.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# @libp2p/perf
2+
3+
[![libp2p.io](https://img.shields.io/badge/project-libp2p-yellow.svg?style=flat-square)](http://libp2p.io/)
4+
[![Discuss](https://img.shields.io/discourse/https/discuss.libp2p.io/posts.svg?style=flat-square)](https://discuss.libp2p.io)
5+
[![codecov](https://img.shields.io/codecov/c/github/libp2p/js-libp2p.svg?style=flat-square)](https://codecov.io/gh/libp2p/js-libp2p)
6+
[![CI](https://img.shields.io/github/actions/workflow/status/libp2p/js-libp2p/main.yml?branch=master\&style=flat-square)](https://github.com/libp2p/js-libp2p/actions/workflows/main.yml?query=branch%3Amaster)
7+
8+
> Implementation of the [Perf Protocol](https://github.com/libp2p/specs/blob/master/perf/perf.md)
9+
10+
## API Docs
11+
12+
- <https://libp2p.github.io/js-libp2p/modules/_libp2p_perf.html>
13+
14+
15+
## License
16+
17+
Licensed under either of
18+
19+
- Apache 2.0, ([LICENSE-APACHE](LICENSE-APACHE) / <http://www.apache.org/licenses/LICENSE-2.0>)
20+
- MIT ([LICENSE-MIT](LICENSE-MIT) / <http://opensource.org/licenses/MIT>)
21+
22+
## Contribution
23+
24+
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.

packages/protocol-perf/package.json

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
{
2+
"name": "@libp2p/perf",
3+
"version": "1.0.0",
4+
"description": "Implementation of Perf Protocol",
5+
"license": "Apache-2.0 OR MIT",
6+
"homepage": "https://github.com/libp2p/js-libp2p/tree/master/packages/perf#readme",
7+
"repository": {
8+
"type": "git",
9+
"url": "git+https://github.com/libp2p/js-libp2p.git"
10+
},
11+
"bugs": {
12+
"url": "https://github.com/libp2p/js-libp2p/issues"
13+
},
14+
"type": "module",
15+
"author": "@maschad / @marcopolo",
16+
"files": [
17+
"src",
18+
"dist",
19+
"!dist/test",
20+
"!**/*.tsbuildinfo"
21+
],
22+
"exports": {
23+
".": {
24+
"types": "./dist/src/index.d.ts",
25+
"import": "./dist/src/index.js"
26+
}
27+
},
28+
"eslintConfig": {
29+
"extends": "ipfs",
30+
"parserOptions": {
31+
"sourceType": "module"
32+
}
33+
},
34+
"scripts": {
35+
"start": "node dist/src/main.js",
36+
"build": "aegir build",
37+
"test": "aegir test",
38+
"clean": "aegir clean",
39+
"lint": "aegir lint",
40+
"test:chrome": "aegir test -t browser --cov",
41+
"test:chrome-webworker": "aegir test -t webworker",
42+
"test:firefox": "aegir test -t browser -- --browser firefox",
43+
"test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
44+
"test:node": "aegir test -t node --cov",
45+
"dep-check": "aegir dep-check",
46+
"renderResults": "node dist/src/renderResults.js"
47+
},
48+
"dependencies": {
49+
"@chainsafe/libp2p-yamux": "^5.0.0",
50+
"@libp2p/crypto": "^2.0.0",
51+
"@libp2p/interface": "^0.1.0",
52+
"@libp2p/interface-compliance-tests": "^4.0.0",
53+
"@libp2p/interface-internal": "^0.1.0",
54+
"@libp2p/interfaces": "3.3.2",
55+
"@libp2p/logger": "^3.0.0",
56+
"@libp2p/peer-id-factory": "3.0.0",
57+
"@libp2p/tcp": "^8.0.0",
58+
"@multiformats/multiaddr": "^12.1.5",
59+
"libp2p": "^0.46.1",
60+
"p-wait-for": "^5.0.2",
61+
"uint8arrays": "^4.0.6",
62+
"yargs": "^17.7.2"
63+
},
64+
"devDependencies": {
65+
"aegir": "^40.0.8"
66+
}
67+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
export const PROTOCOL_NAME = '/perf/1.0.0'
2+
export const WRITE_BLOCK_SIZE = BigInt(64 << 10)

packages/protocol-perf/src/index.ts

Lines changed: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
1+
/**
2+
* @packageDocumentation
3+
*
4+
* The `performanceService` implements the [perf protocol](https://github.com/libp2p/specs/blob/master/perf/perf.md), which is used to measure performance within and across libp2p implementations
5+
* addresses.
6+
*
7+
* @example
8+
*
9+
* ```typescript
10+
* import { createLibp2p } from 'libp2p'
11+
* import { perfService } from '@libp2p/perf'
12+
*
13+
* const node = await createLibp2p({
14+
* service: [
15+
* perfService()
16+
* ]
17+
* })
18+
* ```
19+
*
20+
* The `measurePerformance` function can be used to measure the latency and throughput of a connection.
21+
* server. This will not work in browsers.
22+
*
23+
* @example
24+
*
25+
* ```typescript
26+
* import { createLibp2p } from 'libp2p'
27+
* import { perfService } from 'libp2p/perf'
28+
*
29+
* const node = await createLibp2p({
30+
* services: [
31+
* perf: perfService()
32+
* ]
33+
* })
34+
*
35+
* const connection = await node.dial(multiaddr(multiaddrAddress))
36+
*
37+
* const startTime = Date.now()
38+
*
39+
* await node.services.perf.measurePerformance(startTime, connection, BigInt(uploadBytes), BigInt(downloadBytes))
40+
*
41+
* ```
42+
*/
43+
44+
import { logger } from '@libp2p/logger'
45+
import { PROTOCOL_NAME, WRITE_BLOCK_SIZE } from './constants.js'
46+
import type { Connection } from '@libp2p/interface/connection'
47+
import type { Startable } from '@libp2p/interface/startable'
48+
import type { ConnectionManager } from '@libp2p/interface-internal/connection-manager'
49+
import type { IncomingStreamData, Registrar } from '@libp2p/interface-internal/registrar'
50+
import type { AbortOptions } from '@libp2p/interfaces'
51+
52+
const log = logger('libp2p:perf')
53+
54+
export const defaultInit: PerfServiceInit = {
55+
protocolName: '/perf/1.0.0',
56+
writeBlockSize: BigInt(64 << 10)
57+
}
58+
59+
export interface PerfService {
60+
measurePerformance: (startTime: number, connection: Connection, sendBytes: bigint, recvBytes: bigint, options?: AbortOptions) => Promise<number>
61+
}
62+
63+
export interface PerfServiceInit {
64+
protocolName?: string
65+
maxInboundStreams?: number
66+
maxOutboundStreams?: number
67+
timeout?: number
68+
writeBlockSize?: bigint
69+
}
70+
71+
export interface PerfServiceComponents {
72+
registrar: Registrar
73+
connectionManager: ConnectionManager
74+
}
75+
76+
class DefaultPerfService implements Startable, PerfService {
77+
public readonly protocol: string
78+
private readonly components: PerfServiceComponents
79+
private started: boolean
80+
private readonly databuf: ArrayBuffer
81+
private readonly writeBlockSize: bigint
82+
83+
constructor (components: PerfServiceComponents, init: PerfServiceInit) {
84+
this.components = components
85+
this.started = false
86+
this.protocol = init.protocolName ?? PROTOCOL_NAME
87+
this.writeBlockSize = init.writeBlockSize ?? WRITE_BLOCK_SIZE
88+
this.databuf = new ArrayBuffer(Number(init.writeBlockSize))
89+
}
90+
91+
async start (): Promise<void> {
92+
await this.components.registrar.handle(this.protocol, (data: IncomingStreamData) => {
93+
void this.handleMessage(data).catch((err) => {
94+
log.error('error handling perf protocol message', err)
95+
})
96+
})
97+
this.started = true
98+
}
99+
100+
async stop (): Promise<void> {
101+
await this.components.registrar.unhandle(this.protocol)
102+
this.started = false
103+
}
104+
105+
isStarted (): boolean {
106+
return this.started
107+
}
108+
109+
async handleMessage (data: IncomingStreamData): Promise<void> {
110+
const { stream } = data
111+
112+
const writeBlockSize = this.writeBlockSize
113+
114+
let bytesToSendBack: bigint | null = null
115+
116+
for await (const buf of stream.source) {
117+
if (bytesToSendBack === null) {
118+
bytesToSendBack = BigInt(buf.getBigUint64(0, false))
119+
}
120+
// Ingest all the bufs and wait for the read side to close
121+
}
122+
123+
const uint8Buf = new Uint8Array(this.databuf)
124+
125+
if (bytesToSendBack === null) {
126+
throw new Error('bytesToSendBack was not set')
127+
}
128+
129+
await stream.sink(async function * () {
130+
while (bytesToSendBack > 0n) {
131+
let toSend: bigint = writeBlockSize
132+
if (toSend > bytesToSendBack) {
133+
toSend = bytesToSendBack
134+
}
135+
bytesToSendBack = bytesToSendBack - toSend
136+
yield uint8Buf.subarray(0, Number(toSend))
137+
}
138+
}())
139+
}
140+
141+
async measurePerformance (startTime: number, connection: Connection, sendBytes: bigint, recvBytes: bigint, options: AbortOptions = {}): Promise<number> {
142+
log('opening stream on protocol %s to %p', this.protocol, connection.remotePeer)
143+
144+
const uint8Buf = new Uint8Array(this.databuf)
145+
146+
const writeBlockSize = this.writeBlockSize
147+
148+
const stream = await connection.newStream([this.protocol])
149+
150+
// Convert sendBytes to uint64 big endian buffer
151+
const view = new DataView(this.databuf)
152+
view.setBigInt64(0, recvBytes, false)
153+
154+
log('sending %i bytes to %p', sendBytes, connection.remotePeer)
155+
try {
156+
await stream.sink((async function * () {
157+
// Send the number of bytes to receive
158+
yield uint8Buf.subarray(0, 8)
159+
// Send the number of bytes to send
160+
while (sendBytes > 0n) {
161+
let toSend: bigint = writeBlockSize
162+
if (toSend > sendBytes) {
163+
toSend = sendBytes
164+
}
165+
sendBytes = sendBytes - toSend
166+
yield uint8Buf.subarray(0, Number(toSend))
167+
}
168+
})())
169+
170+
// Read the received bytes
171+
let actualRecvdBytes = BigInt(0)
172+
for await (const buf of stream.source) {
173+
actualRecvdBytes += BigInt(buf.length)
174+
}
175+
176+
if (actualRecvdBytes !== recvBytes) {
177+
throw new Error(`Expected to receive ${recvBytes} bytes, but received ${actualRecvdBytes}`)
178+
}
179+
} catch (err) {
180+
log('error sending %i bytes to %p: %s', sendBytes, connection.remotePeer, err)
181+
throw err
182+
} finally {
183+
log('performed %s to %p', this.protocol, connection.remotePeer)
184+
await stream.close()
185+
}
186+
187+
// Return the latency
188+
return Date.now() - startTime
189+
}
190+
}
191+
192+
export function perfService (init: PerfServiceInit = {}): (components: PerfServiceComponents) => PerfService {
193+
return (components) => new DefaultPerfService(components, init)
194+
}

0 commit comments

Comments
 (0)