-
Notifications
You must be signed in to change notification settings - Fork 182
Expand file tree
/
Copy pathmain.py
More file actions
175 lines (147 loc) · 5.64 KB
/
Copy pathmain.py
File metadata and controls
175 lines (147 loc) · 5.64 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
import logging
import os
from contextlib import asynccontextmanager
from arq import create_pool
from arq.connections import RedisSettings
from fastapi import FastAPI, Request, Depends, HTTPException, Response
from fastapi.responses import RedirectResponse
from fastapi.staticfiles import StaticFiles
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from starlette.middleware import Middleware
from starlette.middleware.sessions import SessionMiddleware
from starlette_wtf import CSRFProtectMiddleware
from config import get_settings, Settings
from db import get_db, AsyncSessionLocal
from dependencies import get_current_user, TemplateResponse
from models import User, Team, Deployment, Project
from routers import auth, project, github, google, team, user, event, admin, api
from services.loki import LokiService
settings = get_settings()
class CachedStaticFiles(StaticFiles):
async def get_response(self, path: str, scope) -> Response:
response = await super().get_response(path, scope)
response.headers["Cache-Control"] = "public, max-age=31536000, immutable"
return response
log_level = getattr(logging, settings.log_level.upper(), logging.INFO)
logging.basicConfig(level=log_level)
if log_level > logging.DEBUG:
logging.getLogger("sqlalchemy").setLevel(logging.WARNING)
@asynccontextmanager
async def lifespan(app: FastAPI):
redis_settings = RedisSettings.from_dsn(settings.redis_url)
app.state.redis_pool = await create_pool(redis_settings)
app.state.loki_service = LokiService()
try:
yield
finally:
try:
await app.state.loki_service.client.aclose()
await app.state.redis_pool.close()
except Exception:
pass
app = FastAPI(
lifespan=lifespan,
middleware=[
Middleware(SessionMiddleware, secret_key=settings.secret_key),
Middleware(CSRFProtectMiddleware, csrf_secret=settings.secret_key),
],
)
app.mount("/assets", CachedStaticFiles(directory="assets"), name="assets")
os.makedirs(settings.upload_dir, exist_ok=True)
app.mount("/upload", StaticFiles(directory=settings.upload_dir), name="upload")
@app.get("/health")
async def health():
return {"status": "ok"}
@app.get("/deployment-not-found/{host}")
async def catch_all_missing_container(
request: Request,
host: str,
db: AsyncSession = Depends(get_db),
settings: Settings = Depends(get_settings),
):
current_user = await get_current_user(
request=request,
db=db,
settings=settings,
redirect_on_fail=False,
)
if current_user and host.endswith(settings.deploy_domain):
import re
subdomain = host.removesuffix(f".{settings.deploy_domain}")
match = re.match(
r"^(?P<project_slug>.+)-id-(?P<short_id>[a-f0-9]{7})$", subdomain
)
if match:
project_slug = match.group("project_slug")
short_id = match.group("short_id")
async with AsyncSessionLocal() as db:
result = await db.execute(
select(Deployment, Project, Team)
.join(Project, Deployment.project_id == Project.id)
.join(Team, Project.team_id == Team.id)
.where(
Project.slug == project_slug,
Deployment.id.startswith(short_id),
)
)
deployment, project, team = result.first() or (None, None, None)
if deployment:
return TemplateResponse(
request=request,
name="error/deployment-not-found.html",
status_code=404,
context={
"current_user": current_user,
"deployment_url": request.url_for(
"project_deployment",
team_slug=team.slug,
project_name=project.name,
deployment_id=deployment.id,
).include_query_params(action="redeploy"),
"deployment_id": deployment.id,
},
)
return TemplateResponse(
request=request,
name="error/deployment-not-found.html",
status_code=404,
context={"current_user": current_user},
)
return TemplateResponse(
request=request,
name="error/deployment-not-found.html",
status_code=404,
context={},
)
@app.get("/", name="root")
async def root(
request: Request,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(get_current_user),
):
result = await db.execute(
select(Team.slug).where(Team.id == current_user.default_team_id)
)
team_slug = result.scalar_one_or_none()
if team_slug:
return RedirectResponse(f"/{team_slug}", status_code=302)
app.include_router(auth.router)
app.include_router(admin.router)
app.include_router(user.router)
app.include_router(project.router)
app.include_router(github.router)
app.include_router(google.router)
app.include_router(team.router)
app.include_router(event.router)
app.include_router(api.router)
@app.exception_handler(404)
async def handle_404(request: Request, exc: HTTPException):
return TemplateResponse(
request=request, name="error/404.html", status_code=404, context={}
)
@app.exception_handler(500)
async def handle_500(request: Request, exc: HTTPException):
return TemplateResponse(
request=request, name="error/500.html", status_code=500, context={}
)