UNPKG

21.3 kBTypeScriptView Raw
1/// <reference types="node" />
2/// <reference types="node" />
3/**
4 * The version of the ØMQ library the bindings were built with. Formatted as
5 * `(major).(minor).(patch)`. For example: `"4.3.2"`.
6 */
7export declare const version: string;
8/**
9 * Exposes some of the optionally available ØMQ capabilities, which may depend
10 * on the library version and platform.
11 *
12 * This is an object with keys corresponding to supported ØMQ features and
13 * transport protocols. Available capabilities will be set to `true`.
14 * Unavailable capabilities will be absent or set to `false`.
15 *
16 * Possible keys include:
17 * * `ipc` - Support for the `ipc://` protocol.
18 * * `pgm` - Support for the `pgm://` protocol.
19 * * `tipc` - Support for the `tipc://` protocol.
20 * * `norm` - Support for the `norm://` protocol.
21 * * `curve` - Support for the CURVE security mechanism.
22 * * `gssapi` - Support for the GSSAPI security mechanism.
23 * * `draft` - Wether the library is built with support for DRAFT sockets.
24 */
25export declare const capability: Partial<{
26 ipc: boolean;
27 pgm: boolean;
28 tipc: boolean;
29 norm: boolean;
30 curve: boolean;
31 gssapi: boolean;
32 draft: boolean;
33}>;
34/**
35 * Returns a new random key pair to be used with the CURVE security mechanism.
36 *
37 * To correctly connect two sockets with this mechanism:
38 *
39 * * Generate a **client** keypair with {@link curveKeyPair}().
40 * * Assign the private and public key on the client socket with
41 * {@link Socket.curveSecretKey} and {@link Socket.curvePublicKey}.
42 * * Generate a **server** keypair with {@link curveKeyPair}().
43 * * Assign the private key on the server socket with {@link Socket.curveSecretKey}.
44 * * Assign the public key **on the client socket** with
45 * {@link Socket.curveServerKey}. The server does *not* need to know its own
46 * public key. Key distribution is *not* handled by the CURVE security
47 * mechanism.
48 *
49 *
50 * @returns An object with a `publicKey` and a `secretKey` property, each being
51 * a 40 character Z85-encoded string.
52 */
53export declare function curveKeyPair(): {
54 publicKey: string;
55 secretKey: string;
56};
57/**
58 * A ØMQ context. Contexts manage the background I/O to send and receive
59 * messages of their associated sockets.
60 *
61 * It is usually not necessary to instantiate a new context - the global
62 * {@link context} is used for new sockets by default. The global context is the
63 * only context that is shared between threads (when using
64 * [worker_threads](https://nodejs.org/api/worker_threads.html)). Custom
65 * contexts can only be used in the same thread.
66 *
67 * ```typescript
68 * // Use default context (recommended).
69 * const socket = new Dealer()
70 * ```
71 *
72 * ```typescript
73 * // Use custom context.
74 * const context = new Context()
75 * const socket = new Dealer({context})
76 * ```
77 *
78 * **Note:** By default all contexts (including the global context) will prevent
79 * the process from terminating if there are any messages in an outgoing queue,
80 * even if the associated socket was closed. For some applications this is
81 * unnecessary or unwanted. Consider setting {@link Context.blocky} to `false`
82 * or setting {@link Socket.linger} for each new socket.
83 */
84export declare class Context {
85 /**
86 * Creates a new ØMQ context and sets any provided context options. Sockets
87 * need to be explicitly associated with a new context during construction.
88 *
89 * @param options An optional object with options that will be set on the
90 * context during creation.
91 */
92 constructor(options?: Options<Context>);
93 protected getBoolOption(option: number): boolean;
94 protected setBoolOption(option: number, value: boolean): void;
95 protected getInt32Option(option: number): number;
96 protected setInt32Option(option: number, value: number): void;
97}
98/**
99 * Any socket that has no explicit context passed in during construction will
100 * be associated with this context. The default context is exposed in order to
101 * be able to change its behaviour with {@link Context} options.
102 */
103export declare const context: Context;
104interface ErrnoError extends Error {
105 code: string;
106 errno: number;
107}
108export interface AuthError extends Error {
109 status: 300 | 400 | 500;
110}
111export interface ProtoError extends Error {
112 code: "ERR_ZMTP_UNSPECIFIED" | "ERR_ZMTP_UNEXPECTED_COMMAND" | "ERR_ZMTP_INVALID_SEQUENCE" | "ERR_ZMTP_KEY_EXCHANGE" | "ERR_ZMTP_MALFORMED_COMMAND_UNSPECIFIED" | "ERR_ZMTP_MALFORMED_COMMAND_MESSAGE" | "ERR_ZMTP_MALFORMED_COMMAND_HELLO" | "ERR_ZMTP_MALFORMED_COMMAND_INITIATE" | "ERR_ZMTP_MALFORMED_COMMAND_ERROR" | "ERR_ZMTP_MALFORMED_COMMAND_READY" | "ERR_ZMTP_MALFORMED_COMMAND_WELCOME" | "ERR_ZMTP_INVALID_METADATA" | "ERR_ZMTP_CRYPTOGRAPHIC" | "ERR_ZMTP_MECHANISM_MISMATCH" | "ERR_ZAP_UNSPECIFIED" | "ERR_ZAP_MALFORMED_REPLY" | "ERR_ZAP_BAD_REQUEST_ID" | "ERR_ZAP_BAD_VERSION" | "ERR_ZAP_INVALID_STATUS_CODE" | "ERR_ZAP_INVALID_METADATA";
113}
114export interface EventAddress {
115 address: string;
116}
117export interface EventInterval {
118 interval: number;
119}
120export interface EventError<E = ErrnoError> {
121 error: E;
122}
123export type EventFor<T extends string, D = {}> = Expand<{
124 type: T;
125} & D>;
126/**
127 * A union type that represents all possible even types and the associated data.
128 * Events always have a `type` property with an {@link EventType} value.
129 *
130 * The following socket events can be generated. This list may be different
131 * depending on the ZeroMQ version that is used.
132 *
133 * Note that the **error** event is avoided by design, since this has a [special
134 * behaviour](https://nodejs.org/api/events.html#events_error_events) in Node.js
135 * causing an exception to be thrown if it is unhandled.
136 *
137 * Other error names are adjusted to be as close to possible as other
138 * [networking related](https://nodejs.org/api/net.html) event names in Node.js
139 * and/or to the corresponding ZeroMQ.js method call. Events (including any
140 * errors) that correspond to a specific operation are namespaced with a colon
141 * `:`, e.g. `bind:error` or `connect:retry`.
142 *
143 * * **accept** - ZMQ_EVENT_ACCEPTED The socket has accepted a connection from a
144 * remote peer.
145 *
146 * * **accept:error** - ZMQ_EVENT_ACCEPT_FAILED The socket has rejected a
147 * connection from a remote peer.
148 *
149 * The following additional details will be included with this event:
150 *
151 * * `error` - An error object that describes the specific error
152 * that occurred.
153 *
154 * * **bind** - ZMQ_EVENT_LISTENING The socket was successfully bound to a
155 * network interface.
156 *
157 * * **bind:error** - ZMQ_EVENT_BIND_FAILED The socket could not bind to a given
158 * interface.
159 *
160 * The following additional details will be included with this event:
161 *
162 * * `error` - An error object that describes the specific error
163 * that occurred.
164 *
165 * * **connect** - ZMQ_EVENT_CONNECTED The socket has successfully connected to
166 * a remote peer.
167 *
168 * * **connect:delay** - ZMQ_EVENT_CONNECT_DELAYED A connect request on the
169 * socket is pending.
170 *
171 * * **connect:retry** - ZMQ_EVENT_CONNECT_RETRIED A connection attempt is being
172 * handled by reconnect timer. Note that the reconnect interval is
173 * recalculated at each retry.
174 *
175 * The following additional details will be included with this event:
176 *
177 * * `interval` - The current reconnect interval.
178 *
179 * * **close** - ZMQ_EVENT_CLOSED The socket was closed.
180 *
181 * * **close:error** - ZMQ_EVENT_CLOSE_FAILED The socket close failed. Note that
182 * this event occurs **only on IPC** transports..
183 *
184 * The following additional details will be included with this event:
185 *
186 * * `error` - An error object that describes the specific error
187 * that occurred.
188 *
189 * * **disconnect** - ZMQ_EVENT_DISCONNECTED The socket was disconnected
190 * unexpectedly.
191 *
192 * * **handshake** - ZMQ_EVENT_HANDSHAKE_SUCCEEDED The ZMTP security mechanism
193 * handshake succeeded. NOTE: This event may still be in DRAFT statea and not
194 * yet available in stable releases.
195 *
196 * * **handshake:error:protocol** - ZMQ_EVENT_HANDSHAKE_FAILED_PROTOCOL The ZMTP
197 * security mechanism handshake failed due to some mechanism protocol error,
198 * either between the ZMTP mechanism peers, or between the mechanism server
199 * and the ZAP handler. This indicates a configuration or implementation error
200 * in either peer resp. the ZAP handler. NOTE: This event may still be in
201 * DRAFT state and not yet available in stable releases.
202 *
203 * * **handshake:error:auth** - ZMQ_EVENT_HANDSHAKE_FAILED_AUTH The ZMTP
204 * security mechanism handshake failed due to an authentication failure. NOTE:
205 * This event may still be in DRAFT state and not yet available in stable
206 * releases.
207 *
208 * * **handshake:error:other** - ZMQ_EVENT_HANDSHAKE_FAILED_NO_DETAIL
209 * Unspecified error during handshake. NOTE: This event may still be in DRAFT
210 * state and not yet available in stable releases.
211 *
212 * * **end** - ZMQ_EVENT_MONITOR_STOPPED Monitoring on this socket ended.
213 *
214 * * **unknown** An event was generated by ZeroMQ that the Node.js library could
215 * not interpret. Please submit a pull request for new event types if they are
216 * not yet included.
217 */
218export type Event = EventFor<"accept", EventAddress> | EventFor<"accept:error", EventAddress & EventError> | EventFor<"bind", EventAddress> | EventFor<"bind:error", EventAddress & EventError> | EventFor<"connect", EventAddress> | EventFor<"connect:delay", EventAddress> | EventFor<"connect:retry", EventAddress & EventInterval> | EventFor<"close", EventAddress> | EventFor<"close:error", EventAddress & EventError> | EventFor<"disconnect", EventAddress> | EventFor<"end"> | EventFor<"handshake", EventAddress> | EventFor<"handshake:error:protocol", EventAddress & EventError<ProtoError>> | EventFor<"handshake:error:auth", EventAddress & EventError<AuthError>> | EventFor<"handshake:error:other", EventAddress & EventError> | EventFor<"unknown">;
219/**
220 * A union type of all available event types. See {@link Event} for an overview
221 * of the events that can be observed.
222 */
223export type EventType = Event["type"];
224/**
225 * Represents the event data object given one particular event type, for example
226 * `EventOfType<"accept">`.
227 *
228 * @typeparam E The specific event type.
229 */
230export type EventOfType<E extends EventType = EventType> = Expand<Extract<Event, Event & EventFor<E>>>;
231/**
232 * An event observer for ØMQ sockets. This starts up a ZMQ monitoring socket
233 * internally that receives all socket events. The event observer can be used in
234 * one of two ways, which are **mutually exclusive**: with {@link receive}() or
235 * with event listeners attached with {@link on}().
236 */
237export declare class Observer {
238 /**
239 * Whether the observer was closed, either manually or because the associated
240 * socket was closed.
241 *
242 * @readonly
243 */
244 readonly closed: boolean;
245 /**
246 * Creates a new ØMQ observer. It should not be necessary to instantiate a new
247 * observer. Access an existing observer for a socket with
248 * {@link Socket.events}.
249 *
250 * ```typescript
251 * const socket = new Publisher()
252 * const events = socket.events
253 * ```
254 *
255 * @param socket The socket to observe.
256 */
257 constructor(socket: Socket);
258 /**
259 * Closes the observer. Afterwards no new events will be received or emitted.
260 * Calling this method is optional.
261 */
262 close(): void;
263 /**
264 * Waits for the next event to become availeble on the observer. Reads an
265 * event immediately if possible. If no events are queued, it will wait
266 * asynchonously. The promise will be resolved with the next event when
267 * available.
268 *
269 * When reading events with {@link receive}() the observer may **not** be in
270 * event emitter mode. Avoid mixing calls to {@link receive}() with event
271 * handlers via attached with {@link on}().
272 *
273 * ```typescript
274 * for await (event of socket.events) {
275 * switch (event.type) {
276 * case "bind":
277 * console.log(`Socket bound to ${event.address}`)
278 * break
279 * // ...
280 * }
281 * }
282 * ```
283 *
284 * @returns Resolved with the next event and its details. See {@link Event}.
285 */
286 receive(): Promise<Event>;
287}
288/**
289 * Proxy messages between two ØMQ sockets. The proxy connects a front-end socket
290 * to a back-end socket. Conceptually, data flows from front-end to back-end.
291 * Depending on the socket types, replies may flow in the opposite direction.
292 * The direction is conceptual only; the proxy is fully symmetric and there is
293 * no technical difference between front-end and back-end.
294 *
295 * ```typescript
296 * // Proxy between a router/dealer socket for 5 seconds.
297 * const proxy = new Proxy(new Router, new Dealer)
298 * await proxy.frontEnd.bind("tcp://*:3001")
299 * await proxy.backEnd.bind("tcp://*:3002")
300 * setTimeout(() => proxy.terminate(), 5000)
301 * await proxy.run()
302 * ```
303 *
304 * [Review the ØMQ documentation](http://api.zeromq.org/4-3:zmq-proxy#toc3) for
305 * an overview of some example applications of a proxy.
306 *
307 * @typeparam F The front-end socket type.
308 * @typeparam B The back-end socket type.
309 */
310export declare class Proxy<F extends Socket = Socket, B extends Socket = Socket> {
311 /**
312 * Returns the original front-end socket.
313 *
314 * @readonly
315 */
316 readonly frontEnd: F;
317 /**
318 * Returns the original back-end socket.
319 *
320 * @readonly
321 */
322 readonly backEnd: B;
323 /**
324 * Creates a new ØMQ proxy. Proxying will start between the front-end and
325 * back-end sockets when {@link run}() is called after both sockets have been
326 * bound or connected.
327 *
328 * @param frontEnd The front-end socket.
329 * @param backEnd The back-end socket.
330 */
331 constructor(frontEnd: F, backEnd: B);
332 /**
333 * Starts the proxy loop in a worker thread and waits for its termination.
334 * Before starting, you must set any socket options, and connect or bind both
335 * front-end and back-end sockets.
336 *
337 * On termination the front-end and back-end sockets will be closed
338 * automatically.
339 *
340 * @returns Resolved when the proxy has terminated.
341 */
342 run(): Promise<void>;
343 /**
344 * Temporarily suspends any proxy activity. Resume activity with
345 * {@link resume}().
346 */
347 pause(): void;
348 /**
349 * Resumes proxy activity after suspending it with {@link pause}().
350 */
351 resume(): void;
352 /**
353 * Gracefully shuts down the proxy. The front-end and back-end sockets will be
354 * closed automatically. There might be a slight delay between terminating and
355 * the {@link run}() method resolving.
356 */
357 terminate(): void;
358}
359/**
360 * A ØMQ socket. This class should generally not be used directly. Instead,
361 * create one of its subclasses that corresponds to the socket type you want to
362 * use.
363 *
364 * ```typescript
365 * new zmq.Pair(...)
366 * new zmq.Publisher(...)
367 * new zmq.Subscriber(...)
368 * new zmq.Request(...)
369 * new zmq.Reply(...)
370 * new zmq.Dealer(...)
371 * new zmq.Router(...)
372 * new zmq.Pull(...)
373 * new zmq.Push(...)
374 * new zmq.XPublisher(...)
375 * new zmq.XSubscriber(...)
376 * new zmq.Stream(...)
377 * ```
378 *
379 * Socket options can be set during construction or via a property after the
380 * socket was created. Most socket options do not take effect until the next
381 * {@link bind}() or {@link connect}() call. Setting such an option after the
382 * socket is already connected or bound will display a warning.
383 */
384export declare abstract class Socket {
385 /**
386 * Event {@link Observer} for this socket. This starts up a ØMQ monitoring
387 * socket internally that receives all socket events.
388 *
389 * @readonly
390 */
391 readonly events: Observer;
392 /**
393 * {@link Context} that this socket belongs to.
394 *
395 * @readonly
396 */
397 readonly context: Context;
398 /**
399 * Whether this socket was previously closed with {@link close}().
400 *
401 * @readonly
402 */
403 readonly closed: boolean;
404 /**
405 * Whether any messages are currently available. If `true`, the next call to
406 * {@link Readable.receive}() will immediately read a message from the socket.
407 * For sockets that cannot receive messsages this is always `false`.
408 *
409 * @readonly
410 */
411 readonly readable: boolean;
412 /**
413 * Whether any messages can be queued for sending. If `true`, the next call to
414 * {@link Writable.send}() will immediately queue a message on the socket.
415 * For sockets that cannot send messsages this is always `false`.
416 *
417 * @readonly
418 */
419 readonly writable: boolean;
420 /**
421 * Creates a new socket of the specified type. Subclasses are expected to
422 * provide the correct socket type.
423 *
424 * @param type The socket type.
425 * @param options Any options to set during construction.
426 */
427 protected constructor(type: SocketType, options?: {});
428 /**
429 * Closes the socket and disposes of all resources. Any messages that are
430 * queued may be discarded or sent in the background depending on the
431 * {@link linger} setting.
432 *
433 * After this method is called, it is no longer possible to call any other
434 * methods on this socket.
435 *
436 * Sockets that go out of scope and have no {@link Readable.receive}() or
437 * {@link Writable.send}() operations in progress will automatically be
438 * closed. Therefore it is not necessary in most applications to call
439 * {@link close}() manually.
440 *
441 * Calling this method on a socket that is already closed is a no-op.
442 */
443 close(): void;
444 /**
445 * Binds the socket to the given address. During {@link bind}() the socket
446 * cannot be used. Do not call any other methods until the returned promise
447 * resolves. Make sure to use `await`.
448 *
449 * You can use `*` in place of a hostname to bind on all interfaces/addresses,
450 * and you can use `*` in place of a port to bind to a random port (which can
451 * be retrieved with {@link lastEndpoint} later).
452 *
453 * ```typescript
454 * await socket.bind("tcp://127.0.0.1:3456")
455 * await socket.bind("tcp://*:3456") // binds on all interfaces
456 * await socket.bind("tcp://127.0.0.1:*") // binds on random port
457 * ```
458 *
459 * @param address Address to bind this socket to.
460 * @returns Resolved when the socket was successfully bound.
461 */
462 bind(address: string): Promise<void>;
463 /**
464 * Unbinds the socket to the given address. During {@link unbind}() the socket
465 * cannot be used. Do not call any other methods until the returned promise
466 * resolves. Make sure to use `await`.
467 *
468 * @param address Address to unbind this socket from.
469 * @returns Resolved when the socket was successfully unbound.
470 */
471 unbind(address: string): Promise<void>;
472 /**
473 * Connects to the socket at the given remote address and returns immediately.
474 * The connection will be made asynchronously in the background.
475 *
476 * ```typescript
477 * socket.connect("tcp://127.0.0.1:3456")
478 * ```
479 *
480 * @param address The address to connect to.
481 */
482 connect(address: string): void;
483 /**
484 * Disconnects a previously connected socket from the given address and
485 * returns immediately. Disonnection will happen asynchronously in the
486 * background.
487 *
488 * ```typescript
489 * socket.disconnect("tcp://127.0.0.1:3456")
490 * ```
491 *
492 * @param address The previously connected address to disconnect from.
493 */
494 disconnect(address: string): void;
495 protected getBoolOption(option: number): boolean;
496 protected setBoolOption(option: number, value: boolean): void;
497 protected getInt32Option(option: number): number;
498 protected setInt32Option(option: number, value: number): void;
499 protected getUint32Option(option: number): number;
500 protected setUint32Option(option: number, value: number): void;
501 protected getInt64Option(option: number): number;
502 protected setInt64Option(option: number, value: number): void;
503 protected getUint64Option(option: number): number;
504 protected setUint64Option(option: number, value: number): void;
505 protected getStringOption(option: number): string | null;
506 protected setStringOption(option: number, value: string | Buffer | null): void;
507}
508export declare const enum SocketType {
509 Pair = 0,
510 Publisher = 1,
511 Subscriber = 2,
512 Request = 3,
513 Reply = 4,
514 Dealer = 5,
515 Router = 6,
516 Pull = 7,
517 Push = 8,
518 XPublisher = 9,
519 XSubscriber = 10,
520 Stream = 11,
521 Server = 12,
522 Client = 13,
523 Radio = 14,
524 Dish = 15,
525 Gather = 16,
526 Scatter = 17,
527 Datagram = 18
528}
529type IfEquals<X, Y, A, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B;
530export type Expand<T> = T extends infer O ? {
531 [K in keyof O]: O[K];
532} : never;
533/** @internal */
534export type ReadableKeys<T> = {
535 [P in keyof T]-?: T[P] extends Function ? never : P;
536}[keyof T];
537/** @internal */
538export type WritableKeys<T> = {
539 [P in keyof T]-?: T[P] extends Function ? never : IfEquals<{
540 [Q in P]: T[P];
541 }, {
542 -readonly [Q in P]: T[P];
543 }, P>;
544}[keyof T];
545export type Options<T, E = {}> = Expand<Partial<E & Pick<T, WritableKeys<T>>>>;
546export {};