EventsModule.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. import {
  2. createClient,
  3. RedisClientOptions,
  4. RedisClientType,
  5. RedisDefaultModules,
  6. RedisFunctions,
  7. RedisModules,
  8. RedisScripts
  9. } from "redis";
  10. import config from "config";
  11. import { forEachIn } from "@common/utils/forEachIn";
  12. import BaseModule, { ModuleStatus } from "@/BaseModule";
  13. import WebSocketModule from "./WebSocketModule";
  14. import Event from "@/modules/EventsModule/Event";
  15. import ModuleManager from "@/ModuleManager";
  16. import DataModule from "@/modules/DataModule";
  17. import { GetPermissionsResult } from "@/modules/DataModule/models/users/jobs/GetPermissions";
  18. import { GetSingleModelPermissionsResult } from "@/modules/DataModule/models/users/jobs/GetModelPermissions";
  19. import JobContext from "@/JobContext";
  20. const permissionRegex =
  21. // eslint-disable-next-line max-len
  22. /^event.(?<moduleName>[a-z]+)\.(?<modelOrEventName>[A-z]+)\.(?<eventName>[A-z]+)(?::(?:(?<modelId>[A-z0-9]{24})(?:\.(?<extraAfterModelId>[A-z]+))?|(?<extraAfterColon>[A-z]+)))?$/;
  23. export class EventsModule extends BaseModule {
  24. /**
  25. * The events module is used to subscribe to events, and to publish events. Events can be documents updating, being created or being deleted.
  26. * Other events can be JobFinished? But probably not for frontend. So atm frontend can only subscribe to update/created/deleted.
  27. */
  28. private _pubClient?: RedisClientType<
  29. RedisDefaultModules & RedisModules,
  30. RedisFunctions,
  31. RedisScripts
  32. >;
  33. private _subClient?: RedisClientType<
  34. RedisDefaultModules & RedisModules,
  35. RedisFunctions,
  36. RedisScripts
  37. >;
  38. private _subscriptions: Record<string, ((message: any) => Promise<void>)[]>;
  39. private _pSubscriptions: Record<
  40. string,
  41. ((event: Event) => Promise<void>)[]
  42. >;
  43. private _socketSubscriptions: Record<string, Set<string>>;
  44. private _scheduleCallbacks: Record<string, (() => Promise<void>)[]>;
  45. /**
  46. * Events Module
  47. */
  48. public constructor() {
  49. super("events");
  50. this._subscriptions = {};
  51. this._pSubscriptions = {};
  52. this._socketSubscriptions = {};
  53. this._scheduleCallbacks = {};
  54. }
  55. /**
  56. * startup - Startup events module
  57. */
  58. public override async startup() {
  59. await super.startup();
  60. await this._createPubClient();
  61. await this._createSubClient();
  62. await super._started();
  63. }
  64. /**
  65. * createPubClient - Create redis client for publishing
  66. */
  67. private async _createPubClient() {
  68. this._pubClient = createClient({
  69. ...config.get<RedisClientOptions>("redis"),
  70. socket: {
  71. reconnectStrategy: (retries: number, error) => {
  72. if (
  73. retries >= 10 ||
  74. ![ModuleStatus.STARTING, ModuleStatus.STARTED].includes(
  75. this.getStatus()
  76. )
  77. )
  78. return false;
  79. this.log({
  80. type: "debug",
  81. message: `Redis reconnect attempt ${retries}`,
  82. data: error
  83. });
  84. return Math.min(retries * 50, 500);
  85. }
  86. }
  87. });
  88. this._pubClient.on("error", error => {
  89. this.log({ type: "error", message: error.message, data: error });
  90. this.setStatus(ModuleStatus.ERROR);
  91. });
  92. this._pubClient.on("ready", () => {
  93. this.log({ type: "debug", message: "Redis connection ready" });
  94. if (this.getStatus() === ModuleStatus.ERROR)
  95. this.setStatus(ModuleStatus.STARTED);
  96. });
  97. await this._pubClient.connect();
  98. const redisConfigResponse = await this._pubClient.sendCommand([
  99. "CONFIG",
  100. "GET",
  101. "notify-keyspace-events"
  102. ]);
  103. if (
  104. !(
  105. Array.isArray(redisConfigResponse) &&
  106. redisConfigResponse[1] === "xE"
  107. )
  108. )
  109. throw new Error(
  110. `notify-keyspace-events is NOT configured correctly! It is set to: ${
  111. (Array.isArray(redisConfigResponse) &&
  112. redisConfigResponse[1]) ||
  113. "unknown"
  114. }`
  115. );
  116. }
  117. /**
  118. * createSubClient - Create redis client for subscribing
  119. */
  120. private async _createSubClient() {
  121. if (!this._pubClient) throw new Error("Redis pubClient unavailable.");
  122. this._subClient = this._pubClient?.duplicate();
  123. this._subClient.on("error", error => {
  124. this.log({ type: "error", message: error.message, data: error });
  125. this.setStatus(ModuleStatus.ERROR);
  126. });
  127. this._subClient.on("ready", () => {
  128. this.log({ type: "debug", message: "Redis connection ready" });
  129. if (this.getStatus() === ModuleStatus.ERROR)
  130. this.setStatus(ModuleStatus.STARTED);
  131. });
  132. await this._subClient.connect();
  133. const { database = 0 } = this._subClient.options ?? {};
  134. await this._subClient.pSubscribe("event.*", async (...args) =>
  135. this._subscriptionListener(...args)
  136. );
  137. await this._subClient.pSubscribe(
  138. `__keyevent@${database}__:expired`,
  139. async message => {
  140. const type = message.substring(0, message.indexOf("."));
  141. if (type !== "schedule") return;
  142. const channel = message.substring(message.indexOf(".") + 1);
  143. if (!this._scheduleCallbacks[channel]) return;
  144. await forEachIn(this._scheduleCallbacks[channel], callback =>
  145. callback()
  146. );
  147. }
  148. );
  149. }
  150. public getEvent(path: string) {
  151. const moduleName = path.substring(0, path.indexOf("."));
  152. const eventName = path.substring(path.indexOf(".") + 1);
  153. if (moduleName === this._name) return super.getEvent(eventName);
  154. const module = ModuleManager.getModule(moduleName);
  155. if (!module) throw new Error(`Module "${moduleName}" not found`);
  156. return module.getEvent(eventName);
  157. }
  158. public getAllEvents() {
  159. return Object.fromEntries(
  160. Object.entries(ModuleManager.getModules() ?? {}).map(
  161. ([name, module]) => [name, Object.keys(module.getEvents())]
  162. )
  163. );
  164. }
  165. /**
  166. * Like JobContext assertPermission, checks if the current user has permission to subscribe to the event associated
  167. * with the provided permission.
  168. * Permission can be for example "event.data.news.created" or "event.data.news.updated:6687eec103808fe513c937ff"
  169. */
  170. public async assertPermission(jobContext: JobContext, permission: string) {
  171. let hasPermission = false;
  172. const {
  173. moduleName,
  174. modelOrEventName,
  175. eventName,
  176. modelId,
  177. extraAfterModelId,
  178. extraAfterColon
  179. } = permissionRegex.exec(permission)?.groups ?? {};
  180. const extra = extraAfterModelId || extraAfterColon;
  181. if (moduleName === "data" && modelOrEventName && eventName) {
  182. const GetModelPermissions = DataModule.getJob(
  183. "users.getModelPermissions"
  184. );
  185. // eslint-disable-next-line
  186. // @ts-ignore
  187. const permissions = (await new GetModelPermissions(
  188. {
  189. modelName: modelOrEventName,
  190. modelId
  191. },
  192. {
  193. session: jobContext.getSession(),
  194. socketId: jobContext.getSocketId()
  195. }
  196. ).execute()) as unknown as GetSingleModelPermissionsResult; // Add context?
  197. let modelPermission = `event.data.${modelOrEventName}.${eventName}`;
  198. if (extra) modelPermission += `.${extra}`;
  199. hasPermission = permissions[modelPermission];
  200. } else {
  201. const GetPermissions = DataModule.getJob("users.getPermissions");
  202. const permissions =
  203. // eslint-disable-next-line
  204. // @ts-ignore
  205. (await new GetPermissions(
  206. {},
  207. {
  208. session: jobContext.getSession(),
  209. socketId: jobContext.getSocketId()
  210. }
  211. ).execute()) as unknown as GetPermissionsResult;
  212. hasPermission = permissions[permission];
  213. }
  214. if (!hasPermission)
  215. throw new Error(
  216. `Insufficient permissions for permission ${permission}`
  217. );
  218. }
  219. /**
  220. * createKey - Create hex key
  221. */
  222. private _createKey(type: "event" | "schedule", channel: string) {
  223. if (!["event", "schedule"].includes(type))
  224. throw new Error("Invalid type");
  225. if (!channel || typeof channel !== "string")
  226. throw new Error("Invalid channel");
  227. return `${type}.${channel}`;
  228. }
  229. /**
  230. * publish - Publish an event
  231. */
  232. public async publish(event: Event) {
  233. if (!this._pubClient) throw new Error("Redis pubClient unavailable.");
  234. const channel = event.getKey();
  235. const value = event.makeMessage();
  236. await this._pubClient.publish(this._createKey("event", channel), value);
  237. }
  238. /**
  239. * subscriptionListener - Listener for event subscriptions
  240. */
  241. private async _subscriptionListener(message: string, key: string) {
  242. const type = key.substring(0, key.indexOf("."));
  243. if (type !== "event") return;
  244. key = key.substring(key.indexOf(".") + 1);
  245. const { path, scope } = Event.parseKey(key);
  246. const EventClass = this.getEvent(path);
  247. const parsedMessage = Event.parseMessage(message);
  248. const event = new EventClass(parsedMessage, scope);
  249. if (this._subscriptions && this._subscriptions[key])
  250. await forEachIn(this._subscriptions[key], async cb => cb(event));
  251. if (this._pSubscriptions)
  252. await forEachIn(
  253. Object.entries(this._pSubscriptions).filter(([subscription]) =>
  254. new RegExp(subscription).test(key)
  255. ),
  256. async ([, callbacks]) =>
  257. forEachIn(callbacks, async cb => cb(event))
  258. );
  259. if (!this._socketSubscriptions[key]) return;
  260. for await (const socketId of this._socketSubscriptions[key].values()) {
  261. await WebSocketModule.dispatch(socketId, key, event.getData());
  262. }
  263. }
  264. /**
  265. * subscribe - Subscribe to an event or schedule completion
  266. */
  267. public async subscribe(
  268. EventClass: any,
  269. callback: (message?: any) => Promise<void>,
  270. scope?: string
  271. ) {
  272. if (!this._subClient) throw new Error("Redis subClient unavailable.");
  273. const key = EventClass.getKey(scope);
  274. const type = EventClass.getType();
  275. if (type === "schedule") {
  276. if (!this._scheduleCallbacks[key])
  277. this._scheduleCallbacks[key] = [];
  278. this._scheduleCallbacks[key].push(() => callback());
  279. return;
  280. }
  281. if (!this._subscriptions[key]) this._subscriptions[key] = [];
  282. this._subscriptions[key].push(callback);
  283. }
  284. /**
  285. * pSubscribe - Subscribe to an event with pattern
  286. */
  287. public async pSubscribe(
  288. pattern: string,
  289. callback: (event: Event) => Promise<void>
  290. ) {
  291. if (!this._subClient) throw new Error("Redis subClient unavailable.");
  292. if (!this._pSubscriptions[pattern]) this._pSubscriptions[pattern] = [];
  293. this._pSubscriptions[pattern].push(callback);
  294. }
  295. /**
  296. * unsubscribe - Unsubscribe from an event or schedule completion
  297. */
  298. public async unsubscribe(
  299. type: "event" | "schedule",
  300. channel: string,
  301. callback: (message?: any) => Promise<void>
  302. ) {
  303. if (!this._subClient) throw new Error("Redis subClient unavailable.");
  304. if (type === "schedule") {
  305. if (!this._scheduleCallbacks[channel]) return;
  306. const index = this._scheduleCallbacks[channel].findIndex(
  307. schedule => schedule.toString() === callback.toString()
  308. );
  309. if (index >= 0) this._scheduleCallbacks[channel].splice(index, 1);
  310. return;
  311. }
  312. if (!this._subscriptions[channel]) return;
  313. const index = this._subscriptions[channel].findIndex(
  314. subscription => subscription.toString() === callback.toString()
  315. );
  316. if (index < 0) return;
  317. this._subscriptions[channel].splice(index, 1);
  318. if (this._subscriptions[channel].length === 0)
  319. delete this._subscriptions[channel];
  320. }
  321. /**
  322. * schedule - Schedule a callback trigger
  323. */
  324. public async schedule(channel: string, time: number) {
  325. if (!this._pubClient) throw new Error("Redis pubClient unavailable.");
  326. if (typeof time !== "number") throw new Error("Time must be a number");
  327. time = Math.round(time);
  328. if (time <= 0) throw new Error("Time must be greater than 0");
  329. await this._pubClient.set(this._createKey("schedule", channel), "", {
  330. PX: time,
  331. NX: true
  332. });
  333. }
  334. /**
  335. * unschedule - Unschedule a callback trigger
  336. */
  337. public async unschedule(channel: string) {
  338. if (!this._pubClient) throw new Error("Redis pubClient unavailable.");
  339. await this._pubClient.del(this._createKey("schedule", channel));
  340. }
  341. public async subscribeSocket(channel: string, socketId: string) {
  342. if (!this._socketSubscriptions[channel]) {
  343. this._socketSubscriptions[channel] = new Set();
  344. }
  345. if (this._socketSubscriptions[channel].has(socketId)) return;
  346. this._socketSubscriptions[channel].add(socketId);
  347. }
  348. public async subscribeManySocket(channels: string[], socketId: string) {
  349. await forEachIn(channels, channel =>
  350. this.subscribeSocket(channel, socketId)
  351. );
  352. }
  353. public async unsubscribeSocket(channel: string, socketId: string) {
  354. if (
  355. !(
  356. this._socketSubscriptions[channel] &&
  357. this._socketSubscriptions[channel].has(socketId)
  358. )
  359. )
  360. return;
  361. this._socketSubscriptions[channel].delete(socketId);
  362. if (this._socketSubscriptions[channel].size === 0)
  363. delete this._socketSubscriptions[channel];
  364. }
  365. public async unsubscribeManySocket(channels: string[], socketId: string) {
  366. await forEachIn(channels, channel =>
  367. this.unsubscribeSocket(channel, socketId)
  368. );
  369. }
  370. public async unsubscribeAllSocket(socketId: string) {
  371. await forEachIn(
  372. Object.entries(this._socketSubscriptions).filter(([, socketIds]) =>
  373. socketIds.has(socketId)
  374. ),
  375. async ([channel]) => this.unsubscribeSocket(channel, socketId)
  376. );
  377. }
  378. /**
  379. * shutdown - Shutdown events module
  380. */
  381. public override async shutdown() {
  382. await super.shutdown();
  383. if (this._pubClient) await this._pubClient.quit();
  384. if (this._subClient) await this._subClient.quit();
  385. this._subscriptions = {};
  386. this._scheduleCallbacks = {};
  387. await this._stopped();
  388. }
  389. }
  390. export default new EventsModule();