Buckets:

download
raw
15.5 kB
"""
Common environment vars / settings
"""
import logging
import os
import re
import warnings
from dataclasses import dataclass
from pathlib import Path
from urllib.parse import urlparse, urlunparse
from urllib.request import url2pathname
from pydantic import Field, field_validator, model_validator
from pydantic_core.core_schema import ValidationInfo
from pydantic_settings import BaseSettings
from extralit_server.constants import (
DATABASE_POSTGRESQL,
DATABASE_SQLITE,
DEFAULT_DATABASE_POSTGRESQL_MAX_OVERFLOW,
DEFAULT_DATABASE_POSTGRESQL_POOL_SIZE,
DEFAULT_DATABASE_POSTGRESQL_SCHEME,
DEFAULT_DATABASE_SQLITE_TIMEOUT,
DEFAULT_LABEL_SELECTION_OPTIONS_MAX_ITEMS,
DEFAULT_SPAN_OPTIONS_MAX_ITEMS,
SEARCH_ENGINE_ELASTICSEARCH,
SEARCH_ENGINE_OPENSEARCH,
)
@dataclass(frozen=True)
class StorageRoot:
"""`settings.storage_url` parsed: where the bucket ends and the key prefix begins."""
scheme: str
endpoint: str | None
bucket: str | None
prefix: str
local_path: Path | None
@property
def remote(self) -> bool:
return self.scheme != "file"
def parse_storage_url(url: str) -> StorageRoot:
parsed = urlparse(url)
# Never echo the URL once it may carry a secret: this message reaches logs and the doctor.
if parsed.username or parsed.password:
raise ValueError(
"Credentials must not be embedded in the storage URL. "
"Use EXTRALIT_S3_ACCESS_KEY and EXTRALIT_S3_SECRET_KEY."
)
if parsed.scheme == "file":
if parsed.netloc not in ("", "localhost"):
raise ValueError(f"file:// storage URL must be an absolute local path: {url}")
return StorageRoot("file", None, None, "", Path(url2pathname(parsed.path)))
if parsed.scheme == "s3":
bucket, prefix = parsed.netloc, parsed.path.strip("/")
endpoint = None
elif parsed.scheme in ("http", "https"):
bucket, _, prefix = parsed.path.strip("/").partition("/")
endpoint = f"{parsed.scheme}://{parsed.netloc}"
else:
raise ValueError(f"Unsupported storage URL scheme {parsed.scheme!r}: {url}")
if not bucket:
raise ValueError(f"Storage URL needs a bucket segment, e.g. {url.rstrip('/')}/extralit")
return StorageRoot(parsed.scheme, endpoint, bucket, prefix, None)
class Settings(BaseSettings):
"""
Main application settings. The pydantic BaseSettings class makes
accessible environment variables by setting attributes.
See <https://pydantic-docs.helpmanual.io/usage/settings/>
only_bulk_api: (ONLY_BULK_API env var)
If True, activate only bulk and search endpoints
elasticseach: (ELASTICSEARCH env var)
The elasticsearch endpoint for datasets persistence
cors_origins: (CORS_ORIGINS env var)
List of host patterns for CORS origin access
docs_enabled: True
If True, enable openapi docs endpoint at /api/docs
es_records_index_shards:
Configures the number of shards for dataset records index creation. Default=1
es_records_index_replicas:
Configures the number of shard replicas for dataset records index creation. Default=0
disable_es_index_template_creation: (DISABLE_ES_INDEX_TEMPLATE_CREATION env var)
Allowing advanced users to create their own es index settings and mappings. Default=False
"""
__LOGGER__ = logging.getLogger(__name__)
__DATASETS_INDEX_NAME__ = "ar.datasets"
__DATASETS_RECORDS_INDEX_NAME__ = "ar.dataset.{}"
home_path: str | None = Field(
None,
validate_default=True,
description="The home path where extralit related files will be stored",
)
base_url: str | None = Field(
None,
validate_default=True,
description="The default base url where server will be deployed",
)
database_url: str | None = Field(
None,
validate_default=True,
description="The database url that extralit will use as data store",
)
# https://docs.sqlalchemy.org/en/20/core/engines.html#sqlalchemy.create_engine.params.pool_size
database_postgresql_pool_size: int | None = Field(
default=DEFAULT_DATABASE_POSTGRESQL_POOL_SIZE,
description="The number of connections to keep open inside the database connection pool",
)
# https://docs.sqlalchemy.org/en/20/core/engines.html#sqlalchemy.create_engine.params.max_overflow
database_postgresql_max_overflow: int | None = Field(
default=DEFAULT_DATABASE_POSTGRESQL_MAX_OVERFLOW,
description="The number of connections that can be opened above and beyond the pool_size setting",
)
# https://docs.python.org/3/library/sqlite3.html#sqlite3.connect
database_sqlite_timeout: int | None = Field(
default=DEFAULT_DATABASE_SQLITE_TIMEOUT,
description="SQLite database connection timeout in seconds",
)
database_postgresql_pool_pre_ping: bool = Field(
default=True,
description="Enable connection validation before use for PostgreSQL",
)
database_postgresql_pool_recycle: int = Field(
default=300,
description="Number of seconds to recycle connections in PostgreSQL pool",
)
database_postgresql_pool_timeout: int = Field(
default=30,
description="Number of seconds to wait for a connection from the pool",
)
database_postgresql_connect_timeout: int = Field(
default=30,
description="PostgreSQL connection establishment timeout in seconds",
)
database_postgresql_command_timeout: int = Field(
default=30,
description="PostgreSQL query execution timeout in seconds",
)
# Connection pooler compatibility mode (for Supabase, PgBouncer, etc.)
database_postgresql_pooler_mode: bool = Field(
default=False,
description="Enable compatibility mode for external connection poolers (disables prepared statements)",
)
storage_url: str | None = Field(
default=None,
validate_default=True,
description="Root of object storage; every workspace is a prefix under it. "
"`file:///path` (default `{home_path}/storage`), `s3://bucket[/prefix]`, or "
"`http(s)://host[:port]/bucket[/prefix]` for MinIO, R2 and other S3-compatible endpoints.",
)
s3_access_key: str | None = Field(default=None, description="The access key for the S3 storage")
s3_secret_key: str | None = Field(default=None, description="The secret key for the S3 storage")
s3_region: str | None = Field(default=None, description="The region for the S3 storage")
lancedb_uri: str | None = Field(
default=None,
validate_default=True,
description="URI for the LanceDB index store (see ENG-36). Defaults to `{home_path}/lance`. "
"A local path works on the compose named volume and HF-Spaces persistent storage; "
"an s3:// URI is accepted by lancedb.connect but unsupported/unvalidated for now.",
)
extralit_url: str | None = Field(default=None, description="The extralit server url for LLM serving endpoint")
elasticsearch: str = "http://localhost:9200"
elasticsearch_ssl_verify: bool = True
elasticsearch_ca_path: str | None = None
cors_origins: list[str] = ["*"]
redis_url: str = "redis://localhost:6379/0"
redis_use_cluster: bool = False
docs_enabled: bool = True
# Analyzer configuration
es_records_index_shards: int = 1
es_records_index_replicas: int = 0
es_mapping_total_fields_limit: int = 2000
search_engine: str = SEARCH_ENGINE_ELASTICSEARCH
# Questions settings
label_selection_options_max_items: int = Field(
default=DEFAULT_LABEL_SELECTION_OPTIONS_MAX_ITEMS,
description="Max number of label options for questions of type `label_selection` and `multi_label_selection`",
)
span_options_max_items: int = Field(
default=DEFAULT_SPAN_OPTIONS_MAX_ITEMS,
description="Max number of label options for questions of type `span`",
)
# Hugging Face settings
show_huggingface_space_persistent_storage_warning: bool = Field(
default=True,
description="If True, show a warning when Hugging Face space persistent storage is disabled",
)
# Hugging Face telemetry
enable_telemetry: bool = Field(
default=True,
validate_default=True,
description="The telemetry configuration for Hugging Face hub telemetry. ",
)
enable_share_your_progress: bool = Field(
default=False,
description="Share your progress feature for community initiatives. Default=False",
)
# See also the telemetry.py module
@field_validator("enable_telemetry", mode="before")
@classmethod
def set_enable_telemetry(cls, enable_telemetry: bool) -> bool:
if os.getenv("HF_HUB_DISABLE_TELEMETRY") == "1" or os.getenv("HF_HUB_OFFLINE") == "1":
enable_telemetry = False
if os.getenv("EXTRALIT_ENABLE_TELEMETRY") == "0":
os.environ["HF_HUB_DISABLE_TELEMETRY"] = "1"
warnings.warn(
"environment vairbale EXTRALIT_ENABLE_TELEMETRY is deprecated, use HF_HUB_DISABLE_TELEMETRY or HF_HUB_OFFLINE instead.",
stacklevel=2,
)
enable_telemetry = False
return enable_telemetry
@field_validator("home_path", mode="before")
@classmethod
def set_home_path_default(cls, home_path: str):
return home_path or os.path.join(Path.home(), ".extralit")
@field_validator("lancedb_uri", mode="before")
@classmethod
def set_lancedb_uri_default(cls, lancedb_uri: str | None, info: ValidationInfo) -> str:
if lancedb_uri:
return lancedb_uri
home_path = info.data.get("home_path") or os.path.join(Path.home(), ".extralit")
return os.path.join(home_path, "lance")
@field_validator("storage_url", mode="before")
@classmethod
def set_storage_url_default(cls, storage_url: str | None, info: ValidationInfo) -> str:
if storage_url:
return storage_url
home_path = info.data.get("home_path") or os.path.join(Path.home(), ".extralit")
return Path(home_path, "storage").as_uri()
@field_validator("base_url")
@classmethod
def normalize_base_url(cls, base_url: str):
if not base_url:
base_url = "/"
if not base_url.startswith("/"):
base_url = "/" + base_url
if not base_url.endswith("/"):
base_url += "/"
return base_url
@field_validator("database_url", mode="before")
@classmethod
def set_database_url(cls, database_url: str, info: ValidationInfo) -> str:
if not database_url:
home_path = info.data.get("home_path")
sqlite_file = os.path.join(home_path, "extralit.db")
return f"sqlite+aiosqlite:///{sqlite_file}?check_same_thread=False"
if "sqlite" in database_url:
regex = re.compile(r"sqlite(?!\+aiosqlite)")
if regex.match(database_url):
warnings.warn(
"From version 1.14.0, Extralit will use `aiosqlite` as default SQLite driver. The protocol in the"
" provided database URL has been automatically replaced from `sqlite` to `sqlite+aiosqlite`."
" Please, update your database URL to use `sqlite+aiosqlite` protocol.",
stacklevel=2,
)
return re.sub(regex, "sqlite+aiosqlite", database_url)
if "postgres" in database_url:
parsed_url = urlparse(database_url)
if parsed_url.scheme.__contains__("postgres") and not parsed_url.scheme.__contains__("asyncpg"):
# warnings.warn(
# "From version 1.14.0, Extralit will use `asyncpg` as default PostgreSQL driver. The protocol in the"
# " provided database URL has been automatically replaced from `postgresql` to `postgresql+asyncpg`."
# " Please, update your database URL to use `postgresql+asyncpg` protocol.",
# stacklevel=2,
# )
database_url = urlunparse(parsed_url._replace(scheme=DEFAULT_DATABASE_POSTGRESQL_SCHEME))
if not database_url.startswith("postgresql+asyncpg://"):
raise ValueError(
f"Invalid database URL format. Expected: 'postgresql+asyncpg://...', given '{parsed_url.scheme}'"
)
return database_url
@model_validator(mode="after")
@classmethod
def create_home_path(cls, instance: "Settings") -> "Settings":
Path(instance.home_path).mkdir(parents=True, exist_ok=True)
return instance
@model_validator(mode="after")
@classmethod
def validate_s3_config(cls, instance: "Settings") -> "Settings":
"""Keys come as a pair or not at all; without them obstore falls back to the AWS credential chain."""
if bool(instance.s3_access_key) != bool(instance.s3_secret_key):
raise ValueError("s3_access_key and s3_secret_key must be set together")
parse_storage_url(instance.storage_url)
return instance
@property
def storage_root(self) -> StorageRoot:
return parse_storage_url(self.storage_url)
@property
def database_engine_args(self) -> dict:
if self.database_is_sqlite:
return {
"connect_args": {
"timeout": self.database_sqlite_timeout,
},
}
if self.database_is_postgresql:
connect_args = {
"server_settings": {
"application_name": "extralit-server",
},
"command_timeout": self.database_postgresql_command_timeout,
}
# For external connection poolers (Supabase, PgBouncer), disable prepared statements
# This is required for Transaction mode pooling
if self.database_postgresql_pooler_mode:
connect_args["prepared_statement_cache_size"] = 0
connect_args["statement_cache_size"] = 0
return {
"pool_size": self.database_postgresql_pool_size,
"max_overflow": self.database_postgresql_max_overflow,
"pool_pre_ping": self.database_postgresql_pool_pre_ping,
"pool_recycle": self.database_postgresql_pool_recycle,
"pool_timeout": self.database_postgresql_pool_timeout,
# Use LIFO to reuse recently-used connections (better for connection poolers)
"pool_use_lifo": True,
"connect_args": connect_args,
}
return {}
@property
def database_is_sqlite(self) -> bool:
if self.database_url is None:
return False
return self.database_url.lower().startswith(DATABASE_SQLITE)
@property
def database_is_postgresql(self) -> bool:
if self.database_url is None:
return False
return self.database_url.lower().startswith(DATABASE_POSTGRESQL)
@property
def search_engine_is_elasticsearch(self) -> bool:
return self.search_engine == SEARCH_ENGINE_ELASTICSEARCH
@property
def search_engine_is_opensearch(self) -> bool:
return self.search_engine == SEARCH_ENGINE_OPENSEARCH
class Config:
env_prefix = "EXTRALIT_"
settings = Settings()

Xet Storage Details

Size:
15.5 kB
·
Xet hash:
c81458c460fe27ad308aee90a1920a974d62b7d76ebe764860a93f3787e841f1

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.