-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
440 lines (359 loc) · 13.6 KB
/
main.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
import contextlib
from dataclasses import dataclass
from datetime import datetime
from enum import Enum, auto
from pathlib import Path
from typing import (
Annotated,
Any,
Dict,
Generic,
List,
NotRequired,
Optional,
TypedDict,
TypeVar,
cast,
override,
)
import anyio
import click
import duckdb
import jsonpath_ng as jp
import jsonschema
import orjson as json
import uvicorn
from anyio import TASK_STATUS_IGNORED, create_memory_object_stream, open_file, to_thread
from anyio.streams.memory import MemoryObjectReceiveStream
from duckdb import DuckDBPyConnection
from jsonschema import ValidationError as JSONSchemaValidationError
from litestar import Litestar, Request, Response, Router, delete, get, post, put
from litestar.config.cors import CORSConfig
from litestar.exceptions import HTTPException, ValidationException
from litestar.openapi import OpenAPIConfig, OpenAPIController
from litestar.openapi.spec import Operation, Schema
from litestar.params import Body, Parameter
from litestar.plugins.structlog import StructlogPlugin
from litestar.static_files import create_static_files_router
from pydantic import BaseModel
from structlog.stdlib import BoundLogger
from typeguard import TypeCheckError as TypeGuardCheckError
from typeguard import check_type
from app.template import TemplateReturn, evaluate_template
duck: Optional[DuckDBPyConnection] = None
DB_NAME = "templates.db"
class TemplateSchemas(TypedDict):
Template: Dict[str, Any]
TemplateReturn: Dict[str, Any]
SCRIPT_DIR = Path(__file__).parent
TEMPLATE_SCHEMAS_DIR = SCRIPT_DIR / "schemas"
TEMPLATE_SCHEMAS: TemplateSchemas = {"Template": {}, "TemplateReturn": {}}
# https://gist.github.com/nymous/f138c7f06062b7c43c060bf03759c29e
# https://github.com/hynek/structlog/issues/360
# https://docs.litestar.dev/2/usage/exceptions.html#application-exceptions
# default exception handler
class RequestError(BaseModel):
"""
General error response model
"""
status_code: int
"""
HTTP status code
"""
detail: str = ""
"""
Error message
"""
extra: Dict[str, Any] = {}
"""
Extra information
Most likely used for debugging
"""
exception: Optional[Exception] = None
"""
Exception object
Most likely used for debugging
"""
class Config:
arbitrary_types_allowed = True
class InjectionOpenAPIController(OpenAPIController):
@override
def _get_schema_as_json(self, request: Request) -> str:
"""
It's ugly post-processing but it works.
"""
if not self._dumped_json_schema:
schema = self.get_schema_from_request(request).to_schema()
# https://gist.github.com/wonderbeyond/22cae14aa553fb137509df2f54b4f728
schemas = schema["components"]["schemas"]
assert isinstance(schemas, dict)
schemas["Template"] = TEMPLATE_SCHEMAS["Template"]
schemas["TemplateReturn"] = TEMPLATE_SCHEMAS["TemplateReturn"]
eval_json_path = "$.paths['/template/eval'].post.requestBody"
val = {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Template"
}
}
}
}
jp.parse(eval_json_path).update(schema, val)
ref_to_template = {"$ref": "#/components/schemas/Template"}
schemas["TemplateEntry"]["properties"]["content"] = ref_to_template
schemas["TemplateCreationRequest"]["properties"][
"content"] = ref_to_template
self._dumped_json_schema = json.dumps(schema,
default=str).decode("utf-8")
return self._dumped_json_schema
def json_schema_exception_handler(
_: Request, exc: JSONSchemaValidationError) -> Response[RequestError]:
status_code = 400
return Response(RequestError(status_code=status_code,
detail=exc.message,
exception=exc),
status_code=status_code)
def type_guard_exception_handler(
_: Request, exc: TypeGuardCheckError) -> Response[RequestError]:
status_code = 400
return Response(RequestError(status_code=status_code,
detail=str(exc),
exception=exc),
status_code=status_code)
class TemplateEntry(BaseModel, frozen=True):
"""
TemplateEntry is a model for a template entry that stored in the database
"""
name: str
"""
name of the template
"""
created_at: datetime
"""
The time when the template was created
"""
updated_at: datetime
"""
The time when the template was updated
"""
content: Dict[str, Any]
"""
Template content
"""
class TemplateCreationRequest(BaseModel, frozen=True):
"""
The create/update template request model
"""
name: str
"""
name of the template
"""
content: Dict[str, Any]
"""
Template content
"""
# https://docs.litestar.dev/2/usage/openapi.html#customizing-operation-class
# https://medium.com/apis-you-wont-hate/openapi-v3-1-and-json-schema-2019-09-6862cf3db959
# https://docs.litestar.dev/latest/usage/requests.html
# https://docs.litestar.dev/2/usage/exceptions.html
@post("/eval", tags=["eval"], summary="evaluate a template")
async def eval_template(data: Dict[str, Any]) -> TemplateReturn:
result = await evaluate_template(data)
return result
async def _read_template(conn: DuckDBPyConnection,
name: str) -> Optional[TemplateEntry]:
def exe():
r = conn.execute(
"""--sql
SELECT * FROM templates WHERE name = ?
""", [name])
return r.fetchone()
entry = await to_thread.run_sync(exe)
if entry is None:
return None
name, created_at, updated_at, content = entry
return TemplateEntry(name=name,
created_at=created_at,
updated_at=updated_at,
content=content)
@get("/{name:str}/eval",
tags=["eval"],
summary="evaluate an existing template")
async def eval_existing_template(name: str) -> TemplateReturn:
assert duck is not None
temp = await _read_template(duck, name)
if temp is None:
raise HTTPException(status_code=404, detail="Not Found")
result = await evaluate_template(temp.content)
return result
def verify_template(template: Dict[str, Any]):
"""
raise JSONSchemaValidationError if the template is invalid
"""
jsonschema.validate(template, TEMPLATE_SCHEMAS["Template"])
def raise_if_names_unmatch(name: str, body_name: str):
if body_name != name:
raise HTTPException(status_code=400,
detail=f"""
field `name` in request body unmatched with path parameter;
{body_name} != {name}; Please make sure the url and request body are consistent
""")
TemplateNameParameter = Parameter(
title="Template name",
description="""The name must match the name in the
request body. The request won't be
fulfilled if the names are
different.
""",
)
@post("{name:str}", tags=["template"], summary="create a template")
async def create_template(name: Annotated[str, TemplateNameParameter],
data: TemplateCreationRequest) -> None:
async def _create_template(conn: DuckDBPyConnection, name: str,
content: Dict[str, Any]):
verify_template(content)
def exe():
conn.execute(
"""--sql
INSERT INTO templates VALUES (?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ?)
""", [name, content])
await to_thread.run_sync(exe)
body_name = data.name
raise_if_names_unmatch(name, body_name)
content = data.content
assert duck is not None
await _create_template(duck, name, content)
@get("/", tags=["template"], summary="browse templates")
async def read_templates(limit: int = 10,
offset: int = 0) -> List[TemplateEntry]:
async def _read_templates(conn: DuckDBPyConnection, offset: int,
limit: int):
MAX_LIMIT = 100
if offset < 0:
raise ValueError("offset must be >= 0")
elif limit < 0 or limit > MAX_LIMIT:
raise ValueError(f"limit must be >= 0 and <= {MAX_LIMIT}")
def exe():
r = conn.execute(
"""--sql
SELECT * FROM templates LIMIT ? OFFSET ?
""", [limit, offset])
tuples = r.fetchall()
return [
TemplateEntry(name=name,
created_at=created_at,
updated_at=updated_at,
content=content)
for name, created_at, updated_at, content in tuples
]
return await to_thread.run_sync(exe)
assert duck is not None
return await _read_templates(duck, offset, limit)
@get("{name:str}", tags=["template"], summary="read a specific template")
async def read_template(name: str) -> TemplateEntry:
assert duck is not None
temp = await _read_template(duck, name)
if temp is None:
raise HTTPException(status_code=404, detail="Not Found")
return temp
@put("{name:str}", tags=["template"], summary="update a template")
async def update_template(name: Annotated[str, TemplateNameParameter],
data: TemplateCreationRequest) -> None:
async def _update_template(conn: DuckDBPyConnection, name: str,
content: Dict[str, Any]):
verify_template(content)
def exe():
conn.execute(
"""--sql
UPDATE templates SET updated_at = CURRENT_TIMESTAMP, content = ? WHERE name = ?
""", [content, name])
await to_thread.run_sync(exe)
body_name = data.name
raise_if_names_unmatch(name, body_name)
content = data.content
assert duck is not None
await _update_template(duck, name, content)
@delete("{name:str}", tags=["template"], summary="delete a template")
async def delete_template(name: str) -> None:
async def _delete_template(conn: DuckDBPyConnection, name: str):
def exe():
conn.execute(
"""--sql
DELETE FROM templates WHERE name = ?
""", [name])
await to_thread.run_sync(exe)
assert duck is not None
await _delete_template(duck, name)
@contextlib.asynccontextmanager
async def lifespan(app: Litestar):
def create_table(conn: DuckDBPyConnection):
conn.execute("""--sql
CREATE TABLE IF NOT EXISTS templates (name TEXT UNIQUE NOT NULL, created_at TIMESTAMP, updated_at TIMESTAMP, content JSON)
""")
assert app.logger is not None
app.logger.info("lifespan start")
async with anyio.create_task_group() as tg:
global TEMPLATE_SCHEMAS
async with await open_file(TEMPLATE_SCHEMAS_DIR / "template.json"
) as f:
TEMPLATE_SCHEMAS["Template"] = json.loads(await f.read())
async with await open_file(TEMPLATE_SCHEMAS_DIR /
"template_return.json") as f:
TEMPLATE_SCHEMAS["TemplateReturn"] = json.loads(await f.read())
global duck
duck = duckdb.connect(DB_NAME, read_only=False)
create_table(duck)
yield
tg.cancel_scope.cancel()
duck.close()
app.logger.info("lifespan end")
template_router = Router(path="/template",
route_handlers=[
create_template, read_templates, read_template,
update_template, delete_template, eval_template,
eval_existing_template
])
@click.command()
@click.option("--port", default=8000, help="Port number")
@click.option("--host", default="0.0.0.0", help="Host")
def main(port: int, host: str):
from importlib.metadata import version
anyio_version_str = version("anyio").split(".")
anyio_version = tuple([int(x) for x in anyio_version_str])
assert anyio_version[0] == 4 and anyio_version[
1] >= 3, "anyio version must be >= 4.3"
# https://docs.litestar.dev/2/usage/applications.html
# https://docs.litestar.dev/2/usage/middleware/builtin-middleware.html#brotli
# https://docs.litestar.dev/2/usage/openapi.html
cors_config = CORSConfig(
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
structlog_plugin = StructlogPlugin()
app = Litestar(
debug=True,
lifespan=[lifespan],
cors_config=cors_config,
plugins=[structlog_plugin],
route_handlers=[
template_router,
create_static_files_router("static",
directories=[TEMPLATE_SCHEMAS_DIR],
include_in_schema=False),
],
exception_handlers={
JSONSchemaValidationError: json_schema_exception_handler,
TypeGuardCheckError: type_guard_exception_handler,
},
openapi_config=OpenAPIConfig(
title="Template API",
version="0.1.0",
path="docs",
openapi_controller=InjectionOpenAPIController,
))
uvicorn.run(app, host=host, port=port)
if __name__ == "__main__":
main() # pylint: disable=no-value-for-parameter