Skip to content

Commit

Permalink
feat(@libp2p/protocol-perf): Implement perf protocol (#1604)
Browse files Browse the repository at this point in the history
Co-authored-by: Marco Munizaga <[email protected]>
Co-authored-by: Chad Nehemiah <[email protected]>
  • Loading branch information
MarcoPolo and maschad authored Aug 11, 2023
1 parent a1fbb7e commit 3345f28
Show file tree
Hide file tree
Showing 10 changed files with 520 additions and 0 deletions.
4 changes: 4 additions & 0 deletions packages/protocol-perf/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/protocol-perf/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/protocol-perf/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.
24 changes: 24 additions & 0 deletions packages/protocol-perf/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# @libp2p/perf

[![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=master\&style=flat-square)](https://github.com/libp2p/js-libp2p/actions/workflows/main.yml?query=branch%3Amaster)

> Implementation of the [Perf Protocol](https://github.com/libp2p/specs/blob/master/perf/perf.md)
## API Docs

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


## License

Licensed under either of

- Apache 2.0, ([LICENSE-APACHE](LICENSE-APACHE) / <http://www.apache.org/licenses/LICENSE-2.0>)
- MIT ([LICENSE-MIT](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.
67 changes: 67 additions & 0 deletions packages/protocol-perf/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
{
"name": "@libp2p/perf",
"version": "1.0.0",
"description": "Implementation of Perf Protocol",
"license": "Apache-2.0 OR MIT",
"homepage": "https://github.com/libp2p/js-libp2p/tree/master/packages/perf#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/libp2p/js-libp2p.git"
},
"bugs": {
"url": "https://github.com/libp2p/js-libp2p/issues"
},
"type": "module",
"author": "@maschad / @marcopolo",
"files": [
"src",
"dist",
"!dist/test",
"!**/*.tsbuildinfo"
],
"exports": {
".": {
"types": "./dist/src/index.d.ts",
"import": "./dist/src/index.js"
}
},
"eslintConfig": {
"extends": "ipfs",
"parserOptions": {
"sourceType": "module"
}
},
"scripts": {
"start": "node dist/src/main.js",
"build": "aegir build",
"test": "aegir test",
"clean": "aegir clean",
"lint": "aegir lint",
"test:chrome": "aegir test -t browser --cov",
"test:chrome-webworker": "aegir test -t webworker",
"test:firefox": "aegir test -t browser -- --browser firefox",
"test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
"test:node": "aegir test -t node --cov",
"dep-check": "aegir dep-check",
"renderResults": "node dist/src/renderResults.js"
},
"dependencies": {
"@chainsafe/libp2p-yamux": "^5.0.0",
"@libp2p/crypto": "^2.0.0",
"@libp2p/interface": "^0.1.0",
"@libp2p/interface-compliance-tests": "^4.0.0",
"@libp2p/interface-internal": "^0.1.0",
"@libp2p/interfaces": "3.3.2",
"@libp2p/logger": "^3.0.0",
"@libp2p/peer-id-factory": "3.0.0",
"@libp2p/tcp": "^8.0.0",
"@multiformats/multiaddr": "^12.1.5",
"libp2p": "^0.46.1",
"p-wait-for": "^5.0.2",
"uint8arrays": "^4.0.6",
"yargs": "^17.7.2"
},
"devDependencies": {
"aegir": "^40.0.8"
}
}
2 changes: 2 additions & 0 deletions packages/protocol-perf/src/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const PROTOCOL_NAME = '/perf/1.0.0'
export const WRITE_BLOCK_SIZE = BigInt(64 << 10)
194 changes: 194 additions & 0 deletions packages/protocol-perf/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
/**
* @packageDocumentation
*
* 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
* addresses.
*
* @example
*
* ```typescript
* import { createLibp2p } from 'libp2p'
* import { perfService } from '@libp2p/perf'
*
* const node = await createLibp2p({
* service: [
* perfService()
* ]
* })
* ```
*
* The `measurePerformance` function can be used to measure the latency and throughput of a connection.
* server. This will not work in browsers.
*
* @example
*
* ```typescript
* import { createLibp2p } from 'libp2p'
* import { perfService } from 'libp2p/perf'
*
* const node = await createLibp2p({
* services: [
* perf: perfService()
* ]
* })
*
* const connection = await node.dial(multiaddr(multiaddrAddress))
*
* const startTime = Date.now()
*
* await node.services.perf.measurePerformance(startTime, connection, BigInt(uploadBytes), BigInt(downloadBytes))
*
* ```
*/

import { logger } from '@libp2p/logger'
import { PROTOCOL_NAME, WRITE_BLOCK_SIZE } from './constants.js'
import type { Connection } from '@libp2p/interface/connection'
import type { Startable } from '@libp2p/interface/startable'
import type { ConnectionManager } from '@libp2p/interface-internal/connection-manager'
import type { IncomingStreamData, Registrar } from '@libp2p/interface-internal/registrar'
import type { AbortOptions } from '@libp2p/interfaces'

const log = logger('libp2p:perf')

export const defaultInit: PerfServiceInit = {
protocolName: '/perf/1.0.0',
writeBlockSize: BigInt(64 << 10)
}

export interface PerfService {
measurePerformance: (startTime: number, connection: Connection, sendBytes: bigint, recvBytes: bigint, options?: AbortOptions) => Promise<number>
}

export interface PerfServiceInit {
protocolName?: string
maxInboundStreams?: number
maxOutboundStreams?: number
timeout?: number
writeBlockSize?: bigint
}

export interface PerfServiceComponents {
registrar: Registrar
connectionManager: ConnectionManager
}

class DefaultPerfService implements Startable, PerfService {
public readonly protocol: string
private readonly components: PerfServiceComponents
private started: boolean
private readonly databuf: ArrayBuffer
private readonly writeBlockSize: bigint

constructor (components: PerfServiceComponents, init: PerfServiceInit) {
this.components = components
this.started = false
this.protocol = init.protocolName ?? PROTOCOL_NAME
this.writeBlockSize = init.writeBlockSize ?? WRITE_BLOCK_SIZE
this.databuf = new ArrayBuffer(Number(init.writeBlockSize))
}

async start (): Promise<void> {
await this.components.registrar.handle(this.protocol, (data: IncomingStreamData) => {
void this.handleMessage(data).catch((err) => {
log.error('error handling perf protocol message', err)
})
})
this.started = true
}

async stop (): Promise<void> {
await this.components.registrar.unhandle(this.protocol)
this.started = false
}

isStarted (): boolean {
return this.started
}

async handleMessage (data: IncomingStreamData): Promise<void> {
const { stream } = data

const writeBlockSize = this.writeBlockSize

let bytesToSendBack: bigint | null = null

for await (const buf of stream.source) {
if (bytesToSendBack === null) {
bytesToSendBack = BigInt(buf.getBigUint64(0, false))
}
// Ingest all the bufs and wait for the read side to close
}

const uint8Buf = new Uint8Array(this.databuf)

if (bytesToSendBack === null) {
throw new Error('bytesToSendBack was not set')
}

await stream.sink(async function * () {
while (bytesToSendBack > 0n) {
let toSend: bigint = writeBlockSize
if (toSend > bytesToSendBack) {
toSend = bytesToSendBack
}
bytesToSendBack = bytesToSendBack - toSend
yield uint8Buf.subarray(0, Number(toSend))
}
}())
}

async measurePerformance (startTime: number, connection: Connection, sendBytes: bigint, recvBytes: bigint, options: AbortOptions = {}): Promise<number> {
log('opening stream on protocol %s to %p', this.protocol, connection.remotePeer)

const uint8Buf = new Uint8Array(this.databuf)

const writeBlockSize = this.writeBlockSize

const stream = await connection.newStream([this.protocol])

// Convert sendBytes to uint64 big endian buffer
const view = new DataView(this.databuf)
view.setBigInt64(0, recvBytes, false)

log('sending %i bytes to %p', sendBytes, connection.remotePeer)
try {
await stream.sink((async function * () {
// Send the number of bytes to receive
yield uint8Buf.subarray(0, 8)
// Send the number of bytes to send
while (sendBytes > 0n) {
let toSend: bigint = writeBlockSize
if (toSend > sendBytes) {
toSend = sendBytes
}
sendBytes = sendBytes - toSend
yield uint8Buf.subarray(0, Number(toSend))
}
})())

// Read the received bytes
let actualRecvdBytes = BigInt(0)
for await (const buf of stream.source) {
actualRecvdBytes += BigInt(buf.length)
}

if (actualRecvdBytes !== recvBytes) {
throw new Error(`Expected to receive ${recvBytes} bytes, but received ${actualRecvdBytes}`)
}
} catch (err) {
log('error sending %i bytes to %p: %s', sendBytes, connection.remotePeer, err)
throw err
} finally {
log('performed %s to %p', this.protocol, connection.remotePeer)
await stream.close()
}

// Return the latency
return Date.now() - startTime
}
}

export function perfService (init: PerfServiceInit = {}): (components: PerfServiceComponents) => PerfService {
return (components) => new DefaultPerfService(components, init)
}
Loading

0 comments on commit 3345f28

Please sign in to comment.