Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Control plane: release tunnels the relay has replaced, relay first at the tunnel limit, version cutoffs (#5160)

Milind Sonif9c25dd2400c
diff --git a/cloudflare/control-plane/README.md b/cloudflare/control-plane/README.md
index fc73514a65..dfe602d56c 100644
--- a/cloudflare/control-plane/README.md
+++ b/cloudflare/control-plane/README.md
@@ -280,7 +280,7 @@ A failure in one account is logged and never stops the others:
- `inactive` (never ran), with no activation time, created at least two
days ago; or
- `down` with its last connection ended at least
- `OMB_TUNNEL_OFFLINE_RECLAIM_DAYS` (default 21, minimum 3) days ago and no
+ `OMB_TUNNEL_OFFLINE_RECLAIM_DAYS` (default 21, minimum 1) days ago and no
later activation.
`healthy` and `degraded` tunnels, any reported connection, an unknown
@@ -623,8 +623,74 @@ old one; no identifiers) answers:
the day, the kind and a count; `relay_adoption.first_seen_at`, `token_at` and `e2e_at` tell a request whether its
installation was already counted today. The stats dashboard (stats.openmausbot.com) charts it. A Worker without the
migration keeps minting tokens and writing `relay_adoption`, and logs `relay_daily_schema` once per isolate.
-- **Tunnels.** From `RELAY_CAPABLE_MIN_VERSION`, a desktop at that version or later that reports `legacyDevices: 0` gets
- `409 relay_capable` instead of a new tunnel. An endpoint it already holds keeps working.
+- **Tunnels.** From `RELAY_CAPABLE_MIN_VERSION`, a desktop at that version or later that the relay can carry (it is
+ on, the computer is inside the rollout and not blocked) and that reports `legacyDevices: 0` gets `409 relay_capable`
+ instead of a tunnel, whether it never had one or is coming back after a release or reclaim. An endpoint it already
+ holds keeps working. A desktop the relay cannot carry gets a tunnel as before. See **Releasing tunnels**.
+
+### Releasing tunnels
+
+A running desktop keeps its connector up, so idle reclaim never sees its tunnel as idle. These rules give tunnels back
+once the relay has replaced them. Each switch is off in `wrangler.jsonc`; all need migration `0015`. The cron only
+marks rows `deleting` (at most 20 a run, every reason together) and the cleanup sweep removes them; the row and its
+hostname stay, so a later provisioning call returns the same address.
+
+| Setting | Default | What it does |
+|---|---|---|
+| `RELAY_TUNNEL_RELEASE_PERCENT` | `0` | Share of computers (the relay rollout's stable hash) whose tunnel is released once it is proven on the relay |
+| `RELAY_TUNNEL_RELEASE_DAYS` | `3` | The wait: no old phone reported for this long. Three days outlasts a weekend away, so a phone that still dials the tunnel has had working days to be counted and stop the wait |
+| `TUNNEL_LEGACY_PHONE_CUTOFF_PERCENT` | `0` | Share of relay-served computers that give up their tunnel whatever phones are paired. Old phone apps stop connecting from outside the home network |
+| `TUNNEL_MIN_APP_VERSION` | empty | A desktop below it gets `426 update_required` and its tunnel is removed. A missing version counts as below |
+| `TUNNEL_REASON_MIN_VERSION` | empty | First desktop release that reads `tunnel` on `409 relay_capable` and keeps asking afterwards. Only from it is a full account answered with `relay_capable` |
+| `OMB_TUNNEL_RECLAIM_PREVIEW_DAYS` | empty | Dry run of idle reclaim at another offline period; counted, never acted on |
+
+- **Proven on the relay** means: a relay token in the last two days, a phone report in the last two days with at
+ least one phone on the encrypted connection and no old phone, and no old phone reported for the whole wait
+ (`relay_adoption.legacy_clear_at`, cleared by any report that counts an old phone). A phone that has used the
+ encrypted connection never dials the tunnel again, so such a tunnel carries nothing. The checks are repeated inside
+ the marking SQL, so a report that lands during the run wins.
+- **One rule for "on the relay".** The cron and provisioning both ask `relayAdmits` (`src/relay.ts`): the relay is
+ on, the computer is not blocked, and it is inside `RELAY_ROLLOUT_PERCENT` or named in `RELAY_ALLOW_INSTALLATIONS`.
+ So the cron never marks a tunnel that provisioning would hand straight back. To give up a tunnel that works, a
+ computer must also hold a relay token from the last two days: the cron always requires it, and under the cutoff
+ provisioning requires it whenever the row still holds a tunnel.
+- **The stored release.** `installations.app_version` is refreshed by every relay-token request (hourly on a
+ relay-capable desktop), as well as at registration and on `POST .../endpoint`. The cron applies
+ `TUNNEL_MIN_APP_VERSION` only to a computer that called in the last two days: had it updated to a relay-capable
+ release it would have said so. A computer that has been off is left to idle reclaim. One case is still judged by
+ a stale release: a desktop that updated with the relay route turned off. Its tunnel is removed, its next request
+ reports the real release and the same address comes back.
+- **Backpressure.** A run marks at most what one cleanup sweep removes (`OMB_CLEANUP_SWEEP_LIMIT`, at most 20) minus
+ the rows already waiting for cleanup. While the sweep is failing or rate-limited nothing more is marked. A marked
+ row is a final delete: its owner is answered `409 endpoint_busy` until the sweep has removed it.
+- **Coming back.** `POST /v1/installations/self/endpoint` creates a tunnel again, with the same hostname, when the
+ desktop reports an old phone (outside the cutoff), or the relay cannot carry it: `RELAY_DISABLED: "1"`, a lower
+ `RELAY_ROLLOUT_PERCENT`, or `relay_blocked_at`. With the relay switched off the cron releases nothing on the
+ relay's account either, so a relay outage is answered by that one switch.
+- **At the tunnel limit** a desktop the relay carries, at `TUNNEL_REASON_MIN_VERSION` or later, is answered
+ `409 {"error":"relay_capable","tunnel":"full"}` instead of `503 endpoint_capacity`: it pairs new phones over the
+ relay and keeps asking for its old phones. An earlier release takes any `relay_capable` as "nothing more to do"
+ and would stop retrying, so it keeps the 503. Under the old-phone cutoff the answer is `"tunnel":"retired"` for
+ every relay-capable release; the earlier ones carry on without a tunnel and say nothing.
+- **Reading before switching.** `/healthz` reports counts only:
+
+```json
+"tunnelRelease": {
+ "relayProven": { "percent": 0, "days": 3, "eligible": 41 },
+ "legacyPhoneCutoff": { "percent": 0, "eligible": 1630 },
+ "minAppVersion": { "on": false, "eligible": 212 }
+}
+```
+
+ `relayProven.eligible` is what the release clears at 100%; `legacyPhoneCutoff.eligible` what the cutoff clears
+ beyond that (both assume the relay rollout is at 100%); `minAppVersion.eligible` the tunnels of desktops seen in
+ the last two days below `TUNNEL_MIN_APP_VERSION`, or below `RELAY_CAPABLE_MIN_VERSION` while no minimum is set. `capacity.reclaim.preview` is
+ `{ "offlineDays": 1, "eligible": 37 }` once every account has finished a full pass at the preview period (about 50
+ minutes per 1,000 tunnels), and `eligible: null` until then.
+- **Order.** Apply migration `0015` and deploy with everything off. Read `tunnelRelease`. Raise
+ `RELAY_TUNNEL_RELEASE_PERCENT` 10, 50, 100. After the desktop release that explains the cutoff is out, set
+ `TUNNEL_REASON_MIN_VERSION` to that release, then raise `TUNNEL_LEGACY_PHONE_CUTOFF_PERCENT` 10, then 100, and last
+ set `TUNNEL_MIN_APP_VERSION`.
Setup, once:
diff --git a/cloudflare/control-plane/migrations/0015_tunnel_release.sql b/cloudflare/control-plane/migrations/0015_tunnel_release.sql
new file mode 100644
index 0000000000..01074ab7ee
--- /dev/null
+++ b/cloudflare/control-plane/migrations/0015_tunnel_release.sql
@@ -0,0 +1,20 @@
+-- Releasing tunnels that relay users no longer need, and a dry-run count for idle reclaim.
+--
+-- `legacy_clear_at` is since when an installation has reported no old phone (one that still needs the tunnel). It is
+-- kept while the count stays 0 and cleared by any old phone, so "no old phone for N days" is one comparison. Rows that
+-- report none today start their wait at their last report: nothing earlier was recorded.
+ALTER TABLE relay_adoption ADD COLUMN legacy_clear_at INTEGER;
+
+UPDATE relay_adoption SET legacy_clear_at = updated_at WHERE legacy_devices = 0;
+
+-- What one full pass of the idle scan would reclaim at OMB_TUNNEL_RECLAIM_PREVIEW_DAYS, per account. Counts and
+-- timestamps only. `running` is the pass under way (NULL between passes, and for a pass joined part-way);
+-- `eligible` the last finished pass (NULL until one finishes at these `days`).
+CREATE TABLE managed_endpoint_reclaim_preview (
+ provider_account TEXT PRIMARY KEY CHECK (length(provider_account) = 32),
+ days INTEGER NOT NULL CHECK (days BETWEEN 1 AND 365),
+ running INTEGER CHECK (running IS NULL OR running >= 0),
+ eligible INTEGER CHECK (eligible IS NULL OR eligible >= 0),
+ completed_at INTEGER,
+ updated_at INTEGER NOT NULL
+);
diff --git a/cloudflare/control-plane/src/config.ts b/cloudflare/control-plane/src/config.ts
index 559b951deb..54828942a7 100644
--- a/cloudflare/control-plane/src/config.ts
+++ b/cloudflare/control-plane/src/config.ts
@@ -15,8 +15,11 @@ export interface CapacityConfig {
/** Zone DNS record quota used for the usage alert. */
dnsRecordLimit: number;
/** A tunnel offline for at least this long (and an installation that has
- * been quiet as long) may be reclaimed. Never below three days. */
+ * been quiet as long) may be reclaimed. Never below one day. */
offlineReclaimMs: number;
+ /** A second offline period that is only counted, never acted on: how many
+ * tunnels a pass would reclaim at it. Null: no preview. */
+ reclaimPreviewMs: number | null;
/** `observe` evaluates and logs reclaim candidates without marking any. */
reclaimMode: TunnelReclaimMode;
/** Account tunnel quota used for the usage alert. */
@@ -67,7 +70,10 @@ const DAY_MS = 24 * 60 * 60 * 1_000;
export const DEFAULT_TUNNEL_LIMIT = 1_000;
export const DEFAULT_DNS_RECORD_LIMIT = 1_000;
export const DEFAULT_OFFLINE_RECLAIM_DAYS = 21;
-export const MIN_OFFLINE_RECLAIM_DAYS = 3;
+// One day is the floor: a computer shut down overnight must never lose its
+// tunnel. Below three days a weekend away does; it gets the same address back
+// when it returns, if its account still has room.
+export const MIN_OFFLINE_RECLAIM_DAYS = 1;
// Each cleanup makes at most ten Cloudflare API calls: twenty rows plus the two
// capacity reads stay near 200 calls per five-minute run, under the token's
// 1,200-per-five-minutes limit and Workers Paid's 10,000 subrequests. Use 4 on
@@ -132,6 +138,16 @@ export function readCapacityConfig(env: Partial<Record<string, unknown>>): Capac
365,
) * DAY_MS,
reclaimMode: reclaimMode(env.OMB_TUNNEL_RECLAIM),
+ reclaimPreviewMs: env.OMB_TUNNEL_RECLAIM_PREVIEW_DAYS === undefined || env.OMB_TUNNEL_RECLAIM_PREVIEW_DAYS === null
+ || env.OMB_TUNNEL_RECLAIM_PREVIEW_DAYS === ""
+ ? null
+ : boundedIntegerVar(
+ env.OMB_TUNNEL_RECLAIM_PREVIEW_DAYS,
+ "OMB_TUNNEL_RECLAIM_PREVIEW_DAYS",
+ 0,
+ MIN_OFFLINE_RECLAIM_DAYS,
+ 365,
+ ) * DAY_MS || null,
tunnelLimit: boundedIntegerVar(
env.OMB_TUNNEL_LIMIT,
"OMB_TUNNEL_LIMIT",
diff --git a/cloudflare/control-plane/src/endpoints.ts b/cloudflare/control-plane/src/endpoints.ts
index ccf43d2ee7..d07bb80331 100644
--- a/cloudflare/control-plane/src/endpoints.ts
+++ b/cloudflare/control-plane/src/endpoints.ts
@@ -11,7 +11,6 @@ import type { ControlPlaneConfig, EndpointAccount } from "./config";
import {
ACTED_ON_ENDPOINT_SQL,
actedOnAccounts,
- appVersionAtLeast,
chooseNewEndpointAccount,
endpointAccountFor,
neverReady,
@@ -38,6 +37,8 @@ import {
releaseCleanedCapacity,
type AccountCleanup,
} from "./tunnel-capacity";
+import { belowMinimum, readsTunnelReason, readTunnelPolicy, relayCapableVersion } from "./tunnel-release";
+import { relayStanding, type RelayStanding } from "./relay";
type EndpointStatus = "pending" | "provisioning" | "ready" | "deleting" | "deleted" | "error";
@@ -251,12 +252,18 @@ async function provisionRequest(request: Request): Promise<{ appVersion: string
return { appVersion: parsed.data.appVersion ?? null, legacyDevices: parsed.data.legacyDevices ?? null };
}
-/** A desktop that reaches its phones through the relay gets no new tunnel unless an old phone still needs one.
- * Off until RELAY_CAPABLE_MIN_VERSION names the first release that can. */
-function relayCapableWithoutLegacy(env: Env, appVersion: string | null, legacyDevices: number | null): boolean {
- const minimum = (env as unknown as Partial<Record<string, unknown>>).RELAY_CAPABLE_MIN_VERSION;
- return typeof minimum === "string" && /^[0-9]+\.[0-9]+\.[0-9]+$/.test(minimum)
- && legacyDevices === 0 && appVersionAtLeast(appVersion, minimum);
+/** Why a relay-capable desktop goes without a tunnel. The code stays `relay_capable`, which every such desktop
+ * already takes as "carry on over the relay"; `tunnel` tells a newer one what to say about it:
+ * - absent: no old phone needs one;
+ * - `retired`: old phone apps no longer hold a tunnel (TUNNEL_LEGACY_PHONE_CUTOFF);
+ * - `full`: an old phone would have had one, but every account is at its limit. */
+function relayCapableResponse(tunnel?: "full" | "retired"): Response {
+ return json(tunnel ? { error: "relay_capable", tunnel } : { error: "relay_capable" }, 409);
+}
+
+/** The row holds a tunnel that works, as far as this Worker knows. */
+function holdsTunnel(row: EndpointRow | null): boolean {
+ return row !== null && row.tunnel_id !== null && row.status !== "deleting" && row.status !== "deleted";
}
async function enforceEndpointRateLimit(
@@ -1178,7 +1185,35 @@ export async function provisionManagedEndpoint(
}
const allocation = allocationFor(env, config, reportedVersion ?? installation.app_version);
const existing = await endpointRow(env, installation.installation_id);
- if (!existing && relayCapableWithoutLegacy(env, reportedVersion, legacyDevices)) throw new HTTPError(409, "relay_capable");
+ const policy = readTunnelPolicy(env);
+ // Below the minimum version a desktop neither gets nor keeps a tunnel; the cron removes one it still holds.
+ if (belowMinimum(policy, reportedVersion ?? installation.app_version)) throw new HTTPError(426, "update_required");
+ // The relay first: a desktop it can carry gets a tunnel only for an old phone, and only while old phones may
+ // still hold one. A desktop the relay cannot carry (an older release, the relay off, outside the rollout,
+ // blocked) falls through to a tunnel, as before the relay existed.
+ let standing: RelayStanding | null = null;
+ const onRelay = async () => {
+ if (!relayCapableVersion(policy, reportedVersion)) return null;
+ standing ??= await relayStanding(env, installation.installation_id);
+ return standing.serves ? standing : null;
+ };
+ if (policy.legacyCutoffPercent > 0) {
+ const relay = await onRelay();
+ // A tunnel that works is given up only by a computer the relay is known to be carrying (the cron's rule).
+ if (
+ relay && relay.bucket !== null && relay.bucket < policy.legacyCutoffPercent
+ && (relay.proven || !holdsTunnel(existing))
+ ) {
+ return relayCapableResponse(legacyDevices === 0 ? undefined : "retired");
+ }
+ }
+ if (legacyDevices === 0 && !holdsTunnel(existing) && await onRelay()) return relayCapableResponse();
+ // At the limit a desktop on the relay still pairs new phones over it, and only its old phones wait. Only a
+ // release that reads `tunnel` is told so: an earlier one takes any relay_capable as "nothing more to do" and
+ // would stop retrying, so it keeps the 503 it shows and retries on.
+ const atCapacity = async () => (
+ readsTunnelReason(policy, reportedVersion) && await onRelay() ? relayCapableResponse("full") : capacityResponse()
+ );
// Only a new row chooses its account; an existing one keeps its own.
const row = existing
?? await ensureEndpointRow(env, installation.installation_id, await newEndpointAccount(config, allocation));
@@ -1209,7 +1244,7 @@ export async function provisionManagedEndpoint(
errorCode: capacity ? "endpoint_capacity" : "endpoint_unavailable",
hostSuffix: account.companionHostSuffix,
}));
- if (capacity) return capacityResponse();
+ if (capacity) return atCapacity();
throw new HTTPError(502, "endpoint_unavailable");
}
const claim = await claimEndpoint(env, row, "provisioning");
@@ -1237,7 +1272,7 @@ export async function provisionManagedEndpoint(
if (capacity || (refused && config.endpointAccounts.length > 1)) {
await recordAccountRefusal(env, config, failedIn, code).catch(() => undefined);
}
- if (capacity) return capacityResponse();
+ if (capacity) return atCapacity();
if (code === "cf_rate_limited") return rateLimitedResponse(retryAfterSeconds(error));
throw new HTTPError(502, "endpoint_unavailable");
}
diff --git a/cloudflare/control-plane/src/index.ts b/cloudflare/control-plane/src/index.ts
index f4fb4ec4f9..165293a743 100644
--- a/cloudflare/control-plane/src/index.ts
+++ b/cloudflare/control-plane/src/index.ts
@@ -14,6 +14,7 @@ import {
} from "./endpoints";
import { registerPushDevice, sendPush, unregisterPushDevice } from "./push";
import { issueRelayToken, relayAdoption } from "./relay";
+import { releaseTunnels, tunnelReleaseHealth } from "./tunnel-release";
import { capacityHealth, reportEndpointAccountProblems, scanTunnelCapacity } from "./tunnel-capacity";
import {
createInstallation,
@@ -192,11 +193,13 @@ export function createWorker(
// so a full quota never hides sign-in, recovery, or local pairing.
const capacity = await capacityHealth(env, healthConfig, ctx).catch(() => null);
const adoption = await relayAdoption(env).catch(() => null);
+ const release = await tunnelReleaseHealth(env, healthConfig).catch(() => null);
return secureResponse(json({
ok: true,
service: "openmausbot-control-plane",
...(capacity === null ? {} : { capacity }),
...(adoption === null ? {} : { relayAdoption: adoption }),
+ ...(release === null ? {} : { tunnelRelease: release }),
}), request, null, requestId);
}
@@ -249,6 +252,17 @@ export function createWorker(
errorCode: "endpoint_internal",
}));
}
+ // Marks only, like the scan: tunnels the relay has replaced, and
+ // those a version cutoff ends. The sweep below removes them.
+ try {
+ await releaseTunnels(env, config, requestId);
+ } catch {
+ console.error(JSON.stringify({
+ message: "managed endpoint tunnel release failed",
+ requestId,
+ errorCode: "endpoint_internal",
+ }));
+ }
try {
await sweepManagedEndpointCleanup(env, config, cloudflareFetch, requestId);
} catch {
diff --git a/cloudflare/control-plane/src/relay.ts b/cloudflare/control-plane/src/relay.ts
index 0613dfd795..f1fbff06bd 100644
--- a/cloudflare/control-plane/src/relay.ts
+++ b/cloudflare/control-plane/src/relay.ts
@@ -4,7 +4,7 @@
import { z } from "zod";
import { errorResponse, HTTPError, json, readBoundedJSON } from "./http";
-import { requireInstallation } from "./installations";
+import { recordReportedAppVersion, requireInstallation } from "./installations";
const HOUR_MS = 60 * 60 * 1_000;
export const RELAY_TOKEN_TTL_S = 12 * 60 * 60;
@@ -237,11 +237,74 @@ async function recordUse(env: Env, use: RelayUse): Promise<boolean> {
).bind(use.installationId, use.appVersion, use.e2e, use.legacy, use.continent, use.now).run().then(() => true, () => false);
}
+/** Since when this installation has reported no old phone: kept while the count stays 0, cleared by any old phone.
+ * The tunnel release waits on it (`tunnel-release.ts`). Skipped without migration 0015, and the release stays off. */
+async function recordLegacyClear(env: Env, use: Pick<RelayUse, "installationId" | "legacy" | "now">): Promise<void> {
+ await env.DB.prepare(
+ `UPDATE relay_adoption
+ SET legacy_clear_at = CASE WHEN ?2 > 0 THEN NULL ELSE COALESCE(legacy_clear_at, ?3) END
+ WHERE installation_id = ?1`,
+ ).bind(use.installationId, use.legacy, use.now).run().catch(() => undefined);
+}
+
+/** The relay gave the computer a token this recently: tokens are renewed hourly while the relay is in use, so two
+ * days covers a night off and a sleeping laptop. */
+export const RELAY_FRESH_MS = 2 * 24 * HOUR_MS;
+
+/**
+ * The one rule for "the relay carries this computer", shared by provisioning and the release cron so they can never
+ * disagree: the relay is on, the computer is not blocked, and it is inside the rollout or admitted by name. `bucket`
+ * is its place (0-99) in every percentage rollout.
+ */
+export async function relayAdmits(
+ settings: Pick<RelaySettings, "allowInstallations" | "rolloutPercent"> | null,
+ computer: { installationId: string; hostId: string | null; blocked: boolean },
+): Promise<{ admitted: boolean; bucket: number | null }> {
+ const bytes = computer.hostId === null ? null : fromB64u(computer.hostId);
+ const bucket = bytes === null || bytes.length !== 16 ? null : await rolloutBucket(bytes);
+ if (!settings || computer.blocked) return { admitted: false, bucket };
+ return {
+ admitted: settings.allowInstallations.has(computer.installationId) || (bucket !== null && bucket < settings.rolloutPercent),
+ bucket,
+ };
+}
+
+export interface RelayStanding {
+ /** `relayAdmits`: the relay would carry it. */
+ serves: boolean;
+ bucket: number | null;
+ /** It also holds a relay token from the last two days: the relay is what it is using. */
+ proven: boolean;
+}
+
+/** `relayAdmits` for one installation, making its host id if it has none. A database that cannot answer (a Worker
+ * ahead of migration 0012) reads as served and unproven, which is what a relay-capable desktop got before. */
+export async function relayStanding(env: Env, installationId: string, now = Date.now()): Promise<RelayStanding> {
+ const settings = await readRelaySettings(env);
+ if (!settings) return { serves: false, bucket: null, proven: false };
+ let host: { hostId: string; blocked: boolean };
+ try {
+ host = await hostIdFor(env, installationId);
+ } catch {
+ return { serves: true, bucket: null, proven: false };
+ }
+ const { admitted, bucket } = await relayAdmits(settings, { installationId, hostId: host.hostId, blocked: host.blocked });
+ if (!admitted) return { serves: false, bucket, proven: false };
+ const adoption = await env.DB.prepare("SELECT token_at FROM relay_adoption WHERE installation_id = ?")
+ .bind(installationId).first<{ token_at: number | null }>().catch(() => null);
+ return { serves: true, bucket, proven: (adoption?.token_at ?? 0) >= now - RELAY_FRESH_MS };
+}
+
export async function issueRelayToken(request: Request, env: Env): Promise<Response> {
const installation = await requireInstallation(request, env);
const parsed = requestSchema.safeParse(await readBoundedJSON(request).catch(() => null));
if (!parsed.success) throw new HTTPError(400, "invalid_request");
const now = Date.now();
+ // The one request every relay-capable desktop makes each hour: it keeps the stored release current, so a desktop
+ // that updated itself is never judged by the version it registered with.
+ if (parsed.data.appVersion !== installation.app_version) {
+ await recordReportedAppVersion(env, installation.installation_id, parsed.data.appVersion).catch(() => undefined);
+ }
const [limited] = await env.DB.batch([limitStatement(env, installation.installation_id, now)]);
if (limited?.meta.changes === 0) {
const response = errorResponse(429, "rate_limited");
@@ -274,6 +337,7 @@ export async function issueRelayToken(request: Request, env: Env): Promise<Respo
now,
});
if (!counted) return relaySchemaMissing();
+ await recordLegacyClear(env, { installationId: installation.installation_id, legacy: parsed.data.devices.legacy, now });
if (!included) return unavailable();
const iat = Math.floor(now / 1000);
const token = await mintRelayToken({ kid: settings.kid, hid: hostId, iid: installation.installation_id, iat, exp: iat + RELAY_TOKEN_TTL_S }, settings.signingKey);
diff --git a/cloudflare/control-plane/src/tunnel-capacity.ts b/cloudflare/control-plane/src/tunnel-capacity.ts
index 656b52d1a4..5cf18af7e7 100644
--- a/cloudflare/control-plane/src/tunnel-capacity.ts
+++ b/cloudflare/control-plane/src/tunnel-capacity.ts
@@ -41,6 +41,17 @@ const MANAGED_TUNNEL_NAME = /^omb-c-[0-9a-f]{32}$/;
const CAPACITY_HEALTH_CACHE_SECONDS = 120;
const CAPACITY_HEALTH_CACHE = "healthz-capacity";
// Never routed. Bump the version when AccountSnapshot changes: copies outlive deploys.
+const DAY_MS = 24 * 60 * 60 * 1_000;
+/** Three cron runs: a pass missing a page for longer starts over. */
+const PREVIEW_PASS_GAP_MS = 15 * 60 * 1_000;
+/** /healthz reads the dry-run total at most this often per isolate. */
+const PREVIEW_MEMO_MS = 5 * 60 * 1_000;
+let previewMemo: { at: number; key: string; value: JSONValue | null } | null = null;
+
+/** Test-only. */
+export function forgetReclaimPreview(): void {
+ previewMemo = null;
+}
const CAPACITY_HEALTH_CACHE_PATH = "/__internal/healthz-capacity-row/v2";
interface ScanEndpointRow {
@@ -295,6 +306,80 @@ function capacityAlert(
}));
}
+/** Adds this page to the account's dry-run pass; the last page closes the
+ * pass and publishes its total. A changed threshold starts over, so a total
+ * never mixes two thresholds. Without migration 0015 nothing is kept. */
+async function recordReclaimPreview(
+ env: Env,
+ config: ControlPlaneConfig,
+ account: EndpointAccount,
+ page: number,
+ lastPage: boolean,
+ eligible: number,
+ now: number,
+): Promise<void> {
+ // Off: nothing is written. A row left from an earlier preview is ignored.
+ const previewMs = config.capacity.reclaimPreviewMs;
+ if (previewMs === null) return;
+ const days = previewMs / DAY_MS;
+ try {
+ const row = await env.DB.prepare(
+ "SELECT days, running, eligible, completed_at, updated_at FROM managed_endpoint_reclaim_preview WHERE provider_account = ?",
+ ).bind(account.accountId).first<{ completed_at: number | null; days: number; eligible: number | null; running: number | null; updated_at: number }>();
+ // A pass counts only from its first page, at one threshold throughout,
+ // with no gap: a running total last touched before the previous cron run
+ // or two belongs to a preview that was switched off part-way.
+ const inPass = page === 1
+ || (row !== null && row.days === days && row.running !== null && row.updated_at >= now - PREVIEW_PASS_GAP_MS);
+ const sameDays = row !== null && row.days === days;
+ const running = inPass ? (page === 1 ? 0 : row?.running ?? 0) + eligible : null;
+ const finished = lastPage && running !== null;
+ await env.DB.prepare(
+ `INSERT INTO managed_endpoint_reclaim_preview (provider_account, days, running, eligible, completed_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?)
+ ON CONFLICT(provider_account) DO UPDATE SET
+ days = excluded.days, running = excluded.running, eligible = excluded.eligible,
+ completed_at = excluded.completed_at, updated_at = excluded.updated_at`,
+ ).bind(
+ account.accountId,
+ days,
+ lastPage ? null : running,
+ finished ? running : sameDays ? row.eligible : null,
+ finished ? now : sameDays ? row.completed_at : null,
+ now,
+ ).run();
+ } catch {
+ // The table is missing: no dry run until the migration is applied.
+ }
+}
+
+/** What a full pass would reclaim at the preview threshold, summed over the
+ * accounts: null until every account has finished a pass at it. */
+async function reclaimPreview(env: Env, config: ControlPlaneConfig, now: number): Promise<JSONValue | null> {
+ const previewMs = config.capacity.reclaimPreviewMs;
+ if (previewMs === null) return null;
+ const days = previewMs / DAY_MS;
+ const key = `${days}:${accountIds(config).join(",")}`;
+ if (previewMemo && previewMemo.key === key && now - previewMemo.at < PREVIEW_MEMO_MS) return previewMemo.value;
+ const value = await readReclaimPreview(env, config, days);
+ previewMemo = { at: now, key, value };
+ return value;
+}
+
+async function readReclaimPreview(env: Env, config: ControlPlaneConfig, days: number): Promise<JSONValue | null> {
+ const found = await env.DB.prepare(
+ `SELECT provider_account, eligible FROM managed_endpoint_reclaim_preview
+ WHERE days = ? AND provider_account IN (SELECT value FROM json_each(?))`,
+ ).bind(days, JSON.stringify(accountIds(config))).all<{ eligible: number | null; provider_account: string }>()
+ .then((result) => result.results, () => null);
+ if (found === null) return null;
+ const complete = found.length === config.endpointAccounts.length && found.every((row) => row.eligible !== null);
+ return {
+ offlineDays: days,
+ eligible: complete ? found.reduce((total, row) => total + (row.eligible ?? 0), 0) : null,
+ };
+}
+
/**
* One bounded step of one account's tunnel scan: a single provider page, the
* shared reclaim-mark budget, one zone record count, and one snapshot.
@@ -362,6 +447,12 @@ async function scanAccount(
const policy = idlePolicy(config);
const idle: Record<IdleReason, number> = { never_connected: 0, offline: 0 };
+ // The dry run: the same rules at OMB_TUNNEL_RECLAIM_PREVIEW_DAYS, counted
+ // before anything is marked and never acted on.
+ const previewPolicy = config.capacity.reclaimPreviewMs === null
+ ? null
+ : { ...policy, offlineMs: config.capacity.reclaimPreviewMs };
+ let previewEligible = 0;
let unmatched = 0;
let eligible = 0;
let marked = 0;
@@ -373,6 +464,13 @@ async function scanAccount(
unmatched += 1;
continue;
}
+ const previewReason = previewPolicy ? idleTunnelReason(tunnel.activity, now, previewPolicy) : null;
+ if (
+ previewPolicy && previewReason
+ && await reclaimEligible(env, account, row, tunnel.id, previewReason, previewPolicy, now)
+ ) {
+ previewEligible += 1;
+ }
const reason = idleTunnelReason(tunnel.activity, now, policy);
if (!reason) continue;
idle[reason] += 1;
@@ -427,6 +525,8 @@ async function scanAccount(
updated_at = excluded.updated_at`,
).bind(account.accountId, nextPage, tunnelCount, dnsRecordCount, reclaimPending, dormantEndpoints, now, now).run();
+ await recordReclaimPreview(env, config, account, page, lastPage, previewEligible, now);
+
capacityAlert(requestId, account, "tunnels", tunnelCount, account.tunnelLimit);
capacityAlert(requestId, account, "dns_records", dnsRecordCount, account.dnsRecordLimit);
@@ -650,6 +750,8 @@ export async function capacityHealth(
): Promise<JSONValue> {
const pool = poolHealth(config, await cachedSnapshots(env, config, ctx), now);
const only = pool.accounts.length === 1 ? pool.accounts[0] : undefined;
+ const dryRun = await reclaimPreview(env, config, now);
+ const preview: Record<string, JSONValue> = dryRun === null ? {} : { preview: dryRun };
if (only) {
return {
status: only.status,
@@ -657,7 +759,7 @@ export async function capacityHealth(
tunnels: { used: only.snapshot.tunnel_count, limit: only.account.tunnelLimit },
dnsRecords: { used: only.snapshot.dns_record_count, limit: only.account.dnsRecordLimit },
providerRejectedAt: only.rejected ? only.snapshot.capacity_rejected_at : null,
- reclaim: { mode: config.capacity.reclaimMode, pending: only.snapshot.reclaim_pending },
+ reclaim: { mode: config.capacity.reclaimMode, pending: only.snapshot.reclaim_pending, ...preview },
};
}
const { open } = pool;
@@ -683,6 +785,7 @@ export async function capacityHealth(
reclaim: {
mode: config.capacity.reclaimMode,
pending: open.reduce((total, each) => total + each.snapshot.reclaim_pending, 0),
+ ...preview,
},
accounts: pool.accounts.map((each) => ({
hostSuffix: each.account.companionHostSuffix,
diff --git a/cloudflare/control-plane/src/tunnel-release.ts b/cloudflare/control-plane/src/tunnel-release.ts
new file mode 100644
index 0000000000..6978cb49e5
--- /dev/null
+++ b/cloudflare/control-plane/src/tunnel-release.ts
@@ -0,0 +1,321 @@
+// Giving tunnels back once the relay has replaced them, and the version
+// cutoffs that clear what is left. Nothing here deletes a provider resource:
+// a release only marks a ready row 'deleting', and the cleanup sweep removes
+// it through the same ownership-verified path as an owner's DELETE. The row
+// and its hostname stay, so a computer the relay later cannot serve gets the
+// same address back by provisioning again.
+import type { ControlPlaneConfig } from "./config";
+import { ACTED_ON_ENDPOINT_SQL, actedOnAccounts, appVersionAtLeast } from "./endpoint-accounts";
+import type { JSONValue } from "./http";
+import { readRelaySettings, RELAY_FRESH_MS, relayAdmits } from "./relay";
+
+const DAY_MS = 24 * 60 * 60 * 1_000;
+const VERSION = /^[0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,6}$/;
+/** Three days: longer than a weekend away, so a phone that still dials the
+ * tunnel has had working days to show up as an old phone and stop the wait. */
+export const DEFAULT_RELEASE_DAYS = 3;
+/** A computer called the control plane this recently, so what is stored about
+ * it is current: a desktop with remote access on checks in every few minutes,
+ * and a relay-capable one reports its release with each hourly relay token. */
+export const SEEN_FRESH_MS = 2 * DAY_MS;
+/** Release marks per cron run, all reasons together: with the cleanup sweep's
+ * 20 rows a run, a wave never outgrows what cleanup removes. */
+export const RELEASE_MARK_LIMIT = 20;
+/** Rows read per run before a percentage is applied. */
+const PROVEN_SCAN_LIMIT = 5_000;
+
+export type ReleaseReason = "legacy_cutoff" | "min_version" | "relay_proven";
+
+export interface TunnelPolicy {
+ /** RELAY_CAPABLE_MIN_VERSION: the first desktop release that reaches phones through the relay. */
+ relayMinVersion: string | null;
+ /** RELAY_TUNNEL_RELEASE_PERCENT: the share of computers whose tunnel is released once proven on the relay. */
+ releasePercent: number;
+ /** RELAY_TUNNEL_RELEASE_DAYS. */
+ releaseMs: number;
+ /** TUNNEL_MIN_APP_VERSION: a desktop below it neither gets nor keeps a tunnel. */
+ minAppVersion: string | null;
+ /** TUNNEL_REASON_MIN_VERSION: the first desktop release that reads `tunnel` on 409 relay_capable and keeps
+ * asking afterwards. Only from it is a full account answered with relay_capable instead of 503. */
+ tunnelReasonMinVersion: string | null;
+ /** TUNNEL_LEGACY_PHONE_CUTOFF_PERCENT: the share of relay-served computers that give up their tunnel whatever
+ * phones they have, so an old phone app no longer holds one. */
+ legacyCutoffPercent: number;
+}
+
+function version(value: unknown): string | null {
+ return typeof value === "string" && VERSION.test(value.trim()) ? value.trim() : null;
+}
+
+function integer(value: unknown, fallback: number, minimum: number, maximum: number): number {
+ const parsed = typeof value === "string" && /^[0-9]{1,3}$/.test(value.trim()) ? Number(value.trim()) : Number.NaN;
+ return Number.isInteger(parsed) && parsed >= minimum && parsed <= maximum ? parsed : fallback;
+}
+
+/** Every switch is off unless set, and an invalid value reads as off. */
+export function readTunnelPolicy(env: Env): TunnelPolicy {
+ const vars = env as unknown as Partial<Record<string, unknown>>;
+ const relayMinVersion = version(vars.RELAY_CAPABLE_MIN_VERSION);
+ return {
+ relayMinVersion,
+ releasePercent: relayMinVersion === null ? 0 : integer(vars.RELAY_TUNNEL_RELEASE_PERCENT, 0, 0, 100),
+ releaseMs: integer(vars.RELAY_TUNNEL_RELEASE_DAYS, DEFAULT_RELEASE_DAYS, 1, 90) * DAY_MS,
+ minAppVersion: version(vars.TUNNEL_MIN_APP_VERSION),
+ tunnelReasonMinVersion: version(vars.TUNNEL_REASON_MIN_VERSION),
+ legacyCutoffPercent: relayMinVersion === null ? 0 : integer(vars.TUNNEL_LEGACY_PHONE_CUTOFF_PERCENT, 0, 0, 100),
+ };
+}
+
+/** A missing or unreadable version is below every minimum. */
+export function belowMinimum(policy: TunnelPolicy, appVersion: string | null): boolean {
+ return policy.minAppVersion !== null && !appVersionAtLeast(appVersion, policy.minAppVersion);
+}
+
+export function readsTunnelReason(policy: TunnelPolicy, appVersion: string | null): boolean {
+ return policy.tunnelReasonMinVersion !== null && appVersionAtLeast(appVersion, policy.tunnelReasonMinVersion);
+}
+
+export function relayCapableVersion(policy: TunnelPolicy, appVersion: string | null): boolean {
+ return policy.relayMinVersion !== null && appVersionAtLeast(appVersion, policy.relayMinVersion);
+}
+
+// A ready tunnel of an active installation, in an account this Worker acts on.
+const HELD_TUNNEL_SQL = `e.status = 'ready'
+ AND e.tunnel_id IS NOT NULL
+ AND i.revoked_at IS NULL
+ AND ${ACTED_ON_ENDPOINT_SQL}`;
+
+/** The relay gave this computer a token lately. */
+const RELAY_SERVED_SQL = "a.token_at IS NOT NULL AND a.token_at >= ?";
+
+/** Every paired phone has used the encrypted connection (a phone that has
+ * never dials the tunnel again), none is an old phone, and that has held for
+ * the whole wait. Binds: fresh cutoff twice, then the wait cutoff. */
+const RELAY_PROVEN_SQL = `${RELAY_SERVED_SQL}
+ AND a.updated_at >= ?
+ AND a.legacy_devices = 0
+ AND a.e2e_devices > 0
+ AND a.legacy_clear_at IS NOT NULL
+ AND a.legacy_clear_at <= ?`;
+
+/** The stored release can be trusted as current: the computer called lately,
+ * and had it updated to a relay-capable release it would have said so with
+ * its relay token. A computer that has been off is left to idle reclaim. */
+const SEEN_LATELY_SQL = "i.last_seen_at IS NOT NULL AND i.last_seen_at >= ?";
+
+interface VersionRow {
+ /** Of `tunnels`, those whose computer called lately. */
+ seen: number;
+ proven: number;
+ relay_served: number;
+ tunnels: number;
+ version: string;
+}
+
+/** Held tunnels by desktop version, with how many of each the relay serves
+ * and how many are proven on it. Throws without migration 0015. */
+async function heldByVersion(env: Env, config: ControlPlaneConfig, policy: TunnelPolicy, now: number): Promise<VersionRow[]> {
+ const fresh = now - RELAY_FRESH_MS;
+ const found = await env.DB.prepare(
+ `SELECT COALESCE(i.app_version, '') AS version,
+ COUNT(*) AS tunnels,
+ COALESCE(SUM(CASE WHEN ${SEEN_LATELY_SQL} THEN 1 ELSE 0 END), 0) AS seen,
+ COALESCE(SUM(CASE WHEN ${RELAY_SERVED_SQL} THEN 1 ELSE 0 END), 0) AS relay_served,
+ COALESCE(SUM(CASE WHEN ${RELAY_PROVEN_SQL} THEN 1 ELSE 0 END), 0) AS proven
+ FROM installation_endpoints e
+ JOIN installations i ON i.id = e.installation_id
+ LEFT JOIN relay_adoption a ON a.installation_id = e.installation_id
+ WHERE ${HELD_TUNNEL_SQL}
+ GROUP BY 1`,
+ ).bind(now - SEEN_FRESH_MS, fresh, fresh, fresh, now - policy.releaseMs, actedOnAccounts(config)).all<VersionRow>();
+ return found.results;
+}
+
+export interface ReleasePreview {
+ /** Held tunnels of desktops seen in the last two days below
+ * TUNNEL_MIN_APP_VERSION, or, while that is unset, below
+ * RELAY_CAPABLE_MIN_VERSION: what a version cutoff would clear. */
+ belowMinVersion: number;
+ /** Held tunnels of relay-served desktops that are not yet proven: what the
+ * old-phone cutoff would clear beyond the release. */
+ legacyPhones: number;
+ /** Held tunnels proven on the relay: what the release clears at 100%. */
+ relayProven: number;
+}
+
+function preview(rows: readonly VersionRow[], policy: TunnelPolicy): ReleasePreview {
+ const cutoff = policy.minAppVersion ?? policy.relayMinVersion;
+ const totals: ReleasePreview = { belowMinVersion: 0, legacyPhones: 0, relayProven: 0 };
+ for (const row of rows) {
+ if (cutoff !== null && !appVersionAtLeast(row.version, cutoff)) {
+ totals.belowMinVersion += row.seen;
+ continue;
+ }
+ if (!relayCapableVersion(policy, row.version)) continue;
+ totals.relayProven += row.proven;
+ totals.legacyPhones += row.relay_served - row.proven;
+ }
+ return totals;
+}
+
+const HEALTH_MEMO_MS = 5 * 60 * 1_000;
+let healthMemo: { at: number; value: JSONValue | null } | null = null;
+
+/** Test-only. */
+export function forgetTunnelRelease(): void {
+ healthMemo = null;
+}
+
+/** Counts only, for /healthz: the switches as set, and what each would clear
+ * now, so the numbers can be read before a switch is turned. Read at most
+ * every five minutes per isolate; left out without migration 0015. */
+export async function tunnelReleaseHealth(env: Env, config: ControlPlaneConfig, now = Date.now()): Promise<JSONValue | null> {
+ if (healthMemo && now - healthMemo.at < HEALTH_MEMO_MS) return healthMemo.value;
+ const policy = readTunnelPolicy(env);
+ const value = await heldByVersion(env, config, policy, now).then((rows): JSONValue => {
+ const counts = preview(rows, policy);
+ return {
+ relayProven: { percent: policy.releasePercent, days: policy.releaseMs / DAY_MS, eligible: counts.relayProven },
+ legacyPhoneCutoff: { percent: policy.legacyCutoffPercent, eligible: counts.legacyPhones },
+ minAppVersion: { on: policy.minAppVersion !== null, eligible: counts.belowMinVersion },
+ };
+ }, () => null);
+ healthMemo = { at: now, value };
+ return value;
+}
+
+interface Candidate {
+ installation_id: string;
+ relay_host_id: string | null;
+}
+
+export interface ReleaseSummary {
+ marked: Record<ReleaseReason, number>;
+ preview: ReleasePreview;
+}
+
+/** `guard` is re-checked inside the UPDATE, so a report that lands between
+ * the read and the write (an old phone appears, the desktop updates) wins. */
+async function mark(env: Env, config: ControlPlaneConfig, installationId: string, guard: string, bindings: unknown[], now: number): Promise<boolean> {
+ const result = await env.DB.prepare(
+ `UPDATE installation_endpoints
+ SET status = 'deleting',
+ delete_requested_at = ?,
+ reclaim_requested_at = NULL,
+ cleanup_attempts = 0,
+ last_cleanup_attempt_at = NULL,
+ last_error_code = NULL,
+ updated_at = ?
+ WHERE installation_id = ?
+ AND (lease_expires_at IS NULL OR lease_expires_at <= ?)
+ AND EXISTS (
+ SELECT 1
+ FROM installation_endpoints e
+ JOIN installations i ON i.id = e.installation_id
+ LEFT JOIN relay_adoption a ON a.installation_id = e.installation_id
+ WHERE e.installation_id = installation_endpoints.installation_id
+ AND ${HELD_TUNNEL_SQL}
+ AND ${guard}
+ )`,
+ ).bind(now, now, installationId, now, actedOnAccounts(config), ...bindings).run();
+ return result.meta.changes > 0;
+}
+
+const VERSION_IN_SQL = "COALESCE(i.app_version, '') IN (SELECT value FROM json_each(?))";
+
+/**
+ * One bounded step, before the cleanup sweep. In order: desktops below the
+ * minimum version, then (with the old-phone cutoff on) every computer the
+ * relay serves, then computers proven on the relay inside the release
+ * percentage. With every switch off it only reads the counts it logs.
+ */
+export async function releaseTunnels(
+ env: Env,
+ config: ControlPlaneConfig,
+ requestId: string,
+ now = Date.now(),
+): Promise<ReleaseSummary | null> {
+ const policy = readTunnelPolicy(env);
+ let rows: VersionRow[];
+ try {
+ rows = await heldByVersion(env, config, policy, now);
+ } catch {
+ // Migration 0015 is not applied yet: nothing is released.
+ return null;
+ }
+ const summary: ReleaseSummary = {
+ marked: { legacy_cutoff: 0, min_version: 0, relay_proven: 0 },
+ preview: preview(rows, policy),
+ };
+ // Never more waiting for cleanup than one sweep removes: while the sweep is
+ // failing or rate-limited its queue stays full and nothing more is marked,
+ // so no owner is left with a row it cannot take back.
+ const queued = await env.DB.prepare(
+ `SELECT COUNT(*) AS count FROM installation_endpoints e WHERE e.status = 'deleting' AND ${ACTED_ON_ENDPOINT_SQL}`,
+ ).bind(actedOnAccounts(config)).first<{ count: number }>();
+ let budget = Math.max(0, Math.min(RELEASE_MARK_LIMIT, config.capacity.cleanupSweepLimit) - (queued?.count ?? 0));
+ const fresh = now - RELAY_FRESH_MS;
+ const versions = rows.map((row) => row.version);
+ const below = JSON.stringify(versions.filter((each) => belowMinimum(policy, each)));
+ const capable = JSON.stringify(versions.filter((each) => relayCapableVersion(policy, each) && !belowMinimum(policy, each)));
+ // With the relay switched off, or a computer outside its rollout, nobody is
+ // moved onto it: the same `relayAdmits` provisioning answers by, so a tunnel
+ // provisioning would hand back is never marked.
+ const relay = await readRelaySettings(env);
+ const inside = (percent: number) => async (row: Candidate) => {
+ const { admitted, bucket } = await relayAdmits(relay, { installationId: row.installation_id, hostId: row.relay_host_id, blocked: false });
+ return admitted && bucket !== null && bucket < percent;
+ };
+
+ const run = async (reason: ReleaseReason, guard: string, bindings: unknown[], admit?: (row: Candidate) => Promise<boolean>) => {
+ if (budget <= 0) return;
+ const found = await env.DB.prepare(
+ `SELECT e.installation_id, i.relay_host_id
+ FROM installation_endpoints e
+ JOIN installations i ON i.id = e.installation_id
+ LEFT JOIN relay_adoption a ON a.installation_id = e.installation_id
+ WHERE ${HELD_TUNNEL_SQL}
+ AND (e.lease_expires_at IS NULL OR e.lease_expires_at <= ?)
+ AND ${guard}
+ ORDER BY e.updated_at ASC, e.installation_id ASC
+ LIMIT ?`,
+ ).bind(actedOnAccounts(config), now, ...bindings, admit ? PROVEN_SCAN_LIMIT : budget)
+ .all<Candidate>();
+ for (const row of found.results) {
+ if (budget <= 0) break;
+ if (admit && !(await admit(row))) continue;
+ if (await mark(env, config, row.installation_id, guard, bindings, now)) {
+ budget -= 1;
+ summary.marked[reason] += 1;
+ }
+ }
+ };
+
+ if (policy.minAppVersion !== null) {
+ await run("min_version", `${VERSION_IN_SQL} AND ${SEEN_LATELY_SQL}`, [below, now - SEEN_FRESH_MS]);
+ }
+ const servedGuard = `${VERSION_IN_SQL} AND i.relay_blocked_at IS NULL`;
+ if (relay && policy.legacyCutoffPercent > 0) {
+ await run("legacy_cutoff", `${servedGuard} AND ${RELAY_SERVED_SQL}`, [capable, fresh], inside(policy.legacyCutoffPercent));
+ }
+ if (relay && policy.releasePercent > 0) {
+ await run(
+ "relay_proven",
+ `${servedGuard} AND ${RELAY_PROVEN_SQL}`,
+ [capable, fresh, fresh, now - policy.releaseMs],
+ inside(policy.releasePercent),
+ );
+ }
+
+ console.log(JSON.stringify({
+ message: "managed endpoint tunnel release",
+ requestId,
+ releasePercent: policy.releasePercent,
+ releaseDays: policy.releaseMs / DAY_MS,
+ legacyCutoffPercent: policy.legacyCutoffPercent,
+ minAppVersion: policy.minAppVersion !== null,
+ marked: summary.marked,
+ eligible: summary.preview,
+ }));
+ return summary;
+}
diff --git a/cloudflare/control-plane/test/control-plane.test.ts b/cloudflare/control-plane/test/control-plane.test.ts
index 07606bcc5b..594f140e04 100644
--- a/cloudflare/control-plane/test/control-plane.test.ts
+++ b/cloudflare/control-plane/test/control-plane.test.ts
@@ -295,6 +295,11 @@ describe("control-plane migrations and health", () => {
reclaim: { mode: "on", pending: 0 },
},
relayAdoption: { e2eDevices: 0, legacyDevices: 0, installs: 0 },
+ tunnelRelease: {
+ relayProven: { percent: 0, days: 3, eligible: 0 },
+ legacyPhoneCutoff: { percent: 0, eligible: 0 },
+ minAppVersion: { on: false, eligible: 0 },
+ },
});
expect(response.headers.get("cache-control")).toBe("no-store");
expect(response.headers.get("access-control-allow-origin")).toBeNull();
@@ -354,6 +359,7 @@ describe("control-plane migrations and health", () => {
dnsRecordLimit: 1000,
offlineReclaimMs: 21 * 24 * 60 * 60 * 1_000,
reclaimMode: "observe",
+ reclaimPreviewMs: null,
tunnelLimit: 1000,
});
const withVars = (vars: Record<string, string>) => ({ ...base, ...vars }) as unknown as Env;
@@ -368,7 +374,12 @@ describe("control-plane migrations and health", () => {
reclaimMode: "observe",
tunnelLimit: 2500,
});
- expect(readConfig(withVars({ OMB_TUNNEL_OFFLINE_RECLAIM_DAYS: "2" })).capacity.offlineReclaimMs).toBe(21 * 24 * 60 * 60 * 1_000);
+ expect(readConfig(withVars({ OMB_TUNNEL_OFFLINE_RECLAIM_DAYS: "0" })).capacity.offlineReclaimMs).toBe(21 * 24 * 60 * 60 * 1_000);
+ expect(readConfig(withVars({ OMB_TUNNEL_OFFLINE_RECLAIM_DAYS: "1" })).capacity.offlineReclaimMs).toBe(24 * 60 * 60 * 1_000);
+ expect(readConfig(withVars({ OMB_TUNNEL_RECLAIM_PREVIEW_DAYS: "1" })).capacity.reclaimPreviewMs).toBe(24 * 60 * 60 * 1_000);
+ for (const invalid of ["", "0", "366", "soon"]) {
+ expect(readConfig(withVars({ OMB_TUNNEL_RECLAIM_PREVIEW_DAYS: invalid })).capacity.reclaimPreviewMs).toBeNull();
+ }
expect(readConfig(withVars({ OMB_TUNNEL_OFFLINE_RECLAIM_DAYS: "3" })).capacity.offlineReclaimMs).toBe(3 * 24 * 60 * 60 * 1_000);
expect(readConfig(withVars({ OMB_CLEANUP_SWEEP_LIMIT: "51" })).capacity.cleanupSweepLimit).toBe(20);
expect(readConfig(withVars({ OMB_TUNNEL_LIMIT: "1e3" })).capacity.tunnelLimit).toBe(1000);
@@ -394,6 +405,12 @@ describe("control-plane migrations and health", () => {
OMB_TUNNEL_RECLAIM: env.OMB_TUNNEL_RECLAIM,
OMB_TUNNEL_OFFLINE_RECLAIM_DAYS: env.OMB_TUNNEL_OFFLINE_RECLAIM_DAYS,
OMB_CLEANUP_SWEEP_LIMIT: env.OMB_CLEANUP_SWEEP_LIMIT,
+ OMB_TUNNEL_RECLAIM_PREVIEW_DAYS: env.OMB_TUNNEL_RECLAIM_PREVIEW_DAYS,
+ RELAY_TUNNEL_RELEASE_PERCENT: env.RELAY_TUNNEL_RELEASE_PERCENT,
+ RELAY_TUNNEL_RELEASE_DAYS: env.RELAY_TUNNEL_RELEASE_DAYS,
+ TUNNEL_LEGACY_PHONE_CUTOFF_PERCENT: env.TUNNEL_LEGACY_PHONE_CUTOFF_PERCENT,
+ TUNNEL_MIN_APP_VERSION: env.TUNNEL_MIN_APP_VERSION,
+ TUNNEL_REASON_MIN_VERSION: env.TUNNEL_REASON_MIN_VERSION,
RELAY_NODES: env.RELAY_NODES,
RELAY_NODES_AMERICAS: env.RELAY_NODES_AMERICAS,
RELAY_TOKEN_KID: env.RELAY_TOKEN_KID,
diff --git a/cloudflare/control-plane/test/managed-endpoints.test.ts b/cloudflare/control-plane/test/managed-endpoints.test.ts
index 88795c4b6d..6251bd2ddd 100644
--- a/cloudflare/control-plane/test/managed-endpoints.test.ts
+++ b/cloudflare/control-plane/test/managed-endpoints.test.ts
@@ -8,6 +8,8 @@ import { readConfig } from "../src/config";
import { cleanupEndpointRow, sweepManagedEndpointCleanup } from "../src/endpoints";
import { createWorker } from "../src/index";
import { forgetCachedCapacity } from "../src/tunnel-capacity";
+import { rolloutBucket } from "../src/relay";
+import { forgetTunnelRelease } from "../src/tunnel-release";
const BASE_URL = "https://auth.openmausbot.test";
const CONNECTOR_TOKEN = "eyJhbGciOiJIUzI1NiJ9.test-only-connector-token.signature";
@@ -3371,6 +3373,11 @@ describe("managed endpoints in several Cloudflare accounts", () => {
],
},
relayAdoption: { e2eDevices: 0, legacyDevices: 0, installs: 0 },
+ tunnelRelease: {
+ relayProven: { percent: 0, days: 3, eligible: 0 },
+ legacyPhoneCutoff: { percent: 0, eligible: 0 },
+ minAppVersion: { on: false, eligible: 0 },
+ },
});
for (const secret of [
PRIMARY_ACCOUNT,
@@ -3621,3 +3628,433 @@ describe("managed endpoints in several Cloudflare accounts", () => {
]);
});
});
+
+const RELAY_SEED = btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32))))
+ .replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+
+/** The relay on for every computer, and 0.1.145 the first desktop that uses it. */
+function relayVars(extra: Record<string, string> = {}): Record<string, string> {
+ return {
+ RELAY_TOKEN_SIGNING_KEY: RELAY_SEED,
+ RELAY_ROLLOUT_PERCENT: "100",
+ RELAY_DISABLED: "0",
+ RELAY_CAPABLE_MIN_VERSION: "0.1.145",
+ ...extra,
+ };
+}
+
+const relayEnv = (extra: Record<string, string> = {}) => ({ ...env, ...relayVars(extra) }) as unknown as Env;
+
+/** A computer on `appVersion` that holds a tunnel, made while an old phone needed one. */
+async function computerWithTunnel(
+ worker: TestWorker,
+ cloudflare: FakeCloudflare,
+ accountToken: string,
+ clientInstanceId: string,
+ appVersion = "0.1.151",
+) {
+ const installation = await createInstallation(worker, accountToken, clientInstanceId, appVersion);
+ const response = await call(worker, "/v1/installations/self/endpoint", {
+ body: { appVersion, legacyDevices: 1 },
+ env: relayEnv(),
+ method: "POST",
+ token: installation.credential,
+ });
+ expect(response.status).toBe(200);
+ const id = installation.installation.id;
+ const state = await endpointState(id);
+ expect(cloudflare.tunnels.has(state.tunnel_name)).toBe(true);
+ return { appVersion, credential: installation.credential, id, state };
+}
+
+type Computer = Awaited<ReturnType<typeof computerWithTunnel>>;
+
+/** The desktop's hourly relay-token request, which carries its phone counts. */
+async function reportPhones(worker: TestWorker, computer: Computer, devices: { e2e: number; legacy: number }, vars = relayVars()) {
+ const response = await call(worker, "/v1/installations/self/relay-token", {
+ body: { appVersion: computer.appVersion, devices },
+ env: { ...env, ...vars } as unknown as Env,
+ method: "POST",
+ token: computer.credential,
+ });
+ return response.status;
+}
+
+async function clearSince(installationId: string, daysAgo: number): Promise<void> {
+ await env.DB.prepare("UPDATE relay_adoption SET legacy_clear_at = ? WHERE installation_id = ?")
+ .bind(Date.now() - daysAgo * DAY_MS, installationId).run();
+}
+
+const askForTunnel = (worker: TestWorker, computer: Computer, legacyDevices: number, vars = relayVars()) =>
+ call(worker, "/v1/installations/self/endpoint", {
+ body: { appVersion: computer.appVersion, legacyDevices },
+ env: { ...env, ...vars } as unknown as Env,
+ method: "POST",
+ token: computer.credential,
+ });
+
+interface ReleaseHealth {
+ legacyPhoneCutoff: { eligible: number; percent: number };
+ minAppVersion: { eligible: number; on: boolean };
+ relayProven: { days: number; eligible: number; percent: number };
+}
+
+async function releaseHealth(worker: TestWorker, vars = relayVars()): Promise<ReleaseHealth> {
+ forgetTunnelRelease();
+ const health = await call(worker, "/healthz", { env: { ...env, ...vars } as unknown as Env });
+ return (await health.json<{ tunnelRelease: ReleaseHealth }>()).tunnelRelease;
+}
+
+describe("the relay first, a tunnel only when it cannot serve", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ forgetTunnelRelease();
+ });
+
+ it("gives a returning computer with no old phone the relay, and a tunnel back when the relay is off", async () => {
+ const cloudflare = new FakeCloudflare();
+ const worker = createWorker(cloudflare.fetch);
+ const owner = await signIn(worker, "[email protected]");
+ const computer = await computerWithTunnel(worker, cloudflare, owner.token, "relay-first");
+ expect((await call(worker, "/v1/installations/self/endpoint", { method: "DELETE", token: computer.credential })).status).toBe(204);
+ expect(cloudflare.tunnels.size).toBe(0);
+
+ const creates = () => cloudflare.calls.filter((entry) => entry.method === "POST" && entry.url.endsWith("/cfd_tunnel")).length;
+ const before = creates();
+ const refused = await askForTunnel(worker, computer, 0);
+ expect(refused.status).toBe(409);
+ await expect(refused.json()).resolves.toEqual({ error: "relay_capable" });
+ expect(creates()).toBe(before);
+
+ // An old phone still gets one, and so does everyone when the relay is switched off.
+ for (const vars of [relayVars({ RELAY_DISABLED: "1" }), relayVars({ RELAY_ROLLOUT_PERCENT: "0" })]) {
+ const fallback = await askForTunnel(worker, computer, 0, vars);
+ expect(fallback.status).toBe(200);
+ const body = await fallback.json<{ endpoint: { url: string } }>();
+ expect(body.endpoint.url).toBe(`https://${computer.state.hostname}`);
+ expect((await call(worker, "/v1/installations/self/endpoint", { method: "DELETE", token: computer.credential })).status).toBe(204);
+ }
+ expect((await askForTunnel(worker, computer, 1)).status).toBe(200);
+ });
+
+ it("never fails a computer that reads the reason at the tunnel limit, and keeps earlier desktops on the 503 they retry from", async () => {
+ const cloudflare = new FakeCloudflare();
+ const worker = createWorker(cloudflare.fetch);
+ const owner = await signIn(worker, "[email protected]");
+ const reads = await createInstallation(worker, owner.token, "relay-cap-reads", "0.1.152");
+ const current = await createInstallation(worker, owner.token, "relay-cap-current", "0.1.151");
+ const older = await createInstallation(worker, owner.token, "relay-cap-older", "0.1.140");
+ cloudflare.providerErrors.set("create_tunnel", 1_045);
+ vi.spyOn(console, "error").mockImplementation(() => undefined);
+ const named = { TUNNEL_REASON_MIN_VERSION: "0.1.152" };
+ const ask = (credential: string, appVersion: string, legacyDevices: number, vars = relayVars(named)) => call(worker, "/v1/installations/self/endpoint", {
+ body: { appVersion, legacyDevices },
+ env: { ...env, ...vars } as unknown as Env,
+ method: "POST",
+ token: credential,
+ });
+
+ // Cloudflare refuses the first; the second is answered from the refusal gate. Both pair over the relay.
+ for (let attempt = 0; attempt < 2; attempt += 1) {
+ const full = await ask(reads.credential, "0.1.152", 2);
+ expect(full.status).toBe(409);
+ await expect(full.json()).resolves.toEqual({ error: "relay_capable", tunnel: "full" });
+ }
+ // A release that would take the 409 as "done" and stop retrying, and one from before the relay: the 503.
+ for (const [credential, appVersion] of [[current.credential, "0.1.151"], [older.credential, "0.1.140"]] as const) {
+ const full = await ask(credential, appVersion, 2);
+ expect(full.status).toBe(503);
+ expect(full.headers.get("retry-after")).toBe("600");
+ await expect(full.json()).resolves.toEqual({ error: "endpoint_capacity" });
+ }
+ // With no old phone nothing is waited for, whatever the release.
+ expect((await ask(current.credential, "0.1.151", 0)).status).toBe(409);
+ // Until the release is named, and with the relay off, the limit is the answer.
+ for (const vars of [relayVars(), relayVars({ ...named, RELAY_DISABLED: "1" })]) {
+ const full = await ask(reads.credential, "0.1.152", 2, vars);
+ expect(full.status).toBe(503);
+ await expect(full.json()).resolves.toEqual({ error: "endpoint_capacity" });
+ }
+ });
+});
+
+describe("releasing tunnels the relay has replaced", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ forgetTunnelRelease();
+ });
+
+ it("releases a tunnel once every phone has been on the encrypted connection for the wait, and keeps one an old phone uses", async () => {
+ const cloudflare = new FakeCloudflare();
+ const worker = createWorker(cloudflare.fetch);
+ const owner = await signIn(worker, "[email protected]");
+ const proven = await computerWithTunnel(worker, cloudflare, owner.token, "release-proven");
+ const oldPhone = await computerWithTunnel(worker, cloudflare, owner.token, "release-old-phone");
+ const recent = await computerWithTunnel(worker, cloudflare, owner.token, "release-recent");
+ const noPhones = await computerWithTunnel(worker, cloudflare, owner.token, "release-no-phones");
+ const silent = await computerWithTunnel(worker, cloudflare, owner.token, "release-silent");
+ expect(await reportPhones(worker, proven, { e2e: 2, legacy: 0 })).toBe(200);
+ expect(await reportPhones(worker, oldPhone, { e2e: 1, legacy: 1 })).toBe(200);
+ expect(await reportPhones(worker, recent, { e2e: 1, legacy: 0 })).toBe(200);
+ expect(await reportPhones(worker, noPhones, { e2e: 0, legacy: 0 })).toBe(200);
+ await clearSince(proven.id, 4);
+ await clearSince(oldPhone.id, 4);
+ await clearSince(recent.id, 1);
+ await clearSince(noPhones.id, 4);
+ // An old phone on its own computer keeps the wait from starting at all.
+ const waiting = await env.DB.prepare("SELECT legacy_clear_at FROM relay_adoption WHERE installation_id = ?")
+ .bind(oldPhone.id).first<{ legacy_clear_at: number | null }>();
+ expect(waiting?.legacy_clear_at).not.toBeNull();
+ expect(await reportPhones(worker, oldPhone, { e2e: 1, legacy: 1 })).toBe(200);
+ expect(await env.DB.prepare("SELECT legacy_clear_at FROM relay_adoption WHERE installation_id = ?").bind(oldPhone.id).first())
+ .toEqual({ legacy_clear_at: null });
+
+ // Off by default: nothing is marked, and /healthz says what the switch would clear.
+ vi.spyOn(console, "log").mockImplementation(() => undefined);
+ await runScheduledCleanup(worker, relayVars());
+ expect(cloudflare.tunnels.size).toBe(5);
+ expect(await releaseHealth(worker)).toEqual({
+ relayProven: { percent: 0, days: 3, eligible: 1 },
+ legacyPhoneCutoff: { percent: 0, eligible: 3 },
+ minAppVersion: { on: false, eligible: 0 },
+ });
+
+ await runScheduledCleanup(worker, relayVars({ RELAY_TUNNEL_RELEASE_PERCENT: "100" }));
+ expect(await endpointState(proven.id)).toMatchObject({ status: "deleted", tunnel_id: null, dns_record_id: null });
+ expect(cloudflare.tunnels.has(proven.state.tunnel_name)).toBe(false);
+ for (const kept of [oldPhone, recent, noPhones, silent]) {
+ expect(await endpointState(kept.id)).toMatchObject({ status: "ready", tunnel_id: kept.state.tunnel_id });
+ }
+
+ // Still on the relay: no tunnel. An old phone paired later, or the relay failing, brings the same address back.
+ expect((await askForTunnel(worker, proven, 0)).status).toBe(409);
+ const back = await askForTunnel(worker, proven, 0, relayVars({ RELAY_DISABLED: "1" }));
+ expect(back.status).toBe(200);
+ expect((await back.json<{ endpoint: { url: string } }>()).endpoint.url).toBe(`https://${proven.state.hostname}`);
+ });
+
+ it("releases only inside the percentage, by the computer's stable place in the rollout", async () => {
+ const cloudflare = new FakeCloudflare();
+ const worker = createWorker(cloudflare.fetch);
+ const owner = await signIn(worker, "[email protected]");
+ const computer = await computerWithTunnel(worker, cloudflare, owner.token, "release-percent");
+ expect(await reportPhones(worker, computer, { e2e: 1, legacy: 0 })).toBe(200);
+ await clearSince(computer.id, 5);
+ const host = await env.DB.prepare("SELECT relay_host_id FROM installations WHERE id = ?").bind(computer.id).first<{ relay_host_id: string }>();
+ const bytes = Uint8Array.from(atob(host!.relay_host_id.replace(/-/g, "+").replace(/_/g, "/") + "=="), (char) => char.charCodeAt(0));
+ const bucket = await rolloutBucket(bytes);
+ vi.spyOn(console, "log").mockImplementation(() => undefined);
+
+ if (bucket > 0) {
+ await runScheduledCleanup(worker, relayVars({ RELAY_TUNNEL_RELEASE_PERCENT: String(bucket) }));
+ expect((await endpointState(computer.id)).status).toBe("ready");
+ }
+ // The relay switched off, or the wait made longer than it has lasted: kept.
+ await runScheduledCleanup(worker, relayVars({ RELAY_TUNNEL_RELEASE_PERCENT: "100", RELAY_DISABLED: "1" }));
+ await runScheduledCleanup(worker, relayVars({ RELAY_TUNNEL_RELEASE_PERCENT: "100", RELAY_TUNNEL_RELEASE_DAYS: "7" }));
+ expect((await endpointState(computer.id)).status).toBe("ready");
+ await runScheduledCleanup(worker, relayVars({ RELAY_TUNNEL_RELEASE_PERCENT: String(bucket + 1) }));
+ expect((await endpointState(computer.id)).status).toBe("deleted");
+ });
+
+ it("stops marking while the cleanup sweep is failing, so no queue of rows their owners cannot take back builds up", async () => {
+ const cloudflare = new FakeCloudflare();
+ const worker = createWorker(cloudflare.fetch);
+ const owner = await signIn(worker, "[email protected]");
+ const computers: Computer[] = [];
+ for (const name of ["a", "b", "c"]) {
+ const computer = await computerWithTunnel(worker, cloudflare, owner.token, `release-backlog-${name}`);
+ expect(await reportPhones(worker, computer, { e2e: 1, legacy: 0 })).toBe(200);
+ await clearSince(computer.id, 5);
+ computers.push(computer);
+ }
+ vi.spyOn(console, "log").mockImplementation(() => undefined);
+ vi.spyOn(console, "error").mockImplementation(() => undefined);
+ cloudflare.failures.add("delete_tunnel");
+ const vars = relayVars({ RELAY_TUNNEL_RELEASE_PERCENT: "100", OMB_CLEANUP_SWEEP_LIMIT: "2" });
+ const deleting = async () => (await Promise.all(computers.map((each) => endpointState(each.id)))).filter((state) => state.status === "deleting").length;
+
+ await runScheduledCleanup(worker, vars);
+ expect(await deleting()).toBe(2);
+ for (let run = 0; run < 3; run += 1) await runScheduledCleanup(worker, vars);
+ expect(await deleting()).toBe(2);
+
+ // Cleanup works again: the queue drains (after its backoff), and marking resumes.
+ cloudflare.failures.delete("delete_tunnel");
+ await env.DB.prepare("UPDATE installation_endpoints SET last_cleanup_attempt_at = 0 WHERE status = 'deleting'").run();
+ await runScheduledCleanup(worker, vars);
+ await runScheduledCleanup(worker, vars);
+ expect((await Promise.all(computers.map((each) => endpointState(each.id)))).map((state) => state.status)).toEqual(["deleted", "deleted", "deleted"]);
+ });
+
+ it("keeps the tunnel of a computer whose relay token has gone stale", async () => {
+ const cloudflare = new FakeCloudflare();
+ const worker = createWorker(cloudflare.fetch);
+ const owner = await signIn(worker, "[email protected]");
+ const computer = await computerWithTunnel(worker, cloudflare, owner.token, "release-stale");
+ expect(await reportPhones(worker, computer, { e2e: 1, legacy: 0 })).toBe(200);
+ await clearSince(computer.id, 9);
+ const stale = Date.now() - 3 * DAY_MS;
+ await env.DB.prepare("UPDATE relay_adoption SET token_at = ?1, updated_at = ?1 WHERE installation_id = ?2").bind(stale, computer.id).run();
+ vi.spyOn(console, "log").mockImplementation(() => undefined);
+ await runScheduledCleanup(worker, relayVars({ RELAY_TUNNEL_RELEASE_PERCENT: "100" }));
+ expect((await endpointState(computer.id)).status).toBe("ready");
+ });
+});
+
+describe("the cutoffs", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ forgetTunnelRelease();
+ });
+
+ it("ends tunnels for old phone apps on computers the relay serves, by percentage, and not while the relay is off", async () => {
+ const cloudflare = new FakeCloudflare();
+ const worker = createWorker(cloudflare.fetch);
+ const owner = await signIn(worker, "[email protected]");
+ const withOldPhone = await computerWithTunnel(worker, cloudflare, owner.token, "cutoff-old-phone");
+ const olderDesktop = await computerWithTunnel(worker, cloudflare, owner.token, "cutoff-older-desktop", "0.1.140");
+ expect(await reportPhones(worker, withOldPhone, { e2e: 0, legacy: 2 })).toBe(200);
+ vi.spyOn(console, "log").mockImplementation(() => undefined);
+ const on = { TUNNEL_LEGACY_PHONE_CUTOFF_PERCENT: "100" };
+
+ // A relay outage: the switch that turns the relay off also stops the cutoff.
+ await runScheduledCleanup(worker, relayVars({ ...on, RELAY_DISABLED: "1" }));
+ expect((await endpointState(withOldPhone.id)).status).toBe("ready");
+ expect((await askForTunnel(worker, withOldPhone, 2, relayVars({ ...on, RELAY_DISABLED: "1" }))).status).toBe(200);
+
+ const retired = await askForTunnel(worker, withOldPhone, 2, relayVars(on));
+ expect(retired.status).toBe(409);
+ await expect(retired.json()).resolves.toEqual({ error: "relay_capable", tunnel: "retired" });
+ await runScheduledCleanup(worker, relayVars(on));
+ expect(await endpointState(withOldPhone.id)).toMatchObject({ status: "deleted", tunnel_id: null });
+ expect(cloudflare.tunnels.has(withOldPhone.state.tunnel_name)).toBe(false);
+
+ // A current desktop the relay has never carried (no token) keeps a tunnel that works, on Retry and in the cron.
+ const neverOnRelay = await computerWithTunnel(worker, cloudflare, owner.token, "cutoff-never-on-relay");
+ const kept = await askForTunnel(worker, neverOnRelay, 1, relayVars(on));
+ expect(kept.status).toBe(200);
+ await runScheduledCleanup(worker, relayVars(on));
+ expect((await endpointState(neverOnRelay.id)).status).toBe("ready");
+ // Its token gone stale reads the same.
+ expect(await reportPhones(worker, neverOnRelay, { e2e: 0, legacy: 1 })).toBe(200);
+ await env.DB.prepare("UPDATE relay_adoption SET token_at = ? WHERE installation_id = ?").bind(Date.now() - 3 * DAY_MS, neverOnRelay.id).run();
+ expect((await askForTunnel(worker, neverOnRelay, 1, relayVars(on))).status).toBe(200);
+ await runScheduledCleanup(worker, relayVars(on));
+ expect((await endpointState(neverOnRelay.id)).status).toBe("ready");
+
+ // The rollout lowered below a computer: the cron leaves the tunnel provisioning would hand back, so nothing loops.
+ const rolledBack = await computerWithTunnel(worker, cloudflare, owner.token, "cutoff-rolled-back");
+ expect(await reportPhones(worker, rolledBack, { e2e: 0, legacy: 1 })).toBe(200);
+ const lowered = relayVars({ ...on, RELAY_ROLLOUT_PERCENT: "0" });
+ for (let round = 0; round < 2; round += 1) {
+ await runScheduledCleanup(worker, lowered);
+ expect((await endpointState(rolledBack.id)).status).toBe("ready");
+ expect((await askForTunnel(worker, rolledBack, 1, lowered)).status).toBe(200);
+ }
+ const deletesBefore = deleteURLs(cloudflare).length;
+ await runScheduledCleanup(worker, lowered);
+ expect(deleteURLs(cloudflare).length).toBe(deletesBefore);
+ // Admitted by name it is on the relay again, and inside the cutoff.
+ await runScheduledCleanup(worker, relayVars({ ...on, RELAY_ROLLOUT_PERCENT: "0", RELAY_ALLOW_INSTALLATIONS: rolledBack.id }));
+ expect((await endpointState(rolledBack.id)).status).toBe("deleted");
+
+ // A desktop from before the relay cannot use it, so this switch leaves it alone.
+ expect((await endpointState(olderDesktop.id)).status).toBe("ready");
+ expect((await askForTunnel(worker, olderDesktop, 2, relayVars(on))).status).toBe(200);
+
+ // Outside the percentage the old phone keeps its tunnel.
+ const outside = await computerWithTunnel(worker, cloudflare, owner.token, "cutoff-outside");
+ expect(await reportPhones(worker, outside, { e2e: 0, legacy: 1 })).toBe(200);
+ const host = await env.DB.prepare("SELECT relay_host_id FROM installations WHERE id = ?").bind(outside.id).first<{ relay_host_id: string }>();
+ const bucket = await rolloutBucket(Uint8Array.from(atob(host!.relay_host_id.replace(/-/g, "+").replace(/_/g, "/") + "=="), (char) => char.charCodeAt(0)));
+ if (bucket > 0) {
+ const partly = { TUNNEL_LEGACY_PHONE_CUTOFF_PERCENT: String(bucket) };
+ await runScheduledCleanup(worker, relayVars(partly));
+ expect((await endpointState(outside.id)).status).toBe("ready");
+ expect((await askForTunnel(worker, outside, 1, relayVars(partly))).status).toBe(200);
+ }
+ });
+
+ it("ends tunnels for desktops below the minimum version with 426 update_required", async () => {
+ const cloudflare = new FakeCloudflare();
+ const worker = createWorker(cloudflare.fetch);
+ const owner = await signIn(worker, "[email protected]");
+ const old = await computerWithTunnel(worker, cloudflare, owner.token, "cutoff-version-old", "0.1.140");
+ const current = await computerWithTunnel(worker, cloudflare, owner.token, "cutoff-version-current");
+ const unknown = await provisioned(worker, cloudflare, owner.token, "cutoff-version-unknown");
+ vi.spyOn(console, "log").mockImplementation(() => undefined);
+ expect((await releaseHealth(worker)).minAppVersion).toEqual({ on: false, eligible: 2 });
+
+ const minimum = relayVars({ TUNNEL_MIN_APP_VERSION: "0.1.145" });
+ expect((await releaseHealth(worker, minimum)).minAppVersion).toEqual({ on: true, eligible: 2 });
+ const refused = await askForTunnel(worker, old, 1, minimum);
+ expect(refused.status).toBe(426);
+ await expect(refused.json()).resolves.toEqual({ error: "update_required" });
+ await runScheduledCleanup(worker, minimum);
+ expect((await endpointState(old.id)).status).toBe("deleted");
+ expect((await endpointState(unknown.id)).status).toBe("deleted");
+ expect((await endpointState(current.id)).status).toBe("ready");
+ expect((await askForTunnel(worker, current, 1, minimum)).status).toBe(200);
+
+ // A computer that has not called for days may have updated since: its stored release proves nothing.
+ const away = await computerWithTunnel(worker, cloudflare, owner.token, "cutoff-version-away", "0.1.140");
+ await env.DB.prepare("UPDATE installations SET last_seen_at = ? WHERE id = ?").bind(Date.now() - 3 * DAY_MS, away.id).run();
+ expect((await releaseHealth(worker, minimum)).minAppVersion).toEqual({ on: true, eligible: 0 });
+ await runScheduledCleanup(worker, minimum);
+ expect((await endpointState(away.id)).status).toBe("ready");
+
+ // A desktop that updated itself while its tunnel kept working says so with its hourly relay token.
+ const selfUpdated = await computerWithTunnel(worker, cloudflare, owner.token, "cutoff-version-updated", "0.1.140");
+ expect(await reportPhones(worker, { ...selfUpdated, appVersion: "0.1.151" }, { e2e: 0, legacy: 1 })).toBe(200);
+ expect(await env.DB.prepare("SELECT app_version FROM installations WHERE id = ?").bind(selfUpdated.id).first())
+ .toEqual({ app_version: "0.1.151" });
+ await runScheduledCleanup(worker, minimum);
+ expect((await endpointState(selfUpdated.id)).status).toBe("ready");
+
+ // Updated: the same address comes back.
+ const updated = await askForTunnel(worker, { ...old, appVersion: "0.1.151" }, 1, minimum);
+ expect(updated.status).toBe(200);
+ expect((await updated.json<{ endpoint: { url: string } }>()).endpoint.url).toBe(`https://${old.state.hostname}`);
+ });
+});
+
+describe("the idle reclaim dry run", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("counts what a shorter offline period would reclaim, on /healthz, without reclaiming it", async () => {
+ const cloudflare = new FakeCloudflare();
+ const worker = createWorker(cloudflare.fetch);
+ const owner = await signIn(worker, "[email protected]");
+ const twoDays = await provisioned(worker, cloudflare, owner.token, "preview-two-days");
+ const online = await provisioned(worker, cloudflare, owner.token, "preview-online");
+ offlineFor(twoDays.tunnel, 2);
+ await quiet(twoDays.id, 2 * DAY_MS);
+ connected(online.tunnel);
+ await quiet(online.id, 2 * DAY_MS);
+ vi.spyOn(console, "log").mockImplementation(() => undefined);
+ const reclaim = async (vars: Record<string, string>) => {
+ await forgetCachedCapacity(readConfig(env));
+ const health = await call(worker, "/healthz", { env: { ...env, ...vars } as unknown as Env });
+ return (await health.json<{ capacity: { reclaim: Record<string, unknown> } }>()).capacity.reclaim;
+ };
+
+ const live = { OMB_TUNNEL_OFFLINE_RECLAIM_DAYS: "3" };
+ await runScheduledCleanup(worker, live);
+ expect(await reclaim(live)).toEqual({ mode: "on", pending: 0 });
+
+ const preview = { ...live, OMB_TUNNEL_RECLAIM_PREVIEW_DAYS: "1" };
+ await runScheduledCleanup(worker, preview);
+ expect(await reclaim(preview)).toEqual({ mode: "on", pending: 0, preview: { offlineDays: 1, eligible: 1 } });
+ expect((await endpointState(twoDays.id)).status).toBe("ready");
+ expect(cloudflare.tunnels.size).toBe(2);
+
+ // Another threshold has no finished pass yet; the live threshold itself still reclaims.
+ expect(await reclaim({ ...live, OMB_TUNNEL_RECLAIM_PREVIEW_DAYS: "2" })).toMatchObject({ preview: { offlineDays: 2, eligible: null } });
+ await runScheduledCleanup(worker, { OMB_TUNNEL_OFFLINE_RECLAIM_DAYS: "1" });
+ expect((await endpointState(twoDays.id)).status).toBe("deleted");
+ expect((await endpointState(online.id)).status).toBe("ready");
+ });
+});
diff --git a/cloudflare/control-plane/test/relay.test.ts b/cloudflare/control-plane/test/relay.test.ts
index 1b4ae14ccd..b850a4c8a1 100644
--- a/cloudflare/control-plane/test/relay.test.ts
+++ b/cloudflare/control-plane/test/relay.test.ts
@@ -6,6 +6,7 @@ import vectors from "../../../companion/src/e2e/vectors/v1.json";
import { createAuth } from "../src/auth";
import { readConfig } from "../src/config";
import { createWorker } from "../src/index";
+import { forgetTunnelRelease, releaseTunnels } from "../src/tunnel-release";
import { forgetRelayAdoption, importSigningSeed, mintRelayToken, orderNodes, RELAY_TOKEN_LIMIT, rolloutBucket } from "../src/relay";
const BASE_URL = "https://auth.openmausbot.test";
@@ -225,7 +226,7 @@ describe("node order", () => {
describe("tunnels for relay-capable desktops", () => {
it("are refused with 409 relay_capable when no old phone needs one, once the release is named", async () => {
const { credential } = await installation("[email protected]");
- const gated = { ...env, RELAY_CAPABLE_MIN_VERSION: "0.1.150" } as unknown as Env;
+ const gated = relayEnv({ RELAY_CAPABLE_MIN_VERSION: "0.1.150" });
const refused = await call(gated, "/v1/installations/self/endpoint", { token: credential, body: { appVersion: "0.1.151", legacyDevices: 0 } });
expect(refused.status).toBe(409);
expect(await refused.json()).toEqual({ error: "relay_capable" });
@@ -233,7 +234,11 @@ describe("tunnels for relay-capable desktops", () => {
[gated, { appVersion: "0.1.151", legacyDevices: 1 }],
[gated, { appVersion: "0.1.149", legacyDevices: 0 }],
[gated, { appVersion: "0.1.151" }],
- [env, { appVersion: "0.1.151", legacyDevices: 0 }],
+ [relayEnv({ RELAY_CAPABLE_MIN_VERSION: "" }), { appVersion: "0.1.151", legacyDevices: 0 }],
+ // The relay cannot carry it: off, outside the rollout, or no signing key yet.
+ [relayEnv({ RELAY_CAPABLE_MIN_VERSION: "0.1.150", RELAY_DISABLED: "1" }), { appVersion: "0.1.151", legacyDevices: 0 }],
+ [relayEnv({ RELAY_CAPABLE_MIN_VERSION: "0.1.150", RELAY_ROLLOUT_PERCENT: "0" }), { appVersion: "0.1.151", legacyDevices: 0 }],
+ [{ ...env, RELAY_CAPABLE_MIN_VERSION: "0.1.150" } as unknown as Env, { appVersion: "0.1.151", legacyDevices: 0 }],
] as const) {
expect((await call(testEnv, "/v1/installations/self/endpoint", { token: credential, body })).status).not.toBe(409);
}
@@ -314,3 +319,37 @@ describe("a Worker deployed before migration 0014", () => {
expect(row).toEqual({ e2e_devices: 1, legacy_devices: 2 });
});
});
+
+describe("a Worker deployed before migration 0015", () => {
+ it("still mints tokens, reports health without the release counts, and releases nothing", async () => {
+ const db = env.MIGRATION_DB;
+ const release = env.TEST_MIGRATIONS.findIndex((migration) => migration.name.startsWith("0015_"));
+ expect(release).toBeGreaterThan(0);
+ await applyD1Migrations(db, env.TEST_MIGRATIONS.slice(0, release));
+ const oldEnv = { ...relayEnv({ RELAY_TUNNEL_RELEASE_PERCENT: "100", TUNNEL_LEGACY_PHONE_CUTOFF_PERCENT: "100", OMB_TUNNEL_RECLAIM_PREVIEW_DAYS: "1" }), DB: db } as unknown as Env;
+ const now = Date.now();
+ const lookup = b64u(crypto.getRandomValues(new Uint8Array(16)));
+ const credential = `omb_install_${lookup}.${b64u(crypto.getRandomValues(new Uint8Array(32)))}`;
+ const secretHash = [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(credential)))]
+ .map((byte) => byte.toString(16).padStart(2, "0")).join("");
+ const installationId = crypto.randomUUID();
+ await db.batch([
+ db.prepare('INSERT INTO "user" (id, name, email, emailVerified, createdAt, updatedAt) VALUES (?, ?, ?, 1, ?, ?)').bind("pre-0015-user", "Old", "[email protected]", now, now),
+ db.prepare("INSERT INTO installations (id, owner_user_id, client_instance_id, display_name, platform, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)")
+ .bind(installationId, "pre-0015-user", crypto.randomUUID(), "Old computer", "darwin", now, now),
+ db.prepare("INSERT INTO installation_credentials (id, installation_id, lookup_id, secret_hash, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?)")
+ .bind(crypto.randomUUID(), installationId, lookup, secretHash, now, now + 3_600_000),
+ ]);
+ expect((await ask(oldEnv, credential, { e2e: 1, legacy: 0 })).status).toBe(200);
+ forgetTunnelRelease();
+ const health = await call(oldEnv, "/healthz", { method: "GET" });
+ expect(health.status).toBe(200);
+ expect(await health.json()).not.toHaveProperty("tunnelRelease");
+ forgetTunnelRelease();
+ expect(await releaseTunnels(oldEnv, readConfig(oldEnv), "test")).toBeNull();
+ const ctx = createExecutionContext();
+ worker.scheduled(createScheduledController(), oldEnv, ctx);
+ await waitOnExecutionContext(ctx);
+ expect((await call(oldEnv, "/v1/installations/self", { token: credential, method: "GET" })).status).toBe(200);
+ });
+});
diff --git a/cloudflare/control-plane/test/setup.ts b/cloudflare/control-plane/test/setup.ts
index 5a3e39ae6b..8be521fc85 100644
--- a/cloudflare/control-plane/test/setup.ts
+++ b/cloudflare/control-plane/test/setup.ts
@@ -3,7 +3,8 @@ import { applyD1Migrations, type D1Migration } from "cloudflare:test";
import { afterEach, beforeAll } from "vitest";
import { readConfig } from "../src/config";
-import { forgetCachedCapacity } from "../src/tunnel-capacity";
+import { forgetCachedCapacity, forgetReclaimPreview } from "../src/tunnel-capacity";
+import { forgetTunnelRelease } from "../src/tunnel-release";
declare global {
namespace Cloudflare {
@@ -22,6 +23,8 @@ beforeAll(async () => {
afterEach(async () => {
await forgetCachedCapacity(readConfig(env));
+ forgetTunnelRelease();
+ forgetReclaimPreview();
await env.DB.batch([
env.DB.prepare("DELETE FROM otp_recipient_rate_limits"),
env.DB.prepare("DELETE FROM control_action_rate_limits"),
@@ -30,6 +33,7 @@ afterEach(async () => {
env.DB.prepare("DELETE FROM installation_push_devices"),
// A missing row reads as an empty snapshot (never scanned, never refused).
env.DB.prepare("DELETE FROM managed_endpoint_account_capacity"),
+ env.DB.prepare("DELETE FROM managed_endpoint_reclaim_preview"),
env.DB.prepare("DELETE FROM installation_credentials"),
env.DB.prepare("DELETE FROM installations"),
env.DB.prepare('DELETE FROM "session"'),
diff --git a/cloudflare/control-plane/wrangler.jsonc b/cloudflare/control-plane/wrangler.jsonc
index be591c7486..dbcc211efb 100644
--- a/cloudflare/control-plane/wrangler.jsonc
+++ b/cloudflare/control-plane/wrangler.jsonc
@@ -57,9 +57,13 @@
// "on" marks idle tunnels for cleanup; "observe" only logs candidates.
"OMB_TUNNEL_RECLAIM": "on",
// Days a tunnel must have been offline (and its installation quiet)
- // before reclaim (minimum 3). Never-connected tunnels use a fixed two days.
+ // before reclaim (minimum 1). Never-connected tunnels use a fixed two days.
// A reclaimed installation gets its same hostname back when it returns.
"OMB_TUNNEL_OFFLINE_RECLAIM_DAYS": "3",
+ // Dry run: a second offline period (days, 1-365) that the scan only
+ // counts. /healthz reports capacity.reclaim.preview.eligible once a full
+ // pass (about 50 minutes per 1,000 tunnels) has run at it. Empty: off.
+ "OMB_TUNNEL_RECLAIM_PREVIEW_DAYS": "",
// Cleanup rows per five-minute cron run. 20 needs Workers Paid; use 4 on
// Workers Free (50 subrequests per invocation).
"OMB_CLEANUP_SWEEP_LIMIT": "20",
@@ -77,7 +81,28 @@
"RELAY_DISABLED": "0",
// The first desktop release that reaches phones through the relay. From it, a desktop with no old phones paired
// gets 409 relay_capable instead of a new tunnel. Empty: never refused.
- "RELAY_CAPABLE_MIN_VERSION": "0.1.145"
+ "RELAY_CAPABLE_MIN_VERSION": "0.1.145",
+ // Giving tunnels back (README "Releasing tunnels"). Each is off as written here; /healthz `tunnelRelease`
+ // shows what each would clear before it is turned on. All of them need migration 0015.
+ // RELAY_TUNNEL_RELEASE_PERCENT (0-100): the share of computers, by the same stable hash as the relay rollout,
+ // whose tunnel is released once every paired phone has used the encrypted connection and no old phone has been
+ // reported for RELAY_TUNNEL_RELEASE_DAYS. Raise it 10, 50, 100.
+ "RELAY_TUNNEL_RELEASE_PERCENT": "0",
+ "RELAY_TUNNEL_RELEASE_DAYS": "3",
+ // The cutoffs, the last step. TUNNEL_LEGACY_PHONE_CUTOFF_PERCENT (0-100, the same stable hash): on that share
+ // of the computers the relay serves, the tunnel is given up whatever phones are paired. An old phone app no
+ // longer connects from outside the home network: the phone is updated and paired again, and the desktop says so
+ // (from the release that reads `tunnel` on 409 relay_capable). Ramp 10, then 100. If the relay itself fails,
+ // RELAY_DISABLED "1" (or a lower RELAY_ROLLOUT_PERCENT) stops the cutoff and desktops get their address back.
+ // TUNNEL_MIN_APP_VERSION (x.y.z): a desktop below it neither gets nor keeps a tunnel and is answered
+ // 426 update_required. The cron removes a tunnel only from a computer seen in the last two days, whose stored
+ // release is therefore current. Empty: no minimum.
+ "TUNNEL_LEGACY_PHONE_CUTOFF_PERCENT": "0",
+ "TUNNEL_MIN_APP_VERSION": "",
+ // The first desktop release that reads `tunnel` on 409 relay_capable and keeps asking afterwards (x.y.z). From
+ // it, a relay-served desktop with an old phone is answered relay_capable ("full") at the tunnel limit instead of
+ // 503 endpoint_capacity; earlier releases keep the 503 they show and retry on. Empty: always the 503.
+ "TUNNEL_REASON_MIN_VERSION": ""
},
"secrets": {
"required": ["BETTER_AUTH_SECRET", "CLOUDFLARE_API_TOKEN", "CLOUDFLARE_API_TOKEN_MAUSBOT_SI", "RELAY_TOKEN_SIGNING_KEY"]