diff --git a/cloud/apps/relay-edge/src/host-relay.ts b/cloud/apps/relay-edge/src/host-relay.ts index 643c64f6b89..80acadffeb6 100644 --- a/cloud/apps/relay-edge/src/host-relay.ts +++ b/cloud/apps/relay-edge/src/host-relay.ts @@ -62,7 +62,7 @@ type ControlAttachment = { lastPongAt?: number lastPingAt?: number leaseExpiresAt?: number - // Client ingress '/', for metrics. + // Client ingress '//', for metrics. place?: string } type Attachment = ControlAttachment diff --git a/cloud/apps/relay-edge/src/metrics.ts b/cloud/apps/relay-edge/src/metrics.ts index 6be3f7a2672..0dc7d3e1465 100644 --- a/cloud/apps/relay-edge/src/metrics.ts +++ b/cloud/apps/relay-edge/src/metrics.ts @@ -22,7 +22,8 @@ export type MetricEvent = | 'not_on_edge' // blobs: [event, label, version, reason, place]; doubles: [value, ...extra]. place is the -// client's ingress '/' (e.g. 'AS/HKG'), '' where no client is involved. One index per event for sampling. +// client's ingress '//' (e.g. 'AS/HKG/HK'; country appended so prefix +// filters on continent/colo keep working), '' where no client is involved. One index per event for sampling. // Heartbeat events fire per host every ping interval; keep 1 in 10 (multiply counts by 10). const HEARTBEAT_SAMPLE = 0.1 @@ -41,6 +42,6 @@ export function metric(env: Env, event: MetricEvent, value = 1, label = '', extr // From the Worker's request (cf is absent in local dev). export function requestPlace(request: Request): string { - const cf = (request as Request & { cf?: { colo?: string; continent?: string } }).cf - return cf ? `${cf.continent ?? '?'}/${cf.colo ?? '?'}` : 'local' + const cf = (request as Request & { cf?: { colo?: string; continent?: string; country?: string } }).cf + return cf ? `${cf.continent ?? '?'}/${cf.colo ?? '?'}/${cf.country ?? '?'}` : 'local' } diff --git a/cloud/apps/relay-edge/src/splice-relay.ts b/cloud/apps/relay-edge/src/splice-relay.ts index 462ef857c6d..f0ee9db8cee 100644 --- a/cloud/apps/relay-edge/src/splice-relay.ts +++ b/cloud/apps/relay-edge/src/splice-relay.ts @@ -23,7 +23,7 @@ type State = { } type SocketKind = 'phone' | 'data' // Per-direction flood guard: bytes forwarded to a peer since that peer last sent anything. -// place: client ingress '/', for metrics. +// place: client ingress '//', for metrics. // sentBytes/sentFrames: what this socket sent, kept on the attachment so it survives hibernation. type GuardAttachment = { silentBytes: number; windowStart: number; place?: string; sentBytes?: number; sentFrames?: number } diff --git a/cloud/apps/relay-edge/test/metrics.test.ts b/cloud/apps/relay-edge/test/metrics.test.ts new file mode 100644 index 00000000000..f44af72c939 --- /dev/null +++ b/cloud/apps/relay-edge/test/metrics.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it, vi } from 'vitest' +import { metric, requestPlace } from '../src/metrics' +import type { Env } from '../src/env' + +const withCf = (cf?: Record) => { + const request = new Request('https://edge.test/v1/connect/x') + if (cf) { + Object.defineProperty(request, 'cf', { value: cf }) + } + return request +} + +describe('metric place', () => { + it('is continent/colo/country of the client ingress, with ? for a missing part', () => { + expect(requestPlace(withCf({ continent: 'AS', colo: 'HKG', country: 'HK' }))).toBe('AS/HKG/HK') + expect(requestPlace(withCf({ continent: 'AS', colo: 'SIN' }))).toBe('AS/SIN/?') + expect(requestPlace(withCf())).toBe('local') + }) + + it('lands in blob 5, with no other request detail', () => { + const writeDataPoint = vi.fn() + const env = { METRICS: { writeDataPoint }, EDGE_VERSION: 'v1' } as unknown as Env + metric(env, 'not_on_edge', 1, '', [], '', requestPlace(withCf({ continent: 'AS', colo: 'HKG', country: 'CN' }))) + expect(writeDataPoint).toHaveBeenCalledWith({ + indexes: ['not_on_edge'], + blobs: ['not_on_edge', '', 'v1', '', 'AS/HKG/CN'], + doubles: [1] + }) + }) +}) diff --git a/cloud/apps/relay/src/app.ts b/cloud/apps/relay/src/app.ts index 6282d4db107..b1e02e561c0 100644 --- a/cloud/apps/relay/src/app.ts +++ b/cloud/apps/relay/src/app.ts @@ -62,6 +62,7 @@ import { mayBeOnEdge, type EdgeAssignments } from './edge-relay.js' +import { requestCountry } from './ip-country.js' import { DRAIN_RETURN_MIN_RETRY_AFTER_SECONDS, RelayDrainReturnAdmission @@ -494,10 +495,15 @@ export function createRelayApp( // Relay edge: a host in the cohort is moved (or kept) there before any other lane, since the // sticky and reserve lanes would read the edge row as not live and re-place the host. const edge = operations.edgeAssignments + // From the IP table only; the address itself is never kept or logged. + const country = edge ? requestCountry(edge.config.ipCountry, context.req.header('x-forwarded-for')) : null + if (edge?.config.ipCountry) { + edge.regionCountries.record(requestedRegion, country) + } const toEdge = edge?.ready === true && body.data.regionCorrection?.action !== 'report' && - inEdgeCohort(edge.config, claims.relayHostId, requestedRegion, claims.sub) + inEdgeCohort(edge.config, claims.relayHostId, requestedRegion, claims.sub, country) if (edge?.pushes && !toEdge && mayBeOnEdge(edge.config, claims.relayHostId, claims.sub)) { // Any lane below may re-place a host whose row is on the edge; its devices come back first. // Hosts that were never in a cohort skip this row read (most asks; the pool is small). diff --git a/cloud/apps/relay/src/config.test.ts b/cloud/apps/relay/src/config.test.ts index a00f434cbb1..93c695d9700 100644 --- a/cloud/apps/relay/src/config.test.ts +++ b/cloud/apps/relay/src/config.test.ts @@ -1,3 +1,6 @@ +import { mkdtempSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' import { describe, expect, it } from 'vitest' import { loadRelayConfig, @@ -382,6 +385,21 @@ describe('relay edge configuration', () => { expect(() => loadRelayConfig({ ...env, ORCA_RELAY_EDGE_CELL_URL: 'https://relay.example.com' })).toThrow() }) + it('loads the IP country table at boot, and fails the boot when it cannot', () => { + const env = { + ...directorEnvironment(), + ORCA_RELAY_EDGE_CELL_URL: 'https://edge.relay.example.com', + ORCA_RELAY_EDGE_ADMIN_SIGNING_KEY: 'edge-admin-key-with-at-least-32-bytes!!' + } + expect(loadRelayConfig(env).edge).not.toHaveProperty('ipCountry') + expect(loadRelayConfig({ ...env, ORCA_RELAY_IP_COUNTRY_DB: '' }).edge).not.toHaveProperty('ipCountry') + const directory = mkdtempSync(join(tmpdir(), 'relay-ip-country-')) + writeFileSync(join(directory, 'table.csv'), '192.0.2.0,192.0.2.255,HK\n') + const edge = loadRelayConfig({ ...env, ORCA_RELAY_IP_COUNTRY_DB: join(directory, 'table.csv') }).edge + expect(edge?.ipCountry?.country('192.0.2.9')).toBe('HK') + expect(() => loadRelayConfig({ ...env, ORCA_RELAY_IP_COUNTRY_DB: join(directory, 'missing.csv') })).toThrow() + }) + it('parses the export skip threshold, leaving the default when unset or empty', () => { const env = { ...directorEnvironment(), diff --git a/cloud/apps/relay/src/config.ts b/cloud/apps/relay/src/config.ts index 07507d810e4..b5ce6992cee 100644 --- a/cloud/apps/relay/src/config.ts +++ b/cloud/apps/relay/src/config.ts @@ -15,6 +15,7 @@ import { RELAY_READINESS_SQL_GRACE_MS } from './relay-readiness.js' import type { EdgeRelayConfig } from './edge-relay.js' +import { loadIpCountryTable } from './ip-country.js' export const RELAY_MAX_CELL_CAPACITY_REQUESTS = 100_000 export const RELAY_DATABASE_POOL_MAX = 10 @@ -179,6 +180,9 @@ const EnvSchema = z.object({ (value) => (value === '' ? undefined : value), z.coerce.number().int().min(0).optional() ), + // Path of an IP → country table baked into the image (ip-country.ts); unset: every ask's + // country is unknown, so no country exclusion of director/edge.json removes anyone. + ORCA_RELAY_IP_COUNTRY_DB: z.preprocess((value) => (value === '' ? undefined : value), z.string().optional()), DATABASE_URL: z.string().optional(), ORCA_RELAY_DATA_DIR: z.string().default('./data/relay') }) @@ -498,6 +502,10 @@ function parseEdgeConfig( allowUsers: userIdList(parsed.ORCA_RELAY_EDGE_ALLOW_USERS), denyHosts: hostIdList(parsed.ORCA_RELAY_EDGE_DENY_HOSTS, 'ORCA_RELAY_EDGE_DENY_HOSTS'), regions: new Set(regions), + // Loaded at boot; an unreadable table fails the boot rather than serving every ask as unknown. + ...(parsed.ORCA_RELAY_IP_COUNTRY_DB === undefined + ? {} + : { ipCountry: loadIpCountryTable(parsed.ORCA_RELAY_IP_COUNTRY_DB) }), ...(parsed.ORCA_RELAY_EDGE_EXPORT_SKIP_AFTER_MS === undefined ? {} : { exportSkipAfterMs: parsed.ORCA_RELAY_EDGE_EXPORT_SKIP_AFTER_MS }) diff --git a/cloud/apps/relay/src/database.ts b/cloud/apps/relay/src/database.ts index 5349992092f..e3e18f0e711 100644 --- a/cloud/apps/relay/src/database.ts +++ b/cloud/apps/relay/src/database.ts @@ -274,6 +274,18 @@ CREATE TABLE IF NOT EXISTS relay_edge_fence_pending ( PRIMARY KEY (user_id, relay_host_id) ); +-- Region each relay edge host was last moved or kept there for (edge-relay.ts), read by the +-- evacuation sweep for hosts whose assignment row names the edge. Written only by edge moves, and +-- deleted when the host is placed off the edge. No CHECK on region: a new region must not need a +-- constraint swap before edge moves can record it (readers validate it). +CREATE TABLE IF NOT EXISTS relay_edge_host_regions ( + user_id TEXT NOT NULL, + relay_host_id TEXT NOT NULL, + region TEXT NOT NULL, + recorded_at BIGINT NOT NULL, + PRIMARY KEY (user_id, relay_host_id) +); + CREATE TABLE IF NOT EXISTS relay_region_decisions ( user_id TEXT NOT NULL, relay_host_id TEXT NOT NULL, generation BIGINT NOT NULL, expires_at BIGINT NOT NULL, diff --git a/cloud/apps/relay/src/edge-region-country-log.ts b/cloud/apps/relay/src/edge-region-country-log.ts new file mode 100644 index 00000000000..70801aefc29 --- /dev/null +++ b/cloud/apps/relay/src/edge-region-country-log.ts @@ -0,0 +1,47 @@ +// Observe-only: how many /v1/assign asks per minute each requested region gets from each country, +// so the share an exclusion would remove is known before it is set. Counts only: no ids, no +// addresses. One `orca_relay_edge_region_country` line per minute with any asks. +export const EDGE_REGION_COUNTRY_EVENT = 'orca_relay_edge_region_country' +export const EDGE_REGION_COUNTRY_WINDOW_MS = 60_000 +// An ask with no requested region, and one whose country is unknown. +const NO_REGION = 'none' +const UNKNOWN_COUNTRY = 'unknown' + +export class EdgeRegionCountryTally { + // region → country → asks; bounded by regions × countries. + private counts = new Map>() + private timer: ReturnType | undefined + + record(region: string | undefined, country: string | null): void { + const key = region ?? NO_REGION + let byCountry = this.counts.get(key) + if (!byCountry) { + byCountry = new Map() + this.counts.set(key, byCountry) + } + const code = country ?? UNKNOWN_COUNTRY + byCountry.set(code, (byCountry.get(code) ?? 0) + 1) + } + + flush(): void { + if (this.counts.size === 0) { + return + } + const counts: Record> = {} + for (const [region, byCountry] of this.counts) { + counts[region] = Object.fromEntries(byCountry) + } + this.counts = new Map() + console.warn(JSON.stringify({ event: EDGE_REGION_COUNTRY_EVENT, windowMs: EDGE_REGION_COUNTRY_WINDOW_MS, counts })) + } + + start(): void { + this.timer ??= setInterval(() => this.flush(), EDGE_REGION_COUNTRY_WINDOW_MS) + this.timer.unref?.() + } + + stop(): void { + clearInterval(this.timer) + this.timer = undefined + } +} diff --git a/cloud/apps/relay/src/edge-relay-app.test.ts b/cloud/apps/relay/src/edge-relay-app.test.ts index 14dd59bce70..ea793e409e1 100644 --- a/cloud/apps/relay/src/edge-relay-app.test.ts +++ b/cloud/apps/relay/src/edge-relay-app.test.ts @@ -3,6 +3,7 @@ import type { RelayConfig } from './config.js' import { openInMemoryRelayDatabase, type RelayDatabase } from './database.js' import type { EdgeControlFlags } from './edge-relay-control.js' import { EdgeAssignments, edgeCohortBucketPermille, type EdgeRelayConfig } from './edge-relay.js' +import { parseIpCountryTable, type IpCountryLookup } from './ip-country.js' const fakes = vi.hoisted(() => ({ verifyRelayToken: vi.fn(async (token: string) => ({ sub: 'user-1', relayHostId: token })) @@ -54,7 +55,9 @@ function config(): RelayConfig { } } -async function harness(options: { seeded?: boolean; control?: () => EdgeControlFlags } = {}) { +async function harness( + options: { seeded?: boolean; control?: () => EdgeControlFlags; ipCountry?: IpCountryLookup } = {} +) { const database = await openInMemoryRelayDatabase() databases.push(database) const edgeConfig: EdgeRelayConfig = { @@ -63,7 +66,8 @@ async function harness(options: { seeded?: boolean; control?: () => EdgeControlF allowHosts: new Set([COHORT_HOST]), denyHosts: new Set(), regions: new Set(['us-central1']), - ...(options.control ? { control: options.control } : {}) + ...(options.control ? { control: options.control } : {}), + ...(options.ipCountry ? { ipCountry: options.ipCountry } : {}) } const edge = new EdgeAssignments(database, edgeConfig) if (options.seeded !== false) await edge.ensureEdgeCell() @@ -91,10 +95,14 @@ async function harness(options: { seeded?: boolean; control?: () => EdgeControlF drain: vi.fn(), ready: vi.fn(async () => true) }) - const assign = async (relayHostId: string, extra: Record = {}) => + const assign = async (relayHostId: string, extra: Record = {}, forwardedFor?: string) => await app.request('/v1/assign', { method: 'POST', - headers: { authorization: `Bearer ${relayHostId}`, 'content-type': 'application/json' }, + headers: { + authorization: `Bearer ${relayHostId}`, + 'content-type': 'application/json', + ...(forwardedFor ? { 'x-forwarded-for': forwardedFor } : {}) + }, body: JSON.stringify({ v: 1, relayHostId, preferredRegion: 'us-central1', ...extra }) }) const resolve = async (relayHostId: string) => @@ -198,4 +206,31 @@ describe('director routes with the relay edge', () => { expect(leave).toHaveBeenCalledTimes(2) expect(read).toHaveBeenCalledTimes(2) }) + + it('keeps an excluded country off a region by the last forwarded hop, and tallies region × country', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const flags: EdgeControlFlags = { + mode: 'on', + regionRolloutPermille: { 'asia-east2': 1000 }, + regionExcludeCountries: { 'asia-east2': ['CN'] } + } + const ipCountry = parseIpCountryTable('192.0.2.0,192.0.2.127,CN\n192.0.2.128,192.0.2.255,HK\n') + const h = await harness({ control: () => flags, ipCountry }) + const asia = { preferredRegion: 'asia-east2' } + // A forged leading entry does not count: the last hop is the client. + const fromChina = await h.assign(OTHER_HOST, asia, '192.0.2.200, 192.0.2.1') + expect(await fromChina.json()).toMatchObject({ cellUrl: 'https://us-c1.relay.example.test' }) + const fromHongKong = await h.assign(OTHER_HOST, asia, '192.0.2.200') + expect(await fromHongKong.json()).toMatchObject({ cellUrl: EDGE_URL }) + // Unknown country: not excluded by default. + expect(await (await h.assign('unknowncountry01', asia)).json()).toMatchObject({ cellUrl: EDGE_URL }) + h.edge.regionCountries.flush() + const tallies = warn.mock.calls + .map(([line]) => JSON.parse(String(line)) as Record) + .filter((event) => event.event === 'orca_relay_edge_region_country') + expect(tallies).toEqual([ + { event: 'orca_relay_edge_region_country', windowMs: 60_000, counts: { 'asia-east2': { CN: 1, HK: 1, unknown: 1 } } } + ]) + warn.mockRestore() + }) }) diff --git a/cloud/apps/relay/src/edge-relay-control.ts b/cloud/apps/relay/src/edge-relay-control.ts index 19db20b8fa1..fea052e79af 100644 --- a/cloud/apps/relay/src/edge-relay-control.ts +++ b/cloud/apps/relay/src/edge-relay-control.ts @@ -3,6 +3,7 @@ // rollout step or a rollback needs no director deploy. Boot uses the defaults (mode on, the env // rollout percent); a failed read keeps the last applied flags. import { z } from 'zod' +import { RELAY_REGIONS, type RelayRegion } from '@orca-cloud/relay-contract/relay-regions' import { startControlFlagChannel, type ControlFlagParse @@ -25,25 +26,47 @@ export type EdgeControlFlags = { // director still skips a host another director has just moved; // - unset it before removing an allow list entry (the ceiling covers buckets, not the lists). leaveCeilingPermille?: number + // Per region rollout (permille), by the region the host asks for. A listed region is in scope + // even when ORCA_RELAY_EDGE_REGIONS omits it; 0 admits only allow-listed hosts and accounts. + // Unlisted regions keep the global rollout when in ORCA_RELAY_EDGE_REGIONS, else stay out. + regionRolloutPermille?: Partial> + // Countries (ISO 3166 alpha-2, from the director's offline IP lookup) whose hosts never join + // the cohort of that region; allow-listed hosts still do, allow-listed accounts do not. + regionExcludeCountries?: Partial> + // Per region: a host whose country is unknown (no database, a miss, an unparsable hop) is + // excluded too. Default false: an unknown country joins, so a gap in the database can let a + // host of an excluded country in; true keeps those out at the cost of every unknown host. + regionExcludeUnknownCountry?: Partial> } export const EDGE_CONTROL_DEFAULTS: EdgeControlFlags = { mode: 'on' } export const EDGE_CONTROL_OBJECT_NAME = 'director/edge.json' export const EDGE_CONTROL_APPLIED_EVENT = 'orca_relay_edge_control_applied' +const permille = z.number().int().min(0).max(1_000) +// An unknown region key voids the object, like any bad value. +const regionKey = z.enum(RELAY_REGIONS) const EdgeControlFlagsSchema = z.object({ mode: z.enum(['on', 'off', 'down']).default(EDGE_CONTROL_DEFAULTS.mode), - rolloutPermille: z.number().int().min(0).max(1_000).optional(), - leaveCeilingPermille: z.number().int().min(0).max(1_000).optional() + rolloutPermille: permille.optional(), + leaveCeilingPermille: permille.optional(), + regionRolloutPermille: z.partialRecord(regionKey, permille).optional(), + regionExcludeCountries: z + // Upper-cased first, so a lower-case code is not a typo that voids the whole file. + .partialRecord(regionKey, z.array(z.string().trim().toUpperCase().regex(/^[A-Z]{2}$/)).max(250)) + .optional(), + regionExcludeUnknownCountry: z.partialRecord(regionKey, z.boolean()).optional() }) const KNOWN_FLAG_KEYS = new Set(Object.keys(EdgeControlFlagsSchema.shape)) const EdgeControlObjectSchema = z.object({ v: z.literal(1), + // A ceiling below any rollout it must cover (global or regional) voids the object. flags: EdgeControlFlagsSchema.refine( (flags) => flags.leaveCeilingPermille === undefined || - flags.rolloutPermille === undefined || - flags.leaveCeilingPermille >= flags.rolloutPermille + [flags.rolloutPermille, ...Object.values(flags.regionRolloutPermille ?? {})].every( + (rollout) => rollout === undefined || flags.leaveCeilingPermille! >= rollout + ) ) }) @@ -59,12 +82,22 @@ export const parseEdgeControl: ControlFlagParse = (body) => { named !== null && typeof named === 'object' ? Object.keys(named).filter((key) => !KNOWN_FLAG_KEYS.has(key)).sort() : [] - const { mode, rolloutPermille, leaveCeilingPermille } = parsed.data.flags + const { + mode, + rolloutPermille, + leaveCeilingPermille, + regionRolloutPermille, + regionExcludeCountries, + regionExcludeUnknownCountry + } = parsed.data.flags return { flags: { mode, ...(rolloutPermille === undefined ? {} : { rolloutPermille }), - ...(leaveCeilingPermille === undefined ? {} : { leaveCeilingPermille }) + ...(leaveCeilingPermille === undefined ? {} : { leaveCeilingPermille }), + ...(regionRolloutPermille === undefined ? {} : { regionRolloutPermille }), + ...(regionExcludeCountries === undefined ? {} : { regionExcludeCountries }), + ...(regionExcludeUnknownCountry === undefined ? {} : { regionExcludeUnknownCountry }) }, ignoredKeys } @@ -108,3 +141,49 @@ export function startEdgeControl( export function edgeRolloutPermille(rolloutPercent: number, flags: EdgeControlFlags): number { return flags.rolloutPermille ?? rolloutPercent * 10 } + +// Any regional share set: the evacuation sweep judges each edge host by its recorded region +// (relay_edge_host_regions). None: it judges every host 'any' with today's query. +export function edgeRegionalRollout(flags: EdgeControlFlags): boolean { + return Object.keys(flags.regionRolloutPermille ?? {}).length > 0 +} + +// Effective rollout for hosts asking for `region`: its regional value, else the global rollout +// when the env scope lists it, else undefined (out of scope). +export function edgeRegionRolloutPermille( + scope: { rolloutPercent: number; regions: ReadonlySet }, + flags: EdgeControlFlags, + region: RelayRegion +): number | undefined { + const regional = flags.regionRolloutPermille?.[region] + if (regional !== undefined) { + return regional + } + return scope.regions.has(region) ? edgeRolloutPermille(scope.rolloutPercent, flags) : undefined +} + +// Rollout for a host whose region is not known (the evacuation sweep): the highest of every +// in-scope region's, so no host the assign path would keep is drained. No region in scope (and +// without regional values) is the global rollout, as before regional values existed. +export function edgeAnyRegionRolloutPermille( + scope: { rolloutPercent: number; regions: ReadonlySet }, + flags: EdgeControlFlags +): number { + const inScope = new Set([ + ...scope.regions, + ...(Object.keys(flags.regionRolloutPermille ?? {}) as RelayRegion[]) + ]) + if (inScope.size === 0) { + return edgeRolloutPermille(scope.rolloutPercent, flags) + } + return Math.max(...[...inScope].map((region) => edgeRegionRolloutPermille(scope, flags, region)!)) +} + +// Whether the country of an ask keeps the host out of `region`'s cohort. `null`: the ask's country +// is unknown. +export function edgeCountryExcluded(flags: EdgeControlFlags, region: RelayRegion, country: string | null): boolean { + if (country === null) { + return flags.regionExcludeUnknownCountry?.[region] === true + } + return flags.regionExcludeCountries?.[region]?.includes(country) === true +} diff --git a/cloud/apps/relay/src/edge-relay-evacuation.ts b/cloud/apps/relay/src/edge-relay-evacuation.ts index dd4f99dbae8..6ce6f7e2263 100644 --- a/cloud/apps/relay/src/edge-relay-evacuation.ts +++ b/cloud/apps/relay/src/edge-relay-evacuation.ts @@ -3,9 +3,11 @@ // rows whose host is no longer in the cohort and asks the edge to drain them; the desktop then // re-asks /v1/assign, and that ask exports its data and places it on a cell (app.ts). Each pass also // retries fences that did not land after a host left (edge-relay-fence.ts). +import { RelayRegionSchema, type RelayRegion } from '@orca-cloud/relay-contract/relay-regions' import type { RelayDatabase, SqlRow } from './database.js' import { EdgeAdminUnavailableError, type EdgeAdmin } from './edge-admin-client.js' import { inEdgeCohort, mayBeOnEdge, type EdgeRelayConfig } from './edge-relay.js' +import { EDGE_CONTROL_DEFAULTS, edgeRegionalRollout } from './edge-relay-control.js' import { forEachBounded, retryPendingFences } from './edge-relay-fence.js' type Identity = { userId: string; relayHostId: string } @@ -116,18 +118,23 @@ export class EdgeEvacuation { private async leavingHosts(): Promise { const leaving: Identity[] = [] this.pass ??= this.newPass() + const regional = edgeRegionalRollout(this.config.control?.() ?? EDGE_CONTROL_DEFAULTS) for (let pages = 0; pages < 2 && this.pass !== undefined; pages += 1) { const pass: Pass = this.pass - const rows = await this.readPage(pass) + const rows = await this.readPage(pass, regional) let filled = false for (const row of rows) { const identity = { userId: text(row, 'user_id'), relayHostId: text(row, 'relay_host_id') } pass.cursor = identity - // Region scope is the assign path's call alone: it decides with the region the desktop - // asks for, which the stored preference can miss or lag. Judging it here too drained - // hosts that the next ask put straight back (a drain every few minutes). A host that asks - // for a region outside the scope leaves on that ask. - if (inEdgeCohort(this.config, identity.relayHostId, 'any', identity.userId)) { continue } + // Region scope is the assign path's call: it decides with the region the desktop asks for. + // Without regional shares the sweep judges 'any' (the cell path's stored preference can + // lag: judging it drained hosts that the next ask put straight back). With them, a host + // is judged by the effective share of the region its last edge ask recorded + // (relay_edge_host_regions), so a regional abort or shrink drains just that region; a + // host with no record is judged 'any'. Country exclusion needs the ask's address, so an + // excluded host leaves on its next ask. + const region = regional ? recordedRegion(row) : 'any' + if (inEdgeCohort(this.config, identity.relayHostId, region, identity.userId)) { continue } if (!mayBeOnEdge(this.config, identity.relayHostId, identity.userId)) { // leaveCeilingPermille is set below a rollout this host was moved under: its asks skip // the leave read, so it would be re-placed without its devices. Raise the ceiling. @@ -153,12 +160,19 @@ export class EdgeEvacuation { return leaving } - // Keys after the cursor; once wrapped, only up to the pass's origin. - private async readPage(pass: Pass) { + // Keys after the cursor; once wrapped, only up to the pass's origin. `regional`: with the region + // the host's last edge ask recorded (primary key join; none: NULL). + private async readPage(pass: Pass, regional: boolean) { const { cursor, origin, wrapped } = pass return await this.database.query( - `SELECT a.user_id, a.relay_host_id - FROM relay_assignments a + `SELECT a.user_id, a.relay_host_id${regional ? ', r.region' : ''} + FROM relay_assignments a${ + regional + ? ` + LEFT JOIN relay_edge_host_regions r + ON r.user_id = a.user_id AND r.relay_host_id = a.relay_host_id` + : '' + } WHERE a.cell_id = ? AND (a.user_id > ? OR (a.user_id = ? AND a.relay_host_id > ?)) ${wrapped ? 'AND (a.user_id < ? OR (a.user_id = ? AND a.relay_host_id <= ?))' : ''} ORDER BY a.user_id, a.relay_host_id @@ -209,6 +223,11 @@ export class EdgeEvacuation { } } +function recordedRegion(row: SqlRow): RelayRegion | 'any' { + const recorded = RelayRegionSchema.safeParse(row.region) + return recorded.success ? recorded.data : 'any' +} + function drainKey(identity: Identity): string { return `${identity.userId}\n${identity.relayHostId}` } diff --git a/cloud/apps/relay/src/edge-relay-postgres.test.ts b/cloud/apps/relay/src/edge-relay-postgres.test.ts index ec4aa9c6b43..925ca8c42cb 100644 --- a/cloud/apps/relay/src/edge-relay-postgres.test.ts +++ b/cloud/apps/relay/src/edge-relay-postgres.test.ts @@ -9,7 +9,8 @@ import { EdgeMoveBusyError, EdgeMoveDeferredError } from './edge-relay.js' -import type { EdgeAssignBody, EdgeDeviceRow } from './edge-admin-client.js' +import { EdgeAdminUnavailableError, type EdgeAssignBody, type EdgeDeviceRow } from './edge-admin-client.js' +import type { EdgeControlFlags } from './edge-relay-control.js' import { EDGE_FENCE_RETRY_BASE_MS, retryPendingFences } from './edge-relay-fence.js' import { EdgeEvacuation } from './edge-relay-evacuation.js' @@ -38,6 +39,7 @@ describePostgres('relay edge on PostgreSQL', () => { await database.query(`DELETE FROM relay_assignments WHERE user_id = ?`, ['edge-pg-user']) await database.query(`DELETE FROM relay_devices WHERE user_id = ?`, ['edge-pg-user']) await database.query(`DELETE FROM relay_edge_fence_pending WHERE user_id = ?`, ['edge-pg-user']) + await database.query(`DELETE FROM relay_edge_host_regions WHERE user_id = ?`, ['edge-pg-user']) // Leave the shared selector as other files expect it: without this file's cells. await database.transaction(async (transaction) => { const selector = ( @@ -271,4 +273,69 @@ describePostgres('relay edge on PostgreSQL', () => { expect(await edge.leaveEdge(downHosts[0]!)).toBe(true) expect(await database.query(`SELECT 1 FROM relay_devices WHERE relay_host_id = ?`, [downHosts[0]!.relayHostId])).toEqual([]) }) + + it('records the region of an edge move in its transaction, and the sweep drains an aborted region by it', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const flags: EdgeControlFlags = { mode: 'on', regionRolloutPermille: { 'asia-east2': 1000 } } + const config = { ...edgeConfig, control: () => flags } + const drained: string[] = [] + let pushes = 0 + const admin = { + assign: async (body: EdgeAssignBody) => { + pushes += 1 + // The third push fails: that move, and its region record, roll back. + if (pushes === 3) { + throw new EdgeAdminUnavailableError('status_503') + } + return { outcome: 'applied' as const, assignmentEpoch: body.assignmentEpoch } + }, + exportHost: async (): Promise => { + throw new Error('unexpected export') + }, + drain: async (relayHostId: string) => { + drained.push(relayHostId) + return { outcome: 'idle' as const } + } + } + let now = Date.now() + const edge = new EdgeAssignments(database, config, () => now, admin) + await edge.ensureEdgeCell() + const [asia, us, failed] = ['edgepgregion0001', 'edgepgregion0002', 'edgepgregion0003'].map((relayHostId) => ({ + userId: 'edge-pg-user', + relayHostId + })) + await edge.moveToEdge(asia!, 0, 'asia-east2') + await edge.moveToEdge(us!, 0, 'us-central1') + await expect(edge.moveToEdge(failed!, 0, 'asia-east2')).rejects.toBeInstanceOf(EdgeMoveDeferredError) + const recordedAt = async (host: { relayHostId: string }) => + Number( + ( + await database.query(`SELECT recorded_at FROM relay_edge_host_regions WHERE user_id = ? AND relay_host_id = ?`, [ + 'edge-pg-user', + host.relayHostId + ]) + )[0]?.recorded_at + ) + // A kept host with the same region writes nothing; a changed region is rewritten. + const first = await recordedAt(us!) + now += 5_000 + await edge.moveToEdge(us!, 0, 'us-central1') + expect(await recordedAt(us!)).toBe(first) + await edge.moveToEdge(us!, 0, 'asia-east2') + expect(await recordedAt(us!)).toBe(now) + await edge.moveToEdge(us!, 0, 'us-central1') + const recorded = await database.query( + `SELECT relay_host_id, region FROM relay_edge_host_regions + WHERE user_id = ? AND relay_host_id LIKE 'edgepgregion%' ORDER BY relay_host_id`, + ['edge-pg-user'] + ) + expect(recorded).toEqual([ + { relay_host_id: asia!.relayHostId, region: 'asia-east2' }, + { relay_host_id: us!.relayHostId, region: 'us-central1' } + ]) + // Abort Asia: only its recorded host drains; us-central1 keeps the global share (100%). + flags.regionRolloutPermille = { 'asia-east2': 0 } + await new EdgeEvacuation(database, config, admin, EDGE_CELL_ID, Date.now, () => 0).sweep() + expect(drained.filter((id) => id.startsWith('edgepgregion'))).toEqual([asia!.relayHostId]) + }) }) diff --git a/cloud/apps/relay/src/edge-relay-region.test.ts b/cloud/apps/relay/src/edge-relay-region.test.ts new file mode 100644 index 00000000000..0b89dc4ef83 --- /dev/null +++ b/cloud/apps/relay/src/edge-relay-region.test.ts @@ -0,0 +1,514 @@ +import { RELAY_DEFAULT_REGION, RELAY_REGIONS, type RelayRegion } from '@orca-cloud/relay-contract/relay-regions' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { openInMemoryRelayDatabase, type RelayDatabase } from './database.js' +import { + edgeAnyRegionRolloutPermille, + edgeRolloutPermille, + parseEdgeControl, + type EdgeControlFlags +} from './edge-relay-control.js' +import { + EDGE_CELL_ID, + EdgeAssignments, + EdgeMoveDeferredError, + edgeCohortBucketPermille, + inEdgeCohort, + mayBeOnEdge, + type EdgeRelayConfig +} from './edge-relay.js' +import { EdgeEvacuation } from './edge-relay-evacuation.js' +import { EDGE_REGION_COUNTRY_EVENT, EdgeRegionCountryTally } from './edge-region-country-log.js' +import { + EdgeAdminUnavailableError, + type EdgeAdmin, + type EdgeAssignBody, + type EdgeDrainResult +} from './edge-admin-client.js' + +function config(flags: EdgeControlFlags, overrides: Partial = {}): EdgeRelayConfig { + return { + cellUrl: 'https://edge.relay.example.test', + rolloutPercent: 0, + allowHosts: new Set(), + denyHosts: new Set(), + regions: new Set(['us-central1']), + control: () => flags, + ...overrides + } +} + +const hosts = Array.from({ length: 600 }, (_, index) => `regionhost${String(index).padStart(6, '0')}`) +const hostUnder = (permille: number) => hosts.find((host) => edgeCohortBucketPermille(host) < permille)! +const hostAtOrAbove = (permille: number) => hosts.find((host) => edgeCohortBucketPermille(host) >= permille)! + +// inEdgeCohort as it was before regional values and country exclusion. +function previousInEdgeCohort( + config: EdgeRelayConfig, + relayHostId: string, + region: RelayRegion | undefined | 'any', + userId?: string +): boolean { + const flags = config.control!() + if (flags.mode !== 'on') { + return false + } + if (config.denyHosts.has(relayHostId)) { + return false + } + if (config.allowHosts.has(relayHostId)) { + return true + } + if (region !== 'any' && !config.regions.has(region ?? RELAY_DEFAULT_REGION)) { + return false + } + if (userId !== undefined && config.allowUsers?.has(userId)) { + return true + } + return edgeCohortBucketPermille(relayHostId) < edgeRolloutPermille(config.rolloutPercent, flags) +} + +function previousMayBeOnEdge(config: EdgeRelayConfig, relayHostId: string, userId?: string): boolean { + const flags = config.control!() + if (flags.leaveCeilingPermille === undefined) { + return true + } + if (config.allowHosts.has(relayHostId) || config.denyHosts.has(relayHostId)) { + return true + } + if (userId !== undefined && config.allowUsers?.has(userId)) { + return true + } + const ceiling = Math.max(flags.leaveCeilingPermille, edgeRolloutPermille(config.rolloutPercent, flags), config.rolloutPercent * 10) + return edgeCohortBucketPermille(relayHostId) < ceiling +} + +describe('edge cohort without regional flags', () => { + it('decides exactly as before for every host, region, account, country and scope', () => { + const flagSets: EdgeControlFlags[] = [ + { mode: 'on' }, + { mode: 'on', rolloutPermille: 0 }, + { mode: 'on', rolloutPermille: 37 }, + { mode: 'on', rolloutPermille: 500, leaveCeilingPermille: 700 }, + { mode: 'off', rolloutPermille: 1000 }, + { mode: 'down' } + ] + const scopes: ReadonlySet[] = [new Set(), new Set(['us-central1']), new Set(RELAY_REGIONS)] + let compared = 0 + for (const flags of flagSets) { + for (const regions of scopes) { + for (const rolloutPercent of [0, 5, 100]) { + const edge = config(flags, { + regions, + rolloutPercent, + allowHosts: new Set([hosts[1]!]), + denyHosts: new Set([hosts[2]!]), + allowUsers: new Set(['user-team']) + }) + for (const host of hosts.slice(0, 120)) { + for (const region of [...RELAY_REGIONS, undefined, 'any'] as const) { + for (const userId of [undefined, 'user-team', 'user-other']) { + const before = previousInEdgeCohort(edge, host, region, userId) + // No exclusion flag: the ask's country (known, unknown or not judged) changes nothing. + for (const country of [undefined, null, 'CN', 'US']) { + expect(inEdgeCohort(edge, host, region, userId, country)).toBe(before) + compared += 1 + } + } + expect(mayBeOnEdge(edge, host)).toBe(previousMayBeOnEdge(edge, host)) + expect(mayBeOnEdge(edge, host, 'user-team')).toBe(previousMayBeOnEdge(edge, host, 'user-team')) + } + } + } + } + } + expect(compared).toBeGreaterThan(100_000) + }) +}) + +describe('edge regionRolloutPermille', () => { + it('brings a listed region into scope at its own share; others keep the global share or stay out', () => { + const flags: EdgeControlFlags = { mode: 'on', rolloutPermille: 1000, regionRolloutPermille: { 'asia-east2': 10 } } + const edge = config(flags) + expect(inEdgeCohort(edge, hostUnder(10), 'asia-east2')).toBe(true) + expect(inEdgeCohort(edge, hostAtOrAbove(10), 'asia-east2')).toBe(false) + // us-central1 is in the env scope: the global share. + expect(inEdgeCohort(edge, hostAtOrAbove(10), 'us-central1')).toBe(true) + expect(inEdgeCohort(edge, hostAtOrAbove(10), undefined)).toBe(true) + // A region neither listed nor in the env scope stays out. + expect(inEdgeCohort(config({ mode: 'on', rolloutPermille: 1000 }, { regions: new Set() }), hostUnder(10), 'asia-east2')).toBe(false) + // A regional value also replaces the global share for an env-scoped region. + const lowered = config({ mode: 'on', rolloutPermille: 1000, regionRolloutPermille: { 'us-central1': 0 } }) + expect(inEdgeCohort(lowered, hostUnder(10), 'us-central1')).toBe(false) + }) + + it('at 0 admits only allow-listed hosts and accounts', () => { + const flags: EdgeControlFlags = { mode: 'on', regionRolloutPermille: { 'asia-east2': 0 } } + const edge = config(flags, { allowHosts: new Set([hosts[1]!]), allowUsers: new Set(['user-team']) }) + expect(inEdgeCohort(edge, hostUnder(1), 'asia-east2')).toBe(false) + expect(inEdgeCohort(edge, hosts[1]!, 'asia-east2')).toBe(true) + expect(inEdgeCohort(edge, hostAtOrAbove(999), 'asia-east2', 'user-team')).toBe(true) + expect(inEdgeCohort(edge, hostAtOrAbove(999), 'asia-east2', 'user-other')).toBe(false) + }) + + it("judges region 'any' by the highest in-scope share", () => { + const flags: EdgeControlFlags = { mode: 'on', rolloutPermille: 10, regionRolloutPermille: { 'asia-east2': 500 } } + expect(edgeAnyRegionRolloutPermille(config(flags), flags)).toBe(500) + expect(inEdgeCohort(config(flags), hostUnder(500), 'any')).toBe(true) + expect(inEdgeCohort(config(flags), hostAtOrAbove(500), 'any')).toBe(false) + // The env-scoped region's global share wins when higher. + const higher: EdgeControlFlags = { mode: 'on', rolloutPermille: 800, regionRolloutPermille: { 'asia-east2': 0 } } + expect(edgeAnyRegionRolloutPermille(config(higher), higher)).toBe(800) + // Out of the env scope, the global share does not count. + expect(edgeAnyRegionRolloutPermille(config(higher, { regions: new Set() }), higher)).toBe(0) + // Nothing in scope at all: the global share, as before. + expect(edgeAnyRegionRolloutPermille(config({ mode: 'on', rolloutPermille: 30 }, { regions: new Set() }), { mode: 'on', rolloutPermille: 30 })).toBe(30) + }) + + it('raises the leave ceiling to every regional share', () => { + const flags: EdgeControlFlags = { + mode: 'on', + rolloutPermille: 0, + leaveCeilingPermille: 10, + regionRolloutPermille: { 'asia-east2': 300 } + } + // A file like this is void (see the refine below); were it applied, regional hosts still read. + expect(mayBeOnEdge(config(flags), hostUnder(300))).toBe(true) + expect(mayBeOnEdge(config(flags), hostAtOrAbove(300))).toBe(false) + }) +}) + +describe('edge regionExcludeCountries', () => { + const flags: EdgeControlFlags = { + mode: 'on', + rolloutPermille: 1000, + regionRolloutPermille: { 'asia-east2': 1000 }, + regionExcludeCountries: { 'asia-east2': ['CN'] } + } + + it('keeps hosts of an excluded country out of that region only', () => { + const edge = config(flags) + const host = hostUnder(1000) + expect(inEdgeCohort(edge, host, 'asia-east2', undefined, 'CN')).toBe(false) + expect(inEdgeCohort(edge, host, 'asia-east2', undefined, 'HK')).toBe(true) + // Other regions are untouched, so today's cohort is unchanged. + expect(inEdgeCohort(edge, host, 'us-central1', undefined, 'CN')).toBe(true) + expect(inEdgeCohort(edge, host, undefined, undefined, 'CN')).toBe(true) + }) + + it('runs after deny and host allow, and before account allow and the share', () => { + const host = hostUnder(1000) + expect(inEdgeCohort(config(flags, { allowHosts: new Set([host]) }), host, 'asia-east2', undefined, 'CN')).toBe(true) + expect( + inEdgeCohort(config(flags, { allowHosts: new Set([host]), denyHosts: new Set([host]) }), host, 'asia-east2', undefined, 'HK') + ).toBe(false) + expect(inEdgeCohort(config(flags, { allowUsers: new Set(['user-team']) }), host, 'asia-east2', 'user-team', 'CN')).toBe(false) + expect(inEdgeCohort(config(flags, { allowUsers: new Set(['user-team']) }), host, 'asia-east2', 'user-team', 'HK')).toBe(true) + // Out of scope is out before the country is looked at. + expect(inEdgeCohort(config({ mode: 'on', rolloutPermille: 1000 }, { regions: new Set() }), host, 'asia-east2', undefined, 'HK')).toBe(false) + }) + + it('lets an unknown country in unless the region excludes unknown countries', () => { + const host = hostUnder(1000) + expect(inEdgeCohort(config(flags), host, 'asia-east2', undefined, null)).toBe(true) + const strict = config({ ...flags, regionExcludeUnknownCountry: { 'asia-east2': true } }) + expect(inEdgeCohort(strict, host, 'asia-east2', undefined, null)).toBe(false) + expect(inEdgeCohort(strict, host, 'asia-east2', undefined, 'HK')).toBe(true) + expect(inEdgeCohort(strict, host, 'us-central1', undefined, null)).toBe(true) + }) + + it('is not judged without an ask (the sweep passes no country)', () => { + const strict = config({ ...flags, regionExcludeUnknownCountry: { 'asia-east2': true } }) + expect(inEdgeCohort(strict, hostUnder(1000), 'asia-east2')).toBe(true) + }) +}) + +describe('edge control regional flags', () => { + it('parses them, and keeps the object whole', () => { + const flags = { + mode: 'on', + rolloutPermille: 10, + leaveCeilingPermille: 100, + regionRolloutPermille: { 'asia-east2': 100, 'us-central1': 10 }, + regionExcludeCountries: { 'asia-east2': ['CN'] }, + regionExcludeUnknownCountry: { 'asia-east2': false } + } + expect(parseEdgeControl({ v: 1, flags })).toEqual({ flags, ignoredKeys: [] }) + }) + + it('upper-cases country codes rather than voiding the file', () => { + expect(parseEdgeControl({ v: 1, flags: { mode: 'on', regionExcludeCountries: { 'asia-east2': ['cn', ' Hk '] } } })).toEqual({ + flags: { mode: 'on', regionExcludeCountries: { 'asia-east2': ['CN', 'HK'] } }, + ignoredKeys: [] + }) + }) + + it('voids a file whose leave ceiling is below any regional share', () => { + expect( + parseEdgeControl({ v: 1, flags: { mode: 'on', leaveCeilingPermille: 50, regionRolloutPermille: { 'asia-east2': 51 } } }) + ).toBeNull() + expect( + parseEdgeControl({ v: 1, flags: { mode: 'on', leaveCeilingPermille: 51, regionRolloutPermille: { 'asia-east2': 51 } } }) + ).not.toBeNull() + // No ceiling: no constraint. + expect(parseEdgeControl({ v: 1, flags: { mode: 'on', regionRolloutPermille: { 'asia-east2': 1000 } } })).not.toBeNull() + }) + + it('voids a malformed regional value as a whole', () => { + for (const bad of [ + { regionRolloutPermille: { 'europe-west1': 10 } }, + { regionRolloutPermille: { 'asia-east2': 1001 } }, + { regionRolloutPermille: { 'asia-east2': 1.5 } }, + { regionRolloutPermille: ['asia-east2'] }, + { regionExcludeCountries: { 'asia-east2': ['C'] } }, + { regionExcludeCountries: { 'asia-east2': ['CHN'] } }, + { regionExcludeCountries: { 'asia-east2': 'CN' } }, + { regionExcludeCountries: { 'mars-north1': ['CN'] } }, + { regionExcludeUnknownCountry: { 'asia-east2': 'yes' } } + ]) { + expect(parseEdgeControl({ v: 1, flags: { mode: 'on', ...bad } })).toBeNull() + } + }) +}) + +describe('edge move records the region', () => { + const databases: RelayDatabase[] = [] + afterEach(async () => { + vi.restoreAllMocks() + for (const database of databases.splice(0)) { + await database.close() + } + }) + const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } + + async function recorded(database: RelayDatabase) { + return ( + await database.query( + `SELECT region, recorded_at FROM relay_edge_host_regions WHERE user_id = ? AND relay_host_id = ?`, + [identity.userId, identity.relayHostId] + ) + ).map((row) => ({ region: row.region, at: Number(row.recorded_at) })) + } + + async function setup(admin?: EdgeAdmin) { + const database = await openInMemoryRelayDatabase() + databases.push(database) + const clock = { now: 1_000 } + // Dark: no regional flag at all. The record does not depend on flags. + const edge = new EdgeAssignments(database, config({ mode: 'on' }), () => clock.now, admin) + await edge.ensureEdgeCell() + return { database, clock, edge } + } + + it('on a first move, and on every move off a cell; no region asked is the default region', async () => { + const { database, clock, edge } = await setup() + await edge.moveToEdge(identity, 0, 'asia-east2') + expect(await recorded(database)).toEqual([{ region: 'asia-east2', at: 1_000 }]) + // Off to a cell row, then moved back on with the same region: rewritten. + await database.query(`UPDATE relay_assignments SET cell_id = 'us-c1' WHERE user_id = ?`, [identity.userId]) + clock.now = 2_000 + await edge.moveToEdge(identity, 0, 'asia-east2') + expect(await recorded(database)).toEqual([{ region: 'asia-east2', at: 2_000 }]) + await database.query(`UPDATE relay_assignments SET cell_id = 'us-c1' WHERE user_id = ?`, [identity.userId]) + clock.now = 3_000 + await edge.moveToEdge(identity, 0) + expect(await recorded(database)).toEqual([{ region: RELAY_DEFAULT_REGION, at: 3_000 }]) + }) + + it('on a kept host only when its region changed or was never recorded', async () => { + const { database, clock, edge } = await setup() + await edge.moveToEdge(identity, 0, 'asia-east2') + clock.now = 2_000 + await edge.moveToEdge(identity, 0, 'asia-east2') + expect(await recorded(database)).toEqual([{ region: 'asia-east2', at: 1_000 }]) + clock.now = 3_000 + await edge.moveToEdge(identity, 0, 'us-central1') + expect(await recorded(database)).toEqual([{ region: 'us-central1', at: 3_000 }]) + // A host moved before records existed is recorded on its next kept ask. + await database.query(`DELETE FROM relay_edge_host_regions`) + clock.now = 4_000 + await edge.moveToEdge(identity, 0, 'us-central1') + expect(await recorded(database)).toEqual([{ region: 'us-central1', at: 4_000 }]) + }) + + it('never writes the cell path region preferences', async () => { + const { database, edge } = await setup() + await edge.moveToEdge(identity, 0, 'asia-east2') + expect(await database.query(`SELECT 1 FROM relay_assignment_region_preferences`)).toEqual([]) + }) + + it('records nothing for a move that does not commit', async () => { + const admin = { + assign: vi.fn(async () => { + throw new EdgeAdminUnavailableError('status_503') + }) + } as unknown as EdgeAdmin + const { database, edge } = await setup(admin) + await expect(edge.moveToEdge(identity, 0, 'asia-east2')).rejects.toBeInstanceOf(EdgeMoveDeferredError) + expect(await recorded(database)).toEqual([]) + }) + + it('forgets the record once the host is placed off the edge', async () => { + const admin = { + // Moves and fences are both assign calls. + assign: async (body: EdgeAssignBody) => ({ outcome: 'applied' as const, assignmentEpoch: body.assignmentEpoch }) + } as unknown as EdgeAdmin + const { database, edge } = await setup(admin) + await edge.moveToEdge(identity, 0, 'asia-east2') + vi.spyOn(console, 'warn').mockImplementation(() => {}) + await edge.fenceAway(identity, 'us-c1', 9) + expect(await recorded(database)).toEqual([]) + }) +}) + +describe('edge evacuation by recorded region', () => { + const databases: RelayDatabase[] = [] + afterEach(async () => { + vi.restoreAllMocks() + for (const database of databases.splice(0)) { + await database.close() + } + }) + + async function harness(flags: EdgeControlFlags) { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const database = await openInMemoryRelayDatabase() + databases.push(database) + const drained: string[] = [] + const admin = { + drain: async (relayHostId: string): Promise => { + drained.push(relayHostId) + return { outcome: 'idle' } + } + } as unknown as EdgeAdmin + const evacuation = new EdgeEvacuation(database, config(flags), admin, EDGE_CELL_ID, () => 1_000, () => 0) + const onEdge = async (relayHostId: string, region?: RelayRegion) => { + await database.query( + `INSERT INTO relay_assignments + (user_id, relay_host_id, cell_id, assignment_epoch, lease_expires_at, last_activity_at, + reserved_controls, reserved_splices, reserved_invites, pending_installs, + pending_confirmations, migration_leases) + VALUES ('user-1', ?, ?, 1, 0, 0, 0, 0, 0, 0, 0, 0)`, + [relayHostId, EDGE_CELL_ID] + ) + if (region) { + await database.query( + `INSERT INTO relay_edge_host_regions (user_id, relay_host_id, region, recorded_at) VALUES ('user-1', ?, ?, 0)`, + [relayHostId, region] + ) + } + } + // What the cell path stores: never read by the sweep. + const prefer = async (relayHostId: string, region: RelayRegion) => + await database.query( + `INSERT INTO relay_assignment_region_preferences (user_id, relay_host_id, preferred_region, observed_at) + VALUES ('user-1', ?, ?, 0)`, + [relayHostId, region] + ) + return { database, evacuation, drained, onEdge, prefer } + } + + it('drains an aborted region by its recorded hosts, and keeps the rest', async () => { + // Asia aborted (0), us-central1 at the global 1000: unrecorded hosts are judged at the max. + const h = await harness({ mode: 'on', rolloutPermille: 1000, regionRolloutPermille: { 'asia-east2': 0 } }) + const [asia, us, unrecorded] = hosts.slice(10, 13) + await h.onEdge(asia!, 'asia-east2') + await h.onEdge(us!, 'us-central1') + await h.onEdge(unrecorded!) + await h.evacuation.sweep() + expect(h.drained).toEqual([asia]) + }) + + it('judges a recorded region by its effective share: global when env-scoped', async () => { + // A us-central1 shrink (global 0) while Asia is at 1000: recorded us-central1 hosts drain; + // an unrecorded host is judged 'any' (Asia's 1000) and stays until its next ask records it. + const h = await harness({ mode: 'on', rolloutPermille: 0, regionRolloutPermille: { 'asia-east2': 1000 } }) + await h.onEdge(hosts[20]!, 'us-central1') + await h.onEdge(hosts[21]!) + await h.onEdge(hosts[22]!, 'asia-east2') + await h.evacuation.sweep() + expect(h.drained).toEqual([hosts[20]]) + }) + + it('drains a recorded region that is out of scope', async () => { + // asia-east2 recorded, but only us-central1 has a key and the env scope is us-central1. + const h = await harness({ mode: 'on', rolloutPermille: 1000, regionRolloutPermille: { 'us-central1': 1000 } }) + await h.onEdge(hosts[40]!, 'asia-east2') + await h.onEdge(hosts[41]!, 'us-central1') + await h.evacuation.sweep() + expect(h.drained).toEqual([hosts[40]]) + }) + + it('ignores a stale cell path preference: only the edge record counts', async () => { + const h = await harness({ mode: 'on', rolloutPermille: 1000, regionRolloutPermille: { 'asia-east2': 0 } }) + // Asked Asia on a cell weeks ago; on the edge now for us-central1. + await h.onEdge(hosts[50]!, 'us-central1') + await h.prefer(hosts[50]!, 'asia-east2') + await h.onEdge(hosts[51]!) + await h.prefer(hosts[51]!, 'asia-east2') + await h.evacuation.sweep() + expect(h.drained).toEqual([]) + }) + + it('without regional flags ignores records and sends the same SQL as before', async () => { + for (const flags of [{ mode: 'on', rolloutPermille: 1000 }, { mode: 'on', rolloutPermille: 1000, regionRolloutPermille: {} }] as EdgeControlFlags[]) { + const h = await harness(flags) + await h.onEdge(hosts[30]!, 'asia-east2') + const query = vi.spyOn(h.database, 'query') + await h.evacuation.sweep() + expect(h.drained).toEqual([]) + const page = query.mock.calls.map(([sql]) => sql).find((sql) => sql.includes('FROM relay_assignments a')) + expect(page).toBe(`SELECT a.user_id, a.relay_host_id + FROM relay_assignments a + WHERE a.cell_id = ? AND (a.user_id > ? OR (a.user_id = ? AND a.relay_host_id > ?)) + + ORDER BY a.user_id, a.relay_host_id + LIMIT ?`) + } + }) +}) + +describe('edge region × country log', () => { + afterEach(() => { + vi.restoreAllMocks() + }) + + it('counts asks per requested region and country and logs nothing else', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const tally = new EdgeRegionCountryTally() + tally.flush() + expect(warn).not.toHaveBeenCalled() + tally.record('asia-east2', 'CN') + tally.record('asia-east2', 'CN') + tally.record('asia-east2', 'HK') + tally.record('asia-east2', null) + tally.record(undefined, 'US') + tally.flush() + expect(warn.mock.calls.map(([line]) => JSON.parse(String(line)))).toEqual([ + { + event: EDGE_REGION_COUNTRY_EVENT, + windowMs: 60_000, + counts: { 'asia-east2': { CN: 2, HK: 1, unknown: 1 }, none: { US: 1 } } + } + ]) + tally.flush() + expect(warn).toHaveBeenCalledTimes(1) + }) + + it('flushes once a minute after start', () => { + vi.useFakeTimers() + try { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const tally = new EdgeRegionCountryTally() + tally.start() + tally.record('asia-east2', 'HK') + vi.advanceTimersByTime(60_000) + expect(warn).toHaveBeenCalledTimes(1) + tally.stop() + tally.record('asia-east2', 'HK') + vi.advanceTimersByTime(120_000) + expect(warn).toHaveBeenCalledTimes(1) + } finally { + vi.useRealTimers() + } + }) +}) diff --git a/cloud/apps/relay/src/edge-relay.ts b/cloud/apps/relay/src/edge-relay.ts index c05d7af3c27..8e97bc9d355 100644 --- a/cloud/apps/relay/src/edge-relay.ts +++ b/cloud/apps/relay/src/edge-relay.ts @@ -15,7 +15,16 @@ import { type EdgeAssignResult, type EdgeDeviceRow } from './edge-admin-client.js' -import { EDGE_CONTROL_DEFAULTS, edgeRolloutPermille, type EdgeControlFlags } from './edge-relay-control.js' +import { + EDGE_CONTROL_DEFAULTS, + edgeAnyRegionRolloutPermille, + edgeCountryExcluded, + edgeRegionRolloutPermille, + edgeRolloutPermille, + type EdgeControlFlags +} from './edge-relay-control.js' +import { EdgeRegionCountryTally } from './edge-region-country-log.js' +import type { IpCountryLookup } from './ip-country.js' // Hosts the director has moved to the relay edge carry this cell id on their assignment row. The // relay_cells row exists only so cells resolve the row (a phone of a moved host gets WRONG_CELL, @@ -38,6 +47,8 @@ export type EdgeRelayConfig = { denyHosts: ReadonlySet // Regions whose hosts may join the cohort, by the region the host asked for. regions: ReadonlySet + // Offline IP → country (ORCA_RELAY_IP_COUNTRY_DB); absent: every ask's country is unknown. + ipCountry?: IpCountryLookup // How long the edge's export must keep failing (unavailable) before a leaving host is placed // without it; default EDGE_EXPORT_SKIP_AFTER_MS, 0 skips on the first failure. exportSkipAfterMs?: number @@ -65,21 +76,38 @@ export function edgeCohortBucketPermille(relayHostId: string): number { return (hash % 100) * 10 + (Math.floor(hash / 100) % 10) } -// Mode off or down empties the cohort. Otherwise deny wins, then host allow, then region scope; -// within the region, account allow or the rollout share. +// Mode off or down empties the cohort. Otherwise deny wins, then host allow, then region scope +// and the region's country exclusion; within the region, account allow or the region's rollout. +// `country`: the ask's (null when unknown); undefined when the caller has no ask (the evacuation +// sweep), which skips the exclusion. Region 'any' (the sweep, for a host with no recorded region) +// has no scope or exclusion and uses the highest in-scope rollout. export function inEdgeCohort( config: EdgeRelayConfig, relayHostId: string, region: RelayRegion | undefined | 'any', - userId?: string + userId?: string, + country?: string | null ): boolean { const flags = config.control?.() ?? EDGE_CONTROL_DEFAULTS if (flags.mode !== 'on') return false if (config.denyHosts.has(relayHostId)) return false if (config.allowHosts.has(relayHostId)) return true - if (region !== 'any' && !config.regions.has(region ?? RELAY_DEFAULT_REGION)) return false + let rollout: number + if (region === 'any') { + rollout = edgeAnyRegionRolloutPermille(config, flags) + } else { + const asked = region ?? RELAY_DEFAULT_REGION + const regional = edgeRegionRolloutPermille(config, flags, asked) + if (regional === undefined) { + return false + } + if (country !== undefined && edgeCountryExcluded(flags, asked, country)) { + return false + } + rollout = regional + } if (userId !== undefined && config.allowUsers?.has(userId)) return true - return edgeCohortBucketPermille(relayHostId) < edgeRolloutPermille(config.rolloutPercent, flags) + return edgeCohortBucketPermille(relayHostId) < rollout } // Whether the host's assignment row may be on the edge, so an ask that is not moving it there must @@ -95,6 +123,7 @@ export function mayBeOnEdge(config: EdgeRelayConfig, relayHostId: string, userId const ceiling = Math.max( flags.leaveCeilingPermille, edgeRolloutPermille(config.rolloutPercent, flags), + ...Object.values(flags.regionRolloutPermille ?? {}), config.rolloutPercent * 10 ) return edgeCohortBucketPermille(relayHostId) < ceiling @@ -188,6 +217,8 @@ export class EdgeAssignments { private exportLastFailureAt: number | undefined // Edge admin calls in flight under an assignment row lock (pushes), capped at EDGE_LOCKED_CALLS_MAX. private lockedCalls = 0 + // Asks by requested region × country (observe only; relay-server starts it with an IP table). + readonly regionCountries = new EdgeRegionCountryTally() // With `admin` (the edge keeps host data in its objects) every move onto the edge pushes the // host's devices before the answer, and every move off exports them back first. @@ -259,9 +290,23 @@ export class EdgeAssignments { // The host's own ask: moves its row to the edge, minting a strictly newer epoch only when the cell // changes (phones accept a move only with a newer epoch; re-asks must not flap the epoch). + // Every committed answer also records the region the cohort was judged for (relay_edge_host_ + // regions), so the evacuation sweep can drain one region's hosts: always on a move, and on a kept + // host only when the region changed (or was never recorded). Written last, under the assignment + // row lock, so its row lock is held only to the commit. async moveToEdge(identity: Identity, mapFloor: number, region?: RelayRegion): Promise { const now = this.now() const leaseExpiresAt = now + ASSIGNMENT_LIMITS.activityLeaseMs + const recordRegion = async (transaction: RelayDatabase, onlyIfChanged = false) => { + await transaction.query( + `INSERT INTO relay_edge_host_regions (user_id, relay_host_id, region, recorded_at) + VALUES (?, ?, ?, ?) + ON CONFLICT (user_id, relay_host_id) DO UPDATE + SET region = excluded.region, recorded_at = excluded.recorded_at + ${onlyIfChanged ? 'WHERE relay_edge_host_regions.region IS DISTINCT FROM excluded.region' : ''}`, + [identity.userId, identity.relayHostId, region ?? RELAY_DEFAULT_REGION, now] + ) + } return await this.database.transaction(async (transaction) => { let rows: SqlRow[] try { @@ -291,6 +336,7 @@ export class EdgeAssignments { ) if (inserted.length === 1) { const pushed = await this.pushOnto(transaction, identity, epoch, region) + await recordRegion(transaction) return this.answer(identity, pushed, leaseExpiresAt) } const winner = ( @@ -309,6 +355,7 @@ export class EdgeAssignments { WHERE user_id = ? AND relay_host_id = ?`, [leaseExpiresAt, now, identity.userId, identity.relayHostId] ) + await recordRegion(transaction, true) return this.answer(identity, integer(row, 'assignment_epoch'), leaseExpiresAt) } if (requestUnits(row) > 0) throw new EdgeMoveDeferredError('units_held') @@ -321,6 +368,7 @@ export class EdgeAssignments { ) // Still under the row lock: the row commits only once the edge holds the host's data. const pushed = await this.pushOnto(transaction, identity, epoch, region) + await recordRegion(transaction) console.warn( JSON.stringify({ event: 'orca_relay_edge_moved', @@ -473,6 +521,20 @@ export class EdgeAssignments { // is recorded for the evacuation sweep to retry (edge-relay-fence.ts). async fenceAway(identity: Identity, cellId: string, assignmentEpoch: number): Promise { if (!this.admin) return true + // Off the edge: its region record goes (the sweep reads only hosts on the edge anyway). + await this.database + .query(`DELETE FROM relay_edge_host_regions WHERE user_id = ? AND relay_host_id = ?`, [ + identity.userId, + identity.relayHostId + ]) + .catch((error: unknown) => + console.warn( + JSON.stringify({ + event: 'orca_relay_edge_region_forget_failed', + reason: error instanceof Error ? error.message : 'unknown' + }) + ) + ) // An edge whose exports are failing (or that is marked down) gets one try, so a skipped export // is not slowed further. const down = this.exportFailingSince !== undefined || this.config.control?.().mode === 'down' diff --git a/cloud/apps/relay/src/ip-country.test.ts b/cloud/apps/relay/src/ip-country.test.ts new file mode 100644 index 00000000000..806a27b256e --- /dev/null +++ b/cloud/apps/relay/src/ip-country.test.ts @@ -0,0 +1,93 @@ +import { mkdtempSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { gzipSync } from 'node:zlib' +import { describe, expect, it } from 'vitest' +import { forwardedClientIp, loadIpCountryTable, parseIpCountryTable, requestCountry } from './ip-country.js' + +// Documentation ranges (RFC 5737, RFC 3849) stand in for real allocations. +const TABLE = [ + '0.0.0.0,0.255.255.255,ZZ', + '192.0.2.0,192.0.2.127,CN', + '192.0.2.128,192.0.2.255,HK', + '198.51.100.0,198.51.100.255,US', + '2001:db8::,2001:db8:0:ffff:ffff:ffff:ffff:ffff,CN', + '2001:db8:1::,2001:db8:1:ffff:ffff:ffff:ffff:ffff,JP', + 'not,a,row', + '' +].join('\n') + +describe('forwardedClientIp', () => { + it('takes the last hop: the peer Cloud Run appended, never an entry the client sent', () => { + expect(forwardedClientIp('192.0.2.1')).toBe('192.0.2.1') + expect(forwardedClientIp('198.51.100.7, 192.0.2.1')).toBe('192.0.2.1') + expect(forwardedClientIp(' 10.0.0.1 ,198.51.100.7,2001:db8::1 ')).toBe('2001:db8::1') + expect(forwardedClientIp('192.0.2.1,')).toBe('192.0.2.1') + }) + + it('skips trusted proxy hops of ours appended after the client', () => { + expect(forwardedClientIp('198.51.100.7, 192.0.2.1, 203.0.113.9', 1)).toBe('192.0.2.1') + expect(forwardedClientIp('192.0.2.1', 1)).toBeUndefined() + }) + + it('is undefined without a usable hop', () => { + expect(forwardedClientIp(undefined)).toBeUndefined() + expect(forwardedClientIp('')).toBeUndefined() + expect(forwardedClientIp(' , ')).toBeUndefined() + expect(forwardedClientIp('192.0.2.1, unknown')).toBeUndefined() + expect(forwardedClientIp('192.0.2.1:443')).toBeUndefined() + }) +}) + +describe('IP country table', () => { + const table = parseIpCountryTable(TABLE) + + it('finds the range of IPv4, IPv4-mapped and IPv6 addresses', () => { + expect(table.country('192.0.2.0')).toBe('CN') + expect(table.country('192.0.2.127')).toBe('CN') + expect(table.country('192.0.2.128')).toBe('HK') + expect(table.country('198.51.100.200')).toBe('US') + expect(table.country('::ffff:192.0.2.200')).toBe('HK') + // The hex spelling of the same mapped addresses, and a fully written-out one. + expect(table.country('::ffff:c000:2c8')).toBe('HK') + expect(table.country('::FFFF:C000:0201')).toBe('CN') + expect(table.country('0:0:0:0:0:ffff:c633:6401')).toBe('US') + expect(table.country('2001:db8::192.0.2.1')).toBe('CN') + expect(table.country('2001:db8::1')).toBe('CN') + expect(table.country('2001:db8:0:ffff::1')).toBe('CN') + expect(table.country('2001:db8:1:2::')).toBe('JP') + expect(table.country('2001:DB8:1::abcd')).toBe('JP') + }) + + it('answers undefined for gaps, reserved codes and non-addresses', () => { + expect(table.country('0.1.2.3')).toBeUndefined() + expect(table.country('203.0.113.1')).toBeUndefined() + expect(table.country('1.1.1.1')).toBeUndefined() + expect(table.country('2001:db8:2::1')).toBeUndefined() + expect(table.country('::1')).toBeUndefined() + expect(table.country('nonsense')).toBeUndefined() + }) + + it('loads plain and gzipped files and refuses an empty table', () => { + const directory = mkdtempSync(join(tmpdir(), 'ip-country-')) + writeFileSync(join(directory, 'table.csv'), TABLE) + writeFileSync(join(directory, 'table.csv.gz'), gzipSync(TABLE)) + writeFileSync(join(directory, 'empty.csv'), 'a,b,c\n') + expect(loadIpCountryTable(join(directory, 'table.csv')).country('192.0.2.200')).toBe('HK') + expect(loadIpCountryTable(join(directory, 'table.csv.gz')).country('192.0.2.1')).toBe('CN') + expect(() => loadIpCountryTable(join(directory, 'empty.csv'))).toThrow('ip_country_table_empty') + expect(() => loadIpCountryTable(join(directory, 'missing.csv'))).toThrow() + }) +}) + +describe('requestCountry', () => { + const table = parseIpCountryTable(TABLE) + + it('is the last hop’s country, or null when unknown', () => { + expect(requestCountry(table, '198.51.100.7, 192.0.2.1')).toBe('CN') + expect(requestCountry(table, '192.0.2.1, 198.51.100.7')).toBe('US') + expect(requestCountry(table, '203.0.113.1')).toBeNull() + expect(requestCountry(table, undefined)).toBeNull() + expect(requestCountry(undefined, '192.0.2.1')).toBeNull() + }) +}) diff --git a/cloud/apps/relay/src/ip-country.ts b/cloud/apps/relay/src/ip-country.ts new file mode 100644 index 00000000000..4dbaad5f7f6 --- /dev/null +++ b/cloud/apps/relay/src/ip-country.ts @@ -0,0 +1,150 @@ +// Country of a director request, from an offline IP → country table loaded at boot. Only the +// country (ISO 3166 alpha-2) leaves this module; addresses are never logged or kept. +import { readFileSync } from 'node:fs' +import { isIPv4, isIPv6 } from 'node:net' +import { gunzipSync } from 'node:zlib' + +export type IpCountryLookup = { + // Undefined when the address is not in the table (or is reserved). + country(ip: string): string | undefined +} + +// The client address of a request that reached the director straight through Cloud Run's front +// end (a domain mapping, no load balancer and no proxy in front): the front end appends the peer +// it accepted the connection from to X-Forwarded-For, so the last entry is the client and every +// earlier one is whatever the client sent (forgeable). `trustedProxyHops` skips proxies of ours +// appended after it (1 behind an external load balancer). Undefined when there is no such hop. +export function forwardedClientIp(header: string | undefined, trustedProxyHops = 0): string | undefined { + const hops = (header ?? '') + .split(',') + .map((hop) => hop.trim()) + .filter((hop) => hop.length > 0) + const client = hops[hops.length - 1 - trustedProxyHops] + return client !== undefined && (isIPv4(client) || isIPv6(client)) ? client : undefined +} + +// The ask's country: null when unknown (no table, no usable hop, or not in the table). +export function requestCountry( + lookup: IpCountryLookup | undefined, + forwardedFor: string | undefined +): string | null { + const ip = lookup ? forwardedClientIp(forwardedFor) : undefined + return (ip !== undefined && lookup?.country(ip)) || null +} + +// Codes the table uses for unallocated or reserved space. +const UNKNOWN_CODES = new Set(['ZZ', 'XX', '--']) + +// A table of address ranges, one per line `first,last,CC[,...]` (IPv4 or IPv6, inclusive), as in +// the country-only CSV releases of common IP geolocation databases; `.gz` is read gunzipped. +// IPv6 ranges are kept to their first 64 bits (country data is allocated far coarser than /64). +// Throws on an unreadable file or a table with no ranges, so a misconfigured revision fails to boot +// rather than serving with every country unknown. +export function loadIpCountryTable(path: string): IpCountryLookup { + const raw = readFileSync(path) + return parseIpCountryTable((path.endsWith('.gz') ? gunzipSync(raw) : raw).toString('utf8')) +} + +export function parseIpCountryTable(text: string): IpCountryLookup { + const codes: string[] = [] + const codeIndex = new Map() + const v4: [number, number, number][] = [] + const v6: [bigint, bigint, number][] = [] + for (const line of text.split('\n')) { + const [first, last, rawCode] = line.split(',').map((field) => field.trim().replace(/^"|"$/g, '')) + const code = rawCode?.toUpperCase() + if (!first || !last || !code || !/^[A-Z]{2}$/.test(code) || UNKNOWN_CODES.has(code)) { + continue + } + let index = codeIndex.get(code) + if (index === undefined) { + index = codes.push(code) - 1 + codeIndex.set(code, index) + } + if (isIPv4(first) && isIPv4(last)) { + v4.push([ipv4Number(first), ipv4Number(last), index]) + } else if (isIPv6(first) && isIPv6(last)) { + v6.push([ipv6Prefix64(ipv6Groups(first)), ipv6Prefix64(ipv6Groups(last)), index]) + } + } + if (v4.length + v6.length === 0) { + throw new Error('ip_country_table_empty') + } + v4.sort((a, b) => a[0] - b[0]) + v6.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)) + const v4First = Uint32Array.from(v4, (range) => range[0]) + const v4Last = Uint32Array.from(v4, (range) => range[1]) + const v4Code = Uint16Array.from(v4, (range) => range[2]) + const v6First = BigUint64Array.from(v6, (range) => range[0]) + const v6Last = BigUint64Array.from(v6, (range) => range[1]) + const v6Code = Uint16Array.from(v6, (range) => range[2]) + return { + country(ip) { + let v4 = isIPv4(ip) ? ipv4Number(ip) : undefined + let groups: number[] | undefined + if (v4 === undefined) { + if (!isIPv6(ip)) { + return undefined + } + groups = ipv6Groups(ip) + // IPv4-mapped (::ffff:a.b.c.d, or its hex spelling ::ffff:abcd:efgh) is the IPv4 address. + if (groups.slice(0, 5).every((group) => group === 0) && groups[5] === 0xffff) { + v4 = groups[6]! * 0x1_0000 + groups[7]! + } + } + if (v4 !== undefined) { + const at = rangeAt(v4First, v4Last, v4) + return at === undefined ? undefined : codes[v4Code[at]!] + } + const at = rangeAt(v6First, v6Last, ipv6Prefix64(groups!)) + return at === undefined ? undefined : codes[v6Code[at]!] + } + } +} + +// Index of the last range starting at or below `value`, if it also ends at or above it. +function rangeAt( + first: ArrayLike, + last: ArrayLike, + value: T +): number | undefined { + let low = 0 + let high = first.length - 1 + let found = -1 + while (low <= high) { + const middle = (low + high) >>> 1 + if (first[middle]! <= value) { + found = middle + low = middle + 1 + } else { + high = middle - 1 + } + } + return found >= 0 && last[found]! >= value ? found : undefined +} + +function ipv4Number(ip: string): number { + return ip.split('.').reduce((value, octet) => value * 256 + Number(octet), 0) +} + +// The eight 16-bit groups of a valid IPv6 address (a trailing dotted IPv4 part is the last two). +function ipv6Groups(ip: string): number[] { + const [head = '', tail] = ip.toLowerCase().split('::') + const tokens = (part: string) => + (part ? part.split(':') : []).flatMap((token) => + token.includes('.') + ? [ipv4Number(token) >>> 16, ipv4Number(token) & 0xffff] + : [Number.parseInt(token, 16)] + ) + const headGroups = tokens(head) + if (tail === undefined) { + return headGroups + } + const tailGroups = tokens(tail) + return [...headGroups, ...Array(8 - headGroups.length - tailGroups.length).fill(0), ...tailGroups] +} + +// The first 64 bits (country data is allocated far coarser than /64). +function ipv6Prefix64(groups: number[]): bigint { + return groups.slice(0, 4).reduce((value, group) => (value << 16n) | BigInt(group), 0n) +} diff --git a/cloud/apps/relay/src/relay-server.ts b/cloud/apps/relay/src/relay-server.ts index 973d1f6cbf7..7efa4069f35 100644 --- a/cloud/apps/relay/src/relay-server.ts +++ b/cloud/apps/relay/src/relay-server.ts @@ -201,6 +201,9 @@ export function createRelayServer( ? new EdgeEvacuation(observedDatabase, edgeConfig, edgeAdmin, EDGE_CELL_ID, options.now, options.random) : undefined edgeEvacuation?.start() + if (edgeConfig?.ipCountry) { + edgeAssignments?.regionCountries.start() + } // A rollback (mode off/down, a smaller share) starts draining within seconds. options.edgeControl?.onChange(() => edgeEvacuation?.controlChanged()) if (edgeAssignments) { @@ -934,6 +937,7 @@ export function createRelayServer( store.resumeAudit.stop() rehomeSwitch?.stop() edgeEvacuation?.stop() + edgeAssignments?.regionCountries.stop() }) const resumeAuditDropped = (): number => { const drops = store.resumeAudit.drops()