@blamejs/core 0.6.33 → 0.6.34

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/lib/pubsub.js ADDED
@@ -0,0 +1,357 @@
1
+ "use strict";
2
+ /**
3
+ * pubsub — distributed pub/sub primitive.
4
+ *
5
+ * Generalizes the cluster-table fan-out pattern that previously lived
6
+ * inline in `lib/websocket-channels.js` and the `NOT_SUPPORTED` cache
7
+ * cluster `invalidateTag` path. Three backends:
8
+ *
9
+ * local — in-process Map<channel, Set<handler>>; publish dispatches
10
+ * SYNCHRONOUSLY before returning. Single-node deploys pay
11
+ * zero coordination overhead.
12
+ * cluster — shared `_blamejs_pubsub_messages` table polled at
13
+ * pollIntervalMs; publish writes a row + dispatches locally;
14
+ * other nodes pick up rows via `id > lastSeenId AND
15
+ * publishedBy <> selfNodeId`. Default cluster mode for any
16
+ * `b.cluster`-aware deploy.
17
+ * redis — Redis PUB/SUB on the bespoke `lib/redis-client.js`. One
18
+ * connection per pubsub instance enters subscribe mode
19
+ * (demultiplexed via `setOnPushMessage`); publish goes
20
+ * through a separate command-mode connection.
21
+ *
22
+ * Operator API:
23
+ *
24
+ * var ps = b.pubsub.create({
25
+ * backend: 'local' | 'cluster' | 'redis' | { custom },
26
+ * // cluster opts
27
+ * cluster: clusterInstance,
28
+ * pollIntervalMs: C.TIME.ms? — default 100ms
29
+ * retentionMs: C.TIME.ms? — default 60s
30
+ * pruneEveryMs: C.TIME.ms? — default 5min
31
+ * // redis opts
32
+ * redisUrl: string — required for redis backend
33
+ * redisPassword: string?
34
+ * redisUsername: string?
35
+ * redisTls: boolean?
36
+ * redisCa: string|Buffer?
37
+ * redisServername: string?
38
+ * // common
39
+ * topicPrefix: string? — every publish/subscribe channel
40
+ * scoped to `<topicPrefix>:<channel>`
41
+ * so independent pubsub instances
42
+ * sharing a backend don't collide.
43
+ * audit: boolean? — default false. When true emits
44
+ * `system.pubsub.publish` per call.
45
+ * });
46
+ *
47
+ * var token = ps.subscribe(channel, function (payload, ev) {
48
+ * // payload is whatever publish() received (objects survive JSON
49
+ * // round-trip on remote backends; on the local backend the
50
+ * // reference is passed through). ev = { channel, source: 'local'
51
+ * // | 'remote', publishedBy?, publishedAt? }.
52
+ * });
53
+ * ps.unsubscribe(token);
54
+ *
55
+ * await ps.publish(channel, payload); // returns { local, remote? }
56
+ *
57
+ * await ps.close(); // tears down backend
58
+ *
59
+ * Local dispatch always happens BEFORE the publish() promise resolves,
60
+ * regardless of backend — same-node subscribers see the payload with
61
+ * near-zero latency. The remote write is awaited so the caller knows
62
+ * the cross-node fan-out completed.
63
+ *
64
+ * Subscription handler errors are caught and logged via the framework's
65
+ * boot logger; they never abort dispatch to other handlers on the same
66
+ * channel.
67
+ *
68
+ * Channel naming is operator-defined — pubsub treats names as opaque
69
+ * strings (with the optional topicPrefix prepended). Pattern subscribe
70
+ * (Redis-style `news.*`) is exposed via `subscribePattern(pattern,
71
+ * handler)`; not every backend supports it (cluster-table backend
72
+ * matches client-side, redis backend uses PSUBSCRIBE, local backend
73
+ * matches client-side too).
74
+ */
75
+ var lazyRequire = require("./lazy-require");
76
+ var safeJson = require("./safe-json");
77
+ var validateOpts = require("./validate-opts");
78
+ var { defineClass } = require("./framework-error");
79
+
80
+ var audit = lazyRequire(function () { return require("./audit"); });
81
+ var logger = lazyRequire(function () { return require("./log").boot("pubsub"); });
82
+
83
+ var PubsubError = defineClass("PubsubError");
84
+
85
+ function _err(code, message) { return new PubsubError(code, message, true); }
86
+
87
+ function _resolveBackend(opts) {
88
+ var requested = opts.backend;
89
+ if (requested && typeof requested === "object") {
90
+ if (typeof requested.publishRemote !== "function" ||
91
+ typeof requested.start !== "function" ||
92
+ typeof requested.stop !== "function") {
93
+ throw _err("BAD_BACKEND",
94
+ "pubsub: custom backend must implement { publishRemote, start, stop }");
95
+ }
96
+ return Object.assign({ name: "custom" }, requested);
97
+ }
98
+ if (!requested || requested === "local") {
99
+ return { name: "local", publishRemote: null, start: null, stop: null };
100
+ }
101
+ if (requested === "cluster") {
102
+ return require("./pubsub-cluster").create(opts);
103
+ }
104
+ if (requested === "redis") {
105
+ return require("./pubsub-redis").create(opts);
106
+ }
107
+ throw _err("UNKNOWN_BACKEND",
108
+ "pubsub: unknown backend '" + requested +
109
+ "' (must be 'local', 'cluster', 'redis', or { publishRemote, start, stop })");
110
+ }
111
+
112
+ function _matchPattern(pattern, channel) {
113
+ // Glob-style: '*' matches any single segment; '**' matches any
114
+ // suffix. Operators wanting full Redis-pattern semantics use the
115
+ // redis backend's PSUBSCRIBE which the redis client routes natively.
116
+ if (pattern === channel) return true;
117
+ if (pattern.indexOf("*") === -1) return false;
118
+ var rx = "^" + pattern
119
+ .split("**").map(function (p) {
120
+ return p.split("*").map(function (s) {
121
+ return s.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
122
+ }).join("[^.]*");
123
+ }).join(".*") + "$";
124
+ return new RegExp(rx).test(channel);
125
+ }
126
+
127
+ function create(opts) {
128
+ opts = opts || {};
129
+ validateOpts(opts, [
130
+ "backend", "cluster", "audit", "topicPrefix",
131
+ "pollIntervalMs", "retentionMs", "pruneEveryMs",
132
+ "redisUrl", "redisPassword", "redisUsername", "redisTls",
133
+ "redisCa", "redisServername",
134
+ ], "b.pubsub");
135
+
136
+ var topicPrefix = opts.topicPrefix || "";
137
+ var auditOn = !!opts.audit;
138
+ var backend = _resolveBackend(opts);
139
+
140
+ // channel -> Set<token-record>; token-record is { channel, handler, isPattern }.
141
+ // Tokens are objects so unsubscribe is O(1) without hashing.
142
+ var exactSubs = new Map();
143
+ var patternSubs = new Set();
144
+ var closed = false;
145
+
146
+ function _scoped(channel) {
147
+ return topicPrefix ? topicPrefix + ":" + channel : channel;
148
+ }
149
+ function _unscope(scopedChannel) {
150
+ if (!topicPrefix) return scopedChannel;
151
+ if (scopedChannel.indexOf(topicPrefix + ":") === 0) {
152
+ return scopedChannel.slice(topicPrefix.length + 1);
153
+ }
154
+ return scopedChannel;
155
+ }
156
+
157
+ function _localDispatch(channel, payload, source, meta) {
158
+ var ev = Object.assign({ channel: channel, source: source || "local" },
159
+ meta || {});
160
+ var dispatched = 0;
161
+ var exact = exactSubs.get(channel);
162
+ if (exact) {
163
+ for (var rec of exact) {
164
+ try { rec.handler(payload, ev); dispatched++; }
165
+ catch (e) {
166
+ try { logger().warn("pubsub handler threw on '" + channel +
167
+ "': " + ((e && e.message) || String(e))); }
168
+ catch (_e) { /* logger best-effort */ }
169
+ }
170
+ }
171
+ }
172
+ for (var prec of patternSubs) {
173
+ if (_matchPattern(prec.channel, channel)) {
174
+ try { prec.handler(payload, ev); dispatched++; }
175
+ catch (e) {
176
+ try { logger().warn("pubsub pattern handler threw on '" +
177
+ channel + "' (pattern '" + prec.channel + "'): " +
178
+ ((e && e.message) || String(e))); }
179
+ catch (_e) { /* logger best-effort */ }
180
+ }
181
+ }
182
+ }
183
+ return dispatched;
184
+ }
185
+
186
+ // Backend invokes this when a remote node's record arrives.
187
+ function _onRemoteMessage(scopedChannel, rawPayload, meta) {
188
+ var channel = _unscope(scopedChannel);
189
+ var payload;
190
+ try {
191
+ payload = (typeof rawPayload === "string" ||
192
+ (rawPayload && Buffer.isBuffer(rawPayload)))
193
+ ? safeJson.parse(Buffer.isBuffer(rawPayload)
194
+ ? rawPayload.toString("utf8")
195
+ : rawPayload)
196
+ : rawPayload;
197
+ } catch (e) {
198
+ try { logger().warn("pubsub remote payload parse failed on '" +
199
+ channel + "': " + ((e && e.message) || String(e))); }
200
+ catch (_e) { /* */ }
201
+ return;
202
+ }
203
+ _localDispatch(channel, payload, "remote", meta || {});
204
+ }
205
+
206
+ if (typeof backend.start === "function") {
207
+ backend.start(_onRemoteMessage);
208
+ }
209
+
210
+ // Track which scoped channels we've subscribed remotely so we can
211
+ // ref-count and unsubscribe when the last local handler goes away.
212
+ var remoteSubCount = new Map();
213
+
214
+ async function _maybeRemoteSubscribe(scopedChannel, isPattern) {
215
+ var n = (remoteSubCount.get(scopedChannel) || 0) + 1;
216
+ remoteSubCount.set(scopedChannel, n);
217
+ if (n === 1 && typeof backend.subscribeRemote === "function") {
218
+ try { await backend.subscribeRemote(scopedChannel, isPattern); }
219
+ catch (e) {
220
+ // Roll back the count so a retry isn't blocked by stale bookkeeping.
221
+ remoteSubCount.set(scopedChannel, n - 1);
222
+ throw e;
223
+ }
224
+ }
225
+ }
226
+ async function _maybeRemoteUnsubscribe(scopedChannel, isPattern) {
227
+ var n = (remoteSubCount.get(scopedChannel) || 1) - 1;
228
+ if (n <= 0) {
229
+ remoteSubCount.delete(scopedChannel);
230
+ if (typeof backend.unsubscribeRemote === "function") {
231
+ try { await backend.unsubscribeRemote(scopedChannel, isPattern); }
232
+ catch (_e) { /* unsubscribe failure is informational */ }
233
+ }
234
+ } else {
235
+ remoteSubCount.set(scopedChannel, n);
236
+ }
237
+ }
238
+
239
+ function subscribe(channel, handler) {
240
+ if (closed) throw _err("CLOSED", "pubsub.subscribe: instance closed");
241
+ if (typeof channel !== "string" || channel.length === 0) {
242
+ throw _err("BAD_OPT", "pubsub.subscribe: channel must be a non-empty string");
243
+ }
244
+ if (typeof handler !== "function") {
245
+ throw _err("BAD_OPT", "pubsub.subscribe: handler must be a function");
246
+ }
247
+ var rec = { channel: channel, handler: handler, isPattern: false };
248
+ var set = exactSubs.get(channel);
249
+ if (!set) { set = new Set(); exactSubs.set(channel, set); }
250
+ set.add(rec);
251
+ // Remote subscribe is fire-and-forget from the caller's perspective;
252
+ // the redis backend awaits the SUBSCRIBE ack internally before its
253
+ // promise resolves, so a sync subscribe() that returns the token
254
+ // doesn't strand the operator if they immediately publish().
255
+ _maybeRemoteSubscribe(_scoped(channel), false).catch(function (e) {
256
+ try { logger().warn("pubsub subscribeRemote('" + channel + "') failed: " +
257
+ ((e && e.message) || String(e))); }
258
+ catch (_e) { /* */ }
259
+ });
260
+ return rec;
261
+ }
262
+
263
+ function subscribePattern(pattern, handler) {
264
+ if (closed) throw _err("CLOSED", "pubsub.subscribePattern: instance closed");
265
+ if (typeof pattern !== "string" || pattern.length === 0) {
266
+ throw _err("BAD_OPT", "pubsub.subscribePattern: pattern must be a non-empty string");
267
+ }
268
+ if (typeof handler !== "function") {
269
+ throw _err("BAD_OPT", "pubsub.subscribePattern: handler must be a function");
270
+ }
271
+ var rec = { channel: pattern, handler: handler, isPattern: true };
272
+ patternSubs.add(rec);
273
+ _maybeRemoteSubscribe(_scoped(pattern), true).catch(function (e) {
274
+ try { logger().warn("pubsub subscribePatternRemote('" + pattern + "') failed: " +
275
+ ((e && e.message) || String(e))); }
276
+ catch (_e) { /* */ }
277
+ });
278
+ return rec;
279
+ }
280
+
281
+ function unsubscribe(token) {
282
+ if (!token || typeof token !== "object") return;
283
+ if (token.isPattern) {
284
+ if (patternSubs.delete(token)) {
285
+ _maybeRemoteUnsubscribe(_scoped(token.channel), true);
286
+ }
287
+ return;
288
+ }
289
+ var set = exactSubs.get(token.channel);
290
+ if (set && set.delete(token)) {
291
+ if (set.size === 0) exactSubs.delete(token.channel);
292
+ _maybeRemoteUnsubscribe(_scoped(token.channel), false);
293
+ }
294
+ }
295
+
296
+ async function publish(channel, payload) {
297
+ if (closed) throw _err("CLOSED", "pubsub.publish: instance closed");
298
+ if (typeof channel !== "string" || channel.length === 0) {
299
+ throw _err("BAD_OPT", "pubsub.publish: channel must be a non-empty string");
300
+ }
301
+ var local = _localDispatch(channel, payload, "local");
302
+ var remote = 0;
303
+ if (typeof backend.publishRemote === "function") {
304
+ try {
305
+ var rv = await backend.publishRemote(_scoped(channel), payload);
306
+ remote = (rv && typeof rv === "object" && Number.isFinite(rv.remote))
307
+ ? rv.remote : 1;
308
+ } catch (e) {
309
+ if (auditOn) {
310
+ try { audit().safeEmit("system.pubsub.publish-failed", {
311
+ channel: channel, error: (e && e.message) || String(e),
312
+ }); } catch (_e) { /* */ }
313
+ }
314
+ throw e;
315
+ }
316
+ }
317
+ if (auditOn) {
318
+ try { audit().safeEmit("system.pubsub.publish", {
319
+ channel: channel, localDispatched: local, remoteWritten: remote,
320
+ }); } catch (_e) { /* */ }
321
+ }
322
+ return { local: local, remote: remote };
323
+ }
324
+
325
+ async function close() {
326
+ if (closed) return;
327
+ closed = true;
328
+ if (typeof backend.stop === "function") {
329
+ try { await backend.stop(); } catch (_e) { /* close failure is informational */ }
330
+ }
331
+ exactSubs.clear();
332
+ patternSubs.clear();
333
+ remoteSubCount.clear();
334
+ }
335
+
336
+ return {
337
+ backend: function () { return backend.name; },
338
+ subscribe: subscribe,
339
+ subscribePattern: subscribePattern,
340
+ unsubscribe: unsubscribe,
341
+ publish: publish,
342
+ close: close,
343
+ // Diagnostic — exposed for tests + observability.
344
+ _state: function () {
345
+ return {
346
+ backend: backend.name,
347
+ exactChannels: exactSubs.size,
348
+ patternCount: patternSubs.size,
349
+ remoteSubCount: remoteSubCount.size,
350
+ closed: closed,
351
+ };
352
+ },
353
+ _matchPatternForTest: _matchPattern,
354
+ };
355
+ }
356
+
357
+ module.exports = { create: create, PubsubError: PubsubError };
@@ -184,6 +184,16 @@ function create(opts) {
184
184
  // Backlog of commands queued before connect resolved
185
185
  var backlog = [];
186
186
  var reconnectAttempt = 0;
187
+ // Pub/sub demultiplex hook. When set, the receive path dispatches
188
+ // server-pushed "message" / "pmessage" frames (RESP arrays whose
189
+ // first element is one of those literals) to onPushMessage instead
190
+ // of consuming a pending request slot. SUBSCRIBE / UNSUBSCRIBE /
191
+ // PSUBSCRIBE / PUNSUBSCRIBE acks still flow through pending — they
192
+ // ARE responses to caller-issued commands. The split lets a single
193
+ // socket handle subscribe-mode acks AND the asynchronous fan-out
194
+ // events without confusing the FIFO.
195
+ var onPushMessage = typeof opts.onPushMessage === "function"
196
+ ? opts.onPushMessage : null;
187
197
 
188
198
  function _scheduleReconnect() {
189
199
  if (closing) return;
@@ -210,11 +220,43 @@ function create(opts) {
210
220
 
211
221
  function _onData(chunk) {
212
222
  rxBuffer = rxBuffer.length === 0 ? chunk : Buffer.concat([rxBuffer, chunk]);
213
- while (pending.length > 0 && rxBuffer.length > 0) {
223
+ while (rxBuffer.length > 0) {
214
224
  var frame = _parseFrame(rxBuffer, 0);
215
225
  if (frame.type === "incomplete") return;
216
226
  var value = _frameToValue(frame);
217
227
  rxBuffer = rxBuffer.slice(frame.consumed);
228
+
229
+ // Pub/sub push detection — server-initiated arrays beginning with
230
+ // "message" (3-tuple: type / channel / payload) or "pmessage"
231
+ // (4-tuple: type / pattern / channel / payload). Routed to
232
+ // onPushMessage; do not consume a pending entry.
233
+ if (onPushMessage && Array.isArray(value) && value.length >= 3 &&
234
+ Buffer.isBuffer(value[0])) {
235
+ var typeStr = value[0].toString("utf8");
236
+ if (typeStr === "message" && value.length === 3) {
237
+ onPushMessage({
238
+ pattern: null,
239
+ channel: Buffer.isBuffer(value[1]) ? value[1].toString("utf8") : String(value[1]),
240
+ payload: value[2],
241
+ });
242
+ continue;
243
+ }
244
+ if (typeStr === "pmessage" && value.length === 4) {
245
+ onPushMessage({
246
+ pattern: Buffer.isBuffer(value[1]) ? value[1].toString("utf8") : String(value[1]),
247
+ channel: Buffer.isBuffer(value[2]) ? value[2].toString("utf8") : String(value[2]),
248
+ payload: value[3],
249
+ });
250
+ continue;
251
+ }
252
+ }
253
+
254
+ if (pending.length === 0) {
255
+ // Orphan frame with no pending request — drop. This is the
256
+ // expected path for subscribe/unsubscribe acks if onPushMessage
257
+ // is wired but the caller didn't await them.
258
+ continue;
259
+ }
218
260
  var p = pending.shift();
219
261
  if (value && value._redisError) {
220
262
  p.reject(_err("REDIS_REPLY", value.message));
@@ -393,6 +435,9 @@ function create(opts) {
393
435
  runScript: runScript,
394
436
  close: close,
395
437
  isOpen: function () { return connected && !closing; },
438
+ setOnPushMessage: function (fn) {
439
+ onPushMessage = typeof fn === "function" ? fn : null;
440
+ },
396
441
  // Diagnostic — exposed for tests + observability
397
442
  _state: function () {
398
443
  return {