Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import type { RefreshResult } from '@/lib/reports/types'
3import { getReportState, getSSEController } from '@/lib/reports/report-storage'
4import { refreshComponent } from '@/lib/reports/refresh-component'
5import { evaluateWatchersForSignals } from '@/lib/reports/evaluate-watchers'
6
7export const Route = createFileRoute('/_reporting/api/invalidate')({
8 server: {
9 handlers: {
10 POST: async ({ request }) => {
11 const body = await request.json()
12 const { reportId, signals } = body
13
14 console.log('[Invalidate] Request received:', { reportId, signals })
15
16 if (!reportId || !signals || !Array.isArray(signals)) {
17 console.log('[Invalidate] Missing reportId or signals')
18 return new Response(
19 JSON.stringify({ error: 'Missing reportId or signals array' }),
20 { status: 400, headers: { 'Content-Type': 'application/json' } },
21 )
22 }
23
24 const reportState = getReportState(reportId)
25 if (!reportState) {
26 console.log('[Invalidate] Report not found:', reportId)
27 return new Response(JSON.stringify({ error: 'Report not found' }), {
28 status: 404,
29 headers: { 'Content-Type': 'application/json' },
30 })
31 }
32
33 console.log('[Invalidate] Report found, nodes:', reportState.nodes.size)
34
35 // Collect all subscribers for the invalidated signals
36 const subscribersToRefresh = new Set<string>()
37 for (const signal of signals) {
38 const subscribers = reportState.signalRegistry.getSubscribers(signal)
39 console.log(
40 `[Invalidate] Signal "${signal}" subscribers:`,
41 Array.from(subscribers),
42 )
43 for (const subscriberId of subscribers) {
44 subscribersToRefresh.add(subscriberId)
45 }
46 }
47
48 console.log(
49 '[Invalidate] Total subscribers to refresh:',
50 Array.from(subscribersToRefresh),
51 )
52
53 // Refresh each subscriber
54 const refreshResults: RefreshResult[] = []
55 for (const componentId of subscribersToRefresh) {
56 console.log('[Invalidate] Refreshing component:', componentId)
57 const result = await refreshComponent(reportState, componentId)
58 console.log('[Invalidate] Refresh result:', result)
59 refreshResults.push(result)
60 }
61
62 console.log(
63 '[Invalidate] Total refresh results:',
64 refreshResults.length,
65 )
66
67 // Evaluate watchers for the invalidated signals
68 const invalidatedSignals = new Set(signals as string[])
69 const watcherResults = await evaluateWatchersForSignals(
70 reportState,
71 invalidatedSignals,
72 )
73
74 // Push updates via SSE if connected
75 const sseController = getSSEController(reportId)
76 console.log('[Invalidate] SSE controller exists:', !!sseController)
77
78 if (sseController) {
79 // Push component refresh results
80 if (refreshResults.length > 0) {
81 const refreshMessage = `data: ${JSON.stringify({
82 type: 'refresh',
83 results: refreshResults,
84 })}\n\n`
85 console.log('[Invalidate] Pushing refresh message via SSE')
86 try {
87 sseController.enqueue(new TextEncoder().encode(refreshMessage))
88 console.log('[Invalidate] SSE message pushed successfully')
89 } catch (e) {
90 console.log('[Invalidate] SSE push failed:', e)
91 }
92 }
93
94 // Push watcher effects (toasts, etc.)
95 if (watcherResults.effects.length > 0) {
96 const effectsMessage = `data: ${JSON.stringify({
97 type: 'effects',
98 effects: watcherResults.effects,
99 })}\n\n`
100 try {
101 sseController.enqueue(new TextEncoder().encode(effectsMessage))
102 } catch {
103 // Connection may have closed
104 }
105 }
106 }
107
108 return new Response(
109 JSON.stringify({
110 success: true,
111 refreshed: refreshResults.length,
112 results: refreshResults,
113 watcherResults: watcherResults.results,
114 effects: watcherResults.effects,
115 }),
116 { headers: { 'Content-Type': 'application/json' } },
117 )
118 },
119 },
120 },
121})