Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ POSTGRES_PASSWORD=change-me-strong-password
# --- API 应用 ---
# 本地测试/脚本用 localhost;docker compose 内会被覆盖为 @db:5432
DATABASE_URL=postgresql+psycopg2://pasay_pm:change-me-strong-password@localhost:5432/pasay_pm
# Optional direct / unpooled URL for migrations and admin tooling.
# For Neon, keep DATABASE_URL on the pooled endpoint and set DATABASE_URL_UNPOOLED
# to the matching direct endpoint (no -pooler host suffix).
# DATABASE_URL_UNPOOLED=postgresql+psycopg2://pasay_pm:change-me-strong-password@localhost:5432/pasay_pm
UPLOAD_DIR=uploads
# V1.2: bot token for the notifier worker (Telegram sendMessage). Leave empty
# to run the scheduler without sending notifications.
Expand Down
8 changes: 8 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,11 @@ pasay-telegram-bot/.pytest_tmp/
.audit/
.build/
.research/

# PASAY-ARCH-CF-NEON-001: local Cloudflare Worker artifacts stay untracked
cloudflare-worker/node_modules/
cloudflare-worker/.wrangler/
cloudflare-worker/.wrangler-config/
cloudflare-worker/.dev.vars*
!cloudflare-worker/.dev.vars.example
cloudflare-worker/.env
Comment thread
coderabbitai[bot] marked this conversation as resolved.
6 changes: 5 additions & 1 deletion alembic/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,18 @@
from sqlalchemy import engine_from_config, pool

from app.config import settings
from app.infrastructure.postgres import build_postgres_runtime_boundary
from app.models import Base

config = context.config

if config.config_file_name is not None:
fileConfig(config.config_file_name)

config.set_main_option("sqlalchemy.url", settings.database_url)
config.set_main_option(
"sqlalchemy.url",
build_postgres_runtime_boundary(settings).migration_url,
)
target_metadata = Base.metadata


Expand Down
1 change: 1 addition & 0 deletions app/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")

database_url: str = "postgresql+psycopg2://pasay_pm:pasay_pm@localhost:5432/pasay_pm"
database_url_unpooled: str | None = None
upload_dir: str = "uploads"
# V1.2: bot token used by the notifier worker for sendMessage. Leave empty
# to run the scheduler without sending notifications.
Expand Down
5 changes: 3 additions & 2 deletions app/database.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from sqlalchemy import create_engine
from sqlalchemy.orm import Session, sessionmaker

from app.config import settings
from app.infrastructure.postgres import build_postgres_runtime_boundary, create_app_engine

engine = create_engine(settings.database_url, pool_pre_ping=True)
database_boundary = build_postgres_runtime_boundary(settings)
engine = create_app_engine(database_boundary)
SessionLocal = sessionmaker(bind=engine, autoflush=False, expire_on_commit=False)


Expand Down
1 change: 1 addition & 0 deletions app/infrastructure/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Infrastructure adapters and runtime-specific boundaries."""
67 changes: 67 additions & 0 deletions app/infrastructure/postgres.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
from __future__ import annotations

from dataclasses import dataclass

from sqlalchemy import create_engine
from sqlalchemy.engine import Engine, make_url
from sqlalchemy.orm import sessionmaker


def normalize_sqlalchemy_postgres_url(database_url: str) -> str:
"""Keep legacy local URLs working while accepting generic Postgres URLs."""
if database_url.startswith("postgresql+"):
return database_url
if database_url.startswith("postgresql://"):
return database_url.replace("postgresql://", "postgresql+psycopg2://", 1)
if database_url.startswith("postgres://"):
return database_url.replace("postgres://", "postgresql+psycopg2://", 1)
return database_url


def detect_connection_mode(database_url: str) -> str:
return "pooled" if "-pooler." in database_url else "direct"


def detect_database_provider(database_url: str) -> str:
lowered = database_url.lower()
return "neon" if "neon.tech" in lowered else "postgres"


@dataclass(frozen=True)
class PostgresRuntimeBoundary:
application_url: str
migration_url: str
provider: str
application_connection_mode: str
migration_connection_mode: str

@property
def config_available(self) -> bool:
return bool(self.application_url)


def build_postgres_runtime_boundary(settings) -> PostgresRuntimeBoundary:
application_url = normalize_sqlalchemy_postgres_url(settings.database_url)
migration_url = normalize_sqlalchemy_postgres_url(
settings.database_url_unpooled or settings.database_url
)
return PostgresRuntimeBoundary(
application_url=application_url,
migration_url=migration_url,
provider=detect_database_provider(application_url),
application_connection_mode=detect_connection_mode(application_url),
migration_connection_mode=detect_connection_mode(migration_url),
)


def create_app_engine(boundary: PostgresRuntimeBoundary) -> Engine:
return create_engine(boundary.application_url, pool_pre_ping=True)


def create_session_local(boundary: PostgresRuntimeBoundary) -> sessionmaker:
engine = create_app_engine(boundary)
return sessionmaker(bind=engine, autoflush=False, expire_on_commit=False)


def redact_database_url(database_url: str) -> str:
return make_url(database_url).render_as_string(hide_password=True)
13 changes: 6 additions & 7 deletions app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@

from fastapi import FastAPI
from fastapi.responses import JSONResponse
from sqlalchemy import text

from app.api.routers import (
attachments,
Expand All @@ -31,6 +30,8 @@
viewings,
)
from app.database import engine
from app.config import settings
from app.runtime.health import build_health_payload

app = FastAPI(
title="PASay Property Management API",
Expand Down Expand Up @@ -61,9 +62,7 @@

@app.get("/health", summary="Health check (no auth)")
def health():
try:
with engine.connect() as conn:
conn.execute(text("SELECT 1"))
except Exception:
return JSONResponse(status_code=503, content={"status": "unavailable"})
return {"status": "ok"}
status_code, payload = build_health_payload(settings=settings, engine=engine)
if status_code != 200:
return JSONResponse(status_code=status_code, content=payload)
return payload
1 change: 1 addition & 0 deletions app/runtime/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Runtime-agnostic application helpers."""
43 changes: 43 additions & 0 deletions app/runtime/health.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
from __future__ import annotations

from typing import Any

from sqlalchemy import text

from app.infrastructure.postgres import build_postgres_runtime_boundary


def build_health_payload(*, settings, engine, include_db_connectivity: bool = True) -> tuple[int, dict[str, Any]]:
boundary = build_postgres_runtime_boundary(settings)
payload: dict[str, Any] = {
"status": "ok",
"runtime": {
"platform": "fastapi",
"alive": True,
},
"application": {
"boot": "ok",
},
"database": {
"configured": boundary.config_available,
"provider": boundary.provider,
"application_connection_mode": boundary.application_connection_mode,
"migration_connection_mode": boundary.migration_connection_mode,
"connectivity_checked": include_db_connectivity,
"reachable": None,
},
}

if not include_db_connectivity:
return 200, payload

try:
with engine.connect() as conn:
conn.execute(text("SELECT 1"))
except Exception:
payload["status"] = "unavailable"
payload["database"]["reachable"] = False
return 503, payload

payload["database"]["reachable"] = True
return 200, payload
6 changes: 6 additions & 0 deletions cloudflare-worker/.dev.vars.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Use this file only for local `wrangler dev`.
# Do not commit real secrets. Prefer the environment variable form
# `CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE` so local creds stay
# out of source control.
PASAY_APP_ENV=local
PASAY_HEALTHCHECK_DB_CONNECTIVITY=false
30 changes: 30 additions & 0 deletions cloudflare-worker/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Pasay Cloudflare Worker Foundation

This directory is the PASAY-ARCH-CF-NEON-001 foundation slice for the future
Cloudflare runtime. It intentionally exposes only a minimal `GET /health`
Worker and keeps all business logic in the existing Python codebase.

## Configuration model

- Worker runtime: Cloudflare Workers (`wrangler.jsonc`)
- Database edge boundary: Hyperdrive binding `HYPERDRIVE`
- Local dev credentials: use
`CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE`
- App-level non-secret vars: `.dev.vars` or `wrangler.jsonc` `vars`
- Secrets: manage outside the repo with Cloudflare secrets / Hyperdrive config

## Neon notes

- Application traffic should use the pooled Neon endpoint behind Hyperdrive.
- Migrations and admin tooling should use the direct Neon endpoint.
- This slice does not create or modify a second schema.

## Commands

- `npm install`
- `npm run typegen`
- `npm test`
- `npx wrangler dev`

For remote Hyperdrive behavior, use `npx wrangler dev --remote` only after the
real Hyperdrive binding ID is provisioned outside this repository.
Loading
Loading