Skip to content

Commit 3acd7df

Browse files
authored
Merge pull request #3588 from lonvia/optional-reverse-api
Add support for adding endpoints to server conditionally
2 parents 04d5f67 + 20d0fb3 commit 3acd7df

File tree

4 files changed

+80
-42
lines changed

4 files changed

+80
-42
lines changed

src/nominatim_api/server/falcon/server.py

Lines changed: 34 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -147,12 +147,36 @@ async def process_response(self, req: Request, resp: Response,
147147
f'{resource.name} "{params}"\n')
148148

149149

150-
class APIShutdown:
151-
""" Middleware that closes any open database connections.
150+
class APIMiddleware:
151+
""" Middleware managing the Nominatim database connection.
152152
"""
153153

154-
def __init__(self, api: NominatimAPIAsync) -> None:
155-
self.api = api
154+
def __init__(self, project_dir: Path, environ: Optional[Mapping[str, str]]) -> None:
155+
self.api = NominatimAPIAsync(project_dir, environ)
156+
self.app: Optional[App] = None
157+
158+
@property
159+
def config(self) -> Configuration:
160+
""" Get the configuration for Nominatim.
161+
"""
162+
return self.api.config
163+
164+
def set_app(self, app: App) -> None:
165+
""" Set the Falcon application this middleware is connected to.
166+
"""
167+
self.app = app
168+
169+
async def process_startup(self, *_: Any) -> None:
170+
""" Process the ASGI lifespan startup event.
171+
"""
172+
assert self.app is not None
173+
legacy_urls = self.api.config.get_bool('SERVE_LEGACY_URLS')
174+
formatter = load_format_dispatcher('v1', self.api.config.project_dir)
175+
for name, func in await api_impl.get_routes(self.api):
176+
endpoint = EndpointWrapper(name, func, self.api, formatter)
177+
self.app.add_route(f"/{name}", endpoint)
178+
if legacy_urls:
179+
self.app.add_route(f"/{name}.php", endpoint)
156180

157181
async def process_shutdown(self, *_: Any) -> None:
158182
"""Process the ASGI lifespan shutdown event.
@@ -164,28 +188,22 @@ def get_application(project_dir: Path,
164188
environ: Optional[Mapping[str, str]] = None) -> App:
165189
""" Create a Nominatim Falcon ASGI application.
166190
"""
167-
api = NominatimAPIAsync(project_dir, environ)
191+
apimw = APIMiddleware(project_dir, environ)
168192

169-
middleware: List[object] = [APIShutdown(api)]
170-
log_file = api.config.LOG_FILE
193+
middleware: List[object] = [apimw]
194+
log_file = apimw.config.LOG_FILE
171195
if log_file:
172196
middleware.append(FileLoggingMiddleware(log_file))
173197

174-
app = App(cors_enable=api.config.get_bool('CORS_NOACCESSCONTROL'),
198+
app = App(cors_enable=apimw.config.get_bool('CORS_NOACCESSCONTROL'),
175199
middleware=middleware)
200+
201+
apimw.set_app(app)
176202
app.add_error_handler(HTTPNominatimError, nominatim_error_handler)
177203
app.add_error_handler(TimeoutError, timeout_error_handler)
178204
# different from TimeoutError in Python <= 3.10
179205
app.add_error_handler(asyncio.TimeoutError, timeout_error_handler) # type: ignore[arg-type]
180206

181-
legacy_urls = api.config.get_bool('SERVE_LEGACY_URLS')
182-
formatter = load_format_dispatcher('v1', project_dir)
183-
for name, func in api_impl.ROUTES:
184-
endpoint = EndpointWrapper(name, func, api, formatter)
185-
app.add_route(f"/{name}", endpoint)
186-
if legacy_urls:
187-
app.add_route(f"/{name}.php", endpoint)
188-
189207
return app
190208

191209

src/nominatim_api/server/starlette/server.py

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,12 @@
77
"""
88
Server implementation using the starlette webserver framework.
99
"""
10-
from typing import Any, Optional, Mapping, Callable, cast, Coroutine, Dict, Awaitable
10+
from typing import Any, Optional, Mapping, Callable, cast, Coroutine, Dict, \
11+
Awaitable, AsyncIterator
1112
from pathlib import Path
1213
import datetime as dt
1314
import asyncio
15+
import contextlib
1416

1517
from starlette.applications import Starlette
1618
from starlette.routing import Route
@@ -66,7 +68,7 @@ def config(self) -> Configuration:
6668
return cast(Configuration, self.request.app.state.API.config)
6769

6870
def formatting(self) -> FormatDispatcher:
69-
return cast(FormatDispatcher, self.request.app.state.API.formatter)
71+
return cast(FormatDispatcher, self.request.app.state.formatter)
7072

7173

7274
def _wrap_endpoint(func: EndpointFunc)\
@@ -132,14 +134,6 @@ def get_application(project_dir: Path,
132134
"""
133135
config = Configuration(project_dir, environ)
134136

135-
routes = []
136-
legacy_urls = config.get_bool('SERVE_LEGACY_URLS')
137-
for name, func in api_impl.ROUTES:
138-
endpoint = _wrap_endpoint(func)
139-
routes.append(Route(f"/{name}", endpoint=endpoint))
140-
if legacy_urls:
141-
routes.append(Route(f"/{name}.php", endpoint=endpoint))
142-
143137
middleware = []
144138
if config.get_bool('CORS_NOACCESSCONTROL'):
145139
middleware.append(Middleware(CORSMiddleware,
@@ -156,14 +150,26 @@ def get_application(project_dir: Path,
156150
asyncio.TimeoutError: timeout_error
157151
}
158152

159-
async def _shutdown() -> None:
153+
@contextlib.asynccontextmanager
154+
async def lifespan(app: Starlette) -> AsyncIterator[Any]:
155+
app.state.API = NominatimAPIAsync(project_dir, environ)
156+
config = app.state.API.config
157+
158+
legacy_urls = config.get_bool('SERVE_LEGACY_URLS')
159+
for name, func in await api_impl.get_routes(app.state.API):
160+
endpoint = _wrap_endpoint(func)
161+
app.routes.append(Route(f"/{name}", endpoint=endpoint))
162+
if legacy_urls:
163+
app.routes.append(Route(f"/{name}.php", endpoint=endpoint))
164+
165+
yield
166+
160167
await app.state.API.close()
161168

162-
app = Starlette(debug=debug, routes=routes, middleware=middleware,
169+
app = Starlette(debug=debug, middleware=middleware,
163170
exception_handlers=exceptions,
164-
on_shutdown=[_shutdown])
171+
lifespan=lifespan)
165172

166-
app.state.API = NominatimAPIAsync(project_dir, environ)
167173
app.state.formatter = load_format_dispatcher('v1', project_dir)
168174

169175
return app

src/nominatim_api/v1/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,4 @@
88
Implementation of API version v1 (aka the legacy version).
99
"""
1010

11-
from .server_glue import ROUTES as ROUTES
11+
from .server_glue import get_routes as get_routes

src/nominatim_api/v1/server_glue.py

Lines changed: 25 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
Generic part of the server implementation of the v1 API.
99
Combine with the scaffolding provided for the various Python ASGI frameworks.
1010
"""
11-
from typing import Optional, Any, Type, Dict, cast
11+
from typing import Optional, Any, Type, Dict, cast, Sequence, Tuple
1212
from functools import reduce
1313
import dataclasses
1414
from urllib.parse import urlencode
@@ -25,7 +25,8 @@
2525
from ..localization import Locales
2626
from . import helpers
2727
from ..server import content_types as ct
28-
from ..server.asgi_adaptor import ASGIAdaptor
28+
from ..server.asgi_adaptor import ASGIAdaptor, EndpointFunc
29+
from ..sql.async_core_library import PGCORE_ERROR
2930

3031

3132
def build_response(adaptor: ASGIAdaptor, output: str, status: int = 200,
@@ -417,12 +418,25 @@ async def polygons_endpoint(api: NominatimAPIAsync, params: ASGIAdaptor) -> Any:
417418
return build_response(params, params.formatting().format_result(results, fmt, {}))
418419

419420

420-
ROUTES = [
421-
('status', status_endpoint),
422-
('details', details_endpoint),
423-
('reverse', reverse_endpoint),
424-
('lookup', lookup_endpoint),
425-
('search', search_endpoint),
426-
('deletable', deletable_endpoint),
427-
('polygons', polygons_endpoint),
428-
]
421+
async def get_routes(api: NominatimAPIAsync) -> Sequence[Tuple[str, EndpointFunc]]:
422+
routes = [
423+
('status', status_endpoint),
424+
('details', details_endpoint),
425+
('reverse', reverse_endpoint),
426+
('lookup', lookup_endpoint),
427+
('deletable', deletable_endpoint),
428+
('polygons', polygons_endpoint),
429+
]
430+
431+
def has_search_name(conn: sa.engine.Connection) -> bool:
432+
insp = sa.inspect(conn)
433+
return insp.has_table('search_name')
434+
435+
try:
436+
async with api.begin() as conn:
437+
if await conn.connection.run_sync(has_search_name):
438+
routes.append(('search', search_endpoint))
439+
except (PGCORE_ERROR, sa.exc.OperationalError):
440+
pass # ignored
441+
442+
return routes

0 commit comments

Comments
 (0)