grpc-frame 0.5.13__py3-none-any.whl
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.
- grpc_frame/__init__.py +45 -0
- grpc_frame/adapter.py +188 -0
- grpc_frame/device_proxy.py +179 -0
- grpc_frame/dispatch_core.py +113 -0
- grpc_frame/event_bus.py +181 -0
- grpc_frame/grpc_client.py +469 -0
- grpc_frame/grpc_com.py +555 -0
- grpc_frame/grpc_server.py +450 -0
- grpc_frame/make_pyi.py +275 -0
- grpc_frame/make_pyi_device_proxy.py +90 -0
- grpc_frame/util/__init__.py +0 -0
- grpc_frame/util/build_proto.py +165 -0
- grpc_frame/util/build_proto_ctrl.py +74 -0
- grpc_frame/util/build_proto_events.py +75 -0
- grpc_frame/util/clean_proto.py +44 -0
- grpc_frame/util/clean_site_packages.py +120 -0
- grpc_frame/util/install_requirements_py37.py +27 -0
- grpc_frame-0.5.13.dist-info/METADATA +34 -0
- grpc_frame-0.5.13.dist-info/RECORD +22 -0
- grpc_frame-0.5.13.dist-info/WHEEL +5 -0
- grpc_frame-0.5.13.dist-info/licenses/LICENSE +201 -0
- grpc_frame-0.5.13.dist-info/top_level.txt +1 -0
grpc_frame/__init__.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
# --- ctrl gRPC スタブ
|
|
6
|
+
from grpc_frame import ctrl_pb2 as _ctrl_pb2
|
|
7
|
+
from grpc_frame import ctrl_pb2_grpc as _ctrl_pb2_grpc
|
|
8
|
+
|
|
9
|
+
# ctrl_pb2 を トップレベル名として解決できるように
|
|
10
|
+
sys.modules["ctrl_pb2"] = _ctrl_pb2
|
|
11
|
+
sys.modules["ctrl_pb2_grpc"] = _ctrl_pb2_grpc
|
|
12
|
+
|
|
13
|
+
# --- events ---
|
|
14
|
+
from grpc_frame import events_pb2 as _events_pb2
|
|
15
|
+
from grpc_frame import events_pb2_grpc as _events_pb2_grpc
|
|
16
|
+
|
|
17
|
+
sys.modules["events_pb2"] = _events_pb2
|
|
18
|
+
sys.modules["events_pb2_grpc"] = _events_pb2_grpc
|
|
19
|
+
|
|
20
|
+
# --- public API (client) ---
|
|
21
|
+
from grpc_frame.grpc_client import AsyncGrpcClient
|
|
22
|
+
from grpc_frame.grpc_client import SyncGrpcClient
|
|
23
|
+
from grpc_frame.grpc_client import GrpcClient
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
# --- public API (DeviceProxy) ---
|
|
27
|
+
from grpc_frame.device_proxy import DeviceProxyEntry
|
|
28
|
+
from grpc_frame.device_proxy import register_device_proxy
|
|
29
|
+
from grpc_frame.device_proxy import unregister_device_proxy
|
|
30
|
+
from grpc_frame.device_proxy import get_device_proxy_entry
|
|
31
|
+
from grpc_frame.device_proxy import list_device_proxies
|
|
32
|
+
from grpc_frame.device_proxy import DeviceProxy
|
|
33
|
+
from grpc_frame.device_proxy import create_device_proxy
|
|
34
|
+
|
|
35
|
+
# --- public API for COM (server) ---
|
|
36
|
+
from grpc_frame.grpc_com import ComExecutionRunner
|
|
37
|
+
from grpc_frame.grpc_com import ThreadSafeCtrlProxy
|
|
38
|
+
|
|
39
|
+
# --- public API (server) ---
|
|
40
|
+
from grpc_frame.grpc_server import _ControlServicer
|
|
41
|
+
from grpc_frame.dispatch_core import *
|
|
42
|
+
from grpc_frame.adapter import *
|
|
43
|
+
|
|
44
|
+
# --- pyi generation ---
|
|
45
|
+
from grpc_frame.make_pyi import generate_client_pyi
|
grpc_frame/adapter.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
引数表現は adapter の「JSON優先 + pickleフォールバック」
|
|
5
|
+
adapter.pack_args/pack_kwargs/pack_result は
|
|
6
|
+
|
|
7
|
+
1. JSON 変換を試す(bytes は base64 で JSON に入れる)
|
|
8
|
+
2. 失敗したら pickle
|
|
9
|
+
|
|
10
|
+
という二段。payload 先頭 1byte に b"J" / b"P" を付ける方式
|
|
11
|
+
|
|
12
|
+
「イベントを JSON で送りたい」
|
|
13
|
+
「バイナリを運びたい」
|
|
14
|
+
いずれも収容可能
|
|
15
|
+
|
|
16
|
+
Kengo NAKADA
|
|
17
|
+
kengo.nakada@mat.shimane-u.ac.jp
|
|
18
|
+
kengo.nakada@gmail.com
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
from typing import Any, Dict, List, Optional, Union, Tuple, Callable, Sequence
|
|
23
|
+
|
|
24
|
+
import base64
|
|
25
|
+
import json
|
|
26
|
+
import pickle
|
|
27
|
+
|
|
28
|
+
# JSON でシリアライズされたことを示す識別子(先頭 1 byte)
|
|
29
|
+
_JSON_MAGIC: bytes = b"J"
|
|
30
|
+
|
|
31
|
+
# pickle でシリアライズされたことを示す識別子(先頭 1 byte)
|
|
32
|
+
_PICKLE_MAGIC: bytes = b"P"
|
|
33
|
+
|
|
34
|
+
# tuple を JSON 上で区別するための識別キー
|
|
35
|
+
_TUPLE_MAGIC_KEY: str = "__frame_tuple__"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class _BytesJsonEncoder(json.JSONEncoder):
|
|
39
|
+
# JSONEncoder を拡張し、bytes / bytearray を base64 文字列として扱う
|
|
40
|
+
def default(
|
|
41
|
+
self,
|
|
42
|
+
obj: Any,
|
|
43
|
+
) -> Any:
|
|
44
|
+
# bytes / bytearray は JSON で直接扱えないため base64 化
|
|
45
|
+
if isinstance(obj, (bytes, bytearray)):
|
|
46
|
+
b64: str = base64.b64encode(bytes(obj)).decode("ascii")
|
|
47
|
+
# 復元用の識別キー "__bytes__" を付与
|
|
48
|
+
return {"__bytes__": b64}
|
|
49
|
+
|
|
50
|
+
# それ以外は標準の JSONEncoder に委譲
|
|
51
|
+
return json.JSONEncoder.default(self, obj)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _bytes_json_object_hook(d: Dict[str, Any]) -> Any:
|
|
55
|
+
# JSON decode 時に "__bytes__" キーを検出した場合の復元処理
|
|
56
|
+
if "__bytes__" in d:
|
|
57
|
+
b64 = d["__bytes__"]
|
|
58
|
+
if isinstance(b64, str):
|
|
59
|
+
# base64 文字列を bytes に戻
|
|
60
|
+
return base64.b64decode(b64.encode("ascii"))
|
|
61
|
+
|
|
62
|
+
# tuple 復元用の識別キー
|
|
63
|
+
if _TUPLE_MAGIC_KEY in d:
|
|
64
|
+
items = d[_TUPLE_MAGIC_KEY]
|
|
65
|
+
if isinstance(items, list):
|
|
66
|
+
return tuple(items)
|
|
67
|
+
if isinstance(items, tuple):
|
|
68
|
+
return tuple(items)
|
|
69
|
+
|
|
70
|
+
# 特殊形式でなければそのまま返す
|
|
71
|
+
return d
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _prepare_json(obj: Any) -> Any:
|
|
75
|
+
# tuple を JSON で識別できる形式に変換(list はそのまま)
|
|
76
|
+
if isinstance(obj, tuple):
|
|
77
|
+
return {
|
|
78
|
+
_TUPLE_MAGIC_KEY: [_prepare_json(item) for item in obj],
|
|
79
|
+
}
|
|
80
|
+
if isinstance(obj, list):
|
|
81
|
+
return [_prepare_json(item) for item in obj]
|
|
82
|
+
if isinstance(obj, dict):
|
|
83
|
+
return {k: _prepare_json(v) for k, v in obj.items()}
|
|
84
|
+
return obj
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _try_json_dumps(obj: Any) -> bytes:
|
|
88
|
+
try:
|
|
89
|
+
# JSON によるシリアライズを最初に試みる
|
|
90
|
+
s: str = json.dumps(
|
|
91
|
+
# obj,
|
|
92
|
+
_prepare_json(obj),
|
|
93
|
+
cls=_BytesJsonEncoder, # bytes 対応エンコーダ
|
|
94
|
+
ensure_ascii=False, # Unicode をそのまま出力
|
|
95
|
+
separators=(",", ":"), # JSON を最小サイズにする
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
# JSON で成功した場合は識別子を先頭に付与
|
|
99
|
+
return _JSON_MAGIC + s.encode("utf-8")
|
|
100
|
+
except Exception:
|
|
101
|
+
# JSON 化できないオブジェクトは pickle にフォールバック
|
|
102
|
+
pass
|
|
103
|
+
|
|
104
|
+
# pickle によるシリアライズ(最高プロトコル)
|
|
105
|
+
payload: bytes = pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)
|
|
106
|
+
|
|
107
|
+
# pickle 識別子を先頭に付与
|
|
108
|
+
return _PICKLE_MAGIC + payload
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _loads(payload: bytes) -> Any:
|
|
112
|
+
# None はそのまま None として扱う
|
|
113
|
+
if payload is None:
|
|
114
|
+
return None
|
|
115
|
+
|
|
116
|
+
# 空 payload も None とみなす
|
|
117
|
+
if len(payload) == 0:
|
|
118
|
+
return None
|
|
119
|
+
|
|
120
|
+
# 先頭 1 byte を識別子として取得
|
|
121
|
+
magic: bytes = payload[:1]
|
|
122
|
+
body: bytes = payload[1:]
|
|
123
|
+
|
|
124
|
+
# JSON フォーマットの場合
|
|
125
|
+
if magic == _JSON_MAGIC:
|
|
126
|
+
s: str = body.decode("utf-8")
|
|
127
|
+
# bytes 復元用の object_hook を指定
|
|
128
|
+
return json.loads(s, object_hook=_bytes_json_object_hook)
|
|
129
|
+
|
|
130
|
+
# pickle フォーマットの場合
|
|
131
|
+
if magic == _PICKLE_MAGIC:
|
|
132
|
+
return pickle.loads(body)
|
|
133
|
+
|
|
134
|
+
# 識別子が無い旧形式などは pickle として扱う
|
|
135
|
+
return pickle.loads(payload)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def pack_args(
|
|
139
|
+
args: Tuple[Any, ...],
|
|
140
|
+
) -> bytes:
|
|
141
|
+
# 位置引数を list に変換してシリアライズ
|
|
142
|
+
return _try_json_dumps(list(args))
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def pack_kwargs(
|
|
146
|
+
kwargs: Dict[str, Any],
|
|
147
|
+
) -> bytes:
|
|
148
|
+
# キーワード引数を dict としてシリアライズ
|
|
149
|
+
return _try_json_dumps(kwargs)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def unpack_args(payload: bytes) -> Tuple[Any, ...]:
|
|
153
|
+
# シリアライズされた args を復元
|
|
154
|
+
obj = _loads(payload)
|
|
155
|
+
|
|
156
|
+
# None の場合は空タプル
|
|
157
|
+
if obj is None:
|
|
158
|
+
return tuple()
|
|
159
|
+
|
|
160
|
+
# 正常系では list → tuple に変換
|
|
161
|
+
if isinstance(obj, list):
|
|
162
|
+
return tuple(obj)
|
|
163
|
+
|
|
164
|
+
# 想定外の型はエラー
|
|
165
|
+
raise TypeError("args は list として復元される必要があります。")
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def unpack_kwargs(payload: bytes) -> Dict[str, Any]:
|
|
169
|
+
# シリアライズされた kwargs を復元
|
|
170
|
+
obj = _loads(payload)
|
|
171
|
+
|
|
172
|
+
# None の場合は空 dict
|
|
173
|
+
if obj is None:
|
|
174
|
+
return {}
|
|
175
|
+
|
|
176
|
+
# 正常系では dict をそのまま返す
|
|
177
|
+
if isinstance(obj, dict):
|
|
178
|
+
return obj
|
|
179
|
+
raise TypeError("kwargs は dict として復元される必要があります。")
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def pack_result(result: Any) -> bytes:
|
|
183
|
+
# 戻り値をシリアライズ
|
|
184
|
+
return _try_json_dumps(result)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def unpack_result(payload: bytes) -> Any:
|
|
188
|
+
return _loads(payload)
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
|
|
4
|
+
"""DeviceProxy support for grpc_frame.
|
|
5
|
+
|
|
6
|
+
This module provides the same entry/register API as
|
|
7
|
+
``ese774_frame.clients.device_proxy`` while constructing gRPC clients.
|
|
8
|
+
|
|
9
|
+
The public entry points are intentionally kept compatible:
|
|
10
|
+
|
|
11
|
+
- DeviceProxyEntry
|
|
12
|
+
- register_device_proxy(...)
|
|
13
|
+
- unregister_device_proxy(...)
|
|
14
|
+
- get_device_proxy_entry(...)
|
|
15
|
+
- list_device_proxies()
|
|
16
|
+
- DeviceProxy(...)
|
|
17
|
+
- create_device_proxy(...)
|
|
18
|
+
|
|
19
|
+
A device package can register direct client classes, for example
|
|
20
|
+
``SyncPixetGrpcClient`` and ``AsyncPixetGrpcClient``. If direct client
|
|
21
|
+
classes are not registered, DeviceProxy falls back to the generic
|
|
22
|
+
``SyncGrpcClient`` / ``AsyncGrpcClient`` classes.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from typing import Any, Dict, List, Optional, Type
|
|
26
|
+
|
|
27
|
+
from grpc_frame.grpc_client import AsyncGrpcClient
|
|
28
|
+
from grpc_frame.grpc_client import SyncGrpcClient
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class DeviceProxyEntry(object):
|
|
32
|
+
"""DeviceProxy registration entry.
|
|
33
|
+
|
|
34
|
+
The field names are kept compatible with ese774_frame.
|
|
35
|
+
``api_spec`` and ``object_name`` are retained as metadata for API
|
|
36
|
+
compatibility and pyi generation. grpc_frame itself obtains callable
|
|
37
|
+
methods from Describe RPC, so these fields are not required for runtime
|
|
38
|
+
method binding.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
def __init__(
|
|
42
|
+
self,
|
|
43
|
+
device_class: str,
|
|
44
|
+
async_client_cls: Optional[Type[Any]] = None,
|
|
45
|
+
sync_client_cls: Optional[Type[Any]] = None,
|
|
46
|
+
api_spec: Optional[list] = None,
|
|
47
|
+
object_name: Optional[str] = None,
|
|
48
|
+
default_async_mode: bool = True,
|
|
49
|
+
) -> None:
|
|
50
|
+
self.device_class = device_class
|
|
51
|
+
self.async_client_cls = async_client_cls
|
|
52
|
+
self.sync_client_cls = sync_client_cls
|
|
53
|
+
self.api_spec = api_spec
|
|
54
|
+
self.object_name = object_name
|
|
55
|
+
self.default_async_mode = default_async_mode
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
_DEVICE_PROXY_REGISTRY: Dict[str, DeviceProxyEntry] = {}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def register_device_proxy(
|
|
62
|
+
device_class: str,
|
|
63
|
+
*,
|
|
64
|
+
async_client_cls: Optional[Type[Any]] = None,
|
|
65
|
+
sync_client_cls: Optional[Type[Any]] = None,
|
|
66
|
+
api_spec: Optional[list] = None,
|
|
67
|
+
object_name: Optional[str] = None,
|
|
68
|
+
default_async_mode: bool = True,
|
|
69
|
+
aliases: Optional[List[str]] = None,
|
|
70
|
+
) -> None:
|
|
71
|
+
"""Register a device class for DeviceProxy.
|
|
72
|
+
|
|
73
|
+
This signature is compatible with ese774_frame. For grpc_frame,
|
|
74
|
+
direct client classes are the normal registration target:
|
|
75
|
+
|
|
76
|
+
``register_device_proxy("MiniPixCtrl", async_client_cls=..., sync_client_cls=...)``
|
|
77
|
+
|
|
78
|
+
``api_spec`` is accepted for compatibility and pyi tooling, but runtime
|
|
79
|
+
methods are resolved by the gRPC Describe RPC.
|
|
80
|
+
"""
|
|
81
|
+
if not device_class:
|
|
82
|
+
raise ValueError("device_class is required")
|
|
83
|
+
|
|
84
|
+
if async_client_cls is None and sync_client_cls is None and api_spec is None:
|
|
85
|
+
raise ValueError("async_client_cls, sync_client_cls, or api_spec is required")
|
|
86
|
+
|
|
87
|
+
entry = DeviceProxyEntry(
|
|
88
|
+
device_class=device_class,
|
|
89
|
+
async_client_cls=async_client_cls,
|
|
90
|
+
sync_client_cls=sync_client_cls,
|
|
91
|
+
api_spec=api_spec,
|
|
92
|
+
object_name=object_name,
|
|
93
|
+
default_async_mode=default_async_mode,
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
names = [device_class]
|
|
97
|
+
if aliases:
|
|
98
|
+
names.extend(aliases)
|
|
99
|
+
|
|
100
|
+
for name in names:
|
|
101
|
+
_DEVICE_PROXY_REGISTRY[name] = entry
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def unregister_device_proxy(device_class: str) -> None:
|
|
105
|
+
"""Unregister one DeviceProxy key.
|
|
106
|
+
|
|
107
|
+
This follows the ese774_frame behavior: only the specified key is removed.
|
|
108
|
+
If aliases were registered, remove each alias explicitly when needed.
|
|
109
|
+
"""
|
|
110
|
+
_DEVICE_PROXY_REGISTRY.pop(device_class, None)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def get_device_proxy_entry(device_class: str) -> DeviceProxyEntry:
|
|
114
|
+
"""Return a registered DeviceProxyEntry."""
|
|
115
|
+
if device_class not in _DEVICE_PROXY_REGISTRY:
|
|
116
|
+
raise KeyError(
|
|
117
|
+
f"DeviceProxy is not registered: {device_class}. "
|
|
118
|
+
"Call register_device_proxy(...) first."
|
|
119
|
+
)
|
|
120
|
+
return _DEVICE_PROXY_REGISTRY[device_class]
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def list_device_proxies() -> List[str]:
|
|
124
|
+
"""Return registered DeviceProxy keys."""
|
|
125
|
+
return sorted(_DEVICE_PROXY_REGISTRY.keys())
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def DeviceProxy(
|
|
129
|
+
device_class: str,
|
|
130
|
+
*args,
|
|
131
|
+
async_mode: Optional[bool] = None,
|
|
132
|
+
**kwargs,
|
|
133
|
+
) -> Any:
|
|
134
|
+
"""Create a client instance from a registered device_class.
|
|
135
|
+
|
|
136
|
+
Args:
|
|
137
|
+
device_class: Registered device class name or alias.
|
|
138
|
+
*args: Forwarded to the selected client class.
|
|
139
|
+
async_mode: True for async client, False for sync client, None to use
|
|
140
|
+
the registration default.
|
|
141
|
+
**kwargs: Forwarded to the selected client class.
|
|
142
|
+
|
|
143
|
+
Returns:
|
|
144
|
+
Async or sync client instance.
|
|
145
|
+
"""
|
|
146
|
+
entry = get_device_proxy_entry(device_class)
|
|
147
|
+
|
|
148
|
+
if async_mode is None:
|
|
149
|
+
async_mode = entry.default_async_mode
|
|
150
|
+
|
|
151
|
+
if async_mode:
|
|
152
|
+
client_cls = entry.async_client_cls or AsyncGrpcClient
|
|
153
|
+
return client_cls(*args, **kwargs)
|
|
154
|
+
|
|
155
|
+
client_cls = entry.sync_client_cls or SyncGrpcClient
|
|
156
|
+
return client_cls(*args, **kwargs)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def create_device_proxy(device_class: str):
|
|
160
|
+
"""Create a DeviceProxy factory with fixed device_class.
|
|
161
|
+
|
|
162
|
+
This helper is compatible with ese774_frame and is useful for generating
|
|
163
|
+
package-local entry functions/classes that preserve IDE completion through
|
|
164
|
+
generated pyi files.
|
|
165
|
+
"""
|
|
166
|
+
|
|
167
|
+
def proxy(
|
|
168
|
+
*args,
|
|
169
|
+
async_mode: Optional[bool] = None,
|
|
170
|
+
**kwargs,
|
|
171
|
+
) -> Any:
|
|
172
|
+
return DeviceProxy(
|
|
173
|
+
device_class,
|
|
174
|
+
*args,
|
|
175
|
+
async_mode=async_mode,
|
|
176
|
+
**kwargs,
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
return proxy
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
Kengo NAKADA
|
|
5
|
+
kengo.nakada@mat.shimane-u.ac.jp
|
|
6
|
+
kengo.nakada@gmail.com
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
from typing import Any, Dict, List, Optional, Union, Tuple, Callable, Sequence
|
|
11
|
+
|
|
12
|
+
import inspect
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class MethodInfo:
|
|
18
|
+
"""公開対象メソッドのメタ情報を保持するデータクラスである。
|
|
19
|
+
|
|
20
|
+
Attributes:
|
|
21
|
+
name: メソッド名である。
|
|
22
|
+
signature: 署名文字列である。取得できない場合は "()" とする。
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
name: str
|
|
26
|
+
signature: str
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def list_public_methods(
|
|
30
|
+
ctrl_obj: Any,
|
|
31
|
+
) -> List[MethodInfo]:
|
|
32
|
+
"""制御オブジェクトの public callable を列挙して MethodInfo の配列を返す関数である。
|
|
33
|
+
|
|
34
|
+
本関数は gRPC の Describe 用途を想定し、公開対象を「呼び出し可能な public メンバー」に限定する。
|
|
35
|
+
ここで property は列挙時に評価され得るため、静的取得で判定し、列挙対象から除外する。
|
|
36
|
+
|
|
37
|
+
Args:
|
|
38
|
+
ctrl_obj: 対象の制御オブジェクトである。
|
|
39
|
+
|
|
40
|
+
Returns:
|
|
41
|
+
List[MethodInfo]:
|
|
42
|
+
public callable の (name, signature) 一覧である。name 昇順にソートして返す。
|
|
43
|
+
"""
|
|
44
|
+
# 収集したメソッド情報を格納するリスト
|
|
45
|
+
methods: List[MethodInfo] = []
|
|
46
|
+
|
|
47
|
+
# # BEFORE(旧版の要点:getmembers による列挙)
|
|
48
|
+
# for name, member in inspect.getmembers(ctrl_obj):
|
|
49
|
+
# if name.startswith("_"):
|
|
50
|
+
# continue
|
|
51
|
+
|
|
52
|
+
# if not callable(member):
|
|
53
|
+
# continue
|
|
54
|
+
|
|
55
|
+
# signature = str(inspect.signature(member))
|
|
56
|
+
# methods.append(MethodInfo(name=name, signature=signature))
|
|
57
|
+
|
|
58
|
+
# 新版
|
|
59
|
+
# inspect.getmembers(ctrl_obj) は property を評価し得るため使用しない
|
|
60
|
+
# dir() により名前一覧のみを取得し、値の評価を伴う走査を避ける
|
|
61
|
+
for name in dir(ctrl_obj):
|
|
62
|
+
# public 以外は除外する
|
|
63
|
+
if name.startswith("_"):
|
|
64
|
+
continue
|
|
65
|
+
|
|
66
|
+
# getattr_static() で descriptor を評価せずに取得する
|
|
67
|
+
try:
|
|
68
|
+
static_member = inspect.getattr_static(ctrl_obj, name)
|
|
69
|
+
except Exception:
|
|
70
|
+
# 取得不能な名前は列挙対象から外す設計
|
|
71
|
+
continue
|
|
72
|
+
|
|
73
|
+
# property は評価時に副作用(COM 呼び出し等)を生む可能性があるため除外する
|
|
74
|
+
# staticmethod/classmethod/callable のみを候補として扱う
|
|
75
|
+
if isinstance(static_member, property):
|
|
76
|
+
continue
|
|
77
|
+
|
|
78
|
+
is_candidate: bool = False
|
|
79
|
+
|
|
80
|
+
if isinstance(static_member, staticmethod):
|
|
81
|
+
is_candidate = True
|
|
82
|
+
elif isinstance(static_member, classmethod):
|
|
83
|
+
is_candidate = True
|
|
84
|
+
else:
|
|
85
|
+
if callable(static_member):
|
|
86
|
+
is_candidate = True
|
|
87
|
+
|
|
88
|
+
if not is_candidate:
|
|
89
|
+
continue
|
|
90
|
+
|
|
91
|
+
# 実体を取得し、呼び出し可能であることを確認する
|
|
92
|
+
try:
|
|
93
|
+
member = getattr(ctrl_obj, name)
|
|
94
|
+
except Exception:
|
|
95
|
+
# 実体取得で例外が出るものは列挙対象から外す
|
|
96
|
+
continue
|
|
97
|
+
|
|
98
|
+
if not callable(member):
|
|
99
|
+
continue
|
|
100
|
+
|
|
101
|
+
# callable の引数の形を表す情報、署名
|
|
102
|
+
# 署名を文字列化する。取得不能なら "()" に丸める。
|
|
103
|
+
sig: str = ""
|
|
104
|
+
try:
|
|
105
|
+
sig = str(inspect.signature(member))
|
|
106
|
+
except Exception:
|
|
107
|
+
sig = "()"
|
|
108
|
+
|
|
109
|
+
methods.append(MethodInfo(name=name, signature=sig))
|
|
110
|
+
|
|
111
|
+
# name 昇順にそろえて返す
|
|
112
|
+
methods.sort(key=lambda m: m.name)
|
|
113
|
+
return methods
|
grpc_frame/event_bus.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
K.NAKADA, kengo.nakada@gmail.com, kengo.nakada@mat.shimane-u.ac.jp
|
|
5
|
+
|
|
6
|
+
EventBus: 軽量な in-process イベント配信機構。
|
|
7
|
+
|
|
8
|
+
- publish: イベントを配信
|
|
9
|
+
- subscribe: イベントを generator で受信
|
|
10
|
+
- スレッド間での待機/通知に Condition を使用
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from typing import Any, Deque, Dict, Iterator, List, Optional
|
|
16
|
+
from collections import deque
|
|
17
|
+
import threading
|
|
18
|
+
import time
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class EventItem:
|
|
23
|
+
"""EventBus が配信するイベント1件のデータ構造。"""
|
|
24
|
+
|
|
25
|
+
topic: str
|
|
26
|
+
payload_obj: Any
|
|
27
|
+
ts_ns: int
|
|
28
|
+
source: str
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class _Subscriber:
|
|
32
|
+
def __init__(
|
|
33
|
+
self,
|
|
34
|
+
topic: str,
|
|
35
|
+
*,
|
|
36
|
+
once: bool,
|
|
37
|
+
source: str,
|
|
38
|
+
) -> None:
|
|
39
|
+
"""
|
|
40
|
+
1トピックの購読状態を保持する内部クラス。
|
|
41
|
+
Condition + queue で publish/subscribe を同期する。
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
self.topic: str = topic
|
|
45
|
+
self.once: bool = once
|
|
46
|
+
self.source: str = source
|
|
47
|
+
self._cond: threading.Condition = threading.Condition()
|
|
48
|
+
self._queue: Deque[EventItem] = deque()
|
|
49
|
+
self._closed: bool = False
|
|
50
|
+
|
|
51
|
+
def close(self) -> None:
|
|
52
|
+
# 待機中の購読者を解除して終了させる
|
|
53
|
+
with self._cond:
|
|
54
|
+
self._closed = True
|
|
55
|
+
self._cond.notify_all()
|
|
56
|
+
|
|
57
|
+
def push(self, item: EventItem) -> None:
|
|
58
|
+
# publish からのイベントをキューへ
|
|
59
|
+
with self._cond:
|
|
60
|
+
if self._closed:
|
|
61
|
+
return
|
|
62
|
+
self._queue.append(item)
|
|
63
|
+
self._cond.notify_all()
|
|
64
|
+
|
|
65
|
+
def pop_wait(self) -> Optional[EventItem]:
|
|
66
|
+
# イベントが来るまでブロックして待機
|
|
67
|
+
with self._cond:
|
|
68
|
+
while True:
|
|
69
|
+
if self._closed:
|
|
70
|
+
return None
|
|
71
|
+
if len(self._queue) > 0:
|
|
72
|
+
item: EventItem = self._queue.popleft()
|
|
73
|
+
return item
|
|
74
|
+
self._cond.wait()
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class EventBus:
|
|
78
|
+
"""
|
|
79
|
+
in-process のイベント配信ハブ。
|
|
80
|
+
|
|
81
|
+
- publish: topic に紐づく購読者へ配信
|
|
82
|
+
- subscribe: generator 形式でイベントを取得
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
def __init__(self) -> None:
|
|
86
|
+
self._lock: threading.Lock = threading.Lock()
|
|
87
|
+
self._subscribers: List[_Subscriber] = []
|
|
88
|
+
|
|
89
|
+
def publish(
|
|
90
|
+
self,
|
|
91
|
+
topic: str,
|
|
92
|
+
payload_obj: Any,
|
|
93
|
+
*,
|
|
94
|
+
source: str = "",
|
|
95
|
+
) -> None:
|
|
96
|
+
"""
|
|
97
|
+
イベントを publish して、該当トピックの購読者へ通知する。
|
|
98
|
+
|
|
99
|
+
Args:
|
|
100
|
+
topic: トピック名
|
|
101
|
+
payload_obj: 任意の payload
|
|
102
|
+
source: 発生元識別子
|
|
103
|
+
"""
|
|
104
|
+
# 配信時刻(ナノ秒)
|
|
105
|
+
ts_ns: int = time.time_ns()
|
|
106
|
+
item: EventItem = EventItem(
|
|
107
|
+
topic=topic,
|
|
108
|
+
payload_obj=payload_obj,
|
|
109
|
+
ts_ns=ts_ns,
|
|
110
|
+
source=source,
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
# 購読者リストのスナップショットを取る(ロック時間最小化)
|
|
114
|
+
subs_snapshot: List[_Subscriber] = []
|
|
115
|
+
with self._lock:
|
|
116
|
+
subs_snapshot = list(self._subscribers)
|
|
117
|
+
|
|
118
|
+
# 該当トピックにのみ配信
|
|
119
|
+
for sub in subs_snapshot:
|
|
120
|
+
if sub.topic != topic:
|
|
121
|
+
continue
|
|
122
|
+
sub.push(item)
|
|
123
|
+
|
|
124
|
+
def subscribe(
|
|
125
|
+
self,
|
|
126
|
+
topic: str,
|
|
127
|
+
*,
|
|
128
|
+
once: bool = False,
|
|
129
|
+
source: str = "",
|
|
130
|
+
cancel_event: Optional[threading.Event] = None,
|
|
131
|
+
) -> Iterator[EventItem]:
|
|
132
|
+
"""
|
|
133
|
+
指定トピックを購読し、EventItem を generator で返す。
|
|
134
|
+
|
|
135
|
+
Args:
|
|
136
|
+
topic: 購読するトピック
|
|
137
|
+
once: True の場合は1件受信したら終了
|
|
138
|
+
source: 発生元フィルタ(未使用だが拡張用)
|
|
139
|
+
cancel_event: 外部から購読解除するための Event
|
|
140
|
+
|
|
141
|
+
Yields:
|
|
142
|
+
EventItem
|
|
143
|
+
"""
|
|
144
|
+
# 購読状態を生成
|
|
145
|
+
sub: _Subscriber = _Subscriber(
|
|
146
|
+
topic=topic,
|
|
147
|
+
once=once,
|
|
148
|
+
source=source,
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
with self._lock:
|
|
152
|
+
# 購読者リストに登録
|
|
153
|
+
self._subscribers.append(sub)
|
|
154
|
+
|
|
155
|
+
try:
|
|
156
|
+
while True:
|
|
157
|
+
if cancel_event is not None:
|
|
158
|
+
if cancel_event.is_set():
|
|
159
|
+
break
|
|
160
|
+
|
|
161
|
+
# イベントを待機して取得
|
|
162
|
+
item = sub.pop_wait()
|
|
163
|
+
if item is None:
|
|
164
|
+
break
|
|
165
|
+
|
|
166
|
+
yield item
|
|
167
|
+
|
|
168
|
+
if sub.once:
|
|
169
|
+
break
|
|
170
|
+
|
|
171
|
+
finally:
|
|
172
|
+
# 終了時に購読解除
|
|
173
|
+
sub.close()
|
|
174
|
+
|
|
175
|
+
with self._lock:
|
|
176
|
+
new_list: List[_Subscriber] = []
|
|
177
|
+
for s in self._subscribers:
|
|
178
|
+
if s is sub:
|
|
179
|
+
continue
|
|
180
|
+
new_list.append(s)
|
|
181
|
+
self._subscribers = new_list
|