forked from webxdc/webxdc-dev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinstance.ts
225 lines (197 loc) · 5.46 KB
/
instance.ts
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import expressWs from "express-ws";
import { WebSocket, Server } from "ws";
import { JsonValue, ReceivedUpdate } from "../types/webxdc";
import { createProcessor, IProcessor, WebXdcMulti, OnMessage } from "./message";
import { Location } from "./location";
import { createPeer, InjectExpress } from "./app";
import { AppInfo } from "./appInfo";
import { getColorForId } from "./color";
import { Instance as FrontendInstance } from '../types/instance';
export type Options = {
basePort: number;
csp: boolean;
verbose: boolean;
};
type SendUpdateMessage = {
type: "sendUpdate";
update: ReceivedUpdate<JsonValue>;
descr: string;
};
type SetUpdateListenerMessage = {
type: "setUpdateListener";
serial: number;
};
type RequestInfoMessage = {
type: "requestInfo";
};
class Instance {
id: string;
color: string;
server: any;
constructor(
public app: expressWs.Application,
public port: number,
public url: string,
public webXdc: WebXdcMulti
) {
this.id = port.toString();
this.color = getColorForId(this.id);
}
start() {
this.server = this.app.listen(this.port, () => {
console.log(`Starting webxdc instance at port ${this.port}`);
});
}
close() {
this.server.close()
}
}
export class Instances {
location: Location;
appInfo: AppInfo;
instances: Map<number, Instance>;
basePort: number;
currentPort: number;
csp: boolean;
injectSim: InjectExpress;
processor: IProcessor;
_onMessage: OnMessage | null = null;
constructor(appInfo: AppInfo, injectSim: InjectExpress, options: Options) {
this.location = appInfo.location;
this.appInfo = appInfo;
this.basePort = options.basePort;
this.csp = options.csp;
this.currentPort = options.basePort;
this.instances = new Map();
this.injectSim = injectSim;
this.processor = createProcessor((message) => {
if (this._onMessage == null) {
return;
}
if (options.verbose) {
console.info(message);
}
this._onMessage(message);
});
}
add(): Instance {
this.currentPort++;
const port = this.currentPort;
if (this.instances.has(port)) {
throw new Error(`Already have Webxdc instance at port: ${port}`);
}
const instanceUrl = `http://localhost:${port}`;
const wsInstance = createPeer({
location: this.location,
injectSim: this.injectSim,
csp: this.csp,
instanceUrl: instanceUrl,
});
const app = wsInstance.app;
const instance = new Instance(
app,
port,
instanceUrl,
this.processor.createClient(port.toString())
);
const wss = wsInstance.getWss();
app.ws("/webxdc", (ws, req) => {
// when receiving an update from this peer
ws.on("message", (msg: string) => {
if (typeof msg !== "string") {
console.error(
"webxdc: Don't know how to handle unexpected non-string data"
);
return;
}
const parsed = JSON.parse(msg);
// XXX should validate parsed
if (isSendUpdateMessage(parsed)) {
instance.webXdc.sendUpdate(parsed.update, parsed.descr);
} else if (isSetUpdateListenerMessage(parsed)) {
instance.webXdc.connect(
(updates) => {
return broadcast(
wss,
JSON.stringify({
type: "updates",
updates: updates.map(([update]) => update),
})
);
},
parsed.serial,
() => {
return broadcast(wss, JSON.stringify({ type: "clear" }));
},
() => {
return broadcast(wss, JSON.stringify({ type: "delete" }));
},
);
} else if (isRequestInfoMessage(parsed)) {
ws.send(
JSON.stringify({
type: "info",
info: {
name: this.appInfo.manifest.name,
color: instance.color,
},
})
);
} else {
throw new Error(`Unknown message: ${JSON.stringify(parsed)}`);
}
});
});
this.instances.set(port, instance);
return instance;
}
delete(id: number) {
let instance = this.instances.get(id);
if (instance == null) {
throw new Error(`Instance with id ${id} can't be deleted because it does not exist`);
}
instance.close();
this.processor.removeClient(instance.id);
this.instances.delete(id);
}
start() {
for (const instance of this.instances.values()) {
instance.start();
}
}
clear() {
this.processor.clear();
}
onMessage(onMessage: OnMessage) {
this._onMessage = onMessage;
}
list(): FrontendInstance[]{
return Array.from(this.instances.values()).map((instance) => ({
id: instance.id,
port: instance.port,
url: instance.url,
color: instance.color,
}))
}
}
function broadcast(wss: Server<WebSocket>, data: string): boolean {
let result = false;
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(data);
result = true;
}
});
return result;
}
function isSendUpdateMessage(value: any): value is SendUpdateMessage {
return value.type === "sendUpdate";
}
function isSetUpdateListenerMessage(
value: any
): value is SetUpdateListenerMessage {
return value.type === "setUpdateListener";
}
function isRequestInfoMessage(value: any): value is RequestInfoMessage {
return value.type === "requestInfo";
}