|
1 | 1 | import logging |
2 | 2 | import os |
3 | 3 |
|
| 4 | +import boto3 |
| 5 | +from botocore.config import Config |
| 6 | +from botocore.exceptions import ClientError |
4 | 7 | from dotenv import load_dotenv |
5 | 8 | from fastapi import FastAPI, Request, HTTPException, Response |
6 | | -from google.cloud import storage |
7 | 9 |
|
8 | 10 | logging.basicConfig(level=logging.INFO) |
9 | 11 | logger = logging.getLogger(__name__) |
10 | 12 |
|
11 | 13 | load_dotenv() |
12 | 14 |
|
13 | 15 | PUBLIC_BUCKET = os.getenv("PUBLIC_BUCKET") |
| 16 | +CLOUDFLARE_ENDPOINT = os.getenv("CLOUDFLARE_ENDPOINT") |
| 17 | + |
14 | 18 | if not PUBLIC_BUCKET: |
15 | 19 | raise RuntimeError("Missing PUBLIC_BUCKET environment variable") |
| 20 | +if not CLOUDFLARE_ENDPOINT: |
| 21 | + raise RuntimeError("Missing CLOUDFLARE_ENDPOINT environment variable") |
| 22 | + |
| 23 | +# R2 uses "auto" region; SigV4 works. Some setups prefer 's3v4' explicit signature. |
| 24 | +boto_cfg = Config( |
| 25 | + region_name="auto", |
| 26 | + retries={"max_attempts": 3, "mode": "standard"}, |
| 27 | + s3={"addressing_style": "virtual"} |
| 28 | +) |
| 29 | + |
| 30 | +session = boto3.session.Session() |
| 31 | +s3_client = session.client( |
| 32 | + service_name="s3", |
| 33 | + endpoint_url=CLOUDFLARE_ENDPOINT, |
| 34 | + config=boto_cfg, |
| 35 | +) |
16 | 36 |
|
17 | | -storage_client = storage.Client() |
18 | | -bucket = storage_client.bucket(PUBLIC_BUCKET) |
19 | 37 |
|
20 | 38 | app = FastAPI() |
21 | 39 |
|
@@ -45,16 +63,18 @@ async def serve_file(request: Request, path: str = ""): |
45 | 63 | if not subdomain: |
46 | 64 | raise HTTPException(status_code=400, detail="Missing subdomain") |
47 | 65 |
|
48 | | - blob_path = f"{subdomain}/{path or 'index.html'}" |
49 | | - blob = bucket.blob(blob_path) |
50 | | - |
51 | | - if not blob.exists(): |
52 | | - raise HTTPException(status_code=404, detail="File not found") |
| 66 | + key = f"{subdomain}/{path or 'index.html'}" |
53 | 67 |
|
54 | | - blob.reload() |
| 68 | + try: |
| 69 | + obj = s3_client.get_object(Bucket=PUBLIC_BUCKET, Key=key) |
| 70 | + except ClientError as e: |
| 71 | + code = e.response.get("Error", {}).get("Code", "") |
| 72 | + if code in ("NoSuchKey", "NotFound", "404"): |
| 73 | + raise HTTPException(status_code=404, detail="File not found") |
| 74 | + raise HTTPException(status_code=502, detail="Storage backend error") |
55 | 75 |
|
56 | | - content_type = blob.content_type or "application/octet-stream" |
57 | | - data = blob.download_as_bytes() |
| 76 | + data = obj["Body"].read() |
| 77 | + content_type = obj.get("ContentType") or "application/octet-stream" |
58 | 78 |
|
59 | 79 | return Response(content=data, media_type=content_type) |
60 | 80 |
|
|
0 commit comments