背景与价值
keepalive适用于卸载阶段上报,但过度使用会导致资源消耗与网络压力。统一限制与终止治理可提升稳定性。
统一规范
- 大小:单请求体≤64KB。
- 速率:每分钟≤60次。
- 终止:异常时终止并退避。
核心实现
限制与终止
```ts
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

发表评论 取消回复