From 27bab5c448e918da12a87f81f4b99b01c4a894e0 Mon Sep 17 00:00:00 2001 From: achingbrain Date: Thu, 11 May 2023 17:53:07 +0100 Subject: [PATCH 1/2] fix: remove protobuf-ts and split code into two folders This module uses both protobuf-ts and protons for protobuf operations. To reduce the bundle size, just use protons for both. Splits the two transports into `private-to-private` and `private-to-public` folders to better tell what code is used by what. Module exports are unaffected so this is a non-breaking change. --- package.json | 5 +- proto_ts/message.ts | 106 ------------------ src/index.ts | 6 +- src/{ => pb}/message.proto | 6 +- src/pb/message.ts | 92 +++++++++++++++ .../handler.ts | 18 +-- .../listener.ts | 0 .../pb/message.proto} | 0 .../pb/message.ts} | 2 +- .../transport.ts | 0 .../util.ts | 13 +-- src/{ => private-to-public}/options.ts | 0 src/{ => private-to-public}/sdp.ts | 2 +- src/{ => private-to-public}/transport.ts | 10 +- src/private-to-public/util.ts | 3 + src/stream.ts | 36 +++--- src/util.ts | 8 +- test/peer.browser.spec.ts | 6 +- test/sdp.spec.ts | 2 +- test/stream.browser.spec.ts | 16 +-- test/transport.browser.spec.ts | 2 +- 21 files changed, 158 insertions(+), 175 deletions(-) delete mode 100644 proto_ts/message.ts rename src/{ => pb}/message.proto (91%) create mode 100644 src/pb/message.ts rename src/{peer_transport => private-to-private}/handler.ts (93%) rename src/{peer_transport => private-to-private}/listener.ts (100%) rename src/{peer_transport/pb/index.proto => private-to-private/pb/message.proto} (100%) rename src/{peer_transport/pb/index.ts => private-to-private/pb/message.ts} (97%) rename src/{peer_transport => private-to-private}/transport.ts (100%) rename src/{peer_transport => private-to-private}/util.ts (84%) rename src/{ => private-to-public}/options.ts (100%) rename src/{ => private-to-public}/sdp.ts (98%) rename src/{ => private-to-public}/transport.ts (97%) create mode 100644 src/private-to-public/util.ts diff --git a/package.json b/package.json index c8603a0..ace2e99 100644 --- a/package.json +++ b/package.json @@ -123,8 +123,7 @@ ] }, "scripts": { - "generate:proto": "npx protoc --ts_out proto_ts --proto_path src src/*.proto", - "generate:webrtc-direct": "protons src/peer_transport/pb/index.proto", + "generate": "protons src/private-to-private/pb/message.proto src/pb/message.proto", "build": "aegir build", "test": "aegir test -t browser", "test:chrome": "aegir test -t browser --cov", @@ -148,7 +147,6 @@ "@libp2p/logger": "^2.0.7", "@libp2p/peer-id": "^2.0.3", "@multiformats/multiaddr": "^12.1.2", - "@protobuf-ts/runtime": "^2.9.0", "abortable-iterator": "^5.0.1", "detect-browser": "^5.3.0", "it-length-prefixed": "^9.0.1", @@ -167,7 +165,6 @@ "devDependencies": { "@libp2p/interface-mocks": "^12.0.1", "@libp2p/peer-id-factory": "^2.0.3", - "@protobuf-ts/protoc": "^2.9.0", "@types/sinon": "^10.0.14", "aegir": "^39.0.6", "it-pair": "^2.0.6", diff --git a/proto_ts/message.ts b/proto_ts/message.ts deleted file mode 100644 index 2a96f67..0000000 --- a/proto_ts/message.ts +++ /dev/null @@ -1,106 +0,0 @@ -// @generated by protobuf-ts 2.8.1 -// @generated from protobuf file "message.proto" (package "webrtc.pb", syntax proto2) -// tslint:disable -// @ts-nocheck -import type { BinaryWriteOptions } from "@protobuf-ts/runtime"; -import type { IBinaryWriter } from "@protobuf-ts/runtime"; -import { WireType } from "@protobuf-ts/runtime"; -import type { BinaryReadOptions } from "@protobuf-ts/runtime"; -import type { IBinaryReader } from "@protobuf-ts/runtime"; -import { UnknownFieldHandler } from "@protobuf-ts/runtime"; -import type { PartialMessage } from "@protobuf-ts/runtime"; -import { reflectionMergePartial } from "@protobuf-ts/runtime"; -import { MESSAGE_TYPE } from "@protobuf-ts/runtime"; -import { MessageType } from "@protobuf-ts/runtime"; -/** - * @generated from protobuf message webrtc.pb.Message - */ -export interface Message { - /** - * @generated from protobuf field: optional webrtc.pb.Message.Flag flag = 1; - */ - flag?: Message_Flag; - /** - * @generated from protobuf field: optional bytes message = 2; - */ - message?: Uint8Array; -} -/** - * @generated from protobuf enum webrtc.pb.Message.Flag - */ -export enum Message_Flag { - /** - * The sender will no longer send messages on the stream. - * - * @generated from protobuf enum value: FIN = 0; - */ - FIN = 0, - /** - * The sender will no longer read messages on the stream. Incoming data is - * being discarded on receipt. - * - * @generated from protobuf enum value: STOP_SENDING = 1; - */ - STOP_SENDING = 1, - /** - * The sender abruptly terminates the sending part of the stream. The - * receiver can discard any data that it already received on that stream. - * - * @generated from protobuf enum value: RESET = 2; - */ - RESET = 2 -} -// @generated message type with reflection information, may provide speed optimized methods -class Message$Type extends MessageType { - constructor() { - super("webrtc.pb.Message", [ - { no: 1, name: "flag", kind: "enum", opt: true, T: () => ["webrtc.pb.Message.Flag", Message_Flag] }, - { no: 2, name: "message", kind: "scalar", opt: true, T: 12 /*ScalarType.BYTES*/ } - ]); - } - create(value?: PartialMessage): Message { - const message = {}; - globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this }); - if (value !== undefined) - reflectionMergePartial(this, message, value); - return message; - } - internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: Message): Message { - let message = target ?? this.create(), end = reader.pos + length; - while (reader.pos < end) { - let [fieldNo, wireType] = reader.tag(); - switch (fieldNo) { - case /* optional webrtc.pb.Message.Flag flag */ 1: - message.flag = reader.int32(); - break; - case /* optional bytes message */ 2: - message.message = reader.bytes(); - break; - default: - let u = options.readUnknownField; - if (u === "throw") - throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`); - let d = reader.skip(wireType); - if (u !== false) - (u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d); - } - } - return message; - } - internalBinaryWrite(message: Message, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter { - /* optional webrtc.pb.Message.Flag flag = 1; */ - if (message.flag !== undefined) - writer.tag(1, WireType.Varint).int32(message.flag); - /* optional bytes message = 2; */ - if (message.message !== undefined) - writer.tag(2, WireType.LengthDelimited).bytes(message.message); - let u = options.writeUnknownFields; - if (u !== false) - (u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer); - return writer; - } -} -/** - * @generated MessageType for protobuf message webrtc.pb.Message - */ -export const Message = new Message$Type(); diff --git a/src/index.ts b/src/index.ts index 2814c8b..02cd39e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,6 @@ -import { WebRTCTransport } from './peer_transport/transport.js' -import { WebRTCDirectTransport, type WebRTCDirectTransportComponents } from './transport.js' -import type { WebRTCTransportComponents, WebRTCTransportInit } from './peer_transport/transport.js' +import { WebRTCTransport } from './private-to-private/transport.js' +import { WebRTCDirectTransport, type WebRTCDirectTransportComponents } from './private-to-public/transport.js' +import type { WebRTCTransportComponents, WebRTCTransportInit } from './private-to-private/transport.js' import type { Transport } from '@libp2p/interface-transport' function webRTCDirect (): (components: WebRTCDirectTransportComponents) => Transport { diff --git a/src/message.proto b/src/pb/message.proto similarity index 91% rename from src/message.proto rename to src/pb/message.proto index cbda09f..9301bd8 100644 --- a/src/message.proto +++ b/src/pb/message.proto @@ -1,6 +1,4 @@ -syntax = "proto2"; - -package webrtc.pb; +syntax = "proto3"; message Message { enum Flag { @@ -10,7 +8,7 @@ message Message { // The sender will no longer read messages on the stream. Incoming data is // being discarded on receipt. STOP_SENDING = 1; - + // The sender abruptly terminates the sending part of the stream. The // receiver can discard any data that it already received on that stream. RESET = 2; diff --git a/src/pb/message.ts b/src/pb/message.ts new file mode 100644 index 0000000..a74ca6d --- /dev/null +++ b/src/pb/message.ts @@ -0,0 +1,92 @@ +/* eslint-disable import/export */ +/* eslint-disable complexity */ +/* eslint-disable @typescript-eslint/no-namespace */ +/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */ +/* eslint-disable @typescript-eslint/no-empty-interface */ + +import { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime' +import type { Codec } from 'protons-runtime' +import type { Uint8ArrayList } from 'uint8arraylist' + +export interface Message { + flag?: Message.Flag + message?: Uint8Array +} + +export namespace Message { + export enum Flag { + FIN = 'FIN', + STOP_SENDING = 'STOP_SENDING', + RESET = 'RESET' + } + + enum __FlagValues { + FIN = 0, + STOP_SENDING = 1, + RESET = 2 + } + + export namespace Flag { + export const codec = (): Codec => { + return enumeration(__FlagValues) + } + } + + let _codec: Codec + + export const codec = (): Codec => { + if (_codec == null) { + _codec = message((obj, w, opts = {}) => { + if (opts.lengthDelimited !== false) { + w.fork() + } + + if (obj.flag != null) { + w.uint32(8) + Message.Flag.codec().encode(obj.flag, w) + } + + if (obj.message != null) { + w.uint32(18) + w.bytes(obj.message) + } + + if (opts.lengthDelimited !== false) { + w.ldelim() + } + }, (reader, length) => { + const obj: any = {} + + const end = length == null ? reader.len : reader.pos + length + + while (reader.pos < end) { + const tag = reader.uint32() + + switch (tag >>> 3) { + case 1: + obj.flag = Message.Flag.codec().decode(reader) + break + case 2: + obj.message = reader.bytes() + break + default: + reader.skipType(tag & 7) + break + } + } + + return obj + }) + } + + return _codec + } + + export const encode = (obj: Partial): Uint8Array => { + return encodeMessage(obj, Message.codec()) + } + + export const decode = (buf: Uint8Array | Uint8ArrayList): Message => { + return decodeMessage(buf, Message.codec()) + } +} diff --git a/src/peer_transport/handler.ts b/src/private-to-private/handler.ts similarity index 93% rename from src/peer_transport/handler.ts rename to src/private-to-private/handler.ts index 4952b2f..cf444f7 100644 --- a/src/peer_transport/handler.ts +++ b/src/private-to-private/handler.ts @@ -3,7 +3,7 @@ import { abortableDuplex } from 'abortable-iterator' import { pbStream } from 'it-pb-stream' import pDefer, { type DeferredPromise } from 'p-defer' import { DataChannelMuxerFactory } from '../muxer.js' -import * as pb from './pb/index.js' +import { Message } from './pb/message.js' import { readCandidatesUntilConnected, resolveOnConnected } from './util.js' import type { Stream } from '@libp2p/interface-connection' import type { IncomingStreamData } from '@libp2p/interface-registrar' @@ -17,7 +17,7 @@ export type IncomingStreamOpts = { rtcConfiguration?: RTCConfiguration } & Incom export async function handleIncomingStream ({ rtcConfiguration, stream: rawStream }: IncomingStreamOpts): Promise<{ pc: RTCPeerConnection, muxerFactory: StreamMuxerFactory, remoteAddress: string }> { const signal = AbortSignal.timeout(DEFAULT_TIMEOUT) - const stream = pbStream(abortableDuplex(rawStream, signal)).pb(pb.Message) + const stream = pbStream(abortableDuplex(rawStream, signal)).pb(Message) const pc = new RTCPeerConnection(rtcConfiguration) const muxerFactory = new DataChannelMuxerFactory(pc) @@ -30,7 +30,7 @@ export async function handleIncomingStream ({ rtcConfiguration, stream: rawStrea answerSentPromise.promise.then( () => { stream.write({ - type: pb.Message.Type.ICE_CANDIDATE, + type: Message.Type.ICE_CANDIDATE, data: (candidate != null) ? JSON.stringify(candidate.toJSON()) : '' }) }, @@ -44,7 +44,7 @@ export async function handleIncomingStream ({ rtcConfiguration, stream: rawStrea // read an SDP offer const pbOffer = await stream.read() - if (pbOffer.type !== pb.Message.Type.SDP_OFFER) { + if (pbOffer.type !== Message.Type.SDP_OFFER) { throw new Error(`expected message type SDP_OFFER, received: ${pbOffer.type ?? 'undefined'} `) } const offer = new RTCSessionDescription({ @@ -64,7 +64,7 @@ export async function handleIncomingStream ({ rtcConfiguration, stream: rawStrea throw new Error('Failed to create answer') }) // write the answer to the remote - stream.write({ type: pb.Message.Type.SDP_ANSWER, data: answer.sdp }) + stream.write({ type: Message.Type.SDP_ANSWER, data: answer.sdp }) await pc.setLocalDescription(answer).catch(err => { log.error('could not execute setLocalDescription', err) @@ -89,7 +89,7 @@ export interface ConnectOptions { } export async function initiateConnection ({ rtcConfiguration, signal, stream: rawStream }: ConnectOptions): Promise<{ pc: RTCPeerConnection, muxerFactory: StreamMuxerFactory, remoteAddress: string }> { - const stream = pbStream(abortableDuplex(rawStream, signal)).pb(pb.Message) + const stream = pbStream(abortableDuplex(rawStream, signal)).pb(Message) // setup peer connection const pc = new RTCPeerConnection(rtcConfiguration) const muxerFactory = new DataChannelMuxerFactory(pc) @@ -107,14 +107,14 @@ export async function initiateConnection ({ rtcConfiguration, signal, stream: ra // peer pc.onicecandidate = ({ candidate }) => { stream.write({ - type: pb.Message.Type.ICE_CANDIDATE, + type: Message.Type.ICE_CANDIDATE, data: (candidate != null) ? JSON.stringify(candidate.toJSON()) : '' }) } // create an offer const offerSdp = await pc.createOffer() // write the offer to the stream - stream.write({ type: pb.Message.Type.SDP_OFFER, data: offerSdp.sdp }) + stream.write({ type: Message.Type.SDP_OFFER, data: offerSdp.sdp }) // set offer as local description await pc.setLocalDescription(offerSdp).catch(err => { log.error('could not execute setLocalDescription', err) @@ -123,7 +123,7 @@ export async function initiateConnection ({ rtcConfiguration, signal, stream: ra // read answer const answerMessage = await stream.read() - if (answerMessage.type !== pb.Message.Type.SDP_ANSWER) { + if (answerMessage.type !== Message.Type.SDP_ANSWER) { throw new Error('remote should send an SDP answer') } diff --git a/src/peer_transport/listener.ts b/src/private-to-private/listener.ts similarity index 100% rename from src/peer_transport/listener.ts rename to src/private-to-private/listener.ts diff --git a/src/peer_transport/pb/index.proto b/src/private-to-private/pb/message.proto similarity index 100% rename from src/peer_transport/pb/index.proto rename to src/private-to-private/pb/message.proto diff --git a/src/peer_transport/pb/index.ts b/src/private-to-private/pb/message.ts similarity index 97% rename from src/peer_transport/pb/index.ts rename to src/private-to-private/pb/message.ts index d2721ae..b0824ed 100644 --- a/src/peer_transport/pb/index.ts +++ b/src/private-to-private/pb/message.ts @@ -82,7 +82,7 @@ export namespace Message { return _codec } - export const encode = (obj: Message): Uint8Array => { + export const encode = (obj: Partial): Uint8Array => { return encodeMessage(obj, Message.codec()) } diff --git a/src/peer_transport/transport.ts b/src/private-to-private/transport.ts similarity index 100% rename from src/peer_transport/transport.ts rename to src/private-to-private/transport.ts diff --git a/src/peer_transport/util.ts b/src/private-to-private/util.ts similarity index 84% rename from src/peer_transport/util.ts rename to src/private-to-private/util.ts index 4b59f89..e1b6697 100644 --- a/src/peer_transport/util.ts +++ b/src/private-to-private/util.ts @@ -1,14 +1,11 @@ import { logger } from '@libp2p/logger' -import { detect } from 'detect-browser' -import * as pb from './pb/index.js' +import { isFirefox } from '../util.js' +import { Message } from './pb/message.js' import type { DeferredPromise } from 'p-defer' -const browser = detect() -export const isFirefox = ((browser != null) && browser.name === 'firefox') - interface MessageStream { - read: () => Promise - write: (d: pb.Message) => void | Promise + read: () => Promise + write: (d: Message) => void | Promise } const log = logger('libp2p:webrtc:peer:util') @@ -19,7 +16,7 @@ export const readCandidatesUntilConnected = async (connectedPromise: DeferredPro // check if readResult is a message if (readResult instanceof Object) { const message = readResult - if (message.type !== pb.Message.Type.ICE_CANDIDATE) { + if (message.type !== Message.Type.ICE_CANDIDATE) { throw new Error('expected only ice candidates') } // end of candidates has been signalled diff --git a/src/options.ts b/src/private-to-public/options.ts similarity index 100% rename from src/options.ts rename to src/private-to-public/options.ts diff --git a/src/sdp.ts b/src/private-to-public/sdp.ts similarity index 98% rename from src/sdp.ts rename to src/private-to-public/sdp.ts index f5ee546..4744550 100644 --- a/src/sdp.ts +++ b/src/private-to-public/sdp.ts @@ -1,7 +1,7 @@ import { logger } from '@libp2p/logger' import { bases } from 'multiformats/basics' import * as multihashes from 'multihashes' -import { inappropriateMultiaddr, invalidArgument, invalidFingerprint, unsupportedHashAlgorithm } from './error.js' +import { inappropriateMultiaddr, invalidArgument, invalidFingerprint, unsupportedHashAlgorithm } from '../error.js' import { CERTHASH_CODE } from './transport.js' import type { Multiaddr } from '@multiformats/multiaddr' import type { HashCode, HashName } from 'multihashes' diff --git a/src/transport.ts b/src/private-to-public/transport.ts similarity index 97% rename from src/transport.ts rename to src/private-to-public/transport.ts index e018668..30d658d 100644 --- a/src/transport.ts +++ b/src/private-to-public/transport.ts @@ -6,12 +6,12 @@ import { protocols } from '@multiformats/multiaddr' import * as multihashes from 'multihashes' import { concat } from 'uint8arrays/concat' import { fromString as uint8arrayFromString } from 'uint8arrays/from-string' -import { dataChannelError, inappropriateMultiaddr, unimplemented, invalidArgument } from './error.js' -import { WebRTCMultiaddrConnection } from './maconn.js' -import { DataChannelMuxerFactory } from './muxer.js' -import { isFirefox } from './peer_transport/util.js' +import { dataChannelError, inappropriateMultiaddr, unimplemented, invalidArgument } from '../error.js' +import { WebRTCMultiaddrConnection } from '../maconn.js' +import { DataChannelMuxerFactory } from '../muxer.js' +import { WebRTCStream } from '../stream.js' +import { isFirefox } from '../util.js' import * as sdp from './sdp.js' -import { WebRTCStream } from './stream.js' import { genUfrag } from './util.js' import type { WebRTCDialOptions } from './options.js' import type { Connection } from '@libp2p/interface-connection' diff --git a/src/private-to-public/util.ts b/src/private-to-public/util.ts new file mode 100644 index 0000000..6ef40af --- /dev/null +++ b/src/private-to-public/util.ts @@ -0,0 +1,3 @@ + +const charset = Array.from('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/') +export const genUfrag = (len: number): string => [...Array(len)].map(() => charset.at(Math.floor(Math.random() * charset.length))).join('') diff --git a/src/stream.ts b/src/stream.ts index fa1675a..cf35eed 100644 --- a/src/stream.ts +++ b/src/stream.ts @@ -5,7 +5,7 @@ import { pipe } from 'it-pipe' import { pushable } from 'it-pushable' import defer, { type DeferredPromise } from 'p-defer' import { Uint8ArrayList } from 'uint8arraylist' -import * as pb from '../proto_ts/message.js' +import { Message } from './pb/message.js' import type { Stream, StreamStat, Direction } from '@libp2p/interface-connection' import type { Source } from 'it-stream-types' @@ -66,7 +66,7 @@ interface StreamStateInput { * 1 = STOP_SENDING * 2 = RESET */ - flag: pb.Message_Flag + flag: Message.Flag } export enum StreamStates { @@ -99,7 +99,7 @@ class StreamState { if (direction === 'inbound') { switch (flag) { - case pb.Message_Flag.FIN: + case Message.Flag.FIN: if (this.state === StreamStates.OPEN) { this.state = StreamStates.READ_CLOSED } else if (this.state === StreamStates.WRITE_CLOSED) { @@ -107,7 +107,7 @@ class StreamState { } break - case pb.Message_Flag.STOP_SENDING: + case Message.Flag.STOP_SENDING: if (this.state === StreamStates.OPEN) { this.state = StreamStates.WRITE_CLOSED } else if (this.state === StreamStates.READ_CLOSED) { @@ -115,7 +115,7 @@ class StreamState { } break - case pb.Message_Flag.RESET: + case Message.Flag.RESET: this.state = StreamStates.CLOSED break default: @@ -123,7 +123,7 @@ class StreamState { } } else { switch (flag) { - case pb.Message_Flag.FIN: + case Message.Flag.FIN: if (this.state === StreamStates.OPEN) { this.state = StreamStates.WRITE_CLOSED } else if (this.state === StreamStates.READ_CLOSED) { @@ -131,7 +131,7 @@ class StreamState { } break - case pb.Message_Flag.STOP_SENDING: + case Message.Flag.STOP_SENDING: if (this.state === StreamStates.OPEN) { this.state = StreamStates.READ_CLOSED } else if (this.state === StreamStates.WRITE_CLOSED) { @@ -139,7 +139,7 @@ class StreamState { } break - case pb.Message_Flag.RESET: + case Message.Flag.RESET: this.state = StreamStates.CLOSED break @@ -313,7 +313,7 @@ export class WebRTCStream implements Stream { if (this.streamState.isWriteClosed()) { return } - const msgbuf = pb.Message.toBinary({ message: buf.subarray() }) + const msgbuf = Message.encode({ message: buf.subarray() }) const sendbuf = lengthPrefixed.encode.single(msgbuf) this.channel.send(sendbuf.subarray()) @@ -324,7 +324,7 @@ export class WebRTCStream implements Stream { * Handle incoming */ processIncomingProtobuf (buffer: Uint8Array): Uint8Array | undefined { - const message = pb.Message.fromBinary(buffer) + const message = Message.decode(buffer) if (message.flag !== undefined) { const [currentState, nextState] = this.streamState.transition({ direction: 'inbound', flag: message.flag }) @@ -371,14 +371,14 @@ export class WebRTCStream implements Stream { * Close a stream for reading only */ closeRead (): void { - const [currentState, nextState] = this.streamState.transition({ direction: 'outbound', flag: pb.Message_Flag.STOP_SENDING }) + const [currentState, nextState] = this.streamState.transition({ direction: 'outbound', flag: Message.Flag.STOP_SENDING }) if (currentState === nextState) { // No change, no op return } if (currentState === StreamStates.OPEN || currentState === StreamStates.WRITE_CLOSED) { - this._sendFlag(pb.Message_Flag.STOP_SENDING) + this._sendFlag(Message.Flag.STOP_SENDING) this._innersrc.end() } @@ -391,14 +391,14 @@ export class WebRTCStream implements Stream { * Close a stream for writing only */ closeWrite (): void { - const [currentState, nextState] = this.streamState.transition({ direction: 'outbound', flag: pb.Message_Flag.FIN }) + const [currentState, nextState] = this.streamState.transition({ direction: 'outbound', flag: Message.Flag.FIN }) if (currentState === nextState) { // No change, no op return } if (currentState === StreamStates.OPEN || currentState === StreamStates.READ_CLOSED) { - this._sendFlag(pb.Message_Flag.FIN) + this._sendFlag(Message.Flag.FIN) this.closeWritePromise.resolve() } @@ -421,20 +421,20 @@ export class WebRTCStream implements Stream { * @see this.closeWrite */ reset (): void { - const [currentState, nextState] = this.streamState.transition({ direction: 'outbound', flag: pb.Message_Flag.RESET }) + const [currentState, nextState] = this.streamState.transition({ direction: 'outbound', flag: Message.Flag.RESET }) if (currentState === nextState) { // No change, no op return } - this._sendFlag(pb.Message_Flag.RESET) + this._sendFlag(Message.Flag.RESET) this.close() } - private _sendFlag (flag: pb.Message_Flag): void { + private _sendFlag (flag: Message.Flag): void { try { log.trace('Sending flag: %s', flag.toString()) - const msgbuf = pb.Message.toBinary({ flag }) + const msgbuf = Message.encode({ flag }) this.channel.send(lengthPrefixed.encode.single(msgbuf).subarray()) } catch (err) { if (err instanceof Error) { diff --git a/src/util.ts b/src/util.ts index c930531..e26e64d 100644 --- a/src/util.ts +++ b/src/util.ts @@ -1,6 +1,8 @@ +import { detect } from 'detect-browser' + +const browser = detect() +export const isFirefox = ((browser != null) && browser.name === 'firefox') + export const nopSource = async function * nop (): AsyncGenerator {} export const nopSink = async (_: any): Promise => {} - -const charset = Array.from('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/') -export const genUfrag = (len: number): string => [...Array(len)].map(() => charset.at(Math.floor(Math.random() * charset.length))).join('') diff --git a/test/peer.browser.spec.ts b/test/peer.browser.spec.ts index 7b28726..d123e0a 100644 --- a/test/peer.browser.spec.ts +++ b/test/peer.browser.spec.ts @@ -8,9 +8,9 @@ import { pair } from 'it-pair' import { duplexPair } from 'it-pair/duplex' import { pbStream } from 'it-pb-stream' import Sinon from 'sinon' -import { initiateConnection, handleIncomingStream } from '../src/peer_transport/handler' -import { Message } from '../src/peer_transport/pb/index.js' -import { WebRTCTransport } from '../src/peer_transport/transport' +import { initiateConnection, handleIncomingStream } from '../src/private-to-private/handler' +import { Message } from '../src/private-to-private/pb/message.js' +import { WebRTCTransport } from '../src/private-to-private/transport' const browser = detect() diff --git a/test/sdp.spec.ts b/test/sdp.spec.ts index dcc5c24..2c32f79 100644 --- a/test/sdp.spec.ts +++ b/test/sdp.spec.ts @@ -1,6 +1,6 @@ import { multiaddr } from '@multiformats/multiaddr' import { expect } from 'aegir/chai' -import * as underTest from '../src/sdp.js' +import * as underTest from '../src/private-to-public/sdp.js' const sampleMultiAddr = multiaddr('/ip4/0.0.0.0/udp/56093/webrtc/certhash/uEiByaEfNSLBexWBNFZy_QB1vAKEj7JAXDizRs4_SnTflsQ') const sampleCerthash = 'uEiByaEfNSLBexWBNFZy_QB1vAKEj7JAXDizRs4_SnTflsQ' diff --git a/test/stream.browser.spec.ts b/test/stream.browser.spec.ts index 8b5375b..5318ece 100644 --- a/test/stream.browser.spec.ts +++ b/test/stream.browser.spec.ts @@ -1,6 +1,6 @@ import { expect, assert } from 'aegir/chai' import { bytes } from 'multiformats' -import * as pb from '../proto_ts/message.js' +import { Message } from '../src/pb/message.js' import * as underTest from '../src/stream' const TEST_MESSAGE = 'test_messgae' @@ -12,12 +12,12 @@ function setup (): { peerConnection: RTCPeerConnection, datachannel: RTCDataChan return { peerConnection, datachannel, webrtcStream } } -function generatePbByFlag (flag?: pb.Message_Flag): Uint8Array { - const testPb: pb.Message = { +function generatePbByFlag (flag?: Message.Flag): Uint8Array { + const testPb: Message = { flag, message: bytes.fromString(TEST_MESSAGE) } - return pb.Message.toBinary(testPb) + return Message.encode(testPb) } describe('Stream Stats', () => { @@ -93,13 +93,13 @@ describe('Stream Read Stats Transition By Incoming Flag', () => { it('open to read-close by flag:FIN', () => { expect(webrtcStream.streamState.state).to.equal(underTest.StreamStates.OPEN) - const IncomingBuffer = generatePbByFlag(pb.Message_Flag.FIN) + const IncomingBuffer = generatePbByFlag(Message.Flag.FIN) webrtcStream.processIncomingProtobuf(IncomingBuffer) expect(webrtcStream.streamState.state).to.equal(underTest.StreamStates.READ_CLOSED) }) it('read-close to close by flag:STOP_SENDING', () => { - const IncomingBuffer = generatePbByFlag(pb.Message_Flag.STOP_SENDING) + const IncomingBuffer = generatePbByFlag(Message.Flag.STOP_SENDING) webrtcStream.processIncomingProtobuf(IncomingBuffer) expect(webrtcStream.streamState.state).to.equal(underTest.StreamStates.CLOSED) }) @@ -109,13 +109,13 @@ describe('Stream Write Stats Transition By Incoming Flag', () => { const webrtcStream = setup().webrtcStream it('open to write-close by flag:STOP_SENDING', () => { expect(webrtcStream.streamState.state).to.equal(underTest.StreamStates.OPEN) - const IncomingBuffer = generatePbByFlag(pb.Message_Flag.STOP_SENDING) + const IncomingBuffer = generatePbByFlag(Message.Flag.STOP_SENDING) webrtcStream.processIncomingProtobuf(IncomingBuffer) expect(webrtcStream.streamState.state).to.equal(underTest.StreamStates.WRITE_CLOSED) }) it('write-close to close by flag:FIN', () => { - const IncomingBuffer = generatePbByFlag(pb.Message_Flag.FIN) + const IncomingBuffer = generatePbByFlag(Message.Flag.FIN) webrtcStream.processIncomingProtobuf(IncomingBuffer) expect(webrtcStream.streamState.state).to.equal(underTest.StreamStates.CLOSED) }) diff --git a/test/transport.browser.spec.ts b/test/transport.browser.spec.ts index 581dd9f..d7878dc 100644 --- a/test/transport.browser.spec.ts +++ b/test/transport.browser.spec.ts @@ -6,7 +6,7 @@ import { createEd25519PeerId } from '@libp2p/peer-id-factory' import { multiaddr, type Multiaddr } from '@multiformats/multiaddr' import { expect, assert } from 'aegir/chai' import { UnimplementedError } from './../src/error.js' -import * as underTest from './../src/transport.js' +import * as underTest from './../src/private-to-public/transport.js' import { expectError } from './util.js' import type { Metrics } from '@libp2p/interface-metrics' From c5ed77d38390a15de2cafc5fbc7d7be842bfe244 Mon Sep 17 00:00:00 2001 From: achingbrain Date: Thu, 11 May 2023 17:59:33 +0100 Subject: [PATCH 2/2] chore: update deps --- examples/browser-to-browser/package.json | 6 +++--- examples/browser-to-server/package.json | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/browser-to-browser/package.json b/examples/browser-to-browser/package.json index 28ce947..94368cb 100644 --- a/examples/browser-to-browser/package.json +++ b/examples/browser-to-browser/package.json @@ -12,9 +12,9 @@ "test": "npm run build && test-browser-example tests" }, "dependencies": { - "@chainsafe/libp2p-noise": "^11.0.0", - "@libp2p/websockets": "^5.0.3", - "@libp2p/mplex": "^7.0.0", + "@chainsafe/libp2p-noise": "^12.0.0", + "@libp2p/websockets": "^6.0.1", + "@libp2p/mplex": "^8.0.1", "@libp2p/webrtc": "file:../../", "@multiformats/multiaddr": "^12.0.0", "it-pushable": "^3.1.0", diff --git a/examples/browser-to-server/package.json b/examples/browser-to-server/package.json index a04965e..22e88e1 100644 --- a/examples/browser-to-server/package.json +++ b/examples/browser-to-server/package.json @@ -12,7 +12,7 @@ "test": "npm run build && test-browser-example tests" }, "dependencies": { - "@chainsafe/libp2p-noise": "^11.0.0", + "@chainsafe/libp2p-noise": "^12.0.0", "@libp2p/webrtc": "file:../../", "@multiformats/multiaddr": "^12.0.0", "it-pushable": "^3.1.0",