-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
346 lines (278 loc) · 9.69 KB
/
index.ts
File metadata and controls
346 lines (278 loc) · 9.69 KB
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
"use strict";
// import * as util from 'util';
import { Duplex, WritableOptions } from 'stream';
import { EventEmitter } from 'events';
import { isAbsolute } from 'path';
const uwrap = require('bindings')('uwrap');
const debug = require('debug');
//-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----
//--
interface USocketOptions {
path?: string;
fd?: number;
allowHalfOpen?: boolean;
}
interface USocketWriteChunk {
data?: Buffer;
fds?: any[];
callback?: Function;
}
interface ReadResult {
data: Buffer | null;
fds: any[];
}
export class USocket extends Duplex {
private _wrap: any;
private fd: number | undefined;
constructor(opts: string | USocketOptions, cb?: () => void) {
const options: USocketOptions = typeof opts === 'string' ? { path: opts } : opts || {};
// I'm guessing those are internal to node and thus not referenced in @types/node?
// Ignoring for now...
// @ts-ignore
const duplexOpts: WritableOptions = { writableObjectMode: true };
// @ts-ignore
if ("allowHalfOpen" in options) duplexOpts.writable = options.allowHalfOpen;
super(duplexOpts);
debug("new USocket", options);
if (options.fd || options.path) {
this.connect(options, cb);
}
}
_read(size: number): void {
debug("USocket._read", size);
if (this._wrap) this._wrap.resume();
}
_write(chunk: USocketWriteChunk, encoding: string | null, callback: Function): void {
if (!this._wrap) return callback(new Error("USocket not connected"));
let data: Buffer | undefined;
let fds: any[] | undefined;
let cb: Function | undefined;
if (Buffer.isBuffer(chunk)) {
data = chunk.data;
} else if (Array.isArray(chunk)) {
fds = chunk.fds;
} else {
cb = chunk.callback;
data = chunk.data;
fds = chunk.fds;
}
if (data && !Buffer.isBuffer(data)) return callback(new Error("USocket data needs to be a buffer"));
if (fds && !Array.isArray(fds)) return callback(new Error("USocket fds needs to be an array"));
if (cb && typeof cb !== 'function') return callback(new Error("USocket write callback needs to be a function"));
if (!data && !fds) return callback(new Error("USocket write needs data or an array"));
debug("USocket._write", data && data.length, fds);
const r = this._wrap.write(data, fds);
if (r instanceof Error) {
debug("USocket._write error", r);
return callback(r);
} else if (!data || r === data.length) {
if (cb) cb(chunk);
return callback();
}
debug("USocket._write waiting");
this._wrap.drain = this._write.bind(this, { data: data.subarray(r), callback: cb }, encoding, callback);
}
connect(opts: USocketOptions, cb?: () => void): void {
if (this._wrap) throw new Error("connect on already connected USocket");
debug("USocket connect", opts);
this._wrap = new uwrap.USocketWrap(this._wrapEvent.bind(this));
this._wrap.shutdownCalled = false;
this._wrap.endReceived = false;
this._wrap.drain = null;
this._wrap.fds = [];
if (typeof opts.fd === 'number') {
this._wrap.adopt(opts.fd);
this.fd = opts.fd;
return;
}
if (typeof opts === 'string') {
opts = { path: opts };
}
if (typeof opts.path !== 'string') throw new Error("USocket#connect expects string path");
if (!isAbsolute(opts.path)) throw new Error("Provided path must be absolute");
if (typeof cb === 'function') this.once('connected', cb);
this._wrap.connect(opts.path);
}
private _wrapEvent(event: string, a0: any, a1: any): void {
if (event === "connect") {
this.fd = a0;
debug("USocket connected on " + this.fd);
this.emit('connected');
}
if (event === "error") {
debug("USocket error", a0);
this._wrap.close();
this._wrap = null;
this.emit("error", a0);
this.emit('close', a0);
}
if (event === "data") {
if (a1 && a1.length > 0) {
debug("USocket received file descriptors", a1);
this._wrap.fds = this._wrap.fds.concat(a1);
this.emit('fds', a1);
}
if (a0) {
if (!this.push(a0)) this._wrap.pause();
}
if (a1 && !a0) {
this.emit('readable');
}
if (!a0 && !a1 && !this._wrap.endReceived) {
debug("USocket end of stream received");
this._wrap.endReceived = true;
this._wrap.pause();
this.push(null);
this.maybeClose();
}
}
if (event === "drain") {
const d = this._wrap.drain;
this._wrap.drain = null;
if (d) d();
}
}
read(size: number): ReadResult | null;
read(size: number | null, fdSize?: number | null): ReadResult | null;
read(size: number | null, fdSize?: number | null): ReadResult | null {
if (!this._wrap) return null;
if (fdSize === undefined)
return super.read(size ?? undefined) as ReadResult | null;
if (fdSize === null)
fdSize = this._wrap.fds.length;
else if (this._wrap.fds.length < fdSize) return null;
const data = super.read(size ?? undefined);
if (size && !data) return data as ReadResult;
const fds = this._wrap.fds.splice(0, fdSize);
return { data: data as Buffer, fds };
}
unshift(chunk: any, encoding?: BufferEncoding): void;
unshift(chunk: Buffer | null, fds?: any[]): void;
unshift(chunk: any, fdsOrEncoding?: any[] | BufferEncoding): void {
if (chunk) {
super.unshift(chunk);
}
if (Array.isArray(fdsOrEncoding) && this._wrap) {
while (fdsOrEncoding.length > 0)
this._wrap.fds.unshift(fdsOrEncoding.pop());
}
throw new Error('Unsupported function call');
}
write(chunk: any, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean;
write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean;
write(chunk: any, encoding?: BufferEncoding | ((error: Error | null | undefined) => void), callback?: (error: Error | null | undefined) => void): boolean {
if (typeof chunk === 'string') {
chunk = Buffer.from(chunk);
}
if (Buffer.isBuffer(chunk)) {
chunk = { data: chunk };
}
if (encoding instanceof Function) return super.write(chunk, encoding);
if (callback == null || encoding == null) {
if (encoding == null) return super.write(chunk);
return super.write(chunk, encoding);
}
return super.write(chunk, encoding, callback);
}
end(cb?: () => void): this;
end(data: any, cb?: () => void): this;
end(data: any, encoding?: BufferEncoding, cb?: () => void): this;
end(data?: Buffer | (() => void), encoding?: BufferEncoding | (() => void), callback?: () => void): this {
if (data instanceof Function) super.end(data);
else if (encoding instanceof Function) super.end(data, encoding);
else if (encoding == null) return super.end(data);
else if (callback == null) return super.end(data, encoding);
else super.end(data, encoding, callback);
if (this._wrap) {
debug("USocket shutdown");
this._wrap.shutdownCalled = true;
this._wrap.shutdown();
this.read(0);
this.maybeClose();
}
return this;
}
destroy(): this {
if (!this._wrap) return this;
this._wrap.close();
this._wrap = null;
return this;
}
private maybeClose(): void {
if (!this._wrap || !this._wrap.shutdownCalled || !this._wrap.endReceived)
return;
debug("USocket closing socket at end");
this.destroy();
this.emit('close');
}
}
//-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----
//--
export class UServer extends EventEmitter<{ 'listening': [], 'connection': [USocket], 'error': [Error] }> {
private _wrap: any;
private paused: boolean;
private listening: boolean;
private fd: number | null = null;
constructor() {
super();
this.paused = false;
this.listening = false;
}
listen(path: string | { path: string; backlog?: number }, backlog?: number | (() => void), cb?: () => void): void {
if (this._wrap || this.listening)
throw new Error("listen on already listened UServer");
if (typeof path === 'object') {
if (typeof backlog === "number") throw new Error('Invalid backlog');
cb = backlog;
backlog = path.backlog;
path = path.path;
} else if (typeof backlog === 'function') {
cb = backlog;
backlog = 0;
}
backlog = backlog || 16;
if (typeof path !== 'string')
throw new Error("UServer expects valid path");
if (typeof backlog !== 'number')
throw new Error("UServer expects valid path");
if (typeof cb === 'function')
this.once('listening', cb);
debug("creating UServerWrap");
this._wrap = new uwrap.UServerWrap(this._wrapEvent.bind(this));
debug("start UServerWrap#listen");
this._wrap.listen(path, backlog);
}
pause(): void {
this.paused = true;
if (this.listening && this._wrap) this._wrap.pause();
}
resume(): void {
this.paused = false;
if (this.listening && this._wrap) this._wrap.resume();
}
close(): void {
if (!this._wrap) return;
this._wrap.close();
this._wrap = undefined;
}
private _wrapEvent(event: string, a0: any, a1: any): void {
if (event === "listening") {
this.fd = a0;
debug("UServer listening on " + this.fd);
this.emit('listening');
this.listening = true;
if (!this.paused) this._wrap.resume();
}
if (event === "error") {
debug("UServer error", a0);
this._wrap.close();
this._wrap = null;
this.emit("error", a0 as Error);
}
if (event === "accept") {
debug("UServer accepted socket " + a0);
const n = new USocket({ fd: a0 });
this.emit('connection', n);
}
}
}