peerpigeon 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1187 -0
  3. package/examples/browser/app-dht-disabled.js +42 -0
  4. package/examples/browser/app.js +51 -0
  5. package/examples/browser/assets/images/favicon.png +0 -0
  6. package/examples/browser/assets/images/pigeon.png +0 -0
  7. package/examples/browser/index-dht-disabled.html +123 -0
  8. package/examples/browser/index.html +340 -0
  9. package/examples/browser/styles.css +1288 -0
  10. package/examples/browser/ui-clean.js +0 -0
  11. package/examples/browser/ui.js +1930 -0
  12. package/index.js +8 -0
  13. package/package.json +70 -0
  14. package/server/index.js +515 -0
  15. package/src/CleanupManager.js +181 -0
  16. package/src/ConnectionManager.js +841 -0
  17. package/src/EventEmitter.js +27 -0
  18. package/src/EvictionManager.js +257 -0
  19. package/src/GossipManager.js +416 -0
  20. package/src/MediaManager.js +225 -0
  21. package/src/MeshOptimizer.js +181 -0
  22. package/src/PeerConnection.js +831 -0
  23. package/src/PeerDiscovery.js +297 -0
  24. package/src/PeerPigeonMesh.js +703 -0
  25. package/src/SignalingClient.js +536 -0
  26. package/src/SignalingHandler.js +325 -0
  27. package/src/StorageManager.js +88 -0
  28. package/src/TimerUtils.js +46 -0
  29. package/src/WebDHT.js +1099 -0
  30. package/websocket-server/README.md +257 -0
  31. package/websocket-server/memory-leak-test.js +193 -0
  32. package/websocket-server/node_modules/.package-lock.json +29 -0
  33. package/websocket-server/node_modules/ws/LICENSE +20 -0
  34. package/websocket-server/node_modules/ws/README.md +548 -0
  35. package/websocket-server/node_modules/ws/browser.js +8 -0
  36. package/websocket-server/node_modules/ws/index.js +13 -0
  37. package/websocket-server/node_modules/ws/lib/buffer-util.js +131 -0
  38. package/websocket-server/node_modules/ws/lib/constants.js +18 -0
  39. package/websocket-server/node_modules/ws/lib/event-target.js +292 -0
  40. package/websocket-server/node_modules/ws/lib/extension.js +203 -0
  41. package/websocket-server/node_modules/ws/lib/limiter.js +55 -0
  42. package/websocket-server/node_modules/ws/lib/permessage-deflate.js +528 -0
  43. package/websocket-server/node_modules/ws/lib/receiver.js +706 -0
  44. package/websocket-server/node_modules/ws/lib/sender.js +602 -0
  45. package/websocket-server/node_modules/ws/lib/stream.js +161 -0
  46. package/websocket-server/node_modules/ws/lib/subprotocol.js +62 -0
  47. package/websocket-server/node_modules/ws/lib/validation.js +152 -0
  48. package/websocket-server/node_modules/ws/lib/websocket-server.js +550 -0
  49. package/websocket-server/node_modules/ws/lib/websocket.js +1388 -0
  50. package/websocket-server/node_modules/ws/package.json +69 -0
  51. package/websocket-server/node_modules/ws/wrapper.mjs +8 -0
  52. package/websocket-server/package-lock.json +39 -0
  53. package/websocket-server/server.js +298 -0
  54. package/websocket-server/test.js +133 -0
@@ -0,0 +1,257 @@
1
+ # PeerPigeon WebSocket Server
2
+
3
+ A local WebSocket server for PeerPigeon development and testing.
4
+
5
+ ## Features
6
+
7
+ - WebSocket-based peer signaling
8
+ - XOR distance-based peer discovery
9
+ - WebRTC signaling message routing
10
+ - In-memory peer storage
11
+ - Real-time peer announcements
12
+ - Graceful connection handling
13
+
14
+ ## Quick Start
15
+
16
+ ### Option 1: Using npm package (Recommended)
17
+
18
+ ```bash
19
+ # Install PeerPigeon
20
+ npm install peerpigeon
21
+
22
+ # Start the server using npm scripts
23
+ npm start
24
+
25
+ # Or with custom configuration
26
+ PORT=8080 HOST=0.0.0.0 npm start
27
+ ```
28
+
29
+ ### Option 2: From source
30
+
31
+ ```bash
32
+ # Clone the repository
33
+ git clone https://github.com/draeder/peerpigeon.git
34
+ cd peerpigeon
35
+
36
+ # Start the server directly
37
+ npm start
38
+ ```
39
+
40
+ ### Option 3: Programmatic usage (Recommended for applications)
41
+
42
+ ```javascript
43
+ import { PeerPigeonServer } from 'peerpigeon';
44
+
45
+ // Create and configure server
46
+ const server = new PeerPigeonServer({
47
+ port: 3000,
48
+ maxConnections: 500
49
+ });
50
+
51
+ // Start server
52
+ await server.start();
53
+
54
+ // Listen for events
55
+ server.on('peerConnected', ({ peerId, totalConnections }) => {
56
+ console.log(`New peer connected: ${peerId}`);
57
+ });
58
+ ```
59
+
60
+ The server will start on `ws://localhost:3000` by default.
61
+
62
+ ### 3. Connect from Browser
63
+
64
+ Update your browser application to connect to the local server:
65
+
66
+ ```javascript
67
+ const mesh = new PeerPigeonMesh();
68
+ await mesh.connect('ws://localhost:3000');
69
+ ```
70
+
71
+ ## Configuration
72
+
73
+ ### Environment Variables
74
+
75
+ - `PORT`: Server port (default: 3000)
76
+ - `HOST`: Server host (default: localhost)
77
+
78
+ ### Example Usage
79
+
80
+ ```bash
81
+ # Start on custom port
82
+ PORT=8080 npm start
83
+
84
+ # Start on all interfaces
85
+ HOST=0.0.0.0 npm start
86
+ ```
87
+
88
+ ## API
89
+
90
+ ### Connection
91
+
92
+ Connect with a valid 40-character hex peer ID:
93
+
94
+ ```
95
+ ws://localhost:3000?peerId=abc123def456...
96
+ ```
97
+
98
+ ### Message Types
99
+
100
+ #### Peer Announcement
101
+ ```json
102
+ {
103
+ "type": "announce",
104
+ "data": { "peerId": "abc123..." }
105
+ }
106
+ ```
107
+
108
+ #### WebRTC Signaling
109
+ ```json
110
+ {
111
+ "type": "offer",
112
+ "data": { "sdp": "..." },
113
+ "targetPeerId": "def456..."
114
+ }
115
+ ```
116
+
117
+ #### Keep-Alive
118
+ ```json
119
+ {
120
+ "type": "ping",
121
+ "data": { "timestamp": 1234567890 }
122
+ }
123
+ ```
124
+
125
+ ### Response Messages
126
+
127
+ #### Connection Confirmation
128
+ ```json
129
+ {
130
+ "type": "connected",
131
+ "peerId": "abc123...",
132
+ "timestamp": 1234567890
133
+ }
134
+ ```
135
+
136
+ #### Peer Discovery
137
+ ```json
138
+ {
139
+ "type": "peer-discovered",
140
+ "data": { "peerId": "def456..." },
141
+ "fromPeerId": "system",
142
+ "targetPeerId": "abc123...",
143
+ "timestamp": 1234567890
144
+ }
145
+ ```
146
+
147
+ #### Pong Response
148
+ ```json
149
+ {
150
+ "type": "pong",
151
+ "timestamp": 1234567890,
152
+ "originalTimestamp": 1234567885
153
+ }
154
+ ```
155
+
156
+ ## Testing
157
+
158
+ ### Manual Testing
159
+
160
+ You can test the server using a WebSocket client:
161
+
162
+ ```javascript
163
+ const ws = new WebSocket('ws://localhost:3000?peerId=1234567890abcdef1234567890abcdef12345678');
164
+
165
+ ws.onopen = () => {
166
+ console.log('Connected');
167
+
168
+ // Send announcement
169
+ ws.send(JSON.stringify({
170
+ type: 'announce',
171
+ data: { peerId: '1234567890abcdef1234567890abcdef12345678' }
172
+ }));
173
+ };
174
+
175
+ ws.onmessage = (event) => {
176
+ console.log('Received:', JSON.parse(event.data));
177
+ };
178
+ ```
179
+
180
+ ### Browser Testing
181
+
182
+ 1. Open `examples/browser/index.html` in multiple browser tabs
183
+ 2. Update the WebSocket URL to `ws://localhost:3000`
184
+ 3. Click "Connect" in each tab
185
+ 4. Watch peers discover each other
186
+
187
+ ## Development
188
+
189
+ ### Watch Mode
190
+
191
+ For development with automatic restarts:
192
+
193
+ ```bash
194
+ npm run dev
195
+ ```
196
+
197
+ ### Logging
198
+
199
+ The server provides detailed logging:
200
+
201
+ - โœ… Peer connections
202
+ - ๐Ÿ“จ Message routing
203
+ - ๐Ÿ“ข Peer announcements
204
+ - ๐Ÿ”Œ Disconnections
205
+ - โŒ Errors
206
+
207
+ ## Architecture
208
+
209
+ ```
210
+ Browser Client 1 Browser Client 2 Browser Client N
211
+ | | |
212
+ v v v
213
+ WebSocket WebSocket WebSocket
214
+ | | |
215
+ +-------------------+-------------------+
216
+ |
217
+ Local WebSocket Server
218
+ |
219
+ In-Memory Storage
220
+ (peers, connections)
221
+ ```
222
+
223
+ ## Comparison with AWS
224
+
225
+ | Feature | Local Server | AWS WebSocket |
226
+ |---------|-------------|---------------|
227
+ | Cost | Free | Pay per message |
228
+ | Scalability | Single machine | Auto-scaling |
229
+ | Persistence | In-memory | DynamoDB |
230
+ | Deployment | Local only | Global |
231
+ | Development | Instant | Deploy cycle |
232
+
233
+ ## Troubleshooting
234
+
235
+ ### Common Issues
236
+
237
+ 1. **Connection Refused**: Check if server is running on correct port
238
+ 2. **Invalid Peer ID**: Ensure peer ID is 40-character hex string
239
+ 3. **Message Not Delivered**: Check if target peer is connected
240
+ 4. **Server Won't Start**: Check if port is already in use
241
+
242
+ ### Debug Commands
243
+
244
+ ```bash
245
+ # Check if port is in use
246
+ lsof -i :3000
247
+
248
+ # Kill process on port
249
+ kill -9 $(lsof -t -i:3000)
250
+
251
+ # Check server logs
252
+ npm start | grep "ERROR"
253
+ ```
254
+
255
+ ## License
256
+
257
+ MIT - Same as PeerPigeon main project
@@ -0,0 +1,193 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Memory Leak Test Script
5
+ *
6
+ * This script helps identify memory leaks by repeatedly connecting and disconnecting
7
+ * multiple peers, monitoring memory usage.
8
+ */
9
+
10
+ import { WebSocket } from 'ws';
11
+
12
+ // Configuration
13
+ const SERVER_URL = 'ws://localhost:3000';
14
+ const NUM_PEERS = 5;
15
+ const CYCLES = 10;
16
+ const CYCLE_DURATION = 5000; // 5 seconds per cycle
17
+
18
+ // Track memory usage
19
+ let initialMemory = 0;
20
+ let cycleCount = 0;
21
+
22
+ // Generate a random 40-character hex peer ID
23
+ function generatePeerId() {
24
+ return Array.from({ length: 40 }, () => Math.floor(Math.random() * 16).toString(16)).join('');
25
+ }
26
+
27
+ // Get memory usage
28
+ function getMemoryUsage() {
29
+ if (typeof process !== 'undefined' && process.memoryUsage) {
30
+ return process.memoryUsage().heapUsed / 1024 / 1024; // MB
31
+ }
32
+ return 0;
33
+ }
34
+
35
+ // Create a test peer that will be disconnected
36
+ function createTestPeer(peerId) {
37
+ return new Promise((resolve, reject) => {
38
+ const ws = new WebSocket(`${SERVER_URL}?peerId=${peerId}`);
39
+ let pingInterval;
40
+
41
+ ws.on('open', () => {
42
+ console.log(`โœ… Peer ${peerId.substring(0, 8)}... connected`);
43
+
44
+ // Send announcement
45
+ ws.send(JSON.stringify({
46
+ type: 'announce',
47
+ data: { peerId }
48
+ }));
49
+
50
+ // Send periodic pings
51
+ pingInterval = setInterval(() => {
52
+ if (ws.readyState === WebSocket.OPEN) {
53
+ ws.send(JSON.stringify({
54
+ type: 'ping',
55
+ data: { timestamp: Date.now() }
56
+ }));
57
+ }
58
+ }, 2000);
59
+
60
+ resolve({ ws, peerId, pingInterval });
61
+ });
62
+
63
+ ws.on('message', (data) => {
64
+ try {
65
+ const message = JSON.parse(data);
66
+ if (message.type === 'peer-discovered') {
67
+ console.log(`๐Ÿ” Peer ${peerId.substring(0, 8)}... discovered: ${message.data.peerId.substring(0, 8)}...`);
68
+ }
69
+ } catch (error) {
70
+ console.error(`โŒ Parse error for ${peerId.substring(0, 8)}...:`, error);
71
+ }
72
+ });
73
+
74
+ ws.on('close', () => {
75
+ if (pingInterval) {
76
+ clearInterval(pingInterval);
77
+ }
78
+ console.log(`๐Ÿ”Œ Peer ${peerId.substring(0, 8)}... disconnected`);
79
+ });
80
+
81
+ ws.on('error', (error) => {
82
+ if (pingInterval) {
83
+ clearInterval(pingInterval);
84
+ }
85
+ console.error(`โŒ Peer ${peerId.substring(0, 8)}... error:`, error.message);
86
+ reject(error);
87
+ });
88
+ });
89
+ }
90
+
91
+ // Run a single cycle
92
+ async function runCycle() {
93
+ cycleCount++;
94
+ console.log(`\n๐Ÿ”„ Starting cycle ${cycleCount}/${CYCLES}`);
95
+
96
+ // Create peers
97
+ const peers = [];
98
+ for (let i = 0; i < NUM_PEERS; i++) {
99
+ const peerId = generatePeerId();
100
+ try {
101
+ const peer = await createTestPeer(peerId);
102
+ peers.push(peer);
103
+ } catch (error) {
104
+ console.error(`โŒ Failed to create peer ${peerId.substring(0, 8)}...:`, error);
105
+ }
106
+ }
107
+
108
+ console.log(`๐Ÿ“Š Created ${peers.length} peers`);
109
+
110
+ // Wait for cycle duration
111
+ await new Promise(resolve => setTimeout(resolve, CYCLE_DURATION));
112
+
113
+ // Disconnect all peers
114
+ console.log('๐Ÿงน Disconnecting all peers...');
115
+ peers.forEach(({ ws, peerId, pingInterval }) => {
116
+ if (pingInterval) {
117
+ clearInterval(pingInterval);
118
+ }
119
+ if (ws.readyState === WebSocket.OPEN) {
120
+ ws.send(JSON.stringify({
121
+ type: 'goodbye',
122
+ data: { peerId }
123
+ }));
124
+ ws.close();
125
+ }
126
+ });
127
+
128
+ // Wait for cleanup
129
+ await new Promise(resolve => setTimeout(resolve, 1000));
130
+
131
+ // Check memory usage
132
+ const currentMemory = getMemoryUsage();
133
+ const memoryDelta = currentMemory - initialMemory;
134
+
135
+ console.log(`๐Ÿ“ˆ Memory usage: ${currentMemory.toFixed(2)} MB (delta: ${memoryDelta > 0 ? '+' : ''}${memoryDelta.toFixed(2)} MB)`);
136
+
137
+ if (memoryDelta > 50) { // Alert if memory increased by more than 50MB
138
+ console.warn(`โš ๏ธ Potential memory leak detected! Memory increased by ${memoryDelta.toFixed(2)} MB`);
139
+ }
140
+ }
141
+
142
+ // Main test function
143
+ async function runMemoryTest() {
144
+ console.log(`๐Ÿš€ Starting memory leak test`);
145
+ console.log(`๐Ÿ“ก Server URL: ${SERVER_URL}`);
146
+ console.log(`๐Ÿ‘ฅ Peers per cycle: ${NUM_PEERS}`);
147
+ console.log(`๐Ÿ”„ Cycles: ${CYCLES}`);
148
+ console.log(`โฑ๏ธ Cycle duration: ${CYCLE_DURATION / 1000} seconds`);
149
+
150
+ // Record initial memory
151
+ initialMemory = getMemoryUsage();
152
+ console.log(`๐Ÿ“Š Initial memory usage: ${initialMemory.toFixed(2)} MB`);
153
+
154
+ // Run cycles
155
+ for (let i = 0; i < CYCLES; i++) {
156
+ try {
157
+ await runCycle();
158
+ } catch (error) {
159
+ console.error(`โŒ Cycle ${i + 1} failed:`, error);
160
+ }
161
+ }
162
+
163
+ // Final memory check
164
+ const finalMemory = getMemoryUsage();
165
+ const totalDelta = finalMemory - initialMemory;
166
+
167
+ console.log(`\n๐Ÿ“Š Final Results:`);
168
+ console.log(`Initial memory: ${initialMemory.toFixed(2)} MB`);
169
+ console.log(`Final memory: ${finalMemory.toFixed(2)} MB`);
170
+ console.log(`Total delta: ${totalDelta > 0 ? '+' : ''}${totalDelta.toFixed(2)} MB`);
171
+
172
+ if (totalDelta > 100) {
173
+ console.error(`โŒ Memory leak detected! Total increase: ${totalDelta.toFixed(2)} MB`);
174
+ process.exit(1);
175
+ } else {
176
+ console.log(`โœ… Memory usage appears stable (increase: ${totalDelta.toFixed(2)} MB)`);
177
+ process.exit(0);
178
+ }
179
+ }
180
+
181
+ // Handle errors
182
+ process.on('uncaughtException', (error) => {
183
+ console.error('โŒ Uncaught Exception:', error);
184
+ process.exit(1);
185
+ });
186
+
187
+ process.on('unhandledRejection', (reason, promise) => {
188
+ console.error('โŒ Unhandled Rejection at:', promise, 'reason:', reason);
189
+ process.exit(1);
190
+ });
191
+
192
+ // Run the test
193
+ runMemoryTest().catch(console.error);
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "local-websocket-server",
3
+ "version": "1.0.0",
4
+ "lockfileVersion": 3,
5
+ "requires": true,
6
+ "packages": {
7
+ "node_modules/ws": {
8
+ "version": "8.18.3",
9
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",
10
+ "integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",
11
+ "license": "MIT",
12
+ "engines": {
13
+ "node": ">=10.0.0"
14
+ },
15
+ "peerDependencies": {
16
+ "bufferutil": "^4.0.1",
17
+ "utf-8-validate": ">=5.0.2"
18
+ },
19
+ "peerDependenciesMeta": {
20
+ "bufferutil": {
21
+ "optional": true
22
+ },
23
+ "utf-8-validate": {
24
+ "optional": true
25
+ }
26
+ }
27
+ }
28
+ }
29
+ }
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2011 Einar Otto Stangvik <einaros@gmail.com>
2
+ Copyright (c) 2013 Arnout Kazemier and contributors
3
+ Copyright (c) 2016 Luigi Pinca and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.