Skip to content

Commit 64723a7

Browse files
authored
fix: remove protobuf-ts and split code into two folders (libp2p#162)
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.
1 parent 2f5c524 commit 64723a7

23 files changed

+162
-179
lines changed

examples/browser-to-browser/package.json

+3-3
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,9 @@
1212
"test": "npm run build && test-browser-example tests"
1313
},
1414
"dependencies": {
15-
"@chainsafe/libp2p-noise": "^11.0.0",
16-
"@libp2p/websockets": "^5.0.3",
17-
"@libp2p/mplex": "^7.0.0",
15+
"@chainsafe/libp2p-noise": "^12.0.0",
16+
"@libp2p/websockets": "^6.0.1",
17+
"@libp2p/mplex": "^8.0.1",
1818
"@libp2p/webrtc": "file:../../",
1919
"@multiformats/multiaddr": "^12.0.0",
2020
"it-pushable": "^3.1.0",

examples/browser-to-server/package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
"test": "npm run build && test-browser-example tests"
1313
},
1414
"dependencies": {
15-
"@chainsafe/libp2p-noise": "^11.0.0",
15+
"@chainsafe/libp2p-noise": "^12.0.0",
1616
"@libp2p/webrtc": "file:../../",
1717
"@multiformats/multiaddr": "^12.0.0",
1818
"it-pushable": "^3.1.0",

package.json

+1-4
Original file line numberDiff line numberDiff line change
@@ -123,8 +123,7 @@
123123
]
124124
},
125125
"scripts": {
126-
"generate:proto": "npx protoc --ts_out proto_ts --proto_path src src/*.proto",
127-
"generate:webrtc-direct": "protons src/peer_transport/pb/index.proto",
126+
"generate": "protons src/private-to-private/pb/message.proto src/pb/message.proto",
128127
"build": "aegir build",
129128
"test": "aegir test -t browser",
130129
"test:chrome": "aegir test -t browser --cov",
@@ -148,7 +147,6 @@
148147
"@libp2p/logger": "^2.0.7",
149148
"@libp2p/peer-id": "^2.0.3",
150149
"@multiformats/multiaddr": "^12.1.2",
151-
"@protobuf-ts/runtime": "^2.9.0",
152150
"abortable-iterator": "^5.0.1",
153151
"detect-browser": "^5.3.0",
154152
"it-length-prefixed": "^9.0.1",
@@ -167,7 +165,6 @@
167165
"devDependencies": {
168166
"@libp2p/interface-mocks": "^12.0.1",
169167
"@libp2p/peer-id-factory": "^2.0.3",
170-
"@protobuf-ts/protoc": "^2.9.0",
171168
"@types/sinon": "^10.0.14",
172169
"aegir": "^39.0.6",
173170
"it-pair": "^2.0.6",

proto_ts/message.ts

-106
This file was deleted.

src/index.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
import { WebRTCTransport } from './peer_transport/transport.js'
2-
import { WebRTCDirectTransport, type WebRTCDirectTransportComponents } from './transport.js'
3-
import type { WebRTCTransportComponents, WebRTCTransportInit } from './peer_transport/transport.js'
1+
import { WebRTCTransport } from './private-to-private/transport.js'
2+
import { WebRTCDirectTransport, type WebRTCDirectTransportComponents } from './private-to-public/transport.js'
3+
import type { WebRTCTransportComponents, WebRTCTransportInit } from './private-to-private/transport.js'
44
import type { Transport } from '@libp2p/interface-transport'
55

66
function webRTCDirect (): (components: WebRTCDirectTransportComponents) => Transport {

src/message.proto renamed to src/pb/message.proto

+2-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
syntax = "proto2";
2-
3-
package webrtc.pb;
1+
syntax = "proto3";
42

53
message Message {
64
enum Flag {
@@ -10,7 +8,7 @@ message Message {
108
// The sender will no longer read messages on the stream. Incoming data is
119
// being discarded on receipt.
1210
STOP_SENDING = 1;
13-
11+
1412
// The sender abruptly terminates the sending part of the stream. The
1513
// receiver can discard any data that it already received on that stream.
1614
RESET = 2;

src/pb/message.ts

+92
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
/* eslint-disable import/export */
2+
/* eslint-disable complexity */
3+
/* eslint-disable @typescript-eslint/no-namespace */
4+
/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */
5+
/* eslint-disable @typescript-eslint/no-empty-interface */
6+
7+
import { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime'
8+
import type { Codec } from 'protons-runtime'
9+
import type { Uint8ArrayList } from 'uint8arraylist'
10+
11+
export interface Message {
12+
flag?: Message.Flag
13+
message?: Uint8Array
14+
}
15+
16+
export namespace Message {
17+
export enum Flag {
18+
FIN = 'FIN',
19+
STOP_SENDING = 'STOP_SENDING',
20+
RESET = 'RESET'
21+
}
22+
23+
enum __FlagValues {
24+
FIN = 0,
25+
STOP_SENDING = 1,
26+
RESET = 2
27+
}
28+
29+
export namespace Flag {
30+
export const codec = (): Codec<Flag> => {
31+
return enumeration<Flag>(__FlagValues)
32+
}
33+
}
34+
35+
let _codec: Codec<Message>
36+
37+
export const codec = (): Codec<Message> => {
38+
if (_codec == null) {
39+
_codec = message<Message>((obj, w, opts = {}) => {
40+
if (opts.lengthDelimited !== false) {
41+
w.fork()
42+
}
43+
44+
if (obj.flag != null) {
45+
w.uint32(8)
46+
Message.Flag.codec().encode(obj.flag, w)
47+
}
48+
49+
if (obj.message != null) {
50+
w.uint32(18)
51+
w.bytes(obj.message)
52+
}
53+
54+
if (opts.lengthDelimited !== false) {
55+
w.ldelim()
56+
}
57+
}, (reader, length) => {
58+
const obj: any = {}
59+
60+
const end = length == null ? reader.len : reader.pos + length
61+
62+
while (reader.pos < end) {
63+
const tag = reader.uint32()
64+
65+
switch (tag >>> 3) {
66+
case 1:
67+
obj.flag = Message.Flag.codec().decode(reader)
68+
break
69+
case 2:
70+
obj.message = reader.bytes()
71+
break
72+
default:
73+
reader.skipType(tag & 7)
74+
break
75+
}
76+
}
77+
78+
return obj
79+
})
80+
}
81+
82+
return _codec
83+
}
84+
85+
export const encode = (obj: Partial<Message>): Uint8Array => {
86+
return encodeMessage(obj, Message.codec())
87+
}
88+
89+
export const decode = (buf: Uint8Array | Uint8ArrayList): Message => {
90+
return decodeMessage(buf, Message.codec())
91+
}
92+
}

src/peer_transport/handler.ts renamed to src/private-to-private/handler.ts

+9-9
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { abortableDuplex } from 'abortable-iterator'
33
import { pbStream } from 'it-pb-stream'
44
import pDefer, { type DeferredPromise } from 'p-defer'
55
import { DataChannelMuxerFactory } from '../muxer.js'
6-
import * as pb from './pb/index.js'
6+
import { Message } from './pb/message.js'
77
import { readCandidatesUntilConnected, resolveOnConnected } from './util.js'
88
import type { Stream } from '@libp2p/interface-connection'
99
import type { IncomingStreamData } from '@libp2p/interface-registrar'
@@ -17,7 +17,7 @@ export type IncomingStreamOpts = { rtcConfiguration?: RTCConfiguration } & Incom
1717

1818
export async function handleIncomingStream ({ rtcConfiguration, stream: rawStream }: IncomingStreamOpts): Promise<{ pc: RTCPeerConnection, muxerFactory: StreamMuxerFactory, remoteAddress: string }> {
1919
const signal = AbortSignal.timeout(DEFAULT_TIMEOUT)
20-
const stream = pbStream(abortableDuplex(rawStream, signal)).pb(pb.Message)
20+
const stream = pbStream(abortableDuplex(rawStream, signal)).pb(Message)
2121
const pc = new RTCPeerConnection(rtcConfiguration)
2222
const muxerFactory = new DataChannelMuxerFactory(pc)
2323

@@ -30,7 +30,7 @@ export async function handleIncomingStream ({ rtcConfiguration, stream: rawStrea
3030
answerSentPromise.promise.then(
3131
() => {
3232
stream.write({
33-
type: pb.Message.Type.ICE_CANDIDATE,
33+
type: Message.Type.ICE_CANDIDATE,
3434
data: (candidate != null) ? JSON.stringify(candidate.toJSON()) : ''
3535
})
3636
},
@@ -44,7 +44,7 @@ export async function handleIncomingStream ({ rtcConfiguration, stream: rawStrea
4444

4545
// read an SDP offer
4646
const pbOffer = await stream.read()
47-
if (pbOffer.type !== pb.Message.Type.SDP_OFFER) {
47+
if (pbOffer.type !== Message.Type.SDP_OFFER) {
4848
throw new Error(`expected message type SDP_OFFER, received: ${pbOffer.type ?? 'undefined'} `)
4949
}
5050
const offer = new RTCSessionDescription({
@@ -64,7 +64,7 @@ export async function handleIncomingStream ({ rtcConfiguration, stream: rawStrea
6464
throw new Error('Failed to create answer')
6565
})
6666
// write the answer to the remote
67-
stream.write({ type: pb.Message.Type.SDP_ANSWER, data: answer.sdp })
67+
stream.write({ type: Message.Type.SDP_ANSWER, data: answer.sdp })
6868

6969
await pc.setLocalDescription(answer).catch(err => {
7070
log.error('could not execute setLocalDescription', err)
@@ -89,7 +89,7 @@ export interface ConnectOptions {
8989
}
9090

9191
export async function initiateConnection ({ rtcConfiguration, signal, stream: rawStream }: ConnectOptions): Promise<{ pc: RTCPeerConnection, muxerFactory: StreamMuxerFactory, remoteAddress: string }> {
92-
const stream = pbStream(abortableDuplex(rawStream, signal)).pb(pb.Message)
92+
const stream = pbStream(abortableDuplex(rawStream, signal)).pb(Message)
9393
// setup peer connection
9494
const pc = new RTCPeerConnection(rtcConfiguration)
9595
const muxerFactory = new DataChannelMuxerFactory(pc)
@@ -107,14 +107,14 @@ export async function initiateConnection ({ rtcConfiguration, signal, stream: ra
107107
// peer
108108
pc.onicecandidate = ({ candidate }) => {
109109
stream.write({
110-
type: pb.Message.Type.ICE_CANDIDATE,
110+
type: Message.Type.ICE_CANDIDATE,
111111
data: (candidate != null) ? JSON.stringify(candidate.toJSON()) : ''
112112
})
113113
}
114114
// create an offer
115115
const offerSdp = await pc.createOffer()
116116
// write the offer to the stream
117-
stream.write({ type: pb.Message.Type.SDP_OFFER, data: offerSdp.sdp })
117+
stream.write({ type: Message.Type.SDP_OFFER, data: offerSdp.sdp })
118118
// set offer as local description
119119
await pc.setLocalDescription(offerSdp).catch(err => {
120120
log.error('could not execute setLocalDescription', err)
@@ -123,7 +123,7 @@ export async function initiateConnection ({ rtcConfiguration, signal, stream: ra
123123

124124
// read answer
125125
const answerMessage = await stream.read()
126-
if (answerMessage.type !== pb.Message.Type.SDP_ANSWER) {
126+
if (answerMessage.type !== Message.Type.SDP_ANSWER) {
127127
throw new Error('remote should send an SDP answer')
128128
}
129129

File renamed without changes.

src/peer_transport/pb/index.ts renamed to src/private-to-private/pb/message.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ export namespace Message {
8282
return _codec
8383
}
8484

85-
export const encode = (obj: Message): Uint8Array => {
85+
export const encode = (obj: Partial<Message>): Uint8Array => {
8686
return encodeMessage(obj, Message.codec())
8787
}
8888

File renamed without changes.

src/peer_transport/util.ts renamed to src/private-to-private/util.ts

+5-8
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,11 @@
11
import { logger } from '@libp2p/logger'
2-
import { detect } from 'detect-browser'
3-
import * as pb from './pb/index.js'
2+
import { isFirefox } from '../util.js'
3+
import { Message } from './pb/message.js'
44
import type { DeferredPromise } from 'p-defer'
55

6-
const browser = detect()
7-
export const isFirefox = ((browser != null) && browser.name === 'firefox')
8-
96
interface MessageStream {
10-
read: () => Promise<pb.Message>
11-
write: (d: pb.Message) => void | Promise<void>
7+
read: () => Promise<Message>
8+
write: (d: Message) => void | Promise<void>
129
}
1310

1411
const log = logger('libp2p:webrtc:peer:util')
@@ -19,7 +16,7 @@ export const readCandidatesUntilConnected = async (connectedPromise: DeferredPro
1916
// check if readResult is a message
2017
if (readResult instanceof Object) {
2118
const message = readResult
22-
if (message.type !== pb.Message.Type.ICE_CANDIDATE) {
19+
if (message.type !== Message.Type.ICE_CANDIDATE) {
2320
throw new Error('expected only ice candidates')
2421
}
2522
// end of candidates has been signalled
File renamed without changes.

0 commit comments

Comments
 (0)