MCPcopy Create free account
hub / github.com/aws-samples/personalization-apis / lambda_handler

Function lambda_handler

src/config_validator_function/main.py:46–101  ·  view source on GitHub ↗
(event, _)

Source from the content-addressed store, hash-verified

44@logger.inject_lambda_context
45@tracer.capture_lambda_handler
46def lambda_handler(event, _):
47 # Step 1: validate configuration against the JSON Schema
48 personalization_config = json.loads(base64.b64decode(event['content']))
49
50 try:
51 jsonschema.validate(instance = personalization_config, schema = schema)
52 except jsonschema.exceptions.ValidationError as e:
53 # Log all details of the exception
54 logger.exception(e)
55 # Return a user-friendly error message
56 raise Exception(e.message)
57
58 # Step 2: do some logical validation against the configuration
59
60 errors: List[str] = []
61 # TODO
62 if errors:
63 raise ValueError('; '.join(errors))
64
65 # Step 3: generate an updated OpenAPI spec file and save to the staging bucket.
66 openapi_generator = OpenApiGenerator()
67 openapi_spec = openapi_generator.generate(
68 apis_config = personalization_config,
69 apigw_host = apigw_host,
70 cloudfront_host = cloudfront_host,
71 auth_scheme = api_auth_scheme
72 )
73
74 openapi_uri = None
75 if 'paths' in openapi_spec and len(openapi_spec['paths']) > 0:
76 object = s3.Object(staging_bucket, openapi_output_key)
77 result = object.put(Body=json.dumps(openapi_spec, indent = 4))
78 logger.debug(result)
79 openapi_uri = f's3://{staging_bucket}/{openapi_output_key}'
80
81 # Step 4: post an event to EventBridge to trigger the resource synchronization step functions state machine.
82
83 # Set the decoded config into event so that it's accessible as JSON in targets (i.e., step function state machine).
84 event['content'] = personalization_config
85 if openapi_uri:
86 event['openApiSpecUri'] = openapi_uri
87
88 region = os.environ['AWS_REGION']
89 account_id = boto3.client('sts').get_caller_identity()['Account']
90 resource = f'arn::appconfig:{region}:{account_id}:application/{event["applicationId"]}/configurationprofile/{event["configurationProfileId"]}'
91
92 event_bridge.put_events(
93 Entries=[
94 {
95 'Source': 'personalization.apis',
96 'Resources': [ resource ],
97 'DetailType': 'PersonalizationApisConfigurationChange',
98 'Detail': json.dumps(event)
99 }
100 ]
101 )

Callers

nothing calls this directly

Calls 3

generateMethod · 0.95
OpenApiGeneratorClass · 0.90
put_eventsMethod · 0.45

Tested by

no test coverage detected