-
Notifications
You must be signed in to change notification settings - Fork 122
/
client.py
1622 lines (1377 loc) · 60.7 KB
/
client.py
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- 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.
"""
import time
import socket
import json
import uuid
from urllib.parse import urlencode
from warnings import warn
from typing import Callable, Dict, Optional, Text, Union, Sequence, List, Any
from typing_extensions import Self
from datetime import datetime
from google.protobuf.message import Message as GrpcMessage
from google.protobuf.empty_pb2 import Empty as GrpcEmpty
import grpc # type: ignore
from grpc import ( # type: ignore
UnaryUnaryClientInterceptor,
UnaryStreamClientInterceptor,
StreamUnaryClientInterceptor,
StreamStreamClientInterceptor,
RpcError,
)
from dapr.clients.exceptions import DaprInternalError, DaprGrpcError
from dapr.clients.grpc._state import StateOptions, StateItem
from dapr.clients.grpc._helpers import getWorkflowRuntimeStatus
from dapr.clients.health import DaprHealth
from dapr.conf import settings
from dapr.proto import api_v1, api_service_v1, common_v1
from dapr.proto.runtime.v1.dapr_pb2 import UnsubscribeConfigurationResponse
from dapr.version import __version__
from dapr.clients.grpc._helpers import (
DaprClientInterceptor,
MetadataTuple,
to_bytes,
validateNotNone,
validateNotBlankString,
)
from dapr.conf.helpers import GrpcEndpoint
from dapr.clients.grpc._request import (
InvokeMethodRequest,
BindingRequest,
TransactionalStateOperation,
)
from dapr.clients.grpc._response import (
BindingResponse,
DaprResponse,
GetSecretResponse,
GetBulkSecretResponse,
GetMetadataResponse,
InvokeMethodResponse,
UnlockResponseStatus,
StateResponse,
BulkStatesResponse,
BulkStateItem,
ConfigurationResponse,
QueryResponse,
QueryResponseItem,
RegisteredComponents,
ConfigurationWatcher,
TryLockResponse,
UnlockResponse,
GetWorkflowResponse,
StartWorkflowResponse,
)
class DaprGrpcClient:
"""The convenient layer implementation of Dapr gRPC APIs.
This provides the wrappers and helpers to allows developers to use Dapr runtime gRPC API
easily and consistently.
Examples:
>>> from dapr.clients import DaprClient
>>> d = DaprClient()
>>> resp = d.invoke_method('callee', 'method', b'data')
With context manager and custom message size limit:
>>> from dapr.clients import DaprClient
>>> MAX = 64 * 1024 * 1024 # 64MB
>>> with DaprClient(max_message_length=MAX) as d:
... resp = d.invoke_method('callee', 'method', b'data')
"""
def __init__(
self,
address: Optional[str] = None,
interceptors: Optional[
List[
Union[
UnaryUnaryClientInterceptor,
UnaryStreamClientInterceptor,
StreamUnaryClientInterceptor,
StreamStreamClientInterceptor,
]
]
] = None,
max_grpc_message_length: Optional[int] = None,
):
"""Connects to Dapr Runtime and initialize gRPC client stub.
Args:
address (str, optional): Dapr Runtime gRPC endpoint address.
interceptors (list of UnaryUnaryClientInterceptor or
UnaryStreamClientInterceptor or
StreamUnaryClientInterceptor or
StreamStreamClientInterceptor, optional): gRPC interceptors.
max_grpc_messsage_length (int, optional): The maximum grpc send and receive
message length in bytes.
"""
DaprHealth.wait_until_ready()
useragent = f'dapr-sdk-python/{__version__}'
if not max_grpc_message_length:
options = [
('grpc.primary_user_agent', useragent),
]
else:
options = [
('grpc.max_send_message_length', max_grpc_message_length), # type: ignore
('grpc.max_receive_message_length', max_grpc_message_length), # type: ignore
('grpc.primary_user_agent', useragent),
]
if not address:
address = settings.DAPR_GRPC_ENDPOINT or (
f'{settings.DAPR_RUNTIME_HOST}:' f'{settings.DAPR_GRPC_PORT}'
)
try:
self._uri = GrpcEndpoint(address)
except ValueError as error:
raise DaprInternalError(f'{error}') from error
if self._uri.tls:
self._channel = grpc.secure_channel( # type: ignore
self._uri.endpoint,
self.get_credentials(),
options=options,
)
else:
self._channel = grpc.insecure_channel( # type: ignore
self._uri.endpoint,
options=options,
)
if settings.DAPR_API_TOKEN:
api_token_interceptor = DaprClientInterceptor(
[
('dapr-api-token', settings.DAPR_API_TOKEN),
]
)
self._channel = grpc.intercept_channel( # type: ignore
self._channel, api_token_interceptor
)
if interceptors:
self._channel = grpc.intercept_channel( # type: ignore
self._channel, *interceptors
)
self._stub = api_service_v1.DaprStub(self._channel)
def get_credentials(self):
# This method is used (overwritten) from tests
# to return credentials for self-signed certificates
return grpc.ssl_channel_credentials() # type: ignore
def close(self):
"""Closes Dapr runtime gRPC channel."""
if hasattr(self, '_channel') and self._channel:
self._channel.close()
def __del__(self):
self.close()
def __enter__(self) -> Self: # type: ignore
return self
def __exit__(self, exc_type, exc_value, traceback) -> None:
self.close()
def _get_http_extension(
self, http_verb: str, http_querystring: Optional[MetadataTuple] = None
) -> common_v1.HTTPExtension: # type: ignore
verb = common_v1.HTTPExtension.Verb.Value(http_verb) # type: ignore
http_ext = common_v1.HTTPExtension(verb=verb)
if http_querystring is not None and len(http_querystring):
http_ext.querystring = urlencode(http_querystring)
return http_ext
def invoke_method(
self,
app_id: str,
method_name: str,
data: Union[bytes, str, GrpcMessage] = '',
content_type: Optional[str] = None,
metadata: Optional[MetadataTuple] = None,
http_verb: Optional[str] = None,
http_querystring: Optional[MetadataTuple] = None,
timeout: Optional[int] = None,
) -> InvokeMethodResponse:
"""Invokes the target service to call method.
This can invoke the specified target service to call method with bytes array data or
custom protocol buffer message. If your callee application uses http appcallback,
http_verb and http_querystring must be specified. Otherwise, Dapr runtime will return
error.
The example calls `callee` service with bytes data, which implements grpc appcallback:
from dapr.clients import DaprClient
with DaprClient() as d:
resp = d.invoke_method(
app_id='callee',
method_name='method',
data=b'message',
content_type='text/plain',
)
# resp.content includes the content in bytes.
# resp.content_type specifies the content type of resp.content.
# Thus, resp.content can be deserialized properly.
When sending custom protocol buffer message object, it doesn't requires content_type:
from dapr.clients import DaprClient
req_data = dapr_example_v1.CustomRequestMessage(data='custom')
with DaprClient() as d:
resp = d.invoke_method(
app_id='callee',
method_name='method',
data=req_data,
)
# Create protocol buffer object
resp_data = dapr_example_v1.CustomResponseMessage()
# Deserialize to resp_data
resp.unpack(resp_data)
The example calls `callee` service which implements http appcallback:
from dapr.clients import DaprClient
with DaprClient() as d:
resp = d.invoke_method(
app_id='callee',
method_name='method',
data=b'message',
content_type='text/plain',
http_verb='POST',
http_querystring=(
('key1', 'value1')
),
)
# resp.content includes the content in bytes.
# resp.content_type specifies the content type of resp.content.
# Thus, resp.content can be deserialized properly.
Args:
app_id (str): the callee app id
method (str): the method name which is called
data (bytes or :obj:`google.protobuf.message.Message`, optional): bytes
or Message for data which will be sent to app id
metadata (tuple, optional, DEPRECATED): gRPC custom metadata
http_verb (str, optional): http method verb to call HTTP callee application
http_querystring (tuple, optional): the tuple to represent query string
timeout (int, optional): request timeout in seconds
Returns:
:class:`InvokeMethodResponse` object returned from callee
"""
warn(
'invoke_method with protocol gRPC is deprecated. Use gRPC proxying instead.',
DeprecationWarning,
stacklevel=2,
)
if metadata is not None:
warn(
'metadata argument is deprecated. Dapr already intercepts API token headers '
'and this is not needed.',
DeprecationWarning,
stacklevel=2,
)
req_data = InvokeMethodRequest(data, content_type)
http_ext = None
if http_verb:
http_ext = self._get_http_extension(http_verb, http_querystring)
content_type = ''
if req_data.content_type:
content_type = req_data.content_type
req = api_v1.InvokeServiceRequest(
id=app_id,
message=common_v1.InvokeRequest(
method=method_name,
data=req_data.proto,
content_type=content_type,
http_extension=http_ext,
),
)
response, call = self._stub.InvokeService.with_call(req, metadata=metadata, timeout=timeout)
resp_data = InvokeMethodResponse(response.data, response.content_type)
resp_data.headers = call.initial_metadata() # type: ignore
return resp_data
def invoke_binding(
self,
binding_name: str,
operation: str,
data: Union[bytes, str] = '',
binding_metadata: Dict[str, str] = {},
metadata: Optional[MetadataTuple] = None,
) -> BindingResponse:
"""Invokes the output binding with the specified operation.
The data field takes any JSON serializable value and acts as the
payload to be sent to the output binding. The metadata field is an
array of key/value pairs and allows you to set binding specific metadata
for each call. The operation field tells the Dapr binding which operation
it should perform.
The example calls output `binding` service with bytes data:
from dapr.clients import DaprClient
with DaprClient() as d:
resp = d.invoke_binding(
binding_name = 'kafkaBinding',
operation = 'create',
data = b'message',
)
# resp.data includes the response data in bytes.
Args:
binding_name (str): the name of the binding as defined in the components
operation (str): the operation to perform on the binding
data (bytes or str, optional): bytes or str for data which will sent to the binding
binding_metadata (dict, optional): Dapr metadata for output binding
metadata (tuple, optional, DEPRECATED): gRPC custom metadata
Returns:
:class:`InvokeBindingResponse` object returned from binding
"""
if metadata is not None:
warn(
'metadata argument is deprecated. Dapr already intercepts API token headers '
'and this is not needed.',
DeprecationWarning,
stacklevel=2,
)
req_data = BindingRequest(data, binding_metadata)
req = api_v1.InvokeBindingRequest(
name=binding_name,
data=req_data.data,
metadata=req_data.binding_metadata,
operation=operation,
)
response, call = self._stub.InvokeBinding.with_call(req, metadata=metadata)
return BindingResponse(response.data, dict(response.metadata), call.initial_metadata())
def publish_event(
self,
pubsub_name: str,
topic_name: str,
data: Union[bytes, str],
publish_metadata: Dict[str, str] = {},
metadata: Optional[MetadataTuple] = None,
data_content_type: Optional[str] = None,
) -> DaprResponse:
"""Publish to a given topic.
This publishes an event with bytes array or str data to a specified topic and
specified pubsub component. The str data is encoded into bytes with default
charset of utf-8. Custom metadata can be passed with the metadata field which
will be passed on a gRPC metadata.
The example publishes a byte array event to a topic:
from dapr.clients import DaprClient
with DaprClient() as d:
resp = d.publish_event(
pubsub_name='pubsub_1',
topic_name='TOPIC_A',
data=b'message',
publish_metadata={'ttlInSeconds': '100', 'rawPayload': 'false'},
)
# resp.headers includes the gRPC initial metadata.
Args:
pubsub_name (str): the name of the pubsub component
topic_name (str): the topic name to publish to
data (bytes or str): bytes or str for data
publish_metadata (Dict[str, str], optional): Dapr metadata per Pub/Sub message
metadata (tuple, optional, DEPRECATED): gRPC custom metadata
data_content_type: (str, optional): content type of the data payload
Returns:
:class:`DaprResponse` gRPC metadata returned from callee
"""
if metadata is not None:
warn(
'metadata argument is deprecated. Dapr already intercepts API token headers '
'and this is not needed.',
DeprecationWarning,
stacklevel=2,
)
if not isinstance(data, bytes) and not isinstance(data, str):
raise ValueError(f'invalid type for data {type(data)}')
req_data: bytes
if isinstance(data, bytes):
req_data = data
else:
if isinstance(data, str):
req_data = data.encode('utf-8')
content_type = ''
if data_content_type:
content_type = data_content_type
req = api_v1.PublishEventRequest(
pubsub_name=pubsub_name,
topic=topic_name,
data=req_data,
data_content_type=content_type,
metadata=publish_metadata,
)
try:
# response is google.protobuf.Empty
_, call = self._stub.PublishEvent.with_call(req, metadata=metadata)
except RpcError as err:
raise DaprGrpcError(err) from err
return DaprResponse(call.initial_metadata())
def get_state(
self,
store_name: str,
key: str,
state_metadata: Optional[Dict[str, str]] = dict(),
metadata: Optional[MetadataTuple] = None,
) -> StateResponse:
"""Gets value from a statestore with a key
The example gets value from a statestore:
from dapr.clients import DaprClient
with DaprClient() as d:
resp = d.get_state(
store_name='state_store'
key='key_1',
state={"key": "value"},
state_metadata={"metakey": "metavalue"},
)
Args:
store_name (str): the state store name to get from
key (str): the key of the key-value pair to be gotten
state_metadata (Dict[str, str], optional): Dapr metadata for state request
metadata (tuple, optional, DEPRECATED): gRPC custom metadata
Returns:
:class:`StateResponse` gRPC metadata returned from callee
and value obtained from the state store
"""
if metadata is not None:
warn(
'metadata argument is deprecated. Dapr already intercepts API token headers '
'and this is not needed.',
DeprecationWarning,
stacklevel=2,
)
if not store_name or len(store_name) == 0 or len(store_name.strip()) == 0:
raise ValueError('State store name cannot be empty')
req = api_v1.GetStateRequest(store_name=store_name, key=key, metadata=state_metadata)
try:
response, call = self._stub.GetState.with_call(req, metadata=metadata)
return StateResponse(
data=response.data, etag=response.etag, headers=call.initial_metadata()
)
except RpcError as err:
raise DaprGrpcError(err) from err
def get_bulk_state(
self,
store_name: str,
keys: Sequence[str],
parallelism: int = 1,
states_metadata: Optional[Dict[str, str]] = dict(),
metadata: Optional[MetadataTuple] = None,
) -> BulkStatesResponse:
"""Gets values from a statestore with keys
The example gets value from a statestore:
from dapr.clients import DaprClient
with DaprClient() as d:
resp = d.get_bulk_state(
store_name='state_store',
keys=['key_1', key_2],
parallelism=2,
states_metadata={"metakey": "metavalue"},
)
Args:
store_name (str): the state store name to get from
key (Sequence[str]): the keys to be retrieved
parallelism (int): number of items to be retrieved in parallel
states_metadata (Dict[str, str], optional): Dapr metadata for state request
metadata (tuple, optional, DEPRECATED): gRPC custom metadata
Returns:
:class:`BulkStatesResponse` gRPC metadata returned from callee
and value obtained from the state store
"""
if metadata is not None:
warn(
'metadata argument is deprecated. Dapr already intercepts API token headers '
'and this is not needed.',
DeprecationWarning,
stacklevel=2,
)
if not store_name or len(store_name) == 0 or len(store_name.strip()) == 0:
raise ValueError('State store name cannot be empty')
req = api_v1.GetBulkStateRequest(
store_name=store_name, keys=keys, parallelism=parallelism, metadata=states_metadata
)
try:
response, call = self._stub.GetBulkState.with_call(req, metadata=metadata)
except RpcError as err:
raise DaprGrpcError(err) from err
items = []
for item in response.items:
items.append(
BulkStateItem(key=item.key, data=item.data, etag=item.etag, error=item.error)
)
return BulkStatesResponse(items=items, headers=call.initial_metadata())
def query_state(
self, store_name: str, query: str, states_metadata: Optional[Dict[str, str]] = dict()
) -> QueryResponse:
"""Queries a statestore with a query
For details on supported queries see https://docs.dapr.io/
This example queries a statestore:
from dapr.clients import DaprClient
query = '''
{
"filter": {
"EQ": { "state": "CA" }
},
"sort": [
{
"key": "person.id",
"order": "DESC"
}
]
}
'''
with DaprClient() as d:
resp = d.query_state(
store_name='state_store',
query=query,
states_metadata={"metakey": "metavalue"},
)
Args:
store_name (str): the state store name to query
query (str): the query to be executed
states_metadata (Dict[str, str], optional): custom metadata for state request
Returns:
:class:`QueryStateResponse` gRPC metadata returned from callee,
pagination token and results of the query
"""
warn(
'The State Store Query API is an Alpha version and is subject to change.',
UserWarning,
stacklevel=2,
)
if not store_name or len(store_name) == 0 or len(store_name.strip()) == 0:
raise ValueError('State store name cannot be empty')
req = api_v1.QueryStateRequest(store_name=store_name, query=query, metadata=states_metadata)
try:
response, call = self._stub.QueryStateAlpha1.with_call(req)
except RpcError as err:
raise DaprGrpcError(err) from err
results = []
for item in response.results:
results.append(
QueryResponseItem(key=item.key, value=item.data, etag=item.etag, error=item.error)
)
return QueryResponse(
token=response.token,
results=results,
metadata=response.metadata,
headers=call.initial_metadata(),
)
def save_state(
self,
store_name: str,
key: str,
value: Union[bytes, str],
etag: Optional[str] = None,
options: Optional[StateOptions] = None,
state_metadata: Optional[Dict[str, str]] = dict(),
metadata: Optional[MetadataTuple] = None,
) -> DaprResponse:
"""Saves key-value pairs to a statestore
This saves a value to the statestore with a given key and state store name.
Options for request can be passed with the options field and custom
metadata can be passed with metadata field.
The example saves states to a statestore:
from dapr.clients import DaprClient
with DaprClient() as d:
resp = d.save_state(
store_name='state_store',
key='key1',
value='value1',
etag='etag',
state_metadata={"metakey": "metavalue"},
)
Args:
store_name (str): the state store name to save to
key (str): the key to be saved
value (bytes or str): the value to be saved
etag (str, optional): the etag to save with
options (StateOptions, optional): custom options
for concurrency and consistency
state_metadata (Dict[str, str], optional): Dapr metadata for state request
metadata (tuple, optional, DEPRECATED): gRPC custom metadata
Returns:
:class:`DaprResponse` gRPC metadata returned from callee
Raises:
ValueError: value is not bytes or str
ValueError: store_name is empty
"""
if metadata is not None:
warn(
'metadata argument is deprecated. Dapr already intercepts API token headers '
'and this is not needed.',
DeprecationWarning,
stacklevel=2,
)
if not isinstance(value, (bytes, str)):
raise ValueError(f'invalid type for data {type(value)}')
req_value = value
if not store_name or len(store_name) == 0 or len(store_name.strip()) == 0:
raise ValueError('State store name cannot be empty')
if options is None:
state_options = None
else:
state_options = options.get_proto()
state = common_v1.StateItem(
key=key,
value=to_bytes(req_value),
etag=common_v1.Etag(value=etag) if etag is not None else None,
options=state_options,
metadata=state_metadata,
)
req = api_v1.SaveStateRequest(store_name=store_name, states=[state])
try:
_, call = self._stub.SaveState.with_call(req, metadata=metadata)
return DaprResponse(headers=call.initial_metadata())
except RpcError as err:
raise DaprGrpcError(err) from err
def save_bulk_state(
self, store_name: str, states: List[StateItem], metadata: Optional[MetadataTuple] = None
) -> DaprResponse:
"""Saves state items to a statestore
This saves a given state item into the statestore specified by store_name.
The example saves states to a statestore:
from dapr.clients import DaprClient
with DaprClient() as d:
resp = d.save_bulk_state(
store_name='state_store',
states=[StateItem(key='key1', value='value1'),
StateItem(key='key2', value='value2', etag='etag'),],
)
Args:
store_name (str): the state store name to save to
states (List[StateItem]): list of states to save
metadata (tuple, optional): gRPC custom metadata
Returns:
:class:`DaprResponse` gRPC metadata returned from callee
Raises:
ValueError: states is empty
ValueError: store_name is empty
"""
if metadata is not None:
warn(
'metadata argument is deprecated. Dapr already intercepts API token headers '
'and this is not needed.',
DeprecationWarning,
stacklevel=2,
)
if not states or len(states) == 0:
raise ValueError('States to be saved cannot be empty')
if not store_name or len(store_name) == 0 or len(store_name.strip()) == 0:
raise ValueError('State store name cannot be empty')
req_states = [
common_v1.StateItem(
key=i.key,
value=to_bytes(i.value),
etag=common_v1.Etag(value=i.etag) if i.etag is not None else None,
options=i.options,
metadata=i.metadata,
)
for i in states
]
req = api_v1.SaveStateRequest(store_name=store_name, states=req_states)
try:
_, call = self._stub.SaveState.with_call(req, metadata=metadata)
return DaprResponse(headers=call.initial_metadata())
except RpcError as err:
raise DaprGrpcError(err) from err
def execute_state_transaction(
self,
store_name: str,
operations: Sequence[TransactionalStateOperation],
transactional_metadata: Optional[Dict[str, str]] = dict(),
metadata: Optional[MetadataTuple] = None,
) -> DaprResponse:
"""Saves or deletes key-value pairs to a statestore as a transaction
This saves or deletes key-values to the statestore as part of a single transaction,
transaction_metadata is used for the transaction operation, while metadata is used
for the GRPC call.
The example saves states to a statestore:
from dapr.clients import DaprClient
with DaprClient() as d:
resp = d.execute_state_transaction(
store_name='state_store',
operations=[
TransactionalStateOperation(key=key, data=value),
TransactionalStateOperation(key=another_key, data=another_value),
TransactionalStateOperation(
operation_type=TransactionOperationType.delete,
key=key_to_delete),
],
transactional_metadata={"header1": "value1"},
)
Args:
store_name (str): the state store name to save to
operations (Sequence[TransactionalStateOperation]): the transaction operations
transactional_metadata (Dict[str, str], optional): Dapr metadata for transaction
metadata (tuple, optional, DEPRECATED): gRPC custom metadata
Returns:
:class:`DaprResponse` gRPC metadata returned from callee
"""
if metadata is not None:
warn(
'metadata argument is deprecated. Dapr already intercepts API token headers '
'and this is not needed.',
DeprecationWarning,
stacklevel=2,
)
if not store_name or len(store_name) == 0 or len(store_name.strip()) == 0:
raise ValueError('State store name cannot be empty')
req_ops = [
api_v1.TransactionalStateOperation(
operationType=o.operation_type.value,
request=common_v1.StateItem(
key=o.key,
value=to_bytes(o.data),
etag=common_v1.Etag(value=o.etag) if o.etag is not None else None,
),
)
for o in operations
]
req = api_v1.ExecuteStateTransactionRequest(
storeName=store_name, operations=req_ops, metadata=transactional_metadata
)
try:
_, call = self._stub.ExecuteStateTransaction.with_call(req, metadata=metadata)
return DaprResponse(headers=call.initial_metadata())
except RpcError as err:
raise DaprGrpcError(err) from err
def delete_state(
self,
store_name: str,
key: str,
etag: Optional[str] = None,
options: Optional[StateOptions] = None,
state_metadata: Optional[Dict[str, str]] = dict(),
metadata: Optional[MetadataTuple] = None,
) -> DaprResponse:
"""Deletes key-value pairs from a statestore
This deletes a value from the statestore with a given key and state store name.
Options for request can be passed with the options field and custom
metadata can be passed with metadata field.
The example deletes states from a statestore:
from dapr.clients import DaprClient
with DaprClient() as d:
resp = d.delete_state(
store_name='state_store',
key='key1',
etag='etag',
state_metadata={"header1": "value1"},
)
Args:
store_name (str): the state store name to delete from
key (str): the key of the key-value pair to delete
etag (str, optional): the etag to delete with
options (StateOptions, optional): custom options
for concurrency and consistency
state_metadata (Dict[str, str], optional): Dapr metadata for state request
metadata (tuple, optional, DEPRECATED): gRPC custom metadata
Returns:
:class:`DaprResponse` gRPC metadata returned from callee
"""
if metadata is not None:
warn(
'metadata argument is deprecated. Dapr already intercepts API token '
'headers and this is not needed.',
DeprecationWarning,
stacklevel=2,
)
if not store_name or len(store_name) == 0 or len(store_name.strip()) == 0:
raise ValueError('State store name cannot be empty')
if options is None:
state_options = None
else:
state_options = options.get_proto()
etag_object = common_v1.Etag(value=etag) if etag is not None else None
req = api_v1.DeleteStateRequest(
store_name=store_name,
key=key,
etag=etag_object,
options=state_options,
metadata=state_metadata,
)
try:
_, call = self._stub.DeleteState.with_call(req, metadata=metadata)
return DaprResponse(headers=call.initial_metadata())
except RpcError as err:
raise DaprGrpcError(err) from err
def get_secret(
self,
store_name: str,
key: str,
secret_metadata: Optional[Dict[str, str]] = {},
metadata: Optional[MetadataTuple] = None,
) -> GetSecretResponse:
"""Get secret with a given key.
This gets a secret from secret store with a given key and secret store name.
Metadata for request can be passed with the secret_metadata field and custom
metadata can be passed with metadata field.
The example gets a secret from secret store:
from dapr.clients import DaprClient
with DaprClient() as d:
resp = d.get_secret(
store_name='secretstoreA',
key='keyA',
secret_metadata={'header1', 'value1'}
)
# resp.headers includes the gRPC initial metadata.
# resp.trailers includes that gRPC trailing metadata.
Args:
store_name (str): store name to get secret from
key (str): str for key
secret_metadata (Dict[str, str], Optional): Dapr metadata for secrets request
metadata (MetadataTuple, optional, DEPRECATED): gRPC custom metadata
Returns:
:class:`GetSecretResponse` object with the secret and metadata returned from callee
"""
if metadata is not None:
warn(
'metadata argument is deprecated. Dapr already intercepts API token '
'headers and this is not needed.',
DeprecationWarning,
stacklevel=2,
)
req = api_v1.GetSecretRequest(store_name=store_name, key=key, metadata=secret_metadata)
response, call = self._stub.GetSecret.with_call(req, metadata=metadata)
return GetSecretResponse(secret=response.data, headers=call.initial_metadata())
def get_bulk_secret(
self,
store_name: str,
secret_metadata: Optional[Dict[str, str]] = {},
metadata: Optional[MetadataTuple] = None,
) -> GetBulkSecretResponse:
"""Get all granted secrets.
This gets all granted secrets from secret store.
Metadata for request can be passed with the secret_metadata field.
The example gets all secrets from secret store:
from dapr.clients import DaprClient
with DaprClient() as d:
resp = d.get_bulk_secret(
store_name='secretstoreA',
secret_metadata={'header1', 'value1'}
)
# resp.headers includes the gRPC initial metadata.
# resp.trailers includes that gRPC trailing metadata.
Args:
store_name (str): store name to get secret from
secret_metadata (Dict[str, Dict[str, str]], Optional): Dapr metadata of secrets request
metadata (MetadataTuple, optional, DEPRECATED): gRPC custom metadata
Returns:
:class:`GetBulkSecretResponse` object with secrets and metadata returned from callee
"""
if metadata is not None: