Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
160 changes: 154 additions & 6 deletions files/k0s/kiosk/kiosk-gate.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,124 @@
const healthURL = 'http://127.0.0.1:8585/health'
const gateID = 'kubestellar-kiosk-gate'

const INITIAL_BACKOFF_MS = 500
const BACKOFF_FACTOR = 2
const MAX_RETRIES = 4
const STAGGER_INTERVAL_MS = 75
const MAX_RETRY_DELAY_MS = 30_000

// Page-lifetime cursor: any concurrent /api burst is spaced, not only the
// first-boot hydration one, because the console rate limiter is also
// page-lifetime and periodic refreshes fan out the same way.
let lastDispatchTime = -STAGGER_INTERVAL_MS

const sleep = (ms, signal) => new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(new DOMException('Aborted', 'AbortError'))
return
}
const timer = setTimeout(resolve, ms)
signal?.addEventListener('abort', () => {
clearTimeout(timer)
reject(new DOMException('Aborted', 'AbortError'))
}, { once: true })
})

const isApiRequest = (input) => {
try {
let urlStr
if (typeof input === 'string') {
urlStr = input
} else if (input instanceof URL) {
urlStr = input.href
} else if (input && typeof input === 'object' && 'url' in input) {
urlStr = input.url
} else {
urlStr = String(input)
}

const origin = typeof window !== 'undefined' && window.location ? window.location.origin : 'http://localhost'
const parsed = new URL(urlStr, origin)
return parsed.origin === origin && (parsed.pathname === '/api' || parsed.pathname.startsWith('/api/'))
} catch {
return false
}
}

const staggerRequest = async (signal) => {
const now = Date.now()
const scheduledTime = Math.max(now, lastDispatchTime + STAGGER_INTERVAL_MS)
lastDispatchTime = scheduledTime
const waitMs = scheduledTime - now
if (waitMs > 0) {
await sleep(waitMs, signal)
}
}

const clampDelay = (ms) => Math.min(Math.max(ms, 0), MAX_RETRY_DELAY_MS)

const parseRetryAfter = (response) => {
try {
const header = response.headers?.get?.('Retry-After')
if (!header) return null
const seconds = Number(header)
if (!Number.isNaN(seconds) && seconds >= 0) {
return clampDelay(seconds * 1000)
}
const dateMs = Date.parse(header)
if (!Number.isNaN(dateMs)) {
return clampDelay(dateMs - Date.now())
}
} catch {
// fallback
}
return null
}

const executeFetch = (originalFetch, input, init) => {
if (typeof Request !== 'undefined' && input instanceof Request) {
try {
return originalFetch(input.clone(), init)
} catch {
return originalFetch(input, init)
}
}
return originalFetch(input, init)
}

if (typeof window !== 'undefined' && typeof window.fetch === 'function') {
const originalFetch = window.fetch.bind(window)

window.fetch = async function (input, init) {
if (!isApiRequest(input)) {
return originalFetch(input, init)
}

const signal = init?.signal || (typeof Request !== 'undefined' && input instanceof Request ? input.signal : undefined)
if (signal?.aborted) {
throw new DOMException('The user aborted a request.', 'AbortError')
}

await staggerRequest(signal)

let attempt = 0
while (true) {
const response = await executeFetch(originalFetch, input, init)
if (response.status !== 429 || attempt >= MAX_RETRIES) {
return response
}

attempt++
const retryAfterMs = parseRetryAfter(response)
const backoffMs = retryAfterMs !== null
? retryAfterMs
: clampDelay(INITIAL_BACKOFF_MS * Math.pow(BACKOFF_FACTOR, attempt - 1))

await sleep(backoffMs, signal)
}
}
}

const hasSession = () => {
try {
return window.localStorage.getItem(sessionKey) === 'true'
Expand Down Expand Up @@ -44,10 +162,40 @@
}
}

document.addEventListener('keydown', (event) => {
const gate = document.getElementById(gateID)
if (gate && !gate.contains(event.target)) event.preventDefault()
}, true)
window.setInterval(() => void updateGate(), 2_000)
void updateGate()
if (typeof document !== 'undefined') {
document.addEventListener('keydown', (event) => {
const gate = document.getElementById(gateID)
if (gate && !gate.contains(event.target)) event.preventDefault()
}, true)
}

const startGateLoop = () => {
window.setInterval(() => void updateGate(), 2_000)
void updateGate()
}

if (typeof window !== 'undefined') {
// The interceptor above is installed at parse time, but the gate markup
// needs document.body, which does not exist yet when this script runs
// synchronously from <head>.
if (typeof document !== 'undefined' && document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', startGateLoop, { once: true })
} else {
startGateLoop()
}
}

if (typeof module !== 'undefined' && module.exports) {
module.exports = {
isApiRequest,
parseRetryAfter,
staggerRequest,
clampDelay,
INITIAL_BACKOFF_MS,
BACKOFF_FACTOR,
MAX_RETRIES,
STAGGER_INTERVAL_MS,
MAX_RETRY_DELAY_MS,
}
}
})()
7 changes: 5 additions & 2 deletions files/k0s/kiosk/nginx.conf
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,11 @@ http {
proxy_set_header Accept-Encoding "";
proxy_set_header Connection "";
sub_filter_once on;
sub_filter '</head>' '<link rel="stylesheet" href="/kiosk-gate.css"></head>';
sub_filter '</body>' '<script defer src="/kiosk-gate.js"></script></body>';
# Injected synchronously at the end of <head> so window.fetch is patched
# before the console bundle executes. Classic non-deferred scripts run
# before any deferred/module script and before end-of-body scripts, so
# the first-boot hydration burst is intercepted.
sub_filter '</head>' '<link rel="stylesheet" href="/kiosk-gate.css"><script src="/kiosk-gate.js"></script></head>';
}
}
}
Loading
Loading