6bf8bebf51
CI / Test and Build (push) Failing after 1s
CI / Migrate Dev DB (push) Has been skipped
CI / Migrate DB (push) Has been skipped
CodeQL / Analyze actions (push) Has been cancelled
CodeQL / Analyze javascript-typescript (push) Has been cancelled
CI / Detect Version (push) Has been cancelled
CI / Detect Desktop Changes (push) Has been cancelled
CI / Build AMD64 (blacksmith-2vcpu-ubuntu-2404, ./docker/cron.Dockerfile, ubuntu-latest, ghcr.io/simstudioai/cron) (push) Has been cancelled
CI / Build AMD64 (blacksmith-2vcpu-ubuntu-2404, ./docker/db.Dockerfile, ECR_MIGRATIONS, ubuntu-latest, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (blacksmith-4vcpu-ubuntu-2404, ./docker/pii.Dockerfile, ECR_PII, ubuntu-latest, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (blacksmith-4vcpu-ubuntu-2404, ./docker/realtime.Dockerfile, ECR_REALTIME, ubuntu-latest, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build AMD64 (blacksmith-8vcpu-ubuntu-2404, ./docker/app.Dockerfile, ECR_APP, linux-x64-8-core, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (blacksmith-4vcpu-ubuntu-2404-arm, ./docker/cron.Dockerfile, ubuntu-24.04-arm, ghcr.io/simstudioai/cron) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (blacksmith-4vcpu-ubuntu-2404-arm, ./docker/db.Dockerfile, ubuntu-24.04-arm, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (blacksmith-4vcpu-ubuntu-2404-arm, ./docker/pii.Dockerfile, ubuntu-24.04-arm, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (blacksmith-4vcpu-ubuntu-2404-arm, ./docker/realtime.Dockerfile, ubuntu-24.04-arm, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (blacksmith-8vcpu-ubuntu-2404-arm, ./docker/app.Dockerfile, linux-arm64-8-core, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
Helm Chart / Lint, test, and validate chart (push) Has been cancelled
Helm Chart / Chart version bumped (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled
CI / Build Dev ECR (blacksmith-8vcpu-ubuntu-2404, ./docker/app.Dockerfile, ECR_APP, linux-x64-8-core) (push) Has been cancelled
CI / Promote Images (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/cron) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build Dev ECR (blacksmith-2vcpu-ubuntu-2404, ./docker/db.Dockerfile, ECR_MIGRATIONS, ubuntu-latest) (push) Has been cancelled
CI / Build Dev ECR (blacksmith-4vcpu-ubuntu-2404, ./docker/pii.Dockerfile, ECR_PII, ubuntu-latest) (push) Has been cancelled
CI / Build Dev ECR (blacksmith-4vcpu-ubuntu-2404, ./docker/realtime.Dockerfile, ECR_REALTIME, ubuntu-latest) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Check Desktop Signing Secrets (push) Has been cancelled
CI / Desktop Release (push) Has been cancelled
CI / Create Desktop Prerelease (push) Has been cancelled
CI / Desktop Prerelease Build (push) Has been cancelled
CI / Publish Desktop Prerelease (push) Has been cancelled
CI / Prune Desktop Prereleases (push) Has been cancelled
Helm Chart / Install on kind and run helm test (push) Has been cancelled
183 lines
6.2 KiB
TypeScript
183 lines
6.2 KiB
TypeScript
/**
|
|
* Direct trigger firing for table row events.
|
|
*
|
|
* When rows are inserted or updated in a table, this module looks up any
|
|
* active webhook triggers watching that table and fires workflow executions
|
|
* immediately - no polling or cron involved.
|
|
*/
|
|
|
|
import { createLogger } from '@sim/logger'
|
|
import { generateShortId } from '@sim/utils/id'
|
|
import { fillMissingColumns, namedRowMapper } from '@/lib/table/cell-format'
|
|
import { buildNameById } from '@/lib/table/column-keys'
|
|
import type { RowData, TableRow, TableSchema } from '@/lib/table/types'
|
|
import { readCanonicalTriggerValue } from '@/lib/webhooks/polling/canonical'
|
|
|
|
const logger = createLogger('TableTrigger')
|
|
|
|
type EventType = 'insert' | 'update'
|
|
|
|
interface TableTriggerPayload {
|
|
row: Record<string, unknown> | null
|
|
rawRow: Record<string, unknown>
|
|
previousRow: Record<string, unknown> | null
|
|
changedColumns: string[]
|
|
rowId: string
|
|
headers: string[]
|
|
tableId: string
|
|
tableName: string
|
|
timestamp: string
|
|
}
|
|
|
|
interface WebhookConfig {
|
|
tableId?: string
|
|
tableSelector?: string
|
|
manualTableId?: string
|
|
eventType?: string
|
|
watchColumns?: string | string[]
|
|
includeHeaders?: boolean
|
|
}
|
|
|
|
/**
|
|
* Fires workflow triggers for table row changes.
|
|
*
|
|
* This is fire-and-forget - errors are logged but never thrown.
|
|
* Call with `void fireTableTrigger(...)` to avoid blocking the caller.
|
|
*
|
|
* @param eventType - 'insert' for new rows, 'update' for changed rows
|
|
* @param oldRows - Map of row ID to previous data. Pass null for inserts.
|
|
*/
|
|
export async function fireTableTrigger(
|
|
tableId: string,
|
|
tableName: string,
|
|
eventType: EventType,
|
|
rows: TableRow[],
|
|
oldRows: Map<string, RowData> | null,
|
|
schema: TableSchema,
|
|
requestId: string
|
|
): Promise<void> {
|
|
try {
|
|
// Lazy: the webhook utils/processor pull in the executor + blocks stack.
|
|
// Eager imports would force every `lib/table/service` consumer (e.g. the
|
|
// dispatcher) to pay that cold-start even when no trigger fires.
|
|
const { fetchActiveWebhooks } = await import('@/lib/webhooks/polling/utils')
|
|
const webhooks = await fetchActiveWebhooks('table')
|
|
if (webhooks.length === 0) return
|
|
|
|
const headers = schema.columns.map((c) => c.name)
|
|
// The webhook payload is name-keyed (the workflow author references columns
|
|
// by name) and carries option names, not stored select ids — the mapper
|
|
// translates both in one pass. Hoisted: reused for every row and webhook.
|
|
const toNamedRow = namedRowMapper(schema.columns)
|
|
const nameById = buildNameById(schema)
|
|
|
|
// Filter to webhooks watching this table with a matching event type
|
|
const matching = webhooks.filter((entry) => {
|
|
const config = entry.webhook.providerConfig as WebhookConfig | null
|
|
// Canonical key `tableId` first; `tableSelector`/`manualTableId` are a transitional
|
|
// basic-first fallback for configs deployed before the canonical key was written.
|
|
const configTableId = readCanonicalTriggerValue(
|
|
config?.tableId,
|
|
config?.tableSelector,
|
|
config?.manualTableId
|
|
)
|
|
if (configTableId !== tableId) return false
|
|
|
|
const configEventType = config?.eventType ?? 'insert'
|
|
return configEventType === eventType
|
|
})
|
|
|
|
if (matching.length === 0) return
|
|
|
|
const { processPolledWebhookEvent } = await import('@/lib/webhooks/processor')
|
|
|
|
logger.info(
|
|
`[${requestId}] Firing ${matching.length} trigger(s) for ${rows.length} ${eventType} event(s) in table ${tableId}`
|
|
)
|
|
|
|
for (const { webhook: webhookData, workflow: workflowData } of matching) {
|
|
const config = webhookData.providerConfig as WebhookConfig | null
|
|
const watchColumns = parseWatchColumns(config?.watchColumns)
|
|
const includeHeaders = config?.includeHeaders !== false
|
|
|
|
for (const row of rows) {
|
|
const previousIdData = oldRows?.get(row.id) ?? null
|
|
const rawRow = toNamedRow(row.data)
|
|
const previousRow = previousIdData ? toNamedRow(previousIdData) : null
|
|
const changedColumns = previousIdData
|
|
? detectChangedColumns(previousIdData, row.data)
|
|
.map((id) => nameById.get(id))
|
|
.filter((name): name is string => name !== undefined)
|
|
: []
|
|
|
|
// For updates with watch columns, skip rows where no watched column changed
|
|
if (eventType === 'update' && watchColumns.length > 0) {
|
|
const hasWatchedChange = changedColumns.some((col) => watchColumns.includes(col))
|
|
if (!hasWatchedChange) continue
|
|
}
|
|
|
|
// `row` is `rawRow` widened so its key set matches `headers` exactly.
|
|
const mappedRow =
|
|
includeHeaders && headers.length > 0 ? fillMissingColumns(rawRow, schema.columns) : null
|
|
|
|
const payload: TableTriggerPayload = {
|
|
row: mappedRow,
|
|
rawRow,
|
|
previousRow,
|
|
changedColumns,
|
|
rowId: row.id,
|
|
headers,
|
|
tableId,
|
|
tableName,
|
|
timestamp: new Date().toISOString(),
|
|
}
|
|
|
|
const eventRequestId = generateShortId()
|
|
|
|
try {
|
|
const result = await processPolledWebhookEvent(
|
|
webhookData,
|
|
workflowData,
|
|
payload,
|
|
eventRequestId
|
|
)
|
|
|
|
if (!result.success) {
|
|
logger.error(
|
|
`[${eventRequestId}] Failed to fire table trigger for row ${row.id}:`,
|
|
result.statusCode,
|
|
result.error
|
|
)
|
|
}
|
|
} catch (error) {
|
|
logger.error(`[${eventRequestId}] Error firing table trigger for row ${row.id}:`, error)
|
|
}
|
|
}
|
|
}
|
|
} catch (error) {
|
|
logger.error(`[${requestId}] Error in fireTableTrigger:`, error)
|
|
}
|
|
}
|
|
|
|
function parseWatchColumns(watchColumns: string | string[] | undefined): string[] {
|
|
if (!watchColumns) return []
|
|
if (Array.isArray(watchColumns)) return watchColumns.filter(Boolean)
|
|
return watchColumns
|
|
.split(',')
|
|
.map((c) => c.trim())
|
|
.filter(Boolean)
|
|
}
|
|
|
|
function detectChangedColumns(oldData: RowData, newData: RowData): string[] {
|
|
const changed: string[] = []
|
|
const allKeys = new Set([...Object.keys(oldData), ...Object.keys(newData)])
|
|
|
|
for (const key of allKeys) {
|
|
if (JSON.stringify(oldData[key]) !== JSON.stringify(newData[key])) {
|
|
changed.push(key)
|
|
}
|
|
}
|
|
|
|
return changed
|
|
}
|