@colabo-flow/s-go 0.1.2

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 (106) hide show
  1. package/DEVELOPMENT.md +38 -0
  2. package/README.md +110 -0
  3. package/__init__.py +0 -0
  4. package/__pycache__/__init__.cpython-39.pyc +0 -0
  5. package/create_client.py +84 -0
  6. package/create_host.py +91 -0
  7. package/create_host_terra.py +103 -0
  8. package/demo/__init__.py +0 -0
  9. package/demo/create-client.ts +51 -0
  10. package/demo/create-host.ts +136 -0
  11. package/demo/send-simple-recommended.py +26 -0
  12. package/demo/send-simple.py +50 -0
  13. package/demo/send.py +352 -0
  14. package/demo/send.ts +40 -0
  15. package/demo/threading/README.md +14 -0
  16. package/demo/threading/basic_consumer_connection_threaded.png +0 -0
  17. package/demo/threading/basic_consumer_connection_threaded.py +135 -0
  18. package/demo/threading/basic_consumer_threaded.py +100 -0
  19. package/demo/threading/long-running-publisher.py +68 -0
  20. package/docs/ColaboFlow-infrastructure-diagram.png +0 -0
  21. package/docs/workflow.md +35 -0
  22. package/index.ts +4 -0
  23. package/jest.config.ts +172 -0
  24. package/lib/__init__.py +0 -0
  25. package/lib/__pycache__/__init__.cpython-39.pyc +0 -0
  26. package/lib/__pycache__/config.cpython-39.pyc +0 -0
  27. package/lib/__pycache__/executor_operators.cpython-39.pyc +0 -0
  28. package/lib/__pycache__/executor_vos.cpython-39.pyc +0 -0
  29. package/lib/__pycache__/go_amqp_client.cpython-39.pyc +0 -0
  30. package/lib/__pycache__/go_amqp_client_threaded.cpython-39.pyc +0 -0
  31. package/lib/__pycache__/go_amqp_host.cpython-39.pyc +0 -0
  32. package/lib/__pycache__/operators.cpython-39.pyc +0 -0
  33. package/lib/__pycache__/vos.cpython-39.pyc +0 -0
  34. package/lib/config.py +21 -0
  35. package/lib/config.ts +22 -0
  36. package/lib/executor_operators.py +23 -0
  37. package/lib/executor_vos.py +318 -0
  38. package/lib/go.amqp.client-old-basic.py +50 -0
  39. package/lib/go.amqp.client.ts +100 -0
  40. package/lib/go.amqp.host-old-basic.py +48 -0
  41. package/lib/go.amqp.host.ts +269 -0
  42. package/lib/go.amqp.host_status.ts +81 -0
  43. package/lib/go.amqp.service.ts +272 -0
  44. package/lib/go_amqp_client.py +263 -0
  45. package/lib/go_amqp_client_non_threaded.py +152 -0
  46. package/lib/go_amqp_host.py +348 -0
  47. package/lib/operators.py +16 -0
  48. package/lib/operators.ts +17 -0
  49. package/lib/params.ts +1 -0
  50. package/lib/vos.py +232 -0
  51. package/lib/vos.ts +212 -0
  52. package/package.json +36 -0
  53. package/requirements.txt +4 -0
  54. package/tests/units/README.md +12 -0
  55. package/tests/units/chalk/index.ts +41 -0
  56. package/tests/units/go.amqp.host.test.ts +116 -0
  57. package/tests/units/tests-vos/tasks-and-flows.vos.ts +128 -0
  58. package/tsconfig.json +45 -0
  59. package/v1 - GRPC/README.md +18 -0
  60. package/v1 - GRPC/node/README.md +13 -0
  61. package/v1 - GRPC/node/colaboflow_go_actionhost_client.ts +91 -0
  62. package/v1 - GRPC/node/colaboflow_go_actionhost_server.ts +84 -0
  63. package/v1 - GRPC/node/colaboflow_go_client.ts +82 -0
  64. package/v1 - GRPC/node/colaboflow_go_server.ts +84 -0
  65. package/v1 - GRPC/node/demos/demo-colaboflow_go_actionhost_client.ts +21 -0
  66. package/v1 - GRPC/node/index.ts +3 -0
  67. package/v1 - GRPC/node/package-lock.json +770 -0
  68. package/v1 - GRPC/node/package.json +30 -0
  69. package/v1 - GRPC/node/tsconfig.json +32 -0
  70. package/v1 - GRPC/node/yarn.lock +642 -0
  71. package/v1 - GRPC/protos/colabo/flow/go/go.proto +135 -0
  72. package/v1 - GRPC/python/DEVELOPMENT.md +86 -0
  73. package/v1 - GRPC/python/DISCUSSION.md +8 -0
  74. package/v1 - GRPC/python/LICENSE.txt +21 -0
  75. package/v1 - GRPC/python/README.md +45 -0
  76. package/v1 - GRPC/python/__init__.py +1 -0
  77. package/v1 - GRPC/python/colabo/__init__.py +3 -0
  78. package/v1 - GRPC/python/colabo/flow/__init__.py +3 -0
  79. package/v1 - GRPC/python/colabo/flow/go/__init__.py +12 -0
  80. package/v1 - GRPC/python/colabo/flow/go/basic/PuzzleImporter.py +77 -0
  81. package/v1 - GRPC/python/colabo/flow/go/basic/__init__.py +5 -0
  82. package/v1 - GRPC/python/colabo/flow/go/basic/colaboflow_go_basic.py +66 -0
  83. package/v1 - GRPC/python/colabo/flow/go/basic/parseFlowJSON.py +32 -0
  84. package/v1 - GRPC/python/colabo/flow/go/colaboflow_go_actionhost.py +44 -0
  85. package/v1 - GRPC/python/colabo/flow/go/colaboflow_go_client.py +48 -0
  86. package/v1 - GRPC/python/colabo/flow/go/colaboflow_go_demo.py +168 -0
  87. package/v1 - GRPC/python/colabo/flow/go/go_pb2.py +976 -0
  88. package/v1 - GRPC/python/colabo/flow/go/go_pb2_grpc.py +139 -0
  89. package/v1 - GRPC/python/colabo.flow.go.egg-info/PKG-INFO +58 -0
  90. package/v1 - GRPC/python/colabo.flow.go.egg-info/SOURCES.txt +16 -0
  91. package/v1 - GRPC/python/colabo.flow.go.egg-info/dependency_links.txt +1 -0
  92. package/v1 - GRPC/python/colabo.flow.go.egg-info/requires.txt +3 -0
  93. package/v1 - GRPC/python/colabo.flow.go.egg-info/top_level.txt +2 -0
  94. package/v1 - GRPC/python/demo-0.py +69 -0
  95. package/v1 - GRPC/python/demo-1.py +146 -0
  96. package/v1 - GRPC/python/demo-actionhost.py +47 -0
  97. package/v1 - GRPC/python/demo-basic.md +13 -0
  98. package/v1 - GRPC/python/demo-basic.py +38 -0
  99. package/v1 - GRPC/python/demo-executeActionSync.py +32 -0
  100. package/v1 - GRPC/python/demo-flows/flow-demo.json +36 -0
  101. package/v1 - GRPC/python/demo-puzzles/puzzles/puzzle-a.py +19 -0
  102. package/v1 - GRPC/python/demo-puzzles/puzzles/puzzle-b.py +21 -0
  103. package/v1 - GRPC/python/demo-puzzles/puzzles/puzzle-c.py +20 -0
  104. package/v1 - GRPC/python/requirements.txt +7 -0
  105. package/v1 - GRPC/python/setup.py +39 -0
  106. package/v1 - GRPC/python/use-cases/__init__.py +0 -0
@@ -0,0 +1,318 @@
1
+ # describes types used in the ColaboFlow.GO puzzle
2
+
3
+ from dataclasses import dataclass, field
4
+ from enum import Enum
5
+ import json
6
+
7
+ # Patching JSON serialization in order to support serialization of @dataclass objects
8
+ # the code is idempotent
9
+ # --start--
10
+ # --start--
11
+ from json import JSONEncoder
12
+
13
+ def _default(self, obj):
14
+ return getattr(obj.__class__, "to_json", _default.default)(obj)
15
+
16
+ _default.default = JSONEncoder().default
17
+ if not hasattr(JSONEncoder, "isPatchedFor_to_json"):
18
+ JSONEncoder.default = _default
19
+ JSONEncoder.isPatchedFor_to_json = True
20
+ # --end--
21
+
22
+ from typing import Any, Optional, Callable
23
+ from enum import Enum
24
+
25
+ from pika.channel import Channel
26
+ from typing import Optional, NamedTuple
27
+
28
+ """ Environment under which the executor can execute """
29
+ # PY > 3.4
30
+ class EExecutingEnvironment(str, Enum):
31
+ """ Executor can execute on any environment, no environment related code """
32
+ ISOMORPHIC = "ISOMORPHIC",
33
+ """ Executor has frontend dependencies """
34
+ FRONTEND = "FRONTEND",
35
+ """ Executor has backend dependencies """
36
+ BACKEND = "BACKEND",
37
+
38
+ """
39
+ references to the executor implementation
40
+ """
41
+ @dataclass
42
+ class IExecutorImplementationReference():
43
+ method: Optional[Callable] = None; # TExecutorReferenceMethod
44
+ async_method: Optional[Callable] = None; # TExecutorReferenceMethod
45
+
46
+ """
47
+ Describes a task executor, its location, initiation, environment, etc
48
+ """
49
+ @dataclass
50
+ class ITaskExecutor():
51
+ """
52
+ id of executor. It should be unique
53
+ at least at the level of each environment
54
+ (maybe we should keep it unique overall, as, for example, isomorphic executors can migrate environments)
55
+ """
56
+ id: str
57
+
58
+ """ describes executor """
59
+ description: str
60
+
61
+ """where the executor can be executed"""
62
+ environment: EExecutingEnvironment
63
+
64
+ """reference to the executor implementation"""
65
+ reference: IExecutorImplementationReference
66
+
67
+ """
68
+ Tells the type of an event
69
+ https://www.lucidchart.com/pages/bpmn-activity-types
70
+ """
71
+ class EFlowTaskType(str, Enum):
72
+ REGULAR = "TASK.REGULAR",
73
+ LOOP = "TASK.LOOP",
74
+ MULTIPLE_PARALLEL = "TASK.MULTIPLE_PARALLEL",
75
+ MULTIPLE_SEQUENTIAL = "TASK.MULTIPLE_SEQUENTIAL",
76
+ COMPENSATION = "TASK.COMPENSATION",
77
+ COMPENSATION_LOOP = "TASK.COMPENSATION_LOOP",
78
+
79
+ SUBPROCESS = "TASK.SUBPROCESS",
80
+ SUBPROCESS_LOOP = "TASK.SUBPROCESS_LOOP",
81
+ SUBPROCESS_MULTIPLE_PARALLEL = "TASK.SUBPROCESS_MULTIPLE_PARALLEL",
82
+ SUBPROCESS_MULTIPLE_SEQUENTIAL = "TASK.SUBPROCESS_MULTIPLE_SEQUENTIAL",
83
+ SUBPROCESS_COMPENSATION = "TASK.SUBPROCESS_COMPENSATION",
84
+ SUBPROCESS_ADHOC = "TASK.SUBPROCESS_ADHOC",
85
+
86
+ SUBPROCESS_EVENT = "TASK.SUBPROCESS_EVENT",
87
+
88
+ TRANSACTION = "TASK.TRANSACTION",
89
+
90
+ CALL_ACTIVITY = "TASK.CALL_ACTIVITY",
91
+
92
+ # EXECUTABLE
93
+ BUSINESS_RULE = "TASK.BUSINESS_RULE",
94
+ MANUAL = "TASK.MANUAL",
95
+ RECEIVE = "TASK.RECEIVE",
96
+ SCRIPT = "TASK.SCRIPT",
97
+ SEND = "TASK.SEND",
98
+ SERVICE = "TASK.SERVICE",
99
+ USER = "TASK.USER",
100
+
101
+ """
102
+ References the executor that should execute the task.
103
+ It also tells the environment in which it should be executed
104
+ """
105
+ @dataclass
106
+ class IExecutorReference:
107
+ """
108
+ id of executor. It should be unique
109
+ at least at the level of each environment
110
+ (maybe we should keep it unique overall, as, for example, isomorphic executors can migrate environments)
111
+ """
112
+ id: str
113
+
114
+ """where the executor should be executed"""
115
+ environment: EExecutingEnvironment
116
+
117
+ """
118
+ id inside of the executor.
119
+
120
+ It is usually a name or an (lookup) id of a *methodor *exportthat should be executed in the module representing the executor
121
+
122
+ Taken from colabo/src/isomorphic/dev_puzzles/flow/core/lib/flow-types/flow-types-vos.ts
123
+ """
124
+ subId: Optional[str] = None
125
+
126
+ class EFlowPlacePortType (str, Enum):
127
+ IN = "IN",
128
+ OUT = "OUT",
129
+ INOUT = "INOUT",
130
+
131
+ class EFlowPlaceType (str, Enum):
132
+ TASK = "TASK",
133
+ EVENT = "EVENT",
134
+ GATEWAY = "GATEWAY",
135
+
136
+ IExtension = NamedTuple("IExtension", [
137
+ ])
138
+
139
+ """
140
+ Describes ports that a place is connected to other places
141
+ """
142
+ @dataclass
143
+ class IFlowPlacePort:
144
+ name: str
145
+ type: EFlowPlacePortType
146
+
147
+ @dataclass
148
+ class IFlowPlace:
149
+ """
150
+ the exact type of the place (to support simpler searching and management)
151
+ TODO: understand if we need it, as places are already distributed across different arrays.
152
+ The distribution can change, often places are aggregated in a single array, and it is really just about extended entity size.
153
+ So probably yes, we will keep it
154
+ """
155
+ # I had to add the default value to avoid the error `TypeError: non-default argument 'placeType' follows default argument` coming from
156
+ # `class IFlowTask(IFlowPlace, IFlowElement):`
157
+ placeType: EFlowPlaceType = EFlowPlaceType.TASK
158
+
159
+ """ additional space for extension of the place without explicit mechanism, like classes implementations or interfaces extensions """
160
+ extension: Optional[IExtension] = None
161
+
162
+ """
163
+ Describes any flow element either place or sequence, etc
164
+ Each of them can have id, name, description
165
+ """
166
+ @dataclass
167
+ class IFlowElement():
168
+ """ place id, uniquely identifying the place across the flow that contains the place"""
169
+ id: str
170
+
171
+ """ name of the place, can overlap with the names of other places inside the flow, but it is not recommended as making confusion"""
172
+ name: Optional[str] = None
173
+
174
+ """ description of the place (activity, task, event, ...)"""
175
+ description: Optional[str] = None
176
+
177
+ inputs: Optional[list[IFlowPlacePort]] = field(default_factory=list)
178
+ outputs: Optional[list[IFlowPlacePort]] = field(default_factory=list)
179
+ inoutputs: Optional[list[IFlowPlacePort]] = field(default_factory=list)
180
+
181
+ # """ transformations required on task inputs and outputs"""
182
+ # transformations: IFlowElementTransformations = None
183
+
184
+ """
185
+ Describes flow task
186
+
187
+ Flow Task is conceptually (from the perspective of flow) atomic element of flow execution
188
+ With various types of sequences it is connected with other flow entities
189
+ """
190
+ @dataclass
191
+ class IFlowTask(IFlowPlace, IFlowElement):
192
+ """
193
+ The type of the task
194
+
195
+ if present, it helps to distinguish different types of tasks
196
+ and help with interpreting additional extensions of the task
197
+ """
198
+ type: Optional[EFlowTaskType] = None
199
+
200
+ """reference to the entity (worker, service, actor) that is designed to execute the task"""
201
+ executorRef: Optional[IExecutorReference] = None
202
+
203
+ """
204
+ Hash array of params that can be provided to the activity in order to tune its behavior to needed one.
205
+
206
+ The difference between **params*and **input data*is in that that input data can change on any activity (task instance, a particular execution of task) while `params` are intended to be fixed for all executions of a particular task in the workflow
207
+ """
208
+ params: dict[str, Any] = field(default_factory=dict)
209
+
210
+ # # extends: ITagsArray
211
+ # tags: Optional[list[str]] = field(default_factory=list)
212
+
213
+ def __post_init__(self):
214
+ self.placeType = EFlowPlaceType.TASK
215
+
216
+
217
+ @dataclass
218
+ class ITagsArray():
219
+ tags: Optional[list[str]] = None
220
+
221
+ """
222
+ Describes any flow element either place or sequence, etc
223
+ Each of them can be tagged, have origin element and initiating token info
224
+ """
225
+ @dataclass
226
+ class IFlowElementInstance(ITagsArray):
227
+
228
+ # I had to add the default value to avoid the error `TypeError: non-default argument 'id' follows default argument` coming from
229
+ """
230
+ element instance id, uniquely identifying the element across the flow execution engine
231
+ there cannot be any other element execution with the same id in the scope of our (resolution) interest
232
+ """
233
+ id: str = "<UNDEFINED>"
234
+
235
+ # I had to add the default value to avoid the error `TypeError: non-default argument 'originId' follows default argument` coming from
236
+ """
237
+ the id of the element this is the instance (execution) of
238
+ """
239
+ originId: str = "<UNDEFINED>"
240
+
241
+ # /** The ids of the tokens that initiated the element instantiation
242
+ # * The key to the hash is place's port id at which the token arrived to
243
+ # *
244
+ # * the record's **key** is port i and
245
+ # *
246
+ # * record's **value** is token id placed on that port
247
+ # *
248
+ # * TODO: The motivation to have it here and not at `IFlowPlaceInstance` is that we want to know about non-places (like sequences) what initiated them as well. On the other hand, non places should not bother on the tokens' PRESENCE (as one of the key distinction between flow's place and element). Therefore it could make sense that this should be part of the flow audit, rather than flow instance execution.
249
+ # *
250
+ # * At the moment we will keep it here, and provide `EFlowSpecialPortIds.DEFAULT` for non-places (specifically sequences)
251
+ # */
252
+ # initiatedTokenIdsPerPorts: Record<str, str>;
253
+
254
+ # /** The list of currently */
255
+ # currentTokenIds: str[];
256
+
257
+ # /** The status of the token that initiated the instance of the element
258
+ # *
259
+ # * TODO: This probably should be renamed and refactored to detach the focus from token to the instance itself, especially when there are more than one token in the instance
260
+ # */
261
+ # tokenStatus: ETokenStatusInFlowPlaceInstance;
262
+
263
+ """
264
+ Describes place instance of any type of the place in a flow
265
+ It tells which type of a place the place is (task, event, gateway, ...)
266
+ """
267
+ @dataclass
268
+ class IFlowPlaceInstance(IFlowElementInstance):
269
+ # I had to add the default value to avoid the error `TypeError: non-default argument 'placeType' follows default argument` coming from
270
+ """
271
+ the exact type of the place (to support simpler searching and management)
272
+ TODO: understand if we need it, as place instances are already distributed across different arrays.
273
+ The distribution can change, often places instances are aggregated in a single array, so to get the info we need to drill to places which might be either expensive or not easily possible (when business logic is not close enough to places) and it is really just about extended entity size.
274
+ So probably yes, we will keep it
275
+ """
276
+ placeType: EFlowPlaceType = EFlowPlaceType.TASK
277
+
278
+ # /** References to the place's instance inputs (stored in DataTalksCache)
279
+ # *
280
+ # * the key to the record is portId and value is cache entry reference (`IDataTalksCacheEntryReference`)
281
+ # *
282
+ # * It references to the data as they arrived to the input port and not the data that got transformed on the way between data arrival to the port and their execution by the task executor
283
+ # */
284
+ # executionInputReferences: Record<str, IDataTalksCacheEntryReference>;
285
+
286
+ # /** References to the place's instance outputs (stored in DataTalksCache)
287
+ # *
288
+ # * the key to the record is portId and value is cache entry reference (`IDataTalksCacheEntryReference`)
289
+ # */
290
+ # executionOutputReferences: Record<str, IDataTalksCacheEntryReference>;
291
+
292
+ """
293
+ Describes flow task instance
294
+
295
+ Flow Task instance is conceptually (from the perspective of flow) an instance of atomic element of flow execution
296
+ """
297
+ @dataclass
298
+ class IFlowTaskInstance(IFlowPlaceInstance):
299
+ """
300
+ reference to the entity (worker, service, actor) that is designed to execute the task
301
+ """
302
+ executorInstanceId: Optional[str] = None
303
+
304
+ # /** status of the running instance of the task */
305
+ # status: EFlowTaskExecutionStatus;
306
+ # /** The exit value of the task execution
307
+ # *
308
+ # * **TODO**:
309
+ # * + currently not used
310
+ # * + the idea is to optimise branching out from the task to its successors in a way
311
+ # * + condensing: avoiding gateways
312
+ # * + states/variables: avoiding having complex variables for conditioning if condition can be resolved based on the last task exit value only
313
+ # * + It could still be used as a value transmitted down the control flow and used in the immediately following gateway
314
+ # * + gateway should use conditional values of its outgoing sequences to understand which sequence to follow
315
+ # */
316
+ # exitValue?: str
317
+ # /** additional space for extension of the flow without explicit mechanism, like classes implementations or interfaces extensions */
318
+ # extension?: IFlowTaskInstanceExtension;
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env python
2
+ # https://pypi.org/project/pika/
3
+ import pika
4
+ import json
5
+ from yachalk import chalk
6
+
7
+ amqp_server = "localhost"
8
+ ORCHESTRATOR_QUEUE = "colabo.flow.orchestrator"
9
+
10
+ import pika
11
+
12
+ # https://pypi.org/project/setproctitle/
13
+ # https://github.com/dvarrazzo/py-setproctitle
14
+ # https://stackoverflow.com/a/1866700/257561
15
+ from setproctitle import setproctitle
16
+ proc_title = "ColaboFlow.Go.Client-Python"
17
+ setproctitle(proc_title)
18
+
19
+ appNameText = f'[{chalk.red.bold("Colabo")}{chalk.blue.bold("Flow")}{chalk.green.bold(".Go")}{chalk.green.yellow(".Client-Python")}]';
20
+
21
+ print(f"{appNameText} Connecting to the server: {amqp_server}");
22
+ parameters = (
23
+ pika.ConnectionParameters(
24
+ host=amqp_server,
25
+ port=5672,
26
+ connection_attempts=5,
27
+ retry_delay=1
28
+ )
29
+ )
30
+
31
+ connection = pika.BlockingConnection(pika.ConnectionParameters(host=amqp_server))
32
+
33
+ queue = ORCHESTRATOR_QUEUE
34
+ channel = connection.channel()
35
+ # https://github.com/MassTransit/MassTransit/issues/370
36
+ channel.queue_declare(queue=queue, durable=True, exclusive=False, auto_delete=False)
37
+
38
+ msg = {
39
+ "client": "send-simple.py",
40
+ "executorId": "colabo.flow.demo.minus",
41
+ "msg": "sudo: make me a pie",
42
+ }
43
+ print(f'{appNameText} Sending [queue: "{chalk.blue_bright(queue)}"]: {json.dumps(msg)}');
44
+ channel.basic_publish(exchange='', routing_key=queue, body=json.dumps(msg))
45
+
46
+ print(f"{appNameText} [x] Sent {msg}")
47
+
48
+ print(f"{appNameText} Closing the {chalk.bold.italic('connection')} to the ColaboFlow service...")
49
+
50
+ connection.close()
@@ -0,0 +1,100 @@
1
+ // https://www.npmjs.com/package/amqplib
2
+ import { connect } from "amqplib";
3
+ import chalk from "chalk";
4
+ import { v1 as uuidv1 } from "uuid";
5
+
6
+ import { connectConfig } from "./config";
7
+ import { EColaboFlowGoMsgType, IColaboFlowClientData, IColaboFlowGoMsg, IColaboFlowGoMsgExtension_TaskExecute_Request, IColaboFlowGoMsgExtension_TaskExecute_Response } from "./vos";
8
+ import { createGoMsg } from "./operators";
9
+
10
+ export const clientRun = async (client: IColaboFlowClientData) => {
11
+ process.title = `ColaboFlow.Go.Client-${client.clientName}`;
12
+ client.appNameText = `[${chalk.red.bold("Colabo")}${chalk.blue.bold("Flow")}${chalk.green.bold(".Go")}-${chalk.green.yellow(client.clientName)}]`;
13
+
14
+ console.log(`${client.appNameText} Connecting to the ColaboFlow service: ${chalk.greenBright(client.amqpUrl)}`);
15
+ try {
16
+ client.connection = await connect(client.amqpUrl);
17
+ } catch (err) {
18
+ console.error(`${client.appNameText} Error connecting to the "${chalk.greenBright(client.amqpUrl)}" ColaboFlow service: ${err}`);
19
+ return;
20
+ }
21
+
22
+ try {
23
+ client.channel = await client.connection.createChannel();
24
+ } catch (err) {
25
+ console.error(`${client.appNameText} Error creating the channel`);
26
+ return;
27
+ }
28
+
29
+
30
+ // console.log(`${client.appNameText} Closing the ${chalk.bold.italic("channel")} to the ColaboFlow service...`);
31
+ // await colaboFlowServiceChannel.close();
32
+
33
+ // console.log(`${client.appNameText} Closing the ${chalk.bold.italic("connection")} to the ColaboFlow service...`);
34
+ // await colaboFlowService.close();
35
+ };
36
+
37
+ export const clientExecuteTask = async (client: IColaboFlowClientData, taskId: string, taskInput?: any): Promise<any> => {
38
+ const promise = new Promise(async (resolve, reject) => {
39
+ const taskExecuteResponseQueue = `client-task_execute_response-${uuidv1()}`;
40
+ const msgTaskRequest: IColaboFlowGoMsg = {
41
+ ...createGoMsg(client.clientName, EColaboFlowGoMsgType.TASK_EXECUTE_REQUEST),
42
+ replyTo: taskExecuteResponseQueue,
43
+ extension: {
44
+ taskId,
45
+ taskInput,
46
+ } as IColaboFlowGoMsgExtension_TaskExecute_Request,
47
+ msg: "run a ffmepg test task",
48
+ };
49
+
50
+ console.log(`${client.appNameText} Sending task request [queue: "${chalk.blueBright(client.queueServiceOrchestrator)}"]: ${JSON.stringify(msgTaskRequest)}`);
51
+ // https://www.w3schools.com/nodejs/met_buffer_from.asp
52
+ await client.channel.sendToQueue(client.queueServiceOrchestrator, Buffer.from(JSON.stringify(msgTaskRequest)));
53
+
54
+ // https://amqp-node.github.io/amqplib/channel_api.html#channel_assertQueue
55
+ await client.channel.assertQueue(taskExecuteResponseQueue, {
56
+ exclusive: true,
57
+ });
58
+
59
+ client.channel.consume(
60
+ taskExecuteResponseQueue,
61
+ function (msgServiceRes: any) {
62
+ let msgServiceResObj: IColaboFlowGoMsg;
63
+ try {
64
+ msgServiceResObj = JSON.parse(msgServiceRes.content);
65
+
66
+ // console.log(`${client.appNameText} Received: "${chalk.blueBright(JSON.stringify(msgHostResObj))}"`);
67
+ // console.log(`${client.appNameText} msgObj.sender: "${chalk.blueBright(msgHostResObj.sender)}", msgObj.type: "${chalk.blueBright(msgHostResObj.type)}, msgObj.msg: "${chalk.blueBright(msgHostResObj.msg)}"`);
68
+ } catch (err) {
69
+ console.error(`Error parsing the message: ${msgServiceRes.content}`);
70
+ return;
71
+ }
72
+ const msgServiceResObjExtension: IColaboFlowGoMsgExtension_TaskExecute_Response = (msgServiceResObj.extension as IColaboFlowGoMsgExtension_TaskExecute_Response);
73
+
74
+ resolve(msgServiceResObjExtension.taskOutput);
75
+ },
76
+ {
77
+ noAck: true,
78
+ }
79
+ );
80
+ });
81
+
82
+ return promise;
83
+ }
84
+
85
+ export const clientClose = async (client: IColaboFlowClientData): Promise<boolean> => {
86
+ const promise: Promise<boolean> = new Promise<boolean>( (resolve, reject) => {
87
+ setTimeout(async () => {
88
+ console.log(`${client.appNameText} Closing the ${chalk.bold.italic("channel")} to the ColaboFlow service...`);
89
+ await client.channel.close();
90
+
91
+ console.log(`${client.appNameText} Closing the ${chalk.bold.italic("connection")} to the ColaboFlow service...`);
92
+ await client.connection.close();
93
+
94
+ resolve(true);
95
+
96
+ }, 500);
97
+ });
98
+
99
+ return promise;
100
+ }
@@ -0,0 +1,48 @@
1
+ #!/usr/bin/env python
2
+ import pika
3
+ import json
4
+ from yachalk import chalk
5
+ # https://docs.python.org/3/library/uuid.html
6
+ import uuid
7
+
8
+ from config import connectConfig
9
+ from vos import (
10
+ IColaboFlowGoMsg,
11
+ EColaboFlowGoMsgType
12
+ )
13
+ from operators import createGoMsg
14
+
15
+ # https://pypi.org/project/setproctitle/
16
+ # https://github.com/dvarrazzo/py-setproctitle
17
+ # https://stackoverflow.com/a/1866700/257561
18
+ from setproctitle import setproctitle
19
+ proc_title = "ColaboFlow.Go.Client-Python"
20
+ setproctitle(proc_title)
21
+
22
+ appNameText = f'[{chalk.red.bold("Colabo")}{chalk.blue.bold("Flow")}{chalk.green.bold(".Go")}.{chalk.green.yellow(connectConfig.APP_NAME)}]';
23
+
24
+ print(f"{appNameText} Connecting to the server: {connectConfig.AMQP_URL}");
25
+
26
+ parameters = (
27
+ pika.ConnectionParameters(
28
+ host=connectConfig.AMQP_URL,
29
+ port=5672,
30
+ connection_attempts=5,
31
+ retry_delay=1
32
+ )
33
+ )
34
+
35
+ connection = pika.BlockingConnection(parameters)
36
+
37
+ channel = connection.channel()
38
+ channel.queue_declare(queue=QUEUE_HOST_PYTHON)
39
+
40
+ def callback(ch, method, properties, body):
41
+ print(" [x] Received %r" % body)
42
+
43
+ # https://stackoverflow.com/questions/50404273/python-tutorial-code-from-rabbitmq-failing-to-run
44
+ channel.basic_consume(on_message_callback=callback, queue=QUEUE_HOST_PYTHON, auto_ack=True)
45
+
46
+ print(' [*] Waiting for messages. To exit press CTRL+C')
47
+
48
+ channel.start_consuming()