@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,348 @@
1
+ #!/usr/bin/env python
2
+ import pika
3
+ import json
4
+ import time
5
+ import functools
6
+ from yachalk import chalk
7
+ # from dataclasses import replace
8
+ # https://docs.python.org/3/library/uuid.html
9
+ import uuid
10
+ from typing import Any
11
+ import asyncio
12
+ from asyncio import Future
13
+ import threading
14
+ import dataclasses
15
+
16
+ # https://pypi.org/project/setproctitle/
17
+ # https://github.com/dvarrazzo/py-setproctitle
18
+ # https://stackoverflow.com/a/1866700/257561
19
+ from setproctitle import setproctitle
20
+
21
+ # https://stackoverflow.com/a/53713336/257561
22
+ # https://github.com/konradhalas/dacite
23
+ from dacite import from_dict, Config
24
+
25
+ from lib.config import connectConfig, reportsConfig
26
+ from lib.vos import (
27
+ IColaboFlowGoMsg,
28
+ EColaboFlowGoMsgType,
29
+ IColaboFlowHostData,
30
+ EProgrammingLanguageSupported,
31
+ IColaboFlowGoMsgExtension_TaskExecute_Request,
32
+ IColaboFlowGoTaskInstanceInfo,
33
+ ETaskExecute_Progress_Status,
34
+ IColaboFlowGoMsgExtension_TaskExecute_Progress,
35
+ IColaboFlowGoMsgExtension_TaskExecute_Response
36
+ )
37
+ from lib.operators import createGoMsg
38
+ from lib.executor_vos import ITaskExecutor, IFlowTask
39
+ from lib.executor_operators import createTaskInstanceForTaskWithoutFlow
40
+
41
+ LANGUAGE = EProgrammingLanguageSupported.PYTHON
42
+
43
+ def registerTaskExecutor(host: IColaboFlowHostData, executor: ITaskExecutor):
44
+ host.taskExecutorsAvailable[executor.id] = executor
45
+
46
+ def registerTask(host: IColaboFlowHostData, task: IFlowTask):
47
+ host.tasksAvailable[task.id] = task
48
+
49
+ def getTaskExecutor(host: IColaboFlowHostData, executorId: str) -> ITaskExecutor:
50
+ return host.taskExecutorsAvailable[executorId]
51
+
52
+ async def run(host: IColaboFlowHostData):
53
+ proc_title = f"ColaboFlow.Go.Host-{host.hostName}"
54
+ setproctitle(proc_title)
55
+
56
+ connect(host)
57
+ start_consuming(host)
58
+
59
+ if host.sendHeartbeat:
60
+ print(f"{host.appNameTextWithContext('run')} Sending heartbeats")
61
+ sendHeartbeatsToHost(host)
62
+ else:
63
+ print(f"{host.appNameTextWithContext('run')} Not sending heartbeats (due to the host configuration)")
64
+
65
+ if host.listenForOrchestratorRequests:
66
+ print(f"{host.appNameTextWithContext('run')} Listening for the orchestrator requests")
67
+ listenOnHostQueue(host)
68
+ else:
69
+ print(f"{host.appNameTextWithContext('run')} Not listening for the orchestrator requests (due to the host configuration)")
70
+
71
+ print(f"{host.appNameTextWithContext('run')} Connection established, returning")
72
+
73
+ def connect(host: IColaboFlowHostData):
74
+ """
75
+ connects to the ColaboFlow service through RabbitMQ broker
76
+ """
77
+ print(f"{host.appNameTextWithContext('connect')} Connecting to the server...")
78
+ parameters = (
79
+ pika.ConnectionParameters(
80
+ host=host.amqpUrl,
81
+ port=5672,
82
+ connection_attempts=5,
83
+ retry_delay=1
84
+ )
85
+ )
86
+
87
+ # https://pika.readthedocs.io/en/stable/modules/adapters/blocking.html
88
+ host.connection = pika.BlockingConnection(parameters)
89
+ print(f"{host.appNameTextWithContext('connect')} Creating a channel...")
90
+ host.chHostHeartbeat = host.connection.channel()
91
+ # https://github.com/MassTransit/MassTransit/issues/370
92
+
93
+ print(f"{host.appNameTextWithContext('connect')} Declaring the host queue ...")
94
+ # TODO: `exclusive=True` is only if the queue is host (worker) specific and the ColaboFlow handles load-balancing (which is the most long-term reasonable scenario as there is more control on which task goes where and when, etc)
95
+ host.chHostHeartbeat.queue_declare(queue=host.queueHost, durable=True, exclusive=False, auto_delete=False)
96
+ # host.chHostHeartbeat.queue_bind(queue=host.queueHost, exchange="test_exchange", routing_key="standard_key")
97
+
98
+ host.running = True
99
+
100
+ def _start_consuming(host: IColaboFlowHostData):
101
+ """
102
+ Starts consuming messages from the ColaboFlow service through RabbitMQ broker
103
+
104
+ NOTE: It runs in the context of a new connection-thread (`host.consumingThread`)
105
+ it is necessary as the `host.chHostHeartbeat.start_consuming()` function is **blocking**
106
+ """
107
+
108
+ while host.running:
109
+ print(f"{host.appNameTextWithContext('_start_consuming')} started")
110
+ # https://pika.readthedocs.io/en/stable/modules/adapters/blocking.html#pika.adapters.blocking_connection.BlockingChannel.start_consuming
111
+ host.chHostHeartbeat.start_consuming()
112
+ print(f'{host.appNameTextWithContext("_start_consuming")} finished')
113
+ # time.sleep(0.001)
114
+ # NOTE: this will delay stopping when the stop_consuming() is triggered. We can avoid it with more clever algorithm
115
+ time.sleep(0.1)
116
+ # time.sleep(1)
117
+ # time.sleep(2)
118
+
119
+ def start_consuming(host: IColaboFlowHostData):
120
+ print(f"{host.appNameTextWithContext('start_consuming')} starting '_start_consuming' as a separate thread to avoid blocking the current ({chalk.blue('the message handling')}) thread")
121
+ host.consumingThread = threading.Thread(target=_start_consuming, args=(host, ))
122
+ host.consumingThread.start()
123
+ native_id = host.consumingThread.native_id
124
+ print(f"{host.appNameTextWithContext('start_consuming')} OK, the '_start_consuming' thread (with the native native_id: {chalk.blue.bold(native_id)} ) is spawned")
125
+
126
+ def _stop_consuming(host: IColaboFlowHostData):
127
+ print(f"{host.appNameTextWithContext('_stop_consuming')} stopping consuming")
128
+ host.chHostHeartbeat.stop_consuming()
129
+ host.running = False
130
+ print(f"{host.appNameTextWithContext('_stop_consuming')} stopped consuming")
131
+
132
+ def stop_consuming(host: IColaboFlowHostData):
133
+ print(f"{host.appNameTextWithContext('stop_consuming')} launching _stop_consuming in the connection-thread")
134
+ host.connection.add_callback_threadsafe(lambda: _stop_consuming(host))
135
+
136
+ def _basic_publish(host: IColaboFlowHostData, sendToQueue: str, msg: IColaboFlowGoMsg):
137
+ print(f'{host.appNameTextWithContext("_basic_publish")} sending to the "{sendToQueue}" queue, the message: {msg}')
138
+ msgStr = json.dumps(msg)
139
+ host.chHostHeartbeat.basic_publish(exchange='', routing_key=sendToQueue, body=msgStr)
140
+
141
+ async def processColaboFlowMsg_TaskExecute(host: IColaboFlowHostData, msgServiceReqObj: IColaboFlowGoMsg):
142
+ msgServiceTaskExecuteReqObjExtension: IColaboFlowGoMsgExtension_TaskExecute_Request = from_dict(data_class=IColaboFlowGoMsgExtension_TaskExecute_Request, data=msgServiceReqObj.extension)
143
+
144
+ taskId: str = msgServiceTaskExecuteReqObjExtension.taskId
145
+ taskInput: Any = msgServiceTaskExecuteReqObjExtension.taskInput
146
+ queueReplyTo: str = msgServiceReqObj.replyTo
147
+ if not queueReplyTo:
148
+ queueReplyTo = host.queueHostHeartbeat
149
+
150
+ task: IFlowTask = host.tasksAvailable[taskId]
151
+
152
+ if not task:
153
+ print(f'{host.appNameTextWithContext("processColaboFlowMsg_TaskExecute")} task is missing for the id: {taskId}')
154
+
155
+ print(f'{host.appNameTextWithContext("processColaboFlowMsg_TaskExecute")} Executing id: {chalk.blue_bright(taskId)}, task.description: {task.description}')
156
+
157
+ taskInstanceId: str = f'taskId:lang-{LANGUAGE}:host-{host.hostName}:{uuid.uuid1()}'
158
+ taskInstance: IFlowTaskInstance = createTaskInstanceForTaskWithoutFlow(task)
159
+ taskInstance.id = taskInstanceId
160
+ host.taskInstances[taskId] = taskInstance
161
+ host.runningTaskInstancesInfos[taskId] = IColaboFlowGoTaskInstanceInfo(
162
+ id = taskInstanceId,
163
+ taskInstance = taskInstance,
164
+ )
165
+
166
+ if not task.executorRef or not task.executorRef.id:
167
+ print(f'{host.appNameTextWithContext("processColaboFlowMsg_TaskExecute")} Executor ID is not provided for the task: {taskId}')
168
+ return
169
+
170
+ taskExecutor: ITaskExecutor = getTaskExecutor(host, task.executorRef.id)
171
+ print(f'{host.appNameTextWithContext("processColaboFlowMsg_TaskExecute")} taskExecutor: {taskExecutor}')
172
+
173
+ # *************************
174
+ # REPLYING THE TASK PROGRESS (task instance id)
175
+ # *************************/
176
+ msgTaskExecutionProgress: IColaboFlowGoMsg = createGoMsg(host.hostName, EColaboFlowGoMsgType.TASK_EXECUTE_PROGRESS)
177
+ msgTaskExecutionProgress.extension = IColaboFlowGoMsgExtension_TaskExecute_Progress(
178
+ taskInstanceId = taskInstanceId,
179
+ status = ETaskExecute_Progress_Status.INITIALIZED,
180
+ progress = 0,
181
+ )
182
+ msgTaskExecutionProgress.msg = f"Returning task execution for the taskId: '{taskId}' over queue: '{queueReplyTo}'"
183
+
184
+ msgTaskExecutionProgressDict: Any = dataclasses.asdict(msgTaskExecutionProgress)
185
+
186
+ if reportsConfig.showExecutionMsgs:
187
+ print(f'{host.appNameTextWithContext("processColaboFlowMsg_TaskExecute")} Sending PROGRESS to the task execution requester (service) [queue: "{chalk.blue_bright(queueReplyTo)}"]: {json.dumps(msgTaskExecutionProgressDict)}')
188
+
189
+ _basic_publish(host, queueReplyTo, msgTaskExecutionProgressDict)
190
+ # host.connection.add_callback_threadsafe(lambda: _basic_publish(host, queueReplyTo, msgTaskExecutionProgressDict))
191
+ # host.chHostHeartbeat.basic_publish(exchange='', routing_key=queueReplyTo, body=msgTaskExecutionProgressDict)
192
+ # # host.connection.add_callback_threadsafe(
193
+ # # functools.partial(host.chHostHeartbeat.basic_publish, exchange='', routing_key=host.queueHostHeartbeat, body=heartbeat.to_json()))
194
+
195
+ # *************************
196
+ # EXECUTING THE TASK
197
+ # *************************/
198
+ """ task execution output """
199
+ taskOutput: Any
200
+ if taskExecutor.reference.async_method:
201
+ print(f'{host.appNameTextWithContext("processColaboFlowMsg_TaskExecute")} executing async executor (taskExecutor.reference.async_method)')
202
+ taskOutput = await taskExecutor.reference.async_method(taskInput)
203
+ elif taskExecutor.reference.method:
204
+ print(f'{host.appNameTextWithContext("processColaboFlowMsg_TaskExecute")} executing sync executor (taskExecutor.reference.method)')
205
+ taskOutput = taskExecutor.reference.method(taskInput)
206
+ else:
207
+ errorMsg = f'{host.appNameTextWithContext("processColaboFlowMsg_TaskExecute")} Error, neither async nor non-async executor reference available for taskId: {taskId} and executorId: "{taskExecutor.id}"'
208
+ print(errorMsg)
209
+ raise Exception(errorMsg)
210
+
211
+ print(f'{host.appNameTextWithContext("processColaboFlowMsg_TaskExecute")} task executed. Result is: {chalk.blue_bright(taskOutput)}')
212
+
213
+ msgTaskExecutionReply: IColaboFlowGoMsg = createGoMsg(host.hostName, EColaboFlowGoMsgType.TASK_EXECUTE_RESPONSE)
214
+ msgTaskExecutionReply.requestId = msgServiceReqObj.requestId
215
+ msgTaskExecutionReply.msgReplyChainIds = [msgServiceReqObj.id]
216
+ msgTaskExecutionReply.extension = IColaboFlowGoMsgExtension_TaskExecute_Response(
217
+ taskOutput = taskOutput,
218
+ )
219
+ msgTaskExecutionReply.msg = f"Returning task execution for the taskId: '{taskId}' over queue: '{queueReplyTo}'"
220
+
221
+ msgTaskExecutionProgressDict: Any = dataclasses.asdict(msgTaskExecutionProgress)
222
+
223
+ if reportsConfig.showExecutionMsgs:
224
+ print(f'{host.appNameTextWithContext("processColaboFlowMsg_TaskExecute")} Sending RESPONSE to the task execution requester (service) [queue: "{chalk.blue_bright(queueReplyTo)}"]: {msgTaskExecutionReply}')
225
+
226
+ msgTaskExecutionReplyDict: Any = dataclasses.asdict(msgTaskExecutionReply)
227
+ _basic_publish(host, queueReplyTo, msgTaskExecutionReplyDict)
228
+
229
+ def processColaboFlowMsg_TaskInstancesReport(host: IColaboFlowHostData, msg: IColaboFlowGoMsg):
230
+ pass
231
+
232
+ def listenOnHostQueue(host: IColaboFlowHostData):
233
+ # Listener (consumer)
234
+ print(f'{host.appNameTextWithContext("listenOnHostQueue")} Listening on the queue: "{chalk.blue_bright(host.queueHost)}"')
235
+ print(f'{host.appNameTextWithContext("listenOnHostQueue")} [*] Waiting for messages in %s. To exit press "{chalk.blue_bright("CTRL+C")}"')
236
+
237
+ def callback_host_msg_request(ch, method, properties, body):
238
+ """
239
+ A callback invited when a message with host request from the ColaboFlow service is received
240
+
241
+ NOTE: It runs in the context of a new connection-thread (`host.consumingThread`)
242
+ """
243
+ # print(f"{host.appNameTextWithContext('callback_host_msg_request')} Received {body}")
244
+ msgObj: Any = json.loads(body)
245
+ print(f"{host.appNameTextWithContext('callback_host_msg_request')} Received {msgObj}")
246
+ # https://github.com/konradhalas/dacite#casting
247
+ msg: IColaboFlowGoMsg = from_dict(data_class=IColaboFlowGoMsg, data=msgObj,
248
+ config=Config(cast=[EColaboFlowGoMsgType])
249
+ )
250
+ print(f'{host.appNameTextWithContext("callback_host_msg_request")} msg.sender: "{chalk.blue_bright(msg.sender)}", msg.type: "{chalk.blue_bright(msg.type)}, msg.msg: "{chalk.blue_bright(msg.msg)}"')
251
+
252
+ # print(f'{host.appNameTextWithContext("callback_host_msg_request")} futTaskExecute: "{futTaskExecute}"')
253
+ # # set the `futTaskExecute` result in the context of the main-thread
254
+ # loop.call_soon_threadsafe(callback_host_msg_request_set_result, futTaskExecute, msg["extension"]["taskOutput"])
255
+
256
+ if msg.type == EColaboFlowGoMsgType.TASK_EXECUTE_REQUEST:
257
+ if host.processOrchestratorTaskExecuteRequests:
258
+ asyncio.run(processColaboFlowMsg_TaskExecute(host, msg))
259
+ elif msg.type == EColaboFlowGoMsgType.TASK_INSTANCES_REPORT__REQUEST:
260
+ processColaboFlowMsg_TaskInstancesReport(host, msg)
261
+
262
+ # https://www.rabbitmq.com/tutorials/tutorial-six-python.html
263
+ # https://github.com/rabbitmq/rabbitmq-tutorials/blob/main/python/rpc_server.py
264
+ ch.basic_ack(delivery_tag=method.delivery_tag)
265
+ print(f'{host.appNameTextWithContext("callback_host_msg_request")} msg is acknowledged back')
266
+
267
+ # Note: prefetch is set to 1 here as an example only and to keep the number of threads created
268
+ # to a reasonable amount. In production you will want to test with different prefetch values
269
+ # to find which one provides the best performance and usability for your solution
270
+ host.chHostHeartbeat.basic_qos(prefetch_count=1)
271
+ # host.chHostHeartbeat.basic_qos(prefetch_count=2)
272
+
273
+ # https://pika.readthedocs.io/en/stable/modules/channel.html#pika.channel.Channel.basic_consume
274
+ # https://stackoverflow.com/questions/50404273/python-tutorial-code-from-rabbitmq-failing-to-run
275
+ # on_message_callback = functools.partial(on_message, args=(host, ))
276
+ # host.chHostHeartbeat.basic_consume(on_message_callback=on_message_callback, queue='standard')
277
+ host.hostMsgRequestConsumerTag = host.chHostHeartbeat.basic_consume(on_message_callback=callback_host_msg_request, queue=host.queueHost, auto_ack=False)
278
+
279
+ """
280
+ * sends heartbeat messages back to the ColaboFlow service
281
+ * to
282
+ * 1. know the host exists
283
+ * 2. know or update (not implemented yet) the available task executors
284
+ """
285
+ def sendHeartbeatsToHost(host: IColaboFlowHostData):
286
+ # https://stackoverflow.com/a/37512537/257561
287
+ async def runHeartbeat():
288
+ print(f"{host.appNameTextWithContext('sendHeartbeatsToHost')} started emitting, host.running: {host.running}")
289
+ while host.running:
290
+ # print(f"{host.appNameTextWithContext('sendHeartbeatsToHost')} running for host.heartbeatId: {host.heartbeatId}")
291
+ sendHeartbeatToHost(host)
292
+ # print(f"{host.appNameTextWithContext('sendHeartbeatsToHost')} sent for host.heartbeatId: {host.heartbeatId}")
293
+ await asyncio.sleep(1)
294
+ # print(f"{host.appNameTextWithContext('sendHeartbeatsToHost')} woke up for host.heartbeatId: {host.heartbeatId}")
295
+ print(f"{appNameTextWithContext('sendHeartbeatsToHost')} stopped emitting, host.running: {host.running}")
296
+
297
+ # def stop():
298
+ # task.cancel()
299
+
300
+ # asyncio.run(runHeartbeat())
301
+ loop = asyncio.get_event_loop()
302
+ # loop.call_later(5, stop)
303
+ runHeartbeatTask = loop.create_task(runHeartbeat())
304
+
305
+ # try:
306
+ # loop.run_until_complete(runHeartbeatTask)
307
+ # except asyncio.CancelledError:
308
+ # pass
309
+
310
+ """
311
+ sends a single heartbeat message back to the ColaboFlow service
312
+ It is invited by the `sendHeartbeatsToHost` function
313
+ """
314
+ def sendHeartbeatToHost(host: IColaboFlowHostData):
315
+ # TODO: support listening for the heartbeat reply and set the timeout after we should send a warning/error on no response
316
+ heartbeat: IColaboFlowGoMsg = createGoMsg(host.hostName, EColaboFlowGoMsgType.HEARTBEAT)
317
+ heartbeat.extension = {
318
+ "id": host.heartbeatId,
319
+ "queueHost": host.queueHost,
320
+ "language": EProgrammingLanguageSupported.PYTHON,
321
+ "taskIds": list(host.taskExecutorsAvailable.keys()),
322
+ }
323
+ heartbeat.msg = f"node host with tasks: {json.dumps(list(host.taskExecutorsAvailable.keys()))}",
324
+ host.heartbeatId = host.heartbeatId + 1
325
+
326
+ if reportsConfig.showHeartbeatMsgs:
327
+ print(f"{host.appNameTextWithContext('sendHeartbeatToHost')} Sending heartbeat [queue: '{chalk.blue_bright(host.queueHostHeartbeat)}']: {json.dumps(heartbeat.to_json())}")
328
+
329
+ # host.chHostHeartbeat.basic_publish(exchange='', routing_key=host.queueHostHeartbeat, body=heartbeat.to_json())
330
+ # host.connection.add_callback_threadsafe(
331
+ # functools.partial(host.chHostHeartbeat.basic_publish, exchange='', routing_key=host.queueHostHeartbeat, body=heartbeat.to_json()))
332
+ host.connection.add_callback_threadsafe(lambda: _sendHeartbeatToHost(host, heartbeat))
333
+
334
+ def _sendHeartbeatToHost(host: IColaboFlowHostData, heartbeat: IColaboFlowGoMsg):
335
+ if reportsConfig.showHeartbeatMsgs:
336
+ print(f"{host.appNameTextWithContext('_sendHeartbeatToHost')} Sending heartbeat [queue: '{chalk.blue_bright(host.queueHostHeartbeat)}']: {json.dumps(heartbeat.to_json())}")
337
+ host.chHostHeartbeat.basic_publish(exchange='', routing_key=host.queueHostHeartbeat, body=heartbeat.to_json())
338
+
339
+ def close(host: IColaboFlowHostData):
340
+ host.running = False
341
+ if(host.hostMsgRequestConsumerTag):
342
+ # host.chHostHeartbeat.basic_cancel(host.hostMsgRequestConsumerTag)
343
+ host.connection.add_callback_threadsafe(lambda: host.chHostHeartbeat.basic_cancel(host.hostMsgRequestConsumerTag))
344
+ host.consumingThread.join()
345
+ # print(f"{host.appNameTextWithContext('close')} Closing the {chalk.bold.italic('channel')} to the ColaboFlow service...")
346
+ # host.chHostHeartbeat.close()
347
+ # print(f"{host.appNameTextWithContext('close')} Closing the {chalk.bold.italic('connection')} to the ColaboFlow service...")
348
+ # host.connection.close()
@@ -0,0 +1,16 @@
1
+ # https://docs.python.org/3/library/uuid.html
2
+ import uuid
3
+ from lib.vos import ( EColaboFlowGoMsgType, IColaboFlowGoMsg )
4
+
5
+ def createGoMsg(sender: str, type: EColaboFlowGoMsgType) -> IColaboFlowGoMsg:
6
+ msg = IColaboFlowGoMsg(
7
+ id = f"ColaboFlow-msg:{uuid.uuid1()}",
8
+ requestId = f"ColaboFlow-request:{uuid.uuid1()}",
9
+ sender = sender,
10
+ # replyTo = "test",
11
+ proxies = [],
12
+ msgReplyChainIds = [],
13
+ type = type,
14
+ )
15
+
16
+ return msg
@@ -0,0 +1,17 @@
1
+ import { EColaboFlowGoMsgType, IColaboFlowGoMsg } from "./vos";
2
+ // https://stackoverflow.com/a/62841516/257561
3
+ // import uuidv1 from "uuid/v1";
4
+ import {v1 as uuidv1} from "uuid";
5
+
6
+ export const createGoMsg = (sender: string, type: EColaboFlowGoMsgType): IColaboFlowGoMsg => {
7
+ const msg: IColaboFlowGoMsg = {
8
+ id: `ColaboFlow-msg:${uuidv1()}`,
9
+ requestId: `ColaboFlow-request:${uuidv1()}`,
10
+ sender,
11
+ proxies: [],
12
+ msgReplyChainIds: [],
13
+ type,
14
+ };
15
+
16
+ return msg;
17
+ };
package/lib/params.ts ADDED
@@ -0,0 +1 @@
1
+ export const MODULE_NAME: string = "@colabo-flow/s-go";
package/lib/vos.py ADDED
@@ -0,0 +1,232 @@
1
+ # describes types used in the ColaboFlow.GO puzzle
2
+
3
+ from dataclasses import dataclass
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 typing import NamedTuple
24
+ import threading
25
+
26
+ from pika.channel import Channel
27
+ from pika.connection import Connection
28
+ from lib.executor_vos import ITaskExecutor, IFlowTask, IFlowTaskInstance
29
+
30
+ @dataclass
31
+ class ReportsConfig:
32
+ """Reports Configuration Data Class."""
33
+ showHeartbeatMsgs: bool
34
+ showReportsMsgs: bool
35
+ showExecutionMsgs: bool
36
+
37
+ @dataclass
38
+ class ConnectConfig:
39
+ """Connect Configuration Data Class."""
40
+
41
+ APP_NAME: str
42
+ AMQP_URL: str
43
+ ORCHESTRATOR_QUEUE: str
44
+ HOST_HEARTBEAT_QUEUE: str
45
+ HOST_QUEUE: str
46
+
47
+
48
+ # PY > 3.4
49
+ class EColaboFlowGoMsgType(str, Enum):
50
+ TASK_EXECUTE_REQUEST = "TASK_EXECUTE_REQUEST",
51
+ TASK_EXECUTE_PROGRESS = "TASK_EXECUTE_PROGRESS",
52
+ TASK_EXECUTE_RESPONSE = "TASK_EXECUTE_RESPONSE",
53
+ TASK_INSTANCES_REPORT__REQUEST = "TASK_INSTANCES_REPORT__REQUEST",
54
+ TASK_INSTANCES_REPORT__RESPONSE = "TASK_INSTANCES_REPORT__RESPONSE",
55
+ HEARTBEAT = "HEARTBEAT",
56
+
57
+ """
58
+ enumeration of all the languages that are supported by ColaboFlow
59
+ """
60
+ class EProgrammingLanguageSupported(str, Enum):
61
+ """Javascript or its extensions that will be compiled to JavaScript eventually (TypeScript, Coffeescript)"""
62
+ JAVASCRIPT = "JAVASCRIPT",
63
+ PYTHON = "PYTHON",
64
+ NATIVE = "NATIVE",
65
+
66
+ @dataclass
67
+ class IColaboFlowGoMsg:
68
+ """An interface describing messages exchanged between ColaboFlow.GO peers"""
69
+ """ unique message id """
70
+ id: str
71
+ type: EColaboFlowGoMsgType;
72
+ """ unique request id, should be kept the same along the course of a same single message exchange """
73
+ requestId: str
74
+ """ the id of the message sender """
75
+ sender: str
76
+ """ the name of the queue to reply to (if there is a reply to the message) """
77
+ replyTo: str = None
78
+ """ the list of proxies that forwarded the message """
79
+ # PY > 3.9
80
+ proxies: Optional[list[str]] = None
81
+ """ list of msg ids with the history of the replying messages """
82
+ msgReplyChainIds: Optional[list[str]] = None
83
+ """ str message that can be used for human purpose mainly """
84
+ msg: Optional[str] = None
85
+
86
+ """ extension for various types of messages """
87
+ extension: Optional[Any] = None
88
+
89
+ def to_json(self):
90
+ return json.dumps(self.__dict__)
91
+
92
+ @dataclass
93
+ class IColaboFlowGoMsgExtension_TaskExecute_Request():
94
+ taskId: str
95
+ taskInput: Optional[Any] = None
96
+
97
+ def to_json(self):
98
+ return json.dumps(self.__dict__)
99
+
100
+ class ETaskExecute_Progress_Status(str, Enum):
101
+ INITIALIZED = "INITIALIZED",
102
+
103
+ """Message extension for the task execution request"""
104
+ @dataclass
105
+ class IColaboFlowGoMsgExtension_TaskExecute_Request:
106
+ """ the id if the task executing instance """
107
+ taskId: str;
108
+
109
+ """input to the task we want to execute"""
110
+ taskInput: Any;
111
+
112
+ def to_json(self):
113
+ return json.dumps(self.__dict__)
114
+
115
+ """Message extension for the task execution progress"""
116
+ @dataclass
117
+ class IColaboFlowGoMsgExtension_TaskExecute_Progress:
118
+ """ the id if the task executing instance """
119
+ taskInstanceId: str
120
+ """ the current status of the task execution """
121
+ status: ETaskExecute_Progress_Status
122
+ """ the percentage of the task executed """
123
+ progress: float
124
+
125
+ def to_json(self):
126
+ return json.dumps(self.__dict__)
127
+
128
+ """Message extension for the task execution response"""
129
+ @dataclass
130
+ class IColaboFlowGoMsgExtension_TaskExecute_Response:
131
+ """ output of the executed task """
132
+ taskOutput: Any
133
+
134
+ def to_json(self):
135
+ return json.dumps(self.__dict__)
136
+
137
+ """ Provides all required info about the task execution request and its progress, etc """
138
+ @dataclass
139
+ class IColaboFlowGoTaskInstanceInfo():
140
+ """ taskInstance id """
141
+ id: str
142
+ """ task instance """
143
+ taskInstance: IFlowTaskInstance
144
+
145
+ """ contains all the data that are necessary for a ColaboFlow.Go host to operate """
146
+ class IColaboFlowHostData():
147
+ hostName: str
148
+ amqpUrl: str
149
+ queueHost: str
150
+ queueHostHeartbeat: str
151
+ connection: Optional[Connection] = None
152
+ consumingThread: threading.Thread = None
153
+ chHostHeartbeat: Optional[Channel] = None
154
+ hostMsgRequestConsumerTag: Optional[str] = None
155
+ """
156
+ the service heartbeat counter
157
+ """
158
+ heartbeatId: int = 0
159
+ sendHeartbeat: bool = True
160
+ listenForOrchestratorRequests: bool = True
161
+ processOrchestratorTaskExecuteRequests: bool = True
162
+
163
+ taskExecutorsAvailable: dict[str, ITaskExecutor] = {}
164
+ tasksAvailable: dict[str, IFlowTask] = {}
165
+ taskInstances: dict[str, IFlowTaskInstance] = {}
166
+ threads: list[int] = []
167
+
168
+ running: bool = False
169
+
170
+ """
171
+ Provides all required info about the task execution requests (except the executed ones) coming for this particular host and its progress, etc
172
+ Provides all required info about the task execution request and its progress, etc
173
+ ***record key*** is the `id` of the `taskInstance`
174
+ """
175
+ runningTaskInstancesInfos: dict[str, IColaboFlowGoTaskInstanceInfo] = {}
176
+
177
+ """
178
+ Provides all required info about the finalized (finished, stopped, failed, ...) task execution requests coming for this particular host and its progress, etc
179
+ Provides all required info about the task execution request and its progress, etc
180
+ ***record key*** is the `id` of the `taskInstance`
181
+ """
182
+ finalizedTaskInstancesInfos: dict[str, IColaboFlowGoTaskInstanceInfo]
183
+
184
+ def __init__(self, hostName, appNameText, appNameTextWithContext, amqpUrl, queueHost, queueHostHeartbeat, queueServiceOrchestrator, sendHeartbeat = True, listenForOrchestratorRequests = True, processOrchestratorTaskExecuteRequests = True):
185
+ self.hostName = hostName
186
+ self.appNameText = appNameText
187
+ self.appNameTextWithContext = appNameTextWithContext
188
+ self.amqpUrl = amqpUrl
189
+ self.queueHost = queueHost
190
+ self.queueHostHeartbeat = queueHostHeartbeat
191
+ self.queueServiceOrchestrator = queueServiceOrchestrator
192
+ self.sendHeartbeat = sendHeartbeat
193
+ self.listenForOrchestratorRequests = listenForOrchestratorRequests
194
+ self.processOrchestratorTaskExecuteRequests = processOrchestratorTaskExecuteRequests
195
+
196
+ """
197
+ Contains all the data that are necessary for a ColaboFlow.Go client to operate
198
+ """
199
+ class IColaboFlowClientData():
200
+ clientName: str
201
+
202
+ appNameText: Optional[str]
203
+
204
+ appNameTextWithContext: Optional[Callable]
205
+
206
+ amqpUrl: str
207
+
208
+ queueServiceOrchestrator: str
209
+
210
+ taskInstances: dict[str, IFlowTaskInstance]
211
+
212
+ connection: Optional[Connection] = None
213
+
214
+ channel: Optional[Channel] = None
215
+
216
+ running: bool = False
217
+
218
+ consumingThread: threading.Thread = None
219
+ eventsThread: threading.Thread = None
220
+
221
+ consumerTag = None
222
+
223
+ def __init__(self, clientName, appNameText, appNameTextWithContext, amqpUrl, queueServiceOrchestrator, taskInstances={}, connection=None, channel=None):
224
+ self.clientName = clientName
225
+ self.appNameText = appNameText
226
+ self.appNameTextWithContext = appNameTextWithContext
227
+ self.amqpUrl = amqpUrl
228
+ self.queueServiceOrchestrator = queueServiceOrchestrator
229
+ self.taskInstances = taskInstances
230
+ self.connection = connection
231
+ self.channel = channel
232
+