retry-timing.ts
This file
Path
source/core/retry-timing.ts
173 lines · 6.0 KiB · TypeScript
Last changed by
RefactorSindre Sorhusbefore adoptiona5ed57b
History of this fileTake it
Skip wrapping a body a hook read, and read a past reset epoch as a timestampSindre Sorhusbefore adoption23ca564
lines 1–2why, one step back1// A reset value is only read as an epoch from this second onwards (2001-09-09). Older values are ambiguous with an ordinary delay, but a delay of 32 years or more is not a real one, so anything below stays delay seconds. This is a fixed constant rather than a date so it cannot go stale and start misreading a recent-but-past reset.2const timestampThresholdSeconds = 1_000_000_000;Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
lines 3–157why, one step back3const delayPattern = /^\d+$/;4const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];56// HTTP-date parsing is limited to IMF-fixdate and the two obsolete HTTP-date formats. Other date-like strings intentionally fall back to the normal retry delay.7const imfDatePattern = /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/;8const rfc850DatePattern = /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{2}):(\d{2}):(\d{2}) GMT$/;9const asctimeDatePattern = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{2}| \d) (\d{2}:\d{2}:\d{2}) (\d{4})$/;1011type RetryTimingHeader = {12 value: string;13 allowTimestamp: boolean;14};1516type RetryTimingDateParts = {17 year: number;18 month: string;19 day: string;20 hours: string;21 minutes: string;22 seconds: string;23};2425export const getRetryTimingHeader = (headers: Headers): RetryTimingHeader | undefined => {26 const retryAfter = headers.get('Retry-After');27 if (retryAfter !== null) {28 return {value: retryAfter, allowTimestamp: false};29 }3031 // Retry-After is authoritative when present. Only missing Retry-After falls through to rate-limit headers.32 const rateLimitReset = headers.get('RateLimit-Reset');33 if (rateLimitReset !== null) {34 return {value: rateLimitReset, allowTimestamp: true};35 }3637 const rateLimitRetryAfter = headers.get('X-RateLimit-Retry-After'); // Symfony-based services38 if (rateLimitRetryAfter !== null) {39 return {value: rateLimitRetryAfter, allowTimestamp: false};40 }4142 const rateLimitResetAlias = headers.get('X-RateLimit-Reset') // GitHub43 ?? headers.get('X-Rate-Limit-Reset'); // Twitter44 if (rateLimitResetAlias !== null) {45 return {value: rateLimitResetAlias, allowTimestamp: true};46 }4748 return undefined;49};5051const createTimestamp = ({year, month, day, hours, minutes, seconds}: RetryTimingDateParts): number | undefined => {52 const monthIndex = months.indexOf(month);53 const dayNumber = Number(day);54 const hoursNumber = Number(hours);55 const minutesNumber = Number(minutes);56 const secondsNumber = Number(seconds);57 if (58 monthIndex === -159 || hoursNumber > 2360 || minutesNumber > 5961 || secondsNumber > 6062 ) {63 return undefined;64 }6566 const normalizedSeconds = Math.min(secondsNumber, 59);67 const date = new Date(Date.UTC(year, monthIndex, dayNumber, hoursNumber, minutesNumber, normalizedSeconds));68 date.setUTCFullYear(year);69 const timestamp = date.getTime();7071 // Date.UTC normalizes overflow, so round-trip the parts to reject invalid dates. A leap second is represented by parsing 60 as 59 and adding one second.72 if (73 date.getUTCFullYear() !== year74 || date.getUTCMonth() !== monthIndex75 || date.getUTCDate() !== dayNumber76 || date.getUTCHours() !== hoursNumber77 || date.getUTCMinutes() !== minutesNumber78 || date.getUTCSeconds() !== normalizedSeconds79 ) {80 return undefined;81 }8283 return secondsNumber === 60 ? timestamp + 1000 : timestamp;84};8586const getCapture = (match: RegExpExecArray, index: number): string => match[index]!;8788const parseDate = (value: string): number | undefined => {89 const imfDate = imfDatePattern.exec(value);90 if (imfDate) {91 return createTimestamp({92 year: Number(getCapture(imfDate, 3)),93 month: getCapture(imfDate, 2),94 day: getCapture(imfDate, 1),95 hours: getCapture(imfDate, 4),96 minutes: getCapture(imfDate, 5),97 seconds: getCapture(imfDate, 6),98 });99 }100101 const rfc850Date = rfc850DatePattern.exec(value);102 if (rfc850Date) {103 const now = new Date();104 const twoDigitYear = Number(getCapture(rfc850Date, 3));105 const currentCenturyYear = (Math.floor(now.getUTCFullYear() / 100) * 100) + twoDigitYear;106 const fiftyYearsFromNow = Date.UTC(now.getUTCFullYear() + 50, now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds());107 let timestamp: number | undefined;108109 // RFC 9110 maps two-digit years to the latest matching century that is not more than 50 years in the future.110 for (const year of [111 currentCenturyYear - 100,112 currentCenturyYear,113 currentCenturyYear + 100,114 ]) {115 const candidateTimestamp = createTimestamp({116 year,117 month: getCapture(rfc850Date, 2),118 day: getCapture(rfc850Date, 1),119 hours: getCapture(rfc850Date, 4),120 minutes: getCapture(rfc850Date, 5),121 seconds: getCapture(rfc850Date, 6),122 });123 if (124 candidateTimestamp !== undefined125 && candidateTimestamp <= fiftyYearsFromNow126 ) {127 timestamp = candidateTimestamp;128 }129 }130131 return timestamp;132 }133134 const asctimeDate = asctimeDatePattern.exec(value);135 if (asctimeDate) {136 const time = getCapture(asctimeDate, 4);137 const [hours, minutes, seconds] = time.split(':') as [string, string, string];138 return createTimestamp({139 year: Number(getCapture(asctimeDate, 5)),140 month: getCapture(asctimeDate, 2),141 day: getCapture(asctimeDate, 3).trim(),142 hours,143 minutes,144 seconds,145 });146 }147148 return undefined;149};150151export const calculateRetryTimingDelay = ({value, allowTimestamp}: RetryTimingHeader): number | undefined => {152 if (delayPattern.test(value)) {153 let delay = Number(value) * 1000;154155 // Standard Retry-After numbers are delay seconds. Timestamp compatibility only applies to reset headers.156 if (157 allowTimestampSkip wrapping a body a hook read, and read a past reset epoch as a timestampSindre Sorhusbefore adoption23ca564
line 158why, one step back158 && Number(value) >= timestampThresholdSecondsImprove `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
lines 159–170why, one step back159 ) {160 delay -= Date.now();161 }162163 return Math.max(0, delay);164 }165166 const timestamp = parseDate(value);167 if (timestamp === undefined) {168 return undefined;169 }170RefactorSindre Sorhusbefore adoptiona5ed57b
lines 171–172why, one step back171 // `createTimestamp()` only returns valid dates, so the delay is always finite.172 return Math.max(0, timestamp - Date.now());Improve `Retry-After` handling (#874)Sindre Sorhusbefore adoption3419113
line 173why, one step back173};