@stemy/backend 6.1.2 → 6.1.4

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.
@@ -1447,6 +1447,39 @@ let JobManager = class JobManager {
1447
1447
  apiPull;
1448
1448
  workerPush;
1449
1449
  workerPull;
1450
+ zmqStats = {
1451
+ apiPush: {
1452
+ queued: 0,
1453
+ pending: 0,
1454
+ failed: 0,
1455
+ sent: 0,
1456
+ received: 0,
1457
+ lastSentAt: 0,
1458
+ lastReceivedAt: 0
1459
+ },
1460
+ apiPull: {
1461
+ sent: 0,
1462
+ received: 0,
1463
+ lastSentAt: 0,
1464
+ lastReceivedAt: 0
1465
+ },
1466
+ workerPush: {
1467
+ queued: 0,
1468
+ pending: 0,
1469
+ failed: 0,
1470
+ sent: 0,
1471
+ received: 0,
1472
+ lastSentAt: 0,
1473
+ lastReceivedAt: 0
1474
+ },
1475
+ workerPull: {
1476
+ sent: 0,
1477
+ received: 0,
1478
+ lastSentAt: 0,
1479
+ lastReceivedAt: 0
1480
+ }
1481
+ };
1482
+ zmqDiagnosticsTimer;
1450
1483
  maxTimeout;
1451
1484
  constructor(config, logger, container, jobTypes) {
1452
1485
  this.config = config;
@@ -1459,9 +1492,13 @@ let JobManager = class JobManager {
1459
1492
  const job = this.resolveJobInstance(jobType, jobParams, uniqueId);
1460
1493
  const messageBridge = {
1461
1494
  sendMessage: (message, params) => {
1462
- params.uniqueId = uniqueId;
1463
- this.workerPush.then(sock => {
1464
- sock.send([message, JSON.stringify(params)]);
1495
+ Promise.resolve().then(() => {
1496
+ return this.sendSocketMessage("workerPush", [
1497
+ message,
1498
+ JSON.stringify({ ...params, uniqueId })
1499
+ ]);
1500
+ }).catch(e => {
1501
+ this.logger.log("job-manager", `ZMQ workerPush send failed: ${e.message}`);
1465
1502
  });
1466
1503
  }
1467
1504
  };
@@ -1472,6 +1509,7 @@ let JobManager = class JobManager {
1472
1509
  }, {});
1473
1510
  this.messages = new Subject();
1474
1511
  this.maxTimeout = this.config.resolve("jobTimeout");
1512
+ this.startZmqDiagnostics();
1475
1513
  }
1476
1514
  on(message, cb) {
1477
1515
  return this.messages
@@ -1521,16 +1559,11 @@ let JobManager = class JobManager {
1521
1559
  const host = this.config.resolve("zmqRemoteHost");
1522
1560
  const pushHost = `${host}:${this.config.resolve("zmqBackPort")}`;
1523
1561
  const pullHost = `${host}:${this.config.resolve("zmqPort")}`;
1524
- this.workerPush = this.workerPush || new Promise(resolve => {
1525
- const sock = socket("push");
1526
- sock.connect(pushHost);
1527
- this.logger.log("job-manager", `Worker producer connected to: ${pushHost}`);
1528
- resolve(sock);
1529
- });
1530
- this.workerPull = this.workerPull || new Promise(resolve => {
1531
- const sock = socket("pull");
1532
- sock.connect(pullHost);
1562
+ this.workerPush = this.workerPush || this.connectSocket("workerPush", "push", pushHost);
1563
+ this.workerPull = this.workerPull || this.connectSocket("workerPull", "pull", pullHost).then(sock => {
1533
1564
  sock.on("message", async (name, args, uniqId) => {
1565
+ this.zmqStats.workerPull.received++;
1566
+ this.zmqStats.workerPull.lastReceivedAt = Date.now();
1534
1567
  try {
1535
1568
  const jobName = name.toString("utf8");
1536
1569
  const jobParams = JSON.parse(args.toString("utf8"));
@@ -1550,13 +1583,15 @@ let JobManager = class JobManager {
1550
1583
  this.logger.log("job-manager", `Failed to start job: ${e.message}`);
1551
1584
  }
1552
1585
  });
1553
- this.logger.log("job-manager", `Worker consumer connected to: ${pullHost}`);
1554
- resolve(sock);
1586
+ return sock;
1555
1587
  });
1556
- await Promise.allSettled([
1557
- this.workerPush,
1558
- this.workerPull,
1559
- ]);
1588
+ try {
1589
+ await Promise.all([this.workerPush, this.workerPull]);
1590
+ }
1591
+ catch (e) {
1592
+ this.logger.log("job-manager", `ZMQ worker initialization failed: ${e.message}`);
1593
+ throw e;
1594
+ }
1560
1595
  }
1561
1596
  tryResolve(jobType, params) {
1562
1597
  const jobName = getConstructorName(jobType);
@@ -1581,33 +1616,98 @@ let JobManager = class JobManager {
1581
1616
  return this.tryResolveAndInit(jobType, params);
1582
1617
  }
1583
1618
  tryResolveAndInit(jobType, params) {
1584
- this.apiPush = this.apiPush || new Promise(resolve => {
1585
- const port = this.config.resolve("zmqPort");
1586
- const sock = socket("push");
1587
- sock.bind(`tcp://0.0.0.0:${port}`, () => {
1588
- this.logger.log("job-manager", `API producer bound to port: ${port}`);
1589
- resolve(sock);
1619
+ const jobName = this.tryResolve(jobType, params);
1620
+ this.apiPush = this.apiPush || this.bindSocket("apiPush", "push", `tcp://0.0.0.0:${this.config.resolve("zmqPort")}`);
1621
+ this.apiPull = this.apiPull || this.bindSocket("apiPull", "pull", `tcp://0.0.0.0:${this.config.resolve("zmqBackPort")}`).then(sock => {
1622
+ sock.on("message", (name, args) => {
1623
+ this.zmqStats.apiPull.received++;
1624
+ this.zmqStats.apiPull.lastReceivedAt = Date.now();
1625
+ const message = name.toString("utf8");
1626
+ const params = JSON.parse(args?.toString("utf8") || "{}");
1627
+ const paramTypes = Object.keys(params).reduce((res, key) => {
1628
+ res[key] = getType(params[key]);
1629
+ return res;
1630
+ }, {});
1631
+ this.logger.log("job-manager", `Received a message from worker: "${colorize(message, ConsoleColor.FgCyan)}" with args: ${jsonHighlight(paramTypes)}\n\n`);
1632
+ this.messages.next({ message, params });
1590
1633
  });
1634
+ return sock;
1591
1635
  });
1592
- this.apiPull = this.apiPush || new Promise(resolve => {
1593
- const backPort = this.config.resolve("zmqBackPort");
1594
- const sock = socket("pull");
1595
- sock.bind(`tcp://0.0.0.0:${backPort}`, () => {
1596
- sock.on("message", (name, args) => {
1597
- const message = name.toString("utf8");
1598
- const params = JSON.parse(args?.toString("utf8") || "{}");
1599
- const paramTypes = Object.keys(params).reduce((res, key) => {
1600
- res[key] = getType(params[key]);
1601
- return res;
1602
- }, {});
1603
- this.logger.log("job-manager", `Received a message from worker: "${colorize(message, ConsoleColor.FgCyan)}" with args: ${jsonHighlight(paramTypes)}\n\n`);
1604
- this.messages.next({ message, params });
1605
- });
1606
- this.logger.log("job-manager", `API consumer bound to port: ${backPort}`);
1636
+ return jobName;
1637
+ }
1638
+ createSocket(name, type) {
1639
+ const sock = socket(type);
1640
+ sock.setsockopt("heartbeat_ivl", 5_000);
1641
+ sock.setsockopt("heartbeat_timeout", 15_000);
1642
+ sock.setsockopt("heartbeat_ttl", 15_000);
1643
+ sock.on("error", (error) => {
1644
+ this.logger.log("job-manager", `ZMQ ${name} error: ${error.message}`);
1645
+ });
1646
+ [
1647
+ "connect", "connect_delay", "connect_retry", "listen", "bind_error",
1648
+ "accept", "accept_error", "close", "close_error", "disconnect"
1649
+ ].forEach(event => {
1650
+ sock.on(event, (value, address, error) => {
1651
+ this.logger.log("job-manager", `ZMQ ${name} ${event}: ${address}` +
1652
+ (value === undefined ? "" : ` (value=${value})`) +
1653
+ (error ? `: ${error.message}` : ""));
1654
+ });
1655
+ });
1656
+ sock.monitor();
1657
+ return sock;
1658
+ }
1659
+ bindSocket(name, type, address) {
1660
+ return new Promise((resolve, reject) => {
1661
+ const sock = this.createSocket(name, type);
1662
+ sock.bind(address, (error) => {
1663
+ if (error) {
1664
+ this.logger.log("job-manager", `ZMQ ${name} bind failed at ${address}: ${error.message}`);
1665
+ sock.close();
1666
+ reject(error);
1667
+ return;
1668
+ }
1669
+ this.logger.log("job-manager", `ZMQ ${name} bound to: ${address}`);
1607
1670
  resolve(sock);
1608
1671
  });
1609
1672
  });
1610
- return this.tryResolve(jobType, params);
1673
+ }
1674
+ async connectSocket(name, type, address) {
1675
+ const sock = this.createSocket(name, type);
1676
+ try {
1677
+ sock.connect(address);
1678
+ this.logger.log("job-manager", `ZMQ ${name} connecting to: ${address}`);
1679
+ return sock;
1680
+ }
1681
+ catch (e) {
1682
+ sock.close();
1683
+ throw e;
1684
+ }
1685
+ }
1686
+ async sendSocketMessage(name, frames) {
1687
+ const stats = this.zmqStats[name];
1688
+ stats.queued++;
1689
+ stats.pending++;
1690
+ try {
1691
+ const sock = await this[name];
1692
+ await new Promise((resolve, reject) => {
1693
+ sock.send(frames, 0, (error) => {
1694
+ if (error) {
1695
+ reject(error);
1696
+ return;
1697
+ }
1698
+ resolve();
1699
+ });
1700
+ });
1701
+ stats.sent++;
1702
+ stats.lastSentAt = Date.now();
1703
+ }
1704
+ catch (e) {
1705
+ stats.failed++;
1706
+ throw e;
1707
+ }
1708
+ finally {
1709
+ stats.pending--;
1710
+ }
1611
1711
  }
1612
1712
  resolveJobInstance(jobType, params, uniqueId = "") {
1613
1713
  const container = this.container.createChildContainer();
@@ -1620,10 +1720,35 @@ let JobManager = class JobManager {
1620
1720
  }
1621
1721
  async sendToWorkers(jobName, params) {
1622
1722
  const uniqueId = new ObjectId$1().toHexString();
1623
- const sock = await this.apiPush;
1624
- sock.send([jobName, JSON.stringify(params), uniqueId]);
1723
+ try {
1724
+ await Promise.all([this.apiPush, this.apiPull]);
1725
+ await this.sendSocketMessage("apiPush", [jobName, JSON.stringify(params), uniqueId]);
1726
+ }
1727
+ catch (e) {
1728
+ this.logger.log("job-manager", `ZMQ API PUSH send failed: ${e.message}`);
1729
+ throw e;
1730
+ }
1625
1731
  return uniqueId;
1626
1732
  }
1733
+ startZmqDiagnostics() {
1734
+ this.zmqDiagnosticsTimer = setInterval(() => {
1735
+ const now = Date.now();
1736
+ const age = (timestamp) => {
1737
+ if (!timestamp) {
1738
+ return "never";
1739
+ }
1740
+ return `${Math.round((now - timestamp) / 1000)}s ago`;
1741
+ };
1742
+ this.logger.log("job-manager", [
1743
+ "ZMQ diagnostics:",
1744
+ `apiPush(queued=${this.zmqStats.apiPush.queued}, pending=${this.zmqStats.apiPush.pending}, failed=${this.zmqStats.apiPush.failed}, sentToZmq=${this.zmqStats.apiPush.sent}, lastSent=${age(this.zmqStats.apiPush.lastSentAt)})`,
1745
+ `apiPull(received=${this.zmqStats.apiPull.received}, lastReceived=${age(this.zmqStats.apiPull.lastReceivedAt)})`,
1746
+ `workerPush(queued=${this.zmqStats.workerPush.queued}, pending=${this.zmqStats.workerPush.pending}, failed=${this.zmqStats.workerPush.failed}, sentToZmq=${this.zmqStats.workerPush.sent}, lastSent=${age(this.zmqStats.workerPush.lastSentAt)})`,
1747
+ `workerPull(received=${this.zmqStats.workerPull.received}, lastReceived=${age(this.zmqStats.workerPull.lastReceivedAt)})`
1748
+ ].join(" | "));
1749
+ }, 30_000);
1750
+ this.zmqDiagnosticsTimer.unref?.();
1751
+ }
1627
1752
  };
1628
1753
  JobManager = __decorate([
1629
1754
  singleton(),