367 lines
7.7 KiB
Markdown
367 lines
7.7 KiB
Markdown
# Database and Caching Systems
|
|
|
|
## Overview
|
|
|
|
Echoion uses SQLite for persistent storage (playlists, history, favorites) and an in-memory LRU cache for frequently accessed data to improve performance.
|
|
|
|
## Database Architecture
|
|
|
|
```mermaid
|
|
flowchart TB
|
|
subgraph "Database Layer"
|
|
API[Database API]
|
|
Impl[DatabaseImpl]
|
|
|
|
subgraph "SQLite"
|
|
Conn[Connection]
|
|
Migrations[Schema Migrations]
|
|
end
|
|
end
|
|
|
|
subgraph "Stored Data"
|
|
Playlists[(Playlists)]
|
|
History[(History)]
|
|
Favorites[(Favorites)]
|
|
Subs[(Subscriptions)]
|
|
end
|
|
|
|
Core --> API
|
|
API --> Impl
|
|
Impl --> Conn
|
|
Conn --> Playlists
|
|
Conn --> History
|
|
Conn --> Favorites
|
|
Conn --> Subs
|
|
|
|
Impl --> Migrations
|
|
```
|
|
|
|
## Database Schema
|
|
|
|
```mermaid
|
|
erDiagram
|
|
PLAYLISTS {
|
|
int id PK
|
|
string name
|
|
string description
|
|
int created_by
|
|
int created_at
|
|
bool is_public
|
|
}
|
|
|
|
PLAYLIST_TRACKS {
|
|
int id PK
|
|
int playlist_id FK
|
|
string track_id
|
|
string title
|
|
string artist
|
|
int position
|
|
}
|
|
|
|
PLAYBACK_HISTORY {
|
|
int id PK
|
|
string track_id
|
|
string title
|
|
string artist
|
|
int played_by
|
|
int played_at
|
|
int duration_ms
|
|
bool completed
|
|
}
|
|
|
|
FAVORITES {
|
|
int id PK
|
|
int user_id
|
|
string track_id
|
|
string title
|
|
string artist
|
|
int added_at
|
|
}
|
|
|
|
SUBSCRIPTIONS {
|
|
int client_id PK
|
|
int subscribed_at
|
|
}
|
|
|
|
SCHEMA_VERSION {
|
|
int version PK
|
|
}
|
|
|
|
PLAYLISTS ||--o{ PLAYLIST_TRACKS : contains
|
|
```
|
|
|
|
## Data Flow
|
|
|
|
```mermaid
|
|
flowchart TB
|
|
subgraph "Write Path"
|
|
W1[User Action] --> W2[Publish Event]
|
|
W2 --> W3[Database Subscribe]
|
|
W3 --> W4[Insert/Update]
|
|
end
|
|
|
|
subgraph "Read Path"
|
|
R1[Data Request] --> R2[Query Database]
|
|
R2 --> R3[Return Results]
|
|
end
|
|
```
|
|
|
|
## Cache Architecture
|
|
|
|
```mermaid
|
|
flowchart TB
|
|
subgraph "Cache System"
|
|
CM[CacheManager<br/>Singleton]
|
|
|
|
subgraph "Cache Types"
|
|
HTTP[HTTP Cache<br/>5 min TTL]
|
|
Track[Track Cache<br/>1 hour TTL]
|
|
Meta[Metadata Cache<br/>30 min TTL]
|
|
end
|
|
|
|
subgraph "LRU Cache"
|
|
LRU[LRU Policy]
|
|
TTL[TTL Expiration]
|
|
end
|
|
end
|
|
|
|
Request[Data Request] --> CM
|
|
CM --> HTTP
|
|
CM --> Track
|
|
CM --> Meta
|
|
|
|
HTTP --> LRU
|
|
Track --> LRU
|
|
Meta --> LRU
|
|
|
|
LRU --> TTL
|
|
```
|
|
|
|
## Cache-Aside Pattern
|
|
|
|
```mermaid
|
|
flowchart TB
|
|
Request[Data Request] --> Check{In Cache?}
|
|
|
|
Check -->|Hit| Return[Return Cached]
|
|
Check -->|Miss| Fetch[Fetch Source]
|
|
|
|
Fetch --> DB[Database]
|
|
Fetch --> HTTP[HTTP/YouTube]
|
|
|
|
DB --> Store[Store in Cache]
|
|
HTTP --> Store
|
|
Store --> Return
|
|
|
|
Return --> Use[Use Data]
|
|
```
|
|
|
|
## Cache Entry Lifecycle
|
|
|
|
```mermaid
|
|
stateDiagram-v2
|
|
[*] --> Empty: Create
|
|
Empty --> Filled: Put value
|
|
|
|
Filled --> Accessed: Get
|
|
Accessed --> Accessed: Get again
|
|
Accessed --> Filled: TTL expires
|
|
|
|
Filled --> Evicted: LRU eviction
|
|
Accessed --> Evicted: LRU eviction
|
|
|
|
Filled --> Expired: TTL expires
|
|
Expired --> Empty: Remove
|
|
Evicted --> Empty: Remove
|
|
|
|
Empty --> [*]: Destroy
|
|
```
|
|
|
|
## Integration Flow
|
|
|
|
```mermaid
|
|
sequenceDiagram
|
|
participant C as Component
|
|
participant Cache as CacheManager
|
|
participant DB as Database
|
|
participant Source as External Source
|
|
|
|
C->>Cache: Request data
|
|
|
|
alt Cache Hit
|
|
Cache-->>C: Return cached
|
|
else Cache Miss
|
|
Cache->>DB: Query database
|
|
|
|
alt DB Hit
|
|
DB-->>Cache: Return data
|
|
Cache->>Cache: Store in cache
|
|
Cache-->>C: Return data
|
|
else DB Miss
|
|
DB-->>Cache: Not found
|
|
Cache->>Source: Fetch from source
|
|
Source-->>Cache: Return data
|
|
Cache->>DB: Persist
|
|
Cache->>Cache: Store in cache
|
|
Cache-->>C: Return data
|
|
end
|
|
end
|
|
```
|
|
|
|
## Cache Eviction Policies
|
|
|
|
| Policy | Description | Use Case |
|
|
|--------|-------------|----------|
|
|
| **LRU** | Least Recently Used | General purpose |
|
|
| **LFU** | Least Frequently Used | Hot data |
|
|
| **FIFO** | First In First Out | Time-sensitive |
|
|
| **TTL** | Time To Live only | Temporary data |
|
|
|
|
## Cache Configuration
|
|
|
|
```mermaid
|
|
classDiagram
|
|
class CacheConfig {
|
|
+size_t maxSize
|
|
+milliseconds defaultTtl
|
|
+EvictionPolicy policy
|
|
}
|
|
|
|
class HttpCache {
|
|
+maxSize: 1000
|
|
+ttl: 5 minutes
|
|
}
|
|
|
|
class TrackCache {
|
|
+maxSize: 500
|
|
+ttl: 1 hour
|
|
}
|
|
|
|
class MetadataCache {
|
|
+maxSize: 1000
|
|
+ttl: 30 minutes
|
|
}
|
|
|
|
CacheConfig <|-- HttpCache
|
|
CacheConfig <|-- TrackCache
|
|
CacheConfig <|-- MetadataCache
|
|
```
|
|
|
|
## Cache Statistics
|
|
|
|
```mermaid
|
|
classDiagram
|
|
class CacheStats {
|
|
+size_t hits
|
|
+size_t misses
|
|
+size_t evictions
|
|
+size_t inserts
|
|
+size_t currentSize
|
|
+double hitRate()
|
|
}
|
|
```
|
|
|
|
| Metric | Description |
|
|
|--------|-------------|
|
|
| Hits | Successful cache lookups |
|
|
| Misses | Failed lookups (fetch required) |
|
|
| Hit Rate | Hits / (Hits + Misses) |
|
|
| Evictions | Items removed due to size limit |
|
|
| Current Size | Active entries in cache |
|
|
|
|
## Database Optimization
|
|
|
|
```mermaid
|
|
flowchart LR
|
|
subgraph "Optimizations"
|
|
WAL[WAL Mode]
|
|
Index[Indexing]
|
|
Prep[Prepared Statements]
|
|
Batch[Batch Operations]
|
|
end
|
|
|
|
WAL -->|Concurrent reads| Perf[Better Performance]
|
|
Index -->|Fast lookups| Perf
|
|
Prep -->|Reuse plans| Perf
|
|
Batch -->|Fewer commits| Perf
|
|
```
|
|
|
|
| Technique | Benefit |
|
|
|-----------|---------|
|
|
| WAL Mode | Concurrent reads during writes |
|
|
| Indexing | Fast column lookups |
|
|
| Prepared Statements | Reuse query plans |
|
|
| Batch Operations | Fewer transaction commits |
|
|
|
|
## Schema Migrations
|
|
|
|
```mermaid
|
|
flowchart TB
|
|
Start[Start Migration] --> Check{Current<br/>Version?}
|
|
|
|
Check -->|v1| M1[Migration 1→2<br/>Add favorites table]
|
|
Check -->|v2| M2[Migration 2→3<br/>Add duration column]
|
|
Check -->|v3| M3[Migration 3→4<br/>Add indexes]
|
|
Check -->|Latest| Done[No migration needed]
|
|
|
|
M1 --> Update[Update version]
|
|
M2 --> Update
|
|
M3 --> Update
|
|
Update --> Verify{Success?}
|
|
|
|
Verify -->|Yes| Done2[Migration complete]
|
|
Verify -->|No| Rollback[Rollback changes]
|
|
```
|
|
|
|
## Performance Tuning
|
|
|
|
### Cache Size Guidelines
|
|
|
|
| Cache Type | Size | TTL | Rationale |
|
|
|------------|------|-----|-----------|
|
|
| HTTP | 100-1000 | 5 min | Short-lived responses |
|
|
| Track Info | 500-2000 | 1 hour | Stable metadata |
|
|
| Metadata | 1000-5000 | 30 min | Moderate change |
|
|
| Search Results | 100-500 | 10 min | Fresh results |
|
|
|
|
### Database Tuning
|
|
|
|
```mermaid
|
|
flowchart TB
|
|
subgraph "SQLite PRAGMAs"
|
|
WAL["journal_mode = WAL"]
|
|
SYNC["synchronous = NORMAL"]
|
|
CACHE["cache_size = 10000"]
|
|
TEMP["temp_store = MEMORY"]
|
|
end
|
|
|
|
WAL --> Throughput[Better Throughput]
|
|
SYNC --> Safety[Durability/Speed Balance]
|
|
CACHE --> Memory[More Memory Cache]
|
|
TEMP --> Speed[Faster Temp Tables]
|
|
```
|
|
|
|
## Monitoring
|
|
|
|
```mermaid
|
|
flowchart TB
|
|
subgraph "Metrics Collection"
|
|
CacheM[Cache Metrics]
|
|
DBM[Database Metrics]
|
|
Health[Health Checks]
|
|
end
|
|
|
|
CacheM -->|Export| Metrics[Metrics Endpoint]
|
|
DBM -->|Export| Metrics
|
|
Health -->|Export| Metrics
|
|
|
|
Metrics --> Dashboard[Dashboard]
|
|
Metrics --> Alerts[Alerts]
|
|
```
|
|
|
|
| Category | Metrics |
|
|
|----------|---------|
|
|
| Cache | Hit rate, size, memory, evictions |
|
|
| Database | Query time, connections, cache hits |
|
|
| Health | Availability, error rates |
|