Skip to content

Commit ec0d700

Browse files
committed
fix(integrations): keep large Firecrawl results, cancel abandoned jobs, cap Pulse downloads
1 parent 84da910 commit ec0d700

8 files changed

Lines changed: 171 additions & 46 deletions

File tree

‎apps/sim/lib/internal/pulse/client.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@ vi.mock('@/lib/core/security/input-validation.server', () => inputValidationMock
99

1010
const { mockSecureFetchWithPinnedIP, mockValidateUrlWithDNS } = inputValidationMockFns
1111

12+
import { PayloadSizeLimitError } from '@/lib/core/utils/stream-limits'
1213
import { submitPulseParse } from '@/lib/internal/pulse/client'
14+
import { MAX_TOOL_RESPONSE_BODY_BYTES } from '@/lib/internal/tool-operations/response-limits'
1315

1416
function requestTo(url: string) {
1517
const call = mockSecureFetchWithPinnedIP.mock.calls.find(([target]) => target === url)
@@ -44,4 +46,33 @@ describe('submitPulseParse large results', () => {
4446

4547
expect(requestTo(resultUrl).headers).toEqual({})
4648
})
49+
50+
it('does not send the API key to the Pulse host over plain HTTP', async () => {
51+
const resultUrl = 'http://api.runpulse.com/results/job-1'
52+
mockSecureFetchWithPinnedIP
53+
.mockResolvedValueOnce(jsonResponse({ is_url: true, url: resultUrl, extraction_id: 'ext-1' }))
54+
.mockResolvedValueOnce(jsonResponse({ markdown: '# Report' }))
55+
56+
await submitPulseParse('pulse-key', new FormData())
57+
58+
expect(requestTo(resultUrl).headers).toEqual({})
59+
})
60+
61+
it('fails with a clear error when the full result is too large to return', async () => {
62+
mockSecureFetchWithPinnedIP
63+
.mockResolvedValueOnce(
64+
jsonResponse({ is_url: true, url: 'https://api.runpulse.com/results/job-1' })
65+
)
66+
.mockRejectedValueOnce(
67+
new PayloadSizeLimitError({
68+
label: 'response body',
69+
maxBytes: MAX_TOOL_RESPONSE_BODY_BYTES,
70+
})
71+
)
72+
73+
await expect(submitPulseParse('pulse-key', new FormData())).rejects.toMatchObject({
74+
status: 413,
75+
body: { success: false, error: expect.stringContaining('too large') },
76+
})
77+
})
4778
})

‎apps/sim/lib/internal/pulse/client.ts‎

Lines changed: 25 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,11 @@ import {
77
} from '@/lib/core/security/input-validation.server'
88
import {
99
DEFAULT_MAX_ERROR_BODY_BYTES,
10+
isPayloadSizeLimitError,
1011
readResponseTextWithLimit,
1112
} from '@/lib/core/utils/stream-limits'
1213
import { PulseOperationError } from '@/lib/internal/pulse/errors'
14+
import { MAX_TOOL_RESPONSE_BODY_BYTES } from '@/lib/internal/tool-operations/response-limits'
1315

1416
const logger = createLogger('PulseClient')
1517
const PULSE_API_HOST = 'api.runpulse.com'
@@ -34,23 +36,32 @@ async function downloadLargeResult(
3436
error: 'Pulse returned an invalid result URL',
3537
})
3638
}
37-
const isPulseHost = new URL(url).hostname === PULSE_API_HOST
38-
const response = await secureFetchWithPinnedIP(url, validation.resolvedIP, {
39-
profile: 'contentFetch',
40-
method: 'GET',
41-
headers: isPulseHost ? { 'x-api-key': apiKey } : {},
42-
maxResponseBytes: DEFAULT_MAX_RESPONSE_BYTES,
43-
signal,
44-
})
45-
signal?.throwIfAborted()
46-
if (!response.ok) {
47-
logger.error('Pulse large result download failed', { status: response.status })
48-
throw new PulseOperationError(response.status, {
39+
const target = new URL(url)
40+
const isPulseHost = target.protocol === 'https:' && target.hostname === PULSE_API_HOST
41+
try {
42+
const response = await secureFetchWithPinnedIP(url, validation.resolvedIP, {
43+
profile: 'contentFetch',
44+
method: 'GET',
45+
headers: isPulseHost ? { 'x-api-key': apiKey } : {},
46+
maxResponseBytes: MAX_TOOL_RESPONSE_BODY_BYTES,
47+
signal,
48+
})
49+
signal?.throwIfAborted()
50+
if (!response.ok) {
51+
logger.error('Pulse large result download failed', { status: response.status })
52+
throw new PulseOperationError(response.status, {
53+
success: false,
54+
error: `Failed to download the Pulse result: ${response.statusText}`,
55+
})
56+
}
57+
return await response.json()
58+
} catch (error) {
59+
if (!isPayloadSizeLimitError(error)) throw error
60+
throw new PulseOperationError(413, {
4961
success: false,
50-
error: `Failed to download the Pulse result: ${response.statusText}`,
62+
error: `The Pulse result is too large to return (over ${MAX_TOOL_RESPONSE_BODY_BYTES / (1024 * 1024)} MiB). Request fewer pages.`,
5163
})
5264
}
53-
return response.json()
5465
}
5566

5667
export async function submitPulseParse(

‎apps/sim/tools/firecrawl/agent.ts‎

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,7 @@ import { createLogger } from '@sim/logger'
22
import { interruptibleSleep } from '@sim/utils/helpers'
33
import { DEFAULT_EXECUTION_TIMEOUT_MS } from '@/lib/core/execution-limits'
44
import { outboundFetch } from '@/lib/core/network/outbound-fetch.server'
5-
import { readResponseJsonWithLimit } from '@/lib/core/utils/stream-limits'
6-
import { MAX_TOOL_RESPONSE_BODY_BYTES } from '@/lib/internal/tool-operations/response-limits'
5+
import { cancelFirecrawlJob, readFirecrawlJobStatus } from '@/tools/firecrawl/job-polling'
76
import type { AgentParams, AgentResponse, FirecrawlJobStatusBody } from '@/tools/firecrawl/types'
87
import type { ToolConfig } from '@/tools/types'
98

@@ -137,13 +136,9 @@ export const agentTool: ToolConfig<AgentParams, AgentResponse> = {
137136
throw new Error(`Failed to get agent status: ${statusResponse.statusText}`)
138137
}
139138

140-
const agentData = await readResponseJsonWithLimit<
139+
const agentData = await readFirecrawlJobStatus<
141140
FirecrawlJobStatusBody<AgentResponse['output']['data']>
142-
>(statusResponse, {
143-
maxBytes: MAX_TOOL_RESPONSE_BODY_BYTES,
144-
label: 'Firecrawl job status',
145-
signal,
146-
})
141+
>(statusResponse, signal)
147142
logger.info(`Firecrawl agent job ${jobId} status: ${agentData.status}`)
148143

149144
if (agentData.status === 'completed') {
@@ -170,6 +165,8 @@ export const agentTool: ToolConfig<AgentParams, AgentResponse> = {
170165
await interruptibleSleep(POLL_INTERVAL_MS, signal)
171166
elapsedTime += POLL_INTERVAL_MS
172167
} catch (error: any) {
168+
if (signal?.aborted)
169+
await cancelFirecrawlJob(`agent/${encodeURIComponent(jobId)}`, params.apiKey)
173170
logger.error('Error polling for agent job status:', {
174171
message: error.message || 'Unknown error',
175172
jobId,

‎apps/sim/tools/firecrawl/batch-scrape.ts‎

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,8 @@ import { createLogger } from '@sim/logger'
22
import { interruptibleSleep } from '@sim/utils/helpers'
33
import { DEFAULT_EXECUTION_TIMEOUT_MS } from '@/lib/core/execution-limits'
44
import { outboundFetch } from '@/lib/core/network/outbound-fetch.server'
5-
import { readResponseJsonWithLimit } from '@/lib/core/utils/stream-limits'
6-
import { MAX_TOOL_RESPONSE_BODY_BYTES } from '@/lib/internal/tool-operations/response-limits'
75
import { firecrawlHosting } from '@/tools/firecrawl/hosting'
6+
import { cancelFirecrawlJob, readFirecrawlJobStatus } from '@/tools/firecrawl/job-polling'
87
import {
98
applyFirecrawlFormatModelInput,
109
applyFirecrawlScrapeOptionsModelInput,
@@ -218,13 +217,9 @@ export const batchScrapeTool: ToolConfig<FirecrawlBatchScrapeParams, FirecrawlBa
218217
throw new Error(`Failed to get batch scrape status: ${statusResponse.statusText}`)
219218
}
220219

221-
const batchData = await readResponseJsonWithLimit<
220+
const batchData = await readFirecrawlJobStatus<
222221
FirecrawlJobStatusBody<FirecrawlBatchScrapeResponse['output']['pages']>
223-
>(statusResponse, {
224-
maxBytes: MAX_TOOL_RESPONSE_BODY_BYTES,
225-
label: 'Firecrawl job status',
226-
signal,
227-
})
222+
>(statusResponse, signal)
228223
logger.info(`Firecrawl batch scrape job ${jobId} status: ${batchData.status}`)
229224

230225
if (batchData.status === 'completed') {
@@ -253,6 +248,8 @@ export const batchScrapeTool: ToolConfig<FirecrawlBatchScrapeParams, FirecrawlBa
253248
await interruptibleSleep(POLL_INTERVAL_MS, signal)
254249
elapsedTime += POLL_INTERVAL_MS
255250
} catch (error: any) {
251+
if (signal?.aborted)
252+
await cancelFirecrawlJob(`batch/scrape/${encodeURIComponent(jobId)}`, params.apiKey)
256253
logger.error('Error polling for batch scrape job status:', {
257254
message: error.message || 'Unknown error',
258255
jobId,

‎apps/sim/tools/firecrawl/crawl.ts‎

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,8 @@ import { interruptibleSleep } from '@sim/utils/helpers'
33
import { escapeRegExp } from '@sim/utils/string'
44
import { DEFAULT_EXECUTION_TIMEOUT_MS } from '@/lib/core/execution-limits'
55
import { outboundFetch } from '@/lib/core/network/outbound-fetch.server'
6-
import { readResponseJsonWithLimit } from '@/lib/core/utils/stream-limits'
7-
import { MAX_TOOL_RESPONSE_BODY_BYTES } from '@/lib/internal/tool-operations/response-limits'
86
import { firecrawlHosting } from '@/tools/firecrawl/hosting'
7+
import { cancelFirecrawlJob, readFirecrawlJobStatus } from '@/tools/firecrawl/job-polling'
98
import {
109
applyFirecrawlFormatModelInput,
1110
applyFirecrawlScrapeOptionsModelInput,
@@ -262,13 +261,9 @@ export const crawlTool: ToolConfig<FirecrawlCrawlParams, FirecrawlCrawlResponse>
262261
throw new Error(`Failed to get crawl status: ${statusResponse.statusText}`)
263262
}
264263

265-
const crawlData = await readResponseJsonWithLimit<
264+
const crawlData = await readFirecrawlJobStatus<
266265
FirecrawlJobStatusBody<FirecrawlCrawlResponse['output']['pages']>
267-
>(statusResponse, {
268-
maxBytes: MAX_TOOL_RESPONSE_BODY_BYTES,
269-
label: 'Firecrawl job status',
270-
signal,
271-
})
266+
>(statusResponse, signal)
272267
logger.info(`Firecrawl crawl job ${jobId} status: ${crawlData.status}`)
273268

274269
if (crawlData.status === 'completed') {
@@ -294,6 +289,8 @@ export const crawlTool: ToolConfig<FirecrawlCrawlParams, FirecrawlCrawlResponse>
294289
await interruptibleSleep(POLL_INTERVAL_MS, signal)
295290
elapsedTime += POLL_INTERVAL_MS
296291
} catch (error: any) {
292+
if (signal?.aborted)
293+
await cancelFirecrawlJob(`crawl/${encodeURIComponent(jobId)}`, params.apiKey)
297294
logger.error('Error polling for crawl job status:', {
298295
message: error.message || 'Unknown error',
299296
jobId,

‎apps/sim/tools/firecrawl/extract.ts‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,8 @@ import { createLogger } from '@sim/logger'
22
import { interruptibleSleep } from '@sim/utils/helpers'
33
import { DEFAULT_EXECUTION_TIMEOUT_MS } from '@/lib/core/execution-limits'
44
import { outboundFetch } from '@/lib/core/network/outbound-fetch.server'
5-
import { readResponseJsonWithLimit } from '@/lib/core/utils/stream-limits'
6-
import { MAX_TOOL_RESPONSE_BODY_BYTES } from '@/lib/internal/tool-operations/response-limits'
75
import { firecrawlHosting } from '@/tools/firecrawl/hosting'
6+
import { readFirecrawlJobStatus } from '@/tools/firecrawl/job-polling'
87
import {
98
applyFirecrawlScrapeOptionsModelInput,
109
selectFirecrawlScrapeOptionsModelInput,
@@ -193,13 +192,9 @@ export const extractTool: ToolConfig<ExtractParams, ExtractResponse> = {
193192
throw new Error(`Failed to get extract status: ${statusResponse.statusText}`)
194193
}
195194

196-
const extractData = await readResponseJsonWithLimit<
195+
const extractData = await readFirecrawlJobStatus<
197196
FirecrawlJobStatusBody<ExtractResponse['output']['data']>
198-
>(statusResponse, {
199-
maxBytes: MAX_TOOL_RESPONSE_BODY_BYTES,
200-
label: 'Firecrawl job status',
201-
signal,
202-
})
197+
>(statusResponse, signal)
203198
logger.info(`Firecrawl extract job ${jobId} status: ${extractData.status}`)
204199

205200
if (extractData.status === 'completed') {
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import { jsonResponse } from '@sim/testing'
2+
import { beforeEach, describe, expect, it, vi } from 'vitest'
3+
import { crawlTool } from '@/tools/firecrawl/crawl'
4+
import type { FirecrawlCrawlResponse } from '@/tools/firecrawl/types'
5+
6+
const fetchMock = vi.fn()
7+
const started = (): FirecrawlCrawlResponse => ({
8+
success: true,
9+
output: { jobId: 'job-1', pages: [], total: 0 },
10+
})
11+
const params = { apiKey: 'fc-key', url: 'https://example.com' }
12+
const executeTool = vi.fn()
13+
14+
function pollCrawl(signal?: AbortSignal) {
15+
if (!crawlTool.postProcess) throw new Error('crawlTool has no postProcess')
16+
return crawlTool.postProcess(started(), params, executeTool, { signal })
17+
}
18+
19+
describe('Firecrawl crawl polling', () => {
20+
beforeEach(() => {
21+
vi.stubGlobal('fetch', fetchMock)
22+
})
23+
24+
it('returns a completed crawl whose status body is over 10 MiB', async () => {
25+
const markdown = '文'.repeat(4 * 1024 * 1024)
26+
fetchMock.mockResolvedValueOnce(
27+
jsonResponse({
28+
status: 'completed',
29+
total: 1,
30+
creditsUsed: 1,
31+
data: [{ markdown, metadata: { title: 'Page', sourceURL: 'https://example.com' } }],
32+
})
33+
)
34+
35+
const result = await pollCrawl()
36+
37+
expect(result.success).toBe(true)
38+
expect(result.output.pages[0].markdown).toHaveLength(markdown.length)
39+
})
40+
41+
it('cancels the Firecrawl job when the workflow run is cancelled', async () => {
42+
fetchMock.mockResolvedValue(jsonResponse({ success: true, status: 'cancelled' }))
43+
const controller = new AbortController()
44+
controller.abort()
45+
46+
const result = await pollCrawl(controller.signal)
47+
48+
expect(result.success).toBe(false)
49+
expect(fetchMock).toHaveBeenCalledWith(
50+
'https://api.firecrawl.dev/v2/crawl/job-1',
51+
expect.objectContaining({ method: 'DELETE' })
52+
)
53+
})
54+
})
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { createLogger } from '@sim/logger'
2+
import { outboundFetch } from '@/lib/core/network/outbound-fetch.server'
3+
import { readResponseJsonWithLimit } from '@/lib/core/utils/stream-limits'
4+
import { MAX_DURABLE_LARGE_VALUE_BYTES } from '@/lib/execution/payloads/limits'
5+
6+
const logger = createLogger('FirecrawlJobPolling')
7+
8+
const CANCEL_TIMEOUT_MS = 10_000
9+
10+
/**
11+
* Reads a Firecrawl job status body. The cap is the largest value a workflow output can carry:
12+
* Firecrawl pages its results at 10MB of characters, so a finished page of multi-byte text can
13+
* exceed 10 MiB, and those results reached the workflow before polling had a cap.
14+
*/
15+
export function readFirecrawlJobStatus<T>(response: Response, signal?: AbortSignal): Promise<T> {
16+
return readResponseJsonWithLimit<T>(response, {
17+
maxBytes: MAX_DURABLE_LARGE_VALUE_BYTES,
18+
label: 'Firecrawl job status',
19+
signal,
20+
})
21+
}
22+
23+
/**
24+
* Asks Firecrawl to stop a job the workflow stopped waiting for, so a cancelled run does not keep
25+
* spending credits. Best effort: a failure is logged and the run still ends as cancelled.
26+
*
27+
* @param jobPath - The job's path under `/v2`, such as `crawl/<id>`.
28+
*/
29+
export async function cancelFirecrawlJob(jobPath: string, apiKey: string): Promise<void> {
30+
try {
31+
const response = await outboundFetch(`https://api.firecrawl.dev/v2/${jobPath}`, {
32+
method: 'DELETE',
33+
headers: { Authorization: `Bearer ${apiKey}` },
34+
signal: AbortSignal.timeout(CANCEL_TIMEOUT_MS),
35+
})
36+
await response.body?.cancel()
37+
if (!response.ok) {
38+
logger.warn('Firecrawl did not cancel the job', { jobPath, status: response.status })
39+
}
40+
} catch (error) {
41+
logger.warn('Failed to cancel the Firecrawl job', { jobPath, error })
42+
}
43+
}

0 commit comments

Comments
 (0)