-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapplication.py
More file actions
290 lines (243 loc) · 9.56 KB
/
application.py
File metadata and controls
290 lines (243 loc) · 9.56 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
import json
import os
from typing import Optional
import dateparser
import asf_search as asf
from fastapi import Depends, FastAPI, Request, HTTPException, APIRouter, UploadFile
from fastapi.responses import Response, JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from .log_router import LoggingRoute
from .logger import api_logger
from .asf_env import load_config_maturity
from .asf_opts import process_baseline_request, process_search_request, process_wkt_request
from .health import get_cmr_health
from .models import BaselineSearchOptsModel, SearchOptsModel
from .output import as_output, get_asf_search_script, make_filename
from .files_to_wkt import FilesToWKT
from . import constants
from .search import stack_aria_gunw
import time
asf.REPORT_ERRORS = False
router = APIRouter(route_class=LoggingRoute)
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@router.api_route("/services/search/param", methods=["GET", "POST", "HEAD"])
async def query_params(searchOptions: SearchOptsModel = Depends(process_search_request)):
# TODO: Now that we don't have to use streaming responses, this count
# block could probably be moved to 'as_output', especially
# since it's a switch statement now.
output = searchOptions.output
opts = searchOptions.opts
non_search_param = ['output', 'maxresults', 'pagesize', 'maturity']
try:
any_searchables = any([key.lower() not in non_search_param for key, _ in opts])
if not any_searchables:
raise ValueError(
'No searchable parameters specified, queries must include'
' parameters besides output= and maxresults='
)
except ValueError as exc:
raise HTTPException(detail=repr(exc), status_code=400) from exc
if output.lower() == 'count':
count=asf.search_count(opts=opts)
return Response(
content=str(count),
status_code=200,
media_type='text/html; charset=utf-8',
headers=constants.DEFAULT_HEADERS
)
if output.lower() == 'python':
file_name, search_script = get_asf_search_script(opts)
return Response(
content=search_script,
status_code=200,
media_type='text/x-python',
headers= {
**constants.DEFAULT_HEADERS,
'Content-Disposition': f"attachment; filename={file_name}",
}
)
try:
results = asf.search(opts=opts)
response_info = as_output(results, output)
return Response(**response_info)
except (asf.ASFSearchError, asf.CMRError, ValueError) as exc:
raise HTTPException(
detail=f"Search failed to find results: {exc}",
status_code=400
) from exc
@router.api_route("/services/search/baseline", methods=["GET", "POST", "HEAD"])
async def query_baseline(searchOptions: BaselineSearchOptsModel = Depends(process_baseline_request)):
opts = searchOptions.opts
opts.maxResults = None
output = searchOptions.output
reference = searchOptions.reference
request_method = searchOptions.request_method
if searchOptions.opts.dataset is not None:
if searchOptions.opts.dataset[0] == asf.DATASET.ARIA_S1_GUNW:
return JSONResponse(
content=stack_aria_gunw(reference),
status_code=200,
headers= {
**constants.DEFAULT_HEADERS,
'Content-Disposition': f"attachment; filename={make_filename('json')}",
}
)
# Load the reference scene:
if output.lower() == 'python':
file_name, search_script = get_asf_search_script(opts, reference=reference, search_endpoint='baseline')
return Response(
content=search_script,
status_code=200,
media_type='text/x-python',
headers= {
**constants.DEFAULT_HEADERS,
'Content-Disposition': f"attachment; filename={file_name}",
}
)
try:
reference_product = asf.granule_search(granule_list=[reference], opts=opts)[0]
except (KeyError, IndexError, ValueError) as exc:
raise HTTPException(detail=f"Reference scene not found: {reference}", status_code=400) from exc
try:
if reference_product.get_stack_opts() is None:
reference_product = asf.ASFStackableProduct(args={'umm': reference_product.umm, 'meta': reference_product.meta}, session=reference_product.session)
if not reference_product.has_baseline() or not reference_product.is_valid_reference():
raise asf.exceptions.ASFBaselineError(f"Requested reference scene has no baseline")
except (asf.exceptions.ASFBaselineError, ValueError) as exc:
raise HTTPException(detail=f"Search failed to find results: {exc}", status_code=400)
if request_method == "HEAD":
# Need head request separately, so it doesn't do all
# the work to figure out the body
if output.lower() == 'count':
return Response(
status_code=200,
media_type='text/html; charset=utf-8',
headers=constants.DEFAULT_HEADERS
)
metadata = as_output(asf.ASFSearchResults([]), output)
return Response(
status_code=200,
headers=metadata["headers"],
media_type=metadata["media_type"]
)
# Figure out the response params:
if output.lower() == 'count':
stack_opts = reference_product.get_stack_opts()
count = asf.search_count(opts=stack_opts)
return Response(
content=str(count),
status_code=200,
media_type='text/html; charset=utf-8',
headers=constants.DEFAULT_HEADERS
)
# Finally stream everything back:
try:
stack = reference_product.stack(opts=opts)
response_info = as_output(stack, output)
return Response(**response_info)
except (asf.ASFSearchError, asf.CMRError, ValueError) as exc:
raise HTTPException(detail=f"Search failed to find results: {exc}", status_code=400) from exc
@router.get('/services/utils/date', response_class=JSONResponse)
async def query_date_validation(date: str):
parsed_date = dateparser.parse(date)
if parsed_date is None:
raise HTTPException(detail=f"Could not parse date: {date}", status_code=400)
response = {
'date': {
'original': date,
'parsed': parsed_date.strftime("%Y-%m-%dT%H:%M:%SZ"),
}
}
return JSONResponse(
content=response,
status_code=200,
headers=constants.DEFAULT_HEADERS
)
@router.get('/services/utils/mission_list', response_class=JSONResponse)
async def query_mission_list(platform: str | None = None):
if platform is not None:
platform = platform.upper()
response = {'result': asf.campaigns(platform)}
return JSONResponse(
content=response,
status_code=200,
headers=constants.DEFAULT_HEADERS
)
@router.api_route("/services/utils/wkt", methods=["GET", "POST"])
async def wkt_validation(wkt: str = Depends(process_wkt_request)):
return Response(
content=json.dumps(validate_wkt(wkt)),
status_code=200,
media_type='application/json; charset=utf-8',
headers=constants.DEFAULT_HEADERS
)
@router.post('/services/utils/files_to_wkt')
async def file_to_wkt(files: list[UploadFile]):
for file in files:
file.file.filename = file.filename
data = FilesToWKT([file.file for file in files]).getWKT()
return JSONResponse(content={
** data,
** validate_wkt(data["parsed wkt"])},
status_code=200,
headers=constants.DEFAULT_HEADERS
)
def validate_wkt(wkt: str):
try:
wrapped, unwrapped, reports = asf.validate_wkt(wkt)
repairs = [{'type': report.report_type, 'report': report.report} for report in reports if report.report_type != "'type': 'WRAP'"]
except Exception as exc:
raise HTTPException(detail=f"Failed to validate wkt {wkt}: {exc}", status_code=400) from exc
return {
'wkt': {
'unwrapped': unwrapped.wkt,
'wrapped': wrapped.wkt
},
'repairs': repairs
}
@router.get('/', response_class=JSONResponse)
@router.get('/health', response_class=JSONResponse)
async def health_check():
try:
version_path = os.path.join("SearchAPI", "version.json")
with open(version_path, 'r', encoding="utf-8") as version_file:
api_version = json.load(version_file)
except Exception as exc:
api_logger.info(exc)
api_version = {'version': 'unknown'}
cfg = load_config_maturity()
cmr_health = get_cmr_health(cfg['cmr_base'], cfg['cmr_health'])
api_health = {
'ASFSearchAPI': {
'ok?': True,
'version': api_version['version'],
'config': load_config_maturity()
},
'CMRSearchAPI': cmr_health
}
return JSONResponse(
content=api_health,
status_code=200,
headers=constants.DEFAULT_HEADERS
)
@app.exception_handler(HTTPException)
async def handle_error(request: Request, error: HTTPException):
response = {
"error": {
"type": "ERROR",
"report": error.detail,
}
}
return JSONResponse(
content=response,
status_code=error.status_code,
headers=constants.DEFAULT_HEADERS
)
app.include_router(router)