weida-nats 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 +79 -2
- package/lib/arguments.js +260 -0
- package/lib/errors.js +30 -0
- package/lib/index.d.ts +309 -0
- package/lib/index.js +848 -0
- package/lib/native.js +12 -0
- package/lib/shared/convert.js +208 -0
- package/lib/shared/errors.js +28 -0
- package/lib/shared/handle.js +55 -0
- package/lib/shared/load.js +74 -0
- package/lib/shared/wait.js +90 -0
- package/lib/signers.js +130 -0
- package/package.json +44 -4
- package/prebuilds/darwin-arm64/libweida_nats.dylib +0 -0
- package/prebuilds/darwin-arm64/weida_nats.node +0 -0
- package/prebuilds/linux-arm64/libweida_nats.so +0 -0
- package/prebuilds/linux-arm64/weida_nats.node +0 -0
- package/prebuilds/linux-x64/libweida_nats.so +0 -0
- package/prebuilds/linux-x64/weida_nats.node +0 -0
- package/prebuilds/win32-x64/weida_nats.dll +0 -0
- package/prebuilds/win32-x64/weida_nats.node +0 -0
package/README.md
CHANGED
|
@@ -1,3 +1,80 @@
|
|
|
1
|
-
#
|
|
1
|
+
# weida-nats
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A Core NATS client for Node, Bun and Deno: one Node-API addon over `libweida_nats`, the C ABI of
|
|
4
|
+
the Rust [weida](https://weida.doodleshnookie.net/) NATS client, with an ES module and TypeScript
|
|
5
|
+
types on top. It connects over TCP or TLS, publishes with headers and reply subjects, subscribes
|
|
6
|
+
with wildcards and queue groups, makes requests with a mandatory window that tell "nobody is
|
|
7
|
+
listening" from "nobody answered in time", answers the server's nonce with your own signer for
|
|
8
|
+
NKey and JWT credentials, and reports what the server refused after the call returned.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npm install weida-nats
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
The package ships prebuilt binaries, so installing it needs no Rust toolchain and no compiler.
|
|
17
|
+
|
|
18
|
+
| Platform | Prebuild |
|
|
19
|
+
| --- | --- |
|
|
20
|
+
| Linux x64, Linux arm64 (glibc) | `linux-x64`, `linux-arm64` |
|
|
21
|
+
| macOS on Apple silicon | `darwin-arm64` |
|
|
22
|
+
| Windows x64 | `win32-x64` |
|
|
23
|
+
|
|
24
|
+
It runs on Node 20 and later, on Bun, and on Deno with `--allow-read --allow-env --allow-ffi`.
|
|
25
|
+
With `weida-native-full` installed at the same version, it and `weida` share one native library
|
|
26
|
+
(`weida/nats` is this package).
|
|
27
|
+
|
|
28
|
+
## Example
|
|
29
|
+
|
|
30
|
+
```js
|
|
31
|
+
import * as nats from "weida-nats";
|
|
32
|
+
|
|
33
|
+
const conn = await nats.connect("127.0.0.1", 4222);
|
|
34
|
+
|
|
35
|
+
const orders = await conn.subscribe("orders.>");
|
|
36
|
+
await conn.publish("orders.created", new TextEncoder().encode("{}"));
|
|
37
|
+
const message = await orders.next();
|
|
38
|
+
console.log(message.subjectStr); // "orders.created"
|
|
39
|
+
|
|
40
|
+
// The window is mandatory: a request API that can hang is a bug.
|
|
41
|
+
try {
|
|
42
|
+
const reply = await conn.request("service.echo", new TextEncoder().encode("ping"), 2000);
|
|
43
|
+
console.log(new TextDecoder().decode(reply.payload));
|
|
44
|
+
} catch (error) {
|
|
45
|
+
if (error.kind === "NoResponders") {
|
|
46
|
+
// 503: nobody was subscribed, now
|
|
47
|
+
} else if (error.kind === "RequestTimeout") {
|
|
48
|
+
// the window closed: somebody may well have been
|
|
49
|
+
} else {
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
for await (const message of orders) {
|
|
55
|
+
console.log(message.sid, message.payload.length);
|
|
56
|
+
break;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
await conn.close();
|
|
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; an aborted receive loses nothing.
|
|
64
|
+
Durations are milliseconds. Failures are one class, `NatsError`, to branch on by `error.kind`
|
|
65
|
+
(`"NoResponders"`, `"RequestTimeout"`, `"InvalidSubject"`, ...) or `error.code`
|
|
66
|
+
(`"WEIDA_NATS_ENO_RESPONDERS"`). Publishing succeeds when the message was queued, and nothing
|
|
67
|
+
more: `conn.refusals()` is where an application learns that the server did not accept one.
|
|
68
|
+
|
|
69
|
+
## Learn more
|
|
70
|
+
|
|
71
|
+
- [Website](https://weida.doodleshnookie.net/) and this package's
|
|
72
|
+
[feature sheet](https://weida.doodleshnookie.net/libraries/nats-js/) with every class and
|
|
73
|
+
method
|
|
74
|
+
- [Repository](https://github.com/tuco86/weida), package in `crates/js/weida-nats`
|
|
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/arguments.js
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
// The arguments of the package's calls, read and refused where they are
|
|
2
|
+
// given: the options of a connect, subjects, header blocks, durations and
|
|
3
|
+
// counts, and the C builders they become (the Python package's
|
|
4
|
+
// weida_nats/_options.py and _convert.py, in camelCase).
|
|
5
|
+
//
|
|
6
|
+
// The options of a connect are every CONNECT field and every bound, read
|
|
7
|
+
// from one object by name; one function reads them, so `connect` and
|
|
8
|
+
// `Connection.connectSharing` cannot come to differ about what an option is
|
|
9
|
+
// called or what it defaults to. The defaults are not written here at all:
|
|
10
|
+
// they are libweida_nats's ConnectionOptions::new. An unknown option is
|
|
11
|
+
// refused with NatsError kind "Configuration" naming every option there is:
|
|
12
|
+
// an options object that silently ignores what it does not recognise is a
|
|
13
|
+
// configuration surface where a typo means "the default, forever". The
|
|
14
|
+
// library's own validate runs here too, so a refusal arrives before
|
|
15
|
+
// anything is dialled.
|
|
16
|
+
//
|
|
17
|
+
// The credential forms are alternatives, and the library makes that
|
|
18
|
+
// structural with one credential setting, so this reads at most one of them:
|
|
19
|
+
// `token`; `user` and `password`; `jwt`, signing the nonce when `signer` is
|
|
20
|
+
// given; `nkeySigner`, which always signs (lib/signers.js).
|
|
21
|
+
import { fileURLToPath } from "node:url";
|
|
22
|
+
|
|
23
|
+
import native from "./native.js";
|
|
24
|
+
import {
|
|
25
|
+
bytes,
|
|
26
|
+
certPem,
|
|
27
|
+
configured,
|
|
28
|
+
describe,
|
|
29
|
+
integer,
|
|
30
|
+
isBytes,
|
|
31
|
+
keyPem,
|
|
32
|
+
millis,
|
|
33
|
+
text,
|
|
34
|
+
} from "./shared/convert.js";
|
|
35
|
+
|
|
36
|
+
const C = native.CONSTANTS;
|
|
37
|
+
|
|
38
|
+
const U32 = 0xffffffff;
|
|
39
|
+
const U64 = 2n ** 64n - 1n;
|
|
40
|
+
|
|
41
|
+
/** The largest queue length handed to the library: `subscriptionQueue`,
|
|
42
|
+
* `outgoingQueue` and `requestMany`'s `maxReplies`. The library builds
|
|
43
|
+
* bounded channels of that capacity and a channel cannot hold more than
|
|
44
|
+
* `usize::MAX >> 3`; it refuses a larger one itself, and this refuses it
|
|
45
|
+
* where it is given. */
|
|
46
|
+
export const MAX_QUEUE = 2n ** 61n - 1n;
|
|
47
|
+
|
|
48
|
+
/** The NatsError kind "Configuration" of a value this package refuses. */
|
|
49
|
+
export function refused(message) {
|
|
50
|
+
return native.errorWith(C.WEIDA_NATS_ECONFIGURATION, message, null, null, 0);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** A RangeError of a shared conversion as the "Configuration" the Python
|
|
54
|
+
* package raises for a number the library would not accept; a TypeError
|
|
55
|
+
* (the wrong kind of value) stays one. */
|
|
56
|
+
function asConfiguration(convert) {
|
|
57
|
+
try {
|
|
58
|
+
return convert();
|
|
59
|
+
} catch (error) {
|
|
60
|
+
if (error instanceof RangeError) {
|
|
61
|
+
throw refused(error.message);
|
|
62
|
+
}
|
|
63
|
+
throw error;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** A duration in milliseconds: rounded, finite and not negative, else
|
|
68
|
+
* "Configuration". */
|
|
69
|
+
export function ms(name, value) {
|
|
70
|
+
return asConfiguration(() => millis(name, value));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** An integer within `min..max` (a number, or a BigInt), else
|
|
74
|
+
* "Configuration". */
|
|
75
|
+
export function count(name, value, max, min = 0) {
|
|
76
|
+
return asConfiguration(() => integer(name, value, max, min));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const flag = (value) => Boolean(value);
|
|
80
|
+
|
|
81
|
+
// option: [setter of weida_nats_connection_options, how the value is read].
|
|
82
|
+
// The setter takes the value last.
|
|
83
|
+
export const SETTERS = Object.freeze({
|
|
84
|
+
name: [native.connectionOptionsSetName, (n, v) => (v == null ? null : text(n, v))],
|
|
85
|
+
verbose: [native.connectionOptionsSetVerbose, (n, v) => flag(v)],
|
|
86
|
+
pedantic: [native.connectionOptionsSetPedantic, (n, v) => flag(v)],
|
|
87
|
+
headers: [native.connectionOptionsSetHeaders, (n, v) => flag(v)],
|
|
88
|
+
noResponders: [native.connectionOptionsSetNoResponders, (n, v) => flag(v)],
|
|
89
|
+
echo: [native.connectionOptionsSetEcho, (n, v) => (v ? 1 : 0)],
|
|
90
|
+
requireTls: [native.connectionOptionsSetRequireTls, (n, v) => flag(v)],
|
|
91
|
+
tlsServerName: [native.connectionOptionsSetTlsServerName, (n, v) => (v == null ? null : text(n, v))],
|
|
92
|
+
pingIntervalMs: [native.connectionOptionsSetPingIntervalMs, ms],
|
|
93
|
+
maxPingsOut: [native.connectionOptionsSetMaxPingsOut, (n, v) => count(n, v, U32)],
|
|
94
|
+
inboxPrefix: [native.connectionOptionsSetInboxPrefix, text],
|
|
95
|
+
maxSubscriptions: [native.connectionOptionsSetMaxSubscriptions, (n, v) => count(n, v, U64)],
|
|
96
|
+
maxPendingRequests: [native.connectionOptionsSetMaxPendingRequests, (n, v) => count(n, v, U64)],
|
|
97
|
+
subscriptionQueue: [native.connectionOptionsSetSubscriptionQueue, (n, v) => count(n, v, MAX_QUEUE)],
|
|
98
|
+
maxQueuedBytes: [native.connectionOptionsSetMaxQueuedBytes, (n, v) => count(n, v, U64)],
|
|
99
|
+
outgoingQueue: [native.connectionOptionsSetOutgoingQueue, (n, v) => count(n, v, MAX_QUEUE)],
|
|
100
|
+
refusalQueue: [native.connectionOptionsSetRefusalQueue, (n, v) => count(n, v, U64)],
|
|
101
|
+
maxConnectUrls: [native.connectionOptionsSetMaxConnectUrls, (n, v) => count(n, v, U32)],
|
|
102
|
+
maxHeaderEntries: [native.connectionOptionsSetMaxHeaderEntries, (n, v) => count(n, v, U32)],
|
|
103
|
+
maxControlLine: [native.connectionOptionsSetMaxControlLine, (n, v) => count(n, v, U64)],
|
|
104
|
+
maxInboundControlLine: [native.connectionOptionsSetMaxInboundControlLine, (n, v) => count(n, v, U64)],
|
|
105
|
+
maxInfoLine: [native.connectionOptionsSetMaxInfoLine, (n, v) => count(n, v, U64)],
|
|
106
|
+
maxInboundPayload: [native.connectionOptionsSetMaxInboundPayload, (n, v) => count(n, v, U64)],
|
|
107
|
+
handshakeTimeoutMs: [native.connectionOptionsSetHandshakeTimeoutMs, ms],
|
|
108
|
+
writeTimeoutMs: [native.connectionOptionsSetWriteTimeoutMs, ms],
|
|
109
|
+
maxResolvedAddresses: [native.connectionOptionsSetMaxResolvedAddresses, (n, v) => count(n, v, U64)],
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
export const CREDENTIALS = Object.freeze(["token", "user", "password", "jwt", "signer", "nkeySigner"]);
|
|
113
|
+
|
|
114
|
+
/** Every option a connect reads besides `tls`, `workerThreads` and
|
|
115
|
+
* `signal`: the Python package's 32 keywords. */
|
|
116
|
+
export const KEYWORDS = Object.freeze([...Object.keys(SETTERS), ...CREDENTIALS]);
|
|
117
|
+
|
|
118
|
+
/** Folds the credential options into the one form a CONNECT carries and
|
|
119
|
+
* returns the signer that form needs, or null. */
|
|
120
|
+
function credentials(handle, options) {
|
|
121
|
+
const { token, user, password, jwt, signer, nkeySigner } = options;
|
|
122
|
+
const named = [token != null, user != null || password != null, jwt != null, nkeySigner != null];
|
|
123
|
+
if (named.filter(Boolean).length > 1) {
|
|
124
|
+
throw refused(
|
|
125
|
+
"a CONNECT carries one credential form: give token, or user and password, or jwt, or nkeySigner - not several",
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
if (token != null) {
|
|
129
|
+
native.connectionOptionsSetCredentialsToken(handle, text("token", token));
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
if (user != null || password != null) {
|
|
133
|
+
if (user == null || password == null) {
|
|
134
|
+
throw refused(
|
|
135
|
+
"user and password go together: CONNECT.user without CONNECT.pass is a credential the server cannot check",
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
native.connectionOptionsSetCredentialsUserPassword(handle, text("user", user), text("password", password));
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
if (jwt != null) {
|
|
142
|
+
native.connectionOptionsSetCredentialsJwt(handle, text("jwt", jwt), signer != null);
|
|
143
|
+
return signer ?? null;
|
|
144
|
+
}
|
|
145
|
+
if (nkeySigner != null) {
|
|
146
|
+
native.connectionOptionsSetCredentialsNkey(handle);
|
|
147
|
+
return nkeySigner;
|
|
148
|
+
}
|
|
149
|
+
if (signer != null) {
|
|
150
|
+
throw refused("signer signs the nonce for a jwt credential; give jwt as well, or use nkeySigner for the NKey form");
|
|
151
|
+
}
|
|
152
|
+
return null;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* The C options of `options` (an object whose undefined entries are
|
|
157
|
+
* absent), validated by the library, and the signer the credential form
|
|
158
|
+
* needs (or null): `{ handle, signer }`, the handle the caller's to drop.
|
|
159
|
+
* Throws "Configuration" naming what is wrong, a TypeError for a value of
|
|
160
|
+
* the wrong kind.
|
|
161
|
+
*/
|
|
162
|
+
export function nativeOptions(options) {
|
|
163
|
+
const given = Object.entries(options).filter(([, value]) => value !== undefined);
|
|
164
|
+
for (const [key] of given) {
|
|
165
|
+
if (!KEYWORDS.includes(key)) {
|
|
166
|
+
throw refused(`${key} is not a connection option. The options are: ${KEYWORDS.join(", ")}`);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
for (const key of ["signer", "nkeySigner"]) {
|
|
170
|
+
if (options[key] != null && typeof options[key] !== "function") {
|
|
171
|
+
throw new TypeError("a signer is called with the server's nonce as bytes, so it must be a function");
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
let signer = null;
|
|
175
|
+
const handle = configured(native.connectionOptionsNew(), (h) => {
|
|
176
|
+
for (const [key, value] of given) {
|
|
177
|
+
if (CREDENTIALS.includes(key) || (key === "echo" && value === null)) {
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
const [setter, read] = SETTERS[key];
|
|
181
|
+
setter(h, read(key, value));
|
|
182
|
+
}
|
|
183
|
+
signer = credentials(h, options);
|
|
184
|
+
native.connectionOptionsValidate(h);
|
|
185
|
+
});
|
|
186
|
+
return { handle, signer };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// ---- subjects, headers and the TLS terms ----
|
|
190
|
+
|
|
191
|
+
/** A subject, reply subject or queue group: a string, or bytes passed as
|
|
192
|
+
* they are (the ABI takes UTF-8 only, and the library refuses other octets
|
|
193
|
+
* as kind "InvalidArgument"). */
|
|
194
|
+
export function subjectOf(name, value) {
|
|
195
|
+
if (typeof value === "string") {
|
|
196
|
+
return text(name, value);
|
|
197
|
+
}
|
|
198
|
+
if (!isBytes(value)) {
|
|
199
|
+
throw new TypeError(`${name} is a string or bytes, not ${describe(value)}`);
|
|
200
|
+
}
|
|
201
|
+
const octets = bytes(name, value);
|
|
202
|
+
if (octets.includes(0)) {
|
|
203
|
+
throw new RangeError(`${name} holds a null byte`);
|
|
204
|
+
}
|
|
205
|
+
return octets;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** A header argument as `[name, value]` pairs, in order: an iterable of
|
|
209
|
+
* pairs (the one spelling that can repeat a name), a Map or a plain object
|
|
210
|
+
* (insertion order is the order sent). */
|
|
211
|
+
export function headersOf(value) {
|
|
212
|
+
let items;
|
|
213
|
+
if (value instanceof Map) {
|
|
214
|
+
items = value.entries();
|
|
215
|
+
} else if (typeof value?.[Symbol.iterator] === "function" && typeof value !== "string") {
|
|
216
|
+
items = value;
|
|
217
|
+
} else if (value !== null && typeof value === "object") {
|
|
218
|
+
items = Object.entries(value);
|
|
219
|
+
} else {
|
|
220
|
+
throw new TypeError("headers is an array of [name, value] pairs, a Map or an object");
|
|
221
|
+
}
|
|
222
|
+
return Array.from(items, (item) => {
|
|
223
|
+
if (!Array.isArray(item) || item.length !== 2) {
|
|
224
|
+
throw new TypeError("headers is an array of [name, value] pairs, a Map or an object");
|
|
225
|
+
}
|
|
226
|
+
return [text("header name", item[0]), text("header value", item[1])];
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** The weida_nats_headers block of `pairs` for one publish. */
|
|
231
|
+
export function buildHeaders(pairs) {
|
|
232
|
+
return configured(native.headersNew(), (h) => {
|
|
233
|
+
for (const [name, value] of pairs) {
|
|
234
|
+
native.headersPush(h, name, value);
|
|
235
|
+
}
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** The weida_nats_tls_client of a TlsConfig `t`, for one connect. */
|
|
240
|
+
export function buildTls(t) {
|
|
241
|
+
return configured(native.tlsClientNew(), (h) => {
|
|
242
|
+
for (const anchor of t.ca) {
|
|
243
|
+
if (typeof anchor === "string") {
|
|
244
|
+
native.tlsClientAddAnchorsPath(h, anchor);
|
|
245
|
+
} else if (anchor instanceof URL) {
|
|
246
|
+
native.tlsClientAddAnchorsPath(h, fileURLToPath(anchor));
|
|
247
|
+
} else {
|
|
248
|
+
native.tlsClientAddAnchorsPem(h, certPem(anchor));
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
if (t.identity !== null) {
|
|
252
|
+
native.tlsClientSetIdentityPem(h, certPem(t.identity.cert), keyPem(t.identity.key));
|
|
253
|
+
}
|
|
254
|
+
if (t.serverName !== null) {
|
|
255
|
+
native.tlsClientSetServerName(h, t.serverName);
|
|
256
|
+
}
|
|
257
|
+
native.tlsClientSetVerify(h, t.verify ? C.WEIDA_NATS_TLS_VERIFY_PEER : C.WEIDA_NATS_TLS_VERIFY_NONE);
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
|
package/lib/errors.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// The one error class every failure of libweida_nats throws (docs/c/README.md
|
|
2
|
+
// R9, docs/libraries/nats-js.md section 3): the shared base's `code` and
|
|
3
|
+
// `errno`, the kind of failure it is, and libweida_nats's thread-local
|
|
4
|
+
// record, which the addon sets from the call that failed.
|
|
5
|
+
import native from "./native.js";
|
|
6
|
+
import { WeidaError } from "./shared/errors.js";
|
|
7
|
+
|
|
8
|
+
export class NatsError extends WeidaError {
|
|
9
|
+
constructor(message) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.name = "NatsError";
|
|
12
|
+
/** What failed, as the Python package names its exception class:
|
|
13
|
+
* "NoResponders", "RequestTimeout", "InvalidSubject", ...; "NatsError"
|
|
14
|
+
* for a code this package does not know. */
|
|
15
|
+
this.kind = "NatsError";
|
|
16
|
+
/** The rule or step that failed, where the library names one: the rule
|
|
17
|
+
* a subject broke (WEIDA_NATS_EINVALID_SUBJECT), the server's -ERR
|
|
18
|
+
* sentence (WEIDA_NATS_ESERVER), the handshake step that was waiting
|
|
19
|
+
* (WEIDA_NATS_EHANDSHAKE_TIMEOUT). */
|
|
20
|
+
this.condition = null;
|
|
21
|
+
/** The bound that was exceeded, where there is one: the server's
|
|
22
|
+
* max_payload of WEIDA_NATS_EPAYLOAD_TOO_LARGE, the table of
|
|
23
|
+
* WEIDA_NATS_ETOO_MANY_SUBSCRIPTIONS, ... */
|
|
24
|
+
this.max = null;
|
|
25
|
+
/** The raw OS error of WEIDA_NATS_EIO, when it carried one. */
|
|
26
|
+
this.osCode = null;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
native.setErrorClass(NatsError);
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
// Types of weida-nats (lib/index.js; docs/libraries/nats-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
|
+
/** A subject, reply subject or queue group: text, or its octets (the ABI
|
|
9
|
+
* takes UTF-8 only). */
|
|
10
|
+
export type Subject = string | Bytes;
|
|
11
|
+
|
|
12
|
+
/** An integer a C `uint64_t` holds: a number up to Number.MAX_SAFE_INTEGER,
|
|
13
|
+
* or a BigInt. */
|
|
14
|
+
export type Count = number | bigint;
|
|
15
|
+
|
|
16
|
+
/** A header block: `[name, value]` pairs (repeats and order kept), a Map or
|
|
17
|
+
* an object. */
|
|
18
|
+
export type Headers =
|
|
19
|
+
| Iterable<readonly [string, string]>
|
|
20
|
+
| ReadonlyMap<string, string>
|
|
21
|
+
| { readonly [name: string]: string };
|
|
22
|
+
|
|
23
|
+
export interface Signal {
|
|
24
|
+
signal?: AbortSignal;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** What failed, as the Python package names its exception class. */
|
|
28
|
+
export type NatsErrorKind =
|
|
29
|
+
| "Io"
|
|
30
|
+
| "Runtime"
|
|
31
|
+
| "Decode"
|
|
32
|
+
| "Encode"
|
|
33
|
+
| "Protocol"
|
|
34
|
+
| "Server"
|
|
35
|
+
| "AuthenticationRequired"
|
|
36
|
+
| "NonceMissing"
|
|
37
|
+
| "Signature"
|
|
38
|
+
| "TlsRequired"
|
|
39
|
+
| "TlsUnsupported"
|
|
40
|
+
| "Tls"
|
|
41
|
+
| "PayloadTooLarge"
|
|
42
|
+
| "ControlLineTooLong"
|
|
43
|
+
| "HeadersUnsupported"
|
|
44
|
+
| "NoResponders"
|
|
45
|
+
| "RequestTimeout"
|
|
46
|
+
| "StaleConnection"
|
|
47
|
+
| "HandshakeTimeout"
|
|
48
|
+
| "WriteTimeout"
|
|
49
|
+
| "ConnectionGone"
|
|
50
|
+
| "TooManySubscriptions"
|
|
51
|
+
| "TooManyPendingRequests"
|
|
52
|
+
| "InvalidSubject"
|
|
53
|
+
| "Configuration"
|
|
54
|
+
| "InvalidArgument"
|
|
55
|
+
| "Closed"
|
|
56
|
+
| "Panic"
|
|
57
|
+
| "Interrupted"
|
|
58
|
+
| "NatsError";
|
|
59
|
+
|
|
60
|
+
/** Every failure of libweida_nats. */
|
|
61
|
+
export class NatsError extends Error {
|
|
62
|
+
readonly name: "NatsError";
|
|
63
|
+
/** The R9 constant name, e.g. "WEIDA_NATS_ENO_RESPONDERS"; null for a
|
|
64
|
+
* code this package does not know. */
|
|
65
|
+
code: string | null;
|
|
66
|
+
/** The positive status code. */
|
|
67
|
+
errno: number;
|
|
68
|
+
kind: NatsErrorKind;
|
|
69
|
+
/** The rule or step that failed, where the library names one. */
|
|
70
|
+
condition: string | null;
|
|
71
|
+
/** The bound that was exceeded, where there is one. */
|
|
72
|
+
max: number | bigint | null;
|
|
73
|
+
/** The raw OS error of an "Io" failure. */
|
|
74
|
+
osCode: number | null;
|
|
75
|
+
/** For a failed connect with a signer: what the signer threw, or the
|
|
76
|
+
* TypeError of an answer of another shape. */
|
|
77
|
+
cause?: unknown;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Every constant of weida_nats.h by name, frozen. */
|
|
81
|
+
export const CONSTANTS: Readonly<Record<string, number>>;
|
|
82
|
+
/** 503, the status of the fast no-responder answer. */
|
|
83
|
+
export const NO_RESPONDERS: number;
|
|
84
|
+
/** 4222. */
|
|
85
|
+
export const DEFAULT_PORT: number;
|
|
86
|
+
/** "_INBOX.", unless the `inboxPrefix` option says otherwise. */
|
|
87
|
+
export const INBOX_PREFIX: string;
|
|
88
|
+
|
|
89
|
+
export function version(): string;
|
|
90
|
+
export function libraryPath(): string;
|
|
91
|
+
export function strerror(code: number): string;
|
|
92
|
+
|
|
93
|
+
/** One delivered message, frozen. */
|
|
94
|
+
export class Message {
|
|
95
|
+
private constructor();
|
|
96
|
+
/** The literal subject it was published on, as octets. */
|
|
97
|
+
readonly subject: Uint8Array;
|
|
98
|
+
/** `subject` as text, null where it is not UTF-8. */
|
|
99
|
+
readonly subjectStr: string | null;
|
|
100
|
+
readonly sid: number | bigint;
|
|
101
|
+
readonly replyTo: Uint8Array | null;
|
|
102
|
+
readonly payload: Uint8Array;
|
|
103
|
+
/** The header block, null for a message that arrived as MSG. */
|
|
104
|
+
readonly headers: ReadonlyArray<readonly [string, string]> | null;
|
|
105
|
+
/** The `NATS/1.0` status, null for none. */
|
|
106
|
+
readonly status: number | null;
|
|
107
|
+
readonly isNoResponders: boolean;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The server's INFO, a frozen snapshot. */
|
|
111
|
+
export class RemoteInfo {
|
|
112
|
+
private constructor();
|
|
113
|
+
readonly serverId: string | null;
|
|
114
|
+
readonly serverName: string | null;
|
|
115
|
+
readonly version: string | null;
|
|
116
|
+
readonly proto: number | bigint;
|
|
117
|
+
readonly host: string | null;
|
|
118
|
+
readonly port: number | bigint | null;
|
|
119
|
+
readonly maxPayload: number | bigint;
|
|
120
|
+
readonly headers: boolean;
|
|
121
|
+
readonly authRequired: boolean;
|
|
122
|
+
readonly tlsRequired: boolean;
|
|
123
|
+
readonly tlsAvailable: boolean;
|
|
124
|
+
readonly tlsVerify: boolean;
|
|
125
|
+
readonly nonce: string | null;
|
|
126
|
+
readonly connectUrls: readonly string[];
|
|
127
|
+
readonly lameDuck: boolean;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Where a connection is, frozen. */
|
|
131
|
+
export class State {
|
|
132
|
+
private constructor();
|
|
133
|
+
readonly name: "connected" | "closed" | "failed";
|
|
134
|
+
/** The reason of a failed connection, else null. */
|
|
135
|
+
readonly why: string | null;
|
|
136
|
+
readonly isUsable: boolean;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export type RefusalKindName = "permissionViolation" | "invalidSubject" | "subscriptionLimit" | "unknown";
|
|
140
|
+
|
|
141
|
+
export const RefusalKind: Readonly<{
|
|
142
|
+
PERMISSION_VIOLATION: "permissionViolation";
|
|
143
|
+
INVALID_SUBJECT: "invalidSubject";
|
|
144
|
+
SUBSCRIPTION_LIMIT: "subscriptionLimit";
|
|
145
|
+
UNKNOWN: "unknown";
|
|
146
|
+
/** The kind of a WEIDA_NATS_REFUSAL_* constant, UNKNOWN for another. */
|
|
147
|
+
of(code: number): RefusalKindName;
|
|
148
|
+
}>;
|
|
149
|
+
|
|
150
|
+
/** An -ERR that leaves the connection alone, frozen. */
|
|
151
|
+
export class Refusal {
|
|
152
|
+
private constructor();
|
|
153
|
+
readonly kind: RefusalKindName;
|
|
154
|
+
readonly subject: string | null;
|
|
155
|
+
readonly reason: string;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** A trust anchor: PEM bytes, an X509Certificate, or the path of a PEM file
|
|
159
|
+
* (a string or a file: URL). */
|
|
160
|
+
export type Anchor = Uint8Array | X509Certificate | string | URL;
|
|
161
|
+
|
|
162
|
+
export interface TlsConfigOptions {
|
|
163
|
+
ca?: Anchor | Anchor[] | null;
|
|
164
|
+
identity?: {
|
|
165
|
+
cert: Uint8Array | X509Certificate | X509Certificate[];
|
|
166
|
+
key: Uint8Array | KeyObject;
|
|
167
|
+
} | null;
|
|
168
|
+
serverName?: string | null;
|
|
169
|
+
verify?: boolean;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** The client side of TLS for a connection, frozen. */
|
|
173
|
+
export class TlsConfig {
|
|
174
|
+
constructor(options?: TlsConfigOptions);
|
|
175
|
+
readonly ca: readonly Anchor[];
|
|
176
|
+
readonly identity: {
|
|
177
|
+
readonly cert: Uint8Array | X509Certificate | X509Certificate[];
|
|
178
|
+
readonly key: Uint8Array | KeyObject;
|
|
179
|
+
} | null;
|
|
180
|
+
readonly serverName: string | null;
|
|
181
|
+
readonly verify: boolean;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** What a signer answers: the base64url signature, or a
|
|
185
|
+
* `[signature, publicKey]` pair (an NKey needs the pair). */
|
|
186
|
+
export type SignerAnswer = string | readonly [string, string];
|
|
187
|
+
/** Called with the server's nonce, unchanged; may return a promise. */
|
|
188
|
+
export type Signer = (nonce: Uint8Array) => SignerAnswer | Promise<SignerAnswer>;
|
|
189
|
+
|
|
190
|
+
/** Every CONNECT field and bound; null or absent is the library's
|
|
191
|
+
* default. */
|
|
192
|
+
export interface ConnectionOptions {
|
|
193
|
+
name?: string | null;
|
|
194
|
+
verbose?: boolean;
|
|
195
|
+
pedantic?: boolean;
|
|
196
|
+
headers?: boolean;
|
|
197
|
+
noResponders?: boolean;
|
|
198
|
+
/** null sends nothing. */
|
|
199
|
+
echo?: boolean | null;
|
|
200
|
+
requireTls?: boolean;
|
|
201
|
+
tlsServerName?: string | null;
|
|
202
|
+
pingIntervalMs?: number;
|
|
203
|
+
maxPingsOut?: Count;
|
|
204
|
+
inboxPrefix?: string;
|
|
205
|
+
maxSubscriptions?: Count;
|
|
206
|
+
maxPendingRequests?: Count;
|
|
207
|
+
subscriptionQueue?: Count;
|
|
208
|
+
maxQueuedBytes?: Count;
|
|
209
|
+
outgoingQueue?: Count;
|
|
210
|
+
refusalQueue?: Count;
|
|
211
|
+
maxConnectUrls?: Count;
|
|
212
|
+
maxHeaderEntries?: Count;
|
|
213
|
+
maxControlLine?: Count;
|
|
214
|
+
maxInboundControlLine?: Count;
|
|
215
|
+
maxInfoLine?: Count;
|
|
216
|
+
maxInboundPayload?: Count;
|
|
217
|
+
handshakeTimeoutMs?: number;
|
|
218
|
+
writeTimeoutMs?: number;
|
|
219
|
+
maxResolvedAddresses?: Count;
|
|
220
|
+
token?: string;
|
|
221
|
+
user?: string;
|
|
222
|
+
password?: string;
|
|
223
|
+
jwt?: string;
|
|
224
|
+
/** Signs the nonce for a `jwt` credential. */
|
|
225
|
+
signer?: Signer;
|
|
226
|
+
/** The NKey form: always signs. */
|
|
227
|
+
nkeySigner?: Signer;
|
|
228
|
+
tls?: TlsConfig | null;
|
|
229
|
+
signal?: AbortSignal;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export interface ConnectOptions extends ConnectionOptions {
|
|
233
|
+
/** The reactor's threads, 1 by default. */
|
|
234
|
+
workerThreads?: Count;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
export function connect(host: string, port: number, options?: ConnectOptions): Promise<Connection>;
|
|
238
|
+
|
|
239
|
+
export interface PublishWithOptions extends Signal {
|
|
240
|
+
replyTo?: Subject | null;
|
|
241
|
+
headers?: Headers | null;
|
|
242
|
+
payload?: Bytes | null;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** One connection to one server. */
|
|
246
|
+
export class Connection {
|
|
247
|
+
private constructor();
|
|
248
|
+
/** Always rejects with kind "Runtime". */
|
|
249
|
+
static connectCurrent(host?: string, port?: number, options?: ConnectionOptions): Promise<never>;
|
|
250
|
+
static connectSharing(other: Connection, host: string, port: number, options?: ConnectionOptions): Promise<Connection>;
|
|
251
|
+
info(): RemoteInfo;
|
|
252
|
+
maxPayload(): number | bigint;
|
|
253
|
+
headersSupported(): boolean;
|
|
254
|
+
isLameDuck(): boolean;
|
|
255
|
+
state(): State;
|
|
256
|
+
refusals(): Refusals;
|
|
257
|
+
publish(subject: Subject, payload: Bytes, options?: Signal): Promise<void>;
|
|
258
|
+
publishWith(subject: Subject, options?: PublishWithOptions): Promise<void>;
|
|
259
|
+
subscribe(subject: Subject, options?: Signal): Promise<Subscription>;
|
|
260
|
+
subscribeWithQueueGroup(subject: Subject, queueGroup: Subject, options?: Signal): Promise<Subscription>;
|
|
261
|
+
request(subject: Subject, payload: Bytes, timeoutMs: number, options?: Signal): Promise<Message>;
|
|
262
|
+
requestMany(
|
|
263
|
+
subject: Subject,
|
|
264
|
+
payload: Bytes,
|
|
265
|
+
timeoutMs: number,
|
|
266
|
+
maxReplies: Count,
|
|
267
|
+
options?: Signal,
|
|
268
|
+
): Promise<readonly Message[]>;
|
|
269
|
+
flush(options?: Signal): Promise<void>;
|
|
270
|
+
close(options?: Signal): Promise<void>;
|
|
271
|
+
lameDuckNotice(options?: Signal): Promise<boolean>;
|
|
272
|
+
closed(options?: Signal): Promise<State>;
|
|
273
|
+
drop(): void;
|
|
274
|
+
[Symbol.dispose](): void;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** One SUB and what it receives. */
|
|
278
|
+
export class Subscription implements AsyncIterable<Message> {
|
|
279
|
+
private constructor();
|
|
280
|
+
next(options?: Signal): Promise<Message | null>;
|
|
281
|
+
/** Throws an Error with `code` "EAGAIN" while another `next()` waits. */
|
|
282
|
+
tryNext(): Message | null;
|
|
283
|
+
unsubscribe(options?: Signal): Promise<void>;
|
|
284
|
+
unsubscribeAfter(maxMsgs: Count, options?: Signal): Promise<void>;
|
|
285
|
+
subject(): Uint8Array;
|
|
286
|
+
queueGroup(): Uint8Array | null;
|
|
287
|
+
sid(): number | bigint;
|
|
288
|
+
dropped(): number | bigint;
|
|
289
|
+
refusal(): Refusal | null;
|
|
290
|
+
drop(): void;
|
|
291
|
+
[Symbol.dispose](): void;
|
|
292
|
+
[Symbol.asyncIterator](): AsyncIterator<Message>;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** The refusals the server sends from the reader's making on. */
|
|
296
|
+
export class Refusals implements AsyncIterable<Refusal> {
|
|
297
|
+
private constructor();
|
|
298
|
+
next(options?: Signal): Promise<Refusal | null>;
|
|
299
|
+
tryNext(): Refusal | null;
|
|
300
|
+
lost(): number | bigint;
|
|
301
|
+
drop(): void;
|
|
302
|
+
[Symbol.dispose](): void;
|
|
303
|
+
[Symbol.asyncIterator](): AsyncIterator<Refusal>;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
export function matches(pattern: string, subject: string): boolean;
|
|
307
|
+
export function checkPublishSubject(subject: string): void;
|
|
308
|
+
export function checkSubscribeSubject(subject: string): void;
|
|
309
|
+
export function checkQueueGroup(group: string): void;
|