mirror of
https://github.com/overleaf/overleaf.git
synced 2024-12-04 02:46:51 -05:00
59e587320a
[misc] prepare migration to user content domain GitOrigin-RevId: 581ccab6d39ec021fb44a555a09e55441c35d0d1
51 lines
1.6 KiB
TypeScript
51 lines
1.6 KiB
TypeScript
import { isNetworkError } from '../../../utils/isNetworkError'
|
|
import getMeta from '../../../utils/meta'
|
|
import OError from '@overleaf/o-error'
|
|
import { postJSON } from '../../../infrastructure/fetch-json'
|
|
|
|
let useFallbackDomainUntil = performance.now()
|
|
const ONE_HOUR_IN_MS = 1000 * 60 * 60
|
|
|
|
export async function fetchFromCompileDomain(url: string, init: RequestInit) {
|
|
const userContentDomain = getMeta('ol-compilesUserContentDomain')
|
|
let isUserContentDomain =
|
|
userContentDomain &&
|
|
new URL(url).hostname === new URL(userContentDomain).hostname
|
|
|
|
if (useFallbackDomainUntil > performance.now()) {
|
|
isUserContentDomain = false
|
|
url = withFallbackCompileDomain(url)
|
|
}
|
|
try {
|
|
return await fetch(url, init)
|
|
} catch (err) {
|
|
if (isNetworkError(err) && isUserContentDomain) {
|
|
try {
|
|
const res = await fetch(withFallbackCompileDomain(url), init)
|
|
// Only switch to the fallback when fetch does not throw there as well.
|
|
if (useFallbackDomainUntil < performance.now()) {
|
|
useFallbackDomainUntil = performance.now() + ONE_HOUR_IN_MS
|
|
recordFallbackUsage()
|
|
}
|
|
return res
|
|
} catch (err2: any) {
|
|
throw OError.tag(err2, 'fallback request failed', {
|
|
errUserContentDomain: err,
|
|
})
|
|
}
|
|
}
|
|
throw err
|
|
}
|
|
}
|
|
|
|
function withFallbackCompileDomain(url: string) {
|
|
const u = new URL(url)
|
|
u.hostname = new URL(getMeta('ol-fallbackCompileDomain')).hostname
|
|
return u.href
|
|
}
|
|
|
|
function recordFallbackUsage() {
|
|
setTimeout(() => {
|
|
postJSON('/record-user-content-domain-fallback-usage').catch(() => {})
|
|
}, 1_000)
|
|
}
|