@hotmeshio/hotmesh 0.0.1

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 (263) hide show
  1. package/LICENSE +214 -0
  2. package/README.md +241 -0
  3. package/build/index.d.ts +4 -0
  4. package/build/index.js +7 -0
  5. package/build/modules/errors.d.ts +28 -0
  6. package/build/modules/errors.js +50 -0
  7. package/build/modules/key.d.ts +75 -0
  8. package/build/modules/key.js +116 -0
  9. package/build/modules/utils.d.ts +34 -0
  10. package/build/modules/utils.js +173 -0
  11. package/build/package.json +73 -0
  12. package/build/services/activities/activity.d.ts +59 -0
  13. package/build/services/activities/activity.js +396 -0
  14. package/build/services/activities/await.d.ts +16 -0
  15. package/build/services/activities/await.js +143 -0
  16. package/build/services/activities/emit.d.ts +9 -0
  17. package/build/services/activities/emit.js +13 -0
  18. package/build/services/activities/index.d.ts +15 -0
  19. package/build/services/activities/index.js +16 -0
  20. package/build/services/activities/iterate.d.ts +9 -0
  21. package/build/services/activities/iterate.js +13 -0
  22. package/build/services/activities/trigger.d.ts +22 -0
  23. package/build/services/activities/trigger.js +161 -0
  24. package/build/services/activities/worker.d.ts +17 -0
  25. package/build/services/activities/worker.js +164 -0
  26. package/build/services/collator/index.d.ts +54 -0
  27. package/build/services/collator/index.js +171 -0
  28. package/build/services/compiler/deployer.d.ts +35 -0
  29. package/build/services/compiler/deployer.js +412 -0
  30. package/build/services/compiler/index.d.ts +30 -0
  31. package/build/services/compiler/index.js +111 -0
  32. package/build/services/compiler/validator.d.ts +32 -0
  33. package/build/services/compiler/validator.js +134 -0
  34. package/build/services/connector/clients/ioredis.d.ts +13 -0
  35. package/build/services/connector/clients/ioredis.js +50 -0
  36. package/build/services/connector/clients/redis.d.ts +13 -0
  37. package/build/services/connector/clients/redis.js +62 -0
  38. package/build/services/connector/index.d.ts +5 -0
  39. package/build/services/connector/index.js +31 -0
  40. package/build/services/dimension/index.d.ts +29 -0
  41. package/build/services/dimension/index.js +35 -0
  42. package/build/services/durable/asyncLocalStorage.d.ts +3 -0
  43. package/build/services/durable/asyncLocalStorage.js +5 -0
  44. package/build/services/durable/client.d.ts +15 -0
  45. package/build/services/durable/client.js +108 -0
  46. package/build/services/durable/connection.d.ts +4 -0
  47. package/build/services/durable/connection.js +51 -0
  48. package/build/services/durable/factory.d.ts +3 -0
  49. package/build/services/durable/factory.js +123 -0
  50. package/build/services/durable/handle.d.ts +8 -0
  51. package/build/services/durable/handle.js +38 -0
  52. package/build/services/durable/index.d.ts +57 -0
  53. package/build/services/durable/index.js +58 -0
  54. package/build/services/durable/native.d.ts +4 -0
  55. package/build/services/durable/native.js +47 -0
  56. package/build/services/durable/worker.d.ts +36 -0
  57. package/build/services/durable/worker.js +266 -0
  58. package/build/services/durable/workflow.d.ts +6 -0
  59. package/build/services/durable/workflow.js +135 -0
  60. package/build/services/engine/index.d.ts +82 -0
  61. package/build/services/engine/index.js +511 -0
  62. package/build/services/hotmesh/index.d.ts +45 -0
  63. package/build/services/hotmesh/index.js +134 -0
  64. package/build/services/logger/index.d.ts +17 -0
  65. package/build/services/logger/index.js +73 -0
  66. package/build/services/mapper/index.d.ts +24 -0
  67. package/build/services/mapper/index.js +72 -0
  68. package/build/services/pipe/functions/array.d.ts +24 -0
  69. package/build/services/pipe/functions/array.js +69 -0
  70. package/build/services/pipe/functions/bitwise.d.ts +9 -0
  71. package/build/services/pipe/functions/bitwise.js +24 -0
  72. package/build/services/pipe/functions/conditional.d.ts +10 -0
  73. package/build/services/pipe/functions/conditional.js +27 -0
  74. package/build/services/pipe/functions/date.d.ts +57 -0
  75. package/build/services/pipe/functions/date.js +167 -0
  76. package/build/services/pipe/functions/index.d.ts +25 -0
  77. package/build/services/pipe/functions/index.js +26 -0
  78. package/build/services/pipe/functions/json.d.ts +5 -0
  79. package/build/services/pipe/functions/json.js +12 -0
  80. package/build/services/pipe/functions/math.d.ts +38 -0
  81. package/build/services/pipe/functions/math.js +111 -0
  82. package/build/services/pipe/functions/number.d.ts +25 -0
  83. package/build/services/pipe/functions/number.js +133 -0
  84. package/build/services/pipe/functions/object.d.ts +22 -0
  85. package/build/services/pipe/functions/object.js +63 -0
  86. package/build/services/pipe/functions/string.d.ts +23 -0
  87. package/build/services/pipe/functions/string.js +69 -0
  88. package/build/services/pipe/functions/symbol.d.ts +12 -0
  89. package/build/services/pipe/functions/symbol.js +33 -0
  90. package/build/services/pipe/functions/unary.d.ts +7 -0
  91. package/build/services/pipe/functions/unary.js +18 -0
  92. package/build/services/pipe/index.d.ts +30 -0
  93. package/build/services/pipe/index.js +128 -0
  94. package/build/services/quorum/index.d.ts +34 -0
  95. package/build/services/quorum/index.js +147 -0
  96. package/build/services/reporter/index.d.ts +47 -0
  97. package/build/services/reporter/index.js +330 -0
  98. package/build/services/serializer/index.d.ts +36 -0
  99. package/build/services/serializer/index.js +222 -0
  100. package/build/services/signaler/store.d.ts +15 -0
  101. package/build/services/signaler/store.js +53 -0
  102. package/build/services/signaler/stream.d.ts +43 -0
  103. package/build/services/signaler/stream.js +317 -0
  104. package/build/services/store/cache.d.ts +66 -0
  105. package/build/services/store/cache.js +127 -0
  106. package/build/services/store/clients/ioredis.d.ts +27 -0
  107. package/build/services/store/clients/ioredis.js +96 -0
  108. package/build/services/store/clients/redis.d.ts +29 -0
  109. package/build/services/store/clients/redis.js +143 -0
  110. package/build/services/store/index.d.ts +88 -0
  111. package/build/services/store/index.js +657 -0
  112. package/build/services/stream/clients/ioredis.d.ts +23 -0
  113. package/build/services/stream/clients/ioredis.js +115 -0
  114. package/build/services/stream/clients/redis.d.ts +23 -0
  115. package/build/services/stream/clients/redis.js +119 -0
  116. package/build/services/stream/index.d.ts +21 -0
  117. package/build/services/stream/index.js +9 -0
  118. package/build/services/sub/clients/ioredis.d.ts +20 -0
  119. package/build/services/sub/clients/ioredis.js +72 -0
  120. package/build/services/sub/clients/redis.d.ts +20 -0
  121. package/build/services/sub/clients/redis.js +63 -0
  122. package/build/services/sub/index.d.ts +18 -0
  123. package/build/services/sub/index.js +9 -0
  124. package/build/services/task/index.d.ts +18 -0
  125. package/build/services/task/index.js +73 -0
  126. package/build/services/telemetry/index.d.ts +49 -0
  127. package/build/services/telemetry/index.js +223 -0
  128. package/build/services/worker/index.d.ts +30 -0
  129. package/build/services/worker/index.js +105 -0
  130. package/build/types/activity.d.ts +86 -0
  131. package/build/types/activity.js +2 -0
  132. package/build/types/app.d.ts +16 -0
  133. package/build/types/app.js +2 -0
  134. package/build/types/async.d.ts +5 -0
  135. package/build/types/async.js +2 -0
  136. package/build/types/cache.d.ts +1 -0
  137. package/build/types/cache.js +2 -0
  138. package/build/types/collator.d.ts +8 -0
  139. package/build/types/collator.js +11 -0
  140. package/build/types/durable.d.ts +59 -0
  141. package/build/types/durable.js +2 -0
  142. package/build/types/hook.d.ts +31 -0
  143. package/build/types/hook.js +9 -0
  144. package/build/types/hotmesh.d.ts +82 -0
  145. package/build/types/hotmesh.js +2 -0
  146. package/build/types/index.d.ts +20 -0
  147. package/build/types/index.js +21 -0
  148. package/build/types/ioredisclient.d.ts +5 -0
  149. package/build/types/ioredisclient.js +5 -0
  150. package/build/types/job.d.ts +50 -0
  151. package/build/types/job.js +2 -0
  152. package/build/types/logger.d.ts +6 -0
  153. package/build/types/logger.js +2 -0
  154. package/build/types/map.d.ts +4 -0
  155. package/build/types/map.js +2 -0
  156. package/build/types/pipe.d.ts +4 -0
  157. package/build/types/pipe.js +2 -0
  158. package/build/types/quorum.d.ts +46 -0
  159. package/build/types/quorum.js +2 -0
  160. package/build/types/redis.d.ts +8 -0
  161. package/build/types/redis.js +2 -0
  162. package/build/types/redisclient.d.ts +25 -0
  163. package/build/types/redisclient.js +2 -0
  164. package/build/types/serializer.d.ts +33 -0
  165. package/build/types/serializer.js +2 -0
  166. package/build/types/stats.d.ts +83 -0
  167. package/build/types/stats.js +2 -0
  168. package/build/types/stream.d.ts +67 -0
  169. package/build/types/stream.js +25 -0
  170. package/build/types/telemetry.d.ts +1 -0
  171. package/build/types/telemetry.js +11 -0
  172. package/build/types/transition.d.ts +17 -0
  173. package/build/types/transition.js +2 -0
  174. package/index.ts +5 -0
  175. package/modules/errors.ts +55 -0
  176. package/modules/key.ts +129 -0
  177. package/modules/utils.ts +170 -0
  178. package/package.json +73 -0
  179. package/services/activities/activity.ts +473 -0
  180. package/services/activities/await.ts +172 -0
  181. package/services/activities/emit.ts +25 -0
  182. package/services/activities/index.ts +15 -0
  183. package/services/activities/iterate.ts +26 -0
  184. package/services/activities/trigger.ts +196 -0
  185. package/services/activities/worker.ts +190 -0
  186. package/services/collator/README.md +102 -0
  187. package/services/collator/index.ts +182 -0
  188. package/services/compiler/deployer.ts +432 -0
  189. package/services/compiler/index.ts +98 -0
  190. package/services/compiler/validator.ts +154 -0
  191. package/services/connector/clients/ioredis.ts +57 -0
  192. package/services/connector/clients/redis.ts +72 -0
  193. package/services/connector/index.ts +44 -0
  194. package/services/dimension/README.md +73 -0
  195. package/services/dimension/index.ts +39 -0
  196. package/services/durable/asyncLocalStorage.ts +3 -0
  197. package/services/durable/client.ts +116 -0
  198. package/services/durable/connection.ts +50 -0
  199. package/services/durable/factory.ts +124 -0
  200. package/services/durable/handle.ts +43 -0
  201. package/services/durable/index.ts +60 -0
  202. package/services/durable/native.ts +46 -0
  203. package/services/durable/worker.ts +254 -0
  204. package/services/durable/workflow.ts +136 -0
  205. package/services/engine/index.ts +615 -0
  206. package/services/hotmesh/index.ts +182 -0
  207. package/services/logger/index.ts +79 -0
  208. package/services/mapper/index.ts +84 -0
  209. package/services/pipe/functions/array.ts +87 -0
  210. package/services/pipe/functions/bitwise.ts +27 -0
  211. package/services/pipe/functions/conditional.ts +31 -0
  212. package/services/pipe/functions/date.ts +214 -0
  213. package/services/pipe/functions/index.ts +25 -0
  214. package/services/pipe/functions/json.ts +11 -0
  215. package/services/pipe/functions/math.ts +143 -0
  216. package/services/pipe/functions/number.ts +150 -0
  217. package/services/pipe/functions/object.ts +79 -0
  218. package/services/pipe/functions/string.ts +86 -0
  219. package/services/pipe/functions/symbol.ts +39 -0
  220. package/services/pipe/functions/unary.ts +19 -0
  221. package/services/pipe/index.ts +138 -0
  222. package/services/quorum/index.ts +200 -0
  223. package/services/reporter/index.ts +379 -0
  224. package/services/serializer/README.md +10 -0
  225. package/services/serializer/index.ts +243 -0
  226. package/services/signaler/store.ts +61 -0
  227. package/services/signaler/stream.ts +354 -0
  228. package/services/store/cache.ts +172 -0
  229. package/services/store/clients/ioredis.ts +123 -0
  230. package/services/store/clients/redis.ts +169 -0
  231. package/services/store/index.ts +757 -0
  232. package/services/stream/clients/ioredis.ts +148 -0
  233. package/services/stream/clients/redis.ts +144 -0
  234. package/services/stream/index.ts +57 -0
  235. package/services/sub/clients/ioredis.ts +83 -0
  236. package/services/sub/clients/redis.ts +74 -0
  237. package/services/sub/index.ts +25 -0
  238. package/services/task/index.ts +86 -0
  239. package/services/telemetry/index.ts +267 -0
  240. package/services/worker/index.ts +165 -0
  241. package/types/activity.ts +115 -0
  242. package/types/app.ts +20 -0
  243. package/types/async.ts +7 -0
  244. package/types/cache.ts +1 -0
  245. package/types/collator.ts +9 -0
  246. package/types/durable.ts +81 -0
  247. package/types/hook.ts +32 -0
  248. package/types/hotmesh.ts +102 -0
  249. package/types/index.ts +138 -0
  250. package/types/ioredisclient.ts +10 -0
  251. package/types/job.ts +59 -0
  252. package/types/logger.ts +6 -0
  253. package/types/map.ts +5 -0
  254. package/types/ms.d.ts +7 -0
  255. package/types/pipe.ts +7 -0
  256. package/types/quorum.ts +59 -0
  257. package/types/redis.ts +27 -0
  258. package/types/redisclient.ts +29 -0
  259. package/types/serializer.ts +38 -0
  260. package/types/stats.ts +100 -0
  261. package/types/stream.ts +75 -0
  262. package/types/telemetry.ts +15 -0
  263. package/types/transition.ts +20 -0
@@ -0,0 +1,615 @@
1
+ import { KeyType } from '../../modules/key';
2
+ import {
3
+ formatISODate,
4
+ getSubscriptionTopic,
5
+ identifyRedisType,
6
+ restoreHierarchy } from '../../modules/utils';
7
+ import Activities from '../activities';
8
+ import { Activity } from '../activities/activity';
9
+ import { Await } from '../activities/await';
10
+ import { Worker } from '../activities/worker';
11
+ import { Trigger } from '../activities/trigger';
12
+ import { CompilerService } from '../compiler';
13
+ import { ILogger } from '../logger';
14
+ import { ReporterService } from '../reporter';
15
+ import { SerializerService } from '../serializer';
16
+ import { StoreSignaler } from '../signaler/store';
17
+ import { StreamSignaler } from '../signaler/stream';
18
+ import { StoreService } from '../store';
19
+ import { RedisStoreService as RedisStore } from '../store/clients/redis';
20
+ import { IORedisStoreService as IORedisStore } from '../store/clients/ioredis';
21
+ import { StreamService } from '../stream';
22
+ import { RedisStreamService as RedisStream } from '../stream/clients/redis';
23
+ import { IORedisStreamService as IORedisStream } from '../stream/clients/ioredis';
24
+ import { SubService } from '../sub';
25
+ import { IORedisSubService as IORedisSub } from '../sub/clients/ioredis';
26
+ import { RedisSubService as RedisSub } from '../sub/clients/redis';
27
+ import { TaskService } from '../task';
28
+ import { AppVID } from '../../types/app';
29
+ import {
30
+ ActivityMetadata,
31
+ ActivityType,
32
+ Consumes } from '../../types/activity';
33
+ import { CacheMode } from '../../types/cache';
34
+ import { RedisClientType as IORedisClientType } from '../../types/ioredisclient';
35
+ import {
36
+ JobState,
37
+ JobData,
38
+ JobMetadata,
39
+ JobOutput,
40
+ PartialJobState,
41
+ JobStatus } from '../../types/job';
42
+ import {
43
+ HotMeshApps,
44
+ HotMeshConfig,
45
+ HotMeshManifest,
46
+ HotMeshSettings } from '../../types/hotmesh';
47
+ import {
48
+ JobMessage,
49
+ JobMessageCallback,
50
+ SubscriptionCallback } from '../../types/quorum';
51
+ import { RedisClient, RedisMulti } from '../../types/redis';
52
+ import { RedisClientType } from '../../types/redisclient';
53
+ import {
54
+ GetStatsOptions,
55
+ IdsResponse,
56
+ JobStatsInput,
57
+ StatsResponse
58
+ } from '../../types/stats';
59
+ import {
60
+ StreamData,
61
+ StreamDataResponse,
62
+ StreamDataType,
63
+ StreamError,
64
+ StreamRole,
65
+ StreamStatus } from '../../types/stream';
66
+
67
+ //wait time to see if a job is complete
68
+ const OTT_WAIT_TIME = 1000;
69
+ const STATUS_CODE_SUCCESS = 200;
70
+ const STATUS_CODE_TIMEOUT = 504;
71
+
72
+ class EngineService {
73
+ namespace: string;
74
+ apps: HotMeshApps | null;
75
+ appId: string;
76
+ guid: string;
77
+ store: StoreService<RedisClient, RedisMulti> | null;
78
+ stream: StreamService<RedisClient, RedisMulti> | null;
79
+ subscribe: SubService<RedisClient, RedisMulti> | null;
80
+ storeSignaler: StoreSignaler | null;
81
+ streamSignaler: StreamSignaler | null;
82
+ task: TaskService | null;
83
+ logger: ILogger;
84
+ cacheMode: CacheMode = 'cache';
85
+ untilVersion: string | null = null;
86
+ jobCallbacks: Record<string, JobMessageCallback> = {};
87
+ reporting = false;
88
+ jobId = 1;
89
+
90
+ static async init(namespace: string, appId: string, guid: string, config: HotMeshConfig, logger: ILogger): Promise<EngineService> {
91
+ if (config.engine) {
92
+ const instance = new EngineService();
93
+ instance.verifyEngineFields(config);
94
+
95
+ instance.namespace = namespace;
96
+ instance.appId = appId;
97
+ instance.guid = guid;
98
+ instance.logger = logger;
99
+
100
+ await instance.initStoreChannel(config.engine.store);
101
+ await instance.initSubChannel(config.engine.sub);
102
+ await instance.initStreamChannel(config.engine.stream);
103
+ instance.streamSignaler = instance.initStreamSignaler(config);
104
+
105
+ instance.streamSignaler.consumeMessages(
106
+ instance.stream.mintKey(
107
+ KeyType.STREAMS,
108
+ { appId: instance.appId },
109
+ ),
110
+ 'ENGINE',
111
+ instance.guid,
112
+ instance.processStreamMessage.bind(instance)
113
+ );
114
+
115
+ //the storeSignaler service is used by the engine to create `webhooks`
116
+ //todo: unify/move to the task service (it manages all `signal` types)
117
+ instance.storeSignaler = new StoreSignaler(instance.store, logger);
118
+
119
+ //the task service is used by the engine to process `webhooks` and `timehooks`
120
+ instance.task = new TaskService(instance.store, logger);
121
+
122
+ return instance;
123
+ }
124
+ }
125
+
126
+ verifyEngineFields(config: HotMeshConfig) {
127
+ if (!identifyRedisType(config.engine.store) ||
128
+ !identifyRedisType(config.engine.stream) ||
129
+ !identifyRedisType(config.engine.sub)) {
130
+ throw new Error('engine config must reference 3 redis client instances');
131
+ }
132
+ }
133
+
134
+ async initStoreChannel(store: RedisClient) {
135
+ if (identifyRedisType(store) === 'redis') {
136
+ this.store = new RedisStore(store as RedisClientType);
137
+ } else {
138
+ this.store = new IORedisStore(store as IORedisClientType);
139
+ }
140
+ await this.store.init(
141
+ this.namespace,
142
+ this.appId,
143
+ this.logger
144
+ );
145
+ }
146
+
147
+ async initSubChannel(sub: RedisClient) {
148
+ if (identifyRedisType(sub) === 'redis') {
149
+ this.subscribe = new RedisSub(sub as RedisClientType);
150
+ } else {
151
+ this.subscribe = new IORedisSub(sub as IORedisClientType);
152
+ }
153
+ await this.subscribe.init(
154
+ this.namespace,
155
+ this.appId,
156
+ this.guid,
157
+ this.logger
158
+ );
159
+ }
160
+
161
+ async initStreamChannel(stream: RedisClient) {
162
+ if (identifyRedisType(stream) === 'redis') {
163
+ this.stream = new RedisStream(stream as RedisClientType);
164
+ } else {
165
+ this.stream = new IORedisStream(stream as IORedisClientType);
166
+ }
167
+ await this.stream.init(
168
+ this.namespace,
169
+ this.appId,
170
+ this.logger
171
+ );
172
+ }
173
+
174
+ initStreamSignaler(config: HotMeshConfig): StreamSignaler {
175
+ return new StreamSignaler(
176
+ {
177
+ namespace: this.namespace,
178
+ appId: this.appId,
179
+ guid: this.guid,
180
+ role: StreamRole.ENGINE,
181
+ reclaimDelay: config.engine.reclaimDelay,
182
+ reclaimCount: config.engine.reclaimCount,
183
+ },
184
+ this.stream,
185
+ this.store,
186
+ this.logger,
187
+ );
188
+ }
189
+
190
+ async getVID(vid?: AppVID): Promise<AppVID> {
191
+ if (this.cacheMode === 'nocache') {
192
+ const app = await this.store.getApp(this.appId, true);
193
+ if (app.version.toString() === this.untilVersion.toString()) {
194
+ //new version is deployed; OK to cache again
195
+ if (!this.apps) this.apps = {};
196
+ this.apps[this.appId] = app;
197
+ this.setCacheMode('cache', app.version.toString());
198
+ }
199
+ return { id: this.appId, version: app.version };
200
+ } else if (!this.apps && vid) {
201
+ this.apps = {};
202
+ this.apps[this.appId] = vid;
203
+ return vid;
204
+ } else {
205
+ return { id: this.appId, version: this.apps?.[this.appId].version };
206
+ }
207
+ }
208
+
209
+ setCacheMode(cacheMode: CacheMode, untilVersion: string) {
210
+ this.logger.info(`engine-rule-cache-updated`, { mode: cacheMode, until: untilVersion });
211
+ this.cacheMode = cacheMode;
212
+ this.untilVersion = untilVersion;
213
+ }
214
+
215
+ async routeToSubscribers(topic: string, message: JobOutput) {
216
+ const jobCallback = this.jobCallbacks[message.metadata.jid];
217
+ if (jobCallback) {
218
+ this.delistJobCallback(message.metadata.jid);
219
+ jobCallback(topic, message);
220
+ }
221
+ }
222
+
223
+ async processWebHooks() {
224
+ this.task.processWebHooks((this.hook).bind(this));
225
+ }
226
+
227
+ async processTimeHooks() {
228
+ this.task.processTimeHooks((this.hookTime).bind(this));
229
+ }
230
+
231
+ async throttle(delayInMillis: number) {
232
+ this.streamSignaler.setThrottle(delayInMillis);
233
+ }
234
+
235
+ // ************* METADATA/MODEL METHODS *************
236
+ async initActivity(topic: string, data: JobData = {}, context?: JobState): Promise<Activity> {
237
+ const [activityId, schema] = await this.getSchema(topic);
238
+ const ActivityHandler = Activities[schema.type];
239
+ if (ActivityHandler) {
240
+ const utc = formatISODate(new Date());
241
+ const metadata: ActivityMetadata = {
242
+ aid: activityId,
243
+ atp: schema.type,
244
+ stp: schema.subtype,
245
+ ac: utc,
246
+ au: utc
247
+ };
248
+ const hook = null;
249
+ return new ActivityHandler(schema, data, metadata, hook, this, context);
250
+ } else {
251
+ throw new Error(`activity type ${schema.type} not found`);
252
+ }
253
+ }
254
+ async getSchema(topic: string): Promise<[activityId: string, schema: ActivityType]> {
255
+ const app = await this.store.getApp(this.appId) as AppVID;
256
+ if (!app) {
257
+ throw new Error(`no app found for id ${this.appId}`);
258
+ }
259
+ if (this.isPrivate(topic)) {
260
+ //private subscriptions use the schema id (.activityId)
261
+ const activityId = topic.substring(1)
262
+ const schema = await this.store.getSchema(activityId, await this.getVID(app));
263
+ return [activityId, schema];
264
+ } else {
265
+ //public subscriptions use a topic (a.b.c) that is associated with a schema id
266
+ const activityId = await this.store.getSubscription(topic, await this.getVID(app));
267
+ if (activityId) {
268
+ const schema = await this.store.getSchema(activityId, await this.getVID(app));
269
+ return [activityId, schema];
270
+ }
271
+ }
272
+ throw new Error(`no subscription found for topic ${topic} in app ${this.appId} for app version ${app.version}`);
273
+ }
274
+ async getSettings(): Promise<HotMeshSettings> {
275
+ return await this.store.getSettings();
276
+ }
277
+ isPrivate(topic: string) {
278
+ return topic.startsWith('.');
279
+ }
280
+
281
+ // ************* COMPILER METHODS *************
282
+ async plan(pathOrYAML: string): Promise<HotMeshManifest> {
283
+ const compiler = new CompilerService(this.store, this.logger);
284
+ return await compiler.plan(pathOrYAML);
285
+ }
286
+ async deploy(pathOrYAML: string): Promise<HotMeshManifest> {
287
+ const compiler = new CompilerService(this.store, this.logger);
288
+ return await compiler.deploy(pathOrYAML);
289
+ }
290
+
291
+ // ************* REPORTER METHODS *************
292
+ async getStats(topic: string, query: JobStatsInput): Promise<StatsResponse> {
293
+ const { id, version } = await this.getVID();
294
+ const reporter = new ReporterService({ id, version }, this.store, this.logger);
295
+ const resolvedQuery = await this.resolveQuery(topic, query);
296
+ return await reporter.getStats(resolvedQuery);
297
+ }
298
+ async getIds(topic: string, query: JobStatsInput, queryFacets = []): Promise<IdsResponse> {
299
+ const { id, version } = await this.getVID();
300
+ const reporter = new ReporterService({ id, version }, this.store, this.logger);
301
+ const resolvedQuery = await this.resolveQuery(topic, query);
302
+ return await reporter.getIds(resolvedQuery, queryFacets);
303
+ }
304
+ async resolveQuery(topic: string, query: JobStatsInput): Promise<GetStatsOptions> {
305
+ const trigger = await this.initActivity(topic, query.data) as Trigger;
306
+ await trigger.getState();
307
+ return {
308
+ end: query.end,
309
+ start: query.start,
310
+ range: query.range,
311
+ granularity: trigger.resolveGranularity(),
312
+ key: trigger.resolveJobKey(trigger.createInputContext()),
313
+ sparse: query.sparse,
314
+ } as GetStatsOptions;
315
+ }
316
+
317
+ // ****************** STREAM RE-ENTRY POINT *****************
318
+ async processStreamMessage(streamData: StreamDataResponse): Promise<void> {
319
+ this.logger.debug('engine-process-stream-message', {
320
+ jid: streamData.metadata.jid,
321
+ dad: streamData.metadata.dad,
322
+ aid: streamData.metadata.aid,
323
+ status: streamData.status || StreamStatus.SUCCESS,
324
+ code: streamData.code || 200,
325
+ });
326
+ const context: PartialJobState = {
327
+ metadata: {
328
+ jid: streamData.metadata.jid,
329
+ dad: streamData.metadata.dad,
330
+ aid: streamData.metadata.aid,
331
+ },
332
+ data: streamData.data,
333
+ };
334
+ if (streamData.type === StreamDataType.TIMEHOOK || streamData.type === StreamDataType.WEBHOOK || streamData.type === StreamDataType.TRANSITION) {
335
+ const activityHandler = await this.initActivity(`.${streamData.metadata.aid}`, context.data, context as JobState) as Activity;
336
+ if (streamData.type === StreamDataType.TIMEHOOK) {
337
+ await activityHandler.processTimeHookEvent(streamData.metadata.jid);
338
+ } else if (streamData.type === StreamDataType.TRANSITION) {
339
+ await activityHandler.process();
340
+ } else {
341
+ await activityHandler.processWebHookEvent();
342
+ }
343
+ } else if (streamData.type === StreamDataType.AWAIT) {
344
+ context.metadata = {
345
+ ...context.metadata,
346
+ pj: streamData.metadata.jid,
347
+ pd: streamData.metadata.dad,
348
+ pa: streamData.metadata.aid,
349
+ trc: streamData.metadata.trc,
350
+ spn: streamData.metadata.spn,
351
+ };
352
+ const activityHandler = await this.initActivity(streamData.metadata.topic, streamData.data, context as JobState) as Trigger;
353
+ await activityHandler.process();
354
+ } else if (streamData.type === StreamDataType.RESULT) {
355
+ const activityHandler = await this.initActivity(`.${context.metadata.aid}`, streamData.data, context as JobState) as Await;
356
+ await activityHandler.processEvent(streamData.status, streamData.code);
357
+ } else {
358
+ const activityHandler = await this.initActivity(`.${streamData.metadata.aid}`, streamData.data, context as JobState) as Worker;
359
+ await activityHandler.processEvent(streamData.status, streamData.code);
360
+ }
361
+ this.logger.debug('engine-process-stream-message-end', {
362
+ jid: streamData.metadata.jid,
363
+ aid: streamData.metadata.aid
364
+ });
365
+ }
366
+
367
+ // ***************** `AWAIT` ACTIVITY RETURN RESPONSE ****************
368
+ async execAdjacentParent(context: JobState, jobOutput: JobOutput): Promise<string> {
369
+ if (this.hasParentJob(context)) {
370
+ //errors are stringified `StreamError` objects
371
+ const error = this.resolveError(jobOutput.metadata);
372
+ const spn = context['$self']?.output?.metadata?.l2s || context['$self']?.output?.metadata?.l1s;
373
+ const streamData: StreamData = {
374
+ metadata: {
375
+ jid: context.metadata.pj,
376
+ dad: context.metadata.pd,
377
+ aid: context.metadata.pa,
378
+ trc: context.metadata.trc,
379
+ spn,
380
+ },
381
+ type: StreamDataType.RESULT,
382
+ data: jobOutput.data,
383
+ };
384
+ if (error && error.code) {
385
+ streamData.status = StreamStatus.ERROR;
386
+ streamData.data = error;
387
+ streamData.code = error.code;
388
+ } else {
389
+ streamData.status = StreamStatus.SUCCESS;
390
+ streamData.code = STATUS_CODE_SUCCESS;
391
+ }
392
+ return (await this.streamSignaler?.publishMessage(null, streamData)) as string;
393
+ }
394
+ }
395
+ hasParentJob(context: JobState): boolean {
396
+ //todo: include the dimensional address (pd)
397
+ return Boolean(context.metadata.pj && context.metadata.pa);
398
+ }
399
+ resolveError(metadata: JobMetadata): StreamError | undefined {
400
+ if (metadata && metadata.err) {
401
+ return JSON.parse(metadata.err) as StreamError;
402
+ }
403
+ }
404
+
405
+ // ****************** `SCRUB` CLEAN COMPLETED JOBS *****************
406
+ async scrub(jobId: string) {
407
+ await this.store.scrub(jobId);
408
+ }
409
+
410
+ // ****************** `HOOK` ACTIVITY RE-ENTRY POINT *****************
411
+ async hook(topic: string, data: JobData): Promise<JobStatus | void> {
412
+ const hookRule = await this.storeSignaler.getHookRule(topic);
413
+ const streamData: StreamData = {
414
+ type: StreamDataType.WEBHOOK,
415
+ metadata: { aid: `${hookRule.to}`, topic },
416
+ data,
417
+ };
418
+ await this.streamSignaler.publishMessage(null, streamData);
419
+ }
420
+ async hookTime(jobId: string, activityId: string): Promise<JobStatus | void> {
421
+ const streamData: StreamData = {
422
+ type: StreamDataType.TIMEHOOK,
423
+ metadata: {
424
+ jid: jobId,
425
+ aid: activityId,
426
+ },
427
+ data: { timestamp: Date.now() },
428
+ };
429
+ await this.streamSignaler.publishMessage(null, streamData);
430
+ }
431
+ async hookAll(hookTopic: string, data: JobData, query: JobStatsInput, queryFacets: string[] = []): Promise<string[]> {
432
+ const config = await this.getVID();
433
+ const hookRule = await this.storeSignaler.getHookRule(hookTopic);
434
+ if (hookRule) {
435
+ const subscriptionTopic = await getSubscriptionTopic(hookRule.to, this.store, config)
436
+ const resolvedQuery = await this.resolveQuery(subscriptionTopic, query);
437
+ const reporter = new ReporterService(config, this.store, this.logger);
438
+ const workItems = await reporter.getWorkItems(resolvedQuery, queryFacets);
439
+ const taskService = new TaskService(this.store, this.logger);
440
+ await taskService.enqueueWorkItems(
441
+ workItems.map(
442
+ workItem => `${hookTopic}::${workItem}::${JSON.stringify(data)}`
443
+ ));
444
+ this.store.publish(
445
+ KeyType.QUORUM,
446
+ { type: 'work', originator: this.guid },
447
+ this.appId
448
+ );
449
+ return workItems;
450
+ } else {
451
+ throw new Error(`unable to find hook rule for topic ${hookTopic}`);
452
+ }
453
+ }
454
+
455
+
456
+ // ********************** PUB/SUB ENTRY POINT **********************
457
+ //publish (returns just the job id)
458
+ async pub(topic: string, data: JobData, context?: JobState) {
459
+ const activityHandler = await this.initActivity(topic, data, context);
460
+ if (activityHandler) {
461
+ return await activityHandler.process();
462
+ } else {
463
+ throw new Error(`unable to process activity for topic ${topic}`);
464
+ }
465
+ }
466
+ //subscribe to all jobs for a topic
467
+ async sub(topic: string, callback: JobMessageCallback): Promise<void> {
468
+ const subscriptionCallback: SubscriptionCallback = async (topic: string, message: {topic: string, job: JobOutput}) => {
469
+ callback(message.topic, message.job);
470
+ };
471
+ return await this.subscribe.subscribe(KeyType.QUORUM, subscriptionCallback, this.appId, topic);
472
+ }
473
+ //unsubscribe to all jobs for a topic
474
+ async unsub(topic: string): Promise<void> {
475
+ return await this.subscribe.unsubscribe(KeyType.QUORUM, this.appId, topic);
476
+ }
477
+ //subscribe to all jobs for a wildcard topic
478
+ async psub(wild: string, callback: JobMessageCallback): Promise<void> {
479
+ const subscriptionCallback: SubscriptionCallback = async (topic: string, message: {topic: string, job: JobOutput}) => {
480
+ callback(message.topic, message.job);
481
+ };
482
+ return await this.subscribe.psubscribe(KeyType.QUORUM, subscriptionCallback, this.appId, wild);
483
+ }
484
+ //unsubscribe to all jobs for a wildcard topic
485
+ async punsub(wild: string): Promise<void> {
486
+ return await this.subscribe.punsubscribe(KeyType.QUORUM, this.appId, wild);
487
+ }
488
+ //publish and await (returns the job and data (if ready)); throws error with jobid if not
489
+ async pubsub(topic: string, data: JobData, context?: JobState | null, timeout = OTT_WAIT_TIME): Promise<JobOutput> {
490
+ context = {
491
+ metadata: {
492
+ ngn: this.guid,
493
+ trc: context?.metadata?.trc,
494
+ spn: context?.metadata?.spn
495
+ }
496
+ } as JobState;
497
+ const jobId = await this.pub(topic, data, context);
498
+ return new Promise((resolve, reject) => {
499
+ this.registerJobCallback(jobId, (topic: string, output: JobOutput) => {
500
+ if (output.metadata.err) {
501
+ const error = JSON.parse(output.metadata.err) as StreamError;
502
+ reject({
503
+ ...error,
504
+ job_id: output.metadata.jid,
505
+ });
506
+ } else {
507
+ resolve(output);
508
+ }
509
+ });
510
+ setTimeout(() => {
511
+ this.delistJobCallback(jobId);
512
+ reject({
513
+ code: STATUS_CODE_TIMEOUT,
514
+ message: 'timeout',
515
+ job_id: jobId
516
+ } as StreamError);
517
+ }, timeout);
518
+ });
519
+ }
520
+ async resolveOneTimeSubscription(context: JobState, jobOutput: JobOutput) {
521
+ //todo: subscriber should query for the job...only publish minimum context needed
522
+ if (this.hasOneTimeSubscription(context)) {
523
+ const message: JobMessage = {
524
+ type: 'job',
525
+ topic: context.metadata.jid,
526
+ job: restoreHierarchy(jobOutput) as JobOutput,
527
+ };
528
+ this.store.publish(KeyType.QUORUM, message, this.appId, context.metadata.ngn);
529
+ }
530
+ }
531
+ async getPublishesTopic(context: JobState): Promise<string> {
532
+ const config = await this.getVID();
533
+ const activityId = context.metadata.aid || context['$self']?.output?.metadata?.aid;
534
+ const schema = await this.store.getSchema(activityId, config);
535
+ return schema.publishes;
536
+ }
537
+ async resolvePersistentSubscriptions(context: JobState, jobOutput: JobOutput) {
538
+ const topic = await this.getPublishesTopic(context);
539
+ if (topic) {
540
+ const message: JobMessage = {
541
+ type: 'job',
542
+ topic,
543
+ job: restoreHierarchy(jobOutput) as JobOutput,
544
+ };
545
+ this.store.publish(KeyType.QUORUM, message, this.appId, `${topic}.${context.metadata.jid}`);
546
+ }
547
+ }
548
+ async add(streamData: StreamData|StreamDataResponse): Promise<string> {
549
+ return await this.streamSignaler.publishMessage(null, streamData) as string;
550
+ }
551
+
552
+ registerJobCallback(jobId: string, jobCallback: JobMessageCallback) {
553
+ this.jobCallbacks[jobId] = jobCallback;
554
+ }
555
+ delistJobCallback(jobId: string) {
556
+ delete this.jobCallbacks[jobId];
557
+ }
558
+ hasOneTimeSubscription(context: JobState): boolean {
559
+ return Boolean(context.metadata.ngn);
560
+ }
561
+
562
+
563
+ // ***************** JOB COMPLETION/CLEANUP *****************
564
+ async runJobCompletionTasks(context: JobState) {
565
+ const isAwait = this.hasParentJob(context);
566
+ const isOneTimeSubscription = this.hasOneTimeSubscription(context);
567
+ const topic = await this.getPublishesTopic(context);
568
+ if (isAwait || isOneTimeSubscription || topic) {
569
+ const jobOutput = await this.getState(context.metadata.tpc, context.metadata.jid);
570
+ //always wait for stream pub/sub
571
+ await this.execAdjacentParent(context, jobOutput);
572
+ //no need to wait for standard pub/sub
573
+ this.resolveOneTimeSubscription(context, jobOutput);
574
+ this.resolvePersistentSubscriptions(context, jobOutput);
575
+ }
576
+ this.task.registerJobForCleanup(context.metadata.jid, context.metadata.expire);
577
+ }
578
+
579
+
580
+ // ****** GET JOB STATE/COLLATION STATUS BY ID *********
581
+ async getStatus(jobId: string): Promise<JobStatus> {
582
+ const { id: appId } = await this.getVID();
583
+ return this.store.getStatus(jobId, appId);
584
+ }
585
+ //todo: add 'options' parameter;
586
+ // (e.g, if {dimensions:true}, use hscan to deliver
587
+ // the full set of dimensional job data)
588
+ async getState(topic: string, jobId: string): Promise<JobOutput> {
589
+ const { id: appId } = await this.getVID();
590
+ const jobSymbols = await this.store.getSymbols(`$${topic}`);
591
+ const consumes: Consumes = {
592
+ [`$${topic}`]: Object.keys(jobSymbols)
593
+ }
594
+ const output = await this.store.getState(jobId, consumes);
595
+ if (!output) {
596
+ throw new Error(`not found ${jobId}`);
597
+ }
598
+ const [state, status] = output;
599
+ const stateTree = restoreHierarchy(state) as JobOutput;
600
+ if (status && stateTree.metadata) {
601
+ stateTree.metadata.js = status;
602
+ }
603
+ return stateTree;
604
+ }
605
+
606
+ async compress(terms: string[]): Promise<boolean> {
607
+ const existingSymbols = await this.store.getSymbolValues();
608
+ const startIndex = Object.keys(existingSymbols).length;
609
+ const maxIndex = Math.pow(52, 2) - 1;
610
+ const newSymbols = SerializerService.filterSymVals(startIndex, maxIndex, existingSymbols, new Set(terms));
611
+ return await this.store.addSymbolValues(newSymbols);
612
+ }
613
+ }
614
+
615
+ export { EngineService };