forked from dapr/python-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
237 lines (180 loc) · 8.13 KB
/
Copy pathapp.py
File metadata and controls
237 lines (180 loc) · 8.13 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
# -*- coding: utf-8 -*-
"""
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from concurrent import futures
from typing import Dict, Optional
import grpc
from dapr.conf import settings
from dapr.ext.grpc._health_servicer import _HealthCheckServicer # type: ignore
from dapr.ext.grpc._servicer import Rule, _CallbackServicer # type: ignore
from dapr.proto import appcallback_service_v1
class App:
"""App object implements a Dapr application callback which can interact with Dapr runtime.
Once its object is initiated, it will act as a central registry for service invocation,
subscribing topic, and input bindings.
You can create a :class:`App` instance in your main module:
from dapr.ext.grpc import App
app = App()
"""
def __init__(self, max_grpc_message_length: Optional[int] = None, **kwargs):
"""Inits App object and creates gRPC server.
Args:
max_grpc_message_length (int, optional): The maximum grpc send and receive
message length in bytes. Only used when kwargs are not set. When this
argument is omitted, the env var
``DAPR_GRPC_MAX_INBOUND_MESSAGE_SIZE_BYTES`` is consulted to set the
receive limit (matches the Java SDK property of the same name).
kwargs: arguments to grpc.server()
"""
self._servicer = _CallbackServicer()
self._health_check_servicer = _HealthCheckServicer()
if not kwargs:
options = []
if max_grpc_message_length is not None:
options = [
('grpc.max_send_message_length', max_grpc_message_length),
('grpc.max_receive_message_length', max_grpc_message_length),
]
elif settings.DAPR_GRPC_MAX_INBOUND_MESSAGE_SIZE_BYTES:
options = [
(
'grpc.max_receive_message_length',
settings.DAPR_GRPC_MAX_INBOUND_MESSAGE_SIZE_BYTES,
),
]
self._server = grpc.server( # type: ignore
futures.ThreadPoolExecutor(max_workers=10), options=options
)
else:
self._server = grpc.server(**kwargs) # type: ignore
appcallback_service_v1.add_AppCallbackServicer_to_server(self._servicer, self._server)
appcallback_service_v1.add_AppCallbackAlphaServicer_to_server(self._servicer, self._server)
appcallback_service_v1.add_AppCallbackHealthCheckServicer_to_server(
self._health_check_servicer, self._server
)
def __del__(self):
self.stop()
def add_external_service(self, servicer_callback, external_servicer):
"""Adds an external gRPC service to the same server"""
servicer_callback(external_servicer, self._server)
def register_health_check(self, health_check_callback):
"""Adds a health check callback
The below example adds a basic health check to check Dapr gRPC is running
@app.register_health_check(lambda: None)
"""
self._health_check_servicer.register_health_check(health_check_callback)
def run(self, app_port: Optional[int] = None, listen_address: Optional[str] = None) -> None:
"""Starts app gRPC server and waits until :class:`App`.stop() is called.
Args:
app_port (int, optional): The port on which to listen for incoming gRPC calls.
Defaults to settings.GRPC_APP_PORT.
listen_address (str, optional): The IP address on which to listen for incoming gRPC
calls. Defaults to [::] (all IP addresses).
"""
if app_port is None:
app_port = settings.GRPC_APP_PORT
self._server.add_insecure_port(f'{listen_address if listen_address else "[::]"}:{app_port}')
self._server.start()
self._server.wait_for_termination()
def stop(self) -> None:
"""Stops app server."""
self._server.stop(0)
def method(self, name: str):
"""A decorator that is used to register the method for the service invocation.
Return JSON formatted data response::
@app.method('start')
def start(request: InvokeMethodRequest):
...
return json.dumps()
Return Protocol buffer response::
@app.method('start')
def start(request: InvokeMethodRequest):
...
return CustomProtoResponse(data='hello world')
Specify Response header::
@app.method('start')
def start(request: InvokeMethodRequest):
...
resp = InvokeMethodResponse('hello world', 'text/plain')
resp.headers = ('key', 'value')
return resp
Args:
name (str): name of invoked method
"""
def decorator(func):
self._servicer.register_method(name, func)
return decorator
def subscribe(
self,
pubsub_name: str,
topic: str,
metadata: Optional[Dict[str, str]] = {},
dead_letter_topic: Optional[str] = None,
rule: Optional[Rule] = None,
disable_topic_validation: Optional[bool] = False,
):
"""A decorator that is used to register the subscribing topic method.
The below example registers 'topic' subscription topic and pass custom
metadata to pubsub component::
from cloudevents.sdk.event import v1
@app.subscribe('pubsub_name', 'topic', metadata=(('session-id', 'session-id-value'),))
def topic(event: v1.Event) -> None:
...
Args:
pubsub_name (str): the name of the pubsub component
topic (str): the topic name which is subscribed
metadata (dict, optional): metadata which will be passed to pubsub component
during initialization
dead_letter_topic (str, optional): the dead letter topic name for the subscription
"""
def decorator(func):
self._servicer.register_topic(
pubsub_name,
topic,
func,
metadata,
dead_letter_topic,
rule,
disable_topic_validation,
)
return decorator
def binding(self, name: str):
"""A decorator that is used to register input binding.
The below registers input binding which this application subscribes:
@app.binding('input')
def input(request: BindingRequest) -> None:
...
Args:
name (str): the name of invoked method
"""
def decorator(func):
self._servicer.register_binding(name, func)
return decorator
def job_event(self, name: str):
"""A decorator that is used to register job event handler.
This decorator registers a handler for job events triggered by the Dapr scheduler.
The handler will be called when a job with the specified name is triggered.
The below registers a job event handler for jobs named 'my-job':
from dapr.ext.grpc import JobEvent
@app.job_event('my-job')
def handle_my_job(job_event: JobEvent) -> None:
print(f"Job {job_event.name} triggered")
data_str = job_event.get_data_as_string()
print(f"Job data: {data_str}")
# Process the job...
Args:
name (str): the name of the job to handle events for
"""
def decorator(func):
self._servicer.register_job_event(name, func)
return decorator