> ## 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.

# Service factory

---
title: Service Factory: Core Service Orchestration
description: Centralized factory for initializing and managing Sophra's core services
---

The ServiceFactory component serves as the central orchestrator for Sophra's core services, providing a unified interface for service initialization, management, and dependency injection. This critical component sits at the heart of Sophra's microservices architecture, facilitating the creation and coordination of essential services such as Elasticsearch, Redis caching, vectorization, PostgreSQL data management, analytics, and data synchronization.

By centralizing service creation, the ServiceFactory ensures consistent configuration and initialization across the entire Sophra ecosystem. This approach significantly reduces code duplication, enhances maintainability, and provides a single point of control for service lifecycle management. The factory pattern employed here allows for flexible service instantiation based on the current environment, enabling seamless transitions between development, testing, and production configurations.

One of the key architectural decisions in the ServiceFactory design is the use of dependency injection. This pattern decouples service consumers from the concrete implementations of the services, promoting modularity and facilitating easier unit testing. By injecting dependencies through the factory, Sophra can easily swap out service implementations or introduce new services without affecting the consumers of those services.

Performance-wise, the ServiceFactory is designed to be lightweight and efficient. It leverages lazy initialization techniques to create services on-demand, reducing memory overhead and improving application startup time. This is particularly crucial in serverless environments where cold starts can significantly impact user experience.

The ServiceFactory also incorporates sophisticated error handling and logging mechanisms. It integrates with Sophra's centralized logging system, ensuring that service initialization errors and runtime issues are properly captured and reported. This integration is vital for maintaining the overall health and observability of the Sophra system.

## Exported Components

<CodeGroup>
  ```typescript Services Interface
  export interface Services {
    elasticsearch: ElasticsearchService;
    redis: RedisCacheService;
    vectorization: VectorizationService;
    postgres: PostgresDataService;
    analytics: AnalyticsService;
    sync: {
      getSyncService(): Promise<DataSyncService>;
      vectorizeDocument(params: { index: string; id: string }): Promise<void>;
      upsertDocument(params: {
        index: string;
        id: string;
        document: Partial<BaseDocument>;
        tableName: string;
      }): Promise<{ id: string }>;
      deleteDocument(params: {
        index: string;
        id: string;
        tableName: string;
      }): Promise<void>;
    };
    documents: {
      createDocument(params: {
        index: string;
        id: string;
        document: BaseDocument;
      }): Promise<ProcessedDocumentMetadata>;
      getDocument(id: string): Promise<BaseDocument & ProcessedDocumentMetadata>;
      updateDocument(id: string, document: Partial<BaseDocument>): Promise<void>;
      deleteDocument(id: string): Promise<void>;
    };
    health: {
      check(): Promise<{
        success: boolean;
        error?: string;
        data: {
          elasticsearch: boolean;
          database: boolean;
          redis: boolean;
          sync: boolean;
          timestamp: string;
        };
      }>;
    };
  }
  ```

  ```typescript ServiceFactory Class
  export class ServiceFactory {
    private readonly logger: Logger;
    private readonly environment: string;

    constructor(config: ServiceFactoryConfig) {
      this.logger = config.logger;
      this.environment = config.environment;
    }

    async createServices(): Promise<Services> {
      // Implementation will be added later
      throw new Error("Not implemented");
    }
  }
  ```
</CodeGroup>

The `Services` interface defines the structure of the service objects created by the ServiceFactory. Each field represents a core service or a group of related operations:

* `elasticsearch`: Manages Elasticsearch operations
* `redis`: Handles Redis caching
* `vectorization`: Provides document vectorization capabilities
* `postgres`: Manages PostgreSQL database operations
* `analytics`: Handles analytics data processing
* `sync`: Manages data synchronization operations
* `documents`: Provides CRUD operations for documents
* `health`: Offers system health check functionality

The `ServiceFactory` class is responsible for creating and initializing these services. It takes a `ServiceFactoryConfig` object in its constructor, which includes a logger and the current environment.

## Implementation Examples

<CodeGroup>
  ```typescript Service Initialization
  const serviceFactory = new ServiceFactory({
    logger: winston.createLogger(/* logger config */),
    environment: process.env.NODE_ENV || 'development'
  });

  const services = await serviceFactory.createServices();

  // Using the elasticsearch service
  const searchResults = await services.elasticsearch.search({
    index: 'products',
    query: { match: { name: 'smartphone' } }
  });

  // Using the redis cache
  await services.redis.set('user:123', JSON.stringify(userData), 'EX', 3600);

  // Performing document operations
  const newDocument = await services.documents.createDocument({
    index: 'articles',
    id: 'article-001',
    document: { title: 'New Article', content: 'Lorem ipsum...' }
  });
  ```

  ```typescript Health Check Usage
  app.get('/health', async (req, res) => {
    const healthStatus = await services.health.check();
    res.status(healthStatus.success ? 200 : 500).json(healthStatus);
  });
  ```
</CodeGroup>

These examples demonstrate how the ServiceFactory is typically used within the Sophra system. The factory is initialized with environment-specific configuration, and then services are created and used throughout the application.

## Sophra Integration Details

The ServiceFactory integrates deeply with Sophra's core systems:

1. **Elasticsearch Integration**: Manages search operations, indexing, and retrieval of documents.
2. **Redis Caching**: Provides high-performance caching for frequently accessed data.
3. **Vectorization Service**: Enables semantic search capabilities by converting documents into vector representations.
4. **PostgreSQL Data Service**: Handles persistent storage and complex data operations.
5. **Analytics Service**: Processes and analyzes user interactions and system metrics.
6. **Data Sync Service**: Ensures data consistency across different services and storage systems.

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

## Error Handling

The ServiceFactory implements robust error handling:

<AccordionGroup>
  <Accordion title="Service Initialization Errors">
    * Logs detailed error information
    * Attempts to gracefully degrade if non-critical services fail
    * Throws fatal errors for critical service failures
  </Accordion>

  <Accordion title="Runtime Errors">
    * Implements circuit breakers for external service calls
    * Provides fallback mechanisms for cache misses
    * Logs errors with contextual information for debugging
  </Accordion>
</AccordionGroup>

## Performance Considerations

<Card title="Optimization Strategies" icon="bolt">
  * Lazy loading of services to reduce startup time
  * Connection pooling for database and Elasticsearch connections
  * Intelligent caching strategies using Redis
</Card>

## Security Implementation

<Note>
  The ServiceFactory integrates with Sophra's security model:

  * Ensures secure initialization of services with proper credentials
  * Implements role-based access control for service operations
  * Encrypts sensitive configuration data
</Note>

## Configuration

The ServiceFactory uses the following configuration options:

<CodeGroup>
  ```env Environment Variables
  ELASTICSEARCH_URL=https://elasticsearch:9200
  REDIS_URL=redis://redis:6379
  POSTGRES_URL=postgresql://user:password@postgres:5432/sophra
  VECTORIZATION_API_KEY=your-api-key-here
  ```

  ```typescript Runtime Options
  interface ServiceFactoryConfig {
    logger: Logger;
    environment: "development" | "production" | "test";
  }
  ```
</CodeGroup>

These configuration options allow for flexible deployment across different environments while maintaining security and performance optimizations.
