Skip to content

Commit

Permalink
Merge pull request #1 from QuanticSchool/working
Browse files Browse the repository at this point in the history
Initial API gateway and client
  • Loading branch information
John-J-Riehl committed Apr 24, 2022
2 parents 3fcd30c + 25f930d commit a9f93d8
Show file tree
Hide file tree
Showing 41 changed files with 27,939 additions and 0 deletions.
1 change: 1 addition & 0 deletions api-gateway/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/api-gateway-env
12 changes: 12 additions & 0 deletions api-gateway/apis.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[
{
"api_name": "immortal_memes",
"api_type": "HTTP",
"integrations": {
"0": {"type": "lambda", "region": "us-east-1", "function": "im-health-check"}
},
"routes": [
{"method": "GET", "path": "/health-check", "integration_id": "0"}
]
}
]
246 changes: 246 additions & 0 deletions api-gateway/application.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,246 @@
# Copyright 2022 Quantic School of Business and technology
#
# This Flask application emulates part of the functionality of an
# AWS API Gateway using Elastic Beanstalk. It was written because
# the AWS Learner Lab does not allow for the use of API Gateway.
#
# The following functionality from the API Gateway is emulated. If
# a capability isn't specifically mentioned (e.g. a $default stage),
# assume it's not implemented:
#
# API types: HTTP
# Integrations: Lambda
# Methods: any (including the ANY method specifier)
# Path variables: yes, except for greedy variables.
#
# For more information on Flask, see
# https://flask.palletsprojects.com/en/2.1.x/. A few notes:
#
# - To initialize a Flask web server, you add routes that the
# server will respond to using add_url_rule(). Part of each
# URL rule is a view function that gets called when the
# URL path matches the rule.
# - When the server processes a request, Flask sets a global
# variable named request with the details of the request.
#
# This application uses the boto3 library to invoke AWS Lambda
# functions. You can learn more about boto3 here:
# https://boto3.amazonaws.com/v1/documentation/api/latest/index.html

from flask import Flask, request
import json, boto3
from botocore.config import Config

# Elastic Beanstalk looks for a callable named application
application = Flask(__name__)

class LambdaInvoker():
"""Represents a callable invoker for an AWS Lambda function.
Normally you pass add_url_rule a view_func. However, we needed to
have a way to associate the view_func with a particular AWS
Lambda function. So we actually make a callable object that
has as attributes the Lambda function and path.
Attributes:
region: A string with the region containing the Lambda to invoke.
Note that this feature is untested for cases in which the
Lambda is in a different region than the Elastic Beanstalk
instance running the API Gateway emulator.
function: A string with the name of the Lambda to invoke.
path: A string with the URL path for this route.
"""
def __init__(self, region, function, path):
self.region = region
self.function = function
self.path = path

def __call__(self, **path_params):
"""Invokes the Lambda.
Invokes the Lambda function and returns the response. This is called
by Flask based on URL rules added to the application with
add_url_rule().
Args:
path_params: A dictionary with the parameters in the path (e.g. if
the route was specified as /foo/{bar} and the path is
/foo/42, the dictionary will be {"bar": 42}).
Returns:
The response from the Lambda function, or an error message.
"""

# build the payload the lambda function expects to see. see
# https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html
# for details on the payload that an API Gateway sends a Lambda.
# we omit requestContext (TODO see about including later) and
# stageVariables (didn't appear in an actual payload sent to
# Lambda from API Gateway).
payload = {
"version": "2.0",
"routeKey": f"{request.method} {self.path}",
"rawPath": request.path,
"rawQueryString": str(request.query_string),
"cookies": [
f"{cookie[0]}={cookie[1]}" for cookie in request.cookies.items()
],
"headers": dict(request.headers),
"queryStringParameters": dict(request.args),
"body": request.get_data(as_text=True),
"isBase64Encoded": False
}

if (path_params):
payload["pathParameters"] = path_params

# invoke the Lambda function. We don't need to specify credentials
# if we give the Elastic Beanstalk instance a role
invoke_config = Config(
region_name=self.region
)
client = boto3.client("lambda", config=invoke_config)
response = client.invoke(
FunctionName=self.function,
InvocationType="RequestResponse",
Payload=json.dumps(payload)
)

# now send the response
if response["StatusCode"] != 200:
return response["FunctionError"], response["StatusCode"]
else:
return response["Payload"].read()

# convenience function to raise an exception if a required dictionary
# entry is missing
def get_required_entry(dictionary, key, exception_text):
"""Raises an exception if a required dictionary key is missing.
Args:
dictionary: The dictionary.
key: The key.
exception_text: The text of the exception.
Returns:
The value for the given key.
Raises:
Exception: the key wasn't found.
"""
result = dictionary.get(key)

if not result:
raise Exception(exception_text)

return result

# load the API(s) from a config file
config = None

try:
with open("apis.json") as config_file:
apis = json.load(config_file)
except Exception as err:
err_str = f"Config file error: {err}"
application.add_url_rule(
"/",
endpoint="config_err",
view_func=lambda: err_str
)
apis = []

# build the route handlers
try:
for api in apis:
api_name = get_required_entry(
api,
"api_name",
"API missing required api_name"
)
api_type = get_required_entry(
api,
"api_type",
f"API {api_name} missing required type"
)

if api_type == "HTTP":
routes = get_required_entry(
api,
"routes",
f"API {api_name} missing required routes"
)
integrations = get_required_entry(
api,
"integrations",
f"API {api_name} missing required integrations"
)

for route in routes:
method = get_required_entry(
route,
"method",
f"Route in API {api_name} missing required method"
)

if method == "ANY":
method = None

path = get_required_entry(
route,
"path",
f"Route in API {api_name} missing required path"
)
integration_id = get_required_entry(
route,
"integration_id",
f"Route in API {api_name} missing required integration_id"
)
integration = get_required_entry(
integrations,
integration_id,
f"API {api_name} missing integration_id {integration_id}"
)
integration_type = get_required_entry(
integration,
"type",
f"integration_id {integration_id} missing required type"
)

if integration_type == "lambda":
region = get_required_entry(
integration,
"region",
f"integration_id {integration_id} missing required region"
)
function = get_required_entry(
integration,
"function",
f"integration_id {integration_id} missing required function"
)
application.add_url_rule(
# Flask uses <> for path variable delimiters
path.replace("{", "<").replace("}", ">"),
endpoint=f"{path}_{region}_{function}",
methods=[method] if method else None,
view_func=LambdaInvoker(region, function, path)
)
else:
raise Exception(f"integration type {integration_type} not implemented")

else:
raise Exception(f"api type {api_type} not implemented")

except Exception as err:
# reset the application and add an error route
application = Flask(__name__)
err_str = f"Gateway config error: {err}"
application.add_url_rule(
"/",
endpoint="config_err",
view_func=lambda: err_str
)

# run the app.
if __name__ == "__main__":
application.run()
Binary file added api-gateway/application.zip
Binary file not shown.
16 changes: 16 additions & 0 deletions api-gateway/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
boto3==1.21.43
botocore==1.24.43
click==8.1.2
colorama==0.4.4
Flask==2.1.1
importlib-metadata==4.11.3
itsdangerous==2.1.2
Jinja2==3.1.1
jmespath==1.0.0
MarkupSafe==2.1.1
python-dateutil==2.8.2
s3transfer==0.5.2
six==1.16.0
urllib3==1.26.9
Werkzeug==2.1.1
zipp==3.8.0
23 changes: 23 additions & 0 deletions client/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
#/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*
70 changes: 70 additions & 0 deletions client/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# Getting Started with Create React App

This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).

## Available Scripts

In the project directory, you can run:

### `npm start`

Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.

The page will reload when you make changes.\
You may also see any lint errors in the console.

### `npm test`

Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.

### `npm run build`

Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.

The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!

See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.

### `npm run eject`

**Note: this is a one-way operation. Once you `eject`, you can't go back!**

If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.

Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.

You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.

## Learn More

You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).

To learn React, check out the [React documentation](https://reactjs.org/).

### Code Splitting

This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)

### Analyzing the Bundle Size

This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)

### Making a Progressive Web App

This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)

### Advanced Configuration

This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)

### Deployment

This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)

### `npm run build` fails to minify

This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
Binary file added client/build/android-chrome-192x192.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added client/build/android-chrome-512x512.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added client/build/apple-touch-icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
13 changes: 13 additions & 0 deletions client/build/asset-manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"files": {
"main.css": "/static/css/main.80c75857.css",
"main.js": "/static/js/main.e1bd46a3.js",
"index.html": "/index.html",
"main.80c75857.css.map": "/static/css/main.80c75857.css.map",
"main.e1bd46a3.js.map": "/static/js/main.e1bd46a3.js.map"
},
"entrypoints": [
"static/css/main.80c75857.css",
"static/js/main.e1bd46a3.js"
]
}
Binary file added client/build/favicon-16x16.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added client/build/favicon-32x32.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added client/build/favicon.ico
Binary file not shown.
1 change: 1 addition & 0 deletions client/build/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<!doctype html><html lang="en"><head><meta charset="utf-8"/><link rel="icon" href="/favicon.ico"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="theme-color" content="#000000"/><meta name="description" content="A web app to find memes that will live in immortality."/><link rel="apple-touch-icon" href="/logo192.png"/><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"><link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png"><link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"><link rel="manifest" href="/manifest.json"/><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"><title>Immortal Memes!</title><script defer="defer" src="/static/js/main.e1bd46a3.js"></script><link href="/static/css/main.80c75857.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div></body></html>
Loading

0 comments on commit a9f93d8

Please sign in to comment.