Skip to content

Consul Client

Overview

The Consul module provides a centralized, lifecycle-managed client for interacting with a HashiCorp Consul agent. This shared client is a fundamental dependency for several other modules that rely on Consul for their operation, including:

How It Works

The ConsulClient is a BaseService that wraps the consul.aio.Consul library. The ConsulClientFactory creates a singleton instance of this client at startup, managing its connection and readiness state.

By using a shared singleton, all other modules are guaranteed to use the same connection pool and configuration, making the system efficient and consistent. The client's lifecycle is managed by the main LifecycleManager, ensuring it connects at startup and disconnects gracefully.

API Reference

nala.athomic.integration.consul.client.ConsulClient

Bases: BaseService

An asynchronous, lifecycle-managed client for interacting with Consul.

This class wraps the consul.aio.Consul client, integrating it into the Athomic service lifecycle. It handles connection setup, readiness checks by verifying a cluster leader, and graceful shutdown. This centralized client is intended to be used as a singleton by other Athomic components that need to interact with Consul, such as service discovery and dynamic configuration providers.

Attributes:

Name Type Description
settings ConsulSettings

The configuration for connecting to the Consul agent.

client Optional[Consul]

The underlying consul.aio.Consul client instance, available after a successful connection.

__init__(settings)

Initializes the ConsulClient.

Parameters:

Name Type Description Default
settings ConsulSettings

The Pydantic model containing Consul connection details.

required

nala.athomic.integration.consul.factory.ConsulClientFactory

A singleton factory to create and provide the ConsulClient instance.

This factory manages a single, shared instance of the ConsulClient. It ensures that the entire application uses the same client, preventing redundant connections and centralizing its creation logic.

clear() classmethod

Clears the cached singleton instance.

This method resets the factory, allowing a new ConsulClient instance to be created on the next create() call. This is essential for ensuring test isolation.

create(settings=None) classmethod

Creates or retrieves the singleton instance of ConsulClient.

On the first call, this method instantiates the client using global or provided settings. Subsequent calls return the cached instance, ensuring a single connection manager is used throughout the application's lifecycle.

Parameters:

Name Type Description Default
settings Optional[ConsulSettings]

Optional Consul settings to use for instantiation, primarily for dependency injection during testing. If None, global settings are used.

None

Returns:

Type Description
ConsulClient

The singleton ConsulClient instance.