Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/Indroic/HexCore/llms.txt

Use this file to discover all available pages before exploring further.

ServerConfig is HexCore’s central Pydantic configuration model. It carries database URLs, Redis settings, CORS rules, the active cache backend, the event bus, repository discovery paths, and optional CQRS wiring — all in one place. LazyConfig is the lazy loader that resolves a ServerConfig instance from your project’s config module at runtime, with environment-variable overrides.

ServerConfig

hexcore.config.ServerConfig Inherits from pydantic.BaseModel with arbitrary_types_allowed=True. All fields have sensible defaults; override only what you need.
from hexcore.config import ServerConfig
from hexcore.infrastructure.cache.cache_backends.redis import RedisCache
from hexcore.infrastructure.events.events_backends.memory import InMemoryEventBus

config = ServerConfig(
    host="0.0.0.0",
    port=8080,
    debug=False,
    async_sql_database_url="postgresql+asyncpg://user:pass@db:5432/mydb",
    redis_uri="redis://redis:6379/0",
    cache_backend=RedisCache(),
    event_bus=InMemoryEventBus(),
)

Project fields

base_dir
Path
default:"Path(\".\")"
Root directory of the project. Used by utilities that need to resolve paths relative to the project root.

Server fields

host
str
default:"\"localhost\""
Bind address for the HTTP server (e.g. "0.0.0.0" for all interfaces).
port
int
default:"8000"
TCP port the server listens on.
debug
bool
default:"True"
Enables debug mode. When True, CORS allow_origins defaults to ["*"].

Database fields

sql_database_url
str
default:"\"sqlite:///./db.sqlite3\""
Synchronous SQLAlchemy database URL. Used by any tooling that requires a synchronous engine (e.g. Alembic migrations).
async_sql_database_url
str
default:"\"sqlite+aiosqlite:///./db.sqlite3\""
Asynchronous SQLAlchemy database URL. Read by get_engine() in the SQLAlchemy session utilities to create the AsyncEngine.
mongo_database_url
str
default:"\"mongodb://localhost:27017\""
Synchronous MongoDB connection string.
async_mongo_database_url
str
default:"\"mongodb+async://localhost:27017\""
Asynchronous MongoDB connection string.
mongo_db_name
str
default:"\"euphoria_db\""
Default MongoDB database name.
mongo_uri
str
default:"\"mongodb://localhost:27017/euphoria_db\""
Full MongoDB URI including the database name. Read by init_beanie_documents() when initialising Beanie.

Redis fields

redis_uri
str
default:"\"redis://localhost:6379/0\""
Full Redis URL. Read by RedisCache and RedisEventBus when creating connections.
redis_host
str
default:"\"localhost\""
Redis host. Available as a convenience field when building the URI programmatically.
redis_port
int
default:"6379"
Redis TCP port.
redis_db
int
default:"0"
Redis logical database index.
redis_cache_duration
int
default:"300"
Default TTL in seconds for RedisCache.set() when no explicit expire is passed.

CORS / security fields

allow_origins
list[str]
default:"[\"*\"] when debug=True"
List of allowed CORS origins. Defaults to ["*"] in debug mode, ["http://localhost:{port}"] in production.
allow_credentials
bool
default:"True"
Whether the browser is allowed to send cookies/credentials in cross-origin requests.
allow_methods
list[str]
default:"[\"*\"]"
HTTP methods allowed in CORS preflight responses.
allow_headers
list[str]
default:"[\"*\"]"
HTTP request headers allowed in CORS preflight responses.

Cache field

cache_backend
ICache
default:"MemoryCache()"
The active cache backend instance. Must implement hexcore.infrastructure.cache.ICache. Swap to RedisCache() for production. See ICache reference.

Event bus field

event_bus
EventBus
default:"InMemoryEventBus()"
The active event bus instance. Defaults to the simple InMemoryEventBus from hexcore.infrastructure.events. For distributed deployments replace with RedisEventBus, PostgresEventBus, or RabbitMQEventBus. See Event Bus Implementations.

Repository discovery field

repository_discovery_paths
set[str]
default:"set()"
Set of Python package paths (dotted module names) that HexCore will scan for BaseSQLAlchemyRepository and BaseBeanieRepository subclasses. When empty, no auto-discovery occurs. Example: {"myapp.infrastructure.repositories"}.

CQRS field

cqrs
Optional[CQRSConfig]
default:"None"
Optional CQRS configuration block. When None, CQRS features are disabled and have no performance impact on non-CQRS services. See CQRSConfig below.

Deprecated

The event_dispatcher field and constructor argument are deprecated aliases for event_bus. HexCore emits a DeprecationWarning when they are used. Migrate to event_bus.

LazyConfig

hexcore.config.LazyConfig Class-level lazy loader that resolves and caches a ServerConfig instance from your project’s configuration module. All resolution is deferred until get_config() is first called.

Resolution priority

When get_config() is called, LazyConfig tries candidate module paths in this order:
PrioritySourceDescription
1HEXCORE_CONFIG_MODULE env varSingle module path, e.g. "myapp.settings"
2HEXCORE_CONFIG_MODULES env varComma-separated list, e.g. "myapp.prod_settings,myapp.settings"
3LazyConfig.set_config_modules(...)Programmatically set list
4Default"config" (looks for config.py in the working directory)
Within each candidate module, LazyConfig looks for:
  1. An attribute named config that is an instance (or subclass) of ServerConfig.
  2. A class named ServerConfig that subclasses the base ServerConfig.
If nothing is found across all candidates, falls back to ServerConfig() (all defaults).

Class methods

set_config_modules(modules: Iterable[str])
None
Sets the list of candidate module paths and clears the cache, forcing re-resolution on the next get_config() call.
LazyConfig.set_config_modules(["myapp.settings", "config"])
clear_cache()
None
Clears the cached ServerConfig instance without changing the candidate list. Useful in tests to force re-resolution between test cases.
LazyConfig.clear_cache()
get_config()
ServerConfig
Resolves and returns the cached ServerConfig instance. Thread-safe for read-heavy workloads; the first call performs the import resolution.
config = LazyConfig.get_config()
print(config.redis_uri)

Typical project setup

# Place at the project root (default candidate "config")
from hexcore.config import ServerConfig
from hexcore.infrastructure.cache.cache_backends.redis import RedisCache
from hexcore.infrastructure.events.events_backends.memory import InMemoryEventBus
from hexcore.application.cqrs.config import CQRSConfig, BusConfig

config = ServerConfig(
    debug=False,
    async_sql_database_url="postgresql+asyncpg://user:pass@db:5432/mydb",
    mongo_uri="mongodb://mongo:27017/mydb",
    redis_uri="redis://redis:6379/0",
    cache_backend=RedisCache(),
    event_bus=InMemoryEventBus(),
    repository_discovery_paths={"myapp.infrastructure.repositories"},
    cqrs=CQRSConfig(
        command_bus=BusConfig(
            middlewares=[
                "hexcore.infrastructure.cqrs.middlewares.TransactionMiddleware",
            ],
        ),
    ),
)

CQRSConfig

hexcore.application.cqrs.config.CQRSConfig Declarative CQRS configuration. Set as ServerConfig.cqrs to enable the CQRS subsystem.
from hexcore.application.cqrs.config import CQRSConfig, BusConfig

cqrs = CQRSConfig(
    enabled=True,
    command_bus=BusConfig(
        middlewares=[
            "hexcore.infrastructure.cqrs.middlewares.TransactionMiddleware",
            "hexcore.infrastructure.cqrs.middlewares.LoggingMiddleware",
        ],
        options={"max_retries": 3},
    ),
    query_bus=BusConfig(),
    event_bus=BusConfig(),
    serializer=None,  # defaults to PydanticSerializer
)
enabled
bool
default:"True"
Master switch for the CQRS subsystem. Setting to False disables all CQRS wiring regardless of other fields.
command_bus
BusConfig
Configuration for the command bus. See BusConfig.
query_bus
BusConfig
default:"BusConfig()"
Configuration for the query bus.
event_bus
BusConfig
default:"BusConfig()"
Configuration for the CQRS event bus (separate from ServerConfig.event_bus).
serializer
Optional[str]
default:"None"
Dotted import path of a custom serialiser class (e.g. "myapp.serializers.MsgPackSerializer"). When None, PydanticSerializer is used.

BusConfig

hexcore.application.cqrs.config.BusConfig Configuration for a single CQRS bus (command, query, or event). Frozen Pydantic model.
backend
Optional[str]
default:"None"
Dotted import path of the bus implementation class (e.g. "hexcore.infrastructure.cqrs.redis_bus.RedisEventBus"). When None, the default in-memory implementation is used.
middlewares
list[str]
default:"[]"
Ordered list of dotted import paths for middleware classes. Middlewares are applied in list order (index 0 runs first, closest to the handler).
options
dict[str, Any]
default:"{}"
Arbitrary key-value options forwarded to the bus backend’s constructor or to individual middlewares.

MiddlewareConfig

hexcore.application.cqrs.config.MiddlewareConfig Configuration for an individual middleware. Frozen Pydantic model.
enabled
bool
default:"True"
When False, the middleware is skipped entirely during pipeline construction.
order
int
default:"0"
Execution order hint. Lower values run closer to the bus entry point (before the handler).
options
dict[str, Any]
default:"{}"
Arbitrary options for the middleware (e.g. {"max_retries": 3}).

Build docs developers (and LLMs) love