/
abstract.py
1903 lines (1581 loc) · 70 KB
/
abstract.py
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This file is part of the Open Data Cube, see https://opendatacube.org for more information
#
# Copyright (c) 2015-2024 ODC Contributors
# SPDX-License-Identifier: Apache-2.0
import datetime
import logging
import sys
from pathlib import Path
from threading import Lock
from time import monotonic
from abc import ABC, abstractmethod
from typing import (Any, Iterable, Iterator,
List, Mapping, MutableMapping,
NamedTuple, Optional,
Tuple, Union, Sequence)
from uuid import UUID
from datetime import timedelta
from datacube.config import LocalConfig
from datacube.index.exceptions import TransactionException
from datacube.index.fields import Field
from datacube.model import Dataset, MetadataType, Range
from datacube.model import Product
from datacube.utils import cached_property, jsonify_document, read_documents, InvalidDocException
from datacube.utils.changes import AllowPolicy, Change, Offset, DocumentMismatchError, check_doc_unchanged
from datacube.utils.generic import thread_local_cache
from datacube.utils.geometry import CRS, Geometry, box
from datacube.utils.documents import UnknownMetadataType
_LOG = logging.getLogger(__name__)
# A named tuple representing the results of a batch add operation:
# - completed: Number of objects added to theMay be None for internal functions and for datasets.
# - skipped: Number of objects skipped, either because they already exist
# or the documents are invalid for this driver.
# - seconds_elapsed: seconds elapsed during the bulk add operation;
# - safe: an optional list of names of bulk added objects that are safe to be
# used for lower level bulk adds. Includes objects added, and objects skipped
# because they already exist in the index and are identical to the version
# being added. May be None for internal functions and for datasets.
class BatchStatus(NamedTuple):
completed: int
skipped: int
seconds_elapsed: float
safe: Optional[Iterable[str]] = None
class AbstractUserResource(ABC):
"""
Abstract base class for the User portion of an index api.
All UserResource implementations should inherit from this base
class and implement all abstract methods.
(If a particular abstract method is not applicable for a particular implementation
raise a NotImplementedError)
"""
@abstractmethod
def grant_role(self, role: str, *usernames: str) -> None:
"""
Grant a role to users
:param role: name of the database role
:param usernames: usernames to grant the role to.
"""
@abstractmethod
def create_user(self,
username: str,
password: str,
role: str,
description: Optional[str] = None) -> None:
"""
Create a new user
:param username: username of the new user
:param password: password of the new user
:param role: default role of the the new user
:param description: optional description for the new user
"""
@abstractmethod
def delete_user(self,
*usernames: str
) -> None:
"""
Delete database users
:param usernames: usernames of users to be deleted
"""
@abstractmethod
def list_users(self) -> Iterable[Tuple[str, str, Optional[str]]]:
"""
List all database users
:return: Iterable of (role, username, description) tuples
"""
_DEFAULT_METADATA_TYPES_PATH = Path(__file__).parent.joinpath('default-metadata-types.yaml')
def default_metadata_type_docs(path=_DEFAULT_METADATA_TYPES_PATH) -> List[MetadataType]:
"""A list of the bare dictionary format of default :class:`datacube.model.MetadataType`"""
return [doc for (path, doc) in read_documents(path)]
class AbstractMetadataTypeResource(ABC):
"""
Abstract base class for the MetadataType portion of an index api.
All MetadataTypeResource implementations should inherit from this base
class and implement all abstract methods.
(If a particular abstract method is not applicable for a particular implementation
raise a NotImplementedError)
"""
@abstractmethod
def from_doc(self, definition: Mapping[str, Any]) -> MetadataType:
"""
Construct a MetadataType object from a dictionary definition
:param definition: A metadata definition dictionary
:return: An unpersisted MetadataType object
"""
@abstractmethod
def add(self,
metadata_type: MetadataType,
allow_table_lock: bool = False
) -> MetadataType:
"""
Add a metadata type to the index.
:param metadata_type: Unpersisted Metadatatype model
:param allow_table_lock:
Allow an exclusive lock to be taken on the table while creating the indexes.
This will halt other user's requests until completed.
If false, creation will be slightly slower and cannot be done in a transaction.
raise NotImplementedError if set to True, and this behaviour is not applicable
for the implementing driver.
:return: Persisted Metadatatype model.
"""
def _add_batch(self, batch_types: Iterable[MetadataType]) -> BatchStatus:
"""
Add a single "batch" of mdts.
Default implementation is simple loop of add
API Note: This API method is not finalised and may be subject to change.
:param batch_types: An iterable of one batch's worth of MetadataType objects to add
:return: BatchStatus named tuple.
"""
b_skipped = 0
b_added = 0
b_started = monotonic()
b_loaded = set()
for mdt in batch_types:
try:
self.add(mdt)
b_added += 1
b_loaded.add(mdt.name)
except DocumentMismatchError as e:
_LOG.warning("%s: Skipping", str(e))
b_skipped += 1
except Exception as e:
_LOG.warning("%s: Skipping", str(e))
b_skipped += 1
return BatchStatus(b_added, b_skipped, monotonic() - b_started, b_loaded)
def bulk_add(self,
metadata_docs: Iterable[Mapping[str, Any]],
batch_size: int = 1000) -> BatchStatus:
"""
Add a group of Metadata Type documents in bulk.
API Note: This API method is not finalised and may be subject to change.
:param metadata_docs: An iterable of metadata type metadata docs.
:param batch_size: Number of metadata types to add per batch (default 1000)
:return: BatchStatus named tuple, with `safe` containing a list of
metadata type names that are safe to include in a subsequent product bulk add.
"""
n_in_batch = 0
added = 0
skipped = 0
started = monotonic()
batch = []
existing = {mdt.name: mdt for mdt in self.get_all()}
batched = set()
safe = set()
for doc in metadata_docs:
try:
mdt = self.from_doc(doc)
if mdt.name in existing:
check_doc_unchanged(
existing[mdt.name].definition,
jsonify_document(mdt.definition),
'Metadata Type {}'.format(mdt.name)
)
_LOG.warning("%s: Skipped - already exists", mdt.name)
skipped += 1
safe.add(mdt.name)
else:
batch.append(mdt)
batched.add(mdt.name)
n_in_batch += 1
except DocumentMismatchError as e:
_LOG.warning("%s: Skipped", str(e))
skipped += 1
except InvalidDocException as e:
_LOG.warning("%s: Skipped", str(e))
skipped += 1
if n_in_batch >= batch_size:
batch_results = self._add_batch(batch)
batch = []
added += batch_results.completed
skipped += batch_results.skipped
if batch_results.safe is None:
safe.update(batched)
else:
safe.update(batch_results.safe)
batched = set()
n_in_batch = 0
if n_in_batch > 0:
batch_results = self._add_batch(batch)
added += batch_results.completed
skipped += batch_results.skipped
if batch_results.safe is None:
safe.update(batched)
else:
safe.update(batch_results.safe)
return BatchStatus(added, skipped, monotonic() - started, safe)
@abstractmethod
def can_update(self,
metadata_type: MetadataType,
allow_unsafe_updates: bool = False
) -> Tuple[bool, Iterable[Change], Iterable[Change]]:
"""
Check if metadata type can be updated. Return bool,safe_changes,unsafe_changes
Safe updates currently allow new search fields to be added, description to be changed.
:param metadata_type: updated MetadataType
:param allow_unsafe_updates: Allow unsafe changes. Use with caution.
:return: Tuple of: boolean (can/can't update); safe changes; unsafe changes
"""
@abstractmethod
def update(self,
metadata_type: MetadataType,
allow_unsafe_updates: bool = False,
allow_table_lock: bool = False
) -> MetadataType:
"""
Update a metadata type from the document. Unsafe changes will throw a ValueError by default.
Safe updates currently allow new search fields to be added, description to be changed.
:param metadata_type: MetadataType model with unpersisted updates
:param allow_unsafe_updates: Allow unsafe changes. Use with caution.
:param allow_table_lock:
Allow an exclusive lock to be taken on the table while creating the indexes.
This will halt other user's requests until completed.
If false, creation will be slower and cannot be done in a transaction.
:return: Persisted updated MetadataType model
"""
def update_document(self,
definition: Mapping[str, Any],
allow_unsafe_updates: bool = False,
) -> MetadataType:
"""
Update a metadata type from the document. Unsafe changes will throw a ValueError by default.
Safe updates currently allow new search fields to be added, description to be changed.
:param definition: Updated definition
:param allow_unsafe_updates: Allow unsafe changes. Use with caution.
:return: Persisted updated MetadataType model
"""
return self.update(self.from_doc(definition), allow_unsafe_updates=allow_unsafe_updates)
def get(self, id_: int) -> Optional[MetadataType]:
"""
Fetch metadata type by id.
:return: MetadataType model or None if not found
"""
try:
return self.get_unsafe(id_)
except KeyError:
return None
def get_by_name(self, name: str) -> Optional[MetadataType]:
"""
Fetch metadata type by name.
:return: MetadataType model or None if not found
"""
try:
return self.get_by_name_unsafe(name)
except KeyError:
return None
@abstractmethod
def get_unsafe(self, id_: int) -> MetadataType:
"""
Fetch metadata type by id
:param id_:
:return: metadata type model
:raises KeyError: if not found
"""
@abstractmethod
def get_by_name_unsafe(self, name: str) -> MetadataType:
"""
Fetch metadata type by name
:param name:
:return: metadata type model
:raises KeyError: if not found
"""
@abstractmethod
def check_field_indexes(self,
allow_table_lock: bool = False,
rebuild_views: bool = False,
rebuild_indexes: bool = False
) -> None:
"""
Create or replace per-field indexes and views.
May have no effect if not relevant for this index implementation
:param allow_table_lock:
Allow an exclusive lock to be taken on the table while creating the indexes.
This will halt other user's requests until completed.
If false, creation will be slightly slower and cannot be done in a transaction.
:param: rebuild_views: whether or not views should be rebuilt
:param: rebuild_indexes: whether or not views should be rebuilt
"""
@abstractmethod
def get_all(self) -> Iterable[MetadataType]:
"""
Retrieve all Metadata Types
:returns: All available MetadataType models
"""
def get_all_docs(self) -> Iterable[Mapping[str, Any]]:
"""
Retrieve all Metadata Types as documents only (e.g. for an index clone)
Default implementation calls self.get_all()
API Note: This API method is not finalised and may be subject to change.
:returns: All available MetadataType definition documents
"""
# Default implementation calls get_all()
for mdt in self.get_all():
yield mdt.definition
QueryField = Union[str, float, int, Range, datetime.datetime]
QueryDict = Mapping[str, QueryField]
class AbstractProductResource(ABC):
"""
Abstract base class for the Product portion of an index api.
All ProductResource implementations should inherit from this base
class and implement all abstract methods.
(If a particular abstract method is not applicable for a particular implementation
raise a NotImplementedError)
"""
metadata_type_resource: AbstractMetadataTypeResource
def from_doc(self, definition: Mapping[str, Any],
metadata_type_cache: Optional[MutableMapping[str, MetadataType]] = None) -> Product:
"""
Construct unpersisted Product model from product metadata dictionary
:param definition: a Product metadata dictionary
:param metadata_type_cache: a dict cache of MetaDataTypes to use in constructing a Product.
MetaDataTypes may come from a different index.
:return: Unpersisted product model
"""
# This column duplication is getting out of hand:
Product.validate(definition) # type: ignore[attr-defined] # validate method added by decorator
# Validate extra dimension metadata
Product.validate_extra_dims(definition)
metadata_type = definition['metadata_type']
# They either specified the name of a metadata type, or specified a metadata type.
# Is it a name?
if isinstance(metadata_type, str):
if metadata_type_cache is not None and metadata_type in metadata_type_cache:
metadata_type = metadata_type_cache[metadata_type]
else:
metadata_type = self.metadata_type_resource.get_by_name(metadata_type)
if (metadata_type is not None
and metadata_type_cache is not None
and metadata_type.name not in metadata_type_cache):
metadata_type_cache[metadata_type.name] = metadata_type
else:
# Otherwise they embedded a document, add it if needed:
metadata_type = self.metadata_type_resource.from_doc(metadata_type)
definition = dict(definition)
definition['metadata_type'] = metadata_type.name
if not metadata_type:
raise UnknownMetadataType('Unknown metadata type: %r' % definition['metadata_type'])
return Product(metadata_type, definition)
@abstractmethod
def add(self,
product: Product,
allow_table_lock: bool = False
) -> Product:
"""
Add a product to the index.
:param metadata_type: Unpersisted Product model
:param allow_table_lock:
Allow an exclusive lock to be taken on the table while creating the indexes.
This will halt other user's requests until completed.
If false, creation will be slightly slower and cannot be done in a transaction.
raise NotImplementedError if set to True, and this behaviour is not applicable
for the implementing driver.
:return: Persisted Product model.
"""
def _add_batch(self, batch_products: Iterable[Product]) -> BatchStatus:
"""
Add a single "batch" of products.
Default implementation is simple loop of add
API Note: This API method is not finalised and may be subject to change.
:param batch_types: An iterable of one batch's worth of Product objects to add
:return: BatchStatus named tuple.
"""
b_skipped = 0
b_added = 0
b_started = monotonic()
for prod in batch_products:
try:
self.add(prod)
b_added += 1
except DocumentMismatchError as e:
_LOG.warning("%s: Skipping", str(e))
b_skipped += 1
except Exception as e:
_LOG.warning("%s: Skipping", str(e))
b_skipped += 1
return BatchStatus(b_added, b_skipped, monotonic()-b_started)
def bulk_add(self,
product_docs: Iterable[Mapping[str, Any]],
metadata_types: Optional[Mapping[str, MetadataType]] = None,
batch_size: int = 1000) -> BatchStatus:
"""
Add a group of product documents in bulk.
API Note: This API method is not finalised and may be subject to change.
:param product_docs: An iterable of product metadata docs.
:param batch_size: Number of products to add per batch (default 1000)
:param metadata_types: Optional dictionary cache of MetadataType objects.
Used for product metadata validation, and for filtering.
(Metadata types not in in this list are skipped.)
:return: BatchStatus named tuple, with `safe` containing a list of
product names that are safe to include in a subsequent dataset bulk add.
"""
n_in_batch = 0
added = 0
skipped = 0
batch = []
started = monotonic()
safe = set()
batched = set()
existing = {prod.name: prod for prod in self.get_all()}
for doc in product_docs:
if metadata_types is not None:
if doc["metadata_type"] not in metadata_types:
skipped += 1
continue
try:
prod = self.from_doc(doc, metadata_type_cache=metadata_types)
if prod.name in existing:
check_doc_unchanged(prod.definition, jsonify_document(doc), f"Product {prod.name}")
_LOG.warning("%s: skipped (already loaded)", prod.name)
skipped += 1
safe.add(prod.name)
else:
batch.append(prod)
n_in_batch += 1
batched.add(prod.name)
except UnknownMetadataType as e:
skipped += 1
except InvalidDocException as e:
_LOG.warning("%s: Skipped", str(e))
skipped += 1
if n_in_batch >= batch_size:
batch_results = self._add_batch(batch)
added += batch_results.completed
skipped += batch_results.skipped
if batch_results.safe is not None:
safe.update(batch_results.safe)
else:
safe.update(batched)
batched = set()
batch = []
n_in_batch = 0
if n_in_batch > 0:
batch_results = self._add_batch(batch)
added += batch_results.completed
skipped += batch_results.skipped
if batch_results.safe is not None:
safe.update(batch_results.safe)
else:
safe.update(batched)
return BatchStatus(added, skipped, monotonic() - started, safe)
@abstractmethod
def can_update(self,
product: Product,
allow_unsafe_updates: bool = False,
allow_table_lock: bool = False
) -> Tuple[bool, Iterable[Change], Iterable[Change]]:
"""
Check if product can be updated. Return bool,safe_changes,unsafe_changes
(An unsafe change is anything that may potentially make the product
incompatible with existing datasets of that type)
:param product: product to update
:param allow_unsafe_updates: Allow unsafe changes. Use with caution.
:param allow_table_lock:
Allow an exclusive lock to be taken on the table while creating the indexes.
This will halt other user's requests until completed.
If false, creation will be slower and cannot be done in a transaction.
:return: Tuple of: boolean (can/can't update); safe changes; unsafe changes
"""
@abstractmethod
def update(self,
metadata_type: Product,
allow_unsafe_updates: bool = False,
allow_table_lock: bool = False
) -> Product:
"""
Persist updates to a product. Unsafe changes will throw a ValueError by default.
(An unsafe change is anything that may potentially make the product
incompatible with existing datasets of that type)
:param metadata_type: Product model with unpersisted updates
:param allow_unsafe_updates: Allow unsafe changes. Use with caution.
:param allow_table_lock:
Allow an exclusive lock to be taken on the table while creating the indexes.
This will halt other user's requests until completed.
If false, creation will be slower and cannot be done in a transaction.
:return: Persisted updated Product model
"""
def update_document(self,
definition: Mapping[str, Any],
allow_unsafe_updates: bool = False,
allow_table_lock: bool = False
) -> Product:
"""
Update a metadata type from a document. Unsafe changes will throw a ValueError by default.
Safe updates currently allow new search fields to be added, description to be changed.
:param definition: Updated definition
:param allow_unsafe_updates: Allow unsafe changes. Use with caution.
:param allow_table_lock:
Allow an exclusive lock to be taken on the table while creating the indexes.
This will halt other user's requests until completed.
If false, creation will be slower and cannot be done in a transaction.
:return: Persisted updated Product model
"""
return self.update(self.from_doc(definition),
allow_unsafe_updates=allow_unsafe_updates,
allow_table_lock=allow_table_lock
)
def add_document(self, definition: Mapping[str, Any]) -> Product:
"""
Add a Product using its definition
:param dict definition: product definition document
:return: Persisted Product model
"""
type_ = self.from_doc(definition)
return self.add(type_)
def get(self, id_: int) -> Optional[Product]:
"""
Fetch product by id.
:param id_: Id of desired product
:return: Product model or None if not found
"""
try:
return self.get_unsafe(id_)
except KeyError:
return None
def get_by_name(self, name: str) -> Optional[Product]:
"""
Fetch product by name.
:param name: Name of desired product
:return: Product model or None if not found
"""
try:
return self.get_by_name_unsafe(name)
except KeyError:
return None
@abstractmethod
def get_unsafe(self, id_: int) -> Product:
"""
Fetch product by id
:param id_: id of desired product
:return: product model
:raises KeyError: if not found
"""
@abstractmethod
def get_by_name_unsafe(self, name: str) -> Product:
"""
Fetch product by name
:param name: name of desired product
:return: product model
:raises KeyError: if not found
"""
@abstractmethod
def get_with_fields(self, field_names: Iterable[str]) -> Iterable[Product]:
"""
Return products that have all of the given fields.
:param field_names: names of fields that returned products must have
:returns: Matching product models
"""
def search(self, **query: QueryField) -> Iterator[Product]:
"""
Return products that match the supplied query
:param query: Query parameters
:return: Generator of product models
"""
for type_, q in self.search_robust(**query):
if not q:
yield type_
@abstractmethod
def search_robust(self,
**query: QueryField
) -> Iterable[Tuple[Product, Mapping[str, QueryField]]]:
"""
Return dataset types that match match-able fields and dict of remaining un-matchable fields.
:param query: Query parameters
:return: Tuples of product model and a dict of remaining unmatchable fields
"""
@abstractmethod
def search_by_metadata(self,
metadata: Mapping[str, QueryField]
) -> Iterable[Dataset]:
"""
Perform a search using arbitrary metadata, returning results as Product objects.
Caution – slow! This will usually not use indexes.
:param metadata: metadata dictionary representing arbitrary search query
:return: Matching product models
"""
@abstractmethod
def get_all(self) -> Iterable[Product]:
"""
Retrieve all Products
:returns: Product models for all known products
"""
def get_all_docs(self) -> Iterable[Mapping[str, Any]]:
"""
Retrieve all Product metadata documents
Default implementation calls get_all()
API Note: This API method is not finalised and may be subject to change.
:returns: Iterable of metadata documents for all known products
"""
for prod in self.get_all():
yield prod.definition
# Non-strict Dataset ID representation
DSID = Union[str, UUID]
def dsid_to_uuid(dsid: DSID) -> UUID:
"""
Convert non-strict dataset ID representation to strict UUID
"""
if isinstance(dsid, UUID):
return dsid
else:
return UUID(dsid)
class DatasetTuple(NamedTuple):
"""
A named tuple representing a complete dataset:
- product: A Product model.
- metadata: The dataset metadata document
- uris: A list of locations (uris)
"""
product: Product
metadata: Mapping[str, Any]
uris: Sequence[str]
class AbstractDatasetResource(ABC):
"""
Abstract base class for the Dataset portion of an index api.
All DatasetResource implementations should inherit from this base
class and implement all abstract methods.
(If a particular abstract method is not applicable for a particular implementation
raise a NotImplementedError)
"""
def __init__(self, index):
self._index = index
self.products = self._index.products
self.types = self.products # types is compatibility alias for products
@abstractmethod
def get(self,
id_: DSID,
include_sources: bool = False
) -> Optional[Dataset]:
"""
Get dataset by id
:param id_: id of the dataset to retrieve
:param include_sources: get the full provenance graph?
:rtype: Dataset model (None if not found)
"""
@abstractmethod
def bulk_get(self, ids: Iterable[DSID]) -> Iterable[Dataset]:
"""
Get multiple datasets by id. (Lineage sources NOT included)
:param ids: ids to retrieve
:return: Iterable of Dataset models
"""
@abstractmethod
def get_derived(self, id_: DSID) -> Iterable[Dataset]:
"""
Get all datasets derived from a dataset (NOT recursive)
:param id_: dataset id
:rtype: list[Dataset]
"""
@abstractmethod
def has(self, id_: DSID) -> bool:
"""
Is this dataset in this index?
:param id_: dataset id
:return: True if the dataset exists in this index
"""
@abstractmethod
def bulk_has(self, ids_: Iterable[DSID]) -> Iterable[bool]:
"""
Like `has` but operates on a multiple ids.
For every supplied id check if database contains a dataset with that id.
:param ids_: iterable of dataset ids to check existence in index
:return: Iterable of bools, true for datasets that exist in index
"""
@abstractmethod
def add(self, dataset: Dataset,
with_lineage: bool = True,
archive_less_mature: Optional[int] = None,
) -> Dataset:
"""
Add ``dataset`` to the index. No-op if it is already present.
:param dataset: Unpersisted dataset model
:param with_lineage:
- ``True (default)`` attempt adding lineage datasets if missing
- ``False`` record lineage relations, but do not attempt
adding lineage datasets to the db
:param archive_less_mature: if integer, search for less
mature versions of the dataset with the int value as a millisecond
delta in timestamp comparison
:return: Persisted Dataset model
"""
@abstractmethod
def search_product_duplicates(self,
product: Product,
*args: Union[str, Field]
) -> Iterable[Tuple[Tuple, Iterable[UUID]]]:
"""
Find dataset ids who have duplicates of the given set of field names.
(Search is always restricted by Product)
Returns a generator returning a tuple containing a namedtuple of
the values of the supplied fields, and the datasets that match those
values.
:param product: The Product to restrict search to
:param args: field names to identify duplicates over
"""
@abstractmethod
def can_update(self,
dataset: Dataset,
updates_allowed: Optional[Mapping[Offset, AllowPolicy]] = None
) -> Tuple[bool, Iterable[Change], Iterable[Change]]:
"""
Check if dataset can be updated. Return bool,safe_changes,unsafe_changes
:param Dataset dataset: Dataset to update
:param updates_allowed: Allowed updates
:return: Tuple of: boolean (can/can't update); safe changes; unsafe changes
"""
@abstractmethod
def update(self,
dataset: Dataset,
updates_allowed: Optional[Mapping[Offset, AllowPolicy]] = None,
archive_less_mature: Optional[int] = None,
) -> Dataset:
"""
Update dataset metadata and location
:param Dataset dataset: Dataset model with unpersisted updates
:param updates_allowed: Allowed updates
:param archive_less_mature: Find and archive less mature datasets with ms delta
:return: Persisted dataset model
"""
@abstractmethod
def archive(self, ids: Iterable[DSID]) -> None:
"""
Mark datasets as archived
:param Iterable[Union[str,UUID]] ids: list of dataset ids to archive
"""
def archive_less_mature(self, ds: Dataset, delta: Union[int, bool] = 500) -> None:
"""
Archive less mature versions of a dataset
:param Dataset ds: dataset to search
:param Union[int,bool] delta: millisecond delta for time range.
If True, default to 500ms. If False, do not find or archive less mature datasets.
Bool value accepted only for improving backwards compatibility, int preferred.
"""
less_mature = self.find_less_mature(ds, delta)
less_mature_ids = map(lambda x: x.id, less_mature)
self.archive(less_mature_ids)
for lm_ds in less_mature_ids:
_LOG.info(f"Archived less mature dataset: {lm_ds}")
def find_less_mature(self, ds: Dataset, delta: Union[int, bool] = 500) -> Iterable[Dataset]:
"""
Find less mature versions of a dataset
:param Dataset ds: Dataset to search
:param Union[int,bool] delta: millisecond delta for time range.
If True, default to 500ms. If None or False, do not find or archive less mature datasets.
Bool value accepted only for improving backwards compatibility, int preferred.
:return: Iterable of less mature datasets
"""
if isinstance(delta, bool):
_LOG.warning("received delta as a boolean value. Int is prefered")
if delta is True: # treat True as default
delta = 500
else: # treat False the same as None
return []
elif isinstance(delta, int):
if delta < 0:
raise ValueError("timedelta must be a positive integer")
elif delta is None:
return []
else:
raise TypeError("timedelta must be None, a positive integer, or a boolean")
def check_maturity_information(dataset, props):
# check that the dataset metadata includes all maturity-related properties
# passing in the required props to enable greater extensibility should it be needed
for prop in props:
if hasattr(dataset.metadata, prop) and (getattr(dataset.metadata, prop) is not None):
return
raise ValueError(
f"Dataset {dataset.id} is missing property {prop} required for maturity check"
)
check_maturity_information(ds, ["region_code", "time", "dataset_maturity"])
# 'expand' the date range by `delta` milliseconds to give a bit more leniency in datetime comparison
expanded_time_range = Range(ds.metadata.time.begin - timedelta(milliseconds=delta),
ds.metadata.time.end + timedelta(milliseconds=delta))
dupes = self.search(product=ds.product.name,
region_code=ds.metadata.region_code,
time=expanded_time_range)
less_mature = []
for dupe in dupes:
if dupe.id == ds.id:
continue
# only need to check that dupe has dataset maturity, missing/null region_code and time
# would already have been filtered out during the search query
check_maturity_information(dupe, ["dataset_maturity"])
if dupe.metadata.dataset_maturity == ds.metadata.dataset_maturity:
# Duplicate has the same maturity, which one should be archived is unclear
raise ValueError(
f"A dataset with the same maturity as dataset {ds.id} already exists, "
f"with id: {dupe.id}"
)
if dupe.metadata.dataset_maturity < ds.metadata.dataset_maturity:
# Duplicate is more mature than dataset
# Note that "final" < "nrt"
raise ValueError(
f"A more mature version of dataset {ds.id} already exists, with id: "
f"{dupe.id} and maturity: {dupe.metadata.dataset_maturity}"
)
less_mature.append(dupe)
return less_mature
@abstractmethod
def restore(self, ids: Iterable[DSID]) -> None:
"""
Mark datasets as not archived
:param Iterable[Union[str,UUID]] ids: list of dataset ids to restore
"""
@abstractmethod
def purge(self, ids: Iterable[DSID]) -> None:
"""
Delete archived datasets