fca-nx 6.8.8 → 7.0.5
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/README.md +24 -10
- package/func/checkUpdate.js +1 -1
- package/func/logAdapter.js +2 -0
- package/index.js +3 -0
- package/module/config.js +5 -2
- package/module/login.js +38 -13
- package/module/loginHelper.js +164 -127
- package/module/options.js +7 -1
- package/package.json +2 -2
- package/src/api/action/addfriend.js +9 -3
- package/src/api/action/changeAvatar.js +1 -0
- package/src/api/action/changeCover.js +3 -1
- package/src/api/action/enableAutoSaveAppState.js +18 -5
- package/src/api/action/refreshFb_dtsg.js +18 -76
- package/src/api/http/httpGet.js +6 -2
- package/src/api/http/httpPost.js +7 -2
- package/src/api/messaging/createNewGroup.js +1 -1
- package/src/api/messaging/deleteMessage.js +1 -1
- package/src/api/messaging/forwardMessage.js +9 -1
- package/src/api/messaging/getEmojiUrl.js +5 -1
- package/src/api/messaging/getMessage.js +4 -2
- package/src/api/messaging/getThemePictures.js +21 -28
- package/src/api/messaging/markAsRead.js +1 -0
- package/src/api/messaging/muteThread.js +1 -1
- package/src/api/messaging/pinMessage.js +10 -1
- package/src/api/messaging/scheduler.js +71 -4
- package/src/api/messaging/sendBroadcast.js +15 -0
- package/src/api/messaging/sendMessage.js +23 -1
- package/src/api/messaging/sendTypingIndicator.js +0 -15
- package/src/api/messaging/sessionGuard.js +45 -9
- package/src/api/messaging/setMessageReaction.js +2 -1
- package/src/api/messaging/threadColors.js +45 -12
- package/src/api/messaging/uploadAttachment.js +37 -3
- package/src/api/socket/OldMessage.js +7 -2
- package/src/api/socket/core/connectMqtt.js +68 -81
- package/src/api/socket/core/emitAuth.js +11 -2
- package/src/api/socket/core/getSeqID.js +28 -36
- package/src/api/socket/core/getTaskResponseData.js +3 -1
- package/src/api/socket/core/parseDelta.js +1 -1
- package/src/api/socket/detail/buildStream.js +4 -1
- package/src/api/socket/detail/constants.js +4 -1
- package/src/api/socket/e2ee/crypto.js +40 -2
- package/src/api/socket/e2ee/index.js +124 -73
- package/src/api/socket/e2ee/protocol.js +40 -32
- package/src/api/socket/e2ee/ratchet.js +43 -37
- package/src/api/socket/e2ee/store.js +47 -133
- package/src/api/socket/e2ee/vendor/fb-e2ee.cjs +18 -140
- package/src/api/socket/listenE2EE.js +23 -12
- package/src/api/socket/listenMqtt.js +94 -110
- package/src/api/socket/middleware/index.js +61 -7
- package/src/api/socket/sendMessage.js +78 -170
- package/src/api/socket/sendMessageMqtt.js +6 -0
- package/src/api/threads/getThreadHistory.js +68 -38
- package/src/api/threads/getThreadInfo.js +4 -3
- package/src/api/threads/getThreadList.js +34 -31
- package/src/api/threads/getThreadPictures.js +1 -1
- package/src/api/users/getUserInfo.js +5 -2
- package/src/api/users/getUserInfoV2.js +65 -59
- package/src/app/createFcaClient.js +2 -2
- package/src/core/sendReqMqtt.js +2 -1
- package/src/database/helpers.js +12 -0
- package/src/database/models/index.js +8 -9
- package/src/utils/broadcast.js +1 -1
- package/src/utils/clientIdentity.js +50 -3
- package/src/utils/cookies.js +4 -2
- package/src/utils/format/utils.js +10 -0
- package/src/utils/headers.js +26 -12
- package/src/utils/loginParser/autoLogin.js +12 -0
- package/src/utils/loginParser/parseAndCheckLogin.js +7 -0
- package/src/utils/loginParser/textUtils.js +6 -0
- package/src/utils/request/config.js +4 -1
- package/src/utils/request/methods.js +0 -13
- package/src/utils/request/proxy.js +13 -0
- package/src/utils/request/retry.js +0 -10
- package/src/utils/request/sanitize.js +1 -1
- package/src/utils/textEffects.js +85 -0
- package/src/utils/utils.js +17 -3
- package/src/utils/instanceLock.js +0 -35
- package/src/utils/ipGuard.js +0 -58
- package/src/utils/sendThrottle.js +0 -51
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Fixed and Optimized listenMqtt.js
|
|
3
|
+
* Prevents MQTT loop hangs, fixes heartbeat ping leaks, and cleans up event listeners.
|
|
4
|
+
*/
|
|
2
5
|
|
|
3
6
|
"use strict";
|
|
4
7
|
|
|
@@ -17,15 +20,14 @@ const getTaskResponseData = require("./core/getTaskResponseData");
|
|
|
17
20
|
const createEmitAuth = require("./core/emitAuth");
|
|
18
21
|
const createMiddlewareSystem = require("./middleware");
|
|
19
22
|
|
|
20
|
-
const CYCLE_MS_DEFAULT =
|
|
21
|
-
const RECONNECT_DELAY_MS_DEFAULT =
|
|
23
|
+
const CYCLE_MS_DEFAULT = 60 * 60 * 1000;
|
|
24
|
+
const RECONNECT_DELAY_MS_DEFAULT = 3000;
|
|
22
25
|
const UNSUB_ALL_TIMEOUT_MS = 5000;
|
|
23
|
-
const MAX_MQTT_RECONNECT_DELAY_MS =
|
|
24
|
-
const MAX_MQTT_RECONNECT_COOLDOWN_MS =
|
|
25
|
-
const MAX_MQTT_RECONNECT_ATTEMPTS =
|
|
26
|
-
const HEARTBEAT_INTERVAL_MS =
|
|
27
|
-
const HEARTBEAT_TIMEOUT_MS =
|
|
28
|
-
const MIN_FORCE_CYCLE_MS = 10 * 60 * 1000;
|
|
26
|
+
const MAX_MQTT_RECONNECT_DELAY_MS = 60000;
|
|
27
|
+
const MAX_MQTT_RECONNECT_COOLDOWN_MS = 10 * 60 * 1000; // long cooldown after exhausting fast retries - never give up permanently
|
|
28
|
+
const MAX_MQTT_RECONNECT_ATTEMPTS = 10;
|
|
29
|
+
const HEARTBEAT_INTERVAL_MS = 30000;
|
|
30
|
+
const HEARTBEAT_TIMEOUT_MS = 10000;
|
|
29
31
|
|
|
30
32
|
const parseDelta = createParseDelta({ parseAndCheckLogin });
|
|
31
33
|
const emitAuth = createEmitAuth({ logger });
|
|
@@ -80,7 +82,11 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
80
82
|
function postSafe(...args) {
|
|
81
83
|
return rawPost(...args).catch(err => {
|
|
82
84
|
const msg = (err && err.error) || (err && err.message) || String(err || "");
|
|
83
|
-
|
|
85
|
+
// A single request can briefly see an expired web session while
|
|
86
|
+
// another request is refreshing the shared cookie jar. Do not
|
|
87
|
+
// tear down the live MQTT session for that recoverable case;
|
|
88
|
+
// the shared auto-login promise handles the HTTP request and
|
|
89
|
+
// MQTT reconnects itself if the socket also needs refreshing.
|
|
84
90
|
if (/blocked the login|Checkpoint/i.test(msg)) {
|
|
85
91
|
emitAuth(
|
|
86
92
|
ctx,
|
|
@@ -103,18 +109,9 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
103
109
|
let isReconnecting = false;
|
|
104
110
|
|
|
105
111
|
function getReconnectDelay() {
|
|
106
|
-
|
|
107
|
-
const immediate = process.env.FCA_NX_MQTT_IMMEDIATE_RECONNECT === "1";
|
|
108
|
-
if (immediate) {
|
|
109
|
-
if (reconnectAttempts <= 1) return 0;
|
|
110
|
-
const fast = Math.min(1000 * Math.pow(2, reconnectAttempts - 2), MAX_MQTT_RECONNECT_DELAY_MS);
|
|
111
|
-
const j = Math.floor(Math.random() * Math.min(500, fast * 0.2));
|
|
112
|
-
return Math.min(fast + j, MAX_MQTT_RECONNECT_DELAY_MS);
|
|
113
|
-
}
|
|
114
112
|
const base = conf.reconnectDelayMs || RECONNECT_DELAY_MS_DEFAULT;
|
|
115
113
|
const exp = Math.min(base * Math.pow(2, reconnectAttempts), MAX_MQTT_RECONNECT_DELAY_MS);
|
|
116
|
-
|
|
117
|
-
const jitter = Math.floor(Math.random() * Math.min(4000, exp * 0.4));
|
|
114
|
+
const jitter = Math.floor(Math.random() * Math.min(1000, exp * 0.2));
|
|
118
115
|
return Math.min(exp + jitter, MAX_MQTT_RECONNECT_DELAY_MS);
|
|
119
116
|
}
|
|
120
117
|
|
|
@@ -124,11 +121,6 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
124
121
|
return Promise.resolve();
|
|
125
122
|
}
|
|
126
123
|
|
|
127
|
-
if (ctx._getSeqIDInFlight) {
|
|
128
|
-
logger("mqtt getSeqID skipped - already in flight", "warn");
|
|
129
|
-
return ctx._getSeqIDInFlight;
|
|
130
|
-
}
|
|
131
|
-
|
|
132
124
|
const form = {
|
|
133
125
|
av: ctx.globalOptions.pageID || ctx.userID,
|
|
134
126
|
fb_dtsg: ctx.fb_dtsg,
|
|
@@ -148,11 +140,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
148
140
|
};
|
|
149
141
|
|
|
150
142
|
logger("mqtt getSeqID call", "info");
|
|
151
|
-
|
|
152
|
-
return getSeqIDFactory(defaultFuncs, api, ctx, globalCallback, form);
|
|
153
|
-
}).finally(function () { ctx._getSeqIDInFlight = null; });
|
|
154
|
-
ctx._getSeqIDInFlight = _seqP;
|
|
155
|
-
return _seqP
|
|
143
|
+
return getSeqIDFactory(defaultFuncs, api, ctx, globalCallback, form)
|
|
156
144
|
.then(() => {
|
|
157
145
|
logger("mqtt getSeqID done", "info");
|
|
158
146
|
ctx._cycling = false;
|
|
@@ -213,9 +201,6 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
213
201
|
|
|
214
202
|
lastPongTime = Date.now();
|
|
215
203
|
|
|
216
|
-
const hbBase = conf.heartbeatInterval || HEARTBEAT_INTERVAL_MS;
|
|
217
|
-
const hbEvery = hbBase + Math.floor(Math.random() * Math.min(8000, hbBase * 0.25));
|
|
218
|
-
let missedPongs = 0;
|
|
219
204
|
heartbeatTimer = setInterval(() => {
|
|
220
205
|
if (!isConnected()) {
|
|
221
206
|
stopHeartbeat();
|
|
@@ -223,22 +208,19 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
223
208
|
}
|
|
224
209
|
|
|
225
210
|
const now = Date.now();
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
if (missedPongs >= 3) {
|
|
231
|
-
logger("mqtt heartbeat: silent too long, closing socket once", "warn");
|
|
232
|
-
missedPongs = 0;
|
|
233
|
-
stopHeartbeat();
|
|
234
|
-
try { ctx.mqttClient.end(true); } catch (_) { }
|
|
235
|
-
return;
|
|
236
|
-
}
|
|
237
|
-
logger("mqtt heartbeat: packet late, waiting", "warn");
|
|
238
|
-
} else {
|
|
239
|
-
missedPongs = 0;
|
|
211
|
+
if (now - lastPongTime > (conf.heartbeatTimeout || HEARTBEAT_TIMEOUT_MS) * 3) {
|
|
212
|
+
logger("mqtt heartbeat: no response, forcing reconnect", "warn");
|
|
213
|
+
forceCycle();
|
|
214
|
+
return;
|
|
240
215
|
}
|
|
241
|
-
|
|
216
|
+
|
|
217
|
+
try {
|
|
218
|
+
ctx.mqttClient.publish("/ping", JSON.stringify({ timestamp: Date.now() }), { qos: 0 });
|
|
219
|
+
logger("mqtt heartbeat sent", "debug");
|
|
220
|
+
} catch (err) {
|
|
221
|
+
logger(`mqtt heartbeat error: ${err.message}`, "warn");
|
|
222
|
+
}
|
|
223
|
+
}, conf.heartbeatInterval || HEARTBEAT_INTERVAL_MS);
|
|
242
224
|
}
|
|
243
225
|
|
|
244
226
|
function stopHeartbeat() {
|
|
@@ -289,7 +271,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
289
271
|
});
|
|
290
272
|
}
|
|
291
273
|
|
|
292
|
-
function endQuietly(next
|
|
274
|
+
function endQuietly(next) {
|
|
293
275
|
stopHeartbeat();
|
|
294
276
|
|
|
295
277
|
const finish = () => {
|
|
@@ -300,15 +282,12 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
300
282
|
} catch (_) { }
|
|
301
283
|
|
|
302
284
|
ctx.mqttClient = undefined;
|
|
285
|
+
ctx.lastSeqId = null;
|
|
286
|
+
ctx.syncToken = undefined;
|
|
303
287
|
ctx.t_mqttCalled = false;
|
|
304
288
|
ctx._ending = false;
|
|
305
289
|
ctx._cycling = false;
|
|
306
290
|
|
|
307
|
-
if (!soft) {
|
|
308
|
-
ctx.lastSeqId = null;
|
|
309
|
-
ctx.syncToken = undefined;
|
|
310
|
-
}
|
|
311
|
-
|
|
312
291
|
if (ctx._reconnectTimer) {
|
|
313
292
|
clearTimeout(ctx._reconnectTimer);
|
|
314
293
|
ctx._reconnectTimer = null;
|
|
@@ -322,18 +301,23 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
322
301
|
ctx.tasks.clear();
|
|
323
302
|
}
|
|
324
303
|
|
|
325
|
-
if (
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
}
|
|
304
|
+
if (ctx._userInfoIntervals && Array.isArray(ctx._userInfoIntervals)) {
|
|
305
|
+
ctx._userInfoIntervals.forEach(interval => {
|
|
306
|
+
try { clearInterval(interval); } catch (_) { }
|
|
307
|
+
});
|
|
308
|
+
ctx._userInfoIntervals = [];
|
|
309
|
+
}
|
|
332
310
|
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
}
|
|
311
|
+
if (ctx._autoSaveInterval && Array.isArray(ctx._autoSaveInterval)) {
|
|
312
|
+
ctx._autoSaveInterval.forEach(interval => {
|
|
313
|
+
try { clearInterval(interval); } catch (_) { }
|
|
314
|
+
});
|
|
315
|
+
ctx._autoSaveInterval = [];
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
if (ctx._scheduler && typeof ctx._scheduler.destroy === "function") {
|
|
319
|
+
try { ctx._scheduler.destroy(); } catch (_) { }
|
|
320
|
+
ctx._scheduler = undefined;
|
|
337
321
|
}
|
|
338
322
|
|
|
339
323
|
reconnectAttempts = 0;
|
|
@@ -344,10 +328,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
344
328
|
|
|
345
329
|
try {
|
|
346
330
|
if (ctx.mqttClient) {
|
|
347
|
-
if (
|
|
348
|
-
try {
|
|
349
|
-
ctx.mqttClient.publish("/foreground_state", JSON.stringify({ foreground: false }), { qos: 0 });
|
|
350
|
-
} catch (_) { }
|
|
331
|
+
if (isConnected()) {
|
|
351
332
|
try {
|
|
352
333
|
ctx.mqttClient.publish("/browser_close", "{}", { qos: 0 });
|
|
353
334
|
} catch (_) { }
|
|
@@ -363,18 +344,15 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
363
344
|
|
|
364
345
|
function delayedReconnect() {
|
|
365
346
|
if (ctx._ending) return;
|
|
347
|
+
const d = getReconnectDelay();
|
|
348
|
+
logger(`mqtt reconnect in ${d}ms`, "info");
|
|
366
349
|
|
|
367
350
|
if (ctx._reconnectTimer) {
|
|
368
|
-
|
|
369
|
-
|
|
351
|
+
clearTimeout(ctx._reconnectTimer);
|
|
352
|
+
ctx._reconnectTimer = null;
|
|
370
353
|
}
|
|
371
|
-
let d = getReconnectDelay();
|
|
372
|
-
|
|
373
|
-
if (d > 0) d += Math.floor(Math.random() * 1500);
|
|
374
|
-
logger(d === 0 ? "mqtt reconnecting immediately" : `mqtt reconnect in ${d}ms`, "info");
|
|
375
354
|
|
|
376
355
|
ctx._reconnectTimer = setTimeout(() => {
|
|
377
|
-
ctx._reconnectTimer = null;
|
|
378
356
|
if (!ctx._ending) {
|
|
379
357
|
isReconnecting = false;
|
|
380
358
|
getSeqIDWrapper();
|
|
@@ -382,7 +360,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
382
360
|
}, d);
|
|
383
361
|
}
|
|
384
362
|
|
|
385
|
-
function forceCycle()
|
|
363
|
+
function forceCycle() {
|
|
386
364
|
if (ctx._cycling) {
|
|
387
365
|
logger("mqtt force cycle already in progress", "warn");
|
|
388
366
|
return;
|
|
@@ -392,34 +370,20 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
392
370
|
return;
|
|
393
371
|
}
|
|
394
372
|
|
|
395
|
-
const now = Date.now();
|
|
396
|
-
if (ctx._lastForceCycleAt && (now - ctx._lastForceCycleAt) < MIN_FORCE_CYCLE_MS) {
|
|
397
|
-
logger("mqtt force cycle skipped - too soon since last cycle", "warn");
|
|
398
|
-
return;
|
|
399
|
-
}
|
|
400
|
-
ctx._lastForceCycleAt = now;
|
|
401
|
-
|
|
402
373
|
ctx._cycling = true;
|
|
403
374
|
ctx._ending = true;
|
|
404
375
|
logger("mqtt force cycle begin", "warn");
|
|
405
376
|
|
|
406
377
|
stopHeartbeat();
|
|
407
378
|
|
|
408
|
-
const finish = () => {
|
|
409
|
-
ctx._ending = false;
|
|
410
|
-
ctx._cycling = false;
|
|
411
|
-
if (conf.reconnectAfterStop || conf.autoReconnect !== false) {
|
|
412
|
-
delayedReconnect();
|
|
413
|
-
}
|
|
414
|
-
};
|
|
415
|
-
|
|
416
379
|
unsubAll(() => {
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
380
|
+
endQuietly(() => {
|
|
381
|
+
ctx._ending = false;
|
|
382
|
+
ctx._cycling = false;
|
|
383
|
+
if (conf.reconnectAfterStop || conf.autoReconnect !== false) {
|
|
384
|
+
delayedReconnect();
|
|
385
|
+
}
|
|
386
|
+
});
|
|
423
387
|
});
|
|
424
388
|
}
|
|
425
389
|
|
|
@@ -444,13 +408,44 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
444
408
|
if (!ctx.mqttClient) return;
|
|
445
409
|
|
|
446
410
|
ctx.mqttClient.removeAllListeners("packetreceive");
|
|
447
|
-
|
|
411
|
+
ctx.mqttClient.removeAllListeners("close");
|
|
412
|
+
ctx.mqttClient.removeAllListeners("error");
|
|
413
|
+
|
|
414
|
+
// [Fixed by xalman] mqtt.js does NOT emit a "pong" event - that was never firing,
|
|
415
|
+
// so lastPongTime was never refreshed and the heartbeat below kept
|
|
416
|
+
// force-reconnecting the account roughly every minute (this is what
|
|
417
|
+
// looked like periodic auto logout). The library's own keepalive
|
|
418
|
+
// (keepalive: 30 in connectMqtt.js) sends PINGREQ/PINGRESP
|
|
419
|
+
// internally; we detect the PINGRESP via "packetreceive" instead.
|
|
420
|
+
// Any other incoming packet (e.g. real messages) also proves the
|
|
421
|
+
// connection is alive, so it counts too.
|
|
448
422
|
ctx.mqttClient.on("packetreceive", (packet) => {
|
|
449
423
|
lastPongTime = Date.now();
|
|
450
424
|
if (packet && packet.cmd === "pingresp") {
|
|
451
425
|
logger("mqtt pong received", "debug");
|
|
452
426
|
}
|
|
453
427
|
});
|
|
428
|
+
|
|
429
|
+
ctx.mqttClient.once("close", () => {
|
|
430
|
+
logger("mqtt connection closed", "warn");
|
|
431
|
+
stopHeartbeat();
|
|
432
|
+
if (!ctx._ending && ctx.globalOptions.autoReconnect !== false) {
|
|
433
|
+
if (!isReconnecting) {
|
|
434
|
+
isReconnecting = true;
|
|
435
|
+
delayedReconnect();
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
});
|
|
439
|
+
|
|
440
|
+
ctx.mqttClient.once("error", (err) => {
|
|
441
|
+
logger(`mqtt error: ${err.message}`, "error");
|
|
442
|
+
if (!ctx._ending && ctx.globalOptions.autoReconnect !== false) {
|
|
443
|
+
if (!isReconnecting) {
|
|
444
|
+
isReconnecting = true;
|
|
445
|
+
forceCycle();
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
});
|
|
454
449
|
}
|
|
455
450
|
|
|
456
451
|
return function (callback) {
|
|
@@ -515,17 +510,6 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
|
|
|
515
510
|
|
|
516
511
|
installPostGuard();
|
|
517
512
|
|
|
518
|
-
if (ctx.mqttClient && ctx.mqttClient.connected) {
|
|
519
|
-
logger("mqtt already connected - not opening a second session", "info");
|
|
520
|
-
attachClientListeners();
|
|
521
|
-
startHeartbeat();
|
|
522
|
-
api.stopListening = msgEmitter.stopListening;
|
|
523
|
-
api.stopListeningAsync = msgEmitter.stopListeningAsync;
|
|
524
|
-
api.forceReconnect = forceCycle;
|
|
525
|
-
api.isMqttConnected = isConnected;
|
|
526
|
-
return msgEmitter;
|
|
527
|
-
}
|
|
528
|
-
|
|
529
513
|
if (!ctx.firstListen) ctx.lastSeqId = null;
|
|
530
514
|
ctx.syncToken = undefined;
|
|
531
515
|
ctx.t_mqttCalled = false;
|
|
@@ -1,9 +1,25 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
const logger = require("../../../../func/logger");
|
|
3
3
|
|
|
4
|
+
/**
|
|
5
|
+
* Middleware system for filtering and processing events before they are emitted
|
|
6
|
+
*
|
|
7
|
+
* Middleware functions receive (event, next) where:
|
|
8
|
+
* - event: The event object (can be modified)
|
|
9
|
+
* - next: Function to call to continue to next middleware
|
|
10
|
+
* - next() - continue to next middleware
|
|
11
|
+
* - next(false) or next(null) - stop processing, don't emit event
|
|
12
|
+
* - next(error) - emit error instead
|
|
13
|
+
*/
|
|
4
14
|
module.exports = function createMiddlewareSystem() {
|
|
5
15
|
const middlewareStack = [];
|
|
6
16
|
|
|
17
|
+
/**
|
|
18
|
+
* Add middleware to the stack
|
|
19
|
+
* @param {Function|string} middleware - Middleware function or name for named middleware
|
|
20
|
+
* @param {Function} [fn] - Middleware function (if first param is name)
|
|
21
|
+
* @returns {Function} Unsubscribe function
|
|
22
|
+
*/
|
|
7
23
|
function use(middleware, fn) {
|
|
8
24
|
let middlewareFn, name;
|
|
9
25
|
|
|
@@ -26,6 +42,7 @@ module.exports = function createMiddlewareSystem() {
|
|
|
26
42
|
middlewareStack.push(wrapped);
|
|
27
43
|
logger(`Middleware "${name}" added`, "info");
|
|
28
44
|
|
|
45
|
+
// Return unsubscribe function
|
|
29
46
|
return function remove() {
|
|
30
47
|
const index = middlewareStack.indexOf(wrapped);
|
|
31
48
|
if (index !== -1) {
|
|
@@ -35,6 +52,11 @@ module.exports = function createMiddlewareSystem() {
|
|
|
35
52
|
};
|
|
36
53
|
}
|
|
37
54
|
|
|
55
|
+
/**
|
|
56
|
+
* Remove middleware by name or function
|
|
57
|
+
* @param {string|Function} identifier - Name or function to remove
|
|
58
|
+
* @returns {boolean} True if removed
|
|
59
|
+
*/
|
|
38
60
|
function remove(identifier) {
|
|
39
61
|
if (typeof identifier === "string") {
|
|
40
62
|
const index = middlewareStack.findIndex(m => m.name === identifier);
|
|
@@ -56,16 +78,29 @@ module.exports = function createMiddlewareSystem() {
|
|
|
56
78
|
return false;
|
|
57
79
|
}
|
|
58
80
|
|
|
81
|
+
/**
|
|
82
|
+
* Remove all middleware
|
|
83
|
+
*/
|
|
59
84
|
function clear() {
|
|
60
85
|
const count = middlewareStack.length;
|
|
61
86
|
middlewareStack.length = 0;
|
|
62
87
|
logger(`All middleware cleared (${count} removed)`, "info");
|
|
63
88
|
}
|
|
64
89
|
|
|
90
|
+
/**
|
|
91
|
+
* Get list of middleware names
|
|
92
|
+
* @returns {string[]} Array of middleware names
|
|
93
|
+
*/
|
|
65
94
|
function list() {
|
|
66
95
|
return middlewareStack.filter(m => m.enabled).map(m => m.name);
|
|
67
96
|
}
|
|
68
97
|
|
|
98
|
+
/**
|
|
99
|
+
* Enable/disable middleware by name
|
|
100
|
+
* @param {string} name - Middleware name
|
|
101
|
+
* @param {boolean} enabled - Enable or disable
|
|
102
|
+
* @returns {boolean} True if found and updated
|
|
103
|
+
*/
|
|
69
104
|
function setEnabled(name, enabled) {
|
|
70
105
|
const middleware = middlewareStack.find(m => m.name === name);
|
|
71
106
|
if (middleware) {
|
|
@@ -76,6 +111,12 @@ module.exports = function createMiddlewareSystem() {
|
|
|
76
111
|
return false;
|
|
77
112
|
}
|
|
78
113
|
|
|
114
|
+
/**
|
|
115
|
+
* Process event through middleware stack
|
|
116
|
+
* @param {*} event - Event object
|
|
117
|
+
* @param {Function} finalCallback - Callback to call after all middleware
|
|
118
|
+
* @returns {Promise} Promise that resolves when processing is complete
|
|
119
|
+
*/
|
|
79
120
|
function process(event, finalCallback) {
|
|
80
121
|
if (!middlewareStack.length) {
|
|
81
122
|
return finalCallback(null, event);
|
|
@@ -85,47 +126,57 @@ module.exports = function createMiddlewareSystem() {
|
|
|
85
126
|
const enabledMiddleware = middlewareStack.filter(m => m.enabled);
|
|
86
127
|
|
|
87
128
|
function next(err) {
|
|
88
|
-
|
|
129
|
+
// Error occurred, stop processing
|
|
89
130
|
if (err && err !== false && err !== null) {
|
|
90
131
|
return finalCallback(err, null);
|
|
91
132
|
}
|
|
92
133
|
|
|
134
|
+
// Explicitly stopped (next(false) or next(null))
|
|
93
135
|
if (err === false || err === null) {
|
|
94
|
-
return finalCallback(null, null);
|
|
136
|
+
return finalCallback(null, null); // null event means don't emit
|
|
95
137
|
}
|
|
96
138
|
|
|
139
|
+
// No more middleware, call final callback
|
|
97
140
|
if (index >= enabledMiddleware.length) {
|
|
98
141
|
return finalCallback(null, event);
|
|
99
142
|
}
|
|
100
143
|
|
|
144
|
+
// Get next middleware
|
|
101
145
|
const middleware = enabledMiddleware[index++];
|
|
102
146
|
|
|
103
147
|
try {
|
|
104
|
-
|
|
148
|
+
// Call middleware with event and next
|
|
105
149
|
const result = middleware.fn(event, next);
|
|
106
150
|
|
|
151
|
+
// If middleware returns a promise, handle it
|
|
107
152
|
if (result && typeof result.then === "function") {
|
|
108
153
|
result
|
|
109
154
|
.then(() => next())
|
|
110
155
|
.catch(err => next(err));
|
|
111
156
|
} else if (result === false || result === null) {
|
|
112
|
-
|
|
157
|
+
// Middleware returned false/null, stop processing
|
|
113
158
|
finalCallback(null, null);
|
|
114
159
|
}
|
|
115
|
-
|
|
160
|
+
// If middleware called next() synchronously, it will continue
|
|
116
161
|
} catch (err) {
|
|
117
162
|
logger(`Middleware "${middleware.name}" error: ${err && err.message ? err.message : String(err)}`, "error");
|
|
118
163
|
next(err);
|
|
119
164
|
}
|
|
120
165
|
}
|
|
121
166
|
|
|
167
|
+
// Start processing
|
|
122
168
|
next();
|
|
123
169
|
}
|
|
124
170
|
|
|
171
|
+
/**
|
|
172
|
+
* Wrap a callback with middleware processing
|
|
173
|
+
* @param {Function} callback - Original callback (err, event)
|
|
174
|
+
* @returns {Function} Wrapped callback
|
|
175
|
+
*/
|
|
125
176
|
function wrapCallback(callback) {
|
|
126
177
|
return function wrappedCallback(err, event) {
|
|
127
178
|
if (err) {
|
|
128
|
-
|
|
179
|
+
// Errors bypass middleware
|
|
129
180
|
return callback(err, null);
|
|
130
181
|
}
|
|
131
182
|
|
|
@@ -133,15 +184,18 @@ module.exports = function createMiddlewareSystem() {
|
|
|
133
184
|
return callback(null, null);
|
|
134
185
|
}
|
|
135
186
|
|
|
187
|
+
// Process event through middleware
|
|
136
188
|
process(event, (middlewareErr, processedEvent) => {
|
|
137
189
|
if (middlewareErr) {
|
|
138
190
|
return callback(middlewareErr, null);
|
|
139
191
|
}
|
|
140
192
|
|
|
193
|
+
// If processedEvent is null, middleware blocked the event
|
|
141
194
|
if (processedEvent === null) {
|
|
142
|
-
return;
|
|
195
|
+
return; // Don't emit
|
|
143
196
|
}
|
|
144
197
|
|
|
198
|
+
// Emit processed event
|
|
145
199
|
callback(null, processedEvent);
|
|
146
200
|
});
|
|
147
201
|
};
|