apollo-rust-client 0.6.3

A Rust client for Apollo configuration center
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
# apollo-rust-client

A robust Rust client for the Apollo Configuration Centre, with support for WebAssembly for browser and Node.js environments.

[![Crates.io](https://img.shields.io/crates/v/apollo-rust-client.svg)](https://crates.io/crates/apollo-rust-client)
[![Docs.rs](https://docs.rs/apollo-rust-client/badge.svg)](https://docs.rs/apollo-rust-client)
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE)
[![Rust CI](https://github.com/qqiao/apollo-rust-client/actions/workflows/rust.yml/badge.svg)](https://github.com/qqiao/apollo-rust-client/actions/workflows/rust.yml)

## Features

- **Multiple Configuration Formats**: Support for Properties, JSON, YAML, Text formats with planned XML support
- **Automatic Format Detection**: Based on namespace file extensions
- **Type-Safe Configuration Management**: Compile-time guarantees and runtime type conversion
- **Cross-Platform Support**: Native Rust and WebAssembly targets
- **TLS Support**: Switchable TLS implementations (native-tls by default, rustls via feature flag)
- **Real-Time Updates**: Background polling with configurable intervals and event listeners
- **Comprehensive Caching**: Multi-level caching with file persistence (native) and memory-only (WASM)
- **Async/Await Support**: Full asynchronous API for non-blocking operations
- **Error Handling**: Detailed error diagnostics with comprehensive error types
- **Grayscale Release Support**: IP and label-based configuration targeting
- **Flexible Configuration**: Direct instantiation or environment variable configuration
- **Memory Management**: Automatic cleanup with explicit control for WASM environments

## Installation

### Rust

Add the following to your `Cargo.toml`:

```toml
[dependencies]
apollo-rust-client = "0.6.3"
```

If you prefer to use `rustls` instead of the system's native TLS (useful for minimal images like Alpine):

```toml
[dependencies]
apollo-rust-client = { version = "0.6.3", default-features = false, features = ["rustls"] }
```

**Note on TLS Support:**

- **Non-WASM Targets**: `native-tls` (enabled by default) and `rustls` are mutually exclusive. You must disable default features if you want to use `rustls`.
- **WASM Targets**: Only `native-tls` (which uses the browser's fetch API) is supported. Enabling the `rustls` feature on WASM targets will result in a compile error.

Alternatively, you can use `cargo add`:

```bash
cargo add apollo-rust-client
```

### WebAssembly (npm)

```bash
npm install @qqiao/apollo-rust-client
```

## Quick Start

### Rust Usage

```rust
use apollo_rust_client::Client;
use apollo_rust_client::client_config::ClientConfig;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create client configuration
    let client_config = ClientConfig {
        app_id: "your_app_id".to_string(),
        cluster: "default".to_string(),
        config_server: "http://your-apollo-server:8080".to_string(),
        secret: Some("your_apollo_secret".to_string()),
        cache_dir: None, // Uses default: /opt/data/{app_id}/config-cache
        label: None,     // For grayscale releases
        ip: None,        // For grayscale releases
        allow_insecure_https: None, // Allow self-signed certificates
        #[cfg(not(target_arch = "wasm32"))]
        cache_ttl: None, // Uses default: 600 seconds (10 minutes)
    };

    let mut client = Client::new(client_config);

    // Start background polling for configuration updates
    client.start().await?;

    // Get configuration for different namespace formats
    let namespace = client.namespace("application").await?;

    // Handle different configuration formats
    match namespace {
        apollo_rust_client::namespace::Namespace::Properties(properties) => {
            // Properties format (default) - key-value pairs
            if let Some(app_name) = properties.get_string("app.name") {
                println!("Application name: {}", app_name);
            }

            if let Some(port) = properties.get_int("server.port") {
                println!("Server port: {}", port);
            }

            if let Some(debug) = properties.get_bool("debug.enabled") {
                println!("Debug enabled: {}", debug);
            }
        }
        apollo_rust_client::namespace::Namespace::Json(json) => {
            // JSON format - structured data
            #[derive(serde::Deserialize)]
            struct Config {
                name: String,
                version: String,
            }

            let config: Config = json.to_object()?;
            println!("Config: {} v{}", config.name, config.version);
        }
        apollo_rust_client::namespace::Namespace::Text(text) => {
            // Text format - plain text content
            println!("Text content: {}", text);
        }
    }

    // Add event listener for configuration changes
    client.add_listener("application", std::sync::Arc::new(|result| {
        match result {
            Ok(namespace) => println!("Configuration updated: {:?}", namespace),
            Err(e) => eprintln!("Configuration update error: {}", e),
        }
    })).await;

    Ok(())
}
```

#### Configuration via Environment Variables

```rust
use apollo_rust_client::client_config::ClientConfig;

// Initialize from environment variables
let client_config = ClientConfig::from_env()?;
```

**Environment Variables:**

- `APP_ID`: Your application ID (required)
- `APOLLO_CONFIG_SERVICE`: The Apollo config server URL (required)
- `IDC`: The cluster name (optional, defaults to "default")
- `APOLLO_ACCESS_KEY_SECRET`: The secret key for authentication (optional)
- `APOLLO_LABEL`: Comma-separated list of labels for grayscale rules (optional)
- `APOLLO_CACHE_DIR`: Directory to store local cache (optional)
- `APOLLO_CACHE_TTL`: Time-to-live for cache in seconds (optional, defaults to 600, native targets only)
- `APOLLO_ALLOW_INSECURE_HTTPS`: Whether to allow insecure HTTPS connections (optional, defaults to false)

### JavaScript/WebAssembly Usage

```javascript
import { Client, ClientConfig } from "@qqiao/apollo-rust-client";

async function main() {
  // Create client configuration
  const clientConfig = new ClientConfig(
    "your_app_id",
    "http://your-apollo-server:8080",
    "default"
  );

  // Set optional properties
  clientConfig.secret = "your_apollo_secret";
  clientConfig.label = "production";
  clientConfig.ip = "192.168.1.100";

  const client = new Client(clientConfig);

  // Start background polling
  await client.start();

  // Get configuration cache
  const cache = await client.namespace("application");

  // Retrieve different data types
  const appName = await cache.get_string("app.name");
  const serverPort = await cache.get_int("server.port");
  const debugEnabled = await cache.get_bool("debug.enabled");
  const timeout = await cache.get_float("timeout.seconds");

  console.log(`App: ${appName}, Port: ${serverPort}, Debug: ${debugEnabled}`);

  // Add event listener for configuration changes
  await cache.add_listener((data, error) => {
    if (error) {
      console.error("Configuration update error:", error);
    } else {
      console.log("Configuration updated:", data);
    }
  });

  // IMPORTANT: Release memory when done
  cache.free();
  client.free();
  clientConfig.free();
}

main().catch(console.error);
```

## Configuration Formats

The library automatically detects configuration formats based on namespace names:

### Properties Format (Default)

- **Namespace**: `"application"`, `"config.properties"`
- **Format**: Key-value pairs
- **Example**:
  ```properties
  app.name = MyApp
  server.port = 8080
  ```

### JSON Format

- **Namespace**: `"config.json"`, `"settings.json"`
- **Format**: Structured JSON data
- **Example**: `{"database": {"host": "localhost", "port": 5432}}`

### Text Format

- **Namespace**: `"readme.txt"`, `"content.txt"`
- **Format**: Plain text content
- **Example**: Raw text content

### YAML Format

- **Namespace**: `"config.yaml"`, `"config.yml"`
- **Format**: Structured YAML data
- **Example**: Complex configuration structures with nested objects

```rust
#[derive(serde::Deserialize)]
struct AppConfig {
    server: ServerConfig,
    database: DatabaseConfig,
}

#[derive(serde::Deserialize)]
struct ServerConfig {
    host: String,
    port: u16,
}

#[derive(serde::Deserialize)]
struct DatabaseConfig {
    host: String,
    port: u16,
    ssl: bool,
}

if let apollo_rust_client::namespace::Namespace::Yaml(yaml) = namespace {
    let config: AppConfig = yaml.to_object()?;
    println!("Server: {}:{}", config.server.host, config.server.port);
    println!("Database: {}:{}", config.database.host, config.database.port);
}
```

### Planned Formats

- **XML**: `"config.xml"`

## Configuration Options

### ClientConfig Fields

- **`app_id`**: Your application ID in Apollo (required)
- **`config_server`**: The Apollo config server URL (required)
- **`cluster`**: The cluster name (required, typically "default")
- **`secret`**: Optional secret key for authentication
- **`cache_dir`**: Directory for local cache files (native only)
  - Default: `/opt/data/{app_id}/config-cache`
  - WASM: Always `None` (memory-only caching)
- **`label`**: Label for grayscale releases (optional)
- **`ip`**: IP address for grayscale releases (optional)

## Error Handling

The library provides comprehensive error handling:

```rust
use apollo_rust_client::Error;

match client.namespace("application").await {
    Ok(namespace) => {
        // Handle successful configuration retrieval
    }
    Err(Error::Cache(cache_error)) => {
        // Handle cache-related errors (network, parsing, etc.)
        eprintln!("Cache error: {}", cache_error);
    }
    Err(Error::Namespace(namespace_error)) => {
        // Handle namespace-related errors (format detection, etc.)
        eprintln!("Namespace error: {}", namespace_error);
    }
    Err(e) => {
        // Handle other errors
        eprintln!("Error: {}", e);
    }
}
```

## Memory Management (WASM)

For WebAssembly environments, explicit memory management is required:

```javascript
// Always call free() on WASM objects when done
cache.free();
client.free();
clientConfig.free();
```

This prevents memory leaks by releasing Rust-allocated memory on the WebAssembly heap.

## Advanced Usage

### Event Listeners

```rust
// Rust - Add event listener
client.add_listener("application", std::sync::Arc::new(|result| {
    match result {
        Ok(namespace) => println!("Config updated: {:?}", namespace),
        Err(e) => eprintln!("Update error: {}", e),
    }
})).await;
```

```javascript
// JavaScript - Add event listener
await cache.add_listener((data, error) => {
  if (error) {
    console.error("Update error:", error);
  } else {
    console.log("Config updated:", data);
  }
});
```

### Grayscale Releases

```rust
let client_config = ClientConfig {
    app_id: "my-app".to_string(),
    config_server: "http://apollo-server:8080".to_string(),
    cluster: "default".to_string(),
    secret: None,
    cache_dir: None,
    label: Some("canary,beta".to_string()),  // Multiple labels
    ip: Some("192.168.1.100".to_string()),  // Client IP
    #[cfg(not(target_arch = "wasm32"))]
    cache_ttl: None,
};
```

### Custom JSON Deserialization

```rust
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize)]
struct DatabaseConfig {
    host: String,
    port: u16,
    ssl: bool,
}

if let apollo_rust_client::namespace::Namespace::Json(json) = namespace {
    let db_config: DatabaseConfig = json.to_object()?;
    println!("Database: {}:{}", db_config.host, db_config.port);
}
```

## API Changes in v0.6.0

- **Typed Namespaces**: Support for multiple configuration formats with automatic detection
- **Event Listeners**: Real-time configuration change notifications
- **Enhanced Error Handling**: Comprehensive error types and better error reporting
- **WASM Improvements**: Better memory management and JavaScript interop
- **Background Polling**: Configurable automatic configuration refresh

## Documentation

For comprehensive documentation, visit our [wiki](docs/wiki/en/Home.md):

- **[Installation Guide]docs/wiki/en/Installation.md** - Setup instructions
- **[Rust Usage]docs/wiki/en/Rust-Usage.md** - Native Rust examples
- **[JavaScript Usage]docs/wiki/en/JavaScript-Usage.md** - WASM usage in JavaScript
- **[Configuration]docs/wiki/en/Configuration.md** - Configuration options
- **[Features]docs/wiki/en/Features.md** - Feature overview
- **[Error Handling]docs/wiki/en/Error-Handling.md** - Error handling guide
- **[Design Overview]docs/wiki/en/Design-Overview.md** - Architecture documentation

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## License

This project is licensed under the Apache License Version 2.0 - see the [LICENSE](LICENSE) file for details.