@motiadev/core 0.0.6 → 0.0.7-build.20250529215343
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.
- package/LICENSE +21 -0
- package/README.md +142 -0
- package/dist/index.d.ts +13 -8
- package/dist/index.js +28 -8
- package/dist/src/call-step-file.d.ts +17 -2
- package/dist/src/call-step-file.js +88 -47
- package/dist/src/cron-handler.d.ts +13 -0
- package/dist/src/cron-handler.js +98 -0
- package/dist/src/event-manager.js +10 -5
- package/dist/src/flows-config-endpoint.d.ts +2 -0
- package/dist/src/flows-config-endpoint.js +51 -0
- package/dist/src/flows-endpoint.d.ts +11 -7
- package/dist/src/flows-endpoint.js +53 -22
- package/dist/src/generate-trace-id.d.ts +2 -0
- package/dist/src/generate-trace-id.js +14 -0
- package/dist/src/get-step-config.d.ts +4 -0
- package/dist/src/get-step-config.js +88 -0
- package/dist/src/guards.d.ts +3 -2
- package/dist/src/guards.js +3 -1
- package/dist/src/locked-data.d.ts +60 -0
- package/dist/src/locked-data.js +278 -0
- package/dist/src/logger-factory.d.ts +15 -0
- package/dist/src/logger-factory.js +14 -0
- package/dist/src/logger.d.ts +21 -15
- package/dist/src/logger.js +49 -29
- package/dist/src/mermaid-generator.d.ts +4 -0
- package/dist/src/mermaid-generator.js +203 -0
- package/dist/src/node/get-config.d.ts +1 -2
- package/dist/src/node/get-config.js +51 -8
- package/dist/src/node/logger.d.ts +10 -6
- package/dist/src/node/logger.js +27 -16
- package/dist/src/node/middleware-compose.d.ts +1 -0
- package/dist/src/node/middleware-compose.js +12 -0
- package/dist/src/node/node-runner.js +28 -9
- package/dist/src/node/rpc-state-manager.d.ts +3 -2
- package/dist/src/node/rpc-state-manager.js +5 -2
- package/dist/src/node/rpc.d.ts +3 -1
- package/dist/src/node/rpc.js +21 -3
- package/dist/src/pretty-print.d.ts +1 -0
- package/dist/src/pretty-print.js +66 -0
- package/dist/src/printer.d.ts +45 -0
- package/dist/src/printer.js +121 -0
- package/dist/src/process-communication/communication-config.d.ts +7 -0
- package/dist/src/process-communication/communication-config.js +12 -0
- package/dist/src/process-communication/process-manager.d.ts +30 -0
- package/dist/src/process-communication/process-manager.js +88 -0
- package/dist/src/process-communication/rpc-processor-interface.d.ts +9 -0
- package/dist/src/process-communication/rpc-processor-interface.js +2 -0
- package/dist/src/python/communication_factory.py +35 -0
- package/dist/src/python/context.py +21 -0
- package/dist/src/python/get-config.py +31 -13
- package/dist/src/python/ipc_communication.py +145 -0
- package/dist/src/python/logger.py +4 -6
- package/dist/src/python/middleware.py +17 -0
- package/dist/src/python/python-runner.py +105 -39
- package/dist/src/python/rpc.py +33 -68
- package/dist/src/python/rpc_communication.py +125 -0
- package/dist/src/python/rpc_state_manager.py +49 -11
- package/dist/src/python/type_definitions.py +34 -0
- package/dist/src/python/validation.py +56 -0
- package/dist/src/ruby/get-config.rb +61 -0
- package/dist/src/ruby/logger.rb +21 -16
- package/dist/src/ruby/rpc.rb +118 -0
- package/dist/src/ruby/rpc_state_manager.rb +41 -0
- package/dist/src/ruby/ruby-runner.rb +94 -0
- package/dist/src/server.d.ts +14 -12
- package/dist/src/server.js +149 -28
- package/dist/src/socket-server.d.ts +39 -0
- package/dist/src/socket-server.js +76 -0
- package/dist/src/state/adapters/default-state-adapter.d.ts +7 -3
- package/dist/src/state/adapters/default-state-adapter.js +37 -14
- package/dist/src/state/adapters/memory-state-adapter.d.ts +14 -0
- package/dist/src/state/adapters/memory-state-adapter.js +58 -0
- package/dist/src/state/create-state-adapter.d.ts +5 -6
- package/dist/src/state/create-state-adapter.js +2 -10
- package/dist/src/state/state-adapter.d.ts +4 -4
- package/dist/src/state-stream.d.ts +19 -0
- package/dist/src/state-stream.js +28 -0
- package/dist/src/step-handler-rpc-processor.d.ts +13 -4
- package/dist/src/step-handler-rpc-processor.js +33 -3
- package/dist/src/step-handler-rpc-stdin-processor.d.ts +22 -0
- package/dist/src/step-handler-rpc-stdin-processor.js +84 -0
- package/dist/src/step-handlers.d.ts +7 -2
- package/dist/src/step-handlers.js +47 -19
- package/dist/src/step-validator.d.ts +14 -0
- package/dist/src/step-validator.js +138 -0
- package/dist/src/steps/emit.step.d.ts +11 -0
- package/dist/src/steps/emit.step.js +27 -0
- package/dist/src/steps/emit.step.ts +34 -0
- package/dist/src/steps/index.d.ts +2 -0
- package/dist/src/steps/index.js +16 -0
- package/dist/src/streams/api-endpoints.d.ts +2 -0
- package/dist/src/streams/api-endpoints.js +71 -0
- package/dist/src/streams/flows-stream.d.ts +14 -0
- package/dist/src/streams/flows-stream.js +29 -0
- package/dist/src/streams/logs-stream.d.ts +16 -0
- package/dist/src/streams/logs-stream.js +22 -0
- package/dist/src/types/generate-type-from-schema.d.ts +2 -0
- package/dist/src/types/generate-type-from-schema.js +28 -0
- package/dist/src/types/generate-types-from-response.d.ts +2 -0
- package/dist/src/types/generate-types-from-response.js +13 -0
- package/dist/src/types/generate-types.d.ts +12 -0
- package/dist/src/types/generate-types.js +108 -0
- package/dist/src/types/merge-schemas.d.ts +3 -0
- package/dist/src/types/merge-schemas.js +59 -0
- package/dist/src/types/schema.types.d.ts +20 -0
- package/dist/src/types/schema.types.js +10 -0
- package/dist/src/types-stream.d.ts +34 -0
- package/dist/src/types-stream.js +2 -0
- package/dist/src/types.d.ts +93 -47
- package/dist/src/utils.d.ts +2 -0
- package/dist/src/utils.js +12 -0
- package/package.json +20 -9
- package/requirements.txt +1 -0
- package/dist/src/node/get-module-export.d.ts +0 -1
- package/dist/src/node/get-module-export.js +0 -63
- package/dist/src/python/get-python-config.d.ts +0 -2
- package/dist/src/python/get-python-config.js +0 -34
- package/dist/src/ruby/get_config.rb +0 -78
- package/dist/src/ruby/ruby_runner.rb +0 -80
- package/dist/src/ruby/state_adapter.rb +0 -62
- package/dist/src/state/adapters/redis-state-adapter.d.ts +0 -19
- package/dist/src/state/adapters/redis-state-adapter.js +0 -44
- package/tsconfig.json +0 -20
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import uuid
|
|
2
|
+
import asyncio
|
|
3
|
+
import json
|
|
4
|
+
import sys
|
|
5
|
+
import os
|
|
6
|
+
from typing import Any, Dict, Optional, Callable
|
|
7
|
+
|
|
8
|
+
def serialize_for_json(obj: Any) -> Any:
|
|
9
|
+
"""Convert Python objects to JSON-serializable types"""
|
|
10
|
+
if hasattr(obj, '__dict__'):
|
|
11
|
+
return obj.__dict__
|
|
12
|
+
elif hasattr(obj, '_asdict'):
|
|
13
|
+
return obj._asdict()
|
|
14
|
+
elif isinstance(obj, (list, tuple)):
|
|
15
|
+
return [serialize_for_json(item) for item in obj]
|
|
16
|
+
elif isinstance(obj, dict):
|
|
17
|
+
return {k: serialize_for_json(v) for k, v in obj.items()}
|
|
18
|
+
else:
|
|
19
|
+
return obj
|
|
20
|
+
|
|
21
|
+
class IpcCommunication:
|
|
22
|
+
"""IPC communication using file descriptors"""
|
|
23
|
+
|
|
24
|
+
def __init__(self):
|
|
25
|
+
self.executing = True
|
|
26
|
+
self.pending_requests: Dict[str, asyncio.Future] = {}
|
|
27
|
+
self.ipc_reader_task: Optional[asyncio.Task] = None
|
|
28
|
+
self.message_handlers: Dict[str, Callable] = {}
|
|
29
|
+
self.ipc_fd: Optional[int] = None
|
|
30
|
+
|
|
31
|
+
# Get IPC file descriptor
|
|
32
|
+
if "NODE_CHANNEL_FD" in os.environ:
|
|
33
|
+
try:
|
|
34
|
+
self.ipc_fd = int(os.environ["NODE_CHANNEL_FD"])
|
|
35
|
+
except (ValueError, TypeError):
|
|
36
|
+
raise RuntimeError("Invalid NODE_CHANNEL_FD environment variable")
|
|
37
|
+
else:
|
|
38
|
+
raise RuntimeError("NODE_CHANNEL_FD environment variable not found")
|
|
39
|
+
|
|
40
|
+
def send_no_wait(self, method: str, args: Any) -> None:
|
|
41
|
+
"""Send IPC request without waiting for response"""
|
|
42
|
+
request = {
|
|
43
|
+
'type': 'rpc_request',
|
|
44
|
+
'method': method,
|
|
45
|
+
'args': args
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
try:
|
|
49
|
+
json_str = json.dumps(request, default=serialize_for_json)
|
|
50
|
+
message_bytes = (json_str + "\n").encode('utf-8')
|
|
51
|
+
os.write(self.ipc_fd, message_bytes)
|
|
52
|
+
except Exception as e:
|
|
53
|
+
print(f"ERROR: Failed to send IPC request: {e}", file=sys.stderr)
|
|
54
|
+
|
|
55
|
+
async def send(self, method: str, args: Any) -> Any:
|
|
56
|
+
"""Send IPC request and wait for response"""
|
|
57
|
+
request_id = str(uuid.uuid4())
|
|
58
|
+
future = asyncio.Future()
|
|
59
|
+
self.pending_requests[request_id] = future
|
|
60
|
+
|
|
61
|
+
request = {
|
|
62
|
+
'type': 'rpc_request',
|
|
63
|
+
'id': request_id,
|
|
64
|
+
'method': method,
|
|
65
|
+
'args': args
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
try:
|
|
69
|
+
json_str = json.dumps(request, default=serialize_for_json)
|
|
70
|
+
message_bytes = (json_str + "\n").encode('utf-8')
|
|
71
|
+
os.write(self.ipc_fd, message_bytes)
|
|
72
|
+
except Exception as e:
|
|
73
|
+
future.set_exception(e)
|
|
74
|
+
return await future
|
|
75
|
+
|
|
76
|
+
return await future
|
|
77
|
+
|
|
78
|
+
def _handle_message(self, msg: Dict[str, Any]) -> None:
|
|
79
|
+
"""Handle incoming message from Node.js"""
|
|
80
|
+
msg_type = msg.get('type')
|
|
81
|
+
|
|
82
|
+
if msg_type == 'rpc_response':
|
|
83
|
+
request_id = msg.get('id')
|
|
84
|
+
if request_id in self.pending_requests:
|
|
85
|
+
future = self.pending_requests[request_id]
|
|
86
|
+
del self.pending_requests[request_id]
|
|
87
|
+
|
|
88
|
+
error = msg.get('error')
|
|
89
|
+
if error is not None:
|
|
90
|
+
future.set_exception(Exception(str(error)))
|
|
91
|
+
else:
|
|
92
|
+
future.set_result(msg.get('result'))
|
|
93
|
+
|
|
94
|
+
elif msg_type in self.message_handlers:
|
|
95
|
+
try:
|
|
96
|
+
self.message_handlers[msg_type](msg)
|
|
97
|
+
except Exception as e:
|
|
98
|
+
print(f"ERROR: Handler for {msg_type} failed: {e}", file=sys.stderr)
|
|
99
|
+
|
|
100
|
+
async def _read_ipc(self) -> None:
|
|
101
|
+
"""Read messages from IPC file descriptor in background"""
|
|
102
|
+
loop = asyncio.get_event_loop()
|
|
103
|
+
buffer = ""
|
|
104
|
+
|
|
105
|
+
while self.executing:
|
|
106
|
+
try:
|
|
107
|
+
data = await loop.run_in_executor(None, os.read, self.ipc_fd, 4096)
|
|
108
|
+
if not data:
|
|
109
|
+
break
|
|
110
|
+
|
|
111
|
+
buffer += data.decode('utf-8')
|
|
112
|
+
lines = buffer.split('\n')
|
|
113
|
+
buffer = lines[-1] # Keep incomplete line in buffer
|
|
114
|
+
|
|
115
|
+
for line in lines[:-1]:
|
|
116
|
+
if line.strip():
|
|
117
|
+
try:
|
|
118
|
+
msg = json.loads(line.strip())
|
|
119
|
+
self._handle_message(msg)
|
|
120
|
+
except json.JSONDecodeError as e:
|
|
121
|
+
print(f"WARNING: Failed to parse JSON: {e}", file=sys.stderr)
|
|
122
|
+
|
|
123
|
+
except OSError:
|
|
124
|
+
# IPC channel closed
|
|
125
|
+
break
|
|
126
|
+
except Exception as e:
|
|
127
|
+
print(f"ERROR: Reading IPC failed: {e}", file=sys.stderr)
|
|
128
|
+
await asyncio.sleep(0.1)
|
|
129
|
+
|
|
130
|
+
async def init(self) -> None:
|
|
131
|
+
"""Initialize IPC communication"""
|
|
132
|
+
if not self.ipc_reader_task:
|
|
133
|
+
self.ipc_reader_task = asyncio.create_task(self._read_ipc())
|
|
134
|
+
|
|
135
|
+
def close(self) -> None:
|
|
136
|
+
"""Close IPC communication"""
|
|
137
|
+
self.executing = False
|
|
138
|
+
|
|
139
|
+
for future in self.pending_requests.values():
|
|
140
|
+
if not future.done():
|
|
141
|
+
future.set_exception(Exception("IPC connection closed"))
|
|
142
|
+
self.pending_requests.clear()
|
|
143
|
+
|
|
144
|
+
if self.ipc_reader_task and not self.ipc_reader_task.done():
|
|
145
|
+
self.ipc_reader_task.cancel()
|
|
@@ -3,11 +3,10 @@ from typing import Any, Dict, Optional
|
|
|
3
3
|
from rpc import RpcSender
|
|
4
4
|
|
|
5
5
|
class Logger:
|
|
6
|
-
def __init__(self, trace_id: str, flows: list[str],
|
|
6
|
+
def __init__(self, trace_id: str, flows: list[str], rpc: RpcSender):
|
|
7
7
|
self.trace_id = trace_id
|
|
8
8
|
self.flows = flows
|
|
9
|
-
self.
|
|
10
|
-
self.sender = sender
|
|
9
|
+
self.rpc = rpc
|
|
11
10
|
|
|
12
11
|
def _log(self, level: str, message: str, args: Optional[Dict[str, Any]] = None) -> None:
|
|
13
12
|
log_entry = {
|
|
@@ -15,19 +14,18 @@ class Logger:
|
|
|
15
14
|
"time": int(time.time() * 1000),
|
|
16
15
|
"traceId": self.trace_id,
|
|
17
16
|
"flows": self.flows,
|
|
18
|
-
"file": self.file_name,
|
|
19
17
|
"msg": message
|
|
20
18
|
}
|
|
21
19
|
|
|
22
20
|
if args:
|
|
23
|
-
#
|
|
21
|
+
# Use our serializer to ensure args are JSON-serializable
|
|
24
22
|
if hasattr(args, '__dict__'):
|
|
25
23
|
args = vars(args)
|
|
26
24
|
elif not isinstance(args, dict):
|
|
27
25
|
args = {"data": args}
|
|
28
26
|
log_entry.update(args)
|
|
29
27
|
|
|
30
|
-
self.
|
|
28
|
+
self.rpc.send_no_wait('log', log_entry)
|
|
31
29
|
|
|
32
30
|
def info(self, message: str, args: Optional[Any] = None) -> None:
|
|
33
31
|
self._log("info", message, args)
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from typing import Any, Callable
|
|
2
|
+
from functools import reduce
|
|
3
|
+
from context import Context
|
|
4
|
+
|
|
5
|
+
def compose_middleware(*middlewares):
|
|
6
|
+
"""Compose multiple middleware functions into a single middleware"""
|
|
7
|
+
def compose_two(f: Callable, g: Callable) -> Callable:
|
|
8
|
+
async def composed(data: Any, context: Context, next_fn: Callable):
|
|
9
|
+
async def wrapped_next(d=data):
|
|
10
|
+
return await g(d, context, next_fn)
|
|
11
|
+
return await f(data, context, wrapped_next)
|
|
12
|
+
return composed
|
|
13
|
+
|
|
14
|
+
if not middlewares:
|
|
15
|
+
return lambda data, context, next_fn: next_fn()
|
|
16
|
+
|
|
17
|
+
return reduce(compose_two, middlewares)
|
|
@@ -1,73 +1,139 @@
|
|
|
1
1
|
import sys
|
|
2
2
|
import json
|
|
3
3
|
import importlib.util
|
|
4
|
-
import traceback
|
|
5
4
|
import os
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
from
|
|
5
|
+
import asyncio
|
|
6
|
+
import traceback
|
|
7
|
+
from typing import Optional, Any, Callable, List, Dict
|
|
9
8
|
|
|
10
|
-
from
|
|
9
|
+
from rpc import RpcSender
|
|
10
|
+
from type_definitions import FlowConfig, ApiResponse
|
|
11
|
+
from context import Context
|
|
12
|
+
from validation import validate_with_jsonschema
|
|
13
|
+
from middleware import compose_middleware
|
|
11
14
|
|
|
12
|
-
def parse_args(arg: str) ->
|
|
13
|
-
|
|
14
|
-
|
|
15
|
+
def parse_args(arg: str) -> Dict:
|
|
16
|
+
"""Parse command line arguments into HandlerArgs"""
|
|
15
17
|
try:
|
|
16
|
-
return json.loads(arg
|
|
18
|
+
return json.loads(arg)
|
|
17
19
|
except json.JSONDecodeError:
|
|
18
20
|
print('Error parsing args:', arg)
|
|
19
21
|
return arg
|
|
20
22
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
23
|
+
async def validate_handler_input(
|
|
24
|
+
module: Any,
|
|
25
|
+
args: Dict,
|
|
26
|
+
context: Context,
|
|
27
|
+
is_api_handler: bool
|
|
28
|
+
) -> Optional[ApiResponse]:
|
|
29
|
+
"""Validate handler input based on module configuration"""
|
|
30
|
+
if not hasattr(args, "contextInFirstArg") or hasattr(module, "config"):
|
|
31
|
+
return None
|
|
32
|
+
|
|
33
|
+
config: FlowConfig = module.config
|
|
34
|
+
input_data = args.get("data")
|
|
29
35
|
|
|
30
|
-
|
|
31
|
-
|
|
36
|
+
if is_api_handler and hasattr(input_data, "body") and hasattr(config, "bodySchema"):
|
|
37
|
+
body = input_data.get("body", {})
|
|
38
|
+
body_schema = config.get("bodySchema", {})
|
|
39
|
+
validation_result = validate_with_jsonschema(body, body_schema)
|
|
32
40
|
|
|
33
|
-
|
|
41
|
+
if not validation_result["success"]:
|
|
42
|
+
return ApiResponse(
|
|
43
|
+
status=400,
|
|
44
|
+
body={"message": f'Input validation error: {validation_result["error"]}'}
|
|
45
|
+
)
|
|
46
|
+
input_data.body = validation_result['data']
|
|
47
|
+
|
|
48
|
+
elif not is_api_handler and config.input is not None:
|
|
49
|
+
validation_result = validate_with_jsonschema(input_data, config.get("input", {}))
|
|
50
|
+
|
|
51
|
+
if not validation_result["success"]:
|
|
52
|
+
context.logger.info(f'Input Validation Error: {validation_result["error"]}', validation_result['details'])
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
input_data = validation_result["data"]
|
|
56
|
+
|
|
57
|
+
return None
|
|
58
|
+
|
|
59
|
+
async def run_python_module(file_path: str, rpc: RpcSender, args: Dict) -> None:
|
|
60
|
+
"""Execute a Python module with the given arguments"""
|
|
34
61
|
try:
|
|
35
|
-
|
|
36
|
-
flows_dir = os.path.
|
|
37
|
-
|
|
62
|
+
module_dir = os.path.dirname(os.path.abspath(file_path))
|
|
63
|
+
flows_dir = os.path.dirname(module_dir)
|
|
64
|
+
|
|
65
|
+
for path in [module_dir, flows_dir]:
|
|
66
|
+
if path not in sys.path:
|
|
67
|
+
sys.path.insert(0, path)
|
|
38
68
|
|
|
39
|
-
|
|
40
|
-
spec = importlib.util.spec_from_file_location("dynamic_module", module_path)
|
|
69
|
+
spec = importlib.util.spec_from_file_location("dynamic_module", file_path)
|
|
41
70
|
if spec is None or spec.loader is None:
|
|
42
|
-
raise ImportError(f"Could not load module from {
|
|
71
|
+
raise ImportError(f"Could not load module from {file_path}")
|
|
43
72
|
|
|
44
73
|
module = importlib.util.module_from_spec(spec)
|
|
74
|
+
module.__package__ = os.path.basename(module_dir)
|
|
45
75
|
spec.loader.exec_module(module)
|
|
46
76
|
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
raise AttributeError(f"Function 'handler' not found in module {module_path}")
|
|
77
|
+
if not hasattr(module, "handler"):
|
|
78
|
+
raise AttributeError(f"Function 'handler' not found in module {file_path}")
|
|
50
79
|
|
|
51
|
-
|
|
52
|
-
|
|
80
|
+
config = module.config
|
|
81
|
+
is_api_handler = (config and config.get("type") == "api")
|
|
82
|
+
|
|
83
|
+
trace_id = args.get("traceId")
|
|
84
|
+
flows = args.get("flows") or []
|
|
85
|
+
data = args.get("data")
|
|
86
|
+
context_in_first_arg = args.get("contextInFirstArg")
|
|
87
|
+
context = Context(trace_id, flows, rpc)
|
|
88
|
+
|
|
89
|
+
validation_result = await validate_handler_input(module, args, context, is_api_handler)
|
|
90
|
+
if validation_result:
|
|
91
|
+
await rpc.send('result', validation_result)
|
|
92
|
+
return
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
middlewares: List[Callable] = config.get("middleware", [])
|
|
96
|
+
composed_middleware = compose_middleware(*middlewares)
|
|
53
97
|
|
|
54
|
-
|
|
98
|
+
async def handler_fn():
|
|
99
|
+
if context_in_first_arg:
|
|
100
|
+
return await module.handler(context)
|
|
101
|
+
else:
|
|
102
|
+
return await module.handler(data, context)
|
|
103
|
+
|
|
104
|
+
result = await composed_middleware(data, context, handler_fn)
|
|
105
|
+
|
|
106
|
+
if not is_api_handler:
|
|
107
|
+
pending = asyncio.all_tasks() - {asyncio.current_task()}
|
|
108
|
+
if pending:
|
|
109
|
+
await asyncio.gather(*pending)
|
|
110
|
+
|
|
111
|
+
if result:
|
|
112
|
+
await rpc.send('result', result)
|
|
113
|
+
|
|
114
|
+
rpc.send_no_wait("close", None)
|
|
115
|
+
rpc.close()
|
|
55
116
|
|
|
56
|
-
# exit with 0 to indicate success
|
|
57
|
-
sys.exit(0)
|
|
58
117
|
except Exception as error:
|
|
59
|
-
print('Error running Python module:', file=sys.stderr)
|
|
60
|
-
|
|
118
|
+
print(f'Error running Python module: {error}', file=sys.stderr)
|
|
61
119
|
traceback.print_exc(file=sys.stderr)
|
|
62
120
|
sys.exit(1)
|
|
63
121
|
|
|
64
122
|
if __name__ == "__main__":
|
|
65
123
|
if len(sys.argv) < 2:
|
|
66
|
-
print(
|
|
124
|
+
print("Usage: python pythonRunner.py <file-path> <arg>", file=sys.stderr)
|
|
67
125
|
sys.exit(1)
|
|
68
126
|
|
|
69
127
|
file_path = sys.argv[1]
|
|
70
128
|
arg = sys.argv[2] if len(sys.argv) > 2 else None
|
|
71
129
|
|
|
72
|
-
|
|
73
|
-
|
|
130
|
+
rpc = RpcSender()
|
|
131
|
+
try:
|
|
132
|
+
loop = asyncio.get_running_loop()
|
|
133
|
+
except RuntimeError:
|
|
134
|
+
loop = asyncio.new_event_loop()
|
|
135
|
+
asyncio.set_event_loop(loop)
|
|
136
|
+
|
|
137
|
+
args = parse_args(arg) if arg else None
|
|
138
|
+
tasks = asyncio.gather(rpc.init(), run_python_module(file_path, rpc, args))
|
|
139
|
+
loop.run_until_complete(tasks)
|
package/dist/src/python/rpc.py
CHANGED
|
@@ -1,80 +1,45 @@
|
|
|
1
1
|
import uuid
|
|
2
2
|
import asyncio
|
|
3
|
-
import os
|
|
4
3
|
import json
|
|
5
4
|
import sys
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
5
|
+
import os
|
|
6
|
+
import platform
|
|
7
|
+
from typing import Any, Dict, Optional, Callable, Union
|
|
8
|
+
from communication_factory import create_communication
|
|
9
|
+
from rpc_communication import RpcCommunication
|
|
10
|
+
from ipc_communication import IpcCommunication
|
|
11
|
+
|
|
12
|
+
def serialize_for_json(obj: Any) -> Any:
|
|
13
|
+
"""Convert Python objects to JSON-serializable types"""
|
|
14
|
+
if hasattr(obj, '__dict__'):
|
|
15
|
+
return obj.__dict__
|
|
16
|
+
elif hasattr(obj, '_asdict'): # For namedtuples
|
|
17
|
+
return obj._asdict()
|
|
18
|
+
elif isinstance(obj, (list, tuple)):
|
|
19
|
+
return [serialize_for_json(item) for item in obj]
|
|
20
|
+
elif isinstance(obj, dict):
|
|
21
|
+
return {k: serialize_for_json(v) for k, v in obj.items()}
|
|
22
|
+
else:
|
|
23
|
+
return obj
|
|
10
24
|
|
|
11
25
|
class RpcSender:
|
|
26
|
+
"""Unified communication interface that delegates to appropriate implementation"""
|
|
27
|
+
|
|
12
28
|
def __init__(self):
|
|
13
|
-
self.
|
|
14
|
-
|
|
29
|
+
self._communication: Union[RpcCommunication, IpcCommunication] = create_communication()
|
|
30
|
+
|
|
15
31
|
def send_no_wait(self, method: str, args: Any) -> None:
|
|
16
|
-
request
|
|
17
|
-
|
|
18
|
-
'method': method,
|
|
19
|
-
'args': args
|
|
20
|
-
}
|
|
21
|
-
# encode message as json string + newline in bytes
|
|
22
|
-
bytesMessage = (json.dumps(request) + "\n").encode('utf-8')
|
|
23
|
-
# send message
|
|
24
|
-
os.write(NODEIPCFD, bytesMessage)
|
|
32
|
+
"""Send request without waiting for response"""
|
|
33
|
+
return self._communication.send_no_wait(method, args)
|
|
25
34
|
|
|
26
35
|
async def send(self, method: str, args: Any) -> Any:
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
self.pending_requests[request_id] = (future, method, args)
|
|
30
|
-
|
|
31
|
-
request = {
|
|
32
|
-
'type': 'rpc_request',
|
|
33
|
-
'id': request_id,
|
|
34
|
-
'method': method,
|
|
35
|
-
'args': args
|
|
36
|
-
}
|
|
37
|
-
# encode message as json string + newline in bytes
|
|
38
|
-
bytesMessage = (json.dumps(request) + "\n").encode('utf-8')
|
|
39
|
-
# send message
|
|
40
|
-
os.write(NODEIPCFD, bytesMessage)
|
|
41
|
-
|
|
42
|
-
return future
|
|
43
|
-
|
|
44
|
-
def init(self):
|
|
45
|
-
def on_message(msg: Dict[str, Any]):
|
|
46
|
-
if msg.get('type') == 'rpc_response':
|
|
47
|
-
request_id = msg['id']
|
|
48
|
-
|
|
49
|
-
if request_id in self.pending_requests:
|
|
50
|
-
future, _, _ = self.pending_requests[request_id]
|
|
51
|
-
|
|
52
|
-
if msg.get('error'):
|
|
53
|
-
future.set_exception(msg['error'])
|
|
54
|
-
elif msg.get('result'):
|
|
55
|
-
future.set_result(msg['result'])
|
|
56
|
-
else:
|
|
57
|
-
# It's a void response
|
|
58
|
-
future.set_result(None)
|
|
59
|
-
|
|
60
|
-
del self.pending_requests[request_id]
|
|
36
|
+
"""Send request and wait for response"""
|
|
37
|
+
return await self._communication.send(method, args)
|
|
61
38
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
# Read message from pipe
|
|
66
|
-
message = os.read(NODEIPCFD, 4096).decode('utf-8')
|
|
67
|
-
if not message:
|
|
68
|
-
continue
|
|
69
|
-
|
|
70
|
-
# Parse messages (may be multiple due to buffering)
|
|
71
|
-
for line in message.splitlines():
|
|
72
|
-
if line:
|
|
73
|
-
try:
|
|
74
|
-
msg = json.loads(line)
|
|
75
|
-
on_message(msg)
|
|
76
|
-
except json.JSONDecodeError:
|
|
77
|
-
pass
|
|
39
|
+
async def init(self) -> None:
|
|
40
|
+
"""Initialize communication"""
|
|
41
|
+
return await self._communication.init()
|
|
78
42
|
|
|
79
|
-
|
|
80
|
-
|
|
43
|
+
def close(self) -> None:
|
|
44
|
+
"""Close communication"""
|
|
45
|
+
return self._communication.close()
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import uuid
|
|
2
|
+
import asyncio
|
|
3
|
+
import json
|
|
4
|
+
import sys
|
|
5
|
+
from typing import Any, Dict, Optional, Callable
|
|
6
|
+
|
|
7
|
+
def serialize_for_json(obj: Any) -> Any:
|
|
8
|
+
"""Convert Python objects to JSON-serializable types"""
|
|
9
|
+
if hasattr(obj, '__dict__'):
|
|
10
|
+
return obj.__dict__
|
|
11
|
+
elif hasattr(obj, '_asdict'):
|
|
12
|
+
return obj._asdict()
|
|
13
|
+
elif isinstance(obj, (list, tuple)):
|
|
14
|
+
return [serialize_for_json(item) for item in obj]
|
|
15
|
+
elif isinstance(obj, dict):
|
|
16
|
+
return {k: serialize_for_json(v) for k, v in obj.items()}
|
|
17
|
+
else:
|
|
18
|
+
return obj
|
|
19
|
+
|
|
20
|
+
class RpcCommunication:
|
|
21
|
+
"""RPC communication using stdin/stdout"""
|
|
22
|
+
|
|
23
|
+
def __init__(self):
|
|
24
|
+
self.executing = True
|
|
25
|
+
self.pending_requests: Dict[str, asyncio.Future] = {}
|
|
26
|
+
self.stdin_reader_task: Optional[asyncio.Task] = None
|
|
27
|
+
self.message_handlers: Dict[str, Callable] = {}
|
|
28
|
+
|
|
29
|
+
def send_no_wait(self, method: str, args: Any) -> None:
|
|
30
|
+
"""Send RPC request without waiting for response"""
|
|
31
|
+
request = {
|
|
32
|
+
'type': 'rpc_request',
|
|
33
|
+
'method': method,
|
|
34
|
+
'args': args
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
try:
|
|
38
|
+
json_str = json.dumps(request, default=serialize_for_json)
|
|
39
|
+
print(json_str, flush=True)
|
|
40
|
+
except Exception as e:
|
|
41
|
+
print(f"ERROR: Failed to send RPC request: {e}", file=sys.stderr)
|
|
42
|
+
|
|
43
|
+
async def send(self, method: str, args: Any) -> Any:
|
|
44
|
+
"""Send RPC request and wait for response"""
|
|
45
|
+
request_id = str(uuid.uuid4())
|
|
46
|
+
future = asyncio.Future()
|
|
47
|
+
self.pending_requests[request_id] = future
|
|
48
|
+
|
|
49
|
+
request = {
|
|
50
|
+
'type': 'rpc_request',
|
|
51
|
+
'id': request_id,
|
|
52
|
+
'method': method,
|
|
53
|
+
'args': args
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
try:
|
|
57
|
+
json_str = json.dumps(request, default=serialize_for_json)
|
|
58
|
+
print(json_str, flush=True)
|
|
59
|
+
except Exception as e:
|
|
60
|
+
future.set_exception(e)
|
|
61
|
+
return await future
|
|
62
|
+
|
|
63
|
+
return await future
|
|
64
|
+
|
|
65
|
+
def _handle_message(self, msg: Dict[str, Any]) -> None:
|
|
66
|
+
"""Handle incoming message from Node.js"""
|
|
67
|
+
msg_type = msg.get('type')
|
|
68
|
+
|
|
69
|
+
if msg_type == 'rpc_response':
|
|
70
|
+
request_id = msg.get('id')
|
|
71
|
+
if request_id in self.pending_requests:
|
|
72
|
+
future = self.pending_requests[request_id]
|
|
73
|
+
del self.pending_requests[request_id]
|
|
74
|
+
|
|
75
|
+
error = msg.get('error')
|
|
76
|
+
if error is not None:
|
|
77
|
+
future.set_exception(Exception(str(error)))
|
|
78
|
+
else:
|
|
79
|
+
future.set_result(msg.get('result'))
|
|
80
|
+
|
|
81
|
+
elif msg_type in self.message_handlers:
|
|
82
|
+
try:
|
|
83
|
+
self.message_handlers[msg_type](msg)
|
|
84
|
+
except Exception as e:
|
|
85
|
+
print(f"ERROR: Handler for {msg_type} failed: {e}", file=sys.stderr)
|
|
86
|
+
|
|
87
|
+
async def _read_stdin(self) -> None:
|
|
88
|
+
"""Read messages from stdin in background"""
|
|
89
|
+
loop = asyncio.get_event_loop()
|
|
90
|
+
|
|
91
|
+
while self.executing:
|
|
92
|
+
try:
|
|
93
|
+
line = await loop.run_in_executor(None, sys.stdin.readline)
|
|
94
|
+
|
|
95
|
+
if not line:
|
|
96
|
+
break
|
|
97
|
+
|
|
98
|
+
line = line.strip()
|
|
99
|
+
if line:
|
|
100
|
+
try:
|
|
101
|
+
msg = json.loads(line)
|
|
102
|
+
self._handle_message(msg)
|
|
103
|
+
except json.JSONDecodeError as e:
|
|
104
|
+
print(f"WARNING: Failed to parse JSON: {e}", file=sys.stderr)
|
|
105
|
+
|
|
106
|
+
except Exception as e:
|
|
107
|
+
print(f"ERROR: Reading stdin failed: {e}", file=sys.stderr)
|
|
108
|
+
await asyncio.sleep(0.1)
|
|
109
|
+
|
|
110
|
+
async def init(self) -> None:
|
|
111
|
+
"""Initialize RPC communication"""
|
|
112
|
+
if not self.stdin_reader_task:
|
|
113
|
+
self.stdin_reader_task = asyncio.create_task(self._read_stdin())
|
|
114
|
+
|
|
115
|
+
def close(self) -> None:
|
|
116
|
+
"""Close RPC communication"""
|
|
117
|
+
self.executing = False
|
|
118
|
+
|
|
119
|
+
for future in self.pending_requests.values():
|
|
120
|
+
if not future.done():
|
|
121
|
+
future.set_exception(Exception("RPC connection closed"))
|
|
122
|
+
self.pending_requests.clear()
|
|
123
|
+
|
|
124
|
+
if self.stdin_reader_task and not self.stdin_reader_task.done():
|
|
125
|
+
self.stdin_reader_task.cancel()
|