Connection bug fix / More than debugging

This commit is contained in:
Abdussamed 2024-03-21 09:25:31 +03:00
parent 63f054f6bf
commit 2439907c59
11 changed files with 72 additions and 460 deletions

View File

@ -101,6 +101,7 @@ Client.prototype.isSecure = function(client)
client = Client.clients.get(client); client = Client.clients.get(client);
}else return false; }else return false;
}else if(!(client instanceof Client)){ }else if(!(client instanceof Client)){
console.error("isSecure Client bir client veri tipinde değil")
return false; return false;
}; };
@ -200,7 +201,16 @@ Client.prototype.send = function(obj){
CLIENT_SEND_MESSAGE(this.id, obj, this.proxyProcess) CLIENT_SEND_MESSAGE(this.id, obj, this.proxyProcess)
}else{ }else{
stats.ws_sended_packs++; stats.ws_sended_packs++;
this.socket.sendUTF(JSON.stringify(obj)); if(this.socket.connected){
this.socket.sendUTF(JSON.stringify(obj),err => {
if(err && this.socket)
{
console.error("I/O: Hatalı yazma işlemi yapıldı",err.message)
}
});
}else{
console.error("Bağlantısı kopmuş yazma işlemi")
}
} }
}; };

View File

@ -10,7 +10,12 @@ process.on('message',data => {
client.isProxy = true; client.isProxy = true;
client.proxyProcess = data.pid; client.proxyProcess = data.pid;
client.id = data.uuid; client.id = data.uuid;
if(Client.clients.has(client.id))
{
console.error("IPC: Zaten var olan kullanıcı oluşturuluyor")
}else{
Client.clients.set(client.id, client); Client.clients.set(client.id, client);
}
break; break;
} }
case "CLIENT_UPDATE_PROP":{ case "CLIENT_UPDATE_PROP":{
@ -25,15 +30,27 @@ process.on('message',data => {
case "CLIENT_SEND_MESSAGE":{ case "CLIENT_SEND_MESSAGE":{
//slog("CLIENT_SEND_MESSAGE"); //slog("CLIENT_SEND_MESSAGE");
let client = Client.clients.get(data.uuid); let client = Client.clients.get(data.uuid);
if(client)
{
if(client.isProxy != true) if(client.isProxy != true)
{ {
client.send(data.message) client.send(data.message)
}else{
console.error("IPC: Proxy olmayan bir client için IPC mesajı alındı")
}
}else{
console.error("IPC: Olmayan bir kullanıcı için mesaj gönderiliyor")
} }
break; break;
} }
case "CLIENT_DESTROY":{ case "CLIENT_DESTROY":{
slog("CLIENT_DESTROY"); slog("CLIENT_DESTROY");
if(Client.clients.has(data.uuid))
{
Client.clients.delete(data.uuid); Client.clients.delete(data.uuid);
}else{
console.error("IPC: Olmayan bir kullanıcı için silme gerçekleştiriliyor")
}
break; break;
} }
case "ROOM_CREATED":{ case "ROOM_CREATED":{

View File

@ -29,6 +29,7 @@ addService(({
let {to,pack,handshake} = message; let {to,pack,handshake} = message;
if(!client.packReadable()){ if(!client.packReadable()){
console.error("Okunabilir olmayan client bir mesaj iletiyor")
handshake && end({ handshake && end({
type: 'fail' type: 'fail'
}) })
@ -39,12 +40,14 @@ addService(({
let otherPeer = Client.clients.get(to); let otherPeer = Client.clients.get(to);
if(otherPeer.requiredPair && !otherPeer.pairs.has(to)) if(otherPeer.requiredPair && !otherPeer.pairs.has(to))
{ {
console.error("Client, güvenilir olmayan bir cliente mesaj iletiyor")
return handshake && end({ return handshake && end({
type: 'fail' type: 'fail'
}) })
} }
if(!otherPeer.packWriteable()){ if(!otherPeer.packWriteable()){
console.error("Client, yazılabilir olmayan bir cliente mesaj iletiyor")
handshake && end({ handshake && end({
type: 'fail' type: 'fail'
}) })
@ -57,6 +60,7 @@ addService(({
type: 'success' type: 'success'
}) })
}else{ }else{
console.error("Client, olmayan bir cliente mesaj iletiyor")
handshake && end({ handshake && end({
type: 'fail' type: 'fail'
}) })
@ -70,6 +74,7 @@ addService(({
let otherPeer = Client.clients.get(to); let otherPeer = Client.clients.get(to);
if(otherPeer.requiredPair && !otherPeer.pairs.has(to)) if(otherPeer.requiredPair && !otherPeer.pairs.has(to))
{ {
console.error("response istenen peer güvenli değil")
return; return;
} }
otherPeer.send([{ otherPeer.send([{
@ -87,6 +92,7 @@ addService(({
let otherPeer = Client.clients.get(to); let otherPeer = Client.clients.get(to);
if(otherPeer.requiredPair && !otherPeer.pairs.has(to)) if(otherPeer.requiredPair && !otherPeer.pairs.has(to))
{ {
console.error("response istenen peer güvenli değil")
return; return;
} }
otherPeer.send([{ otherPeer.send([{
@ -101,6 +107,7 @@ addService(({
if(!client.packReadable()){ if(!client.packReadable()){
console.error("Client paketi okumak için müsait değil")
handshake && end({ handshake && end({
type: 'fail' type: 'fail'
}) })
@ -110,6 +117,7 @@ addService(({
{ {
if(!client.rooms.has(to)) if(!client.rooms.has(to))
{ {
console.error("Client katılmadığı bir odaya mesaj iletiyor")
return handshake && end({ return handshake && end({
type: 'fail' type: 'fail'
}) })
@ -129,6 +137,7 @@ addService(({
type: 'success' type: 'success'
}) })
}else{ }else{
console.error("Olmayan oda için veri gönderme isteniyor")
handshake && end({ handshake && end({
type: 'fail' type: 'fail'
}) })

View File

@ -227,7 +227,7 @@ Room.prototype.eject = function(client){
}, },
'room/ejected' 'room/ejected'
], ],
void 0, client.id,
client => client.peerInfoNotifiable() client => client.peerInfoNotifiable()
); );
} }

View File

@ -63,7 +63,7 @@ wsServer.addListener("connect",(socket) => {
stats.mwse_clients--; stats.mwse_clients--;
emit("disconnect", global, xClient); emit("disconnect", global, xClient);
CLIENT_DESTROY(id); CLIENT_DESTROY(id);
Client.clients.set(id, xClient); Client.clients.delete(id);
clearInterval(timer); clearInterval(timer);
clearInterval(pingTimer); clearInterval(pingTimer);
}); });

View File

@ -8,15 +8,15 @@ require("./Services/DataTransfer.js");
require("./Services/IPPressure.js"); require("./Services/IPPressure.js");
require("./Services/Session.js"); require("./Services/Session.js");
process.on('unhandledRejection',()=>{ process.on('unhandledRejection',(reason, promise)=>{
console.log("Process unhandledRejection",{reason, promise})
}); });
process.on('rejectionHandled',()=>{ process.on('rejectionHandled',(promise)=>{
console.log("Process rejectionHandled",{promise})
}); });
process.on('multipleResolves',()=>{ process.on('multipleResolves',(type, promise, value)=>{
console.log("Process multipleResolves",{type, promise, value})
}); });
process.on('warning',()=>{ process.on('warning',(err)=>{
console.log("Process warning", err)
}); });

View File

@ -4,6 +4,8 @@ export interface IConnection{
timeout: number; timeout: number;
} }
} }
const RootURL : string = ( <HTMLScriptElement> document.currentScript).src
export class Connection export class Connection
{ {
public ws! : WebSocket; public ws! : WebSocket;
@ -15,7 +17,23 @@ export class Connection
public autoReconnectTimeout : number = 3000; public autoReconnectTimeout : number = 3000;
public autoReconnectTimer? : number; public autoReconnectTimer? : number;
constructor(options: IConnection){ constructor(options: IConnection){
if(options.endpoint == "auto")
{
let scriptPath = new URL(RootURL);
let isSecurity = scriptPath.protocol == "https:";
let dumeUrl = scriptPath.pathname.split('/').slice(0,-1).join('/') + '/';
let wsSocket = new URL(dumeUrl, scriptPath);
wsSocket.protocol = isSecurity ? 'wss:' : 'ws:';
this.endpoint = new URL(wsSocket.href);
}else{
try{
// Testing
this.endpoint = new URL(options.endpoint); this.endpoint = new URL(options.endpoint);
}catch{
throw new Error("endpoint is required")
}
}
if(typeof options.autoReconnect == "boolean") if(typeof options.autoReconnect == "boolean")
{ {
this.autoReconnect = true; this.autoReconnect = true;

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,41 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2><pre id="log"></pre></h2>
<h1 id="message"></h1>
<script src="http://localhost:7707/script"></script>
<script>
async function main(){
const wsjs = new MWSE({
endpoint: "ws://localhost:7707"
});
wsjs.scope(async ()=>{
let me = wsjs.peer('me');
me.disablePairAuth();
let room = wsjs.datastore({
type: 'temp',
sha256: 'f1290186a5d0b1ceab27f4e77c0c5d68'
});
});
};
function gg()
{
log.innerHTML = `${gg.w} packet writed\n${gg.r} packet recaived`
}
gg.w = 0;
gg.r = 0;
/*setInterval(()=>{
window.location.reload();
}, 30000)*/
main();
</script>
</body>
</html>

View File

@ -1,401 +0,0 @@
function WebRTC()
{
this.id = null;
this.active = false;
this.connectionStatus = "";
this.iceStatus = "";
this.gatheringStatus = "";
this.signalingStatus = "";
this.rtc = new RTCPeerConnection({
iceCandidatePoolSize: 0,
iceTransportPolicy:"all",
rtcpMuxPolicy:"require",
iceServers:[{
urls: "stun:stun.l.google.com:19302"
},{
urls: "stun:stun1.l.google.com:19302"
},{
urls: "stun:stun2.l.google.com:19302"
},{
urls: "stun:stun3.l.google.com:19302"
},{
urls: "stun:stun4.l.google.com:19302"
}]
});
/**
* @type {Map<string, {stream:MediaStream?,id:string,name:string}>}
*/
this.recaivingStream = new Map();
/**
* @type {Map<string, {stream:MediaStream?,id:string,name:string}>}
*/
this.sendingStream = new Map();
this.rtc.addEventListener("connectionstatechange",(...args)=>{
this.eventConnectionState(...args);
})
this.rtc.addEventListener("icecandidate",(...args)=>{
this.eventIcecandidate(...args);
})
this.rtc.addEventListener("iceconnectionstatechange",(...args)=>{
this.eventICEConnectionState(...args);
})
this.rtc.addEventListener("icegatheringstatechange",(...args)=>{
this.eventICEGatherinState(...args);
})
this.rtc.addEventListener("negotiationneeded",(...args)=>{
this.eventNogationNeeded(...args);
})
this.rtc.addEventListener("signalingstatechange",(...args)=>{
this.eventSignalingState(...args);
})
this.rtc.addEventListener("track",(...args)=>{
this.eventTrack(...args);
})
this.rtc.addEventListener("datachannel",(...args)=>{
this.eventDatachannel(...args);
})
let events = {};
/**
* @param {Function} callback
*/
this.addEventListener = function(event,callback){
(events[event] || (events[event]=[])).push(callback);
};
this.on = this.addEventListener;
this.dispatch = async (event,...args) => {
if(events[event]) for (const callback of events[event]) {
await callback(...args)
}
}
this.emit = this.dispatch;
/**
* @type {RTCDataChannel}
*/
this.channel = null;
this.on('input',async (data)=>{
switch(data.type)
{
case "icecandidate":{
await this.rtc.addIceCandidate(new RTCIceCandidate(data.value));
break;
}
case "offer":{
await this.rtc.setRemoteDescription(new RTCSessionDescription(data.value));
let answer = await this.rtc.createAnswer({
offerToReceiveAudio: true,
offerToReceiveVideo: true
})
await this.rtc.setLocalDescription(answer);
this.send({
type: 'answer',
value: answer
});
break;
}
case "answer":{
await this.rtc.setRemoteDescription(new RTCSessionDescription(data.value))
break;
}
case "streamInfo":{
let {id,value} = data;
if(!this.recaivingStream.has(id))
{
this.recaivingStream.set(id,{
stream: null
});
};
Object.assign(this.recaivingStream.get(id), value);
this.send({
type:'streamAccept',
id
})
break;
}
case "streamRemoved":{
let {id} = data;
this.emit('stream:stopped', this.recaivingStream.get(id));
this.sendingStream.delete(id);
break;
}
case "streamAccept":{
let {id} = data;
let {stream} = this.sendingStream.get(id);
let senders = [];
for (const track of stream.getTracks()) {
senders.push(this.rtc.addTrack(track, stream));
};
stream.senders = senders;
break;
}
case "message":{
this.emit('message', data.payload);
break;
}
}
})
};
WebRTC.channels = new Map();
WebRTC.prototype.connect = function(object){
if(!this.channel)
{
this.createDefaultDataChannel();
}
};
WebRTC.prototype.sendMessage = function(object){
this.send({
type:'message',
payload: object
});
};
WebRTC.prototype.createDefaultDataChannel = function(){
let dt = this.rtc.createDataChannel(":default:",{
ordered: true
});
dt.addEventListener("open",()=>{
this.channel = dt;
console.log(...rtcLabel, this.id, dt.label + ' veri kanalııldı');
WebRTC.channels.set(this.id, this);
});
dt.addEventListener("message",({data})=>{
let pack = JSON.parse(data);
console.log(...rtcLabel, this.id, dt.label + ' P2P Pack ', pack);
this.emit('input', pack);
})
dt.addEventListener("close",()=>{
this.channel = null;
console.log(...rtcLabel, this.id, dt.label + ' veri kanalı kapandı');
})
};
WebRTC.prototype.destroy = function(){
this.active = false;
if(this.channel)
{
this.channel.close();
this.channel = null;
}
if(this.rtc)
{
this.rtc.close();
this.rtc = null;
};
this.emit('disconnected');
WebRTC.channels.delete(this.id);
}
/**
*
* @param {RTCDataChannelEvent} event
*/
WebRTC.prototype.eventDatachannel = function(event){
console.log(...rtcLabel, this.id, event.channel.label + ' veri kanalııldı');
if(event.channel.label == ':default:'){
WebRTC.channels.set(this.id, this);
this.channel = event.channel
}
event.channel.addEventListener("message",({data})=>{
let pack = JSON.parse(data);
console.log(...rtcLabel, this.id, event.channel.label + ' P2P Pack ', pack);
this.emit('input', pack);
})
event.channel.addEventListener("close",()=>{
this.channel = null;
WebRTC.channels.delete(this.id);
WebRTC.requireGC = true;
console.log(...rtcLabel, this.id, event.channel.label + ' veri kanalı kapandı');
})
};
WebRTC.requireGC = false;
setInterval(()=>{
if(WebRTC.requireGC == false) return;
let img = document.createElement("img");
img.src = window.URL.createObjectURL(new Blob([new ArrayBuffer(5e+7)]));
img.onerror = function() {
window.URL.revokeObjectURL(this.src);
img = null;
console.log("WebRTC Pool connections garbage connection microtask completed")
};
WebRTC.requireGC = false;
}, 3000)
WebRTC.prototype.send = function(object){
if(this.channel?.readyState == "open")
{
this.channel.send(JSON.stringify(object));
}else{
this.emit('output', object);
}
};
let rtcLabel = ["%cRTC","color:red;font-weight:bold"];
WebRTC.prototype.eventConnectionState = function(){
this.connectionStatus = this.rtc.connectionState;
if(this.connectionStatus == 'connected')
{
if(this.active == false)
{
this.emit('connected');
this.active = true;
}
};
if(this.connectionStatus == 'failed' || this.connectionStatus == "disconnected" || this.connectionStatus == "closed")
{
if(this.active)
{
this.destroy();
}
}
console.log(...rtcLabel, this.id, "connectionStatus", this.connectionStatus)
};
/**
*
* @param {RTCPeerConnectionIceEvent} event
*/
WebRTC.prototype.eventIcecandidate = function(event){
console.log(...rtcLabel, this.id, 'ice created');
if(event.candidate)
{
this.send({
type:'icecandidate',
value: event.candidate
})
}
};
WebRTC.prototype.eventICEConnectionState = function(){
this.iceStatus = this.rtc.iceConnectionState;
console.log(...rtcLabel, this.id, "iceStatus",this.iceStatus)
};
WebRTC.prototype.eventICEGatherinState = function(){
this.gatheringStatus = this.rtc.iceGatheringState;
console.log(...rtcLabel, this.id, "gatheringStatus",this.gatheringStatus)
};
WebRTC.prototype.eventNogationNeeded = async function(){
console.log(...rtcLabel, this.id, "requested nogation");
let offer = await this.rtc.createOffer({
iceRestart: true,
offerToReceiveAudio: true,
offerToReceiveVideo: true
});
await this.rtc.setLocalDescription(offer);
this.send({
type: 'offer',
value: offer
});
};
WebRTC.prototype.eventSignalingState = function(){
this.signalingStatus = this.rtc.signalingState;
console.log(...rtcLabel, this.id, "signalingStatus",this.signalingStatus)
};
/**
* @param {RTCTrackEvent} event
*/
WebRTC.prototype.eventTrack = function(event){
if(event.streams.length)
{
for (const stream of event.streams) {
if(this.recaivingStream.get(stream.id).stream == null)
{
this.recaivingStream.get(stream.id).stream = stream;
this.emit('stream:added', this.recaivingStream.get(stream.id));
}else{
this.recaivingStream.get(stream.id).stream = stream;
}
}
}
};
/**
* @param {MediaStream} stream
* @param {string} name
* @param {any} info
*/
WebRTC.prototype.sendStream = function(stream,name,info){
this.send({
type: 'streamInfo',
id: stream.id,
value: {
...info,
name: name
}
});
this.sendingStream.set(stream.id,{
...info,
name: name,
stream
});
};
/**
* @param {MediaStream} stream
* @param {string} name
* @param {any} info
*/
WebRTC.prototype.stopStream = function(_stream){
if(this.connectionStatus != 'connected'){
return
}
if(this.sendingStream.has(_stream.id))
{
let {stream} = this.sendingStream.get(_stream.id);
for (const track of stream.getTracks()) {
for (const RTCPSender of this.rtc.getSenders()) {
if(RTCPSender.track?.id == track.id)
{
this.rtc.removeTrack(RTCPSender);
}
}
}
this.send({
type: 'streamRemoved',
id: stream.id
});
this.sendingStream.delete(_stream.id)
}
};
/**
* @param {string} name
* @param {any} info
*/
WebRTC.prototype.stopAllStreams = function(){
if(this.connectionStatus != 'connected'){
return
}
for (const [id, {stream}] of this.sendingStream) {
for (const track of stream.getTracks()) {
for (const RTCPSender of this.rtc.getSenders()) {
if(RTCPSender.track?.id == track.id)
{
this.rtc.removeTrack(RTCPSender);
}
}
}
this.send({
type: 'streamRemoved',
id: stream.id
});
};
this.sendingStream.clear();
};
WebRTC.getCamera = async (options) => {
return navigator.mediaDevices.getUserMedia({
video: options || {
frameRate: 10,
width: 640,
height: 480
}
})
}
WebRTC.getMicrophone = async (options) => {
return navigator.mediaDevices.getUserMedia({
audio: options || {
channelCount: 1,
sampleRate: 16000,
sampleSize: 16,
volume: 1
}
})
}
WebRTC.getDisplay = async (videoOptions) => {
return navigator.mediaDevices.getDisplayMedia({
video: videoOptions || true
})
}