-
-
Notifications
You must be signed in to change notification settings - Fork 129
feat(updates): colo cache for /updates with targeted worldwide invalidation #2662
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
riderx
wants to merge
12
commits into
main
Choose a base branch
from
feat/updates-colo-cache
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
169d28f
feat(updates): colo cache for /updates with targeted worldwide invali…
riderx 8fd4807
fix(migration): reword comment flagged by typos check
riderx 543583a
fix(updates-cache): dedupe with pg helpers, bound invalidation fan-out
riderx 7faa8ba
fix(migration): lock down cache invalidation functions to service roles
riderx a22d38d
test(updates-cache): postgres-level trigger coverage + review quick wins
riderx ff3a3c6
fix(updates-cache): request-consistent tokens, no error caching, stri…
riderx 277f652
refactor(updates-cache): reuse API_SECRET for invalidation auth
riderx 0b601ac
fix(updates-cache): long negative TTL for unknown apps + restore devi…
riderx eee4ff0
fix(updates-cache): statement-level triggers, host-independent keys, …
riderx 09ec66f
fix(tests): align release-scope changelog assertion with Workers AI flow
riderx 31bee67
fix(updates-cache): sonar reliability trio + ownership + stronger tests
riderx 2d73154
chore(tests): take main's release-scope changelog coverage
riderx File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| // Colo cache invalidation endpoint, mounted on every regional plugin worker. | ||
| // | ||
| // The plugin workers are placement-pinned, so a request to each regional | ||
| // domain lands in the colo whose cache serves that region's devices. The | ||
| // cache_invalidate trigger handler fans a token bump out to all regions; | ||
| // each bump makes every cached /updates payload of the app unreachable | ||
| // (see updates_colo_cache.ts). Auth is a dedicated shared secret so this | ||
| // stays independent from the API-secret used by Supabase triggers. | ||
|
|
||
| import type { MiddlewareKeyVariables } from '../utils/hono.ts' | ||
| import { Hono } from 'hono/tiny' | ||
| import { BRES, middlewareAPISecret, parseBody, quickError } from '../utils/hono.ts' | ||
| import { cloudlog } from '../utils/logging.ts' | ||
| import { bumpAppCacheToken, isUpdatesCacheEnabled } from '../utils/updates_colo_cache.ts' | ||
|
|
||
| export const MAX_INVALIDATE_APPS = 100 | ||
|
|
||
| export const app = new Hono<MiddlewareKeyVariables>() | ||
|
|
||
| app.post('/', middlewareAPISecret, async (c) => { | ||
|
riderx marked this conversation as resolved.
|
||
| const body = await parseBody<{ app_ids?: unknown }>(c) | ||
| const appIds = Array.isArray(body.app_ids) | ||
| ? body.app_ids.filter((appId): appId is string => typeof appId === 'string' && appId.length > 0) | ||
| : [] | ||
| if (appIds.length === 0) | ||
| throw quickError(400, 'missing_app_ids', 'app_ids must be a non-empty array of strings') | ||
| // Loud rejection instead of silent truncation: the fan-out chunks to this | ||
| // size, so anything larger is a caller bug that would leave caches stale. | ||
| if (appIds.length > MAX_INVALIDATE_APPS) | ||
| throw quickError(400, 'too_many_app_ids', `app_ids is limited to ${MAX_INVALIDATE_APPS} per request`) | ||
|
|
||
| // Bump even when the cache mode is off so entries from a prior "on" | ||
| // window can never be served stale after a toggle. | ||
| const results = await Promise.all(appIds.map(appId => bumpAppCacheToken(c, appId))) | ||
| const bumped = results.filter(Boolean).length | ||
| cloudlog({ requestId: c.get('requestId'), message: 'updates cache invalidated', appIds, bumped, enabled: isUpdatesCacheEnabled(c) }) | ||
| return c.json({ ...BRES, bumped }) | ||
| }) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| // Fan-out of /updates colo-cache invalidations to every regional plugin | ||
| // worker. | ||
| // | ||
| // Called by the invalidate_updates_cache() database trigger (via pg_net) | ||
| // whenever a row that feeds the update hot path changes (channels, | ||
| // channel_devices, apps, app_versions, orgs, stripe_info). The plugin | ||
| // workers are placement-pinned, so one POST per regional domain reaches | ||
| // every colo that caches this app — end-to-end reaction is ~1s from the | ||
| // database commit, with the cache TTL as backstop when a call is lost. | ||
|
|
||
| import type { MiddlewareKeyVariables } from '../utils/hono.ts' | ||
| import { Hono } from 'hono/tiny' | ||
| import { MAX_INVALIDATE_APPS } from '../private/cache_invalidate.ts' | ||
| import { BRES, middlewareAPISecret, parseBody } from '../utils/hono.ts' | ||
| import { cloudlog, cloudlogErr, serializeError } from '../utils/logging.ts' | ||
| import { existInEnv, getEnv } from '../utils/utils.ts' | ||
|
|
||
| const FANOUT_TIMEOUT_MS = 5000 | ||
| const FANOUT_CHUNK_SIZE = MAX_INVALIDATE_APPS | ||
|
|
||
| export function chunkAppIds(appIds: string[], size = FANOUT_CHUNK_SIZE): string[][] { | ||
| const unique = [...new Set(appIds)] | ||
| const chunks: string[][] = [] | ||
| for (let i = 0; i < unique.length; i += size) | ||
| chunks.push(unique.slice(i, i + size)) | ||
| return chunks | ||
| } | ||
|
|
||
| export function parsePluginInvalidateUrls(raw: string): string[] { | ||
| return raw | ||
| .split(',') | ||
| .map(url => url.trim().replace(/\/$/, '')) | ||
| .filter(Boolean) | ||
| } | ||
|
|
||
| export const app = new Hono<MiddlewareKeyVariables>() | ||
|
|
||
| app.post('/', middlewareAPISecret, async (c) => { | ||
|
riderx marked this conversation as resolved.
|
||
| const body = await parseBody<{ app_ids?: unknown }>(c) | ||
| const appIds = Array.isArray(body.app_ids) | ||
| ? body.app_ids.filter((appId): appId is string => typeof appId === 'string' && appId.length > 0) | ||
| : [] | ||
| if (appIds.length === 0) { | ||
| cloudlog({ requestId: c.get('requestId'), message: 'cache invalidate fanout skipped (no app_ids)' }) | ||
| return c.json(BRES) | ||
| } | ||
|
|
||
| if (!existInEnv(c, 'PLUGIN_INVALIDATE_URLS')) { | ||
| // Soft-skip: invalidation is an accelerator, the cache TTL is the backstop. | ||
| cloudlog({ requestId: c.get('requestId'), message: 'cache invalidate fanout skipped (missing env)', appIds }) | ||
| return c.json(BRES) | ||
| } | ||
|
|
||
| const urls = parsePluginInvalidateUrls(getEnv(c, 'PLUGIN_INVALIDATE_URLS')) | ||
| // Same intercommunication secret that authenticated this request. | ||
| const secret = getEnv(c, 'API_SECRET') | ||
| const chunks = chunkAppIds(appIds) | ||
| const results = await Promise.all(urls.map(async (url) => { | ||
| try { | ||
| // Chunked to the route's per-request cap: nothing is ever silently | ||
| // dropped, a large org just becomes a few sequential calls per region. | ||
| for (const chunk of chunks) { | ||
| const response = await fetch(`${url}/cache_invalidate`, { | ||
| method: 'POST', | ||
| headers: { | ||
| 'Content-Type': 'application/json', | ||
| 'apisecret': secret, | ||
| }, | ||
| body: JSON.stringify({ app_ids: chunk }), | ||
| signal: AbortSignal.timeout(FANOUT_TIMEOUT_MS), | ||
| }) | ||
| if (!response.ok) { | ||
| cloudlogErr({ requestId: c.get('requestId'), message: 'cache invalidate fanout failed', url, status: response.status }) | ||
| return false | ||
| } | ||
| } | ||
| return true | ||
| } | ||
| catch (e) { | ||
| cloudlogErr({ requestId: c.get('requestId'), message: 'cache invalidate fanout error', url, error: serializeError(e) }) | ||
| return false | ||
| } | ||
| })) | ||
| const succeeded = results.filter(Boolean).length | ||
| cloudlog({ requestId: c.get('requestId'), message: 'cache invalidate fanout done', appIds, regions: urls.length, succeeded }) | ||
| return c.json({ ...BRES, regions: urls.length, succeeded }) | ||
| }) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.