Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.py
More file actions
Latest commit
executable file
·223 lines (178 loc) · 7.62 KB
/
Copy pathhandler.py
File metadata and controls
executable file
·223 lines (178 loc) · 7.62 KB
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
importjson
fromevaluation_function_utils.errorsimportEvaluationException
from .toolsimportcommands, docs, parse, validate
from .tools.parseimportParseError
fromtypingimportAny, Optional
from .tools.utilsimportDocsResponse, ErrorCode, ErrorResponse, HandlerResponse, JsonType, Response
from .tools.validateimport (
LegacyReqBodyValidators,
LegacyResBodyValidators,
MuEdReqBodyValidators,
MuEdResBodyValidators,
ValidationError,
)
defhandle_legacy_command(event: JsonType, command: str) ->HandlerResponse:
"""Switch case for handling different command options using legacy schemas.
Args:
event (JsonType): The AWS Lambda event recieved by the handler.
command (str): The name of the function to invoke.
Returns:
HandlerResponse: The response object returned by the handler.
"""
# No validation of the doc commands.
ifcommandin ("docs-dev", "docs"):
returndocs.dev()
elifcommand=="docs-user":
returndocs.user()
body=parse.body(event)
response: Response
validator: LegacyResBodyValidators
ifcommandin ("eval", "grade"):
validate.body(body, LegacyReqBodyValidators.EVALUATION)
response=commands.evaluate(body)
validator=LegacyResBodyValidators.EVALUATION
elifcommand=="preview":
validate.body(body, LegacyReqBodyValidators.PREVIEW)
response=commands.preview(body)
validator=LegacyResBodyValidators.PREVIEW
elifcommand=="healthcheck":
response=commands.healthcheck()
validator=LegacyResBodyValidators.HEALTHCHECK
else:
response=Response(
error=ErrorResponse(message=f"Unknown command '{command}'.")
)
validator=LegacyResBodyValidators.EVALUATION
validate.body(response, validator)
returnresponse
defwrap_muEd_response(body: Any, event: JsonType, status_code: int=200) ->DocsResponse:
"""Wrap a muEd response body in Lambda proxy format with X-Api-Version header.
Args:
body: The response body to serialise.
event (JsonType): The incoming event (used to resolve the served version).
status_code (int): The HTTP status code. Defaults to 200.
Returns:
DocsResponse: Proxy-format response with X-Api-Version header set.
"""
requested= (event.get("headers") or {}).get("X-Api-Version")
ifrequestedandrequestedincommands.SUPPORTED_MUED_VERSIONS:
version=requested
else:
version=commands.SUPPORTED_MUED_VERSIONS[-1]
returnDocsResponse(
statusCode=status_code,
headers={"X-Api-Version": version},
body=json.dumps(body),
isBase64Encoded=False,
)
defcheck_muEd_version(event: JsonType) ->Optional[HandlerResponse]:
"""Check the X-Api-Version header against supported muEd versions.
Args:
event (JsonType): The AWS Lambda event received by the handler.
Returns:
Optional[HandlerResponse]: A version-not-supported error response if
the requested version is unsupported, otherwise None.
"""
version= (event.get("headers") or {}).get("X-Api-Version")
ifversionandversionnotincommands.SUPPORTED_MUED_VERSIONS:
return {
"title": "API version not supported",
"message": (
f"The requested API version '{version}' is not supported. "
f"Supported versions are: {commands.SUPPORTED_MUED_VERSIONS}."
),
"code": ErrorCode.VERSION_NOT_SUPPORTED,
"details": {
"requestedVersion": version,
"supportedVersions": commands.SUPPORTED_MUED_VERSIONS,
},
}
returnNone
defhandle_muEd_command(event: JsonType, command: str) ->HandlerResponse:
"""Switch case for handling different command options using muEd schemas.
Args:
event (JsonType): The AWS Lambda event recieved by the handler.
command (str): The name of the function to invoke.
Returns:
HandlerResponse: The response object returned by the handler.
"""
try:
version_error=check_muEd_version(event)
ifversion_error:
returnwrap_muEd_response(version_error, event, 406)
ifcommand=="eval":
body=parse.body(event)
validate.body(body, MuEdReqBodyValidators.EVALUATION)
response=commands.evaluate_muEd(body)
validate.body(response, MuEdResBodyValidators.EVALUATION)
elifcommand=="healthcheck":
response=commands.healthcheck_muEd()
validate.body(response, MuEdResBodyValidators.HEALTHCHECK)
status_code=503ifresponse.get("status") =="UNAVAILABLE"else200
returnwrap_muEd_response(response, event, status_code)
else:
error= {
"title": "Not implemented",
"message": f"Unknown command '{command}'.",
"code": ErrorCode.NOT_IMPLEMENTED,
}
returnwrap_muEd_response(error, event, 501)
returnwrap_muEd_response(response, event)
except (ParseError, ValidationError) ase:
error= {
"title": "Bad request",
"message": e.message,
"code": ErrorCode.VALIDATION_ERROR,
"details": {"error": str(e.error_thrown)} ife.error_thrownelseNone,
}
returnwrap_muEd_response(error, event, 400)
exceptEvaluationExceptionase:
detail=str(e) ifstr(e) elserepr(e)
error= {"title": "Internal server error", "message": detail, "code": ErrorCode.INTERNAL_ERROR}
returnwrap_muEd_response(error, event, 500)
exceptExceptionase:
detail=str(e) ifstr(e) elserepr(e)
error= {"title": "Internal server error", "message": detail, "code": ErrorCode.INTERNAL_ERROR}
returnwrap_muEd_response(error, event, 500)
defhandler(event: JsonType, _=None) ->HandlerResponse:
"""Main function invoked by AWS Lambda to handle incoming requests.
Args:
event (JsonType): The AWS Lambda event received by the gateway.
_ (JsonType): The AWS Lambda context object (unused).
Returns:
HandlerResponse: The response to return back to the requestor.
"""
if_isNone:
_= {}
# Normalise path: prefer rawPath (HTTP API v2) over path (REST API v1).
# API Gateway v1 includes the full resource prefix in `path`
# (e.g. /compareExpressions-staging/evaluate), so we match on suffix.
# API Gateway v2 uses `rawPath` at the top level; `path` may be absent.
raw_path=event.get("rawPath") orevent.get("path", "/")
ifraw_path.endswith("/evaluate/health"):
path="/evaluate/health"
elifraw_path.endswith("/evaluate"):
path="/evaluate"
else:
path=raw_path
try:
ifpath=="/evaluate":
returnhandle_muEd_command(event, "eval")
elifpath=="/evaluate/health":
returnhandle_muEd_command(event, "healthcheck")
else:
headers=event.get("headers", dict())
command=headers.get("command", "eval")
returnhandle_legacy_command(event, command)
except (ParseError, ValidationError) ase:
error=ErrorResponse(message=e.message, detail=e.error_thrown)
exceptEvaluationExceptionase:
error=e.error_dict
# Catch-all for any unexpected errors.
exceptExceptionase:
error=ErrorResponse(
message="An exception was raised while "
"executing the evaluation function.",
detail=(str(e) ifstr(e) !=""elserepr(e)),
)
returnResponse(error=error)