@futdevpro/nts-dynamo 1.15.82 → 1.15.84

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.
Files changed (365) hide show
  1. package/.c8rc.json +26 -26
  2. package/.copilot/patterns.json +7 -7
  3. package/.cursor/rules/__assistant_guide.mdc +30 -30
  4. package/.cursor/rules/_ag_backend-structure.mdc +85 -85
  5. package/.cursor/rules/_ag_backend.mdc +16 -16
  6. package/.cursor/rules/_ag_frontend-structure.mdc +86 -86
  7. package/.cursor/rules/_ag_frontend.mdc +39 -39
  8. package/.cursor/rules/_ag_import-rules.mdc +44 -44
  9. package/.cursor/rules/_ag_naming.mdc +115 -115
  10. package/.cursor/rules/_ag_should-be.mdc +6 -6
  11. package/.cursor/rules/ai_development_guide.md +60 -60
  12. package/.cursor/rules/cursor-rules.md +160 -160
  13. package/.cursor/rules/default-command.mdc +464 -464
  14. package/.cursor/rules/error_code_pattern.md +39 -39
  15. package/.cursor/rules/saved rule mcp server use.md +15 -15
  16. package/.vscode/settings.json +10 -10
  17. package/HOWTO.md +15 -15
  18. package/LICENSE +21 -21
  19. package/__documentations/nts-integration-tests-2026-03-17.md +26 -26
  20. package/__documentations/plans/BEDROCK-HYPERPLAN.md +95 -95
  21. package/_specifications/BACKLOG.md +92 -92
  22. package/_specifications/TODO.md +15 -15
  23. package/_specifications/agent.md +138 -138
  24. package/build/_modules/server/errors/errors.controller.d.ts +15 -0
  25. package/build/_modules/server/errors/errors.controller.d.ts.map +1 -1
  26. package/build/_modules/server/errors/errors.controller.js +51 -13
  27. package/build/_modules/server/errors/errors.controller.js.map +1 -1
  28. package/build/_modules/server/server-status/server-status.controller.d.ts +8 -0
  29. package/build/_modules/server/server-status/server-status.controller.d.ts.map +1 -1
  30. package/build/_modules/server/server-status/server-status.controller.js +25 -5
  31. package/build/_modules/server/server-status/server-status.controller.js.map +1 -1
  32. package/eslint.config.js +3 -3
  33. package/nodemon.json +24 -24
  34. package/package.json +3 -3
  35. package/pnpm-workspace.yaml +5 -5
  36. package/scripts/run-coverage-tests.js +28 -28
  37. package/spec/support/helpers/spec-reporter-loader.js +359 -359
  38. package/spec/support/helpers/ts-node-helper.js +93 -93
  39. package/spec/support/jasmine.coverage.json +24 -24
  40. package/spec/support/jasmine.json +24 -24
  41. package/src/_collections/archive.util.spec.ts +57 -57
  42. package/src/_collections/archive.util.ts +18 -18
  43. package/src/_collections/atlas-default-db-options.const.ts +9 -9
  44. package/src/_collections/default-fallback-cache-max-age.const.spec.ts +11 -11
  45. package/src/_collections/default-fallback-cache-max-age.const.ts +2 -2
  46. package/src/_collections/default-not-found-page.const.spec.ts +19 -19
  47. package/src/_collections/default-not-found-page.const.ts +22 -22
  48. package/src/_collections/default-socket-path.const.spec.ts +12 -12
  49. package/src/_collections/default-socket-path.const.ts +2 -2
  50. package/src/_collections/get-environment-settings.util.spec.ts +210 -210
  51. package/src/_collections/get-environment-settings.util.ts +48 -48
  52. package/src/_collections/global-settings.const.ts +109 -109
  53. package/src/_collections/sample.env +21 -21
  54. package/src/_collections/star.controller.spec.ts +224 -224
  55. package/src/_collections/star.controller.ts +129 -129
  56. package/src/_enums/data-model-type.enum.ts +14 -14
  57. package/src/_enums/data-service-function.enum.ts +24 -24
  58. package/src/_enums/predefined-data-types.enum.ts +16 -16
  59. package/src/_enums/route-security.enum.ts +12 -12
  60. package/src/_models/control-models/api-call-params.control-model.spec.ts +152 -152
  61. package/src/_models/control-models/api-call-params.control-model.ts +142 -142
  62. package/src/_models/control-models/app-ext-system-controls.control-model.spec.ts +52 -52
  63. package/src/_models/control-models/app-ext-system-controls.control-model.ts +9 -9
  64. package/src/_models/control-models/app-params.control-model.spec.ts +225 -225
  65. package/src/_models/control-models/app-params.control-model.ts +136 -136
  66. package/src/_models/control-models/app-system-controls.control-model.spec.ts +31 -31
  67. package/src/_models/control-models/app-system-controls.control-model.ts +9 -9
  68. package/src/_models/control-models/endpoint-params.control-model.spec.ts +627 -627
  69. package/src/_models/control-models/endpoint-params.control-model.ts +627 -627
  70. package/src/_models/control-models/http-settings.control-model.spec.ts +77 -77
  71. package/src/_models/control-models/http-settings.control-model.ts +37 -37
  72. package/src/_models/control-models/system-control.control-model.spec.ts +27 -27
  73. package/src/_models/control-models/system-control.control-model.ts +12 -12
  74. package/src/_models/interfaces/certification-settings.interface.ts +7 -7
  75. package/src/_models/interfaces/environment-settings.interface.ts +59 -59
  76. package/src/_models/interfaces/global-log-settings.interface.ts +171 -171
  77. package/src/_models/interfaces/global-service-settings.interface.ts +47 -47
  78. package/src/_models/interfaces/global-settings.interface.ts +235 -235
  79. package/src/_models/interfaces/routing-module-settings.interface.ts +21 -21
  80. package/src/_models/interfaces/static-client-settings.interface.spec.ts +29 -29
  81. package/src/_models/interfaces/static-client-settings.interface.ts +28 -28
  82. package/src/_models/types/db-update.type.ts +100 -100
  83. package/src/_modules/ai/_models/ai-input-interfaces.ts +117 -117
  84. package/src/_modules/ai/_models/ai-test-generation-result.interface.ts +16 -16
  85. package/src/_modules/ai/_modules/anthropic/_services/aai-user-key.control-service.ts +138 -138
  86. package/src/_modules/ai/_modules/anthropic/index.ts +5 -5
  87. package/src/_modules/ai/_modules/document-ai/_collections/dai-chunking.util.spec.ts +242 -242
  88. package/src/_modules/ai/_modules/document-ai/_collections/dai-chunking.util.ts +639 -639
  89. package/src/_modules/ai/_modules/document-ai/_collections/dai-code-chunking.util.spec.ts +295 -295
  90. package/src/_modules/ai/_modules/document-ai/_collections/dai-code-chunking.util.ts +518 -518
  91. package/src/_modules/ai/_modules/document-ai/_collections/dai-document.util.spec.ts +209 -209
  92. package/src/_modules/ai/_modules/document-ai/_collections/dai-document.util.ts +85 -85
  93. package/src/_modules/ai/_modules/document-ai/_enums/dai-compare-result-type.enum.ts +7 -7
  94. package/src/_modules/ai/_modules/document-ai/_models/data-models/dai-doc-chunk.data-model.ts +146 -146
  95. package/src/_modules/ai/_modules/document-ai/_models/data-models/dai-doc-page.data-model.ts +162 -162
  96. package/src/_modules/ai/_modules/document-ai/_models/data-models/dai-document.data-model.ts +99 -99
  97. package/src/_modules/ai/_modules/document-ai/_models/interfaces/dai-code-chunk.interface.ts +68 -68
  98. package/src/_modules/ai/_modules/document-ai/_models/interfaces/dai-doc-chunk-compare-result.interface.ts +18 -18
  99. package/src/_modules/ai/_modules/document-ai/_models/interfaces/dai-doc-page-compare-result.interface.ts +19 -19
  100. package/src/_modules/ai/_modules/document-ai/_models/interfaces/dai-document-compare-result.interface.ts +25 -25
  101. package/src/_modules/ai/_modules/document-ai/index.ts +30 -30
  102. package/src/_modules/ai/_modules/fdp-ai/_services/fdpai-user-key.control-service.ts +189 -189
  103. package/src/_modules/ai/_modules/fdp-ai/index.ts +5 -5
  104. package/src/_modules/ai/_modules/open-ai/_collections/oai-global-settings.const.ts +9 -9
  105. package/src/_modules/ai/_modules/open-ai/_collections/oai-llm-predefined-requests-hu.conts.ts +82 -82
  106. package/src/_modules/ai/_modules/open-ai/_collections/oai-llm-predefined-requests.conts.ts +75 -75
  107. package/src/_modules/ai/_modules/open-ai/_enums/oai-gpt-message-role.enum.ts +45 -45
  108. package/src/_modules/ai/_modules/open-ai/_models/interfaces/oai-global-settings.interface.ts +7 -7
  109. package/src/_modules/ai/_modules/open-ai/_models/interfaces/oai-gpt-message.interface.ts +7 -7
  110. package/src/_modules/ai/_modules/open-ai/_models/interfaces/oai-llm-predefined-requests.interface.ts +57 -57
  111. package/src/_modules/ai/_modules/open-ai/_services/data-services/oai-doc-chunk-data.service.ts +292 -292
  112. package/src/_modules/ai/_modules/open-ai/_services/data-services/oai-document.data-service.spec.ts +342 -342
  113. package/src/_modules/ai/_modules/open-ai/_services/data-services/oai-vector-data.service.spec.ts +550 -550
  114. package/src/_modules/ai/_modules/open-ai/_services/data-services/oai-vector-data.service.ts +630 -630
  115. package/src/_modules/ai/_modules/open-ai/_services/oai-embedding.control-service.spec.ts +332 -332
  116. package/src/_modules/ai/_modules/open-ai/_services/oai-llm-chat.service-base.spec.ts +462 -462
  117. package/src/_modules/ai/_modules/open-ai/_services/oai-llm-chat.service-base.ts +634 -634
  118. package/src/_modules/ai/_modules/open-ai/_services/oai-llm.service-base.spec.ts +489 -489
  119. package/src/_modules/ai/_modules/open-ai/_services/oai-llm.service-base.tools.spec.ts +173 -173
  120. package/src/_modules/ai/_modules/open-ai/_services/oai-llm.service-base.ts +1033 -1033
  121. package/src/_modules/ai/_modules/open-ai/_services/oai-user-key.control-service.ts +157 -157
  122. package/src/_modules/ai/_services/ai-embedding-mock.service.spec.ts +115 -115
  123. package/src/_modules/ai/_services/ai-embedding-mock.service.ts +212 -212
  124. package/src/_modules/ai/_services/ai-embedding-provider.registry.spec.ts +110 -110
  125. package/src/_modules/ai/_services/ai-embedding-provider.registry.ts +110 -110
  126. package/src/_modules/ai/_services/ai-embedding.service-base.spec.ts +98 -98
  127. package/src/_modules/ai/_services/ai-embedding.service-base.ts +48 -48
  128. package/src/_modules/ai/_services/ai-llm-chat.service-base.spec.ts +229 -229
  129. package/src/_modules/ai/_services/ai-llm-chat.service-base.ts +68 -68
  130. package/src/_modules/ai/_services/ai-llm.service-base.spec.ts +250 -250
  131. package/src/_modules/ai/_services/ai-llm.service-base.ts +519 -519
  132. package/src/_modules/ai/_services/ai-provider.service-base.spec.ts +158 -158
  133. package/src/_modules/ai/_services/ai-user-key.service-base.ts +59 -59
  134. package/src/_modules/ai/_services/lmstudio-embedding.control-service.spec.ts +197 -197
  135. package/src/_modules/ai/_services/lmstudio-embedding.control-service.ts +371 -371
  136. package/src/_modules/ai/index.ts +23 -23
  137. package/src/_modules/assistant/_collections/ass-global-settings.const.ts +13 -13
  138. package/src/_modules/assistant/_collections/ass.util.spec.ts +176 -176
  139. package/src/_modules/assistant/_collections/ass.util.ts +50 -50
  140. package/src/_modules/assistant/_models/ass-global-settings.interface.ts +15 -15
  141. package/src/_modules/assistant/_services/ass-io.control-service.spec.ts +140 -140
  142. package/src/_modules/assistant/_services/ass-main.control-service.spec.ts +192 -192
  143. package/src/_modules/assistant/_services/ass-main.control-service.ts +107 -107
  144. package/src/_modules/bot/_collections/bot-default-commands.const.ts +12 -12
  145. package/src/_modules/bot/_collections/bot-global-settings.const.ts +39 -39
  146. package/src/_modules/bot/_models/bot-channel-wrapper.interface.ts +62 -62
  147. package/src/_modules/bot/_models/bot-command.interface.ts +8 -8
  148. package/src/_modules/bot/_models/bot-global-settings.interface.ts +96 -96
  149. package/src/_modules/bot/_models/bot-last-mention-date.interface.ts +6 -6
  150. package/src/_modules/bot/_models/bot-last-message-date.interface.ts +5 -5
  151. package/src/_modules/bot/_models/bot-user-wrapper.interface.ts +41 -41
  152. package/src/_modules/bot/_modules/discord-bot/_models/dib-platform.types.ts +9 -9
  153. package/src/_modules/bot/_modules/discord-bot/_services/dib-messaging-provider.control-service.spec.ts +431 -431
  154. package/src/_modules/bot/_modules/dynamo-bot/_collections/dyb-operations.util.spec.ts +160 -160
  155. package/src/_modules/bot/_modules/dynamo-bot/_collections/dyb-operations.util.ts +55 -55
  156. package/src/_modules/bot/_modules/dynamo-bot/_models/dyb-platform.types.ts +15 -15
  157. package/src/_modules/bot/_modules/dynamo-bot/_services/dyb-messaging-provider.control-service.spec.ts +374 -374
  158. package/src/_modules/bot/_modules/dynamo-bot/_services/dyb-messaging-provider.control-service.ts +447 -447
  159. package/src/_modules/bot/_modules/dynamo-bot/index.ts +15 -15
  160. package/src/_modules/bot/_modules/slack-bot/_models/slb-platform.types.ts +9 -9
  161. package/src/_modules/bot/_modules/slack-bot/_services/slb-messaging-provider.control-service.spec.ts +344 -344
  162. package/src/_modules/bot/_modules/slack-bot/_services/slb-messaging-provider.control-service.ts +197 -197
  163. package/src/_modules/bot/_modules/teams-bot/_models/teb-platform.types.ts +9 -9
  164. package/src/_modules/bot/_modules/teams-bot/_services/teb-messaging-provider.control-service.spec.ts +345 -345
  165. package/src/_modules/bot/_modules/teams-bot/_services/teb-messaging-provider.control-service.ts +197 -197
  166. package/src/_modules/bot/_services/bot-commands.control-service.spec.ts +116 -116
  167. package/src/_modules/bot/_services/bot-io.control-service.spec.ts +285 -285
  168. package/src/_modules/bot/_services/bot-main.control-service.spec.ts +208 -208
  169. package/src/_modules/bot/_services/bot-messaging-provider.service-base.spec.ts +349 -349
  170. package/src/_modules/bot/_services/bot-routines.control-service.spec.ts +111 -111
  171. package/src/_modules/custom-data/custom-data.controller.spec.ts +49 -49
  172. package/src/_modules/custom-data/custom-data.controller.ts +67 -67
  173. package/src/_modules/custom-data/custom-data.data-service.spec.ts +54 -54
  174. package/src/_modules/custom-data/custom-data.data-service.ts +21 -21
  175. package/src/_modules/custom-data/get-custom-data-routing-module.util.spec.ts +28 -28
  176. package/src/_modules/custom-data/get-custom-data-routing-module.util.ts +24 -24
  177. package/src/_modules/custom-data/index.ts +9 -9
  178. package/src/_modules/data-readers/_collections/dynts-sqlite-reader.util.spec.ts +161 -161
  179. package/src/_modules/data-readers/_collections/dynts-sqlite-reader.util.ts +203 -203
  180. package/src/_modules/data-readers/_models/interfaces/dynts-sqlite-reader.interface.ts +33 -33
  181. package/src/_modules/data-readers/index.ts +11 -11
  182. package/src/_modules/defaults/_collections/default-endpoints.util.ts +487 -487
  183. package/src/_modules/defaults/_models/default-user.data-model.ts +72 -72
  184. package/src/_modules/defaults/_services/default-auth.service.spec.ts +269 -269
  185. package/src/_modules/defaults/_services/default-auth.service.ts +177 -177
  186. package/src/_modules/defaults/_services/default-socket-events.service.spec.ts +42 -42
  187. package/src/_modules/defaults/_services/default-socket-events.service.ts +61 -61
  188. package/src/_modules/defaults/_services/default-user.data-service.spec.ts +187 -187
  189. package/src/_modules/defaults/_services/default-user.data-service.ts +98 -98
  190. package/src/_modules/defaults/index.ts +17 -17
  191. package/src/_modules/discord-assistant/_collections/dias-global-settings.const.ts +19 -19
  192. package/src/_modules/discord-assistant/_collections/dias.util.spec.ts +366 -366
  193. package/src/_modules/discord-assistant/_collections/dias.util.ts +132 -132
  194. package/src/_modules/discord-assistant/_models/dias-global-settings.interface.ts +19 -19
  195. package/src/_modules/discord-assistant/_models/dias-knowledge.data-model.ts +52 -52
  196. package/src/_modules/discord-assistant/_services/dias-chunk.data-service.ts +177 -177
  197. package/src/_modules/discord-assistant/_services/dias-io.control-service.spec.ts +108 -108
  198. package/src/_modules/discord-assistant/_services/dias-io.control-service.ts +69 -69
  199. package/src/_modules/discord-assistant/_services/dias-main.control-service.spec.ts +22 -22
  200. package/src/_modules/discord-assistant/_services/dias-main.control-service.ts +27 -27
  201. package/src/_modules/discord-assistant/_services/dias.service-base.spec.ts +195 -195
  202. package/src/_modules/discord-assistant/_services/dias.service-base.ts +76 -76
  203. package/src/_modules/discord-assistant/index.ts +38 -38
  204. package/src/_modules/discord-assistant-voiced/_services/dias-discord-bot.control-service.spec.ts +34 -34
  205. package/src/_modules/discord-assistant-voiced/_services/dias-discord-bot.control-service.ts +11 -11
  206. package/src/_modules/discord-assistant-voiced/index.ts +36 -36
  207. package/src/_modules/discord-bot/_collections/dibo-default-commands.const.ts +16 -16
  208. package/src/_modules/discord-bot/_collections/dibo-global-settings.conts.ts +55 -55
  209. package/src/_modules/discord-bot/_collections/dibo-operations.util.spec.ts +214 -214
  210. package/src/_modules/discord-bot/_collections/dibo-operations.util.ts +387 -387
  211. package/src/_modules/discord-bot/_models/dibo-command.interface.ts +12 -12
  212. package/src/_modules/discord-bot/_models/dibo-global-settings.interface.ts +98 -98
  213. package/src/_modules/discord-bot/_models/dibo-last-mention-date.inteface.ts +7 -7
  214. package/src/_modules/discord-bot/_models/dibo-last-message-date.interface.ts +6 -6
  215. package/src/_modules/discord-bot/_services/dibo-commands.control-service.spec.ts +154 -154
  216. package/src/_modules/discord-bot/_services/dibo-commands.control-service.ts +153 -153
  217. package/src/_modules/discord-bot/_services/dibo-io.control-service.spec.ts +264 -264
  218. package/src/_modules/discord-bot/_services/dibo-io.control-service.ts +306 -306
  219. package/src/_modules/discord-bot/_services/dibo-main.control-service.spec.ts +408 -408
  220. package/src/_modules/discord-bot/_services/dibo-main.control-service.ts +487 -487
  221. package/src/_modules/discord-bot/_services/dibo-routines.control-service.spec.ts +105 -105
  222. package/src/_modules/discord-bot/index.ts +36 -36
  223. package/src/_modules/local-vector-search/_enums/lvs-search-mode.enum.ts +35 -35
  224. package/src/_modules/local-vector-search/_models/data-models/lvs-vector-persist.data-model.ts +59 -59
  225. package/src/_modules/local-vector-search/_models/lvs-search-result.interface.ts +17 -17
  226. package/src/_modules/local-vector-search/_services/lvs-doc-chunk-data.service.spec.ts +418 -418
  227. package/src/_modules/local-vector-search/_services/lvs-doc-chunk-data.service.ts +276 -276
  228. package/src/_modules/local-vector-search/_services/lvs-local-vector-search.data-service.spec.ts +480 -480
  229. package/src/_modules/local-vector-search/_services/lvs-local-vector-search.data-service.ts +416 -416
  230. package/src/_modules/local-vector-search/_services/lvs-persistent-vector-pool.control-service.spec.ts +198 -198
  231. package/src/_modules/local-vector-search/_services/lvs-persistent-vector-pool.control-service.ts +146 -146
  232. package/src/_modules/local-vector-search/_services/lvs-vector-persist.data-service.spec.ts +167 -167
  233. package/src/_modules/local-vector-search/_services/lvs-vector-persist.data-service.ts +106 -106
  234. package/src/_modules/local-vector-search/_services/lvs-vector-pool.control-service.spec.ts +507 -507
  235. package/src/_modules/local-vector-search/_services/lvs-vector-pool.control-service.ts +272 -272
  236. package/src/_modules/local-vector-search/index.ts +16 -16
  237. package/src/_modules/logs/index.ts +11 -11
  238. package/src/_modules/mcp/_models/interfaces/dynts-mcp.interface.ts +111 -111
  239. package/src/_modules/mcp/_services/dynts-mcp-server.service-base.spec.ts +142 -142
  240. package/src/_modules/mcp/_services/dynts-mcp-server.service-base.ts +120 -120
  241. package/src/_modules/mcp/_services/dynts-mcp.adapter.ts +168 -168
  242. package/src/_modules/mcp/index.ts +13 -13
  243. package/src/_modules/messaging/README.md +354 -354
  244. package/src/_modules/messaging/_collections/get-messaging-routing-module.util.ts +26 -26
  245. package/src/_modules/messaging/_collections/msg-global-settings.const.ts +22 -22
  246. package/src/_modules/messaging/_collections/msg.util.spec.ts +226 -226
  247. package/src/_modules/messaging/_models/msg-global-settings.interface.ts +37 -37
  248. package/src/_modules/messaging/_services/msg-conversation.data-service.ts +146 -146
  249. package/src/_modules/messaging/_services/msg-events.service.spec.ts +219 -219
  250. package/src/_modules/messaging/_services/msg-events.service.ts +267 -267
  251. package/src/_modules/messaging/_services/msg-integration.control-service.ts +179 -179
  252. package/src/_modules/messaging/_services/msg-main.control-service.spec.ts +147 -147
  253. package/src/_modules/messaging/_services/msg-main.control-service.ts +571 -571
  254. package/src/_modules/messaging/_services/msg-message.data-service.ts +129 -129
  255. package/src/_modules/messaging/_services/msg.controller.spec.ts +201 -201
  256. package/src/_modules/messaging/index.ts +30 -30
  257. package/src/_modules/mock/app-extended-server.mock.ts +201 -201
  258. package/src/_modules/mock/app-integration-test.mock.ts +51 -51
  259. package/src/_modules/mock/app-params.mock.spec.ts +21 -21
  260. package/src/_modules/mock/app-params.mock.ts +9 -9
  261. package/src/_modules/mock/app-server.mock.ts +188 -188
  262. package/src/_modules/mock/auth-service.mock.spec.ts +47 -47
  263. package/src/_modules/mock/auth-service.mock.ts +28 -28
  264. package/src/_modules/mock/controller.mock.spec.ts +26 -26
  265. package/src/_modules/mock/controller.mock.ts +16 -16
  266. package/src/_modules/mock/data-model.mock.spec.ts +111 -111
  267. package/src/_modules/mock/data-model.mock.ts +82 -82
  268. package/src/_modules/mock/email-service-collection.mock.spec.ts +24 -24
  269. package/src/_modules/mock/email-service-collection.mock.ts +15 -15
  270. package/src/_modules/mock/email-service.mock.spec.ts +17 -17
  271. package/src/_modules/mock/email-service.mock.ts +20 -20
  272. package/src/_modules/mock/email-template.mock.html +14 -14
  273. package/src/_modules/mock/endpoint.mock.ts +91 -91
  274. package/src/_modules/mock/socket-client.mock.spec.ts +40 -40
  275. package/src/_modules/mock/socket-client.mock.ts +45 -45
  276. package/src/_modules/mock/socket-server.mock.spec.ts +44 -44
  277. package/src/_modules/mock/socket-server.mock.ts +46 -46
  278. package/src/_modules/oauth2/_routes/oauth2.controller.spec.ts +107 -107
  279. package/src/_modules/oauth2/_routes/oauth2.controller.ts +98 -98
  280. package/src/_modules/oauth2/_services/oauth2.auth-service.spec.ts +254 -254
  281. package/src/_modules/oauth2/_services/oauth2.auth-service.ts +232 -232
  282. package/src/_modules/oauth2/_services/oauth2.control-service.spec.ts +585 -585
  283. package/src/_modules/oauth2/_services/oauth2.control-service.ts +653 -653
  284. package/src/_modules/oauth2/index.ts +17 -17
  285. package/src/_modules/scoped-config/_enums/dynts-scoped-config-level.enum.ts +22 -22
  286. package/src/_modules/scoped-config/_models/data-models/dynts-scoped-config.data-model.ts +81 -81
  287. package/src/_modules/scoped-config/_models/interfaces/dynts-scoped-config.interface.ts +107 -107
  288. package/src/_modules/scoped-config/_services/dynts-scoped-config.control-service.spec.ts +306 -306
  289. package/src/_modules/scoped-config/_services/dynts-scoped-config.control-service.ts +295 -295
  290. package/src/_modules/scoped-config/_services/dynts-scoped-config.data-service.spec.ts +118 -118
  291. package/src/_modules/scoped-config/_services/dynts-scoped-config.data-service.ts +105 -105
  292. package/src/_modules/scoped-config/index.ts +17 -17
  293. package/src/_modules/server/errors/errors.control-service.spec.ts +238 -238
  294. package/src/_modules/server/errors/errors.control-service.ts +100 -100
  295. package/src/_modules/server/errors/errors.controller.spec.ts +268 -249
  296. package/src/_modules/server/errors/errors.controller.ts +527 -489
  297. package/src/_modules/server/errors/errors.data-service.spec.ts +480 -480
  298. package/src/_modules/server/index.ts +30 -30
  299. package/src/_modules/server/server-status/server-status-snapshot.control-service.spec.ts +70 -70
  300. package/src/_modules/server/server-status/server-status-snapshot.control-service.ts +17 -17
  301. package/src/_modules/server/server-status/server-status-snapshot.data-service.spec.ts +77 -77
  302. package/src/_modules/server/server-status/server-status-snapshot.data-service.ts +37 -37
  303. package/src/_modules/server/server-status/server-status.control-service.spec.ts +576 -576
  304. package/src/_modules/server/server-status/server-status.control-service.ts +396 -396
  305. package/src/_modules/server/server-status/server-status.controller.spec.ts +255 -248
  306. package/src/_modules/server/server-status/server-status.controller.ts +272 -253
  307. package/src/_modules/socket/_enums/socket-security.enum.ts +11 -11
  308. package/src/_modules/socket/_models/socket-client-service-params.control-model.spec.ts +32 -32
  309. package/src/_modules/socket/_models/socket-client-service-params.control-model.ts +22 -22
  310. package/src/_modules/socket/_models/socket-presence.control-model.spec.ts +164 -164
  311. package/src/_modules/socket/_models/socket-presence.control-model.ts +210 -210
  312. package/src/_modules/socket/_models/socket-server-service-params.control-model.spec.ts +46 -46
  313. package/src/_modules/socket/_models/socket-server-service-params.control-model.ts +22 -22
  314. package/src/_modules/socket/_services/socket-client.service.spec.ts +15 -15
  315. package/src/_modules/socket/_services/socket-client.service.ts +260 -260
  316. package/src/_modules/socket/_services/socket-server.service.spec.ts +11 -11
  317. package/src/_modules/socket/app-extended.integration.spec.ts +85 -85
  318. package/src/_modules/socket/app-extended.server.ts +630 -630
  319. package/src/_modules/socket/index.ts +42 -42
  320. package/src/_modules/test/get-test-routing-module.util.spec.ts +28 -28
  321. package/src/_modules/test/get-test-routing-module.util.ts +23 -23
  322. package/src/_modules/test/index.ts +11 -11
  323. package/src/_modules/test/test.controller.spec.ts +72 -72
  324. package/src/_modules/test/test.controller.ts +115 -115
  325. package/src/_modules/usage/get-usage-routing-module.util.ts +22 -22
  326. package/src/_modules/usage/index.ts +15 -15
  327. package/src/_modules/usage/usage.controller.spec.ts +81 -81
  328. package/src/_modules/usage/usage.controller.ts +126 -126
  329. package/src/_modules/usage/usage.data-service.spec.ts +332 -332
  330. package/src/_modules/usage/usage.data-service.ts +185 -185
  331. package/src/_services/base/api.service-base.spec.ts +125 -125
  332. package/src/_services/base/api.service-base.ts +74 -74
  333. package/src/_services/base/archive-data.service.spec.ts +209 -209
  334. package/src/_services/base/archive-data.service.ts +224 -224
  335. package/src/_services/base/data.service.spec.ts +729 -729
  336. package/src/_services/base/data.service.ts +2740 -2740
  337. package/src/_services/base/db.service.spec.ts +73 -73
  338. package/src/_services/base/db.service.ts +1575 -1575
  339. package/src/_services/base/singleton.service-base.spec.ts +28 -28
  340. package/src/_services/base/singleton.service-base.ts +24 -24
  341. package/src/_services/base/singleton.service.spec.ts +114 -114
  342. package/src/_services/base/singleton.service.ts +38 -38
  343. package/src/_services/core/api.service.spec.ts +140 -140
  344. package/src/_services/core/auth.service.spec.ts +159 -159
  345. package/src/_services/core/auth.service.ts +174 -174
  346. package/src/_services/core/email.service.spec.ts +85 -85
  347. package/src/_services/core/email.service.ts +742 -742
  348. package/src/_services/core/global.service.spec.ts +292 -292
  349. package/src/_services/core/global.service.ts +487 -487
  350. package/src/_services/core/memory-guard.service.spec.ts +245 -245
  351. package/src/_services/core/memory-guard.service.ts +481 -481
  352. package/src/_services/core/service-collection.service.spec.ts +46 -46
  353. package/src/_services/core/service-collection.service.ts +6 -6
  354. package/src/_services/route/controller.service.spec.ts +53 -53
  355. package/src/_services/route/controller.service.ts +148 -148
  356. package/src/_services/route/routing-module.service.spec.ts +98 -98
  357. package/src/_services/route/routing-module.service.ts +330 -330
  358. package/src/_services/server/app.server.ts +1905 -1905
  359. package/src/_services/shared.static-service.spec.ts +99 -99
  360. package/src/_services/shared.static-service.ts +78 -78
  361. package/src/index.ts +97 -97
  362. package/tsconfig.app.json +12 -12
  363. package/tsconfig.json +42 -42
  364. package/.dynamo/logs/cicd-pipeline/output.log +0 -2867
  365. package/.dynamo/logs/cicd-pipeline/status.json +0 -94
@@ -1,1905 +1,1905 @@
1
-
2
- import Mongoose = require('mongoose');
3
- import Express = require('express');
4
- /* import Mongoose from 'mongoose';
5
- import Express from 'express'; */
6
-
7
- import * as BodyParser from 'body-parser';
8
- import * as FileSystem from 'fs';
9
- import * as Http from 'http';
10
- import * as Https from 'https';
11
- import * as Path from 'path';
12
- import * as dotenv from 'dotenv'
13
-
14
- /* import { version } from '../../../package.json'; */
15
-
16
- import {
17
- DyFM_AnyError,
18
- DyFM_Array,
19
- DyFM_Async,
20
- DyFM_Error,
21
- DyFM_error_defaults,
22
- DyFM_Error_Settings,
23
- DyFM_ErrorLevel,
24
- DyFM_Log,
25
- DyFM_resolveRetentionTtlSeconds,
26
- megabyte,
27
- second
28
- } from '@futdevpro/fsm-dynamo';
29
-
30
- import { DyNTS_defaultFallbackCacheMaxAge } from '../../_collections/default-fallback-cache-max-age.const';
31
- import { DyNTS_defaultNotFoundPageHtml } from '../../_collections/default-not-found-page.const';
32
- import { DyNTS_global_settings } from '../../_collections/global-settings.const';
33
- import { startMongoReconnectGuard } from '../../_collections/mongo-reconnect-guard.util';
34
- import { DyNTS_RouteSecurity } from '../../_enums/route-security.enum';
35
- import { DyNTS_App_Params } from '../../_models/control-models/app-params.control-model';
36
- import {
37
- DyNTS_AppSystemControls
38
- } from '../../_models/control-models/app-system-controls.control-model';
39
- import {
40
- DyNTS_Endpoint_Params
41
- } from '../../_models/control-models/endpoint-params.control-model';
42
- import { DyNTS_Http_Settings } from '../../_models/control-models/http-settings.control-model';
43
- import {
44
- DyNTS_Certification_Settings
45
- } from '../../_models/interfaces/certification-settings.interface';
46
- import {
47
- DyNTS_GlobalService_Settings
48
- } from '../../_models/interfaces/global-service-settings.interface';
49
- import {
50
- DyNTS_StaticClient_Settings
51
- } from '../../_models/interfaces/static-client-settings.interface';
52
- import {
53
- DyNTS_Cors_Settings
54
- } from '../../_models/interfaces/cors-settings.interface';
55
- import { DyNTS_DBService } from '../base/db.service';
56
- import { DyNTS_SingletonService } from '../base/singleton.service';
57
- import { DyNTS_GlobalService } from '../core/global.service';
58
- import { DyNTS_CollectionGrowthMonitor } from '../core/collection-growth-monitor.service';
59
- import { DyNTS_MemoryGuard } from '../core/memory-guard.service';
60
- import { DyNTS_RoutingModule } from '../route/routing-module.service';
61
- import { DyNTS_getStarRoute } from '../../_collections/star.controller';
62
-
63
- /**
64
- *
65
- * function MyDecorator(config: any) {
66
- return function (target: Function) {
67
- // attach metadata or modify target
68
- target.prototype.myMeta = config;
69
- };
70
- }
71
-
72
- @MyDecorator({ role: 'admin' })
73
- class User {
74
- printRole() {
75
- console.log((this as any).myMeta.role); // → "admin"
76
- }
77
- }
78
-
79
- */
80
-
81
- /**
82
- * This will be the MAIN service of our server project,
83
- * follow the types and type instructions while setting up your project
84
- *
85
- * In this service, there are abstract functions that you will need to implement,
86
- * where you need to set up the main params for your application.
87
- *
88
- * (after the example, you can find the list of services you can/should setup)
89
- *
90
- * @example
91
- * export class App extends DyNTS_AppExtended {
92
- *
93
- * ...
94
- *
95
- * // Setting up App params, and preparing project global settings
96
- * setupAppParams(): void {
97
- * this.params = new DyNTS_AppParams({
98
- * name: 'Warbots Server',
99
- * title: warbotsTitleLog,
100
- * version: version,
101
- * dbName: 'warbots',
102
- * });
103
- *
104
- * // dynamoNTS_GlobalSettings.logRequestsContent = false;
105
- * }
106
- *
107
- * ...
108
- *
109
- * // Setting up DBServices
110
- * setGlobalServiceCollection(): void {
111
- * DyNTS_GlobalService.setServices({
112
- * authService: AuthService.getInstance(),
113
- * emailServiceCollection: EmailServiceCollectionService.getInstance(),
114
- * dbModels: [
115
- * userModelParams,
116
- * userDataModelParams,
117
- * userOptionsModelParams,
118
- * userStatisticsModelParams,
119
- * userAchievementsModelParams,
120
- * userNotificationsModelParams,
121
- *
122
- * matchStatisticsModelParams,
123
- * matchDataModelParams,
124
-
125
- * DyFM_usageSession_dataParams,
126
- * DyFM_customData_dataParams,
127
- * ]
128
- * });
129
- * }
130
- *
131
- * ...
132
- *
133
- * // Setting up Routes
134
- * setupRoutingModules(): void {
135
- * this.httpPort = env.port;
136
-
137
- * this.routingModules = [
138
- * new DyNTS_RoutingModule({
139
- * route: '/user',
140
- * controllers: [
141
- * UserController.getInstance(),
142
- * UserDataController.getInstance(),
143
- * UserOptionsController.getInstance(),
144
- * UserStatisticsController.getInstance(),
145
- * UserAchievementsController.getInstance(),
146
- * UserNotificationsController.getInstance()
147
- * ]
148
- * }),
149
- * new DyNTS_RoutingModule({
150
- * route: '/match',
151
- * controllers: [
152
- * MatchController.getInstance(),
153
- * MatchDistributionController.getInstance(),
154
- * MatchStatisticsController.getInstance(),
155
- * ]
156
- * }),
157
- * new DyNTS_RoutingModule({
158
- * route: '/server',
159
- * controllers: [
160
- * ServerController.getInstance(),
161
- * ]
162
- * }),
163
-
164
- * getTestRoutingModule(),
165
- * getUsageRoutingModule()
166
- * ];
167
- * }
168
- * }
169
- *
170
- * //
171
- * // The Services available
172
- * //
173
- * // Authentication Service
174
- * // A commonly used basic service,
175
- * // which is necessary fur certain functions (such as registering call issuers)
176
- * //
177
- * // This will handle Authentication Token checking/refreshing,
178
- * // checking issuer's identifier and routeParams,
179
- * // handling JWT Token, or maybe with OAuth2 or other commonly used security procedures
180
- * //
181
- * // You can create one with this Dynamo Object:
182
- * //
183
- *
184
- * @example
185
- * // follow the instructions on the abstract class (DyNTS_AuthService)
186
- * export class AuthService extends DyNTS_AuthService {}
187
- *
188
- *
189
- *
190
- * //
191
- */
192
-
193
- /**
194
- * This will be the MAIN service of our server project,
195
- * follow the types and type instructions while setting up your project
196
- *
197
- * In this service, there are abstract functions that you will need to implement,
198
- * where you need to set up the main params for your application.
199
- *
200
- * (after the example, you can find the list of services you can/should setup)
201
- *
202
- * You need to setup the following functions:
203
- * ```ts
204
- * // this is where you set up the main params for your application
205
- * getAppParams(): DyNTS_AppParams
206
- *
207
- * // this is where you connect your main services
208
- * getGlobalServiceSettings(): DyNTS_GlobalService_Settings
209
- *
210
- * // this is where you set up your ports
211
- * getPorts(): DyNTS_PortSettings
212
- *
213
- * // this is where you set up your routes
214
- * getRoutingModules(): DyNTS_RoutingModule[]
215
- *
216
- *
217
- *
218
- * ```
219
- * optionally you can setup the following functions:
220
- * ```ts
221
- * // this is where you set up your certifications
222
- * getCertificationSettings(): DyNTS_CertificationSettings
223
- *
224
- * // this is where you set up additional root services
225
- * getRootServices(): DyNTS_SingletonService[]
226
- *
227
- * // this is where you set up your initial db entries
228
- * createEntries(): void
229
- *
230
- * // this is where you can define post setup processes
231
- * postProcess(): void
232
- *
233
- *
234
- *
235
- * ```
236
- *
237
- */
238
-
239
- /** FR-258 / SR-2 — one entry from `collection.indexes()` (only the fields the TTL-installer reads). */
240
- export interface DyNTS_TtlIndexInfo {
241
- name?: string;
242
- key?: Record<string, number>;
243
- expireAfterSeconds?: number;
244
- }
245
-
246
- /**
247
- * FR-258 / SR-2 — the minimal native-driver collection surface the TTL-installer needs. Declared
248
- * structurally (not importing mongodb types) so it stays dependency-light and is trivially mockable
249
- * in unit tests.
250
- */
251
- export interface DyNTS_TtlIndexCollection {
252
- indexes?: () => Promise<DyNTS_TtlIndexInfo[]>;
253
- createIndex: (keys: Record<string, number>, options: { expireAfterSeconds: number }) => Promise<unknown>;
254
- dropIndex?: (name: string) => Promise<unknown>;
255
- }
256
-
257
- /**
258
- * FR-258 / SR-2 — outcome of {@link DyNTS_App.ensureRetentionTtlIndex}.
259
- * - `created`: no `__created` TTL index existed → one was created.
260
- * - `noop`: an index with the SAME TTL already existed → nothing done.
261
- * - `differs`: an index exists with a DIFFERENT TTL (or a non-TTL `__created` index) → left UNTOUCHED,
262
- * only a warning is emitted. We deliberately DO NOT drop+recreate at boot: rebuilding a TTL index on a
263
- * multi-GB production collection is a heavy server-side op that can starve concurrent boot queries (e.g.
264
- * the health-probe) and trip a fail-safe deploy revert. A deliberate retention CHANGE must be applied via
265
- * maintenance, not silently at every startup.
266
- */
267
- export type DyNTS_TtlIndexAction = 'created' | 'differs' | 'noop';
268
-
269
- export abstract class DyNTS_App extends DyNTS_SingletonService {
270
-
271
- protected systemControls: DyNTS_AppSystemControls = new DyNTS_AppSystemControls();
272
- get started(): boolean {
273
- return this.systemControls.app.started;
274
- }
275
- protected get superStarted(): boolean {
276
- return this.systemControls.app.started;
277
- }
278
- protected constructErrors: (Error | DyFM_Error)[] = [];
279
-
280
- /* removed since cant use version from package.json
281
- private readonly _ntsVersion: string = 'v01.07.18';
282
- protected get ntsVersion(): string {
283
- return this._ntsVersion;
284
- } */
285
-
286
- get serverName(): string {
287
- return this.params.name;
288
- }
289
-
290
- private _params: DyNTS_App_Params;
291
- protected get params(): DyNTS_App_Params {
292
- return this._params;
293
- }
294
-
295
- protected mongoose = Mongoose;
296
-
297
- private _security: DyNTS_RouteSecurity;
298
- protected get security(): DyNTS_RouteSecurity {
299
- return this._security;
300
- }
301
-
302
- protected _portSettings: DyNTS_Http_Settings = new DyNTS_Http_Settings();
303
- protected get portSettings(): DyNTS_Http_Settings {
304
- return this._portSettings;
305
- }
306
-
307
- private _cert?: DyNTS_Certification_Settings;
308
- protected get cert(): DyNTS_Certification_Settings {
309
- return this._cert;
310
- }
311
-
312
- protected openExpress: Express.Application;
313
- protected secureExpress: Express.Application;
314
- protected httpsServer: Https.Server;
315
- protected httpServer: Http.Server;
316
-
317
- private globalService: DyNTS_GlobalService;
318
- private _rootServices: DyNTS_SingletonService[] = [];
319
-
320
- private _routingModules: DyNTS_RoutingModule[] = [];
321
-
322
- protected readonly defaultReadyTimeout: number = 30 * second;
323
-
324
- override readonly defaultErrorUserMsg =
325
- `We encountered an unhandled Server Error, ` +
326
- `\nplease contact the responsible development team.` +
327
- `\n(Internal Server error)`;
328
-
329
- get logSetup(): boolean {
330
- return DyNTS_global_settings.log_settings.setup;
331
- }
332
- get deepLog(): boolean {
333
- return DyNTS_global_settings.log_settings.deep;
334
- }
335
- get fnLogs(): boolean {
336
- return DyNTS_global_settings.log_settings.functions;
337
- }
338
- debugLog: boolean = DyNTS_global_settings.log_settings.server_debug;
339
-
340
- constructor(/* extended?: boolean */){
341
- super();
342
-
343
- /* dotenv.config() */
344
-
345
- process.on(
346
- 'unhandledRejection',
347
- (reason_theError: object, p_passWhatIsThis_maybeThePromise: any): void => {
348
- if (reason_theError instanceof DyFM_Error) {
349
- reason_theError.logSimple('Unhandled Rejection');
350
- } else {
351
- DyFM_Log.H_error(
352
- 'Unhandled Rejection:', (p_passWhatIsThis_maybeThePromise as Promise<any>)?.toString(),
353
- '\n Rejection reason:', (reason_theError as Error)?.stack?.split('at')?.[0],
354
- /* '\n ErrorCode:', (reason as any)?.code, */
355
- '\n\n Stack:',
356
- (reason_theError as Error)?.stack?.replaceAll?.('\n at', '\n at'),
357
- );
358
- }
359
-
360
- try {
361
- DyNTS_GlobalService.globalErrorHandler?.(
362
- new DyFM_Error({
363
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-BASE-UR`,
364
- message:
365
- `Unhandled Rejection!: "${(reason_theError as Error)?.stack?.split('at')?.[0]}"`,
366
- userMessage: this.defaultErrorUserMsg,
367
- addECToUserMsg: true,
368
- error: reason_theError as Error,
369
- additionalContent: {
370
- reason: reason_theError,
371
- rejectedPromise: p_passWhatIsThis_maybeThePromise,
372
- },
373
- systemVersion: DyNTS_global_settings.systemVersion,
374
- level: DyFM_ErrorLevel.critical,
375
- })
376
- );
377
- } catch (error) {
378
- DyFM_Log.error('globalErrorHandler (MULTILEVEL) ERROR:', error);
379
- }
380
- }
381
- );
382
-
383
- this.asyncConstruct(/* extended */).catch((error: any): void => {
384
- if (error instanceof DyFM_Error) {
385
- if (error.additionalContent?.constructErrors?.length) {
386
- error.additionalContent.constructErrors.forEach((errorItem: DyFM_Error): void => {
387
- DyFM_Error.logSimple('(constructor asyncConstruct.catch) error:', errorItem);
388
- /* if (errorItem instanceof DyFM_Error) {
389
- errorItem.logSimple(`(constructor asyncConstruct.catch) error:\n`);
390
- } else {
391
- DyFM_Log.H_warn(
392
- '(constructor asyncConstruct.catch) additional error content:\n',
393
- errorItem
394
- );
395
- } */
396
- });
397
- } else {
398
- DyFM_Log.H_warn(
399
- '(constructor asyncConstruct.catch) additional error content:\n',
400
- error?.additionalContent
401
- );
402
- }
403
- }
404
-
405
- DyFM_Error.logSimple('(constructor asyncConstruct.catch) error:', error);
406
- /* if (
407
- !DyNTS_global_settings.log_settings.highDetailedLogs &&
408
- (error instanceof DyFM_Error)
409
- ) {
410
- error.logSimple(
411
- `Application: "${this.params?.name}" start failed. (constructor asyncConstruct.catch)` +
412
- '\n all error messages (from this stack):\n\n"' +
413
- error._messages.join('"\n\n"') + '"\n\n'
414
- );
415
- } else if (error instanceof DyFM_Error) {
416
- DyFM_Log.H_error(
417
- `Application: "${this.params?.name}" start failed. (constructor asyncConstruct.catch)`,
418
- `\n ERROR:`, error
419
- );
420
- } */
421
-
422
- const message: string =
423
- (error as DyFM_Error)?.additionalContent?.constructErrors?.flatMap(
424
- (errorItem: DyFM_Error): string[] => {
425
- return errorItem?._messages ?? [];
426
- }
427
- )?.join?.('\n') ??
428
- (error as DyFM_Error)?.errors?.flatMap(
429
- (errorItem: DyFM_AnyError): string[] =>
430
- (errorItem as DyFM_Error)?._messages ?? [ (errorItem as Error)?.message ]
431
- )?.join?.('\n') ??
432
- error?.message ??
433
- 'UNKNOWN';
434
-
435
- DyFM_Log.testError('Application start failed:\n', message);
436
-
437
- process.exit(1);
438
- });
439
- }
440
-
441
- protected async asyncConstruct(extended?: boolean): Promise<void> {
442
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. asyncConstruct');
443
-
444
- try {
445
- this.systemControls.app.init = true;
446
- this._params = this.getAppParams();
447
- DyFM_Log.log(
448
- `\n\n\n\n\n\n\n\n\n\n` +
449
- `Starting ${this._params?.name}... ` +
450
- /* `v${version}` + */
451
- `\n\n\n\n\n\n\n\n\n\n`
452
- );
453
-
454
- if (!this._params) {
455
- throw new Error('getAppParams() must return a DyNTS_AppParams object!');
456
- }
457
-
458
- if (this.params.systemShortCodeName) {
459
- DyNTS_global_settings.systemShortCodeName = this.params.systemShortCodeName;
460
- }
461
-
462
- if (this.params.systemName) {
463
- DyNTS_global_settings.systemName = this.params.systemName;
464
- DyFM_error_defaults.issuerSystem = this.params.systemName;
465
- }
466
-
467
- if (this.params.version) {
468
- DyNTS_global_settings.systemVersion = this.params.version;
469
- DyFM_error_defaults.systemVersion = this.params.version;
470
- }
471
-
472
- process.stdout.write(
473
- String.fromCharCode(27) + ']0;' +
474
- this._params?.name +
475
- String.fromCharCode(7)
476
- );
477
-
478
- DyFM_error_defaults.issuerSystem = this._params.systemName;
479
-
480
- this.overrideDynamoNTSGlobalSettings?.();
481
-
482
- if (DyNTS_global_settings.log_settings.setup) {
483
- DyFM_Log.S_info(`env settings;\n`, {
484
- systemName: DyNTS_global_settings.systemName,
485
- systemShortCodeName: DyNTS_global_settings.systemShortCodeName,
486
- systemVersion: DyNTS_global_settings.systemVersion,
487
- environment: DyNTS_global_settings.env_settings.environment,
488
- /* log_settings: DyNTS_global_settings.log_settings,
489
- env_settings: DyNTS_global_settings.env_settings, */
490
- });
491
- }
492
-
493
- this.globalService = DyNTS_GlobalService.getInstance();
494
- await DyNTS_GlobalService.setServices(this.getGlobalServiceCollection());
495
- DyNTS_GlobalService.setParams(this.params);
496
-
497
- if (this.getPortSettings) {
498
- this._portSettings = this.getPortSettings();
499
- }
500
-
501
- if (this.getCertificationSettings) {
502
- this._cert = this.getCertificationSettings();
503
- }
504
-
505
- if (this.getApiBasePath) {
506
- DyNTS_global_settings.baseUrl = this.getApiBasePath();
507
- }
508
-
509
- if (this.getRoutingModules) {
510
- this._routingModules = this.getRoutingModules();
511
-
512
- // ezt egyelőre csak tesztelem, nem kerül be
513
- /* if (
514
- !DyNTS_global_settings.dontCreateDefaultRoute &&
515
- !this._routingModules.some((routingModule: DyNTS_RoutingModule): boolean => routingModule.route === '/*')
516
- ) {
517
- this._routingModules.push(
518
- DyNTS_getStarRoute()
519
- );
520
- } */
521
- }
522
-
523
- if (this._params.dbUri) {
524
- await this.startDB();
525
-
526
- // createEntries csak akkor fut, ha a DB tényleg fel-jött.
527
- // Ha a startDB jelezte a hibát, de továbbment, akkor a started flag false marad,
528
- // és nem próbálunk meg írni egy nem létező kapcsolatra.
529
- if (this.createEntries && this.systemControls.mongoose.started) {
530
- await this.createEntries();
531
- }
532
- } else {
533
- DyFM_Log.log(
534
- `\nNo database connection created.`,
535
- );
536
- }
537
-
538
- if (this._routingModules?.length) {
539
- if (this.logSetup) DyFM_Log.log('\nsetting up express routes...');
540
-
541
- this.setSecurity();
542
-
543
- await this.initExpresses();
544
- await this.startExpresses();
545
-
546
- if (this._security !== DyNTS_RouteSecurity.secure) {
547
- await this.mountOpenRoutes();
548
- }
549
-
550
- if (this._security !== DyNTS_RouteSecurity.open && this._cert) {
551
- await this.mountSecureRoutes();
552
- }
553
-
554
- // Generikus, auth-agnosztikus extension-point: custom middleware az API
555
- // route-ok UTÁN, de a SPA static catch-all (mountStaticClient) ELŐTT.
556
- await this.mountCustomMiddleware();
557
-
558
- await this.mountStaticClient();
559
-
560
- if (this.logSetup) {
561
- DyFM_Log.log(`\nRoutes mounted.... server using security: ${this._security}`);
562
- }
563
- } else {
564
- DyFM_Log.warn(
565
- `\nNo routes mounted!`,
566
- );
567
- }
568
-
569
- if (this.getRootServices) {
570
- this._rootServices = await this.getRootServices();
571
- }
572
-
573
- if (this.postProcess) {
574
- await this.postProcess().catch((error: any): void => {
575
- DyFM_Error.logSimple(`"${this._params.name}" postProcess failed:`, error);
576
- DyNTS_GlobalService.globalErrorHandler?.(error);
577
- });
578
- }
579
-
580
- // FR-193 — bedrock OOM korai-figyelmeztetés: feltelepítjük a heap-watchdogot, ha
581
- // engedélyezve (DyNTS_global_settings.memoryGuard.enabled, default true). Biztonságos:
582
- // a guard egy könnyű setInterval, ami SOHA nem dob; csak near-OOM küszöböknél hagy
583
- // tartós nyomot az error-sinkbe, mielőtt a fatal heap-OOM megölné a process-t.
584
- try {
585
- if (DyNTS_global_settings.memoryGuard?.enabled) {
586
- DyNTS_MemoryGuard.getInstance().install();
587
- }
588
- } catch (memoryGuardError: unknown) {
589
- DyFM_Log.warn('[DyNTS_MemoryGuard] auto-install skipped (non-fatal):', memoryGuardError);
590
- }
591
-
592
- // FR-258 / SR-4 — proactive collection-growth monitor (companion to the MemoryGuard). Warns
593
- // into the Errors-sink when a collection grows unbounded, BEFORE it can be loaded into heap and
594
- // OOM. Default-on, observation-only, never throws.
595
- try {
596
- if (DyNTS_global_settings.collectionGrowthMonitor?.enabled) {
597
- DyNTS_CollectionGrowthMonitor.getInstance().install();
598
- }
599
- } catch (cgmError: unknown) {
600
- DyFM_Log.warn('[DyNTS_CollectionGrowthMonitor] auto-install skipped (non-fatal):', cgmError);
601
- }
602
-
603
- if (!extended) {
604
- await this.ready();
605
-
606
- if (this.params.title) {
607
- DyFM_Log.success(this.params.title);
608
- }
609
- DyFM_Log.info(`Version: ${this.params.version}`);
610
- /* DyFM_Log.info(`NTS Version: ${this.ntsVersion}`); */
611
- DyFM_Log.H_success(`${this.params.name} started successfully.`);
612
- }
613
- } catch (error) {
614
- this.constructErrors.push(error);
615
-
616
- if (this.deepLog) {
617
- if (DyNTS_global_settings.log_settings.highDetailedLogs) {
618
- DyFM_Log.H_error(
619
- `"${this._params.name}" start failed (in asyncConstruct (highDetailedLog)). `,
620
- `\n\n construct ERRORS:`, this.constructErrors,
621
- '\n\nlast error:', error
622
- );
623
- } else {
624
- DyFM_Log.H_error(
625
- `"${this._params.name}" start failed (in asyncConstruct). `,
626
- `\n\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
627
- '\n\nlast error:', error instanceof DyFM_Error ? error.getErrorSimplified() : error
628
- );
629
- }
630
- }
631
-
632
- throw new DyFM_Error({
633
- ...this._getDefaultErrorSettings('asyncConstruct', error),
634
-
635
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-001`,
636
- additionalContent: {
637
- constructErrors: this.constructErrors,
638
- systemControls: this.systemControls,
639
- systemReadies: {
640
- app: this.systemControls.app.getIsReady(),
641
- mongoose: this.systemControls.mongoose.getIsReady(),
642
- httpServer: this.systemControls.httpServer.getIsReady(),
643
- httpsServer: this.systemControls.httpsServer.getIsReady(),
644
- },
645
- },
646
- });
647
- }
648
- }
649
-
650
- async ready(timeout: number = this.defaultReadyTimeout): Promise<void> {
651
- try {
652
- if (this.fnLogs) DyFM_Log.log('\nfn:. ready');
653
-
654
- await DyFM_Async.delay(100);
655
-
656
- let ready: boolean = false;
657
- const start: number = +new Date();
658
-
659
- if (this.constructErrors.length) {
660
- if (this.deepLog) {
661
- if (DyNTS_global_settings.log_settings.highDetailedLogs) {
662
- DyFM_Log.H_error(
663
- `"${this._params.name}" start failed. (ready; constructErrors check 1)`,
664
- `\n construct ERRORS:`, this.constructErrors
665
- );
666
- } else {
667
- DyFM_Log.H_error(
668
- `"${this._params.name}" start failed. (ready; constructErrors check 1)`,
669
- `\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
670
- );
671
- }
672
- }
673
-
674
- throw new DyFM_Error({
675
- ...this._getDefaultErrorSettings(
676
- 'ready',
677
- new Error(`"${this._params.name}" start failed.`)
678
- ),
679
-
680
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R01`,
681
- additionalContent:
682
- this.constructErrors.length === 1 ?
683
- { error: this.constructErrors[0] } :
684
- { errors: this.constructErrors },
685
- });
686
- }
687
-
688
- while (!ready && +new Date() - start < timeout) {
689
- if (this.systemControls.app.init) {
690
- ready = (
691
- this.systemControls.mongoose.getIsReady() &&
692
- this.systemControls.httpServer.getIsReady() &&
693
- this.systemControls.httpsServer.getIsReady()
694
- );
695
- } else {
696
- DyFM_Log.error(`"${this._params.name}" APP NOT INITIALIZED while trying to get ready.`);
697
- }
698
-
699
- if (!ready) {
700
- await DyFM_Async.wait(100);
701
- }
702
- }
703
-
704
- if (timeout < +new Date() - start) {
705
- if (this.deepLog) {
706
- if (DyNTS_global_settings.log_settings.highDetailedLogs) {
707
- DyFM_Log.H_error(
708
- `"${this._params.name}" start failed. (ready; TIMEOUT check)`,
709
- `\n construct ERRORS:`, this.constructErrors
710
- );
711
- } else {
712
- DyFM_Log.H_error(
713
- `"${this._params.name}" start failed. (ready; TIMEOUT check)`,
714
- `\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
715
- );
716
- }
717
- }
718
-
719
- throw new DyFM_Error({
720
- ...this._getDefaultErrorSettings(
721
- 'ready',
722
- new Error(`"${this._params.name}" start failed. TIMEOUT`)
723
- ),
724
-
725
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R02`,
726
- additionalContent: {
727
- constructErrors: this.constructErrors,
728
- systemControls: this.systemControls,
729
- systemReadies: {
730
- mongoose: this.systemControls.mongoose.getIsReady(),
731
- httpServer: this.systemControls.httpServer.getIsReady(),
732
- httpsServer: this.systemControls.httpsServer.getIsReady(),
733
- },
734
- },
735
- });
736
- }
737
-
738
- if (this.constructErrors.length) {
739
- if (this.deepLog) {
740
- if (DyNTS_global_settings.log_settings.highDetailedLogs) {
741
- DyFM_Log.H_error(
742
- `"${this._params.name}" start failed. (ready; constructErrors check 2)`,
743
- `\n construct ERRORS:`, this.constructErrors
744
- );
745
- } else {
746
- DyFM_Log.H_error(
747
- `"${this._params.name}" start failed. (ready; constructErrors check 2)`,
748
- `\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
749
- );
750
- }
751
- }
752
-
753
- throw new DyFM_Error({
754
- ...this._getDefaultErrorSettings(
755
- 'ready',
756
- new Error(`"${this._params.name}" start failed.`)
757
- ),
758
-
759
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R03`,
760
- additionalContent: this.constructErrors,
761
- });
762
- }
763
-
764
- if (ready) {
765
- this.systemControls.app.started = true;
766
-
767
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. ready: return');
768
-
769
- return;
770
- }
771
-
772
- this.systemControls.app.started = false;
773
-
774
- let msg: string = `"${this._params.name}" start failed. UNKNOWN`;
775
-
776
- if (this.systemControls.mongoose.init && !this.systemControls.mongoose.started) {
777
- msg += `\nMongoose start failed.`;
778
- }
779
-
780
- if (this.systemControls.httpServer.init && !this.systemControls.httpServer.started) {
781
- msg += `\nHTTP Server start failed.`;
782
- }
783
-
784
- if (this.systemControls.httpsServer.init && !this.systemControls.httpsServer.started) {
785
- msg += `\nHTTPS Server start failed.`;
786
- }
787
-
788
- DyFM_Log.error(msg, this.constructErrors);
789
-
790
- throw new DyFM_Error({
791
- ...this._getDefaultErrorSettings('ready', new Error(msg)),
792
-
793
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R04`,
794
- additionalContent: {
795
- constructErrors: this.constructErrors,
796
- systemControls: this.systemControls,
797
- systemReadies: {
798
- app: this.systemControls.app.getIsReady(),
799
- mongoose: this.systemControls.mongoose.getIsReady(),
800
- httpServer: this.systemControls.httpServer.getIsReady(),
801
- httpsServer: this.systemControls.httpsServer.getIsReady(),
802
- },
803
- },
804
- error: this.constructErrors?.[0] ?? new Error(),
805
- });
806
- } catch (error) {
807
- throw new DyFM_Error({
808
- ...this._getDefaultErrorSettings('ready', error),
809
-
810
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-READY0`,
811
- });
812
- }
813
- }
814
-
815
- protected getSimplifiedConstructErrors(): string[] {
816
- return this.constructErrors.map((error: any): any => {
817
- if (error instanceof DyFM_Error) {
818
- return error.getErrorSimplified();
819
- } else {
820
- return error;
821
- }
822
- });
823
- }
824
-
825
- async stop(dontLog?: boolean): Promise<void> {
826
- try {
827
- DyFM_Log.info('\nstopping server...\n');
828
-
829
- await this.ready();
830
-
831
- if (this.started) {
832
-
833
- if (this.systemControls.mongoose.init) {
834
- DyFM_Log.info(`\nstopping Mongoose....`);
835
-
836
- let tryCount: number = 0;
837
-
838
- while (
839
- !this.systemControls.mongoose.started &&
840
- !this.constructErrors.length &&
841
- tryCount++ < 10
842
- ) {
843
- DyFM_Log.warn(`Mongoose not even started yet....`);
844
- await DyFM_Async.wait(second);
845
- }
846
- this.systemControls.mongoose.started = false;
847
-
848
- if (this.mongoose) {
849
- await DyFM_Array.asyncForEach(
850
- Object.keys(this.mongoose.models),
851
- async (modelName): Promise<void> => {
852
- this.mongoose.deleteModel(modelName);
853
- }
854
- );
855
-
856
- const disconnect: Promise<void> = new Promise((resolve): void => {
857
- this.mongoose.connection.on('disconnecting', (): void => {
858
- resolve();
859
- });
860
- });
861
-
862
- await this.mongoose.disconnect();
863
- await this.mongoose.connection.close();
864
- await disconnect;
865
-
866
- this.mongoose.connection.removeAllListeners();
867
-
868
- while (
869
- this.mongoose.connection.readyState !== 0 &&
870
- !this.constructErrors.length
871
- ) {
872
- DyFM_Log.warn(`\nMongoose still not disconnected....`);
873
- await DyFM_Async.wait(second);
874
- }
875
- } else {
876
- DyFM_Log.error(`\nMongoose not found.`);
877
- }
878
- this.systemControls.mongoose.init = false;
879
- }
880
-
881
- if (this.systemControls.httpServer.init) {
882
- this.systemControls.httpServer.started = false;
883
-
884
- if (this.httpServer) {
885
- await new Promise((resolve): void => {
886
- this.httpServer.close(resolve);
887
- });
888
- } else {
889
- DyFM_Log.error(`\nHTTP Server not found.`);
890
- }
891
- this.systemControls.httpServer.init = false;
892
- }
893
-
894
- if (this.systemControls.httpsServer.init) {
895
- this.systemControls.httpsServer.started = false;
896
-
897
- if (this.httpsServer) {
898
- await new Promise((resolve): void => {
899
- this.httpsServer.close(resolve);
900
- });
901
- } else {
902
- DyFM_Log.error(`\nHTTPS Server not found.`);
903
- }
904
- this.systemControls.httpsServer.init = false;
905
- }
906
-
907
- await DyFM_Async.wait(second);
908
-
909
- if (!dontLog) {
910
- DyFM_Log.H_log(`"${this._params.name}" stopped successfully.`);
911
- }
912
- }
913
- } catch (error) {
914
- throw new DyFM_Error({
915
- ...this._getDefaultErrorSettings('stop', error),
916
-
917
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-STOP0`,
918
- });
919
- }
920
- }
921
-
922
- /**
923
- *
924
- */
925
- private async startDB(): Promise<void> {
926
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. startDB');
927
- else if (this.logSetup) DyFM_Log.log('\nstarting DB connection...');
928
-
929
- if (!this._params.dbUri) {
930
- throw new DyFM_Error({
931
- ...this._getDefaultErrorSettings('startDB', new Error('DB URI is not set.')),
932
-
933
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
934
- });
935
- }
936
-
937
- if (!this._params.dbOptions) {
938
- throw new DyFM_Error({
939
- ...this._getDefaultErrorSettings('startDB', new Error('DB OPTIONS are not set.')),
940
-
941
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
942
- });
943
- }
944
-
945
- if (this.systemControls.mongoose.init || this.systemControls.mongoose.started) {
946
- throw new DyFM_Error({
947
- ...this._getDefaultErrorSettings('startDB', new Error('Mongoose is already initialized.')),
948
-
949
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
950
- });
951
- }
952
-
953
- try {
954
- await new Promise<void>(
955
- (resolve, reject): void => {
956
- this.systemControls.mongoose.init = true;
957
-
958
- this.mongoose.connection
959
- .once('open', (): void => {
960
- this.systemControls.mongoose.started = true;
961
- DyFM_Log.success(`\nConnected to MongoDB (${this._params.dbUri})\n`);
962
-
963
- resolve();
964
-
965
- // FR-258 / SR-2 — install declared-retention TTL indexes. DEFERRED + fire-and-forget +
966
- // fully non-fatal: a create-if-missing index op (and the `indexes()` probes) must NOT
967
- // compete with boot-readiness. We delay it well past the deploy health-probe window so a
968
- // cold boot is never slowed by it, then run it detached. `.unref()` keeps it from holding
969
- // the event loop open. Any failure is logged but never crashes the app. (`'differs'` never
970
- // rebuilds a live index — see ensureRetentionTtlIndex.)
971
- const ttlInstallTimer: ReturnType<typeof setTimeout> = setTimeout((): void => {
972
- void this.installRetentionTtlIndexes();
973
- }, 30000);
974
- if (typeof ttlInstallTimer.unref === 'function') { ttlInstallTimer.unref(); }
975
- })
976
- .on('error', (error): void => {
977
- if (!this.systemControls.mongoose.started) {
978
- // Initial DB-csatlakozás sikertelen:
979
- // jelezzük a hibát (log + globalErrorHandler), de NEM szakítjuk meg az
980
- // App startup-ot (nincs constructErrors push, nincs reject).
981
- // A mongoose.init-et resetteljük, hogy a ready() ne várjon a DB-re.
982
- // Ha a mongoose később mégis tudna csatlakozni, az 'open' event
983
- // beállítja a started flag-et, így a runtime DB-műveletek elindulnak.
984
- this.systemControls.mongoose.init = false;
985
-
986
- const d_error: DyFM_Error = new DyFM_Error({
987
- ...this._getDefaultErrorSettings('startDB', error),
988
-
989
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB1`,
990
- message: `Unable to connect to MongoDB server (${this._params.dbUri}), ` +
991
- `ERROR: ${error}`,
992
- level: DyFM_ErrorLevel.serious,
993
- });
994
-
995
- DyFM_Log.H_error(
996
- `\nUnable to connect to MongoDB server (${this._params.dbUri}).` +
997
- `\nServer will continue WITHOUT DB connection.` +
998
- `\nDB-using endpoints will fail at runtime until connection recovers.`
999
- );
1000
-
1001
- if (this.debugLog) DyFM_Log.S_error(
1002
- `\nMongoDB connect ERROR: `,
1003
- error
1004
- );
1005
-
1006
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1007
-
1008
- resolve();
1009
-
1010
- } else {
1011
- if (this.debugLog) DyFM_Log.error('\nMongoDB ERROR: ', error);
1012
-
1013
- const d_error: DyFM_Error = new DyFM_Error({
1014
- ...this._getDefaultErrorSettings('mongoose.connection.on(error)', error),
1015
-
1016
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB2`,
1017
- message: `MongoDB ERROR: ${error}`,
1018
- level: DyFM_ErrorLevel.critical,
1019
- });
1020
-
1021
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1022
- }
1023
- });
1024
-
1025
- try {
1026
- this.mongoose.connect(
1027
- this._params.dbUri,
1028
- this._params.dbOptions
1029
- /* {
1030
- directConnection: true,
1031
- } */
1032
- );
1033
- } catch (error) {
1034
- throw new DyFM_Error({
1035
- ...this._getDefaultErrorSettings('startDB', error),
1036
-
1037
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB3`,
1038
- });
1039
- }
1040
- }
1041
- );
1042
- } catch (error) {
1043
- throw new DyFM_Error({
1044
- ...this._getDefaultErrorSettings('startDB', error),
1045
-
1046
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
1047
- });
1048
- }
1049
-
1050
- // 2026-06-20 — Mongo reconnect-guard. A MongoDB-driver a hostnevet connect-kor EGYSZER
1051
- // resolválja + cache-eli az IP-t; ha a Mongo-konténert recreate-elik (új docker-network IP),
1052
- // a driver a HALOTT IP-n ragad → ECONNREFUSED + buffering-timeout, és a service magától SOHA
1053
- // nem áll vissza. A guard sustained-disconnect (readyState !== 1) esetén — a driver saját
1054
- // grace-e UTÁN — TELJES disconnect()+connect()-et csinál → ÚJ MongoClient → ÚJ DNS-resolve →
1055
- // új IP → reconnect. Best-effort, always-on, healthy connection-t (===1) SOHA nem bánt; csak
1056
- // konténer-IP-frissítés, nem ír adatot. Lásd: mongo-reconnect-guard.util.ts.
1057
- try {
1058
- startMongoReconnectGuard({
1059
- getReadyState: (): number => this.mongoose.connection.readyState,
1060
- reconnect: async (): Promise<void> => {
1061
- await this.mongoose.disconnect().catch((): void => undefined);
1062
- await this.mongoose.connect(this._params.dbUri, this._params.dbOptions);
1063
- },
1064
- log: (msg: string): void => DyFM_Log.warn(msg),
1065
- });
1066
- } catch (guardErr) {
1067
- DyFM_Log.warn(`[mongo-reconnect-guard] failed to start (non-fatal): ${guardErr instanceof Error ? guardErr.message : String(guardErr)}`);
1068
- }
1069
- }
1070
-
1071
- /**
1072
- * FR-258 / SR-2 — install MongoDB TTL indexes for every data-model that declared `retention`.
1073
- *
1074
- * Runs ONCE right after the DB connection opens. For each registered DB service (including the
1075
- * auto-created `_archived` siblings, which inherit the parent model's `retention`), it ensures a
1076
- * TTL index on the `__created` Date field with the resolved `expireAfterSeconds` — so MongoDB
1077
- * NATIVELY auto-deletes documents older than the configured age. This is the fleet-wide defense
1078
- * against the unbounded-collection-growth → in-memory-load → GC-thrash/OOM class.
1079
- *
1080
- * Guarantees:
1081
- * - **Non-fatal** — any error is logged but NEVER blocks startup (called fire-and-forget).
1082
- * - **Idempotent** — an existing index with the same TTL is a no-op; a CHANGED retention (different
1083
- * `expireAfterSeconds`, or an existing non-TTL `__created` index) is reconciled by drop+recreate
1084
- * (the field index is restored immediately, so query coverage is preserved).
1085
- */
1086
- private async installRetentionTtlIndexes(): Promise<void> {
1087
- try {
1088
- const services: DyNTS_DBService<any>[] = DyNTS_GlobalService.getAllDBServices();
1089
- let ensured: number = 0;
1090
-
1091
- for (const service of services) {
1092
- const ttlSeconds: number | undefined = DyFM_resolveRetentionTtlSeconds(service?.dataParams?.retention);
1093
- if (!ttlSeconds) { continue; }
1094
-
1095
- const dataName: string = service.dataParams.dataName;
1096
- // The mongoose Model exposes the native driver collection (.indexes / .createIndex / .dropIndex).
1097
- const collection: DyNTS_TtlIndexCollection | undefined =
1098
- (service?.dataModel as unknown as { collection?: DyNTS_TtlIndexCollection })?.collection;
1099
- if (!collection || typeof collection.createIndex !== 'function') { continue; }
1100
-
1101
- try {
1102
- const action: DyNTS_TtlIndexAction = await DyNTS_App.ensureRetentionTtlIndex(collection, ttlSeconds);
1103
- if (action === 'created') {
1104
- ensured++;
1105
- if (this.logSetup) {
1106
- DyFM_Log.success(
1107
- `[FR-258 retention] TTL index created on "${dataName}" — ` +
1108
- `${Math.round(ttlSeconds / 86400)}d (${ttlSeconds}s)`,
1109
- );
1110
- }
1111
- } else if (action === 'differs') {
1112
- // Live index has a different TTL — left untouched at boot (see ensureRetentionTtlIndex doc).
1113
- DyFM_Log.warn(
1114
- `[FR-258 retention] "${dataName}" already has a {__created} index with a DIFFERENT TTL than the ` +
1115
- `declared ${Math.round(ttlSeconds / 86400)}d (${ttlSeconds}s) — left as-is (no boot-time rebuild). ` +
1116
- `Apply the change via maintenance if intended.`,
1117
- );
1118
- }
1119
- } catch (idxErr: unknown) {
1120
- DyFM_Log.warn(
1121
- `[FR-258 retention] TTL index on "${dataName}" failed (non-fatal): ` +
1122
- `${idxErr instanceof Error ? idxErr.message : String(idxErr)}`,
1123
- );
1124
- }
1125
- }
1126
-
1127
- if (ensured > 0) {
1128
- DyFM_Log.success(`[FR-258 retention] ${ensured} TTL index(es) ensured (auto-retention active).`);
1129
- }
1130
- } catch (err: unknown) {
1131
- DyFM_Log.warn(
1132
- `[FR-258 retention] TTL-installer failed (non-fatal): ` +
1133
- `${err instanceof Error ? err.message : String(err)}`,
1134
- );
1135
- }
1136
- }
1137
-
1138
- /**
1139
- * FR-258 / SR-2 — ensure a single `{ __created: 1 }` TTL index with the given `expireAfterSeconds`.
1140
- * Extracted as a pure-ish static so it is unit-testable with a mock collection. Idempotent + BOOT-SAFE:
1141
- * - no existing `__created` index → create it → `'created'`
1142
- * - existing with the SAME TTL → no-op → `'noop'`
1143
- * - existing with a DIFFERENT TTL / non-TTL → leave it as-is → `'differs'` (warn only — NO drop+recreate)
1144
- *
1145
- * The `'differs'` case intentionally does NOT mutate the live index. Dropping + recreating a TTL index on a
1146
- * large (multi-GB) production collection is a heavy server-side operation; doing it automatically inside the
1147
- * startup path can starve the concurrent boot queries (including the deploy health-probe) and trigger a
1148
- * fail-safe revert. Create-if-missing is the essential growth-prevention behaviour; a deliberate retention
1149
- * CHANGE on an already-indexed collection is a maintenance action, not a silent every-boot rebuild.
1150
- */
1151
- static async ensureRetentionTtlIndex(
1152
- collection: DyNTS_TtlIndexCollection,
1153
- ttlSeconds: number,
1154
- ): Promise<DyNTS_TtlIndexAction> {
1155
- const existingList: DyNTS_TtlIndexInfo[] = typeof collection.indexes === 'function'
1156
- ? await collection.indexes().catch((): DyNTS_TtlIndexInfo[] => [])
1157
- : [];
1158
- const existing: DyNTS_TtlIndexInfo | undefined =
1159
- existingList.find((ix): boolean => !!ix?.key && ix.key.__created === 1);
1160
-
1161
- if (!existing) {
1162
- await collection.createIndex({ __created: 1 }, { expireAfterSeconds: ttlSeconds });
1163
- return 'created';
1164
- }
1165
- if (existing.expireAfterSeconds === ttlSeconds) {
1166
- return 'noop';
1167
- }
1168
- // Retention differs from the live index (or it is a non-TTL `__created` index). Leave it UNTOUCHED at
1169
- // boot — only report it. Avoids a heavy drop+recreate competing with boot-readiness on a large collection.
1170
- return 'differs';
1171
- }
1172
-
1173
- /**
1174
- *
1175
- */
1176
- private async initExpresses(): Promise<void> {
1177
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. initExpresses');
1178
-
1179
- try {
1180
- if (this._security && this._security !== DyNTS_RouteSecurity.secure) {
1181
- if (this._portSettings.httpPort === undefined || this._portSettings.httpPort === null) {
1182
- let errorMsg: string =
1183
- `\nYou have open routes, but httpPort is not set!` +
1184
- `\nThere are ${this._routingModules.filter(
1185
- m => m.security != DyNTS_RouteSecurity.secure
1186
- ).length} open/both routes` +
1187
- `\nroot security: ${this._security}` +
1188
- `\nset httpPort in DynamoBEServer - setupRoutingModules() to enable secure routes.`;
1189
-
1190
- errorMsg += '\n\nThe routes setted to use open server:';
1191
- this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1192
- if (module.security != DyNTS_RouteSecurity.secure) {
1193
- errorMsg += `\n ${module.route} (security: ${module.security})`;
1194
- errorMsg += `\n subroutes using open sever:`;
1195
- module.endpoints.forEach((endpoint: DyNTS_Endpoint_Params): void => {
1196
- if (endpoint.security != DyNTS_RouteSecurity.secure) {
1197
- errorMsg += `\n ${endpoint.endpoint} (security: ${endpoint.security})`;
1198
- }
1199
- });
1200
- }
1201
- });
1202
-
1203
- const error = new Error(`Open routes cannot be established!\n${errorMsg}`);
1204
- const errorStack: string[] = error.stack.split('\n');
1205
-
1206
- errorStack.splice(1, 2);
1207
- error.stack = errorStack.join('\n');
1208
-
1209
- DyFM_Log.error(errorMsg);
1210
-
1211
- throw error;
1212
- }
1213
-
1214
- await this.initOpenExpress();
1215
- }
1216
-
1217
- if (this._security && this._security !== DyNTS_RouteSecurity.open) {
1218
- if (!this._cert || !this._portSettings.httpsPort) {
1219
- let errorMsg: string =
1220
- `\nYou have secure routes, but the certification paths or httpsPort are not set!` +
1221
- `\nThere are ${this._routingModules.filter(
1222
- m => m.security && m.security !== DyNTS_RouteSecurity.open
1223
- ).length} secure routes` +
1224
- `\nroot security: ${this._security}` +
1225
- `\nset...` +
1226
- `\n(missing exact howto...)` +
1227
- /* `\n httpsPort and` +
1228
- `\n cert: {` +
1229
- `\n keyPath: FileSystem.PathLike,` +
1230
- `\n certPath: FileSystem.PathLike,` +
1231
- `\n }` + */
1232
- `\nin DynamoBEServer - getRoutingModules() to enable secure routes.`;
1233
-
1234
- errorMsg += '\n\nThe routes setted to use secure server:';
1235
- this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1236
- if (module.security && module.security !== DyNTS_RouteSecurity.open) {
1237
- errorMsg += `\n ${module.route} (security: ${module.security})`;
1238
- errorMsg += `\n location: ${module.stackLocation}`;
1239
- errorMsg += `\n subroutes using secure sever:`;
1240
- module.endpoints.forEach((endpoint: DyNTS_Endpoint_Params): void => {
1241
- if (endpoint.security && endpoint.security !== DyNTS_RouteSecurity.open) {
1242
- errorMsg += `\n ${endpoint.endpoint} (security: ${endpoint.security})`;
1243
- errorMsg += `\n location: ${endpoint.stackLocation}`;
1244
- }
1245
- });
1246
- }
1247
- });
1248
-
1249
- const error = new Error(`Secure routes cannot be established!\n${errorMsg}`);
1250
- const errorStack: string[] = error.stack.split('\n');
1251
-
1252
- errorStack.splice(1, 2);
1253
- error.stack = errorStack.join('\n');
1254
-
1255
- DyFM_Log.error(errorMsg);
1256
-
1257
- throw error;
1258
- }
1259
-
1260
- await this.initSecureExpress();
1261
- }
1262
- } catch (error) {
1263
- throw new DyFM_Error({
1264
- ...this._getDefaultErrorSettings('initExpresses', error),
1265
-
1266
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-IE0`,
1267
- });
1268
- }
1269
- }
1270
-
1271
- /**
1272
- *
1273
- */
1274
- protected async initOpenExpress(): Promise<void> {
1275
- if (this.fnLogs) DyFM_Log.log('\nfn:. initOpenExpress');
1276
- this.openExpress = Express();
1277
- this.openExpress.set('maxHeaderSize', 10 * megabyte); // 1024 * 1024 * 10, // 10MB
1278
- this.openExpress.use(BodyParser.urlencoded(this._portSettings.httpUrlencoded));
1279
- this.openExpress.use(BodyParser.json(this._portSettings.httpJson));
1280
- // FR-041 — CORS allowlist enforcement. No-op if getCorsSettings() is not overridden.
1281
- this.mountCors(this.openExpress);
1282
- }
1283
-
1284
- /**
1285
- *
1286
- */
1287
- protected async initSecureExpress(): Promise<void> {
1288
- if (this.fnLogs) DyFM_Log.log('\nfn:. initSecureExpress');
1289
- this.secureExpress = Express();
1290
- this.secureExpress.use(BodyParser.urlencoded(this._portSettings.httpsUrlencoded));
1291
- this.secureExpress.use(BodyParser.json(this._portSettings.httpsJson));
1292
- // FR-041 — CORS allowlist enforcement (same as open express).
1293
- this.mountCors(this.secureExpress);
1294
-
1295
- const options = {
1296
- key: FileSystem.readFileSync(this._cert.keyPath),
1297
- cert: FileSystem.readFileSync(this._cert.certPath),
1298
- maxHeaderSize: 10 * megabyte, // 1024 * 1024 * 10, // 10MB
1299
- };
1300
-
1301
- this.httpsServer = Https.createServer(options, this.secureExpress);
1302
- }
1303
-
1304
- /**
1305
- *
1306
- */
1307
- private async startExpresses(): Promise<void> {
1308
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. startExpresses');
1309
-
1310
- try {
1311
- if (this._security && this._security !== DyNTS_RouteSecurity.open) {
1312
- await new Promise<void>((resolve, reject): void => {
1313
- this.systemControls.httpsServer.init = true;
1314
- this.httpsServer
1315
- .listen(
1316
- this._portSettings.httpsPort,
1317
- this.params.secureHost,
1318
- this.params.expressBacklog,
1319
- (): void => {
1320
- this.systemControls.httpsServer.started = true;
1321
- DyFM_Log.success(
1322
- `\nHTTPS (secure) server is listening on port: ` +
1323
- `${this.params.secureHost}:${this._portSettings.httpsPort}`
1324
- );
1325
-
1326
- resolve();
1327
- })
1328
- .on('error', (error): void => {
1329
- if (this.debugLog) DyFM_Log.error(`\nHTTPS (secure) server ERROR`, error);
1330
-
1331
- if (!this.systemControls.httpsServer.started) {
1332
- const d_error: DyFM_Error = new DyFM_Error({
1333
- ...this._getDefaultErrorSettings('startExpresses', error),
1334
-
1335
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE1`,
1336
- message: `HTTPS (secure) start server ERROR`,
1337
- });
1338
-
1339
- this.constructErrors.push(d_error);
1340
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1341
-
1342
- reject(d_error);
1343
-
1344
- } else {
1345
- const d_error: DyFM_Error = new DyFM_Error({
1346
- ...this._getDefaultErrorSettings('httpsServer.on(error)', error),
1347
-
1348
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE2`,
1349
- message: `HTTPS (secure) server ERROR`,
1350
- level: DyFM_ErrorLevel.serious,
1351
- });
1352
-
1353
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1354
- }
1355
- })
1356
- .on('uncaughtException', (exception): void => {
1357
- const d_error: DyFM_Error = new DyFM_Error({
1358
- ...this._getDefaultErrorSettings('httpsServer.on(uncaughtException)', exception),
1359
-
1360
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE3`,
1361
- message: `HTTPS (secure) server uncaughtException`,
1362
- level: DyFM_ErrorLevel.critical,
1363
- });
1364
-
1365
- if (this.debugLog) DyFM_Log.warn(
1366
- `\nHTTPS (secure) server uncaughtException`,
1367
- d_error
1368
- );
1369
-
1370
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1371
- });
1372
- });
1373
- }
1374
-
1375
- if (this._security && this._security !== DyNTS_RouteSecurity.secure) {
1376
- this.systemControls.httpServer.init = true;
1377
- await new Promise<void>((resolve, reject): void => {
1378
- this.httpServer = this.openExpress
1379
- .listen(
1380
- this._portSettings.httpPort,
1381
- this.params.openHost,
1382
- this.params.expressBacklog,
1383
- (): void => {
1384
- this.systemControls.httpServer.started = true;
1385
-
1386
- const resolvedPort: number = this.httpServer?.address?.()?.['port'] ?? this._portSettings.httpPort;
1387
-
1388
- if (this._portSettings.httpPort === 0) {
1389
- DyFM_Log.H_warn(
1390
- `\nHTTP (open) server is using a randomly selected port by the OS: ${resolvedPort}` +
1391
- `\n (httpPort was set to 0 — this is intended for testing only)`
1392
- );
1393
- }
1394
-
1395
- DyFM_Log.success(
1396
- `\nHTTP (open) server is listening on port: ` +
1397
- `${this.params.openHost}:${resolvedPort}`
1398
- );
1399
-
1400
- resolve();
1401
- }
1402
- )
1403
- .on('error', (error): void => {
1404
- if (this.debugLog) DyFM_Log.error(`\nHTTP (open) server ERROR`, error);
1405
-
1406
- if (!this.systemControls.httpServer.started) {
1407
- const d_error: DyFM_Error = new DyFM_Error({
1408
- ...this._getDefaultErrorSettings('startExpresses', error),
1409
-
1410
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE3`,
1411
- message: `HTTP (open) start server ERROR`,
1412
- });
1413
-
1414
- this.constructErrors.push(d_error);
1415
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1416
-
1417
- reject(d_error);
1418
-
1419
- } else {
1420
- const d_error: DyFM_Error = new DyFM_Error({
1421
- ...this._getDefaultErrorSettings('httpServer.on(error)', error),
1422
-
1423
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE4`,
1424
- message: `HTTP (open) server ERROR`,
1425
- level: DyFM_ErrorLevel.serious,
1426
- });
1427
-
1428
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1429
- }
1430
- })
1431
- .on('uncaughtException', (exception): void => {
1432
- const d_error: DyFM_Error = new DyFM_Error({
1433
- ...this._getDefaultErrorSettings('httpServer.on(uncaughtException)', exception),
1434
-
1435
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE5`,
1436
- message: `HTTP (open) server uncaughtException`,
1437
- level: DyFM_ErrorLevel.critical,
1438
- });
1439
-
1440
- if (this.debugLog) {
1441
- DyFM_Log.warn(`\nHTTP (open) server uncaughtException`, d_error);
1442
- }
1443
-
1444
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1445
- });
1446
- });
1447
- }
1448
- } catch (error) {
1449
- throw new DyFM_Error({
1450
- ...this._getDefaultErrorSettings('startExpresses', error),
1451
-
1452
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE0`,
1453
- });
1454
- }
1455
- }
1456
-
1457
- /**
1458
- *
1459
- */
1460
- private async expressErrorHandling(error, req, res, next): Promise<void> {
1461
- try {
1462
- if (error) {
1463
- const d_error: DyFM_Error = new DyFM_Error({
1464
- ...this._getDefaultErrorSettings('expressErrorHandling', error),
1465
-
1466
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-EEH1`,
1467
- message: `Express ERROR`,
1468
- additionalContent: {
1469
- req,
1470
- res,
1471
- },
1472
- level: DyFM_ErrorLevel.error,
1473
- });
1474
-
1475
- await DyNTS_GlobalService.globalErrorHandler?.(d_error, req, res);
1476
-
1477
- res.send(error)
1478
- } else {
1479
- DyFM_Log.H_error(
1480
- 'WTF??? express error; without error?...' +
1481
- '\nerr:', error,
1482
- '\nreq:', req,
1483
- '\nres:', res
1484
- );
1485
- }
1486
- } catch (error) {
1487
- DyFM_Log.H_error(
1488
- 'MULTILEVEL ERROR (expressErrorHandling)....' +
1489
- '\n', error
1490
- );
1491
- }
1492
- }
1493
-
1494
- /**
1495
- *
1496
- */
1497
- private async mountSecureRoutes (): Promise<void> {
1498
- try {
1499
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. mountSecureRoutes');
1500
-
1501
- if (!this.secureExpress) {
1502
- throw new Error(
1503
- 'secureExpress was not initialized. ' +
1504
- 'Secure routes require getCertificationSettings and httpsPort, and cert files must exist.' +
1505
- '\n\nYou need to set security to secure or both in any route and set httpsPort in getPortSettings.' +
1506
- '\n\nYou need to set cert files in getCertificationSettings.'
1507
- );
1508
- }
1509
-
1510
- this.secureExpress.use(
1511
- (error, req, res, next): Promise<void> => this.expressErrorHandling(error, req, res, next)
1512
- );
1513
-
1514
- await DyFM_Array.asyncForEach(
1515
- this._routingModules,
1516
- async (module: DyNTS_RoutingModule): Promise<void> => {
1517
- if (module.security !== DyNTS_RouteSecurity.open) {
1518
- if (this.logSetup) {
1519
- DyFM_Log.log(`route mount (secure): ${module.route}`);
1520
- }
1521
-
1522
- const existingRoutes: DyNTS_RoutingModule[] = this._routingModules.filter(
1523
- (mod: DyNTS_RoutingModule): boolean => mod.route === module.route
1524
- );
1525
-
1526
- if (1 < existingRoutes.length) {
1527
- const error: Error = new Error(`ROUTE DUPLICATION: ${module.route}`);
1528
- /* const errorStack: string[] = error.stack.split('\n');
1529
-
1530
- errorStack.splice(1, 4);
1531
- error.stack = errorStack.join('\n'); */
1532
- error.stack = module.stackLocation;
1533
-
1534
- DyFM_Log.S_error(`ROUTE DUPLICATION: ${module.route}`, error);
1535
-
1536
- throw new DyFM_Error({
1537
- ...this._getDefaultErrorSettings('mountSecureRoutes', error),
1538
-
1539
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MSR1`,
1540
- message: `ROUTE DUPLICATION: ${module.route}`,
1541
- });
1542
- }
1543
-
1544
- this.secureExpress.use(module.route, module.secureRouter);
1545
- }
1546
- }
1547
- );
1548
- } catch (error) {
1549
- throw new DyFM_Error({
1550
- ...this._getDefaultErrorSettings('mountSecureRoutes', error),
1551
-
1552
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MSR0`,
1553
- });
1554
- }
1555
- }
1556
-
1557
- /**
1558
- *
1559
- */
1560
- private async mountOpenRoutes(): Promise<void> {
1561
- try {
1562
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. mountOpenRoutes');
1563
-
1564
- if (!this.openExpress) {
1565
- throw new Error(
1566
- 'openExpress was not initialized. Open routes require getOpenExpress and httpPort.' +
1567
- '\n\nYou need to set security to open or both in any route and set httpPort in getPortSettings.'
1568
- );
1569
- }
1570
-
1571
- this.openExpress.use(
1572
- (error, req, res, next): Promise<void> => this.expressErrorHandling(error, req, res, next)
1573
- );
1574
-
1575
- await DyFM_Array.asyncForEach(
1576
- this._routingModules,
1577
- async (module: DyNTS_RoutingModule): Promise<void> => {
1578
- if (module.security !== DyNTS_RouteSecurity.secure) {
1579
- if (this.logSetup) {
1580
- DyFM_Log.log(`route mount (open): ${module.route}`);
1581
- }
1582
-
1583
- const existingRoutes: DyNTS_RoutingModule[] = this._routingModules.filter(
1584
- (mod: DyNTS_RoutingModule): boolean => mod.route === module.route
1585
- );
1586
-
1587
- if (1 < existingRoutes.length) {
1588
- const error: Error = new Error(`ROUTE DUPLICATION: ${module.route}`);
1589
- /* const errorStack: string[] = error.stack.split('\n');
1590
-
1591
- errorStack.splice(1, 4);
1592
- error.stack = errorStack.join('\n'); */
1593
- error.stack = module.stackLocation;
1594
-
1595
- DyFM_Log.S_error(`ROUTE DUPLICATION: ${module.route}`, error);
1596
-
1597
- throw new DyFM_Error({
1598
- ...this._getDefaultErrorSettings('mountOpenRoutes', error),
1599
-
1600
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MOR1`,
1601
- message: `ROUTE DUPLICATION: ${module.route}`,
1602
- });
1603
- }
1604
-
1605
- this.openExpress.use(module.route, module.openRouter);
1606
- }
1607
- }
1608
- );
1609
- } catch (error) {
1610
- throw new DyFM_Error({
1611
- ...this._getDefaultErrorSettings('mountOpenRoutes', error),
1612
-
1613
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MOR0`,
1614
- });
1615
- }
1616
- }
1617
-
1618
- /**
1619
- * FR-041 — CORS middleware. Echoes a matching `Access-Control-Allow-Origin`
1620
- * for any request whose Origin header is in `getCorsSettings().allowedOrigins`,
1621
- * adds the canonical `Access-Control-*` companion headers, and short-circuits
1622
- * the OPTIONS preflight with a 204.
1623
- *
1624
- * No-op when the subclass does NOT override `getCorsSettings()` — preserves
1625
- * back-compat for apps that have always been same-origin and never needed
1626
- * CORS (the typical pre-FR-041 case).
1627
- *
1628
- * Why hand-rolled instead of the `cors` npm package:
1629
- * - ~30 lines, zero new dependency.
1630
- * - Full control over Vary/credentials/preflight semantics.
1631
- * - Aligns with FDP "no unnecessary deps" philosophy.
1632
- */
1633
- protected mountCors(express: Express.Application): void {
1634
- const settings: DyNTS_Cors_Settings | undefined = this.getCorsSettings?.();
1635
- if (!settings) {
1636
- return;
1637
- }
1638
-
1639
- const allowCreds: boolean = settings.allowCredentials !== false;
1640
- const methods: string[] = settings.allowedMethods ?? [
1641
- 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS',
1642
- ];
1643
- const headers: string[] = settings.allowedHeaders ?? [
1644
- 'Authorization', 'Content-Type', 'X-Admin-Key', 'X-Requested-With',
1645
- ];
1646
- const exposed: string[] = settings.exposedHeaders ?? [
1647
- 'Content-Length', 'Content-Type',
1648
- ];
1649
- const maxAge: number = settings.maxAgeSeconds ?? 86400;
1650
-
1651
- const isAllowed: (origin: string) => boolean = (origin: string): boolean => {
1652
- if (settings.allowedOrigins === '*') return true;
1653
- if (typeof settings.allowedOrigins === 'function') {
1654
- return settings.allowedOrigins(origin);
1655
- }
1656
- return settings.allowedOrigins.includes(origin);
1657
- };
1658
-
1659
- express.use((req: Express.Request, res: Express.Response, next: Express.NextFunction): void => {
1660
- const origin: string | undefined = req.headers.origin;
1661
- if (origin && isAllowed(origin)) {
1662
- // Echo the matching origin (NOT wildcard) because credentials require it.
1663
- res.setHeader('Access-Control-Allow-Origin', origin);
1664
- if (allowCreds) {
1665
- res.setHeader('Access-Control-Allow-Credentials', 'true');
1666
- }
1667
- res.setHeader('Access-Control-Allow-Methods', methods.join(', '));
1668
- res.setHeader('Access-Control-Allow-Headers', headers.join(', '));
1669
- res.setHeader('Access-Control-Expose-Headers', exposed.join(', '));
1670
- res.setHeader('Access-Control-Max-Age', String(maxAge));
1671
- res.setHeader('Vary', 'Origin');
1672
- }
1673
- if (req.method === 'OPTIONS') {
1674
- res.status(204).end();
1675
- return;
1676
- }
1677
- next();
1678
- });
1679
- }
1680
-
1681
- /**
1682
- * Generikus, auth-agnosztikus extension-point orchestrator. A `registerCustomMiddleware`
1683
- * hookot hívja (ha a subclass override-olja) minden AKTÍV Express instance-ra
1684
- * (open + secure), az API route-ok UTÁN, de a SPA static catch-all (`app.get('*')`)
1685
- * ELŐTT — ez az EGYETLEN korrekt pont egy sub-path middleware-hez (pl. reverse-proxy),
1686
- * mert a catch-all minden utána mountolt route-ot elnyel. No-op ha nincs override (back-compat).
1687
- */
1688
- private async mountCustomMiddleware(): Promise<void> {
1689
- if (!this.registerCustomMiddleware) {
1690
- return;
1691
- }
1692
-
1693
- if (this.openExpress) {
1694
- await this.registerCustomMiddleware(this.openExpress, DyNTS_RouteSecurity.open);
1695
- }
1696
-
1697
- if (this.secureExpress) {
1698
- await this.registerCustomMiddleware(this.secureExpress, DyNTS_RouteSecurity.secure);
1699
- }
1700
-
1701
- if (this.logSetup) {
1702
- DyFM_Log.log('\nCustom middleware registered (pre-static).');
1703
- }
1704
- }
1705
-
1706
- /**
1707
- * Ha getStaticClientSettings() visszaad beállításokat, a client static fájlok a '/' alatt
1708
- * lesznek kiszolgálva (API route-ok után). SPA fallback opcionális (fallbackPath).
1709
- * Asset cache (assetCacheMaxAge, assetCacheImmutable) és fallback cache (fallbackCacheMaxAge)
1710
- * opcionálisak; ha nincs megadva fallbackCacheMaxAge, DyNTS_defaultFallbackCacheMaxAge (0) marad.
1711
- */
1712
- private async mountStaticClient(): Promise<void> {
1713
- const settings: DyNTS_StaticClient_Settings | undefined = this.getStaticClientSettings?.();
1714
- if (!settings) {
1715
- return;
1716
- }
1717
-
1718
- const absoluteRoot: string = Path.isAbsolute(settings.root)
1719
- ? settings.root
1720
- : Path.resolve(process.cwd(), settings.root);
1721
-
1722
- const hasAssetCache: boolean =
1723
- settings.assetCacheMaxAge !== undefined || settings.assetCacheImmutable === true;
1724
- const staticOptions: { setHeaders: (res: Express.Response) => void } | undefined =
1725
- hasAssetCache && settings.assetCacheMaxAge !== undefined
1726
- ? {
1727
- setHeaders: (res: Express.Response): void => {
1728
- const maxAge: number = settings.assetCacheMaxAge!;
1729
- const immutable: string =
1730
- settings.assetCacheImmutable === true ? ', immutable' : '';
1731
- res.setHeader('Cache-Control', `max-age=${maxAge}${immutable}`);
1732
- },
1733
- }
1734
- : undefined;
1735
-
1736
- const staticMiddleware: Express.Handler =
1737
- staticOptions
1738
- ? Express.static(absoluteRoot, staticOptions)
1739
- : Express.static(absoluteRoot);
1740
-
1741
- const fallbackMaxAge: number =
1742
- settings.fallbackCacheMaxAge ?? DyNTS_defaultFallbackCacheMaxAge;
1743
-
1744
- if (this.openExpress) {
1745
- this.openExpress.use('/', staticMiddleware);
1746
- if (settings.fallbackPath) {
1747
- this.openExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1748
- res.setHeader('Cache-Control', `max-age=${fallbackMaxAge}`);
1749
- res.sendFile(settings.fallbackPath!, { root: absoluteRoot });
1750
- });
1751
- } else {
1752
- this.openExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1753
- res.status(404).type('html').send(DyNTS_defaultNotFoundPageHtml);
1754
- });
1755
- }
1756
- }
1757
-
1758
- if (this.secureExpress) {
1759
- this.secureExpress.use('/', staticMiddleware);
1760
- if (settings.fallbackPath) {
1761
- this.secureExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1762
- res.setHeader('Cache-Control', `max-age=${fallbackMaxAge}`);
1763
- res.sendFile(settings.fallbackPath!, { root: absoluteRoot });
1764
- });
1765
- } else {
1766
- this.secureExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1767
- res.status(404).type('html').send(DyNTS_defaultNotFoundPageHtml);
1768
- });
1769
- }
1770
- }
1771
-
1772
- if (this.logSetup) {
1773
- DyFM_Log.log(`\nStatic client mounted at / (root: ${absoluteRoot})`);
1774
- }
1775
- }
1776
-
1777
- /**
1778
- *
1779
- */
1780
- private setSecurity(): void {
1781
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. setSecurity');
1782
- this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1783
- if (!module.security) {
1784
- DyFM_Log.warn(`RoutingModule security is not set for ${module.route}\n`);
1785
-
1786
- } else if (!this._security) {
1787
- this._security = module.security;
1788
-
1789
- } else if (this._security !== module.security) {
1790
- this._security = DyNTS_RouteSecurity.both;
1791
- }
1792
- });
1793
-
1794
- if (!this._security) {
1795
- let msg = `Could not set security for the server! (${this.security})`;
1796
-
1797
- msg += '\n RoutingModules:';
1798
- this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1799
- msg += `\n ${module.route} (security: ${module.security})`;
1800
- });
1801
-
1802
- if (this._routingModules.length === 0) {
1803
- msg += '\n - no RoutingModule found -\n';
1804
- }
1805
- DyFM_Log.warn(msg);
1806
- }
1807
- }
1808
-
1809
- private _getDefaultErrorSettings(
1810
- fnName: string,
1811
- error: DyFM_AnyError
1812
- ): DyFM_Error_Settings {
1813
- return {
1814
- status: (error as DyFM_Error)?.___status ?? 500,
1815
- message: (error as Error)?.message ??
1816
- (error as DyFM_Error)?._message ??
1817
- `${fnName} was UNSUCCESSFUL (NTS)`,
1818
- userMessage: (error as DyFM_Error)?.__userMessage ?? this.defaultErrorUserMsg,
1819
- addECToUserMsg: !(error as DyFM_Error)?.__userMessage,
1820
- issuerService: `${this?.constructor?.name}-DyNTS_App`,
1821
- level: DyFM_ErrorLevel.fatal,
1822
- error: error,
1823
- systemVersion: DyNTS_global_settings.systemVersion,
1824
- };
1825
- }
1826
-
1827
- /**
1828
- * MISSING Description (TODO)
1829
- */
1830
- abstract getAppParams(): DyNTS_App_Params;
1831
-
1832
- /**
1833
- * MISSING Description (TODO)
1834
- */
1835
- abstract getGlobalServiceCollection(): DyNTS_GlobalService_Settings;
1836
-
1837
- /**
1838
- * MISSING Description (TODO)
1839
- */
1840
- abstract getPortSettings(): DyNTS_Http_Settings;
1841
-
1842
- /**
1843
- * MISSING Description (TODO)
1844
- */
1845
- overrideDynamoNTSGlobalSettings?(): void;
1846
-
1847
- /**
1848
- * Ha megadva, a visszaadott értéket használjuk a route prefix-ként
1849
- * (DyNTS_global_settings.baseUrl felülírása erre az app-ra).
1850
- */
1851
- getApiBasePath?(): string;
1852
-
1853
- /**
1854
- * MISSING Description (TODO)
1855
- */
1856
- getRoutingModules?(): DyNTS_RoutingModule[];
1857
-
1858
- /**
1859
- * MISSING Description (TODO)
1860
- */
1861
- getRootServices?(): Promise<any[]>;
1862
-
1863
- /**
1864
- * MISSING Description (TODO)
1865
- */
1866
- getCertificationSettings?(): DyNTS_Certification_Settings;
1867
-
1868
- /**
1869
- * Ha megadva, a client static fájlok a '/' alatt lesznek kiszolgálva (API route-ok után).
1870
- * Opcionális fallbackPath pl. SPA index.html-hez.
1871
- */
1872
- getStaticClientSettings?(): DyNTS_StaticClient_Settings | undefined;
1873
-
1874
- /**
1875
- * FR-041 — Ha megadva, CORS middleware mount-olódik mindkét Express instance-ra
1876
- * (open + secure). Az `allowedOrigins` listán szereplő Origin-eket echo-zza vissza,
1877
- * `Access-Control-Allow-Credentials: true`-val (default) együtt a Bearer JWT
1878
- * cross-domain auth flow miatt. OPTIONS preflight 204-gyel rövidre záródik.
1879
- * Ha undefined → no CORS headers, no preflight handling — back-compat.
1880
- */
1881
- getCorsSettings?(): DyNTS_Cors_Settings | undefined;
1882
-
1883
- /**
1884
- * Opcionális generikus hook: custom Express middleware regisztrálása az API route-ok
1885
- * UTÁN és a SPA static catch-all ELŐTT. Auth-AGNOSZTIKUS framework extension-point —
1886
- * a subclass (pl. FDP base App) ezen keresztül mount-olhat reverse-proxyt egy sub-path-re
1887
- * (pl. `/auth-api`), ami a `app.get('*')` catch-all elé kell kerüljön. A hívási időzítést
1888
- * lásd: `mountCustomMiddleware`. Undefined → no-op (back-compat).
1889
- */
1890
- registerCustomMiddleware?(
1891
- express: Express.Application,
1892
- security: DyNTS_RouteSecurity,
1893
- ): void | Promise<void>;
1894
-
1895
- /**
1896
- * MISSING Description (TODO)
1897
- */
1898
- createEntries?(): Promise<void>;
1899
-
1900
- /**
1901
- * MISSING Description (TODO)
1902
- */
1903
- postProcess?(): Promise<void>;
1904
-
1905
- }
1
+
2
+ import Mongoose = require('mongoose');
3
+ import Express = require('express');
4
+ /* import Mongoose from 'mongoose';
5
+ import Express from 'express'; */
6
+
7
+ import * as BodyParser from 'body-parser';
8
+ import * as FileSystem from 'fs';
9
+ import * as Http from 'http';
10
+ import * as Https from 'https';
11
+ import * as Path from 'path';
12
+ import * as dotenv from 'dotenv'
13
+
14
+ /* import { version } from '../../../package.json'; */
15
+
16
+ import {
17
+ DyFM_AnyError,
18
+ DyFM_Array,
19
+ DyFM_Async,
20
+ DyFM_Error,
21
+ DyFM_error_defaults,
22
+ DyFM_Error_Settings,
23
+ DyFM_ErrorLevel,
24
+ DyFM_Log,
25
+ DyFM_resolveRetentionTtlSeconds,
26
+ megabyte,
27
+ second
28
+ } from '@futdevpro/fsm-dynamo';
29
+
30
+ import { DyNTS_defaultFallbackCacheMaxAge } from '../../_collections/default-fallback-cache-max-age.const';
31
+ import { DyNTS_defaultNotFoundPageHtml } from '../../_collections/default-not-found-page.const';
32
+ import { DyNTS_global_settings } from '../../_collections/global-settings.const';
33
+ import { startMongoReconnectGuard } from '../../_collections/mongo-reconnect-guard.util';
34
+ import { DyNTS_RouteSecurity } from '../../_enums/route-security.enum';
35
+ import { DyNTS_App_Params } from '../../_models/control-models/app-params.control-model';
36
+ import {
37
+ DyNTS_AppSystemControls
38
+ } from '../../_models/control-models/app-system-controls.control-model';
39
+ import {
40
+ DyNTS_Endpoint_Params
41
+ } from '../../_models/control-models/endpoint-params.control-model';
42
+ import { DyNTS_Http_Settings } from '../../_models/control-models/http-settings.control-model';
43
+ import {
44
+ DyNTS_Certification_Settings
45
+ } from '../../_models/interfaces/certification-settings.interface';
46
+ import {
47
+ DyNTS_GlobalService_Settings
48
+ } from '../../_models/interfaces/global-service-settings.interface';
49
+ import {
50
+ DyNTS_StaticClient_Settings
51
+ } from '../../_models/interfaces/static-client-settings.interface';
52
+ import {
53
+ DyNTS_Cors_Settings
54
+ } from '../../_models/interfaces/cors-settings.interface';
55
+ import { DyNTS_DBService } from '../base/db.service';
56
+ import { DyNTS_SingletonService } from '../base/singleton.service';
57
+ import { DyNTS_GlobalService } from '../core/global.service';
58
+ import { DyNTS_CollectionGrowthMonitor } from '../core/collection-growth-monitor.service';
59
+ import { DyNTS_MemoryGuard } from '../core/memory-guard.service';
60
+ import { DyNTS_RoutingModule } from '../route/routing-module.service';
61
+ import { DyNTS_getStarRoute } from '../../_collections/star.controller';
62
+
63
+ /**
64
+ *
65
+ * function MyDecorator(config: any) {
66
+ return function (target: Function) {
67
+ // attach metadata or modify target
68
+ target.prototype.myMeta = config;
69
+ };
70
+ }
71
+
72
+ @MyDecorator({ role: 'admin' })
73
+ class User {
74
+ printRole() {
75
+ console.log((this as any).myMeta.role); // → "admin"
76
+ }
77
+ }
78
+
79
+ */
80
+
81
+ /**
82
+ * This will be the MAIN service of our server project,
83
+ * follow the types and type instructions while setting up your project
84
+ *
85
+ * In this service, there are abstract functions that you will need to implement,
86
+ * where you need to set up the main params for your application.
87
+ *
88
+ * (after the example, you can find the list of services you can/should setup)
89
+ *
90
+ * @example
91
+ * export class App extends DyNTS_AppExtended {
92
+ *
93
+ * ...
94
+ *
95
+ * // Setting up App params, and preparing project global settings
96
+ * setupAppParams(): void {
97
+ * this.params = new DyNTS_AppParams({
98
+ * name: 'Warbots Server',
99
+ * title: warbotsTitleLog,
100
+ * version: version,
101
+ * dbName: 'warbots',
102
+ * });
103
+ *
104
+ * // dynamoNTS_GlobalSettings.logRequestsContent = false;
105
+ * }
106
+ *
107
+ * ...
108
+ *
109
+ * // Setting up DBServices
110
+ * setGlobalServiceCollection(): void {
111
+ * DyNTS_GlobalService.setServices({
112
+ * authService: AuthService.getInstance(),
113
+ * emailServiceCollection: EmailServiceCollectionService.getInstance(),
114
+ * dbModels: [
115
+ * userModelParams,
116
+ * userDataModelParams,
117
+ * userOptionsModelParams,
118
+ * userStatisticsModelParams,
119
+ * userAchievementsModelParams,
120
+ * userNotificationsModelParams,
121
+ *
122
+ * matchStatisticsModelParams,
123
+ * matchDataModelParams,
124
+
125
+ * DyFM_usageSession_dataParams,
126
+ * DyFM_customData_dataParams,
127
+ * ]
128
+ * });
129
+ * }
130
+ *
131
+ * ...
132
+ *
133
+ * // Setting up Routes
134
+ * setupRoutingModules(): void {
135
+ * this.httpPort = env.port;
136
+
137
+ * this.routingModules = [
138
+ * new DyNTS_RoutingModule({
139
+ * route: '/user',
140
+ * controllers: [
141
+ * UserController.getInstance(),
142
+ * UserDataController.getInstance(),
143
+ * UserOptionsController.getInstance(),
144
+ * UserStatisticsController.getInstance(),
145
+ * UserAchievementsController.getInstance(),
146
+ * UserNotificationsController.getInstance()
147
+ * ]
148
+ * }),
149
+ * new DyNTS_RoutingModule({
150
+ * route: '/match',
151
+ * controllers: [
152
+ * MatchController.getInstance(),
153
+ * MatchDistributionController.getInstance(),
154
+ * MatchStatisticsController.getInstance(),
155
+ * ]
156
+ * }),
157
+ * new DyNTS_RoutingModule({
158
+ * route: '/server',
159
+ * controllers: [
160
+ * ServerController.getInstance(),
161
+ * ]
162
+ * }),
163
+
164
+ * getTestRoutingModule(),
165
+ * getUsageRoutingModule()
166
+ * ];
167
+ * }
168
+ * }
169
+ *
170
+ * //
171
+ * // The Services available
172
+ * //
173
+ * // Authentication Service
174
+ * // A commonly used basic service,
175
+ * // which is necessary fur certain functions (such as registering call issuers)
176
+ * //
177
+ * // This will handle Authentication Token checking/refreshing,
178
+ * // checking issuer's identifier and routeParams,
179
+ * // handling JWT Token, or maybe with OAuth2 or other commonly used security procedures
180
+ * //
181
+ * // You can create one with this Dynamo Object:
182
+ * //
183
+ *
184
+ * @example
185
+ * // follow the instructions on the abstract class (DyNTS_AuthService)
186
+ * export class AuthService extends DyNTS_AuthService {}
187
+ *
188
+ *
189
+ *
190
+ * //
191
+ */
192
+
193
+ /**
194
+ * This will be the MAIN service of our server project,
195
+ * follow the types and type instructions while setting up your project
196
+ *
197
+ * In this service, there are abstract functions that you will need to implement,
198
+ * where you need to set up the main params for your application.
199
+ *
200
+ * (after the example, you can find the list of services you can/should setup)
201
+ *
202
+ * You need to setup the following functions:
203
+ * ```ts
204
+ * // this is where you set up the main params for your application
205
+ * getAppParams(): DyNTS_AppParams
206
+ *
207
+ * // this is where you connect your main services
208
+ * getGlobalServiceSettings(): DyNTS_GlobalService_Settings
209
+ *
210
+ * // this is where you set up your ports
211
+ * getPorts(): DyNTS_PortSettings
212
+ *
213
+ * // this is where you set up your routes
214
+ * getRoutingModules(): DyNTS_RoutingModule[]
215
+ *
216
+ *
217
+ *
218
+ * ```
219
+ * optionally you can setup the following functions:
220
+ * ```ts
221
+ * // this is where you set up your certifications
222
+ * getCertificationSettings(): DyNTS_CertificationSettings
223
+ *
224
+ * // this is where you set up additional root services
225
+ * getRootServices(): DyNTS_SingletonService[]
226
+ *
227
+ * // this is where you set up your initial db entries
228
+ * createEntries(): void
229
+ *
230
+ * // this is where you can define post setup processes
231
+ * postProcess(): void
232
+ *
233
+ *
234
+ *
235
+ * ```
236
+ *
237
+ */
238
+
239
+ /** FR-258 / SR-2 — one entry from `collection.indexes()` (only the fields the TTL-installer reads). */
240
+ export interface DyNTS_TtlIndexInfo {
241
+ name?: string;
242
+ key?: Record<string, number>;
243
+ expireAfterSeconds?: number;
244
+ }
245
+
246
+ /**
247
+ * FR-258 / SR-2 — the minimal native-driver collection surface the TTL-installer needs. Declared
248
+ * structurally (not importing mongodb types) so it stays dependency-light and is trivially mockable
249
+ * in unit tests.
250
+ */
251
+ export interface DyNTS_TtlIndexCollection {
252
+ indexes?: () => Promise<DyNTS_TtlIndexInfo[]>;
253
+ createIndex: (keys: Record<string, number>, options: { expireAfterSeconds: number }) => Promise<unknown>;
254
+ dropIndex?: (name: string) => Promise<unknown>;
255
+ }
256
+
257
+ /**
258
+ * FR-258 / SR-2 — outcome of {@link DyNTS_App.ensureRetentionTtlIndex}.
259
+ * - `created`: no `__created` TTL index existed → one was created.
260
+ * - `noop`: an index with the SAME TTL already existed → nothing done.
261
+ * - `differs`: an index exists with a DIFFERENT TTL (or a non-TTL `__created` index) → left UNTOUCHED,
262
+ * only a warning is emitted. We deliberately DO NOT drop+recreate at boot: rebuilding a TTL index on a
263
+ * multi-GB production collection is a heavy server-side op that can starve concurrent boot queries (e.g.
264
+ * the health-probe) and trip a fail-safe deploy revert. A deliberate retention CHANGE must be applied via
265
+ * maintenance, not silently at every startup.
266
+ */
267
+ export type DyNTS_TtlIndexAction = 'created' | 'differs' | 'noop';
268
+
269
+ export abstract class DyNTS_App extends DyNTS_SingletonService {
270
+
271
+ protected systemControls: DyNTS_AppSystemControls = new DyNTS_AppSystemControls();
272
+ get started(): boolean {
273
+ return this.systemControls.app.started;
274
+ }
275
+ protected get superStarted(): boolean {
276
+ return this.systemControls.app.started;
277
+ }
278
+ protected constructErrors: (Error | DyFM_Error)[] = [];
279
+
280
+ /* removed since cant use version from package.json
281
+ private readonly _ntsVersion: string = 'v01.07.18';
282
+ protected get ntsVersion(): string {
283
+ return this._ntsVersion;
284
+ } */
285
+
286
+ get serverName(): string {
287
+ return this.params.name;
288
+ }
289
+
290
+ private _params: DyNTS_App_Params;
291
+ protected get params(): DyNTS_App_Params {
292
+ return this._params;
293
+ }
294
+
295
+ protected mongoose = Mongoose;
296
+
297
+ private _security: DyNTS_RouteSecurity;
298
+ protected get security(): DyNTS_RouteSecurity {
299
+ return this._security;
300
+ }
301
+
302
+ protected _portSettings: DyNTS_Http_Settings = new DyNTS_Http_Settings();
303
+ protected get portSettings(): DyNTS_Http_Settings {
304
+ return this._portSettings;
305
+ }
306
+
307
+ private _cert?: DyNTS_Certification_Settings;
308
+ protected get cert(): DyNTS_Certification_Settings {
309
+ return this._cert;
310
+ }
311
+
312
+ protected openExpress: Express.Application;
313
+ protected secureExpress: Express.Application;
314
+ protected httpsServer: Https.Server;
315
+ protected httpServer: Http.Server;
316
+
317
+ private globalService: DyNTS_GlobalService;
318
+ private _rootServices: DyNTS_SingletonService[] = [];
319
+
320
+ private _routingModules: DyNTS_RoutingModule[] = [];
321
+
322
+ protected readonly defaultReadyTimeout: number = 30 * second;
323
+
324
+ override readonly defaultErrorUserMsg =
325
+ `We encountered an unhandled Server Error, ` +
326
+ `\nplease contact the responsible development team.` +
327
+ `\n(Internal Server error)`;
328
+
329
+ get logSetup(): boolean {
330
+ return DyNTS_global_settings.log_settings.setup;
331
+ }
332
+ get deepLog(): boolean {
333
+ return DyNTS_global_settings.log_settings.deep;
334
+ }
335
+ get fnLogs(): boolean {
336
+ return DyNTS_global_settings.log_settings.functions;
337
+ }
338
+ debugLog: boolean = DyNTS_global_settings.log_settings.server_debug;
339
+
340
+ constructor(/* extended?: boolean */){
341
+ super();
342
+
343
+ /* dotenv.config() */
344
+
345
+ process.on(
346
+ 'unhandledRejection',
347
+ (reason_theError: object, p_passWhatIsThis_maybeThePromise: any): void => {
348
+ if (reason_theError instanceof DyFM_Error) {
349
+ reason_theError.logSimple('Unhandled Rejection');
350
+ } else {
351
+ DyFM_Log.H_error(
352
+ 'Unhandled Rejection:', (p_passWhatIsThis_maybeThePromise as Promise<any>)?.toString(),
353
+ '\n Rejection reason:', (reason_theError as Error)?.stack?.split('at')?.[0],
354
+ /* '\n ErrorCode:', (reason as any)?.code, */
355
+ '\n\n Stack:',
356
+ (reason_theError as Error)?.stack?.replaceAll?.('\n at', '\n at'),
357
+ );
358
+ }
359
+
360
+ try {
361
+ DyNTS_GlobalService.globalErrorHandler?.(
362
+ new DyFM_Error({
363
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-BASE-UR`,
364
+ message:
365
+ `Unhandled Rejection!: "${(reason_theError as Error)?.stack?.split('at')?.[0]}"`,
366
+ userMessage: this.defaultErrorUserMsg,
367
+ addECToUserMsg: true,
368
+ error: reason_theError as Error,
369
+ additionalContent: {
370
+ reason: reason_theError,
371
+ rejectedPromise: p_passWhatIsThis_maybeThePromise,
372
+ },
373
+ systemVersion: DyNTS_global_settings.systemVersion,
374
+ level: DyFM_ErrorLevel.critical,
375
+ })
376
+ );
377
+ } catch (error) {
378
+ DyFM_Log.error('globalErrorHandler (MULTILEVEL) ERROR:', error);
379
+ }
380
+ }
381
+ );
382
+
383
+ this.asyncConstruct(/* extended */).catch((error: any): void => {
384
+ if (error instanceof DyFM_Error) {
385
+ if (error.additionalContent?.constructErrors?.length) {
386
+ error.additionalContent.constructErrors.forEach((errorItem: DyFM_Error): void => {
387
+ DyFM_Error.logSimple('(constructor asyncConstruct.catch) error:', errorItem);
388
+ /* if (errorItem instanceof DyFM_Error) {
389
+ errorItem.logSimple(`(constructor asyncConstruct.catch) error:\n`);
390
+ } else {
391
+ DyFM_Log.H_warn(
392
+ '(constructor asyncConstruct.catch) additional error content:\n',
393
+ errorItem
394
+ );
395
+ } */
396
+ });
397
+ } else {
398
+ DyFM_Log.H_warn(
399
+ '(constructor asyncConstruct.catch) additional error content:\n',
400
+ error?.additionalContent
401
+ );
402
+ }
403
+ }
404
+
405
+ DyFM_Error.logSimple('(constructor asyncConstruct.catch) error:', error);
406
+ /* if (
407
+ !DyNTS_global_settings.log_settings.highDetailedLogs &&
408
+ (error instanceof DyFM_Error)
409
+ ) {
410
+ error.logSimple(
411
+ `Application: "${this.params?.name}" start failed. (constructor asyncConstruct.catch)` +
412
+ '\n all error messages (from this stack):\n\n"' +
413
+ error._messages.join('"\n\n"') + '"\n\n'
414
+ );
415
+ } else if (error instanceof DyFM_Error) {
416
+ DyFM_Log.H_error(
417
+ `Application: "${this.params?.name}" start failed. (constructor asyncConstruct.catch)`,
418
+ `\n ERROR:`, error
419
+ );
420
+ } */
421
+
422
+ const message: string =
423
+ (error as DyFM_Error)?.additionalContent?.constructErrors?.flatMap(
424
+ (errorItem: DyFM_Error): string[] => {
425
+ return errorItem?._messages ?? [];
426
+ }
427
+ )?.join?.('\n') ??
428
+ (error as DyFM_Error)?.errors?.flatMap(
429
+ (errorItem: DyFM_AnyError): string[] =>
430
+ (errorItem as DyFM_Error)?._messages ?? [ (errorItem as Error)?.message ]
431
+ )?.join?.('\n') ??
432
+ error?.message ??
433
+ 'UNKNOWN';
434
+
435
+ DyFM_Log.testError('Application start failed:\n', message);
436
+
437
+ process.exit(1);
438
+ });
439
+ }
440
+
441
+ protected async asyncConstruct(extended?: boolean): Promise<void> {
442
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. asyncConstruct');
443
+
444
+ try {
445
+ this.systemControls.app.init = true;
446
+ this._params = this.getAppParams();
447
+ DyFM_Log.log(
448
+ `\n\n\n\n\n\n\n\n\n\n` +
449
+ `Starting ${this._params?.name}... ` +
450
+ /* `v${version}` + */
451
+ `\n\n\n\n\n\n\n\n\n\n`
452
+ );
453
+
454
+ if (!this._params) {
455
+ throw new Error('getAppParams() must return a DyNTS_AppParams object!');
456
+ }
457
+
458
+ if (this.params.systemShortCodeName) {
459
+ DyNTS_global_settings.systemShortCodeName = this.params.systemShortCodeName;
460
+ }
461
+
462
+ if (this.params.systemName) {
463
+ DyNTS_global_settings.systemName = this.params.systemName;
464
+ DyFM_error_defaults.issuerSystem = this.params.systemName;
465
+ }
466
+
467
+ if (this.params.version) {
468
+ DyNTS_global_settings.systemVersion = this.params.version;
469
+ DyFM_error_defaults.systemVersion = this.params.version;
470
+ }
471
+
472
+ process.stdout.write(
473
+ String.fromCharCode(27) + ']0;' +
474
+ this._params?.name +
475
+ String.fromCharCode(7)
476
+ );
477
+
478
+ DyFM_error_defaults.issuerSystem = this._params.systemName;
479
+
480
+ this.overrideDynamoNTSGlobalSettings?.();
481
+
482
+ if (DyNTS_global_settings.log_settings.setup) {
483
+ DyFM_Log.S_info(`env settings;\n`, {
484
+ systemName: DyNTS_global_settings.systemName,
485
+ systemShortCodeName: DyNTS_global_settings.systemShortCodeName,
486
+ systemVersion: DyNTS_global_settings.systemVersion,
487
+ environment: DyNTS_global_settings.env_settings.environment,
488
+ /* log_settings: DyNTS_global_settings.log_settings,
489
+ env_settings: DyNTS_global_settings.env_settings, */
490
+ });
491
+ }
492
+
493
+ this.globalService = DyNTS_GlobalService.getInstance();
494
+ await DyNTS_GlobalService.setServices(this.getGlobalServiceCollection());
495
+ DyNTS_GlobalService.setParams(this.params);
496
+
497
+ if (this.getPortSettings) {
498
+ this._portSettings = this.getPortSettings();
499
+ }
500
+
501
+ if (this.getCertificationSettings) {
502
+ this._cert = this.getCertificationSettings();
503
+ }
504
+
505
+ if (this.getApiBasePath) {
506
+ DyNTS_global_settings.baseUrl = this.getApiBasePath();
507
+ }
508
+
509
+ if (this.getRoutingModules) {
510
+ this._routingModules = this.getRoutingModules();
511
+
512
+ // ezt egyelőre csak tesztelem, nem kerül be
513
+ /* if (
514
+ !DyNTS_global_settings.dontCreateDefaultRoute &&
515
+ !this._routingModules.some((routingModule: DyNTS_RoutingModule): boolean => routingModule.route === '/*')
516
+ ) {
517
+ this._routingModules.push(
518
+ DyNTS_getStarRoute()
519
+ );
520
+ } */
521
+ }
522
+
523
+ if (this._params.dbUri) {
524
+ await this.startDB();
525
+
526
+ // createEntries csak akkor fut, ha a DB tényleg fel-jött.
527
+ // Ha a startDB jelezte a hibát, de továbbment, akkor a started flag false marad,
528
+ // és nem próbálunk meg írni egy nem létező kapcsolatra.
529
+ if (this.createEntries && this.systemControls.mongoose.started) {
530
+ await this.createEntries();
531
+ }
532
+ } else {
533
+ DyFM_Log.log(
534
+ `\nNo database connection created.`,
535
+ );
536
+ }
537
+
538
+ if (this._routingModules?.length) {
539
+ if (this.logSetup) DyFM_Log.log('\nsetting up express routes...');
540
+
541
+ this.setSecurity();
542
+
543
+ await this.initExpresses();
544
+ await this.startExpresses();
545
+
546
+ if (this._security !== DyNTS_RouteSecurity.secure) {
547
+ await this.mountOpenRoutes();
548
+ }
549
+
550
+ if (this._security !== DyNTS_RouteSecurity.open && this._cert) {
551
+ await this.mountSecureRoutes();
552
+ }
553
+
554
+ // Generikus, auth-agnosztikus extension-point: custom middleware az API
555
+ // route-ok UTÁN, de a SPA static catch-all (mountStaticClient) ELŐTT.
556
+ await this.mountCustomMiddleware();
557
+
558
+ await this.mountStaticClient();
559
+
560
+ if (this.logSetup) {
561
+ DyFM_Log.log(`\nRoutes mounted.... server using security: ${this._security}`);
562
+ }
563
+ } else {
564
+ DyFM_Log.warn(
565
+ `\nNo routes mounted!`,
566
+ );
567
+ }
568
+
569
+ if (this.getRootServices) {
570
+ this._rootServices = await this.getRootServices();
571
+ }
572
+
573
+ if (this.postProcess) {
574
+ await this.postProcess().catch((error: any): void => {
575
+ DyFM_Error.logSimple(`"${this._params.name}" postProcess failed:`, error);
576
+ DyNTS_GlobalService.globalErrorHandler?.(error);
577
+ });
578
+ }
579
+
580
+ // FR-193 — bedrock OOM korai-figyelmeztetés: feltelepítjük a heap-watchdogot, ha
581
+ // engedélyezve (DyNTS_global_settings.memoryGuard.enabled, default true). Biztonságos:
582
+ // a guard egy könnyű setInterval, ami SOHA nem dob; csak near-OOM küszöböknél hagy
583
+ // tartós nyomot az error-sinkbe, mielőtt a fatal heap-OOM megölné a process-t.
584
+ try {
585
+ if (DyNTS_global_settings.memoryGuard?.enabled) {
586
+ DyNTS_MemoryGuard.getInstance().install();
587
+ }
588
+ } catch (memoryGuardError: unknown) {
589
+ DyFM_Log.warn('[DyNTS_MemoryGuard] auto-install skipped (non-fatal):', memoryGuardError);
590
+ }
591
+
592
+ // FR-258 / SR-4 — proactive collection-growth monitor (companion to the MemoryGuard). Warns
593
+ // into the Errors-sink when a collection grows unbounded, BEFORE it can be loaded into heap and
594
+ // OOM. Default-on, observation-only, never throws.
595
+ try {
596
+ if (DyNTS_global_settings.collectionGrowthMonitor?.enabled) {
597
+ DyNTS_CollectionGrowthMonitor.getInstance().install();
598
+ }
599
+ } catch (cgmError: unknown) {
600
+ DyFM_Log.warn('[DyNTS_CollectionGrowthMonitor] auto-install skipped (non-fatal):', cgmError);
601
+ }
602
+
603
+ if (!extended) {
604
+ await this.ready();
605
+
606
+ if (this.params.title) {
607
+ DyFM_Log.success(this.params.title);
608
+ }
609
+ DyFM_Log.info(`Version: ${this.params.version}`);
610
+ /* DyFM_Log.info(`NTS Version: ${this.ntsVersion}`); */
611
+ DyFM_Log.H_success(`${this.params.name} started successfully.`);
612
+ }
613
+ } catch (error) {
614
+ this.constructErrors.push(error);
615
+
616
+ if (this.deepLog) {
617
+ if (DyNTS_global_settings.log_settings.highDetailedLogs) {
618
+ DyFM_Log.H_error(
619
+ `"${this._params.name}" start failed (in asyncConstruct (highDetailedLog)). `,
620
+ `\n\n construct ERRORS:`, this.constructErrors,
621
+ '\n\nlast error:', error
622
+ );
623
+ } else {
624
+ DyFM_Log.H_error(
625
+ `"${this._params.name}" start failed (in asyncConstruct). `,
626
+ `\n\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
627
+ '\n\nlast error:', error instanceof DyFM_Error ? error.getErrorSimplified() : error
628
+ );
629
+ }
630
+ }
631
+
632
+ throw new DyFM_Error({
633
+ ...this._getDefaultErrorSettings('asyncConstruct', error),
634
+
635
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-001`,
636
+ additionalContent: {
637
+ constructErrors: this.constructErrors,
638
+ systemControls: this.systemControls,
639
+ systemReadies: {
640
+ app: this.systemControls.app.getIsReady(),
641
+ mongoose: this.systemControls.mongoose.getIsReady(),
642
+ httpServer: this.systemControls.httpServer.getIsReady(),
643
+ httpsServer: this.systemControls.httpsServer.getIsReady(),
644
+ },
645
+ },
646
+ });
647
+ }
648
+ }
649
+
650
+ async ready(timeout: number = this.defaultReadyTimeout): Promise<void> {
651
+ try {
652
+ if (this.fnLogs) DyFM_Log.log('\nfn:. ready');
653
+
654
+ await DyFM_Async.delay(100);
655
+
656
+ let ready: boolean = false;
657
+ const start: number = +new Date();
658
+
659
+ if (this.constructErrors.length) {
660
+ if (this.deepLog) {
661
+ if (DyNTS_global_settings.log_settings.highDetailedLogs) {
662
+ DyFM_Log.H_error(
663
+ `"${this._params.name}" start failed. (ready; constructErrors check 1)`,
664
+ `\n construct ERRORS:`, this.constructErrors
665
+ );
666
+ } else {
667
+ DyFM_Log.H_error(
668
+ `"${this._params.name}" start failed. (ready; constructErrors check 1)`,
669
+ `\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
670
+ );
671
+ }
672
+ }
673
+
674
+ throw new DyFM_Error({
675
+ ...this._getDefaultErrorSettings(
676
+ 'ready',
677
+ new Error(`"${this._params.name}" start failed.`)
678
+ ),
679
+
680
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R01`,
681
+ additionalContent:
682
+ this.constructErrors.length === 1 ?
683
+ { error: this.constructErrors[0] } :
684
+ { errors: this.constructErrors },
685
+ });
686
+ }
687
+
688
+ while (!ready && +new Date() - start < timeout) {
689
+ if (this.systemControls.app.init) {
690
+ ready = (
691
+ this.systemControls.mongoose.getIsReady() &&
692
+ this.systemControls.httpServer.getIsReady() &&
693
+ this.systemControls.httpsServer.getIsReady()
694
+ );
695
+ } else {
696
+ DyFM_Log.error(`"${this._params.name}" APP NOT INITIALIZED while trying to get ready.`);
697
+ }
698
+
699
+ if (!ready) {
700
+ await DyFM_Async.wait(100);
701
+ }
702
+ }
703
+
704
+ if (timeout < +new Date() - start) {
705
+ if (this.deepLog) {
706
+ if (DyNTS_global_settings.log_settings.highDetailedLogs) {
707
+ DyFM_Log.H_error(
708
+ `"${this._params.name}" start failed. (ready; TIMEOUT check)`,
709
+ `\n construct ERRORS:`, this.constructErrors
710
+ );
711
+ } else {
712
+ DyFM_Log.H_error(
713
+ `"${this._params.name}" start failed. (ready; TIMEOUT check)`,
714
+ `\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
715
+ );
716
+ }
717
+ }
718
+
719
+ throw new DyFM_Error({
720
+ ...this._getDefaultErrorSettings(
721
+ 'ready',
722
+ new Error(`"${this._params.name}" start failed. TIMEOUT`)
723
+ ),
724
+
725
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R02`,
726
+ additionalContent: {
727
+ constructErrors: this.constructErrors,
728
+ systemControls: this.systemControls,
729
+ systemReadies: {
730
+ mongoose: this.systemControls.mongoose.getIsReady(),
731
+ httpServer: this.systemControls.httpServer.getIsReady(),
732
+ httpsServer: this.systemControls.httpsServer.getIsReady(),
733
+ },
734
+ },
735
+ });
736
+ }
737
+
738
+ if (this.constructErrors.length) {
739
+ if (this.deepLog) {
740
+ if (DyNTS_global_settings.log_settings.highDetailedLogs) {
741
+ DyFM_Log.H_error(
742
+ `"${this._params.name}" start failed. (ready; constructErrors check 2)`,
743
+ `\n construct ERRORS:`, this.constructErrors
744
+ );
745
+ } else {
746
+ DyFM_Log.H_error(
747
+ `"${this._params.name}" start failed. (ready; constructErrors check 2)`,
748
+ `\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
749
+ );
750
+ }
751
+ }
752
+
753
+ throw new DyFM_Error({
754
+ ...this._getDefaultErrorSettings(
755
+ 'ready',
756
+ new Error(`"${this._params.name}" start failed.`)
757
+ ),
758
+
759
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R03`,
760
+ additionalContent: this.constructErrors,
761
+ });
762
+ }
763
+
764
+ if (ready) {
765
+ this.systemControls.app.started = true;
766
+
767
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. ready: return');
768
+
769
+ return;
770
+ }
771
+
772
+ this.systemControls.app.started = false;
773
+
774
+ let msg: string = `"${this._params.name}" start failed. UNKNOWN`;
775
+
776
+ if (this.systemControls.mongoose.init && !this.systemControls.mongoose.started) {
777
+ msg += `\nMongoose start failed.`;
778
+ }
779
+
780
+ if (this.systemControls.httpServer.init && !this.systemControls.httpServer.started) {
781
+ msg += `\nHTTP Server start failed.`;
782
+ }
783
+
784
+ if (this.systemControls.httpsServer.init && !this.systemControls.httpsServer.started) {
785
+ msg += `\nHTTPS Server start failed.`;
786
+ }
787
+
788
+ DyFM_Log.error(msg, this.constructErrors);
789
+
790
+ throw new DyFM_Error({
791
+ ...this._getDefaultErrorSettings('ready', new Error(msg)),
792
+
793
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R04`,
794
+ additionalContent: {
795
+ constructErrors: this.constructErrors,
796
+ systemControls: this.systemControls,
797
+ systemReadies: {
798
+ app: this.systemControls.app.getIsReady(),
799
+ mongoose: this.systemControls.mongoose.getIsReady(),
800
+ httpServer: this.systemControls.httpServer.getIsReady(),
801
+ httpsServer: this.systemControls.httpsServer.getIsReady(),
802
+ },
803
+ },
804
+ error: this.constructErrors?.[0] ?? new Error(),
805
+ });
806
+ } catch (error) {
807
+ throw new DyFM_Error({
808
+ ...this._getDefaultErrorSettings('ready', error),
809
+
810
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-READY0`,
811
+ });
812
+ }
813
+ }
814
+
815
+ protected getSimplifiedConstructErrors(): string[] {
816
+ return this.constructErrors.map((error: any): any => {
817
+ if (error instanceof DyFM_Error) {
818
+ return error.getErrorSimplified();
819
+ } else {
820
+ return error;
821
+ }
822
+ });
823
+ }
824
+
825
+ async stop(dontLog?: boolean): Promise<void> {
826
+ try {
827
+ DyFM_Log.info('\nstopping server...\n');
828
+
829
+ await this.ready();
830
+
831
+ if (this.started) {
832
+
833
+ if (this.systemControls.mongoose.init) {
834
+ DyFM_Log.info(`\nstopping Mongoose....`);
835
+
836
+ let tryCount: number = 0;
837
+
838
+ while (
839
+ !this.systemControls.mongoose.started &&
840
+ !this.constructErrors.length &&
841
+ tryCount++ < 10
842
+ ) {
843
+ DyFM_Log.warn(`Mongoose not even started yet....`);
844
+ await DyFM_Async.wait(second);
845
+ }
846
+ this.systemControls.mongoose.started = false;
847
+
848
+ if (this.mongoose) {
849
+ await DyFM_Array.asyncForEach(
850
+ Object.keys(this.mongoose.models),
851
+ async (modelName): Promise<void> => {
852
+ this.mongoose.deleteModel(modelName);
853
+ }
854
+ );
855
+
856
+ const disconnect: Promise<void> = new Promise((resolve): void => {
857
+ this.mongoose.connection.on('disconnecting', (): void => {
858
+ resolve();
859
+ });
860
+ });
861
+
862
+ await this.mongoose.disconnect();
863
+ await this.mongoose.connection.close();
864
+ await disconnect;
865
+
866
+ this.mongoose.connection.removeAllListeners();
867
+
868
+ while (
869
+ this.mongoose.connection.readyState !== 0 &&
870
+ !this.constructErrors.length
871
+ ) {
872
+ DyFM_Log.warn(`\nMongoose still not disconnected....`);
873
+ await DyFM_Async.wait(second);
874
+ }
875
+ } else {
876
+ DyFM_Log.error(`\nMongoose not found.`);
877
+ }
878
+ this.systemControls.mongoose.init = false;
879
+ }
880
+
881
+ if (this.systemControls.httpServer.init) {
882
+ this.systemControls.httpServer.started = false;
883
+
884
+ if (this.httpServer) {
885
+ await new Promise((resolve): void => {
886
+ this.httpServer.close(resolve);
887
+ });
888
+ } else {
889
+ DyFM_Log.error(`\nHTTP Server not found.`);
890
+ }
891
+ this.systemControls.httpServer.init = false;
892
+ }
893
+
894
+ if (this.systemControls.httpsServer.init) {
895
+ this.systemControls.httpsServer.started = false;
896
+
897
+ if (this.httpsServer) {
898
+ await new Promise((resolve): void => {
899
+ this.httpsServer.close(resolve);
900
+ });
901
+ } else {
902
+ DyFM_Log.error(`\nHTTPS Server not found.`);
903
+ }
904
+ this.systemControls.httpsServer.init = false;
905
+ }
906
+
907
+ await DyFM_Async.wait(second);
908
+
909
+ if (!dontLog) {
910
+ DyFM_Log.H_log(`"${this._params.name}" stopped successfully.`);
911
+ }
912
+ }
913
+ } catch (error) {
914
+ throw new DyFM_Error({
915
+ ...this._getDefaultErrorSettings('stop', error),
916
+
917
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-STOP0`,
918
+ });
919
+ }
920
+ }
921
+
922
+ /**
923
+ *
924
+ */
925
+ private async startDB(): Promise<void> {
926
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. startDB');
927
+ else if (this.logSetup) DyFM_Log.log('\nstarting DB connection...');
928
+
929
+ if (!this._params.dbUri) {
930
+ throw new DyFM_Error({
931
+ ...this._getDefaultErrorSettings('startDB', new Error('DB URI is not set.')),
932
+
933
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
934
+ });
935
+ }
936
+
937
+ if (!this._params.dbOptions) {
938
+ throw new DyFM_Error({
939
+ ...this._getDefaultErrorSettings('startDB', new Error('DB OPTIONS are not set.')),
940
+
941
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
942
+ });
943
+ }
944
+
945
+ if (this.systemControls.mongoose.init || this.systemControls.mongoose.started) {
946
+ throw new DyFM_Error({
947
+ ...this._getDefaultErrorSettings('startDB', new Error('Mongoose is already initialized.')),
948
+
949
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
950
+ });
951
+ }
952
+
953
+ try {
954
+ await new Promise<void>(
955
+ (resolve, reject): void => {
956
+ this.systemControls.mongoose.init = true;
957
+
958
+ this.mongoose.connection
959
+ .once('open', (): void => {
960
+ this.systemControls.mongoose.started = true;
961
+ DyFM_Log.success(`\nConnected to MongoDB (${this._params.dbUri})\n`);
962
+
963
+ resolve();
964
+
965
+ // FR-258 / SR-2 — install declared-retention TTL indexes. DEFERRED + fire-and-forget +
966
+ // fully non-fatal: a create-if-missing index op (and the `indexes()` probes) must NOT
967
+ // compete with boot-readiness. We delay it well past the deploy health-probe window so a
968
+ // cold boot is never slowed by it, then run it detached. `.unref()` keeps it from holding
969
+ // the event loop open. Any failure is logged but never crashes the app. (`'differs'` never
970
+ // rebuilds a live index — see ensureRetentionTtlIndex.)
971
+ const ttlInstallTimer: ReturnType<typeof setTimeout> = setTimeout((): void => {
972
+ void this.installRetentionTtlIndexes();
973
+ }, 30000);
974
+ if (typeof ttlInstallTimer.unref === 'function') { ttlInstallTimer.unref(); }
975
+ })
976
+ .on('error', (error): void => {
977
+ if (!this.systemControls.mongoose.started) {
978
+ // Initial DB-csatlakozás sikertelen:
979
+ // jelezzük a hibát (log + globalErrorHandler), de NEM szakítjuk meg az
980
+ // App startup-ot (nincs constructErrors push, nincs reject).
981
+ // A mongoose.init-et resetteljük, hogy a ready() ne várjon a DB-re.
982
+ // Ha a mongoose később mégis tudna csatlakozni, az 'open' event
983
+ // beállítja a started flag-et, így a runtime DB-műveletek elindulnak.
984
+ this.systemControls.mongoose.init = false;
985
+
986
+ const d_error: DyFM_Error = new DyFM_Error({
987
+ ...this._getDefaultErrorSettings('startDB', error),
988
+
989
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB1`,
990
+ message: `Unable to connect to MongoDB server (${this._params.dbUri}), ` +
991
+ `ERROR: ${error}`,
992
+ level: DyFM_ErrorLevel.serious,
993
+ });
994
+
995
+ DyFM_Log.H_error(
996
+ `\nUnable to connect to MongoDB server (${this._params.dbUri}).` +
997
+ `\nServer will continue WITHOUT DB connection.` +
998
+ `\nDB-using endpoints will fail at runtime until connection recovers.`
999
+ );
1000
+
1001
+ if (this.debugLog) DyFM_Log.S_error(
1002
+ `\nMongoDB connect ERROR: `,
1003
+ error
1004
+ );
1005
+
1006
+ DyNTS_GlobalService.globalErrorHandler?.(d_error);
1007
+
1008
+ resolve();
1009
+
1010
+ } else {
1011
+ if (this.debugLog) DyFM_Log.error('\nMongoDB ERROR: ', error);
1012
+
1013
+ const d_error: DyFM_Error = new DyFM_Error({
1014
+ ...this._getDefaultErrorSettings('mongoose.connection.on(error)', error),
1015
+
1016
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB2`,
1017
+ message: `MongoDB ERROR: ${error}`,
1018
+ level: DyFM_ErrorLevel.critical,
1019
+ });
1020
+
1021
+ DyNTS_GlobalService.globalErrorHandler?.(d_error);
1022
+ }
1023
+ });
1024
+
1025
+ try {
1026
+ this.mongoose.connect(
1027
+ this._params.dbUri,
1028
+ this._params.dbOptions
1029
+ /* {
1030
+ directConnection: true,
1031
+ } */
1032
+ );
1033
+ } catch (error) {
1034
+ throw new DyFM_Error({
1035
+ ...this._getDefaultErrorSettings('startDB', error),
1036
+
1037
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB3`,
1038
+ });
1039
+ }
1040
+ }
1041
+ );
1042
+ } catch (error) {
1043
+ throw new DyFM_Error({
1044
+ ...this._getDefaultErrorSettings('startDB', error),
1045
+
1046
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
1047
+ });
1048
+ }
1049
+
1050
+ // 2026-06-20 — Mongo reconnect-guard. A MongoDB-driver a hostnevet connect-kor EGYSZER
1051
+ // resolválja + cache-eli az IP-t; ha a Mongo-konténert recreate-elik (új docker-network IP),
1052
+ // a driver a HALOTT IP-n ragad → ECONNREFUSED + buffering-timeout, és a service magától SOHA
1053
+ // nem áll vissza. A guard sustained-disconnect (readyState !== 1) esetén — a driver saját
1054
+ // grace-e UTÁN — TELJES disconnect()+connect()-et csinál → ÚJ MongoClient → ÚJ DNS-resolve →
1055
+ // új IP → reconnect. Best-effort, always-on, healthy connection-t (===1) SOHA nem bánt; csak
1056
+ // konténer-IP-frissítés, nem ír adatot. Lásd: mongo-reconnect-guard.util.ts.
1057
+ try {
1058
+ startMongoReconnectGuard({
1059
+ getReadyState: (): number => this.mongoose.connection.readyState,
1060
+ reconnect: async (): Promise<void> => {
1061
+ await this.mongoose.disconnect().catch((): void => undefined);
1062
+ await this.mongoose.connect(this._params.dbUri, this._params.dbOptions);
1063
+ },
1064
+ log: (msg: string): void => DyFM_Log.warn(msg),
1065
+ });
1066
+ } catch (guardErr) {
1067
+ DyFM_Log.warn(`[mongo-reconnect-guard] failed to start (non-fatal): ${guardErr instanceof Error ? guardErr.message : String(guardErr)}`);
1068
+ }
1069
+ }
1070
+
1071
+ /**
1072
+ * FR-258 / SR-2 — install MongoDB TTL indexes for every data-model that declared `retention`.
1073
+ *
1074
+ * Runs ONCE right after the DB connection opens. For each registered DB service (including the
1075
+ * auto-created `_archived` siblings, which inherit the parent model's `retention`), it ensures a
1076
+ * TTL index on the `__created` Date field with the resolved `expireAfterSeconds` — so MongoDB
1077
+ * NATIVELY auto-deletes documents older than the configured age. This is the fleet-wide defense
1078
+ * against the unbounded-collection-growth → in-memory-load → GC-thrash/OOM class.
1079
+ *
1080
+ * Guarantees:
1081
+ * - **Non-fatal** — any error is logged but NEVER blocks startup (called fire-and-forget).
1082
+ * - **Idempotent** — an existing index with the same TTL is a no-op; a CHANGED retention (different
1083
+ * `expireAfterSeconds`, or an existing non-TTL `__created` index) is reconciled by drop+recreate
1084
+ * (the field index is restored immediately, so query coverage is preserved).
1085
+ */
1086
+ private async installRetentionTtlIndexes(): Promise<void> {
1087
+ try {
1088
+ const services: DyNTS_DBService<any>[] = DyNTS_GlobalService.getAllDBServices();
1089
+ let ensured: number = 0;
1090
+
1091
+ for (const service of services) {
1092
+ const ttlSeconds: number | undefined = DyFM_resolveRetentionTtlSeconds(service?.dataParams?.retention);
1093
+ if (!ttlSeconds) { continue; }
1094
+
1095
+ const dataName: string = service.dataParams.dataName;
1096
+ // The mongoose Model exposes the native driver collection (.indexes / .createIndex / .dropIndex).
1097
+ const collection: DyNTS_TtlIndexCollection | undefined =
1098
+ (service?.dataModel as unknown as { collection?: DyNTS_TtlIndexCollection })?.collection;
1099
+ if (!collection || typeof collection.createIndex !== 'function') { continue; }
1100
+
1101
+ try {
1102
+ const action: DyNTS_TtlIndexAction = await DyNTS_App.ensureRetentionTtlIndex(collection, ttlSeconds);
1103
+ if (action === 'created') {
1104
+ ensured++;
1105
+ if (this.logSetup) {
1106
+ DyFM_Log.success(
1107
+ `[FR-258 retention] TTL index created on "${dataName}" — ` +
1108
+ `${Math.round(ttlSeconds / 86400)}d (${ttlSeconds}s)`,
1109
+ );
1110
+ }
1111
+ } else if (action === 'differs') {
1112
+ // Live index has a different TTL — left untouched at boot (see ensureRetentionTtlIndex doc).
1113
+ DyFM_Log.warn(
1114
+ `[FR-258 retention] "${dataName}" already has a {__created} index with a DIFFERENT TTL than the ` +
1115
+ `declared ${Math.round(ttlSeconds / 86400)}d (${ttlSeconds}s) — left as-is (no boot-time rebuild). ` +
1116
+ `Apply the change via maintenance if intended.`,
1117
+ );
1118
+ }
1119
+ } catch (idxErr: unknown) {
1120
+ DyFM_Log.warn(
1121
+ `[FR-258 retention] TTL index on "${dataName}" failed (non-fatal): ` +
1122
+ `${idxErr instanceof Error ? idxErr.message : String(idxErr)}`,
1123
+ );
1124
+ }
1125
+ }
1126
+
1127
+ if (ensured > 0) {
1128
+ DyFM_Log.success(`[FR-258 retention] ${ensured} TTL index(es) ensured (auto-retention active).`);
1129
+ }
1130
+ } catch (err: unknown) {
1131
+ DyFM_Log.warn(
1132
+ `[FR-258 retention] TTL-installer failed (non-fatal): ` +
1133
+ `${err instanceof Error ? err.message : String(err)}`,
1134
+ );
1135
+ }
1136
+ }
1137
+
1138
+ /**
1139
+ * FR-258 / SR-2 — ensure a single `{ __created: 1 }` TTL index with the given `expireAfterSeconds`.
1140
+ * Extracted as a pure-ish static so it is unit-testable with a mock collection. Idempotent + BOOT-SAFE:
1141
+ * - no existing `__created` index → create it → `'created'`
1142
+ * - existing with the SAME TTL → no-op → `'noop'`
1143
+ * - existing with a DIFFERENT TTL / non-TTL → leave it as-is → `'differs'` (warn only — NO drop+recreate)
1144
+ *
1145
+ * The `'differs'` case intentionally does NOT mutate the live index. Dropping + recreating a TTL index on a
1146
+ * large (multi-GB) production collection is a heavy server-side operation; doing it automatically inside the
1147
+ * startup path can starve the concurrent boot queries (including the deploy health-probe) and trigger a
1148
+ * fail-safe revert. Create-if-missing is the essential growth-prevention behaviour; a deliberate retention
1149
+ * CHANGE on an already-indexed collection is a maintenance action, not a silent every-boot rebuild.
1150
+ */
1151
+ static async ensureRetentionTtlIndex(
1152
+ collection: DyNTS_TtlIndexCollection,
1153
+ ttlSeconds: number,
1154
+ ): Promise<DyNTS_TtlIndexAction> {
1155
+ const existingList: DyNTS_TtlIndexInfo[] = typeof collection.indexes === 'function'
1156
+ ? await collection.indexes().catch((): DyNTS_TtlIndexInfo[] => [])
1157
+ : [];
1158
+ const existing: DyNTS_TtlIndexInfo | undefined =
1159
+ existingList.find((ix): boolean => !!ix?.key && ix.key.__created === 1);
1160
+
1161
+ if (!existing) {
1162
+ await collection.createIndex({ __created: 1 }, { expireAfterSeconds: ttlSeconds });
1163
+ return 'created';
1164
+ }
1165
+ if (existing.expireAfterSeconds === ttlSeconds) {
1166
+ return 'noop';
1167
+ }
1168
+ // Retention differs from the live index (or it is a non-TTL `__created` index). Leave it UNTOUCHED at
1169
+ // boot — only report it. Avoids a heavy drop+recreate competing with boot-readiness on a large collection.
1170
+ return 'differs';
1171
+ }
1172
+
1173
+ /**
1174
+ *
1175
+ */
1176
+ private async initExpresses(): Promise<void> {
1177
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. initExpresses');
1178
+
1179
+ try {
1180
+ if (this._security && this._security !== DyNTS_RouteSecurity.secure) {
1181
+ if (this._portSettings.httpPort === undefined || this._portSettings.httpPort === null) {
1182
+ let errorMsg: string =
1183
+ `\nYou have open routes, but httpPort is not set!` +
1184
+ `\nThere are ${this._routingModules.filter(
1185
+ m => m.security != DyNTS_RouteSecurity.secure
1186
+ ).length} open/both routes` +
1187
+ `\nroot security: ${this._security}` +
1188
+ `\nset httpPort in DynamoBEServer - setupRoutingModules() to enable secure routes.`;
1189
+
1190
+ errorMsg += '\n\nThe routes setted to use open server:';
1191
+ this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1192
+ if (module.security != DyNTS_RouteSecurity.secure) {
1193
+ errorMsg += `\n ${module.route} (security: ${module.security})`;
1194
+ errorMsg += `\n subroutes using open sever:`;
1195
+ module.endpoints.forEach((endpoint: DyNTS_Endpoint_Params): void => {
1196
+ if (endpoint.security != DyNTS_RouteSecurity.secure) {
1197
+ errorMsg += `\n ${endpoint.endpoint} (security: ${endpoint.security})`;
1198
+ }
1199
+ });
1200
+ }
1201
+ });
1202
+
1203
+ const error = new Error(`Open routes cannot be established!\n${errorMsg}`);
1204
+ const errorStack: string[] = error.stack.split('\n');
1205
+
1206
+ errorStack.splice(1, 2);
1207
+ error.stack = errorStack.join('\n');
1208
+
1209
+ DyFM_Log.error(errorMsg);
1210
+
1211
+ throw error;
1212
+ }
1213
+
1214
+ await this.initOpenExpress();
1215
+ }
1216
+
1217
+ if (this._security && this._security !== DyNTS_RouteSecurity.open) {
1218
+ if (!this._cert || !this._portSettings.httpsPort) {
1219
+ let errorMsg: string =
1220
+ `\nYou have secure routes, but the certification paths or httpsPort are not set!` +
1221
+ `\nThere are ${this._routingModules.filter(
1222
+ m => m.security && m.security !== DyNTS_RouteSecurity.open
1223
+ ).length} secure routes` +
1224
+ `\nroot security: ${this._security}` +
1225
+ `\nset...` +
1226
+ `\n(missing exact howto...)` +
1227
+ /* `\n httpsPort and` +
1228
+ `\n cert: {` +
1229
+ `\n keyPath: FileSystem.PathLike,` +
1230
+ `\n certPath: FileSystem.PathLike,` +
1231
+ `\n }` + */
1232
+ `\nin DynamoBEServer - getRoutingModules() to enable secure routes.`;
1233
+
1234
+ errorMsg += '\n\nThe routes setted to use secure server:';
1235
+ this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1236
+ if (module.security && module.security !== DyNTS_RouteSecurity.open) {
1237
+ errorMsg += `\n ${module.route} (security: ${module.security})`;
1238
+ errorMsg += `\n location: ${module.stackLocation}`;
1239
+ errorMsg += `\n subroutes using secure sever:`;
1240
+ module.endpoints.forEach((endpoint: DyNTS_Endpoint_Params): void => {
1241
+ if (endpoint.security && endpoint.security !== DyNTS_RouteSecurity.open) {
1242
+ errorMsg += `\n ${endpoint.endpoint} (security: ${endpoint.security})`;
1243
+ errorMsg += `\n location: ${endpoint.stackLocation}`;
1244
+ }
1245
+ });
1246
+ }
1247
+ });
1248
+
1249
+ const error = new Error(`Secure routes cannot be established!\n${errorMsg}`);
1250
+ const errorStack: string[] = error.stack.split('\n');
1251
+
1252
+ errorStack.splice(1, 2);
1253
+ error.stack = errorStack.join('\n');
1254
+
1255
+ DyFM_Log.error(errorMsg);
1256
+
1257
+ throw error;
1258
+ }
1259
+
1260
+ await this.initSecureExpress();
1261
+ }
1262
+ } catch (error) {
1263
+ throw new DyFM_Error({
1264
+ ...this._getDefaultErrorSettings('initExpresses', error),
1265
+
1266
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-IE0`,
1267
+ });
1268
+ }
1269
+ }
1270
+
1271
+ /**
1272
+ *
1273
+ */
1274
+ protected async initOpenExpress(): Promise<void> {
1275
+ if (this.fnLogs) DyFM_Log.log('\nfn:. initOpenExpress');
1276
+ this.openExpress = Express();
1277
+ this.openExpress.set('maxHeaderSize', 10 * megabyte); // 1024 * 1024 * 10, // 10MB
1278
+ this.openExpress.use(BodyParser.urlencoded(this._portSettings.httpUrlencoded));
1279
+ this.openExpress.use(BodyParser.json(this._portSettings.httpJson));
1280
+ // FR-041 — CORS allowlist enforcement. No-op if getCorsSettings() is not overridden.
1281
+ this.mountCors(this.openExpress);
1282
+ }
1283
+
1284
+ /**
1285
+ *
1286
+ */
1287
+ protected async initSecureExpress(): Promise<void> {
1288
+ if (this.fnLogs) DyFM_Log.log('\nfn:. initSecureExpress');
1289
+ this.secureExpress = Express();
1290
+ this.secureExpress.use(BodyParser.urlencoded(this._portSettings.httpsUrlencoded));
1291
+ this.secureExpress.use(BodyParser.json(this._portSettings.httpsJson));
1292
+ // FR-041 — CORS allowlist enforcement (same as open express).
1293
+ this.mountCors(this.secureExpress);
1294
+
1295
+ const options = {
1296
+ key: FileSystem.readFileSync(this._cert.keyPath),
1297
+ cert: FileSystem.readFileSync(this._cert.certPath),
1298
+ maxHeaderSize: 10 * megabyte, // 1024 * 1024 * 10, // 10MB
1299
+ };
1300
+
1301
+ this.httpsServer = Https.createServer(options, this.secureExpress);
1302
+ }
1303
+
1304
+ /**
1305
+ *
1306
+ */
1307
+ private async startExpresses(): Promise<void> {
1308
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. startExpresses');
1309
+
1310
+ try {
1311
+ if (this._security && this._security !== DyNTS_RouteSecurity.open) {
1312
+ await new Promise<void>((resolve, reject): void => {
1313
+ this.systemControls.httpsServer.init = true;
1314
+ this.httpsServer
1315
+ .listen(
1316
+ this._portSettings.httpsPort,
1317
+ this.params.secureHost,
1318
+ this.params.expressBacklog,
1319
+ (): void => {
1320
+ this.systemControls.httpsServer.started = true;
1321
+ DyFM_Log.success(
1322
+ `\nHTTPS (secure) server is listening on port: ` +
1323
+ `${this.params.secureHost}:${this._portSettings.httpsPort}`
1324
+ );
1325
+
1326
+ resolve();
1327
+ })
1328
+ .on('error', (error): void => {
1329
+ if (this.debugLog) DyFM_Log.error(`\nHTTPS (secure) server ERROR`, error);
1330
+
1331
+ if (!this.systemControls.httpsServer.started) {
1332
+ const d_error: DyFM_Error = new DyFM_Error({
1333
+ ...this._getDefaultErrorSettings('startExpresses', error),
1334
+
1335
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE1`,
1336
+ message: `HTTPS (secure) start server ERROR`,
1337
+ });
1338
+
1339
+ this.constructErrors.push(d_error);
1340
+ DyNTS_GlobalService.globalErrorHandler?.(d_error);
1341
+
1342
+ reject(d_error);
1343
+
1344
+ } else {
1345
+ const d_error: DyFM_Error = new DyFM_Error({
1346
+ ...this._getDefaultErrorSettings('httpsServer.on(error)', error),
1347
+
1348
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE2`,
1349
+ message: `HTTPS (secure) server ERROR`,
1350
+ level: DyFM_ErrorLevel.serious,
1351
+ });
1352
+
1353
+ DyNTS_GlobalService.globalErrorHandler?.(d_error);
1354
+ }
1355
+ })
1356
+ .on('uncaughtException', (exception): void => {
1357
+ const d_error: DyFM_Error = new DyFM_Error({
1358
+ ...this._getDefaultErrorSettings('httpsServer.on(uncaughtException)', exception),
1359
+
1360
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE3`,
1361
+ message: `HTTPS (secure) server uncaughtException`,
1362
+ level: DyFM_ErrorLevel.critical,
1363
+ });
1364
+
1365
+ if (this.debugLog) DyFM_Log.warn(
1366
+ `\nHTTPS (secure) server uncaughtException`,
1367
+ d_error
1368
+ );
1369
+
1370
+ DyNTS_GlobalService.globalErrorHandler?.(d_error);
1371
+ });
1372
+ });
1373
+ }
1374
+
1375
+ if (this._security && this._security !== DyNTS_RouteSecurity.secure) {
1376
+ this.systemControls.httpServer.init = true;
1377
+ await new Promise<void>((resolve, reject): void => {
1378
+ this.httpServer = this.openExpress
1379
+ .listen(
1380
+ this._portSettings.httpPort,
1381
+ this.params.openHost,
1382
+ this.params.expressBacklog,
1383
+ (): void => {
1384
+ this.systemControls.httpServer.started = true;
1385
+
1386
+ const resolvedPort: number = this.httpServer?.address?.()?.['port'] ?? this._portSettings.httpPort;
1387
+
1388
+ if (this._portSettings.httpPort === 0) {
1389
+ DyFM_Log.H_warn(
1390
+ `\nHTTP (open) server is using a randomly selected port by the OS: ${resolvedPort}` +
1391
+ `\n (httpPort was set to 0 — this is intended for testing only)`
1392
+ );
1393
+ }
1394
+
1395
+ DyFM_Log.success(
1396
+ `\nHTTP (open) server is listening on port: ` +
1397
+ `${this.params.openHost}:${resolvedPort}`
1398
+ );
1399
+
1400
+ resolve();
1401
+ }
1402
+ )
1403
+ .on('error', (error): void => {
1404
+ if (this.debugLog) DyFM_Log.error(`\nHTTP (open) server ERROR`, error);
1405
+
1406
+ if (!this.systemControls.httpServer.started) {
1407
+ const d_error: DyFM_Error = new DyFM_Error({
1408
+ ...this._getDefaultErrorSettings('startExpresses', error),
1409
+
1410
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE3`,
1411
+ message: `HTTP (open) start server ERROR`,
1412
+ });
1413
+
1414
+ this.constructErrors.push(d_error);
1415
+ DyNTS_GlobalService.globalErrorHandler?.(d_error);
1416
+
1417
+ reject(d_error);
1418
+
1419
+ } else {
1420
+ const d_error: DyFM_Error = new DyFM_Error({
1421
+ ...this._getDefaultErrorSettings('httpServer.on(error)', error),
1422
+
1423
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE4`,
1424
+ message: `HTTP (open) server ERROR`,
1425
+ level: DyFM_ErrorLevel.serious,
1426
+ });
1427
+
1428
+ DyNTS_GlobalService.globalErrorHandler?.(d_error);
1429
+ }
1430
+ })
1431
+ .on('uncaughtException', (exception): void => {
1432
+ const d_error: DyFM_Error = new DyFM_Error({
1433
+ ...this._getDefaultErrorSettings('httpServer.on(uncaughtException)', exception),
1434
+
1435
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE5`,
1436
+ message: `HTTP (open) server uncaughtException`,
1437
+ level: DyFM_ErrorLevel.critical,
1438
+ });
1439
+
1440
+ if (this.debugLog) {
1441
+ DyFM_Log.warn(`\nHTTP (open) server uncaughtException`, d_error);
1442
+ }
1443
+
1444
+ DyNTS_GlobalService.globalErrorHandler?.(d_error);
1445
+ });
1446
+ });
1447
+ }
1448
+ } catch (error) {
1449
+ throw new DyFM_Error({
1450
+ ...this._getDefaultErrorSettings('startExpresses', error),
1451
+
1452
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE0`,
1453
+ });
1454
+ }
1455
+ }
1456
+
1457
+ /**
1458
+ *
1459
+ */
1460
+ private async expressErrorHandling(error, req, res, next): Promise<void> {
1461
+ try {
1462
+ if (error) {
1463
+ const d_error: DyFM_Error = new DyFM_Error({
1464
+ ...this._getDefaultErrorSettings('expressErrorHandling', error),
1465
+
1466
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-EEH1`,
1467
+ message: `Express ERROR`,
1468
+ additionalContent: {
1469
+ req,
1470
+ res,
1471
+ },
1472
+ level: DyFM_ErrorLevel.error,
1473
+ });
1474
+
1475
+ await DyNTS_GlobalService.globalErrorHandler?.(d_error, req, res);
1476
+
1477
+ res.send(error)
1478
+ } else {
1479
+ DyFM_Log.H_error(
1480
+ 'WTF??? express error; without error?...' +
1481
+ '\nerr:', error,
1482
+ '\nreq:', req,
1483
+ '\nres:', res
1484
+ );
1485
+ }
1486
+ } catch (error) {
1487
+ DyFM_Log.H_error(
1488
+ 'MULTILEVEL ERROR (expressErrorHandling)....' +
1489
+ '\n', error
1490
+ );
1491
+ }
1492
+ }
1493
+
1494
+ /**
1495
+ *
1496
+ */
1497
+ private async mountSecureRoutes (): Promise<void> {
1498
+ try {
1499
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. mountSecureRoutes');
1500
+
1501
+ if (!this.secureExpress) {
1502
+ throw new Error(
1503
+ 'secureExpress was not initialized. ' +
1504
+ 'Secure routes require getCertificationSettings and httpsPort, and cert files must exist.' +
1505
+ '\n\nYou need to set security to secure or both in any route and set httpsPort in getPortSettings.' +
1506
+ '\n\nYou need to set cert files in getCertificationSettings.'
1507
+ );
1508
+ }
1509
+
1510
+ this.secureExpress.use(
1511
+ (error, req, res, next): Promise<void> => this.expressErrorHandling(error, req, res, next)
1512
+ );
1513
+
1514
+ await DyFM_Array.asyncForEach(
1515
+ this._routingModules,
1516
+ async (module: DyNTS_RoutingModule): Promise<void> => {
1517
+ if (module.security !== DyNTS_RouteSecurity.open) {
1518
+ if (this.logSetup) {
1519
+ DyFM_Log.log(`route mount (secure): ${module.route}`);
1520
+ }
1521
+
1522
+ const existingRoutes: DyNTS_RoutingModule[] = this._routingModules.filter(
1523
+ (mod: DyNTS_RoutingModule): boolean => mod.route === module.route
1524
+ );
1525
+
1526
+ if (1 < existingRoutes.length) {
1527
+ const error: Error = new Error(`ROUTE DUPLICATION: ${module.route}`);
1528
+ /* const errorStack: string[] = error.stack.split('\n');
1529
+
1530
+ errorStack.splice(1, 4);
1531
+ error.stack = errorStack.join('\n'); */
1532
+ error.stack = module.stackLocation;
1533
+
1534
+ DyFM_Log.S_error(`ROUTE DUPLICATION: ${module.route}`, error);
1535
+
1536
+ throw new DyFM_Error({
1537
+ ...this._getDefaultErrorSettings('mountSecureRoutes', error),
1538
+
1539
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MSR1`,
1540
+ message: `ROUTE DUPLICATION: ${module.route}`,
1541
+ });
1542
+ }
1543
+
1544
+ this.secureExpress.use(module.route, module.secureRouter);
1545
+ }
1546
+ }
1547
+ );
1548
+ } catch (error) {
1549
+ throw new DyFM_Error({
1550
+ ...this._getDefaultErrorSettings('mountSecureRoutes', error),
1551
+
1552
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MSR0`,
1553
+ });
1554
+ }
1555
+ }
1556
+
1557
+ /**
1558
+ *
1559
+ */
1560
+ private async mountOpenRoutes(): Promise<void> {
1561
+ try {
1562
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. mountOpenRoutes');
1563
+
1564
+ if (!this.openExpress) {
1565
+ throw new Error(
1566
+ 'openExpress was not initialized. Open routes require getOpenExpress and httpPort.' +
1567
+ '\n\nYou need to set security to open or both in any route and set httpPort in getPortSettings.'
1568
+ );
1569
+ }
1570
+
1571
+ this.openExpress.use(
1572
+ (error, req, res, next): Promise<void> => this.expressErrorHandling(error, req, res, next)
1573
+ );
1574
+
1575
+ await DyFM_Array.asyncForEach(
1576
+ this._routingModules,
1577
+ async (module: DyNTS_RoutingModule): Promise<void> => {
1578
+ if (module.security !== DyNTS_RouteSecurity.secure) {
1579
+ if (this.logSetup) {
1580
+ DyFM_Log.log(`route mount (open): ${module.route}`);
1581
+ }
1582
+
1583
+ const existingRoutes: DyNTS_RoutingModule[] = this._routingModules.filter(
1584
+ (mod: DyNTS_RoutingModule): boolean => mod.route === module.route
1585
+ );
1586
+
1587
+ if (1 < existingRoutes.length) {
1588
+ const error: Error = new Error(`ROUTE DUPLICATION: ${module.route}`);
1589
+ /* const errorStack: string[] = error.stack.split('\n');
1590
+
1591
+ errorStack.splice(1, 4);
1592
+ error.stack = errorStack.join('\n'); */
1593
+ error.stack = module.stackLocation;
1594
+
1595
+ DyFM_Log.S_error(`ROUTE DUPLICATION: ${module.route}`, error);
1596
+
1597
+ throw new DyFM_Error({
1598
+ ...this._getDefaultErrorSettings('mountOpenRoutes', error),
1599
+
1600
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MOR1`,
1601
+ message: `ROUTE DUPLICATION: ${module.route}`,
1602
+ });
1603
+ }
1604
+
1605
+ this.openExpress.use(module.route, module.openRouter);
1606
+ }
1607
+ }
1608
+ );
1609
+ } catch (error) {
1610
+ throw new DyFM_Error({
1611
+ ...this._getDefaultErrorSettings('mountOpenRoutes', error),
1612
+
1613
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MOR0`,
1614
+ });
1615
+ }
1616
+ }
1617
+
1618
+ /**
1619
+ * FR-041 — CORS middleware. Echoes a matching `Access-Control-Allow-Origin`
1620
+ * for any request whose Origin header is in `getCorsSettings().allowedOrigins`,
1621
+ * adds the canonical `Access-Control-*` companion headers, and short-circuits
1622
+ * the OPTIONS preflight with a 204.
1623
+ *
1624
+ * No-op when the subclass does NOT override `getCorsSettings()` — preserves
1625
+ * back-compat for apps that have always been same-origin and never needed
1626
+ * CORS (the typical pre-FR-041 case).
1627
+ *
1628
+ * Why hand-rolled instead of the `cors` npm package:
1629
+ * - ~30 lines, zero new dependency.
1630
+ * - Full control over Vary/credentials/preflight semantics.
1631
+ * - Aligns with FDP "no unnecessary deps" philosophy.
1632
+ */
1633
+ protected mountCors(express: Express.Application): void {
1634
+ const settings: DyNTS_Cors_Settings | undefined = this.getCorsSettings?.();
1635
+ if (!settings) {
1636
+ return;
1637
+ }
1638
+
1639
+ const allowCreds: boolean = settings.allowCredentials !== false;
1640
+ const methods: string[] = settings.allowedMethods ?? [
1641
+ 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS',
1642
+ ];
1643
+ const headers: string[] = settings.allowedHeaders ?? [
1644
+ 'Authorization', 'Content-Type', 'X-Admin-Key', 'X-Requested-With',
1645
+ ];
1646
+ const exposed: string[] = settings.exposedHeaders ?? [
1647
+ 'Content-Length', 'Content-Type',
1648
+ ];
1649
+ const maxAge: number = settings.maxAgeSeconds ?? 86400;
1650
+
1651
+ const isAllowed: (origin: string) => boolean = (origin: string): boolean => {
1652
+ if (settings.allowedOrigins === '*') return true;
1653
+ if (typeof settings.allowedOrigins === 'function') {
1654
+ return settings.allowedOrigins(origin);
1655
+ }
1656
+ return settings.allowedOrigins.includes(origin);
1657
+ };
1658
+
1659
+ express.use((req: Express.Request, res: Express.Response, next: Express.NextFunction): void => {
1660
+ const origin: string | undefined = req.headers.origin;
1661
+ if (origin && isAllowed(origin)) {
1662
+ // Echo the matching origin (NOT wildcard) because credentials require it.
1663
+ res.setHeader('Access-Control-Allow-Origin', origin);
1664
+ if (allowCreds) {
1665
+ res.setHeader('Access-Control-Allow-Credentials', 'true');
1666
+ }
1667
+ res.setHeader('Access-Control-Allow-Methods', methods.join(', '));
1668
+ res.setHeader('Access-Control-Allow-Headers', headers.join(', '));
1669
+ res.setHeader('Access-Control-Expose-Headers', exposed.join(', '));
1670
+ res.setHeader('Access-Control-Max-Age', String(maxAge));
1671
+ res.setHeader('Vary', 'Origin');
1672
+ }
1673
+ if (req.method === 'OPTIONS') {
1674
+ res.status(204).end();
1675
+ return;
1676
+ }
1677
+ next();
1678
+ });
1679
+ }
1680
+
1681
+ /**
1682
+ * Generikus, auth-agnosztikus extension-point orchestrator. A `registerCustomMiddleware`
1683
+ * hookot hívja (ha a subclass override-olja) minden AKTÍV Express instance-ra
1684
+ * (open + secure), az API route-ok UTÁN, de a SPA static catch-all (`app.get('*')`)
1685
+ * ELŐTT — ez az EGYETLEN korrekt pont egy sub-path middleware-hez (pl. reverse-proxy),
1686
+ * mert a catch-all minden utána mountolt route-ot elnyel. No-op ha nincs override (back-compat).
1687
+ */
1688
+ private async mountCustomMiddleware(): Promise<void> {
1689
+ if (!this.registerCustomMiddleware) {
1690
+ return;
1691
+ }
1692
+
1693
+ if (this.openExpress) {
1694
+ await this.registerCustomMiddleware(this.openExpress, DyNTS_RouteSecurity.open);
1695
+ }
1696
+
1697
+ if (this.secureExpress) {
1698
+ await this.registerCustomMiddleware(this.secureExpress, DyNTS_RouteSecurity.secure);
1699
+ }
1700
+
1701
+ if (this.logSetup) {
1702
+ DyFM_Log.log('\nCustom middleware registered (pre-static).');
1703
+ }
1704
+ }
1705
+
1706
+ /**
1707
+ * Ha getStaticClientSettings() visszaad beállításokat, a client static fájlok a '/' alatt
1708
+ * lesznek kiszolgálva (API route-ok után). SPA fallback opcionális (fallbackPath).
1709
+ * Asset cache (assetCacheMaxAge, assetCacheImmutable) és fallback cache (fallbackCacheMaxAge)
1710
+ * opcionálisak; ha nincs megadva fallbackCacheMaxAge, DyNTS_defaultFallbackCacheMaxAge (0) marad.
1711
+ */
1712
+ private async mountStaticClient(): Promise<void> {
1713
+ const settings: DyNTS_StaticClient_Settings | undefined = this.getStaticClientSettings?.();
1714
+ if (!settings) {
1715
+ return;
1716
+ }
1717
+
1718
+ const absoluteRoot: string = Path.isAbsolute(settings.root)
1719
+ ? settings.root
1720
+ : Path.resolve(process.cwd(), settings.root);
1721
+
1722
+ const hasAssetCache: boolean =
1723
+ settings.assetCacheMaxAge !== undefined || settings.assetCacheImmutable === true;
1724
+ const staticOptions: { setHeaders: (res: Express.Response) => void } | undefined =
1725
+ hasAssetCache && settings.assetCacheMaxAge !== undefined
1726
+ ? {
1727
+ setHeaders: (res: Express.Response): void => {
1728
+ const maxAge: number = settings.assetCacheMaxAge!;
1729
+ const immutable: string =
1730
+ settings.assetCacheImmutable === true ? ', immutable' : '';
1731
+ res.setHeader('Cache-Control', `max-age=${maxAge}${immutable}`);
1732
+ },
1733
+ }
1734
+ : undefined;
1735
+
1736
+ const staticMiddleware: Express.Handler =
1737
+ staticOptions
1738
+ ? Express.static(absoluteRoot, staticOptions)
1739
+ : Express.static(absoluteRoot);
1740
+
1741
+ const fallbackMaxAge: number =
1742
+ settings.fallbackCacheMaxAge ?? DyNTS_defaultFallbackCacheMaxAge;
1743
+
1744
+ if (this.openExpress) {
1745
+ this.openExpress.use('/', staticMiddleware);
1746
+ if (settings.fallbackPath) {
1747
+ this.openExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1748
+ res.setHeader('Cache-Control', `max-age=${fallbackMaxAge}`);
1749
+ res.sendFile(settings.fallbackPath!, { root: absoluteRoot });
1750
+ });
1751
+ } else {
1752
+ this.openExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1753
+ res.status(404).type('html').send(DyNTS_defaultNotFoundPageHtml);
1754
+ });
1755
+ }
1756
+ }
1757
+
1758
+ if (this.secureExpress) {
1759
+ this.secureExpress.use('/', staticMiddleware);
1760
+ if (settings.fallbackPath) {
1761
+ this.secureExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1762
+ res.setHeader('Cache-Control', `max-age=${fallbackMaxAge}`);
1763
+ res.sendFile(settings.fallbackPath!, { root: absoluteRoot });
1764
+ });
1765
+ } else {
1766
+ this.secureExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1767
+ res.status(404).type('html').send(DyNTS_defaultNotFoundPageHtml);
1768
+ });
1769
+ }
1770
+ }
1771
+
1772
+ if (this.logSetup) {
1773
+ DyFM_Log.log(`\nStatic client mounted at / (root: ${absoluteRoot})`);
1774
+ }
1775
+ }
1776
+
1777
+ /**
1778
+ *
1779
+ */
1780
+ private setSecurity(): void {
1781
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. setSecurity');
1782
+ this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1783
+ if (!module.security) {
1784
+ DyFM_Log.warn(`RoutingModule security is not set for ${module.route}\n`);
1785
+
1786
+ } else if (!this._security) {
1787
+ this._security = module.security;
1788
+
1789
+ } else if (this._security !== module.security) {
1790
+ this._security = DyNTS_RouteSecurity.both;
1791
+ }
1792
+ });
1793
+
1794
+ if (!this._security) {
1795
+ let msg = `Could not set security for the server! (${this.security})`;
1796
+
1797
+ msg += '\n RoutingModules:';
1798
+ this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1799
+ msg += `\n ${module.route} (security: ${module.security})`;
1800
+ });
1801
+
1802
+ if (this._routingModules.length === 0) {
1803
+ msg += '\n - no RoutingModule found -\n';
1804
+ }
1805
+ DyFM_Log.warn(msg);
1806
+ }
1807
+ }
1808
+
1809
+ private _getDefaultErrorSettings(
1810
+ fnName: string,
1811
+ error: DyFM_AnyError
1812
+ ): DyFM_Error_Settings {
1813
+ return {
1814
+ status: (error as DyFM_Error)?.___status ?? 500,
1815
+ message: (error as Error)?.message ??
1816
+ (error as DyFM_Error)?._message ??
1817
+ `${fnName} was UNSUCCESSFUL (NTS)`,
1818
+ userMessage: (error as DyFM_Error)?.__userMessage ?? this.defaultErrorUserMsg,
1819
+ addECToUserMsg: !(error as DyFM_Error)?.__userMessage,
1820
+ issuerService: `${this?.constructor?.name}-DyNTS_App`,
1821
+ level: DyFM_ErrorLevel.fatal,
1822
+ error: error,
1823
+ systemVersion: DyNTS_global_settings.systemVersion,
1824
+ };
1825
+ }
1826
+
1827
+ /**
1828
+ * MISSING Description (TODO)
1829
+ */
1830
+ abstract getAppParams(): DyNTS_App_Params;
1831
+
1832
+ /**
1833
+ * MISSING Description (TODO)
1834
+ */
1835
+ abstract getGlobalServiceCollection(): DyNTS_GlobalService_Settings;
1836
+
1837
+ /**
1838
+ * MISSING Description (TODO)
1839
+ */
1840
+ abstract getPortSettings(): DyNTS_Http_Settings;
1841
+
1842
+ /**
1843
+ * MISSING Description (TODO)
1844
+ */
1845
+ overrideDynamoNTSGlobalSettings?(): void;
1846
+
1847
+ /**
1848
+ * Ha megadva, a visszaadott értéket használjuk a route prefix-ként
1849
+ * (DyNTS_global_settings.baseUrl felülírása erre az app-ra).
1850
+ */
1851
+ getApiBasePath?(): string;
1852
+
1853
+ /**
1854
+ * MISSING Description (TODO)
1855
+ */
1856
+ getRoutingModules?(): DyNTS_RoutingModule[];
1857
+
1858
+ /**
1859
+ * MISSING Description (TODO)
1860
+ */
1861
+ getRootServices?(): Promise<any[]>;
1862
+
1863
+ /**
1864
+ * MISSING Description (TODO)
1865
+ */
1866
+ getCertificationSettings?(): DyNTS_Certification_Settings;
1867
+
1868
+ /**
1869
+ * Ha megadva, a client static fájlok a '/' alatt lesznek kiszolgálva (API route-ok után).
1870
+ * Opcionális fallbackPath pl. SPA index.html-hez.
1871
+ */
1872
+ getStaticClientSettings?(): DyNTS_StaticClient_Settings | undefined;
1873
+
1874
+ /**
1875
+ * FR-041 — Ha megadva, CORS middleware mount-olódik mindkét Express instance-ra
1876
+ * (open + secure). Az `allowedOrigins` listán szereplő Origin-eket echo-zza vissza,
1877
+ * `Access-Control-Allow-Credentials: true`-val (default) együtt a Bearer JWT
1878
+ * cross-domain auth flow miatt. OPTIONS preflight 204-gyel rövidre záródik.
1879
+ * Ha undefined → no CORS headers, no preflight handling — back-compat.
1880
+ */
1881
+ getCorsSettings?(): DyNTS_Cors_Settings | undefined;
1882
+
1883
+ /**
1884
+ * Opcionális generikus hook: custom Express middleware regisztrálása az API route-ok
1885
+ * UTÁN és a SPA static catch-all ELŐTT. Auth-AGNOSZTIKUS framework extension-point —
1886
+ * a subclass (pl. FDP base App) ezen keresztül mount-olhat reverse-proxyt egy sub-path-re
1887
+ * (pl. `/auth-api`), ami a `app.get('*')` catch-all elé kell kerüljön. A hívási időzítést
1888
+ * lásd: `mountCustomMiddleware`. Undefined → no-op (back-compat).
1889
+ */
1890
+ registerCustomMiddleware?(
1891
+ express: Express.Application,
1892
+ security: DyNTS_RouteSecurity,
1893
+ ): void | Promise<void>;
1894
+
1895
+ /**
1896
+ * MISSING Description (TODO)
1897
+ */
1898
+ createEntries?(): Promise<void>;
1899
+
1900
+ /**
1901
+ * MISSING Description (TODO)
1902
+ */
1903
+ postProcess?(): Promise<void>;
1904
+
1905
+ }