Performance Monitoring
Relevant source files
The following files were used as context for generating this wiki page:
The performance monitoring system in Vinesight is a two-fold feature set designed to track and analyze performance from both a technical and an agricultural perspective. It includes client-side hooks for measuring web application performance (e.g., component render times, Core Web Vitals) and a comprehensive backend and frontend system for analyzing farm operational efficiency (e.g., yield per hectare, water usage).
This dual approach ensures that the application is both technically performant for a smooth user experience and effective in delivering actionable insights on agricultural performance. The system logs technical metrics to the console in development and provides a dedicated "Farm Efficiency Dashboard" for users to monitor their agricultural productivity.
Client-Side Performance Hooks
The core of the technical performance monitoring is implemented through a set of custom React hooks located in src/hooks/usePerformanceMonitor.ts. These hooks can be integrated into any component to measure various performance aspects.
Sources: src/hooks/usePerformanceMonitor.ts
Available Hooks
| Hook Name | Description |
|---|---|
usePerformanceMonitor | Measures component-specific metrics like load time, render time, and memory usage. |
useAsyncPerformance | A utility hook to measure the duration of asynchronous operations, logging the time taken for success or failure. |
useBundleAnalyzer | Tracks bundle-related metrics for a given chunk using the PerformanceNavigationTiming API. |
useCoreWebVitals | Utilizes PerformanceObserver to monitor and log Core Web Vitals: Largest Contentful Paint (LCP), First Input Delay (FID), and Cumulative Layout Shift (CLS). |
Sources: src/hooks/usePerformanceMonitor.ts:10-221
usePerformanceMonitor
This is the primary hook for component-level monitoring. It tracks the lifecycle of a component from initial render to mount.
Data Structure
The hook collects metrics into the PerformanceMetrics interface.
// src/hooks/usePerformanceMonitor.ts:5-10
interface PerformanceMetrics {
loadTime: number
renderTime: number
componentName: string
memoryUsage?: number
}
Measurement Flow
The following diagram illustrates how usePerformanceMonitor captures metrics.
This diagram shows the flow of the usePerformanceMonitor hook, capturing start time, then calculating load time on mount and render time on each subsequent render.
Sources: src/hooks/usePerformanceMonitor.ts:13-60
useAsyncPerformance
This hook provides a measureAsync function to wrap and time any promise-based operation.
// src/hooks/usePerformanceMonitor.ts:91-115
export function useAsyncPerformance() {
const measureAsync = useCallback(
async <T>(operation: () => Promise<T>, operationName: string): Promise<T> => {
const startTime = Date.now()
try {
const result = await operation()
const duration = Date.now() - startTime
if (process.env.NODE_ENV === 'development') {
console.log(`🚀 Async Operation [${operationName}]:`, `${duration}ms`)
}
return result
} catch (error) {
const duration = Date.now() - startTime
if (process.env.NODE_ENV === 'development') {
console.error(`❌ Async Operation Failed [${operationName}]:`, `${duration}ms`, error)
}
throw error
}
},
[],
)
return { measureAsync }
}
Sources: src/hooks/usePerformanceMonitor.ts:91-115
Farm Efficiency Dashboard
The /performance page provides a user-facing dashboard to monitor agricultural performance metrics for a selected farm. It is a practical application of the performance monitoring philosophy, focusing on operational efficiency rather than technical metrics.
Sources: src/app/performance/page.tsx
Architecture and Data Flow
The dashboard fetches farm data and various operational records to calculate key efficiency metrics.
This sequence diagram shows the data flow for the Farm Efficiency Dashboard, from user interaction to data fetching and rendering.
Sources: src/app/performance/page.tsx:43-85, src/lib/supabase-service.ts:133-149, 253-264
Key Metrics
The dashboard calculates and displays several FarmEfficiencyMetric objects.
FarmEfficiencyMetric Interface
| Field | Type | Description |
|---|---|---|
name | string | The name of the metric (e.g., 'Yield per Hectare'). |
value | number | The calculated value of the metric. |
unit | string | The unit for the metric's value (e.g., 'kg/ha'). |
status | 'excellent' | 'good' | 'needs-improvement' | 'poor' | A qualitative status based on the value against benchmarks. |
benchmark | number | The target value for the metric. |
category | 'yield' | 'water' | 'cost' | 'quality' | The category the metric belongs to. |
Sources: src/app/performance/page.tsx:28-36
Metric Calculation
Metrics are derived from raw operational data fetched from CloudDataService. For example, Yield per Hectare is calculated by summing the quantity from all harvest records and dividing by the farm's area.
// src/app/performance/page.tsx:89-94
// Calculate efficiency metrics based on real data
const totalHarvest = harvestRecords.reduce((sum, record) => sum + record.quantity, 0)
const totalIrrigation = irrigationRecords.reduce(
(sum, record) => sum + record.duration * record.system_discharge,
0,
)
const yieldPerHectare = totalHarvest / selectedFarm.area
Sources: src/app/performance/page.tsx:89-94
An overall efficiency score is also calculated by averaging the scores of individual metrics.
// src/app/performance/page.tsx:236-247
const calculateOverallScore = () => {
if (metrics.length === 0) return 0
const scores = metrics.map((metric) => {
if (metric.status === 'excellent') return 100
if (metric.status === 'good') return 85
if (metric.status === 'needs-improvement') return 60
return 30
})
return Math.round(scores.reduce((sum, score) => sum + score, 0) / scores.length)
}
Sources: src/app/performance/page.tsx:236-247
Backend Analytics Service
The AnalyticsService provides a more advanced, server-side approach to performance analysis, generating in-depth reports on cost, yield, and overall farm performance.
Sources: src/lib/analytics-service.ts
Service Architecture
The AnalyticsService is a static class that aggregates data from multiple farm records to produce a comprehensive AdvancedAnalytics object.
This class diagram shows the structure of the AnalyticsService and the data models it produces.
Sources: src/lib/analytics-service.ts:6-60
Key Analysis Methods
| Method | Description |
|---|---|
generateAdvancedAnalytics | The main entry point that orchestrates the generation of cost, yield, and performance analyses. |
calculateCostAnalysis | Aggregates expense and harvest records to calculate total costs, profit margin, ROI, and cost breakdowns by category and month. |
calculateYieldAnalysis | Calculates current yield, yield efficiency against benchmarks, historical trends, and a simple projection for future yield. |
calculatePerformanceMetrics | Scores farm practices in irrigation, nutrition, and pest management to produce an overall performance score and generate actionable recommendations and alerts. |
Sources: src/lib/analytics-service.ts:62-397
The service relies on CloudDataService (which uses SupabaseService) to fetch the necessary records for its calculations, similar to the Farm Efficiency Dashboard.
Sources: src/lib/analytics-service.ts:83, 97, src/lib/supabase-service.ts
Conclusion
The performance monitoring capabilities in Vinesight are robust and multi-faceted. On the client side, a suite of custom hooks provides developers with the tools to measure and optimize application responsiveness and user experience. On the agricultural side, both a user-facing dashboard and a backend analytics service work in tandem to transform raw farm data into meaningful performance indicators. This allows users to track their farm's efficiency, identify areas for improvement, and make data-driven decisions to enhance productivity and profitability, fulfilling a key objective outlined in the project's requirements.
Sources: src/hooks/usePerformanceMonitor.ts, src/app/performance/page.tsx, src/lib/analytics-service.ts, context/PRD.md:144-152