2
0

model.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. # Copyright 2015 ksyun.com, Inc. or its affiliates. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"). You
  4. # may not use this file except in compliance with the License. A copy of
  5. # the License is located at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # or in the "license" file accompanying this file. This file is
  10. # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
  11. # ANY KIND, either express or implied. See the License for the specific
  12. # language governing permissions and limitations under the License.
  13. """Abstractions to interact with service models."""
  14. from collections import defaultdict
  15. from kscore.utils import CachedProperty, instance_cache
  16. from kscore.compat import OrderedDict
  17. NOT_SET = object()
  18. class NoShapeFoundError(Exception):
  19. pass
  20. class InvalidShapeError(Exception):
  21. pass
  22. class OperationNotFoundError(Exception):
  23. pass
  24. class InvalidShapeReferenceError(Exception):
  25. pass
  26. class UndefinedModelAttributeError(Exception):
  27. pass
  28. class Shape(object):
  29. """Object representing a shape from the service model."""
  30. # To simplify serialization logic, all shape params that are
  31. # related to serialization are moved from the top level hash into
  32. # a 'serialization' hash. This list below contains the names of all
  33. # the attributes that should be moved.
  34. SERIALIZED_ATTRS = ['locationName', 'queryName', 'flattened', 'location',
  35. 'payload', 'streaming', 'timestampFormat',
  36. 'xmlNamespace', 'resultWrapper', 'xmlAttribute']
  37. METADATA_ATTRS = ['required', 'min', 'max', 'sensitive', 'enum']
  38. MAP_TYPE = OrderedDict
  39. def __init__(self, shape_name, shape_model, shape_resolver=None):
  40. """
  41. :type shape_name: string
  42. :param shape_name: The name of the shape.
  43. :type shape_model: dict
  44. :param shape_model: The shape model. This would be the value
  45. associated with the key in the "shapes" dict of the
  46. service model (i.e ``model['shapes'][shape_name]``)
  47. :type shape_resolver: kscore.model.ShapeResolver
  48. :param shape_resolver: A shape resolver object. This is used to
  49. resolve references to other shapes. For scalar shape types
  50. (string, integer, boolean, etc.), this argument is not
  51. required. If a shape_resolver is not provided for a complex
  52. type, then a ``ValueError`` will be raised when an attempt
  53. to resolve a shape is made.
  54. """
  55. self.name = shape_name
  56. self.type_name = shape_model['type']
  57. self.documentation = shape_model.get('documentation', '')
  58. self._shape_model = shape_model
  59. if shape_resolver is None:
  60. # If a shape_resolver is not provided, we create an object
  61. # that will throw errors if you attempt to resolve
  62. # a shape. This is actually ok for scalar shapes
  63. # because they don't need to resolve shapes and shouldn't
  64. # be required to provide an object they won't use.
  65. shape_resolver = UnresolvableShapeMap()
  66. self._shape_resolver = shape_resolver
  67. self._cache = {}
  68. @CachedProperty
  69. def serialization(self):
  70. """Serialization information about the shape.
  71. This contains information that may be needed for input serialization
  72. or response parsing. This can include:
  73. * name
  74. * queryName
  75. * flattened
  76. * location
  77. * payload
  78. * streaming
  79. * xmlNamespace
  80. * resultWrapper
  81. * xmlAttribute
  82. :rtype: dict
  83. :return: Serialization information about the shape.
  84. """
  85. model = self._shape_model
  86. serialization = {}
  87. for attr in self.SERIALIZED_ATTRS:
  88. if attr in self._shape_model:
  89. serialization[attr] = model[attr]
  90. # For consistency, locationName is renamed to just 'name'.
  91. if 'locationName' in serialization:
  92. serialization['name'] = serialization.pop('locationName')
  93. return serialization
  94. @CachedProperty
  95. def metadata(self):
  96. """Metadata about the shape.
  97. This requires optional information about the shape, including:
  98. * min
  99. * max
  100. * enum
  101. * sensitive
  102. * required
  103. :rtype: dict
  104. :return: Metadata about the shape.
  105. """
  106. model = self._shape_model
  107. metadata = {}
  108. for attr in self.METADATA_ATTRS:
  109. if attr in self._shape_model:
  110. metadata[attr] = model[attr]
  111. return metadata
  112. @CachedProperty
  113. def required_members(self):
  114. """A list of members that are required.
  115. A structure shape can define members that are required.
  116. This value will return a list of required members. If there
  117. are no required members an empty list is returned.
  118. """
  119. return self.metadata.get('required', [])
  120. def _resolve_shape_ref(self, shape_ref):
  121. return self._shape_resolver.resolve_shape_ref(shape_ref)
  122. def __repr__(self):
  123. return "<%s(%s)>" % (self.__class__.__name__,
  124. self.name)
  125. class StructureShape(Shape):
  126. @CachedProperty
  127. def members(self):
  128. members = self._shape_model['members']
  129. # The members dict looks like:
  130. # 'members': {
  131. # 'MemberName': {'shape': 'shapeName'},
  132. # 'MemberName2': {'shape': 'shapeName'},
  133. # }
  134. # We return a dict of member name to Shape object.
  135. shape_members = self.MAP_TYPE()
  136. for name, shape_ref in members.items():
  137. shape_members[name] = self._resolve_shape_ref(shape_ref)
  138. return shape_members
  139. class ListShape(Shape):
  140. @CachedProperty
  141. def member(self):
  142. return self._resolve_shape_ref(self._shape_model['member'])
  143. class MapShape(Shape):
  144. @CachedProperty
  145. def key(self):
  146. return self._resolve_shape_ref(self._shape_model['key'])
  147. @CachedProperty
  148. def value(self):
  149. return self._resolve_shape_ref(self._shape_model['value'])
  150. class StringShape(Shape):
  151. @CachedProperty
  152. def enum(self):
  153. return self.metadata.get('enum', [])
  154. class ServiceModel(object):
  155. """
  156. :ivar service_description: The parsed service description dictionary.
  157. """
  158. def __init__(self, service_description, service_name=None):
  159. """
  160. :type service_description: dict
  161. :param service_description: The service description model. This value
  162. is obtained from a kscore.loader.Loader, or from directly loading
  163. the file yourself::
  164. service_description = json.load(
  165. open('/path/to/service-description-model.json'))
  166. model = ServiceModel(service_description)
  167. :type service_name: str
  168. :param service_name: The name of the service. Normally this is
  169. the endpoint prefix defined in the service_description. However,
  170. you can override this value to provide a more convenient name.
  171. This is done in a few places in kscore (ses instead of email,
  172. emr instead of elasticmapreduce). If this value is not provided,
  173. it will default to the endpointPrefix defined in the model.
  174. """
  175. self._service_description = service_description
  176. # We want clients to be able to access metadata directly.
  177. self.metadata = service_description.get('metadata', {})
  178. self._shape_resolver = ShapeResolver(
  179. service_description.get('shapes', {}))
  180. self._signature_version = NOT_SET
  181. self._service_name = service_name
  182. self._instance_cache = {}
  183. def shape_for(self, shape_name, member_traits=None):
  184. return self._shape_resolver.get_shape_by_name(
  185. shape_name, member_traits)
  186. def resolve_shape_ref(self, shape_ref):
  187. return self._shape_resolver.resolve_shape_ref(shape_ref)
  188. @instance_cache
  189. def operation_model(self, operation_name):
  190. try:
  191. model = self._service_description['operations'][operation_name]
  192. except KeyError:
  193. raise OperationNotFoundError(operation_name)
  194. return OperationModel(model, self, operation_name)
  195. @CachedProperty
  196. def documentation(self):
  197. return self._service_description.get('documentation', '')
  198. @CachedProperty
  199. def operation_names(self):
  200. return list(self._service_description.get('operations', []))
  201. @CachedProperty
  202. def service_name(self):
  203. """The name of the service.
  204. This defaults to the endpointPrefix defined in the service model.
  205. However, this value can be overriden when a ``ServiceModel`` is
  206. created. If a service_name was not provided when the ``ServiceModel``
  207. was created and if there is no endpointPrefix defined in the
  208. service model, then an ``UndefinedModelAttributeError`` exception
  209. will be raised.
  210. """
  211. if self._service_name is not None:
  212. return self._service_name
  213. else:
  214. return self.endpoint_prefix
  215. @CachedProperty
  216. def signing_name(self):
  217. """The name to use when computing signatures.
  218. If the model does not define a signing name, this
  219. value will be the endpoint prefix defined in the model.
  220. """
  221. signing_name = self.metadata.get('signingName')
  222. if signing_name is None:
  223. signing_name = self.endpoint_prefix
  224. return signing_name
  225. @CachedProperty
  226. def api_version(self):
  227. return self._get_metadata_property('apiVersion')
  228. @CachedProperty
  229. def protocol(self):
  230. return self._get_metadata_property('protocol')
  231. @CachedProperty
  232. def endpoint_prefix(self):
  233. return self._get_metadata_property('endpointPrefix')
  234. def _get_metadata_property(self, name):
  235. try:
  236. return self.metadata[name]
  237. except KeyError:
  238. raise UndefinedModelAttributeError(
  239. '"%s" not defined in the metadata of the the model: %s' %
  240. (name, self))
  241. # Signature version is one of the rare properties
  242. # than can be modified so a CachedProperty is not used here.
  243. @property
  244. def signature_version(self):
  245. if self._signature_version is NOT_SET:
  246. signature_version = self.metadata.get('signatureVersion')
  247. self._signature_version = signature_version
  248. return self._signature_version
  249. @signature_version.setter
  250. def signature_version(self, value):
  251. self._signature_version = value
  252. class OperationModel(object):
  253. def __init__(self, operation_model, service_model, name=None):
  254. """
  255. :type operation_model: dict
  256. :param operation_model: The operation model. This comes from the
  257. service model, and is the value associated with the operation
  258. name in the service model (i.e ``model['operations'][op_name]``).
  259. :type service_model: kscore.model.ServiceModel
  260. :param service_model: The service model associated with the operation.
  261. :type name: string
  262. :param name: The operation name. This is the operation name exposed to
  263. the users of this model. This can potentially be different from
  264. the "wire_name", which is the operation name that *must* by
  265. provided over the wire. For example, given::
  266. "CreateCloudFrontOriginAccessIdentity":{
  267. "name":"CreateCloudFrontOriginAccessIdentity2014_11_06",
  268. ...
  269. }
  270. The ``name`` would be ``CreateCloudFrontOriginAccessIdentity``,
  271. but the ``self.wire_name`` would be
  272. ``CreateCloudFrontOriginAccessIdentity2014_11_06``, which is the
  273. value we must send in the corresponding HTTP request.
  274. """
  275. self._operation_model = operation_model
  276. self._service_model = service_model
  277. self._api_name = name
  278. # Clients can access '.name' to get the operation name
  279. # and '.metadata' to get the top level metdata of the service.
  280. self._wire_name = operation_model.get('name')
  281. self.metadata = service_model.metadata
  282. self.http = operation_model.get('http', {})
  283. @CachedProperty
  284. def name(self):
  285. if self._api_name is not None:
  286. return self._api_name
  287. else:
  288. return self.wire_name
  289. @property
  290. def wire_name(self):
  291. """The wire name of the operation.
  292. In many situations this is the same value as the
  293. ``name``, value, but in some services, the operation name
  294. exposed to the user is different from the operaiton name
  295. we send across the wire (e.g cloudfront).
  296. Any serialization code should use ``wire_name``.
  297. """
  298. return self._operation_model.get('name')
  299. @property
  300. def protocol(self):
  301. """protocol from operation_model or service_model
  302. """
  303. return self._operation_model.get("protocol", self.metadata['protocol'])
  304. @property
  305. def is_rewrite_protocol(self):
  306. return "protocol" in self._operation_model
  307. @property
  308. def service_model(self):
  309. return self._service_model
  310. @CachedProperty
  311. def documentation(self):
  312. return self._operation_model.get('documentation', '')
  313. @CachedProperty
  314. def input_shape(self):
  315. if 'input' not in self._operation_model:
  316. # Some operations do not accept any input and do not define an
  317. # input shape.
  318. return None
  319. return self._service_model.resolve_shape_ref(
  320. self._operation_model['input'])
  321. @CachedProperty
  322. def output_shape(self):
  323. if 'output' not in self._operation_model:
  324. # Some operations do not define an output shape,
  325. # in which case we return None to indicate the
  326. # operation has no expected output.
  327. return None
  328. return self._service_model.resolve_shape_ref(
  329. self._operation_model['output'])
  330. @CachedProperty
  331. def has_streaming_input(self):
  332. return self.get_streaming_input() is not None
  333. @CachedProperty
  334. def has_streaming_output(self):
  335. return self.get_streaming_output() is not None
  336. def get_streaming_input(self):
  337. return self._get_streaming_body(self.input_shape)
  338. def get_streaming_output(self):
  339. return self._get_streaming_body(self.output_shape)
  340. def _get_streaming_body(self, shape):
  341. """Returns the streaming member's shape if any; or None otherwise."""
  342. if shape is None:
  343. return None
  344. payload = shape.serialization.get('payload')
  345. if payload is not None:
  346. payload_shape = shape.members[payload]
  347. if payload_shape.type_name == 'blob':
  348. return payload_shape
  349. return None
  350. class ShapeResolver(object):
  351. """Resolves shape references."""
  352. # Any type not in this mapping will default to the Shape class.
  353. SHAPE_CLASSES = {
  354. 'structure': StructureShape,
  355. 'list': ListShape,
  356. 'map': MapShape,
  357. 'string': StringShape
  358. }
  359. def __init__(self, shape_map):
  360. self._shape_map = shape_map
  361. self._shape_cache = {}
  362. def get_shape_by_name(self, shape_name, member_traits=None):
  363. try:
  364. shape_model = self._shape_map[shape_name]
  365. except KeyError:
  366. raise NoShapeFoundError(shape_name)
  367. try:
  368. shape_cls = self.SHAPE_CLASSES.get(shape_model['type'], Shape)
  369. except KeyError:
  370. raise InvalidShapeError("Shape is missing required key 'type': %s"
  371. % shape_model)
  372. if member_traits:
  373. shape_model = shape_model.copy()
  374. shape_model.update(member_traits)
  375. result = shape_cls(shape_name, shape_model, self)
  376. return result
  377. def resolve_shape_ref(self, shape_ref):
  378. # A shape_ref is a dict that has a 'shape' key that
  379. # refers to a shape name as well as any additional
  380. # member traits that are then merged over the shape
  381. # definition. For example:
  382. # {"shape": "StringType", "locationName": "Foobar"}
  383. if len(shape_ref) == 1 and 'shape' in shape_ref:
  384. # It's just a shape ref with no member traits, we can avoid
  385. # a .copy(). This is the common case so it's specifically
  386. # called out here.
  387. return self.get_shape_by_name(shape_ref['shape'])
  388. else:
  389. member_traits = shape_ref.copy()
  390. try:
  391. shape_name = member_traits.pop('shape')
  392. except KeyError:
  393. raise InvalidShapeReferenceError(
  394. "Invalid model, missing shape reference: %s" % shape_ref)
  395. return self.get_shape_by_name(shape_name, member_traits)
  396. class UnresolvableShapeMap(object):
  397. """A ShapeResolver that will throw ValueErrors when shapes are resolved.
  398. """
  399. def get_shape_by_name(self, shape_name, member_traits=None):
  400. raise ValueError("Attempted to lookup shape '%s', but no shape "
  401. "map was provided.")
  402. def resolve_shape_ref(self, shape_ref):
  403. raise ValueError("Attempted to resolve shape '%s', but no shape "
  404. "map was provided.")
  405. class DenormalizedStructureBuilder(object):
  406. """Build a StructureShape from a denormalized model.
  407. This is a convenience builder class that makes it easy to construct
  408. ``StructureShape``s based on a denormalized model.
  409. It will handle the details of creating unique shape names and creating
  410. the appropriate shape map needed by the ``StructureShape`` class.
  411. Example usage::
  412. builder = DenormalizedStructureBuilder()
  413. shape = builder.with_members({
  414. 'A': {
  415. 'type': 'structure',
  416. 'members': {
  417. 'B': {
  418. 'type': 'structure',
  419. 'members': {
  420. 'C': {
  421. 'type': 'string',
  422. }
  423. }
  424. }
  425. }
  426. }
  427. }).build_model()
  428. # ``shape`` is now an instance of kscore.model.StructureShape
  429. :type dict_type: class
  430. :param dict_type: The dictionary type to use, allowing you to opt-in
  431. to using OrderedDict or another dict type. This can
  432. be particularly useful for testing when order
  433. matters, such as for documentation.
  434. """
  435. def __init__(self, name=None):
  436. self.members = OrderedDict()
  437. self._name_generator = ShapeNameGenerator()
  438. if name is None:
  439. self.name = self._name_generator.new_shape_name('structure')
  440. def with_members(self, members):
  441. """
  442. :type members: dict
  443. :param members: The denormalized members.
  444. :return: self
  445. """
  446. self._members = members
  447. return self
  448. def build_model(self):
  449. """Build the model based on the provided members.
  450. :rtype: kscore.model.StructureShape
  451. :return: The built StructureShape object.
  452. """
  453. shapes = OrderedDict()
  454. denormalized = {
  455. 'type': 'structure',
  456. 'members': self._members,
  457. }
  458. self._build_model(denormalized, shapes, self.name)
  459. resolver = ShapeResolver(shape_map=shapes)
  460. return StructureShape(shape_name=self.name,
  461. shape_model=shapes[self.name],
  462. shape_resolver=resolver)
  463. def _build_model(self, model, shapes, shape_name):
  464. if model['type'] == 'structure':
  465. shapes[shape_name] = self._build_structure(model, shapes)
  466. elif model['type'] == 'list':
  467. shapes[shape_name] = self._build_list(model, shapes)
  468. elif model['type'] == 'map':
  469. shapes[shape_name] = self._build_map(model, shapes)
  470. elif model['type'] in ['string', 'integer', 'boolean', 'blob', 'float',
  471. 'timestamp', 'long', 'double', 'char']:
  472. shapes[shape_name] = self._build_scalar(model)
  473. else:
  474. raise InvalidShapeError("Unknown shape type: %s" % model['type'])
  475. def _build_structure(self, model, shapes):
  476. members = OrderedDict()
  477. shape = self._build_initial_shape(model)
  478. shape['members'] = members
  479. for name, member_model in model['members'].items():
  480. member_shape_name = self._get_shape_name(member_model)
  481. members[name] = {'shape': member_shape_name}
  482. self._build_model(member_model, shapes, member_shape_name)
  483. return shape
  484. def _build_list(self, model, shapes):
  485. member_shape_name = self._get_shape_name(model)
  486. shape = self._build_initial_shape(model)
  487. shape['member'] = {'shape': member_shape_name}
  488. self._build_model(model['member'], shapes, member_shape_name)
  489. return shape
  490. def _build_map(self, model, shapes):
  491. key_shape_name = self._get_shape_name(model['key'])
  492. value_shape_name = self._get_shape_name(model['value'])
  493. shape = self._build_initial_shape(model)
  494. shape['key'] = {'shape': key_shape_name}
  495. shape['value'] = {'shape': value_shape_name}
  496. self._build_model(model['key'], shapes, key_shape_name)
  497. self._build_model(model['value'], shapes, value_shape_name)
  498. return shape
  499. def _build_initial_shape(self, model):
  500. shape = {
  501. 'type': model['type'],
  502. }
  503. if 'documentation' in model:
  504. shape['documentation'] = model['documentation']
  505. if 'enum' in model:
  506. shape['enum'] = model['enum']
  507. return shape
  508. def _build_scalar(self, model):
  509. return self._build_initial_shape(model)
  510. def _get_shape_name(self, model):
  511. if 'shape_name' in model:
  512. return model['shape_name']
  513. else:
  514. return self._name_generator.new_shape_name(model['type'])
  515. class ShapeNameGenerator(object):
  516. """Generate unique shape names for a type.
  517. This class can be used in conjunction with the DenormalizedStructureBuilder
  518. to generate unique shape names for a given type.
  519. """
  520. def __init__(self):
  521. self._name_cache = defaultdict(int)
  522. def new_shape_name(self, type_name):
  523. """Generate a unique shape name.
  524. This method will guarantee a unique shape name each time it is
  525. called with the same type.
  526. ::
  527. >>> s = ShapeNameGenerator()
  528. >>> s.new_shape_name('structure')
  529. 'StructureType1'
  530. >>> s.new_shape_name('structure')
  531. 'StructureType2'
  532. >>> s.new_shape_name('list')
  533. 'ListType1'
  534. >>> s.new_shape_name('list')
  535. 'ListType2'
  536. :type type_name: string
  537. :param type_name: The type name (structure, list, map, string, etc.)
  538. :rtype: string
  539. :return: A unique shape name for the given type
  540. """
  541. self._name_cache[type_name] += 1
  542. current_index = self._name_cache[type_name]
  543. return '%sType%s' % (type_name.capitalize(),
  544. current_index)