weida-nng 0.0.0-stage → 0.1.0-alpha.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,80 @@
1
- # Temporary Holding Version
1
+ # weida-nng
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ nanomsg/NNG's Scalability Protocols for Node, Bun and Deno: one Node-API addon over
4
+ `libweida_nng`, the C ABI of the Rust [weida](https://weida.doodleshnookie.net/) SP library, with
5
+ an ES module and TypeScript types on top. Eleven socket types (REQ/REP, PUSH/PULL, PUB/SUB, PAIR
6
+ v0 and v1, SURVEYOR/RESPONDENT, BUS) over `tcp://`, `tls+tcp://`, `ipc://` and `inproc://`, contexts
7
+ for parallel transactions, raw sockets and `device` for forwarders, and a pipe-event stream that
8
+ admits or rejects a connection before it becomes a pipe. It speaks the wire protocol of the NNG C
9
+ library and is tested against it.
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ npm install weida-nng
15
+ ```
16
+
17
+ The package ships prebuilt binaries, so installing it needs no Rust toolchain and no compiler.
18
+
19
+ | Platform | Prebuild |
20
+ | --- | --- |
21
+ | Linux x64, Linux arm64 (glibc) | `linux-x64`, `linux-arm64` |
22
+ | macOS on Apple silicon | `darwin-arm64` |
23
+ | Windows x64 | `win32-x64` |
24
+
25
+ It runs on Node 20 and later, on Bun, and on Deno with `--allow-read --allow-env --allow-ffi`.
26
+ With `weida-native-full` installed at the same version, it and `weida` share one native library
27
+ (`weida/nng` is this package).
28
+
29
+ ## Example
30
+
31
+ ```js
32
+ import * as nng from "weida-nng";
33
+
34
+ const context = new nng.Context();
35
+ const server = new nng.RepSocket(context);
36
+ const client = new nng.ReqSocket(context);
37
+ const url = await server.listen("tcp://127.0.0.1:0"); // the port it got
38
+ await client.dial(url);
39
+
40
+ await client.send(new TextEncoder().encode("Hello"));
41
+ console.log(new TextDecoder().decode(await server.recv())); // Hello
42
+ await server.send(new TextEncoder().encode("World"));
43
+ console.log(new TextDecoder().decode(await client.recv())); // World
44
+
45
+ await context.shutdown();
46
+ ```
47
+
48
+ Admitting connections: iterate a socket's pipe events while the dial or listen that needs them
49
+ is awaited.
50
+
51
+ ```js
52
+ const events = server.pipeEvents();
53
+ (async () => {
54
+ for await (const event of events) {
55
+ if (event.kind === "addPre") {
56
+ event.pipe.uid === allowed ? event.accept() : event.reject("not on the list");
57
+ }
58
+ }
59
+ })();
60
+ ```
61
+
62
+ The JavaScript thread never blocks: every wait is a promise, and every waiting method takes
63
+ `{ signal }`, so `AbortSignal.timeout(ms)` is a deadline of the caller's own beside the socket's
64
+ `recvTimeoutMs` and `sendTimeoutMs`; an aborted receive loses nothing. Durations are
65
+ milliseconds, bodies are Uint8Arrays. Failures are one class, `NngError`, to branch on by
66
+ `error.kind`, NNG's errno (`"ESTATE"`, `"ETIMEDOUT"`, `"EPEERAUTH"`, ...), or `error.code`
67
+ (`"WEIDA_NNG_ESTATE"`).
68
+
69
+ ## Learn more
70
+
71
+ - [Website](https://weida.doodleshnookie.net/) and this package's
72
+ [feature sheet](https://weida.doodleshnookie.net/libraries/nng-js/) with every class and
73
+ method
74
+ - [Repository](https://github.com/tuco86/weida), package in `crates/js/weida-nng`
75
+
76
+ Status: alpha (`0.1.0-alpha.N`); breaking changes are permitted within `0.x`.
77
+
78
+ ## License
79
+
80
+ MIT OR Apache-2.0, at your option.
package/lib/errors.js ADDED
@@ -0,0 +1,24 @@
1
+ // The one error class every failure of libweida_nng throws (docs/c/README.md
2
+ // R9, docs/libraries/nng-js.md section 3): the shared base's `code` and
3
+ // `errno`, the kind of failure it is, and NNG's name for it from
4
+ // libweida_nng's thread-local record, which the addon sets from the call
5
+ // that failed.
6
+ import native from "./native.js";
7
+ import { WeidaError } from "./shared/errors.js";
8
+
9
+ export class NngError extends WeidaError {
10
+ constructor(message) {
11
+ super(message);
12
+ this.name = "NngError";
13
+ /** What failed, as the Python package names its exception class, which
14
+ * is NNG's errno: "ESTATE", "ETIMEDOUT", "ECLOSED", "EPEERAUTH", ...;
15
+ * "InvalidArgument", "Closed" and "Panic" for the C ABI's own codes;
16
+ * "NngError" for a code this package does not know. */
17
+ this.kind = "NngError";
18
+ /** NNG's name for the failure ("NNG_ESTATE"), when the library names
19
+ * one; null for the ABI's own codes. */
20
+ this.condition = null;
21
+ }
22
+ }
23
+
24
+ native.setErrorClass(NngError);
package/lib/index.d.ts ADDED
@@ -0,0 +1,399 @@
1
+ // Types of weida-nng (lib/index.js; docs/libraries/nng-js.md).
2
+ import type { KeyObject, X509Certificate } from "node:crypto";
3
+
4
+ /** Bytes: a Uint8Array (a Buffer is one), another ArrayBuffer view or an
5
+ * ArrayBuffer. A string is refused. */
6
+ export type Bytes = Uint8Array | ArrayBufferView | ArrayBuffer;
7
+
8
+ /** An integer a C `uint64_t` holds: a number up to Number.MAX_SAFE_INTEGER,
9
+ * or a BigInt. */
10
+ export type Count = number | bigint;
11
+
12
+ export interface Signal {
13
+ signal?: AbortSignal;
14
+ }
15
+
16
+ /** What failed, as the Python package names its exception class: NNG's
17
+ * errno, and the C ABI's own three. */
18
+ export type NngErrorKind =
19
+ | "ESTATE"
20
+ | "ETIMEDOUT"
21
+ | "ECLOSED"
22
+ | "EMSGSIZE"
23
+ | "ECONNREFUSED"
24
+ | "ECONNABORTED"
25
+ | "ECONNRESET"
26
+ | "EUNREACHABLE"
27
+ | "EADDRINUSE"
28
+ | "EADDRINVAL"
29
+ | "ENOTSUP"
30
+ | "EINVAL"
31
+ | "EAGAIN"
32
+ | "EPROTO"
33
+ | "EPEERAUTH"
34
+ | "EPERM"
35
+ | "ENOENT"
36
+ | "EREADONLY"
37
+ | "EWRITEONLY"
38
+ | "ECANCELED"
39
+ | "EINTR"
40
+ | "ENOFILES"
41
+ | "ESYSERR"
42
+ | "InvalidArgument"
43
+ | "Closed"
44
+ | "Panic"
45
+ | "NngError";
46
+
47
+ /** Every failure of libweida_nng. */
48
+ export class NngError extends Error {
49
+ readonly name: "NngError";
50
+ /** The R9 constant name, e.g. "WEIDA_NNG_ESTATE"; null for a code this
51
+ * package does not know. */
52
+ code: string | null;
53
+ /** The positive status code. */
54
+ errno: number;
55
+ kind: NngErrorKind;
56
+ /** NNG's name for the failure ("NNG_ESTATE"); null for the ABI's own. */
57
+ condition: string | null;
58
+ }
59
+
60
+ export const CONSTANTS: Readonly<Record<string, number>>;
61
+ export const DEFAULT_MAX_SOCKETS: number;
62
+ export const DEFAULT_MAX_PIPES: number;
63
+ export const DEFAULT_RECV_MAX_SIZE: number;
64
+ export const MAX_QUEUE_DEPTH: number;
65
+ export const NNG_MAX_TTL: number;
66
+ export const SPEC_MAX_TTL: number;
67
+ export const NNG_MAXADDRLEN: number;
68
+ export const DEFAULT_CLOSE_BUDGET_MS: number;
69
+ export const DEFAULT_SURVEY_TIME_MS: number;
70
+ export const DEFAULT_RESEND_TIME_MS: number;
71
+ export const DEFAULT_HANDSHAKE_TIMEOUT_MS: number;
72
+ export const PIPE_QUEUE_CAPACITY: number;
73
+
74
+ export function version(): string;
75
+ export function libraryPath(): string;
76
+ export function strerror(code: number): string;
77
+
78
+ export type ProtocolName =
79
+ | "pair0"
80
+ | "pair1"
81
+ | "pub"
82
+ | "sub"
83
+ | "req"
84
+ | "rep"
85
+ | "push"
86
+ | "pull"
87
+ | "surveyor"
88
+ | "respondent"
89
+ | "bus";
90
+
91
+ export const PROTOCOLS: Readonly<Record<ProtocolName, number>>;
92
+
93
+ export const AuthMode: Readonly<{ NONE: number; OPTIONAL: number; REQUIRED: number }>;
94
+
95
+ /** PEM text: bytes, the path of a PEM file (read at construction) or a
96
+ * certificate object. */
97
+ export type Certificates =
98
+ | Uint8Array
99
+ | string
100
+ | URL
101
+ | X509Certificate
102
+ | ReadonlyArray<Uint8Array | string | URL | X509Certificate>;
103
+
104
+ /** The terms of `tls+tcp://`, for both roles; immutable. */
105
+ export class Tls {
106
+ constructor(options?: {
107
+ ca?: Certificates | null;
108
+ cert?: Certificates | null;
109
+ key?: Uint8Array | string | URL | KeyObject | null;
110
+ serverName?: string | null;
111
+ authMode?: number;
112
+ });
113
+ readonly authMode: number;
114
+ readonly ca: Uint8Array | null;
115
+ readonly cert: Uint8Array | null;
116
+ readonly serverName: string | null;
117
+ /** Whether a key was given; the key itself is write only. */
118
+ readonly hasKey: boolean;
119
+ }
120
+
121
+ /** One dialler's or listener's own options; immutable. */
122
+ export class EndpointOptions {
123
+ constructor(options?: { recvMaxSize?: Count | null });
124
+ readonly recvMaxSize: Count | null;
125
+ }
126
+
127
+ export interface SocketOptionsInit {
128
+ recvMaxSize?: Count | null;
129
+ sendDepth?: Count | null;
130
+ recvDepth?: Count | null;
131
+ sendTimeoutMs?: number | null;
132
+ recvTimeoutMs?: number | null;
133
+ reconnectMinMs?: number | null;
134
+ reconnectMaxMs?: number | null;
135
+ maxPipes?: Count | null;
136
+ handshakeTimeoutMs?: number | null;
137
+ maxAddresses?: Count | null;
138
+ maxPipesPerPeer?: Count | null;
139
+ maxTlsHandshakes?: Count | null;
140
+ messageTimeoutMs?: number | null;
141
+ idleTimeoutMs?: number | null;
142
+ subPreferNew?: boolean | null;
143
+ resendTimeMs?: number | null;
144
+ maxTtl?: Count | null;
145
+ surveyTimeMs?: number | null;
146
+ subscribe?: Bytes | Iterable<Bytes> | null;
147
+ tls?: Tls | null;
148
+ }
149
+
150
+ /** What a socket is opened with: validated by the library at construction,
151
+ * every field read back from it; immutable. */
152
+ export class SocketOptions {
153
+ constructor(options?: SocketOptionsInit);
154
+ readonly recvMaxSize: Count;
155
+ readonly sendDepth: Count | null;
156
+ readonly recvDepth: Count | null;
157
+ readonly sendTimeoutMs: number | null;
158
+ readonly recvTimeoutMs: number | null;
159
+ readonly reconnectMinMs: number;
160
+ readonly reconnectMaxMs: number;
161
+ readonly maxPipes: Count;
162
+ readonly handshakeTimeoutMs: number;
163
+ readonly maxAddresses: Count;
164
+ readonly maxPipesPerPeer: Count;
165
+ readonly maxTlsHandshakes: Count;
166
+ readonly messageTimeoutMs: number | null;
167
+ readonly idleTimeoutMs: number | null;
168
+ readonly subPreferNew: boolean;
169
+ readonly resendTimeMs: number;
170
+ readonly maxTtl: Count;
171
+ readonly surveyTimeMs: number;
172
+ readonly subscribe: readonly Uint8Array[];
173
+ readonly tls: Tls | null;
174
+ }
175
+
176
+ /** A raw socket's message: a header and a body; immutable. */
177
+ export class Message {
178
+ constructor(body?: Bytes | null, options?: { header?: Bytes | null });
179
+ readonly header: Uint8Array;
180
+ readonly body: Uint8Array;
181
+ }
182
+
183
+ /** What a broadcast became; immutable. */
184
+ export class Broadcast {
185
+ constructor(queued: number, dropped: number);
186
+ readonly queued: number;
187
+ readonly dropped: number;
188
+ }
189
+
190
+ /** One row of nng_options(5); immutable. */
191
+ export class NngOption {
192
+ private constructor();
193
+ readonly name: string;
194
+ readonly scope: "socket" | "dialer" | "listener" | "pipe" | "transport";
195
+ readonly honoured: boolean;
196
+ readonly note: string;
197
+ readonly refusal: string | null;
198
+ readonly honouredBy: string | null;
199
+ }
200
+
201
+ export const OPTIONS: readonly NngOption[];
202
+ export function option(name: string): NngOption | null;
203
+
204
+ /** What is known of one pipe; immutable. */
205
+ export class PipeInfo {
206
+ private constructor();
207
+ readonly id: number;
208
+ readonly role: "dial" | "listen" | null;
209
+ readonly peer: ProtocolName | null;
210
+ readonly url: string | null;
211
+ readonly localAddr: string | null;
212
+ readonly remoteAddr: string | null;
213
+ readonly uid: number | null;
214
+ readonly gid: number | null;
215
+ readonly pid: number | null;
216
+ readonly tlsVerified: boolean | null;
217
+ readonly tlsCommonName: string | null;
218
+ readonly tlsAltNames: readonly string[];
219
+ }
220
+
221
+ /** One event of a socket's pipes. */
222
+ export class PipeEvent {
223
+ private constructor();
224
+ readonly kind: "addPre" | "addPost" | "remPost" | "unknown";
225
+ readonly pipe: PipeInfo;
226
+ readonly answered: boolean;
227
+ accept(): void;
228
+ reject(cause?: string | null): void;
229
+ }
230
+
231
+ declare class Handle {
232
+ /** Releases the handle now; pending waits end with kind "Closed". */
233
+ drop(): void;
234
+ [Symbol.dispose](): void;
235
+ }
236
+
237
+ /** A context owning a reactor, the inproc:// namespace and the socket
238
+ * ceiling. */
239
+ export class Context extends Handle {
240
+ constructor(options?: { maxSockets?: Count | null; workerThreads?: Count | null; closeBudgetMs?: number | null });
241
+ static owned(options?: { maxSockets?: Count | null; workerThreads?: Count | null; closeBudgetMs?: number | null }): Context;
242
+ static current(): never;
243
+ static sharing(other: Context): never;
244
+ readonly maxSockets: Count;
245
+ readonly workerThreads: Count;
246
+ readonly closeBudgetMs: number;
247
+ readonly maxInprocNameBytes: Count;
248
+ readonly socketCount: Count;
249
+ readonly closed: boolean;
250
+ /** Resolves with the sockets still open when the budget ran out. */
251
+ shutdown(call?: Signal): Promise<Count>;
252
+ }
253
+
254
+ /** The stream of a socket's pipe events. */
255
+ export class PipeEvents extends Handle {
256
+ private constructor();
257
+ nextEvent(call?: Signal): Promise<PipeEvent>;
258
+ readonly dropped: Count;
259
+ close(): void;
260
+ [Symbol.asyncIterator](): AsyncGenerator<PipeEvent, void, undefined>;
261
+ }
262
+
263
+ /** The surface every socket has. */
264
+ declare class Socket extends Handle {
265
+ readonly protocol: ProtocolName;
266
+ readonly pipeCount: Count;
267
+ pipes(): readonly PipeInfo[];
268
+ close(): void;
269
+ dial(url: string, options?: EndpointOptions | null, call?: Signal): Promise<string>;
270
+ listen(url: string, options?: EndpointOptions | null, call?: Signal): Promise<string>;
271
+ dialNowait(url: string): string;
272
+ pipeEvents(options?: { boundMs?: number | null }): PipeEvents;
273
+ }
274
+
275
+ declare class SocketContext extends Handle {
276
+ readonly id: Count;
277
+ send(body: Bytes, call?: Signal): Promise<void>;
278
+ recv(call?: Signal): Promise<Uint8Array>;
279
+ }
280
+
281
+ export class ReqContext extends SocketContext {
282
+ private constructor();
283
+ }
284
+ export class ReplyContext extends SocketContext {
285
+ private constructor();
286
+ }
287
+ export class SurveyContext extends SocketContext {
288
+ private constructor();
289
+ }
290
+
291
+ export class ReqSocket extends Socket {
292
+ constructor(context: Context, options?: SocketOptions | null);
293
+ send(body: Bytes, call?: Signal): Promise<void>;
294
+ recv(call?: Signal): Promise<Uint8Array>;
295
+ context(): ReqContext;
296
+ implicitContext(): ReqContext;
297
+ readonly resendTimeMs: number;
298
+ }
299
+
300
+ export class RepSocket extends Socket {
301
+ constructor(context: Context, options?: SocketOptions | null);
302
+ send(body: Bytes, call?: Signal): Promise<void>;
303
+ recv(call?: Signal): Promise<Uint8Array>;
304
+ context(): ReplyContext;
305
+ implicitContext(): ReplyContext;
306
+ readonly dropped: Count;
307
+ }
308
+
309
+ export class PushSocket extends Socket {
310
+ constructor(context: Context, options?: SocketOptions | null);
311
+ send(body: Bytes, call?: Signal): Promise<void>;
312
+ sendNowait(body: Bytes): void;
313
+ }
314
+
315
+ export class PullSocket extends Socket {
316
+ constructor(context: Context, options?: SocketOptions | null);
317
+ recv(call?: Signal): Promise<Uint8Array>;
318
+ recvNowait(): Uint8Array;
319
+ }
320
+
321
+ export class PubSocket extends Socket {
322
+ constructor(context: Context, options?: SocketOptions | null);
323
+ send(body: Bytes, call?: Signal): Promise<Broadcast>;
324
+ sendNowait(body: Bytes): Broadcast;
325
+ }
326
+
327
+ export class SubSocket extends Socket {
328
+ constructor(context: Context, options?: SocketOptions | null);
329
+ recv(call?: Signal): Promise<Uint8Array>;
330
+ recvNowait(): Uint8Array;
331
+ subscribe(prefix: Bytes): void;
332
+ unsubscribe(prefix: Bytes): void;
333
+ readonly subscriptions: readonly Uint8Array[];
334
+ readonly discarded: Count;
335
+ }
336
+
337
+ export class Pair0Socket extends Socket {
338
+ constructor(context: Context, options?: SocketOptions | null);
339
+ send(body: Bytes, call?: Signal): Promise<void>;
340
+ sendNowait(body: Bytes): void;
341
+ recv(call?: Signal): Promise<Uint8Array>;
342
+ recvNowait(): Uint8Array;
343
+ }
344
+
345
+ export class Pair1Socket extends Socket {
346
+ constructor(context: Context, options?: SocketOptions | null);
347
+ send(body: Bytes, call?: Signal): Promise<void>;
348
+ sendNowait(body: Bytes): void;
349
+ recv(call?: Signal): Promise<Uint8Array>;
350
+ readonly droppedOverTtl: Count;
351
+ readonly maxTtl: Count;
352
+ }
353
+
354
+ export class SurveyorSocket extends Socket {
355
+ constructor(context: Context, options?: SocketOptions | null);
356
+ send(body: Bytes, call?: Signal): Promise<void>;
357
+ recv(call?: Signal): Promise<Uint8Array>;
358
+ context(): SurveyContext;
359
+ implicitContext(): SurveyContext;
360
+ readonly surveyTimeMs: number;
361
+ readonly discardedLate: Count;
362
+ }
363
+
364
+ export class RespondentSocket extends Socket {
365
+ constructor(context: Context, options?: SocketOptions | null);
366
+ send(body: Bytes, call?: Signal): Promise<void>;
367
+ recv(call?: Signal): Promise<Uint8Array>;
368
+ context(): ReplyContext;
369
+ implicitContext(): ReplyContext;
370
+ readonly dropped: Count;
371
+ }
372
+
373
+ export class BusSocket extends Socket {
374
+ constructor(context: Context, options?: SocketOptions | null);
375
+ send(body: Bytes, call?: Signal): Promise<Broadcast>;
376
+ sendNowait(body: Bytes): Broadcast;
377
+ recv(call?: Signal): Promise<Uint8Array>;
378
+ recvNowait(): Uint8Array;
379
+ }
380
+
381
+ export interface RawReceived {
382
+ readonly pipe: number;
383
+ readonly message: Message;
384
+ }
385
+
386
+ export class RawSocket extends Socket {
387
+ constructor(context: Context, protocol: ProtocolName | number, options?: SocketOptions | null);
388
+ send(message: Message, call?: Signal): Promise<number>;
389
+ sendTo(pipe: number, message: Message, call?: Signal): Promise<void>;
390
+ sendToAll(message: Message): Broadcast;
391
+ sendToAllExcluding(pipe: number, message: Message): Broadcast;
392
+ recv(call?: Signal): Promise<RawReceived>;
393
+ }
394
+
395
+ export function device(
396
+ first: RawSocket,
397
+ second: RawSocket,
398
+ call?: Signal,
399
+ ): Promise<Readonly<{ forwarded: Count; dropped: Count }>>;