@imqueue/core 3.6.0 → 3.8.0
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/.claude/settings.local.json +9 -0
- package/CHANGELOG.md +75 -0
- package/package.json +1 -1
- package/src/ClusterManager.d.ts +17 -2
- package/src/ClusteredRedisQueue.d.ts +74 -3
- package/src/ClusteredRedisQueue.js +181 -6
- package/src/IMessageQueue.d.ts +12 -0
- package/src/RedisQueue.d.ts +42 -0
- package/src/RedisQueue.js +108 -3
- package/src/UDPClusterManager.js +12 -2
- package/src/UDPWorker.d.ts +9 -0
- package/src/UDPWorker.js +15 -2
- package/AGENTS.md +0 -150
- package/CONTRIBUTION-TERMS.md +0 -79
- package/signatures/version1/cla.json +0 -12
package/CHANGELOG.md
CHANGED
|
@@ -9,6 +9,81 @@ queue does has an entry.
|
|
|
9
9
|
|
|
10
10
|
This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
11
11
|
|
|
12
|
+
## [Unreleased]
|
|
13
|
+
|
|
14
|
+
### Fixed
|
|
15
|
+
|
|
16
|
+
- **A broker kept after its announcements lapsed was never checked again, so
|
|
17
|
+
one that later hung stayed in routing until the process restarted.** Since
|
|
18
|
+
3.7.0 a server whose UDP announcements lapse is kept while it answers a
|
|
19
|
+
PING. But the cluster manager reports a lapse once and arms no further
|
|
20
|
+
liveness check, so nothing looked at a kept server again: if its
|
|
21
|
+
announcements never resumed and the broker then stopped answering — its
|
|
22
|
+
connection open and nothing coming back, as with a frozen or partitioned
|
|
23
|
+
host — it kept its share of round-robin and every call routed to it timed
|
|
24
|
+
out. Measured with two brokers at 50 calls/s, one kept and then frozen for
|
|
25
|
+
25 s: 822 calls timed out, and the broker was never removed. Now a kept
|
|
26
|
+
server is asked again at the interval it announced itself at (one second
|
|
27
|
+
by default, never less), for as long as its announcements stay away, and is
|
|
28
|
+
drained and removed the first time it does not answer within
|
|
29
|
+
`IMQ_LAPSED_ANSWER_TIMEOUT`. The same run lost 93 calls, those already sent
|
|
30
|
+
to the broker before it was removed 3 s after it froze. The check stops when
|
|
31
|
+
the server's announcements resume, when it is removed, and on `destroy()`;
|
|
32
|
+
nothing is scheduled for a server whose announcements never lapsed.
|
|
33
|
+
|
|
34
|
+
A lapse means the announcements did not arrive — lost on the network, or
|
|
35
|
+
not sent by the announcer — not that the receiving process was busy:
|
|
36
|
+
holding a service's event loop for 10 s, and stopping its whole process for
|
|
37
|
+
10 s, both kept their brokers with no lapse, since announcements are
|
|
38
|
+
received on the UDP worker thread and datagrams already buffered renew the
|
|
39
|
+
server before its expiry is acted on.
|
|
40
|
+
|
|
41
|
+
### Added
|
|
42
|
+
|
|
43
|
+
- **`IServerInput.timeout`**, how long a server may go unheard, in
|
|
44
|
+
milliseconds, as announced to a discovering cluster manager.
|
|
45
|
+
`UDPClusterManager` sets it from the announcement's interval, static
|
|
46
|
+
`cluster` entries leave it out, and a clustered queue re-checks a server
|
|
47
|
+
kept after its announcements lapsed at that interval (never less than one
|
|
48
|
+
second, and one second where it is missing).
|
|
49
|
+
|
|
50
|
+
### Changed
|
|
51
|
+
|
|
52
|
+
- **The UDP cluster manager tells a cluster when a server it already has
|
|
53
|
+
announces itself again after a lapse.** Repeat announcements of a known
|
|
54
|
+
server were all withheld from the cluster, so a cluster that kept a lapsed
|
|
55
|
+
server could not learn that its announcements had resumed. With the alive
|
|
56
|
+
check on, the first announcement the manager hears from a server — after a
|
|
57
|
+
lapse, or at all — now reaches the cluster's `add()` even where the cluster
|
|
58
|
+
already has that server; later ones are withheld as before. `add()` is
|
|
59
|
+
idempotent, so a custom cluster sees one extra call per resumption (and one
|
|
60
|
+
at start for a server it was configured with) and nothing else changes.
|
|
61
|
+
|
|
62
|
+
## [3.7.0] - 2026-11-22
|
|
63
|
+
|
|
64
|
+
### Fixed
|
|
65
|
+
|
|
66
|
+
- **A broker whose heartbeats lapsed was dropped while its connections were
|
|
67
|
+
healthy, and the replies it had already delivered were lost.** The UDP
|
|
68
|
+
cluster manager removes a server once it misses its heartbeats for the
|
|
69
|
+
check's timeout. A lapse means only that the announcements did not arrive —
|
|
70
|
+
lost on the network, or not sent by the announcer — not that the broker is
|
|
71
|
+
gone, and the removal destroyed the server's queue at once: its listeners went
|
|
72
|
+
before its reader was disconnected, so a reply already read was dropped and
|
|
73
|
+
its caller waited out its whole timeout. Now a server removed for lapsed
|
|
74
|
+
heartbeats is asked first; one that answers within
|
|
75
|
+
`IMQ_LAPSED_ANSWER_TIMEOUT` (2 s) is kept. One that does not is drained
|
|
76
|
+
before it is destroyed: its blocked read is unblocked, and what it already
|
|
77
|
+
read is handed on before its listeners go.
|
|
78
|
+
|
|
79
|
+
### Added
|
|
80
|
+
|
|
81
|
+
- **`IMQ_LAPSED_ANSWER_TIMEOUT`**, how long a server whose heartbeats lapsed
|
|
82
|
+
has to answer before it is removed, in milliseconds (default 2000).
|
|
83
|
+
- **`ServerRemoval`**, the optional second argument of a cluster's
|
|
84
|
+
`remove()`: `{ lapsed: true }` where the removal is for missed heartbeats
|
|
85
|
+
rather than a server that said it was leaving.
|
|
86
|
+
|
|
12
87
|
## [3.6.0] - 2026-11-12
|
|
13
88
|
|
|
14
89
|
### Added
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@imqueue/core",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.8.0",
|
|
4
4
|
"description": "Fast JSON message queue over Redis for inter-service communication in Node.js & TypeScript microservices — the transport layer of the @imqueue framework",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"message-queue",
|
package/src/ClusterManager.d.ts
CHANGED
|
@@ -1,4 +1,14 @@
|
|
|
1
1
|
import { type IMessageQueueConnection, type IServerInput } from './IMessageQueue.js';
|
|
2
|
+
/**
|
|
3
|
+
* Why a {@link ClusterManager} removes a server, where it can say.
|
|
4
|
+
*/
|
|
5
|
+
export interface ServerRemoval {
|
|
6
|
+
/**
|
|
7
|
+
* True where the server's announcements stopped arriving and nothing said
|
|
8
|
+
* it went away: a missed heartbeat, not a `down` notice.
|
|
9
|
+
*/
|
|
10
|
+
lapsed?: boolean;
|
|
11
|
+
}
|
|
2
12
|
/**
|
|
3
13
|
* Membership callbacks a clustered queue hands to a {@link ClusterManager} so
|
|
4
14
|
* the manager can add and remove servers as it discovers them.
|
|
@@ -10,13 +20,18 @@ export interface ICluster {
|
|
|
10
20
|
/**
|
|
11
21
|
* Adds a server to the cluster and returns its registration record.
|
|
12
22
|
* Registration is idempotent — an already-known server is returned
|
|
13
|
-
* unchanged.
|
|
23
|
+
* unchanged. A manager calls it again for a known server whose
|
|
24
|
+
* announcements resumed after a lapse, so a cluster still checking that
|
|
25
|
+
* server can stop.
|
|
14
26
|
*/
|
|
15
27
|
add: (server: IServerInput) => IMessageQueueConnection;
|
|
16
28
|
/**
|
|
17
29
|
* Removes a server from the cluster. A no-op when the server is unknown.
|
|
30
|
+
* With `removal.lapsed`, only the server's announcements stopped arriving,
|
|
31
|
+
* and a cluster may keep a server that still answers on its connections —
|
|
32
|
+
* checking it itself until it stops answering or `add` reports it again.
|
|
18
33
|
*/
|
|
19
|
-
remove: (server: IServerInput) => void;
|
|
34
|
+
remove: (server: IServerInput, removal?: ServerRemoval) => void;
|
|
20
35
|
/**
|
|
21
36
|
* Looks a server up, matching by `id` when both sides carry one and by host
|
|
22
37
|
* and port otherwise. Returns `undefined` when it is not registered.
|
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
* <support@imqueue.com> to get commercial licensing options.
|
|
23
23
|
*/
|
|
24
24
|
import { EventEmitter } from 'node:events';
|
|
25
|
+
import { type ServerRemoval } from './ClusterManager.js';
|
|
25
26
|
import { type EventMap, type ILogger, type IMessageQueue, type IMessageQueueConnection, IMQMode, type IMQOptions, type IServerInput, type JsonObject, RedisQueue } from './index.js';
|
|
26
27
|
/**
|
|
27
28
|
* A server registered in a {@link ClusteredRedisQueue}: its address, plus the
|
|
@@ -164,6 +165,8 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
|
|
|
164
165
|
private readonly waitingSends;
|
|
165
166
|
/** Pending startup shared by batch startup and joining-host initialization. */
|
|
166
167
|
private readonly starting;
|
|
168
|
+
/** Servers kept after their announcements lapsed, while they stay silent. */
|
|
169
|
+
private readonly lapsedWatches;
|
|
167
170
|
/** Membership admission stays closed after the first destroy() call. */
|
|
168
171
|
private closed;
|
|
169
172
|
/** Failed cleanup tasks remain here for an explicit destroy() retry. */
|
|
@@ -610,17 +613,85 @@ export declare class ClusteredRedisQueue implements IMessageQueue, EventEmitter<
|
|
|
610
613
|
* Removes a server from the cluster, matching by `id` or by host and port.
|
|
611
614
|
*
|
|
612
615
|
* @param server - address of the server to remove
|
|
616
|
+
* @param removal - why it is removed, where the manager can say
|
|
613
617
|
*
|
|
614
618
|
* @remarks
|
|
615
619
|
* A silent no-op when no server matches. Routing stops using the host
|
|
616
620
|
* immediately, but teardown of its redis connections is started in the
|
|
617
|
-
* background and not awaited:
|
|
618
|
-
* and teardown errors are only logged.
|
|
621
|
+
* background and not awaited: what its reader already took is drained to
|
|
622
|
+
* the listeners first, and teardown errors are only logged.
|
|
623
|
+
*
|
|
624
|
+
* With `removal.lapsed` the server is not removed yet: it is asked a PING
|
|
625
|
+
* and kept while it answers within `IMQ_LAPSED_ANSWER_TIMEOUT`, asked
|
|
626
|
+
* again at the interval it announced itself at for as long as its
|
|
627
|
+
* announcements stay away, and removed the first time it does not answer.
|
|
628
|
+
* An `add` for the same server ends that watch.
|
|
619
629
|
*
|
|
620
630
|
* Because the underlying queues are matched by host and port, all entries
|
|
621
631
|
* sharing an address are removed together.
|
|
622
632
|
*/
|
|
623
|
-
protected removeServer(server: IServerInput): void;
|
|
633
|
+
protected removeServer(server: IServerInput, removal?: ServerRemoval): void;
|
|
634
|
+
/**
|
|
635
|
+
* Starts watching a server whose announcements lapsed: it is kept while
|
|
636
|
+
* it answers a PING, and dropped the first time it does not.
|
|
637
|
+
*
|
|
638
|
+
* @param server - the removal's address, carrying the interval the server
|
|
639
|
+
* announced itself at where the manager knows it
|
|
640
|
+
* @param imq - the queue serving that server
|
|
641
|
+
*
|
|
642
|
+
* @remarks
|
|
643
|
+
* Once a server is kept, nothing else would look at it again: its cluster
|
|
644
|
+
* manager has already reported the lapse and arms no further liveness
|
|
645
|
+
* check. Without this watch a kept broker that later hung - its socket
|
|
646
|
+
* open, nothing answering - stayed in round-robin until the process
|
|
647
|
+
* restarted, and every call routed to it timed out.
|
|
648
|
+
*
|
|
649
|
+
* A repeated lapse for a server already watched is ignored: the watch in
|
|
650
|
+
* progress already decides it.
|
|
651
|
+
*/
|
|
652
|
+
private watchLapsed;
|
|
653
|
+
/**
|
|
654
|
+
* Asks a lapsed server whether it answers, keeps it and schedules the
|
|
655
|
+
* next check where it does, and drops it where it does not.
|
|
656
|
+
*
|
|
657
|
+
* @param server - the removal's address
|
|
658
|
+
* @param imq - the queue serving that server
|
|
659
|
+
* @param watch - the watch this check belongs to; a check whose watch has
|
|
660
|
+
* ended meanwhile does nothing
|
|
661
|
+
* @param first - whether this is the check made when the lapse was
|
|
662
|
+
* reported, which is the one that logs the server as kept
|
|
663
|
+
*/
|
|
664
|
+
private checkLapsed;
|
|
665
|
+
/**
|
|
666
|
+
* Ends the watch over a lapsed server: its announcements resumed, it is
|
|
667
|
+
* being removed, or the cluster is being destroyed.
|
|
668
|
+
*
|
|
669
|
+
* @param imq - the queue serving that server
|
|
670
|
+
* @returns whether a watch was in progress
|
|
671
|
+
*/
|
|
672
|
+
private cancelLapsed;
|
|
673
|
+
/**
|
|
674
|
+
* How long to wait before asking a kept server again.
|
|
675
|
+
*
|
|
676
|
+
* @param server - the removal's address
|
|
677
|
+
* @returns the interval the server announced itself at, where the
|
|
678
|
+
* removal carries it, but never less than
|
|
679
|
+
* {@link LAPSED_RECHECK_INTERVAL}
|
|
680
|
+
*
|
|
681
|
+
* @remarks
|
|
682
|
+
* The interval is {@link IServerInput.timeout}, which
|
|
683
|
+
* {@link UDPClusterManager} sets from the announcement. A manager that
|
|
684
|
+
* does not set it, or sets a value that is not a positive number, gets
|
|
685
|
+
* the default.
|
|
686
|
+
*/
|
|
687
|
+
private static recheckInterval;
|
|
688
|
+
/**
|
|
689
|
+
* Removes a server known to be gone: out of routing at once, its queue
|
|
690
|
+
* drained of what it already read and then torn down.
|
|
691
|
+
*
|
|
692
|
+
* @param server - address of the server to remove
|
|
693
|
+
*/
|
|
694
|
+
private dropServer;
|
|
624
695
|
/**
|
|
625
696
|
* Adds a server to the cluster, optionally bringing its queue up to the
|
|
626
697
|
* cluster's current state.
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
*/
|
|
24
24
|
import { EventEmitter } from 'node:events';
|
|
25
25
|
import {} from './ClusterManager.js';
|
|
26
|
-
import { buildOptions, copyEventEmitter, errorCode } from './helpers/index.js';
|
|
26
|
+
import { buildOptions, copyEventEmitter, envInt, errorCode, } from './helpers/index.js';
|
|
27
27
|
import { DEFAULT_IMQ_OPTIONS, IMQMode, RedisQueue, } from './index.js';
|
|
28
28
|
/**
|
|
29
29
|
* Time (ms) send() waits for the first cluster server to become available
|
|
@@ -40,6 +40,32 @@ const SEND_INIT_TIMEOUT = +(process.env.IMQ_SEND_INIT_TIMEOUT || 0) || 30000;
|
|
|
40
40
|
const SYNC_RETRY_BASE_DELAY = 1000;
|
|
41
41
|
/** Longest delay (ms) between subscription catch-up retries. */
|
|
42
42
|
const SYNC_RETRY_MAX_DELAY = 30000;
|
|
43
|
+
/**
|
|
44
|
+
* Time (ms) a server whose announcements lapsed is given to answer a PING
|
|
45
|
+
* before it is removed. Configurable via the IMQ_LAPSED_ANSWER_TIMEOUT
|
|
46
|
+
* environment variable, defaults to 2,000.
|
|
47
|
+
*/
|
|
48
|
+
const LAPSED_ANSWER_TIMEOUT = envInt('IMQ_LAPSED_ANSWER_TIMEOUT', 2000);
|
|
49
|
+
/**
|
|
50
|
+
* Shortest interval (ms) between two checks of a server kept after its
|
|
51
|
+
* announcements lapsed, and the interval used where the removal does not say
|
|
52
|
+
* how often the server announced itself.
|
|
53
|
+
*
|
|
54
|
+
* @remarks
|
|
55
|
+
* A kept server is asked again at the interval it announced itself at - the
|
|
56
|
+
* `timeout` a UDP announcement carries, how long its sender may go unheard,
|
|
57
|
+
* which brokers set to their announcement interval (`REDIS_BROADCAST_INTERVAL`,
|
|
58
|
+
* one second by default). The cluster does not know the manager's
|
|
59
|
+
* `aliveTimeoutCorrection`, and does not need it: that correction is slack
|
|
60
|
+
* for datagrams lost on the way, while a PING travels on the connection the
|
|
61
|
+
* queue already holds and carries its own budget,
|
|
62
|
+
* {@link LAPSED_ANSWER_TIMEOUT}. So a broker kept
|
|
63
|
+
* while silent is watched at the cadence its announcements promised, and one
|
|
64
|
+
* that hangs is out of routing within that interval plus the answer budget.
|
|
65
|
+
* The floor keeps a server announcing a zero or tiny interval from turning
|
|
66
|
+
* the check into a PING loop.
|
|
67
|
+
*/
|
|
68
|
+
const LAPSED_RECHECK_INTERVAL = 1000;
|
|
43
69
|
/**
|
|
44
70
|
* Scales a single logical queue horizontally across several redis instances.
|
|
45
71
|
* This is what {@link IMQ.create} returns when {@link IMQOptions.cluster} or
|
|
@@ -150,6 +176,8 @@ export class ClusteredRedisQueue {
|
|
|
150
176
|
waitingSends = new Set();
|
|
151
177
|
/** Pending startup shared by batch startup and joining-host initialization. */
|
|
152
178
|
starting = new WeakMap();
|
|
179
|
+
/** Servers kept after their announcements lapsed, while they stay silent. */
|
|
180
|
+
lapsedWatches = new Map();
|
|
153
181
|
/** Membership admission stays closed after the first destroy() call. */
|
|
154
182
|
closed = false;
|
|
155
183
|
/** Failed cleanup tasks remain here for an explicit destroy() retry. */
|
|
@@ -374,6 +402,7 @@ export class ClusteredRedisQueue {
|
|
|
374
402
|
this.state.started = false;
|
|
375
403
|
for (const imq of this.imqs) {
|
|
376
404
|
this.cancelSync(imq);
|
|
405
|
+
this.cancelLapsed(imq);
|
|
377
406
|
this.cleanup.add(() => imq.destroy());
|
|
378
407
|
}
|
|
379
408
|
for (const manager of this.options.clusterManagers || []) {
|
|
@@ -870,26 +899,163 @@ export class ClusteredRedisQueue {
|
|
|
870
899
|
* Removes a server from the cluster, matching by `id` or by host and port.
|
|
871
900
|
*
|
|
872
901
|
* @param server - address of the server to remove
|
|
902
|
+
* @param removal - why it is removed, where the manager can say
|
|
873
903
|
*
|
|
874
904
|
* @remarks
|
|
875
905
|
* A silent no-op when no server matches. Routing stops using the host
|
|
876
906
|
* immediately, but teardown of its redis connections is started in the
|
|
877
|
-
* background and not awaited:
|
|
878
|
-
* and teardown errors are only logged.
|
|
907
|
+
* background and not awaited: what its reader already took is drained to
|
|
908
|
+
* the listeners first, and teardown errors are only logged.
|
|
909
|
+
*
|
|
910
|
+
* With `removal.lapsed` the server is not removed yet: it is asked a PING
|
|
911
|
+
* and kept while it answers within `IMQ_LAPSED_ANSWER_TIMEOUT`, asked
|
|
912
|
+
* again at the interval it announced itself at for as long as its
|
|
913
|
+
* announcements stay away, and removed the first time it does not answer.
|
|
914
|
+
* An `add` for the same server ends that watch.
|
|
879
915
|
*
|
|
880
916
|
* Because the underlying queues are matched by host and port, all entries
|
|
881
917
|
* sharing an address are removed together.
|
|
882
918
|
*/
|
|
883
|
-
removeServer(server) {
|
|
919
|
+
removeServer(server, removal) {
|
|
884
920
|
this.verbose(`Removing the server: ${JSON.stringify(server)}`);
|
|
921
|
+
const remove = this.findServer(server);
|
|
922
|
+
if (!remove) {
|
|
923
|
+
return;
|
|
924
|
+
}
|
|
925
|
+
// only its announcements lapsed, and a lapse says only that they
|
|
926
|
+
// stopped arriving - lost on the network, or not sent - not that the
|
|
927
|
+
// broker is gone. So the broker is asked first, kept where it still
|
|
928
|
+
// answers, and asked again for as long as it stays silent
|
|
929
|
+
if (removal?.lapsed && remove.imq) {
|
|
930
|
+
this.watchLapsed(server, remove.imq);
|
|
931
|
+
return;
|
|
932
|
+
}
|
|
933
|
+
this.dropServer(server);
|
|
934
|
+
}
|
|
935
|
+
/**
|
|
936
|
+
* Starts watching a server whose announcements lapsed: it is kept while
|
|
937
|
+
* it answers a PING, and dropped the first time it does not.
|
|
938
|
+
*
|
|
939
|
+
* @param server - the removal's address, carrying the interval the server
|
|
940
|
+
* announced itself at where the manager knows it
|
|
941
|
+
* @param imq - the queue serving that server
|
|
942
|
+
*
|
|
943
|
+
* @remarks
|
|
944
|
+
* Once a server is kept, nothing else would look at it again: its cluster
|
|
945
|
+
* manager has already reported the lapse and arms no further liveness
|
|
946
|
+
* check. Without this watch a kept broker that later hung - its socket
|
|
947
|
+
* open, nothing answering - stayed in round-robin until the process
|
|
948
|
+
* restarted, and every call routed to it timed out.
|
|
949
|
+
*
|
|
950
|
+
* A repeated lapse for a server already watched is ignored: the watch in
|
|
951
|
+
* progress already decides it.
|
|
952
|
+
*/
|
|
953
|
+
watchLapsed(server, imq) {
|
|
954
|
+
if (this.closed || this.lapsedWatches.has(imq)) {
|
|
955
|
+
return;
|
|
956
|
+
}
|
|
957
|
+
const watch = {};
|
|
958
|
+
this.lapsedWatches.set(imq, watch);
|
|
959
|
+
this.checkLapsed(server, imq, watch, true);
|
|
960
|
+
}
|
|
961
|
+
/**
|
|
962
|
+
* Asks a lapsed server whether it answers, keeps it and schedules the
|
|
963
|
+
* next check where it does, and drops it where it does not.
|
|
964
|
+
*
|
|
965
|
+
* @param server - the removal's address
|
|
966
|
+
* @param imq - the queue serving that server
|
|
967
|
+
* @param watch - the watch this check belongs to; a check whose watch has
|
|
968
|
+
* ended meanwhile does nothing
|
|
969
|
+
* @param first - whether this is the check made when the lapse was
|
|
970
|
+
* reported, which is the one that logs the server as kept
|
|
971
|
+
*/
|
|
972
|
+
checkLapsed(server, imq, watch, first) {
|
|
973
|
+
void imq.answers(LAPSED_ANSWER_TIMEOUT).then(answers => {
|
|
974
|
+
// announcements resumed, the server was removed or the cluster
|
|
975
|
+
// destroyed while the PING was out: this verdict is no longer
|
|
976
|
+
// anybody's to act on
|
|
977
|
+
if (this.closed || this.lapsedWatches.get(imq) !== watch) {
|
|
978
|
+
return;
|
|
979
|
+
}
|
|
980
|
+
if (!answers) {
|
|
981
|
+
this.lapsedWatches.delete(imq);
|
|
982
|
+
if (this.findServer(server)?.imq === imq) {
|
|
983
|
+
if (!first) {
|
|
984
|
+
this.verbose(`Removing the server ${imq.redisKey}: kept after its announcements lapsed, it no longer answers`);
|
|
985
|
+
}
|
|
986
|
+
this.dropServer(server);
|
|
987
|
+
}
|
|
988
|
+
return;
|
|
989
|
+
}
|
|
990
|
+
if (first) {
|
|
991
|
+
this.verbose(`Kept the server ${imq.redisKey}: its announcements lapsed, but it answers`);
|
|
992
|
+
}
|
|
993
|
+
const timer = setTimeout(() => {
|
|
994
|
+
watch.timer = undefined;
|
|
995
|
+
if (!this.closed && this.lapsedWatches.get(imq) === watch) {
|
|
996
|
+
this.checkLapsed(server, imq, watch, false);
|
|
997
|
+
}
|
|
998
|
+
}, ClusteredRedisQueue.recheckInterval(server));
|
|
999
|
+
// a kept server must not hold the process open on its own
|
|
1000
|
+
timer.unref?.();
|
|
1001
|
+
watch.timer = timer;
|
|
1002
|
+
});
|
|
1003
|
+
}
|
|
1004
|
+
/**
|
|
1005
|
+
* Ends the watch over a lapsed server: its announcements resumed, it is
|
|
1006
|
+
* being removed, or the cluster is being destroyed.
|
|
1007
|
+
*
|
|
1008
|
+
* @param imq - the queue serving that server
|
|
1009
|
+
* @returns whether a watch was in progress
|
|
1010
|
+
*/
|
|
1011
|
+
cancelLapsed(imq) {
|
|
1012
|
+
const watch = this.lapsedWatches.get(imq);
|
|
1013
|
+
if (!watch) {
|
|
1014
|
+
return false;
|
|
1015
|
+
}
|
|
1016
|
+
clearTimeout(watch.timer);
|
|
1017
|
+
this.lapsedWatches.delete(imq);
|
|
1018
|
+
return true;
|
|
1019
|
+
}
|
|
1020
|
+
/**
|
|
1021
|
+
* How long to wait before asking a kept server again.
|
|
1022
|
+
*
|
|
1023
|
+
* @param server - the removal's address
|
|
1024
|
+
* @returns the interval the server announced itself at, where the
|
|
1025
|
+
* removal carries it, but never less than
|
|
1026
|
+
* {@link LAPSED_RECHECK_INTERVAL}
|
|
1027
|
+
*
|
|
1028
|
+
* @remarks
|
|
1029
|
+
* The interval is {@link IServerInput.timeout}, which
|
|
1030
|
+
* {@link UDPClusterManager} sets from the announcement. A manager that
|
|
1031
|
+
* does not set it, or sets a value that is not a positive number, gets
|
|
1032
|
+
* the default.
|
|
1033
|
+
*/
|
|
1034
|
+
static recheckInterval(server) {
|
|
1035
|
+
const announced = server.timeout;
|
|
1036
|
+
return announced !== undefined &&
|
|
1037
|
+
Number.isFinite(announced) &&
|
|
1038
|
+
announced > 0
|
|
1039
|
+
? Math.max(LAPSED_RECHECK_INTERVAL, announced)
|
|
1040
|
+
: LAPSED_RECHECK_INTERVAL;
|
|
1041
|
+
}
|
|
1042
|
+
/**
|
|
1043
|
+
* Removes a server known to be gone: out of routing at once, its queue
|
|
1044
|
+
* drained of what it already read and then torn down.
|
|
1045
|
+
*
|
|
1046
|
+
* @param server - address of the server to remove
|
|
1047
|
+
*/
|
|
1048
|
+
dropServer(server) {
|
|
885
1049
|
const remove = this.findServer(server);
|
|
886
1050
|
if (!remove) {
|
|
887
1051
|
return;
|
|
888
1052
|
}
|
|
889
1053
|
const imqToRemove = remove.imq;
|
|
890
1054
|
if (imqToRemove) {
|
|
891
|
-
// a retry scheduled for this host must not
|
|
1055
|
+
// a retry or a lapse check scheduled for this host must not
|
|
1056
|
+
// outlive it
|
|
892
1057
|
this.cancelSync(imqToRemove);
|
|
1058
|
+
this.cancelLapsed(imqToRemove);
|
|
893
1059
|
// dropped from routing first: a catch-up run in progress tests
|
|
894
1060
|
// membership between handlers and stops as soon as it sees this
|
|
895
1061
|
this.imqs = this.imqs.filter(imq => imqToRemove.redisKey !== imq.redisKey);
|
|
@@ -897,8 +1063,11 @@ export class ClusteredRedisQueue {
|
|
|
897
1063
|
// connection that never answers would then never be torn down at
|
|
898
1064
|
// all, and teardown is the one operation that has to happen
|
|
899
1065
|
// regardless of what the host is doing
|
|
1066
|
+
// drained first: a reply its reader already took from the
|
|
1067
|
+
// broker reaches its caller rather than going with the socket
|
|
900
1068
|
imqToRemove
|
|
901
|
-
.
|
|
1069
|
+
.drain()
|
|
1070
|
+
.then(() => imqToRemove.destroy())
|
|
902
1071
|
.catch((err) => this.verbose(`Error destroying removed server: ${err}`));
|
|
903
1072
|
}
|
|
904
1073
|
this.imqLength = this.imqs.length;
|
|
@@ -925,6 +1094,12 @@ export class ClusteredRedisQueue {
|
|
|
925
1094
|
}
|
|
926
1095
|
const existingServer = this.findServer(server);
|
|
927
1096
|
if (existingServer) {
|
|
1097
|
+
// a server kept after its announcements lapsed is announcing
|
|
1098
|
+
// itself again: it is back under its manager's liveness check,
|
|
1099
|
+
// and no longer needs this cluster's
|
|
1100
|
+
if (existingServer.imq && this.cancelLapsed(existingServer.imq)) {
|
|
1101
|
+
this.verbose(`Stopped checking the server ${existingServer.imq.redisKey}: its announcements resumed`);
|
|
1102
|
+
}
|
|
928
1103
|
return existingServer;
|
|
929
1104
|
}
|
|
930
1105
|
const newServer = {
|
package/src/IMessageQueue.d.ts
CHANGED
|
@@ -137,6 +137,18 @@ export interface IServerInput {
|
|
|
137
137
|
* TCP port the server listens on.
|
|
138
138
|
*/
|
|
139
139
|
port: number;
|
|
140
|
+
/**
|
|
141
|
+
* How long this server may go unheard, in milliseconds, as announced to a
|
|
142
|
+
* discovering cluster manager — {@link UDPClusterManager} sets it from the
|
|
143
|
+
* interval carried by the server's announcement. Static `cluster` entries
|
|
144
|
+
* leave it out.
|
|
145
|
+
*
|
|
146
|
+
* @remarks
|
|
147
|
+
* {@link ClusteredRedisQueue} uses it as the interval at which it asks a
|
|
148
|
+
* server kept after its announcements lapsed whether it still answers,
|
|
149
|
+
* never less than one second, and one second where it is missing.
|
|
150
|
+
*/
|
|
151
|
+
timeout?: number;
|
|
140
152
|
}
|
|
141
153
|
/**
|
|
142
154
|
* A single queue-host endpoint: where to connect and, optionally, how to
|
package/src/RedisQueue.d.ts
CHANGED
|
@@ -152,6 +152,20 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
|
|
|
152
152
|
* Reader connection associated with this queue instance
|
|
153
153
|
*/
|
|
154
154
|
private reader?;
|
|
155
|
+
/**
|
|
156
|
+
* The reader's id on the broker, which {@link RedisQueue.drain} unblocks
|
|
157
|
+
* it by from another connection.
|
|
158
|
+
*/
|
|
159
|
+
private readerId?;
|
|
160
|
+
/**
|
|
161
|
+
* The read loop running on the reader, settled once it stops.
|
|
162
|
+
*/
|
|
163
|
+
private reading?;
|
|
164
|
+
/**
|
|
165
|
+
* Set while {@link RedisQueue.drain} runs: the read loop hands on what it
|
|
166
|
+
* already read and stops instead of reading again.
|
|
167
|
+
*/
|
|
168
|
+
private draining;
|
|
155
169
|
/**
|
|
156
170
|
* Channel connection associated with this queue instance
|
|
157
171
|
* Specially designed for client subscriptions to server-emitted events
|
|
@@ -624,6 +638,34 @@ export declare class RedisQueue extends EventEmitter<EventMap> implements IMessa
|
|
|
624
638
|
* server the same way reports the same value.
|
|
625
639
|
*/
|
|
626
640
|
get available(): boolean;
|
|
641
|
+
/**
|
|
642
|
+
* Whether the broker answers this queue's writer within the given time.
|
|
643
|
+
*
|
|
644
|
+
* @param timeoutMs - how long to wait for its answer, in milliseconds
|
|
645
|
+
* @returns true where a PING came back in time, false otherwise
|
|
646
|
+
*
|
|
647
|
+
* @remarks
|
|
648
|
+
* A connection that only reports itself ready may sit on a socket nobody
|
|
649
|
+
* answers; this asks the broker itself. Never rejects.
|
|
650
|
+
*/
|
|
651
|
+
answers(timeoutMs: number): Promise<boolean>;
|
|
652
|
+
/**
|
|
653
|
+
* Stops reading and hands on every message the reader already took from
|
|
654
|
+
* the broker, before a teardown that would drop the reader at once.
|
|
655
|
+
*
|
|
656
|
+
* @param timeoutMs - how long to wait for the read loop to stop, in
|
|
657
|
+
* milliseconds
|
|
658
|
+
*
|
|
659
|
+
* @remarks
|
|
660
|
+
* The reader is released from its blocking read by `CLIENT UNBLOCK` sent
|
|
661
|
+
* on the writer. A message the broker already handed it is still in the
|
|
662
|
+
* socket, ahead of the release, so it reaches the `message` listeners
|
|
663
|
+
* before the loop stops; nothing further is taken. Without this, a reply
|
|
664
|
+
* popped but not yet read was lost with the socket, and its caller waited
|
|
665
|
+
* out its whole timeout. Never rejects; a host that does not answer is
|
|
666
|
+
* given up on after `timeoutMs`.
|
|
667
|
+
*/
|
|
668
|
+
drain(timeoutMs?: number): Promise<void>;
|
|
627
669
|
/**
|
|
628
670
|
* Writer connection associated with this queue instance. Shared by every
|
|
629
671
|
* queue in the process that targets the same {@link RedisQueue.poolKey}.
|
package/src/RedisQueue.js
CHANGED
|
@@ -269,6 +269,20 @@ let RedisQueue = (() => {
|
|
|
269
269
|
* Reader connection associated with this queue instance
|
|
270
270
|
*/
|
|
271
271
|
reader;
|
|
272
|
+
/**
|
|
273
|
+
* The reader's id on the broker, which {@link RedisQueue.drain} unblocks
|
|
274
|
+
* it by from another connection.
|
|
275
|
+
*/
|
|
276
|
+
readerId;
|
|
277
|
+
/**
|
|
278
|
+
* The read loop running on the reader, settled once it stops.
|
|
279
|
+
*/
|
|
280
|
+
reading;
|
|
281
|
+
/**
|
|
282
|
+
* Set while {@link RedisQueue.drain} runs: the read loop hands on what it
|
|
283
|
+
* already read and stops instead of reading again.
|
|
284
|
+
*/
|
|
285
|
+
draining = false;
|
|
272
286
|
/**
|
|
273
287
|
* Channel connection associated with this queue instance
|
|
274
288
|
* Specially designed for client subscriptions to server-emitted events
|
|
@@ -1145,6 +1159,84 @@ let RedisQueue = (() => {
|
|
|
1145
1159
|
get available() {
|
|
1146
1160
|
return !this.writer || this.writer.status === 'ready';
|
|
1147
1161
|
}
|
|
1162
|
+
/**
|
|
1163
|
+
* Whether the broker answers this queue's writer within the given time.
|
|
1164
|
+
*
|
|
1165
|
+
* @param timeoutMs - how long to wait for its answer, in milliseconds
|
|
1166
|
+
* @returns true where a PING came back in time, false otherwise
|
|
1167
|
+
*
|
|
1168
|
+
* @remarks
|
|
1169
|
+
* A connection that only reports itself ready may sit on a socket nobody
|
|
1170
|
+
* answers; this asks the broker itself. Never rejects.
|
|
1171
|
+
*/
|
|
1172
|
+
async answers(timeoutMs) {
|
|
1173
|
+
const writer = this.writer;
|
|
1174
|
+
if (!writer || writer.status !== 'ready' || this.destroyed) {
|
|
1175
|
+
return false;
|
|
1176
|
+
}
|
|
1177
|
+
let timer;
|
|
1178
|
+
try {
|
|
1179
|
+
return await Promise.race([
|
|
1180
|
+
writer.ping().then(reply => reply === 'PONG'),
|
|
1181
|
+
new Promise(resolve => {
|
|
1182
|
+
timer = setTimeout(() => resolve(false), timeoutMs);
|
|
1183
|
+
timer.unref();
|
|
1184
|
+
}),
|
|
1185
|
+
]);
|
|
1186
|
+
}
|
|
1187
|
+
catch {
|
|
1188
|
+
return false;
|
|
1189
|
+
}
|
|
1190
|
+
finally {
|
|
1191
|
+
clearTimeout(timer);
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
/**
|
|
1195
|
+
* Stops reading and hands on every message the reader already took from
|
|
1196
|
+
* the broker, before a teardown that would drop the reader at once.
|
|
1197
|
+
*
|
|
1198
|
+
* @param timeoutMs - how long to wait for the read loop to stop, in
|
|
1199
|
+
* milliseconds
|
|
1200
|
+
*
|
|
1201
|
+
* @remarks
|
|
1202
|
+
* The reader is released from its blocking read by `CLIENT UNBLOCK` sent
|
|
1203
|
+
* on the writer. A message the broker already handed it is still in the
|
|
1204
|
+
* socket, ahead of the release, so it reaches the `message` listeners
|
|
1205
|
+
* before the loop stops; nothing further is taken. Without this, a reply
|
|
1206
|
+
* popped but not yet read was lost with the socket, and its caller waited
|
|
1207
|
+
* out its whole timeout. Never rejects; a host that does not answer is
|
|
1208
|
+
* given up on after `timeoutMs`.
|
|
1209
|
+
*/
|
|
1210
|
+
async drain(timeoutMs = IMQ_CONNECTION_QUIT_TIMEOUT) {
|
|
1211
|
+
const reading = this.reading;
|
|
1212
|
+
if (!this.reader || !reading || this.destroyed) {
|
|
1213
|
+
return;
|
|
1214
|
+
}
|
|
1215
|
+
this.draining = true;
|
|
1216
|
+
let timer;
|
|
1217
|
+
try {
|
|
1218
|
+
if (this.readerId !== undefined && this.writer) {
|
|
1219
|
+
await Promise.race([
|
|
1220
|
+
this.writer.client('UNBLOCK', this.readerId),
|
|
1221
|
+
new Promise(resolve => {
|
|
1222
|
+
timer = setTimeout(resolve, timeoutMs);
|
|
1223
|
+
timer.unref();
|
|
1224
|
+
}),
|
|
1225
|
+
]).catch(() => undefined);
|
|
1226
|
+
clearTimeout(timer);
|
|
1227
|
+
}
|
|
1228
|
+
await Promise.race([
|
|
1229
|
+
reading,
|
|
1230
|
+
new Promise(resolve => {
|
|
1231
|
+
timer = setTimeout(resolve, timeoutMs);
|
|
1232
|
+
timer.unref();
|
|
1233
|
+
}),
|
|
1234
|
+
]);
|
|
1235
|
+
}
|
|
1236
|
+
finally {
|
|
1237
|
+
clearTimeout(timer);
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1148
1240
|
/**
|
|
1149
1241
|
* Writer connection associated with this queue instance. Shared by every
|
|
1150
1242
|
* queue in the process that targets the same {@link RedisQueue.poolKey}.
|
|
@@ -1391,6 +1483,12 @@ let RedisQueue = (() => {
|
|
|
1391
1483
|
this.logger.info('%s: %s channel connected, host %s, pid %s', this.name, channel, this.redisKey, process.pid);
|
|
1392
1484
|
switch (channel) {
|
|
1393
1485
|
case 'reader':
|
|
1486
|
+
// asked before the first blocking read: a blocked reader
|
|
1487
|
+
// answers nothing else until its read returns
|
|
1488
|
+
this.readerId = await redis
|
|
1489
|
+
.client('ID')
|
|
1490
|
+
.then(id => Number(id))
|
|
1491
|
+
.catch(() => undefined);
|
|
1394
1492
|
this.read();
|
|
1395
1493
|
break;
|
|
1396
1494
|
case 'writer':
|
|
@@ -2041,7 +2139,7 @@ let RedisQueue = (() => {
|
|
|
2041
2139
|
try {
|
|
2042
2140
|
const key = this.key;
|
|
2043
2141
|
while (true) {
|
|
2044
|
-
if (!this.reader) {
|
|
2142
|
+
if (!this.reader || this.draining) {
|
|
2045
2143
|
break;
|
|
2046
2144
|
}
|
|
2047
2145
|
try {
|
|
@@ -2100,7 +2198,10 @@ let RedisQueue = (() => {
|
|
|
2100
2198
|
const timeout = Math.max(0.1, Math.min(Number(this.options.safeDeliveryTtl) / 2, READ_MAX_BLOCK) /
|
|
2101
2199
|
1000);
|
|
2102
2200
|
while (true) {
|
|
2103
|
-
if (!this.reader ||
|
|
2201
|
+
if (!this.reader ||
|
|
2202
|
+
!this.writer ||
|
|
2203
|
+
this.destroyed ||
|
|
2204
|
+
this.draining) {
|
|
2104
2205
|
break;
|
|
2105
2206
|
}
|
|
2106
2207
|
const expire = Date.now() + Number(this.options.safeDeliveryTtl);
|
|
@@ -2175,7 +2276,11 @@ let RedisQueue = (() => {
|
|
|
2175
2276
|
const runReader = this.options.safeDelivery
|
|
2176
2277
|
? this.readSafe
|
|
2177
2278
|
: this.readUnsafe;
|
|
2178
|
-
|
|
2279
|
+
this.reading = new Promise(resolve => {
|
|
2280
|
+
process.nextTick(() => {
|
|
2281
|
+
runReader.call(this).then(resolve, () => resolve());
|
|
2282
|
+
});
|
|
2283
|
+
});
|
|
2179
2284
|
return this;
|
|
2180
2285
|
}
|
|
2181
2286
|
/**
|
package/src/UDPClusterManager.js
CHANGED
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
*/
|
|
24
24
|
import { join } from 'node:path';
|
|
25
25
|
import { Worker } from 'node:worker_threads';
|
|
26
|
-
import { ClusterManager } from './ClusterManager.js';
|
|
26
|
+
import { ClusterManager, } from './ClusterManager.js';
|
|
27
27
|
import {} from './IMessageQueue.js';
|
|
28
28
|
const IMQ_UDP_CLUSTER_MANAGER_ALIVE_CHECK = !!+(process.env.IMQ_UDP_CLUSTER_MANAGER_ALIVE_CHECK || 1);
|
|
29
29
|
/** Delay (ms) before an unexpectedly dead worker is re-spawned */
|
|
@@ -307,11 +307,21 @@ export class UDPClusterManager extends ClusterManager {
|
|
|
307
307
|
}
|
|
308
308
|
const action = method;
|
|
309
309
|
await this.forEachCluster(cluster => {
|
|
310
|
+
// the worker's announcement, its `timeout` already converted from
|
|
311
|
+
// the wire's seconds to the milliseconds IServerInput declares
|
|
310
312
|
const server = message.server;
|
|
311
|
-
|
|
313
|
+
// a known server is announced again every interval, and only the
|
|
314
|
+
// first announcement after a lapse tells its cluster anything
|
|
315
|
+
if (action === 'add' &&
|
|
316
|
+
message.resumed !== true &&
|
|
317
|
+
cluster.find(server)) {
|
|
312
318
|
return;
|
|
313
319
|
}
|
|
314
320
|
const handler = cluster[action];
|
|
321
|
+
if (action === 'remove') {
|
|
322
|
+
handler?.(server, { lapsed: message.lapsed === true });
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
315
325
|
handler?.(server);
|
|
316
326
|
});
|
|
317
327
|
}
|
package/src/UDPWorker.d.ts
CHANGED
|
@@ -89,6 +89,13 @@ export declare class UDPWorker {
|
|
|
89
89
|
* when {@link UDPWorkerOptions.useAliveCheck} is on.
|
|
90
90
|
*
|
|
91
91
|
* @param message - the announcement that named it
|
|
92
|
+
*
|
|
93
|
+
* @remarks
|
|
94
|
+
* With the alive check on, the first announcement of a server this worker
|
|
95
|
+
* is not tracking - first heard, or heard again after its announcements
|
|
96
|
+
* lapsed - is marked `resumed`. The manager hands that one to a cluster
|
|
97
|
+
* even where the cluster already has the server: a cluster that kept a
|
|
98
|
+
* lapsed server learns from it that the server announces itself again.
|
|
92
99
|
*/
|
|
93
100
|
private addServer;
|
|
94
101
|
/**
|
|
@@ -96,6 +103,8 @@ export declare class UDPWorker {
|
|
|
96
103
|
*
|
|
97
104
|
* @param message - the announcement that named it, whether a `down` notice
|
|
98
105
|
* or the stale `up` whose liveness timer expired
|
|
106
|
+
* @param lapsed - true where only its announcements stopped arriving, and
|
|
107
|
+
* no `down` notice said it went away
|
|
99
108
|
*/
|
|
100
109
|
private removeServer;
|
|
101
110
|
/**
|
package/src/UDPWorker.js
CHANGED
|
@@ -140,11 +140,21 @@ export class UDPWorker {
|
|
|
140
140
|
* when {@link UDPWorkerOptions.useAliveCheck} is on.
|
|
141
141
|
*
|
|
142
142
|
* @param message - the announcement that named it
|
|
143
|
+
*
|
|
144
|
+
* @remarks
|
|
145
|
+
* With the alive check on, the first announcement of a server this worker
|
|
146
|
+
* is not tracking - first heard, or heard again after its announcements
|
|
147
|
+
* lapsed - is marked `resumed`. The manager hands that one to a cluster
|
|
148
|
+
* even where the cluster already has the server: a cluster that kept a
|
|
149
|
+
* lapsed server learns from it that the server announces itself again.
|
|
143
150
|
*/
|
|
144
151
|
addServer(message) {
|
|
152
|
+
const resumed = this.options.useAliveCheck &&
|
|
153
|
+
!this.servers.has(UDPWorker.getServerKey(message));
|
|
145
154
|
this.messagePort.postMessage({
|
|
146
155
|
type: 'cluster:add',
|
|
147
156
|
server: UDPWorker.mapMessage(message),
|
|
157
|
+
...(resumed ? { resumed } : {}),
|
|
148
158
|
});
|
|
149
159
|
if (this.options.useAliveCheck) {
|
|
150
160
|
this.serverAliveWait(message);
|
|
@@ -155,12 +165,15 @@ export class UDPWorker {
|
|
|
155
165
|
*
|
|
156
166
|
* @param message - the announcement that named it, whether a `down` notice
|
|
157
167
|
* or the stale `up` whose liveness timer expired
|
|
168
|
+
* @param lapsed - true where only its announcements stopped arriving, and
|
|
169
|
+
* no `down` notice said it went away
|
|
158
170
|
*/
|
|
159
|
-
removeServer(message) {
|
|
171
|
+
removeServer(message, lapsed = false) {
|
|
160
172
|
this.servers.delete(UDPWorker.getServerKey(message));
|
|
161
173
|
this.messagePort.postMessage({
|
|
162
174
|
type: 'cluster:remove',
|
|
163
175
|
server: UDPWorker.mapMessage(message),
|
|
176
|
+
lapsed,
|
|
164
177
|
});
|
|
165
178
|
}
|
|
166
179
|
/**
|
|
@@ -203,7 +216,7 @@ export class UDPWorker {
|
|
|
203
216
|
this.servers.set(key, stamp);
|
|
204
217
|
const timer = setTimeout(() => setImmediate(() => {
|
|
205
218
|
if (this.servers.get(key) === stamp) {
|
|
206
|
-
this.removeServer(message);
|
|
219
|
+
this.removeServer(message, true);
|
|
207
220
|
}
|
|
208
221
|
}), effectiveTimeout);
|
|
209
222
|
// a pending liveness timer must not keep the worker alive on its own
|
package/AGENTS.md
DELETED
|
@@ -1,150 +0,0 @@
|
|
|
1
|
-
# AGENTS.md — orientation for coding agents
|
|
2
|
-
|
|
3
|
-
This file is for AI coding agents (and humans who like density) working on
|
|
4
|
-
`@imqueue/core`. It captures how the codebase is built, tested and structured,
|
|
5
|
-
plus the invariants that are easy to get wrong. Read it before making changes.
|
|
6
|
-
For contribution *process/terms* see [CONTRIBUTING.md](./CONTRIBUTING.md); for
|
|
7
|
-
end-user docs see the [README](./README.md) and https://imqueue.org/.
|
|
8
|
-
|
|
9
|
-
## What this is
|
|
10
|
-
|
|
11
|
-
`@imqueue/core` is the foundation of the @imqueue framework: a fast,
|
|
12
|
-
JSON-message queue for inter-service communication, implemented over **Redis**.
|
|
13
|
-
It is the transport that [`@imqueue/rpc`](https://github.com/imqueue/rpc) builds
|
|
14
|
-
its typed RPC layer on top of. No timers, no polling — delivery is driven by
|
|
15
|
-
Redis blocking list moves and keyspace notifications.
|
|
16
|
-
|
|
17
|
-
## Toolchain & invariants (do not fight these)
|
|
18
|
-
|
|
19
|
-
- **ESM only**, `"type": "module"`. Use `import`, not `require()`. Import
|
|
20
|
-
sibling modules with the **`.js`** extension (NodeNext resolves it to the
|
|
21
|
-
`.ts` source), e.g. `import { RedisQueue } from './RedisQueue.js'`.
|
|
22
|
-
- **TypeScript, `module`/`moduleResolution: nodenext`**, `target: es2024`,
|
|
23
|
-
`verbatimModuleSyntax: true`, `isolatedModules: true`, `strict: true`. Use
|
|
24
|
-
`import type` / `import { type X }` for type-only imports.
|
|
25
|
-
- **Node ≥ 22.12.**
|
|
26
|
-
- **Single runtime dependency: `ioredis`.** Do not add heavyweight deps; this
|
|
27
|
-
package is meant to stay small.
|
|
28
|
-
- **Lint/format:** `oxlint` + `oxfmt`. Run `npm run format` before committing;
|
|
29
|
-
CI checks `npm run format:check`.
|
|
30
|
-
- Build **emits `.js`/`.d.ts`/`.js.map` next to sources**; these are
|
|
31
|
-
**gitignored, not committed** (`build` runs `clean-compiled` first, so stale
|
|
32
|
-
artifacts never linger). Never commit compiled output.
|
|
33
|
-
- `removeComments` is intentionally **`false`** — downstream tooling and
|
|
34
|
-
`@imqueue/rpc` rely on doc-blocks surviving compilation. Keep it that way.
|
|
35
|
-
|
|
36
|
-
## Commands
|
|
37
|
-
|
|
38
|
-
```bash
|
|
39
|
-
npm install
|
|
40
|
-
npm run build # clean-compiled + tsc (emits alongside sources)
|
|
41
|
-
npm test # build + node:test over test/unit/**/*.spec.js (mocked)
|
|
42
|
-
npm run test-integration # build + test/integration/**/*.spec.js (real redis)
|
|
43
|
-
npm run lint # oxlint
|
|
44
|
-
npm run format # oxfmt (write) | npm run format:check (verify)
|
|
45
|
-
npm run test-coverage # tests + experimental coverage summary
|
|
46
|
-
npm run test-lcov # writes coverage/lcov.info
|
|
47
|
-
npm run benchmark # message-throughput benchmark (see below)
|
|
48
|
-
```
|
|
49
|
-
|
|
50
|
-
Unit specs live in `test/unit/` and use the native `node:test` runner with
|
|
51
|
-
`--experimental-test-module-mocks` and a preload of `./test/mocks/index.js`;
|
|
52
|
-
timeout is 15s per test. Run a single spec after a build with
|
|
53
|
-
`node --experimental-test-module-mocks --import ./test/mocks/index.js --test test/unit/RedisQueue.spec.js`.
|
|
54
|
-
|
|
55
|
-
`npm test` deliberately globs `test/unit` rather than `test`: the integration
|
|
56
|
-
specs must not run under a preload that replaces `ioredis` wholesale. Keep that
|
|
57
|
-
glob scoped when adding runners.
|
|
58
|
-
|
|
59
|
-
**The unit specs never open a socket** — `test/mocks/redis.ts` replaces
|
|
60
|
-
`ioredis` wholesale. That is fine for everything except the TLS option, whose
|
|
61
|
-
entire point is what happens during a handshake the mock does not perform.
|
|
62
|
-
`test/integration/` covers that against a real broker, and anything touching
|
|
63
|
-
`tls`, the connection literal in `RedisQueue.connect()`, the pool key or
|
|
64
|
-
connection teardown must be checked with `npm run test-integration` as well as
|
|
65
|
-
`npm test`.
|
|
66
|
-
|
|
67
|
-
`test/integration/tlsBroker.ts` issues a throwaway CA, server and client
|
|
68
|
-
certificate with `openssl`, then starts `redis-server` on a port picked at run
|
|
69
|
-
time with `--port 0 --tls-port <n>`. `--port 0` is the part that matters: with
|
|
70
|
-
no plaintext listener at all, a queue that reaches the broker has demonstrably
|
|
71
|
-
done so over TLS. It is started twice, once with `--tls-auth-clients no` and
|
|
72
|
-
once with `yes`, so both server-authenticated and mutual TLS are exercised.
|
|
73
|
-
|
|
74
|
-
**The integration specs skip, never fail, when the machine cannot host a
|
|
75
|
-
broker.** `startTlsBroker()` returns a reason string instead of throwing when
|
|
76
|
-
`redis-server` or `openssl` is missing, or when redis will not start with TLS
|
|
77
|
-
enabled, and that reason becomes the suite's `skip`. CI has no redis and must
|
|
78
|
-
stay green, so keep that contract: report a skip reason, do not throw, and do
|
|
79
|
-
not add these specs to a runner that CI invokes.
|
|
80
|
-
|
|
81
|
-
## Layout
|
|
82
|
-
|
|
83
|
-
| Path | Role |
|
|
84
|
-
|---|---|
|
|
85
|
-
| `index.ts` | Public entry: default export `IMQ` (factory — `IMQ.create(name, opts)`) plus `export * from './src/index.js'` |
|
|
86
|
-
| `src/IMessageQueue.ts` | The `IMessageQueue` interface + options/types + the `'message'`/`'error'` event contract. The abstraction every adapter implements. |
|
|
87
|
-
| `src/RedisQueue.ts` | Single-Redis-instance queue implementation (the default). |
|
|
88
|
-
| `src/ClusteredRedisQueue.ts` | Round-robin queue across multiple Redis instances for horizontal scaling. |
|
|
89
|
-
| `src/ClusterManager.ts`, `src/UDPClusterManager.ts`, `src/UDPWorker.ts` | Cluster membership / worker coordination (UDP-based discovery). |
|
|
90
|
-
| `src/IMQMode.ts` | `IMQMode` enum (queue role/mode). |
|
|
91
|
-
| `src/redis.ts` | `ioredis` wiring / connection helpers. |
|
|
92
|
-
| `src/profile.ts` | Profiling helper used across the library. |
|
|
93
|
-
| `benchmark/**` | Throughput benchmark (CPU-affinity pinned). |
|
|
94
|
-
| `test/**` | `node:test` specs + `test/mocks/` preload. |
|
|
95
|
-
|
|
96
|
-
## Delivery model (behavioural invariants)
|
|
97
|
-
|
|
98
|
-
- **Two delivery modes**, selected by the `safeDelivery` option: *unreliable*
|
|
99
|
-
(fast; a message is lost if a consumer grabs it and dies) and *safe/guaranteed*
|
|
100
|
-
(1.5–2× slower; a grabbed-then-lost message is rescheduled). Safe delivery
|
|
101
|
-
covers the **processing**, not only the hand-off: the worker key is held until
|
|
102
|
-
the `message` listener is done, and **a listener says so by what it
|
|
103
|
-
returns** — a returned promise keeps the message checked out until it
|
|
104
|
-
settles, anything else releases it as the listener returns. Listeners are
|
|
105
|
-
therefore invoked through `rawListeners()` rather than `emit()`, which
|
|
106
|
-
discards return values. Safe delivery relies on Redis `LMOVE`/`BLMOVE` —
|
|
107
|
-
**Redis 6.2+ is required.** Unreliable delivery uses `BRPOP` alone and works
|
|
108
|
-
on 3.2+, so quote 6.2+ as the requirement unless the sentence is specifically
|
|
109
|
-
about the unreliable mode.
|
|
110
|
-
- **No polling / no timers.** Delivery uses blocking Redis ops + keyspace
|
|
111
|
-
notification events. This is why a lease is reclaimed by asking the broker who
|
|
112
|
-
is still connected (`CLIENT LIST`, already read once per maintenance tick for
|
|
113
|
-
the cleanup pass) rather than by renewing a deadline: a per-message heartbeat
|
|
114
|
-
would be a timer, and would prove only that the event loop is free rather than
|
|
115
|
-
that work is progressing. `safeDeliveryTtl` bounds processing on top of that,
|
|
116
|
-
for the handler that wedges inside a process which is otherwise healthy. If
|
|
117
|
-
Redis has the `CONFIG` command disabled (e.g. AWS ElastiCache), keyspace
|
|
118
|
-
notifications must be enabled out of band:
|
|
119
|
-
`notify-keyspace-events Ex`.
|
|
120
|
-
- **Keyspace-notification flags are merged, never overwritten.**
|
|
121
|
-
`notify-keyspace-events` is server-global, so `watch()` reads the current
|
|
122
|
-
value and appends only the missing `E`/`x` flags (`A` counts as covering
|
|
123
|
-
`x`), skipping `CONFIG SET` when the config already suffices. Do not go back
|
|
124
|
-
to setting a literal — that silently breaks other consumers of the same
|
|
125
|
-
Redis.
|
|
126
|
-
- **Messages must be JSON-serializable** (`IJson`/`JsonObject`). Delayed
|
|
127
|
-
delivery is supported via the send `delay` argument.
|
|
128
|
-
- Scaling the number of workers must **not** increase Redis traffic — preserve
|
|
129
|
-
this property in any queue change. `ClusteredRedisQueue` balances round-robin
|
|
130
|
-
across instances.
|
|
131
|
-
- Idle queues must consume no resources — do not introduce background intervals.
|
|
132
|
-
|
|
133
|
-
## Using this package correctly (for consumer-facing code an agent writes)
|
|
134
|
-
|
|
135
|
-
```typescript
|
|
136
|
-
import IMQ, { IMessageQueue, IJson } from '@imqueue/core';
|
|
137
|
-
|
|
138
|
-
const q: IMessageQueue = IMQ.create('MyQueue'); // default: RedisQueue
|
|
139
|
-
await q.start();
|
|
140
|
-
q.on('message', (msg: IJson, id: string, from: string) => { /* handle */ });
|
|
141
|
-
await q.send('OtherQueue', { hello: 'world' }); // JSON-serializable only
|
|
142
|
-
await q.send('MyQueue', { later: true }, 1000); // delayed 1000ms
|
|
143
|
-
```
|
|
144
|
-
|
|
145
|
-
Prefer `@imqueue/rpc` for typed service-to-service calls; use `core` directly
|
|
146
|
-
only when you need raw queue semantics.
|
|
147
|
-
|
|
148
|
-
## License
|
|
149
|
-
|
|
150
|
-
GPL-3.0. Commercial licensing for closed-source products: https://imqueue.com/.
|
package/CONTRIBUTION-TERMS.md
DELETED
|
@@ -1,79 +0,0 @@
|
|
|
1
|
-
# @imqueue Contribution Terms (v1.0)
|
|
2
|
-
|
|
3
|
-
These terms apply to every contribution to any repository of the **@imqueue**
|
|
4
|
-
project — the packages published under the `@imqueue` npm scope and any repository
|
|
5
|
-
in the imqueue GitHub organisation.
|
|
6
|
-
|
|
7
|
-
**By submitting a contribution — opening a pull request, pushing a commit, sending
|
|
8
|
-
a patch, or otherwise offering work for inclusion — you accept these terms in
|
|
9
|
-
full. If you do not agree with them, do not contribute.**
|
|
10
|
-
|
|
11
|
-
In these terms, **"Owner"** means Mykhailo Stadnyk, together with his successors,
|
|
12
|
-
assigns and any entity he controls (including VaryLogic s.r.o.), and
|
|
13
|
-
**"Contribution"** means any work of authorship — code, documentation or other
|
|
14
|
-
material — you submit to an @imqueue repository.
|
|
15
|
-
|
|
16
|
-
## 1. What you grant
|
|
17
|
-
|
|
18
|
-
You grant the Owner a **perpetual, worldwide, irrevocable, royalty-free,
|
|
19
|
-
non-exclusive, transferable and sublicensable** license to use, reproduce,
|
|
20
|
-
modify, adapt, publish, distribute and otherwise exploit your Contribution and
|
|
21
|
-
derivative works of it, **and to license and sub-license it under any terms the
|
|
22
|
-
Owner chooses — including commercial and proprietary (closed-source) licenses,
|
|
23
|
-
without any obligation to release source code.**
|
|
24
|
-
|
|
25
|
-
In plain terms: the Owner may include your Contribution in @imqueue and **sell
|
|
26
|
-
commercial licenses that cover it**, alongside the open-source edition.
|
|
27
|
-
|
|
28
|
-
## 2. No royalties, fees or compensation
|
|
29
|
-
|
|
30
|
-
The rights above are granted **free of charge**. You **waive** any right to
|
|
31
|
-
royalties, license fees, revenue share or any other compensation arising from the
|
|
32
|
-
Owner's use or licensing of your Contribution, including its commercial licensing,
|
|
33
|
-
and you agree not to seek any such payment now or in the future.
|
|
34
|
-
|
|
35
|
-
## 3. You keep your copyright
|
|
36
|
-
|
|
37
|
-
You **retain ownership** of the copyright in your Contribution and may use it
|
|
38
|
-
elsewhere for your own purposes. You are granting the Owner the rights in Section
|
|
39
|
-
1 — you are not required to transfer ownership. Your Contribution also remains
|
|
40
|
-
available to the public under the repository's open-source license (GPL-3.0).
|
|
41
|
-
|
|
42
|
-
## 4. Patent license
|
|
43
|
-
|
|
44
|
-
You grant the Owner and all downstream recipients a perpetual, worldwide,
|
|
45
|
-
royalty-free, irrevocable (except as stated) patent license to make, use, sell,
|
|
46
|
-
offer to sell, import and transfer your Contribution, limited to the patent claims
|
|
47
|
-
you can license that are necessarily infringed by your Contribution alone or in
|
|
48
|
-
combination with the project. If you start patent litigation alleging the project
|
|
49
|
-
or your Contribution infringes your patents, the patent license you received
|
|
50
|
-
terminates.
|
|
51
|
-
|
|
52
|
-
## 5. Your promises
|
|
53
|
-
|
|
54
|
-
You confirm that: (a) the Contribution is your own original work, or you have the
|
|
55
|
-
right to submit it and to grant these rights; (b) if your employer has any rights
|
|
56
|
-
in your work, you have their permission to contribute, or they have waived those
|
|
57
|
-
rights; and (c) you have identified any third-party material in your Contribution
|
|
58
|
-
and its license.
|
|
59
|
-
|
|
60
|
-
## 6. Moral rights
|
|
61
|
-
|
|
62
|
-
To the maximum extent permitted by applicable law, you waive, or agree not to
|
|
63
|
-
exercise, any moral rights in your Contribution in a way that would prevent the
|
|
64
|
-
Owner from exercising the rights in Section 1. (Certain moral rights are
|
|
65
|
-
inalienable under Slovak/EU law; nothing here purports to transfer those.)
|
|
66
|
-
|
|
67
|
-
## 7. No obligation; "as is"
|
|
68
|
-
|
|
69
|
-
The Owner is under no obligation to use your Contribution. It is provided **"as
|
|
70
|
-
is"**, without warranty of any kind.
|
|
71
|
-
|
|
72
|
-
## 8. Governing law
|
|
73
|
-
|
|
74
|
-
These terms are governed by the laws of the Slovak Republic, without regard to its
|
|
75
|
-
conflict-of-laws rules.
|
|
76
|
-
|
|
77
|
-
---
|
|
78
|
-
|
|
79
|
-
**If you do not agree to all of the above, do not contribute to @imqueue.**
|