Skip to content

Commit c283839

Browse files
Merge pull request #42 from developmentseed/feature/customize-original-pg-settings
customize runtime's initial pg-settings for raster and vector, as done for stac
2 parents 0ca9fbc + fc22078 commit c283839

File tree

8 files changed

+57
-61
lines changed

8 files changed

+57
-61
lines changed

infrastructure/handlers/raster_handler.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,23 +5,18 @@
55
import os
66

77
from eoapi.raster.app import app
8-
from eoapi.raster.config import ApiSettings
8+
from eoapi.raster.config import PostgresSettings
99
from mangum import Mangum
1010
from titiler.pgstac.db import connect_to_db
1111

1212
logging.getLogger("mangum.lifespan").setLevel(logging.ERROR)
1313
logging.getLogger("mangum.http").setLevel(logging.ERROR)
1414

15-
settings = ApiSettings()
16-
1715

1816
@app.on_event("startup")
1917
async def startup_event() -> None:
2018
"""Connect to database on startup."""
21-
await connect_to_db(
22-
app,
23-
settings=settings.load_postgres_settings(),
24-
)
19+
await connect_to_db(app, settings=PostgresSettings())
2520

2621

2722
handler = Mangum(app, lifespan="off")

infrastructure/handlers/vector_handler.py

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,24 +3,17 @@
33
import asyncio
44
import logging
55
import os
6+
from importlib.resources import files as resources_files
67

78
from eoapi.vector.app import app
8-
from eoapi.vector.config import ApiSettings
9+
from eoapi.vector.config import PostgresSettings
910
from mangum import Mangum
1011
from tipg.collections import register_collection_catalog
1112
from tipg.database import connect_to_db
1213

1314
logging.getLogger("mangum.lifespan").setLevel(logging.ERROR)
1415
logging.getLogger("mangum.http").setLevel(logging.ERROR)
1516

16-
settings = ApiSettings()
17-
18-
try:
19-
from importlib.resources import files as resources_files # type: ignore
20-
except ImportError:
21-
# Try backported to PY<39 `importlib_resources`.
22-
from importlib_resources import files as resources_files # type: ignore
23-
2417

2518
CUSTOM_SQL_DIRECTORY = resources_files("eoapi.vector") / "sql"
2619
sql_files = list(CUSTOM_SQL_DIRECTORY.glob("*.sql")) # type: ignore
@@ -31,7 +24,7 @@ async def startup_event() -> None:
3124
"""Connect to database on startup."""
3225
await connect_to_db(
3326
app,
34-
settings=settings.load_postgres_settings(),
27+
settings=PostgresSettings(),
3528
# We enable both pgstac and public schemas (pgstac will be used by custom functions)
3629
schemas=["pgstac", "public"],
3730
user_sql_files=sql_files,

runtimes/eoapi/raster/eoapi/raster/app.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@
4747
from titiler.pgstac.reader import PgSTACReader
4848

4949
from . import __version__ as eoapi_raster_version
50-
from .config import ApiSettings
50+
from .config import ApiSettings, PostgresSettings
5151
from .logs import init_logging
5252

5353
settings = ApiSettings()
@@ -90,7 +90,7 @@
9090
async def lifespan(app: FastAPI):
9191
"""FastAPI Lifespan."""
9292
logger.debug("Connecting to db...")
93-
await connect_to_db(app, settings=settings.load_postgres_settings())
93+
await connect_to_db(app, settings=PostgresSettings())
9494
logger.debug("Connected to db.")
9595

9696
yield

runtimes/eoapi/raster/eoapi/raster/config.py

Lines changed: 22 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,15 @@
22

33
import base64
44
import json
5-
from typing import Optional
5+
from typing import Any, Dict, Optional
66

77
import boto3
8-
from pydantic import field_validator
8+
from pydantic import field_validator, model_validator
99
from pydantic_settings import BaseSettings
10-
from titiler.pgstac.settings import PostgresSettings
10+
from titiler.pgstac.settings import PostgresSettings as _PostgresSettings
1111

1212

13-
def get_secret_dict(secret_name: str):
13+
def get_secret_dict(secret_name: str) -> Dict:
1414
"""Retrieve secrets from AWS Secrets Manager
1515
1616
Args:
@@ -43,8 +43,6 @@ class ApiSettings(BaseSettings):
4343
debug: bool = False
4444
root_path: str = ""
4545

46-
pgstac_secret_arn: Optional[str] = None
47-
4846
model_config = {
4947
"env_file": ".env",
5048
"extra": "allow",
@@ -60,18 +58,24 @@ def parse_cors_methods(cls, v):
6058
"""Parse CORS methods."""
6159
return [method.strip() for method in v.split(",")]
6260

63-
def load_postgres_settings(self) -> "PostgresSettings":
64-
"""Load postgres connection params from AWS secret"""
6561

66-
if self.pgstac_secret_arn:
67-
secret = get_secret_dict(self.pgstac_secret_arn)
62+
class PostgresSettings(_PostgresSettings):
63+
"""Extent titiler-pgstac PostgresSettings settings"""
6864

69-
return PostgresSettings(
70-
postgres_host=secret["host"],
71-
postgres_dbname=secret["dbname"],
72-
postgres_user=secret["username"],
73-
postgres_pass=secret["password"],
74-
postgres_port=secret["port"],
65+
pgstac_secret_arn: Optional[str] = None
66+
67+
@model_validator(mode="before")
68+
def get_postgres_setting(cls, data: Any) -> Any:
69+
if arn := data.get("pgstac_secret_arn"):
70+
secret = get_secret_dict(arn)
71+
data.update(
72+
{
73+
"postgres_host": secret["host"],
74+
"postgres_dbname": secret["dbname"],
75+
"postgres_user": secret["username"],
76+
"postgres_pass": secret["password"],
77+
"postgres_port": secret["port"],
78+
}
7579
)
76-
else:
77-
return PostgresSettings()
80+
81+
return data

runtimes/eoapi/raster/pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ classifiers = [
2020
]
2121
dynamic = ["version"]
2222
dependencies = [
23-
"titiler.pgstac==1.6.0",
23+
"titiler.pgstac==1.7.1",
2424
"titiler.extensions",
2525
"starlette-cramjam>=0.4,<0.5",
2626
"importlib_resources>=1.1.0;python_version<'3.9'",

runtimes/eoapi/stac/eoapi/stac/config.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,14 @@
22

33
import base64
44
import json
5-
from typing import Any, Optional
5+
from typing import Any, Dict, Optional
66

77
import boto3
88
from pydantic import model_validator
99
from stac_fastapi.pgstac import config
1010

1111

12-
def get_secret_dict(secret_name: str):
12+
def get_secret_dict(secret_name: str) -> Dict:
1313
"""Retrieve secrets from AWS Secrets Manager
1414
1515
Args:

runtimes/eoapi/vector/eoapi/vector/app.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import logging
44
from contextlib import asynccontextmanager
5-
from importlib.resources import files as resources_files # type: ignore
5+
from importlib.resources import files as resources_files
66

77
import jinja2
88
from eoapi.auth_utils import OpenIdConnectAuth, OpenIdConnectSettings
@@ -17,13 +17,12 @@
1717
from tipg.middleware import CacheControlMiddleware, CatalogUpdateMiddleware
1818

1919
from . import __version__ as eoapi_vector_version
20-
from .config import ApiSettings
20+
from .config import ApiSettings, PostgresSettings
2121
from .logs import init_logging
2222

2323
CUSTOM_SQL_DIRECTORY = resources_files(__package__) / "sql"
2424

2525
settings = ApiSettings()
26-
postgres_settings = settings.load_postgres_settings()
2726
auth_settings = OpenIdConnectSettings()
2827

2928
# Logs
@@ -53,7 +52,7 @@ async def lifespan(app: FastAPI):
5352
logger.debug("Connecting to db...")
5453
await connect_to_db(
5554
app,
56-
settings=postgres_settings,
55+
settings=PostgresSettings(),
5756
# We enable both pgstac and public schemas (pgstac will be used by custom functions)
5857
schemas=["pgstac", "public"],
5958
user_sql_files=list(CUSTOM_SQL_DIRECTORY.glob("*.sql")), # type: ignore

runtimes/eoapi/vector/eoapi/vector/config.py

Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,15 @@
22

33
import base64
44
import json
5-
from typing import Optional
5+
from typing import Any, Dict, Optional
66

77
import boto3
8-
from pydantic import field_validator
8+
from pydantic import field_validator, model_validator
99
from pydantic_settings import BaseSettings
10-
from tipg.settings import PostgresSettings
10+
from tipg.settings import PostgresSettings as _PostgresSettings
1111

1212

13-
def get_secret_dict(secret_name: str):
13+
def get_secret_dict(secret_name: str) -> Dict:
1414
"""Retrieve secrets from AWS Secrets Manager
1515
1616
Args:
@@ -43,7 +43,6 @@ class ApiSettings(BaseSettings):
4343
debug: bool = False
4444
root_path: str = ""
4545

46-
pgstac_secret_arn: Optional[str] = None
4746
catalog_ttl: int = 300
4847

4948
model_config = {
@@ -61,18 +60,24 @@ def parse_cors_methods(cls, v):
6160
"""Parse CORS methods."""
6261
return [method.strip() for method in v.split(",")]
6362

64-
def load_postgres_settings(self) -> "PostgresSettings":
65-
"""Load postgres connection params from AWS secret"""
6663

67-
if self.pgstac_secret_arn:
68-
secret = get_secret_dict(self.pgstac_secret_arn)
64+
class PostgresSettings(_PostgresSettings):
65+
"""Extent tipg PostgresSettings settings"""
66+
67+
pgstac_secret_arn: Optional[str] = None
6968

70-
return PostgresSettings(
71-
postgres_host=secret["host"],
72-
postgres_dbname=secret["dbname"],
73-
postgres_user=secret["username"],
74-
postgres_pass=secret["password"],
75-
postgres_port=secret["port"],
69+
@model_validator(mode="before")
70+
def get_postgres_setting(cls, data: Any) -> Any:
71+
if arn := data.get("pgstac_secret_arn"):
72+
secret = get_secret_dict(arn)
73+
data.update(
74+
{
75+
"postgres_host": secret["host"],
76+
"postgres_dbname": secret["dbname"],
77+
"postgres_user": secret["username"],
78+
"postgres_pass": secret["password"],
79+
"postgres_port": secret["port"],
80+
}
7681
)
77-
else:
78-
return PostgresSettings()
82+
83+
return data

0 commit comments

Comments
 (0)