GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — feast/sdk/python/feast/data_source.py at master · feast-dev/feast Expand file tree/ Copy pathdata_source.pyMore file actions 1025 lines (876 loc) · 38.5 KB / Copy pathdata_source.pyFile metadata and controls1025 lines (876 loc) · 38.5 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 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 # Copyright 2020 The Feast Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import enum import warnings from abc import ABC, abstractmethod from datetime import datetime, timedelta, timezone from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union from google.protobuf.duration_pb2 import Duration from google.protobuf.json_format import MessageToJson from typeguard import typechecked from feast import type_map from feast.credentials import TAG_PREFIX, ConnectionRef from feast.data_format import StreamFormat from feast.field import Field from feast.protos.feast.core.DataSource_pb2 import DataSource as DataSourceProto from feast.repo_config import RepoConfig, get_data_source_class_from_type from feast.types import from_value_type from feast.utils import _utc_now from feast.value_type import ValueType class KafkaOptions: """ DataSource Kafka options used to source features from Kafka messages """ def __init__( self, kafka_bootstrap_servers: str, message_format: StreamFormat, topic: str, watermark_delay_threshold: Optional[timedelta] = None, ): self.kafka_bootstrap_servers = kafka_bootstrap_servers self.message_format = message_format self.topic = topic self.watermark_delay_threshold = watermark_delay_threshold @classmethod def from_proto(cls, kafka_options_proto: DataSourceProto.KafkaOptions): """ Creates a KafkaOptions from a protobuf representation of a kafka option Args: kafka_options_proto: A protobuf representation of a DataSource Returns: Returns a KafkaOptions object based on the kafka_options protobuf """ watermark_delay_threshold = None if kafka_options_proto.HasField("watermark_delay_threshold"): watermark_delay_threshold = ( kafka_options_proto.watermark_delay_threshold.ToTimedelta() ) kafka_options = cls( kafka_bootstrap_servers=kafka_options_proto.kafka_bootstrap_servers, message_format=StreamFormat.from_proto(kafka_options_proto.message_format), topic=kafka_options_proto.topic, watermark_delay_threshold=watermark_delay_threshold, ) return kafka_options def to_proto(self) -> DataSourceProto.KafkaOptions: """ Converts an KafkaOptionsProto object to its protobuf representation. Returns: KafkaOptionsProto protobuf """ watermark_delay_threshold = None if self.watermark_delay_threshold is not None: watermark_delay_threshold = Duration() watermark_delay_threshold.FromTimedelta(self.watermark_delay_threshold) kafka_options_proto = DataSourceProto.KafkaOptions( kafka_bootstrap_servers=self.kafka_bootstrap_servers, message_format=self.message_format.to_proto(), topic=self.topic, watermark_delay_threshold=watermark_delay_threshold, ) return kafka_options_proto class KinesisOptions: """ DataSource Kinesis options used to source features from Kinesis records """ def __init__( self, record_format: StreamFormat, region: str, stream_name: str, ): self.record_format = record_format self.region = region self.stream_name = stream_name @classmethod def from_proto(cls, kinesis_options_proto: DataSourceProto.KinesisOptions): """ Creates a KinesisOptions from a protobuf representation of a kinesis option Args: kinesis_options_proto: A protobuf representation of a DataSource Returns: Returns a KinesisOptions object based on the kinesis_options protobuf """ kinesis_options = cls( record_format=StreamFormat.from_proto(kinesis_options_proto.record_format), region=kinesis_options_proto.region, stream_name=kinesis_options_proto.stream_name, ) return kinesis_options def to_proto(self) -> DataSourceProto.KinesisOptions: """ Converts an KinesisOptionsProto object to its protobuf representation. Returns: KinesisOptionsProto protobuf """ kinesis_options_proto = DataSourceProto.KinesisOptions( record_format=self.record_format.to_proto(), region=self.region, stream_name=self.stream_name, ) return kinesis_options_proto _DATA_SOURCE_OPTIONS = { DataSourceProto.SourceType.BATCH_FILE: "feast.infra.offline_stores.file_source.FileSource", DataSourceProto.SourceType.BATCH_BIGQUERY: "feast.infra.offline_stores.bigquery_source.BigQuerySource", DataSourceProto.SourceType.BATCH_REDSHIFT: "feast.infra.offline_stores.redshift_source.RedshiftSource", DataSourceProto.SourceType.BATCH_SNOWFLAKE: "feast.infra.offline_stores.snowflake_source.SnowflakeSource", DataSourceProto.SourceType.BATCH_TRINO: "feast.infra.offline_stores.contrib.trino_offline_store.trino_source.TrinoSource", DataSourceProto.SourceType.BATCH_SPARK: "feast.infra.offline_stores.contrib.spark_offline_store.spark_source.SparkSource", DataSourceProto.SourceType.BATCH_ATHENA: "feast.infra.offline_stores.contrib.athena_offline_store.athena_source.AthenaSource", DataSourceProto.SourceType.BATCH_ICEBERG: "feast.infra.data_sources.contrib.iceberg_catalog.iceberg_source.IcebergSource", DataSourceProto.SourceType.STREAM_KAFKA: "feast.data_source.KafkaSource", DataSourceProto.SourceType.STREAM_KINESIS: "feast.data_source.KinesisSource", DataSourceProto.SourceType.REQUEST_SOURCE: "feast.data_source.RequestSource", DataSourceProto.SourceType.PUSH_SOURCE: "feast.data_source.PushSource", } _DATA_SOURCE_FOR_OFFLINE_STORE = { DataSourceProto.SourceType.BATCH_FILE: "feast.infra.offline_stores.dask.DaskOfflineStore", DataSourceProto.SourceType.BATCH_BIGQUERY: "feast.infra.offline_stores.bigquery.BigQueryOfflineStore", DataSourceProto.SourceType.BATCH_REDSHIFT: "feast.infra.offline_stores.redshift.RedshiftOfflineStore", DataSourceProto.SourceType.BATCH_SNOWFLAKE: "feast.infra.offline_stores.snowflake.SnowflakeOfflineStore", DataSourceProto.SourceType.BATCH_TRINO: "feast.infra.offline_stores.contrib.trino_offline_store.trino.TrinoOfflineStore", DataSourceProto.SourceType.BATCH_SPARK: "feast.infra.offline_stores.contrib.spark_offline_store.spark.SparkOfflineStore", DataSourceProto.SourceType.BATCH_ATHENA: "feast.infra.offline_stores.contrib.athena_offline_store.athena.AthenaOfflineStore", } @typechecked class DataSource(ABC): """ DataSource that can be used to source features. Args: name: Name of data source, which should be unique within a project timestamp_field (optional): Event timestamp field used for point-in-time joins of feature values. created_timestamp_column (optional): Timestamp column indicating when the row was created, used for deduplicating rows. field_mapping (optional): A dictionary mapping of column names in this data source to feature names in a feature table or view. Only used for feature columns and timestamp columns, not entity columns. description (optional) A human-readable description. tags (optional): A dictionary of key-value pairs to store arbitrary metadata. owner (optional): The owner of the data source, typically the email of the primary maintainer. date_partition_column (optional): Timestamp column used for partitioning. Not supported by all offline stores. connection_ref (optional): Connection reference for this data source. When set, OfflineStores resolve connection type and credentials at runtime via the registered CredentialProvider instead of using ambient env vars or the global offline_store config. All fields except provider and name are optional. created_timestamp: The time when the data source was created. last_updated_timestamp: The time when the data source was last updated. """ name: str timestamp_field: str created_timestamp_column: str field_mapping: Dict[str, str] description: str tags: Dict[str, str] owner: str date_partition_column: str timestamp_field_type: str connection_ref: Optional[ConnectionRef] created_timestamp: Optional[datetime] last_updated_timestamp: Optional[datetime] def __init__( self, *, name: str, timestamp_field: Optional[str] = None, created_timestamp_column: Optional[str] = None, field_mapping: Optional[Dict[str, str]] = None, description: Optional[str] = "", tags: Optional[Dict[str, str]] = None, owner: Optional[str] = "", date_partition_column: Optional[str] = None, timestamp_field_type: Optional[str] = None, connection_ref: Optional[ConnectionRef] = None, ): """ Creates a DataSource object. Args: name: Name of data source, which should be unique within a project. timestamp_field (optional): Event timestamp field used for point-in-time joins of feature values. created_timestamp_column (optional): Timestamp column indicating when the row was created, used for deduplicating rows. field_mapping (optional): A dictionary mapping of column names in this data source to feature names in a feature table or view. Only used for feature columns, not entity or timestamp columns. description (optional): A human-readable description. tags (optional): A dictionary of key-value pairs to store arbitrary metadata. owner (optional): The owner of the data source, typically the email of the primary maintainer. date_partition_column (optional): Timestamp column used for partitioning. Not supported by all stores timestamp_field_type (optional): Type of the timestamp_field column. Defaults to "TIMESTAMP". Set to "DATE" when the event timestamp column is a DATE type, so SQL generation uses date-only comparisons. connection_ref (optional): Connection reference for this data source. See :class:`~feast.credentials.ConnectionRef`. """ self.name = name self.timestamp_field = timestamp_field or "" self.created_timestamp_column = ( created_timestamp_column if created_timestamp_column else "" ) self.field_mapping = field_mapping if field_mapping else {} if ( self.timestamp_field and self.timestamp_field == self.created_timestamp_column ): raise ValueError( "Please do not use the same column for 'timestamp_field' and 'created_timestamp_column'." ) self.description = description or "" self.tags = tags or {} self.owner = owner or "" self.date_partition_column = ( date_partition_column if date_partition_column else "" ) self.timestamp_field_type = timestamp_field_type if timestamp_field_type else "" self.connection_ref = connection_ref now = _utc_now() self.created_timestamp = now self.last_updated_timestamp = now def resolve_credentials(self) -> Optional[Dict[str, str]]: """Resolve credentials from the ``connection_ref`` if set. Returns ``None`` when no ``connection_ref`` is configured (ambient credentials are used instead). """ if self.connection_ref is None: return None from feast.credentials import resolve_credentials return resolve_credentials(self.connection_ref) def __hash__(self): return hash((self.name, self.timestamp_field)) def __str__(self): return str(MessageToJson(self.to_proto())) def __eq__(self, other): if other is None: return False if not isinstance(other, DataSource): return False if ( self.name != other.name or self.timestamp_field != other.timestamp_field or self.created_timestamp_column != other.created_timestamp_column or self.field_mapping != other.field_mapping or self.date_partition_column != other.date_partition_column or self.timestamp_field_type != other.timestamp_field_type or self.description != other.description or self.tags != other.tags or self.owner != other.owner or self.connection_ref != other.connection_ref ): return False return True @staticmethod @abstractmethod def from_proto(data_source: DataSourceProto) -> Any: """ Converts data source config in protobuf spec to a DataSource class object. Args: data_source: A protobuf representation of a DataSource. Returns: A DataSource class object. Raises: ValueError: The type of DataSource could not be identified. """ data_source_type = data_source.type if not data_source_type or ( data_source_type not in list(_DATA_SOURCE_OPTIONS.keys()) + [DataSourceProto.SourceType.CUSTOM_SOURCE] ): raise ValueError("Could not identify the source type being added.") if data_source_type == DataSourceProto.SourceType.CUSTOM_SOURCE: cls = get_data_source_class_from_type(data_source.data_source_class_type) data_source_instance = cls.from_proto(data_source) else: cls = get_data_source_class_from_type( _DATA_SOURCE_OPTIONS[data_source_type] ) data_source_instance = cls.from_proto(data_source) data_source_instance._extract_timestamps_from_proto(data_source) data_source_instance.connection_ref = ConnectionRef.from_tags( dict(data_source.tags) ) data_source_instance.tags = { key: value for key, value in data_source_instance.tags.items() if not key.startswith(TAG_PREFIX) } return data_source_instance def to_proto(self) -> DataSourceProto: """ Converts a DataSourceProto object to its protobuf representation. """ proto = self._to_proto_impl() self._set_timestamps_in_proto(proto) if self.connection_ref is not None: for key, value in self.connection_ref.to_tags().items(): proto.tags[key] = value return proto @abstractmethod def _to_proto_impl(self) -> DataSourceProto: """ Subclass implementation of protobuf conversion. This should be implemented by each DataSource subclass. """ raise NotImplementedError def validate(self, config: RepoConfig): """ Validates the underlying data source. Args: config: Configuration object used to configure a feature store. """ raise NotImplementedError @staticmethod @abstractmethod def source_datatype_to_feast_value_type() -> Callable[[str], ValueType]: """ Returns the callable method that returns Feast type given the raw column type. """ raise NotImplementedError def get_table_column_names_and_types( self, config: RepoConfig ) -> Iterable[Tuple[str, str]]: """ Returns the list of column names and raw column types. Args: config: Configuration object used to configure a feature store. """ raise NotImplementedError def get_table_query_string(self) -> str: """ Returns a string that can directly be used to reference this table in SQL. """ raise NotImplementedError def _extract_timestamps_from_proto(self, data_source_proto: DataSourceProto): """ Internal method to extract created_timestamp and last_updated_timestamp from protobuf. Called automatically by the base from_proto method. """ if data_source_proto.HasField("meta"): if data_source_proto.meta.HasField("created_timestamp"): self.created_timestamp = ( data_source_proto.meta.created_timestamp.ToDatetime().replace( tzinfo=timezone.utc ) ) if data_source_proto.meta.HasField("last_updated_timestamp"): self.last_updated_timestamp = ( data_source_proto.meta.last_updated_timestamp.ToDatetime().replace( tzinfo=timezone.utc ) ) def _set_timestamps_in_proto(self, data_source_proto: DataSourceProto): """ Internal method to set created_timestamp and last_updated_timestamp in protobuf. Called automatically by the base to_proto method. """ if not data_source_proto.HasField("meta"): data_source_proto.meta.CopyFrom(DataSourceProto.SourceMeta()) if self.created_timestamp: data_source_proto.meta.created_timestamp.FromDatetime( self.created_timestamp ) if self.last_updated_timestamp: data_source_proto.meta.last_updated_timestamp.FromDatetime( self.last_updated_timestamp ) @abstractmethod def source_type(self) -> DataSourceProto.SourceType.ValueType: ... @typechecked class KafkaSource(DataSource): """A KafkaSource allow users to register Kafka streams as data sources.""" def __init__( self, *, name: str, timestamp_field: str, message_format: StreamFormat, bootstrap_servers: Optional[str] = None, kafka_bootstrap_servers: Optional[str] = None, topic: Optional[str] = None, created_timestamp_column: Optional[str] = "", field_mapping: Optional[Dict[str, str]] = None, description: Optional[str] = "", tags: Optional[Dict[str, str]] = None, owner: Optional[str] = "", batch_source: Optional[DataSource] = None, watermark_delay_threshold: Optional[timedelta] = None, ): """ Creates a KafkaSource object. Args: name: Name of data source, which should be unique within a project timestamp_field: Event timestamp field used for point-in-time joins of feature values. message_format: StreamFormat of serialized messages. bootstrap_servers: (Deprecated) The servers of the kafka broker in the form "localhost:9092". kafka_bootstrap_servers (optional): The servers of the kafka broker in the form "localhost:9092". topic (optional): The name of the topic to read from in the kafka source. created_timestamp_column (optional): Timestamp column indicating when the row was created, used for deduplicating rows. field_mapping (optional): A dictionary mapping of column names in this data source to feature names in a feature table or view. Only used for feature columns, not entity or timestamp columns. description (optional): A human-readable description. tags (optional): A dictionary of key-value pairs to store arbitrary metadata. owner (optional): The owner of the data source, typically the email of the primary maintainer. batch_source (optional): The datasource that acts as a batch source. watermark_delay_threshold (optional): The watermark delay threshold for stream data. Specifically how late stream data can arrive without being discarded. """ if bootstrap_servers: warnings.warn( ( "The 'bootstrap_servers' parameter has been deprecated in favor of 'kafka_bootstrap_servers'. " "Feast 0.25 and onwards will not support the 'bootstrap_servers' parameter." ), DeprecationWarning, ) super().__init__( name=name, timestamp_field=timestamp_field, created_timestamp_column=created_timestamp_column, field_mapping=field_mapping, description=description, tags=tags, owner=owner, ) self.batch_source = batch_source kafka_bootstrap_servers = kafka_bootstrap_servers or bootstrap_servers or "" topic = topic or "" self.kafka_options = KafkaOptions( kafka_bootstrap_servers=kafka_bootstrap_servers, message_format=message_format, topic=topic, watermark_delay_threshold=watermark_delay_threshold, ) def __eq__(self, other): if not isinstance(other, KafkaSource): return False if not super().__eq__(other): return False if ( self.kafka_options.kafka_bootstrap_servers != other.kafka_options.kafka_bootstrap_servers or self.kafka_options.message_format != other.kafka_options.message_format or self.kafka_options.topic != other.kafka_options.topic or self.kafka_options.watermark_delay_threshold != other.kafka_options.watermark_delay_threshold ): return False return True def __hash__(self): return super().__hash__() @staticmethod def from_proto(data_source: DataSourceProto): watermark_delay_threshold = None if data_source.kafka_options.HasField("watermark_delay_threshold"): watermark_delay_threshold = ( data_source.kafka_options.watermark_delay_threshold.ToTimedelta() ) return KafkaSource( name=data_source.name, field_mapping=dict(data_source.field_mapping), kafka_bootstrap_servers=data_source.kafka_options.kafka_bootstrap_servers, message_format=StreamFormat.from_proto( data_source.kafka_options.message_format ), watermark_delay_threshold=watermark_delay_threshold, topic=data_source.kafka_options.topic, created_timestamp_column=data_source.created_timestamp_column, timestamp_field=data_source.timestamp_field, description=data_source.description, tags=dict(data_source.tags), owner=data_source.owner, batch_source=( DataSource.from_proto(data_source.batch_source) if data_source.HasField("batch_source") else None ), ) def _to_proto_impl(self) -> DataSourceProto: data_source_proto = DataSourceProto( name=self.name, type=DataSourceProto.STREAM_KAFKA, field_mapping=self.field_mapping, kafka_options=self.kafka_options.to_proto(), description=self.description, tags=self.tags, owner=self.owner, ) data_source_proto.timestamp_field = self.timestamp_field data_source_proto.created_timestamp_column = self.created_timestamp_column if self.batch_source: data_source_proto.batch_source.MergeFrom(self.batch_source.to_proto()) return data_source_proto def validate(self, config: RepoConfig): raise NotImplementedError def get_table_column_names_and_types( self, config: RepoConfig ) -> Iterable[Tuple[str, str]]: raise NotImplementedError @staticmethod def source_datatype_to_feast_value_type() -> Callable[[str], ValueType]: return type_map.redshift_to_feast_value_type def get_table_query_string(self) -> str: raise NotImplementedError def source_type(self) -> DataSourceProto.SourceType.ValueType: return DataSourceProto.STREAM_KAFKA @typechecked class RequestSource(DataSource): """ RequestSource that can be used to provide input features for on demand transforms Attributes: name: Name of the request data source schema: Schema mapping from the input feature name to a ValueType description: A human-readable description. tags: A dictionary of key-value pairs to store arbitrary metadata. owner: The owner of the request data source, typically the email of the primary maintainer. """ name: str schema: List[Field] description: str tags: Dict[str, str] owner: str def __init__( self, *, name: str, schema: List[Field], timestamp_field: Optional[str] = None, description: Optional[str] = "", tags: Optional[Dict[str, str]] = None, owner: Optional[str] = "", ): """Creates a RequestSource object.""" super().__init__( name=name, timestamp_field=timestamp_field, description=description, tags=tags, owner=owner, ) self.schema = schema def validate(self, config: RepoConfig): raise NotImplementedError def get_table_column_names_and_types( self, config: RepoConfig ) -> Iterable[Tuple[str, str]]: raise NotImplementedError def __eq__(self, other): if not isinstance(other, RequestSource): return False if not super().__eq__(other): return False if isinstance(self.schema, List) and isinstance(other.schema, List): for field1, field2 in zip(self.schema, other.schema): if field1 != field2: return False return True else: return False def __hash__(self): return super().__hash__() @staticmethod def from_proto(data_source: DataSourceProto): schema_pb = data_source.request_data_options.schema list_schema = [] for field_proto in schema_pb: list_schema.append(Field.from_proto(field_proto)) return RequestSource( name=data_source.name, schema=list_schema, timestamp_field=data_source.timestamp_field, description=data_source.description, tags=dict(data_source.tags), owner=data_source.owner, ) def _to_proto_impl(self) -> DataSourceProto: schema_pb = [] if isinstance(self.schema, Dict): for key, value in self.schema.items(): schema_pb.append( Field(name=key, dtype=from_value_type(value.value)).to_proto() ) else: for field in self.schema: schema_pb.append(field.to_proto()) data_source_proto = DataSourceProto( name=self.name, type=DataSourceProto.REQUEST_SOURCE, description=self.description, tags=self.tags, owner=self.owner, ) data_source_proto.timestamp_field = self.timestamp_field data_source_proto.request_data_options.schema.extend(schema_pb) return data_source_proto def get_table_query_string(self) -> str: raise NotImplementedError @staticmethod def source_datatype_to_feast_value_type() -> Callable[[str], ValueType]: raise NotImplementedError def source_type(self) -> DataSourceProto.SourceType.ValueType: return DataSourceProto.REQUEST_SOURCE @typechecked class KinesisSource(DataSource): """A KinesisSource allows users to register Kinesis streams as data sources.""" def validate(self, config: RepoConfig): raise NotImplementedError def get_table_column_names_and_types( self, config: RepoConfig ) -> Iterable[Tuple[str, str]]: raise NotImplementedError @staticmethod def from_proto(data_source: DataSourceProto): return KinesisSource( name=data_source.name, timestamp_field=data_source.timestamp_field, field_mapping=dict(data_source.field_mapping), record_format=StreamFormat.from_proto( data_source.kinesis_options.record_format ), region=data_source.kinesis_options.region, stream_name=data_source.kinesis_options.stream_name, created_timestamp_column=data_source.created_timestamp_column, description=data_source.description, tags=dict(data_source.tags), owner=data_source.owner, batch_source=( DataSource.from_proto(data_source.batch_source) if data_source.HasField("batch_source") else None ), ) @staticmethod def source_datatype_to_feast_value_type() -> Callable[[str], ValueType]: raise NotImplementedError def get_table_query_string(self) -> str: raise NotImplementedError def __init__( self, *, name: str, record_format: StreamFormat, region: str, stream_name: str, timestamp_field: Optional[str] = "", created_timestamp_column: Optional[str] = "", field_mapping: Optional[Dict[str, str]] = None, description: Optional[str] = "", tags: Optional[Dict[str, str]] = None, owner: Optional[str] = "", batch_source: Optional[DataSource] = None, ): """ Args: name: The unique name of the Kinesis source. record_format: The record format of the Kinesis stream. region: The AWS region of the Kinesis stream. stream_name: The name of the Kinesis stream. timestamp_field: Event timestamp field used for point-in-time joins of feature values. created_timestamp_column: Timestamp column indicating when the row was created, used for deduplicating rows. field_mapping: A dictionary mapping of column names in this data source to feature names in a feature table or view. Only used for feature columns, not entity or timestamp columns. description: A human-readable description. tags: A dictionary of key-value pairs to store arbitrary metadata. owner: The owner of the Kinesis source, typically the email of the primary maintainer. batch_source: A DataSource backing the Kinesis stream (used for retrieving historical features). """ if record_format is None: raise ValueError("Record format must be specified for kinesis source") super().__init__( name=name, timestamp_field=timestamp_field, created_timestamp_column=created_timestamp_column, field_mapping=field_mapping, description=description, tags=tags, owner=owner, ) self.batch_source = batch_source self.kinesis_options = KinesisOptions( record_format=record_format, region=region, stream_name=stream_name ) def __eq__(self, other): if not isinstance(other, KinesisSource): return False if not super().__eq__(other): return False if ( self.kinesis_options.record_format != other.kinesis_options.record_format or self.kinesis_options.region != other.kinesis_options.region or self.kinesis_options.stream_name != other.kinesis_options.stream_name ): return False return True def __hash__(self): return super().__hash__() def _to_proto_impl(self) -> DataSourceProto: data_source_proto = DataSourceProto( name=self.name, type=DataSourceProto.STREAM_KINESIS, field_mapping=self.field_mapping, kinesis_options=self.kinesis_options.to_proto(), description=self.description, tags=self.tags, owner=self.owner, ) data_source_proto.timestamp_field = self.timestamp_field data_source_proto.created_timestamp_column = self.created_timestamp_column if self.batch_source: data_source_proto.batch_source.MergeFrom(self.batch_source.to_proto()) return data_source_proto def source_type(self) -> DataSourceProto.SourceType.ValueType: return DataSourceProto.STREAM_KINESIS class PushMode(enum.Enum): ONLINE = 1 OFFLINE = 2 ONLINE_AND_OFFLINE = 3 @typechecked class PushSource(DataSource): """ A source that can be used to ingest features on request """ # TODO(adchia): consider adding schema here in case where Feast manages pushing events to the offline store # TODO(adchia): consider a "mode" to support pushing raw vs transformed events batch_source: Optional[DataSource] = None upstream_feature_view_names: List[str] = [] def __init__( self, *, name: str, batch_source: Optional[DataSource] = None, upstream_feature_view_names: Optional[Sequence[Union[Any, str]]] = None, description: Optional[str] = "", tags: Optional[Dict[str, str]] = None, owner: Optional[str] = "", ): """ Creates a PushSource object. Args: name: Name of the push source. batch_source (optional): The batch source that backs this push source. It's used when materializing from the offline store to the online store, and when retrieving historical features. upstream_feature_view_names (optional): Sequence of upstream FeatureView/LabelView objects or names consumed by the external process feeding this push source. Represents external pipeline lineage metadata and does not trigger Feast-managed DAG execution. description (optional): A human-readable description. tags (optional): A dictionary of key-value pairs to store arbitrary metadata. owner (optional): The owner of the data source, typically the email of the primary maintainer. """ super().__init__(name=name, description=description, tags=tags, owner=owner) self.batch_source = batch_source normalized_upstream_names: List[str] = [] if upstream_feature_view_names is not None: for item in upstream_feature_view_names: if hasattr(item, "name"): name_val = item.name if not isinstance(name_val, str) or not name_val.strip(): raise ValueError( f"Upstream feature view object {item} has an invalid or empty name" ) normalized_upstream_names.append(name_val.strip()) elif isinstance(item, str): if not item.strip(): raise ValueError("Upstream feature view name cannot be empty") normalized_upstream_names.append(item.strip()) else: raise TypeError( f"Unsupported type for upstream feature view: {type(item)}. " "Expected str or object with a 'name' attribute (e.g. FeatureView, LabelView)." ) self.upstream_feature_view_names = normalized_upstream_names def __eq__(self, other): if not isinstance(other, PushSource): return False if not super().__eq__(other): return False if self.batch_source != other.batch_source: return False if self.upstream_feature_view_names != other.upstream_feature_view_names: return False return True def __hash__(self): return super().__hash__() def validate(self, config: RepoConfig): raise NotImplementedError def get_table_column_names_and_types( self, config: RepoConfig ) -> Iterable[Tuple[str, str]]: raise NotImplementedError @staticmethod def from_proto(data_source: DataSourceProto): batch_source = ( DataSource.from_proto(data_source.batch_source) if data_source.HasField("batch_source") else None ) upstream_feature_view_names = ( list(data_source.push_options.upstream_feature_view_names) if data_source.HasField("push_options") else [] ) return PushSource( name=data_source.name, batch_source=batch_source, upstream_feature_view_names=upstream_feature_view_names, description=data_source.description, tags=dict(data_source.tags), owner=data_source.owner, ) def _to_proto_impl(self) -> DataSourceProto: data_source_proto = DataSourceProto( name=self.name, type=DataSourceProto.PUSH_SOURCE, description=self.description, tags=self.tags, owner=self.owner, ) data_source_proto.push_options.upstream_feature_view_names.extend( self.upstream_feature_view_names ) # Only set timestamp fields if we have a batch source and this PushSource doesn't have its own fields if self.batch_source and not ( |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |