Skip to content

Commit 8493e04

Browse files
authored
fix(polling): back off failed polls, disable revoked credentials at once, and email when a trigger is turned off (#10736)
* fix(polling): back off failed polls, disable revoked credentials at once, and email when a trigger is turned off * fix(polling): honor Retry-After from Outlook and HubSpot, and log trigger-disabled emails that were not sent * fix(polling): honor Retry-After from Gmail search too
1 parent 724f8ba commit 8493e04

21 files changed

Lines changed: 703 additions & 55 deletions

‎apps/sim/components/emails/notifications/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@ export {
66
SubprocessorChangeEmail,
77
type SubprocessorChangeType,
88
} from './subprocessor-change-email'
9+
export { TriggerDisabledEmail } from './trigger-disabled-email'
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import { Section, Text } from '@react-email/components'
2+
import { baseStyles } from '@/components/emails/_styles'
3+
import { EmailButton, EmailLayout } from '@/components/emails/components'
4+
import {
5+
WEBHOOK_DISABLE_REASON_COPY,
6+
type WebhookDisableReason,
7+
} from '@/lib/webhooks/polling/disable-reasons'
8+
9+
interface TriggerDisabledEmailProps {
10+
recipientName?: string
11+
/** Workflow name. Absent when the workflow could not be read. */
12+
workflowName?: string
13+
reason: WebhookDisableReason
14+
/** Consecutive failures at disable time. Rendered only for `consecutive_failures`. */
15+
failedCount?: number
16+
/** Deep link to the workflow. Absent when the workspace is unknown. */
17+
manageLink?: string
18+
}
19+
20+
/** Sent when Sim turns a polling trigger off on its own. */
21+
export function TriggerDisabledEmail({
22+
recipientName,
23+
workflowName,
24+
reason,
25+
failedCount,
26+
manageLink,
27+
}: TriggerDisabledEmailProps) {
28+
const workflowLabel = workflowName ?? 'a workflow'
29+
const reasonCopy =
30+
reason === 'consecutive_failures' && failedCount
31+
? `It failed ${failedCount.toLocaleString()} times in a row.`
32+
: WEBHOOK_DISABLE_REASON_COPY[reason]
33+
const previewText = `Sim turned off the trigger for ${workflowLabel}`
34+
35+
return (
36+
<EmailLayout preview={previewText} showUnsubscribe={true}>
37+
<Text style={baseStyles.greeting}>{recipientName ? `Hi ${recipientName},` : 'Hi,'}</Text>
38+
39+
<Text style={baseStyles.paragraph}>
40+
Sim turned off the trigger for {workflowLabel}. The workflow will not run for new events
41+
until you fix the problem and turn the trigger back on.
42+
</Text>
43+
44+
<Section style={baseStyles.infoBox}>
45+
<Text style={baseStyles.infoBoxTitle}>Reason</Text>
46+
<Text style={baseStyles.infoBoxList}>{reasonCopy}</Text>
47+
</Section>
48+
49+
{manageLink ? <EmailButton href={manageLink}>Open workflow</EmailButton> : null}
50+
51+
<div style={baseStyles.divider} />
52+
53+
<Text style={baseStyles.footnote}>
54+
Sent to workspace admins and the person who owns this workflow.
55+
</Text>
56+
</EmailLayout>
57+
)
58+
}
59+
60+
export default TriggerDisabledEmail

‎apps/sim/components/emails/render.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,12 @@ import {
3434
ScheduleDisabledEmail,
3535
type SubprocessorChange,
3636
SubprocessorChangeEmail,
37+
TriggerDisabledEmail,
3738
} from '@/components/emails/notifications'
3839
import { HelpConfirmationEmail } from '@/components/emails/support'
3940
import type { UpgradeReason } from '@/lib/billing/upgrade-reasons'
4041
import { getBaseUrl } from '@/lib/core/utils/urls'
42+
import type { WebhookDisableReason } from '@/lib/webhooks/polling/disable-reasons'
4143
import type { ScheduleDisableReason } from '@/lib/workflows/schedules/disable-reasons'
4244

4345
interface WorkspaceInvitation {
@@ -177,6 +179,16 @@ export async function renderScheduleDisabledEmail(params: {
177179
return await render(ScheduleDisabledEmail(params))
178180
}
179181

182+
export async function renderTriggerDisabledEmail(params: {
183+
recipientName?: string
184+
workflowName?: string
185+
reason: WebhookDisableReason
186+
failedCount?: number
187+
manageLink?: string
188+
}): Promise<string> {
189+
return await render(TriggerDisabledEmail(params))
190+
}
191+
180192
export async function renderDeprecatedModelEmail(params: {
181193
recipientName?: string
182194
workflowName: string

‎apps/sim/components/emails/subjects.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ export type EmailSubjectType =
2424
| 'abandoned-checkout'
2525
| 'free-tier-exhausted'
2626
| 'schedule-disabled'
27+
| 'trigger-disabled'
2728
| 'deprecated-model'
2829
| 'subprocessor-change'
2930
| 'onboarding-followup'
@@ -80,6 +81,8 @@ export function getEmailSubject(type: EmailSubjectType): string {
8081
return `You've run out of free credits on Sim`
8182
case 'schedule-disabled':
8283
return `A schedule was turned off on Sim`
84+
case 'trigger-disabled':
85+
return `A trigger was turned off on Sim`
8386
case 'deprecated-model':
8487
return `A workflow uses a retired model on Sim`
8588
case 'subprocessor-change':

‎apps/sim/lib/oauth/credential-service.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -907,6 +907,27 @@ describe('OAuth access-token refresh headroom', () => {
907907
)
908908
})
909909

910+
it('names a revoked credential to a caller that asks, and stays null for every other caller', async () => {
911+
vi.mocked(isTerminalRefreshError).mockReturnValue(true)
912+
vi.mocked(isCredentialRevocationError).mockReturnValue(true)
913+
mocks.refreshOAuthToken.mockResolvedValue({ ok: false, errorCode: 'invalid_grant' })
914+
const row = createOAuthAccount(100_000)
915+
queueCredentialAccount(row)
916+
queueTableRows(account, [row])
917+
918+
await expect(
919+
resolveCredentialTokenBundle(RAW_CREDENTIAL_ID, RAW_USER_ID, 'test', undefined, undefined, {
920+
throwIfRevoked: true,
921+
})
922+
).rejects.toBeInstanceOf(CredentialRevokedError)
923+
924+
queueCredentialAccount(row)
925+
queueTableRows(account, [row])
926+
await expect(
927+
resolveCredentialTokenBundle(RAW_CREDENTIAL_ID, RAW_USER_ID, 'test')
928+
).resolves.toBeNull()
929+
})
930+
910931
it.each(readers)(
911932
'$name rethrows an unavailable egress route instead of a missing, revoked or failed token',
912933
async ({ read }) => {

‎apps/sim/lib/oauth/credential-service.ts‎

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,11 @@ export interface CredentialTokenResolutionOptions {
132132
* waiting on an OAuth refresh without cancelling the refresh other callers share.
133133
*/
134134
signal?: AbortSignal
135+
/**
136+
* Throw {@link CredentialRevokedError} instead of returning `null` when the provider revoked the
137+
* grant, for a caller that acts differently on a credential only its owner can restore.
138+
*/
139+
throwIfRevoked?: boolean
135140
}
136141

137142
function privateCredentialIdentity(namespace: string, value: string): string {
@@ -2085,7 +2090,12 @@ export async function resolveCredentialTokenBundle(
20852090
logger.warn('OAuth access token expired and cannot be refreshed; reconnect the account')
20862091
return null
20872092
}
2088-
if (result.kind === 'failed') return null
2093+
if (result.kind === 'failed') {
2094+
if (options?.throwIfRevoked && result.outcome?.kind === 'revoked') {
2095+
throw revokedCredentialError(credential.providerId, result.outcome.errorCode)
2096+
}
2097+
return null
2098+
}
20892099
if (!result.accessToken) {
20902100
// We have no access token and either no refresh token or not eligible to refresh
20912101
logger.error('Missing access token for credential', { requestId })
@@ -2152,10 +2162,14 @@ export async function refreshTokenIfNeeded(
21522162
}
21532163
}
21542164
if (result.outcome?.kind === 'revoked') {
2155-
throw new CredentialRevokedError(
2156-
`The ${credential.providerId} credential was revoked by the provider (${result.outcome.errorCode}). Reconnect it to continue.`,
2157-
{ providerId: credential.providerId, errorCode: result.outcome.errorCode }
2158-
)
2165+
throw revokedCredentialError(credential.providerId, result.outcome.errorCode)
21592166
}
21602167
throw new Error('Failed to refresh token')
21612168
}
2169+
2170+
function revokedCredentialError(providerId: string, errorCode: string): CredentialRevokedError {
2171+
return new CredentialRevokedError(
2172+
`The ${providerId} credential was revoked by the provider (${errorCode}). Reconnect it to continue.`,
2173+
{ providerId, errorCode }
2174+
)
2175+
}
Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
import { db } from '@sim/db'
2+
import { user, webhook, workflow, workspace } from '@sim/db/schema'
3+
import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures'
4+
import { createLogger } from '@sim/logger'
5+
import { generateId } from '@sim/utils/id'
6+
import { eq } from 'drizzle-orm'
7+
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
8+
9+
const { mockNotifyWebhookAutoDisabled } = vi.hoisted(() => ({
10+
mockNotifyWebhookAutoDisabled: vi.fn(async () => {}),
11+
}))
12+
vi.mock('@/lib/webhooks/polling/disable-notifications', () => ({
13+
notifyWebhookAutoDisabled: mockNotifyWebhookAutoDisabled,
14+
}))
15+
16+
import { CredentialRevokedError } from '@/lib/oauth/credential-revoked'
17+
import {
18+
markWebhookFailed,
19+
markWebhookSuccess,
20+
recordPollSourceFailure,
21+
} from '@/lib/webhooks/polling/utils'
22+
import { MAX_CONSECUTIVE_FAILURES } from '@/triggers/constants'
23+
24+
const logger = createLogger('PollAutoDisableIntegration')
25+
const owner = generateId()
26+
const workspaceId = generateId()
27+
const workflowId = generateId()
28+
29+
const CONFIG = { credentialId: 'credential-1', historyId: '4100' }
30+
31+
/** One active Gmail webhook on the fixture workflow; returns its id. */
32+
async function insertWebhook(values: {
33+
failedCount?: number
34+
providerConfig?: Record<string, unknown> | null
35+
}): Promise<string> {
36+
const id = generateId()
37+
await db.insert(webhook).values({
38+
id,
39+
workflowId,
40+
blockId: 'trigger',
41+
path: `poll-auto-disable-${id}`,
42+
provider: 'gmail',
43+
isActive: true,
44+
failedCount: values.failedCount ?? 0,
45+
providerConfig: values.providerConfig === undefined ? CONFIG : values.providerConfig,
46+
})
47+
return id
48+
}
49+
50+
async function readWebhook(id: string) {
51+
const [row] = await db
52+
.select({
53+
isActive: webhook.isActive,
54+
failedCount: webhook.failedCount,
55+
providerConfig: webhook.providerConfig,
56+
})
57+
.from(webhook)
58+
.where(eq(webhook.id, id))
59+
return row
60+
}
61+
62+
beforeAll(async () => {
63+
const now = new Date()
64+
await db.insert(user).values({
65+
id: owner,
66+
name: 'Poll auto-disable fixture',
67+
email: `${owner}@poll-auto-disable.test`,
68+
emailVerified: true,
69+
createdAt: now,
70+
updatedAt: now,
71+
})
72+
await insertWorkspaceFixture(db, [
73+
{
74+
id: workspaceId,
75+
name: 'Poll auto-disable fixture',
76+
ownerId: owner,
77+
billedAccountUserId: owner,
78+
},
79+
])
80+
await db.insert(workflow).values({
81+
id: workflowId,
82+
userId: owner,
83+
workspaceId,
84+
name: 'Poll auto-disable fixture',
85+
lastSynced: now,
86+
createdAt: now,
87+
updatedAt: now,
88+
isDeployed: true,
89+
})
90+
})
91+
92+
beforeEach(() => {
93+
mockNotifyWebhookAutoDisabled.mockClear()
94+
})
95+
96+
afterAll(async () => {
97+
await deleteWorkspaceFixture(db, eq(workspace.id, workspaceId))
98+
await db.delete(user).where(eq(user.id, owner))
99+
await db.$client.end()
100+
})
101+
102+
describe('markWebhookSuccess', () => {
103+
it('drops a recorded source backoff and resets the count, keeping the rest of the config', async () => {
104+
const id = await insertWebhook({
105+
failedCount: 3,
106+
providerConfig: {
107+
...CONFIG,
108+
pollSourceFailures: 3,
109+
pollBackoffUntil: new Date(Date.now() + 60_000).toISOString(),
110+
},
111+
})
112+
113+
await markWebhookSuccess(id, logger)
114+
115+
expect(await readWebhook(id)).toMatchObject({ failedCount: 0, providerConfig: CONFIG })
116+
})
117+
118+
it('resets the count of a webhook with no config without touching it', async () => {
119+
const id = await insertWebhook({ failedCount: 2, providerConfig: null })
120+
121+
await markWebhookSuccess(id, logger)
122+
123+
expect(await readWebhook(id)).toMatchObject({ failedCount: 0, providerConfig: null })
124+
})
125+
})
126+
127+
describe('auto-disable', () => {
128+
const revoked = new CredentialRevokedError('The google credential was revoked by the provider')
129+
130+
it('turns a webhook off at once when its credential was revoked, telling its people once', async () => {
131+
const id = await insertWebhook({ failedCount: 1 })
132+
const webhookData = { id, providerConfig: CONFIG }
133+
134+
await recordPollSourceFailure(webhookData, Date.now(), revoked, 'poll failed', logger)
135+
await recordPollSourceFailure(webhookData, Date.now(), revoked, 'poll failed', logger)
136+
137+
expect(await readWebhook(id)).toMatchObject({ isActive: false, failedCount: 1 })
138+
expect(mockNotifyWebhookAutoDisabled).toHaveBeenCalledTimes(1)
139+
expect(mockNotifyWebhookAutoDisabled).toHaveBeenCalledWith({
140+
webhookId: id,
141+
reason: 'credential_revoked',
142+
})
143+
})
144+
145+
it('tells its people once when consecutive failures turn it off', async () => {
146+
const id = await insertWebhook({ failedCount: MAX_CONSECUTIVE_FAILURES - 2 })
147+
148+
await markWebhookFailed(id, logger)
149+
expect(mockNotifyWebhookAutoDisabled).not.toHaveBeenCalled()
150+
151+
await markWebhookFailed(id, logger)
152+
await markWebhookFailed(id, logger)
153+
154+
expect(await readWebhook(id)).toMatchObject({ isActive: false })
155+
expect(mockNotifyWebhookAutoDisabled).toHaveBeenCalledTimes(1)
156+
expect(mockNotifyWebhookAutoDisabled).toHaveBeenCalledWith({
157+
webhookId: id,
158+
reason: 'consecutive_failures',
159+
failedCount: MAX_CONSECUTIVE_FAILURES,
160+
})
161+
})
162+
})

0 commit comments

Comments
 (0)