Skip to content

Commit

Permalink
dht peer selection wip
Browse files Browse the repository at this point in the history
  • Loading branch information
slugalisk committed Mar 4, 2019
1 parent 906efd3 commit b7341d6
Show file tree
Hide file tree
Showing 16 changed files with 511 additions and 99 deletions.
4 changes: 2 additions & 2 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"plugins": [
"@babel/plugin-transform-modules-commonjs"
]
"@babel/plugin-transform-modules-commonjs"
]
}
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@
"react-scripts": "2.1.5",
"reconnecting-websocket": "^3.2.2",
"seedrandom": "^2.4.4",
"three": "^0.102.0",
"three-spritetext": "^1.0.6",
"urlsafe-base64": "^1.0.0",
"uuid": "^3.3.2",
"wrtc": "^0.3.5"
Expand All @@ -41,6 +43,7 @@
"test": "react-scripts test --env=jsdom --watch --verbose false",
"eject": "react-scripts eject",
"server": "nodemon --delay 2.5s ./node_modules/.bin/babel-node src/server.js",
"_server": "nodemon ./node_modules/.bin/babel-node src/server.js",
"predeploy": "yarn run build",
"deploy": "gh-pages -d build"
},
Expand Down
16 changes: 11 additions & 5 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,28 @@
import React, {useEffect, useState} from 'react';
import URI from './ppspp/uri';
// import DiagnosticMenu from './DiagnosticMenu';
import SwarmPlayer from './SwarmPlayer';
import {Client} from './client';
import {ConnManager} from './wrtc';
// import {ChunkedReadStream} from './chunkedStream';

import './App.css';

const BOOTSTRAP_ADDRESS = process.env.NODE_ENV === 'development'
? window.location.hostname + ':8080'
: window.location.host;

const App = () => {
const [ppsppClient, setPpsppClient] = useState(null);
const [swarmUri, setSwarmUri] = useState('');
const [swarm, setSwarm] = useState(null);

useEffect(() => {
const connManager = new ConnManager(BOOTSTRAP_ADDRESS);
const proto = window.location.protocol === 'https:' ? 'wss' : 'ws';
const host = process.env.NODE_ENV === 'development'
? window.location.hostname + ':8080'
: window.location.host;
const bootstrapAddress = `${proto}://${host}`;

console.log({bootstrapAddress});

const connManager = new ConnManager(bootstrapAddress);

Client.create(connManager).then(({ppsppClient, swarmUri}) => {
setPpsppClient(ppsppClient);
Expand All @@ -26,6 +31,7 @@ const App = () => {
}, []);

if (swarm) {
// return <DiagnosticMenu swarm={swarm} />;
return <SwarmPlayer swarm={swarm} />;
}

Expand Down
192 changes: 177 additions & 15 deletions src/DhtGraph.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import arrayBufferToHex from 'array-buffer-to-hex';
import ForceGraph3D from 'react-force-graph-3d';
import {schemeCategory10} from 'd3-scale-chromatic';
import {scaleOrdinal} from 'd3-scale';
// import SpriteText from 'three-spritetext';
// import {Mesh, SphereBufferGeometry, MeshLambertMaterial} from 'three';

import './App.css';

Expand All @@ -17,24 +19,74 @@ const reduceGraph = (graph, {type, ...data}) => {
nodes: [...graph.nodes, data],
links: graph.links,
};
case 'REMOVE_NODE':
return {
nodes: graph.nodes.filter(node => node.id !== data.id),
links: graph.links.filter(({source, target}) => {
return source.id !== data.id && target.id !== data.id;
}),
};
case 'ADD_LINK':
return {
nodes: graph.nodes,
links: [...graph.links, data],
links: [...graph.links, {...data, activity: 0}],
};
case 'UPDATE_LINK':
return {
nodes: graph.nodes,
links: graph.links.map((link) => {
const {source, target} = link;
if (source.id !== data.source || target.id !== data.target) {
return link;
}
return {
...link,
...data,
};
}),
};
case 'INCR_LINK_ACTIVITY':
return {
nodes: graph.nodes,
links: graph.links.map((link) => {
const {source, target} = link;
if (source.id !== data.source || target.id !== data.target) {
return link;
}
return {
...link,
activity: link.activity + 1,
};
}),
};
case 'DECR_LINK_ACTIVITY':
return {
nodes: graph.nodes,
links: graph.links.map((link) => {
const {source, target} = link;
if (source.id !== data.source || target.id !== data.target) {
return link;
}
return {
...link,
activity: link.activity - 1,
};
}),
};
case 'REMOVE_LINK':
console.log(data);
return {
nodes: graph.nodes,
links: graph.links.filter(({source, target}) => {
return source !== data.source || target !== data.target;
return source.id !== data.source || target.id !== data.target;
}),
};
default:
return graph;
}
};

const App = () => {
const useGraph = () => {
const [server] = useState(new Server());
const [gen, setGen] = useState(1);
const [graph, dispatchGraphAction] = useReducer(reduceGraph, {nodes: [], links: []});
Expand All @@ -45,45 +97,155 @@ const App = () => {
type: 'ADD_NODE',
id: source,
color: color(0),
dhtClient: server.dhtClient,
});
}, []);

const handleAddPeerClick = (n=1) => {
const addNodes = (n = 1, props = {}) => {
setGen(gen + 1);

Promise.all(new Array(n).fill(0).map(() => Client.create(new ConnManager(server))))
.then(clients => clients.forEach(({dhtClient: {id, channels}}) => {
.then(clients => clients.forEach(({dhtClient}) => {
// if (Math.random() > 0.5) {
// setTimeout(() => dhtClient.close(), Math.random() * 30000);
// }

const {id, allChannels} = dhtClient;
console.log(allChannels);

const source = arrayBufferToHex(id);
dispatchGraphAction({
type: 'ADD_NODE',
id: source,
color: color(gen),
dhtClient,
...props,
});

channels.on('added', ({id}) => dispatchGraphAction({
type: 'ADD_LINK',
source,
target: arrayBufferToHex(id),
dhtClient.on('close', () => dispatchGraphAction({
type: 'REMOVE_NODE',
id: source,
}));
channels.on('removed', ({id}) => dispatchGraphAction({

allChannels.toArray().forEach(({id, conn}) => {
if (conn != null) {
dispatchGraphAction({
type: 'ADD_LINK',
source,
target: arrayBufferToHex(id),
color: conn ? '#fff' : '#66f',
});
}
});

// const registerConnObservers = (target, conn) => {
// const handleMessage = () => {
// dispatchGraphAction({type: 'INCR_LINK_ACTIVITY', source, target});
// setTimeout(() => dispatchGraphAction({type: 'DECR_LINK_ACTIVITY', source, target}), 10000);
// };

// conn.on('message', handleMessage);
// conn.remote.on('message', handleMessage);
// };

allChannels.on('added', ({id, conn}) => {
if (conn != null) {
const target = arrayBufferToHex(id);
dispatchGraphAction({
type: 'ADD_LINK',
source,
target,
color: conn ? '#fff' : '#66f',
});


// registerConnObservers(target, conn);
}
});
allChannels.on('updated', ({conn: oldConn}, {id, conn}) => {
if (conn !== oldConn) {
const target = arrayBufferToHex(id);
// dispatchGraphAction({
// type: 'UPDATE_LINK',
// source,
// target,
// color: conn ? '#fff' : '#66f',
// });

dispatchGraphAction({
type: 'ADD_LINK',
source,
target,
color: conn ? '#fff' : '#66f',
});


// registerConnObservers(target, conn);
}
});
allChannels.on('removed', ({id}) => dispatchGraphAction({
type: 'REMOVE_LINK',
source,
target: arrayBufferToHex(id),
}));
}));
};

return [graph, {addNodes}];
};

const useNodePinger = () => {
const [source, setSource] = useState(null);

const handleNodeClick = node => {
console.log(node);
if (source === null) {
setSource(node);
console.log('set source', arrayBufferToHex(node.dhtClient.id));
return;
}

console.log('pinging %s > %s', arrayBufferToHex(source.dhtClient.id), arrayBufferToHex(node.dhtClient.id))
source.dhtClient.sendPing(node.dhtClient.id, (data) => {
console.log('received ping response', data);
});
setSource(null);
};

return handleNodeClick;
};

const App = () => {
const [graph, {addNodes}] = useGraph();
const handleNodeClick = useNodePinger();

console.log(graph);

// useEffect(() => {
// let n = 1;
// const ivl = setInterval(() => {
// addNodes(1, {color: color(n)});
// if (++ n == 50) {
// clearInterval(ivl);
// }
// }, 1000);
// return () => clearInterval(ivl);
// }, []);

return (
<div>
<div className="graph-buttons">
<button onClick={() => handleAddPeerClick(1)}>add 1 peer</button>
<button onClick={() => handleAddPeerClick(5)}>add 5 peers</button>
<button onClick={() => handleAddPeerClick(10)}>add 10 peers</button>
<button onClick={() => handleAddPeerClick(50)}>add 50 peers</button>
<button onClick={() => addNodes(1)}>add 1 peer</button>
<button onClick={() => addNodes(5)}>add 5 peers</button>
<button onClick={() => addNodes(10)}>add 10 peers</button>
</div>
<ForceGraph3D
graphData={graph}
nodeAutoColorBy="gen"
onNodeClick={handleNodeClick}
linkColor={link => link.color}
linkWidth={1.5}
nodeRelSize={2}
nodeVal={node => node.dhtClient.allChannels.count()}
/>
</div>
);
Expand Down
2 changes: 1 addition & 1 deletion src/DiagnosticMenu/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ class PeerStateTable extends Component {
const rows = values.map(({key, value}) => (
<tr key={key}>
<td className="diagnostic_table__key_cell">{key}</td>
<td>{value}</td>
<td>{String(value)}</td>
</tr>
));

Expand Down
15 changes: 13 additions & 2 deletions src/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,21 @@ export class Client {
this.dhtClient.createChannel(id, client.createDataChannel('dht'));
this.ppsppClient.createChannel(client.createDataChannel('ppspp'));

this.dhtClient.send(id, 'connect.request', {channelId: sub.id}, () => client.init());
const timeout = setTimeout(() => client.close(), 10000);

const init = () => {
clearTimeout(timeout);
client.init();
};

this.dhtClient.send(id, 'connect.request', {channelId: sub.id}, init);
}

handleReceiveConnectRequest({data: {channelId, from}, callback}) {
// if (this.dhtClient.channels.count() > 10) {
// return;
// }

// console.log('handleReceiveConnectRequest', {channelId, from, callback});
const id = new hexToUint8Array(from);
const client = this.connManager.createClient(new dht.SubChannel(this.dhtClient, id, channelId));
Expand All @@ -56,6 +67,6 @@ export class Client {
}
});

callback();
callback({});
}
}
Loading

0 comments on commit b7341d6

Please sign in to comment.