Mail relay: review of 7d766b6 — R-1 to R-12, four mutations, two sentences
- R-1 a delivered token becomes the one in use only on 200 or a refusal given after authentication - R-2 a token of another site is refused by what /v1/status says (access-key field, scripts); docs for staging - R-3 the confirm route looks the nonce up first and counts only refused calls - R-4 one budget of time per message (10 s, 30 s with files), enrolment and retries included - R-5 'Disconnect' without the service's answer is not confirmed and keeps the token to try again - R-6 no enrolment without the confirm route in the config - R-7 half an SMTP set-up: one log line and a hint in the panel - R-8 to R-10, R-12 docs; R-11 the last failure stays in the state block - tests for redirect: manual, the candidate's nonce, the expectation taken back, one recipient only Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
0ee74ab2a4
commit
a2b07b1dc1
@@ -84,7 +84,7 @@ function describeRefusal(answer: RelayRefusal): { sent: false } & RelaySendResul
|
||||
const extra = [answer.limit ? `limit: ${answer.limit}` : '', answer.reason ? `reason: ${answer.reason}` : '', answer.field ? `field: ${answer.field}` : ''].filter(Boolean).join(', ')
|
||||
const said = `${answer.code}${extra ? ` (${extra})` : ''}: ${answer.message}`
|
||||
if (answer.code === LOCAL_CODES.disconnected) {return failure('relay-disconnected', answer.code, answer.message)}
|
||||
if (answer.code === LOCAL_CODES.noToken || answer.code === LOCAL_CODES.noHost) {return failure('relay-refused', answer.code, answer.message)}
|
||||
if (([LOCAL_CODES.foreignToken, LOCAL_CODES.noHost, LOCAL_CODES.noRoute, LOCAL_CODES.noToken] as string[]).includes(answer.code)) {return failure('relay-refused', answer.code, answer.message)}
|
||||
// No answer at all, or a send the service cannot report on yet: it may be out.
|
||||
if (answer.noAnswer || answer.code === 'in-progress') {return failure('relay-not-confirmed', answer.code, `Not confirmed — the message may have been sent. ${said}`, false)}
|
||||
if (answer.code === 'callback-failed' && answer.reason === 'status') {
|
||||
@@ -113,6 +113,9 @@ export type RelaySendContext = {
|
||||
* `Idempotency-Key`: at most three attempts, 30 seconds each, at most ten seconds of waiting between
|
||||
* them in all (which win over the service's `retryAfter`), and only after an answer that says
|
||||
* `retryable` or after no answer. An enrolment made on the way is not one of the three.
|
||||
*
|
||||
* All of it shares one budget (`totalTimeoutMs`: 10 seconds, 30 with files): the request that sends the
|
||||
* mail has somebody waiting. An attempt cut off by it counts as no answer — "not confirmed".
|
||||
*/
|
||||
export async function sendThroughRelay(payload: BasePayload, options: ResolvedRelayOptions, message: SendEmailOptions, context: RelaySendContext = {}): Promise<RelaySendResult> {
|
||||
// What the message is: its own mark; else what an auth operation said about a message to this address
|
||||
@@ -158,26 +161,51 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
|
||||
}
|
||||
}
|
||||
|
||||
// Somebody waits for this request (a form's visitor): everything from here on — a check, an enrolment, the
|
||||
// attempts and the waits between them — shares one budget. A service that hangs costs that much, not the
|
||||
// sum of the attempts' time-outs.
|
||||
const total = options.totalTimeoutMs
|
||||
const hasFiles = Boolean(request.attachments?.length)
|
||||
const budgetMs =
|
||||
typeof total === 'number' ? total
|
||||
: hasFiles ? (total?.files ?? RELAY_DEFAULTS.totalTimeoutWithFilesMs)
|
||||
: (total?.plain ?? RELAY_DEFAULTS.totalTimeoutMs)
|
||||
const deadline = Date.now() + Math.max(1, budgetMs)
|
||||
const left = () => deadline - Date.now()
|
||||
|
||||
// A token stored by hand is used only once the service has said that it is this host's (a token of another
|
||||
// site, pasted in or copied, must not send as that site).
|
||||
if (stored.token && stored.manual && !stored.hostChecked && options.token === undefined) {
|
||||
const checked = await refreshRelayStatus(payload, options, { timeoutMs: Math.max(1, left()) })
|
||||
if (checked.error && checked.error.code !== 'reverify' && checked.error.code !== 'invalid-token') {
|
||||
// nothing was sent: the check itself did not get through, or the token is another site's
|
||||
return checked.error.code === LOCAL_CODES.foreignToken
|
||||
? failure('relay-refused', checked.error.code, checked.error.message)
|
||||
: failure('relay-unreachable', checked.error.code, `The token stored by hand could not be checked with the mail service, so nothing was sent. ${checked.error.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
if (stored.service?.rotateAfter && Date.parse(stored.service.rotateAfter) <= Date.now()) {
|
||||
await rotateRelayToken(payload, options).catch(() => undefined)
|
||||
await rotateRelayToken(payload, options, { timeoutMs: Math.max(1, left()) }).catch(() => undefined)
|
||||
}
|
||||
|
||||
const body = Buffer.from(JSON.stringify(request), 'utf8')
|
||||
const hash = createHash('sha256').update(body).digest('hex')
|
||||
const idempotencyKey = keyFor(hash)
|
||||
const use: TokenUse = {}
|
||||
const use: TokenUse = { deadline }
|
||||
const budget = RELAY_DEFAULTS.waitBudgetMs
|
||||
let attempts = 0
|
||||
let waited = 0
|
||||
let answer: RelayAnswer<SendBody> = { code: 'unavailable', message: 'not tried', noAnswer: false, ok: false, retryable: false, status: 0 }
|
||||
|
||||
while (attempts < RELAY_DEFAULTS.attempts) {
|
||||
if (left() <= 0) {break} // the time is up: report what the last attempt said
|
||||
answer = await withRelayToken<SendBody>(
|
||||
payload,
|
||||
options,
|
||||
(token) => {
|
||||
attempts += 1
|
||||
return relayRequest<SendBody>({ body, fetchImpl: options.fetchImpl, idempotencyKey, method: 'POST', path: '/v1/send', timeoutMs: options.timeoutMs ?? RELAY_DEFAULTS.attemptTimeoutMs, token, url: options.url })
|
||||
return relayRequest<SendBody>({ body, fetchImpl: options.fetchImpl, idempotencyKey, method: 'POST', path: '/v1/send', timeoutMs: Math.max(1, Math.min(options.timeoutMs ?? RELAY_DEFAULTS.attemptTimeoutMs, left())), token, url: options.url })
|
||||
},
|
||||
use,
|
||||
)
|
||||
@@ -186,7 +214,7 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
|
||||
if (use.enrolment && !use.enrolment.ok) {break}
|
||||
const wait = answer.retryAfter !== undefined ? answer.retryAfter * 1000 : attempts * (options.retryBackoffMs ?? 1000)
|
||||
// The ten seconds win over retryAfter: stop at once and report.
|
||||
if (waited + wait > budget) {break}
|
||||
if (waited + wait > budget || wait >= left()) {break}
|
||||
await sleep(wait)
|
||||
waited += wait
|
||||
}
|
||||
@@ -214,7 +242,7 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
|
||||
// Limits, quota and the day to rotate: read again once they are an hour old. Awaited (one short GET an
|
||||
// hour): a write to the store that lands after the request has ended could undo a "Disconnect" or a rotation.
|
||||
if (!now.service || Date.now() - Date.parse(now.service.fetchedAt) > RELAY_DEFAULTS.statusTtlMs) {
|
||||
await refreshRelayStatus(payload, options)
|
||||
await refreshRelayStatus(payload, options, { timeoutMs: Math.max(2000, left()) })
|
||||
}
|
||||
} catch {
|
||||
/* bookkeeping must not turn a sent mail into a failed one */
|
||||
@@ -241,6 +269,17 @@ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRe
|
||||
const state = answer.code === 'site-pending' ? 'pending' : 'suspended'
|
||||
if (stored.state !== state) {await updateRelayStore(payload, (current) => ({ ...current, state })).catch(() => undefined)}
|
||||
}
|
||||
// The panel's status is the LAST send's; a later good mail must not hide this one: kept with its time
|
||||
// (written when the code changes, or every ten minutes while it lasts).
|
||||
try {
|
||||
const now = await readRelayStore(payload)
|
||||
const last = now.lastFailure
|
||||
if (!last || last.code !== result.code || Date.now() - Date.parse(last.at) > 10 * 60_000) {
|
||||
await updateRelayStore(payload, (current) => ({ ...current, lastFailure: { at: new Date().toISOString(), code: result.code, kind } }))
|
||||
}
|
||||
} catch {
|
||||
/* bookkeeping only */
|
||||
}
|
||||
payload.logger.error(`[iapl] mail service: e-mail ${result.confirmed ? 'not sent' : 'not confirmed'} (${result.code}; ${answer.code}${answer.limit ? `, ${answer.limit}` : ''}${answer.reason ? `, ${answer.reason}` : ''}).`)
|
||||
return result
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user