@lyxa.ai/core 1.0.382 → 1.0.384
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/index.js +6 -2
- package/dist/index.js.map +1 -1
- package/dist/libraries/socket/core/socket-redis-connections.d.ts +1 -1
- package/dist/libraries/socket/core/socket-redis-connections.js +12 -13
- package/dist/libraries/socket/core/socket-redis-connections.js.map +1 -1
- package/dist/types/README.md +1 -1
- package/dist/types/package.json +1 -1
- package/package.json +1 -1
- package/dist/libraries/socket-manager/connection.store.d.ts +0 -12
- package/dist/libraries/socket-manager/connection.store.js +0 -57
- package/dist/libraries/socket-manager/connection.store.js.map +0 -1
- package/dist/libraries/socket-manager/index.d.ts +0 -1
- package/dist/libraries/socket-manager/index.js +0 -18
- package/dist/libraries/socket-manager/index.js.map +0 -1
- package/dist/libraries/socket-manager/socket-manager.service.d.ts +0 -22
- package/dist/libraries/socket-manager/socket-manager.service.js +0 -90
- package/dist/libraries/socket-manager/socket-manager.service.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -28,6 +28,7 @@ const settings_1 = require("./libraries/cache/settings");
|
|
|
28
28
|
const fcmService_1 = require("./libraries/firebase/fcmService");
|
|
29
29
|
const bull_mq_service_1 = require("./libraries/bullmq/bull-mq-service");
|
|
30
30
|
const cash_settlement_1 = require("./libraries/cash-settlement");
|
|
31
|
+
const socket_1 = require("./libraries/socket");
|
|
31
32
|
var EnvironmentConfigurationType_2 = require("./libraries/configuration/types/EnvironmentConfigurationType");
|
|
32
33
|
Object.defineProperty(exports, "EnvironmentConfigurationType", { enumerable: true, get: function () { return EnvironmentConfigurationType_2.EnvironmentConfigurationType; } });
|
|
33
34
|
var mongo_2 = require("./libraries/mongo");
|
|
@@ -38,6 +39,7 @@ async function bootstrapCore(options) {
|
|
|
38
39
|
getLibraries().getLogger().logger.info('Successfully bootstrapped lyxa-core.');
|
|
39
40
|
const gracefulShutdown = async () => {
|
|
40
41
|
getLibraries().getLogger().logger.info('Received shutdown signal, shutting down gracefully...');
|
|
42
|
+
await (0, socket_1.disconnectAllEntitiesFromInstance)();
|
|
41
43
|
process.exit();
|
|
42
44
|
};
|
|
43
45
|
process.on('SIGTERM', gracefulShutdown);
|
|
@@ -64,7 +66,9 @@ async function registerLibraries(options) {
|
|
|
64
66
|
typedi_1.Container.set(secrets_1.SecretManagerService, secretInstance);
|
|
65
67
|
const bullMQInstance = new bull_mq_service_1.BullMQService(redisInstance);
|
|
66
68
|
typedi_1.Container.set(bull_mq_service_1.BullMQService, bullMQInstance);
|
|
67
|
-
const mongoUrl = options?.mongoDbUrl
|
|
69
|
+
const mongoUrl = options?.mongoDbUrl
|
|
70
|
+
? options.mongoDbUrl
|
|
71
|
+
: await getLibraries().getSecretsService().getKey('MONGO_URL');
|
|
68
72
|
await mongoose_1.default.connect(mongoUrl, {
|
|
69
73
|
dbName: `lyxa-${options.environment}-${options.tenet}`,
|
|
70
74
|
maxPoolSize: 20,
|
|
@@ -78,7 +82,7 @@ async function registerLibraries(options) {
|
|
|
78
82
|
serverSelectionTimeoutMS: 5000,
|
|
79
83
|
heartbeatFrequencyMS: 10000,
|
|
80
84
|
bufferCommands: false,
|
|
81
|
-
compressors: ['zlib']
|
|
85
|
+
compressors: ['zlib'],
|
|
82
86
|
});
|
|
83
87
|
mongoose_1.default.set('debug', options?.mongooseDebug !== undefined
|
|
84
88
|
? options?.mongooseDebug
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"/","sources":["index.ts"],"names":[],"mappings":";;;;;;AAkCA,sCAyBC;AAED,8CAgHC;AAED,oCAEC;AAhLD,qFAAqF;AACrF,IAAA,0CAAqB,GAAE,CAAC;AAExB,2CAA6C;AAC7C,mCAAmC;AACnC,wDAAgC;AAChC,6DAAuF;AACvF,+GAA4G;AAC5G,+CAAgD;AAChD,6CAAiD;AACjD,6CAAyD;AACzD,iDAA2D;AAC3D,uDAAgE;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AG,CAAC,+BAAkB,EAAE,0BAA0B,CAAC,CAAC;IAC9D,kBAAS,CAAC,GAAG,CAAC,8BAAiB,EAAE,yBAAyB,CAAC,CAAC;IAE5D,OAAO,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC;IAEtC,MAAM,IAAA,oBAAY,EAAC,kFAAkF,CAAC,CAAC;IACvG,MAAM,gBAAgB,GAAG,2CAAoB,CAAC,mBAAmB,EAAE,CAAC;IAEpE,MAAM,oBAAoB,GAAG,IAAI,GAAG,EAAiB,CAAC;IAEtD,KAAK,MAAM,EAAE,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,IAAI,gBAAgB,EAAE,CAAC;QAC3E,IAAI,QAAQ,GAAG,oBAAoB,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;QAC3D,IAAI,CAAC,QAAQ,EAAE,CAAC;YACf,QAAQ,GAAG,kBAAS,CAAC,GAAG,CAAC,iBAAwB,CAAC,CAAC;YACnD,oBAAoB,CAAC,GAAG,CAAC,iBAAiB,EAAE,QAAQ,CAAC,CAAC;QACvD,CAAC;QAED,MAAM,IAAA,wBAAgB,EAAC,OAAO,EAAE,KAAK,EAAC,OAAO,EAAC,EAAE;YAC/C,OAAO,QAAQ,CAAC,UAAU,CAAC,CAAC,OAAO,CAAC,CAAC;QACtC,CAAC,CAAC,CAAC;IACJ,CAAC;AACF,CAAC;AAED,SAAgB,YAAY;IAC3B,OAAO,kBAAS,CAAC,GAAG,CAAC,0BAAc,CAAC,CAAC;AACtC,CAAC","sourcesContent":["// Apply the soft delete plugin globally before any connections or models\nimport { applySoftDeletePlugin } from './libraries/mongo/plugins/soft-delete-plugin';\napplySoftDeletePlugin();\n\nimport { LibraryManager } from './libraries';\nimport { Container } from 'typedi';\nimport mongoose from 'mongoose';\nimport { ConfigurationOptions, ConfigurationService } from './libraries/configuration';\nimport { EnvironmentConfigurationType } from './libraries/configuration/types/EnvironmentConfigurationType';\nimport { LyxaLogger } from './libraries/logger';\nimport { RedisService } from './libraries/redis';\nimport { initGlobalConnection } from './libraries/mongo';\nimport { SecretManagerService } from './libraries/secrets';\nimport { MicroServiceDispatcher } from './libraries/dispatcher';\nimport { TwilioService } from './libraries/twilio';\nimport { FirebaseService } from './libraries/firebase';\nimport { initEventBus, subscribeToEvent } from './libraries/event';\nimport { SubscriptionRegistry } from './libraries/event/registry/SubscriptionRegistry';\nimport { MapService, GoogleMapsService } from './libraries/map';\nimport { CachedSettingsService } from './libraries/cache/settings';\nimport {\n\tFCMService,\n\tFCMServiceForRider,\n\tFCMServiceForShop,\n\tFCMServiceForUser,\n} from './libraries/firebase/fcmService';\nimport { BullMQService } from './libraries/bullmq/bull-mq-service';\nimport { BOBSecrets, BOBService, CashSettlementService } from './libraries/cash-settlement';\nimport { RedisUrlMap } from './utilities/environment/redis-environments';\n\nexport { ConfigurationOptions } from './libraries/configuration';\nexport { EnvironmentConfigurationType } from './libraries/configuration/types/EnvironmentConfigurationType';\nexport { initGlobalConnection } from './libraries/mongo';\n\nexport async function bootstrapCore(options?: ConfigurationOptions) {\n\ttry {\n\t\tawait registerLibraries(options);\n\n\t\tgetLibraries().getLogger().logger.info('Successfully bootstrapped lyxa-core.');\n\n\t\tconst gracefulShutdown = async () => {\n\t\t\tgetLibraries().getLogger().logger.info('Received shutdown signal, shutting down gracefully...');\n\t\t\tprocess.exit();\n\t\t};\n\n\t\tprocess.on('SIGTERM', gracefulShutdown);\n\t\tprocess.on('SIGINT', gracefulShutdown);\n\t\tprocess.on('uncaughtException', err => {\n\t\t\tgetLibraries().getLogger().logger.error('Uncaught exception, shutting down...', err);\n\t\t\tgracefulShutdown();\n\t\t});\n\t\tprocess.on('exit', code => {\n\t\t\tgetLibraries().getLogger().logger.info(`Exiting with code: ${code}`);\n\t\t});\n\n\t\tconsole.log('Created hooks.');\n\t} catch (e) {\n\t\tconsole.error(e);\n\t}\n}\n\nexport async function registerLibraries(options?: ConfigurationOptions) {\n\n\t// Setup configuration.\n\tconst configurationInstance = new ConfigurationService(options);\n\tContainer.set(ConfigurationService, configurationInstance);\n\n\t// Setup redis.\n\tconst redisInstance = new RedisService(configurationInstance.redisURL);\n\tContainer.set(RedisService, redisInstance);\n\n\t// Setup secret\n\tconst secretInstance = new SecretManagerService(configurationInstance, redisInstance);\n\tContainer.set(SecretManagerService, secretInstance);\n\n\t// Setup BullMQ\n\tconst bullMQInstance = new BullMQService(redisInstance);\n\tContainer.set(BullMQService, bullMQInstance);\n\n\tconst mongoUrl = options?.mongoDbUrl ? options.mongoDbUrl : await getLibraries().getSecretsService().getKey('MONGO_URL');\t\n\n\tawait mongoose.connect(mongoUrl!, {\n\t\tdbName: `lyxa-${options!.environment}-${options!.tenet}`,\n\t\tmaxPoolSize: 20,\n\t\tminPoolSize: 4,\n\t\tmaxIdleTimeMS: 30000,\n\t\twaitQueueTimeoutMS: 10000,\n\t\tretryWrites: true,\n\t\tw: 1,\n\t\treadPreference: 'primary',\n \treadConcern: { level: 'local' },\n\t\tserverSelectionTimeoutMS: 5000,\n\t\theartbeatFrequencyMS: 10000,\n\t\tbufferCommands: false,\n\t\tcompressors: ['zlib'] // Reduces network traffic\n\t});\n\tmongoose.set(\n\t\t'debug',\n\t\toptions?.mongooseDebug !== undefined\n\t\t\t? options?.mongooseDebug\n\t\t\t: getLibraries().getConfigurationService().options.environment == EnvironmentConfigurationType.DEV\n\t);\n\n\tawait initGlobalConnection(mongoUrl!, options!.environment);\n\n\t// Setup logger\n\tconst loggerInstance = new LyxaLogger(options!.instanceType!, mongoUrl!);\n\tContainer.set(LyxaLogger, loggerInstance);\n\n\t// Setup firebase\n\tconst firebaseInstance = new FirebaseService(configurationInstance!);\n\tContainer.set(FirebaseService, firebaseInstance);\n\n\t// Setup microservice dispatcher\n\tconst microserviceDispatcherInstance = new MicroServiceDispatcher(secretInstance);\n\tContainer.set(MicroServiceDispatcher, microserviceDispatcherInstance);\n\n\t// Setup twilio\n\tconst twilioServiceInstance = new TwilioService();\n\tContainer.set(TwilioService, twilioServiceInstance);\n\n\t// Setup map service\n\tconst googleMapsKey = await getLibraries().getSecretsService().getKey('GOOGLE_MAPS_API_KEY');\n\tconst googleMapService = new GoogleMapsService(googleMapsKey as string);\n\tconst mapServiceInstance = new MapService(googleMapService);\n\tContainer.set(MapService, mapServiceInstance);\n\n\t// Setup cash settlement service\n\tconst bobUsername = await getLibraries().getSecretsService().getKey('BOB_USER_NAME');\n\tconst bobPassword = await getLibraries().getSecretsService().getKey('BOB_PASSWORD');\n\tconst bobURL = await getLibraries().getSecretsService().getKey('BOB_URL');\n\n\tconst bobService = new BOBService({\n\t\tBOB_USER_NAME: bobUsername,\n\t\tBOB_PASSWORD: bobPassword,\n\t\tBOB_URL: bobURL,\n\t} as BOBSecrets);\n\tconst cashSettlementServiceInstance = new CashSettlementService(bobService);\n\tContainer.set(CashSettlementService, cashSettlementServiceInstance);\n\tContainer.set(BOBService, bobService);\n\n\tconst settingsServiceInstance = new CachedSettingsService(redisInstance);\n\tContainer.set(CachedSettingsService, settingsServiceInstance);\n\n\t// Setup fcm service\n\tconst firebaseService = getLibraries().getFirebaseService();\n\tconst fcmServiceInstance = new FCMService(firebaseService.superApp);\n\tconst fcmServiceInstanceForUser = new FCMService(firebaseService.userApp);\n\tconst fcmServiceInstanceForRider = new FCMService(firebaseService.riderApp);\n\tconst fcmServiceInstanceForShop = new FCMService(firebaseService.shopApp);\n\tContainer.set(FCMService, fcmServiceInstance);\n\tContainer.set(FCMServiceForUser, fcmServiceInstanceForUser);\n\tContainer.set(FCMServiceForRider, fcmServiceInstanceForRider);\n\tContainer.set(FCMServiceForShop, fcmServiceInstanceForShop);\n\n\tconsole.log('Initialized everything');\n\n\tawait initEventBus('amqps://adlvedna:oY_X4qH1AphtB83YNcf9DHMO3UVmX23s@dog.lmq.cloudamqp.com/adlvedna');\n\tconst allSubscriptions = SubscriptionRegistry.getAllSubscriptions();\n\n\tconst instantiatedServices = new Map<Function, any>();\n\n\tfor (const { eventId, targetConstructor, methodName } of allSubscriptions) {\n\t\tlet instance = instantiatedServices.get(targetConstructor);\n\t\tif (!instance) {\n\t\t\tinstance = Container.get(targetConstructor as any);\n\t\t\tinstantiatedServices.set(targetConstructor, instance);\n\t\t}\n\n\t\tawait subscribeToEvent(eventId, async payload => {\n\t\t\treturn instance[methodName](payload);\n\t\t});\n\t}\n}\n\nexport function getLibraries(): LibraryManager {\n\treturn Container.get(LibraryManager);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"/","sources":["index.ts"],"names":[],"mappings":";;;;;;AAmCA,sCA0BC;AAED,8CAiHC;AAED,oCAEC;AAnLD,qFAAqF;AAErF,IAAA,0CAAqB,GAAE,CAAC;AAExB,2CAA6C;AAC7C,mCAAmC;AACnC,wDAAgC;AAChC,6DAAuF;AACvF,+GAA4G;AAC5G,+CAAgD;AAChD,6CAAiD;AACjD,6CAAyD;AACzD,iDAA2D;AAC3D,uDAAgE;AAChE,+CAAmD;AACnD,mDAAuD;AACvD,6CAAmE;AACnE,0FAAuF;AACvF,yCAAgE;AAChE,yDAAmE;AACnE,gEAKyC;AACzC,wEAAmE;AACnE,iEAA4F;AAC5F,+CAAuE;AAGvE,6GAA4G;AAAnG,4IAAA,4BAA4B,OAAA;AACrC,2CAAyD;AAAhD,6GAAA,oBAAoB,OAAA;AAEtB,KAAK,UAAU,aAAa,CAAC,OAA8B;IACjE,IAAI,CAAC;QACJ,MAAM,iBAAiB,CAAC,OAAO,CAAC,CAAC;QAEjC,YAAY,EAAE,CAAC,SAAS,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,sCAAsC,CAAC,CAAC;QAE/E,MAAM,gBAAgB,GAAG,KAAK,IAAI,EAAE;YACnC,YAAY,EAAE,CAAC,SAAS,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,uDAAuD,CAAC,CAAC;YAChG,MAAM,IAAA,0CAAiC,GAAE,CAAC;YAC1C,OAAO,CAAC,IAAI,EAAE,CAAC;QAChB,CAAC,CAAC;QAEF,OAAO,CAAC,E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AAC,GAAG,CAAC,iBAAiB,EAAE,QAAQ,CAAC,CAAC;QACvD,CAAC;QAED,MAAM,IAAA,wBAAgB,EAAC,OAAO,EAAE,KAAK,EAAC,OAAO,EAAC,EAAE;YAC/C,OAAO,QAAQ,CAAC,UAAU,CAAC,CAAC,OAAO,CAAC,CAAC;QACtC,CAAC,CAAC,CAAC;IACJ,CAAC;AACF,CAAC;AAED,SAAgB,YAAY;IAC3B,OAAO,kBAAS,CAAC,GAAG,CAAC,0BAAc,CAAC,CAAC;AACtC,CAAC","sourcesContent":["// Apply the soft delete plugin globally before any connections or models\nimport { applySoftDeletePlugin } from './libraries/mongo/plugins/soft-delete-plugin';\n\napplySoftDeletePlugin();\n\nimport { LibraryManager } from './libraries';\nimport { Container } from 'typedi';\nimport mongoose from 'mongoose';\nimport { ConfigurationOptions, ConfigurationService } from './libraries/configuration';\nimport { EnvironmentConfigurationType } from './libraries/configuration/types/EnvironmentConfigurationType';\nimport { LyxaLogger } from './libraries/logger';\nimport { RedisService } from './libraries/redis';\nimport { initGlobalConnection } from './libraries/mongo';\nimport { SecretManagerService } from './libraries/secrets';\nimport { MicroServiceDispatcher } from './libraries/dispatcher';\nimport { TwilioService } from './libraries/twilio';\nimport { FirebaseService } from './libraries/firebase';\nimport { initEventBus, subscribeToEvent } from './libraries/event';\nimport { SubscriptionRegistry } from './libraries/event/registry/SubscriptionRegistry';\nimport { MapService, GoogleMapsService } from './libraries/map';\nimport { CachedSettingsService } from './libraries/cache/settings';\nimport {\n\tFCMService,\n\tFCMServiceForRider,\n\tFCMServiceForShop,\n\tFCMServiceForUser,\n} from './libraries/firebase/fcmService';\nimport { BullMQService } from './libraries/bullmq/bull-mq-service';\nimport { BOBSecrets, BOBService, CashSettlementService } from './libraries/cash-settlement';\nimport { disconnectAllEntitiesFromInstance } from './libraries/socket';\n\nexport { ConfigurationOptions } from './libraries/configuration';\nexport { EnvironmentConfigurationType } from './libraries/configuration/types/EnvironmentConfigurationType';\nexport { initGlobalConnection } from './libraries/mongo';\n\nexport async function bootstrapCore(options?: ConfigurationOptions) {\n\ttry {\n\t\tawait registerLibraries(options);\n\n\t\tgetLibraries().getLogger().logger.info('Successfully bootstrapped lyxa-core.');\n\n\t\tconst gracefulShutdown = async () => {\n\t\t\tgetLibraries().getLogger().logger.info('Received shutdown signal, shutting down gracefully...');\n\t\t\tawait disconnectAllEntitiesFromInstance();\n\t\t\tprocess.exit();\n\t\t};\n\n\t\tprocess.on('SIGTERM', gracefulShutdown);\n\t\tprocess.on('SIGINT', gracefulShutdown);\n\t\tprocess.on('uncaughtException', err => {\n\t\t\tgetLibraries().getLogger().logger.error('Uncaught exception, shutting down...', err);\n\t\t\tgracefulShutdown();\n\t\t});\n\t\tprocess.on('exit', code => {\n\t\t\tgetLibraries().getLogger().logger.info(`Exiting with code: ${code}`);\n\t\t});\n\n\t\tconsole.log('Created hooks.');\n\t} catch (e) {\n\t\tconsole.error(e);\n\t}\n}\n\nexport async function registerLibraries(options?: ConfigurationOptions) {\n\t// Setup configuration.\n\tconst configurationInstance = new ConfigurationService(options);\n\tContainer.set(ConfigurationService, configurationInstance);\n\n\t// Setup redis.\n\tconst redisInstance = new RedisService(configurationInstance.redisURL);\n\tContainer.set(RedisService, redisInstance);\n\n\t// Setup secret\n\tconst secretInstance = new SecretManagerService(configurationInstance, redisInstance);\n\tContainer.set(SecretManagerService, secretInstance);\n\n\t// Setup BullMQ\n\tconst bullMQInstance = new BullMQService(redisInstance);\n\tContainer.set(BullMQService, bullMQInstance);\n\n\tconst mongoUrl = options?.mongoDbUrl\n\t\t? options.mongoDbUrl\n\t\t: await getLibraries().getSecretsService().getKey('MONGO_URL');\n\n\tawait mongoose.connect(mongoUrl!, {\n\t\tdbName: `lyxa-${options!.environment}-${options!.tenet}`,\n\t\tmaxPoolSize: 20,\n\t\tminPoolSize: 4,\n\t\tmaxIdleTimeMS: 30000,\n\t\twaitQueueTimeoutMS: 10000,\n\t\tretryWrites: true,\n\t\tw: 1,\n\t\treadPreference: 'primary',\n\t\treadConcern: { level: 'local' },\n\t\tserverSelectionTimeoutMS: 5000,\n\t\theartbeatFrequencyMS: 10000,\n\t\tbufferCommands: false,\n\t\tcompressors: ['zlib'], // Reduces network traffic\n\t});\n\tmongoose.set(\n\t\t'debug',\n\t\toptions?.mongooseDebug !== undefined\n\t\t\t? options?.mongooseDebug\n\t\t\t: getLibraries().getConfigurationService().options.environment == EnvironmentConfigurationType.DEV\n\t);\n\n\tawait initGlobalConnection(mongoUrl!, options!.environment);\n\n\t// Setup logger\n\tconst loggerInstance = new LyxaLogger(options!.instanceType!, mongoUrl!);\n\tContainer.set(LyxaLogger, loggerInstance);\n\n\t// Setup firebase\n\tconst firebaseInstance = new FirebaseService(configurationInstance!);\n\tContainer.set(FirebaseService, firebaseInstance);\n\n\t// Setup microservice dispatcher\n\tconst microserviceDispatcherInstance = new MicroServiceDispatcher(secretInstance);\n\tContainer.set(MicroServiceDispatcher, microserviceDispatcherInstance);\n\n\t// Setup twilio\n\tconst twilioServiceInstance = new TwilioService();\n\tContainer.set(TwilioService, twilioServiceInstance);\n\n\t// Setup map service\n\tconst googleMapsKey = await getLibraries().getSecretsService().getKey('GOOGLE_MAPS_API_KEY');\n\tconst googleMapService = new GoogleMapsService(googleMapsKey as string);\n\tconst mapServiceInstance = new MapService(googleMapService);\n\tContainer.set(MapService, mapServiceInstance);\n\n\t// Setup cash settlement service\n\tconst bobUsername = await getLibraries().getSecretsService().getKey('BOB_USER_NAME');\n\tconst bobPassword = await getLibraries().getSecretsService().getKey('BOB_PASSWORD');\n\tconst bobURL = await getLibraries().getSecretsService().getKey('BOB_URL');\n\n\tconst bobService = new BOBService({\n\t\tBOB_USER_NAME: bobUsername,\n\t\tBOB_PASSWORD: bobPassword,\n\t\tBOB_URL: bobURL,\n\t} as BOBSecrets);\n\tconst cashSettlementServiceInstance = new CashSettlementService(bobService);\n\tContainer.set(CashSettlementService, cashSettlementServiceInstance);\n\tContainer.set(BOBService, bobService);\n\n\tconst settingsServiceInstance = new CachedSettingsService(redisInstance);\n\tContainer.set(CachedSettingsService, settingsServiceInstance);\n\n\t// Setup fcm service\n\tconst firebaseService = getLibraries().getFirebaseService();\n\tconst fcmServiceInstance = new FCMService(firebaseService.superApp);\n\tconst fcmServiceInstanceForUser = new FCMService(firebaseService.userApp);\n\tconst fcmServiceInstanceForRider = new FCMService(firebaseService.riderApp);\n\tconst fcmServiceInstanceForShop = new FCMService(firebaseService.shopApp);\n\tContainer.set(FCMService, fcmServiceInstance);\n\tContainer.set(FCMServiceForUser, fcmServiceInstanceForUser);\n\tContainer.set(FCMServiceForRider, fcmServiceInstanceForRider);\n\tContainer.set(FCMServiceForShop, fcmServiceInstanceForShop);\n\n\tconsole.log('Initialized everything');\n\n\tawait initEventBus('amqps://adlvedna:oY_X4qH1AphtB83YNcf9DHMO3UVmX23s@dog.lmq.cloudamqp.com/adlvedna');\n\tconst allSubscriptions = SubscriptionRegistry.getAllSubscriptions();\n\n\tconst instantiatedServices = new Map<Function, any>();\n\n\tfor (const { eventId, targetConstructor, methodName } of allSubscriptions) {\n\t\tlet instance = instantiatedServices.get(targetConstructor);\n\t\tif (!instance) {\n\t\t\tinstance = Container.get(targetConstructor as any);\n\t\t\tinstantiatedServices.set(targetConstructor, instance);\n\t\t}\n\n\t\tawait subscribeToEvent(eventId, async payload => {\n\t\t\treturn instance[methodName](payload);\n\t\t});\n\t}\n}\n\nexport function getLibraries(): LibraryManager {\n\treturn Container.get(LibraryManager);\n}\n"]}
|
|
@@ -9,4 +9,4 @@ export interface SocketRedisEventInformation {
|
|
|
9
9
|
export declare function connectEntityToSocketEvent(entityId: string, socketRedisEventInformation: SocketRedisEventInformation): Promise<void>;
|
|
10
10
|
export declare function disconnectEntityFromSocketEvent(entityId: string, socketRedisEventInformation: SocketRedisEventInformation): Promise<void>;
|
|
11
11
|
export declare function isEntitySubscribed(entityId: string, eventKey: string): Promise<boolean>;
|
|
12
|
-
export declare function disconnectAllEntitiesFromInstance(
|
|
12
|
+
export declare function disconnectAllEntitiesFromInstance(): Promise<void>;
|
|
@@ -6,6 +6,7 @@ exports.disconnectEntityFromSocketEvent = disconnectEntityFromSocketEvent;
|
|
|
6
6
|
exports.isEntitySubscribed = isEntitySubscribed;
|
|
7
7
|
exports.disconnectAllEntitiesFromInstance = disconnectAllEntitiesFromInstance;
|
|
8
8
|
const __1 = require("../../..");
|
|
9
|
+
const instance_utils_1 = require("../../../utilities/instance.utils");
|
|
9
10
|
const kEntityEvents = (entityId) => `socket:events:entity:${entityId}`;
|
|
10
11
|
exports.kEntityEvents = kEntityEvents;
|
|
11
12
|
const kEntityInstances = (entityId) => `socket:instances:entity:${entityId}`;
|
|
@@ -34,27 +35,25 @@ async function isEntitySubscribed(entityId, eventKey) {
|
|
|
34
35
|
const events = await redis.getSetMembers((0, exports.kEntityEvents)(entityId));
|
|
35
36
|
return events.map(e => JSON.parse(e)).some(e => e.eventKey === eventKey);
|
|
36
37
|
}
|
|
37
|
-
async function disconnectAllEntitiesFromInstance(
|
|
38
|
+
async function disconnectAllEntitiesFromInstance() {
|
|
39
|
+
const instanceId = (0, instance_utils_1.getInstanceId)();
|
|
38
40
|
const redis = (0, __1.getLibraries)().getRedisService();
|
|
39
41
|
const connectedEntities = await redis.getSetMembers((0, exports.kEntityConnection)());
|
|
40
|
-
if (connectedEntities.length
|
|
42
|
+
if (!connectedEntities.length)
|
|
41
43
|
return;
|
|
42
44
|
for (const entityId of connectedEntities) {
|
|
43
45
|
const allEvents = await redis.getSetMembers((0, exports.kEntityEvents)(entityId));
|
|
44
|
-
if (allEvents.length
|
|
46
|
+
if (!allEvents.length)
|
|
45
47
|
continue;
|
|
46
|
-
const eventsToKeep =
|
|
47
|
-
for (const e of allEvents) {
|
|
48
|
+
const eventsToKeep = allEvents.filter(e => {
|
|
48
49
|
const parsed = JSON.parse(e);
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
}
|
|
50
|
+
return parsed.instanceId !== instanceId;
|
|
51
|
+
});
|
|
52
|
+
const eventsToRemove = allEvents.filter(e => !eventsToKeep.includes(e));
|
|
53
|
+
for (const e of eventsToRemove) {
|
|
54
|
+
await redis.removeFromSet((0, exports.kEntityEvents)(entityId), e);
|
|
55
55
|
}
|
|
56
|
-
|
|
57
|
-
if (!stillOnInstance) {
|
|
56
|
+
if (!eventsToKeep.some(e => JSON.parse(e).instanceId === instanceId)) {
|
|
58
57
|
await redis.removeFromSet((0, exports.kEntityInstances)(entityId), instanceId);
|
|
59
58
|
}
|
|
60
59
|
if (eventsToKeep.length === 0) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"socket-redis-connections.js","sourceRoot":"/","sources":["libraries/socket/core/socket-redis-connections.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"socket-redis-connections.js","sourceRoot":"/","sources":["libraries/socket/core/socket-redis-connections.ts"],"names":[],"mappings":";;;AAaA,gEASC;AAED,0EAmBC;AAED,gDAIC;AAED,8EA6BC;AAhFD,gCAAwC;AACxC,sEAAkE;AAE3D,MAAM,aAAa,GAAG,CAAC,QAAgB,EAAE,EAAE,CAAC,wBAAwB,QAAQ,EAAE,CAAC;AAAzE,QAAA,aAAa,iBAA4D;AAC/E,MAAM,gBAAgB,GAAG,CAAC,QAAgB,EAAE,EAAE,CAAC,2BAA2B,QAAQ,EAAE,CAAC;AAA/E,QAAA,gBAAgB,oBAA+D;AACrF,MAAM,iBAAiB,GAAG,GAAG,EAAE,CAAC,oBAAoB,CAAC;AAA/C,QAAA,iBAAiB,qBAA8B;AAQrD,KAAK,UAAU,0BAA0B,CAC/C,QAAgB,EAChB,2BAAwD;IAExD,MAAM,KAAK,GAAG,IAAA,gBAAY,GAAE,CAAC,eAAe,EAAE,CAAC;IAE/C,MAAM,KAAK,CAAC,QAAQ,CAAC,IAAA,qBAAa,EAAC,QAAQ,CAAC,EAAE,IAAI,CAAC,SAAS,CAAC,2BAA2B,CAAC,CAAC,CA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AC;QACvD,CAAC;QAED,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAiC,CAAC,UAAU,KAAK,UAAU,CAAC,EAAE,CAAC;YACvG,MAAM,KAAK,CAAC,aAAa,CAAC,IAAA,wBAAgB,EAAC,QAAQ,CAAC,EAAE,UAAU,CAAC,CAAC;QACnE,CAAC;QAED,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC/B,MAAM,KAAK,CAAC,aAAa,CAAC,IAAA,yBAAiB,GAAE,EAAE,QAAQ,CAAC,CAAC;QAC1D,CAAC;IACF,CAAC;AACF,CAAC","sourcesContent":["import { getLibraries } from '../../..';\nimport { getInstanceId } from '../../../utilities/instance.utils';\n\nexport const kEntityEvents = (entityId: string) => `socket:events:entity:${entityId}`;\nexport const kEntityInstances = (entityId: string) => `socket:instances:entity:${entityId}`;\nexport const kEntityConnection = () => `socket:connections`;\n\nexport interface SocketRedisEventInformation {\n\teventKey: string;\n\tinstanceId: string;\n\tsocketId: string;\n}\n\nexport async function connectEntityToSocketEvent(\n\tentityId: string,\n\tsocketRedisEventInformation: SocketRedisEventInformation\n) {\n\tconst redis = getLibraries().getRedisService();\n\n\tawait redis.addToSet(kEntityEvents(entityId), JSON.stringify(socketRedisEventInformation));\n\tawait redis.addToSet(kEntityInstances(entityId), socketRedisEventInformation.instanceId);\n\tawait redis.addToSet(kEntityConnection(), entityId);\n}\n\nexport async function disconnectEntityFromSocketEvent(\n\tentityId: string,\n\tsocketRedisEventInformation: SocketRedisEventInformation\n) {\n\tconst redis = getLibraries().getRedisService();\n\n\tawait redis.removeFromSet(kEntityEvents(entityId), JSON.stringify(socketRedisEventInformation));\n\n\tconst remainingEvents = (await redis.getSetMembers(kEntityEvents(entityId))).map(\n\t\tr => JSON.parse(r) as SocketRedisEventInformation\n\t);\n\n\tif (remainingEvents.filter(e => e.instanceId === socketRedisEventInformation.instanceId).length === 0) {\n\t\tawait redis.removeFromSet(kEntityInstances(entityId), socketRedisEventInformation.instanceId);\n\t}\n\n\tif (remainingEvents.length === 0) {\n\t\tawait redis.removeFromSet(kEntityConnection(), entityId);\n\t}\n}\n\nexport async function isEntitySubscribed(entityId: string, eventKey: string): Promise<boolean> {\n\tconst redis = getLibraries().getRedisService();\n\tconst events = await redis.getSetMembers(kEntityEvents(entityId));\n\treturn events.map(e => JSON.parse(e) as SocketRedisEventInformation).some(e => e.eventKey === eventKey);\n}\n\nexport async function disconnectAllEntitiesFromInstance() {\n\tconst instanceId = getInstanceId();\n\tconst redis = getLibraries().getRedisService();\n\n\tconst connectedEntities = await redis.getSetMembers(kEntityConnection());\n\tif (!connectedEntities.length) return;\n\n\tfor (const entityId of connectedEntities) {\n\t\tconst allEvents = await redis.getSetMembers(kEntityEvents(entityId));\n\t\tif (!allEvents.length) continue;\n\n\t\tconst eventsToKeep = allEvents.filter(e => {\n\t\t\tconst parsed = JSON.parse(e) as SocketRedisEventInformation;\n\t\t\treturn parsed.instanceId !== instanceId;\n\t\t});\n\n\t\tconst eventsToRemove = allEvents.filter(e => !eventsToKeep.includes(e));\n\t\tfor (const e of eventsToRemove) {\n\t\t\tawait redis.removeFromSet(kEntityEvents(entityId), e);\n\t\t}\n\n\t\tif (!eventsToKeep.some(e => (JSON.parse(e) as SocketRedisEventInformation).instanceId === instanceId)) {\n\t\t\tawait redis.removeFromSet(kEntityInstances(entityId), instanceId);\n\t\t}\n\n\t\tif (eventsToKeep.length === 0) {\n\t\t\tawait redis.removeFromSet(kEntityConnection(), entityId);\n\t\t}\n\t}\n}\n"]}
|
package/dist/types/README.md
CHANGED
package/dist/types/package.json
CHANGED
package/package.json
CHANGED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import { ConnectionInfo } from '../../utilities/connection.types';
|
|
2
|
-
export declare class ConnectionStore {
|
|
3
|
-
private connections;
|
|
4
|
-
private entityConnections;
|
|
5
|
-
add(contextId: string, info: ConnectionInfo): void;
|
|
6
|
-
remove(contextId: string): void;
|
|
7
|
-
getByContext(contextId: string): ConnectionInfo | undefined;
|
|
8
|
-
getContextsByClientId(clientIdStr: string): string[];
|
|
9
|
-
getAll(): Map<string, ConnectionInfo>;
|
|
10
|
-
clear(): void;
|
|
11
|
-
}
|
|
12
|
-
export declare const connectionStore: ConnectionStore;
|
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
-
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
-
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
-
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
-
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
-
};
|
|
8
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
-
exports.connectionStore = exports.ConnectionStore = void 0;
|
|
10
|
-
const typedi_1 = require("typedi");
|
|
11
|
-
let ConnectionStore = class ConnectionStore {
|
|
12
|
-
connections = new Map();
|
|
13
|
-
entityConnections = new Map();
|
|
14
|
-
add(contextId, info) {
|
|
15
|
-
this.connections.set(contextId, info);
|
|
16
|
-
const clientId = info.clientId.toString();
|
|
17
|
-
if (!this.entityConnections.has(clientId)) {
|
|
18
|
-
this.entityConnections.set(clientId, []);
|
|
19
|
-
}
|
|
20
|
-
const contexts = this.entityConnections.get(clientId);
|
|
21
|
-
if (!contexts.includes(contextId))
|
|
22
|
-
contexts.push(contextId);
|
|
23
|
-
}
|
|
24
|
-
remove(contextId) {
|
|
25
|
-
const info = this.connections.get(contextId);
|
|
26
|
-
if (!info)
|
|
27
|
-
return;
|
|
28
|
-
const clientId = info.clientId.toString();
|
|
29
|
-
this.connections.delete(contextId);
|
|
30
|
-
const updated = (this.entityConnections.get(clientId) || []).filter(id => id !== contextId);
|
|
31
|
-
if (updated.length === 0) {
|
|
32
|
-
this.entityConnections.delete(clientId);
|
|
33
|
-
}
|
|
34
|
-
else {
|
|
35
|
-
this.entityConnections.set(clientId, updated);
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
getByContext(contextId) {
|
|
39
|
-
return this.connections.get(contextId);
|
|
40
|
-
}
|
|
41
|
-
getContextsByClientId(clientIdStr) {
|
|
42
|
-
return this.entityConnections.get(clientIdStr) || [];
|
|
43
|
-
}
|
|
44
|
-
getAll() {
|
|
45
|
-
return new Map(this.connections);
|
|
46
|
-
}
|
|
47
|
-
clear() {
|
|
48
|
-
this.connections.clear();
|
|
49
|
-
this.entityConnections.clear();
|
|
50
|
-
}
|
|
51
|
-
};
|
|
52
|
-
exports.ConnectionStore = ConnectionStore;
|
|
53
|
-
exports.ConnectionStore = ConnectionStore = __decorate([
|
|
54
|
-
(0, typedi_1.Service)()
|
|
55
|
-
], ConnectionStore);
|
|
56
|
-
exports.connectionStore = typedi_1.Container.get(ConnectionStore);
|
|
57
|
-
//# sourceMappingURL=connection.store.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"connection.store.js","sourceRoot":"/","sources":["libraries/socket-manager/connection.store.ts"],"names":[],"mappings":";;;;;;;;;AAAA,mCAA4C;AAIrC,IAAM,eAAe,GAArB,MAAM,eAAe;IACnB,WAAW,GAAgC,IAAI,GAAG,EAAE,CAAC;IACrD,iBAAiB,GAA0B,IAAI,GAAG,EAAE,CAAC;IAE7D,GAAG,CAAC,SAAiB,EAAE,IAAoB;QAC1C,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;QAEtC,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,CAAC;QAC1C,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,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CAAC;IAED,MAAM;QACL,OAAO,IAAI,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IAClC,CAAC;IAED,KAAK;QACJ,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC;QACzB,IAAI,CAAC,iBAAiB,CAAC,KAAK,EAAE,CAAC;IAChC,CAAC;CACD,CAAA;AA/CY,0CAAe;0BAAf,eAAe;IAD3B,IAAA,gBAAO,GAAE;GACG,eAAe,CA+C3B;AAEY,QAAA,eAAe,GAAG,kBAAS,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC","sourcesContent":["import { Service, Container } from 'typedi';\nimport { ConnectionInfo } from '../../utilities/connection.types';\n\n@Service()\nexport class ConnectionStore {\n\tprivate connections: Map<string, ConnectionInfo> = new Map();\n\tprivate entityConnections: Map<string, string[]> = new Map();\n\n\tadd(contextId: string, info: ConnectionInfo) {\n\t\tthis.connections.set(contextId, info);\n\n\t\tconst clientId = info.clientId.toString();\n\t\tif (!this.entityConnections.has(clientId)) {\n\t\t\tthis.entityConnections.set(clientId, []);\n\t\t}\n\n\t\tconst contexts = this.entityConnections.get(clientId)!;\n\t\tif (!contexts.includes(contextId)) contexts.push(contextId);\n\t}\n\n\tremove(contextId: string): void {\n\t\tconst info = this.connections.get(contextId);\n\t\tif (!info) return;\n\n\t\tconst clientId = info.clientId.toString();\n\t\tthis.connections.delete(contextId);\n\n\t\tconst updated = (this.entityConnections.get(clientId) || []).filter(id => id !== contextId);\n\t\tif (updated.length === 0) {\n\t\t\tthis.entityConnections.delete(clientId);\n\t\t} else {\n\t\t\tthis.entityConnections.set(clientId, updated);\n\t\t}\n\t}\n\n\tgetByContext(contextId: string): ConnectionInfo | undefined {\n\t\treturn this.connections.get(contextId);\n\t}\n\n\tgetContextsByClientId(clientIdStr: string): string[] {\n\t\treturn this.entityConnections.get(clientIdStr) || [];\n\t}\n\n\tgetAll(): Map<string, ConnectionInfo> {\n\t\treturn new Map(this.connections);\n\t}\n\n\tclear(): void {\n\t\tthis.connections.clear();\n\t\tthis.entityConnections.clear();\n\t}\n}\n\nexport const connectionStore = Container.get(ConnectionStore);\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * from './socket-manager.service';
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
-
if (k2 === undefined) k2 = k;
|
|
4
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
-
}
|
|
8
|
-
Object.defineProperty(o, k2, desc);
|
|
9
|
-
}) : (function(o, m, k, k2) {
|
|
10
|
-
if (k2 === undefined) k2 = k;
|
|
11
|
-
o[k2] = m[k];
|
|
12
|
-
}));
|
|
13
|
-
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
-
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
-
};
|
|
16
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
__exportStar(require("./socket-manager.service"), exports);
|
|
18
|
-
//# sourceMappingURL=index.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"/","sources":["libraries/socket-manager/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,2DAAyC","sourcesContent":["export * from './socket-manager.service';\n"]}
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import { mongoose } from '@typegoose/typegoose';
|
|
2
|
-
import { UserRef } from '../../utilities/enum';
|
|
3
|
-
import { ConnectionInfo } from '../../utilities/connection.types';
|
|
4
|
-
import { Observer } from '@trpc/server/observable';
|
|
5
|
-
export declare class SocketManager {
|
|
6
|
-
private readonly store;
|
|
7
|
-
private readonly instanceId;
|
|
8
|
-
constructor();
|
|
9
|
-
subscribeUser(userId: mongoose.Types.ObjectId, userType: UserRef, emit: Observer<unknown, unknown>): {
|
|
10
|
-
cleanup: () => void;
|
|
11
|
-
};
|
|
12
|
-
private addConnection;
|
|
13
|
-
private removeConnection;
|
|
14
|
-
sendToClient(clientIds: mongoose.Types.ObjectId[], event: string, data: any): Promise<{
|
|
15
|
-
successCount: number;
|
|
16
|
-
failedClientIds: string[];
|
|
17
|
-
}>;
|
|
18
|
-
getAllConnections(): Map<string, ConnectionInfo>;
|
|
19
|
-
getInstanceId(): string;
|
|
20
|
-
cleanup(): Promise<void>;
|
|
21
|
-
}
|
|
22
|
-
export declare const socketManager: SocketManager;
|
|
@@ -1,90 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
-
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
-
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
-
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
-
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
-
};
|
|
8
|
-
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
-
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
-
};
|
|
11
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
-
exports.socketManager = exports.SocketManager = void 0;
|
|
13
|
-
const typedi_1 = require("typedi");
|
|
14
|
-
const connection_store_1 = require("./connection.store");
|
|
15
|
-
let SocketManager = class SocketManager {
|
|
16
|
-
store;
|
|
17
|
-
instanceId = `instance-${process.pid}-${Date.now()}`;
|
|
18
|
-
constructor() {
|
|
19
|
-
this.store = connection_store_1.connectionStore;
|
|
20
|
-
}
|
|
21
|
-
subscribeUser(userId, userType, emit) {
|
|
22
|
-
const contextId = `${userId}-${Date.now()}-${Math.random()}`;
|
|
23
|
-
this.addConnection(contextId, userId, userType, emit.next.bind(emit));
|
|
24
|
-
return {
|
|
25
|
-
cleanup: () => {
|
|
26
|
-
this.removeConnection(contextId);
|
|
27
|
-
},
|
|
28
|
-
};
|
|
29
|
-
}
|
|
30
|
-
addConnection(contextId, clientId, entityType, emitter) {
|
|
31
|
-
this.store.remove(contextId);
|
|
32
|
-
this.store.add(contextId, {
|
|
33
|
-
clientId,
|
|
34
|
-
entityType,
|
|
35
|
-
emitter,
|
|
36
|
-
connectedAt: new Date(),
|
|
37
|
-
instanceId: this.instanceId,
|
|
38
|
-
});
|
|
39
|
-
}
|
|
40
|
-
removeConnection(contextId) {
|
|
41
|
-
this.store.remove(contextId);
|
|
42
|
-
}
|
|
43
|
-
async sendToClient(clientIds, event, data) {
|
|
44
|
-
let successCount = 0;
|
|
45
|
-
const failedClientIds = [];
|
|
46
|
-
const message = {
|
|
47
|
-
type: event,
|
|
48
|
-
data,
|
|
49
|
-
timestamp: new Date().toISOString(),
|
|
50
|
-
};
|
|
51
|
-
for (const clientId of clientIds) {
|
|
52
|
-
const clientIdStr = clientId.toString();
|
|
53
|
-
const contexts = this.store.getContextsByClientId(clientIdStr);
|
|
54
|
-
let sent = false;
|
|
55
|
-
for (const ctx of contexts) {
|
|
56
|
-
const connection = this.store.getByContext(ctx);
|
|
57
|
-
if (connection && typeof connection.emitter === 'function') {
|
|
58
|
-
try {
|
|
59
|
-
connection.emitter(message);
|
|
60
|
-
sent = true;
|
|
61
|
-
}
|
|
62
|
-
catch {
|
|
63
|
-
this.store.remove(ctx);
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
if (sent)
|
|
68
|
-
successCount++;
|
|
69
|
-
else
|
|
70
|
-
failedClientIds.push(clientIdStr);
|
|
71
|
-
}
|
|
72
|
-
return { successCount, failedClientIds };
|
|
73
|
-
}
|
|
74
|
-
getAllConnections() {
|
|
75
|
-
return this.store.getAll();
|
|
76
|
-
}
|
|
77
|
-
getInstanceId() {
|
|
78
|
-
return this.instanceId;
|
|
79
|
-
}
|
|
80
|
-
async cleanup() {
|
|
81
|
-
this.store.clear();
|
|
82
|
-
}
|
|
83
|
-
};
|
|
84
|
-
exports.SocketManager = SocketManager;
|
|
85
|
-
exports.SocketManager = SocketManager = __decorate([
|
|
86
|
-
(0, typedi_1.Service)(),
|
|
87
|
-
__metadata("design:paramtypes", [])
|
|
88
|
-
], SocketManager);
|
|
89
|
-
exports.socketManager = typedi_1.Container.get(SocketManager);
|
|
90
|
-
//# sourceMappingURL=socket-manager.service.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"socket-manager.service.js","sourceRoot":"/","sources":["libraries/socket-manager/socket-manager.service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,mCAA4C;AAC5C,yDAAsE;AAO/D,IAAM,aAAa,GAAnB,MAAM,aAAa;IACR,KAAK,CAAkB;IACvB,UAAU,GAAG,YAAY,OAAO,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC;IAEtE;QACC,IAAI,CAAC,KAAK,GAAG,kCAAe,CAAC;IAC9B,CAAC;IAEM,aAAa,CACnB,MAA+B,EAC/B,QAAiB,EACjB,IAAgC;QAEhC,MAAM,SAAS,GAAG,GAAG,MAAM,IAAI,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,EAAE,CAAC;QAC7D,IAAI,CAAC,aAAa,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;QAEtE,OAAO;YACN,OAAO,EAAE,GAAG,EAAE;gBACb,IAAI,CAAC,gBAAgB,CAAC,SAAS,CAAC,CAAC;YAClC,C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oBACb,CAAC;oBAAC,MAAM,CAAC;wBACR,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;oBACxB,CAAC;gBACF,CAAC;YACF,CAAC;YAED,IAAI,IAAI;gBAAE,YAAY,EAAE,CAAC;;gBACpB,eAAe,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACxC,CAAC;QAED,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,CAAC;IAC1C,CAAC;IAEM,iBAAiB;QACvB,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC;IAC5B,CAAC;IAEM,aAAa;QACnB,OAAO,IAAI,CAAC,UAAU,CAAC;IACxB,CAAC;IAEM,KAAK,CAAC,OAAO;QACnB,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;IACpB,CAAC;CACD,CAAA;AA5FY,sCAAa;wBAAb,aAAa;IADzB,IAAA,gBAAO,GAAE;;GACG,aAAa,CA4FzB;AAEY,QAAA,aAAa,GAAG,kBAAS,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC","sourcesContent":["import { Service, Container } from 'typedi';\nimport { ConnectionStore, connectionStore } from './connection.store';\nimport { mongoose } from '@typegoose/typegoose';\nimport { UserRef } from '../../utilities/enum';\nimport { ConnectionInfo } from '../../utilities/connection.types';\nimport { Observer } from '@trpc/server/observable';\n\n@Service()\nexport class SocketManager {\n\tprivate readonly store: ConnectionStore;\n\tprivate readonly instanceId = `instance-${process.pid}-${Date.now()}`;\n\n\tconstructor() {\n\t\tthis.store = connectionStore;\n\t}\n\n\tpublic subscribeUser(\n\t\tuserId: mongoose.Types.ObjectId,\n\t\tuserType: UserRef,\n\t\temit: Observer<unknown, unknown>\n\t): { cleanup: () => void } {\n\t\tconst contextId = `${userId}-${Date.now()}-${Math.random()}`;\n\t\tthis.addConnection(contextId, userId, userType, emit.next.bind(emit));\n\n\t\treturn {\n\t\t\tcleanup: () => {\n\t\t\t\tthis.removeConnection(contextId);\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate addConnection(\n\t\tcontextId: string,\n\t\tclientId: mongoose.Types.ObjectId,\n\t\tentityType: UserRef,\n\t\temitter: (data: any) => void\n\t): void {\n\t\tthis.store.remove(contextId);\n\t\tthis.store.add(contextId, {\n\t\t\tclientId,\n\t\t\tentityType,\n\t\t\temitter,\n\t\t\tconnectedAt: new Date(),\n\t\t\tinstanceId: this.instanceId,\n\t\t});\n\t}\n\n\tprivate removeConnection(contextId: string): void {\n\t\tthis.store.remove(contextId);\n\t}\n\n\tpublic async sendToClient(\n\t\tclientIds: mongoose.Types.ObjectId[],\n\t\tevent: string,\n\t\tdata: any\n\t): Promise<{ successCount: number; failedClientIds: string[] }> {\n\t\tlet successCount = 0;\n\t\tconst failedClientIds: string[] = [];\n\n\t\tconst message = {\n\t\t\ttype: event,\n\t\t\tdata,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t};\n\n\t\tfor (const clientId of clientIds) {\n\t\t\tconst clientIdStr = clientId.toString();\n\t\t\tconst contexts = this.store.getContextsByClientId(clientIdStr);\n\n\t\t\tlet sent = false;\n\t\t\tfor (const ctx of contexts) {\n\t\t\t\tconst connection = this.store.getByContext(ctx);\n\t\t\t\tif (connection && typeof connection.emitter === 'function') {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconnection.emitter(message);\n\t\t\t\t\t\tsent = true;\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tthis.store.remove(ctx);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (sent) successCount++;\n\t\t\telse failedClientIds.push(clientIdStr);\n\t\t}\n\n\t\treturn { successCount, failedClientIds };\n\t}\n\n\tpublic getAllConnections(): Map<string, ConnectionInfo> {\n\t\treturn this.store.getAll();\n\t}\n\n\tpublic getInstanceId(): string {\n\t\treturn this.instanceId;\n\t}\n\n\tpublic async cleanup(): Promise<void> {\n\t\tthis.store.clear();\n\t}\n}\n\nexport const socketManager = Container.get(SocketManager);\n"]}
|