|
| 1 | +import { db } from '@sim/db' |
| 2 | +import { tableRunDispatches, userTableRows } from '@sim/db/schema' |
| 3 | +import { createLogger } from '@sim/logger' |
| 4 | +import { generateId } from '@sim/utils/id' |
| 5 | +import { and, asc, eq, gt, inArray, sql } from 'drizzle-orm' |
| 6 | +import { appendTableEvent } from '@/lib/table/events' |
| 7 | +import type { RowData, TableRow } from '@/lib/table/types' |
| 8 | +import { |
| 9 | + isGroupEligible, |
| 10 | + scheduleRunsForRows, |
| 11 | + type ScheduleOpts, |
| 12 | + TABLE_CONCURRENCY_LIMIT, |
| 13 | + toTableRow, |
| 14 | +} from './workflow-columns' |
| 15 | + |
| 16 | +const logger = createLogger('TableRunDispatcher') |
| 17 | + |
| 18 | +/** Window size matches the cell-execution concurrency cap so one window |
| 19 | + * saturates the pool before the next is loaded — yields a row-major |
| 20 | + * scan-line crawl (rows 1-20 finish before 21-40 start). */ |
| 21 | +const WINDOW_SIZE = TABLE_CONCURRENCY_LIMIT |
| 22 | + |
| 23 | +const ACTIVE_DISPATCH_STATUSES = ['pending', 'dispatching'] as const |
| 24 | + |
| 25 | +export type DispatchStatus = 'pending' | 'dispatching' | 'complete' | 'cancelled' |
| 26 | +export type DispatchMode = 'all' | 'incomplete' |
| 27 | + |
| 28 | +export interface DispatchScope { |
| 29 | + groupIds: string[] |
| 30 | + rowIds?: string[] |
| 31 | +} |
| 32 | + |
| 33 | +export interface DispatchRow { |
| 34 | + id: string |
| 35 | + tableId: string |
| 36 | + workspaceId: string |
| 37 | + requestId: string |
| 38 | + mode: DispatchMode |
| 39 | + scope: DispatchScope |
| 40 | + status: DispatchStatus |
| 41 | + cursor: number |
| 42 | + requestedAt: Date |
| 43 | +} |
| 44 | + |
| 45 | +export type DispatcherStepResult = 'continue' | 'done' |
| 46 | + |
| 47 | +export async function insertDispatch(input: { |
| 48 | + tableId: string |
| 49 | + workspaceId: string |
| 50 | + requestId: string |
| 51 | + mode: DispatchMode |
| 52 | + scope: DispatchScope |
| 53 | +}): Promise<string> { |
| 54 | + const id = `tdsp_${generateId().replace(/-/g, '')}` |
| 55 | + await db.insert(tableRunDispatches).values({ |
| 56 | + id, |
| 57 | + tableId: input.tableId, |
| 58 | + workspaceId: input.workspaceId, |
| 59 | + requestId: input.requestId, |
| 60 | + mode: input.mode, |
| 61 | + scope: input.scope, |
| 62 | + status: 'pending', |
| 63 | + cursor: 0, |
| 64 | + }) |
| 65 | + return id |
| 66 | +} |
| 67 | + |
| 68 | +export async function readDispatch(dispatchId: string): Promise<DispatchRow | null> { |
| 69 | + const [row] = await db |
| 70 | + .select() |
| 71 | + .from(tableRunDispatches) |
| 72 | + .where(eq(tableRunDispatches.id, dispatchId)) |
| 73 | + .limit(1) |
| 74 | + if (!row) return null |
| 75 | + return { |
| 76 | + id: row.id, |
| 77 | + tableId: row.tableId, |
| 78 | + workspaceId: row.workspaceId, |
| 79 | + requestId: row.requestId, |
| 80 | + mode: row.mode as DispatchMode, |
| 81 | + scope: row.scope as DispatchScope, |
| 82 | + status: row.status as DispatchStatus, |
| 83 | + cursor: row.cursor, |
| 84 | + requestedAt: row.requestedAt, |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +/** Run one window of the dispatcher state machine. Caller re-invokes (via the |
| 89 | + * trigger.dev task wrapper) until the returned status is `'done'`. */ |
| 90 | +export async function dispatcherStep(dispatchId: string): Promise<DispatcherStepResult> { |
| 91 | + const dispatch = await readDispatch(dispatchId) |
| 92 | + if (!dispatch) { |
| 93 | + logger.warn(`[${dispatchId}] dispatch row missing — aborting`) |
| 94 | + return 'done' |
| 95 | + } |
| 96 | + if (dispatch.status === 'cancelled' || dispatch.status === 'complete') return 'done' |
| 97 | + |
| 98 | + if (dispatch.status === 'pending') { |
| 99 | + await db |
| 100 | + .update(tableRunDispatches) |
| 101 | + .set({ status: 'dispatching' }) |
| 102 | + .where(eq(tableRunDispatches.id, dispatchId)) |
| 103 | + } |
| 104 | + |
| 105 | + const { getTableById, batchUpdateRows } = await import('./service') |
| 106 | + const table = await getTableById(dispatch.tableId) |
| 107 | + if (!table) { |
| 108 | + logger.warn(`[${dispatchId}] table ${dispatch.tableId} missing — completing dispatch`) |
| 109 | + await markDispatchComplete(dispatchId) |
| 110 | + return 'done' |
| 111 | + } |
| 112 | + |
| 113 | + const allGroups = table.schema.workflowGroups ?? [] |
| 114 | + const targetGroups = allGroups.filter((g) => dispatch.scope.groupIds.includes(g.id)) |
| 115 | + if (targetGroups.length === 0) { |
| 116 | + await markDispatchComplete(dispatchId) |
| 117 | + return 'done' |
| 118 | + } |
| 119 | + |
| 120 | + const filters = [ |
| 121 | + eq(userTableRows.tableId, dispatch.tableId), |
| 122 | + gt(userTableRows.position, dispatch.cursor), |
| 123 | + ] |
| 124 | + if (dispatch.scope.rowIds && dispatch.scope.rowIds.length > 0) { |
| 125 | + filters.push(inArray(userTableRows.id, dispatch.scope.rowIds)) |
| 126 | + } |
| 127 | + |
| 128 | + const chunk = await db |
| 129 | + .select() |
| 130 | + .from(userTableRows) |
| 131 | + .where(and(...filters)) |
| 132 | + .orderBy(asc(userTableRows.position)) |
| 133 | + .limit(WINDOW_SIZE) |
| 134 | + |
| 135 | + if (chunk.length === 0) { |
| 136 | + await markDispatchComplete(dispatchId) |
| 137 | + await appendTableEvent({ |
| 138 | + kind: 'dispatch', |
| 139 | + tableId: dispatch.tableId, |
| 140 | + dispatchId, |
| 141 | + status: 'complete', |
| 142 | + }) |
| 143 | + return 'done' |
| 144 | + } |
| 145 | + |
| 146 | + type Update = { |
| 147 | + rowId: string |
| 148 | + data: RowData |
| 149 | + executionsPatch: Record<string, null> |
| 150 | + } |
| 151 | + const updates: Update[] = [] |
| 152 | + const clearedRows: TableRow[] = [] |
| 153 | + for (const r of chunk) { |
| 154 | + const tableRow = toTableRow(r) |
| 155 | + const eligibleGroups = targetGroups.filter((g) => { |
| 156 | + // Skip cells the user explicitly cancelled after this dispatch |
| 157 | + // started — a per-row cancel mid-cascade must stick even under |
| 158 | + // isManualRun, otherwise the dispatcher resurrects the row. |
| 159 | + const exec = tableRow.executions?.[g.id] |
| 160 | + if (exec?.cancelledAt) { |
| 161 | + const cancelledAtMs = Date.parse(exec.cancelledAt) |
| 162 | + if (Number.isFinite(cancelledAtMs) && cancelledAtMs > dispatch.requestedAt.getTime()) { |
| 163 | + return false |
| 164 | + } |
| 165 | + } |
| 166 | + return isGroupEligible(g, tableRow, { isManualRun: true, mode: dispatch.mode }) |
| 167 | + }) |
| 168 | + if (eligibleGroups.length === 0) continue |
| 169 | + |
| 170 | + const clearedData: RowData = {} |
| 171 | + const executionsPatch: Record<string, null> = {} |
| 172 | + for (const g of eligibleGroups) { |
| 173 | + for (const o of g.outputs) clearedData[o.columnName] = null |
| 174 | + executionsPatch[g.id] = null |
| 175 | + } |
| 176 | + updates.push({ rowId: r.id, data: clearedData, executionsPatch }) |
| 177 | + |
| 178 | + const remainingExec = { ...tableRow.executions } |
| 179 | + for (const g of eligibleGroups) delete remainingExec[g.id] |
| 180 | + clearedRows.push({ |
| 181 | + ...tableRow, |
| 182 | + data: { ...tableRow.data, ...clearedData }, |
| 183 | + executions: remainingExec, |
| 184 | + }) |
| 185 | + } |
| 186 | + |
| 187 | + // Cursor advances to the last position in this chunk regardless of |
| 188 | + // eligibility — otherwise a window full of completed cells loops forever. |
| 189 | + const lastPosition = chunk[chunk.length - 1].position |
| 190 | + |
| 191 | + if (updates.length > 0) { |
| 192 | + await batchUpdateRows( |
| 193 | + { |
| 194 | + tableId: dispatch.tableId, |
| 195 | + updates, |
| 196 | + workspaceId: dispatch.workspaceId, |
| 197 | + skipScheduler: true, |
| 198 | + }, |
| 199 | + table, |
| 200 | + dispatch.requestId |
| 201 | + ) |
| 202 | + |
| 203 | + const scheduleOpts: ScheduleOpts = { |
| 204 | + isManualRun: true, |
| 205 | + groupIds: dispatch.scope.groupIds, |
| 206 | + mode: dispatch.mode, |
| 207 | + } |
| 208 | + await scheduleRunsForRows(table, clearedRows, scheduleOpts) |
| 209 | + } |
| 210 | + |
| 211 | + await Promise.all([ |
| 212 | + advanceCursor(dispatchId, lastPosition), |
| 213 | + appendTableEvent({ |
| 214 | + kind: 'dispatch', |
| 215 | + tableId: dispatch.tableId, |
| 216 | + dispatchId, |
| 217 | + status: 'dispatching', |
| 218 | + }), |
| 219 | + ]) |
| 220 | + |
| 221 | + return 'continue' |
| 222 | +} |
| 223 | + |
| 224 | +async function advanceCursor(dispatchId: string, newCursor: number): Promise<void> { |
| 225 | + await db |
| 226 | + .update(tableRunDispatches) |
| 227 | + .set({ cursor: newCursor }) |
| 228 | + .where(eq(tableRunDispatches.id, dispatchId)) |
| 229 | +} |
| 230 | + |
| 231 | +async function markDispatchComplete(dispatchId: string): Promise<void> { |
| 232 | + await db |
| 233 | + .update(tableRunDispatches) |
| 234 | + .set({ status: 'complete', completedAt: new Date() }) |
| 235 | + .where(eq(tableRunDispatches.id, dispatchId)) |
| 236 | +} |
| 237 | + |
| 238 | +export async function markDispatchCancelled(dispatchId: string): Promise<void> { |
| 239 | + await db |
| 240 | + .update(tableRunDispatches) |
| 241 | + .set({ status: 'cancelled', cancelledAt: new Date() }) |
| 242 | + .where( |
| 243 | + and( |
| 244 | + eq(tableRunDispatches.id, dispatchId), |
| 245 | + inArray(tableRunDispatches.status, [...ACTIVE_DISPATCH_STATUSES]) |
| 246 | + ) |
| 247 | + ) |
| 248 | +} |
| 249 | + |
| 250 | +/** Mark every active dispatch on this table as cancelled. Single atomic |
| 251 | + * UPDATE so the dispatcher's next iteration observes the cancel. */ |
| 252 | +export async function markActiveDispatchesCancelled(tableId: string): Promise<void> { |
| 253 | + await db |
| 254 | + .update(tableRunDispatches) |
| 255 | + .set({ status: 'cancelled', cancelledAt: new Date() }) |
| 256 | + .where( |
| 257 | + and( |
| 258 | + eq(tableRunDispatches.tableId, tableId), |
| 259 | + inArray(tableRunDispatches.status, [...ACTIVE_DISPATCH_STATUSES]) |
| 260 | + ) |
| 261 | + ) |
| 262 | +} |
0 commit comments