forked from zeromq/zeromq.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
1862 lines (1689 loc) · 61.8 KB
/
index.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
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
export {
capability,
context,
curveKeyPair,
version,
Context,
Event,
EventOfType,
EventType,
Socket,
Observer,
Proxy,
} from "./native"
import {
capability,
methods,
Context,
EventOfType,
EventType,
Observer,
Options,
ReadableKeys,
Socket,
SocketType,
WritableKeys,
} from "./native"
import * as draft from "./draft"
const {send, receive} = methods
/**
* A type representing the messages that are returned inside promises by
* {@link Readable.receive}().
*/
export type Message = Buffer
/**
* Union type representing all message types that are accepted by
* {@link Writable.send}().
*/
export type MessageLike =
| ArrayBufferView /* Includes Node.js Buffer and all TypedArray types. */
| ArrayBuffer /* Backing buffer of TypedArrays. */
| SharedArrayBuffer
| string
| null
/**
* Describes sockets that can send messages.
*
* @typeparam M The type of the message or message parts that can be sent.
* @typeparam O Rest type for any options, if applicable to the socket type
* (DRAFT only).
*/
export interface Writable<
M extends MessageLike | MessageLike[] = MessageLike | MessageLike[],
O extends [...object[]] = []
> {
/**
* ZMQ_MULTICAST_HOPS
*
* Sets the time-to-live field in every multicast packet sent from this
* socket. The default is 1 which means that the multicast packets don't leave
* the local network.
*/
multicastHops: number
/**
* ZMQ_SNDBUF
*
* Underlying kernel transmit buffer size in bytes. A value of -1 means leave
* the OS default unchanged.
*/
sendBufferSize: number
/**
* ZMQ_SNDHWM
*
* The high water mark is a hard limit on the maximum number of outgoing
* messages ØMQ shall queue in memory for any single peer that the specified
* socket is communicating with. A value of zero means no limit.
*
* If this limit has been reached the socket shall enter an exceptional state
* and depending on the socket type, ØMQ shall take appropriate action such as
* blocking or dropping sent messages.
*/
sendHighWaterMark: number
/**
* ZMQ_SNDTIMEO
*
* Sets the timeout for sending messages on the socket. If the value is 0,
* {@link send}() will return a rejected promise immediately if the message
* cannot be sent. If the value is -1, it will wait asynchronously until the
* message is sent. For all other values, it will try to send the message for
* that amount of time before rejecting.
*/
sendTimeout: number
/**
* Sends a single message or a multipart message on the socket. Queues the
* message immediately if possible, and returns a resolved promise. If the
* message cannot be queued because the high water mark has been reached, it
* will wait asynchronously. The promise will be resolved when the message was
* queued successfully.
*
* ```typescript
* await socket.send("hello world")
* await socket.send(["hello", "world"])
* ```
*
* Queueing may fail eventually if the socket has been configured with a
* {@link sendTimeout}.
*
* A call to {@link send}() is guaranteed to return with a resolved promise
* immediately if the message could be queued directly.
*
* Only **one** asynchronously blocking call to {@link send}() may be executed
* simultaneously. If you call {@link send}() again on a socket that is in the
* mute state it will return a rejected promise with an `EBUSY` error.
*
* The reason for disallowing multiple {@link send}() calls simultaneously is
* that it could create an implicit queue of unsendable outgoing messages.
* This would circumvent the socket's {@link sendHighWaterMark}. Such an
* implementation could even exhaust all system memory and cause the Node.js
* process to abort.
*
* For most application you should not notice this implementation detail. Only
* in rare occasions will a call to {@link send}() that does not resolve
* immediately be undesired. Here are some common scenarios:
*
* * If you wish to **send a message**, use `await send(...)`. ZeroMQ socket
* types have been carefully designed to give you the correct blocking
* behaviour on the chosen socket type in almost all cases:
*
* * If sending is not possible, it is often better to wait than to continue
* as if nothing happened. For example, on a {@link Request} socket, you
* can only receive a reply once a message has been sent; so waiting until
* a message could be queued before continuing with the rest of the
* program (likely to read from the socket) is required.
*
* * Certain socket types (such as {@link Router}) will always allow
* queueing messages and `await send(...)` won't delay any code that comes
* after. This makes sense for routers, since typically you don't want a
* single send operation to stop the handling of other incoming or
* outgoing messages.
*
* * If you wish to send on an occasionally **blocking** socket (for example
* on a {@link Router} with the {@link Router.mandatory} option set, or on a
* {@link Dealer}) and you're 100% certain that **dropping a message is
* better than blocking**, then you can set the {@link sendTimeout} option
* to `0` to effectively force {@link send}() to always resolve immediately.
* Be prepared to catch exceptions if sending a message is not immediately
* possible.
*
* * If you wish to send on a socket and **messages should be queued before
* they are dropped**, you should implement a [simple
* queue](examples/queue/queue.ts) in JavaScript. Such a queue is not
* provided by this library because most real world applications need to
* deal with undeliverable messages in more complex ways – for example, they
* might need to reply with a status message; or first retry delivery a
* certain number of times before giving up.
*
* @param message Single message or multipart message to queue for sending.
* @param options Any options, if applicable to the socket type (DRAFT only).
* @returns Resolved when the message was successfully queued.
*/
send(message: M, ...options: O): Promise<void>
}
type ReceiveType<T> = T extends {receive(): Promise<infer U>} ? U : never
/**
* Describes sockets that can receive messages.
*
* @typeparam M The type of the message or message parts that can be read.
*/
export interface Readable<M extends object[] = Message[]> {
/**
* ZMQ_RCVBUF
*
* Underlying kernel receive buffer size in bytes. A value of -1 means leave
* the OS default unchanged.
*/
receiveBufferSize: number
/**
* ZMQ_RCVHWM
*
* The high water mark is a hard limit on the maximum number of incoming
* messages ØMQ shall queue in memory for any single peer that the specified
* socket is communicating with. A value of zero means no limit.
*
* If this limit has been reached the socket shall enter an exceptional state
* and depending on the socket type, ØMQ shall take appropriate action such as
* blocking or dropping sent messages.
*/
receiveHighWaterMark: number
/**
* ZMQ_RCVTIMEO
*
* Sets the timeout receiving messages on the socket. If the value is 0,
* {@link receive}() will return a rejected promise immediately if there is no
* message to receive. If the value is -1, it will wait asynchronously until a
* message is available. For all other values, it will wait for a message for
* that amount of time before rejecting.
*/
receiveTimeout: number
/**
* Waits for the next single or multipart message to become availeble on the
* socket. Reads a message immediately if possible. If no messages can be
* read, it will wait asynchonously. The promise will be resolved with an
* array containing the parts of the next message when available.
*
* ```typescript
* const [msg] = await socket.receive()
* const [part1, part2] = await socket.receive()
* ```
*
* Reading may fail (eventually) if the socket has been configured with a
* {@link receiveTimeout}.
*
* A call to {@link receive}() is guaranteed to return with a resolved promise
* immediately if a message could be read from the socket directly.
*
* Only **one** asynchronously blocking call to {@link receive}() can be in
* progress simultaneously. If you call {@link receive}() again on the same
* socket it will return a rejected promise with an `EBUSY` error. For
* example, if no messages can be read and no `await` is used:
*
* ```typescript
* socket.receive() // -> pending promise until read is possible
* socket.receive() // -> promise rejection with `EBUSY` error
* ```
*
* **Note:** Due to the nature of Node.js and to avoid blocking the main
* thread, this method always attempts to read messages with the
* `ZMQ_DONTWAIT` flag. It polls asynchronously if reading is not currently
* possible. This means that all functionality related to timeouts and
* blocking behaviour is reimplemented in the Node.js bindings. Any
* differences in behaviour with the native ZMQ library is considered a bug.
*
* @returns Resolved with message parts that were successfully read.
*/
receive(): Promise<M>
/**
* Asynchronously iterate over messages becoming available on the socket. When
* the socket is closed with {@link Socket.close}(), the iterator will return.
* Returning early from the iterator will **not** close the socket unless it
* also goes out of scope.
*
* ```typescript
* for await (const [msg] of socket) {
* // handle messages
* }
* ```
*/
[Symbol.asyncIterator](): AsyncIterator<ReceiveType<this>, undefined>
}
/**
* Represents the options that can be assigned in the constructor of a given
* socket type, for example `new Dealer({...})`. Readonly options
* for the particular socket will be omitted.
*
* @typeparam S The socket type to which the options should be applied.
*/
export type SocketOptions<S extends Socket> = Options<S, {context: Context}>
interface SocketLikeIterable<T> {
closed: boolean
receive(): Promise<T>
}
/* Support async iteration over received messages. Implementing this in JS
is faster as long as there is no C++ native API to chain promises. */
function asyncIterator<T extends SocketLikeIterable<U>, U>(this: T) {
return {
next: async (): Promise<IteratorResult<U, undefined>> => {
if (this.closed) {
/* Cast so we can omit 'value: undefined'. */
return {done: true} as IteratorReturnResult<undefined>
}
try {
return {value: await this.receive(), done: false}
} catch (err) {
if (this.closed && err.code === "EAGAIN") {
/* Cast so we can omit 'value: undefined'. */
return {done: true} as IteratorReturnResult<undefined>
} else {
throw err
}
}
},
}
}
Object.assign(Socket.prototype, {[Symbol.asyncIterator]: asyncIterator})
Object.assign(Observer.prototype, {[Symbol.asyncIterator]: asyncIterator})
interface EventSubscriber {
/**
* Adds a listener function which will be invoked when the given event type is
* observed. Calling this method will convert the {@link Observer} to **event
* emitter mode**, which will make it impossible to call
* {@link Observer.receive}() at the same time.
*
* ```typescript
* socket.events.on("bind", event => {
* console.log(`Socket bound to ${event.address}`)
* // ...
* })
* ```
*
* @param type The type of event to listen for.
* @param listener The listener function that will be called with all event
* data when the event is observed.
*/
on<E extends EventType>(
type: E,
listener: (data: EventOfType<E>) => void,
): EventSubscriber
/**
* Removes the specified listener function from the list of functions to call
* when the given event is observed.
*
* @param type The type of event that the listener was listening for.
* @param listener The previously registered listener function.
*/
off<E extends EventType>(
type: E,
listener: (data: EventOfType<E>) => void,
): EventSubscriber
}
interface EventEmitter {
emit<E extends EventType>(type: E, data: EventOfType<E>): void
}
if (!Observer.prototype.hasOwnProperty("emitter")) {
Object.defineProperty(Observer.prototype, "emitter", {
get: function emitter(this: Observer) {
/* eslint-disable-next-line @typescript-eslint/no-var-requires */
const events = require("events")
const value: EventEmitter = new events.EventEmitter()
const boundReceive = this.receive.bind(this)
Object.defineProperty(this, "receive", {
get: () => {
throw new Error(
"Observer is in event emitter mode. " +
"After a call to events.on() it is not possible to read events " +
"with events.receive().",
)
},
})
const run = async () => {
while (!this.closed) {
const event = await boundReceive()
value.emit(event.type, event)
}
}
run()
Object.defineProperty(this, "emitter", {value})
return value
},
})
}
Observer.prototype.on = function on(this: {emitter: EventSubscriber}, ...args) {
return this.emitter.on(...args)
}
Observer.prototype.off = function off(
this: {emitter: EventSubscriber},
...args
) {
return this.emitter.off(...args)
}
/* Declare all additional TypeScript prototype methods that have been added
in this file here. They will augment the native module exports. */
declare module "./native" {
export interface Context {
/**
* ZMQ_BLOCKY
*
* By default the context will block forever when closed at process exit.
* The assumption behind this behavior is that abrupt termination will cause
* message loss. Most real applications use some form of handshaking to
* ensure applications receive termination messages, and then terminate the
* context with {@link Socket.linger} set to zero on all sockets. This
* setting is an easier way to get the same result. When {@link blocky} is
* set to `false`, all new sockets are given a linger timeout of zero. You
* must still close all sockets before exiting.
*/
blocky: boolean
/**
* ZMQ_IO_THREADS
*
* Size of the ØMQ thread pool to handle I/O operations. If your application
* is using only the `inproc` transport for messaging you may set this to
* zero, otherwise set it to at least one (default).
*/
ioThreads: number
/**
* ZMQ_MAX_MSGSZ
*
* Maximum allowed size of a message sent in the context.
*/
maxMessageSize: number
/**
* ZMQ_MAX_SOCKETS
*
* Maximum number of sockets allowed on the context.
*/
maxSockets: number
/**
* ZMQ_IPV6
*
* Enable or disable IPv6. When IPv6 is enabled, a socket will connect to,
* or accept connections from, both IPv4 and IPv6 hosts.
*/
ipv6: boolean
/**
* ZMQ_THREAD_PRIORITY
*
* Scheduling priority for internal context's thread pool. This option is
* not available on Windows. Supported values for this option depend on
* chosen scheduling policy. Details can be found at
* http://man7.org/linux/man-pages/man2/sched_setscheduler.2.html. This
* option only applies before creating any sockets on the context.
*
* @writeonly
*/
threadPriority: number
/**
* ZMQ_THREAD_SCHED_POLICY
*
* Scheduling policy for internal context's thread pool. This option is not
* available on Windows. Supported values for this option can be found at
* http://man7.org/linux/man-pages/man2/sched_setscheduler.2.html. This
* option only applies before creating any sockets on the context.
*
* @writeonly
*/
threadSchedulingPolicy: number
/**
* ZMQ_SOCKET_LIMIT
*
* Largest number of sockets that can be set with {@link maxSockets}.
*
* @readonly
*/
readonly maxSocketsLimit: number
}
/**
* Socket option names differ somewhat from the native libzmq option names.
* This is intentional to improve readability and be more idiomatic for
* JavaScript/TypeScript.
*/
export interface Socket {
/**
* ZMQ_AFFINITY
*
* I/O thread affinity, which determines which threads from the ØMQ I/O
* thread pool associated with the socket's context shall handle newly
* created connections.
*
* **Note:** This value is a bit mask, but values higher than
* `Number.MAX_SAFE_INTEGER` may not be represented accurately! This
* currently means that configurations beyond 52 threads are unreliable.
*/
affinity: number
/**
* ZMQ_RATE
*
* Maximum send or receive data rate for multicast transports such as `pgm`.
*/
rate: number
/**
* ZMQ_RECOVERY_IVL
*
* Maximum time in milliseconds that a receiver can be absent from a
* multicast group before unrecoverable data loss will occur.
*/
recoveryInterval: number
/**
* ZMQ_LINGER
*
* Determines how long pending messages which have yet to be sent to a peer
* shall linger in memory after a socket is closed with {@link close}().
*/
linger: number
/**
* ZMQ_RECONNECT_IVL
*
* Period ØMQ shall wait between attempts to reconnect disconnected peers
* when using connection-oriented transports. The value -1 means no
* reconnection.
*/
reconnectInterval: number
/**
* ZMQ_BACKLOG
*
* Maximum length of the queue of outstanding peer connections for the
* specified socket. This only applies to connection-oriented transports.
*/
backlog: number
/**
* ZMQ_RECONNECT_IVL_MAX
*
* Maximum period ØMQ shall wait between attempts to reconnect. On each
* reconnect attempt, the previous interval shall be doubled until
* {@link reconnectMaxInterval} is reached. This allows for exponential
* backoff strategy. Zero (the default) means no exponential backoff is
* performed and reconnect interval calculations are only based on
* {@link reconnectInterval}.
*/
reconnectMaxInterval: number
/**
* ZMQ_MAXMSGSIZE
*
* Limits the size of the inbound message. If a peer sends a message larger
* than the limit it is disconnected. Value of -1 means no limit.
*/
maxMessageSize: number
/**
* ZMQ_TCP_KEEPALIVE
*
* Override SO_KEEPALIVE socket option (if supported by OS). The default
* value of -1 leaves it to the OS default.
*/
tcpKeepalive: number
/**
* ZMQ_TCP_KEEPALIVE_CNT
*
* Overrides TCP_KEEPCNT socket option (if supported by OS). The default
* value of -1 leaves it to the OS default.
*/
tcpKeepaliveCount: number
/**
* ZMQ_TCP_KEEPALIVE_IDLE
*
* Overrides TCP_KEEPIDLE / TCP_KEEPALIVE socket option (if supported by
* OS). The default value of -1 leaves it to the OS default.
*/
tcpKeepaliveIdle: number
/**
* ZMQ_TCP_KEEPALIVE_INTVL
*
* Overrides TCP_KEEPINTVL socket option (if supported by the OS). The
* default value of -1 leaves it to the OS default.
*/
tcpKeepaliveInterval: number
/**
* ZMQ_TCP_ACCEPT_FILTER
*
* Assign a filter that will be applied for each new TCP transport
* connection on a listening socket. If no filters are applied, then the TCP
* transport allows connections from any IP address. If at least one filter
* is applied then new connection source IP should be matched. To clear all
* filters set to `null`. Filter is a string with IPv6 or IPv4 CIDR.
*/
tcpAcceptFilter: string | null
/**
* ZMQ_IMMEDIATE
*
* By default queues will fill on outgoing connections even if the
* connection has not completed. This can lead to "lost" messages on sockets
* with round-robin routing ({@link Request}, {@link Push}, {@link Dealer}).
* If this option is set to `true`, messages shall be queued only to
* completed connections. This will cause the socket to block if there are
* no other connections, but will prevent queues from filling on pipes
* awaiting connection.
*/
immediate: boolean
/**
* ZMQ_IPV6
*
* Enable or disable IPv6. When IPv6 is enabled, the socket will connect to,
* or accept connections from, both IPv4 and IPv6 hosts.
*/
ipv6: boolean
/**
* ZMQ_PLAIN_SERVER
*
* Defines whether the socket will act as server for PLAIN security. A value
* of `true` means the socket will act as PLAIN server. A value of `false`
* means the socket will not act as PLAIN server, and its security role then
* depends on other option settings.
*/
plainServer: boolean
/**
* ZMQ_PLAIN_USERNAME
*
* Sets the username for outgoing connections over TCP or IPC. If you set
* this to a non-null value, the security mechanism used for connections
* shall be PLAIN.
*/
plainUsername: string | null
/**
* ZMQ_PLAIN_PASSWORD
*
* Sets the password for outgoing connections over TCP or IPC. If you set
* this to a non-null value, the security mechanism used for connections
* shall be PLAIN.
*/
plainPassword: string | null
/**
* ZMQ_CURVE_SERVER
*
* Defines whether the socket will act as server for CURVE security. A value
* of `true` means the socket will act as CURVE server. A value of `false`
* means the socket will not act as CURVE server, and its security role then
* depends on other option settings.
*/
curveServer: boolean
/**
* ZMQ_CURVE_PUBLICKEY
*
* Sets the socket's long term public key. You must set this on CURVE client
* sockets. A server socket does not need to know its own public key. You
* can create a new keypair with {@link curveKeyPair}().
*/
curvePublicKey: string | null
/**
* ZMQ_CURVE_SECRETKEY
*
* Sets the socket's long term secret key. You must set this on both CURVE
* client and server sockets. You can create a new keypair with
* {@link curveKeyPair}().
*/
curveSecretKey: string | null
/**
* ZMQ_CURVE_SERVERKEY
*
* Sets the socket's long term server key. This is the public key of the
* CURVE *server* socket. You must set this on CURVE *client* sockets. This
* key must have been generated together with the server's secret key. You
* can create a new keypair with {@link curveKeyPair}().
*/
curveServerKey: string | null
/** */
gssapiServer: boolean
/** */
gssapiPrincipal: string | null
/** */
gssapiServicePrincipal: string | null
/** */
gssapiPlainText: boolean
/** */
gssapiPrincipalNameType: "hostBased" | "userName" | "krb5Principal"
/** */
gssapiServicePrincipalNameType: "hostBased" | "userName" | "krb5Principal"
/**
* ZMQ_ZAP_DOMAIN
*
* Sets the domain for ZAP (ZMQ RFC 27) authentication. For NULL security
* (the default on all `tcp://` connections), ZAP authentication only
* happens if you set a non-empty domain. For PLAIN and CURVE security, ZAP
* requests are always made, if there is a ZAP handler present. See
* http://rfc.zeromq.org/spec:27 for more details.
*/
zapDomain: string | null
/**
* ZMQ_TOS
*
* Sets the ToS fields (the *Differentiated Services* (DS) and *Explicit
* Congestion Notification* (ECN) field) of the IP header. The ToS field is
* typically used to specify a packet's priority. The availability of this
* option is dependent on intermediate network equipment that inspect the
* ToS field and provide a path for low-delay, high-throughput,
* highly-reliable service, etc.
*/
typeOfService: number
/**
* ZMQ_HANDSHAKE_IVL
*
* Handshaking is the exchange of socket configuration information (socket
* type, identity, security) that occurs when a connection is first opened
* (only for connection-oriented transports). If handshaking does not
* complete within the configured time, the connection shall be closed. The
* value 0 means no handshake time limit.
*/
handshakeInterval: number
/**
* ZMQ_SOCKS_PROXY
*
* The SOCKS5 proxy address that shall be used by the socket for the TCP
* connection(s). Does not support SOCKS5 authentication. If the endpoints
* are domain names instead of addresses they shall not be resolved and they
* shall be forwarded unchanged to the SOCKS proxy service in the client
* connection request message (address type 0x03 domain name).
*/
socksProxy: string | null
/**
* ZMQ_HEARTBEAT_IVL
*
* Interval in milliseconds between sending ZMTP heartbeats for the
* specified socket. If this option is greater than 0, then a PING ZMTP
* command will be sent after every interval.
*/
heartbeatInterval: number
/**
* ZMQ_HEARTBEAT_TTL
*
* The timeout in milliseconds on the remote peer for ZMTP heartbeats. If
* this option is greater than 0, the remote side shall time out the
* connection if it does not receive any more traffic within the TTL period.
* This option does not have any effect if {@link heartbeatInterval} is 0.
* Internally, this value is rounded down to the nearest decisecond, any
* value less than 100 will have no effect.
*/
heartbeatTimeToLive: number
/**
* ZMQ_HEARTBEAT_TIMEOUT
*
* How long (in milliseconds) to wait before timing-out a connection after
* sending a PING ZMTP command and not receiving any traffic. This option is
* only valid if {@link heartbeatInterval} is greater than 0. The connection
* will time out if there is no traffic received after sending the PING
* command. The received traffic does not have to be a PONG command - any
* received traffic will cancel the timeout.
*/
heartbeatTimeout: number
/**
* ZMQ_CONNECT_TIMEOUT
*
* Sets how long to wait before timing-out a connect() system call. The
* connect() system call normally takes a long time before it returns a time
* out error. Setting this option allows the library to time out the call at
* an earlier interval.
*/
connectTimeout: number
/**
* ZMQ_TCP_MAXRT
*
* Sets how long before an unacknowledged TCP retransmit times out (if
* supported by the OS). The system normally attempts many TCP retransmits
* following an exponential backoff strategy. This means that after a
* network outage, it may take a long time before the session can be
* re-established. Setting this option allows the timeout to happen at a
* shorter interval.
*/
tcpMaxRetransmitTimeout: number
/**
* ZMQ_MULTICAST_MAXTPDU
*
* Sets the maximum transport data unit size used for outbound multicast
* packets. This must be set at or below the minimum Maximum Transmission
* Unit (MTU) for all network paths over which multicast reception is
* required.
*/
multicastMaxTransportDataUnit: number
/**
* ZMQ_VMCI_BUFFER_SIZE
*
* The size of the underlying buffer for the socket. Used during negotiation
* before the connection is established.
* For `vmci://` transports only.
*/
vmciBufferSize: number
/**
* ZMQ_VMCI_BUFFER_MIN_SIZE
*
* Minimum size of the underlying buffer for the socket. Used during
* negotiation before the connection is established.
* For `vmci://` transports only.
*/
vmciBufferMinSize: number
/**
* ZMQ_VMCI_BUFFER_MAX_SIZE
*
* Maximum size of the underlying buffer for the socket. Used during
* negotiation before the connection is established.
* For `vmci://` transports only.
*/
vmciBufferMaxSize: number
/**
* ZMQ_VMCI_CONNECT_TIMEOUT
*
* Connection timeout for the socket.
* For `vmci://` transports only.
*/
vmciConnectTimeout: number
/**
* ZMQ_BINDTODEVICE
*
* Binds the socket to the given network interface (Linux only). Allows to
* use Linux VRF, see:
* https://www.kernel.org/doc/Documentation/networking/vrf.txt. Requires the
* program to be ran as root **or** with `CAP_NET_RAW`.
*/
interface: string | null
/**
* ZMQ_ZAP_ENFORCE_DOMAIN
*
* The ZAP (ZMQ RFC 27) authentication protocol specifies that a domain must
* always be set. Older versions of libzmq did not follow the spec and
* allowed an empty domain to be set. This option can be used to enabled or
* disable the stricter, backward incompatible behaviour. For now it is
* disabled by default, but in a future version it will be enabled by
* default.
*/
zapEnforceDomain: boolean
/**
* ZMQ_LOOPBACK_FASTPATH
*
* Enable faster TCP connections on loopback devices. An application can
* enable this option to reduce the latency and improve the performance of
* loopback operations on a TCP socket on Windows.
*
* @windows
*/
loopbackFastPath: boolean
/**
* ZMQ_TYPE
*
* Retrieve the socket type. This is fairly useless because you can test the
* socket class with e.g. `socket instanceof Dealer`.
*
* @readonly
*/
readonly type: SocketType
/**
* ZMQ_LAST_ENDPOINT
*
* The last endpoint bound for TCP and IPC transports.
*
* @readonly
*/
readonly lastEndpoint: string | null
/**
* ZMQ_MECHANISM
*
* Returns the current security mechanism for the socket, if any. The
* security mechanism is set implictly by using any of the relevant security
* options. The returned value is one of:
* * `null` – No security mechanism is used.
* * `"plain"` – The PLAIN mechanism defines a simple username/password
* mechanism that lets a server authenticate a client. PLAIN makes no
* attempt at security or confidentiality.
* * `"curve"` – The CURVE mechanism defines a mechanism for secure
* authentication and confidentiality for communications between a client
* and a server. CURVE is intended for use on public networks.
* * `"gssapi"` – The GSSAPI mechanism defines a mechanism for secure
* authentication and confidentiality for communications between a client
* and a server using the Generic Security Service Application Program
* Interface (GSSAPI). The GSSAPI mechanism can be used on both public and
* private networks.
*
* @readonly
*/
readonly securityMechanism: null | "plain" | "curve" | "gssapi"
/**
* ZMQ_THREAD_SAFE
*
* Whether or not the socket is threadsafe. Currently only DRAFT sockets is
* thread-safe.
*
* @readonly
*/
readonly threadSafe: boolean
}
export interface Observer extends EventSubscriber {
/**
* Asynchronously iterate over socket events. When the socket is closed or
* when the observer is closed manually with {@link Observer.close}(), the
* iterator will return.
*
* ```typescript
* for await (event of socket.events) {
* switch (event.type) {
* case "bind":
* console.log(`Socket bound to ${event.address}`)
* break
* // ...
* }
* }
* ```
*/
[Symbol.asyncIterator](): AsyncIterator<ReceiveType<this>, undefined>
}
}
/* Concrete socket types. */
/**
* A {@link Pair} socket can only be connected to one other {@link Pair} at any
* one time. No message routing or filtering is performed on any messages.
*
* When a {@link Pair} socket enters the mute state due to having reached the
* high water mark for the connected peer, or if no peer is connected, then any
* {@link Writable.send}() operations on the socket shall block until the peer
* becomes available for sending; messages are not discarded.
*
* While {@link Pair} sockets can be used over transports other than
* `inproc://`, their inability to auto-reconnect coupled with the fact new
* incoming connections will be terminated while any previous connections
* (including ones in a closing state) exist makes them unsuitable for `tcp://`
* in most cases.
*/
export class Pair extends Socket {
constructor(options?: SocketOptions<Pair>) {
super(SocketType.Pair, options)
}
}
export interface Pair extends Writable, Readable {}
Object.assign(Pair.prototype, {send, receive})
/**
* A {@link Publisher} socket is used to distribute data to {@link Subscriber}s.
* Messages sent are distributed in a fan out fashion to all connected peers.
* This socket cannot receive messages.
*
* When a {@link Publisher} enters the mute state due to having reached the high
* water mark for a connected {@link Subscriber}, then any messages that would
* be sent to the subscriber in question shall instead be dropped until the mute
* state ends. The {@link Writable.send}() method will never block.
*/
export class Publisher extends Socket {
/**
* ZMQ_XPUB_NODROP
*
* Sets the socket behaviour to return an error if the high water mark is
* reached and the message could not be send. The default is to drop the
* message silently when the peer high water mark is reached.
*/
noDrop: boolean
/**