teempe

PARALLEL_INTEGRATION_PROMPT.MD

Aug 23rd, 2025
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.71 KB | None | 0 0
  1. # Parallel Frontend-Backend Integration Execution Prompt
  2.  
  3. ## PROJECT CONTEXT
  4. **Project**: Pastebin Viewer Application
  5. **Current State**: Backend API functional, Frontend displaying mock data
  6. **Objective**: Complete frontend-backend integration using parallel agent execution
  7. **Timeline**: 2-3 days maximum
  8. **Execution Mode**: Parallel with defined synchronization points
  9.  
  10. ## CURRENT SYSTEM STATE
  11.  
  12. ### Backend (Kotlin/Spring Boot) - PORT 8080
  13. - ✅ All API endpoints operational
  14. - ✅ Database populated with test data
  15. - ✅ Health checks passing
  16. - ✅ CORS configured
  17. - ✅ Actuator endpoints available
  18.  
  19. ### Frontend (React/TypeScript) - PORT 5173
  20. - ❌ Using hardcoded mock data (`mockStats`)
  21. - ✅ Vite proxy configured correctly
  22. - ✅ API service layer exists but unused
  23. - ❌ Pages showing placeholder content
  24. - ✅ Type definitions present
  25.  
  26. ## PARALLEL EXECUTION PLAN
  27.  
  28. ### PHASE 0: INITIAL VERIFICATION (15 minutes)
  29. **Both Agents Execute Simultaneously**
  30.  
  31. #### Backend Agent Tasks:
  32. ```bash
  33. # Verify backend is running and healthy
  34. curl http://localhost:8080/actuator/health
  35. curl http://localhost:8080/api/stats
  36. curl http://localhost:8080/api/pastes?page=0&size=10
  37.  
  38. # Check database has data
  39. # Log first 5 pastes with classifications
  40. ```
  41.  
  42. #### Frontend Agent Tasks:
  43. ```bash
  44. # Verify frontend dev server is running
  45. curl http://localhost:5173
  46.  
  47. # Check current mock data structure
  48. # Document all hardcoded values in use
  49. # List all API endpoints that need connection
  50. ```
  51.  
  52. **Synchronization Point 0**: Both agents confirm systems are ready
  53.  
  54. ---
  55.  
  56. ### PHASE 1: FOUNDATION SETUP (30 minutes)
  57. **Parallel Execution with No Dependencies**
  58.  
  59. #### Backend Agent Tasks:
  60. 1. **Create Integration Test Endpoints**
  61. - `/api/test/connection` - Simple ping endpoint
  62. - `/api/test/data-summary` - Returns count of pastes, classifications
  63. - Document actual API response formats
  64.  
  65. 2. **Verify API Contracts**
  66. - Test each endpoint and document exact response structure
  67. - Create sample responses for frontend reference
  68. - File: `/backend/docs/API_RESPONSE_SAMPLES.md`
  69.  
  70. 3. **Add CORS Debug Logging**
  71. - Enable detailed CORS logging
  72. - Verify headers are correctly set
  73.  
  74. #### Frontend Agent Tasks:
  75. 1. **Create React Hooks Infrastructure**
  76. ```typescript
  77. // /frontend/src/hooks/useApi.ts
  78. export const useApi = <T>(
  79. apiCall: () => Promise<T>,
  80. deps: any[] = []
  81. ) => {
  82. const [data, setData] = useState<T | null>(null);
  83. const [loading, setLoading] = useState(true);
  84. const [error, setError] = useState<string | null>(null);
  85.  
  86. useEffect(() => {
  87. const fetchData = async () => {
  88. try {
  89. setLoading(true);
  90. setError(null);
  91. const result = await apiCall();
  92. setData(result);
  93. } catch (err) {
  94. setError(err.message || 'API call failed');
  95. } finally {
  96. setLoading(false);
  97. }
  98. };
  99.  
  100. fetchData();
  101. }, deps);
  102.  
  103. return { data, loading, error, refetch: fetchData };
  104. };
  105. ```
  106.  
  107. 2. **Create Common Components**
  108. - `/frontend/src/components/common/LoadingSpinner.tsx` (if not exists)
  109. - `/frontend/src/components/common/ErrorBoundary.tsx`
  110. - `/frontend/src/components/common/RetryError.tsx`
  111.  
  112. 3. **Update Type Definitions**
  113. - Align with backend response structures
  114. - Add pagination types
  115. - Add API error types
  116.  
  117. **Synchronization Point 1**: Share API response samples between agents
  118.  
  119. ---
  120.  
  121. ### PHASE 2: DASHBOARD INTEGRATION (45 minutes)
  122. **Sequential within phase, parallel between agents**
  123.  
  124. #### Backend Agent Tasks:
  125. 1. **Create Aggregated Stats Endpoint**
  126. ```kotlin
  127. @GetMapping("/api/dashboard/stats")
  128. fun getDashboardStats(): DashboardStats {
  129. return DashboardStats(
  130. totalPastes = pasteService.getTotalCount(),
  131. recentPastes = pasteService.getRecentCount(24.hours),
  132. classifications = classificationService.getCountByType(),
  133. systemHealth = healthService.getSystemStatus(),
  134. lastScrapingTime = scrapingService.getLastRunTime(),
  135. queueSize = kafkaService?.getQueueSize() ?: 0
  136. )
  137. }
  138. ```
  139.  
  140. 2. **Add Real-time Metrics**
  141. - Response time metrics
  142. - Active connections count
  143. - Error rate calculation
  144.  
  145. #### Frontend Agent Tasks:
  146. 1. **Replace Mock Data in App.tsx**
  147. ```typescript
  148. // REMOVE: import { mockStats } from '@/services/mockData';
  149. // ADD:
  150. import { apiService } from '@/services/api';
  151. import { useApi } from '@/hooks/useApi';
  152.  
  153. function App() {
  154. const { data: stats, loading, error, refetch } = useApi(
  155. () => apiService.getDashboardStats(),
  156. []
  157. );
  158.  
  159. // Auto-refresh every 30 seconds
  160. useEffect(() => {
  161. const interval = setInterval(refetch, 30000);
  162. return () => clearInterval(interval);
  163. }, [refetch]);
  164.  
  165. if (loading) return <LoadingSpinner fullScreen />;
  166. if (error) return <ErrorMessage message={error} onRetry={refetch} />;
  167. if (!stats) return <EmptyState message="No data available" />;
  168.  
  169. // Rest of component...
  170. }
  171. ```
  172.  
  173. 2. **Update Dashboard Component**
  174. - Add refresh button
  175. - Show last updated timestamp
  176. - Implement skeleton loading for cards
  177.  
  178. **Validation Checkpoint**: Dashboard shows real backend data
  179.  
  180. ---
  181.  
  182. ### PHASE 3: PASTES PAGE IMPLEMENTATION (1 hour)
  183. **Agents work on complementary tasks**
  184.  
  185. #### Backend Agent Tasks:
  186. 1. **Optimize Paste Endpoints**
  187. ```kotlin
  188. @GetMapping("/api/pastes")
  189. fun getPastes(
  190. @RequestParam(defaultValue = "0") page: Int,
  191. @RequestParam(defaultValue = "20") size: Int,
  192. @RequestParam(required = false) search: String?,
  193. @RequestParam(required = false) classification: String?,
  194. @RequestParam(defaultValue = "createdAt,desc") sort: String
  195. ): Page<PasteDto>
  196. ```
  197.  
  198. 2. **Add Paste Details Endpoint**
  199. ```kotlin
  200. @GetMapping("/api/pastes/{id}/full")
  201. fun getPasteWithDetails(@PathVariable id: String): PasteDetailsDto
  202. ```
  203.  
  204. 3. **Create Search Suggestions Endpoint**
  205. ```kotlin
  206. @GetMapping("/api/pastes/suggestions")
  207. fun getSearchSuggestions(@RequestParam query: String): List<String>
  208. ```
  209.  
  210. #### Frontend Agent Tasks:
  211. 1. **Create Paste List Components**
  212. ```typescript
  213. // /frontend/src/components/pastes/PasteList.tsx
  214. export const PasteList: React.FC = () => {
  215. const [page, setPage] = useState(0);
  216. const [filters, setFilters] = useState<PasteFilters>({});
  217.  
  218. const { data, loading, error } = useApi(
  219. () => apiService.getPastes(page, 20, filters),
  220. [page, filters]
  221. );
  222.  
  223. return (
  224. <div className="space-y-4">
  225. <PasteFilters onChange={setFilters} />
  226. {loading && <LoadingSpinner />}
  227. {error && <ErrorMessage message={error} />}
  228. {data && (
  229. <>
  230. <div className="grid gap-4">
  231. {data.content.map(paste => (
  232. <PasteCard key={paste.id} paste={paste} />
  233. ))}
  234. </div>
  235. <Pagination
  236. current={page}
  237. total={data.totalPages}
  238. onChange={setPage}
  239. />
  240. </>
  241. )}
  242. </div>
  243. );
  244. };
  245. ```
  246.  
  247. 2. **Implement Pastes Page**
  248. - Replace placeholder content
  249. - Add paste details modal
  250. - Implement search functionality
  251.  
  252. **Validation Checkpoint**: Pastes page displays paginated data from backend
  253.  
  254. ---
  255.  
  256. ### PHASE 4: CLASSIFICATIONS PAGE (45 minutes)
  257. **Parallel implementation with shared components**
  258.  
  259. #### Backend Agent Tasks:
  260. 1. **Create Classification Statistics Endpoint**
  261. ```kotlin
  262. @GetMapping("/api/classifications/statistics")
  263. fun getClassificationStats(): ClassificationStats
  264.  
  265. @GetMapping("/api/classifications/timeline")
  266. fun getClassificationTimeline(
  267. @RequestParam days: Int = 7
  268. ): List<TimelineEntry>
  269. ```
  270.  
  271. 2. **Add Filtering Capabilities**
  272. ```kotlin
  273. @GetMapping("/api/classifications")
  274. fun getClassifications(
  275. @RequestParam(required = false) type: ClassificationType?,
  276. @RequestParam(required = false) minConfidence: Double?,
  277. @RequestParam(required = false) startDate: LocalDateTime?,
  278. @RequestParam(required = false) endDate: LocalDateTime?
  279. ): Page<ClassificationDto>
  280. ```
  281.  
  282. #### Frontend Agent Tasks:
  283. 1. **Create Classification Components**
  284. ```typescript
  285. // /frontend/src/components/classifications/ClassificationList.tsx
  286. export const ClassificationList: React.FC = () => {
  287. const [filters, setFilters] = useState<ClassificationFilters>({
  288. type: null,
  289. minConfidence: 0.5,
  290. dateRange: 'week'
  291. });
  292.  
  293. const { data, loading, error } = useApi(
  294. () => apiService.getClassifications(filters),
  295. [filters]
  296. );
  297.  
  298. // Component implementation
  299. };
  300. ```
  301.  
  302. 2. **Add Visualization Components**
  303. - Classification type distribution chart
  304. - Confidence score histogram
  305. - Timeline graph
  306.  
  307. **Validation Checkpoint**: Classifications page shows filtered results
  308.  
  309. ---
  310.  
  311. ### PHASE 5: ERROR HANDLING & RESILIENCE (30 minutes)
  312. **Both agents implement complementary error handling**
  313.  
  314. #### Backend Agent Tasks:
  315. 1. **Implement Global Exception Handler**
  316. ```kotlin
  317. @RestControllerAdvice
  318. class GlobalExceptionHandler {
  319. @ExceptionHandler(ResourceNotFoundException::class)
  320. fun handleNotFound(e: ResourceNotFoundException): ResponseEntity<ApiError> {
  321. return ResponseEntity.status(404).body(
  322. ApiError(
  323. timestamp = Instant.now(),
  324. status = 404,
  325. error = "Not Found",
  326. message = e.message ?: "Resource not found",
  327. path = request.servletPath
  328. )
  329. )
  330. }
  331. }
  332. ```
  333.  
  334. 2. **Add Circuit Breaker for External Services**
  335. 3. **Implement Request Validation**
  336.  
  337. #### Frontend Agent Tasks:
  338. 1. **Create Toast Notification System**
  339. ```typescript
  340. // /frontend/src/contexts/ToastContext.tsx
  341. export const useToast = () => {
  342. const show = (message: string, type: 'success' | 'error' | 'info') => {
  343. // Implementation
  344. };
  345.  
  346. return { show };
  347. };
  348. ```
  349.  
  350. 2. **Add Retry Logic to API Service**
  351. ```typescript
  352. const retryWithBackoff = async <T>(
  353. fn: () => Promise<T>,
  354. maxRetries = 3
  355. ): Promise<T> => {
  356. for (let i = 0; i < maxRetries; i++) {
  357. try {
  358. return await fn();
  359. } catch (error) {
  360. if (i === maxRetries - 1) throw error;
  361. await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
  362. }
  363. }
  364. throw new Error('Max retries exceeded');
  365. };
  366. ```
  367.  
  368. 3. **Implement Offline Detection**
  369.  
  370. **Validation Checkpoint**: Error scenarios handled gracefully
  371.  
  372. ---
  373.  
  374. ### PHASE 6: REAL-TIME UPDATES (30 minutes)
  375. **Optional - Implement if time permits**
  376.  
  377. #### Backend Agent Tasks:
  378. 1. **Add SSE Endpoint for Live Updates**
  379. ```kotlin
  380. @GetMapping("/api/stream/updates", produces = [MediaType.TEXT_EVENT_STREAM_VALUE])
  381. fun streamUpdates(): Flux<ServerSentEvent<UpdateEvent>>
  382. ```
  383.  
  384. 2. **Implement Change Detection Service**
  385.  
  386. #### Frontend Agent Tasks:
  387. 1. **Create SSE Hook**
  388. ```typescript
  389. export const useServerSentEvents = (url: string) => {
  390. const [events, setEvents] = useState<any[]>([]);
  391.  
  392. useEffect(() => {
  393. const eventSource = new EventSource(url);
  394.  
  395. eventSource.onmessage = (event) => {
  396. const data = JSON.parse(event.data);
  397. setEvents(prev => [...prev, data]);
  398. };
  399.  
  400. return () => eventSource.close();
  401. }, [url]);
  402.  
  403. return events;
  404. };
  405. ```
  406.  
  407. 2. **Add Live Update Indicators**
  408. - New paste notifications
  409. - Classification completion alerts
  410.  
  411. ---
  412.  
  413. ### PHASE 7: TESTING & VALIDATION (45 minutes)
  414. **Both agents run comprehensive tests**
  415.  
  416. #### Backend Agent Tasks:
  417. 1. **Integration Test Suite**
  418. ```kotlin
  419. @Test
  420. fun `should return dashboard stats`() {
  421. val stats = restTemplate.getForObject(
  422. "http://localhost:8080/api/dashboard/stats",
  423. DashboardStats::class.java
  424. )
  425.  
  426. assertThat(stats).isNotNull
  427. assertThat(stats.totalPastes).isGreaterThan(0)
  428. }
  429. ```
  430.  
  431. 2. **Load Testing**
  432. ```bash
  433. # Using Apache Bench
  434. ab -n 1000 -c 10 http://localhost:8080/api/pastes
  435. ```
  436.  
  437. #### Frontend Agent Tasks:
  438. 1. **Component Tests**
  439. ```typescript
  440. describe('PasteList', () => {
  441. it('should fetch and display pastes', async () => {
  442. render(<PasteList />);
  443.  
  444. await waitFor(() => {
  445. expect(screen.getByText(/paste title/i)).toBeInTheDocument();
  446. });
  447. });
  448.  
  449. it('should handle API errors', async () => {
  450. // Mock API error
  451. apiService.getPastes = jest.fn().mockRejectedValue(new Error('API Error'));
  452.  
  453. render(<PasteList />);
  454.  
  455. await waitFor(() => {
  456. expect(screen.getByText(/API Error/i)).toBeInTheDocument();
  457. });
  458. });
  459. });
  460. ```
  461.  
  462. 2. **E2E Test Scenarios**
  463. - User journey from dashboard to paste details
  464. - Filter and search functionality
  465. - Error recovery flows
  466.  
  467. ---
  468.  
  469. ## ERROR HANDLING STRATEGIES
  470.  
  471. ### Backend Agent Error Handling:
  472. 1. **Database Connection Lost**: Implement retry with exponential backoff
  473. 2. **Kafka Unavailable**: Fallback to direct database writes
  474. 3. **External API Timeout**: Circuit breaker pattern
  475. 4. **Out of Memory**: Implement request throttling
  476.  
  477. ### Frontend Agent Error Handling:
  478. 1. **Network Failure**: Show offline banner, queue actions
  479. 2. **401 Unauthorized**: Redirect to login (if auth implemented)
  480. 3. **500 Server Error**: Show friendly error with retry
  481. 4. **Timeout**: Show timeout message with retry option
  482.  
  483. ## ROLLBACK PROCEDURES
  484.  
  485. ### If Integration Fails:
  486. 1. **Frontend Rollback**:
  487. ```bash
  488. # Revert to mock data
  489. git checkout -- frontend/src/App.tsx
  490. npm run dev
  491. ```
  492.  
  493. 2. **Backend Rollback**:
  494. ```bash
  495. # Revert to previous version
  496. git checkout -- backend/src/main/kotlin/
  497. ./gradlew bootRun
  498. ```
  499.  
  500. ## SUCCESS CRITERIA
  501.  
  502. ### Must Have (Critical):
  503. - [ ] Dashboard displays real backend data
  504. - [ ] Pastes list loads with pagination
  505. - [ ] Classifications page shows data
  506. - [ ] No console errors in production mode
  507. - [ ] API error handling works
  508.  
  509. ### Should Have (Important):
  510. - [ ] Auto-refresh on dashboard
  511. - [ ] Search functionality works
  512. - [ ] Filters work correctly
  513. - [ ] Loading states for all async operations
  514. - [ ] Toast notifications for actions
  515.  
  516. ### Nice to Have (Optional):
  517. - [ ] Real-time updates via SSE/WebSocket
  518. - [ ] Offline mode support
  519. - [ ] Advanced search with suggestions
  520. - [ ] Export functionality
  521. - [ ] Keyboard shortcuts
  522.  
  523. ## VALIDATION COMMANDS
  524.  
  525. ### Backend Validation:
  526. ```bash
  527. # Health check
  528. curl http://localhost:8080/actuator/health
  529.  
  530. # Stats endpoint
  531. curl http://localhost:8080/api/dashboard/stats | jq .
  532.  
  533. # Pastes with pagination
  534. curl "http://localhost:8080/api/pastes?page=0&size=5" | jq .
  535.  
  536. # Classifications
  537. curl http://localhost:8080/api/classifications | jq .
  538. ```
  539.  
  540. ### Frontend Validation:
  541. ```bash
  542. # Build check
  543. cd frontend && npm run build
  544.  
  545. # Type check
  546. npm run type-check
  547.  
  548. # Test suite
  549. npm test
  550.  
  551. # Lint check
  552. npm run lint
  553. ```
  554.  
  555. ### Integration Validation:
  556. ```bash
  557. # Check proxy is working
  558. curl http://localhost:5173/api/health
  559.  
  560. # Check CORS headers
  561. curl -H "Origin: http://localhost:5173" \
  562. -I http://localhost:8080/api/pastes
  563.  
  564. # Monitor network tab in browser DevTools
  565. # Should see API calls to /api/* endpoints
  566. ```
  567.  
  568. ## COMMON ISSUES & SOLUTIONS
  569.  
  570. ### Issue: CORS Errors
  571. **Solution**: Ensure backend has proper CORS configuration:
  572. ```kotlin
  573. @CrossOrigin(origins = ["http://localhost:5173"])
  574. ```
  575.  
  576. ### Issue: Type Mismatches
  577. **Solution**: Generate types from backend OpenAPI spec or manually align
  578.  
  579. ### Issue: Proxy Not Working
  580. **Solution**: Verify vite.config.ts proxy configuration:
  581. ```typescript
  582. proxy: {
  583. '/api': {
  584. target: 'http://localhost:8080',
  585. changeOrigin: true,
  586. secure: false
  587. }
  588. }
  589. ```
  590.  
  591. ### Issue: Data Not Updating
  592. **Solution**: Check React dependency arrays in useEffect hooks
  593.  
  594. ### Issue: Memory Leaks
  595. **Solution**: Clean up intervals/subscriptions in useEffect cleanup
  596.  
  597. ## EXECUTION NOTES
  598.  
  599. 1. **Communication Protocol**:
  600. - Agents should log progress every 15 minutes
  601. - Use clear markers for synchronization points
  602. - Document any blockers immediately
  603.  
  604. 2. **File Organization**:
  605. - Backend changes: `/backend/src/main/kotlin/`
  606. - Frontend changes: `/frontend/src/`
  607. - Shared docs: `/docs/integration/`
  608.  
  609. 3. **Testing Protocol**:
  610. - Test each phase before moving to next
  611. - Keep both systems running during integration
  612. - Use browser DevTools Network tab to monitor API calls
  613.  
  614. 4. **Performance Targets**:
  615. - API response time < 200ms (P95)
  616. - Frontend initial load < 2 seconds
  617. - Smooth scrolling with 100+ items
  618.  
  619. ## FINAL CHECKLIST
  620.  
  621. ### Before Starting:
  622. - [ ] Backend running on port 8080
  623. - [ ] Frontend running on port 5173
  624. - [ ] Database has test data
  625. - [ ] All dependencies installed
  626.  
  627. ### After Completion:
  628. - [ ] All mock data removed
  629. - [ ] All API endpoints connected
  630. - [ ] Error handling implemented
  631. - [ ] Loading states implemented
  632. - [ ] Tests passing
  633. - [ ] No console errors
  634. - [ ] Documentation updated
  635.  
  636. ## AGENT COORDINATION MARKERS
  637.  
  638. Use these markers in your responses for clarity:
  639.  
  640. ```
  641. [BACKEND-AGENT: PHASE_1_START]
  642. [FRONTEND-AGENT: PHASE_1_START]
  643. [SYNC_POINT_1: READY]
  644. [VALIDATION: DASHBOARD_CONNECTED]
  645. [BLOCKER: <description>]
  646. [COMPLETE: PHASE_3]
  647. ```
  648.  
  649. ---
  650.  
  651. **Execute this plan systematically. Prioritize working features over perfect code. Focus on getting the integration working end-to-end first, then optimize.**
Advertisement
Add Comment
Please, Sign In to add comment