@colabo-flow/s-go 0.1.2 → 0.2.4

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 (222) hide show
  1. package/README.md +1 -1
  2. package/dist/cjs/index.js +8 -0
  3. package/dist/cjs/index.js.map +1 -0
  4. package/dist/cjs/jest.config.d.ts +3 -0
  5. package/{index.ts → dist/cjs/src/index.d.ts} +3 -4
  6. package/dist/cjs/src/lib/config.d.ts +13 -0
  7. package/dist/cjs/src/lib/go.amqp.client.d.ts +4 -0
  8. package/dist/cjs/src/lib/go.amqp.host.d.ts +6 -0
  9. package/dist/cjs/src/lib/go.amqp.host_status.d.ts +1 -0
  10. package/dist/cjs/src/lib/go.amqp.service.d.ts +1 -0
  11. package/dist/cjs/src/lib/operators.d.ts +2 -0
  12. package/dist/cjs/src/lib/params.d.ts +1 -0
  13. package/dist/cjs/src/lib/vos.d.ts +173 -0
  14. package/dist/cjs/tests/units/chalk/index.d.ts +21 -0
  15. package/dist/cjs/tests/units/tests-vos/tasks-and-flows.vos.d.ts +20 -0
  16. package/dist/colabo/src/services/puzzles/flow/go/index.js +7 -0
  17. package/dist/colabo/src/services/puzzles/flow/go/index.js.map +1 -0
  18. package/dist/colabo/src/services/puzzles/flow/go/lib/config.js +21 -0
  19. package/dist/colabo/src/services/puzzles/flow/go/lib/config.js.map +1 -0
  20. package/dist/colabo/src/services/puzzles/flow/go/lib/go.amqp.client.js +80 -0
  21. package/dist/colabo/src/services/puzzles/flow/go/lib/go.amqp.client.js.map +1 -0
  22. package/dist/colabo/src/services/puzzles/flow/go/lib/go.amqp.host.js +237 -0
  23. package/dist/colabo/src/services/puzzles/flow/go/lib/go.amqp.host.js.map +1 -0
  24. package/dist/colabo/src/services/puzzles/flow/go/lib/go.amqp.host_status.js +67 -0
  25. package/dist/colabo/src/services/puzzles/flow/go/lib/go.amqp.host_status.js.map +1 -0
  26. package/dist/colabo/src/services/puzzles/flow/go/lib/go.amqp.service.js +244 -0
  27. package/dist/colabo/src/services/puzzles/flow/go/lib/go.amqp.service.js.map +1 -0
  28. package/dist/colabo/src/services/puzzles/flow/go/lib/operators.js +15 -0
  29. package/dist/colabo/src/services/puzzles/flow/go/lib/operators.js.map +1 -0
  30. package/dist/colabo/src/services/puzzles/flow/go/lib/params.js +2 -0
  31. package/dist/colabo/src/services/puzzles/flow/go/lib/params.js.map +1 -0
  32. package/dist/colabo/src/services/puzzles/flow/go/lib/vos.js +23 -0
  33. package/dist/colabo/src/services/puzzles/flow/go/lib/vos.js.map +1 -0
  34. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/index.js +22 -0
  35. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/index.js.map +1 -0
  36. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/execution/execution-semaphore.js +203 -0
  37. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/execution/execution-semaphore.js.map +1 -0
  38. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/execution/execution-semaphore.vos.js +2 -0
  39. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/execution/execution-semaphore.vos.js.map +1 -0
  40. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/execution/execution-vos.js +45 -0
  41. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/execution/execution-vos.js.map +1 -0
  42. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/execution/execution.operators.js +42 -0
  43. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/execution/execution.operators.js.map +1 -0
  44. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/execution/flow-execution.service.js +334 -0
  45. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/execution/flow-execution.service.js.map +1 -0
  46. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/executors/executors-store.js +2 -0
  47. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/executors/executors-store.js.map +1 -0
  48. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/executors/executors-vos.js +30 -0
  49. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/executors/executors-vos.js.map +1 -0
  50. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-instance-engine/flow-instance-engine-updates-vos.js +10 -0
  51. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-instance-engine/flow-instance-engine-updates-vos.js.map +1 -0
  52. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-instance-engine/flow-instance-engine-vos.js +106 -0
  53. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-instance-engine/flow-instance-engine-vos.js.map +1 -0
  54. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-instance-engine/flow-instance-engine.js +1513 -0
  55. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-instance-engine/flow-instance-engine.js.map +1 -0
  56. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-instance-engine/index.js +5 -0
  57. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-instance-engine/index.js.map +1 -0
  58. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-types/flow-type-utils.js +189 -0
  59. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-types/flow-type-utils.js.map +1 -0
  60. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-types/flow-types-condensed.operators.js +335 -0
  61. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-types/flow-types-condensed.operators.js.map +1 -0
  62. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-types/flow-types-condensed.vos.js +8 -0
  63. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-types/flow-types-condensed.vos.js.map +1 -0
  64. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-types/flow-types-form-condensed.operators.js +38 -0
  65. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-types/flow-types-form-condensed.operators.js.map +1 -0
  66. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-types/flow-types-form-condensed.vos.js +10 -0
  67. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-types/flow-types-form-condensed.vos.js.map +1 -0
  68. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-types/flow-types-form.vos.js +2 -0
  69. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-types/flow-types-form.vos.js.map +1 -0
  70. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-types/flow-types-translators.vos.js +5 -0
  71. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-types/flow-types-translators.vos.js.map +1 -0
  72. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-types/flow-types-visual.vos.js +16 -0
  73. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-types/flow-types-visual.vos.js.map +1 -0
  74. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-types/flow-types-vos.js +103 -0
  75. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-types/flow-types-vos.js.map +1 -0
  76. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-types/flow-types.operators.js +121 -0
  77. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/lib/flow-types/flow-types.operators.js.map +1 -0
  78. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/vos.js +25 -0
  79. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/flow/core/vos.js.map +1 -0
  80. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/utils/verify/index.js +3 -0
  81. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/utils/verify/index.js.map +1 -0
  82. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/utils/verify/lib/assertion.js +20 -0
  83. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/utils/verify/lib/assertion.js.map +1 -0
  84. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/utils/verify/lib/params.js +2 -0
  85. package/dist/colabo-vue3/src/isomorphic/dev_puzzles/utils/verify/lib/params.js.map +1 -0
  86. package/dist/colabo-vue3/src/isomorphic/puzzles/datatalks/cache/index.js +7 -0
  87. package/dist/colabo-vue3/src/isomorphic/puzzles/datatalks/cache/index.js.map +1 -0
  88. package/dist/colabo-vue3/src/isomorphic/puzzles/datatalks/cache/lib/datatalks-cache.service.js +33 -0
  89. package/dist/colabo-vue3/src/isomorphic/puzzles/datatalks/cache/lib/datatalks-cache.service.js.map +1 -0
  90. package/dist/colabo-vue3/src/isomorphic/puzzles/datatalks/cache/lib/datatalks-cache.vos.js +2 -0
  91. package/dist/colabo-vue3/src/isomorphic/puzzles/datatalks/cache/lib/datatalks-cache.vos.js.map +1 -0
  92. package/dist/colabo-vue3/src/isomorphic/puzzles/datatalks/cache/lib/params.js +2 -0
  93. package/dist/colabo-vue3/src/isomorphic/puzzles/datatalks/cache/lib/params.js.map +1 -0
  94. package/dist/colabo-vue3/src/isomorphic/puzzles/datatalks/cache/vos.js +2 -0
  95. package/dist/colabo-vue3/src/isomorphic/puzzles/datatalks/cache/vos.js.map +1 -0
  96. package/dist/colabo-vue3/src/isomorphic/puzzles/headless/core-backend/chalk/index.js +3 -0
  97. package/dist/colabo-vue3/src/isomorphic/puzzles/headless/core-backend/chalk/index.js.map +1 -0
  98. package/dist/colabo-vue3/src/isomorphic/puzzles/transform/json/index.js +6 -0
  99. package/dist/colabo-vue3/src/isomorphic/puzzles/transform/json/index.js.map +1 -0
  100. package/dist/colabo-vue3/src/isomorphic/puzzles/transform/json/lib/transform.js +582 -0
  101. package/dist/colabo-vue3/src/isomorphic/puzzles/transform/json/lib/transform.js.map +1 -0
  102. package/dist/colabo-vue3/src/isomorphic/puzzles/transform/json/lib/vos/transform.vos.js +33 -0
  103. package/dist/colabo-vue3/src/isomorphic/puzzles/transform/json/lib/vos/transform.vos.js.map +1 -0
  104. package/dist/esm/index.js +8 -0
  105. package/dist/esm/index.js.map +1 -0
  106. package/dist/esm/jest.config.d.ts +3 -0
  107. package/dist/esm/src/index.d.ts +3 -0
  108. package/dist/esm/src/lib/config.d.ts +13 -0
  109. package/dist/esm/src/lib/go.amqp.client.d.ts +4 -0
  110. package/dist/esm/src/lib/go.amqp.host.d.ts +6 -0
  111. package/dist/esm/src/lib/go.amqp.host_status.d.ts +1 -0
  112. package/dist/esm/src/lib/go.amqp.service.d.ts +1 -0
  113. package/dist/esm/src/lib/operators.d.ts +2 -0
  114. package/dist/esm/src/lib/params.d.ts +1 -0
  115. package/dist/esm/src/lib/vos.d.ts +173 -0
  116. package/dist/esm/tests/units/chalk/index.d.ts +21 -0
  117. package/dist/esm/tests/units/tests-vos/tasks-and-flows.vos.d.ts +20 -0
  118. package/dist/index.d.ts +184 -0
  119. package/package.json +38 -6
  120. package/DEVELOPMENT.md +0 -38
  121. package/__init__.py +0 -0
  122. package/__pycache__/__init__.cpython-39.pyc +0 -0
  123. package/create_client.py +0 -84
  124. package/create_host.py +0 -91
  125. package/create_host_terra.py +0 -103
  126. package/demo/__init__.py +0 -0
  127. package/demo/create-client.ts +0 -51
  128. package/demo/create-host.ts +0 -136
  129. package/demo/send-simple-recommended.py +0 -26
  130. package/demo/send-simple.py +0 -50
  131. package/demo/send.py +0 -352
  132. package/demo/send.ts +0 -40
  133. package/demo/threading/README.md +0 -14
  134. package/demo/threading/basic_consumer_connection_threaded.png +0 -0
  135. package/demo/threading/basic_consumer_connection_threaded.py +0 -135
  136. package/demo/threading/basic_consumer_threaded.py +0 -100
  137. package/demo/threading/long-running-publisher.py +0 -68
  138. package/docs/ColaboFlow-infrastructure-diagram.png +0 -0
  139. package/docs/workflow.md +0 -35
  140. package/jest.config.ts +0 -172
  141. package/lib/__init__.py +0 -0
  142. package/lib/__pycache__/__init__.cpython-39.pyc +0 -0
  143. package/lib/__pycache__/config.cpython-39.pyc +0 -0
  144. package/lib/__pycache__/executor_operators.cpython-39.pyc +0 -0
  145. package/lib/__pycache__/executor_vos.cpython-39.pyc +0 -0
  146. package/lib/__pycache__/go_amqp_client.cpython-39.pyc +0 -0
  147. package/lib/__pycache__/go_amqp_client_threaded.cpython-39.pyc +0 -0
  148. package/lib/__pycache__/go_amqp_host.cpython-39.pyc +0 -0
  149. package/lib/__pycache__/operators.cpython-39.pyc +0 -0
  150. package/lib/__pycache__/vos.cpython-39.pyc +0 -0
  151. package/lib/config.py +0 -21
  152. package/lib/config.ts +0 -22
  153. package/lib/executor_operators.py +0 -23
  154. package/lib/executor_vos.py +0 -318
  155. package/lib/go.amqp.client-old-basic.py +0 -50
  156. package/lib/go.amqp.client.ts +0 -100
  157. package/lib/go.amqp.host-old-basic.py +0 -48
  158. package/lib/go.amqp.host.ts +0 -269
  159. package/lib/go.amqp.host_status.ts +0 -81
  160. package/lib/go.amqp.service.ts +0 -272
  161. package/lib/go_amqp_client.py +0 -263
  162. package/lib/go_amqp_client_non_threaded.py +0 -152
  163. package/lib/go_amqp_host.py +0 -348
  164. package/lib/operators.py +0 -16
  165. package/lib/operators.ts +0 -17
  166. package/lib/params.ts +0 -1
  167. package/lib/vos.py +0 -232
  168. package/lib/vos.ts +0 -212
  169. package/requirements.txt +0 -4
  170. package/tests/units/README.md +0 -12
  171. package/tests/units/chalk/index.ts +0 -41
  172. package/tests/units/go.amqp.host.test.ts +0 -116
  173. package/tests/units/tests-vos/tasks-and-flows.vos.ts +0 -128
  174. package/tsconfig.json +0 -45
  175. package/v1 - GRPC/README.md +0 -18
  176. package/v1 - GRPC/node/README.md +0 -13
  177. package/v1 - GRPC/node/colaboflow_go_actionhost_client.ts +0 -91
  178. package/v1 - GRPC/node/colaboflow_go_actionhost_server.ts +0 -84
  179. package/v1 - GRPC/node/colaboflow_go_client.ts +0 -82
  180. package/v1 - GRPC/node/colaboflow_go_server.ts +0 -84
  181. package/v1 - GRPC/node/demos/demo-colaboflow_go_actionhost_client.ts +0 -21
  182. package/v1 - GRPC/node/index.ts +0 -3
  183. package/v1 - GRPC/node/package-lock.json +0 -770
  184. package/v1 - GRPC/node/package.json +0 -30
  185. package/v1 - GRPC/node/tsconfig.json +0 -32
  186. package/v1 - GRPC/node/yarn.lock +0 -642
  187. package/v1 - GRPC/protos/colabo/flow/go/go.proto +0 -135
  188. package/v1 - GRPC/python/DEVELOPMENT.md +0 -86
  189. package/v1 - GRPC/python/DISCUSSION.md +0 -8
  190. package/v1 - GRPC/python/LICENSE.txt +0 -21
  191. package/v1 - GRPC/python/README.md +0 -45
  192. package/v1 - GRPC/python/__init__.py +0 -1
  193. package/v1 - GRPC/python/colabo/__init__.py +0 -3
  194. package/v1 - GRPC/python/colabo/flow/__init__.py +0 -3
  195. package/v1 - GRPC/python/colabo/flow/go/__init__.py +0 -12
  196. package/v1 - GRPC/python/colabo/flow/go/basic/PuzzleImporter.py +0 -77
  197. package/v1 - GRPC/python/colabo/flow/go/basic/__init__.py +0 -5
  198. package/v1 - GRPC/python/colabo/flow/go/basic/colaboflow_go_basic.py +0 -66
  199. package/v1 - GRPC/python/colabo/flow/go/basic/parseFlowJSON.py +0 -32
  200. package/v1 - GRPC/python/colabo/flow/go/colaboflow_go_actionhost.py +0 -44
  201. package/v1 - GRPC/python/colabo/flow/go/colaboflow_go_client.py +0 -48
  202. package/v1 - GRPC/python/colabo/flow/go/colaboflow_go_demo.py +0 -168
  203. package/v1 - GRPC/python/colabo/flow/go/go_pb2.py +0 -976
  204. package/v1 - GRPC/python/colabo/flow/go/go_pb2_grpc.py +0 -139
  205. package/v1 - GRPC/python/colabo.flow.go.egg-info/PKG-INFO +0 -58
  206. package/v1 - GRPC/python/colabo.flow.go.egg-info/SOURCES.txt +0 -16
  207. package/v1 - GRPC/python/colabo.flow.go.egg-info/dependency_links.txt +0 -1
  208. package/v1 - GRPC/python/colabo.flow.go.egg-info/requires.txt +0 -3
  209. package/v1 - GRPC/python/colabo.flow.go.egg-info/top_level.txt +0 -2
  210. package/v1 - GRPC/python/demo-0.py +0 -69
  211. package/v1 - GRPC/python/demo-1.py +0 -146
  212. package/v1 - GRPC/python/demo-actionhost.py +0 -47
  213. package/v1 - GRPC/python/demo-basic.md +0 -13
  214. package/v1 - GRPC/python/demo-basic.py +0 -38
  215. package/v1 - GRPC/python/demo-executeActionSync.py +0 -32
  216. package/v1 - GRPC/python/demo-flows/flow-demo.json +0 -36
  217. package/v1 - GRPC/python/demo-puzzles/puzzles/puzzle-a.py +0 -19
  218. package/v1 - GRPC/python/demo-puzzles/puzzles/puzzle-b.py +0 -21
  219. package/v1 - GRPC/python/demo-puzzles/puzzles/puzzle-c.py +0 -20
  220. package/v1 - GRPC/python/requirements.txt +0 -7
  221. package/v1 - GRPC/python/setup.py +0 -39
  222. package/v1 - GRPC/python/use-cases/__init__.py +0 -0
@@ -0,0 +1,1513 @@
1
+ import { v1 as uuidv1 } from "uuid";
2
+ import { EFlowTaskExecutionStatus, EFlowSequenceStatus, EFlowGatewayStatus, EFlowEventStatus, ETokenStatusInFlowPlaceInstance, ESemaphoreNames } from "./flow-instance-engine-vos";
3
+ import { EFlowEventType, EFlowPlaceType, EFlowSpecialPortIds, EFlowPlacePortType } from "../flow-types/flow-types-vos";
4
+ import { flowGetSequencesOutgoingFromPlace, flowGetPlaces, flowGetPlaceById, flowGetTaskById, flowGetSequencesIngoingToPlace } from "../flow-types/flow-type-utils";
5
+ import { EFlowExecutionStatus, ETaskExecutionStatus } from "../execution/execution-vos";
6
+ import { asyncExecuteTransformationOnDataObj } from "@colabo-transform/i-json";
7
+ import { assert, assertIsDefined } from "@colabo-utils/i-verify";
8
+ import { EExecutorIdPlace } from "../executors/executors-vos";
9
+ import { asyncSemaphoreWaitOnResource, semaphoresCreate, semaphoreSetBlocking } from "../execution/execution-semaphore";
10
+ /** Checks if the port of the specific direction exists on the place */
11
+ export const isPortIdValidForPlace = (place, portId, portDirection) => {
12
+ if (portDirection == EFlowPlacePortType.IN || portDirection == EFlowPlacePortType.INOUT) {
13
+ if (place.inputs?.length) {
14
+ if (place.inputs.findIndex((input) => input.name === portId) >= 0)
15
+ return true;
16
+ }
17
+ if (place.inoutputs?.length) {
18
+ if (place.inoutputs.findIndex((inoutput) => inoutput.name === portId) >= 0)
19
+ return true;
20
+ }
21
+ if (portId === EFlowSpecialPortIds.DEFAULT)
22
+ return true;
23
+ return false;
24
+ }
25
+ if (portDirection == EFlowPlacePortType.OUT || portDirection == EFlowPlacePortType.INOUT) {
26
+ if (place.outputs?.length) {
27
+ if (place.outputs.findIndex((output) => output.name === portId) >= 0)
28
+ return true;
29
+ }
30
+ if (place.inoutputs?.length) {
31
+ if (place.inoutputs.findIndex((inoutput) => inoutput.name === portId) >= 0)
32
+ return true;
33
+ }
34
+ if (portId === EFlowSpecialPortIds.DEFAULT)
35
+ return true;
36
+ return false;
37
+ }
38
+ return false;
39
+ };
40
+ /**
41
+ /* Creates a task-instance of the provided task. The task instance will relate to its originating task through the `originId` prop
42
+ * @param task the task we want to create the instance of
43
+ * @returns the created task instance of the provided task
44
+ */
45
+ export const createTaskInstanceForTask = (task, token, flowInstance, initiatedPortId = EFlowSpecialPortIds.DEFAULT) => {
46
+ // check port id if it exists in the place
47
+ if (!isPortIdValidForPlace(task, initiatedPortId, EFlowPlacePortType.IN)) {
48
+ throw new Error(`port id "${initiatedPortId}" with direction "{EFlowPlacePortType.IN}" is not matching the task ${JSON.stringify(task)}`);
49
+ }
50
+ const taskInstance = {
51
+ id: `${task.id}:${uuidv1()}`,
52
+ originId: task.id,
53
+ placeType: EFlowPlaceType.TASK,
54
+ status: EFlowTaskExecutionStatus.WAITING,
55
+ tokenStatus: ETokenStatusInFlowPlaceInstance.JUST_ENTERED,
56
+ initiatedTokenIdsPerPorts: { [initiatedPortId]: token.id },
57
+ executionInputReferences: {},
58
+ executionOutputReferences: {},
59
+ currentTokenIds: [],
60
+ };
61
+ flowInstance.taskInstances.push(taskInstance);
62
+ return taskInstance;
63
+ };
64
+ /**
65
+ /* Creates a task-instance of the provided task. The task instance will relate to its originating task through the `originId` prop
66
+ * @param task the task we want to create the instance of
67
+ * @returns the created task instance of the provided task
68
+ */
69
+ export const createTaskInstanceForTaskWithoutFlow = (task) => {
70
+ const taskInstance = {
71
+ id: `${task.id}:${uuidv1()}`,
72
+ originId: task.id,
73
+ placeType: EFlowPlaceType.TASK,
74
+ status: EFlowTaskExecutionStatus.WAITING,
75
+ tokenStatus: ETokenStatusInFlowPlaceInstance.JUST_ENTERED,
76
+ initiatedTokenIdsPerPorts: {},
77
+ executionInputReferences: {},
78
+ executionOutputReferences: {},
79
+ currentTokenIds: [],
80
+ };
81
+ return taskInstance;
82
+ };
83
+ /**
84
+ /* Creates a gateway-instance of the provided gateway. The gateway instance will relate to its originating gateway through the `originId` prop
85
+ * @param gateway the gateway we want to create the instance of
86
+ * @returns the created gateway instance of the provided gateway
87
+ */
88
+ export const createGatewayInstanceForGateway = (gateway, token, flowInstance, initiatedPortId = EFlowSpecialPortIds.DEFAULT) => {
89
+ // check port id if it exists in the place
90
+ if (!isPortIdValidForPlace(gateway, initiatedPortId, EFlowPlacePortType.IN)) {
91
+ throw new Error(`port id "${initiatedPortId}" with direction "{EFlowPlacePortType.IN}" is not matching the gateway ${JSON.stringify(gateway)}`);
92
+ }
93
+ const gatewayInstance = {
94
+ id: `${gateway.id}:${uuidv1()}`,
95
+ originId: gateway.id,
96
+ placeType: EFlowPlaceType.GATEWAY,
97
+ status: EFlowGatewayStatus.WAITING,
98
+ tokenStatus: ETokenStatusInFlowPlaceInstance.JUST_ENTERED,
99
+ initiatedTokenIdsPerPorts: { [initiatedPortId]: token.id },
100
+ executionInputReferences: {},
101
+ executionOutputReferences: {},
102
+ currentTokenIds: [],
103
+ };
104
+ flowInstance.gatewayInstances.push(gatewayInstance);
105
+ return gatewayInstance;
106
+ };
107
+ /**
108
+ /* Creates a event-instance of the provided event. The event instance will relate to its originating event through the `originId` prop
109
+ * @param event the event we want to create the instance of
110
+ * @param token the initiator of the event instance
111
+ * @param flowInstance the floe instance the event instance should belong to
112
+ * @returns the created event instance of the provided event
113
+ */
114
+ export const createEventInstanceForEvent = (event, token, flowInstance, initiatedPortId = EFlowSpecialPortIds.DEFAULT) => {
115
+ // check port id if it exists in the place
116
+ if (!isPortIdValidForPlace(event, initiatedPortId, EFlowPlacePortType.IN)) {
117
+ throw new Error(`port id "${initiatedPortId}" with direction "{EFlowPlacePortType.IN}" is not matching the event ${JSON.stringify(event)}`);
118
+ }
119
+ const eventInstance = {
120
+ id: `${event.id}:${uuidv1()}`,
121
+ originId: event.id,
122
+ placeType: EFlowPlaceType.EVENT,
123
+ status: EFlowEventStatus.WAITING,
124
+ tokenStatus: ETokenStatusInFlowPlaceInstance.JUST_ENTERED,
125
+ initiatedTokenIdsPerPorts: { [initiatedPortId]: token.id },
126
+ executionInputReferences: {},
127
+ executionOutputReferences: {},
128
+ currentTokenIds: [],
129
+ };
130
+ flowInstance.eventInstances.push(eventInstance);
131
+ return eventInstance;
132
+ };
133
+ /**
134
+ /* Creates a place-instance of the provided place. The place instance will relate to its originating place through the `originId`
135
+ * @param place the place we want to create the instance of
136
+ * @param type the type of the place we provided (task, gateway, event, ...)
137
+ * @returns the created place instance of the provided place
138
+ */
139
+ export const createPlaceInstanceForPlace = (place, token, flowInstance, initiatedPortId = EFlowSpecialPortIds.DEFAULT) => {
140
+ let placeInstance;
141
+ switch (place.placeType) {
142
+ case EFlowPlaceType.TASK:
143
+ placeInstance = createTaskInstanceForTask(place, token, flowInstance, initiatedPortId);
144
+ break;
145
+ case EFlowPlaceType.EVENT:
146
+ placeInstance = createEventInstanceForEvent(place, token, flowInstance, initiatedPortId);
147
+ break;
148
+ case EFlowPlaceType.GATEWAY:
149
+ placeInstance = createGatewayInstanceForGateway(place, token, flowInstance, initiatedPortId);
150
+ break;
151
+ }
152
+ return placeInstance;
153
+ };
154
+ /**
155
+ /* Creates a sequence-instance of the provided sequence. The sequence instance will relate to its originating sequence through the `originId` prop
156
+ * @param sequence the sequence we want to create the instance of
157
+ * @returns the created sequence instance of the provided sequence
158
+ */
159
+ export const createSequenceInstanceForSequence = (sequence, token, flowInstance) => {
160
+ const sequenceInstance = {
161
+ id: `${sequence.id}:${uuidv1()}`,
162
+ originId: sequence.id,
163
+ status: EFlowSequenceStatus.WAITING,
164
+ tokenStatus: ETokenStatusInFlowPlaceInstance.JUST_ENTERED,
165
+ initiatedTokenIdsPerPorts: { [EFlowSpecialPortIds.DEFAULT]: token.id },
166
+ currentTokenIds: [],
167
+ };
168
+ flowInstance.sequenceInstances.push(sequenceInstance);
169
+ return sequenceInstance;
170
+ };
171
+ /**
172
+ * Creates flow instance out of a flow
173
+ */
174
+ export const createFlowInstanceForFlow = (flow) => {
175
+ const flowInstance = {
176
+ id: `${flow.id}:${uuidv1()}`,
177
+ flowId: flow.id,
178
+ /** no any token before starting the flow */
179
+ tokens: [],
180
+ /** no any sequence before tokens start flowing through the flow */
181
+ sequenceInstances: [],
182
+ /** no any tasks before tokens start firing them */
183
+ taskInstances: [],
184
+ /** no any events before initial tokens created in the start event(s) or triggering events start creating new tokens and therefore new event instances */
185
+ eventInstances: [],
186
+ /** no any sequence before tokens start flowing through the them */
187
+ gatewayInstances: [],
188
+ executionResult: {
189
+ executionStatus: EFlowExecutionStatus.UNKNOWN,
190
+ },
191
+ };
192
+ // generate tokens
193
+ // currently we should start from (a single) `start` event, put token in it, and then immediately (probably later we will need to provide delayed conditional transition) transit it to the next entity (either task/activity or gateway)
194
+ return flowInstance;
195
+ };
196
+ /**
197
+ * Creates non-serializable part of the pre-created flow instance
198
+ */
199
+ export const createFlowInstanceNSForFlow = (flow, flowInstance) => {
200
+ const flowInstanceNS = {
201
+ flowId: flow.id,
202
+ id: flowInstance.id,
203
+ taskInstancesNS: [],
204
+ eventInstancesNS: [],
205
+ executionSemaphores: semaphoresCreate(flowInstance.executionResult, {
206
+ microTick: {
207
+ resourcesAvailable: -1, // infinite execution
208
+ },
209
+ tick: {
210
+ resourcesAvailable: -1, // infinite execution
211
+ },
212
+ breakpoint: {
213
+ resourcesAvailable: 0, // the next one will
214
+ },
215
+ }),
216
+ };
217
+ return flowInstanceNS;
218
+ };
219
+ /** Returns token matching token id
220
+ * @param tokenId id of the token we want to retrieve
221
+ */
222
+ export const getTokenById = (flowInstance, tokenId) => {
223
+ return flowInstance.tokens.find((token) => token.id === tokenId);
224
+ };
225
+ /**
226
+ * Gets task instances of a task. There might be multiple as many as there were executions of particular task (whenever token entered it)
227
+ * @param flowInstance the flow instance which we want to search in
228
+ * @param taskId the id of the task the instance we search for
229
+ * @returns task instances of the taskId task if they exists or empty array otherwise
230
+ */
231
+ export const getTaskInstancesByTaskId = (flowInstance, taskId) => {
232
+ const taskInstances = [];
233
+ for (const taskInstance of flowInstance.taskInstances) {
234
+ if (taskInstance.originId == taskId)
235
+ taskInstances.push(taskInstance);
236
+ }
237
+ return taskInstances;
238
+ };
239
+ /**
240
+ * Gets place instances of a place. There might be multiple instances as there might be multiple executions (visiting) of a particular place (whenever token entered it)
241
+ * @param flowInstance the flow instance which we want to search in
242
+ * @param placeId the id of the place the instance we search for
243
+ * @param placeType the type of places we search through. If not provided (conditional) the search will still be proceeded but slower as it will be necessary to search through the all place types
244
+ * @returns place instances of the `placeId` place if they exists or empty array otherwise
245
+ */
246
+ export const getPlaceInstancesByPlaceId = (flowInstance, placeId, placeType) => {
247
+ const placeInstances = [];
248
+ if (!placeType || placeType === EFlowPlaceType.TASK) {
249
+ for (const taskInstance of flowInstance.taskInstances) {
250
+ if (taskInstance.originId == placeId)
251
+ placeInstances.push(taskInstance);
252
+ }
253
+ }
254
+ if (!placeType || placeType === EFlowPlaceType.EVENT) {
255
+ for (const eventInstance of flowInstance.eventInstances) {
256
+ if (eventInstance.originId == placeId)
257
+ placeInstances.push(eventInstance);
258
+ }
259
+ }
260
+ if (!placeType || placeType === EFlowPlaceType.GATEWAY) {
261
+ for (const gatewayInstance of flowInstance.gatewayInstances) {
262
+ if (gatewayInstance.originId == placeId)
263
+ placeInstances.push(gatewayInstance);
264
+ }
265
+ }
266
+ return placeInstances;
267
+ };
268
+ /**
269
+ * Gets task instance of a task
270
+ * @param flowInstance the flow instance which we want to search in
271
+ * @param taskId the id of the task the instance we search for
272
+ * @returns task instance of the taskId task if it exists or null otherwise
273
+ */
274
+ export const getTaskInstanceByTaskInstanceId = (flowInstance, taskInstanceId) => {
275
+ for (const taskInstance of flowInstance.taskInstances) {
276
+ if (taskInstance.id == taskInstanceId)
277
+ return taskInstance;
278
+ }
279
+ return undefined;
280
+ };
281
+ /**
282
+ * @param flowInstance the flow instance which we want to search in
283
+ * @param placeInstanceId
284
+ * @returns
285
+ * TODO: TEST
286
+ */
287
+ export const getPlaceInstanceByPlaceInstanceId = (flowInstance, placeInstanceId) => {
288
+ for (const taskInstance of flowInstance.taskInstances) {
289
+ if (taskInstance.id == placeInstanceId)
290
+ return taskInstance;
291
+ }
292
+ for (const eventInstance of flowInstance.eventInstances) {
293
+ if (eventInstance.id == placeInstanceId)
294
+ return eventInstance;
295
+ }
296
+ for (const gatewayInstance of flowInstance.gatewayInstances) {
297
+ if (gatewayInstance.id == placeInstanceId)
298
+ return gatewayInstance;
299
+ }
300
+ };
301
+ /**
302
+ * Returns the input ports in a place
303
+ * @param place place we want to evaluate
304
+ * @returns input ports
305
+ */
306
+ export const placeInputPorts = (place) => {
307
+ return [...(place?.inputs ?? []), ...(place?.inoutputs ?? [])];
308
+ };
309
+ /**
310
+ * Returns the output ports in a place
311
+ * @param place place we want to evaluate
312
+ * @returns input ports
313
+ */
314
+ export const placeOutputPorts = (place) => {
315
+ return [...(place?.outputs ?? []), ...(place?.inoutputs ?? [])];
316
+ };
317
+ /**
318
+ * Returns the number input ports in a place
319
+ *
320
+ * **NOTE**: The default input port is not counted
321
+ * @param place place we want to evaluate
322
+ * @returns number if input ports
323
+ */
324
+ export const placeNumberOfInputPorts = (place) => {
325
+ const portsIn = (place.inputs?.length ?? 0) + (place.inoutputs?.length ?? 0);
326
+ return portsIn;
327
+ };
328
+ /**
329
+ * Evaluates if the place has (only) the default input
330
+ * @param place place we want to evaluate
331
+ * @returns true if place has (only) the default input
332
+ */
333
+ export const isPlaceWithDefaultInput = (place) => {
334
+ return placeNumberOfInputPorts(place) == 0;
335
+ };
336
+ /**
337
+ * Returns the number output ports in a place
338
+ *
339
+ * **NOTE**: The default output port is not counted
340
+ * @param place place we want to evaluate
341
+ * @returns number if output ports
342
+ */
343
+ export const placeNumberOfOutputPorts = (place) => {
344
+ const portsOut = (place.outputs?.length ?? 0) + (place.inoutputs?.length ?? 0);
345
+ return portsOut;
346
+ };
347
+ /**
348
+ * Evaluates if the place has (only) the default output
349
+ * @param place place we want to evaluate
350
+ * @returns true if place has (only) the default output
351
+ */
352
+ export const isPlaceWithDefaultOutput = (place) => {
353
+ return (place.outputs?.length ?? 0) + (place.inoutputs?.length ?? 0) == 0;
354
+ };
355
+ /** returns (creates if missing) non-serializable counterpart to the task instance and places it into `flowInstanceNS` */
356
+ export const getOrCreatePlaceInstanceNSByPlaceInstanceId = (flowInstanceNS, placeInstanceId, placeType = EFlowPlaceType.TASK) => {
357
+ let placeInstancesNS;
358
+ switch (placeType) {
359
+ case EFlowPlaceType.EVENT:
360
+ placeInstancesNS = flowInstanceNS.eventInstancesNS;
361
+ break;
362
+ default:
363
+ placeInstancesNS = flowInstanceNS.taskInstancesNS;
364
+ break;
365
+ }
366
+ for (const placeInstanceNS of placeInstancesNS) {
367
+ if (placeInstanceNS.id == placeInstanceId)
368
+ return placeInstanceNS;
369
+ }
370
+ const placeInstanceNS = {
371
+ id: placeInstanceId,
372
+ promises: {},
373
+ };
374
+ placeInstancesNS.push(placeInstanceNS);
375
+ return placeInstanceNS;
376
+ };
377
+ /** returns (creates if missing) non-serializable counterpart to the task instance and places it into `flowInstanceNS` */
378
+ export const createTaskInstanceNSByTaskInstanceIdWithoutFlow = (taskInstanceId) => {
379
+ const taskInstanceNS = {
380
+ id: taskInstanceId,
381
+ promises: {},
382
+ };
383
+ return taskInstanceNS;
384
+ };
385
+ /**
386
+ * Merges or expands the number of tokens in a place according to the number of place's output ports. It also sets the output tokens port ids to match the place output port ids
387
+ *
388
+ * TODO: This is currently brutally implemented as there is no any proper management of transformed tokens, their data entry references, etc
389
+ *
390
+ */
391
+ export const transformTokensForPlaceInstanceOnExit = (flowInstanceEngine, flowInstance, place, placeInstance) => {
392
+ let portsIn = placeNumberOfInputPorts(place);
393
+ // counts default input port if no other named ports provided
394
+ if (portsIn == 0)
395
+ portsIn = 1;
396
+ let portsOut = placeNumberOfOutputPorts(place);
397
+ // counts default output port if no other named ports provided
398
+ if (portsOut == 0)
399
+ portsOut = 1;
400
+ const tokens = getTokensInPlaceInstance(flowInstance, placeInstance);
401
+ const outputTokens = [...tokens];
402
+ const outputPorts = placeOutputPorts(place);
403
+ outputTokens.length = portsOut;
404
+ // create missing tokens
405
+ if (portsOut > portsIn) {
406
+ const referralToken = tokens[0];
407
+ for (let i = 0; i < portsIn - portsOut; i++) {
408
+ const newToken = flowInstanceEngine.createTokenInPlace(place, placeInstance);
409
+ // clone `referralToken.dataEntryReferences` into `newToken.dataEntryReferences`
410
+ newToken.dataEntryReferences = referralToken.dataEntryReferences.map((reference) => {
411
+ const newReference = {
412
+ id: reference.id,
413
+ };
414
+ return newReference;
415
+ });
416
+ outputTokens.push(newToken);
417
+ }
418
+ }
419
+ // destroy surplus of tokens
420
+ if (portsOut < portsIn) {
421
+ for (let i = portsOut; i < portsIn; i++) {
422
+ flowInstanceEngine.destroyToken(tokens[i].id);
423
+ }
424
+ }
425
+ // adjust props of the output tokens
426
+ for (let outputTokenIndex = 0; outputTokenIndex < outputTokens.length; outputTokenIndex++) {
427
+ const outputToken = outputTokens[outputTokenIndex];
428
+ if (outputPorts[outputTokenIndex]) {
429
+ const outputPortId = outputPorts[outputTokenIndex].name;
430
+ outputToken.placeInstancePortId = outputPortId;
431
+ }
432
+ else {
433
+ delete outputToken.placeInstancePortId;
434
+ }
435
+ }
436
+ return outputTokens;
437
+ };
438
+ export const setPlaceInstanceExecutionResult = (placeInstanceNS, executionResultPromised) => {
439
+ if (!placeInstanceNS.promises) {
440
+ placeInstanceNS.promises = {};
441
+ }
442
+ placeInstanceNS.promises.executionResultPromise = executionResultPromised;
443
+ };
444
+ /**
445
+ * Store task instance execution output:
446
+ * + in data cache and
447
+ * + the reference to it in
448
+ * + output port tokens
449
+ * + place instance
450
+ * @param flow the flow which we want to search in
451
+ * @param flowInstance the flow instance which we want to search in
452
+ * @param dataCache data cache that contains data entries
453
+ * @param finishedPlaceInstanceNS the flow instance (non serialized) which we want to search in
454
+ * @param tokens the output tokens that should (partially if more than one token (equal to output port)) store store the task execution output
455
+ * @returns hash of caches that stored partial (if more than one token (equal to output port)) task execution outputs
456
+ */
457
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
458
+ export const asyncStorePlaceExecutionOutput = async (flow, flowInstance, dataCache, finishedPlaceInstanceNS, tokens) => {
459
+ const dataTalksCacheEntries = {};
460
+ const finishedPlaceInstance = getPlaceInstanceByPlaceInstanceId(flowInstance, finishedPlaceInstanceNS.id);
461
+ assert(finishedPlaceInstance, `[asyncStorePlaceExecutionOutput] no finishedPlaceInstance for finishedPlaceInstanceNS.id: ${finishedPlaceInstanceNS.id}`);
462
+ const finishedPlace = flowGetPlaceById(flow, finishedPlaceInstance.originId);
463
+ assert(finishedPlace, `[asyncStorePlaceExecutionOutput] no finishedPlace for finishedTaskInstance.originId: ${finishedPlaceInstance.originId}`);
464
+ const placeExecutionResult = await finishedPlaceInstanceNS.promises?.executionResultPromise;
465
+ assert(placeExecutionResult, `[asyncStorePlaceExecutionOutput] placeExecutionResult not available`);
466
+ /** the outcome of the place execution (usually the output of the task executor or input in the start event) */
467
+ const placeExit = placeExecutionResult.rawResult;
468
+ /** we need placeExit to provide it to the output transformation so it can reintegrate it into the place output after extracting just part of the place input that was necessary for the place execution */
469
+ const placeInput = await asyncGetPlaceInput(flow, dataCache, finishedPlace, finishedPlaceInstance);
470
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
471
+ const placeOutput = await asyncTransformPlaceExitToOutputData(finishedPlace, placeExit, placeInput);
472
+ if (placeExecutionResult) {
473
+ // TODO: Understand if this is acceptable, to modify the current execution result or somehow to preserve it, and store somewhere else
474
+ placeExecutionResult.rawResult = placeOutput;
475
+ }
476
+ const createCacheEntry = async (tokenId, placeExecutionResultPartial, portId = EFlowSpecialPortIds.DEFAULT) => {
477
+ const cacheEntry = {
478
+ // It will be set immediately afterwards in the `dataCache.awaitStoreEntry()` method
479
+ id: undefined,
480
+ origin: finishedPlaceInstanceNS.id,
481
+ value: placeExecutionResultPartial,
482
+ };
483
+ const dataTalksCacheEntry = await dataCache.asyncStoreEntry(cacheEntry);
484
+ dataTalksCacheEntries[portId] = dataTalksCacheEntry;
485
+ // TODO: This should be set for a specific exiting token
486
+ setLastDataEntryReferenceForToken(flowInstance, dataTalksCacheEntry, tokenId);
487
+ setPlaceExecutionOutputReferenceInPlaceInstance(flowInstance, dataTalksCacheEntry, finishedPlaceInstance, portId);
488
+ };
489
+ const defaultOutput = isPlaceWithDefaultOutput(finishedPlace);
490
+ // save a single place execution result for single (default) output place
491
+ if (defaultOutput) {
492
+ // there should be only a single token
493
+ const tokenId = tokens[0].id;
494
+ createCacheEntry(tokenId, placeExecutionResult);
495
+ } // save multiple partial place execution results for each output port
496
+ else {
497
+ // get output port ids
498
+ // eslint-disable-next-line prettier/prettier
499
+ const portIds = [
500
+ ...finishedPlace?.outputs ? finishedPlace?.outputs?.map((output) => output.name) : [],
501
+ ...(finishedPlace?.inoutputs ? finishedPlace?.inoutputs?.map((inoutput) => inoutput.name) : [])
502
+ ];
503
+ // save partial place execution result for each port
504
+ for (const portId of portIds) {
505
+ // there should be a token for each port id
506
+ const tokenForPortId = tokens.find((token) => token.placeInstancePortId === portId);
507
+ if (!tokenForPortId) {
508
+ throw new Error(`[asyncStorePlaceExecutionOutput] cannot find token for the output port ${portId}`);
509
+ }
510
+ /** create partial result from whole result */
511
+ const placeExecutionResultPerPort = {
512
+ ...placeExecutionResult,
513
+ // extract the port id related part of the result
514
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
515
+ rawResult: placeExecutionResult.rawResult[portId],
516
+ };
517
+ createCacheEntry(tokenForPortId.id, placeExecutionResultPerPort, portId);
518
+ }
519
+ }
520
+ return dataTalksCacheEntries;
521
+ };
522
+ /**
523
+ * Transforms task's input (all that arrived to the task) into task entrance (data entity that will be provided to the task executor as an input)
524
+ * @param task task which task input we want to transform into task entrance
525
+ * @param taskInput the input of the task we want to transform
526
+ * @returns task entrance
527
+ */
528
+ export const asyncTransformInputDataToTaskEntrance = async (task, taskInput) => {
529
+ if (!taskInput)
530
+ return taskInput;
531
+ assertIsDefined(task.transformations);
532
+ let taskInputTransformed;
533
+ const transformations = task.transformations;
534
+ /**
535
+ * TODO:OPTIMIZATION: we need to identify scenarios where duplicating data is not required
536
+ * + single task using the data
537
+ * + data will be readonly
538
+ * + we do not need to change the structure of data, just take parts of it
539
+ * + we can implement transformations that do not destroy original data
540
+ * + we can support `readonly` input parameters
541
+ */
542
+ if (transformations?.inputTransforms?.length > 0) {
543
+ taskInputTransformed = JSON.parse(JSON.stringify(taskInput));
544
+ const transformation = {
545
+ name: "transformations.inputTransforms",
546
+ description: "Built from `task.transformations.inputTransforms`",
547
+ transforms: transformations.inputTransforms,
548
+ tool: {
549
+ version: "unknown",
550
+ },
551
+ from: {
552
+ version: "unknown",
553
+ },
554
+ to: {
555
+ version: "unknown",
556
+ },
557
+ };
558
+ taskInputTransformed = await asyncExecuteTransformationOnDataObj(taskInputTransformed, transformation);
559
+ }
560
+ else {
561
+ taskInputTransformed = taskInput;
562
+ }
563
+ console.log(`[asyncTransformInputData] taskInputTransformed: ${JSON.stringify(taskInputTransformed)}`);
564
+ return taskInputTransformed;
565
+ };
566
+ /**
567
+ * Transforms task's exit (the outcome/result of the execution of the task's executor) into task output (data entity that will be delivered out through the task output(s))
568
+ * @param place task which task exit we want to transform into task output
569
+ * @param placeExit the exit of the task execution we want to transform
570
+ * @returns task output
571
+ */
572
+ export const asyncTransformPlaceExitToOutputData = async (place, placeExit, placeInput) => {
573
+ if (!placeExit || !place.transformations)
574
+ return placeExit;
575
+ /**
576
+ * TODO:OPTIMIZATION: we need to identify scenarios where duplicating data is not required
577
+ * + single task using the data
578
+ * + data will be readonly
579
+ * + we do not need to change the structure of data, just take parts of it
580
+ * + we can implement transformations that do not destroy original data
581
+ * + we can support `readonly` input parameters
582
+ */
583
+ // it seems we do not need to clone as the original `taskOutput` is not provided to any external actor anyway
584
+ // let taskOutputTransformed = JSON.parse(JSON.stringify(taskOutput));
585
+ let placeOutput = placeExit;
586
+ const transformations = place.transformations;
587
+ if (transformations.outputTransforms.length > 0) {
588
+ const transformation = {
589
+ name: "transformations.inputTransforms",
590
+ description: "Built from `place.transformations.outputTransforms`",
591
+ transforms: transformations.outputTransforms,
592
+ tool: {
593
+ version: "unknown",
594
+ },
595
+ from: {
596
+ version: "unknown",
597
+ },
598
+ to: {
599
+ version: "unknown",
600
+ },
601
+ };
602
+ // TODO: WARNING: NOTE: We CANNOT (CURRENTLY) use `^` to refer to original data entry before the first transform applied (i.e. `taskOutputTransformed`)
603
+ // but when we use `^` it will refer to the `taskInput` provided as 3rd parameter
604
+ // taskOutput = await asyncExecuteTransformationOnDataObj(taskOutput, transformation, taskInput);
605
+ // We swapped `taskOutput` and `taskInput` as this makes transformations healthier and simpler as it is expected
606
+ // So a complex and dirty:
607
+ // outputTransforms: [
608
+ // {
609
+ // name: "Recover `transformations` input port",
610
+ // description: "Recover `transformations` input port",
611
+ // src: "^transformations",
612
+ // dest: "transformations",
613
+ // },
614
+ // {
615
+ // name: "Recover original `dataEntities` (1)",
616
+ // description: "Recover original `dataEntities` input port but under temp name to not destry the task exit data entity which is also with the same name `dataEntities`",
617
+ // src: "^dataEntities",
618
+ // dest: "dataEntities2",
619
+ // },
620
+ // {
621
+ // name: "Bring task exit",
622
+ // description: "Move task exit to its final position `dataEntities/dataEntities`",
623
+ // src: "dataEntities",
624
+ // dest: "dataEntities2/dataEntities",
625
+ // },
626
+ // {
627
+ // name: "Recover original `dataEntities` (2)",
628
+ // description: "Rename the temp name to the final name",
629
+ // src: "dataEntities2",
630
+ // dest: "dataEntities",
631
+ // },
632
+ // ],
633
+ // bacame:
634
+ placeOutput = await asyncExecuteTransformationOnDataObj(placeInput, transformation, placeOutput);
635
+ }
636
+ else {
637
+ // workaround to have taskExit safely passed to taskOutput in the case there is no transformation
638
+ // this is not necessary as already done but just to "highlight" workaround :)
639
+ placeOutput = placeExit;
640
+ }
641
+ console.log(`[asyncTransformOutputData] placeOutputTransformed: ${JSON.stringify(placeOutput)}`);
642
+ return placeOutput;
643
+ };
644
+ /**
645
+ * It **collects** the data content from the tokens arriving to the place instance and
646
+ * **stores** them as the **place instance execution input** in data cache and other references:
647
+ * + in data cache and
648
+ * + the reference to it in
649
+ * + output port tokens
650
+ * + place instance
651
+ *
652
+ * In that way, it makes the place input **available**:
653
+ * + available to the task executor
654
+ * + reference to observers
655
+ * + reference for audit
656
+ * + etc
657
+ *
658
+ * It also **transforms** input data to match specified shape described in `IFlowElement.transformations`
659
+ *
660
+ * Finally it returns the collected and transformed place instance input
661
+ *
662
+ * @param flowInstance the flow instance which we want to search in
663
+ * @param dataCache data cache that contains data entries
664
+ * @param place place which we look the data input for
665
+ * @param placeInstance place instance for which we look the data input for
666
+ * @param placeTokens tokens that enters the place and brings data entries
667
+ * @returns the collected and transformed place instance input
668
+ */
669
+ export const asyncStoreTaskExecutionInput = async (flow, flowInstance, dataCache, place, placeInstance, placeTokens) => {
670
+ await asyncSetExecutionInputReferencesInPlaceInstance(flowInstance, dataCache, place, placeInstance, placeTokens);
671
+ const placeInput = await asyncGetPlaceInput(flow, dataCache, place, placeInstance);
672
+ const placeEntrance = await asyncTransformInputDataToTaskEntrance(place, placeInput);
673
+ return placeEntrance;
674
+ };
675
+ /** Set place execution input references for all ports in the place
676
+ * @param flowInstance the flow instance which we want to search in
677
+ * @param place place which we look the data input for
678
+ * @param placeInstance place instance for which we look the data input for
679
+ * @param placeTokens tokens that enters the place and brings data entries
680
+ */
681
+ export const asyncSetExecutionInputReferencesInPlaceInstance = async (flowInstance, dataCache, place, placeInstance, placeTokens) => {
682
+ const defaultInput = isPlaceWithDefaultInput(place);
683
+ /** creates a blanco cache entry if there is no any data entry on particular port */
684
+ const createBlancoCacheEntry = async (portId) => {
685
+ // if (last) data entry cache doesn't exist (for example the first task in the flow, as events do not generate task outputs and therefore no cache entries neither) we should create an empty one so the place has covered all input ports
686
+ const taskExecutionResult = {
687
+ // nothing executed so not "known"
688
+ place: EExecutorIdPlace.UNKNOWN,
689
+ executionStatus: ETaskExecutionStatus.NOT_EXECUTED,
690
+ rawResult: undefined,
691
+ };
692
+ const cacheEntry = {
693
+ // It will be set immediately afterwards in the `dataCache.awaitStoreEntry()` method
694
+ id: undefined,
695
+ // we can "claim" the origin with this place instance
696
+ origin: placeInstance.id,
697
+ value: taskExecutionResult,
698
+ };
699
+ const dataTalksCacheEntry = await dataCache.asyncStoreEntry(cacheEntry);
700
+ setExecutionInputReferenceInPlaceInstance(flowInstance, dataTalksCacheEntry, placeInstance, portId);
701
+ };
702
+ /** set the default place input */
703
+ if (defaultInput) {
704
+ assert(placeTokens.length == 1, `The taskTokens.length=${placeTokens.length} has to be exactly 1 for a default input port`);
705
+ const placeToken = placeTokens[0];
706
+ console.log(`taskToken: ${JSON.stringify(placeToken)}`);
707
+ // get the data entry reference of the last (previous) task (instance) execution that the token (`taskToken`) encountered on its voyage to this current task (instance) (`task`)
708
+ const lastDataEntryReference = getLastDataEntryReferenceForToken(flowInstance, placeToken.id);
709
+ if (lastDataEntryReference) {
710
+ setExecutionInputReferenceInPlaceInstance(flowInstance, lastDataEntryReference, placeInstance);
711
+ }
712
+ else {
713
+ createBlancoCacheEntry();
714
+ }
715
+ }
716
+ else {
717
+ for (const placeToken of placeTokens) {
718
+ console.log(`taskToken: ${JSON.stringify(placeToken)}`);
719
+ // get the data entry reference of the last (previous) task (instance) execution that the token (`taskToken`) encountered on its voyage to this current task (instance) (`task`)
720
+ const lastDataEntryReference = getLastDataEntryReferenceForToken(flowInstance, placeToken.id);
721
+ // the port id which the token entered into the task
722
+ const portId = placeToken.placeInstancePortId;
723
+ /** set the portId property of the task input */
724
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
725
+ if (lastDataEntryReference) {
726
+ setExecutionInputReferenceInPlaceInstance(flowInstance, lastDataEntryReference, placeInstance, portId);
727
+ }
728
+ else {
729
+ createBlancoCacheEntry(portId);
730
+ }
731
+ }
732
+ }
733
+ };
734
+ /**
735
+ * Returns execution input for a place instance (`IPlaceExecutionResult`(s) not `IPlaceExecutionResult.rawResult`(s))
736
+ *
737
+ * It collects all partial input references (from `executionInputReferences`) into a single hash raw of `IPlaceExecutionResult`(s) mapped through port ids
738
+ * @param dataCache data cache that contains data entries
739
+ * @param placeInstance the place instance which execution input we want to retrieve
740
+ * @returns execution input of the place instance
741
+ */
742
+ export const asyncGetPlaceExecutionInput = async (dataCache, placeInstance) => {
743
+ const placeExecutionInput = {};
744
+ console.log(`[asyncGetPlaceExecutionInput] placeInstance.executionInputReferences keys: ${Object.keys(placeInstance.executionInputReferences)}`);
745
+ for (const portId in placeInstance.executionInputReferences) {
746
+ const dataEntryReference = placeInstance.executionInputReferences[portId];
747
+ // TODO: figure out in future if this is acceptable
748
+ if (!dataEntryReference) {
749
+ throw new Error(`[asyncGetPlaceExecutionInput] dataEntryReference is missing for placeInstance.executionInputReferences[portId="${portId}"]`);
750
+ }
751
+ const dataEntryCache = await dataCache.asyncRetrieveEntryById(dataEntryReference.id);
752
+ placeExecutionInput[portId] = dataEntryCache?.value;
753
+ }
754
+ return placeExecutionInput;
755
+ };
756
+ /**
757
+ * Returns place input for a place instance (`IPlaceExecutionResult.rawResult`(s) not `IPlaceExecutionResult`(s))
758
+ *
759
+ * It collects all partial input references (from `executionInputReferences`) into a single data entity where port's sub-data entities are mapped through port ids
760
+ * @param dataCache data cache that contains data entries
761
+ * @param placeInstance the place instance which input we want to retrieve
762
+ * @returns the input of the place instance
763
+ */
764
+ export const asyncGetPlaceInput = async (flow, dataCache, place, placeInstance) => {
765
+ let placeInput;
766
+ const defaultInput = isPlaceWithDefaultInput(place);
767
+ // there is no any input port (this is the case for the start event)
768
+ if (flowGetSequencesIngoingToPlace(flow, place.id).length <= 0) {
769
+ console.log(`${place.id} has no input ports`);
770
+ return undefined;
771
+ }
772
+ console.log(`[asyncGetPlaceExecutionInput] placeInstance.executionInputReferences keys: ${Object.keys(placeInstance.executionInputReferences)}`);
773
+ /** set the default place input */
774
+ if (defaultInput) {
775
+ const portId = EFlowSpecialPortIds.DEFAULT;
776
+ const dataEntryReference = placeInstance.executionInputReferences[portId];
777
+ // TODO: figure out in future if this is acceptable
778
+ if (!dataEntryReference) {
779
+ throw new Error(`[asyncGetPlaceExecutionInput] dataEntryReference is missing for [placeInstance.id="${placeInstance.id}", placeInstance.executionInputReferences[portId="${portId}"]`);
780
+ }
781
+ const dataEntryCache = await dataCache.asyncRetrieveEntryById(dataEntryReference.id);
782
+ const executionResult = dataEntryCache?.value;
783
+ placeInput = executionResult.rawResult;
784
+ }
785
+ else {
786
+ placeInput = {};
787
+ for (const portId in placeInstance.executionInputReferences) {
788
+ const dataEntryReference = placeInstance.executionInputReferences[portId];
789
+ // TODO: figure out in future if this is acceptable
790
+ if (!dataEntryReference) {
791
+ throw new Error(`[asyncGetPlaceExecutionInput] dataEntryReference is missing for placeInstance.executionInputReferences[portId="${portId}"]`);
792
+ }
793
+ const dataEntryCache = await dataCache.asyncRetrieveEntryById(dataEntryReference.id);
794
+ const executionResult = dataEntryCache?.value;
795
+ placeInput[portId] = executionResult.rawResult;
796
+ }
797
+ }
798
+ return placeInput;
799
+ };
800
+ /**
801
+ * Returns execution output for a place instance (`IPlaceExecutionResult`(s) not `IPlaceExecutionResult.rawResult`(s))
802
+ *
803
+ * It collects all partial output references (from `executionInputReferences`) into a single hash raw of `IPlaceExecutionResult`(s) mapped through port ids
804
+ * @param dataCache data cache that contains data entries
805
+ * @param placeInstance the place instance which execution output we want to retrieve
806
+ * @returns execution output of the place instance
807
+ */
808
+ export const asyncGetPlaceExecutionOutput = async (flowInstance, dataCache, placeInstanceId) => {
809
+ const placeExecutionOutput = {};
810
+ const placeInstance = getPlaceInstanceByPlaceInstanceId(flowInstance, placeInstanceId);
811
+ if (!placeInstance) {
812
+ throw new Error(`[asyncSetLastTaskExecutionOutputForToken] no taskInstance for taskInstanceId: ${placeInstanceId}`);
813
+ }
814
+ for (const portId in placeInstance.executionOutputReferences) {
815
+ const dataEntryReference = placeInstance.executionOutputReferences[portId];
816
+ // TODO: figure out in future if this is acceptable
817
+ if (!dataEntryReference)
818
+ continue;
819
+ const lastDataEntry = await dataCache.asyncRetrieveEntryById(dataEntryReference.id);
820
+ placeExecutionOutput[portId] = lastDataEntry?.value;
821
+ }
822
+ return placeExecutionOutput;
823
+ };
824
+ /**
825
+ * Sets the reference to the execution input (cache entry) into particular "slot" of the `placeInstance.executionInputReferences`
826
+ *
827
+ * This function should be invited once for each port of a multi-input-port place
828
+ */
829
+ export const setExecutionInputReferenceInPlaceInstance = async (flowInstance, dataTalksCacheEntryReference, placeInstance, portId = EFlowSpecialPortIds.DEFAULT) => {
830
+ const dataEntryReference = {
831
+ id: dataTalksCacheEntryReference.id,
832
+ };
833
+ // set place instance execution input reference to placeInstance
834
+ placeInstance.executionInputReferences[portId] = dataEntryReference;
835
+ return dataEntryReference;
836
+ };
837
+ /**
838
+ * Sets the reference to the execution output (cache entry) into particular "slot" of the `placeInstance.executionOutputReferences`
839
+ *
840
+ * This function should be invited once for each port of a multi-output-port place
841
+ */
842
+ export const setPlaceExecutionOutputReferenceInPlaceInstance = async (flowInstance, dataTalksCacheEntry, placeInstance, portId = EFlowSpecialPortIds.DEFAULT) => {
843
+ const dataEntryReference = {
844
+ id: dataTalksCacheEntry.id,
845
+ };
846
+ // set data entry reference to taskInstance
847
+ placeInstance.executionOutputReferences[portId] = dataEntryReference;
848
+ return dataEntryReference;
849
+ };
850
+ /**
851
+ * Gets the reference (`IDataTalksCacheEntryReference`) to the execution output (result) of the last encountered place instance on the token's travel
852
+ * @param flowInstance the flow instance which we want to search in
853
+ * @param tokenId the token which data entry we are interested in
854
+ * @returns
855
+ */
856
+ export const getLastDataEntryReferenceForToken = (flowInstance, tokenId) => {
857
+ const token = getTokenById(flowInstance, tokenId);
858
+ if (!token) {
859
+ throw new Error(`[asyncGetLastTaskExecutionOutputForToken] no token for tokenId: ${tokenId}`);
860
+ }
861
+ if (token.dataEntryReferences.length <= 0)
862
+ return undefined;
863
+ const lastDataEntryReference = token.dataEntryReferences[token.dataEntryReferences.length - 1];
864
+ return lastDataEntryReference;
865
+ };
866
+ /**
867
+ * Get the execution (`IPlaceExecutionResult`) output of the last place instance encountered by the token
868
+ * @param flowInstance the flow instance which we want to search in
869
+ * @param dataTalksCacheEntry the cache entry which reference we want to set to the token
870
+ * @param tokenId the token we want to get the last execution for
871
+ * @returns the task instance execution output
872
+ */
873
+ export const setLastDataEntryReferenceForToken = (flowInstance, dataTalksCacheEntry, tokenId) => {
874
+ const token = getTokenById(flowInstance, tokenId);
875
+ const dataEntryReference = {
876
+ id: dataTalksCacheEntry.id,
877
+ };
878
+ if (!token) {
879
+ throw new Error(`[asyncSetLastTaskExecutionOutputForToken] no token for tokenId: ${tokenId}`);
880
+ }
881
+ token.dataEntryReferences.push(dataEntryReference);
882
+ return dataEntryReference;
883
+ };
884
+ /**
885
+ * Get the execution (`IPlaceExecutionResult`) output of the last place instance encountered by the token
886
+ * @param flowInstance the flow instance which we want to search in
887
+ * @param dataCache data cache that contains data entries
888
+ * @param tokenId the token we want to get the last execution for
889
+ * @returns the task instance execution output
890
+ */
891
+ export const asyncGetLastPlaceExecutionOutputForToken = async (flowInstance, dataCache, tokenId) => {
892
+ const lastDataEntryReference = getLastDataEntryReferenceForToken(flowInstance, tokenId);
893
+ if (!lastDataEntryReference)
894
+ return undefined;
895
+ const lastDataEntry = await dataCache.asyncRetrieveEntryById(lastDataEntryReference.id);
896
+ return lastDataEntry?.value;
897
+ };
898
+ /** All token statuses in place instances that can be recognized as actively running tokens in particular place instance (like the originating token didn't leave the place instance or it is not about to leave it) */
899
+ const ACTIVE_TOKEN_STATUSES_IN_PLACE_INSTANCES = [ETokenStatusInFlowPlaceInstance.JUST_ENTERED, ETokenStatusInFlowPlaceInstance.INITIATED, ETokenStatusInFlowPlaceInstance.RUNNING];
900
+ /** get all place instances that are active; places instances that have tokens in them which are in an active status in regard to the place instance (like the originating token didn't leave the place instance or it is not about to leave it)
901
+ * @param flowInstance the flow instance which we want to search in
902
+ * @returns active place instances
903
+ * TODO: TEST
904
+ */
905
+ export const getActivePlaceInstances = (flowInstance) => {
906
+ const placesInstances = [];
907
+ for (const taskInstance of flowInstance.taskInstances) {
908
+ if (ACTIVE_TOKEN_STATUSES_IN_PLACE_INSTANCES.indexOf(taskInstance.tokenStatus) >= 0) {
909
+ placesInstances.push(taskInstance);
910
+ }
911
+ }
912
+ for (const eventInstance of flowInstance.eventInstances) {
913
+ if (ACTIVE_TOKEN_STATUSES_IN_PLACE_INSTANCES.indexOf(eventInstance.tokenStatus) >= 0) {
914
+ placesInstances.push(eventInstance);
915
+ }
916
+ }
917
+ for (const gatewayInstance of flowInstance.gatewayInstances) {
918
+ if (ACTIVE_TOKEN_STATUSES_IN_PLACE_INSTANCES.indexOf(gatewayInstance.tokenStatus) >= 0) {
919
+ placesInstances.push(gatewayInstance);
920
+ }
921
+ }
922
+ return placesInstances;
923
+ };
924
+ /** get all place instances that confirm with: (1) have initiated tokens in them in the required status (like the initiated token didn't leave the place instance or it is not about to leave it) (2) are of a specific place type
925
+ * @param flowInstance the flow instance which we want to search in
926
+ * @param TOKEN_STATUSES_IN_PLACE_INSTANCES token statuses that we are interested for
927
+ * @param type of places where the tokens of interest should be located at
928
+ * @returns matched tokens
929
+ */
930
+ export const getTokensByPlaceTypeAndTokenStatus = (flowInstance, TOKEN_STATUSES_IN_PLACE_INSTANCES, type) => {
931
+ const matchingTokens = [];
932
+ const tokens = flowInstance.tokens;
933
+ for (const token of tokens) {
934
+ const placeInstance = getPlaceInstanceByPlaceInstanceId(flowInstance, token.placeInstanceId);
935
+ if (!placeInstance)
936
+ continue;
937
+ if (TOKEN_STATUSES_IN_PLACE_INSTANCES.indexOf(placeInstance.tokenStatus) >= 0 && placeInstance.placeType == type) {
938
+ matchingTokens.push(token);
939
+ }
940
+ }
941
+ return matchingTokens;
942
+ };
943
+ export const asyncBreakOnBreakingPlaces = async (flow, flowInstance, flowInstanceNS, placeInstancesIds) => {
944
+ for (const placeInstanceId of placeInstancesIds) {
945
+ const placeInstance = getPlaceInstanceByPlaceInstanceId(flowInstance, placeInstanceId);
946
+ if (!placeInstance) {
947
+ throw new Error(`[asyncBreakOnBreakingTasks] placeInstance doesn't exist for placeInstanceId: ${placeInstanceId}`);
948
+ }
949
+ const place = flowGetPlaceById(flow, placeInstance.originId);
950
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
951
+ if (place?.extension?.debug?.breakpoint) {
952
+ // TODO
953
+ // window.alert(`Breakpoint reached on place (id: "${place?.id}")`);
954
+ semaphoreSetBlocking(flowInstanceNS.executionSemaphores.semaphores[ESemaphoreNames.BREAKPOINT]);
955
+ if (flowInstance.executionResult)
956
+ flowInstance.executionResult.executionStatus = EFlowExecutionStatus.INTERRUPTED;
957
+ await asyncSemaphoreWaitOnResource(flowInstanceNS.executionSemaphores.semaphores[ESemaphoreNames.BREAKPOINT], `Breakpoint reached on place (id: "${place?.id}")`);
958
+ return place;
959
+ }
960
+ }
961
+ return undefined;
962
+ };
963
+ /** Get all place instances that are ready to execute, meaning that they have all (required) input ports covered with tokens in proper states
964
+ * @param flow the flow which we want to search in
965
+ * @param flowInstance the flow instance which we want to search in
966
+ * @returns matched place instances
967
+ */
968
+ export const getPlaceInstancesThatAreReadyToExecute = (flow, flowInstance, placeType) => {
969
+ /** the list of place instances that have all (required) input ports covered with tokens */
970
+ const matchingPlaceInstances = [];
971
+ const tokensInNewlyEnteredTasks = getTokensByPlaceTypeAndTokenStatus(flowInstance, [ETokenStatusInFlowPlaceInstance.JUST_ENTERED], placeType);
972
+ const placeInstancesSatisfied = {};
973
+ for (const token of tokensInNewlyEnteredTasks) {
974
+ const placeInstance = getPlaceInstanceByPlaceInstanceId(flowInstance, token.placeInstanceId);
975
+ if (!placeInstance)
976
+ continue;
977
+ // process only if not processed already
978
+ if (!(placeInstance.id in placeInstancesSatisfied)) {
979
+ const place = flowGetPlaceById(flow, token.placeId);
980
+ if (!place)
981
+ continue;
982
+ /** satisfied if all place inputs are covered in the place instance with tokens */
983
+ let inputsSatisfied = true;
984
+ if (place.inputs) {
985
+ inputsSatisfied =
986
+ inputsSatisfied &&
987
+ place.inputs.reduce((satisfied, input) => {
988
+ return satisfied && !!placeInstance.initiatedTokenIdsPerPorts[input.name];
989
+ }, true);
990
+ }
991
+ /** satisfied if all place inoutputs are covered in the place instance with tokens */
992
+ let inoutputsSatisfied = true;
993
+ if (place.inoutputs) {
994
+ inoutputsSatisfied =
995
+ inoutputsSatisfied &&
996
+ place.inoutputs.reduce((satisfied, inoutput) => {
997
+ return satisfied && !!placeInstance.initiatedTokenIdsPerPorts[inoutput.name];
998
+ }, true);
999
+ }
1000
+ const placeSatisfied = inputsSatisfied && inoutputsSatisfied;
1001
+ placeInstancesSatisfied[placeInstance.id] = placeSatisfied;
1002
+ if (placeSatisfied) {
1003
+ matchingPlaceInstances.push(placeInstance.id);
1004
+ }
1005
+ }
1006
+ }
1007
+ return matchingPlaceInstances;
1008
+ };
1009
+ /** Get all place instances that finished execution, meaning that they have provided all the data results for the output ports
1010
+ * @param flow the flow which we want to search in
1011
+ * @param flowInstance the flow instance which we want to search in
1012
+ * @returns matched place instances
1013
+ */
1014
+ export const getPlaceInstancesThatFinishedExecution = (flow, flowInstance, placeType) => {
1015
+ /** the list of place instances that have all (required) output ports covered with data results */
1016
+ const matchingPlaceInstances = [];
1017
+ /** we could go directly through task, but we assume that it is
1018
+ * 1. more optimal as there might be large number of tasks, and only few of them are currently visited with tokens (though the number of token instances is usually similar to number of tokens)
1019
+ * 2. healthier for future algorithms (?!) It could be also opposite as discussed in [token vs. task centric execution](./colabo/src/isomorphic/dev_puzzles/flow/core/lib/execution/README.md#token-vs.-task-centric-execution)
1020
+ */
1021
+ const tokensInNewlyFinishedTasks = getTokensByPlaceTypeAndTokenStatus(flowInstance, [ETokenStatusInFlowPlaceInstance.FINISHED], placeType);
1022
+ const placeInstancesSatisfied = {};
1023
+ for (const token of tokensInNewlyFinishedTasks) {
1024
+ const placeInstance = getPlaceInstanceByPlaceInstanceId(flowInstance, token.placeInstanceId);
1025
+ if (!placeInstance)
1026
+ continue;
1027
+ // process only if not processed already
1028
+ if (!(placeInstance.id in placeInstancesSatisfied)) {
1029
+ // currently there no any other condition to evaluate satisfaction
1030
+ const placeSatisfied = true;
1031
+ placeInstancesSatisfied[placeInstance.id] = placeSatisfied;
1032
+ if (placeSatisfied) {
1033
+ matchingPlaceInstances.push(placeInstance.id);
1034
+ }
1035
+ }
1036
+ }
1037
+ return matchingPlaceInstances;
1038
+ };
1039
+ /**
1040
+ * Returns all references to tokens in provided place instance
1041
+ *
1042
+ * @param flowInstance the flow instance which we want to search in
1043
+ * @param placeInstance the place instance which tokens we want to get
1044
+ * @returns array of the token references in the place instance
1045
+ */
1046
+ export const getTokensInPlaceInstance = (flowInstance, placeInstance) => {
1047
+ const tokens = Object.keys(placeInstance.initiatedTokenIdsPerPorts).map((portId) => {
1048
+ const tokenId = placeInstance.initiatedTokenIdsPerPorts[portId];
1049
+ const token = getTokenById(flowInstance, tokenId);
1050
+ if (!token)
1051
+ throw new Error(`[getTokensInPlaceInstance] cannot find matching token for tokenId: "${tokenId}"`);
1052
+ return token;
1053
+ });
1054
+ return tokens;
1055
+ };
1056
+ /** get all place instances that confirm with: (1) have initiated tokens in them in the required status (like the initiated token didn't leave the place instance or it is not about to leave it) (2) are of a specific place type
1057
+ * @param flowInstance the flow instance which we want to search in
1058
+ * @returns active place instances
1059
+ * TODO: TEST
1060
+ */
1061
+ export const getPlaceInstancesByTypeAndTokenStatus = (flowInstance, TOKEN_STATUSES_IN_PLACE_INSTANCES, type) => {
1062
+ const placesInstances = [];
1063
+ if (type === EFlowPlaceType.TASK) {
1064
+ for (const taskInstance of flowInstance.taskInstances) {
1065
+ if (TOKEN_STATUSES_IN_PLACE_INSTANCES.indexOf(taskInstance.tokenStatus) >= 0) {
1066
+ placesInstances.push(taskInstance);
1067
+ }
1068
+ }
1069
+ }
1070
+ if (type === EFlowPlaceType.EVENT) {
1071
+ for (const eventInstance of flowInstance.eventInstances) {
1072
+ if (TOKEN_STATUSES_IN_PLACE_INSTANCES.indexOf(eventInstance.tokenStatus) >= 0) {
1073
+ placesInstances.push(eventInstance);
1074
+ }
1075
+ }
1076
+ }
1077
+ if (type === EFlowPlaceType.GATEWAY) {
1078
+ for (const gatewayInstance of flowInstance.gatewayInstances) {
1079
+ if (TOKEN_STATUSES_IN_PLACE_INSTANCES.indexOf(gatewayInstance.tokenStatus) >= 0) {
1080
+ placesInstances.push(gatewayInstance);
1081
+ }
1082
+ }
1083
+ }
1084
+ return placesInstances;
1085
+ };
1086
+ /**
1087
+ * Checks if the provided status is finished or failed
1088
+ * @param status status we want to evaluate
1089
+ * @returns returns `true` if the status is finished or failed
1090
+ */
1091
+ export const isTaskStatusFinishedOrFailed = (status) => {
1092
+ const result = [EFlowTaskExecutionStatus.FINISHED, EFlowTaskExecutionStatus.FAILED_SYSTEM, EFlowTaskExecutionStatus.FAILED_ENGINE, EFlowTaskExecutionStatus.FAILED_FLOW, EFlowTaskExecutionStatus.FAILED_TASK, EFlowTaskExecutionStatus.FAILED_USER].indexOf(status) >= 0;
1093
+ return result;
1094
+ };
1095
+ export class FlowInstanceEngine {
1096
+ flow;
1097
+ flowInstance;
1098
+ flowInstanceNS;
1099
+ constructor(flow) {
1100
+ this.flow = flow;
1101
+ // it will create a first token(s?) in start events to promote initial start of the flow
1102
+ this.flowInstance = createFlowInstanceForFlow(flow);
1103
+ this.flowInstanceNS = createFlowInstanceNSForFlow(flow, this.flowInstance);
1104
+ }
1105
+ get id() {
1106
+ return this.flowInstance.id;
1107
+ }
1108
+ async asyncGetFlowInstance() {
1109
+ return this.flowInstance;
1110
+ }
1111
+ async asyncGetFlowInstanceNS() {
1112
+ return this.flowInstanceNS;
1113
+ }
1114
+ async asyncGetFlow() {
1115
+ return this.flow;
1116
+ }
1117
+ /** Returns all tokens from the running flow instance
1118
+ */
1119
+ getTokens() {
1120
+ return this.flowInstance.tokens;
1121
+ }
1122
+ /**
1123
+ * Creates a new token in a place and potentially a new place instance (if not already provided)
1124
+ * @param place place in which token should be created
1125
+ * @param placeInstance place instance where token should be created. If not provided, a **new** place instance will be created
1126
+ * @returns newly created token
1127
+ */
1128
+ createTokenInPlace(place, placeInstance) {
1129
+ const placeId = place?.id;
1130
+ if (placeId) {
1131
+ const token = {
1132
+ id: `${placeId}:${uuidv1()}`,
1133
+ placeId: placeId,
1134
+ placeInstanceId: placeInstance?.id,
1135
+ dataEntryReferences: [],
1136
+ };
1137
+ if (!placeInstance) {
1138
+ const placeInstanceNew = createPlaceInstanceForPlace(place, token, this.flowInstance);
1139
+ placeInstance = placeInstanceNew;
1140
+ }
1141
+ token.placeInstanceId = placeInstance.id;
1142
+ placeInstance.currentTokenIds.push(token.id);
1143
+ this.flowInstance.tokens.push(token);
1144
+ return token;
1145
+ }
1146
+ else {
1147
+ throw new Error(`[createPlaceInstanceForPlace] place?.id is not defined`);
1148
+ }
1149
+ }
1150
+ cloneToken(token, idSuffix) {
1151
+ const newToken = {
1152
+ ...token,
1153
+ id: `${token.id}:cloned:${idSuffix}`,
1154
+ dataEntryReferences: [...token.dataEntryReferences],
1155
+ };
1156
+ if (this.flowInstance.tokens.find((t) => t.id === newToken.id)) {
1157
+ throw new Error(`[cloneToken] newToken.id=${newToken.id} already exists in this.flowInstance.tokens`);
1158
+ }
1159
+ this.flowInstance.tokens.push(newToken);
1160
+ const placeInstance = getPlaceInstanceByPlaceInstanceId(this.flowInstance, token.placeInstanceId);
1161
+ if (!placeInstance) {
1162
+ throw new Error(`[cloneToken] couldn't find placeInstance for token.placeId: ${token.placeInstanceId}`);
1163
+ }
1164
+ placeInstance.currentTokenIds.push(newToken.id);
1165
+ return newToken;
1166
+ }
1167
+ /** Destroy a token
1168
+ * @param tokenId id if the token that should be removed
1169
+ */
1170
+ destroyToken(tokenId) {
1171
+ /** position of token in the flow instance */
1172
+ const tokenPositionFlow = this.flowInstance.tokens.findIndex((token) => token.id === tokenId);
1173
+ const token = this.flowInstance.tokens[tokenPositionFlow];
1174
+ this.flowInstance.tokens.splice(tokenPositionFlow, 1);
1175
+ const placeInstance = getPlaceInstanceByPlaceInstanceId(this.flowInstance, token.placeInstanceId);
1176
+ if (!placeInstance) {
1177
+ throw new Error(`[destroyToken] couldn't find placeInstance for token.placeId: ${token.placeInstanceId}`);
1178
+ }
1179
+ /** position of token in the place instance */
1180
+ const tokenPositionPlace = placeInstance.currentTokenIds.findIndex((tokenIdCompare) => tokenIdCompare === tokenId);
1181
+ placeInstance.currentTokenIds.splice(tokenPositionPlace, 1);
1182
+ }
1183
+ /** It starts the flow and updates the flow instance
1184
+ * It adds a single (?) token at the starting event(s?)
1185
+ * TODO: Check about plurality of the start
1186
+ * @param flowInput that the flow should start execution with. It is injected in the start event and token that is created at it
1187
+ */
1188
+ async awaitStart(flowInput, dataCache) {
1189
+ // get event
1190
+ const eventStart = flowGetPlaces(this.flow, EFlowEventType.START)?.[0];
1191
+ // create token
1192
+ const token = this.createTokenInPlace(eventStart);
1193
+ // get event instance
1194
+ const eventStartInstance = getPlaceInstanceByPlaceInstanceId(this.flowInstance, token.placeInstanceId);
1195
+ assert(eventStartInstance, `[awaitStart] eventStartInstance should be created in createTokenInPlace`);
1196
+ // get event instance NS
1197
+ const eventInstanceNS = getOrCreatePlaceInstanceNSByPlaceInstanceId(this.flowInstanceNS, eventStartInstance.id, EFlowPlaceType.EVENT);
1198
+ /**
1199
+ * Create the event output as if it was a task that was executed
1200
+ *
1201
+ * In such a way we can let the successor tasks to retrieve its output but also to see the output properly on the flow overview
1202
+ * --------------------------
1203
+ */
1204
+ // create event instance execution result
1205
+ const executionResult = {
1206
+ // executed as we wil immediately resolve the result
1207
+ executionStatus: ETaskExecutionStatus.EXECUTED,
1208
+ // TODO: check if we need to do it more properly
1209
+ place: EExecutorIdPlace.LOCAL_TIER,
1210
+ rawResult: flowInput,
1211
+ };
1212
+ // promise the result (already resolved)
1213
+ const executionResultPromised = Promise.resolve(executionResult);
1214
+ // set the event's execution result
1215
+ setPlaceInstanceExecutionResult(eventInstanceNS, executionResultPromised);
1216
+ eventStartInstance;
1217
+ // set event execution output
1218
+ asyncStorePlaceExecutionOutput(this.flow, this.flowInstance, dataCache, eventInstanceNS, [token]);
1219
+ return token;
1220
+ }
1221
+ /** Updates task identified by where the token is placed */
1222
+ updateTaskInstanceByToken(flowInstanceEngine, token, taskStatus, tokenStatus) {
1223
+ const task = flowGetTaskById(this.flow, token.placeId);
1224
+ if (!task) {
1225
+ throw new Error(`[updateTaskInstanceByToken] task not retrieved for token.placeId: ${token.placeId}`);
1226
+ }
1227
+ const taskInstance = getTaskInstanceByTaskInstanceId(this.flowInstance, task.id);
1228
+ if (!taskInstance) {
1229
+ throw new Error(`[updateTaskInstanceByToken] taskInstance not retrieved for task.id: ${task.id}`);
1230
+ }
1231
+ taskInstance.status = taskStatus;
1232
+ if (tokenStatus) {
1233
+ taskInstance.tokenStatus = tokenStatus;
1234
+ }
1235
+ if (isTaskStatusFinishedOrFailed(taskStatus)) {
1236
+ this.progressTokenToNextPlace(token);
1237
+ }
1238
+ }
1239
+ /**
1240
+ * Progress all tokens further on if their corresponding task instances finished execution
1241
+ * TODO: This is much more complex than presented here, for example
1242
+ * + we do not handle tasks that failed
1243
+ * + we handle only start event
1244
+ * + we do not handle gateways
1245
+ * + we need to understand how about parallel gateways and multiplying tokens
1246
+ * + we need to understand how about conditional gateways, interpreting and retrieving required values and conditions
1247
+ */
1248
+ async asyncProgressTokensThatAreFinished() {
1249
+ let progressedTokens = [];
1250
+ for (const token of this.flowInstance.tokens) {
1251
+ console.log(`[asyncProgressTokensThatAreFinished] token: ${JSON.stringify(token)}`);
1252
+ const tokenCurrentPlaceInstance = getPlaceInstanceByPlaceInstanceId(this.flowInstance, token.placeInstanceId);
1253
+ if (!tokenCurrentPlaceInstance) {
1254
+ throw new Error(`[asyncProgressTokensThatAreFinished] tokenCurrentPlaceInstance missing for the token.placeInstanceId: ${token.placeInstanceId}`);
1255
+ }
1256
+ // progress task
1257
+ console.log(`[asyncProgressTokensThatAreFinished] tokenCurrentPlaceInstance: ${JSON.stringify(tokenCurrentPlaceInstance)}`);
1258
+ if (tokenCurrentPlaceInstance.placeType == EFlowPlaceType.TASK) {
1259
+ if (tokenCurrentPlaceInstance.tokenStatus === ETokenStatusInFlowPlaceInstance.RESULTS_STORED) {
1260
+ progressedTokens = [...progressedTokens, ...this.progressTokenToNextPlace(token)];
1261
+ }
1262
+ // TBD: Other task statuses
1263
+ }
1264
+ const currentPlaceForToken = flowGetPlaceById(this.flow, token.placeId);
1265
+ // progress event
1266
+ if (tokenCurrentPlaceInstance.placeType == EFlowPlaceType.EVENT) {
1267
+ if (currentPlaceForToken.type === EFlowEventType.START && tokenCurrentPlaceInstance.tokenStatus === ETokenStatusInFlowPlaceInstance.JUST_ENTERED) {
1268
+ progressedTokens = [...progressedTokens, ...this.progressTokenToNextPlace(token)];
1269
+ }
1270
+ // other types of events
1271
+ // TBD
1272
+ }
1273
+ // progress gateway
1274
+ // TBD
1275
+ }
1276
+ return progressedTokens;
1277
+ }
1278
+ /** Progress the token to the next place
1279
+ * TODO: There is a serious decision on when and how the token should be split/multiplied merged/reduced in the matter of increased concurrency (parallel gateways, etc (?))
1280
+ * [Token life-cycle](colabo/src/isomorphic/dev_puzzles/flow/core/lib/execution/README.md#Token life-cycle)
1281
+ * @param token token that should be progressed
1282
+ *
1283
+ * **NOTE**: the `token.placeInstancePortId` should be set to output port of a place before calling this function, and in the case of the `asyncExecuteFlow()` function (algorithm) it is set with the `transformTokensForPlaceInstanceOnExit()` function before calling this function.
1284
+ /**
1285
+ * Params flow instance engine
1286
+ * @param token
1287
+ * @returns token to next place
1288
+ */
1289
+ progressTokenToNextPlace(token) {
1290
+ const tokensProgressed = [];
1291
+ /** the place instance where the token is currently placed */
1292
+ const tokenCurrentPlaceInstance = getPlaceInstanceByPlaceInstanceId(this.flowInstance, token.placeInstanceId);
1293
+ if (!tokenCurrentPlaceInstance) {
1294
+ throw new Error(`[progressTokenToNextPlace] tokenCurrentPlaceInstance missing for the token.placeInstanceId: ${token.placeInstanceId}`);
1295
+ }
1296
+ /** the current place and port id outgoing sequences
1297
+ *
1298
+ * **NOTE**: the `token.placeInstancePortId` should be set to output port of a place before calling this function, and in the case of the `asyncExecuteFlow()` function (algorithm) it is set with the `transformTokensForPlaceInstanceOnExit()` function before calling this function.
1299
+ */
1300
+ const sequencesToNextPlace = flowGetSequencesOutgoingFromPlace(this.flow, token.placeId, token.placeInstancePortId);
1301
+ /** If there is a way to next places from the current token place */
1302
+ if (sequencesToNextPlace.length > 0) {
1303
+ // update current place instance
1304
+ tokenCurrentPlaceInstance.tokenStatus = ETokenStatusInFlowPlaceInstance.LEAVING;
1305
+ const downSequenceTokens = [];
1306
+ // clone tokens
1307
+ // NOTE: If we clone them in the main (2nd, next) loop we will end up cloning the changed original token
1308
+ // which already led us to uncomfortable bug
1309
+ for (let sequenceId = 0; sequenceId < sequencesToNextPlace.length; sequenceId++) {
1310
+ /** get or clone token for the current sequence
1311
+ * --------------------------
1312
+ * for any, except the first sequence, we CLONE send a new token down
1313
+ * TODO: understand more on token life-cycle
1314
+ * [Token life-cycle](colabo/src/isomorphic/dev_puzzles/flow/core/lib/execution/README.md#Token life-cycle)
1315
+ * */
1316
+ if (sequenceId == 0) {
1317
+ downSequenceTokens.push(token);
1318
+ }
1319
+ else {
1320
+ downSequenceTokens.push(this.cloneToken(token, sequenceId.toString()));
1321
+ }
1322
+ }
1323
+ /** Progress down all the outgoing sequences (there is no conditioning at the moment).
1324
+ * --------------------------
1325
+ * For each (except the 1st) sequence we create a (or rather clone from the original one) new token
1326
+ * We also create task instances for the all the tasks reached by tokens (unless they are already instantiated and possible to accept new token)
1327
+ * We also update place's in regard of the `tokenStatus` and `currentTokenIds` */
1328
+ for (let sequenceId = 0; sequenceId < sequencesToNextPlace.length; sequenceId++) {
1329
+ const sequenceToNextPlace = sequencesToNextPlace[sequenceId];
1330
+ const downSequenceToken = downSequenceTokens[sequenceId];
1331
+ // put the token into the progressed tokens report list
1332
+ // TODO: consider should we condition this due to the code further down that might NOT progress the token (like `if (!nextPlace)`, etc)
1333
+ tokensProgressed.push(downSequenceToken);
1334
+ /** get the next place for token to departure to
1335
+ * --------------------------
1336
+ * get the place
1337
+ * get or create new instance
1338
+ * */
1339
+ const nextPlace = flowGetPlaceById(this.flow, sequenceToNextPlace.targetId);
1340
+ if (!nextPlace) {
1341
+ throw new Error(`[progressTokenToNextPlace] nextPlace missing for the sequenceToNextPlace.targetId: ${sequenceToNextPlace.targetId}`);
1342
+ }
1343
+ /** Create a **new instance** of the next place for token to departure to
1344
+ * --------------------------
1345
+ * We support **multi-input-ports** places where
1346
+ * + the first token arriving **creates** a new instance
1347
+ * + later tokens arriving **joins** the existing instance
1348
+ *
1349
+ * TODO: This has a problem if task is already initiated, we currently avoid finished instances
1350
+ *
1351
+ * TODO: Later we should develop more advanced mechanism on the decision-making when a new instance should be created. The simplest possible are:
1352
+ * 1. there are no running (active) task instances for the visited task
1353
+ * 2. there is already task running with token occupying the port the new token arrived to
1354
+ */
1355
+ let nextPlaceInstance;
1356
+ const nextPlaceInstances = getTaskInstancesByTaskId(this.flowInstance, nextPlace.id);
1357
+ for (const nextPlaceInstanceCheck of nextPlaceInstances) {
1358
+ // skip for finished instances
1359
+ if (nextPlaceInstanceCheck.tokenStatus === ETokenStatusInFlowPlaceInstance.FINISHED)
1360
+ continue;
1361
+ // skip the instances that already has a token at the same position
1362
+ if (nextPlaceInstanceCheck.initiatedTokenIdsPerPorts[sequenceToNextPlace.targetPortId ?? EFlowSpecialPortIds.DEFAULT])
1363
+ continue;
1364
+ nextPlaceInstance = nextPlaceInstances[0];
1365
+ }
1366
+ // eslint-disable-next-line no-empty
1367
+ if (nextPlaceInstance) {
1368
+ }
1369
+ else {
1370
+ nextPlaceInstance = createPlaceInstanceForPlace(nextPlace, downSequenceToken, this.flowInstance, sequenceToNextPlace.targetPortId);
1371
+ }
1372
+ /** PROGRESS the token `tokenDownSequence`: `tokenPositionPlace` -> `nextPlaceInstance`
1373
+ * ------------------------------------------------------------------------------
1374
+ * LEAVE `tokenPositionPlace`
1375
+ * UPDATE `tokenCurrentPlaceInstance`
1376
+ * ENTER `nextPlaceInstance`
1377
+ */
1378
+ /** LEAVE the `tokenPositionPlace` place
1379
+ * -------------------------------------
1380
+ */
1381
+ // update current place instance
1382
+ tokenCurrentPlaceInstance.tokenStatus = ETokenStatusInFlowPlaceInstance.LEFT;
1383
+ // remove token from `tokenPositionPlace` ...
1384
+ /** position of token in the place instance */
1385
+ const tokenPositionPlace = tokenCurrentPlaceInstance.currentTokenIds.findIndex((tokenIdCompare) => tokenIdCompare === downSequenceToken.id);
1386
+ tokenCurrentPlaceInstance.currentTokenIds.splice(tokenPositionPlace, 1);
1387
+ /** ENTER the `nextPlaceInstance` place
1388
+ * -------------------------------------
1389
+ * + update new place and let it ready for the flow instance logic to deliver it to execution business logic
1390
+ * + Update token with the new place info (placeId, placeInstanceId, [placeInstancePortId])
1391
+ * + Update nextPlaceInstance with new token (tokenStatus, currentTokenIds, [initiatedTokenIdsPerPorts])
1392
+ */
1393
+ downSequenceToken.placeId = nextPlace.id;
1394
+ downSequenceToken.placeInstanceId = nextPlaceInstance.id;
1395
+ // NOTE: it would be set as an `undefined` property if stated just as:
1396
+ // `token.placeInstancePortId = sequenceToNextPlace.targetPortId;`
1397
+ // and therefore visible and iterable, which might not be ideal
1398
+ // therefore we check `sequenceToNextPlace.targetPortId` first
1399
+ if (sequenceToNextPlace.targetPortId) {
1400
+ downSequenceToken.placeInstancePortId = sequenceToNextPlace.targetPortId;
1401
+ }
1402
+ // ... and put token in the `nextPlaceInstance`
1403
+ nextPlaceInstance.currentTokenIds.push(downSequenceToken.id);
1404
+ // token entered the instance
1405
+ nextPlaceInstance.tokenStatus = ETokenStatusInFlowPlaceInstance.JUST_ENTERED;
1406
+ // make sure that the place knows that token arrived to its `sequenceToNextPlace.targetPortId` port
1407
+ nextPlaceInstance.initiatedTokenIdsPerPorts[sequenceToNextPlace.targetPortId ?? EFlowSpecialPortIds.DEFAULT] = downSequenceToken.id;
1408
+ console.log(`[asyncProgressTokensThatAreFinished] nextPlaceInstance: ${JSON.stringify(nextPlaceInstance)}`);
1409
+ }
1410
+ }
1411
+ else {
1412
+ throw new Error(`[progressTokenToNextPlace] no output sequences (sequencesToNextPlace.length==0) for the token ("${token.id}") at the place token.placeId="${token.placeId}"`);
1413
+ }
1414
+ return tokensProgressed;
1415
+ }
1416
+ /** Returns currently executing tasks (as they may be tasks executing in parallel).
1417
+ *
1418
+ * Currently executing tasks are those which have tokens "in them"
1419
+ */
1420
+ getCurrentTasks() {
1421
+ const tasks = [];
1422
+ for (const token of this.flowInstance.tokens) {
1423
+ const task = flowGetTaskById(this.flow, token.placeId);
1424
+ if (!task) {
1425
+ throw new Error(`[getCurrentPlaces] task is not available for token.placeId: "${token.placeId}"`);
1426
+ }
1427
+ if (task)
1428
+ tasks.push(task);
1429
+ }
1430
+ return tasks;
1431
+ }
1432
+ /** Returns currently executing places (as they may be places executing in parallel).
1433
+ *
1434
+ * Currently executing places are those which have tokens "in them"
1435
+ */
1436
+ getCurrentPlaces() {
1437
+ const places = [];
1438
+ for (const token of this.flowInstance.tokens) {
1439
+ const place = flowGetPlaceById(this.flow, token.placeId);
1440
+ if (!place) {
1441
+ throw new Error(`[getCurrentPlaces] place is not available for token.placeId: "${token.placeId}"`);
1442
+ }
1443
+ places.push(place);
1444
+ }
1445
+ return places;
1446
+ }
1447
+ /**
1448
+ * Gets next task id
1449
+ *
1450
+ * if the exitValue is not provided the returned task will be the one reached through the default (condition == null || undefined) sequence, or null if there is no default sequence
1451
+ *
1452
+ * if the exitValue is provided but not matched it will return null
1453
+ *
1454
+ * @param taskId the task which we want to traverse from
1455
+ * @param [exitValue] exitValue (condition) for the task
1456
+ * @returns next task id or null if not successfully matched
1457
+ */
1458
+ getNextTaskId(taskId, exitValue) {
1459
+ // const executingTask: eFlowTask = this.flowUtility.getTask(taskId);
1460
+ const outgoingSequences = flowGetSequencesOutgoingFromPlace(this.flow, taskId);
1461
+ // no exit sequences
1462
+ if (outgoingSequences.length <= 0) {
1463
+ return undefined;
1464
+ }
1465
+ else {
1466
+ // go through all sequences and see which matches the exitValue
1467
+ for (const sequence of outgoingSequences) {
1468
+ // it will match either explicit exitValue and
1469
+ // implicit exitValue (undefined/null) which will match with the default sequence
1470
+ // with the `condition` == null || undefined
1471
+ if (sequence.condition == exitValue || (!sequence.condition && !exitValue)) {
1472
+ // return id of the task on the other end of the sequence
1473
+ return sequence.targetId;
1474
+ }
1475
+ }
1476
+ // no sequence with matching exitValue
1477
+ // this is usually NOT GOOD :)
1478
+ return undefined;
1479
+ }
1480
+ }
1481
+ /**
1482
+ * Gets the list of available next places' ids of particular type (`placeTypes: EFlowPlaceType`)
1483
+ *
1484
+ * If the `exitValue` is not provided the returned places' ids will all reached through exit sequences
1485
+ *
1486
+ * @param placeId the place which we want to traverse from
1487
+ * @param placeTypes the array of types of the place we are interest in (it will return all places if not provided (`null` or `undefined`))
1488
+ * @param exitValue exitValue (condition) for the current place
1489
+ * @returns next places' ids or empty array `[]` if nothing matched
1490
+ */
1491
+ getNextPlacesIds(placeId, placeTypes, exitValue) {
1492
+ const nextPlacesIds = [];
1493
+ const outgoingSequences = flowGetSequencesOutgoingFromPlace(this.flow, placeId);
1494
+ // no exit sequences
1495
+ if (outgoingSequences.length <= 0) {
1496
+ return nextPlacesIds;
1497
+ }
1498
+ else {
1499
+ // go through all sequences and see which matches the exitValue
1500
+ for (const sequence of outgoingSequences) {
1501
+ // it will match either explicit exitValue and
1502
+ // implicit exitValue (undefined/null) which will match with the default sequence
1503
+ // with the `condition` == null || undefined
1504
+ if ((placeTypes.indexOf(sequence.targetType) >= 0 || !placeTypes) && (sequence.condition == exitValue || (!sequence.condition && !exitValue))) {
1505
+ // return id of the task on the other end of the sequence
1506
+ nextPlacesIds.push(sequence.targetId);
1507
+ }
1508
+ }
1509
+ return nextPlacesIds;
1510
+ }
1511
+ }
1512
+ }
1513
+ //# sourceMappingURL=flow-instance-engine.js.map