@okf/ootils 1.5.5 → 1.6.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/dist/node.mjs CHANGED
@@ -170,15 +170,10 @@ var init_Annotations = __esm({
170
170
  }
171
171
  });
172
172
 
173
- // src/models/PlatformConfigs.ts
174
- var PlatformConfigs_exports = {};
175
- __export(PlatformConfigs_exports, {
176
- default: () => PlatformConfigs_default
177
- });
178
- import mongoose2 from "mongoose";
179
- var platformConfigTypes, PlatformConfigsSchema, PlatformConfigs_default;
180
- var init_PlatformConfigs = __esm({
181
- "src/models/PlatformConfigs.ts"() {
173
+ // src/models/PlatformConfigs/platformConfigTypes.ts
174
+ var platformConfigTypes;
175
+ var init_platformConfigTypes = __esm({
176
+ "src/models/PlatformConfigs/platformConfigTypes.ts"() {
182
177
  "use strict";
183
178
  platformConfigTypes = [
184
179
  "roles",
@@ -189,6 +184,20 @@ var init_PlatformConfigs = __esm({
189
184
  "theme",
190
185
  "ai"
191
186
  ];
187
+ }
188
+ });
189
+
190
+ // src/models/PlatformConfigs/index.ts
191
+ var PlatformConfigs_exports = {};
192
+ __export(PlatformConfigs_exports, {
193
+ default: () => PlatformConfigs_default
194
+ });
195
+ import mongoose2 from "mongoose";
196
+ var PlatformConfigsSchema, PlatformConfigs_default;
197
+ var init_PlatformConfigs = __esm({
198
+ "src/models/PlatformConfigs/index.ts"() {
199
+ "use strict";
200
+ init_platformConfigTypes();
192
201
  PlatformConfigsSchema = new mongoose2.Schema(
193
202
  {
194
203
  type: {
@@ -588,36 +597,6 @@ var require_ElasticSearchConnector = __commonJS({
588
597
  }
589
598
  });
590
599
 
591
- // src/db/getDbByTenant.js
592
- var getDbByTenant_exports = {};
593
- __export(getDbByTenant_exports, {
594
- getDbByTenant: () => getDbByTenant
595
- });
596
- import { Connection } from "mongoose";
597
- var import_MongoConnector, getDbByTenant;
598
- var init_getDbByTenant = __esm({
599
- "src/db/getDbByTenant.js"() {
600
- "use strict";
601
- import_MongoConnector = __toESM(require_MongoConnector());
602
- getDbByTenant = ({
603
- tenant,
604
- env: _env
605
- }) => {
606
- if (!tenant) throw new Error("tenant id has not been provided");
607
- const env = _env || import_MongoConnector.MongoConnector.getEnv();
608
- const dbConfigs = import_MongoConnector.MongoConnector.getDbConfigs();
609
- const clusterConnections = import_MongoConnector.MongoConnector.getClusterConnections();
610
- const { CLUSTER_NAME } = dbConfigs[env];
611
- const dbName = `${tenant}_${env}`;
612
- const connection = clusterConnections[CLUSTER_NAME];
613
- if (!connection) {
614
- throw new Error(`Connection not found for cluster: ${CLUSTER_NAME}`);
615
- }
616
- return connection.useDb(dbName, { useCache: true });
617
- };
618
- }
619
- });
620
-
621
600
  // src/models/AIChat.ts
622
601
  import mongoose4 from "mongoose";
623
602
  var AIChatSchema, AIChat_default;
@@ -680,13 +659,43 @@ var init_models = __esm({
680
659
  }
681
660
  });
682
661
 
662
+ // src/db/getDbByTenant.js
663
+ var getDbByTenant_exports = {};
664
+ __export(getDbByTenant_exports, {
665
+ getDbByTenant: () => getDbByTenant
666
+ });
667
+ import { Connection } from "mongoose";
668
+ var import_MongoConnector, getDbByTenant;
669
+ var init_getDbByTenant = __esm({
670
+ "src/db/getDbByTenant.js"() {
671
+ "use strict";
672
+ import_MongoConnector = __toESM(require_MongoConnector());
673
+ getDbByTenant = ({
674
+ tenant,
675
+ env: _env
676
+ }) => {
677
+ if (!tenant) throw new Error("tenant id has not been provided");
678
+ const env = _env || import_MongoConnector.MongoConnector.getEnv();
679
+ const dbConfigs = import_MongoConnector.MongoConnector.getDbConfigs();
680
+ const clusterConnections = import_MongoConnector.MongoConnector.getClusterConnections();
681
+ const { CLUSTER_NAME } = dbConfigs[env];
682
+ const dbName = `${tenant}_${env}`;
683
+ const connection = clusterConnections[CLUSTER_NAME];
684
+ if (!connection) {
685
+ throw new Error(`Connection not found for cluster: ${CLUSTER_NAME}`);
686
+ }
687
+ return connection.useDb(dbName, { useCache: true });
688
+ };
689
+ }
690
+ });
691
+
683
692
  // src/db/getModelByTenant.js
684
693
  var require_getModelByTenant = __commonJS({
685
694
  "src/db/getModelByTenant.js"(exports, module) {
686
695
  "use strict";
687
696
  var { getDbByTenant: getDbByTenant2 } = (init_getDbByTenant(), __toCommonJS(getDbByTenant_exports));
688
697
  var { AIChatSchema: AIChatSchema2, AnnotationSchema: AnnotationSchema2, PlatformConfigsSchema: PlatformConfigsSchema2, TplSchema: TplSchema2 } = (init_models(), __toCommonJS(models_exports));
689
- var getModelByTenant2 = ({ tenant, modelName, schema, env }) => {
698
+ var getModelByTenant3 = ({ tenant, modelName, schema, env }) => {
690
699
  if (!tenant) {
691
700
  throw new Error("tenant id has not been provided");
692
701
  }
@@ -696,32 +705,32 @@ var require_getModelByTenant = __commonJS({
696
705
  }
697
706
  return db.model(modelName);
698
707
  };
699
- var getAnnotationsModelByTenant2 = ({ tenant, env, mongodb, dbConfigs, modelName }) => getModelByTenant2({
708
+ var getAnnotationsModelByTenant2 = ({ tenant, env, mongodb, dbConfigs, modelName }) => getModelByTenant3({
700
709
  tenant,
701
710
  modelName: modelName || "annotations",
702
711
  schema: AnnotationSchema2,
703
712
  env
704
713
  });
705
- var getPlatformConfigsModelByTenant2 = ({ tenant, env, mongodb, dbConfigs }) => getModelByTenant2({
714
+ var getPlatformConfigsModelByTenant2 = ({ tenant, env, mongodb, dbConfigs }) => getModelByTenant3({
706
715
  tenant,
707
716
  modelName: "platformConfigs",
708
717
  schema: PlatformConfigsSchema2,
709
718
  env
710
719
  });
711
- var getTplModelByTenant2 = ({ tenant, env, mongodb, dbConfigs }) => getModelByTenant2({
720
+ var getTplModelByTenant2 = ({ tenant, env, mongodb, dbConfigs }) => getModelByTenant3({
712
721
  tenant,
713
722
  modelName: "tpl",
714
723
  schema: TplSchema2,
715
724
  env
716
725
  });
717
- var getAIChatModelByTenant2 = ({ tenant, env, mongodb, dbConfigs }) => getModelByTenant2({
726
+ var getAIChatModelByTenant2 = ({ tenant, env, mongodb, dbConfigs }) => getModelByTenant3({
718
727
  tenant,
719
728
  modelName: "aiChat",
720
729
  schema: AIChatSchema2,
721
730
  env
722
731
  });
723
732
  module.exports = {
724
- getModelByTenant: getModelByTenant2,
733
+ getModelByTenant: getModelByTenant3,
725
734
  getAIChatModelByTenant: getAIChatModelByTenant2,
726
735
  getAnnotationsModelByTenant: getAnnotationsModelByTenant2,
727
736
  getPlatformConfigsModelByTenant: getPlatformConfigsModelByTenant2,
@@ -784,6 +793,145 @@ var require_WorkerManager = __commonJS({
784
793
  }
785
794
  });
786
795
 
796
+ // src/bullmq/ProducerManager.js
797
+ var require_ProducerManager = __commonJS({
798
+ "src/bullmq/ProducerManager.js"(exports, module) {
799
+ "use strict";
800
+ var _ProducerManager = class _ProducerManager {
801
+ constructor(producerClasses = []) {
802
+ if (_ProducerManager.instance) {
803
+ return _ProducerManager.instance;
804
+ }
805
+ this.producerClasses = producerClasses;
806
+ this.activeProducers = /* @__PURE__ */ new Map();
807
+ _ProducerManager.instance = this;
808
+ }
809
+ // Static methods that delegate to singleton instance
810
+ static initialize(producerClasses = []) {
811
+ if (!this.instance) {
812
+ this.instance = new _ProducerManager(producerClasses);
813
+ }
814
+ return this.instance.initializeAllProducers();
815
+ }
816
+ static async addJob(producerClassName, jobName, jobData, opts = {}) {
817
+ if (!this.instance) {
818
+ throw new Error("ProducerManager not initialized. Call ProducerManager.initialize() first.");
819
+ }
820
+ return await this.instance.addJob(producerClassName, jobName, jobData, opts);
821
+ }
822
+ static async addBulkJobs(producerClassName, jobs) {
823
+ if (!this.instance) {
824
+ throw new Error("ProducerManager not initialized. Call ProducerManager.initialize() first.");
825
+ }
826
+ return await this.instance.addBulkJobs(producerClassName, jobs);
827
+ }
828
+ static async getStatus() {
829
+ if (!this.instance) {
830
+ throw new Error("ProducerManager not initialized. Call ProducerManager.initialize() first.");
831
+ }
832
+ return await this.instance.getStatus();
833
+ }
834
+ static async shutdown() {
835
+ if (this.instance) {
836
+ await this.instance.shutdown();
837
+ this.instance = null;
838
+ }
839
+ }
840
+ /**
841
+ * Initialize all producers as singletons
842
+ */
843
+ initializeAllProducers() {
844
+ if (this.producerClasses.length === 0) {
845
+ console.log("No producers provided to initialize");
846
+ return [];
847
+ }
848
+ console.log("\u{1F680} Initializing all producers...");
849
+ this.producerClasses.forEach((ProducerClass) => {
850
+ try {
851
+ const producerInstance = new ProducerClass();
852
+ this.activeProducers.set(ProducerClass.name, {
853
+ class: ProducerClass,
854
+ instance: producerInstance
855
+ });
856
+ console.log(`\u2705 Initialized ${ProducerClass.name}`);
857
+ } catch (error) {
858
+ console.error(`\u274C Failed to initialize ${ProducerClass.name}:`, error);
859
+ }
860
+ });
861
+ console.log(`\u{1F389} Successfully initialized ${this.activeProducers.size} producers`);
862
+ return Array.from(this.activeProducers.values());
863
+ }
864
+ /**
865
+ * Get a specific producer instance
866
+ */
867
+ getProducer(producerClassName) {
868
+ const producer = this.activeProducers.get(producerClassName);
869
+ if (!producer) {
870
+ throw new Error(`Producer ${producerClassName} not found. Make sure it's initialized.`);
871
+ }
872
+ return producer.instance;
873
+ }
874
+ /**
875
+ * Add a job using a specific producer
876
+ */
877
+ async addJob(producerClassName, jobData, opts = {}) {
878
+ const producer = this.getProducer(producerClassName);
879
+ return await producer.addJobWithName(jobData, opts);
880
+ }
881
+ /**
882
+ * Add bulk jobs using a specific producer
883
+ */
884
+ async addBulkJobs(producerClassName, jobs) {
885
+ const producer = this.getProducer(producerClassName);
886
+ return await producer.addBulkJobs(jobs);
887
+ }
888
+ /**
889
+ * Get status of all producers
890
+ */
891
+ async getStatus() {
892
+ const statusPromises = Array.from(this.activeProducers.entries()).map(
893
+ async ([name, { instance }]) => {
894
+ try {
895
+ const status = await instance.getStatus();
896
+ return {
897
+ name,
898
+ queueId: instance.config?.id || "unknown",
899
+ isActive: !!instance.queue,
900
+ ...status
901
+ };
902
+ } catch (error) {
903
+ return {
904
+ name,
905
+ queueId: instance.config?.id || "unknown",
906
+ isActive: false,
907
+ error: error.message
908
+ };
909
+ }
910
+ }
911
+ );
912
+ return await Promise.all(statusPromises);
913
+ }
914
+ /**
915
+ * Gracefully shutdown all producers
916
+ */
917
+ async shutdown() {
918
+ console.log("\u{1F6D1} Stopping all producers...");
919
+ const stopPromises = Array.from(this.activeProducers.entries()).map(
920
+ ([name, { instance }]) => instance.stop().catch(
921
+ (err) => console.error(`\u274C Error stopping ${name}:`, err)
922
+ )
923
+ );
924
+ await Promise.all(stopPromises);
925
+ this.activeProducers.clear();
926
+ console.log("\u2705 All producers stopped");
927
+ }
928
+ };
929
+ __publicField(_ProducerManager, "instance", null);
930
+ var ProducerManager2 = _ProducerManager;
931
+ module.exports = { ProducerManager: ProducerManager2 };
932
+ }
933
+ });
934
+
787
935
  // src/bullmq/BaseProducer.js
788
936
  var require_BaseProducer = __commonJS({
789
937
  "src/bullmq/BaseProducer.js"(exports, module) {
@@ -866,7 +1014,8 @@ var require_BaseProducer = __commonJS({
866
1014
  async stop() {
867
1015
  if (this.queue) {
868
1016
  await this.queue.close();
869
- console.log(`\u{1F6D1} ${this.constructor.name} queue closed`);
1017
+ await this.queue.disconnect();
1018
+ console.log(`\u{1F6D1} ${this.constructor.name} queue closed & disconnected`);
870
1019
  }
871
1020
  }
872
1021
  };
@@ -926,7 +1075,8 @@ var require_BaseWorker = __commonJS({
926
1075
  async stop() {
927
1076
  if (this.worker) {
928
1077
  await this.worker.close();
929
- console.log(`\u{1F6D1} ${this.constructor.name} stopped`);
1078
+ await this.worker.disconnect();
1079
+ console.log(`\u{1F6D1} ${this.constructor.name} stopped & disconnected`);
930
1080
  }
931
1081
  }
932
1082
  };
@@ -961,7 +1111,7 @@ var init_GLOBAL_BULLMQ_CONFIG = __esm({
961
1111
  concurrency: 1,
962
1112
  // Process jobs one at a time to avoid race conditions
963
1113
  limiter: {
964
- max: 10,
1114
+ max: 5,
965
1115
  // Max 10 jobs per...
966
1116
  duration: 6e4
967
1117
  // ...60 seconds (rate limiting)
@@ -1033,7 +1183,7 @@ var init_GLOBAL_BULLMQ_CONFIG = __esm({
1033
1183
  workerConfig: {
1034
1184
  concurrency: 1,
1035
1185
  limiter: {
1036
- max: 5,
1186
+ max: 15,
1037
1187
  // Max 50 jobs per...
1038
1188
  duration: 6e4
1039
1189
  // ...60 seconds (higher throughput for chunking)
@@ -1079,8 +1229,8 @@ var init_GLOBAL_BULLMQ_CONFIG = __esm({
1079
1229
  workerConfig: {
1080
1230
  concurrency: 1,
1081
1231
  limiter: {
1082
- max: 5,
1083
- // Max 5 jobs per...
1232
+ max: 15,
1233
+ // (lets always keep this same as content enhance & embed since it comes immediately after)
1084
1234
  duration: 6e4
1085
1235
  // ...60 seconds (higher throughput for chunking)
1086
1236
  }
@@ -1102,8 +1252,8 @@ var init_GLOBAL_BULLMQ_CONFIG = __esm({
1102
1252
  workerConfig: {
1103
1253
  concurrency: 5,
1104
1254
  limiter: {
1105
- max: 5,
1106
- // Max 5 jobs per...
1255
+ max: 15,
1256
+ // (lets always keep this same as content enhance & embed since it comes immediately after)
1107
1257
  duration: 6e4
1108
1258
  // ...60 seconds (higher throughput for chunking)
1109
1259
  }
@@ -1117,10 +1267,10 @@ var init_GLOBAL_BULLMQ_CONFIG = __esm({
1117
1267
  var require_GET_GLOBAL_BULLMQ_CONFIG = __commonJS({
1118
1268
  "src/bullmq/GET_GLOBAL_BULLMQ_CONFIG.js"(exports, module) {
1119
1269
  "use strict";
1120
- var { default: Redis } = __require("ioredis");
1270
+ var { default: Redis2 } = __require("ioredis");
1121
1271
  var { BASE_BULLMQ_CONFIG: BASE_BULLMQ_CONFIG2 } = (init_GLOBAL_BULLMQ_CONFIG(), __toCommonJS(GLOBAL_BULLMQ_CONFIG_exports));
1122
1272
  function GET_GLOBAL_BULLMQ_CONFIG2({ env, redisCredentials }) {
1123
- const redisConnectionForBullMQ = new Redis({
1273
+ const redisConnectionForBullMQ = new Redis2({
1124
1274
  host: redisCredentials.REDIS_HOST,
1125
1275
  port: redisCredentials.REDIS_PORT,
1126
1276
  password: redisCredentials.REDIS_PASSWORD,
@@ -1425,6 +1575,319 @@ var _extractBlocksFromSomeBuilders = ({
1425
1575
  // src/node.ts
1426
1576
  var import_MongoConnector2 = __toESM(require_MongoConnector());
1427
1577
  var import_ElasticSearchConnector = __toESM(require_ElasticSearchConnector());
1578
+
1579
+ // src/RedisCacheConnector.js
1580
+ init_models();
1581
+ import Redis from "ioredis";
1582
+ var import_getModelByTenant = __toESM(require_getModelByTenant());
1583
+ init_platformConfigTypes();
1584
+ var BASE_SETTINGS_FOR_CONFIGS_CACHE = [
1585
+ {
1586
+ modelName: "tpl",
1587
+ collectionName: "tpls",
1588
+ schema: Tpl_default,
1589
+ defaultQuery: [
1590
+ {
1591
+ status: {
1592
+ $ne: "unpublished"
1593
+ }
1594
+ },
1595
+ {
1596
+ drafts: 0
1597
+ }
1598
+ ],
1599
+ typeKey: "kp_content_type"
1600
+ },
1601
+ {
1602
+ modelName: "platformConfigs",
1603
+ collectionName: "platformConfigs",
1604
+ schema: PlatformConfigs_default,
1605
+ defaultQuery: [],
1606
+ typeKey: "type"
1607
+ }
1608
+ ];
1609
+ var RedisCacheConnector = class _RedisCacheConnector {
1610
+ constructor(options = {}) {
1611
+ /**
1612
+ * Initialize Redis client
1613
+ */
1614
+ __publicField(this, "connect", async () => {
1615
+ try {
1616
+ this.client = new Redis({
1617
+ host: this.host,
1618
+ port: this.port,
1619
+ password: this.password
1620
+ });
1621
+ this.client.on("connect", () => {
1622
+ console.log("\u2705 Connected to our redis cache instance!");
1623
+ });
1624
+ await new Promise((resolve, reject) => {
1625
+ this.client.on("ready", resolve);
1626
+ this.client.on("error", reject);
1627
+ });
1628
+ return this.client;
1629
+ } catch (err) {
1630
+ console.error(err.message);
1631
+ process.exit(1);
1632
+ }
1633
+ });
1634
+ if (_RedisCacheConnector.instance) {
1635
+ throw new Error(
1636
+ "RedisCacheConnector instance already exists. Use RedisCacheConnector.getInstance() instead."
1637
+ );
1638
+ }
1639
+ this.client = null;
1640
+ this.host = options.host;
1641
+ this.env = options.env;
1642
+ this.port = options.port;
1643
+ this.password = options.password;
1644
+ _RedisCacheConnector.instance = this;
1645
+ if (!this.host) {
1646
+ throw new Error("Host must be provided in constructor options");
1647
+ }
1648
+ if (!this.port) {
1649
+ throw new Error("Port must be provided in constructor options");
1650
+ }
1651
+ if (!this.password) {
1652
+ throw new Error("Password must be provided in constructor options");
1653
+ }
1654
+ if (!this.env) {
1655
+ throw new Error("Env must be provided in constructor options");
1656
+ }
1657
+ }
1658
+ static getEnv() {
1659
+ if (!_RedisCacheConnector.instance) {
1660
+ throw new Error("RedisCacheConnector not initialized");
1661
+ }
1662
+ return _RedisCacheConnector.instance.env;
1663
+ }
1664
+ // Static method to get the instance
1665
+ static getInstance() {
1666
+ if (!_RedisCacheConnector.instance) {
1667
+ throw new Error("RedisCacheConnector not initialized");
1668
+ }
1669
+ return _RedisCacheConnector.instance;
1670
+ }
1671
+ // Static method to get the client
1672
+ static getClient() {
1673
+ if (!_RedisCacheConnector.instance || !_RedisCacheConnector.instance.client) {
1674
+ throw new Error(
1675
+ "RedisCacheConnector not initialized or client not connected"
1676
+ );
1677
+ }
1678
+ return _RedisCacheConnector.instance.client;
1679
+ }
1680
+ /**
1681
+ * Find documents in Redis cache
1682
+ * @param {Object} params - Search parameters
1683
+ * @param {string} params.tenant - The tenant identifier
1684
+ * @param {'platformConfigs'|'tpl'} params.modelName - The collection to search in
1685
+ * @param {string} [params.type] - When modelName='platformConfigs': one of platformConfigTypes array values; when modelName='tpl': content type string. If omitted, returns all documents for the collection.
1686
+ * @returns {Promise<Array>} Array of matching documents
1687
+ * @see {platformConfigTypes} for valid platformConfigs type values
1688
+ */
1689
+ static async findConfigsInCache({ tenant, modelName, type }) {
1690
+ try {
1691
+ const client = this.getClient();
1692
+ const environment = this.getEnv();
1693
+ const keyPrefix = `${environment}:${tenant}:${modelName}:`;
1694
+ const keys = await client.keys(`${keyPrefix}${type || "*"}`);
1695
+ if (keys.length === 0) {
1696
+ const { schema, typeKey } = BASE_SETTINGS_FOR_CONFIGS_CACHE.find(
1697
+ (obj) => obj.modelName === modelName
1698
+ );
1699
+ const model = (0, import_getModelByTenant.getModelByTenant)({
1700
+ tenant,
1701
+ env: environment,
1702
+ modelName,
1703
+ schema
1704
+ });
1705
+ let findQuery = {};
1706
+ if (type) {
1707
+ findQuery = { [typeKey]: type };
1708
+ }
1709
+ const data = await model.find(findQuery);
1710
+ await Promise.all(
1711
+ data.map(
1712
+ (doc) => this.setOneConfigInCache({
1713
+ tenant,
1714
+ modelName,
1715
+ type: doc[typeKey],
1716
+ val: doc
1717
+ })
1718
+ )
1719
+ );
1720
+ return data;
1721
+ }
1722
+ const cachedDocs = await Promise.all(
1723
+ keys.map(async (key) => {
1724
+ const value = await client.get(key);
1725
+ return JSON.parse(value);
1726
+ })
1727
+ );
1728
+ return cachedDocs;
1729
+ } catch (error) {
1730
+ console.error("Error in findConfigsInCache:", error);
1731
+ throw error;
1732
+ }
1733
+ }
1734
+ /**
1735
+ * Find a single document in Redis cache (returns first match)
1736
+ * @param {Object} params - Search parameters
1737
+ * @param {string} params.tenant - The tenant identifier
1738
+ * @param {'platformConfigs'|'tpl'} params.modelName - The collection to search in
1739
+ * @param {string} [params.type] - When modelName='platformConfigs': one of platformConfigTypes array values; when modelName='tpl': content type string. If omitted, returns first document of any type.
1740
+ * @returns {Promise<Object|undefined>} First matching document or undefined if none found
1741
+ * @see {platformConfigTypes} for valid platformConfigs type values
1742
+ */
1743
+ static async findOneConfigInCache({ tenant, modelName, type }) {
1744
+ const cacheData = await this.findConfigsInCache({
1745
+ tenant,
1746
+ modelName,
1747
+ type
1748
+ });
1749
+ return cacheData?.[0];
1750
+ }
1751
+ /**
1752
+ * Generate Redis key for config caching
1753
+ * @private
1754
+ * @param {Object} params - Parameters for key generation
1755
+ * @param {string} params.tenant - The tenant identifier
1756
+ * @param {'platformConfigs'|'tpl'} params.modelName - The model/collection name
1757
+ * @param {string} params.type - The document type
1758
+ * @param {string} [params.env] - Environment (defaults to current env)
1759
+ * @returns {string} The Redis key
1760
+ */
1761
+ static _getRedisKeyForConfig({ tenant, modelName, type, env }) {
1762
+ const environment = env || this.getEnv();
1763
+ return `${environment}:${tenant}:${modelName}:${type}`;
1764
+ }
1765
+ /**
1766
+ * Set a single config document in Redis cache
1767
+ * @param {Object} params - Cache parameters
1768
+ * @param {string} params.tenant - The tenant identifier
1769
+ * @param {'platformConfigs'|'tpl'} params.modelName - The model/collection name
1770
+ * @param {string} params.type - When modelName='platformConfigs': one of platformConfigTypes array values; when modelName='tpl': content type string
1771
+ * @param {Object} params.val - The value to cache
1772
+ * @param {string} [params.env] - Environment (defaults to current env)
1773
+ * @returns {Promise<void>}
1774
+ * @see {platformConfigTypes} for valid platformConfigs type values
1775
+ */
1776
+ static async setOneConfigInCache({ tenant, modelName, type, val, env }) {
1777
+ const client = this.getClient();
1778
+ const cacheKey = this._getRedisKeyForConfig({
1779
+ tenant,
1780
+ modelName,
1781
+ type,
1782
+ env
1783
+ });
1784
+ await client.set(cacheKey, JSON.stringify(val));
1785
+ }
1786
+ /**
1787
+ * Invalidate (delete) a config from Redis cache and optionally set a new value
1788
+ * @param {Object} params - Cache parameters
1789
+ * @param {string} params.tenant - The tenant identifier
1790
+ * @param {'platformConfigs'|'tpl'} params.modelName - The model/collection name
1791
+ * @param {string} params.type - When modelName='platformConfigs': one of platformConfigTypes array values; when modelName='tpl': content type string
1792
+ * @param {Object} [params.newVal] - New value to set after deletion
1793
+ * @param {string} [params.env] - Environment (defaults to current env)
1794
+ * @returns {Promise<void>}
1795
+ * @see {platformConfigTypes} for valid platformConfigs type values
1796
+ * @note According to the current usecases this function is called only after a database operation.
1797
+ * We should include this function call within the MongoDB transaction.
1798
+ * Otherwise, if the database operation succeeds but cache deletion fails, the cache will hold the outdated data.
1799
+ * We can ignore setAsync failure as we are checking db also if cache is not present (inside findInCache function)
1800
+ */
1801
+ static async invalidateOneConfigInCache({
1802
+ tenant,
1803
+ modelName,
1804
+ type,
1805
+ newVal,
1806
+ env
1807
+ }) {
1808
+ const client = this.getClient();
1809
+ const cacheKey = this._getRedisKeyForConfig({
1810
+ tenant,
1811
+ modelName,
1812
+ type,
1813
+ env
1814
+ });
1815
+ await client.del(cacheKey);
1816
+ if (newVal) {
1817
+ try {
1818
+ await client.set(cacheKey, JSON.stringify(newVal));
1819
+ } catch (err) {
1820
+ console.log("invalidateCache - Cache set failed: ", err);
1821
+ }
1822
+ }
1823
+ }
1824
+ /**
1825
+ * Load all collections and templates into Redis cache for all tenants
1826
+ * Clears existing cache and rebuilds it from database
1827
+ * @returns {Promise<void>}
1828
+ * @param {string} [params.tenant] - Tenant (either a single tenant or an array of tenants for whom the config cache should be refreshed)
1829
+ * @static
1830
+ */
1831
+ static async loadTplsAndPlatformConfigsToCache({ tenant }) {
1832
+ try {
1833
+ const client = this.getClient();
1834
+ const environment = this.getEnv();
1835
+ if (!tenant) throw new Error("No tenant/s defined to recache");
1836
+ console.log(`Loading configs and templates into cache...`);
1837
+ const tenantCollectionPromises = toArray(tenant).map(async (tenant2) => {
1838
+ return Promise.all(
1839
+ BASE_SETTINGS_FOR_CONFIGS_CACHE.map(
1840
+ async ({ modelName, schema, defaultQuery, typeKey }) => {
1841
+ const model = (0, import_getModelByTenant.getModelByTenant)({
1842
+ tenant: tenant2,
1843
+ env: environment,
1844
+ modelName,
1845
+ schema
1846
+ });
1847
+ const keys = await client.keys(
1848
+ `${environment}:${tenant2}:${modelName}:*`
1849
+ );
1850
+ if (keys.length) await client.del(keys);
1851
+ const documents = await model.find(...defaultQuery);
1852
+ await Promise.all(
1853
+ documents.map(async (doc) => {
1854
+ const type = doc[typeKey];
1855
+ await this.setOneConfigInCache({
1856
+ tenant: tenant2,
1857
+ modelName,
1858
+ type,
1859
+ val: doc
1860
+ });
1861
+ })
1862
+ );
1863
+ console.log(
1864
+ `Successfully cached ${documents.length} documents from ${modelName} for tenant: ${tenant2} | env: ${environment}`
1865
+ );
1866
+ }
1867
+ )
1868
+ );
1869
+ });
1870
+ await Promise.all(tenantCollectionPromises);
1871
+ console.log(`Finished caching for all tenants`);
1872
+ } catch (error) {
1873
+ console.error("Error in loadTplsAndPlatformConfigsToCache: ", error);
1874
+ throw error;
1875
+ }
1876
+ }
1877
+ /**
1878
+ * Close the Redis client
1879
+ */
1880
+ async close() {
1881
+ if (this.client) {
1882
+ await this.client.quit();
1883
+ console.log("\u2705 Redis client closed");
1884
+ this.client = null;
1885
+ }
1886
+ }
1887
+ };
1888
+ RedisCacheConnector.instance = null;
1889
+
1890
+ // src/node.ts
1428
1891
  init_getDbByTenant();
1429
1892
 
1430
1893
  // src/db/getGlobalConfig.ts
@@ -1449,121 +1912,10 @@ var updateGlobalConfig = (updates) => {
1449
1912
  };
1450
1913
 
1451
1914
  // src/node.ts
1452
- var import_getModelByTenant = __toESM(require_getModelByTenant());
1453
-
1454
- // src/redis/functions.ts
1455
- init_getDbByTenant();
1456
-
1457
- // src/redis/index.ts
1458
- import IORedis from "ioredis";
1459
- var redisClient = null;
1460
- var REDIS_CONFIG = {
1461
- port: Number(process.env.REDIS_PORT),
1462
- host: process.env.REDIS_HOST || "",
1463
- username: process.env.REDIS_USERNAME || "",
1464
- password: process.env.REDIS_PASSWORD || ""
1465
- };
1466
- var connectToRedis = async () => {
1467
- try {
1468
- redisClient = new IORedis(REDIS_CONFIG);
1469
- await redisClient.ping();
1470
- console.log("Redis connected successfully");
1471
- } catch (error) {
1472
- console.error(
1473
- "Redis connection failed:",
1474
- error instanceof Error && error.message
1475
- );
1476
- if (redisClient) {
1477
- redisClient.disconnect();
1478
- }
1479
- throw error;
1480
- }
1481
- };
1482
- var getRedisClient = () => {
1483
- if (!redisClient) {
1484
- throw new Error("Redis client not initialized. Call connectToRedis first.");
1485
- }
1486
- return redisClient;
1487
- };
1488
-
1489
- // src/redis/functions.ts
1490
- var findInCache = async ({
1491
- tenant,
1492
- modelName,
1493
- type,
1494
- query = {}
1495
- }) => {
1496
- const key = `${process.env.ENV}:${tenant}:${modelName}:${type}`;
1497
- try {
1498
- const redisClient2 = getRedisClient();
1499
- const value = await redisClient2.get(key);
1500
- if (value) {
1501
- return JSON.parse(value);
1502
- }
1503
- } catch (error) {
1504
- console.warn(
1505
- `redis read failed for key ${key}`,
1506
- error instanceof Error && error.message
1507
- );
1508
- }
1509
- try {
1510
- const collection = getDbByTenant({
1511
- tenant,
1512
- env: process.env.ENV
1513
- }).collection(modelName);
1514
- const value = await collection.findOne(query);
1515
- if (!value) {
1516
- throw new Error(`${type} value not found in ${modelName} for ${tenant}`);
1517
- }
1518
- try {
1519
- const redisClient2 = getRedisClient();
1520
- await redisClient2.set(key, JSON.stringify(value));
1521
- } catch (error) {
1522
- console.warn(
1523
- `redis write failed for key ${key}:`,
1524
- error instanceof Error && error.message
1525
- );
1526
- }
1527
- return value;
1528
- } catch (error) {
1529
- throw new Error(
1530
- `db read failed: ${error instanceof Error && error.message}`
1531
- );
1532
- }
1533
- };
1534
- var getTpl = async ({ name, tenant }) => {
1535
- if (!name || !tenant) {
1536
- throw new Error("Missing required parameters: name or tenant");
1537
- }
1538
- return await findInCache({
1539
- modelName: "tpl",
1540
- type: name,
1541
- tenant,
1542
- query: {
1543
- kp_content_type: name,
1544
- status: { $in: ["published", "editPublished"] }
1545
- }
1546
- });
1547
- };
1548
- var getAIConfigs = async ({
1549
- tenant
1550
- }) => {
1551
- if (!tenant) {
1552
- throw new Error("Missing required parameter: tenant");
1553
- }
1554
- return await findInCache({
1555
- modelName: "platformConfigs",
1556
- type: "ai",
1557
- tenant,
1558
- query: {
1559
- type: "ai"
1560
- }
1561
- });
1562
- };
1563
-
1564
- // src/node.ts
1915
+ var import_getModelByTenant2 = __toESM(require_getModelByTenant());
1565
1916
  init_models();
1566
1917
  var import_WorkerManager = __toESM(require_WorkerManager());
1918
+ var import_ProducerManager = __toESM(require_ProducerManager());
1567
1919
  var import_BaseProducer = __toESM(require_BaseProducer());
1568
1920
  var import_BaseWorker = __toESM(require_BaseWorker());
1569
1921
  var import_GET_GLOBAL_BULLMQ_CONFIG = __toESM(require_GET_GLOBAL_BULLMQ_CONFIG());
@@ -1572,12 +1924,13 @@ var export_BaseWorker = import_BaseWorker.BaseWorker;
1572
1924
  var export_ElasticSearchConnector = import_ElasticSearchConnector.ElasticSearchConnector;
1573
1925
  var export_GET_GLOBAL_BULLMQ_CONFIG = import_GET_GLOBAL_BULLMQ_CONFIG.GET_GLOBAL_BULLMQ_CONFIG;
1574
1926
  var export_MongoConnector = import_MongoConnector2.MongoConnector;
1927
+ var export_ProducerManager = import_ProducerManager.ProducerManager;
1575
1928
  var export_WorkerManager = import_WorkerManager.WorkerManager;
1576
- var export_getAIChatModelByTenant = import_getModelByTenant.getAIChatModelByTenant;
1577
- var export_getAnnotationsModelByTenant = import_getModelByTenant.getAnnotationsModelByTenant;
1578
- var export_getModelByTenant = import_getModelByTenant.getModelByTenant;
1579
- var export_getPlatformConfigsModelByTenant = import_getModelByTenant.getPlatformConfigsModelByTenant;
1580
- var export_getTplModelByTenant = import_getModelByTenant.getTplModelByTenant;
1929
+ var export_getAIChatModelByTenant = import_getModelByTenant2.getAIChatModelByTenant;
1930
+ var export_getAnnotationsModelByTenant = import_getModelByTenant2.getAnnotationsModelByTenant;
1931
+ var export_getModelByTenant = import_getModelByTenant2.getModelByTenant;
1932
+ var export_getPlatformConfigsModelByTenant = import_getModelByTenant2.getPlatformConfigsModelByTenant;
1933
+ var export_getTplModelByTenant = import_getModelByTenant2.getTplModelByTenant;
1581
1934
  export {
1582
1935
  AIChat_default as AIChatSchema,
1583
1936
  Annotations_default as AnnotationSchema,
@@ -1587,20 +1940,18 @@ export {
1587
1940
  export_GET_GLOBAL_BULLMQ_CONFIG as GET_GLOBAL_BULLMQ_CONFIG,
1588
1941
  export_MongoConnector as MongoConnector,
1589
1942
  PlatformConfigs_default as PlatformConfigsSchema,
1943
+ export_ProducerManager as ProducerManager,
1944
+ RedisCacheConnector,
1590
1945
  Tpl_default as TplSchema,
1591
1946
  export_WorkerManager as WorkerManager,
1592
- connectToRedis,
1593
1947
  deleteVal,
1594
1948
  extractAllBlocksFromTpl,
1595
1949
  genTagId,
1596
1950
  export_getAIChatModelByTenant as getAIChatModelByTenant,
1597
- getAIConfigs,
1598
1951
  export_getAnnotationsModelByTenant as getAnnotationsModelByTenant,
1599
1952
  getDbByTenant,
1600
1953
  export_getModelByTenant as getModelByTenant,
1601
1954
  export_getPlatformConfigsModelByTenant as getPlatformConfigsModelByTenant,
1602
- getRedisClient,
1603
- getTpl,
1604
1955
  export_getTplModelByTenant as getTplModelByTenant,
1605
1956
  getVal,
1606
1957
  initializeGlobalConfig,