|
| 1 | +import base64 |
| 2 | +import json |
| 3 | +import logging |
| 4 | +from concurrent.futures import ThreadPoolExecutor, wait |
| 5 | +from dataclasses import dataclass |
| 6 | +from datetime import datetime |
| 7 | +from typing import Callable, List, Literal, Optional, Sequence, Union |
| 8 | + |
| 9 | +import boto3 |
| 10 | +from pydantic import StrictStr |
| 11 | +from tqdm import tqdm |
| 12 | + |
| 13 | +from feast.batch_feature_view import BatchFeatureView |
| 14 | +from feast.constants import FEATURE_STORE_YAML_ENV_NAME |
| 15 | +from feast.entity import Entity |
| 16 | +from feast.feature_view import FeatureView |
| 17 | +from feast.infra.materialization.batch_materialization_engine import ( |
| 18 | + BatchMaterializationEngine, |
| 19 | + MaterializationJob, |
| 20 | + MaterializationJobStatus, |
| 21 | + MaterializationTask, |
| 22 | +) |
| 23 | +from feast.infra.offline_stores.offline_store import OfflineStore |
| 24 | +from feast.infra.online_stores.online_store import OnlineStore |
| 25 | +from feast.registry import BaseRegistry |
| 26 | +from feast.repo_config import FeastConfigBaseModel, RepoConfig |
| 27 | +from feast.stream_feature_view import StreamFeatureView |
| 28 | +from feast.utils import _get_column_names |
| 29 | +from feast.version import get_version |
| 30 | + |
| 31 | +DEFAULT_BATCH_SIZE = 10_000 |
| 32 | + |
| 33 | +logger = logging.getLogger(__name__) |
| 34 | + |
| 35 | + |
| 36 | +class LambdaMaterializationEngineConfig(FeastConfigBaseModel): |
| 37 | + """Batch Materialization Engine config for lambda based engine""" |
| 38 | + |
| 39 | + type: Literal["lambda"] = "lambda" |
| 40 | + """ Type selector""" |
| 41 | + |
| 42 | + materialization_image: StrictStr |
| 43 | + """ The URI of a container image in the Amazon ECR registry, which should be used for materialization. """ |
| 44 | + |
| 45 | + lambda_role: StrictStr |
| 46 | + """ Role that should be used by the materialization lambda """ |
| 47 | + |
| 48 | + |
| 49 | +@dataclass |
| 50 | +class LambdaMaterializationJob(MaterializationJob): |
| 51 | + def __init__(self, job_id: str, status: MaterializationJobStatus) -> None: |
| 52 | + super().__init__() |
| 53 | + self._job_id: str = job_id |
| 54 | + self._status = status |
| 55 | + self._error = None |
| 56 | + |
| 57 | + def status(self) -> MaterializationJobStatus: |
| 58 | + return self._status |
| 59 | + |
| 60 | + def error(self) -> Optional[BaseException]: |
| 61 | + return self._error |
| 62 | + |
| 63 | + def should_be_retried(self) -> bool: |
| 64 | + return False |
| 65 | + |
| 66 | + def job_id(self) -> str: |
| 67 | + return self._job_id |
| 68 | + |
| 69 | + def url(self) -> Optional[str]: |
| 70 | + return None |
| 71 | + |
| 72 | + |
| 73 | +class LambdaMaterializationEngine(BatchMaterializationEngine): |
| 74 | + """ |
| 75 | + WARNING: This engine should be considered "Alpha" functionality. |
| 76 | + """ |
| 77 | + |
| 78 | + def update( |
| 79 | + self, |
| 80 | + project: str, |
| 81 | + views_to_delete: Sequence[ |
| 82 | + Union[BatchFeatureView, StreamFeatureView, FeatureView] |
| 83 | + ], |
| 84 | + views_to_keep: Sequence[ |
| 85 | + Union[BatchFeatureView, StreamFeatureView, FeatureView] |
| 86 | + ], |
| 87 | + entities_to_delete: Sequence[Entity], |
| 88 | + entities_to_keep: Sequence[Entity], |
| 89 | + ): |
| 90 | + # This should be setting up the lambda function. |
| 91 | + r = self.lambda_client.create_function( |
| 92 | + FunctionName=self.lambda_name, |
| 93 | + PackageType="Image", |
| 94 | + Role=self.repo_config.batch_engine.lambda_role, |
| 95 | + Code={"ImageUri": self.repo_config.batch_engine.materialization_image}, |
| 96 | + Timeout=600, |
| 97 | + Tags={ |
| 98 | + "feast-owned": "True", |
| 99 | + "project": project, |
| 100 | + "feast-sdk-version": get_version(), |
| 101 | + }, |
| 102 | + ) |
| 103 | + logger.info("Creating lambda function %s, %s", self.lambda_name, r) |
| 104 | + |
| 105 | + logger.info("Waiting for function %s to be active", self.lambda_name) |
| 106 | + waiter = self.lambda_client.get_waiter("function_active") |
| 107 | + waiter.wait(FunctionName=self.lambda_name) |
| 108 | + |
| 109 | + def teardown_infra( |
| 110 | + self, |
| 111 | + project: str, |
| 112 | + fvs: Sequence[Union[BatchFeatureView, StreamFeatureView, FeatureView]], |
| 113 | + entities: Sequence[Entity], |
| 114 | + ): |
| 115 | + # This should be tearing down the lambda function. |
| 116 | + logger.info("Tearing down lambda %s", self.lambda_name) |
| 117 | + r = self.lambda_client.delete_function(FunctionName=self.lambda_name) |
| 118 | + logger.info("Finished tearing down lambda %s: %s", self.lambda_name, r) |
| 119 | + |
| 120 | + def __init__( |
| 121 | + self, |
| 122 | + *, |
| 123 | + repo_config: RepoConfig, |
| 124 | + offline_store: OfflineStore, |
| 125 | + online_store: OnlineStore, |
| 126 | + **kwargs, |
| 127 | + ): |
| 128 | + super().__init__( |
| 129 | + repo_config=repo_config, |
| 130 | + offline_store=offline_store, |
| 131 | + online_store=online_store, |
| 132 | + **kwargs, |
| 133 | + ) |
| 134 | + repo_path = self.repo_config.repo_path |
| 135 | + assert repo_path |
| 136 | + feature_store_path = repo_path / "feature_store.yaml" |
| 137 | + self.feature_store_base64 = str( |
| 138 | + base64.b64encode(bytes(feature_store_path.read_text(), "UTF-8")), "UTF-8" |
| 139 | + ) |
| 140 | + |
| 141 | + self.lambda_name = f"feast-materialize-{self.repo_config.project}" |
| 142 | + if len(self.lambda_name) > 64: |
| 143 | + self.lambda_name = self.lambda_name[:64] |
| 144 | + self.lambda_client = boto3.client("lambda") |
| 145 | + |
| 146 | + def materialize( |
| 147 | + self, registry, tasks: List[MaterializationTask] |
| 148 | + ) -> List[MaterializationJob]: |
| 149 | + return [ |
| 150 | + self._materialize_one( |
| 151 | + registry, |
| 152 | + task.feature_view, |
| 153 | + task.start_time, |
| 154 | + task.end_time, |
| 155 | + task.project, |
| 156 | + task.tqdm_builder, |
| 157 | + ) |
| 158 | + for task in tasks |
| 159 | + ] |
| 160 | + |
| 161 | + def _materialize_one( |
| 162 | + self, |
| 163 | + registry: BaseRegistry, |
| 164 | + feature_view: Union[BatchFeatureView, StreamFeatureView, FeatureView], |
| 165 | + start_date: datetime, |
| 166 | + end_date: datetime, |
| 167 | + project: str, |
| 168 | + tqdm_builder: Callable[[int], tqdm], |
| 169 | + ): |
| 170 | + entities = [] |
| 171 | + for entity_name in feature_view.entities: |
| 172 | + entities.append(registry.get_entity(entity_name, project)) |
| 173 | + |
| 174 | + ( |
| 175 | + join_key_columns, |
| 176 | + feature_name_columns, |
| 177 | + timestamp_field, |
| 178 | + created_timestamp_column, |
| 179 | + ) = _get_column_names(feature_view, entities) |
| 180 | + |
| 181 | + job_id = f"{feature_view.name}-{start_date}-{end_date}" |
| 182 | + |
| 183 | + offline_job = self.offline_store.pull_latest_from_table_or_query( |
| 184 | + config=self.repo_config, |
| 185 | + data_source=feature_view.batch_source, |
| 186 | + join_key_columns=join_key_columns, |
| 187 | + feature_name_columns=feature_name_columns, |
| 188 | + timestamp_field=timestamp_field, |
| 189 | + created_timestamp_column=created_timestamp_column, |
| 190 | + start_date=start_date, |
| 191 | + end_date=end_date, |
| 192 | + ) |
| 193 | + |
| 194 | + paths = offline_job.to_remote_storage() |
| 195 | + max_workers = len(paths) if len(paths) <= 20 else 20 |
| 196 | + executor = ThreadPoolExecutor(max_workers=max_workers) |
| 197 | + futures = [] |
| 198 | + |
| 199 | + for path in paths: |
| 200 | + payload = { |
| 201 | + FEATURE_STORE_YAML_ENV_NAME: self.feature_store_base64, |
| 202 | + "view_name": feature_view.name, |
| 203 | + "view_type": "batch", |
| 204 | + "path": path, |
| 205 | + } |
| 206 | + # Invoke a lambda to materialize this file. |
| 207 | + |
| 208 | + logger.info("Invoking materialization for %s", path) |
| 209 | + futures.append( |
| 210 | + executor.submit( |
| 211 | + self.lambda_client.invoke, |
| 212 | + FunctionName=self.lambda_name, |
| 213 | + InvocationType="RequestResponse", |
| 214 | + Payload=json.dumps(payload), |
| 215 | + ) |
| 216 | + ) |
| 217 | + |
| 218 | + done, not_done = wait(futures) |
| 219 | + logger.info("Done: %s Not Done: %s", done, not_done) |
| 220 | + for f in done: |
| 221 | + response = f.result() |
| 222 | + output = json.loads(response["Payload"].read()) |
| 223 | + |
| 224 | + logger.info( |
| 225 | + f"Ingested task; request id {response['ResponseMetadata']['RequestId']}, " |
| 226 | + f"rows written: {output['written_rows']}" |
| 227 | + ) |
| 228 | + |
| 229 | + for f in not_done: |
| 230 | + response = f.result() |
| 231 | + logger.error(f"Ingestion failed: {response}") |
| 232 | + |
| 233 | + return LambdaMaterializationJob( |
| 234 | + job_id=job_id, |
| 235 | + status=MaterializationJobStatus.SUCCEEDED |
| 236 | + if not not_done |
| 237 | + else MaterializationJobStatus.ERROR, |
| 238 | + ) |
0 commit comments