@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.
Files changed (124) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +142 -0
  3. package/dist/index.d.ts +13 -8
  4. package/dist/index.js +28 -8
  5. package/dist/src/call-step-file.d.ts +17 -2
  6. package/dist/src/call-step-file.js +88 -47
  7. package/dist/src/cron-handler.d.ts +13 -0
  8. package/dist/src/cron-handler.js +98 -0
  9. package/dist/src/event-manager.js +10 -5
  10. package/dist/src/flows-config-endpoint.d.ts +2 -0
  11. package/dist/src/flows-config-endpoint.js +51 -0
  12. package/dist/src/flows-endpoint.d.ts +11 -7
  13. package/dist/src/flows-endpoint.js +53 -22
  14. package/dist/src/generate-trace-id.d.ts +2 -0
  15. package/dist/src/generate-trace-id.js +14 -0
  16. package/dist/src/get-step-config.d.ts +4 -0
  17. package/dist/src/get-step-config.js +88 -0
  18. package/dist/src/guards.d.ts +3 -2
  19. package/dist/src/guards.js +3 -1
  20. package/dist/src/locked-data.d.ts +60 -0
  21. package/dist/src/locked-data.js +278 -0
  22. package/dist/src/logger-factory.d.ts +15 -0
  23. package/dist/src/logger-factory.js +14 -0
  24. package/dist/src/logger.d.ts +21 -15
  25. package/dist/src/logger.js +49 -29
  26. package/dist/src/mermaid-generator.d.ts +4 -0
  27. package/dist/src/mermaid-generator.js +203 -0
  28. package/dist/src/node/get-config.d.ts +1 -2
  29. package/dist/src/node/get-config.js +51 -8
  30. package/dist/src/node/logger.d.ts +10 -6
  31. package/dist/src/node/logger.js +27 -16
  32. package/dist/src/node/middleware-compose.d.ts +1 -0
  33. package/dist/src/node/middleware-compose.js +12 -0
  34. package/dist/src/node/node-runner.js +28 -9
  35. package/dist/src/node/rpc-state-manager.d.ts +3 -2
  36. package/dist/src/node/rpc-state-manager.js +5 -2
  37. package/dist/src/node/rpc.d.ts +3 -1
  38. package/dist/src/node/rpc.js +21 -3
  39. package/dist/src/pretty-print.d.ts +1 -0
  40. package/dist/src/pretty-print.js +66 -0
  41. package/dist/src/printer.d.ts +45 -0
  42. package/dist/src/printer.js +121 -0
  43. package/dist/src/process-communication/communication-config.d.ts +7 -0
  44. package/dist/src/process-communication/communication-config.js +12 -0
  45. package/dist/src/process-communication/process-manager.d.ts +30 -0
  46. package/dist/src/process-communication/process-manager.js +88 -0
  47. package/dist/src/process-communication/rpc-processor-interface.d.ts +9 -0
  48. package/dist/src/process-communication/rpc-processor-interface.js +2 -0
  49. package/dist/src/python/communication_factory.py +35 -0
  50. package/dist/src/python/context.py +21 -0
  51. package/dist/src/python/get-config.py +31 -13
  52. package/dist/src/python/ipc_communication.py +145 -0
  53. package/dist/src/python/logger.py +4 -6
  54. package/dist/src/python/middleware.py +17 -0
  55. package/dist/src/python/python-runner.py +105 -39
  56. package/dist/src/python/rpc.py +33 -68
  57. package/dist/src/python/rpc_communication.py +125 -0
  58. package/dist/src/python/rpc_state_manager.py +49 -11
  59. package/dist/src/python/type_definitions.py +34 -0
  60. package/dist/src/python/validation.py +56 -0
  61. package/dist/src/ruby/get-config.rb +61 -0
  62. package/dist/src/ruby/logger.rb +21 -16
  63. package/dist/src/ruby/rpc.rb +118 -0
  64. package/dist/src/ruby/rpc_state_manager.rb +41 -0
  65. package/dist/src/ruby/ruby-runner.rb +94 -0
  66. package/dist/src/server.d.ts +14 -12
  67. package/dist/src/server.js +149 -28
  68. package/dist/src/socket-server.d.ts +39 -0
  69. package/dist/src/socket-server.js +76 -0
  70. package/dist/src/state/adapters/default-state-adapter.d.ts +7 -3
  71. package/dist/src/state/adapters/default-state-adapter.js +37 -14
  72. package/dist/src/state/adapters/memory-state-adapter.d.ts +14 -0
  73. package/dist/src/state/adapters/memory-state-adapter.js +58 -0
  74. package/dist/src/state/create-state-adapter.d.ts +5 -6
  75. package/dist/src/state/create-state-adapter.js +2 -10
  76. package/dist/src/state/state-adapter.d.ts +4 -4
  77. package/dist/src/state-stream.d.ts +19 -0
  78. package/dist/src/state-stream.js +28 -0
  79. package/dist/src/step-handler-rpc-processor.d.ts +13 -4
  80. package/dist/src/step-handler-rpc-processor.js +33 -3
  81. package/dist/src/step-handler-rpc-stdin-processor.d.ts +22 -0
  82. package/dist/src/step-handler-rpc-stdin-processor.js +84 -0
  83. package/dist/src/step-handlers.d.ts +7 -2
  84. package/dist/src/step-handlers.js +47 -19
  85. package/dist/src/step-validator.d.ts +14 -0
  86. package/dist/src/step-validator.js +138 -0
  87. package/dist/src/steps/emit.step.d.ts +11 -0
  88. package/dist/src/steps/emit.step.js +27 -0
  89. package/dist/src/steps/emit.step.ts +34 -0
  90. package/dist/src/steps/index.d.ts +2 -0
  91. package/dist/src/steps/index.js +16 -0
  92. package/dist/src/streams/api-endpoints.d.ts +2 -0
  93. package/dist/src/streams/api-endpoints.js +71 -0
  94. package/dist/src/streams/flows-stream.d.ts +14 -0
  95. package/dist/src/streams/flows-stream.js +29 -0
  96. package/dist/src/streams/logs-stream.d.ts +16 -0
  97. package/dist/src/streams/logs-stream.js +22 -0
  98. package/dist/src/types/generate-type-from-schema.d.ts +2 -0
  99. package/dist/src/types/generate-type-from-schema.js +28 -0
  100. package/dist/src/types/generate-types-from-response.d.ts +2 -0
  101. package/dist/src/types/generate-types-from-response.js +13 -0
  102. package/dist/src/types/generate-types.d.ts +12 -0
  103. package/dist/src/types/generate-types.js +108 -0
  104. package/dist/src/types/merge-schemas.d.ts +3 -0
  105. package/dist/src/types/merge-schemas.js +59 -0
  106. package/dist/src/types/schema.types.d.ts +20 -0
  107. package/dist/src/types/schema.types.js +10 -0
  108. package/dist/src/types-stream.d.ts +34 -0
  109. package/dist/src/types-stream.js +2 -0
  110. package/dist/src/types.d.ts +93 -47
  111. package/dist/src/utils.d.ts +2 -0
  112. package/dist/src/utils.js +12 -0
  113. package/package.json +20 -9
  114. package/requirements.txt +1 -0
  115. package/dist/src/node/get-module-export.d.ts +0 -1
  116. package/dist/src/node/get-module-export.js +0 -63
  117. package/dist/src/python/get-python-config.d.ts +0 -2
  118. package/dist/src/python/get-python-config.js +0 -34
  119. package/dist/src/ruby/get_config.rb +0 -78
  120. package/dist/src/ruby/ruby_runner.rb +0 -80
  121. package/dist/src/ruby/state_adapter.rb +0 -62
  122. package/dist/src/state/adapters/redis-state-adapter.d.ts +0 -19
  123. package/dist/src/state/adapters/redis-state-adapter.js +0 -44
  124. 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], file_path: str, sender: RpcSender):
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.file_name = file_path.split('/')[-1]
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
- # Convert SimpleNamespace to dict if needed
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.sender.send_no_wait('log', log_entry)
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
- from logger import Logger
7
- from rpc import RpcSender
8
- from rpc_state_manager import RpcStateManager
5
+ import asyncio
6
+ import traceback
7
+ from typing import Optional, Any, Callable, List, Dict
9
8
 
10
- from typing import Any
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) -> Any:
13
- from types import SimpleNamespace
14
-
15
+ def parse_args(arg: str) -> Dict:
16
+ """Parse command line arguments into HandlerArgs"""
15
17
  try:
16
- return json.loads(arg, object_hook=lambda d: SimpleNamespace(**d))
18
+ return json.loads(arg)
17
19
  except json.JSONDecodeError:
18
20
  print('Error parsing args:', arg)
19
21
  return arg
20
22
 
21
- class Context:
22
- def __init__(self, args: Any, file_name: str):
23
- self.trace_id = args.traceId
24
- self.flows = args.flows
25
- self.file_name = file_name
26
- self.sender = RpcSender()
27
- self.state = RpcStateManager(self.sender)
28
- self.logger = Logger(self.trace_id, self.flows, self.file_name, self.sender)
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
- async def emit(self, event: Any):
31
- await self.sender.send('emit', event)
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
- async def run_python_module(file_path: str, args: Any) -> None:
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
- # Construct path relative to steps directory
36
- flows_dir = os.path.join(os.getcwd(), 'steps')
37
- module_path = os.path.join(flows_dir, file_path)
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
- # Load the module dynamically
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 {module_path}")
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
- # Check if the handler function exists
48
- if not hasattr(module, 'handler'):
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
- context = Context(args, file_path)
52
- context.sender.init()
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
- await module.handler(args.data, context)
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('Usage: python pythonRunner.py <file-path> <arg>', file=sys.stderr)
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
- import asyncio
73
- asyncio.run(run_python_module(file_path, parse_args(arg)))
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)
@@ -1,80 +1,45 @@
1
1
  import uuid
2
2
  import asyncio
3
- import os
4
3
  import json
5
4
  import sys
6
- from typing import Any, Dict, Tuple
7
-
8
- # get the FD from ENV
9
- NODEIPCFD = int(os.environ["NODE_CHANNEL_FD"])
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.pending_requests: Dict[str, Tuple[asyncio.Future, str, Any]] = {}
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
- 'type': 'rpc_request',
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
- future = asyncio.Future()
28
- request_id = str(uuid.uuid4())
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
- # Read messages from Node IPC file descriptor
63
- async def read_messages():
64
- while True:
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
- # Start message reading loop
80
- asyncio.create_task(read_messages())
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()