-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
rpc.py
1250 lines (1043 loc) 路 48.5 KB
/
rpc.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
# Copyright 2016-2021, Pulumi Corporation.
#
# 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.
"""
Support for serializing and deserializing properties going into or flowing
out of RPC calls.
"""
import asyncio
from collections import abc
import functools
import inspect
from abc import ABC, abstractmethod
from typing import (
List,
Any,
Callable,
Dict,
Mapping,
Optional,
Sequence,
Set,
TYPE_CHECKING,
cast,
)
from enum import Enum
from google.protobuf import struct_pb2
from semver import VersionInfo as Version
import six
from . import known_types, settings
from .resource import _expand_dependencies
from .. import log
from .. import _types
from .. import urn as urn_util
if TYPE_CHECKING:
from ..output import Inputs, Input, Output
from ..resource import CustomResource, Resource, ProviderResource
from ..asset import (
FileAsset,
RemoteAsset,
StringAsset,
FileArchive,
RemoteArchive,
AssetArchive,
)
UNKNOWN = "04da6b54-80e4-46f7-96ec-b56ff0331ba9"
"""If a value is None, we serialize as UNKNOWN, which tells the engine that it may be computed later."""
_special_sig_key = "4dabf18193072939515e22adb298388d"
"""
_special_sig_key is sometimes used to encode type identity inside of a map.
See sdk/go/common/resource/properties.go.
"""
_special_asset_sig = "c44067f5952c0a294b673a41bacd8c17"
"""
special_asset_sig is a randomly assigned hash used to identify assets in maps.
See sdk/go/common/resource/asset.go.
"""
_special_archive_sig = "0def7320c3a5731c473e5ecbe6d01bc7"
"""
special_archive_sig is a randomly assigned hash used to identify assets in maps.
See sdk/go/common/resource/asset.go.
"""
_special_secret_sig = "1b47061264138c4ac30d75fd1eb44270"
"""
special_secret_sig is a randomly assigned hash used to identify secrets in maps.
See sdk/go/common/resource/properties.go.
"""
_special_resource_sig = "5cf8f73096256a8f31e491e813e4eb8e"
"""
special_resource_sig is a randomly assigned hash used to identify resources in maps.
See sdk/go/common/resource/properties.go.
"""
_special_output_value_sig = "d0e6a833031e9bbcd3f4e8bde6ca49a4"
"""
_special_output_value_sig is a randomly assigned hash used to identify outputs in maps.
See sdk/go/common/resource/properties.go.
"""
_INT_OR_FLOAT = six.integer_types + (float,)
# This setting overrides a hardcoded maximum protobuf size in the python protobuf bindings. This avoids deserialization
# exceptions on large gRPC payloads, but makes it possible to use enough memory to cause an OOM error instead [1].
# Note: We hit the default maximum protobuf size in practice when processing Kubernetes CRDs [2]. If this setting ends
# up causing problems, it should be possible to work around it with more intelligent resource chunking in the k8s
# provider.
#
# [1] https://github.com/protocolbuffers/protobuf/blob/0a59054c30e4f0ba10f10acfc1d7f3814c63e1a7/python/google/protobuf/pyext/message.cc#L2017-L2024
# [2] https://github.com/pulumi/pulumi-kubernetes/issues/984
#
# This setting requires a platform-specific and python version-specific .so file called
# `_message.cpython-[py-version]-[platform].so`, which is not present in situations when a new python version is
# released but the corresponding dist wheel has not been. So, we wrap the import in a try/except to avoid breaking all
# python programs using a new version.
try:
from google.protobuf.pyext._message import ( # pylint: disable-msg=C0412
SetAllowOversizeProtos,
) # pylint: disable-msg=E0611
SetAllowOversizeProtos(True)
except ImportError:
pass
# New versions of protobuf have moved the above import to api_implementation
try:
from google.protobuf.pyext import (
cpp_message,
) # pylint: disable-msg=E0611
if cpp_message._message is not None:
cpp_message._message.SetAllowOversizeProtos(True)
except ImportError:
pass
def isLegalProtobufValue(value: Any) -> bool:
"""
Returns True if the given value is a legal Protobuf value as per the source at
https://github.com/protocolbuffers/protobuf/blob/master/python/google/protobuf/internal/well_known_types.py#L714-L732
"""
return value is None or isinstance(
value, (bool, six.string_types, _INT_OR_FLOAT, dict, list)
)
def _get_list_element_type(typ: Optional[type]) -> Optional[type]:
if typ is None:
return None
# Annotations not specifying the element type are assumed by mypy
# to signify Any element type. Follow suit here.
if typ in [list, List, Sequence, abc.Sequence]:
return cast(type, Any)
# If typ is a list, get the type for its values, to pass
# along for each item.
origin = _types.get_origin(typ)
if typ is list or origin in [list, List, Sequence, abc.Sequence]:
args = _types.get_args(typ)
if len(args) == 1:
return args[0]
raise AssertionError(f"Unexpected type. Expected 'list' got '{typ}'")
async def serialize_properties(
inputs: "Inputs",
property_deps: Dict[str, List["Resource"]],
input_transformer: Optional[Callable[[str], str]] = None,
typ: Optional[type] = None,
keep_output_values: Optional[bool] = None,
) -> struct_pb2.Struct:
"""
Serializes an arbitrary Input bag into a Protobuf structure, keeping track of the list
of dependent resources in the `deps` list. Serializing properties is inherently async
because it awaits any futures that are contained transitively within the input bag.
When `typ` is an input type, the metadata from the type is used to translate Python snake_case
names to Pulumi camelCase names, rather than using the `input_transformer`.
Modifies given property_deps dict to collect discovered dependencies by property name.
:param Inputs inputs: The bag to serialize.
:param Dict[str, List[Resource]] property_deps: Dependencies are set here.
:param input_transfomer: Optional name translator.
"""
# Default implementation of get_type that always returns None.
get_type: Callable[[str], Optional[type]] = lambda k: None
# Key translator.
translate = input_transformer
# If we have type information, we'll use it to do name translations rather than using
# any passed-in input_transformer.
if typ is not None:
py_name_to_pulumi_name = _types.input_type_py_to_pulumi_names(typ)
types = _types.input_type_types(typ)
# pylint: disable=C3001
translate = lambda k: py_name_to_pulumi_name.get(k) or k
# pylint: disable=C3001
get_type = lambda k: types.get(translate(k)) # type: ignore
struct = struct_pb2.Struct()
# We're deliberately not using `inputs.items()` here in case inputs is a subclass of `dict` that redefines items.
for k in inputs:
v = inputs[k]
deps: List["Resource"] = []
result = await serialize_property(
v, deps, input_transformer, get_type(k), keep_output_values
)
# We treat properties that serialize to None as if they don't exist.
if result is not None:
# While serializing to a pb struct, we must "translate" all key names to be what the
# engine is going to expect. Resources provide the "transform" function for doing this.
translated_name = k
if translate is not None:
translated_name = translate(k)
if settings.excessive_debug_output:
log.debug(
f"top-level input property translated: {k} -> {translated_name}"
)
# pylint: disable=unsupported-assignment-operation
struct[translated_name] = result
property_deps[translated_name] = deps
return struct
# pylint: disable=too-many-return-statements, too-many-branches
async def serialize_property(
value: "Input[Any]",
deps: List["Resource"],
input_transformer: Optional[Callable[[str], str]] = None,
typ: Optional[type] = None,
keep_output_values: Optional[bool] = None,
) -> Any:
"""
Serializes a single Input into a form suitable for remoting to the engine, awaiting
any futures required to do so.
When `typ` is specified, the metadata from the type is used to translate Python snake_case
names to Pulumi camelCase names, rather than using the `input_transformer`.
If `keep_output_values` is true and the monitor supports output values, they will be kept.
"""
# Set typ to T if it's Optional[T], Input[T], or InputType[T].
typ = _types.unwrap_type(typ) if typ else typ
# If the typ is Any, set it to None to treat it as if we don't have any type information,
# to avoid raising errors about unexpected types, since it could be any type.
if typ is Any:
typ = None
# Exclude some built-in types that are instances of Sequence that we don't want to treat as sequences here.
# From: https://github.com/python/cpython/blob/master/Lib/_collections_abc.py
if isinstance(value, abc.Sequence) and not isinstance(
value, (tuple, str, range, memoryview, bytes, bytearray)
):
element_type = _get_list_element_type(typ)
props = []
for elem in value:
props.append(
await serialize_property(
elem, deps, input_transformer, element_type, keep_output_values
)
)
return props
if known_types.is_unknown(value):
return UNKNOWN
if known_types.is_resource(value):
resource = cast("Resource", value)
is_custom = known_types.is_custom_resource(value)
resource_id = cast("CustomResource", value).id if is_custom else None
# If we're retaining resources, serialize the resource as a reference.
if await settings.monitor_supports_resource_references():
res = {
_special_sig_key: _special_resource_sig,
"urn": await serialize_property(
resource.urn, deps, input_transformer, keep_output_values=False
),
}
if is_custom:
res["id"] = await serialize_property(
resource_id, deps, input_transformer, keep_output_values=False
)
return res
# Otherwise, serialize the resource as either its ID (for custom resources) or its URN (for component resources)
return await serialize_property(
resource_id if is_custom else resource.urn,
deps,
input_transformer,
keep_output_values=False,
)
if known_types.is_asset(value):
# Serializing an asset requires the use of a magical signature key, since otherwise it would
# look like any old weakly typed object/map when received by the other side of the RPC
# boundary.
obj = {_special_sig_key: _special_asset_sig}
if hasattr(value, "path"):
file_asset = cast("FileAsset", value)
obj["path"] = await serialize_property(
file_asset.path, deps, input_transformer, keep_output_values=False
)
elif hasattr(value, "text"):
str_asset = cast("StringAsset", value)
obj["text"] = await serialize_property(
str_asset.text, deps, input_transformer, keep_output_values=False
)
elif hasattr(value, "uri"):
remote_asset = cast("RemoteAsset", value)
obj["uri"] = await serialize_property(
remote_asset.uri, deps, input_transformer, keep_output_values=False
)
else:
raise AssertionError(f"unknown asset type: {value!r}")
return obj
if known_types.is_archive(value):
# Serializing an archive requires the use of a magical signature key, since otherwise it
# would look like any old weakly typed object/map when received by the other side of the RPC
# boundary.
obj = {_special_sig_key: _special_archive_sig}
if hasattr(value, "assets"):
asset_archive = cast("AssetArchive", value)
obj["assets"] = await serialize_property(
asset_archive.assets, deps, input_transformer, keep_output_values=False
)
elif hasattr(value, "path"):
file_archive = cast("FileArchive", value)
obj["path"] = await serialize_property(
file_archive.path, deps, input_transformer, keep_output_values=False
)
elif hasattr(value, "uri"):
remote_archive = cast("RemoteArchive", value)
obj["uri"] = await serialize_property(
remote_archive.uri, deps, input_transformer, keep_output_values=False
)
else:
raise AssertionError(f"unknown archive type: {value!r}")
return obj
if inspect.isawaitable(value):
# Coroutines and Futures are both awaitable. Coroutines need to be scheduled.
# asyncio.ensure_future returns futures verbatim while converting coroutines into
# futures by arranging for the execution on the event loop.
#
# The returned future can then be awaited to yield a value, which we'll continue
# serializing.
awaitable = cast("Any", value)
future_return = await asyncio.ensure_future(awaitable)
return await serialize_property(
future_return, deps, input_transformer, typ, keep_output_values
)
if known_types.is_output(value):
output = cast("Output", value)
value_resources: Set["Resource"] = await output.resources()
deps.extend(value_resources)
# When serializing an Output, we will either serialize it as its resolved value or the
# "unknown value" sentinel. We will do the former for all outputs created directly by user
# code (such outputs always resolve isKnown to true) and for any resource outputs that were
# resolved with known values.
is_known = await output._is_known
is_secret = await output._is_secret
promise_deps: List["Resource"] = []
value = await serialize_property(
output.future(),
promise_deps,
input_transformer,
typ,
keep_output_values=False,
)
deps.extend(promise_deps)
value_resources.update(promise_deps)
if keep_output_values and await settings.monitor_supports_output_values():
urn_deps: List["Resource"] = []
for resource in value_resources:
await serialize_property(
resource.urn, urn_deps, input_transformer, keep_output_values=False
)
promise_deps.extend(set(urn_deps))
value_resources.update(urn_deps)
dependencies = await _expand_dependencies(value_resources, None)
output_value: Dict[str, Any] = {_special_sig_key: _special_output_value_sig}
if is_known:
output_value["value"] = value
if is_secret:
output_value["secret"] = is_secret
if dependencies:
output_value["dependencies"] = sorted(dependencies)
return output_value
if not is_known:
return UNKNOWN
if is_secret and await settings.monitor_supports_secrets():
# Serializing an output with a secret value requires the use of a magical signature key,
# which the engine detects.
return {_special_sig_key: _special_secret_sig, "value": value}
return value
# If value is an input type, convert it to a dict.
value_cls = type(value)
if _types.is_input_type(value_cls):
value = _types.input_type_to_dict(value)
types = _types.input_type_types(value_cls)
return {
k: await serialize_property(
v, deps, input_transformer, types.get(k), keep_output_values
)
for k, v in value.items()
}
if isinstance(value, abc.Mapping):
# Default implementation of get_type that always returns None.
get_type: Callable[[str], Optional[type]] = lambda k: None
# Key translator.
translate = input_transformer
# If we have type information, we'll use it to do name translations rather than using
# any passed-in input_transformer.
if typ is not None:
if _types.is_input_type(typ):
# If it's intended to be an input type, translate using the type's metadata.
py_name_to_pulumi_name = _types.input_type_py_to_pulumi_names(typ)
# pylint: disable=C3001
types = _types.input_type_types(typ)
# pylint: disable=C3001
translate = lambda k: py_name_to_pulumi_name.get(k) or k
get_type = types.get
else:
# Otherwise, don't do any translation of user-defined dict keys.
origin = _types.get_origin(typ)
if typ is dict or origin in [dict, Dict, Mapping, abc.Mapping]:
args = _types.get_args(typ)
if len(args) == 2 and args[0] is str:
# pylint: disable=C3001
get_type = lambda k: args[1]
translate = None
else:
translate = None
# Note: Alternatively, we could assert here that we expected a dict type but got some other type,
# but there are cases where we've historically allowed a user-defined dict value to be passed even
# though the type annotation isn't a dict type (e.g. the `aws.s3.BucketPolicy.policy` input property
# is currently typed as `pulumi.Input[str]`, but we've allowed a dict to be passed, which will
# "magically" work at runtime because the provider will convert the dict value to a JSON string).
# Ideally, we'd update the type annotations for such cases to reflect that a dict could be passed,
# but we haven't done that yet and want these existing cases to continue to work as they have
# before.
obj = {}
# Don't use value.items() here, as it will error in the case of outputs with an `items` property.
for k in value:
transformed_key = k
if translate is not None:
transformed_key = translate(k)
if settings.excessive_debug_output:
log.debug(f"transforming input property: {k} -> {transformed_key}")
obj[transformed_key] = await serialize_property(
value[k],
deps,
input_transformer,
get_type(transformed_key),
keep_output_values,
)
return obj
# Ensure that we have a value that Protobuf understands.
if not isLegalProtobufValue(value):
raise ValueError(f"unexpected input of type {type(value).__name__}")
return value
# pylint: disable=too-many-return-statements
def deserialize_properties(
props_struct: struct_pb2.Struct,
keep_unknowns: Optional[bool] = None,
keep_internal: Optional[bool] = None,
) -> Any:
"""
Deserializes a protobuf `struct_pb2.Struct` into a Python dictionary containing normal
Python types.
"""
# Check out this link for details on what sort of types Protobuf is going to generate:
# https://developers.google.com/protocol-buffers/docs/reference/python-generated
#
# We assume that we are deserializing properties that we got from a Resource RPC endpoint,
# which has type `Struct` in our gRPC proto definition.
if _special_sig_key in props_struct:
from .. import ( # pylint: disable=import-outside-toplevel
FileAsset,
StringAsset,
RemoteAsset,
AssetArchive,
FileArchive,
RemoteArchive,
)
if props_struct[_special_sig_key] == _special_asset_sig:
# This is an asset. Re-hydrate this object into an Asset.
if "path" in props_struct:
return FileAsset(props_struct["path"])
if "text" in props_struct:
return StringAsset(props_struct["text"])
if "uri" in props_struct:
return RemoteAsset(props_struct["uri"])
raise AssertionError(
"Invalid asset encountered when unmarshalling resource property"
)
if props_struct[_special_sig_key] == _special_archive_sig:
# This is an archive. Re-hydrate this object into an Archive.
if "assets" in props_struct:
return AssetArchive(deserialize_property(props_struct["assets"]))
if "path" in props_struct:
return FileArchive(props_struct["path"])
if "uri" in props_struct:
return RemoteArchive(props_struct["uri"])
raise AssertionError(
"Invalid archive encountered when unmarshalling resource property"
)
if props_struct[_special_sig_key] == _special_secret_sig:
return wrap_rpc_secret(deserialize_property(props_struct["value"]))
if props_struct[_special_sig_key] == _special_resource_sig:
return deserialize_resource(props_struct, keep_unknowns)
if props_struct[_special_sig_key] == _special_output_value_sig:
return deserialize_output_value(props_struct)
raise AssertionError(
"Unrecognized signature when unmarshalling resource property"
)
# Struct is duck-typed like a dictionary, so we can iterate over it in the normal ways. Note
# that if the struct had any secret properties, we push the secretness of the object up to us
# since we can only set secret outputs on top level properties.
output = {}
for k, v in list(props_struct.items()):
# Unilaterally skip properties considered internal by the Pulumi engine.
# These don't actually contribute to the exposed shape of the object, do
# not need to be passed back to the engine, and often will not match the
# expected type we are deserializing into.
# Keep "__provider" as it's the property name used by Python dynamic providers.
if not keep_internal and k.startswith("__") and k != "__provider":
continue
value = deserialize_property(v, keep_unknowns)
# We treat values that deserialize to "None" as if they don't exist.
if value is not None:
output[k] = value
return output
def deserialize_resource(
ref_struct: struct_pb2.Struct, keep_unknowns: Optional[bool] = None
) -> "Resource":
urn = ref_struct["urn"]
version = ref_struct["packageVersion"] if "packageVersion" in ref_struct else ""
urn_parts = urn_util._parse_urn(urn)
urn_name = urn_parts.urn_name
typ = urn_parts.typ
pkg_name = urn_parts.pkg_name
mod_name = urn_parts.mod_name
typ_name = urn_parts.typ_name
is_provider = pkg_name == "pulumi" and mod_name == "providers"
if is_provider:
resource_package = get_resource_package(typ_name, version)
if resource_package is not None:
return cast(
"Resource", resource_package.construct_provider(urn_name, typ, urn)
)
else:
resource_module = get_resource_module(pkg_name, mod_name, version)
if resource_module is not None:
return cast("Resource", resource_module.construct(urn_name, typ, urn))
# If we've made it here, deserialize the reference as either a URN or an ID (if present).
if "id" in ref_struct:
ref_id = ref_struct["id"]
return deserialize_property(UNKNOWN if ref_id == "" else ref_id, keep_unknowns)
return urn
def deserialize_output_value(ref_struct: struct_pb2.Struct) -> "Output[Any]":
is_known = "value" in ref_struct
is_known_future: "asyncio.Future" = asyncio.Future()
is_known_future.set_result(is_known)
value = None
if is_known:
value = deserialize_property(ref_struct["value"])
value_future: "asyncio.Future" = asyncio.Future()
value_future.set_result(value)
is_secret = False
if "secret" in ref_struct:
is_secret = deserialize_property(ref_struct["secret"]) is True
is_secret_future: "asyncio.Future" = asyncio.Future()
is_secret_future.set_result(is_secret)
resources: Set["Resource"] = set()
if "dependencies" in ref_struct:
from ..resource import ( # pylint: disable=import-outside-toplevel
DependencyResource,
)
dependencies = cast(List[str], deserialize_property(ref_struct["dependencies"]))
for urn in dependencies:
resources.add(DependencyResource(urn))
from .. import Output # pylint: disable=import-outside-toplevel
return Output(resources, value_future, is_known_future, is_secret_future)
def is_rpc_secret(value: Any) -> bool:
"""
Returns if a given python value is actually a wrapped secret.
"""
return (
isinstance(value, dict)
and _special_sig_key in value
and value[_special_sig_key] == _special_secret_sig
)
def wrap_rpc_secret(value: Any) -> Any:
"""
Given a value, wrap it as a secret value if it isn't already a secret, otherwise return the value unmodified.
"""
if is_rpc_secret(value):
return value
return {
_special_sig_key: _special_secret_sig,
"value": value,
}
def unwrap_rpc_secret(value: Any) -> Any:
"""
Given a value, if it is a wrapped secret value, return the underlying, otherwise return the value unmodified.
"""
if is_rpc_secret(value):
return value["value"]
return value
def deserialize_property(value: Any, keep_unknowns: Optional[bool] = None) -> Any:
"""
Deserializes a single protobuf value (either `Struct` or `ListValue`) into idiomatic
Python values.
"""
from ..output import Unknown # pylint: disable=import-outside-toplevel
if value == UNKNOWN:
return Unknown() if settings.is_dry_run() or keep_unknowns else None
# ListValues are projected to lists
if isinstance(value, struct_pb2.ListValue):
# values has no __iter__ defined but this works.
values = [deserialize_property(v, keep_unknowns) for v in value] # type: ignore
# If there are any secret values in the list, push the secretness "up" a level by returning
# an array that is marked as a secret with raw values inside.
if any(is_rpc_secret(v) for v in values):
return wrap_rpc_secret([unwrap_rpc_secret(v) for v in values])
return values
# Structs are projected to dictionaries
if isinstance(value, struct_pb2.Struct):
props = deserialize_properties(value, keep_unknowns)
# If there are any secret values in the dictionary, push the secretness "up" a level by returning
# a dictionary that is marked as a secret with raw values inside. Note: the isinstance check here is
# important, since deserialize_properties will return either a dictionary or a concret type (in the case of
# assets).
if isinstance(props, dict) and any(is_rpc_secret(v) for v in props.values()):
return wrap_rpc_secret({k: unwrap_rpc_secret(v) for k, v in props.items()})
return props
# Everything else is identity projected.
return value
Resolver = Callable[
[Any, bool, bool, Optional[Set["Resource"]], Optional[Exception]], None
]
"""
A Resolver is a function that takes four arguments:
1. A value, which represents the "resolved" value of a particular output (from the engine)
2. A boolean "is_known", which represents whether or not this value is known to have a particular value at this
point in time (not always true for previews), and
3. A boolean "is_secret", which represents whether or not this value is contains secret data, and
4. An exception, which (if provided) is an exception that occured when attempting to create the resource to whom
this resolver belongs.
If argument 4 is not none, this output is considered to be abnormally resolved and attempts to await its future will
result in the exception being re-thrown.
"""
def transfer_properties(res: "Resource", props: "Inputs") -> Dict[str, Resolver]:
from .. import Output # pylint: disable=import-outside-toplevel
resolvers: Dict[str, Resolver] = {}
for name in props:
if name in ["id", "urn"]:
# these properties are handled specially elsewhere.
continue
resolve_value: "asyncio.Future" = asyncio.Future()
resolve_is_known: "asyncio.Future" = asyncio.Future()
resolve_is_secret: "asyncio.Future" = asyncio.Future()
resolve_deps: "asyncio.Future" = asyncio.Future()
def do_resolve(
r: "Resource",
value_fut: "asyncio.Future",
known_fut: "asyncio.Future[bool]",
secret_fut: "asyncio.Future[bool]",
deps_fut: "asyncio.Future[Set[Resource]]",
value: Any,
is_known: bool,
is_secret: bool,
deps: Set["Resource"],
failed: Optional[Exception],
):
# Create a union of deps and the resource.
deps_union = set(deps) if deps else set()
deps_union.add(r)
deps_fut.set_result(deps_union)
# Was an exception provided? If so, this is an abnormal (exceptional) resolution. Resolve the futures
# using set_exception so that any attempts to wait for their resolution will also fail.
if failed is not None:
value_fut.set_exception(failed)
known_fut.set_exception(failed)
secret_fut.set_exception(failed)
else:
value_fut.set_result(value)
known_fut.set_result(is_known)
secret_fut.set_result(is_secret)
# Important to note here is that the resolver's future is assigned to the resource object using the
# name before translation. When properties are returned from the engine, we must first translate the name
# from the Pulumi name to the Python name and then use *that* name to index into the resolvers table.
resolvers[name] = functools.partial(
do_resolve,
res,
resolve_value,
resolve_is_known,
resolve_is_secret,
resolve_deps,
)
res.__dict__[name] = Output(
resolve_deps, resolve_value, resolve_is_known, resolve_is_secret
)
return resolvers
def translate_output_properties(
output: Any,
output_transformer: Callable[[str], str],
typ: Optional[type] = None,
transform_using_type_metadata: bool = False,
path: Optional["_Path"] = None,
return_none_on_dict_type_mismatch: bool = False,
) -> Any:
"""
Recursively rewrite keys of objects returned by the engine to conform with a naming
convention specified by `output_transformer`. If `transform_using_type_metadata` is
set to True, then the metadata from `typ` is used to do the translation, and `dict`
values that are intended to be user-defined dicts aren't translated at all.
Additionally, perform any type conversions as necessary, based on the optional `typ` parameter.
If output is a `dict`, every key is translated (unless `transform_using_type_metadata is True,
the dict isn't an output type, and it is intended to be a user-defined dict) while every value is
transformed by recursing.
If output is a `list`, every value is recursively transformed.
If output is a `dict` and `typ` is an output type, instantiate the output type,
passing the values in the dict to the output type's __init__() method.
If output is a `float` and `typ` is `int`, the value is cast to `int`.
If output is in [`str`, `int`, `float`] and `typ` is an enum type, instantiate the enum type.
Otherwise, if output is a primitive (i.e. not a dict or list), the value is returned without modification.
:param Any output: The output value.
:param Callable[[str], str] output_transformer: The function used to translate.
:param Optional[type] typ: The output's target type.
:param bool transform_using_type_metadata: Set to True to use the metadata from `typ` to do name translation instead
of using `output_transformer`.
:param Optional[Any] path: Used internally to track recursive descent and enhance error messages.
"""
# If it's a secret, unwrap the value so the output is in alignment with the expected type, call
# translate_output_properties with the unwrapped value, and then rewrap the result as a secret.
if is_rpc_secret(output):
unwrapped = unwrap_rpc_secret(output)
result = translate_output_properties(
unwrapped,
output_transformer,
typ,
transform_using_type_metadata,
path,
return_none_on_dict_type_mismatch,
)
return wrap_rpc_secret(result)
# Unwrap optional types.
typ = _types.unwrap_optional_type(typ) if typ else typ
# If the typ is Any, set it to None to treat it as if we don't have any type information,
# to avoid raising errors about unexpected types, since it could be any type.
if typ is Any:
typ = None
if isinstance(output, dict):
# Function called to lookup a type for a given key.
# The default always returns None.
get_type: Callable[[str], Optional[type]] = lambda k: None
translate = output_transformer
if typ is not None:
# If typ is an output type, instantiate it. We do not translate the top-level keys,
# as the output type will take care of doing that if it has a _translate_property()
# method.
if _types.is_output_type(typ):
# If typ is an output type, get its types, so we can pass the type along for each property.
types = _types.output_type_types(typ)
get_type = types.get
translated_values = {
k: translate_output_properties(
v,
output_transformer,
get_type(k),
transform_using_type_metadata,
_Path(k, parent=path),
return_none_on_dict_type_mismatch,
)
for k, v in output.items()
}
return _types.output_type_from_dict(typ, translated_values)
# If typ is a dict, get the type for its values, to pass along for each key.
origin = _types.get_origin(typ)
if typ is dict or origin in [dict, Dict, Mapping, abc.Mapping]:
args = _types.get_args(typ)
if len(args) == 2 and args[0] is str:
# pylint: disable=C3001
get_type = lambda k: args[1]
# If transform_using_type_metadata is True, don't translate its keys because
# it is intended to be a user-defined dict.
if transform_using_type_metadata:
# pylint: disable=C3001
translate = lambda k: k
elif return_none_on_dict_type_mismatch:
return None
else:
raise AssertionError(
(
f"Unexpected type; expected a value of type `{typ}`"
f" but got a value of type `{dict}`{_Path.format(path)}:"
f" {output}"
)
)
return {
translate(k): translate_output_properties(
v,
output_transformer,
get_type(k),
transform_using_type_metadata,
_Path(k, parent=path),
return_none_on_dict_type_mismatch,
)
for k, v in output.items()
}
if isinstance(output, list):
element_type = _get_list_element_type(typ)
return [
translate_output_properties(
v,
output_transformer,
element_type,
transform_using_type_metadata,
_Path(str(i), parent=path),
return_none_on_dict_type_mismatch,
)
for i, v in enumerate(output)
]
if (
typ
and isinstance(output, (int, float, str))
and inspect.isclass(typ)
and issubclass(typ, Enum)
):
return typ(output)
if isinstance(output, float) and typ is int:
return int(output)
return output
class _Path:
"""Internal helper for `translate_output_properties` error reporting,
essentially an immutable linked list of prop names with an
additional context resource name slot.
"""
prop: str
resource: Optional[str]
parent: Optional["_Path"]
def __init__(
self,
prop: str,
parent: Optional["_Path"] = None,
resource: Optional[str] = None,
) -> None:
self.prop = prop
self.parent = parent
self.resource = resource
@staticmethod
def format(path: Optional["_Path"]) -> str:
chain: List[str] = []
p: Optional[_Path] = path
resource: Optional[str] = None
while p is not None:
chain.append(p.prop)
resource = p.resource or resource
p = p.parent
chain.reverse()
coordinates = []
if resource is not None:
coordinates.append(f"resource `{resource}`")
if chain:
coordinates.append(f'property `{".".join(chain)}`')
if coordinates:
return f' at {", ".join(coordinates)}'
return ""
def contains_unknowns(val: Any) -> bool:
def impl(val: Any, stack: List[Any]) -> bool:
if known_types.is_unknown(val):
return True
if not any((x is val for x in stack)):
stack.append(val)
if isinstance(val, dict):
return any((impl(val[k], stack) for k in val))
if isinstance(val, list):
return any((impl(x, stack) for x in val))
return False
return impl(val, [])