@imqueue/core 3.4.2 → 3.4.3

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.
@@ -153,6 +153,13 @@ export declare const DEFAULT_UDP_CLUSTER_MANAGER_OPTIONS: UDPClusterManagerOptio
153
153
  * announcement removes it immediately.
154
154
  */
155
155
  export declare class UDPClusterManager extends ClusterManager {
156
+ /**
157
+ * The broadcast worker thread per worker key.
158
+ *
159
+ * @remarks
160
+ * Shared process-wide: managers configured alike use one worker between
161
+ * them rather than each binding its own socket to the same port.
162
+ */
156
163
  private static workers;
157
164
  /** Number of manager instances sharing each worker (by worker key) */
158
165
  private static workerRefs;
@@ -168,9 +175,17 @@ export declare class UDPClusterManager extends ClusterManager {
168
175
  * a crash and trigger a spurious "exited unexpectedly" warning and respawn.
169
176
  */
170
177
  private static intentionallyStopped;
178
+ /** This manager's effective options, defaults already applied */
171
179
  private readonly options;
180
+ /**
181
+ * Key identifying the worker this manager shares, derived from every option
182
+ * that affects what the worker listens to — so managers differing in any of
183
+ * them get workers of their own.
184
+ */
172
185
  private workerKey;
186
+ /** The worker thread this manager is attached to */
173
187
  private worker;
188
+ /** Set by {@link UDPClusterManager.destroy}, to keep it idempotent */
174
189
  private destroyed;
175
190
  /**
176
191
  * Creates the manager and starts listening for broadcasts immediately,
@@ -215,6 +230,14 @@ export declare class UDPClusterManager extends ClusterManager {
215
230
  * @param signal -
216
231
  */
217
232
  private static freeAndRaise;
233
+ /**
234
+ * Tears down every shared worker in this process, on the way out.
235
+ *
236
+ * @remarks
237
+ * Called from the process signal handlers, so it works across all managers
238
+ * rather than just one, and marks the process as shutting down first so a
239
+ * worker exiting is not mistaken for a crash and respawned.
240
+ */
218
241
  private static free;
219
242
  /**
220
243
  * Registers this instance on the (possibly shared) worker for its
@@ -264,5 +287,17 @@ export declare class UDPClusterManager extends ClusterManager {
264
287
  * that, which itself calls this method once the last cluster is gone.
265
288
  */
266
289
  destroy(): Promise<void>;
290
+ /**
291
+ * Terminates one shared worker and forgets it.
292
+ *
293
+ * @param workerKey - the key it is registered under
294
+ * @param worker - the worker itself; absent when it is already gone, in
295
+ * which case this does nothing
296
+ *
297
+ * @remarks
298
+ * The worker is marked as intentionally stopped before termination, because
299
+ * `terminate()` makes the `exit` event fire with a non-zero code that would
300
+ * otherwise read as a crash and trigger a respawn.
301
+ */
267
302
  private static destroyWorker;
268
303
  }
@@ -74,6 +74,13 @@ export const DEFAULT_UDP_CLUSTER_MANAGER_OPTIONS = {
74
74
  * announcement removes it immediately.
75
75
  */
76
76
  export class UDPClusterManager extends ClusterManager {
77
+ /**
78
+ * The broadcast worker thread per worker key.
79
+ *
80
+ * @remarks
81
+ * Shared process-wide: managers configured alike use one worker between
82
+ * them rather than each binding its own socket to the same port.
83
+ */
77
84
  static workers = {};
78
85
  /** Number of manager instances sharing each worker (by worker key) */
79
86
  static workerRefs = {};
@@ -89,9 +96,17 @@ export class UDPClusterManager extends ClusterManager {
89
96
  * a crash and trigger a spurious "exited unexpectedly" warning and respawn.
90
97
  */
91
98
  static intentionallyStopped = new WeakSet();
99
+ /** This manager's effective options, defaults already applied */
92
100
  options;
101
+ /**
102
+ * Key identifying the worker this manager shares, derived from every option
103
+ * that affects what the worker listens to — so managers differing in any of
104
+ * them get workers of their own.
105
+ */
93
106
  workerKey;
107
+ /** The worker thread this manager is attached to */
94
108
  worker;
109
+ /** Set by {@link UDPClusterManager.destroy}, to keep it idempotent */
95
110
  destroyed = false;
96
111
  /**
97
112
  * Creates the manager and starts listening for broadcasts immediately,
@@ -172,6 +187,14 @@ export class UDPClusterManager extends ClusterManager {
172
187
  // re-raising hits the default handler and terminates the process
173
188
  process.kill(process.pid, signal);
174
189
  }
190
+ /**
191
+ * Tears down every shared worker in this process, on the way out.
192
+ *
193
+ * @remarks
194
+ * Called from the process signal handlers, so it works across all managers
195
+ * rather than just one, and marks the process as shutting down first so a
196
+ * worker exiting is not mistaken for a crash and respawned.
197
+ */
175
198
  static async free() {
176
199
  UDPClusterManager.shuttingDown = true;
177
200
  const workerKeys = Object.keys(UDPClusterManager.workers);
@@ -324,6 +347,18 @@ export class UDPClusterManager extends ClusterManager {
324
347
  delete UDPClusterManager.instances[this.workerKey];
325
348
  await UDPClusterManager.destroyWorker(this.workerKey, this.worker);
326
349
  }
350
+ /**
351
+ * Terminates one shared worker and forgets it.
352
+ *
353
+ * @param workerKey - the key it is registered under
354
+ * @param worker - the worker itself; absent when it is already gone, in
355
+ * which case this does nothing
356
+ *
357
+ * @remarks
358
+ * The worker is marked as intentionally stopped before termination, because
359
+ * `terminate()` makes the `exit` event fire with a non-zero code that would
360
+ * otherwise read as a crash and trigger a respawn.
361
+ */
327
362
  static async destroyWorker(workerKey, worker) {
328
363
  if (!worker) {
329
364
  return;
@@ -24,19 +24,124 @@
24
24
  */
25
25
  import { MessagePort } from 'node:worker_threads';
26
26
  import { type UDPWorkerOptions } from './UDPClusterManager.js';
27
+ /**
28
+ * The worker-thread half of {@link UDPClusterManager}: listens for UDP
29
+ * broadcast announcements and reports cluster membership back to the main
30
+ * thread.
31
+ *
32
+ * @remarks
33
+ * Instantiated automatically at the bottom of this module when it is loaded as
34
+ * a worker thread, so it is never constructed by hand. It owns the socket and
35
+ * the liveness timers, which is the point — keeping the datagram traffic and
36
+ * its timers off the main thread means a busy queue cannot delay membership
37
+ * updates, and a socket failure cannot crash the process.
38
+ *
39
+ * It talks to the main thread in one direction only: `cluster:add`,
40
+ * `cluster:remove`, `error` and `stopped` messages out, a `stop` message in.
41
+ */
27
42
  export declare class UDPWorker {
43
+ /** Worker configuration, delivered through `workerData` */
28
44
  private readonly options;
45
+ /** The port every membership update and error is reported over */
29
46
  private readonly messagePort;
47
+ /** The bound UDP socket announcements arrive on */
30
48
  private readonly socket;
49
+ /**
50
+ * Last announcement stamp seen per server, keyed by the announcing
51
+ * instance's id.
52
+ *
53
+ * @remarks
54
+ * The value is a per-announcement uuid rather than a timestamp: a liveness
55
+ * timer only removes a server if the stamp it captured is still the current
56
+ * one, so a fresh announcement silently invalidates the timer that was
57
+ * waiting on the previous one.
58
+ */
31
59
  private readonly servers;
32
- constructor(options: UDPWorkerOptions, messagePort: MessagePort);
60
+ /**
61
+ * Binds the socket and starts listening for announcements.
62
+ *
63
+ * @param options - worker configuration, passed through `workerData`
64
+ * @param messagePort - the port back to the main thread
65
+ */
66
+ constructor(
67
+ /** Worker configuration, delivered through `workerData` */
68
+ options: UDPWorkerOptions,
69
+ /** The port every membership update and error is reported over */
70
+ messagePort: MessagePort);
71
+ /**
72
+ * Identifies the server an announcement is about.
73
+ *
74
+ * @param message - the announcement
75
+ * @returns the key its liveness stamp is tracked under
76
+ *
77
+ * @remarks
78
+ * The sender's own id, not its `host:port`: two instances may legitimately
79
+ * advertise the same address, and keying by address would let one of them
80
+ * expire the other's entry.
81
+ */
33
82
  private static getServerKey;
83
+ /**
84
+ * Listens for instructions from the main thread. `stop` is the only one.
85
+ */
34
86
  private setupMessageHandlers;
87
+ /**
88
+ * Reports a server as part of the cluster, and starts its liveness timer
89
+ * when {@link UDPWorkerOptions.useAliveCheck} is on.
90
+ *
91
+ * @param message - the announcement that named it
92
+ */
35
93
  private addServer;
94
+ /**
95
+ * Drops a server from the cluster and forgets its liveness stamp.
96
+ *
97
+ * @param message - the announcement that named it, whether a `down` notice
98
+ * or the stale `up` whose liveness timer expired
99
+ */
36
100
  private removeServer;
101
+ /**
102
+ * Copies an announcement field by field before it crosses to the main
103
+ * thread.
104
+ *
105
+ * @param message - the announcement to copy
106
+ * @returns a plain object safe to post through the message port
107
+ */
37
108
  private static mapMessage;
109
+ /**
110
+ * Arms the timer that drops a server which stops announcing itself.
111
+ *
112
+ * @param message - the announcement that renewed it
113
+ *
114
+ * @remarks
115
+ * The timer waits the sender's own timeout plus
116
+ * {@link UDPWorkerOptions.aliveTimeoutCorrection} and a millisecond, so a
117
+ * sender that announces exactly on its own deadline is not dropped by a
118
+ * race. It is unref'd: a pending liveness timer must not keep the worker
119
+ * thread alive on its own.
120
+ *
121
+ * Only the timer holding the current stamp may remove the server, so each
122
+ * new announcement supersedes the one before it without cancelling timers.
123
+ */
38
124
  private serverAliveWait;
125
+ /**
126
+ * Routes one decoded announcement to add or remove its sender.
127
+ *
128
+ * @param message - the decoded announcement; an unrecognised type is
129
+ * ignored rather than treated as either
130
+ */
39
131
  private processMessage;
132
+ /**
133
+ * Chooses the local address to bind the broadcast socket to.
134
+ *
135
+ * @returns the address of the interface carrying the configured broadcast
136
+ * address, or `0.0.0.0` when none matches
137
+ *
138
+ * @remarks
139
+ * Binding to the specific interface rather than to every one keeps the
140
+ * worker from receiving the same announcement on several interfaces at
141
+ * once. Falling back to `0.0.0.0` is deliberate: a misconfigured broadcast
142
+ * address should degrade to hearing everything rather than to hearing
143
+ * nothing.
144
+ */
40
145
  private selectNetworkInterface;
41
146
  /**
42
147
  * Parses a raw broadcast datagram into a message. Returns null for
@@ -47,7 +152,35 @@ export declare class UDPWorker {
47
152
  * @param {Buffer} input
48
153
  * @returns {Message | null}
49
154
  */
155
+ /**
156
+ * Decodes one datagram.
157
+ *
158
+ * @param input - the raw datagram
159
+ * @returns the decoded announcement, or `null` when it is malformed —
160
+ * a missing field, an out-of-range port, or an unparseable
161
+ * timeout. Datagrams arrive from anywhere on the network, so
162
+ * anything unrecognised is dropped rather than trusted
163
+ *
164
+ * @remarks
165
+ * The wire timeout is in seconds and is returned in milliseconds.
166
+ */
50
167
  private parseMessage;
168
+ /**
169
+ * Shuts the worker down and confirms it to the main thread.
170
+ *
171
+ * @remarks
172
+ * `stopped` is posted from the socket's close callback so the main thread
173
+ * learns of it only once the port is really released, and unconditionally
174
+ * if there is no socket to close.
175
+ */
51
176
  private stop;
177
+ /**
178
+ * Drops known servers and stops taking new announcements.
179
+ *
180
+ * @remarks
181
+ * The socket's `error` listener is deliberately left attached: a failure
182
+ * raised while closing must not surface as an unhandled `error` event and
183
+ * take the worker down on its way out.
184
+ */
52
185
  private cleanup;
53
186
  }
package/src/UDPWorker.js CHANGED
@@ -27,17 +27,58 @@ import { createSocket } from 'node:dgram';
27
27
  import { networkInterfaces } from 'node:os';
28
28
  import { randomUUID } from 'node:crypto';
29
29
  import {} from './UDPClusterManager.js';
30
+ /**
31
+ * What a broadcast announcement is saying about its sender.
32
+ */
30
33
  var MessageType;
31
34
  (function (MessageType) {
35
+ /** The sender is available and should be in the cluster */
32
36
  MessageType["Up"] = "up";
37
+ /** The sender is going away and should be dropped from the cluster */
33
38
  MessageType["Down"] = "down";
34
39
  })(MessageType || (MessageType = {}));
40
+ /**
41
+ * The worker-thread half of {@link UDPClusterManager}: listens for UDP
42
+ * broadcast announcements and reports cluster membership back to the main
43
+ * thread.
44
+ *
45
+ * @remarks
46
+ * Instantiated automatically at the bottom of this module when it is loaded as
47
+ * a worker thread, so it is never constructed by hand. It owns the socket and
48
+ * the liveness timers, which is the point — keeping the datagram traffic and
49
+ * its timers off the main thread means a busy queue cannot delay membership
50
+ * updates, and a socket failure cannot crash the process.
51
+ *
52
+ * It talks to the main thread in one direction only: `cluster:add`,
53
+ * `cluster:remove`, `error` and `stopped` messages out, a `stop` message in.
54
+ */
35
55
  export class UDPWorker {
36
56
  options;
37
57
  messagePort;
58
+ /** The bound UDP socket announcements arrive on */
38
59
  socket;
60
+ /**
61
+ * Last announcement stamp seen per server, keyed by the announcing
62
+ * instance's id.
63
+ *
64
+ * @remarks
65
+ * The value is a per-announcement uuid rather than a timestamp: a liveness
66
+ * timer only removes a server if the stamp it captured is still the current
67
+ * one, so a fresh announcement silently invalidates the timer that was
68
+ * waiting on the previous one.
69
+ */
39
70
  servers = new Map();
40
- constructor(options, messagePort) {
71
+ /**
72
+ * Binds the socket and starts listening for announcements.
73
+ *
74
+ * @param options - worker configuration, passed through `workerData`
75
+ * @param messagePort - the port back to the main thread
76
+ */
77
+ constructor(
78
+ /** Worker configuration, delivered through `workerData` */
79
+ options,
80
+ /** The port every membership update and error is reported over */
81
+ messagePort) {
41
82
  this.options = options;
42
83
  this.messagePort = messagePort;
43
84
  this.setupMessageHandlers();
@@ -70,9 +111,23 @@ export class UDPWorker {
70
111
  });
71
112
  this.socket.bind(this.options.port, this.selectNetworkInterface());
72
113
  }
114
+ /**
115
+ * Identifies the server an announcement is about.
116
+ *
117
+ * @param message - the announcement
118
+ * @returns the key its liveness stamp is tracked under
119
+ *
120
+ * @remarks
121
+ * The sender's own id, not its `host:port`: two instances may legitimately
122
+ * advertise the same address, and keying by address would let one of them
123
+ * expire the other's entry.
124
+ */
73
125
  static getServerKey(message) {
74
126
  return message.id;
75
127
  }
128
+ /**
129
+ * Listens for instructions from the main thread. `stop` is the only one.
130
+ */
76
131
  setupMessageHandlers() {
77
132
  this.messagePort.on('message', message => {
78
133
  if (message.type === 'stop') {
@@ -80,6 +135,12 @@ export class UDPWorker {
80
135
  }
81
136
  });
82
137
  }
138
+ /**
139
+ * Reports a server as part of the cluster, and starts its liveness timer
140
+ * when {@link UDPWorkerOptions.useAliveCheck} is on.
141
+ *
142
+ * @param message - the announcement that named it
143
+ */
83
144
  addServer(message) {
84
145
  this.messagePort.postMessage({
85
146
  type: 'cluster:add',
@@ -89,6 +150,12 @@ export class UDPWorker {
89
150
  this.serverAliveWait(message);
90
151
  }
91
152
  }
153
+ /**
154
+ * Drops a server from the cluster and forgets its liveness stamp.
155
+ *
156
+ * @param message - the announcement that named it, whether a `down` notice
157
+ * or the stale `up` whose liveness timer expired
158
+ */
92
159
  removeServer(message) {
93
160
  this.servers.delete(UDPWorker.getServerKey(message));
94
161
  this.messagePort.postMessage({
@@ -96,6 +163,13 @@ export class UDPWorker {
96
163
  server: UDPWorker.mapMessage(message),
97
164
  });
98
165
  }
166
+ /**
167
+ * Copies an announcement field by field before it crosses to the main
168
+ * thread.
169
+ *
170
+ * @param message - the announcement to copy
171
+ * @returns a plain object safe to post through the message port
172
+ */
99
173
  static mapMessage(message) {
100
174
  return {
101
175
  id: message.id,
@@ -106,6 +180,21 @@ export class UDPWorker {
106
180
  timeout: message.timeout,
107
181
  };
108
182
  }
183
+ /**
184
+ * Arms the timer that drops a server which stops announcing itself.
185
+ *
186
+ * @param message - the announcement that renewed it
187
+ *
188
+ * @remarks
189
+ * The timer waits the sender's own timeout plus
190
+ * {@link UDPWorkerOptions.aliveTimeoutCorrection} and a millisecond, so a
191
+ * sender that announces exactly on its own deadline is not dropped by a
192
+ * race. It is unref'd: a pending liveness timer must not keep the worker
193
+ * thread alive on its own.
194
+ *
195
+ * Only the timer holding the current stamp may remove the server, so each
196
+ * new announcement supersedes the one before it without cancelling timers.
197
+ */
109
198
  serverAliveWait(message) {
110
199
  const stamp = randomUUID();
111
200
  const correction = this.options.aliveTimeoutCorrection ?? 0;
@@ -120,6 +209,12 @@ export class UDPWorker {
120
209
  // a pending liveness timer must not keep the worker alive on its own
121
210
  timer.unref();
122
211
  }
212
+ /**
213
+ * Routes one decoded announcement to add or remove its sender.
214
+ *
215
+ * @param message - the decoded announcement; an unrecognised type is
216
+ * ignored rather than treated as either
217
+ */
123
218
  processMessage(message) {
124
219
  if (message.type === MessageType.Down) {
125
220
  return this.removeServer(message);
@@ -128,6 +223,19 @@ export class UDPWorker {
128
223
  return this.addServer(message);
129
224
  }
130
225
  }
226
+ /**
227
+ * Chooses the local address to bind the broadcast socket to.
228
+ *
229
+ * @returns the address of the interface carrying the configured broadcast
230
+ * address, or `0.0.0.0` when none matches
231
+ *
232
+ * @remarks
233
+ * Binding to the specific interface rather than to every one keeps the
234
+ * worker from receiving the same announcement on several interfaces at
235
+ * once. Falling back to `0.0.0.0` is deliberate: a misconfigured broadcast
236
+ * address should degrade to hearing everything rather than to hearing
237
+ * nothing.
238
+ */
131
239
  selectNetworkInterface() {
132
240
  const interfaces = networkInterfaces();
133
241
  const broadcastAddress = this.options.address || this.options.limitedAddress;
@@ -159,6 +267,18 @@ export class UDPWorker {
159
267
  * @param {Buffer} input
160
268
  * @returns {Message | null}
161
269
  */
270
+ /**
271
+ * Decodes one datagram.
272
+ *
273
+ * @param input - the raw datagram
274
+ * @returns the decoded announcement, or `null` when it is malformed —
275
+ * a missing field, an out-of-range port, or an unparseable
276
+ * timeout. Datagrams arrive from anywhere on the network, so
277
+ * anything unrecognised is dropped rather than trusted
278
+ *
279
+ * @remarks
280
+ * The wire timeout is in seconds and is returned in milliseconds.
281
+ */
162
282
  parseMessage(input) {
163
283
  const [name, id, type, address = '', timeout = '0'] = input
164
284
  .toString()
@@ -186,6 +306,14 @@ export class UDPWorker {
186
306
  timeout: timeoutMs,
187
307
  };
188
308
  }
309
+ /**
310
+ * Shuts the worker down and confirms it to the main thread.
311
+ *
312
+ * @remarks
313
+ * `stopped` is posted from the socket's close callback so the main thread
314
+ * learns of it only once the port is really released, and unconditionally
315
+ * if there is no socket to close.
316
+ */
189
317
  stop() {
190
318
  this.cleanup();
191
319
  if (this.socket) {
@@ -196,6 +324,14 @@ export class UDPWorker {
196
324
  }
197
325
  this.messagePort.postMessage({ type: 'stopped' });
198
326
  }
327
+ /**
328
+ * Drops known servers and stops taking new announcements.
329
+ *
330
+ * @remarks
331
+ * The socket's `error` listener is deliberately left attached: a failure
332
+ * raised while closing must not surface as an unhandled `error` event and
333
+ * take the worker down on its way out.
334
+ */
199
335
  cleanup() {
200
336
  this.servers.clear();
201
337
  if (this.socket) {
@@ -205,6 +341,9 @@ export class UDPWorker {
205
341
  }
206
342
  }
207
343
  }
344
+ // this module doubles as the worker thread's entry point: loading it in a
345
+ // worker starts the listener, while loading it on the main thread (as the type
346
+ // imports above do) defines the class and does nothing else
208
347
  if (!isMainThread && parentPort) {
209
348
  new UDPWorker(workerData, parentPort);
210
349
  }
@@ -22,6 +22,27 @@
22
22
  * <support@imqueue.com> to get commercial licensing options.
23
23
  */
24
24
  import { EventEmitter } from 'node:events';
25
+ /**
26
+ * Re-attaches every listener registered on one emitter to another.
27
+ *
28
+ * @param source - emitter to copy listeners from; left untouched
29
+ * @param target - emitter to attach them to, in addition to whatever it already
30
+ * has
31
+ *
32
+ * @remarks
33
+ * Used when a queue handle is replaced by another instance that must keep
34
+ * serving the original's listeners — the caller registered them on the object
35
+ * it was given, and has no way to know it was swapped.
36
+ *
37
+ * `once` listeners stay `once`. They are detected by inspecting the wrapper
38
+ * Node puts around them, and the wrapped listener is unwrapped through its
39
+ * `.listener` property before being re-registered, so a one-shot listener does
40
+ * not silently become permanent on the target.
41
+ *
42
+ * The max-listeners limit is carried across too, but only when the source has
43
+ * one set: reading it unconditionally would replace the target's default with
44
+ * Node's, which is the same number today and need not stay so.
45
+ */
25
46
  export declare function copyEventEmitter(source: EventEmitter & {
26
47
  _maxListeners?: number;
27
48
  _events?: Record<string | symbol, any>;
@@ -23,6 +23,27 @@
23
23
  */
24
24
  import { EventEmitter } from 'node:events';
25
25
  import { inspect } from 'node:util';
26
+ /**
27
+ * Re-attaches every listener registered on one emitter to another.
28
+ *
29
+ * @param source - emitter to copy listeners from; left untouched
30
+ * @param target - emitter to attach them to, in addition to whatever it already
31
+ * has
32
+ *
33
+ * @remarks
34
+ * Used when a queue handle is replaced by another instance that must keep
35
+ * serving the original's listeners — the caller registered them on the object
36
+ * it was given, and has no way to know it was swapped.
37
+ *
38
+ * `once` listeners stay `once`. They are detected by inspecting the wrapper
39
+ * Node puts around them, and the wrapped listener is unwrapped through its
40
+ * `.listener` property before being re-registered, so a one-shot listener does
41
+ * not silently become permanent on the target.
42
+ *
43
+ * The max-listeners limit is carried across too, but only when the source has
44
+ * one set: reading it unconditionally would replace the target's default with
45
+ * Node's, which is the same number today and need not stay so.
46
+ */
26
47
  export function copyEventEmitter(source, target) {
27
48
  if (typeof source._maxListeners !== 'undefined') {
28
49
  target.setMaxListeners(source.getMaxListeners());
package/CLAUDE.md DELETED
@@ -1,2 +0,0 @@
1
- See [AGENTS.md](./AGENTS.md) for build, test, layout and the invariants to
2
- respect when working on `@imqueue/core`. End-user docs: https://imqueue.org/.