Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

evaluate-watchers.ts

166 lines4.8 KB

1import type { WatcherResult, WatcherSubscription } from './types'
2import type { ServerReportState } from './report-storage'
3import { markWatcherFired } from './report-storage'
4​
5/**
6 * Creates read-only bindings for watcher condition evaluation.
7 * Same as dataSource - only data fetching, no effects.
8 */
9async function createConditionBindings() {
10 const { createHandlerBindings } = await import('./create-handler-bindings')
11 const handlerBindings = createHandlerBindings()
12​
13 return {
14 external_get_balances: handlerBindings.external_get_balances,
15 external_get_transactions: handlerBindings.external_get_transactions,
16 }
18​
19/**
20 * Creates bindings for watcher action execution.
21 * Includes effect bindings like toast.
22 */
23async function createActionBindings(
24 onEffect: (effect: { type: string; params: Record<string, unknown> }) => void,
25) {
26 const { createHandlerBindings } = await import('./create-handler-bindings')
27 const handlerBindings = createHandlerBindings({
28 report: { id: '', title: '', createdAt: 0, updatedAt: 0 },
29 onEffect: onEffect as any,
30 onUIUpdate: () => {},
31 })
32​
33 return {
34 external_get_balances: handlerBindings.external_get_balances,
35 external_get_transactions: handlerBindings.external_get_transactions,
36 external_ui_toast: handlerBindings.external_ui_toast,
37 }
39​
40/**
41 * Evaluate a single watcher's condition and execute its action if true.
42 */
43export async function evaluateWatcher(
44 reportState: ServerReportState,
45 watcher: WatcherSubscription,
46 collectedEffects: Array<{ type: string; params: Record<string, unknown> }>,
47): Promise<WatcherResult> {
48 const { createIsolateDriver } = await import('@/lib/create-isolate-driver')
49 const driver = await createIsolateDriver()
50​
51 // First, evaluate the condition
52 const conditionContext = await driver.createContext({
53 bindings: await createConditionBindings(),
54 timeout: 3000,
55 memoryLimit: 32,
56 })
57​
58 let conditionMet = false
59 try {
60 const conditionCode = `(async () => { ${watcher.condition} })()`
61 const conditionResult = await conditionContext.execute(conditionCode)
62​
63 if (!conditionResult.success) {
64 return {
65 watcherId: watcher.id,
66 conditionMet: false,
67 actionExecuted: false,
68 error: `Condition error: ${conditionResult.error?.message}`,
69 }
70 }
71​
72 conditionMet = Boolean(conditionResult.value)
73 } catch (error) {
74 return {
75 watcherId: watcher.id,
76 conditionMet: false,
77 actionExecuted: false,
78 error: `Condition error: ${error instanceof Error ? error.message : String(error)}`,
79 }
80 } finally {
81 await conditionContext.dispose()
82 }
83​
84 // If condition not met, we're done
85 if (!conditionMet) {
86 return {
87 watcherId: watcher.id,
88 conditionMet: false,
89 actionExecuted: false,
90 }
91 }
92​
93 // Execute the action
94 const actionContext = await driver.createContext({
95 bindings: await createActionBindings((effect) =>
96 collectedEffects.push(effect),
97 ),
98 timeout: 5000,
99 memoryLimit: 64,
100 })
101​
102 try {
103 const actionCode = `(async () => { ${watcher.action} })()`
104 const actionResult = await actionContext.execute(actionCode)
105​
106 // Mark watcher as fired
107 markWatcherFired(reportState.report.id, watcher.id)
108​
109 if (!actionResult.success) {
110 return {
111 watcherId: watcher.id,
112 conditionMet: true,
113 actionExecuted: false,
114 error: `Action error: ${actionResult.error?.message}`,
115 }
116 }
117​
118 return {
119 watcherId: watcher.id,
120 conditionMet: true,
121 actionExecuted: true,
122 }
123 } catch (error) {
124 return {
125 watcherId: watcher.id,
126 conditionMet: true,
127 actionExecuted: false,
128 error: `Action error: ${error instanceof Error ? error.message : String(error)}`,
129 }
130 } finally {
131 await actionContext.dispose()
132 }
134​
135/**
136 * Evaluate all watchers for the given invalidated signals.
137 * Returns results and collected effects.
138 */
139export async function evaluateWatchersForSignals(
140 reportState: ServerReportState,
141 invalidatedSignals: Set<string>,
142): Promise<{
143 results: WatcherResult[]
144 effects: Array<{ type: string; params: Record<string, unknown> }>
145}> {
146 const results: WatcherResult[] = []
147 const effects: Array<{ type: string; params: Record<string, unknown> }> = []
148​
149 // Collect watchers that monitor any of the invalidated signals
150 const watchersToEvaluate = new Set<WatcherSubscription>()
151 for (const signal of invalidatedSignals) {
152 for (const watcher of reportState.watchers.values()) {
153 if (watcher.signals.includes(signal) && !watcher.fired) {
154 watchersToEvaluate.add(watcher)
155 }
156 }
157 }
158​
159 // Evaluate each watcher
160 for (const watcher of watchersToEvaluate) {
161 const result = await evaluateWatcher(reportState, watcher, effects)
162 results.push(result)
163 }
164​
165 return { results, effects }