From 8ba49c5655eb6eabfed2138abbae456160a0b889 Mon Sep 17 00:00:00 2001 From: Marco Munizaga Date: Thu, 10 Aug 2023 19:16:34 -0700 Subject: [PATCH] feat(@libp2p/protocol-perf): Implement perf protocol (#1604) Co-authored-by: Marco Munizaga Co-authored-by: Chad Nehemiah --- packages/protocol-perf/LICENSE | 4 + packages/protocol-perf/LICENSE-APACHE | 5 + packages/protocol-perf/LICENSE-MIT | 19 +++ packages/protocol-perf/README.md | 24 +++ packages/protocol-perf/package.json | 67 ++++++++ packages/protocol-perf/src/constants.ts | 2 + packages/protocol-perf/src/index.ts | 194 ++++++++++++++++++++++ packages/protocol-perf/src/main.ts | 130 +++++++++++++++ packages/protocol-perf/test/index.spec.ts | 60 +++++++ packages/protocol-perf/tsconfig.json | 15 ++ 10 files changed, 520 insertions(+) create mode 100644 packages/protocol-perf/LICENSE create mode 100644 packages/protocol-perf/LICENSE-APACHE create mode 100644 packages/protocol-perf/LICENSE-MIT create mode 100644 packages/protocol-perf/README.md create mode 100644 packages/protocol-perf/package.json create mode 100644 packages/protocol-perf/src/constants.ts create mode 100644 packages/protocol-perf/src/index.ts create mode 100644 packages/protocol-perf/src/main.ts create mode 100644 packages/protocol-perf/test/index.spec.ts create mode 100644 packages/protocol-perf/tsconfig.json diff --git a/packages/protocol-perf/LICENSE b/packages/protocol-perf/LICENSE new file mode 100644 index 0000000000..20ce483c86 --- /dev/null +++ b/packages/protocol-perf/LICENSE @@ -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 diff --git a/packages/protocol-perf/LICENSE-APACHE b/packages/protocol-perf/LICENSE-APACHE new file mode 100644 index 0000000000..14478a3b60 --- /dev/null +++ b/packages/protocol-perf/LICENSE-APACHE @@ -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. diff --git a/packages/protocol-perf/LICENSE-MIT b/packages/protocol-perf/LICENSE-MIT new file mode 100644 index 0000000000..72dc60d84b --- /dev/null +++ b/packages/protocol-perf/LICENSE-MIT @@ -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. diff --git a/packages/protocol-perf/README.md b/packages/protocol-perf/README.md new file mode 100644 index 0000000000..f017c3df69 --- /dev/null +++ b/packages/protocol-perf/README.md @@ -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 + +- + + +## License + +Licensed under either of + +- Apache 2.0, ([LICENSE-APACHE](LICENSE-APACHE) / ) +- MIT ([LICENSE-MIT](LICENSE-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. diff --git a/packages/protocol-perf/package.json b/packages/protocol-perf/package.json new file mode 100644 index 0000000000..d005e71690 --- /dev/null +++ b/packages/protocol-perf/package.json @@ -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" + } +} diff --git a/packages/protocol-perf/src/constants.ts b/packages/protocol-perf/src/constants.ts new file mode 100644 index 0000000000..a2e514d6f8 --- /dev/null +++ b/packages/protocol-perf/src/constants.ts @@ -0,0 +1,2 @@ +export const PROTOCOL_NAME = '/perf/1.0.0' +export const WRITE_BLOCK_SIZE = BigInt(64 << 10) diff --git a/packages/protocol-perf/src/index.ts b/packages/protocol-perf/src/index.ts new file mode 100644 index 0000000000..15713cd6ec --- /dev/null +++ b/packages/protocol-perf/src/index.ts @@ -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 +} + +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 { + 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 { + await this.components.registrar.unhandle(this.protocol) + this.started = false + } + + isStarted (): boolean { + return this.started + } + + async handleMessage (data: IncomingStreamData): Promise { + 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 { + 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) +} diff --git a/packages/protocol-perf/src/main.ts b/packages/protocol-perf/src/main.ts new file mode 100644 index 0000000000..33c96e6a92 --- /dev/null +++ b/packages/protocol-perf/src/main.ts @@ -0,0 +1,130 @@ +import { yamux } from '@chainsafe/libp2p-yamux' +import { unmarshalPrivateKey } from '@libp2p/crypto/keys' +import { createFromPrivKey } from '@libp2p/peer-id-factory' +import { tcp } from '@libp2p/tcp' +import { multiaddr } from '@multiformats/multiaddr' +import { createLibp2p } from 'libp2p' +import { plaintext } from 'libp2p/insecure' +import pWaitFor from 'p-wait-for' +import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string' +import yargs from 'yargs' +import { hideBin } from 'yargs/helpers' +import { defaultInit, perfService } from '../src/index.js' +import type { Connection } from '@libp2p/interface/connection' + +const argv = yargs(hideBin(process.argv)) + .options({ + 'run-server': { + type: 'boolean', + demandOption: true, + default: false, + description: 'Whether to run as a server' + }, + 'server-address': { + type: 'string', + demandOption: false, + description: 'Server IP address', + default: '' + }, + transport: { + type: 'string', + demandOption: false, + description: 'Transport to use', + default: 'tcp' + }, + 'upload-bytes': { + type: 'number', + demandOption: false, + description: 'Number of bytes to upload', + default: 0 + }, + 'download-bytes': { + type: 'number', + demandOption: false, + description: 'Number of bytes to download', + default: 0 + } + }) + .command('help', 'Print usage information', yargs.help) + .parseSync() + +export async function main (runServer: boolean, serverIpAddress: string, transport: string, uploadBytes: number, downloadBytes: number): Promise { + const listenAddrs: string[] = [] + + const { host, port } = splitHostPort(serverIpAddress) + // #TODO: right now we only support tcp + const tcpMultiaddr = multiaddr(`/ip4/${host}/tcp/${port}`) + + const config = { + transports: [tcp()], + streamMuxers: [yamux()], + connectionEncryption: [ + plaintext() + ], + services: { + perf: perfService(defaultInit) + } + } + + const testPrivKey = 'CAASpgkwggSiAgEAAoIBAQC2SKo/HMFZeBml1AF3XijzrxrfQXdJzjePBZAbdxqKR1Mc6juRHXij6HXYPjlAk01BhF1S3Ll4Lwi0cAHhggf457sMg55UWyeGKeUv0ucgvCpBwlR5cQ020i0MgzjPWOLWq1rtvSbNcAi2ZEVn6+Q2EcHo3wUvWRtLeKz+DZSZfw2PEDC+DGPJPl7f8g7zl56YymmmzH9liZLNrzg/qidokUv5u1pdGrcpLuPNeTODk0cqKB+OUbuKj9GShYECCEjaybJDl9276oalL9ghBtSeEv20kugatTvYy590wFlJkkvyl+nPxIH0EEYMKK9XRWlu9XYnoSfboiwcv8M3SlsjAgMBAAECggE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0OCdpdISqk0F0Pxby22DFOKXZEpiyI9XYP1C8wPiJsShGm2yEwBPWXnrrZNWczaVuCbXHrZkWQogBDG3HGXNdU4MAWCyiYlyinIBpPpoAJZSzpGLmWbMWh28+RJS6AQX6KHrK1o2uw==' + const encoded = uint8ArrayFromString(testPrivKey, 'base64pad') + const privateKey = await unmarshalPrivateKey(encoded) + const peerId = await createFromPrivKey(privateKey) + const tcpMultiaddrAddress = `${tcpMultiaddr.toString()}/p2p/${peerId.toString()}` + + if (runServer) { + listenAddrs.push(tcpMultiaddrAddress) + + Object.assign(config, { + peerId, + addresses: { + listen: listenAddrs + } + }) + } + + const node = await createLibp2p(config) + + await node.start() + + const startTime = Date.now() + + let connection: any = null + + if (runServer) { + node.addEventListener('connection:open', (eventInfo) => { + connection = eventInfo.detail + }) + } else { + connection = await node.dial(multiaddr(tcpMultiaddrAddress)) + } + + await pWaitFor(() => connection != null) + + const duration = await node.services.perf.measurePerformance(startTime, connection as Connection, BigInt(uploadBytes), BigInt(downloadBytes)) + + await node.stop() + + // eslint-disable-next-line no-console + console.log('latency: ' + JSON.stringify({ latency: duration })) +} + +function splitHostPort (address: string): { host: string, port?: string } { + try { + const parts = address.split(':') + const host = parts[0] + const port = parts[1] + return { + host, + port + } + } catch (error) { + throw Error('Invalid server address') + } +} + +main(argv['run-server'], argv['server-address'], argv.transport, argv['upload-bytes'], argv['download-bytes']).catch((err) => { + // eslint-disable-next-line no-console + console.error(err) + process.exit(1) +}) diff --git a/packages/protocol-perf/test/index.spec.ts b/packages/protocol-perf/test/index.spec.ts new file mode 100644 index 0000000000..83fd6c310f --- /dev/null +++ b/packages/protocol-perf/test/index.spec.ts @@ -0,0 +1,60 @@ +/* eslint-env mocha */ + +import { EventEmitter } from '@libp2p/interface/events' +import { start, stop } from '@libp2p/interface/startable' +import { connectionPair, mockRegistrar, type MockNetworkComponents, mockConnectionManager } from '@libp2p/interface-compliance-tests/mocks' +import { createEd25519PeerId } from '@libp2p/peer-id-factory' +import { expect } from 'aegir/chai' +import { defaultInit, perfService } from '../src/index.js' + +export async function createComponents (): Promise { + const components: any = { + peerId: await createEd25519PeerId(), + registrar: mockRegistrar(), + events: new EventEmitter() + } + + components.connectionManager = mockConnectionManager(components) + + return components as MockNetworkComponents +} + +describe('perf', () => { + let localComponents: MockNetworkComponents + let remoteComponents: MockNetworkComponents + + beforeEach(async () => { + localComponents = await createComponents() + remoteComponents = await createComponents() + + await Promise.all([ + start(localComponents), + start(remoteComponents) + ]) + }) + + afterEach(async () => { + await Promise.all([ + stop(localComponents), + stop(remoteComponents) + ]) + }) + + it('should run perf', async () => { + const client = perfService(defaultInit)(localComponents) + const server = perfService(defaultInit)(remoteComponents) + + await start(client) + await start(server) + + // simulate connection between nodes + const [localToRemote, remoteToLocal] = connectionPair(localComponents, remoteComponents) + localComponents.events.safeDispatchEvent('connection:open', { detail: localToRemote }) + remoteComponents.events.safeDispatchEvent('connection:open', { detail: remoteToLocal }) + + const startTime = Date.now() + + // Run Perf + await expect(client.measurePerformance(startTime, localToRemote, 1024n, 1024n)).to.eventually.be.fulfilled() + }) +}) diff --git a/packages/protocol-perf/tsconfig.json b/packages/protocol-perf/tsconfig.json new file mode 100644 index 0000000000..2a0bd0091c --- /dev/null +++ b/packages/protocol-perf/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "aegir/src/config/tsconfig.aegir.json", + "compilerOptions": { + "outDir": "dist" + }, + "include": [ + "src", + "test" + ], + "references": [ + { + "path": "../libp2p" + } + ] +}