|
| 1 | +import json |
| 2 | +from contextlib import asynccontextmanager, contextmanager |
| 3 | +from dataclasses import dataclass |
| 4 | +from typing import TYPE_CHECKING, Any, AsyncGenerator, Generator, Optional |
| 5 | + |
| 6 | +from pydantic import Field, Secret, model_validator |
| 7 | + |
| 8 | +from unstructured_ingest.error import DestinationConnectionError |
| 9 | +from unstructured_ingest.utils.data_prep import batch_generator |
| 10 | +from unstructured_ingest.utils.dep_check import requires_dependencies |
| 11 | +from unstructured_ingest.v2.interfaces import ( |
| 12 | + AccessConfig, |
| 13 | + ConnectionConfig, |
| 14 | + FileData, |
| 15 | + Uploader, |
| 16 | + UploaderConfig, |
| 17 | +) |
| 18 | +from unstructured_ingest.v2.logger import logger |
| 19 | +from unstructured_ingest.v2.processes.connector_registry import DestinationRegistryEntry |
| 20 | + |
| 21 | +if TYPE_CHECKING: |
| 22 | + from redis.asyncio import Redis |
| 23 | + |
| 24 | +import asyncio |
| 25 | + |
| 26 | +CONNECTOR_TYPE = "redis" |
| 27 | +SERVER_API_VERSION = "1" |
| 28 | + |
| 29 | + |
| 30 | +class RedisAccessConfig(AccessConfig): |
| 31 | + uri: Optional[str] = Field( |
| 32 | + default=None, description="If not anonymous, use this uri, if specified." |
| 33 | + ) |
| 34 | + password: Optional[str] = Field( |
| 35 | + default=None, description="If not anonymous, use this password, if specified." |
| 36 | + ) |
| 37 | + |
| 38 | + |
| 39 | +class RedisConnectionConfig(ConnectionConfig): |
| 40 | + access_config: Secret[RedisAccessConfig] = Field( |
| 41 | + default=RedisAccessConfig(), validate_default=True |
| 42 | + ) |
| 43 | + host: Optional[str] = Field( |
| 44 | + default=None, description="Hostname or IP address of a Redis instance to connect to." |
| 45 | + ) |
| 46 | + database: int = Field(default=0, description="Database index to connect to.") |
| 47 | + port: int = Field(default=6379, description="port used to connect to database.") |
| 48 | + username: Optional[str] = Field( |
| 49 | + default=None, description="Username used to connect to database." |
| 50 | + ) |
| 51 | + ssl: bool = Field(default=True, description="Whether the connection should use SSL encryption.") |
| 52 | + connector_type: str = Field(default=CONNECTOR_TYPE, init=False) |
| 53 | + |
| 54 | + @model_validator(mode="after") |
| 55 | + def validate_host_or_url(self) -> "RedisConnectionConfig": |
| 56 | + if not self.access_config.get_secret_value().uri and not self.host: |
| 57 | + raise ValueError("Please pass a hostname either directly or through uri") |
| 58 | + return self |
| 59 | + |
| 60 | + @requires_dependencies(["redis"], extras="redis") |
| 61 | + @asynccontextmanager |
| 62 | + async def create_async_client(self) -> AsyncGenerator["Redis", None]: |
| 63 | + from redis.asyncio import Redis, from_url |
| 64 | + |
| 65 | + access_config = self.access_config.get_secret_value() |
| 66 | + |
| 67 | + options = { |
| 68 | + "host": self.host, |
| 69 | + "port": self.port, |
| 70 | + "db": self.database, |
| 71 | + "ssl": self.ssl, |
| 72 | + "username": self.username, |
| 73 | + } |
| 74 | + |
| 75 | + if access_config.password: |
| 76 | + options["password"] = access_config.password |
| 77 | + |
| 78 | + if access_config.uri: |
| 79 | + async with from_url(access_config.uri) as client: |
| 80 | + yield client |
| 81 | + else: |
| 82 | + async with Redis(**options) as client: |
| 83 | + yield client |
| 84 | + |
| 85 | + @requires_dependencies(["redis"], extras="redis") |
| 86 | + @contextmanager |
| 87 | + def create_client(self) -> Generator["Redis", None, None]: |
| 88 | + from redis import Redis, from_url |
| 89 | + |
| 90 | + access_config = self.access_config.get_secret_value() |
| 91 | + |
| 92 | + options = { |
| 93 | + "host": self.host, |
| 94 | + "port": self.port, |
| 95 | + "db": self.database, |
| 96 | + "ssl": self.ssl, |
| 97 | + "username": self.username, |
| 98 | + } |
| 99 | + |
| 100 | + if access_config.password: |
| 101 | + options["password"] = access_config.password |
| 102 | + |
| 103 | + if access_config.uri: |
| 104 | + with from_url(access_config.uri) as client: |
| 105 | + yield client |
| 106 | + else: |
| 107 | + with Redis(**options) as client: |
| 108 | + yield client |
| 109 | + |
| 110 | + |
| 111 | +class RedisUploaderConfig(UploaderConfig): |
| 112 | + batch_size: int = Field(default=100, description="Number of records per batch") |
| 113 | + |
| 114 | + |
| 115 | +@dataclass |
| 116 | +class RedisUploader(Uploader): |
| 117 | + upload_config: RedisUploaderConfig |
| 118 | + connection_config: RedisConnectionConfig |
| 119 | + connector_type: str = CONNECTOR_TYPE |
| 120 | + |
| 121 | + def is_async(self) -> bool: |
| 122 | + return True |
| 123 | + |
| 124 | + def precheck(self) -> None: |
| 125 | + try: |
| 126 | + with self.connection_config.create_client() as client: |
| 127 | + client.ping() |
| 128 | + except Exception as e: |
| 129 | + logger.error(f"failed to validate connection: {e}", exc_info=True) |
| 130 | + raise DestinationConnectionError(f"failed to validate connection: {e}") |
| 131 | + |
| 132 | + async def run_data_async(self, data: list[dict], file_data: FileData, **kwargs: Any) -> None: |
| 133 | + first_element = data[0] |
| 134 | + redis_stack = await self._check_redis_stack(first_element) |
| 135 | + logger.info( |
| 136 | + f"writing {len(data)} objects to destination asynchronously, " |
| 137 | + f"db, {self.connection_config.database}, " |
| 138 | + f"at {self.connection_config.host}", |
| 139 | + ) |
| 140 | + |
| 141 | + batches = list(batch_generator(data, batch_size=self.upload_config.batch_size)) |
| 142 | + await asyncio.gather(*[self._write_batch(batch, redis_stack) for batch in batches]) |
| 143 | + |
| 144 | + async def _write_batch(self, batch: list[dict], redis_stack: bool) -> None: |
| 145 | + async with self.connection_config.create_async_client() as async_client: |
| 146 | + async with async_client.pipeline(transaction=True) as pipe: |
| 147 | + for element in batch: |
| 148 | + element_id = element["element_id"] |
| 149 | + if redis_stack: |
| 150 | + pipe.json().set(element_id, "$", element) |
| 151 | + else: |
| 152 | + pipe.set(element_id, json.dumps(element)) |
| 153 | + await pipe.execute() |
| 154 | + |
| 155 | + @requires_dependencies(["redis"], extras="redis") |
| 156 | + async def _check_redis_stack(self, element: dict) -> bool: |
| 157 | + from redis import exceptions as redis_exceptions |
| 158 | + |
| 159 | + redis_stack = True |
| 160 | + async with self.connection_config.create_async_client() as async_client: |
| 161 | + async with async_client.pipeline(transaction=True) as pipe: |
| 162 | + element_id = element["element_id"] |
| 163 | + try: |
| 164 | + # Redis with stack extension supports JSON type |
| 165 | + await pipe.json().set(element_id, "$", element).execute() |
| 166 | + except redis_exceptions.ResponseError as e: |
| 167 | + message = str(e) |
| 168 | + if "unknown command `JSON.SET`" in message: |
| 169 | + # if this error occurs, Redis server doesn't support JSON type, |
| 170 | + # so save as string type instead |
| 171 | + await pipe.set(element_id, json.dumps(element)).execute() |
| 172 | + redis_stack = False |
| 173 | + else: |
| 174 | + raise e |
| 175 | + return redis_stack |
| 176 | + |
| 177 | + |
| 178 | +redis_destination_entry = DestinationRegistryEntry( |
| 179 | + connection_config=RedisConnectionConfig, |
| 180 | + uploader=RedisUploader, |
| 181 | + uploader_config=RedisUploaderConfig, |
| 182 | +) |
0 commit comments