背景与价值keepalive适用于卸载阶段上报,但过度使用会导致资源消耗与网络压力。统一限制与终止治理可提升稳定性。统一规范大小:单请求体≤64KB。速率:每分钟≤60次。终止:异常时终止并退避。核心实现限制与终止function withinSize(body: Blob | string | ArrayBuffer, max = 64 * 1024): boolean { if (typeof body === 'string') return new TextEncoder().encode(body).length <= max if (body instanceof Blob) return body.size <= max if (body instanceof ArrayBuffer) return body.byteLength <= max return false } class Rate { tokens = 0; cap = 60; last = Date.now(); refill(rpm = 60) { const now = Date.now(); const add = ((now - this.last) / 60000) * rpm; this.tokens = Math.min(this.cap, this.tokens + add); this.last = now } take(n = 1): boolean { this.refill(); if (this.tokens >= n) { this.tokens -= n; return true } return false } } async function sendKeepalive(url: string, body: any, rate: Rate): Promise<boolean> { if (!withinSize(body)) return false if (!rate.take()) return false try { const r = await fetch(url, { method: 'POST', body, keepalive: true }) return r.ok } catch { return false } } 落地建议对keepalive上报设置大小与速率限制,异常时终止与退避,避免卸载阶段网络压力。验证清单请求体是否≤64KB;速率是否在每分钟限制;异常是否终止并退避。

发表评论 取消回复