Skip to content

Commit 6929841

Browse files
authored
Merge pull request #25 from pgulb/8-implement-mongo-connectivity
8 implement mongo connectivity
2 parents 16ba2bd + e2b5499 commit 6929841

File tree

6 files changed

+66
-2
lines changed

6 files changed

+66
-2
lines changed

.github/workflows/deploy-api.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,4 @@ jobs:
3131
run: |
3232
echo ${{ secrets.FROG_KEY }} | base64 -d > frog &&
3333
chmod 600 frog &&
34-
ssh -o StrictHostKeyChecking=no -i frog ${{ secrets.FROG_ADDRESS }} -p${{ secrets.FROG_PORT }} "docker run -d -p 30149:6789 --name flush-log-api --restart=unless-stopped ghcr.io/pgulb/flush-log:api"
34+
ssh -o StrictHostKeyChecking=no -i frog ${{ secrets.FROG_ADDRESS }} -p${{ secrets.FROG_PORT }} "docker run -d -p 30149:6789 -e MONGO_URL=mock --name flush-log-api --restart=unless-stopped ghcr.io/pgulb/flush-log:api"

api/__init__.py

Whitespace-only changes.

api/db.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
from pymongo import MongoClient
2+
from pymongo.errors import ConnectionFailure
3+
4+
5+
class MockClient:
6+
def __init__(self, not_avalaible: str):
7+
self.admin = self
8+
if not_avalaible == "true":
9+
self.command = self.__bad_command
10+
11+
def __bad_command(self, command: str):
12+
raise ConnectionFailure(f"Mock server not available, used command: {command}")
13+
14+
def command(self, command: str) -> str:
15+
if command == "ping":
16+
return "OK"
17+
raise NotImplementedError
18+
19+
20+
def create_mongo_client(url: str) -> MongoClient:
21+
return MongoClient(url)
22+
23+
24+
def create_mock_client(not_avalaible: str) -> MockClient:
25+
return MockClient(not_avalaible)

api/main.py

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
1+
import logging
2+
import os
13
from random import randint
24

35
import fastapi
4-
from fastapi import Depends, HTTPException, status
6+
from db import create_mock_client, create_mongo_client
7+
from fastapi import Depends, HTTPException, Response, status
58
from fastapi.middleware.cors import CORSMiddleware
69
from fastapi.security import HTTPBasic, HTTPBasicCredentials
710

@@ -18,6 +21,20 @@
1821
)
1922
security = HTTPBasic()
2023

24+
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(asctime)s %(message)s")
25+
26+
mongo_setting = os.getenv("MONGO_URL")
27+
if mongo_setting is None:
28+
raise ValueError("MONGO_URL not set")
29+
if mongo_setting == "mock":
30+
client = create_mock_client(os.getenv("MOCK_NOT_AVAILABLE"))
31+
logging.info("Using mock client")
32+
else:
33+
client = create_mongo_client(mongo_setting)
34+
logging.info("Using mongo client")
35+
if "/?" in mongo_setting:
36+
logging.info(f"client options: {mongo_setting.split("/?")[1]}")
37+
2138

2239
def check_creds(credentials: HTTPBasicCredentials):
2340
if not (credentials.username == "admin" and credentials.password == "admin"):
@@ -32,3 +49,17 @@ def check_creds(credentials: HTTPBasicCredentials):
3249
def root(credentials: HTTPBasicCredentials = Depends(security)):
3350
check_creds(credentials)
3451
return f"Random string from api {randint(0, 10000)}"
52+
53+
54+
@app.get("/healthz", status_code=status.HTTP_200_OK)
55+
def healthz():
56+
return "OK"
57+
58+
59+
@app.get("/readyz", status_code=status.HTTP_200_OK)
60+
def readyz():
61+
try:
62+
client.admin.command("ping")
63+
except Exception:
64+
return Response("NOT OK", status_code=status.HTTP_503_SERVICE_UNAVAILABLE)
65+
return "OK"

api/requirements.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,13 @@ annotated-types==0.7.0
22
anyio==4.6.2.post1
33
click==8.1.7
44
colorama==0.4.6
5+
dnspython==2.7.0
56
fastapi==0.115.2
67
h11==0.14.0
78
idna==3.10
89
pydantic==2.9.2
910
pydantic-core==2.23.4
11+
pymongo==4.10.1
1012
sniffio==1.3.1
1113
starlette==0.40.0
1214
typing-extensions==4.12.2

docker-compose.yml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,5 +17,11 @@ services:
1717
ports:
1818
- 6789:6789
1919
restart: unless-stopped
20+
environment:
21+
- MONGO_URL=mongodb://mongo:27017/?connectTimeoutMS=3000&timeoutMS=4000&socketTimeoutMS=3000&serverSelectionTimeoutMS=4000
22+
- MOCK_NOT_AVAILABLE=false
2023
volumes:
2124
- ./api:/src/
25+
mongo:
26+
image: mongo:8.0.1-noble
27+
restart: unless-stopped

0 commit comments

Comments
 (0)