-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmetadata.py
More file actions
392 lines (325 loc) · 12.2 KB
/
metadata.py
File metadata and controls
392 lines (325 loc) · 12.2 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
import collections.abc
from datetime import datetime
from typing import List, Optional, Union
from app.models.listeners import (
EventListenerIn,
EventListenerOut,
LegacyEventListenerIn,
)
from app.models.mongomodel import MongoDBRef
from app.models.users import UserOut
from app.search.connect import insert_record, update_record
from beanie import Document, PydanticObjectId, View
from elasticsearch import Elasticsearch, NotFoundError
from fastapi import HTTPException
from pydantic import AnyUrl, BaseModel, Field, validator
# List of valid types that can be specified for metadata fields
FIELD_TYPES = {
"int": int,
"float": float,
"str": str,
"string": str,
"TextField": str,
"bool": bool,
# TODO figure out how to parse "yyyymmdd hh:mm:ssssssz" into datetime object
# "date": datetime.date,
# "time": datetime.time,
"date": str,
"time": str,
"dict": dict, # TODO: does this work?
"enum": str, # TODO: need a way to validate enum,
"tuple": tuple,
} # JSON schema can handle this for us?
class MetadataRequiredForItems(BaseModel):
datasets: bool = False
files: bool = False
class MetadataConfig(BaseModel):
type: str = "str" # must be one of FIELD_TYPES
class MetadataEnumConfig(BaseModel):
type: str = "enum"
options: List[str] # a list of options must be provided if type is enum
class MetadataField(BaseModel):
name: str
list: bool = False # whether a list[type] is acceptable
widgetType: str = "TextField" # match material ui widget name?
config: Union[MetadataEnumConfig, MetadataConfig]
# TODO: Eventually move this to space level?
required: bool = False # Whether the definition requires this field
class MetadataDefinitionBase(BaseModel):
"""This describes a metadata object with a short name and description, predefined set of fields, and context.
These provide a shorthand for use by listeners as well as a source for building GUI widgets to add new entries.
Example: {
"name" : "LatLon",
"description" : "A set of Latitude/Longitude coordinates",
"required_for_items": {
"datasets": false,
"files": false
},
"context" : [
{
"longitude" : "https://schema.org/longitude",
"latitude" : "https://schema.org/latitude"
},
],
"fields" : [
{
"name" : "longitude",
"list" : false,
"widgetType": "TextField",
"config": {
"type" : "float"
},
"required" : true
},
{
"name" : "latitude",
"list" : false,
"widgetType": "TextField",
"config": {
"type" : "float"
},
"required" : true
}
]
}"""
name: str
description: Optional[str]
required_for_items: MetadataRequiredForItems
created: datetime = Field(default_factory=datetime.utcnow)
context: Optional[
List[Union[dict, AnyUrl]]
] # https://json-ld.org/spec/latest/json-ld/#the-context
context_url: Optional[str] # single URL applying to contents
fields: List[MetadataField]
modified: datetime = Field(default_factory=datetime.utcnow)
# TODO: Space-level requirements?
class Settings:
name = "metadata_definitions"
class Config:
# Serialization Config Options
# Specify JSON key names
# This will rename the field `context` to `@context` in the JSON output
fields = {"context": {"alias": "@context"}}
# This will allow input by field name 'context' too along with '@context'
allow_population_by_field_name = True
class MetadataDefinitionIn(MetadataDefinitionBase):
pass
class MetadataDefinitionDB(Document, MetadataDefinitionBase):
creator: UserOut
class Settings:
name = "metadata.definitions"
class MetadataDefinitionOut(MetadataDefinitionDB):
class Config:
fields = {"id": "id"}
def validate_definition(content: dict, metadata_def: MetadataDefinitionOut):
"""Convenience function for checking if a value matches MetadataDefinition criteria"""
# Reject if there are any extraneous fields
for entry in content:
found = False
for field in metadata_def.fields:
if field.name == entry:
found = True
break
if not found:
raise HTTPException(
status_code=400,
detail=f"{metadata_def.name} field does not have a field called {entry}",
)
# For all fields in definition, are they present and matching format?
for field in metadata_def.fields:
if field.name in content:
value = content[field.name]
t = FIELD_TYPES[field.config.type]
try:
# Try casting value as required type, raise exception if unable
content[field.name] = t(content[field.name])
except ValueError:
if field.list and type(value) is list:
typecast_list = []
try:
for v in value:
typecast_list.append(t(v))
content[field.name] = typecast_list
except HTTPException:
raise HTTPException(
status_code=400,
detail=f"{metadata_def.name} field {field.name} requires {field.config.type} for all values in list",
)
raise HTTPException(
status_code=400,
detail=f"{metadata_def.name} field {field.name} requires {field.config.type}",
)
elif field.required:
raise HTTPException(
status_code=400,
detail=f"{metadata_def.name} requires field {field.name}",
)
# Return original dict with any type castings applied
return content
class MetadataAgent(BaseModel):
"""Describes the user who created a piece of metadata. If listener is provided, user refers to the user who
triggered the job."""
creator: UserOut
listener: Optional[EventListenerOut]
class MetadataBase(BaseModel):
context: Optional[
List[Union[dict, AnyUrl]]
] # https://json-ld.org/spec/latest/json-ld/#the-context
context_url: Optional[str] # single URL applying to contents
definition: Optional[str] # name of a metadata definition
content: dict
description: Optional[
str
] # This will be fetched from metadata definition if one is provided (shown by GUI)
class Config:
# Serialization Config Options
# Specify JSON key names
# This will rename the field `context` to `@context` in the JSON output
fields = {"context": {"alias": "@context"}}
# This will allow input by field name 'context' too along with '@context'
allow_population_by_field_name = True
@validator("context")
def contexts_are_valid(cls, v):
if False:
raise ValueError("Problem with context.")
return v
@validator("context_url")
def context_url_is_valid(cls, v):
if False:
raise ValueError("Problem with context URL.")
return v
@validator("definition")
def definition_is_valid(cls, v):
# TODO: Possible to query MongoDB here with name? Currently done in routers
if False:
raise ValueError("Problem with definition.")
return v
class Settings:
name = "metadata"
class MetadataIn(MetadataBase):
file_version: Optional[int]
listener: Optional[EventListenerIn]
extractor: Optional[LegacyEventListenerIn]
class MetadataPatch(MetadataIn):
metadata_id: Optional[str] # specific metadata ID we are patching
class MetadataDelete(BaseModel):
metadata_id: Optional[str] # specific metadata ID we are deleting
definition: Optional[str]
listener: Optional[EventListenerIn]
extractor: Optional[LegacyEventListenerIn]
class MetadataBaseCommon(MetadataBase):
resource: MongoDBRef
agent: MetadataAgent
created: datetime = Field(default_factory=datetime.utcnow)
origin_id: Optional[PydanticObjectId] = None
class MetadataDB(Document, MetadataBaseCommon):
class Settings:
name = "metadata"
class Config:
arbitrary_types_allowed = True
@validator("resource")
def resource_dbref_is_valid(cls, v):
if False:
raise ValueError("Problem with db reference.")
return v
class MetadataFreezeDB(Document, MetadataBaseCommon):
frozen: bool = True
class Settings:
name = "metadata_freeze"
@validator("resource")
def resource_dbref_is_valid(cls, v):
if False:
raise ValueError("Problem with db reference.")
return v
class MetadataOut(MetadataDB, MetadataFreezeDB):
class Config:
fields = {"id": "id"}
async def validate_context(
content: dict,
definition: Optional[str] = None,
context_url: Optional[str] = None,
context: Optional[List[Union[dict, AnyUrl]]] = None,
):
"""Convenience function for making sure incoming metadata has valid definitions or resolvable context.
Returns:
Metadata content with incoming values typecast to match expected data type of any definitions
"""
if context is None and context_url is None and definition is None:
raise HTTPException(
status_code=400,
detail="Context is required",
)
if context is not None:
# TODO validate context
return content
if context_url is not None:
# TODO validate context
return content
if definition is not None:
if (
md_def := await MetadataDefinitionDB.find_one(
MetadataDefinitionDB.name == definition
)
) is not None:
content = validate_definition(content, md_def)
else:
raise HTTPException(
status_code=400,
detail=f"{definition} is not valid metadata definition",
)
return content
def deep_update(orig: dict, new: dict):
"""Recursively update a nested dict with any proivded values."""
for k, v in new.items():
if isinstance(v, collections.abc.Mapping):
orig[k] = deep_update(orig.get(k, {}), v)
else:
orig[k] = v
return orig
async def patch_metadata(metadata: MetadataDB, new_entries: dict, es: Elasticsearch):
"""Convenience function for updating original metadata contents with new entries."""
try:
# TODO: For list-type definitions, should we append to list instead?
updated_content = deep_update(metadata.content, new_entries)
updated_content = await validate_context(
updated_content,
metadata.definition,
metadata.context_url,
metadata.context,
)
metadata.content = updated_content
await metadata.replace()
doc = {"doc": {"content": metadata.content}}
try:
update_record(es, "metadata", {"doc": doc}, metadata.id)
except NotFoundError:
insert_record(es, "metadata", doc, metadata.id)
except Exception as e:
raise e
return MetadataOut(**metadata.dict())
class MetadataDBViewList(View, MetadataBaseCommon):
id: PydanticObjectId = Field(None, alias="_id") # necessary for Views
# for dataset versioning
origin_id: PydanticObjectId
frozen: bool = False
class Settings:
source = MetadataDB
name = "metadata_view"
pipeline = [
{
"$addFields": {
"frozen": False,
"origin_id": "$_id",
}
},
{
"$unionWith": {
"coll": "metadata_freeze",
"pipeline": [{"$addFields": {"frozen": True}}],
}
},
]
# Needs fix to work https://github.com/roman-right/beanie/pull/521
# use_cache = True
# cache_expiration_time = timedelta(seconds=10)
# cache_capacity = 5