Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
executable file
·234 lines (191 loc) · 6.92 KB
/
Copy pathapp.py
File metadata and controls
executable file
·234 lines (191 loc) · 6.92 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
224
225
226
227
228
229
230
231
232
233
234
#!/usr/bin/env python3
import asyncio
import logging
import os
import sys
import traceback
import uuid
from contextlib import asynccontextmanager
from typing import Annotated
import asyncpg
import fastapi_structured_logging
import httpx
from fastapi import FastAPI
from fastapi import Header
from fastapi import HTTPException
from fastapi import Request
from fastapi import status
from fastapi.responses import JSONResponse
from fastapi.responses import RedirectResponse
import webhook
from config import DefaultConfig
from db import database
from gitlab_model import EmojiPayload
from gitlab_model import MergeRequestPayload
from gitlab_model import NotePayload
from gitlab_model import PipelinePayload
from periodic_cleanup import periodic_cleanup
from webhook.merge_request import PartialMessageUpdateError
config = DefaultConfig()
# Configure structured logging
log_format = os.getenv("LOG_FORMAT", "auto").lower()
log_level = os.getenv("LOG_LEVEL", "INFO").upper()
if log_format == "json":
fastapi_structured_logging.setup_logging(json_logs=True, log_level=log_level)
elif log_format == "line":
fastapi_structured_logging.setup_logging(json_logs=False, log_level=log_level)
else:
fastapi_structured_logging.setup_logging(log_level=log_level)
logging.getLogger("uvicorn.error").disabled = True
# Suppress traceback printing to stderr
traceback.print_exception = lambda *args, **kwargs: None
logger = fastapi_structured_logging.get_logger()
@asynccontextmanager
async def lifespan(app: FastAPI):
logger.info("starting app version %s", app.version)
await database.connect()
task = asyncio.create_task(periodic_cleanup(config, database))
yield
task.cancel()
await database.disconnect()
app: FastAPI = FastAPI(
title="Teams Notifier gitlab-mr-api",
version=os.environ.get("VERSION", "v0.0.0-dev"),
lifespan=lifespan,
)
app.add_middleware(fastapi_structured_logging.AccessLogMiddleware)
@app.exception_handler(asyncpg.UniqueViolationError)
async def database_uniqueviolation_handler(request: Request, exc: asyncpg.UniqueViolationError):
logger.error(
"database unique violation error",
error_type=type(exc).__name__,
error_detail=str(exc),
constraint=getattr(exc, "constraint_name", None),
path=request.url.path,
method=request.method,
)
return JSONResponse(
status_code=status.HTTP_409_CONFLICT,
content={"detail": "Resource already exists", "error": str(exc)},
)
@app.exception_handler(asyncpg.PostgresError)
async def database_exception_handler(request: Request, exc: asyncpg.PostgresError):
logger.error(
"database error",
error_type=type(exc).__name__,
error_detail=str(exc),
sqlstate=getattr(exc, "sqlstate", None),
path=request.url.path,
method=request.method,
)
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={"detail": "Database error occurred"},
)
@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
exc_type, exc_value, exc_traceback = sys.exc_info()
logger.error(
"unhandled exception",
error_type=type(exc).__name__,
error_detail=str(exc),
path=request.url.path,
method=request.method,
traceback="".join(traceback.format_exception(exc_type, exc_value, exc_traceback)),
)
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={"detail": "Internal server error"},
)
@app.get("/", response_class=RedirectResponse, status_code=302)
async def root():
return "/docs"
def validate_gitlab_token(token: str) -> None:
if not config.is_valid_token(token):
raise HTTPException(status_code=403, detail=f"Invalid gitlab token {token}")
def validate_uuid(val: str) -> str | None:
try:
return str(uuid.UUID(str(val)))
except ValueError:
return None
@app.post("/api/v1/gitlab-webhook")
async def handle_webhook(
payload: MergeRequestPayload | PipelinePayload | EmojiPayload | NotePayload,
x_conversation_token: Annotated[str, Header()],
x_gitlab_token: Annotated[str, Header()],
filter_on_participant_ids: str | None = None,
new_commits_revoke_approvals: bool = True,
):
validate_gitlab_token(x_gitlab_token)
conversation_tokens = list(
filter(
None,
[validate_uuid(ct.strip()) for ct in x_conversation_token.split(",")],
)
)
try:
if isinstance(payload, MergeRequestPayload):
participant_ids_filter: list[int] = []
if filter_on_participant_ids:
try:
participant_ids_filter = [int(entry) for entry in filter_on_participant_ids.split(",")]
except ValueError:
raise HTTPException(
status_code=400,
detail="filter_on_participant_ids must be a list of comma separated integers",
) from None
await webhook.merge_request(
payload,
conversation_tokens,
participant_ids_filter,
new_commits_revoke_approvals,
)
if isinstance(payload, PipelinePayload):
await webhook.pipeline(payload, conversation_tokens)
if isinstance(payload, EmojiPayload):
await webhook.emoji(payload, conversation_tokens)
if isinstance(payload, NotePayload):
await webhook.note(payload)
return {"status": "ok"}
except PartialMessageUpdateError as exc:
raise HTTPException(
status_code=502,
detail={
"error": "partial_message_update_failure",
"message": str(exc),
"failed": exc.failed,
"succeeded": exc.succeeded,
"total": exc.total,
},
) from exc
except httpx.HTTPStatusError as exc:
raise HTTPException(
status_code=exc.response.status_code,
detail=exc.response.json(),
) from exc
@app.get("/healthz", include_in_schema=False)
async def healthcheck():
try:
connection: asyncpg.pool.PoolConnectionProxy
async with await database.acquire() as connection:
result = await connection.fetchval("SELECT true FROM merge_request_ref")
return {"ok": result}
except Exception as e:
logger.error(
"health check failed",
error_type=type(e).__name__,
error_detail=str(e),
exc_info=True,
)
raise HTTPException(status_code=500, detail=f"{type(e)}: {e}") from e
if __name__ == "__main__":
# fmt: off
print(
"use fastapi cli to run this app\n"
"- fastapi run # for prod\n"
"- fastapi dev # for dev :)\n"
)
# fmt: on
# for debug entry point
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)