-
Notifications
You must be signed in to change notification settings - Fork 0
/
panrpc-example-tcp-nested-server-cli.ts
284 lines (233 loc) · 6.4 KB
/
panrpc-example-tcp-nested-server-cli.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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
/* eslint-disable no-console */
import { env, exit, stdin, stdout } from "process";
import { createInterface } from "readline/promises";
import { parse } from "url";
// eslint-disable-next-line import/no-extraneous-dependencies
import { JSONParser } from "@streamparser/json-whatwg";
import { Socket, createServer } from "net";
import { ILocalContext, IRemoteContext, Registry } from "../index";
class TimeLocal {
constructor() {
this.GetSystemTime = this.GetSystemTime.bind(this);
}
// eslint-disable-next-line class-methods-use-this, @typescript-eslint/no-unused-vars
async GetSystemTime(ctx: ILocalContext): Promise<number> {
console.log("Getting system time");
return Math.floor(Date.now() / 1000);
}
}
class Local {
#counter = 0;
constructor(public Time: TimeLocal) {
this.Increment = this.Increment.bind(this);
}
async Increment(ctx: ILocalContext, delta: number): Promise<number> {
console.log(
"Incrementing counter by",
delta,
"for remote with ID",
ctx.remoteID
);
this.#counter += delta;
return this.#counter;
}
}
class Remote {
// eslint-disable-next-line class-methods-use-this, @typescript-eslint/no-unused-vars, @typescript-eslint/no-empty-function
async Println(ctx: IRemoteContext, msg: string) {}
}
let clients = 0;
const registry = new Registry(
new Local(new TimeLocal()),
new Remote(),
{
onClientConnect: () => {
clients++;
console.log(clients, "clients connected");
},
onClientDisconnect: () => {
clients--;
console.log(clients, "clients connected");
},
}
);
(async () => {
console.log(`Enter one of the following letters followed by <ENTER> to run a function on the remote(s):
- a: Print "Hello, world!
`);
const rl = createInterface({ input: stdin, output: stdout });
// eslint-disable-next-line no-constant-condition
while (true) {
const line =
// eslint-disable-next-line no-await-in-loop
await rl.question("");
// eslint-disable-next-line no-await-in-loop
await registry.forRemotes(async (remoteID, remote) => {
console.log("Calling functions for remote with ID", remoteID);
switch (line) {
case "a":
try {
// eslint-disable-next-line no-await-in-loop
await remote.Println(undefined, "Hello, world!");
} catch (e) {
console.error(`Got error for Increment func: ${e}`);
}
break;
default:
console.log(`Unknown letter ${line}, ignoring input`);
}
});
}
})();
const addr = env.ADDR || "127.0.0.1:1337";
const listen = env.LISTEN !== "false";
if (listen) {
const u = parse(`tcp://${addr}`);
const server = createServer(async (socket) => {
socket.on("error", (e) => {
console.error("Client disconnected with error:", e);
});
const linkSignal = new AbortController();
const encoder = new WritableStream({
write(chunk) {
return new Promise<void>((res) => {
const isDrained = socket.write(JSON.stringify(chunk));
if (!isDrained) {
socket.once("drain", res);
} else {
res();
}
});
},
close() {
return new Promise((res) => {
socket.end(res);
});
},
abort(reason) {
socket.destroy(reason instanceof Error ? reason : new Error(reason));
},
});
const parser = new JSONParser({
paths: ["$"],
separator: "",
});
const parserWriter = parser.writable.getWriter();
const parserReader = parser.readable.getReader();
const decoder = new ReadableStream({
start(controller) {
parserReader
.read()
.then(async function process({ done, value }) {
if (done) {
controller.close();
return;
}
controller.enqueue(value?.value);
parserReader
.read()
.then(process)
.catch((e) => controller.error(e));
})
.catch((e) => controller.error(e));
},
});
socket.on("data", (m) => parserWriter.write(m));
socket.on("close", () => {
parserReader.cancel();
parserWriter.abort();
linkSignal.abort();
});
registry.linkStream(
linkSignal.signal,
encoder,
decoder,
(v) => v,
(v) => v
);
});
server.listen(
{
host: u.hostname as string,
port: parseInt(u.port as string, 10),
},
() => console.log("Listening on", addr)
);
} else {
const u = parse(`tcp://${addr}`);
const socket = new Socket();
socket.on("error", (e) => {
console.error("Disconnected with error:", e.cause);
exit(1);
});
socket.on("close", () => exit(0));
await new Promise<void>((res, rej) => {
socket.connect(
{
host: u.hostname as string,
port: parseInt(u.port as string, 10),
},
res
);
socket.on("error", rej);
});
const linkSignal = new AbortController();
const encoder = new WritableStream({
write(chunk) {
return new Promise<void>((res) => {
const isDrained = socket.write(JSON.stringify(chunk));
if (!isDrained) {
socket.once("drain", res);
} else {
res();
}
});
},
close() {
return new Promise((res) => {
socket.end(res);
});
},
abort(reason) {
socket.destroy(reason instanceof Error ? reason : new Error(reason));
},
});
const parser = new JSONParser({
paths: ["$"],
separator: "",
});
const parserWriter = parser.writable.getWriter();
const parserReader = parser.readable.getReader();
const decoder = new ReadableStream({
start(controller) {
parserReader
.read()
.then(async function process({ done, value }) {
if (done) {
controller.close();
return;
}
controller.enqueue(value?.value);
parserReader
.read()
.then(process)
.catch((e) => controller.error(e));
})
.catch((e) => controller.error(e));
},
});
socket.on("data", (m) => parserWriter.write(m));
socket.on("close", () => {
parserReader.cancel();
parserWriter.abort();
linkSignal.abort();
});
registry.linkStream(
linkSignal.signal,
encoder,
decoder,
(v) => v,
(v) => v
);
console.log("Connected to", addr);
}