diff --git a/Makefile b/Makefile index 6a1351ab..2b99dd32 100644 --- a/Makefile +++ b/Makefile @@ -27,20 +27,20 @@ ifeq ("$(wildcard ${DC})","") endif check-dc-config-%: check-prerequisites ## Check docker-compose syntax - ${DC} -f docker-compose.yml config -q + ${DC} config -q build: check-dc-config-% - TAG=${TAG} ${DC} -f docker-compose.yml build + TAG=${TAG} ${DC} build up: check-dc-config-% ifeq ("$(WORKSPACE)","preprod") - TAG=${TAG} PORT_PROD=8080 ${DC} -f docker-compose.yml up -d + TAG=${TAG} PORT_PROD=8080 ${DC} up -d else - TAG=${TAG} ${DC} -f docker-compose.yml up -d + TAG=${TAG} ${DC} up -d endif down: - ${DC} -f docker-compose.yml down + ${DC} down tag: show-current-tag git tag -a v${TAG} diff --git a/backend/src/main.py b/backend/src/main.py index 6c5ddfd3..bf692f4d 100644 --- a/backend/src/main.py +++ b/backend/src/main.py @@ -9,8 +9,7 @@ from typing import Union import boto3 -from botocore.client import ClientError -from fastapi import BackgroundTasks, Cookie, FastAPI, File, Form, HTTPException, Request, Response, UploadFile +from fastapi import BackgroundTasks, Cookie, FastAPI, APIRouter, File, Form, HTTPException, Request, Response, UploadFile from fastapi.responses import PlainTextResponse from fastapi.middleware.cors import CORSMiddleware from gelfformatter import GelfFormatter @@ -138,7 +137,9 @@ def upload_image(content: bytes, image_key: str): #################### # FastAPI Setup -app = FastAPI() +app = FastAPI(docs_url="/api/docs") +router = APIRouter(prefix="/api") + origins = [ # allow requests from front-end "http://basegun.fr", "https://basegun.fr", @@ -198,17 +199,17 @@ def upload_image(content: bytes, image_key: str): #################### # ROUTES # #################### -@app.get("/", response_class=PlainTextResponse) +@router.get("/", response_class=PlainTextResponse) def home(): return "Basegun backend" -@app.get("/version", response_class=PlainTextResponse) +@router.get("/version", response_class=PlainTextResponse) def version(): return APP_VERSION -@app.get("/logs") +@router.get("/logs") def logs(): if "WORKSPACE" in os.environ and os.environ["WORKSPACE"] != "prod": with open(os.path.join(PATH_LOGS, "log.json"), "r") as f: @@ -220,7 +221,7 @@ def logs(): return PlainTextResponse("Forbidden") -@app.post("/upload") +@router.post("/upload") async def imageupload( request: Request, response: Response, @@ -279,7 +280,7 @@ async def imageupload( raise HTTPException(status_code=500, detail=str(e)) -@app.post("/identification-feedback") +@router.post("/identification-feedback") async def log_feedback(request: Request, user_id: Union[str, None] = Cookie(None)): res = await request.json() @@ -294,7 +295,7 @@ async def log_feedback(request: Request, user_id: Union[str, None] = Cookie(None return -@app.post("/tutorial-feedback") +@router.post("/tutorial-feedback") async def log_tutorial_feedback(request: Request, user_id: Union[str, None] = Cookie(None)): res = await request.json() @@ -309,7 +310,7 @@ async def log_tutorial_feedback(request: Request, user_id: Union[str, None] = Co return -@app.post("/identification-dummy") +@router.post("/identification-dummy") async def log_identification_dummy(request: Request, user_id: Union[str, None] = Cookie(None)): res = await request.json() @@ -322,4 +323,6 @@ async def log_identification_dummy(request: Request, user_id: Union[str, None] = extras_logging["bg_"+key] = res[key] logger.info("Identification dummy", extra=extras_logging) - return \ No newline at end of file + return + +app.include_router(router) \ No newline at end of file diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py index 4659144a..ec828d9a 100644 --- a/backend/tests/test_api.py +++ b/backend/tests/test_api.py @@ -39,12 +39,12 @@ def create_bucket(): class TestModel(unittest.TestCase): def test_home(self): """Checks that the route / is alive""" - response = client.get("/") + response = client.get("/api/") self.assertEqual(response.text, "Basegun backend") def test_version(self): """Checks that the route /version sends a version""" - response = client.get("/version") + response = client.get("/api/version") self.assertEqual(response.status_code, 200) def check_log_base(self, log): @@ -66,7 +66,7 @@ def test_upload(self): geoloc = "12.666,7.666" with open(path, 'rb') as f: - r = client.post("/upload", + r = client.post("/api/upload", files={"image": f}, data={"date": time.time(), "geolocation": geoloc}) self.assertEqual(r.status_code, 200) @@ -77,7 +77,7 @@ def test_upload(self): self.assertAlmostEqual(res["confidence"], 98.43, places=1) self.assertTrue(res["confidence_level"], "high") # checks that the result is written in logs - r = client.get("/logs") + r = client.get("/api/logs") self.assertEqual(r.status_code, 200) # checks the latest log with validates upload to object storage self.assertEqual(r.json()[0]["_bg_image_url"], r.json()[1]["_bg_image_url"]) @@ -98,11 +98,11 @@ def test_feedback_and_logs(self): label = "revolver" confidence_level = "high" image_url = "https://storage.gra.cloud.ovh.net/v1/test" - r = client.post("/identification-feedback", + r = client.post("/api/identification-feedback", json={"image_url": image_url, "feedback": True, "confidence": confidence, "label": label, "confidence_level": confidence_level}) self.assertEqual(r.status_code, 200) - r = client.get("/logs") + r = client.get("/api/logs") self.assertEqual(r.status_code, 200) log = r.json()[0] self.check_log_base(log) diff --git a/frontend/.env.development b/frontend/.env.development new file mode 100644 index 00000000..531964bd --- /dev/null +++ b/frontend/.env.development @@ -0,0 +1 @@ +VITE_API_HOST=http://localhost:5000 \ No newline at end of file diff --git a/frontend/Dockerfile b/frontend/Dockerfile index 8dfbef8c..46cd2c1f 100644 --- a/frontend/Dockerfile +++ b/frontend/Dockerfile @@ -9,9 +9,7 @@ COPY ./cert/. /etc/ssl/certs/ COPY ./package.json ./package-lock.json ./ RUN npm ci --legacy-peer-deps -COPY src ./src -COPY public ./public -COPY vite.config.js index.html ./ +COPY . . FROM base as dev diff --git a/frontend/nginx.conf b/frontend/nginx.conf index f72c168d..04175476 100644 --- a/frontend/nginx.conf +++ b/frontend/nginx.conf @@ -15,14 +15,6 @@ http { try_files $uri $uri/ /index.html; } - location /api/ { - proxy_pass http://basegun-backend:5000/; - client_max_body_size 5M; - proxy_read_timeout 1800; - proxy_connect_timeout 1800; - proxy_send_timeout 1800; - } - error_page 404 /404.html; error_page 500 502 503 504 /50x.html; diff --git a/frontend/src/main.js b/frontend/src/main.js index 4946bc39..f1107945 100644 --- a/frontend/src/main.js +++ b/frontend/src/main.js @@ -20,8 +20,6 @@ register() const pinia = createPinia() -axios.defaults.withCredentials = true - // the FastAPI backend axios.defaults.baseURL = '/api/' diff --git a/frontend/vite.config.js b/frontend/vite.config.js index 60e8385b..1cf9cb78 100644 --- a/frontend/vite.config.js +++ b/frontend/vite.config.js @@ -6,7 +6,7 @@ import transformerDirectives from '@unocss/transformer-directives' import transformerVariantGroup from '@unocss/transformer-variant-group' const path = require('path') -const apiHost = process.env.API_HOST || 'basegun-backend' +const apiHost = process.env.API_HOST || 'http://basegun-backend:5000' // https://vitejs.dev/config/ export default defineConfig({ @@ -61,9 +61,8 @@ export default defineConfig({ host: true, proxy: { '^/api': { - target: `http://${apiHost}:5000`, - changeOrigin: true, - rewrite: (path) => path.replace(/^\/api/, ''), + target: `${apiHost}`, + changeOrigin: true }, }, }, diff --git a/infra/kube/helm/templates/deployment-backend.yaml b/infra/kube/helm/templates/deployment-backend.yaml index 9d0b4bf9..ca4fecbc 100644 --- a/infra/kube/helm/templates/deployment-backend.yaml +++ b/infra/kube/helm/templates/deployment-backend.yaml @@ -45,13 +45,13 @@ spec: protocol: TCP livenessProbe: httpGet: - path: / + path: /api/ port: api initialDelaySeconds: 10 periodSeconds: 60 readinessProbe: httpGet: - path: / + path: /api/ port: api volumeMounts: - name: logs diff --git a/infra/kube/helm/templates/ingress.yaml b/infra/kube/helm/templates/ingress.yaml index 9e72b1fe..49689be9 100644 --- a/infra/kube/helm/templates/ingress.yaml +++ b/infra/kube/helm/templates/ingress.yaml @@ -1,18 +1,7 @@ {{- if .Values.ingress.enabled -}} -{{- $fullName := include "basegun.chart" . -}} -{{- $svcPort := .Values.frontend.service.port -}} -{{- if and .Values.ingress.className (not (semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion)) }} - {{- if not (hasKey .Values.ingress.annotations "kubernetes.io/ingress.class") }} - {{- $_ := set .Values.ingress.annotations "kubernetes.io/ingress.class" .Values.ingress.className}} - {{- end }} -{{- end }} -{{- if semverCompare ">=1.19-0" .Capabilities.KubeVersion.GitVersion -}} +{{- $svcPortFrontend := .Values.frontend.service.port -}} +{{- $svcPortBackend := .Values.backend.service.port -}} apiVersion: networking.k8s.io/v1 -{{- else if semverCompare ">=1.14-0" .Capabilities.KubeVersion.GitVersion -}} -apiVersion: networking.k8s.io/v1beta1 -{{- else -}} -apiVersion: extensions/v1beta1 -{{- end }} kind: Ingress metadata: name: "basegun-ingress" @@ -23,9 +12,7 @@ metadata: {{- toYaml . | nindent 4 }} {{- end }} spec: - {{- if and .Values.ingress.className (semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion) }} ingressClassName: {{ .Values.ingress.className }} - {{- end }} {{- if .Values.ingress.tls }} tls: {{- range .Values.ingress.tls }} @@ -41,21 +28,19 @@ spec: - host: {{ .host | quote }} http: paths: - {{- range .paths }} - - path: {{ .path }} - {{- if and .pathType (semverCompare ">=1.18-0" $.Capabilities.KubeVersion.GitVersion) }} - pathType: {{ .pathType }} - {{- end }} - backend: - {{- if semverCompare ">=1.19-0" $.Capabilities.KubeVersion.GitVersion }} - service: - name: "basegun-frontend" - port: - number: {{ $svcPort }} - {{- else }} - serviceName: "basegun-frontend" - servicePort: {{ $svcPort }} - {{- end }} - {{- end }} + - path: / + pathType: Prefix + backend: + service: + name: basegun-frontend + port: + number: {{ $svcPortFrontend }} + - path: /api/ + pathType: Prefix + backend: + service: + name: basegun-backend + port: + number: {{ $svcPortBackend }} {{- end }} -{{- end }} +{{- end }} \ No newline at end of file diff --git a/infra/kube/helm/values.yaml b/infra/kube/helm/values.yaml index c7d5a92d..d9430866 100644 --- a/infra/kube/helm/values.yaml +++ b/infra/kube/helm/values.yaml @@ -59,7 +59,7 @@ backend: memory: 256Mi service: type: ClusterIP - port: 5000 + port: 80 containerPort: 5000 autoscaling: enabled: false @@ -111,7 +111,7 @@ frontend: service: type: ClusterIP - port: 8080 + port: 80 containerPort: 8080 resources: # We usually recommend not to specify default resources and to leave this as a conscious