Skip to content

Commit 0fbbbe0

Browse files
fix(execution-counts): execution counts by trigger type recorded accurately (#1670)
1 parent 29c7827 commit 0fbbbe0

File tree

6 files changed

+24
-82
lines changed

6 files changed

+24
-82
lines changed

apps/sim/app/api/workflows/[id]/execute/route.ts

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
1-
import { db } from '@sim/db'
2-
import { userStats } from '@sim/db/schema'
31
import { tasks } from '@trigger.dev/sdk'
4-
import { eq, sql } from 'drizzle-orm'
52
import { type NextRequest, NextResponse } from 'next/server'
63
import { v4 as uuidv4 } from 'uuid'
74
import { z } from 'zod'
@@ -134,7 +131,8 @@ export async function executeWorkflow(
134131
throw new Error('Execution is already running')
135132
}
136133

137-
const loggingSession = new LoggingSession(workflowId, executionId, 'api', requestId)
134+
const triggerType: TriggerType = streamConfig?.workflowTriggerType || 'api'
135+
const loggingSession = new LoggingSession(workflowId, executionId, triggerType, requestId)
138136

139137
const usageCheck = await checkServerSideUsageLimits(actorUserId)
140138
if (usageCheck.isExceeded) {
@@ -367,14 +365,6 @@ export async function executeWorkflow(
367365

368366
if (result.success) {
369367
await updateWorkflowRunCounts(workflowId)
370-
371-
await db
372-
.update(userStats)
373-
.set({
374-
totalApiCalls: sql`total_api_calls + 1`,
375-
lastActive: sql`now()`,
376-
})
377-
.where(eq(userStats.userId, actorUserId))
378368
}
379369

380370
if (!streamConfig?.skipLoggingComplete) {

apps/sim/app/api/workflows/[id]/stats/route.ts

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -41,20 +41,17 @@ export async function POST(request: NextRequest, { params }: { params: Promise<{
4141
throw error
4242
}
4343

44-
// Upsert user stats record
4544
try {
46-
// Check if record exists
4745
const userStatsRecords = await db
4846
.select()
4947
.from(userStats)
5048
.where(eq(userStats.userId, workflowRecord.userId))
5149

5250
if (userStatsRecords.length === 0) {
53-
// Create new record if none exists
5451
await db.insert(userStats).values({
5552
id: crypto.randomUUID(),
5653
userId: workflowRecord.userId,
57-
totalManualExecutions: runs,
54+
totalManualExecutions: 0,
5855
totalApiCalls: 0,
5956
totalWebhookTriggers: 0,
6057
totalScheduledExecutions: 0,
@@ -64,17 +61,15 @@ export async function POST(request: NextRequest, { params }: { params: Promise<{
6461
lastActive: sql`now()`,
6562
})
6663
} else {
67-
// Update existing record
6864
await db
6965
.update(userStats)
7066
.set({
71-
totalManualExecutions: sql`total_manual_executions + ${runs}`,
72-
lastActive: new Date(),
67+
lastActive: sql`now()`,
7368
})
7469
.where(eq(userStats.userId, workflowRecord.userId))
7570
}
7671
} catch (error) {
77-
logger.error(`Error upserting userStats for userId ${workflowRecord.userId}:`, error)
72+
logger.error(`Error ensuring userStats for userId ${workflowRecord.userId}:`, error)
7873
// Don't rethrow - we want to continue even if this fails
7974
}
8075

apps/sim/app/workspace/[workspaceId]/w/[workflowId]/hooks/use-workflow-execution.ts

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -503,7 +503,8 @@ export function useWorkflowExecution() {
503503
workflowInput,
504504
onStream,
505505
executionId,
506-
onBlockComplete
506+
onBlockComplete,
507+
'chat'
507508
)
508509

509510
// Check if execution was cancelled
@@ -611,7 +612,13 @@ export function useWorkflowExecution() {
611612
// For manual (non-chat) execution
612613
const executionId = uuidv4()
613614
try {
614-
const result = await executeWorkflow(workflowInput, undefined, executionId)
615+
const result = await executeWorkflow(
616+
workflowInput,
617+
undefined,
618+
executionId,
619+
undefined,
620+
'manual'
621+
)
615622
if (result && 'metadata' in result && result.metadata?.isDebugSession) {
616623
setDebugContext(result.metadata.context || null)
617624
if (result.metadata.pendingBlocks) {
@@ -666,7 +673,8 @@ export function useWorkflowExecution() {
666673
workflowInput?: any,
667674
onStream?: (se: StreamingExecution) => Promise<void>,
668675
executionId?: string,
669-
onBlockComplete?: (blockId: string, output: any) => Promise<void>
676+
onBlockComplete?: (blockId: string, output: any) => Promise<void>,
677+
overrideTriggerType?: 'chat' | 'manual' | 'api'
670678
): Promise<ExecutionResult | StreamingExecution> => {
671679
// Use currentWorkflow but check if we're in diff mode
672680
const { blocks: workflowBlocks, edges: workflowEdges } = currentWorkflow
@@ -683,7 +691,8 @@ export function useWorkflowExecution() {
683691
)
684692

685693
const isExecutingFromChat =
686-
workflowInput && typeof workflowInput === 'object' && 'input' in workflowInput
694+
overrideTriggerType === 'chat' ||
695+
(workflowInput && typeof workflowInput === 'object' && 'input' in workflowInput)
687696

688697
logger.info('Executing workflow', {
689698
isDiffMode: currentWorkflow.isDiffMode,

apps/sim/background/schedule-execution.ts

Lines changed: 2 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
import { db, userStats, workflow, workflowSchedule } from '@sim/db'
1+
import { db, workflow, workflowSchedule } from '@sim/db'
22
import { task } from '@trigger.dev/sdk'
33
import { Cron } from 'croner'
4-
import { eq, sql } from 'drizzle-orm'
4+
import { eq } from 'drizzle-orm'
55
import { v4 as uuidv4 } from 'uuid'
66
import { getApiKeyOwnerUserId } from '@/lib/api-key/service'
77
import { checkServerSideUsageLimits } from '@/lib/billing'
@@ -366,20 +366,6 @@ export async function executeScheduleJob(payload: ScheduleExecutionPayload) {
366366

367367
if (executionResult.success) {
368368
await updateWorkflowRunCounts(payload.workflowId)
369-
370-
try {
371-
await db
372-
.update(userStats)
373-
.set({
374-
totalScheduledExecutions: sql`total_scheduled_executions + 1`,
375-
lastActive: now,
376-
})
377-
.where(eq(userStats.userId, actorUserId))
378-
379-
logger.debug(`[${requestId}] Updated user stats for scheduled execution`)
380-
} catch (statsError) {
381-
logger.error(`[${requestId}] Error updating user stats:`, statsError)
382-
}
383369
}
384370

385371
const { traceSpans, totalDuration } = buildTraceSpans(executionResult)

apps/sim/background/webhook-execution.ts

Lines changed: 2 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { db } from '@sim/db'
2-
import { userStats, webhook, workflow as workflowTable } from '@sim/db/schema'
2+
import { webhook, workflow as workflowTable } from '@sim/db/schema'
33
import { task } from '@trigger.dev/sdk'
4-
import { eq, sql } from 'drizzle-orm'
4+
import { eq } from 'drizzle-orm'
55
import { v4 as uuidv4 } from 'uuid'
66
import { checkServerSideUsageLimits } from '@/lib/billing'
77
import { getPersonalAndWorkspaceEnv } from '@/lib/environment/utils'
@@ -291,15 +291,6 @@ async function executeWebhookJobInternal(
291291
// Update workflow run counts on success
292292
if (executionResult.success) {
293293
await updateWorkflowRunCounts(payload.workflowId)
294-
295-
// Track execution in user stats
296-
await db
297-
.update(userStats)
298-
.set({
299-
totalWebhookTriggers: sql`total_webhook_triggers + 1`,
300-
lastActive: sql`now()`,
301-
})
302-
.where(eq(userStats.userId, payload.userId))
303294
}
304295

305296
// Build trace spans and complete logging session
@@ -492,17 +483,6 @@ async function executeWebhookJobInternal(
492483
// Update workflow run counts on success
493484
if (executionResult.success) {
494485
await updateWorkflowRunCounts(payload.workflowId)
495-
496-
// Track execution in user stats (skip in test mode)
497-
if (!payload.testMode) {
498-
await db
499-
.update(userStats)
500-
.set({
501-
totalWebhookTriggers: sql`total_webhook_triggers + 1`,
502-
lastActive: sql`now()`,
503-
})
504-
.where(eq(userStats.userId, payload.userId))
505-
}
506486
}
507487

508488
// Build trace spans and complete logging session

apps/sim/background/workflow-execution.ts

Lines changed: 2 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { db } from '@sim/db'
2-
import { userStats, workflow as workflowTable } from '@sim/db/schema'
2+
import { workflow as workflowTable } from '@sim/db/schema'
33
import { task } from '@trigger.dev/sdk'
4-
import { eq, sql } from 'drizzle-orm'
4+
import { eq } from 'drizzle-orm'
55
import { v4 as uuidv4 } from 'uuid'
66
import { checkServerSideUsageLimits } from '@/lib/billing'
77
import { getPersonalAndWorkspaceEnv } from '@/lib/environment/utils'
@@ -148,24 +148,6 @@ export async function executeWorkflowJob(payload: WorkflowExecutionPayload) {
148148
// Update workflow run counts on success
149149
if (executionResult.success) {
150150
await updateWorkflowRunCounts(workflowId)
151-
152-
// Track execution in user stats
153-
const statsUpdate =
154-
triggerType === 'api'
155-
? { totalApiCalls: sql`total_api_calls + 1` }
156-
: triggerType === 'webhook'
157-
? { totalWebhookTriggers: sql`total_webhook_triggers + 1` }
158-
: triggerType === 'schedule'
159-
? { totalScheduledExecutions: sql`total_scheduled_executions + 1` }
160-
: { totalManualExecutions: sql`total_manual_executions + 1` }
161-
162-
await db
163-
.update(userStats)
164-
.set({
165-
...statsUpdate,
166-
lastActive: sql`now()`,
167-
})
168-
.where(eq(userStats.userId, payload.userId))
169151
}
170152

171153
// Build trace spans and complete logging session (for both success and failure)

0 commit comments

Comments
 (0)