-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
190 lines (182 loc) · 6.26 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import {ProtoDef, Serializer, Parser} from 'protodef';
import Logger from '@meteor-it/logger';
import {isBrowser} from '@meteor-it/platform';
const potatoLogger=new Logger('potato');
// Converts potato packet description to protodef acceptable
function convertObj(data) {
let dataOut=[];
Object.keys(data).forEach(key=>{
dataOut.push({
"name": key,
"type": convertAll(data[key])
});
});
return ["container", dataOut];
}
function convertArray(data){
if(data.length!==1)
throw new Error('Array can contain items only of one type!');
return [
"array",
{
"countType": "i32",
"type": data[0]
}
];
}
function convertAll(data){
if(typeof data === 'string')
return data;
if(data instanceof Array)
return convertArray(data);
if(typeof data === 'object')
return convertObj(data);
}
function convertDescription(description) {
potatoLogger.debug('convertDescription IN: ',description);
let data=convertAll(description);
potatoLogger.debug('convertDescription OUT: ',data);
return data;
}
// Calls the RPC methon on socket
function callRPC(socket, name, args) {
throw new Error('RPC is WorkInProgress');
// if(name==='then')
// return;
// socket.emit('rpc_call',{
// functionName: name,
// args:AJSON.stringify(args)
// });
}
// Generates socket id
function getSocketId() {
return new Promise((res,rej)=>{
if(isBrowser){
var array = new Uint8Array(32);
window.crypto.getRandomValues(array);
btoa(array).replace(/\//g,'a').replace(/\+/g,'a').replace(/\=/g, '')
}
else {
// TODO: Use webpack?
require('crypto').randomBytes(32, (ex, buf)=>res(buf.toString('base64').replace(/\//g,'a').replace(/\+/g,'a').replace(/\=/g, '')));
}
});
}
// function getCallbackId() {
// return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, char=>{
// let random = Math.random()*16|0;
// let outChr = char == 'x' ? random : (random&0x3|0x8);
// return outChr.toString(16);
// });
// }
export async function createPotatoSocket(socket) {
let packetId=0;
const protocol = {
"container": "native",
"varint": "native",
"byte": "native",
"bool": "native",
"switch": "native",
"string": "cstring",
"packet": [
"container", [{
"name": "name",
"type": [
"mapper", {
"type": "varint",
"mappings": {}
}
]
}, {
"name": "params",
"type": [
"switch", {
"compareTo": "name",
"fields": {}
}
]
}]
]
};
const proto = new ProtoDef();
let parser = null;
let serializer = null;
// body...
const target = {
id:await getSocketId(),
declarationFinished: false,
then:null,
end(...data){
socket.close(...data);
},
emit(name, data) {
if (!target.declarationFinished)
return potatoLogger.error('emit(): Declaration of socket is not finished before usage! Call finishDeclaration before doing anything with socket!',new Error().stack);
potatoLogger.debug('emit()');
serializer.write({
name: name,
params: data
});
potatoLogger.debug('/emit()');
},
eventListeners:{},
on(name, handler) {
if (!target.declarationFinished)
return potatoLogger.error('on(): Declaration of socket is not finished before usage! Call finishDeclaration before doing anything with socket!');
potatoLogger.debug('on(%s)',name);
if(!target.eventListeners[name])
target.eventListeners[name]=[];
target.eventListeners[name].push(handler);
potatoLogger.debug('/on()');
},
addPacket(name, description) {
if (target.declarationFinished)
return potatoLogger.error('addPacket(): Socket declaration is already finished!');
potatoLogger.log('Added packet: %s',name.blue);
description=convertDescription(description);
let id=packetId++;
id=id.toString(10);
protocol.packet[1][0].type[1].mappings[id]=name;
protocol.packet[1][1].type[1].fields[name]=name;
protocol[name]=description;
potatoLogger.debug('addPacket(id: %d, fieldCount: %d)',id,description.length);
},
finishDeclaration() {
if (target.declarationFinished)
return potatoLogger.error('finishDeclaration(): Socket declaration is already finished!');
potatoLogger.log('Done declaration');
proto.addTypes(protocol);
potatoLogger.log('Done adding');
parser = new Parser(proto, "packet");
parser.on('data',data=>{
data=data.data;
let eventName=data.name;
if(!target.eventListeners[eventName])
return potatoLogger.warn('No listeners defined for %s',eventName);
let eventData=data.params;
target.eventListeners[eventName].forEach(eventListener=>{
eventListener(eventData);
});
});
serializer = new Serializer(proto, "packet");
serializer.on('data',(a)=>{
socket.send(new Uint8Array(a).buffer); // Convert to arrayBuffer and send
});
socket.on('message',m=>{
parser.write(new Buffer(m.data));
});
potatoLogger.log('Done finishing');
target.declarationFinished = true;
}
};
//console.log(target.id);
// target.addPacket('rpc_call',{
// functionName:'string',
// args:'string'
// });
return new Proxy(target, {
get(target, name) {
return name in target ? target[name] : (...props) => callRPC(target, name, props);
}
});
};