BaseModule.ts 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. import { readdir } from "fs/promises";
  2. import path from "path";
  3. import { forEachIn } from "@common/utils/forEachIn";
  4. import LogBook, { Log } from "@/LogBook";
  5. import ModuleManager from "@/ModuleManager";
  6. import Job from "./Job";
  7. import { EventClass } from "./modules/EventsModule/Event";
  8. export enum ModuleStatus {
  9. LOADED = "LOADED",
  10. STARTING = "STARTING",
  11. STARTED = "STARTED",
  12. STOPPED = "STOPPED",
  13. STOPPING = "STOPPING",
  14. ERROR = "ERROR",
  15. DISABLED = "DISABLED"
  16. }
  17. export default abstract class BaseModule {
  18. protected _name: string;
  19. protected _status: ModuleStatus;
  20. protected _dependentModules: string[];
  21. protected _jobs: Record<string, typeof Job>;
  22. protected _events: Record<string, EventClass>;
  23. /**
  24. * Base Module
  25. *
  26. * @param name - Module name
  27. */
  28. public constructor(name: string) {
  29. this._name = name;
  30. this._status = ModuleStatus.LOADED;
  31. this._dependentModules = [];
  32. this._jobs = {};
  33. this._events = {};
  34. this.log(`Module (${this._name}) loaded`);
  35. }
  36. /**
  37. * getName - Get module name
  38. *
  39. * @returns name
  40. */
  41. public getName() {
  42. return this._name;
  43. }
  44. /**
  45. * getStatus - Get module status
  46. *
  47. * @returns status
  48. */
  49. public getStatus() {
  50. return this._status;
  51. }
  52. /**
  53. * setStatus - Set module status
  54. *
  55. * @param status - Module status
  56. */
  57. public setStatus(status: ModuleStatus) {
  58. this._status = status;
  59. }
  60. /**
  61. * getDependentModules - Get module dependencies
  62. */
  63. public getDependentModules() {
  64. return this._dependentModules;
  65. }
  66. /**
  67. * _loadJobs - Load jobs available via api module
  68. */
  69. private async _loadJobs() {
  70. let jobs;
  71. try {
  72. jobs = await readdir(
  73. path.resolve(
  74. __dirname,
  75. `./modules/${this.constructor.name}/jobs`
  76. )
  77. );
  78. } catch (error) {
  79. if (
  80. error instanceof Error &&
  81. "code" in error &&
  82. error.code === "ENOENT"
  83. )
  84. return;
  85. throw error;
  86. }
  87. await forEachIn(jobs, async jobFile => {
  88. if (jobFile.includes(".spec.")) return;
  89. const { default: Job } = await import(
  90. `./modules/${this.constructor.name}/jobs/${jobFile}`
  91. );
  92. const jobName = Job.getName();
  93. this._jobs[jobName] = Job;
  94. });
  95. }
  96. /**
  97. * getJob - Get module job
  98. */
  99. public getJob(name: string) {
  100. const [, Job] =
  101. Object.entries(this._jobs).find(([jobName]) => jobName === name) ??
  102. [];
  103. if (!Job) throw new Error(`Job "${name}" not found.`);
  104. return Job;
  105. }
  106. /**
  107. * getJobs - Get module jobs
  108. */
  109. public getJobs() {
  110. return this._jobs;
  111. }
  112. /**
  113. * canRunJobs - Determine if module can run jobs
  114. */
  115. public canRunJobs() {
  116. return this.getDependentModules().reduce(
  117. (canRunJobs: boolean, moduleName: string): boolean => {
  118. if (canRunJobs === false) return false;
  119. return !!ModuleManager.getModule(moduleName)?.canRunJobs();
  120. },
  121. this.getStatus() === ModuleStatus.STARTED
  122. );
  123. }
  124. /**
  125. * _loadEvents - Load events
  126. */
  127. private async _loadEvents() {
  128. let events;
  129. try {
  130. events = await readdir(
  131. path.resolve(
  132. __dirname,
  133. `./modules/${this.constructor.name}/events`
  134. )
  135. );
  136. } catch (error) {
  137. if (
  138. error instanceof Error &&
  139. "code" in error &&
  140. error.code === "ENOENT"
  141. )
  142. return;
  143. throw error;
  144. }
  145. await forEachIn(events, async eventFile => {
  146. if (eventFile.includes(".spec.")) return;
  147. const { default: EventClass } = await import(
  148. `./modules/${this.constructor.name}/events/${eventFile}`
  149. );
  150. const eventName = EventClass.getName();
  151. this._events[eventName] = EventClass;
  152. });
  153. }
  154. /**
  155. * getEvent - Get module event
  156. */
  157. public getEvent(name: string): EventClass {
  158. const [, Event] =
  159. Object.entries(this._events).find(
  160. ([eventName]) => eventName === name
  161. ) ?? [];
  162. if (!Event) throw new Error(`Event "${name}" not found.`);
  163. return Event;
  164. }
  165. /**
  166. * getEvents - Get module events
  167. */
  168. public getEvents() {
  169. return this._events;
  170. }
  171. /**
  172. * startup - Startup module
  173. */
  174. public async startup() {
  175. this.log(`Module (${this._name}) starting`);
  176. this.setStatus(ModuleStatus.STARTING);
  177. }
  178. /**
  179. * started - called with the module has started
  180. */
  181. protected async _started() {
  182. await this._loadJobs();
  183. await this._loadEvents();
  184. this.log(`Module (${this._name}) started`);
  185. this.setStatus(ModuleStatus.STARTED);
  186. }
  187. /**
  188. * shutdown - Shutdown module
  189. */
  190. public async shutdown() {
  191. this.log(`Module (${this._name}) stopping`);
  192. this.setStatus(ModuleStatus.STOPPING);
  193. }
  194. /**
  195. * stopped - called when the module has stopped
  196. */
  197. protected async _stopped() {
  198. this.log(`Module (${this._name}) stopped`);
  199. this.setStatus(ModuleStatus.STOPPED);
  200. }
  201. /**
  202. * log - Add log to logbook
  203. *
  204. * @param log - Log message or object
  205. */
  206. public log(log: string | Omit<Log, "timestamp" | "category">) {
  207. const {
  208. message,
  209. type = "info",
  210. data = {}
  211. } = {
  212. ...(typeof log === "string" ? { message: log } : log)
  213. };
  214. LogBook.log({
  215. message,
  216. type,
  217. category: `modules.${this.getName()}`,
  218. data: {
  219. moduleName: this._name,
  220. ...data
  221. }
  222. });
  223. }
  224. }