forked from temporalio/sdk-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgen_bridge_client.py
More file actions
275 lines (223 loc) · 8.01 KB
/
Copy pathgen_bridge_client.py
File metadata and controls
275 lines (223 loc) · 8.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
import re
from functools import partial
from string import Template
from google.protobuf.descriptor import (
FileDescriptor,
MethodDescriptor,
ServiceDescriptor,
)
import temporalio.api.cloud.cloudservice.v1.service_pb2 as cloud_service
import temporalio.api.operatorservice.v1.service_pb2 as operator_service
import temporalio.api.testservice.v1.service_pb2 as test_service
import temporalio.api.workflowservice.v1.service_pb2 as workflow_service
import temporalio.bridge.proto.health.v1.health_pb2 as health_service
def generate_python_services(
file_descriptors: list[FileDescriptor],
output_file: str = "temporalio/bridge/services_generated.py",
):
print("generating python services")
services_template = Template('''# Generated file. DO NOT EDIT
"""Generated RPC calls for Temporal services."""
from __future__ import annotations
from datetime import timedelta
from typing import TYPE_CHECKING
from collections.abc import Mapping
import google.protobuf.empty_pb2
$service_imports
if TYPE_CHECKING:
from temporalio.service import ServiceClient
$service_defns
''')
def service_name(s):
return f"import {sanitize_proto_name(s.full_name)[: -len(s.name) - 1]}"
service_imports = [
service_name(service_descriptor)
for file_descriptor in file_descriptors
for service_descriptor in file_descriptor.services_by_name.values()
]
service_defns = [
generate_python_service(service_descriptor)
for file_descriptor in file_descriptors
for service_descriptor in file_descriptor.services_by_name.values()
]
with open(output_file, "w") as f:
f.write(
services_template.substitute(
service_imports="\n".join(service_imports),
service_defns="\n".join(service_defns),
)
)
def generate_python_service(service_descriptor: ServiceDescriptor) -> str:
service_template = Template('''
class $service_name:
"""RPC calls for the $service_name."""
def __init__(self, client: ServiceClient):
"""Initialize service with the provided ServiceClient."""
self._client = client
self._service = "$rpc_service_name"
$method_calls
''')
sanitized_service_name: str = service_descriptor.name
# The health service doesn't end in "Service" in the proto definition
# this check ensures that the proto descriptor name will match the format in core
if not sanitized_service_name.endswith("Service"):
sanitized_service_name += "Service"
# remove "Service" and lowercase
rpc_name = sanitized_service_name[:-7].lower()
# remove any streaming methods b/c we don't support them at the moment
methods = [
method
for method in service_descriptor.methods
if not method.client_streaming and not method.server_streaming
]
method_calls = [
generate_python_method_call(sanitized_service_name, method)
for method in sorted(methods, key=lambda m: m.name)
]
return service_template.substitute(
service_name=sanitized_service_name,
rpc_service_name=pascal_to_snake(rpc_name),
method_calls="\n".join(method_calls),
)
def generate_python_method_call(
service_name: str, method_descriptor: MethodDescriptor
) -> str:
method_template = Template('''
async def $method_name(
self,
req: $request_type,
retry: bool = False,
metadata: Mapping[str, str | bytes] = {},
timeout: timedelta | None = None,
) -> $response_type:
"""Invokes the $service_name.$method_name rpc method."""
return await self._client._rpc_call(
rpc="$method_name",
req=req,
service=self._service,
resp_type=$response_type,
retry=retry,
metadata=metadata,
timeout=timeout,
)
''')
return method_template.substitute(
service_name=service_name,
method_name=pascal_to_snake(method_descriptor.name),
request_type=sanitize_proto_name(method_descriptor.input_type.full_name),
response_type=sanitize_proto_name(method_descriptor.output_type.full_name),
)
def generate_rust_client_impl(
file_descriptors: list[FileDescriptor],
output_file: str = "temporalio/bridge/src/client_rpc_generated.rs",
):
print("generating bridge rpc calls")
service_calls = [
generate_rust_service_call(service_descriptor)
for file_descriptor in file_descriptors
for service_descriptor in file_descriptor.services_by_name.values()
]
impl_template = Template("""// Generated file. DO NOT EDIT
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use super::{
client::{rpc_req, rpc_resp, ClientRef, RpcCall},
rpc_call,
};
#[pymethods]
impl ClientRef {
$service_calls
}""")
with open(output_file, "w") as f:
f.write(impl_template.substitute(service_calls="\n".join(service_calls)))
def generate_rust_service_call(service_descriptor: ServiceDescriptor) -> str:
call_template = Template("""
fn call_${service_name}<'p>(
&self,
py: Python<'p>,
call: RpcCall,
) -> PyResult<Bound<'p, PyAny>> {
self.runtime.assert_same_process("use client")?;
use temporalio_client::grpc::${descriptor_name};
let mut connection = self.connection.clone();
self.runtime.future_into_py(py, async move {
let bytes = match call.rpc.as_str() {
$match_arms
_ => {
return Err(PyValueError::new_err(format!(
"Unknown RPC call {}",
call.rpc
)))
}
}?;
Ok(bytes)
})
}""")
sanitized_service_name: str = service_descriptor.name
# The health service doesn't end in "Service" in the proto definition
# this check ensures that the proto descriptor name will match the format in core
if not sanitized_service_name.endswith("Service"):
sanitized_service_name += "Service"
# remove any streaming methods b/c we don't support them at the moment
methods = [
method
for method in service_descriptor.methods
if not method.client_streaming and not method.server_streaming
]
service_method = pascal_to_snake(sanitized_service_name)
match_arms = [
generate_rust_match_arm(sanitized_service_name, service_method, method)
for method in sorted(methods, key=lambda m: m.name)
]
return call_template.substitute(
service_name=service_method,
descriptor_name=sanitized_service_name,
match_arms="\n".join(match_arms),
)
def generate_rust_match_arm(
trait_name: str, service_method: str, method: MethodDescriptor
) -> str:
match_template = Template("""\
"$method_name" => {
rpc_call!(connection, call, $trait_name, $service_method, $method_name)
}""")
return match_template.substitute(
method_name=pascal_to_snake(method.name),
trait_name=trait_name,
service_method=service_method,
)
def pascal_to_snake(input: str) -> str:
return re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", input).lower()
sanitize_import_fixes = [
partial(re.compile(r"temporal\.api\.").sub, r"temporalio.api."),
partial(
re.compile(r"temporal\.grpc.health\.").sub, r"temporalio.bridge.proto.health."
),
partial(
re.compile(r"google\.protobuf\.Empty").sub, r"google.protobuf.empty_pb2.Empty"
),
]
def sanitize_proto_name(input: str) -> str:
content = input
for fix in sanitize_import_fixes:
content = fix(content)
return content
if __name__ == "__main__":
generate_rust_client_impl(
[
workflow_service.DESCRIPTOR,
operator_service.DESCRIPTOR,
cloud_service.DESCRIPTOR,
test_service.DESCRIPTOR,
health_service.DESCRIPTOR,
]
)
generate_python_services(
[
workflow_service.DESCRIPTOR,
operator_service.DESCRIPTOR,
cloud_service.DESCRIPTOR,
test_service.DESCRIPTOR,
health_service.DESCRIPTOR,
]
)