npm package: @sailboat-computer/config-client
Description: Client library for the Sailboat Computer Configuration Service
Author: Sailboat Computer Team
Latest version: 1.1.56

# Configuration Client

A client library for the Sailboat Computer Configuration Service. This package provides a unified approach to configuration management with versioning, rollback support, validation, and real-time updates.

## Features

- **Centralized Configuration**: Access configurations from the central Configuration Service
- **Local Fallback**: Automatically fall back to local files when the service is unavailable
- **Versioning and Rollback**: Track configuration changes and enable rollback to previous versions
- **Validation**: Ensure configurations adhere to defined schemas before application
- **Real-time Updates**: Watch for configuration changes and react to them
- **Resilience**: Built-in circuit breaker, retry, and timeout mechanisms
- **Caching**: In-memory caching with configurable TTL
- **Local Schema Validation**: Validate configurations against JSON schemas locally when the service is unavailable

## Installation

```bash
npm install @sailboat-computer/config-client
```

## Usage

### Basic Usage

```typescript
import { createConfigClient } from '@sailboat-computer/config-client';

// Create client
const configClient = createConfigClient({
  serviceUrl: 'http://localhost:3000',
  serviceName: 'my-service',
  fallbackDir: './config'
});

// Get configuration
const config = await configClient.getConfig<MyConfig>('my-config');
console.log('Configuration:', config);
```

### Watching for Changes

```typescript
// Watch for configuration changes
const stopWatching = configClient.watchConfig<MyConfig>('my-config', (event) => {
  console.log('Configuration changed:', event.data);
  console.log('Version:', event.version);
  console.log('Timestamp:', event.timestamp);
});

// Later, stop watching
stopWatching();
```

### Saving Configuration

```typescript
// Save configuration
await configClient.saveConfig('my-config', {
  setting1: 'new-value',
  setting2: 100
}, 'Updated settings');
```

### Rollback to Previous Version

```typescript
// Rollback to previous version
await configClient.rollback('my-config', 1, 'Rolling back to initial version');
```

### Validating Configuration

```typescript
// Validate configuration
const errors = await configClient.validateConfig('my-config', {
  setting1: 'value',
  setting2: 100
});

if (errors.length === 0) {
  console.log('Configuration is valid');
} else {
  console.error('Configuration is invalid:', errors);
}
```

### Advanced Options

```typescript
const configClient = createConfigClient({
  serviceUrl: 'http://localhost:3000',
  serviceName: 'my-service',
  fallbackDir: './config',
  environment: 'development',
  validate: true,
  watch: true,
  pollingIntervalMs: 10000, // 10 seconds polling interval
  cacheTtlMs: 60000, // 1 minute cache TTL
  resilience: {
    timeoutMs: 5000,
    circuitBreaker: {
      failureThreshold: 5,
      resetTimeoutMs: 30000
    },
    retry: {
      maxRetries: 3,
      baseDelayMs: 1000,
      maxDelayMs: 10000
    }
  },
  logger: customLogger
});
```

### Local Schema Validation

The client supports local schema validation when the configuration service is unavailable. To use this feature, place your JSON schema files in the fallback directory with the naming convention `<service-name>/config.schema.json`.

```typescript
// Validate configuration against schema
const errors = await configClient.validateConfig('my-config', {
  setting1: 'value',
  setting2: -1 // Invalid value
});

if (errors.length === 0) {
  console.log('Configuration is valid');
} else {
  console.error('Configuration is invalid:', errors);
  // [
  //   {
  //     path: "/setting2",
  //     message: "must be >= 0",
  //     details: { ... }
  //   }
  // ]
}
```

### Resilience Patterns

The client implements several resilience patterns to handle service unavailability and other failure scenarios:

1. **Circuit Breaker**: Prevents cascading failures by stopping requests to the service when it's unavailable
2. **Timeout Management**: Ensures operations don't hang indefinitely
3. **Retry Mechanisms**: Automatically retries failed operations with exponential backoff
4. **Fallback Mechanisms**: Falls back to local files when the service is unavailable
5. **Caching**: Uses in-memory cache to reduce service calls and provide data when the service is unavailable

```typescript
// The client automatically applies these patterns
const config = await configClient.getConfig<MyConfig>('my-config');
// If the service is unavailable:
// 1. The circuit breaker will trip after multiple failures
// 2. The client will fall back to local files
// 3. If local files are unavailable, it will use cached data if available
```

### Examples

Check out the examples directory for more detailed usage examples:

- `basic-usage.ts`: Basic usage of the client
- `resilience-example.ts`: Demonstrates resilience patterns
- `local-validation-example.ts`: Shows local schema validation

## API Reference

### `createConfigClient(options)`

Creates a new configuration client.

#### Options

- `serviceUrl` - URL of the Configuration Service
- `serviceName` - Name of the service using the client
- `fallbackDir` - Directory for local configuration files (optional)
- `environment` - Environment to use (default: "production")
- `validate` - Whether to validate configurations against schemas (optional)
- `watch` - Whether to watch for configuration changes (optional)
- `pollingIntervalMs` - Polling interval for configuration changes in milliseconds (optional, default: 30000)
- `cacheTtlMs` - Cache time-to-live in milliseconds (optional, default: 60000)
- `resilience` - Resilience options (optional)
  - `timeoutMs` - Timeout in milliseconds (optional, default: 5000)
  - `circuitBreaker` - Circuit breaker options (optional)
    - `failureThreshold` - Failure threshold (optional, default: 5)
    - `resetTimeoutMs` - Reset timeout in milliseconds (optional, default: 30000)
  - `retry` - Retry options (optional)
    - `maxRetries` - Maximum number of retries (optional, default: 3)
    - `baseDelayMs` - Base delay in milliseconds (optional, default: 1000)
    - `maxDelayMs` - Maximum delay in milliseconds (optional, default: 10000)
- `logger` - Custom logger (optional)

### Methods

- `getConfig<T>(id)` - Get configuration
- `watchConfig<T>(id, listener)` - Watch for configuration changes
- `getConfigVersion<T>(id, version)` - Get configuration version
- `listVersions(id)` - List configuration versions
- `saveConfig<T>(id, data, description?)` - Save configuration
- `rollback(id, version, description?)` - Rollback configuration to a previous version
- `validateConfig<T>(id, data)` - Validate configuration against schema

## License

MIT