Skip to content
Merged
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
15 changes: 14 additions & 1 deletion supabase/functions/_backend/triggers/updates_cache_purge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ export async function purgeUpdatesCacheTags(c: Context, tags: string[]): Promise
const localPurgeUrl = getEnv(c, 'UPDATES_CACHE_LOCAL_PURGE_URL')
const result: PurgeResult = { configured: Boolean(token || localPurgeUrl), calls: 0, failed: 0, retryAfterSeconds: 0 }
const targets: { url: string, headers: Record<string, string>, cloudflare: boolean }[] = []
const rateLimitedTargets = new Set<string>()

if (token) {
const zoneIds = await resolvePurgeZoneIds(c, token)
Expand All @@ -173,6 +174,12 @@ export async function purgeUpdatesCacheTags(c: Context, tags: string[]): Promise

for (const target of targets) {
for (const tagChunk of chunk(tags, PURGE_TAGS_PER_CALL)) {
// A rate-limited zone stays limited for this batch: more calls only use
// up the purge quota. The whole batch is requeued at its Retry-After.
if (target.cloudflare && rateLimitedTargets.has(target.url)) {
result.failed++
continue
}
result.calls++
try {
const response = await fetch(target.url, {
Expand All @@ -187,6 +194,8 @@ export async function purgeUpdatesCacheTags(c: Context, tags: string[]): Promise
const body = await response.json().catch(() => null) as { success?: boolean } | null
if (!response.ok || (target.cloudflare && body?.success !== true)) {
result.failed++
if (response.status === 429)
rateLimitedTargets.add(target.url)
result.retryAfterSeconds = Math.max(result.retryAfterSeconds, parseRetryAfterSeconds(response))
cloudlogErr({ requestId: c.get('requestId'), message: 'updates cache purge failed', url: target.url, status: response.status, cfSuccess: body?.success, tags: tagChunk.length })
}
Expand Down Expand Up @@ -279,7 +288,11 @@ export async function drainUpdatesCachePurge(
// placement data center before devices hit it cold.
schedulePluginStatePrewarm(c, apps.filter(row => row.scope === 'plugin_state').map(row => row.app_id))
}
if (!claim.has_more)
// A failed batch is already requeued at its Retry-After. Claiming the next
// one would hit the same rate limit and keep the purge quota spent (prod:
// thousands of 429s a minute, so no purge got through); the cron tick and
// the next wakeup resume once the limit clears.
if (!ok || !claim.has_more)
break
}
return { purgedApps, purgedAppIds }
Expand Down
30 changes: 30 additions & 0 deletions tests/updates-edge-cache.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,20 @@ describe('updates cache purge trigger', () => {
expect(fetchMock).toHaveBeenCalledTimes(1)
})

it('stops calling a zone that answered 429 for the rest of the batch', async () => {
vi.stubEnv('CF_CACHE_PURGE_TOKEN', 'token')
vi.stubEnv('CF_CACHE_PURGE_ZONE_IDS', 'zone-a, zone-b')
const fetchMock = vi.fn(async (url: string) => url.includes('/zone-a/')
? new Response('{}', { status: 429, headers: { 'Retry-After': '9' } })
: new Response(JSON.stringify({ success: true }), { status: 200 }))
vi.stubGlobal('fetch', fetchMock)
const tags = Array.from({ length: 250 }, (_, i) => `capgo-updates-app${i}`)

// zone-a: one call, then its 2 other chunks count as failed; zone-b: 3 calls.
await expect(purgeUpdatesCacheTags(makeContext(), tags)).resolves.toEqual({ configured: true, calls: 4, failed: 3, retryAfterSeconds: 9 })
expect(fetchMock.mock.calls.filter(call => String(call[0]).includes('/zone-a/'))).toHaveLength(1)
})

it('treats a token with no discoverable plugin zone as a failure to retry', async () => {
vi.stubEnv('CF_CACHE_PURGE_TOKEN', 'token')
vi.stubEnv('CF_CACHE_PURGE_ZONE_IDS', '')
Expand Down Expand Up @@ -473,6 +487,22 @@ describe('updates cache purge drain', () => {
expect(calls.find(call => call.fn === 'ack_updates_cache_purge')?.args).toEqual({ p_lease_token: 'lease-1', p_success: false, p_retry_after_seconds: 12 })
})

it('stops draining after a failed batch instead of claiming the next one', async () => {
vi.stubEnv('CF_CACHE_PURGE_TOKEN', 'token')
vi.stubEnv('CF_CACHE_PURGE_ZONE_IDS', 'zone-a')
const fetchMock = vi.fn().mockResolvedValue(new Response('{}', { status: 429, headers: { 'Retry-After': '12' } }))
vi.stubGlobal('fetch', fetchMock)
const { rpc, calls } = rpcFrom([
{ status: 'ok', lease_token: 'lease-1', apps: [{ app_id: 'com.a', initial: true }], has_more: true },
{ status: 'ok', lease_token: 'lease-2', apps: [{ app_id: 'com.b', initial: true }], has_more: false },
])

await expect(drainUpdatesCachePurge(makeContext(), rpc)).resolves.toEqual({ purgedApps: 0, purgedAppIds: [] })
expect(calls.filter(call => call.fn === 'claim_updates_cache_purge')).toHaveLength(1)
expect(fetchMock).toHaveBeenCalledTimes(1)
expect(calls.find(call => call.fn === 'ack_updates_cache_purge')?.args).toEqual({ p_lease_token: 'lease-1', p_success: false, p_retry_after_seconds: 12 })
})

it('treats a 200 answer with success: false as a failed purge', async () => {
vi.stubEnv('CF_CACHE_PURGE_TOKEN', 'token')
vi.stubEnv('CF_CACHE_PURGE_ZONE_IDS', 'zone-a')
Expand Down
Loading