Repository navigation
Expand file tree
/
Copy pathhttp.py
More file actions
819 lines (752 loc) · 32.8 KB
/
Copy pathhttp.py
File metadata and controls
819 lines (752 loc) · 32.8 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
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
import logging
import threading
import time
from datetime import datetime, timedelta
from pathlib import Path
from threading import Lock
from typing import Any, List, Optional, Set, Union
import httpx
from pydantic import StrictStr
from feast.base_feature_view import BaseFeatureView
from feast.data_source import DataSource, KafkaSource, PushSource, RequestSource
from feast.entity import Entity
from feast.errors import (
DataSourceObjectNotFoundException,
EntityNotFoundException,
FeatureServiceNotFoundException,
FeatureViewNotFoundException,
ProjectMetadataNotFoundException,
)
from feast.expediagroup.pydantic_models.data_source_model import (
KafkaSourceModel,
PushSourceModel,
RequestSourceModel,
SparkSourceModel,
)
from feast.expediagroup.pydantic_models.entity_model import EntityModel
from feast.expediagroup.pydantic_models.feature_service import FeatureServiceModel
from feast.expediagroup.pydantic_models.feature_view_model import (
FeatureViewModel,
OnDemandFeatureViewModel,
)
from feast.expediagroup.pydantic_models.project_metadata_model import (
ProjectMetadataModel,
)
from feast.feature_service import FeatureService
from feast.feature_view import FeatureView
from feast.infra.infra_object import Infra
from feast.infra.offline_stores.contrib.spark_offline_store.spark_source import (
SparkSource,
)
from feast.infra.registry import proto_registry_utils
from feast.infra.registry.base_registry import BaseRegistry
from feast.on_demand_feature_view import OnDemandFeatureView
from feast.project_metadata import ProjectMetadata
from feast.protos.feast.core.Registry_pb2 import Registry as RegistryProto
from feast.repo_config import RegistryConfig
from feast.saved_dataset import SavedDataset, ValidationReference
from feast.stream_feature_view import StreamFeatureView
logger = logging.getLogger(__name__)
class HttpRegistryConfig(RegistryConfig):
registry_type: StrictStr = "http"
""" str: Provider name or a class name that implements Registry."""
path: StrictStr = ""
""" str: Endpoint of Feature registry.
If registry_type is 'http', then this is a endpoint of Feature Registry """
client_id: Optional[StrictStr] = "Unknown"
CACHE_REFRESH_THRESHOLD_SECONDS = 300
class HttpRegistry(BaseRegistry):
def __init__(
self,
registry_config: Optional[Union[RegistryConfig, HttpRegistryConfig]],
project: str,
repo_path: Optional[Path],
):
assert registry_config is not None, "HTTPRegistry needs a valid registry_config"
# Timeouts in seconds
timeout = httpx.Timeout(5.0, connect=60.0)
transport = httpx.HTTPTransport(retries=3, verify=False)
self.base_url = registry_config.path
headers_dict = {
"Content-Type": "application/json",
"Client-Id": registry_config.client_id,
}
headers = httpx.Headers(
{k: str(v) for k, v in headers_dict.items() if v is not None}
)
self.http_client = httpx.Client(
timeout=timeout, transport=transport, headers=headers
)
self.project = project
self.apply_project(self.project)
self.cached_registry_proto_created = datetime.utcnow()
self._refresh_lock = Lock()
self.cached_registry_proto_ttl = timedelta(
seconds=(
registry_config.cache_ttl_seconds
if registry_config.cache_ttl_seconds is not None
else 0
)
)
self.cached_registry_proto = self.proto()
self.stop_thread = False
self.refresh_cache_thread = threading.Thread(target=self._refresh_cache)
self.refresh_cache_thread.daemon = True
self.refresh_cache_thread.start()
def _refresh_cache(self):
while not self.stop_thread:
try:
self.refresh()
except Exception as e:
logger.error(f"Registry refresh failed with exception: {e}")
# Sleep for cached_registry_proto_ttl - 10 seconds
# TODO: This process needs an update. There is not way to send kill signal to
# the thread. When the cached_registry_proto_ttl is large, it will wait longer
# before it terminates the thread.
time.sleep(self.cached_registry_proto_ttl.total_seconds() - 10)
def close(self):
self.stop_thread = True
self.refresh_cache_thread.join(10)
def teardown(self):
self.close()
def _handle_exception(self, exception: Exception):
logger.exception("Request failed with exception: %s", repr(exception))
raise httpx.HTTPError(
"Request failed with exception: " + repr(exception)
) from exception
def _send_request(self, method: str, url: str, params=None, data=None):
try:
request = httpx.Request(method=method, url=url, params=params, data=data)
response = self.http_client.send(request)
response.raise_for_status()
return response.json()
except httpx.HTTPError as http_exception:
self._handle_exception(http_exception)
except Exception as exception:
self._handle_exception(exception)
def apply_project( # type: ignore[return]
self,
project: str,
commit: bool = True,
) -> ProjectMetadataModel:
try:
url = f"{self.base_url}/projects"
params = {"project": project, "commit": commit}
response_data = self._send_request("PUT", url, params=params)
return ProjectMetadataModel.model_validate(response_data)
except Exception as exception:
self._handle_exception(exception)
def apply_entity(self, entity: Entity, project: str, commit: bool = True):
try:
url = f"{self.base_url}/projects/{project}/entities"
data = EntityModel.from_entity(entity).model_dump_json()
params = {"commit": commit}
response_data = self._send_request("PUT", url, params=params, data=data)
return EntityModel.model_validate(response_data).to_entity()
except Exception as exception:
self._handle_exception(exception)
def delete_entity(self, name: str, project: str, commit: bool = True):
try:
url = f"{self.base_url}/projects/{project}/entities/{name}"
params = {"commit": commit}
self._send_request("DELETE", url, params=params)
logger.info(f"Deleted Entity {name} from project {project}")
except EntityNotFoundException as exception:
logger.error(
f"Entity {name} requested does not exist for deletion: {str(exception)}",
)
raise httpx.HTTPError(message=f"Entity: {name} not found")
except Exception as exception:
self._handle_exception(exception)
def get_entity( # type: ignore[return]
self,
name: str,
project: str,
allow_cache: bool = False,
) -> Entity:
if allow_cache:
self._check_if_registry_refreshed()
return proto_registry_utils.get_entity(
self.cached_registry_proto, name, project
)
try:
url = f"{self.base_url}/projects/{project}/entities/{name}"
response_data = self._send_request("GET", url)
return EntityModel.model_validate(response_data).to_entity()
except EntityNotFoundException as exception:
logger.error(
f"Entity {name} requested does not exist: {str(exception)}",
)
raise httpx.HTTPError(message=f"Entity: {name} not found")
except Exception as exception:
self._handle_exception(exception)
def list_entities( # type: ignore[return]
self,
project: str,
allow_cache: bool = False,
tags: Optional[dict[str, str]] = None,
) -> List[Entity]:
if allow_cache:
self._check_if_registry_refreshed()
return proto_registry_utils.list_entities(
self.cached_registry_proto, project, tags
)
try:
url = f"{self.base_url}/projects/{project}/entities"
response_data = self._send_request("GET", url)
response_list = response_data if isinstance(response_data, list) else []
return [
EntityModel.model_validate(entity).to_entity()
for entity in response_list
]
except Exception as exception:
self._handle_exception(exception)
def apply_data_source(
self, data_source: DataSource, project: str, commit: bool = True
):
try:
url = f"{self.base_url}/projects/{project}/data_sources"
params = {"commit": commit}
if isinstance(data_source, SparkSource):
data = SparkSourceModel.from_data_source(data_source).model_dump_json()
response_data = self._send_request("PUT", url, params=params, data=data)
return SparkSourceModel.model_validate(response_data).to_data_source()
elif isinstance(data_source, RequestSource):
data = RequestSourceModel.from_data_source(
data_source
).model_dump_json()
response_data = self._send_request("PUT", url, params=params, data=data)
return RequestSourceModel.model_validate(response_data).to_data_source()
elif isinstance(data_source, PushSource):
data = PushSourceModel.from_data_source(data_source).model_dump_json()
response_data = self._send_request("PUT", url, params=params, data=data)
return PushSourceModel.model_validate(response_data).to_data_source()
elif isinstance(data_source, KafkaSource):
data = KafkaSourceModel.from_data_source(data_source).model_dump_json()
response_data = self._send_request("PUT", url, params=params, data=data)
return KafkaSourceModel.model_validate(response_data).to_data_source()
else:
raise TypeError(
"Unsupported DataSource type. Please use either SparkSource, RequestSource, PushSource or KafkaSource only"
)
except Exception as exception:
self._handle_exception(exception)
def delete_data_source(self, name: str, project: str, commit: bool = True):
try:
url = f"{self.base_url}/projects/{project}/data_sources/{name}"
params = {"commit": commit}
self._send_request("DELETE", url, params=params)
logger.info(f"Deleted Datasource {name} from project {project}")
except DataSourceObjectNotFoundException as exception:
logger.error(
f"Requested DataSource {name} does not exist for deletion: {str(exception)}",
)
raise httpx.HTTPError(message=f"DataSource: {name} not found")
except Exception as exception:
self._handle_exception(exception)
def get_data_source( # type: ignore[return]
self,
name: str,
project: str,
allow_cache: bool = False,
) -> DataSource:
if allow_cache:
self._check_if_registry_refreshed()
return proto_registry_utils.get_data_source(
self.cached_registry_proto, name, project
)
try:
url = f"{self.base_url}/projects/{project}/data_sources/{name}"
response_data = self._send_request("GET", url)
if "model_type" in response_data:
if response_data["model_type"] == "RequestSourceModel":
return RequestSourceModel.model_validate(
response_data
).to_data_source()
elif response_data["model_type"] == "SparkSourceModel":
return SparkSourceModel.model_validate(
response_data
).to_data_source()
elif response_data["model_type"] == "KafkaSourceModel":
return KafkaSourceModel.model_validate(
response_data
).to_data_source()
logger.error(f"Unable to parse object with response: {response_data}")
raise ValueError("Unable to parse object")
except DataSourceObjectNotFoundException as exception:
logger.error(
f"DataSource {name} requested does not exist: {str(exception)}",
)
raise httpx.HTTPError(message=f"DataSource: {name} not found")
except Exception as exception:
self._handle_exception(exception)
def list_data_sources( # type: ignore[return]
self,
project: str,
allow_cache: bool = False,
tags: Optional[dict[str, str]] = None,
) -> List[DataSource]:
if allow_cache:
self._check_if_registry_refreshed()
return proto_registry_utils.list_data_sources(
self.cached_registry_proto, project, tags
)
try:
url = f"{self.base_url}/projects/{project}/data_sources"
response_data = self._send_request("GET", url)
response_list = response_data if isinstance(response_data, list) else []
data_source_list: List[DataSource] = []
for data_source in response_list:
if "model_type" in data_source:
if data_source["model_type"] == "RequestSourceModel":
data_source_list.append(
RequestSourceModel.model_validate(
data_source
).to_data_source()
)
elif data_source["model_type"] == "SparkSourceModel":
data_source_list.append(
SparkSourceModel.model_validate(
data_source
).to_data_source()
)
elif data_source["model_type"] == "KafkaSourceModel":
data_source_list.append(
KafkaSourceModel.model_validate(
data_source
).to_data_source()
)
else:
logger.error(
f"Unable to parse model_type for data_source response: {data_source}"
)
raise ValueError(
"Unable to parse object with data_source name: {data_source.name}"
)
return data_source_list
except Exception as exception:
self._handle_exception(exception)
def apply_feature_service(
self, feature_service: FeatureService, project: str, commit: bool = True
):
try:
url = f"{self.base_url}/projects/{project}/feature_services"
data = FeatureServiceModel.from_feature_service(
feature_service
).model_dump_json()
params = {"commit": commit}
response_data = self._send_request("PUT", url, params=params, data=data)
return FeatureServiceModel.model_validate(
response_data
).to_feature_service()
except Exception as exception:
self._handle_exception(exception)
def delete_feature_service(self, name: str, project: str, commit: bool = True):
try:
url = f"{self.base_url}/projects/{project}/feature_services/{name}"
params = {"commit": commit}
self._send_request("DELETE", url, params=params)
logger.info(f"Deleted FeatureService {name} from project {project}")
except FeatureServiceNotFoundException as exception:
logger.error(
f"FeatureService {name} requested does not exist for deletion: %s",
str(exception),
)
raise httpx.HTTPError(message=f"FeatureService: {name} not found")
except Exception as exception:
self._handle_exception(exception)
def get_feature_service( # type: ignore[return]
self,
name: str,
project: str,
allow_cache: bool = False,
) -> FeatureService:
if allow_cache:
self._check_if_registry_refreshed()
return proto_registry_utils.get_feature_service(
self.cached_registry_proto, name, project
)
try:
url = f"{self.base_url}/projects/{project}/feature_services/{name}"
response_data = self._send_request("GET", url)
return FeatureServiceModel.model_validate(
response_data
).to_feature_service()
except FeatureServiceNotFoundException as exception:
logger.error(
f"FeatureService {name} requested does not exist: %s", str(exception)
)
raise httpx.HTTPError(message=f"FeatureService: {name} not found")
except Exception as exception:
self._handle_exception(exception)
def list_feature_services( # type: ignore[return]
self,
project: str,
allow_cache: bool = False,
tags: Optional[dict[str, str]] = None,
) -> List[FeatureService]:
if allow_cache:
self._check_if_registry_refreshed()
return proto_registry_utils.list_feature_services(
self.cached_registry_proto, project, tags
)
try:
url = f"{self.base_url}/projects/{project}/feature_services"
response_data = self._send_request("GET", url)
response_list = response_data if isinstance(response_data, list) else []
return [
FeatureServiceModel.model_validate(feature_service).to_feature_service()
for feature_service in response_list
]
except Exception as exception:
self._handle_exception(exception)
def apply_feature_view(
self, feature_view: BaseFeatureView, project: str, commit: bool = True
):
try:
params = {"commit": commit}
if isinstance(feature_view, FeatureView):
url = f"{self.base_url}/projects/{project}/feature_views"
data = FeatureViewModel.from_feature_view(
feature_view
).model_dump_json()
response_data = self._send_request("PUT", url, params=params, data=data)
return FeatureViewModel.model_validate(response_data).to_feature_view()
elif isinstance(feature_view, OnDemandFeatureView):
url = f"{self.base_url}/projects/{project}/on_demand_feature_views"
data = OnDemandFeatureViewModel.from_feature_view(
feature_view
).model_dump_json()
response_data = self._send_request("PUT", url, params=params, data=data)
return OnDemandFeatureViewModel.model_validate(
response_data
).to_feature_view()
else:
raise TypeError(
"Unsupported FeatureView type. Please use either FeatureView or OnDemandFeatureView only"
)
except Exception as exception:
self._handle_exception(exception)
def delete_feature_view(self, name: str, project: str, commit: bool = True):
try:
url = f"{self.base_url}/projects/{project}/feature_views/{name}"
params = {"commit": commit}
self._send_request("DELETE", url, params=params)
logger.info(f"Deleted FeatureView {name} from project {project}")
except FeatureViewNotFoundException as exception:
logger.error(
f"Requested FeatureView {name} does not exist for deletion: %s",
str(exception),
)
raise httpx.HTTPError(message=f"FeatureView: {name} not found")
except Exception as exception:
self._handle_exception(exception)
def get_feature_view( # type: ignore[return]
self,
name: str,
project: str,
allow_cache: bool = False,
) -> FeatureView:
if allow_cache:
self._check_if_registry_refreshed()
return proto_registry_utils.get_feature_view(
self.cached_registry_proto, name, project
)
try:
url = f"{self.base_url}/projects/{project}/feature_views/{name}"
response_data = self._send_request("GET", url)
return FeatureViewModel.model_validate(response_data).to_feature_view()
except FeatureViewNotFoundException as exception:
logger.error(
f"FeatureView {name} requested does not exist: %s", str(exception)
)
raise httpx.HTTPError(message=f"FeatureView: {name} not found")
except Exception as exception:
self._handle_exception(exception)
def list_feature_views( # type: ignore[return]
self,
project: str,
allow_cache: bool = False,
tags: Optional[dict[str, str]] = None,
) -> List[FeatureView]:
if allow_cache:
self._check_if_registry_refreshed()
return proto_registry_utils.list_feature_views(
self.cached_registry_proto, project, tags
)
try:
url = f"{self.base_url}/projects/{project}/feature_views"
response_data = self._send_request("GET", url)
response_list = response_data if isinstance(response_data, list) else []
return [
FeatureViewModel.model_validate(feature_view).to_feature_view()
for feature_view in response_list
]
except Exception as exception:
self._handle_exception(exception)
def get_on_demand_feature_view( # type: ignore[return]
self, name: str, project: str, allow_cache: bool = False
) -> OnDemandFeatureView:
if allow_cache:
self._check_if_registry_refreshed()
return proto_registry_utils.get_on_demand_feature_view(
self.cached_registry_proto, name, project
)
try:
url = f"{self.base_url}/projects/{project}/on_demand_feature_views/{name}"
response_data = self._send_request("GET", url)
return OnDemandFeatureViewModel.model_validate(
response_data
).to_feature_view()
except FeatureViewNotFoundException as exception:
logger.error(
f"FeatureView {name} requested does not exist: %s", str(exception)
)
raise httpx.HTTPError(message=f"FeatureView: {name} not found")
except Exception as exception:
self._handle_exception(exception)
def list_on_demand_feature_views( # type: ignore[return]
self,
project: str,
allow_cache: bool = False,
tags: Optional[dict[str, str]] = None,
) -> List[OnDemandFeatureView]:
if allow_cache:
self._check_if_registry_refreshed()
return proto_registry_utils.list_on_demand_feature_views(
self.cached_registry_proto, project, tags
)
try:
url = f"{self.base_url}/projects/{project}/on_demand_feature_views"
response_data = self._send_request("GET", url)
response_list = response_data if isinstance(response_data, list) else []
return [
OnDemandFeatureViewModel.model_validate(feature_view).to_feature_view()
for feature_view in response_list
]
except Exception as exception:
self._handle_exception(exception)
def get_stream_feature_view(
self,
name: str,
project: str,
allow_cache: bool = False,
):
raise NotImplementedError("Method not implemented")
def list_stream_feature_views(
self,
project: str,
allow_cache: bool = False,
tags: Optional[dict[str, str]] = None,
) -> List[StreamFeatureView]:
# TODO: Implement listing Stream Feature Views
return []
def apply_materialization(
self,
feature_view: FeatureView,
project: str,
start_date: datetime,
end_date: datetime,
commit: bool = True,
):
try:
if isinstance(feature_view, FeatureView):
feature_view.materialization_intervals.append((start_date, end_date))
params = {"commit": commit}
url = f"{self.base_url}/projects/{project}/feature_views"
data = FeatureViewModel.from_feature_view(
feature_view
).model_dump_json()
response_data = self._send_request("PUT", url, params=params, data=data)
return FeatureViewModel.model_validate(response_data).to_feature_view()
else:
raise TypeError(
"Unsupported FeatureView type. Please use either FeatureView or OnDemandFeatureView only"
)
except Exception as exception:
self._handle_exception(exception)
def apply_saved_dataset(
self, saved_dataset: SavedDataset, project: str, commit: bool = True
):
raise NotImplementedError("Method not implemented")
def get_saved_dataset(
self,
name: str,
project: str,
allow_cache: bool = False,
) -> SavedDataset:
raise NotImplementedError("Method not implemented")
def list_saved_datasets(
self,
project: str,
allow_cache: bool = False,
) -> List[SavedDataset]:
return []
def apply_validation_reference(
self,
validation_reference: ValidationReference,
project: str,
commit: bool = True,
):
raise NotImplementedError("Method not implemented")
def delete_validation_reference(self, name: str, project: str, commit: bool = True):
raise NotImplementedError("Method not implemented")
def get_validation_reference(
self,
name: str,
project: str,
allow_cache: bool = False,
) -> ValidationReference:
raise NotImplementedError("Method not implemented")
def update_infra(self, infra: Infra, project: str, commit: bool = True):
raise NotImplementedError("Method not implemented")
def get_infra(
self,
project: str,
allow_cache: bool = False,
) -> Infra:
# TODO: Need to implement this when necessary
return Infra()
def apply_user_metadata(
self,
project: str,
feature_view: BaseFeatureView,
metadata_bytes: Optional[bytes],
):
raise NotImplementedError("Method not implemented")
def get_user_metadata(
self, project: str, feature_view: BaseFeatureView
) -> Optional[bytes]:
raise NotImplementedError("Method not implemented")
def list_validation_references(
self,
project: str,
allow_cache: bool = False,
) -> List[ValidationReference]:
return []
def proto(self) -> RegistryProto:
r = RegistryProto()
# last_updated_timestamps = []
if self.project is None:
projects = self._get_all_projects()
else:
projects = [self.project]
for project in projects:
for lister, registry_proto_field in [
(self.list_entities, r.entities),
(self.list_feature_views, r.feature_views),
(self.list_data_sources, r.data_sources),
(self.list_on_demand_feature_views, r.on_demand_feature_views),
(self.list_stream_feature_views, r.stream_feature_views),
(self.list_feature_services, r.feature_services),
(self.list_saved_datasets, r.saved_datasets),
(self.list_validation_references, r.validation_references),
(self.list_project_metadata, r.project_metadata),
]:
objs: List[Any] = lister(project) # type: ignore
if objs:
obj_protos = [obj.to_proto() for obj in objs]
for obj_proto in obj_protos:
if "spec" in obj_proto.DESCRIPTOR.fields_by_name:
obj_proto.spec.project = project
else:
obj_proto.project = project
registry_proto_field.extend(obj_protos)
# This is suuuper jank. Because of https://github.com/feast-dev/feast/issues/2783,
# the registry proto only has a single infra field, which we're currently setting as the "last" project.
r.infra.CopyFrom(self.get_infra(project).to_proto())
# last_updated_timestamps.append(self._get_last_updated_metadata(project))
# if last_updated_timestamps:
# r.last_updated.FromDatetime(max(last_updated_timestamps))
r.last_updated.FromDatetime(datetime.utcnow())
return r
def commit(self):
# This method is a no-op since we're always writing values eagerly to the db.
pass
def refresh(self, project: Optional[str] = None):
if project:
project_metadata = proto_registry_utils.get_project_metadata(
registry_proto=self.cached_registry_proto, project=project
)
if project_metadata is None:
proto_registry_utils.init_project_metadata(
self.cached_registry_proto, project
)
refreshed_cache_registry_proto = self.proto()
with self._refresh_lock:
self.cached_registry_proto = refreshed_cache_registry_proto
self.cached_registry_proto_created = datetime.utcnow()
def _refresh_cached_registry_if_necessary(self):
with self._refresh_lock:
expired = (
self.cached_registry_proto is None
or self.cached_registry_proto_created is None
) or (
self.cached_registry_proto_ttl.total_seconds()
> 0 # 0 ttl means infinity
and (
datetime.utcnow()
> (
self.cached_registry_proto_created
+ self.cached_registry_proto_ttl
)
)
)
if expired:
logger.info("Registry cache expired, so refreshing")
self.refresh()
def _check_if_registry_refreshed(self):
if (
self.cached_registry_proto is None
or self.cached_registry_proto_created is None
) or (
self.cached_registry_proto_ttl.total_seconds() > 0 # 0 ttl means infinity
and (
datetime.utcnow()
> (self.cached_registry_proto_created + self.cached_registry_proto_ttl)
)
):
seconds_since_last_refresh = (
datetime.utcnow() - self.cached_registry_proto_created
).total_seconds()
if seconds_since_last_refresh > CACHE_REFRESH_THRESHOLD_SECONDS:
logger.warning(
f"Cache is stale: {seconds_since_last_refresh} seconds since last refresh"
)
def _get_all_projects(self) -> Set[str]: # type: ignore[return]
try:
url = f"{self.base_url}/projects"
projects = self._send_request("GET", url)
return {project["project_name"] for project in projects}
except Exception as exception:
self._handle_exception(exception)
def _get_last_updated_metadata(self, project: str):
try:
url = f"{self.base_url}/projects/{project}"
response_data = self._send_request("GET", url)
return datetime.strptime(
response_data["last_updated_timestamp"], "%Y-%m-%dT%H:%M:%S"
)
except Exception as exception:
self._handle_exception(exception)
def list_project_metadata( # type: ignore[return]
self, project: str, allow_cache: bool = False
) -> List[ProjectMetadata]:
if allow_cache:
self._check_if_registry_refreshed()
return proto_registry_utils.list_project_metadata(
self.cached_registry_proto, project
)
try:
url = f"{self.base_url}/projects/{project}"
response_data = self._send_request("GET", url)
return [
ProjectMetadataModel.model_validate(response_data).to_project_metadata()
]
except ProjectMetadataNotFoundException as exception:
logger.error(
f"Project {project} requested does not exist: {str(exception)}"
)
raise httpx.HTTPError(message=f"ProjectMetadata: {project} not found")
except Exception as exception:
self._handle_exception(exception)