mirror of
https://github.com/CherryHQ/cherry-studio.git
synced 2025-12-30 07:39:06 +08:00
- Revised the README files for shared data and main data layers to improve clarity and structure. - Consolidated documentation on shared data types and API types, removing the now-deleted `api-design-guidelines.md`. - Streamlined directory structure descriptions and updated links to relevant documentation. - Enhanced quick reference sections for better usability and understanding of the data architecture. |
||
|---|---|---|
| .. | ||
| api-design-guidelines.md | ||
| api-types.md | ||
| cache-overview.md | ||
| cache-usage.md | ||
| data-api-in-main.md | ||
| data-api-in-renderer.md | ||
| data-api-overview.md | ||
| database-patterns.md | ||
| preference-overview.md | ||
| preference-usage.md | ||
| README.md | ||
| v2-migration-guide.md | ||
Data System Reference
This is the main entry point for Cherry Studio's data management documentation. The application uses three distinct data systems based on data characteristics.
Quick Navigation
System Overview (Architecture)
- Cache Overview - Three-tier caching architecture
- Preference Overview - User settings management
- DataApi Overview - Business data API architecture
Usage Guides (Code Examples)
- Cache Usage - useCache hooks, CacheService examples
- Preference Usage - usePreference hook, PreferenceService examples
- DataApi in Renderer - useQuery/useMutation, DataApiService
- DataApi in Main - Handlers, Services, Repositories patterns
Reference Guides (Coding Standards)
- API Design Guidelines - RESTful design rules
- Database Patterns - DB naming, schema patterns
- API Types - API type system, schemas, error handling
- V2 Migration Guide - Migration system
Choosing the Right System
Quick Decision Table
| Service | Data Characteristics | Lifecycle | Data Loss Impact | Examples |
|---|---|---|---|---|
| CacheService | Regenerable, temporary | ≤ App process or survives restart | None to minimal | API responses, computed results, UI state |
| PreferenceService | User settings, key-value | Permanent until changed | Low (can rebuild) | Theme, language, font size, shortcuts |
| DataApiService | Business data, structured | Permanent | Severe (irreplaceable) | Topics, messages, files, knowledge base |
Decision Flowchart
Ask these questions in order:
-
Can this data be regenerated or lost without affecting the user?
- Yes → CacheService
- No → Continue to #2
-
Is this a user-configurable setting that affects app behavior?
- Yes → Does it have a fixed key and stable value structure?
- Yes → PreferenceService
- No (structure changes often) → DataApiService
- No → Continue to #3
- Yes → Does it have a fixed key and stable value structure?
-
Is this business data created/accumulated through user activity?
- Yes → DataApiService
- No → Reconsider #1 (most data falls into one of these categories)
System Characteristics
CacheService - Runtime & Cache Data
Use CacheService when:
- Data can be regenerated or lost without user impact
- No backup or cross-device synchronization needed
- Lifecycle is tied to component, window, or app session
Two sub-categories:
- Performance cache: Computed results, API responses, expensive calculations
- UI state cache: Temporary settings, scroll positions, panel states
Three tiers based on persistence needs:
useCache(memory): Lost on app restart, component-level sharinguseSharedCache(shared): Cross-window sharing, lost on restartusePersistCache(persist): Survives app restarts via localStorage
// Good: Temporary computed results
const [searchResults, setSearchResults] = useCache('search.results', [])
// Good: UI state that can be lost
const [sidebarCollapsed, setSidebarCollapsed] = useSharedCache('ui.sidebar.collapsed', false)
// Good: Recent items (nice to have, not critical)
const [recentSearches, setRecentSearches] = usePersistCache('search.recent', [])
PreferenceService - User Preferences
Use PreferenceService when:
- Data is a user-modifiable setting that affects app behavior
- Structure is key-value with predefined keys (users modify values, not keys)
- Value structure is stable (won't change frequently)
- Data loss has low impact (user can reconfigure)
Key characteristics:
- Auto-syncs across all windows
- Each preference item should be atomic (one setting = one key)
- Values are typically: boolean, string, number, or simple array/object
// Good: App behavior settings
const [theme, setTheme] = usePreference('app.theme.mode')
const [language, setLanguage] = usePreference('app.language')
const [fontSize, setFontSize] = usePreference('chat.message.font_size')
// Good: Feature toggles
const [showTimestamp, setShowTimestamp] = usePreference('chat.display.show_timestamp')
DataApiService - User Data
Use DataApiService when:
- Data is business data accumulated through user activity
- Data is structured with dedicated schemas/tables
- Users can create, delete, modify records (no fixed limit)
- Data loss would be severe and irreplaceable
- Data volume can be large (potentially GBs)
Key characteristics:
- No automatic window sync (fetch on demand for fresh data)
- May contain sensitive data (encryption consideration)
- Requires proper CRUD operations and transactions
// Good: User-generated business data
const { data: topics } = useQuery('/topics')
const { trigger: createTopic } = useMutation('/topics', 'POST')
// Good: Conversation history (irreplaceable)
const { data: messages } = useQuery('/messages', { query: { topicId } })
// Good: User files and knowledge base
const { data: files } = useQuery('/files')
Common Anti-patterns
| Wrong Choice | Why It's Wrong | Correct Choice |
|---|---|---|
| Storing AI provider configs in Cache | User loses configured providers on restart | PreferenceService |
| Storing conversation history in Preferences | Unbounded growth, complex structure | DataApiService |
| Storing topic list in Preferences | User-created records, can grow large | DataApiService |
| Storing theme/language in DataApi | Overkill for simple key-value settings | PreferenceService |
| Storing API responses in DataApi | Regenerable data, doesn't need persistence | CacheService |
| Storing window positions in Preferences | Can be lost without impact | CacheService (persist tier) |
Edge Cases
- Recently used items (e.g., recent files, recent searches): Use
usePersistCache- nice to have but not critical if lost - Draft content (e.g., unsaved message): Use
useSharedCachefor cross-window, consider auto-save to DataApi for recovery - Computed statistics: Use
useCachewith TTL - regenerate when expired - User-created templates/presets: Use DataApiService - user-generated content that can grow
Architecture Overview
┌─────────────────┐
│ React Components│
└─────────┬───────┘
│
┌─────────▼───────┐
│ React Hooks │ ← useDataApi, usePreference, useCache
└─────────┬───────┘
│
┌─────────▼───────┐
│ Services │ ← DataApiService, PreferenceService, CacheService
└─────────┬───────┘
│
┌─────────▼───────┐
│ IPC Layer │ ← Main Process Communication
└─────────────────┘
Related Source Code
Type Definitions
packages/shared/data/api/- API type systempackages/shared/data/cache/- Cache type definitionspackages/shared/data/preference/- Preference type definitions
Main Process Implementation
src/main/data/api/- API server and handlerssrc/main/data/CacheService.ts- Cache servicesrc/main/data/PreferenceService.ts- Preference servicesrc/main/data/db/- Database schemas
Renderer Process Implementation
src/renderer/src/data/DataApiService.ts- API clientsrc/renderer/src/data/CacheService.ts- Cache servicesrc/renderer/src/data/PreferenceService.ts- Preference servicesrc/renderer/src/data/hooks/- React hooks