Skip to content

Commit 321c446

Browse files
Sg312waleedlatif1icecrasher321
authored
fix(streaming-api): fix streaming execution (#1845)
* fix(billing): should allow restoring subscription (#1728) * fix(already-cancelled-sub): UI should allow restoring subscription * restore functionality fixed * fix * Fix streaming api * Fix uuid stuff * Lint * Stripe docs fix * Fix docs build error * Fix uuid check --------- Co-authored-by: Waleed <walif6@gmail.com> Co-authored-by: Vikhyath Mondreti <vikhyathvikku@gmail.com>
1 parent c9a8c7e commit 321c446

File tree

6 files changed

+99
-16
lines changed

6 files changed

+99
-16
lines changed

apps/docs/content/docs/de/tools/stripe.mdx

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -359,7 +359,7 @@ Ein neues Abonnement für einen Kunden erstellen
359359
| --------- | ---- | -------- | ----------- |
360360
| `apiKey` | string | Ja | Stripe API-Schlüssel (geheimer Schlüssel) |
361361
| `customer` | string | Ja | Kunden-ID für das Abonnement |
362-
| `items` | json | Ja | Array von Artikeln mit Preis-IDs (z.B. [{"price": "price_xxx", "quantity": 1}]) |
362+
| `items` | json | Ja | Array von Artikeln mit Preis-IDs \(z.B. \[\{"price": "price_xxx", "quantity": 1\}\]\) |
363363
| `trial_period_days` | number | Nein | Anzahl der Testtage |
364364
| `default_payment_method` | string | Nein | Zahlungsmethoden-ID |
365365
| `cancel_at_period_end` | boolean | Nein | Abonnement am Ende der Periode kündigen |
@@ -774,7 +774,7 @@ Alle Zahlungen auflisten
774774
| `apiKey` | string | Ja | Stripe API-Schlüssel (geheimer Schlüssel) |
775775
| `limit` | number | Nein | Anzahl der zurückzugebenden Ergebnisse (Standard 10, max. 100) |
776776
| `customer` | string | Nein | Nach Kunden-ID filtern |
777-
| `created` | json | Nein | Nach Erstellungsdatum filtern (z.B. {"gt": 1633024800}) |
777+
| `created` | json | Nein | Nach Erstellungsdatum filtern \(z.B. \{"gt": 1633024800\}\) |
778778

779779
#### Output
780780

@@ -1051,7 +1051,7 @@ Alle Events auflisten
10511051
| `apiKey` | string | Ja | Stripe API-Schlüssel (Secret-Key) |
10521052
| `limit` | number | Nein | Anzahl der zurückzugebenden Ergebnisse (Standard 10, max. 100) |
10531053
| `type` | string | Nein | Nach Event-Typ filtern (z.B. payment_intent.created) |
1054-
| `created` | json | Nein | Nach Erstellungsdatum filtern (z.B. {"gt": 1633024800}) |
1054+
| `created` | json | Nein | Nach Erstellungsdatum filtern \(z.B. \{"gt": 1633024800\}\) |
10551055

10561056
#### Output
10571057

apps/docs/content/docs/es/tools/stripe.mdx

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ Crear un nuevo Payment Intent para procesar un pago
7979
| `description` | string | No | Descripción del pago |
8080
| `receipt_email` | string | No | Dirección de correo electrónico para enviar el recibo |
8181
| `metadata` | json | No | Conjunto de pares clave-valor para almacenar información adicional |
82-
| `automatic_payment_methods` | json | No | Habilitar métodos de pago automáticos (p. ej., {"enabled": true}) |
82+
| `automatic_payment_methods` | json | No | Habilitar métodos de pago automáticos \(p. ej., \{"enabled": true\}\) |
8383

8484
#### Salida
8585

@@ -359,7 +359,7 @@ Crear una nueva suscripción para un cliente
359359
| --------- | ---- | -------- | ----------- |
360360
| `apiKey` | string || Clave API de Stripe (clave secreta) |
361361
| `customer` | string || ID del cliente a suscribir |
362-
| `items` | json || Array de elementos con IDs de precio (p. ej., [{"price": "price_xxx", "quantity": 1}]) |
362+
| `items` | json || Array de elementos con IDs de precio \(p. ej., \[\{"price": "price_xxx", "quantity": 1\}\]\) |
363363
| `trial_period_days` | number | No | Número de días de prueba |
364364
| `default_payment_method` | string | No | ID del método de pago |
365365
| `cancel_at_period_end` | boolean | No | Cancelar suscripción al final del período |
@@ -1051,7 +1051,7 @@ Listar todos los eventos
10511051
| `apiKey` | string || Clave API de Stripe (clave secreta) |
10521052
| `limit` | number | No | Número de resultados a devolver (predeterminado 10, máximo 100) |
10531053
| `type` | string | No | Filtrar por tipo de evento (p. ej., payment_intent.created) |
1054-
| `created` | json | No | Filtrar por fecha de creación (p. ej., {"gt": 1633024800}) |
1054+
| `created` | json | No | Filtrar por fecha de creación \(p. ej., \{"gt": 1633024800\}\) |
10551055

10561056
#### Salida
10571057

apps/docs/content/docs/fr/tools/stripe.mdx

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ Créer une nouvelle intention de paiement pour traiter un paiement
7979
| `description` | string | Non | Description du paiement |
8080
| `receipt_email` | string | Non | Adresse e-mail pour l'envoi du reçu |
8181
| `metadata` | json | Non | Ensemble de paires clé-valeur pour stocker des informations supplémentaires |
82-
| `automatic_payment_methods` | json | Non | Activer les méthodes de paiement automatiques (par ex., {"enabled": true}) |
82+
| `automatic_payment_methods` | json | Non | Activer les méthodes de paiement automatiques \(par ex., \{"enabled": true\}\) |
8383

8484
#### Sortie
8585

@@ -359,7 +359,7 @@ Créer un nouvel abonnement pour un client
359359
| --------- | ---- | -------- | ----------- |
360360
| `apiKey` | string | Oui | Clé API Stripe (clé secrète) |
361361
| `customer` | string | Oui | ID du client à abonner |
362-
| `items` | json | Oui | Tableau d'articles avec IDs de prix (ex., \[\{"price": "price_xxx", "quantity": 1\}\]) |
362+
| `items` | json | Oui | Tableau d'articles avec IDs de prix \(ex., \[\{"price": "price_xxx", "quantity": 1\}\]\) |
363363
| `trial_period_days` | number | Non | Nombre de jours d'essai |
364364
| `default_payment_method` | string | Non | ID de la méthode de paiement |
365365
| `cancel_at_period_end` | boolean | Non | Annuler l'abonnement à la fin de la période |
@@ -1051,7 +1051,7 @@ Lister tous les événements
10511051
| `apiKey` | string | Oui | Clé API Stripe (clé secrète) |
10521052
| `limit` | number | Non | Nombre de résultats à retourner (par défaut 10, max 100) |
10531053
| `type` | string | Non | Filtrer par type d'événement (ex. : payment_intent.created) |
1054-
| `created` | json | Non | Filtrer par date de création (ex. : {"gt": 1633024800}) |
1054+
| `created` | json | Non | Filtrer par date de création \(ex. : \{"gt": 1633024800\}\) |
10551055

10561056
#### Sortie
10571057

apps/docs/content/docs/ja/tools/stripe.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -359,7 +359,7 @@ IDで既存の顧客を取得する
359359
| --------- | ---- | -------- | ----------- |
360360
| `apiKey` | string | はい | Stripe APIキー(シークレットキー) |
361361
| `customer` | string | はい | サブスクライブする顧客ID |
362-
| `items` | json | はい | 価格IDを含むアイテムの配列(例:[{"price": "price_xxx", "quantity": 1}]|
362+
| `items` | json | はい | 価格IDを含むアイテムの配列(例:\[\{"price": "price_xxx", "quantity": 1\}\]|
363363
| `trial_period_days` | number | いいえ | トライアル日数 |
364364
| `default_payment_method` | string | いいえ | 支払い方法ID |
365365
| `cancel_at_period_end` | boolean | いいえ | 期間終了時にサブスクリプションをキャンセルする |

apps/docs/content/docs/zh/tools/stripe.mdx

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ import { BlockInfoCard } from "@/components/ui/block-info-card"
7979
| `description` | string || 支付描述 |
8080
| `receipt_email` | string || 用于发送收据的电子邮件地址 |
8181
| `metadata` | json || 用于存储附加信息的键值对集合 |
82-
| `automatic_payment_methods` | json || 启用自动支付方式(例如,{"enabled": true}|
82+
| `automatic_payment_methods` | json || 启用自动支付方式(例如,\{"enabled": true\}|
8383

8484
#### 输出
8585

@@ -197,7 +197,7 @@ import { BlockInfoCard } from "@/components/ui/block-info-card"
197197
| `apiKey` | string || Stripe API 密钥(secret key) |
198198
| `limit` | number || 返回结果数量(默认 10,最大 100) |
199199
| `customer` | string || 按客户 ID 过滤 |
200-
| `created` | json || 按创建日期过滤(例如,{"gt": 1633024800}|
200+
| `created` | json || 按创建日期过滤(例如,\{"gt": 1633024800\}|
201201

202202
#### 输出
203203

@@ -774,7 +774,7 @@ import { BlockInfoCard } from "@/components/ui/block-info-card"
774774
| `apiKey` | string || Stripe API 密钥(密钥) |
775775
| `limit` | number || 返回结果的数量(默认 10,最大 100) |
776776
| `customer` | string || 按客户 ID 过滤 |
777-
| `created` | json || 按创建日期过滤(例如,{"gt": 1633024800}|
777+
| `created` | json || 按创建日期过滤(例如,\{"gt": 1633024800\}|
778778

779779
#### 输出
780780

@@ -1051,7 +1051,7 @@ import { BlockInfoCard } from "@/components/ui/block-info-card"
10511051
| `apiKey` | string || Stripe API 密钥(密钥) |
10521052
| `limit` | number || 返回结果数量(默认 10,最大 100) |
10531053
| `type` | string || 按事件类型过滤(例如,payment_intent.created) |
1054-
| `created` | json || 按创建日期过滤(例如,{"gt": 1633024800}|
1054+
| `created` | json || 按创建日期过滤(例如,\{"gt": 1633024800\}|
10551055

10561056
#### 输出
10571057

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

Lines changed: 85 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { type NextRequest, NextResponse } from 'next/server'
2-
import { v4 as uuidv4 } from 'uuid'
2+
import { validate as uuidValidate, v4 as uuidv4 } from 'uuid'
33
import { checkHybridAuth } from '@/lib/auth/hybrid'
44
import { checkServerSideUsageLimits } from '@/lib/billing'
55
import { processInputFileFields } from '@/lib/execution/files'
@@ -13,6 +13,7 @@ import {
1313
import { executeWorkflowCore } from '@/lib/workflows/executor/execution-core'
1414
import { type ExecutionEvent, encodeSSEEvent } from '@/lib/workflows/executor/execution-events'
1515
import { PauseResumeManager } from '@/lib/workflows/executor/pause-resume-manager'
16+
import { createStreamingResponse } from '@/lib/workflows/streaming'
1617
import { validateWorkflowAccess } from '@/app/api/workflows/middleware'
1718
import { type ExecutionMetadata, ExecutionSnapshot } from '@/executor/execution/snapshot'
1819
import type { StreamingExecution } from '@/executor/types'
@@ -184,6 +185,63 @@ export function createFilteredResult(result: any) {
184185
}
185186
}
186187

188+
function resolveOutputIds(
189+
selectedOutputs: string[] | undefined,
190+
blocks: Record<string, any>
191+
): string[] | undefined {
192+
if (!selectedOutputs || selectedOutputs.length === 0) {
193+
return selectedOutputs
194+
}
195+
196+
return selectedOutputs.map((outputId) => {
197+
const underscoreIndex = outputId.indexOf('_')
198+
const dotIndex = outputId.indexOf('.')
199+
200+
// Check if starts with UUID followed by separator
201+
if (underscoreIndex > 0) {
202+
const maybeUuid = outputId.substring(0, underscoreIndex)
203+
if (uuidValidate(maybeUuid)) {
204+
return outputId
205+
}
206+
}
207+
208+
if (dotIndex > 0) {
209+
const maybeUuid = outputId.substring(0, dotIndex)
210+
if (uuidValidate(maybeUuid)) {
211+
// Convert to underscore format for consistency
212+
return outputId.substring(0, dotIndex) + '_' + outputId.substring(dotIndex + 1)
213+
}
214+
}
215+
216+
if (uuidValidate(outputId)) {
217+
return outputId
218+
}
219+
220+
if (dotIndex === -1) {
221+
logger.warn(`Invalid output ID format (missing dot): ${outputId}`)
222+
return outputId
223+
}
224+
225+
const blockName = outputId.substring(0, dotIndex)
226+
const path = outputId.substring(dotIndex + 1)
227+
228+
const normalizedBlockName = blockName.toLowerCase().replace(/\s+/g, '')
229+
const block = Object.values(blocks).find((b: any) => {
230+
const normalized = (b.name || '').toLowerCase().replace(/\s+/g, '')
231+
return normalized === normalizedBlockName
232+
})
233+
234+
if (!block) {
235+
logger.warn(`Block not found for name: ${blockName} (from output ID: ${outputId})`)
236+
return outputId
237+
}
238+
239+
const resolvedId = `${block.id}_${path}`
240+
logger.debug(`Resolved output ID: ${outputId} -> ${resolvedId}`)
241+
return resolvedId
242+
})
243+
}
244+
187245
/**
188246
* POST /api/workflows/[id]/execute
189247
*
@@ -425,7 +483,32 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id:
425483
}
426484
}
427485

428-
logger.info(`[${requestId}] Using SSE execution (streaming response)`)
486+
if (shouldUseDraftState) {
487+
logger.info(`[${requestId}] Using SSE console log streaming (manual execution)`)
488+
} else {
489+
logger.info(`[${requestId}] Using streaming API response`)
490+
const deployedData = await loadDeployedWorkflowState(workflowId)
491+
const resolvedSelectedOutputs = resolveOutputIds(selectedOutputs, deployedData?.blocks || {})
492+
const stream = await createStreamingResponse({
493+
requestId,
494+
workflow,
495+
input: processedInput,
496+
executingUserId: userId,
497+
streamConfig: {
498+
selectedOutputs: resolvedSelectedOutputs,
499+
isSecureMode: false,
500+
workflowTriggerType: triggerType === 'chat' ? 'chat' : 'api',
501+
},
502+
createFilteredResult,
503+
executionId,
504+
})
505+
506+
return new NextResponse(stream, {
507+
status: 200,
508+
headers: SSE_HEADERS,
509+
})
510+
}
511+
429512
const encoder = new TextEncoder()
430513
let executorInstance: any = null
431514
let isStreamClosed = false

0 commit comments

Comments
 (0)