nmtjs 0.15.0-beta.2 → 0.15.0-beta.20

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 (254) hide show
  1. package/dist/cli.d.ts +2 -0
  2. package/dist/cli.js +3 -2
  3. package/dist/cli.js.map +1 -0
  4. package/dist/config.d.ts +51 -0
  5. package/dist/config.js +1 -0
  6. package/dist/config.js.map +1 -0
  7. package/dist/entrypoints/cli.d.ts +1 -0
  8. package/dist/entrypoints/cli.js +1 -0
  9. package/dist/entrypoints/cli.js.map +1 -0
  10. package/dist/entrypoints/main.d.ts +5 -0
  11. package/dist/entrypoints/main.js +83 -15
  12. package/dist/entrypoints/main.js.map +1 -0
  13. package/dist/entrypoints/thread.d.ts +14 -0
  14. package/dist/entrypoints/thread.js +130 -24
  15. package/dist/entrypoints/thread.js.map +1 -0
  16. package/dist/entrypoints/worker.d.ts +3 -0
  17. package/dist/entrypoints/worker.js +4 -3
  18. package/dist/entrypoints/worker.js.map +1 -0
  19. package/dist/index.d.ts +69 -0
  20. package/dist/{_exports/index.js → index.js} +9 -5
  21. package/dist/index.js.map +1 -0
  22. package/dist/resolver.d.ts +2 -0
  23. package/dist/resolver.js +1 -0
  24. package/dist/resolver.js.map +1 -0
  25. package/dist/runtime/application/api/api.d.ts +49 -0
  26. package/dist/runtime/application/api/api.js +193 -0
  27. package/dist/runtime/application/api/api.js.map +1 -0
  28. package/dist/runtime/application/api/constants.d.ts +14 -0
  29. package/dist/runtime/application/api/constants.js +8 -0
  30. package/dist/runtime/application/api/constants.js.map +1 -0
  31. package/dist/runtime/application/api/filters.d.ts +14 -0
  32. package/dist/runtime/application/api/filters.js +11 -0
  33. package/dist/runtime/application/api/filters.js.map +1 -0
  34. package/dist/runtime/application/api/guards.d.ts +13 -0
  35. package/dist/runtime/application/api/guards.js +8 -0
  36. package/dist/runtime/application/api/guards.js.map +1 -0
  37. package/dist/runtime/application/api/index.d.ts +8 -0
  38. package/dist/runtime/application/api/index.js +9 -0
  39. package/dist/runtime/application/api/index.js.map +1 -0
  40. package/dist/runtime/application/api/middlewares.d.ts +14 -0
  41. package/dist/runtime/application/api/middlewares.js +12 -0
  42. package/dist/runtime/application/api/middlewares.js.map +1 -0
  43. package/dist/runtime/application/api/procedure.d.ts +67 -0
  44. package/dist/runtime/application/api/procedure.js +50 -0
  45. package/dist/runtime/application/api/procedure.js.map +1 -0
  46. package/dist/runtime/application/api/router.d.ts +71 -0
  47. package/dist/runtime/application/api/router.js +51 -0
  48. package/dist/runtime/application/api/router.js.map +1 -0
  49. package/dist/runtime/application/api/types.d.ts +32 -0
  50. package/dist/runtime/application/api/types.js +2 -0
  51. package/dist/runtime/application/api/types.js.map +1 -0
  52. package/dist/runtime/application/config.d.ts +26 -0
  53. package/dist/runtime/application/config.js +21 -0
  54. package/dist/runtime/application/config.js.map +1 -0
  55. package/dist/runtime/application/constants.d.ts +2 -0
  56. package/dist/runtime/application/constants.js +2 -0
  57. package/dist/runtime/application/constants.js.map +1 -0
  58. package/dist/runtime/application/hook.d.ts +19 -0
  59. package/dist/runtime/application/hook.js +11 -0
  60. package/dist/runtime/application/hook.js.map +1 -0
  61. package/dist/runtime/application/hooks.d.ts +3 -0
  62. package/dist/runtime/application/hooks.js +4 -0
  63. package/dist/runtime/application/hooks.js.map +1 -0
  64. package/dist/runtime/application/index.d.ts +5 -0
  65. package/dist/runtime/application/index.js +6 -0
  66. package/dist/runtime/application/index.js.map +1 -0
  67. package/dist/runtime/constants.d.ts +8 -0
  68. package/dist/runtime/constants.js +5 -0
  69. package/dist/runtime/constants.js.map +1 -0
  70. package/dist/runtime/core/hooks.d.ts +4 -0
  71. package/dist/runtime/core/hooks.js +4 -0
  72. package/dist/runtime/core/hooks.js.map +1 -0
  73. package/dist/runtime/core/plugin.d.ts +8 -0
  74. package/dist/runtime/core/plugin.js +4 -0
  75. package/dist/runtime/core/plugin.js.map +1 -0
  76. package/dist/runtime/core/runtime.d.ts +27 -0
  77. package/dist/runtime/core/runtime.js +81 -0
  78. package/dist/runtime/core/runtime.js.map +1 -0
  79. package/dist/runtime/enums.d.ts +21 -0
  80. package/dist/runtime/enums.js +26 -0
  81. package/dist/runtime/enums.js.map +1 -0
  82. package/dist/runtime/index.d.ts +21 -0
  83. package/dist/runtime/index.js +22 -0
  84. package/dist/runtime/index.js.map +1 -0
  85. package/dist/runtime/injectables.d.ts +23 -0
  86. package/dist/runtime/injectables.js +20 -0
  87. package/dist/runtime/injectables.js.map +1 -0
  88. package/dist/runtime/jobs/job.d.ts +132 -0
  89. package/dist/runtime/jobs/job.js +68 -0
  90. package/dist/runtime/jobs/job.js.map +1 -0
  91. package/dist/runtime/jobs/manager.d.ts +103 -0
  92. package/dist/runtime/jobs/manager.js +200 -0
  93. package/dist/runtime/jobs/manager.js.map +1 -0
  94. package/dist/runtime/jobs/router.d.ts +251 -0
  95. package/dist/runtime/jobs/router.js +396 -0
  96. package/dist/runtime/jobs/router.js.map +1 -0
  97. package/dist/runtime/jobs/runner.d.ts +64 -0
  98. package/dist/runtime/jobs/runner.js +256 -0
  99. package/dist/runtime/jobs/runner.js.map +1 -0
  100. package/dist/runtime/jobs/step.d.ts +22 -0
  101. package/dist/runtime/jobs/step.js +18 -0
  102. package/dist/runtime/jobs/step.js.map +1 -0
  103. package/dist/runtime/jobs/ui.d.ts +3 -0
  104. package/dist/runtime/jobs/ui.js +17 -0
  105. package/dist/runtime/jobs/ui.js.map +1 -0
  106. package/dist/runtime/pubsub/manager.d.ts +48 -0
  107. package/dist/runtime/pubsub/manager.js +119 -0
  108. package/dist/runtime/pubsub/manager.js.map +1 -0
  109. package/dist/runtime/pubsub/redis.d.ts +16 -0
  110. package/dist/runtime/pubsub/redis.js +98 -0
  111. package/dist/runtime/pubsub/redis.js.map +1 -0
  112. package/dist/runtime/scheduler/index.d.ts +22 -0
  113. package/dist/runtime/scheduler/index.js +20 -0
  114. package/dist/runtime/scheduler/index.js.map +1 -0
  115. package/dist/runtime/server/applications.d.ts +52 -0
  116. package/dist/runtime/server/applications.js +133 -0
  117. package/dist/runtime/server/applications.js.map +1 -0
  118. package/dist/runtime/server/config.d.ts +121 -0
  119. package/dist/runtime/server/config.js +33 -0
  120. package/dist/runtime/server/config.js.map +1 -0
  121. package/dist/runtime/server/jobs.d.ts +41 -0
  122. package/dist/runtime/server/jobs.js +181 -0
  123. package/dist/runtime/server/jobs.js.map +1 -0
  124. package/dist/runtime/server/pool.d.ts +54 -0
  125. package/dist/runtime/server/pool.js +194 -0
  126. package/dist/runtime/server/pool.js.map +1 -0
  127. package/dist/runtime/server/proxy.d.ts +21 -0
  128. package/dist/runtime/server/proxy.js +79 -0
  129. package/dist/runtime/server/proxy.js.map +1 -0
  130. package/dist/runtime/server/server.d.ts +53 -0
  131. package/dist/runtime/server/server.js +90 -0
  132. package/dist/runtime/server/server.js.map +1 -0
  133. package/dist/runtime/store/index.d.ts +3 -0
  134. package/dist/runtime/store/index.js +23 -0
  135. package/dist/runtime/store/index.js.map +1 -0
  136. package/dist/runtime/types.d.ts +103 -0
  137. package/dist/runtime/types.js +2 -0
  138. package/dist/runtime/types.js.map +1 -0
  139. package/dist/runtime/workers/application.d.ts +47 -0
  140. package/dist/runtime/workers/application.js +162 -0
  141. package/dist/runtime/workers/application.js.map +1 -0
  142. package/dist/runtime/workers/base.d.ts +16 -0
  143. package/dist/runtime/workers/base.js +46 -0
  144. package/dist/runtime/workers/base.js.map +1 -0
  145. package/dist/runtime/workers/cli.d.ts +1 -0
  146. package/dist/runtime/workers/cli.js +2 -0
  147. package/dist/runtime/workers/cli.js.map +1 -0
  148. package/dist/runtime/workers/job.d.ts +20 -0
  149. package/dist/runtime/workers/job.js +172 -0
  150. package/dist/runtime/workers/job.js.map +1 -0
  151. package/dist/typings.d.ts +5 -0
  152. package/dist/typings.js +4 -3
  153. package/dist/typings.js.map +1 -0
  154. package/dist/vite/builder.d.ts +5 -0
  155. package/dist/vite/builder.js +5 -1
  156. package/dist/vite/builder.js.map +1 -0
  157. package/dist/vite/config.d.ts +28 -0
  158. package/dist/vite/config.js +1 -0
  159. package/dist/vite/config.js.map +1 -0
  160. package/dist/vite/plugins.d.ts +2 -0
  161. package/dist/vite/plugins.js +1 -0
  162. package/dist/vite/plugins.js.map +1 -0
  163. package/dist/vite/runners/worker.d.ts +4 -0
  164. package/dist/vite/runners/worker.js +1 -0
  165. package/dist/vite/runners/worker.js.map +1 -0
  166. package/dist/vite/server.d.ts +3 -0
  167. package/dist/vite/server.js +6 -1
  168. package/dist/vite/server.js.map +1 -0
  169. package/dist/vite/servers/main.d.ts +8 -0
  170. package/dist/vite/servers/main.js +1 -0
  171. package/dist/vite/servers/main.js.map +1 -0
  172. package/dist/vite/servers/worker.d.ts +11 -0
  173. package/dist/vite/servers/worker.js +28 -0
  174. package/dist/vite/servers/worker.js.map +1 -0
  175. package/package.json +31 -18
  176. package/src/cli.ts +144 -0
  177. package/src/config.ts +64 -0
  178. package/src/entrypoints/cli.ts +13 -0
  179. package/src/entrypoints/main.ts +200 -0
  180. package/src/entrypoints/thread.ts +184 -0
  181. package/src/entrypoints/worker.ts +48 -0
  182. package/src/index.ts +82 -0
  183. package/src/resolver.ts +16 -0
  184. package/src/runtime/application/api/api.ts +265 -0
  185. package/src/runtime/application/api/constants.ts +22 -0
  186. package/src/runtime/application/api/filters.ts +39 -0
  187. package/src/runtime/application/api/guards.ts +29 -0
  188. package/src/runtime/application/api/index.ts +8 -0
  189. package/src/runtime/application/api/middlewares.ts +37 -0
  190. package/src/runtime/application/api/procedure.ts +229 -0
  191. package/src/runtime/application/api/router.ts +193 -0
  192. package/src/runtime/application/api/types.ts +124 -0
  193. package/src/runtime/application/config.ts +69 -0
  194. package/src/runtime/application/constants.ts +4 -0
  195. package/src/runtime/application/hook.ts +51 -0
  196. package/src/runtime/application/hooks.ts +3 -0
  197. package/src/runtime/application/index.ts +5 -0
  198. package/src/runtime/constants.ts +13 -0
  199. package/src/runtime/core/hooks.ts +5 -0
  200. package/src/runtime/core/plugin.ts +13 -0
  201. package/src/runtime/core/runtime.ts +109 -0
  202. package/src/runtime/enums.ts +24 -0
  203. package/src/runtime/index.ts +21 -0
  204. package/src/runtime/injectables.ts +61 -0
  205. package/src/runtime/jobs/job.ts +370 -0
  206. package/src/runtime/jobs/manager.ts +332 -0
  207. package/src/runtime/jobs/router.ts +835 -0
  208. package/src/runtime/jobs/runner.ts +320 -0
  209. package/src/runtime/jobs/step.ts +65 -0
  210. package/src/runtime/jobs/ui.ts +21 -0
  211. package/src/runtime/pubsub/manager.ts +211 -0
  212. package/src/runtime/pubsub/redis.ts +108 -0
  213. package/src/runtime/scheduler/index.ts +39 -0
  214. package/src/runtime/server/applications.ts +210 -0
  215. package/src/runtime/server/config.ts +158 -0
  216. package/src/runtime/server/jobs.ts +250 -0
  217. package/src/runtime/server/pool.ts +260 -0
  218. package/src/runtime/server/proxy.ts +118 -0
  219. package/src/runtime/server/server.ts +155 -0
  220. package/src/runtime/store/index.ts +30 -0
  221. package/src/runtime/types.ts +93 -0
  222. package/src/runtime/workers/application.ts +209 -0
  223. package/src/runtime/workers/base.ts +68 -0
  224. package/src/runtime/workers/cli.ts +0 -0
  225. package/src/runtime/workers/job.ts +153 -0
  226. package/src/typings.ts +30 -0
  227. package/src/vite/builder.ts +122 -0
  228. package/src/vite/config.ts +45 -0
  229. package/src/vite/plugins.ts +26 -0
  230. package/src/vite/runners/worker.ts +57 -0
  231. package/src/vite/server.ts +39 -0
  232. package/src/vite/servers/main.ts +34 -0
  233. package/src/vite/servers/worker.ts +143 -0
  234. package/dist/_exports/application.js +0 -1
  235. package/dist/_exports/common.js +0 -1
  236. package/dist/_exports/contract.js +0 -2
  237. package/dist/_exports/core.js +0 -1
  238. package/dist/_exports/gateway.js +0 -1
  239. package/dist/_exports/http-transport/bun.js +0 -1
  240. package/dist/_exports/http-transport/deno.js +0 -1
  241. package/dist/_exports/http-transport/node.js +0 -1
  242. package/dist/_exports/http-transport.js +0 -1
  243. package/dist/_exports/json-format.js +0 -1
  244. package/dist/_exports/protocol/client.js +0 -1
  245. package/dist/_exports/protocol/server.js +0 -1
  246. package/dist/_exports/protocol.js +0 -1
  247. package/dist/_exports/runtime/types.js +0 -1
  248. package/dist/_exports/runtime.js +0 -1
  249. package/dist/_exports/type.js +0 -2
  250. package/dist/_exports/ws-transport/bun.js +0 -1
  251. package/dist/_exports/ws-transport/deno.js +0 -1
  252. package/dist/_exports/ws-transport/node.js +0 -1
  253. package/dist/_exports/ws-transport.js +0 -1
  254. package/dist/command.js +0 -30
@@ -0,0 +1,108 @@
1
+ import EventEmitter, { on } from 'node:events'
2
+
3
+ import { isAbortError } from '@nmtjs/common'
4
+ import { createFactoryInjectable, provide } from '@nmtjs/core'
5
+
6
+ import type { RuntimePlugin } from '../core/plugin.ts'
7
+ import type { Store } from '../types.ts'
8
+ import type { PubSubAdapterEvent, PubSubAdapterType } from './manager.ts'
9
+ import { pubSubAdapter, storeConfig } from '../injectables.ts'
10
+ import { createStoreClient } from '../store/index.ts'
11
+
12
+ export class RedisPubSubAdapter implements PubSubAdapterType {
13
+ protected readonly events = new EventEmitter()
14
+ protected readonly listeners = new Map<string, number>()
15
+ protected subscriberClient?: Store
16
+
17
+ constructor(protected readonly client: Store) {}
18
+
19
+ async initialize() {
20
+ // Create a dedicated subscriber client (Redis requires separate clients for pub/sub)
21
+ this.subscriberClient = this.client.duplicate()
22
+
23
+ // Set up message handler
24
+ this.subscriberClient.on('message', (channel: string, message: string) => {
25
+ try {
26
+ const parsed = JSON.parse(message)
27
+ this.events.emit(channel, parsed)
28
+ } catch {}
29
+ })
30
+ }
31
+
32
+ async dispose() {
33
+ if (this.subscriberClient) {
34
+ await this.subscriberClient.quit()
35
+ this.subscriberClient = undefined
36
+ }
37
+ }
38
+
39
+ async publish(channel: string, payload: any): Promise<boolean> {
40
+ try {
41
+ await this.client.publish(channel, JSON.stringify(payload))
42
+ return true
43
+ } catch {
44
+ return false
45
+ }
46
+ }
47
+
48
+ async *subscribe(
49
+ channel: string,
50
+ signal?: AbortSignal,
51
+ ): AsyncGenerator<PubSubAdapterEvent> {
52
+ if (!this.subscriberClient) {
53
+ throw new Error('RedisPubSubAdapter not initialized')
54
+ }
55
+
56
+ if (!this.listeners.has(channel)) {
57
+ await this.subscriberClient.subscribe(channel)
58
+ this.listeners.set(channel, 1)
59
+ } else {
60
+ this.listeners.set(channel, this.listeners.get(channel)! + 1)
61
+ }
62
+
63
+ try {
64
+ signal?.throwIfAborted()
65
+ for await (const [payload] of on(this.events, channel, { signal })) {
66
+ yield { channel, payload }
67
+ }
68
+ } catch (error: any) {
69
+ if (isAbortError(error)) throw error
70
+ } finally {
71
+ const count = this.listeners.get(channel)
72
+ if (count !== undefined) {
73
+ if (count > 1) {
74
+ this.listeners.set(channel, count - 1)
75
+ } else {
76
+ await this.subscriberClient?.unsubscribe(channel)
77
+ this.listeners.delete(channel)
78
+ }
79
+ }
80
+ }
81
+ }
82
+ }
83
+
84
+ export const RedisPubSubAdapterPlugin = (): RuntimePlugin => {
85
+ return {
86
+ name: 'pubsub-redis-adapter',
87
+ hooks: {
88
+ 'lifecycle:afterInitialize': async (ctx) => {
89
+ await ctx.container.provide([
90
+ provide(
91
+ pubSubAdapter,
92
+ createFactoryInjectable({
93
+ dependencies: { config: storeConfig },
94
+ factory: async ({ config }) => {
95
+ const connection = await createStoreClient(config)
96
+ const adapter = new RedisPubSubAdapter(connection)
97
+ await adapter.initialize()
98
+ return { adapter, connection }
99
+ },
100
+ pick: ({ adapter }) => adapter,
101
+ dispose: ({ connection }) => connection.quit(),
102
+ }),
103
+ ),
104
+ ])
105
+ },
106
+ },
107
+ }
108
+ }
@@ -0,0 +1,39 @@
1
+ import type { AnyJob } from '../jobs/job.ts'
2
+
3
+ export interface JobsSchedulerEntry<T extends AnyJob = AnyJob> {
4
+ job: T
5
+ data: T['_']['input']
6
+ cron: string
7
+ }
8
+
9
+ export type JobsSchedulerOptions = { entries: JobsSchedulerEntry[] }
10
+
11
+ /**
12
+ * @deprecated Job scheduler is currently being refactored and is not available.
13
+ * This will throw an error if instantiated.
14
+ */
15
+ export class JobsScheduler {
16
+ constructor() {
17
+ throw new Error(
18
+ 'JobsScheduler is currently a work in progress and not available. ' +
19
+ 'Scheduled jobs will be supported in a future release.',
20
+ )
21
+ }
22
+
23
+ async initialize() {}
24
+ async stop() {}
25
+ }
26
+
27
+ /**
28
+ * @deprecated Job scheduler is currently being refactored and is not available.
29
+ */
30
+ export function createSchedulerJobEntry<T extends AnyJob>(
31
+ job: T,
32
+ data: T['_']['input'],
33
+ cron: string,
34
+ ): JobsSchedulerEntry<T> {
35
+ throw new Error(
36
+ 'createSchedulerJobEntry is currently a work in progress and not available. ' +
37
+ 'Scheduled jobs will be supported in a future release.',
38
+ )
39
+ }
@@ -0,0 +1,210 @@
1
+ import { EventEmitter } from 'node:events'
2
+
3
+ import type { Logger } from '@nmtjs/core'
4
+ import type { ProxyableTransportType } from '@nmtjs/gateway'
5
+
6
+ import type { ThreadPortMessageTypes, WorkerThreadError } from '../types.ts'
7
+ import type { ServerApplicationConfig, ServerConfig } from './config.ts'
8
+ import type { Thread } from './pool.ts'
9
+ import type {
10
+ ApplicationServerWorkerConfig,
11
+ ApplicationWorkerErrorEvent,
12
+ ApplicationWorkerReadyEvent,
13
+ } from './server.ts'
14
+ import { Pool } from './pool.ts'
15
+
16
+ export type ApplicationProxyUpstream = {
17
+ type: ProxyableTransportType
18
+ url: string
19
+ }
20
+
21
+ export class ApplicationServerApplications extends EventEmitter<{
22
+ add: [application: string, upstream: ApplicationProxyUpstream]
23
+ remove: [application: string, upstream: ApplicationProxyUpstream]
24
+ }> {
25
+ pool: Pool
26
+
27
+ protected readonly upstreams = new Map<
28
+ string,
29
+ Map<string, { upstream: ApplicationProxyUpstream; count: number }>
30
+ >()
31
+ protected readonly upstreamsByThread = new WeakMap<
32
+ Thread,
33
+ Array<{ application: string; key: string }>
34
+ >()
35
+
36
+ constructor(
37
+ readonly params: {
38
+ logger: Logger
39
+ applications: string[]
40
+ workerConfig: ApplicationServerWorkerConfig
41
+ applicationsConfig: Record<
42
+ string,
43
+ { type: 'neemata' | 'custom'; specifier: string }
44
+ >
45
+ serverConfig: ServerConfig
46
+ },
47
+ ) {
48
+ super()
49
+ this.pool = new Pool({
50
+ path: this.params.workerConfig.path,
51
+ worker: this.params.workerConfig.worker,
52
+ workerData: { ...this.params.workerConfig.workerData },
53
+ })
54
+ }
55
+
56
+ get appsNames() {
57
+ return this.params.applications
58
+ }
59
+
60
+ async start() {
61
+ const { logger, applications, applicationsConfig, serverConfig } =
62
+ this.params
63
+
64
+ for (const applicationName of applications) {
65
+ const applicationPath = applicationsConfig[applicationName]
66
+ if (!applicationPath) {
67
+ logger.warn(
68
+ `Application [${applicationName}] not found in applicationsConfig, skipping...`,
69
+ )
70
+ continue
71
+ }
72
+
73
+ const applicationConfig = serverConfig.applications[
74
+ applicationName
75
+ ] as ServerApplicationConfig
76
+
77
+ const threadsConfig = Array.isArray(applicationConfig.threads)
78
+ ? applicationConfig.threads
79
+ : new Array(applicationConfig.threads).fill(undefined)
80
+
81
+ logger.info(
82
+ `Spinning [${threadsConfig.length}] workers for [${applicationName}] application...`,
83
+ )
84
+
85
+ for (let i = 0; i < threadsConfig.length; i++) {
86
+ const thread = this.pool.add({
87
+ index: i,
88
+ name: `application-${applicationName}`,
89
+ workerData: {
90
+ runtime: {
91
+ type: 'application',
92
+ name: applicationName,
93
+ path: applicationPath.specifier,
94
+ transportsData: threadsConfig[i],
95
+ },
96
+ },
97
+ })
98
+
99
+ thread.on('ready', ({ hosts }) => {
100
+ this.removeThreadUpstreams(thread)
101
+
102
+ const keys: Array<{ application: string; key: string }> = []
103
+ const sanitizedHosts: ThreadPortMessageTypes['ready']['hosts'] = []
104
+
105
+ if (hosts?.length) {
106
+ for (const host of hosts) {
107
+ const url = new URL(host.url)
108
+ if (url.hostname === '0.0.0.0') url.hostname = '127.0.0.1'
109
+
110
+ const normalizedUrl = url.toString()
111
+ sanitizedHosts.push({ type: host.type, url: normalizedUrl })
112
+
113
+ const upstream: ApplicationProxyUpstream = {
114
+ type: host.type,
115
+ url: normalizedUrl,
116
+ }
117
+
118
+ const key = `${upstream.type}:${upstream.url}`
119
+ keys.push({ application: applicationName, key })
120
+ this.addUpstream(applicationName, key, upstream)
121
+ }
122
+ }
123
+
124
+ this.upstreamsByThread.set(thread, keys)
125
+
126
+ this.emitWorkerReady({
127
+ application: applicationName,
128
+ threadId: thread.worker.threadId,
129
+ hosts: sanitizedHosts.length ? sanitizedHosts : undefined,
130
+ })
131
+ })
132
+
133
+ thread.on('error', (error: WorkerThreadError) => {
134
+ this.emitWorkerError({
135
+ application: applicationName,
136
+ threadId: thread.worker.threadId,
137
+ error,
138
+ })
139
+ this.removeThreadUpstreams(thread)
140
+ })
141
+
142
+ thread.worker.once('exit', () => {
143
+ this.removeThreadUpstreams(thread)
144
+ })
145
+ }
146
+ }
147
+
148
+ await this.pool.start()
149
+ }
150
+
151
+ async stop() {
152
+ await this.pool.stop()
153
+ }
154
+
155
+ protected addUpstream(
156
+ application: string,
157
+ key: string,
158
+ upstream: ApplicationProxyUpstream,
159
+ ) {
160
+ let appUpstreams = this.upstreams.get(application)
161
+ if (!appUpstreams) {
162
+ appUpstreams = new Map()
163
+ this.upstreams.set(application, appUpstreams)
164
+ }
165
+
166
+ const current = appUpstreams.get(key)
167
+ if (!current) {
168
+ appUpstreams.set(key, { upstream, count: 1 })
169
+ this.emit('add', application, upstream)
170
+ return
171
+ }
172
+
173
+ current.count++
174
+ }
175
+
176
+ protected removeThreadUpstreams(thread: Thread) {
177
+ const keys = this.upstreamsByThread.get(thread)
178
+ if (!keys) return
179
+ this.upstreamsByThread.delete(thread)
180
+
181
+ for (const { application, key } of keys) {
182
+ const appUpstreams = this.upstreams.get(application)
183
+ const current = appUpstreams?.get(key)
184
+ if (!current) continue
185
+
186
+ current.count--
187
+ if (current.count <= 0) {
188
+ appUpstreams?.delete(key)
189
+ this.emit('remove', application, current.upstream)
190
+ }
191
+ if (appUpstreams && appUpstreams.size === 0) {
192
+ this.upstreams.delete(application)
193
+ }
194
+ }
195
+ }
196
+
197
+ protected emitWorkerReady(event: ApplicationWorkerReadyEvent) {
198
+ this.params.workerConfig.events?.emit('worker-ready', event)
199
+ }
200
+
201
+ protected emitWorkerError(event: ApplicationWorkerErrorEvent) {
202
+ this.params.logger.error(
203
+ new Error(
204
+ `Worker [${event.application}] thread ${event.threadId} error`,
205
+ { cause: event.error },
206
+ ),
207
+ )
208
+ this.params.workerConfig.events?.emit('worker-error', event)
209
+ }
210
+ }
@@ -0,0 +1,158 @@
1
+ import type { TSError } from '@nmtjs/common'
2
+ import type { LoggingOptions } from '@nmtjs/core'
3
+ import type { Transport } from '@nmtjs/gateway'
4
+ import type { ApplicationOptions, PortUpstreamOptions } from '@nmtjs/proxy'
5
+ import type { Applications } from 'nmtjs/runtime/types'
6
+
7
+ import type { ApplicationConfig } from '../application/config.ts'
8
+ import type { JobWorkerPool, StoreType } from '../enums.ts'
9
+ import type { AnyJob } from '../jobs/job.ts'
10
+ import type { PubSubAdapterType } from '../pubsub/manager.ts'
11
+ import type { JobsSchedulerOptions } from '../scheduler/index.ts'
12
+ import type { StoreTypeOptions } from '../types.ts'
13
+ import { kServerConfig } from '../constants.ts'
14
+
15
+ export type ServerPoolOptions = {
16
+ /**
17
+ * Number of worker threads
18
+ */
19
+ threads: number
20
+ /**
21
+ * Max number of jobs per worker
22
+ */
23
+ jobs: number
24
+ }
25
+
26
+ export type ServerStoreConfig =
27
+ | { type: StoreType.Redis; options: StoreTypeOptions[StoreType.Redis] }
28
+ | { type: StoreType.Valkey; options: StoreTypeOptions[StoreType.Valkey] }
29
+
30
+ export type ServerApplicationConfig<T = ApplicationConfig> =
31
+ T extends ApplicationConfig<any, infer Transports>
32
+ ? {
33
+ threads: {
34
+ [K in keyof Transports]: Transports[K] extends Transport<
35
+ any,
36
+ infer Options
37
+ >
38
+ ? Options
39
+ : never
40
+ }[]
41
+ }
42
+ : any
43
+
44
+ export type ServerJobsConfig = {
45
+ pools: {
46
+ [JobWorkerPool.Io]: ServerPoolOptions
47
+ [JobWorkerPool.Compute]: ServerPoolOptions
48
+ }
49
+ jobs?: AnyJob[]
50
+ /**
51
+ * @deprecated Scheduler is currently being refactored and is not available.
52
+ * Using this option will throw an error at startup.
53
+ */
54
+ scheduler?: JobsSchedulerOptions
55
+ ui?: { hostname?: string; port?: number }
56
+ }
57
+
58
+ export interface ServerConfigInit {
59
+ logger: LoggingOptions
60
+ applications: {
61
+ [K in keyof Applications]: Applications[K]['type'] extends 'neemata'
62
+ ? ServerApplicationConfig<
63
+ (Applications[K] & { type: 'neemata' })['definition']
64
+ >
65
+ : ServerApplicationConfig<any>
66
+ }
67
+ store?: ServerStoreConfig
68
+ /**
69
+ * Proxy configuration. Enabling this will start a reverse proxy server that handles TLS, routing,
70
+ * load balancing, and health checks for your applications.
71
+ *
72
+ * The applications will be accessible via `<hostname>:<port>/<application-name>/**`
73
+ *
74
+ * Requires adding `@nmtjs/proxy` package to your dependencies
75
+ * and [`cargo`](https://doc.rust-lang.org/cargo/getting-started/installation.html) alongside with
76
+ * [`rustc`](https://www.rust-lang.org/tools/install) to be available globally for building native modules.
77
+ */
78
+ proxy?: {
79
+ port: number
80
+ hostname: string
81
+ applications: {
82
+ [K in keyof Applications]?: Omit<ApplicationOptions, 'name'>
83
+ }
84
+ threads?: number
85
+ healthChecks?: { interval?: number }
86
+ tls?: { key: string; cert: string }
87
+ }
88
+ jobs?: ServerJobsConfig
89
+ commands?: {}
90
+ pubsub?: { adapter: PubSubAdapterType }
91
+ deploymentId?: string
92
+ }
93
+
94
+ export interface ServerConfig {
95
+ [kServerConfig]: true
96
+ logger: ServerConfigInit['logger']
97
+ applications: ServerConfigInit['applications']
98
+ store: ServerConfigInit['store']
99
+ /**
100
+ * Proxy configuration. Enabling this will start a reverse proxy server that handles TLS, routing,
101
+ * load balancing, and health checks for your applications.
102
+ *
103
+ * The applications will be accessible via `<hostname>:<port>/<application-name>/**`
104
+ *
105
+ * Requires adding `@nmtjs/proxy` package to your dependencies
106
+ * and [`cargo`](https://doc.rust-lang.org/cargo/getting-started/installation.html) alongside with
107
+ * [`rustc`](https://www.rust-lang.org/tools/install) to be available globally for building native modules.
108
+ */
109
+ proxy: ServerConfigInit['proxy']
110
+ jobs?: {
111
+ pools: ServerJobsConfig['pools']
112
+ jobs: Map<string, AnyJob>
113
+ /**
114
+ * @deprecated Scheduler is currently being refactored and is not available.
115
+ * Using this option will throw an error at startup.
116
+ */
117
+ scheduler?: JobsSchedulerOptions
118
+ ui?: ServerJobsConfig['ui']
119
+ }
120
+ commands?: {}
121
+ pubsub: ServerConfigInit['pubsub']
122
+ deploymentId: ServerConfigInit['deploymentId']
123
+ }
124
+
125
+ export function defineServer(options: ServerConfigInit): ServerConfig {
126
+ const { deploymentId, logger, commands, proxy, store, applications, pubsub } =
127
+ options
128
+
129
+ let jobs: ServerConfig['jobs'] | undefined
130
+ if (options.jobs) {
131
+ const map = new Map<string, AnyJob>()
132
+ for (const job of options.jobs.jobs ?? []) map.set(job.name, job)
133
+ for (const { job } of options.jobs.scheduler?.entries ?? [])
134
+ map.set(job.name, job)
135
+ jobs = {
136
+ pools: options.jobs.pools,
137
+ jobs: map,
138
+ scheduler: options.jobs.scheduler,
139
+ ui: options.jobs.ui,
140
+ }
141
+ }
142
+
143
+ return Object.freeze({
144
+ [kServerConfig]: true,
145
+ deploymentId,
146
+ logger,
147
+ commands,
148
+ proxy,
149
+ store,
150
+ applications,
151
+ pubsub,
152
+ jobs,
153
+ } as const)
154
+ }
155
+
156
+ export function isServerConfig(value: any): value is ServerConfig {
157
+ return Boolean(value?.[kServerConfig])
158
+ }