The services layer provides business logic abstraction between UI components and the database layer. All 17 services follow consistent patterns and never expose IndexedDB operations directly to components.
Purpose: Adaptive session creation and problem selection algorithms
Key Methods:
createAdaptiveSession()- Generates personalized learning sessionsgetSessionProblems()- Selects problems based on mastery and FSRSgetProblemByDescription()- Fetches problems from standard_problems or problems stores
Integration: TagService (mastery analysis), ScheduleService (FSRS), SessionService (session building)
Purpose: Session lifecycle management and performance analysis
Key Methods:
summarizeSessionPerformance()- Comprehensive session analysis and mastery updatesbuildSession()- Constructs session objects with metadatacompleteSession()- Finalizes sessions and triggers analytics
Integration: AttemptsService (performance data), TagService (mastery updates), ProblemService (problem relationships)
Purpose: Tag mastery and learning state management
Key Methods:
getCurrentLearningState()- Analyzes current mastery across all tagsgetIntelligentFocusTags()- Identifies tags needing focused practiceupdateTagMastery()- Recalculates mastery scores after attempts
Integration: Database (tag_mastery, pattern_ladders), ScheduleService (FSRS calculations)
Purpose: Problem attempt tracking and statistics
Key Methods:
recordAttempt()- Logs individual problem attempts with timinggetAttemptHistory()- Retrieves attempt data for analysiscalculateSuccessRates()- Computes performance metrics
Integration: SessionService (session updates), TagService (mastery updates)
Purpose: Spaced repetition scheduling using FSRS algorithm
Key Methods:
getDailyReviewSchedule()- Generates review schedule based on FSRScalculateNextReview()- Determines optimal review timingupdateCardParameters()- Updates FSRS parameters after attempts
Integration: TagService (mastery state), ProblemService (problem selection)
getTagStrategy()- Provides contextual hints for algorithm patternsgeneratePrimers()- Creates educational content for algorithm concepts
generateReasoning()- Creates "Why This Problem?" explanationsanalyzeSelectionContext()- Provides context for problem recommendations
updateRelationships()- Maintains problem relationship graphfindSimilarProblems()- Identifies related problems for recommendations
getSettings()- Retrieves user preferencessaveSettings()- Persists configuration changes
getDashboardStatistics()- Compiles performance metricsgenerateInsights()- Creates performance insights
Purpose: Database operation resilience with retry logic and timeout handling
Key Methods:
executeWithRetry()- Executes database operations with exponential backoffcreateTimeoutPromise()- Provides timeout handling for long-running operationsdeduplicateRequests()- Prevents duplicate simultaneous operations
Features: Circuit breaker patterns, operation prioritization, performance monitoring
Purpose: Robust Chrome extension message handling with error recovery
Key Methods:
sendMessageWithRetry()- Chrome messaging with automatic retry and fallbackhandleChromeError()- Intelligent error classification and recoveryvalidateChromeResponse()- Response validation and error detection
Features: Exponential backoff, network error handling, extension context validation
All services follow these patterns:
export const ServiceName = {
// Primary operations
async primaryOperation(params) {
// Business logic
return result;
},
// Data retrieval
async getData(criteria) {
// Database queries via db layer
return data;
},
// State updates
async updateState(changes) {
// State management logic
return updated;
},
};- All services implement consistent error handling
- Database errors are caught and transformed into user-friendly messages
- Async operations include proper error propagation
- Services communicate through well-defined interfaces
- No direct database access from components
- Chrome API access through useChromeMessage hook
- State updates flow through service layer
// Component using service through Chrome messaging
const { data, loading, error } = useChromeMessage(
{ type: "createSession" },
[],
{
onSuccess: (response) => setSession(response.session),
onError: (error) => console.error("Session creation failed:", error),
}
);// Background script handler
case "createSession":
try {
const session = await ProblemService.createAdaptiveSession(request.params);
sendResponse({ success: true, session });
} catch (error) {
sendResponse({ success: false, error: error.message });
}
break;Each service has comprehensive test coverage in __tests__/ directory:
- Unit Tests: Individual service method testing
- Integration Tests: Service-to-service interaction testing
- Mock Data: Standardized test data via
mockDataFactories.js
Current test coverage: 110 total tests passing with high coverage across all critical service functions.
Services implement automatic fallback to stable functionality when enhanced features fail:
const session = await HabitLearningCircuitBreaker.safeExecute(
() => createEnhancedSession(params),
() => createBasicSession(params),
"session-creation"
);Database Retry Strategy:
- Exponential backoff: 100ms → 200ms → 400ms delays
- Max 3 retries for critical operations
- Configurable timeouts per operation type
- Deduplication prevents duplicate operations
Chrome API Retry Strategy:
- Network error recovery with automatic retry
- Context validation handles extension context loss
- Response validation retries on malformed responses
- Graceful degradation when Chrome APIs fail
Built-in operation tracking captures:
- Operation latency and success rates
- Retry frequency and patterns
- Error categorization and trends
- Cache hit rates and performance impact
All services are located in chrome-extension-app/src/shared/services/:
Core Services:
problemService.js- Problem selection and session creationsessionService.js- Session management and analyticstagServices.js- Tag mastery and learning stateattemptsService.js- Attempt tracking and statisticsscheduleService.js- FSRS spaced repetition scheduling
Infrastructure Services:
ChromeAPIErrorHandler.js- Chrome messaging with retry logicIndexedDBRetryService.js- Database resilience and performancestorageService.js- Chrome storage API wrapper
Feature Services:
strategyService.js- Algorithm hints and educational contentdashboardService.js- Analytics data aggregationproblemReasoningService.js- Problem selection explanationsproblemRelationshipService.js- Problem similarity analysis
For detailed implementation examples and integration patterns, see the service source files and their corresponding test suites.