> ## Documentation Index
> Fetch the complete documentation index at: https://documentation.sophra.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Client

---
title: SophraClient: Core Service Integration Hub
description: A centralized client for managing connections to Elasticsearch, Redis, and PostgreSQL within the Sophra ecosystem.
---

The SophraClient serves as the cornerstone of the Sophra system, acting as a unified interface for interacting with critical services such as Elasticsearch, Redis, and PostgreSQL. This sophisticated client encapsulates the complexity of managing multiple service connections, providing a streamlined API for other components within the Sophra ecosystem.

At its core, the SophraClient is designed with a focus on reliability, performance, and extensibility. It leverages TypeScript's strong typing system to ensure type safety across service interactions, reducing the potential for runtime errors and improving overall system stability. The client's architecture is built around the principle of dependency injection, allowing for flexible configuration and easy testing.

One of the key architectural decisions in the SophraClient's design is the use of a lazy initialization pattern. Services are only connected when explicitly requested, which optimizes resource utilization and allows for fine-grained control over system startup. This approach is particularly beneficial in a microservices environment where different components may require access to different subsets of services.

Performance is a critical consideration in the SophraClient's implementation. The client incorporates connection pooling for database operations, ensuring efficient reuse of established connections. For Redis interactions, the client utilizes the ioredis library, known for its high performance and support for clustering. Elasticsearch operations are optimized through the use of the official Elasticsearch client, which includes features like connection sniffing and automatic retries.

A unique feature of the SophraClient is its comprehensive health check system. The `healthCheck` method provides real-time status information for all connected services, enabling proactive monitoring and rapid issue detection. This capability is crucial for maintaining high availability in a distributed system architecture.

## Exported Components

<CodeGroup>
  ```typescript SophraClientConfig
  interface SophraClientConfig {
    environment: "development" | "production" | "test";
  }
  ```

  ```typescript SophraClient
  class SophraClient {
    constructor(config: SophraClientConfig);
    initialize(): Promise<void>;
    shutdown(): Promise<void>;
    healthCheck(): Promise<Record<string, boolean>>;
    getElasticClient(): ElasticClient;
    getRedisClient(): RedisClient;
  }
  ```
</CodeGroup>

The `SophraClientConfig` interface defines the configuration options for the client:

* `environment`: Specifies the runtime environment, affecting logging and optimization strategies.

The `SophraClient` class provides the following key methods:

* `initialize()`: Establishes connections to all configured services.
* `shutdown()`: Gracefully closes all service connections.
* `healthCheck()`: Performs a status check on all connected services.
* `getElasticClient()`: Retrieves the Elasticsearch client instance.
* `getRedisClient()`: Retrieves the Redis client instance.

## Implementation Examples

<CodeGroup>
  ```typescript Client Initialization
  import { SophraClient } from '@/lib/cortex/core/client';

  const client = new SophraClient({ environment: 'production' });
  await client.initialize();

  // Perform operations
  const elasticClient = client.getElasticClient();
  await elasticClient.search({ /* ... */ });

  // Shutdown
  await client.shutdown();
  ```

  ```typescript Health Check Usage
  import { SophraClient } from '@/lib/cortex/core/client';

  const client = new SophraClient({ environment: 'production' });
  await client.initialize();

  const healthStatus = await client.healthCheck();
  console.log('Service Health:', healthStatus);
  // Output: Service Health: { elasticsearch: true, database: true, redis: true }

  await client.shutdown();
  ```
</CodeGroup>

## Sophra Integration Details

The SophraClient integrates tightly with other Sophra services:

1. **Search Service**: Utilizes the Elasticsearch client for complex query operations and indexing.
2. **Caching Layer**: Employs the Redis client for high-speed data caching and temporary storage.
3. **Data Persistence**: Interfaces with PostgreSQL through Prisma ORM for robust data management.

<Accordion title="Data Flow Diagram">
  <img src="https://mintlify.s3.us-west-1.amazonaws.com/sophra/images/sophra-client-data-flow.png" alt="SophraClient Data Flow" />
</Accordion>

## Error Handling

The SophraClient implements a comprehensive error handling strategy:

<AccordionGroup>
  <Accordion title="Initialization Errors">
    * Validates configuration before attempting connections
    * Wraps service-specific errors in custom `CustomError` types
    * Attempts graceful shutdown on initialization failure
  </Accordion>

  <Accordion title="Runtime Errors">
    * Implements retry logic for transient failures
    * Logs detailed error information using structured logging
    * Propagates errors to callers with contextual information
  </Accordion>
</AccordionGroup>

## Data Flow

```mermaid
sequenceDiagram
    participant App as Application
    participant SC as SophraClient
    participant ES as ElasticClient
    participant RC as RedisClient
    participant DB as PostgreSQL

    App->>SC: initialize()
    SC->>ES: new ElasticClient()
    SC->>RC: new RedisClient()
    SC->>DB: prisma.$connect()
    SC-->>App: Initialization Complete

    App->>SC: getElasticClient()
    SC-->>App: ElasticClient Instance
    App->>ES: search()
    ES-->>App: Search Results

    App->>SC: getRedisClient()
    SC-->>App: RedisClient Instance
    App->>RC: get()
    RC-->>App: Cached Data

    App->>SC: shutdown()
    SC->>RC: disconnect()
    SC->>DB: prisma.$disconnect()
    SC-->>App: Shutdown Complete
```

## Performance Considerations

* **Connection Pooling**: Utilizes connection pools for database operations to minimize connection overhead.
* **Lazy Initialization**: Services are only connected when first requested, optimizing resource usage.
* **Caching Strategy**: Implements intelligent caching using Redis to reduce load on primary data stores.

<Note>
  The SophraClient achieves an average query response time of 50ms for cached operations and 150ms for database queries in production environments.
</Note>

## Security Implementation

<CodeGroup>
  ```typescript Authentication
  // API Key validation for Elasticsearch
  if (!process.env.ELASTICSEARCH_API_KEY && !process.env.SOPHRA_ES_API_KEY) {
    throw new Error("Either ELASTICSEARCH_API_KEY or SOPHRA_ES_API_KEY is required");
  }
  ```

  ```typescript Authorization
  // Role-based access control is implemented at the service level
  // Example: Search service authorization
  async function authorizedSearch(user, query) {
    const elasticClient = sophraClient.getElasticClient();
    if (user.hasPermission('search:execute')) {
      return elasticClient.search(query);
    }
    throw new CustomError('UNAUTHORIZED', new Error('User lacks search permission'));
  }
  ```
</CodeGroup>

## Configuration

<CodeGroup>
  ```env Environment Variables
  ELASTICSEARCH_URL=https://elasticsearch-cluster.example.com
  ELASTICSEARCH_API_KEY=your_api_key_here
  DATABASE_URL=postgresql://user:password@localhost:5432/sophra
  SOPHRA_REDIS_URL=redis://localhost:6379
  ```

  ```typescript Runtime Options
  const clientConfig: SophraClientConfig = {
    environment: process.env.NODE_ENV as "development" | "production" | "test",
    // Additional runtime options can be added here
  };

  const sophraClient = new SophraClient(clientConfig);
  ```
</CodeGroup>

<Card title="Integration Settings" icon="gear">
  Elasticsearch Index Prefix: `sophra_`
  Redis Key Prefix: `sph:`
  Database Schema: `public`
</Card>
