Files
orca/cloud/apps/relay-edge/src/edge-database.ts
T
Neil 3f0c565994 relay-edge: Cloudflare Worker + Durable Objects relay (#39363)
* spike(relay-edge): local Durable Object relay prototype and de-risk harness

Stateless Worker routes control/phone/data sockets to one object per host.
Harness drives the shipped desktop control client and data transport against
wrangler dev. Not wired into builds or deploys.

* spike(relay-edge): one Durable Object per splice isolates slow phones

The host object keeps control, session and connection bookkeeping. Each
phone connection and its host data socket live in their own object and talk
to the host over DO RPC. Harness adds flood isolation, splice reset, budget
reclaim and RPC latency checks; the silent-bytes guard is measured and left
disabled.

* spike(relay-edge): Cloudflare de-risk kit (spike env, load, deploy, canary, rtt tools, runbook)

* spike(relay-edge): rebind after an object reset keeps the generation

* spike(relay-edge): pool splice objects per host to avoid object creation per phone connect

* spike(relay-edge): slow-phone flood test for Cloudflare

* relay-edge: MVP backend (credential store over Hyperdrive, JWKS, epoch check, host commands)

* relay-edge: MVP checks on local Postgres (credentials, commands, epoch, DB-down)

* relay-edge: refusal and database-latency metrics; Analytics Engine on the spike

* relay-edge: alerts cron Worker over Analytics Engine; edge.relay.orca.dev on the spike

* relay-edge: slow assignment check closes 4429, never 4401; staging env over Hyperdrive; db latency debug route

* relay-edge alerts: silence only after traffic

* relay-edge: Durable Object SQLite adapter; relay credential-store tests pass on it (P1)

* relay-edge phase 2: credential store on HostRelay SQLite, signed director push/export/erase; 17/17 in workerd

* relay-edge phase 2: Cloudflare env, push-assignments load prep, remote mode for phase-2 checks

* relay-edge: export freezes the host and is refused while connected; move-on replaces host data; stale/conflict carry the edge epoch; push location hint; admin content-length check

* relay-edge: daily store sweep on the object alarm (armed on every wake and admin call), wipe of objects whose host never arrived or left 30 days ago, erase guard ignores expired bases, admin and sweep metrics

* relay-edge: admin key renamed ADMIN_SIGNING_KEY; optional erase-only signer for the erasure job; a move onto the edge also voids audit rows from an earlier stay

* relay-edge: phase2 test env names the erasure issuer

* relay-edge: director ⇄ cell ⇄ edge round trip with the shipped desktop and phone clients

* relay-edge: round trip resolves the live phone first (a failed resolve rate-limits the host)

* relay-edge: per-source pre-auth limits; phones for unpushed hosts answered without storage

Phone and host data upgrades are counted per source (CF-Connecting-IP, IPv6 by /64)
through a Rate Limiting binding, failing open. A phone for a host the director never
pushed (or one since wiped) gets relay-hello 4409 from the Worker, so neither the host
nor a splice object writes storage. Local 25/25, phase2 21/21.

* relay-edge: production env on edge.relay.orca.dev; object schema version; frame caps; place on metrics

- production env (orca-relay-edge): custom domain edge.relay.orca.dev moved off the
  spike env; object backend, production auth JWKS, no debug/reset routes.
- Object storage carries a schema version; code older than an object's schema refuses
  it; a test pins the version to a hash of the tables so changes need a migration.
- Frames over the cells' limits close 1009 (control 1 MiB, splices 8 MiB).
- Metrics carry the client's ingress '<continent>/<colo>'.
Local 26/26, phase2 22/22, unit 24/24.

* relay-edge: production alerts env (reads the production dataset)

* relay-edge: keep only local dev config in this repo

Deployed environments (Worker names, hostname, account id, dataset names,
rate limits, Hyperdrive id) move to the private deploy config. The local
config and tests are unchanged.

* cloud: keep relay-edge out of the pnpm workspace (own npm lockfile)

* Revert "cloud: keep relay-edge out of the pnpm workspace (own npm lockfile)"

This reverts commit a55955d3c023964ccd2dfb644e2d09ca67322722.

* cloud: relay-edge as a pnpm workspace member (lockfile; workerd binary-only)

* relay-edge: follow main's relay module moves; alias workspace packages by directory so subpath imports resolve

* relay-edge: splice byte counters on the socket attachment (survive hibernation)

* relay-edge: keep deployed-target load tools out of the public tree; abort routes only on the spike backend

The local harness (spike/run-all.ts, lib.ts, keys.ts) stays. The tools that drive a deployed
Worker and the Cloudflare runbook live with the private deploy config.

* relay-edge: satisfy the changed-lines lint gate

Braces on every if, type aliases over interfaces, template strings, no explicit any,
!== -1 index checks, and a justified max-lines header on the per-host object, the splice
object and the end-to-end harnesses. No behaviour change: unit 19/19, object MVP 26/26.

* relay-edge: split the host object and harnesses under the 300-line limit

HostRelay is layered base → handshake → control → phones → HostRelay (one object, one state;
method bodies moved verbatim, private → protected). SpliceRelay's state types move to
splice-state.ts. The harnesses' helpers move to sibling modules. No max-lines disables.
Unit 19/19, object MVP 26/26, local spike harness 19/19.

* relay-edge: run its vitest suite from cloud's pnpm -r test and register the runner
2026-11-07 18:47:21 -08:00

182 lines
6.3 KiB
TypeScript

// The relay's RelayDatabase interface over Hyperdrive, so the credential store runs unchanged.
// Mirrors cloud/apps/relay/src/database/database.ts PostgresDatabase where the store depends on it:
// `?` placeholders become $n, writes without RETURNING answer [{ changes }], transactions retry
// serialization/deadlock/lock/statement-timeout aborts up to 3 times on a fresh connection.
// Hyperdrive pools connections to the origin, so each operation opens a short-lived client (the
// pattern Hyperdrive expects); nothing is held across requests, which keeps objects hibernatable.
import { Client } from 'pg'
import type {
RelayDatabase,
RelayLockOptions,
RelayTransactionOptions,
SqlRow
} from '../../relay/src/database/database'
const TRANSACTION_ATTEMPTS = 3
const RETRY_MAX_DELAY_MS = 25
const CONNECT_TIMEOUT_MS = 2_000
const QUERY_TIMEOUT_MS = 5_000
function postgresSql(sql: string): string {
let index = 0
return sql.replace(/\?/g, () => `$${++index}`)
}
function returnsRows(sql: string): boolean {
return /^\s*(select|with)/i.test(sql) || /returning/i.test(sql)
}
function lockedStatement(sql: string, options: RelayLockOptions): string {
if (options.lockClauseInStatement) { return sql }
return `${sql} FOR UPDATE${options.failIfUnavailable ? ' NOWAIT' : ''}`
}
function sqlState(error: unknown): string {
return String((error as { code?: unknown } | null)?.code)
}
function retryableTransactionError(error: unknown): boolean {
return ['40P01', '40001', '55P03', '57014'].includes(sqlState(error))
}
// Same classification as the cells' isRelayDatabaseTransientError: callers answer 4429/4503 (or
// control-error database_transient), never a credential rejection.
const TRANSIENT_STATES = new Set([
'40P01', '40001', '55P03', '57014', '53300', '57P03', '08000', '08001', '08003', '08006',
'57P01', '57P02', '25P03'
])
export function isEdgeDatabaseTransientError(error: unknown): boolean {
if (error instanceof EdgeDatabaseError) { return true }
const code = sqlState(error)
if (TRANSIENT_STATES.has(code) || code === 'ECONNRESET' || code === 'EPIPE' || code === 'ECONNREFUSED') {
return true
}
const message = error instanceof Error ? error.message : ''
return /^Connection terminated|timeout|connect/i.test(message)
}
// Wraps connection failures so they are recognisably the database's, without the URL in the text.
export class EdgeDatabaseError extends Error {
constructor(readonly cause: unknown) {
super('database_unavailable')
}
}
async function run(client: Client, sql: string, params: unknown[]): Promise<SqlRow[]> {
const result = await client.query({ text: postgresSql(sql), values: params })
return returnsRows(sql) ? (result.rows as SqlRow[]) : [{ changes: result.rowCount ?? 0 }]
}
class EdgeTransaction implements RelayDatabase {
readonly dialect = 'postgres' as const
constructor(private readonly client: Client) {}
query(sql: string, params: unknown[] = []): Promise<SqlRow[]> {
return run(this.client, sql, params)
}
async queryLocked(sql: string, params: unknown[] = [], options: RelayLockOptions = {}): Promise<SqlRow[]> {
try {
return await run(this.client, lockedStatement(sql, options), params)
} catch (error) {
if (options.failIfUnavailable && sqlState(error) === '55P03') { throw new Error('database_lock_unavailable') }
throw error
}
}
async transaction<T>(operation: (transaction: RelayDatabase) => Promise<T>): Promise<T> {
return await operation(this)
}
async close(): Promise<void> {}
}
export class EdgePostgresDatabase implements RelayDatabase {
readonly dialect = 'postgres' as const
constructor(
private readonly connectionString: string,
// Called once per operation with its wall time and outcome (metrics; must not throw).
private readonly onOp: (ms: number, outcome: 'ok' | 'transient' | 'error') => void = () => {}
) {}
private async timed<T>(operation: () => Promise<T>): Promise<T> {
const started = Date.now()
try {
const result = await operation()
this.onOp(Date.now() - started, 'ok')
return result
} catch (error) {
this.onOp(Date.now() - started, isEdgeDatabaseTransientError(error) ? 'transient' : 'error')
throw error
}
}
private async connect(): Promise<Client> {
const client = new Client({
connectionString: this.connectionString,
connectionTimeoutMillis: CONNECT_TIMEOUT_MS,
query_timeout: QUERY_TIMEOUT_MS
})
// An idle client error after end() must not become an unhandled rejection.
client.on('error', () => {})
try {
await client.connect()
} catch (error) {
await client.end().catch(() => {})
throw new EdgeDatabaseError(error)
}
return client
}
query(sql: string, params: unknown[] = []): Promise<SqlRow[]> {
return this.timed(async () => {
const client = await this.connect()
try {
return await run(client, sql, params)
} finally {
await client.end().catch(() => {})
}
})
}
async queryLocked(sql: string, params: unknown[] = [], options: RelayLockOptions = {}): Promise<SqlRow[]> {
try {
return await this.query(lockedStatement(sql, options), params)
} catch (error) {
if (options.failIfUnavailable && sqlState(error) === '55P03') { throw new Error('database_lock_unavailable') }
throw error
}
}
async transaction<T>(
operation: (transaction: RelayDatabase) => Promise<T>,
_options: RelayTransactionOptions = {}
): Promise<T> {
return this.timed(() => this.runTransaction(operation))
}
private async runTransaction<T>(operation: (transaction: RelayDatabase) => Promise<T>): Promise<T> {
for (let attempt = 1; ; attempt++) {
const client = await this.connect()
let begun = false
try {
await client.query('BEGIN')
begun = true
const result = await operation(new EdgeTransaction(client))
await client.query('COMMIT')
return result
} catch (error) {
if (begun) { await client.query('ROLLBACK').catch(() => {}) }
if (!retryableTransactionError(error) || attempt >= TRANSACTION_ATTEMPTS) { throw error }
} finally {
await client.end().catch(() => {})
}
await new Promise((resolve) => setTimeout(resolve, Math.random() * RETRY_MAX_DELAY_MS))
}
}
async close(): Promise<void> {}
}