@@ -27,6 +27,11 @@ import {
2727} from '@/lib/webhooks/polling/utils'
2828import { processPolledWebhookEvent } from '@/lib/webhooks/processor'
2929
30+ /** How far back the first poll of a mailbox (with no stored check time) searches. */
31+ const FIRST_POLL_LOOKBACK_MS = 24 * 60 * 60 * 1000
32+ /** How far before the stored check time each later search starts. */
33+ const SINCE_BUFFER_MS = 60_000
34+
3035interface ImapWebhookConfig {
3136 host : string
3237 port : number
@@ -142,6 +147,7 @@ export const imapPollingHandler: PollingProviderHandler = {
142147 await client . connect ( )
143148
144149 const result = await fetchNewEmails ( client , config , logger )
150+ const { firstPollSince } = result
145151 emails = result . emails
146152 latestUidByMailbox = result . latestUidByMailbox
147153 uidValidityByMailbox = result . uidValidityByMailbox
@@ -165,7 +171,7 @@ export const imapPollingHandler: PollingProviderHandler = {
165171
166172 logger . info ( `Found ${ emails . length } new emails for webhook ${ webhookId } ` )
167173
168- const { processedCount, failedCount } = await processEmails (
174+ const { processedCount, failedCount, refusedAt } = await processEmails (
169175 emails ,
170176 webhookData ,
171177 workflowData ,
@@ -175,6 +181,27 @@ export const imapPollingHandler: PollingProviderHandler = {
175181 logger
176182 )
177183
184+ if ( refusedAt !== undefined ) {
185+ // A refusal that holds until a person acts, after earlier emails completed: save each
186+ // mailbox's cursor right before the refused email, and pin the `since` window this
187+ // search used so it still reaches that email once the refusal lifts.
188+ await updateImapState (
189+ webhookId ,
190+ highestUidByMailbox ( emails . slice ( 0 , refusedAt ) ) ,
191+ config . lastCheckedTimestamp ??
192+ new Date ( firstPollSince . getTime ( ) + SINCE_BUFFER_MS ) . toISOString ( ) ,
193+ config ,
194+ logger ,
195+ uidValidityByMailbox
196+ )
197+ await client . logout ( )
198+ await markWebhookSuccess ( webhookId , logger )
199+ logger . info ( 'Execution admission refused the webhook; left its items for a later poll' , {
200+ webhookId,
201+ } )
202+ return 'skipped'
203+ }
204+
178205 await updateImapState (
179206 webhookId ,
180207 latestUidByMailbox ,
@@ -213,6 +240,15 @@ export const imapPollingHandler: PollingProviderHandler = {
213240 } ,
214241}
215242
243+ /** The highest UID among `emails` in each mailbox they come from. */
244+ function highestUidByMailbox ( emails : ReadonlyArray < { uid : number ; mailboxPath : string } > ) {
245+ const highest : Record < string , number > = { }
246+ for ( const { uid, mailboxPath } of emails ) {
247+ highest [ mailboxPath ] = Math . max ( uid , highest [ mailboxPath ] ?? 0 )
248+ }
249+ return highest
250+ }
251+
216252async function updateImapState (
217253 webhookId : string ,
218254 uidByMailbox : Record < string , number > ,
@@ -275,10 +311,13 @@ async function fetchNewEmails(client: ImapFlow, config: ImapWebhookConfig, logge
275311
276312 const maxEmails = config . maxEmailsPerPoll || 25
277313 let totalEmailsCollected = 0
314+ /** One window for every mailbox, so a poll held by a refusal can save exactly what it searched. */
315+ const firstPollSince = new Date ( Date . now ( ) - FIRST_POLL_LOOKBACK_MS )
278316
279317 for ( const mailboxPath of mailboxes ) {
280318 if ( totalEmailsCollected >= maxEmails ) break
281319
320+ const mailboxEmails : typeof emails = [ ]
282321 try {
283322 const mailbox = await client . mailboxOpen ( mailboxPath )
284323
@@ -314,11 +353,10 @@ async function fetchNewEmails(client: ImapFlow, config: ImapWebhookConfig, logge
314353
315354 if ( config . lastCheckedTimestamp ) {
316355 const lastChecked = new Date ( config . lastCheckedTimestamp )
317- const bufferTime = new Date ( lastChecked . getTime ( ) - 60000 )
356+ const bufferTime = new Date ( lastChecked . getTime ( ) - SINCE_BUFFER_MS )
318357 searchCriteria = { ...searchCriteria , since : bufferTime }
319358 } else {
320- const oneDayAgo = new Date ( Date . now ( ) - 24 * 60 * 60 * 1000 )
321- searchCriteria = { ...searchCriteria , since : oneDayAgo }
359+ searchCriteria = { ...searchCriteria , since : firstPollSince }
322360 }
323361
324362 let messageUids : number [ ] = [ ]
@@ -340,7 +378,7 @@ async function fetchNewEmails(client: ImapFlow, config: ImapWebhookConfig, logge
340378 { uid : true , envelope : true , bodyStructure : true , source : true } ,
341379 { uid : true }
342380 ) ) {
343- emails . push ( {
381+ mailboxEmails . push ( {
344382 uid : msg . uid ,
345383 mailboxPath,
346384 envelope : msg . envelope ,
@@ -355,9 +393,11 @@ async function fetchNewEmails(client: ImapFlow, config: ImapWebhookConfig, logge
355393 } catch {
356394 logger . warn ( `Error processing mailbox ${ mailboxPath } ` )
357395 }
396+ // Ascending UIDs, so a batch stopped by a refusal can save its cursor right before that email.
397+ emails . push ( ...mailboxEmails . sort ( ( a , b ) => a . uid - b . uid ) )
358398 }
359399
360- return { emails, latestUidByMailbox, uidValidityByMailbox }
400+ return { emails, latestUidByMailbox, uidValidityByMailbox, firstPollSince }
361401}
362402
363403function getMailboxesToCheck ( config : ImapWebhookConfig ) : string [ ] {
@@ -516,7 +556,7 @@ async function processEmails(
516556 const lockState : { lock : MailboxLockObject | null } = { lock : null }
517557
518558 try {
519- for ( const email of emails ) {
559+ for ( const [ index , email ] of emails . entries ( ) ) {
520560 try {
521561 await pollingIdempotency . executeWithIdempotency (
522562 'imap' ,
@@ -609,7 +649,10 @@ async function processEmails(
609649 processedCount ++
610650 } catch ( error ) {
611651 if ( holdsCursorPastCompletedItems ( error ) ) throw error
612- if ( isUncountedPollFailure ( error ) && processedCount === 0 ) throw error
652+ if ( isUncountedPollFailure ( error ) ) {
653+ if ( processedCount === 0 ) throw error
654+ return { processedCount, failedCount, refusedAt : index }
655+ }
613656 logger . error ( `Error processing email ${ email . uid } ` )
614657 failedCount ++
615658 }
@@ -622,5 +665,5 @@ async function processEmails(
622665 }
623666 }
624667
625- return { processedCount, failedCount }
668+ return { processedCount, failedCount, refusedAt : undefined }
626669}
0 commit comments