-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathplugin.py
More file actions
412 lines (351 loc) · 15.1 KB
/
plugin.py
File metadata and controls
412 lines (351 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
"""
OGC EDR router for datasets with CF convention metadata
"""
from typing import Annotated, List
import xarray as xr
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from shapely.errors import GEOSException
from xpublish import Dependencies, Plugin, hookimpl
from xpublish_edr.format import area_formats, cube_formats, position_formats
from xpublish_edr.formats.to_covjson import to_cf_covjson
from xpublish_edr.geometry.area import select_by_area
from xpublish_edr.geometry.bbox import select_by_bbox
from xpublish_edr.geometry.common import project_dataset
from xpublish_edr.geometry.position import select_by_position
from xpublish_edr.logger import logger
from xpublish_edr.metadata import collection_metadata
from xpublish_edr.query import EDRAreaQuery, EDRCubeQuery, EDRPositionQuery
class CfEdrPlugin(Plugin):
"""
OGC EDR compatible endpoints for Xpublish datasets
"""
name: str = "cf_edr"
app_router_prefix: str = "/edr"
app_router_tags: List[str] = ["edr"]
dataset_router_prefix: str = "/edr"
dataset_router_tags: List[str] = ["edr"]
@hookimpl
def app_router(self):
"""Register an application level router for EDR format info"""
router = APIRouter(prefix=self.app_router_prefix, tags=self.app_router_tags)
@router.get(
"/position/formats",
summary="Position query response formats",
)
def get_position_formats():
"""
Returns the various supported formats for position queries
"""
formats = {key: value.__doc__ for key, value in position_formats().items()}
return formats
@router.get(
"/area/formats",
summary="Area query response formats",
)
def get_area_formats():
"""
Returns the various supported formats for area queries
"""
formats = {key: value.__doc__ for key, value in area_formats().items()}
return formats
@router.get("/cube/formats", summary="Cube query response formats")
def get_cube_formats():
"""
Returns the various supported formats for cube queries
"""
formats = {key: value.__doc__ for key, value in cube_formats().items()}
return formats
return router
@hookimpl
def ogc_router(self, deps: Dependencies):
"""Register OGC routers at the application level"""
router = APIRouter(tags=["OGC EDR"])
@router.get(
"/collections/{collection_id}/position", summary="OGC EDR Position endpoint",
)
def get_position(
collection_id: str,
request: Request,
query: Annotated[EDRPositionQuery, Query()],
):
"""Stub for OGC EDR position endpoint"""
dataset = deps.dataset(collection_id)
try:
ds = query.select(dataset, dict(request.query_params))
except ValueError as e:
logger.error(
f"Error selecting from query while selecting by position: {e}",
)
raise HTTPException(
status_code=404,
detail=f"Error selecting from query: {e.args[0]}",
)
logger.debug(f"Dataset filtered by query params {ds}")
try:
ds = select_by_position(ds, query.project_geometry(ds), query.method)
except GEOSException as e:
logger.error(
f"Error parsing coordinates to geometry while selecting by position: {e}",
)
raise HTTPException(
status_code=422,
detail="Could not parse coordinates to geometry, "
+ "check the format of the 'coords' query parameter",
)
except KeyError as e:
logger.error(f"Error selecting by position: {e}")
raise HTTPException(
status_code=404,
detail="Dataset does not have CF Convention compliant metadata",
)
logger.debug(
f"Dataset filtered by position ({query.geometry}): {ds}",
)
try:
ds = project_dataset(ds, query.crs)
except Exception as e:
logger.error(
f"Error projecting dataset while selecting by position: {e}",
)
raise HTTPException(
status_code=404,
detail="Error projecting dataset",
)
logger.debug(f"Dataset projected to {query.crs}: {ds}")
if query.format:
try:
format_fn = position_formats()[query.format]
except KeyError as e:
logger.error(
f"Error getting format function while selecting by position: {e}",
)
raise HTTPException(
404,
f"{query.format} is not a valid format for EDR position queries. "
"Get `./position/formats` for valid formats",
)
return format_fn(ds)
return to_cf_covjson(ds)
return router
@hookimpl
def ogc_collection_dataqueries(self, collection_id: str, ds: xr.Dataset):
"""Register data queries for OGC collection metadata"""
return {
"position": {
"link": {
"href": f"/collections/{collection_id}/position",
"variables": {},
"rel": "alternate",
"type": "application/geo+json",
"hreflang": "en",
"title": "OGC EDR Position Query Endpoint",
"length": 0,
"templated": True,
},
},
}
@hookimpl
def dataset_router(self, deps: Dependencies):
"""Register dataset level router for EDR endpoints"""
router = APIRouter(prefix=self.app_router_prefix, tags=self.dataset_router_tags)
@router.get("/", summary="Collection metadata")
def get_collection_metadata(dataset: xr.Dataset = Depends(deps.dataset)):
"""
Returns the collection metadata for the dataset
There is no nested hierarchy in our router right now, so instead we return the metadata
for the current dataset as the a single collection. See the spec for more information:
https://docs.ogc.org/is/19-086r6/19-086r6.html#_162817c2-ccd7-43c9-b1ea-ad3aea1b4d6b
"""
position_output_formats = list(position_formats().keys())
area_output_formats = list(area_formats().keys())
cube_output_formats = list(cube_formats().keys())
return collection_metadata(
dataset,
position_output_formats,
area_output_formats,
cube_output_formats,
).dict(
exclude_none=True,
)
@router.get("/position", summary="Position query")
def get_position(
request: Request,
query: Annotated[EDRPositionQuery, Query()],
dataset: xr.Dataset = Depends(deps.dataset),
):
"""
Returns vectorized position data based on WKT `Point(lon lat)` coordinates
Extra selecting/slicing parameters can be provided as extra query parameters
"""
try:
ds = query.select(dataset, dict(request.query_params))
except ValueError as e:
logger.error(
f"Error selecting from query while selecting by position: {e}",
)
raise HTTPException(
status_code=404,
detail=f"Error selecting from query: {e.args[0]}",
)
logger.debug(f"Dataset filtered by query params {ds}")
try:
ds = select_by_position(ds, query.project_geometry(ds), query.method)
except GEOSException as e:
logger.error(
f"Error parsing coordinates to geometry while selecting by position: {e}",
)
raise HTTPException(
status_code=422,
detail="Could not parse coordinates to geometry, "
+ "check the format of the 'coords' query parameter",
)
except KeyError as e:
logger.error(f"Error selecting by position: {e}")
raise HTTPException(
status_code=404,
detail="Dataset does not have CF Convention compliant metadata",
)
logger.debug(
f"Dataset filtered by position ({query.geometry}): {ds}",
)
try:
ds = project_dataset(ds, query.crs)
except Exception as e:
logger.error(
f"Error projecting dataset while selecting by position: {e}",
)
raise HTTPException(
status_code=404,
detail="Error projecting dataset",
)
logger.debug(f"Dataset projected to {query.crs}: {ds}")
if query.format:
try:
format_fn = position_formats()[query.format]
except KeyError as e:
logger.error(
f"Error getting format function while selecting by position: {e}",
)
raise HTTPException(
404,
f"{query.format} is not a valid format for EDR position queries. "
"Get `./position/formats` for valid formats",
)
return format_fn(ds)
return to_cf_covjson(ds)
@router.get("/area", summary="Area query")
def get_area(
request: Request,
query: Annotated[EDRAreaQuery, Query()],
dataset: xr.Dataset = Depends(deps.dataset),
):
"""
Returns vectorized area data based on WKT `Polygon(lon lat)` coordinates
Extra selecting/slicing parameters can be provided as extra query parameters
"""
try:
ds = query.select(dataset, dict(request.query_params))
except ValueError as e:
logger.error(f"Error selecting from query while selecting by area: {e}")
raise HTTPException(
status_code=404,
detail=f"Error selecting from query: {e.args[0]}",
)
logger.debug(f"Dataset filtered by query params {ds}")
try:
ds = select_by_area(ds, query.project_geometry(ds))
except GEOSException as e:
logger.error(
f"Error parsing coordinates to geometry while selecting by area: {e}",
)
raise HTTPException(
status_code=422,
detail="Could not parse coordinates to geometry, "
+ "check the format of the 'coords' query parameter",
)
except KeyError as e:
logger.error(f"Error selecting by area: {e}")
raise HTTPException(
status_code=404,
detail="Dataset does not have CF Convention compliant metadata",
)
logger.debug(f"Dataset filtered by polygon {query.geometry.boundary}: {ds}")
try:
ds = project_dataset(ds, query.crs)
except Exception as e:
logger.error(f"Error projecting dataset while selecting by area: {e}")
raise HTTPException(
status_code=404,
detail="Error projecting dataset",
)
logger.debug(f"Dataset projected to {query.crs}: {ds}")
if query.format:
try:
format_fn = area_formats()[query.format]
except KeyError as e:
logger.error(f"Error getting format function: {e}")
raise HTTPException(
404,
f"{query.format} is not a valid format for EDR area queries. "
"Get `./area/formats` for valid formats",
)
return format_fn(ds)
return to_cf_covjson(ds)
@router.get("/cube", summary="Cube query")
def get_cube(
request: Request,
query: Annotated[EDRCubeQuery, Query()],
dataset: xr.Dataset = Depends(deps.dataset),
):
"""
Returns gridded cube data based on bbox coordinates and optional elevation
Extra selecting/slicing parameters can be provided as extra query parameters
"""
try:
ds = query.select(dataset, dict(request.query_params))
except ValueError as e:
logger.error(f"Error selecting from query while selecting by cube: {e}")
raise HTTPException(
status_code=404,
detail=f"Error selecting from query: {e.args[0]}",
)
logger.debug(f"Dataset filtered by query params {ds}")
try:
ds = select_by_bbox(ds, query.project_bbox(ds))
except KeyError as e:
logger.error(f"Error selecting by bbox: {e}")
raise HTTPException(
status_code=404,
detail="Dataset does not have CF Convention compliant metadata",
)
except ValueError as e:
logger.error(f"Error selecting by bbox: {e}")
raise HTTPException(
status_code=404,
detail="Error selecting by bbox, see logs for more details",
)
logger.debug(
f"Dataset filtered by bbox ({query.bbox}): {ds}",
)
try:
ds = project_dataset(ds, query.crs)
except Exception as e:
logger.error(f"Error projecting dataset while selecting by area: {e}")
raise HTTPException(
status_code=404,
detail="Error projecting dataset",
)
logger.debug(f"Dataset projected to {query.crs}: {ds}")
if query.format:
try:
format_fn = cube_formats()[query.format]
except KeyError as e:
logger.error(f"Error getting format function: {e}")
raise HTTPException(
404,
f"{query.format} is not a valid format for EDR cube queries. "
"Get `./cube/formats` for valid formats",
)
return format_fn(ds)
return to_cf_covjson(ds)
return router