-
Notifications
You must be signed in to change notification settings - Fork 37
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(twilio): add retry on message send fail (#651)
- Loading branch information
1 parent
f389ff8
commit a40bc7b
Showing
2 changed files
with
39 additions
and
12 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,22 +1,45 @@ | ||
import { backOff } from 'exponential-backoff' | ||
import ms from 'ms' | ||
import { CommonSender } from '../../base/senders/common' | ||
import { TwilioContext } from '../context' | ||
|
||
const DEFAULT_MAX_ATTEMPTS = 3 | ||
|
||
export class TwilioCommonSender extends CommonSender { | ||
async send(context: TwilioContext) { | ||
for (const message of context.messages) { | ||
await context.state.twilio.messages.create({ | ||
...message, | ||
from: context.identity, | ||
to: context.sender | ||
}) | ||
const { messageDelay, retryDelay, retryMaxAttempts = DEFAULT_MAX_ATTEMPTS } = context.state.config | ||
await backOff( | ||
async () => { | ||
await context.state.twilio.messages.create({ | ||
...message, | ||
from: context.identity, | ||
to: context.sender | ||
}) | ||
|
||
const { messageDelay } = context.state.config | ||
if (messageDelay) { | ||
// depending on the account it might be required to limit the rps to each number | ||
// usually this is an issue for carousels | ||
await new Promise((resolve) => setTimeout(resolve, ms(messageDelay))) | ||
} | ||
if (messageDelay) { | ||
// depending on the account it might be required to limit the rps to each number | ||
// usually this is an issue for carousels | ||
await new Promise((resolve) => setTimeout(resolve, ms(messageDelay))) | ||
} | ||
}, | ||
{ | ||
jitter: 'none', | ||
numOfAttempts: retryMaxAttempts, | ||
startingDelay: (retryDelay && ms(retryDelay)) || 1000, | ||
retry: (e, attemptNumber) => { | ||
if (attemptNumber === 1) { | ||
context.logger?.error( | ||
e, | ||
`Failed to send message to Twilio on first attempt. Retrying ${retryMaxAttempts} more times` | ||
) | ||
} else { | ||
context.logger?.error(e, `Failed again, retry: ${attemptNumber}`) | ||
} | ||
return true | ||
} | ||
} | ||
) | ||
} | ||
} | ||
} |