@futdevpro/nts-dynamo 1.15.84 → 1.15.86

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