|
| 1 | +"""API configuration.""" |
| 2 | +import os |
| 3 | +import ssl |
| 4 | +from typing import Any, Dict, Set |
| 5 | + |
| 6 | +from opensearchpy import AsyncOpenSearch, OpenSearch |
| 7 | +from stac_fastapi.types.config import ApiSettings |
| 8 | + |
| 9 | + |
| 10 | +def _es_config() -> Dict[str, Any]: |
| 11 | + # Determine the scheme (http or https) |
| 12 | + use_ssl = os.getenv("ES_USE_SSL", "true").lower() == "true" |
| 13 | + scheme = "https" if use_ssl else "http" |
| 14 | + |
| 15 | + # Configure the hosts parameter with the correct scheme |
| 16 | + hosts = [f"{scheme}://{os.getenv('ES_HOST')}:{os.getenv('ES_PORT')}"] |
| 17 | + |
| 18 | + # Initialize the configuration dictionary |
| 19 | + config = { |
| 20 | + "hosts": hosts, |
| 21 | + "headers": {"accept": "application/vnd.elasticsearch+json; compatible-with=7"}, |
| 22 | + } |
| 23 | + |
| 24 | + # Explicitly exclude SSL settings when not using SSL |
| 25 | + if not use_ssl: |
| 26 | + return config |
| 27 | + |
| 28 | + # Include SSL settings if using https |
| 29 | + config["ssl_version"] = ssl.TLSVersion.TLSv1_3 # type: ignore |
| 30 | + config["verify_certs"] = os.getenv("ES_VERIFY_CERTS", "true").lower() != "false" # type: ignore |
| 31 | + |
| 32 | + # Include CA Certificates if verifying certs |
| 33 | + if config["verify_certs"]: |
| 34 | + config["ca_certs"] = os.getenv( |
| 35 | + "CURL_CA_BUNDLE", "/etc/ssl/certs/ca-certificates.crt" |
| 36 | + ) |
| 37 | + |
| 38 | + # Handle authentication |
| 39 | + if (u := os.getenv("ES_USER")) and (p := os.getenv("ES_PASS")): |
| 40 | + config["http_auth"] = (u, p) |
| 41 | + |
| 42 | + return config |
| 43 | + |
| 44 | + |
| 45 | +_forbidden_fields: Set[str] = {"type"} |
| 46 | + |
| 47 | + |
| 48 | +class ElasticsearchSettings(ApiSettings): |
| 49 | + """API settings.""" |
| 50 | + |
| 51 | + # Fields which are defined by STAC but not included in the database model |
| 52 | + forbidden_fields: Set[str] = _forbidden_fields |
| 53 | + indexed_fields: Set[str] = {"datetime"} |
| 54 | + |
| 55 | + @property |
| 56 | + def create_client(self): |
| 57 | + """Create es client.""" |
| 58 | + return OpenSearch(**_es_config()) |
| 59 | + |
| 60 | + |
| 61 | +class AsyncElasticsearchSettings(ApiSettings): |
| 62 | + """API settings.""" |
| 63 | + |
| 64 | + # Fields which are defined by STAC but not included in the database model |
| 65 | + forbidden_fields: Set[str] = _forbidden_fields |
| 66 | + indexed_fields: Set[str] = {"datetime"} |
| 67 | + |
| 68 | + @property |
| 69 | + def create_client(self): |
| 70 | + """Create async elasticsearch client.""" |
| 71 | + return AsyncOpenSearch(**_es_config()) |
0 commit comments