apicentric 0.1.1

Toolkit for building, recording, and sharing mock APIs
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
# Apicentric Architecture

This document describes the architecture and design decisions of Apicentric.

## Overview

Apicentric is built using a layered architecture that separates concerns and promotes maintainability. The system follows the ports and adapters (hexagonal) architecture pattern, with clear boundaries between layers.

## Layered Architecture

```mermaid
graph TD
    A[CLI Layer] --> B[Application Layer]
    B --> C[Domain Layer]
    C --> D[Adapter Layer]
    
    A1[Commands] --> A
    A2[Argument Parsing] --> A
    
    B1[Context Builder] --> B
    B2[Configuration] --> B
    
    C1[Business Logic] --> C
    C2[Entities] --> C
    C3[Ports] --> C
    
    D1[HTTP Client] --> D
    D2[Simulator] --> D
    D3[Storage] --> D
    D4[P2P] --> D
```

### CLI Layer

The CLI layer handles user interaction and command parsing.

**Location**: `src/cli/`, `src/commands/`

**Responsibilities**:
- Parse command-line arguments using `clap`
- Validate user input
- Dispatch commands to application layer
- Format output for users

**Key Components**:
- `mod.rs` - CLI entry point and command definitions
- `simulator/` - Simulator commands (start, stop, validate, etc.)
- `contract.rs` - Contract testing commands
- `tui.rs` - TUI (Terminal User Interface) command
- `gui.rs` - GUI launcher command

### Application Layer

The application layer orchestrates business logic and manages application state.

**Location**: `src/app/`, `src/context/`

**Responsibilities**:
- Build execution context
- Load and validate configuration
- Coordinate between domain and adapters
- Manage application lifecycle

**Key Components**:
- `ContextBuilder` - Builds execution context with dependencies
- `ExecutionContext` - Holds application state and configuration
- `Config` - Application configuration management

### Domain Layer

The domain layer contains business logic and domain entities.

**Location**: `src/domain/`

**Responsibilities**:
- Define business entities
- Implement business rules
- Define ports (interfaces) for adapters
- Validate domain invariants

**Key Components**:

#### Entities (`src/domain/entities.rs`)
- `ServiceDefinition` - API service specification
- `Endpoint` - API endpoint definition
- `Response` - Response specification
- `Contract` - Contract testing specification

#### Ports (`src/domain/ports/`)
- `ContractRepository` - Contract storage interface
- `HttpClient` - HTTP client interface
- `SystemInterface` - System operations interface
- `UIInterface` - User interface operations

#### Business Logic
- Contract testing (`src/domain/contract/`)
- Service validation
- Scenario management

### Adapter Layer

The adapter layer implements ports and integrates with external systems.

**Location**: `src/adapters/`, `src/simulator/`, `src/storage/`

**Responsibilities**:
- Implement domain ports
- Integrate with external systems
- Handle I/O operations
- Manage infrastructure concerns

**Key Components**:

#### HTTP (`src/adapters/http_client.rs`)
- HTTP client implementation using `reqwest`
- Request/response handling
- Error mapping

#### Simulator (`src/adapters/mock_server.rs`)
- HTTP server using `hyper`
- Request routing
- Response generation

#### Storage (`src/storage/`)
- SQLite database integration
- Contract persistence
- Configuration storage

#### Simulator (`src/simulator/`)
- Service lifecycle management
- Configuration loading
- Template rendering
- Route registry

## Feature Flag System

Apicentric uses Cargo features to make heavy dependencies optional, improving build times and binary size.

### Feature Flags

```toml
[features]
default = ["simulator"]

# Core features
simulator = []
contract-testing = ["reqwest", "async-trait"]

# Optional features
tui = ["ratatui", "crossterm", "indicatif"]
p2p = ["libp2p", "automerge", "tokio-tungstenite"]
graphql = ["async-graphql", "async-graphql-parser"]
scripting = ["deno_core"]
ai = []

# Convenience bundles
full = ["tui", "p2p", "graphql", "scripting", "ai"]
minimal = ["simulator"]
cli-tools = ["simulator", "contract-testing", "tui"]
```

### Conditional Compilation

Features are enabled using conditional compilation:

```rust
#[cfg(feature = "tui")]
pub mod tui;

#[cfg(feature = "p2p")]
pub mod p2p;

#[cfg(feature = "graphql")]
pub mod graphql;
```

This allows users to install only the features they need:

```bash
# Minimal installation
cargo install apicentric --no-default-features --features minimal

# Full installation
cargo install apicentric --features full
```

## Key Design Decisions

### 1. Ports and Adapters Pattern

**Decision**: Use hexagonal architecture with ports and adapters.

**Rationale**:
- Separates business logic from infrastructure
- Makes testing easier with mock implementations
- Allows swapping implementations without changing business logic
- Promotes loose coupling

### 2. YAML Configuration

**Decision**: Use YAML for service definitions.

**Rationale**:
- Human-readable and writable
- Widely used in DevOps tools
- Good library support in Rust
- Easy to version control

### 3. Feature Flags

**Decision**: Make heavy dependencies optional via Cargo features.

**Rationale**:
- Reduces build time for users who don't need all features
- Smaller binary size
- Faster CI/CD pipelines
- Users can choose their own trade-offs

### 4. Async Execution

**Decision**: Use Tokio for async operations.

**Rationale**:
- Industry standard for async Rust
- Excellent ecosystem support
- Good performance characteristics
- Well-documented

### 5. Error Handling

**Decision**: Use custom error type with suggestions.

**Rationale**:
- Provides helpful error messages
- Suggests solutions to users
- Maintains error context
- Easy to extend

## Module Organization

```
src/
├── cli/              # CLI commands and parsing
├── commands/         # Command implementations
│   ├── simulator/    # Simulator commands
│   ├── contract.rs   # Contract testing
│   ├── tui.rs        # TUI (Terminal User Interface)
│   └── gui.rs        # GUI launcher
├── app/              # Application orchestration
├── context/          # Execution context
├── domain/           # Business logic
│   ├── entities.rs   # Domain entities
│   ├── ports/        # Port definitions
│   └── contract/     # Contract testing logic
├── adapters/         # Infrastructure adapters
│   ├── http_client.rs
│   ├── mock_server.rs
│   └── contract_repository.rs
├── simulator/        # API simulator
│   ├── config/       # Configuration
│   ├── service/      # Service management
│   └── template/     # Template rendering
├── storage/          # Data persistence
└── utils/            # Utilities

```

## Data Flow

### Starting the Simulator

```mermaid
sequenceDiagram
    participant User
    participant CLI
    participant App
    participant Domain
    participant Adapter
    
    User->>CLI: apicentric simulator start
    CLI->>App: Build context
    App->>Domain: Load services
    Domain->>Adapter: Read YAML files
    Adapter-->>Domain: Service definitions
    Domain->>Adapter: Start HTTP servers
    Adapter-->>User: Services running
```

### Contract Testing

```mermaid
sequenceDiagram
    participant User
    participant CLI
    participant Domain
    participant Mock
    participant Real
    
    User->>CLI: apicentric contract demo
    CLI->>Domain: Execute contract
    Domain->>Mock: Send request
    Mock-->>Domain: Mock response
    Domain->>Real: Send request
    Real-->>Domain: Real response
    Domain->>Domain: Compare responses
    Domain-->>User: Report differences
```

## Testing Strategy

### Unit Tests

- Test individual functions and modules
- Mock external dependencies
- Focus on business logic
- Located alongside source code

### Integration Tests

- Test component interactions
- Use real implementations where possible
- Test end-to-end scenarios
- Located in `tests/` directory

### Feature Tests

- Test with different feature combinations
- Ensure features work independently
- Verify conditional compilation
- Run in CI matrix

## Performance Considerations

### Build Time Optimization

- Feature flags reduce compilation units
- Dependency caching in CI
- Parallel compilation enabled by default
- Incremental compilation for development

### Execution Performance

- Async I/O for concurrency
- Efficient template rendering
- Connection pooling for HTTP
- Bounded buffers for logs

### Memory Management

- Streaming for large files
- Bounded log buffers (max 1000 entries)
- Efficient data structures
- Minimal cloning

## Security Considerations

### Input Validation

- Validate all user input
- Sanitize file paths
- Check port ranges
- Validate YAML structure

### Sandboxing

- Deno execution environment for scripts (when enabled)
- No network access from scripts
- No file system access from scripts
- Isolated execution environment

### Dependencies

- Regular security audits with `cargo audit`
- Minimal dependency tree
- Trusted crates only
- Keep dependencies updated

## Future Directions

### Planned Improvements

1. **Plugin System**: Allow users to extend functionality
2. **GraphQL Support**: Better GraphQL mocking capabilities
3. **Performance**: Optimize template rendering
4. **Documentation**: More examples and guides

### Potential Refactoring

1. **HTTP Server**: Consider migrating from hyper to axum
2. **Error Handling**: Unify error types across modules
3. **Logging**: Standardize on `tracing` crate
4. **Configuration**: Support multiple config formats

## Contributing

When contributing to Apicentric:

1. Follow the layered architecture
2. Keep business logic in the domain layer
3. Use ports for external dependencies
4. Add tests for new functionality
5. Update documentation

See [CONTRIBUTING.md](CONTRIBUTING.md) for detailed guidelines.