Skip to content

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

Control plane: remove a released tunnel whose computer is still online (#5344)

Milind Sonid0ae545f34f3
diff --git a/cloudflare/control-plane/README.md b/cloudflare/control-plane/README.md
index dfe602d56c..cb4608ac43 100644
--- a/cloudflare/control-plane/README.md
+++ b/cloudflare/control-plane/README.md
@@ -176,10 +176,11 @@ no configured account acts on (see **Several Cloudflare accounts**) are
skipped. Rows run five at a time (the Workers limit is six connections
awaiting headers), and a run stops
starting new rows in an account as soon as that account's API answers `429`.
-At ten provider calls per row the default is about
-200 calls per run: a sixth of the API token's 1,200 requests per five minutes,
-and far below the Workers Paid limit of 10,000 subrequests per invocation. On
-Workers Free (50 subrequests per invocation) set the limit to 4. Failed
+At up to 14 provider calls per row (four of them only when a forced removal
+meets a tunnel that is still connected) the default is at most about 290 calls per
+run: under a quarter of the API token's 1,200 requests per five minutes, and far
+below the Workers Paid limit of 10,000 subrequests per invocation. On Workers
+Free (50 subrequests per invocation) set the limit to 3. Failed
scheduled cleanups back off from five minutes through 15 minutes, one hour,
six hours, and then 24 hours. Once a deletion has been pending for 24 hours,
each eligible sweep emits a distinct aggregate operator-attention log without
@@ -586,8 +587,8 @@ no new endpoint while another account has room.
Each account adds two Cloudflare reads to every cron run (a tunnel page and a
DNS count), and each move two lookups in the old account. Tokens created by
the same Cloudflare user share its 1,200 requests per five minutes. On
-Workers Free, four accounts with `OMB_CLEANUP_SWEEP_LIMIT` 4 use the whole
-50-subrequest budget, hence at most three extra accounts.
+Workers Free, three accounts with `OMB_CLEANUP_SWEEP_LIMIT` 3 use the whole
+50-subrequest budget; a fourth needs the limit at 2.
### MausBot Relay
@@ -660,9 +661,17 @@ hostname stay, so a later provisioning call returns the same address.
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.
+- **Online computers.** Cloudflare refuses to delete a tunnel that has active connections (API error 1022, recorded as
+ `cf_tunnel_connected`), and a running desktop's cloudflared is connected. For a release, an owner's delete or a
+ revoked installation, the sweep then drops the tunnel's connections (`DELETE .../cfd_tunnel/{id}/connections`) and
+ deletes again at once, for at most two rounds, the last with `?cascade=true` (what `cloudflared tunnel delete
+ --force` sends; not in the public API reference); a deleted tunnel's connector token no longer connects. Idle reclaim never does this: a tunnel that answers
+ "still connected" is left, and its next attempt finds it connected and cancels.
- **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.
+ the rows already waiting for cleanup. While the sweep is failing or rate-limited nothing more is marked. A forced
+ removal still refused as connected after its rounds does not count as waiting: it backs off (5 minutes up to 24
+ hours) and retries while the sweep and the marking go on. 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
diff --git a/cloudflare/control-plane/src/cloudflare-api.ts b/cloudflare/control-plane/src/cloudflare-api.ts
index cbc818bf05..2940ab48ef 100644
--- a/cloudflare/control-plane/src/cloudflare-api.ts
+++ b/cloudflare/control-plane/src/cloudflare-api.ts
@@ -116,6 +116,11 @@ export class CloudflareAPIError extends Error {
}
}
+/** Cloudflare's refusal to delete a tunnel that still has active connections. */
+const TUNNEL_CONNECTED_PROVIDER_CODE = "cf_api_1022";
+/** `deleteTunnel`'s name for it: the tunnel's connector is up. */
+export const TUNNEL_CONNECTED_CODE = "cf_tunnel_connected";
+
function isNotFound(error: unknown): boolean {
return error instanceof CloudflareAPIError
&& (error.status === 404 || error.code === "cf_http_404" || error.code === "cf_api_81044");
@@ -485,10 +490,31 @@ export class CloudflareAPI {
}
}
- async deleteTunnel(tunnelId: string): Promise<void> {
+ /** `cascade` is what `cloudflared tunnel delete --force` sends; the public
+ * API reference lists no such option, so a caller must not depend on it. */
+ async deleteTunnel(tunnelId: string, { cascade = false }: { cascade?: boolean } = {}): Promise<void> {
try {
await this.request(
- `accounts/${encodeURIComponent(this.config.accountId)}/cfd_tunnel/${encodeURIComponent(tunnelId)}`,
+ `accounts/${encodeURIComponent(this.config.accountId)}/cfd_tunnel/${encodeURIComponent(tunnelId)}${cascade ? "?cascade=true" : ""}`,
+ z.unknown(),
+ { method: "DELETE" },
+ );
+ } catch (error) {
+ if (isNotFound(error)) return;
+ if (error instanceof CloudflareAPIError && error.code === TUNNEL_CONNECTED_PROVIDER_CODE) {
+ throw new CloudflareAPIError(TUNNEL_CONNECTED_CODE, error.status);
+ }
+ throw error;
+ }
+ }
+
+ /** Drops every connector registration of the tunnel, whatever its state
+ * (`DELETE .../cfd_tunnel/{id}/connections`, no `client_id`). A running
+ * cloudflared reconnects within seconds unless the tunnel is gone by then. */
+ async cleanupTunnelConnections(tunnelId: string): Promise<void> {
+ try {
+ await this.request(
+ `accounts/${encodeURIComponent(this.config.accountId)}/cfd_tunnel/${encodeURIComponent(tunnelId)}/connections`,
z.unknown(),
{ method: "DELETE" },
);
diff --git a/cloudflare/control-plane/src/config.ts b/cloudflare/control-plane/src/config.ts
index 54828942a7..0250a1e283 100644
--- a/cloudflare/control-plane/src/config.ts
+++ b/cloudflare/control-plane/src/config.ts
@@ -74,16 +74,18 @@ export const DEFAULT_OFFLINE_RECLAIM_DAYS = 21;
// 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
-// Workers Free, whose limit is 50 subrequests (4 x 10 + 2 + 2 Cache API
-// deletes = 44).
+// Each cleanup makes at most 14 Cloudflare API calls (an idle reclaim at most
+// 12; a forced removal whose tunnel is still connected adds two connection
+// cleanups and two deletes to the usual ten): twenty rows plus the two capacity
+// reads stay under 290 calls per run, under the token's
+// 1,200-per-five-minutes limit and Workers Paid's 10,000 subrequests. Use 3 on
+// Workers Free, whose limit is 50 subrequests (3 x 14 + 2 + 2 Cache API
+// deletes = 46).
export const DEFAULT_CLEANUP_SWEEP_LIMIT = 20;
export const MAX_CLEANUP_SWEEP_LIMIT = 50;
-/** Each account adds two Cloudflare reads per cron run: on Workers Free, 4
- * cleanup rows x 10 calls + 4 x 2 + two Cache API deletes is the whole
- * 50-subrequest budget. */
+/** Each account adds two Cloudflare reads per cron run: on Workers Free, 3
+ * cleanup rows x 14 calls + 3 x 2 + two Cache API deletes is the whole
+ * 50-subrequest budget, and four accounts need the sweep limit at 2. */
export const MAX_ENDPOINT_ACCOUNTS = 4;
function boundedIntegerVar(
diff --git a/cloudflare/control-plane/src/endpoints.ts b/cloudflare/control-plane/src/endpoints.ts
index d07bb80331..1671f846f0 100644
--- a/cloudflare/control-plane/src/endpoints.ts
+++ b/cloudflare/control-plane/src/endpoints.ts
@@ -6,6 +6,7 @@ import {
type CloudflareDNSRecord,
type CloudflareFetch,
type CloudflareTunnel,
+ TUNNEL_CONNECTED_CODE,
} from "./cloudflare-api";
import type { ControlPlaneConfig, EndpointAccount } from "./config";
import {
@@ -73,7 +74,7 @@ const LEASE_MS = 60_000;
const ENDPOINT_ACTION_WINDOW_MS = 60 * 60 * 1_000;
const ENDPOINT_RECONCILE_LIMIT = 20;
const ENDPOINT_DELETE_LIMIT = 30;
-// A cleanup makes at most ten Cloudflare API calls; five rows at a time stays
+// A cleanup makes at most 14 Cloudflare API calls; five rows at a time stays
// inside the Workers limit of six connections awaiting headers.
const CLEANUP_CONCURRENCY = 5;
const CLEANUP_BACKOFF_1_MS = 5 * 60 * 1_000;
@@ -81,6 +82,9 @@ const CLEANUP_BACKOFF_2_MS = 15 * 60 * 1_000;
const CLEANUP_BACKOFF_3_MS = 60 * 60 * 1_000;
const CLEANUP_BACKOFF_4_MS = 6 * 60 * 60 * 1_000;
const CLEANUP_BACKOFF_MAX_MS = 24 * 60 * 60 * 1_000;
+/** Connection cleanups, each followed at once by a delete, that a forced
+ * removal makes after Cloudflare answers that the tunnel is still connected. */
+const FORCED_TUNNEL_DELETE_ROUNDS = 2;
const MANUAL_CLEANUP_THRESHOLD_MS = 24 * 60 * 60 * 1_000;
/** Cloudflare blocks a rate-limited API token for up to five minutes. */
const RATE_LIMIT_RETRY_AFTER_DEFAULT_SECONDS = 60;
@@ -657,6 +661,30 @@ async function deleteVerifiedTunnel(
}
}
+/** Removes a tunnel taken on purpose (a release, the owner's delete, a revoked
+ * installation) even while its computer is online. Cloudflare refuses to delete
+ * a tunnel with active connections, and a running cloudflared reconnects within
+ * seconds of losing them, so each round drops the connections and deletes at
+ * once: first as documented, last with `cascade` as cloudflared's own forced
+ * delete sends it. Bounded: two calls per round. */
+async function forceDeleteTunnel(
+ env: Env,
+ claim: ClaimedEndpoint,
+ api: CloudflareAPI,
+ tunnelId: string,
+): Promise<void> {
+ for (let round = 0; ; round += 1) {
+ try {
+ await api.deleteTunnel(tunnelId, { cascade: round === FORCED_TUNNEL_DELETE_ROUNDS });
+ return;
+ } catch (error) {
+ if (errorCode(error) !== TUNNEL_CONNECTED_CODE || round >= FORCED_TUNNEL_DELETE_ROUNDS) throw error;
+ }
+ await renewClaim(env, claim);
+ await api.cleanupTunnelConnections(tunnelId);
+ }
+}
+
async function rollbackCreatedResources(
env: Env,
claim: ClaimedEndpoint,
@@ -1141,7 +1169,10 @@ async function deleteClaim(
return "cancelled";
}
await renewClaim(env, claim);
- await api.deleteTunnel(tunnelId);
+ // An idle reclaim never forces: a tunnel that answers "still connected"
+ // is left to the next attempt, which finds it connected and cancels.
+ if (idleReclaim) await api.deleteTunnel(tunnelId);
+ else await forceDeleteTunnel(env, claim, api, tunnelId);
freed.tunnels += 1;
}
tunnelId = null;
diff --git a/cloudflare/control-plane/src/tunnel-release.ts b/cloudflare/control-plane/src/tunnel-release.ts
index 6978cb49e5..46748b91df 100644
--- a/cloudflare/control-plane/src/tunnel-release.ts
+++ b/cloudflare/control-plane/src/tunnel-release.ts
@@ -4,6 +4,7 @@
// 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 { TUNNEL_CONNECTED_CODE } from "./cloudflare-api";
import type { ControlPlaneConfig } from "./config";
import { ACTED_ON_ENDPOINT_SQL, actedOnAccounts, appVersionAtLeast } from "./endpoint-accounts";
import type { JSONValue } from "./http";
@@ -21,6 +22,8 @@ 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;
+/** A forced removal that met a tunnel still connected: by name, and as Cloudflare's own code from before it was named. */
+const STILL_CONNECTED_CODES = JSON.stringify([TUNNEL_CONNECTED_CODE, "cf_api_1022"]);
/** Rows read per run before a percentage is applied. */
const PROVEN_SCAN_LIMIT = 5_000;
@@ -249,10 +252,14 @@ export async function releaseTunnels(
};
// 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.
+ // so no owner is left with a row it cannot take back. A forced removal
+ // whose tunnel was still connected after its cleanup rounds is not a failing
+ // sweep: it backs off and retries on its own, and does not hold the queue.
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 }>();
+ `SELECT COUNT(*) AS count FROM installation_endpoints e
+ WHERE e.status = 'deleting' AND ${ACTED_ON_ENDPOINT_SQL}
+ AND NOT (e.reclaim_requested_at IS NULL AND COALESCE(e.last_error_code, '') IN (SELECT value FROM json_each(?)))`,
+ ).bind(actedOnAccounts(config), STILL_CONNECTED_CODES).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);
diff --git a/cloudflare/control-plane/test/managed-endpoints.test.ts b/cloudflare/control-plane/test/managed-endpoints.test.ts
index 6251bd2ddd..0e7fede4a6 100644
--- a/cloudflare/control-plane/test/managed-endpoints.test.ts
+++ b/cloudflare/control-plane/test/managed-endpoints.test.ts
@@ -210,6 +210,13 @@ class FakeCloudflare {
rateLimitRetryAfter: string | null = null;
readonly afterHooks = new Map<string, () => void>();
readonly tunnels = new Map<string, FakeTunnel>();
+ /** Tunnel IDs with a connector up: a plain delete answers error 1022. */
+ readonly connectedTunnels = new Set<string>();
+ /** Connection cleanups after which cloudflared is back before the next request. */
+ reconnectsAfterCleanup = 0;
+ /** Whether `?cascade=true` deletes a connected tunnel. The API reference
+ * does not list it, so by default it is ignored. */
+ cascadeHonoured = false;
dnsTotalCount: number | null = null;
tunnelTotalCount: number | null = null;
/** Answer the account-wide tunnel listing without `result_info`. */
@@ -431,10 +438,31 @@ class FakeCloudflare {
this.after("delete_dns");
return Response.json({ result: { id } });
}
+ if (method === "DELETE" && url.pathname.endsWith("/connections")) {
+ const failed = await this.before("cleanup_connections");
+ if (failed) return failed;
+ const id = url.pathname.split("/").at(-2) ?? "";
+ this.connectedTunnels.delete(id);
+ if (this.reconnectsAfterCleanup > 0) {
+ this.reconnectsAfterCleanup -= 1;
+ this.connectedTunnels.add(id);
+ }
+ return jsonResult({});
+ }
if (method === "DELETE" && url.pathname.includes("/cfd_tunnel/")) {
const failed = await this.before("delete_tunnel");
if (failed) return failed;
const id = url.pathname.split("/").at(-1);
+ const cascade = this.cascadeHonoured && url.searchParams.get("cascade") === "true";
+ if (id && this.connectedTunnels.has(id) && !cascade) {
+ return Response.json({
+ errors: [{ code: 1_022, message: "Cannot delete a tunnel with active connections" }],
+ messages: [],
+ result: null,
+ success: false,
+ }, { status: 400 });
+ }
+ if (id) this.connectedTunnels.delete(id);
for (const [name, tunnel] of this.tunnels) {
if (tunnel.id === id) this.tunnels.delete(name);
}
@@ -4058,3 +4086,214 @@ describe("the idle reclaim dry run", () => {
expect((await endpointState(online.id)).status).toBe("ready");
});
});
+
+describe("removing a tunnel whose computer is online", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ forgetTunnelRelease();
+ });
+
+ const minimum = (extra: Record<string, string> = {}) => relayVars({ TUNNEL_MIN_APP_VERSION: "0.1.145", ...extra });
+ const tunnelOf = (cloudflare: FakeCloudflare, computer: Computer) => {
+ const tunnel = cloudflare.tunnels.get(computer.state.tunnel_name);
+ if (!tunnel) throw new Error("fake tunnel missing");
+ return tunnel;
+ };
+ const tunnelDeletes = (cloudflare: FakeCloudflare, tunnelId: string) => deleteURLs(cloudflare)
+ .filter((url) => new URL(url).pathname.endsWith(`/cfd_tunnel/${tunnelId}`));
+ const connectionCleanups = (cloudflare: FakeCloudflare, tunnelId: string) => deleteURLs(cloudflare)
+ .filter((url) => new URL(url).pathname.endsWith(`/cfd_tunnel/${tunnelId}/connections`));
+ const retryNow = () => env.DB.prepare(
+ "UPDATE installation_endpoints SET last_cleanup_attempt_at = 0 WHERE status = 'deleting'",
+ ).run();
+
+ it("names Cloudflare's still-connected refusal and cleans up connections", async () => {
+ const tunnelId = "10000000-0000-4000-8000-000000000001";
+ const refused = new CloudflareAPI(readConfig(env).cloudflare, async () => Response.json({
+ errors: [{ code: 1_022, message: "Cannot delete a tunnel with active connections" }],
+ result: null,
+ success: false,
+ }, { status: 400 }));
+ await expect(refused.deleteTunnel(tunnelId)).rejects.toMatchObject({ code: "cf_tunnel_connected", status: 400 });
+
+ const seen: string[] = [];
+ const cleaned = new CloudflareAPI(readConfig(env).cloudflare, async (input, init) => {
+ seen.push(`${init?.method} ${new URL(input.toString()).pathname}`);
+ return jsonResult({});
+ });
+ await expect(cleaned.cleanupTunnelConnections(tunnelId)).resolves.toBeUndefined();
+ expect(seen).toEqual([`DELETE /client/v4/accounts/${PRIMARY_ACCOUNT}/cfd_tunnel/${tunnelId}/connections`]);
+ // A tunnel that is already gone has nothing to clean up.
+ const gone = new CloudflareAPI(readConfig(env).cloudflare, async () => jsonNotFound());
+ await expect(gone.cleanupTunnelConnections(tunnelId)).resolves.toBeUndefined();
+ });
+
+ it("drops the connections of a released tunnel and deletes it in the same attempt, and nothing hands it back", 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, "online-release", "0.1.140");
+ const tunnel = tunnelOf(cloudflare, old);
+ connected(tunnel);
+ cloudflare.connectedTunnels.add(tunnel.id);
+ vi.spyOn(console, "log").mockImplementation(() => undefined);
+ cloudflare.calls.length = 0;
+
+ await runScheduledCleanup(worker, minimum());
+
+ expect(await endpointState(old.id)).toMatchObject({ status: "deleted", tunnel_id: null, dns_record_id: null, last_error_code: null });
+ expect(cloudflare.tunnels.has(old.state.tunnel_name)).toBe(false);
+ // Refused, connections dropped, deleted: back to back, as documented.
+ expect(deleteURLs(cloudflare).filter((url) => !url.includes("/dns_records/")).map((url) => new URL(url).pathname.split("/").slice(-2).join("/")))
+ .toEqual([`cfd_tunnel/${tunnel.id}`, `${tunnel.id}/connections`, `cfd_tunnel/${tunnel.id}`]);
+ expect(tunnelDeletes(cloudflare, tunnel.id).every((url) => !url.includes("cascade"))).toBe(true);
+
+ // The same old desktop asking again is refused before any provider call.
+ const creates = () => cloudflare.calls.filter((entry) => entry.method === "POST" && entry.url.endsWith("/cfd_tunnel")).length;
+ const before = creates();
+ const again = await askForTunnel(worker, old, 1, minimum());
+ expect(again.status).toBe(426);
+ await expect(again.json()).resolves.toEqual({ error: "update_required" });
+ expect(creates()).toBe(before);
+ });
+
+ it("deletes with cascade on the last round when cloudflared is back at once", async () => {
+ const cloudflare = new FakeCloudflare();
+ cloudflare.cascadeHonoured = true;
+ const worker = createWorker(cloudflare.fetch);
+ const owner = await signIn(worker, "[email protected]");
+ const old = await computerWithTunnel(worker, cloudflare, owner.token, "online-reconnect", "0.1.140");
+ const tunnel = tunnelOf(cloudflare, old);
+ cloudflare.connectedTunnels.add(tunnel.id);
+ cloudflare.reconnectsAfterCleanup = 2;
+ vi.spyOn(console, "log").mockImplementation(() => undefined);
+ cloudflare.calls.length = 0;
+
+ await runScheduledCleanup(worker, minimum());
+
+ expect(await endpointState(old.id)).toMatchObject({ status: "deleted", tunnel_id: null });
+ expect(connectionCleanups(cloudflare, tunnel.id)).toHaveLength(2);
+ const deletes = tunnelDeletes(cloudflare, tunnel.id);
+ expect(deletes).toHaveLength(3);
+ expect(deletes.map((url) => new URL(url).searchParams.get("cascade"))).toEqual([null, null, "true"]);
+ });
+
+ it("stays inside its call budget, backs off, and keeps the release marking while a tunnel stays connected", async () => {
+ const cloudflare = new FakeCloudflare();
+ const worker = createWorker(cloudflare.fetch);
+ const owner = await signIn(worker, "[email protected]");
+ const first = await computerWithTunnel(worker, cloudflare, owner.token, "online-stuck-a", "0.1.140");
+ const second = await computerWithTunnel(worker, cloudflare, owner.token, "online-stuck-b", "0.1.140");
+ for (const each of [first, second]) cloudflare.connectedTunnels.add(tunnelOf(cloudflare, each).id);
+ cloudflare.reconnectsAfterCleanup = 1_000;
+ vi.spyOn(console, "log").mockImplementation(() => undefined);
+ vi.spyOn(console, "error").mockImplementation(() => undefined);
+ const vars = minimum({ OMB_CLEANUP_SWEEP_LIMIT: "1" });
+ const firstTunnel = tunnelOf(cloudflare, first).id;
+ cloudflare.calls.length = 0;
+
+ await runScheduledCleanup(worker, vars);
+
+ expect(await endpointState(first.id)).toMatchObject({ status: "deleting", last_error_code: "cf_tunnel_connected", tunnel_id: firstTunnel });
+ expect(await endpointState(second.id)).toMatchObject({ status: "ready" });
+ // Bounded: the usual verified cleanup plus two rounds of cleanup and delete.
+ expect(connectionCleanups(cloudflare, firstTunnel)).toHaveLength(2);
+ expect(tunnelDeletes(cloudflare, firstTunnel)).toHaveLength(3);
+ expect(cleanupCalls(cloudflare).length).toBeLessThanOrEqual(14);
+
+ // Backing off, it neither takes the sweep's slot nor holds the release.
+ cloudflare.calls.length = 0;
+ await runScheduledCleanup(worker, vars);
+ expect(tunnelDeletes(cloudflare, firstTunnel)).toHaveLength(0);
+ expect(await endpointState(second.id)).toMatchObject({ status: "deleting", last_error_code: "cf_tunnel_connected" });
+
+ // Once the connector stays down both go.
+ cloudflare.reconnectsAfterCleanup = 0;
+ await retryNow();
+ await runScheduledCleanup(worker, vars);
+ await retryNow();
+ await runScheduledCleanup(worker, vars);
+ for (const each of [first, second]) expect(await endpointState(each.id)).toMatchObject({ status: "deleted", tunnel_id: null });
+ expect(cloudflare.tunnels.size).toBe(0);
+ });
+
+ it("records a failed connection cleanup, holds the release, and retries later", async () => {
+ const cloudflare = new FakeCloudflare();
+ const worker = createWorker(cloudflare.fetch);
+ const owner = await signIn(worker, "[email protected]");
+ const first = await computerWithTunnel(worker, cloudflare, owner.token, "online-cleanup-fails-a", "0.1.140");
+ const second = await computerWithTunnel(worker, cloudflare, owner.token, "online-cleanup-fails-b", "0.1.140");
+ const tunnel = tunnelOf(cloudflare, first);
+ cloudflare.connectedTunnels.add(tunnel.id);
+ cloudflare.failures.add("cleanup_connections");
+ vi.spyOn(console, "log").mockImplementation(() => undefined);
+ vi.spyOn(console, "error").mockImplementation(() => undefined);
+ const vars = minimum({ OMB_CLEANUP_SWEEP_LIMIT: "1" });
+
+ await runScheduledCleanup(worker, vars);
+ expect(await endpointState(first.id)).toMatchObject({ status: "deleting", last_error_code: "cf_api_10000", tunnel_id: tunnel.id });
+ expect(tunnelDeletes(cloudflare, tunnel.id)).toHaveLength(1);
+ // A sweep that is failing for another reason still stops the marking.
+ await runScheduledCleanup(worker, vars);
+ expect(await endpointState(second.id)).toMatchObject({ status: "ready" });
+
+ cloudflare.failures.delete("cleanup_connections");
+ await retryNow();
+ await runScheduledCleanup(worker, vars);
+ expect(await endpointState(first.id)).toMatchObject({ status: "deleted", tunnel_id: null });
+ expect(cloudflare.tunnels.has(first.state.tunnel_name)).toBe(false);
+ });
+
+ it("never forces an idle reclaim: a tunnel still connected is left, then the reclaim is cancelled", async () => {
+ const cloudflare = new FakeCloudflare();
+ const worker = createWorker(cloudflare.fetch);
+ const owner = await signIn(worker, "[email protected]");
+ const idle = await provisioned(worker, cloudflare, owner.token, "online-idle");
+ await quiet(idle.id, 30 * DAY_MS);
+ neverRan(idle.tunnel, 30);
+ // Its connector came up after the last check: Cloudflare refuses the delete.
+ cloudflare.connectedTunnels.add(idle.tunnel.id);
+ cloudflare.cascadeHonoured = true;
+ vi.spyOn(console, "log").mockImplementation(() => undefined);
+ vi.spyOn(console, "error").mockImplementation(() => undefined);
+ cloudflare.calls.length = 0;
+
+ await runScheduledCleanup(worker);
+
+ const marked = await endpointState(idle.id);
+ expect(marked).toMatchObject({ status: "deleting", last_error_code: "cf_tunnel_connected", tunnel_id: idle.tunnel.id });
+ expect(marked.reclaim_requested_at).not.toBeNull();
+ expect(connectionCleanups(cloudflare, idle.tunnel.id)).toHaveLength(0);
+ expect(tunnelDeletes(cloudflare, idle.tunnel.id)).toHaveLength(1);
+ expect(tunnelDeletes(cloudflare, idle.tunnel.id).some((url) => url.includes("cascade"))).toBe(false);
+
+ connected(idle.tunnel);
+ await retryNow();
+ await runScheduledCleanup(worker);
+
+ expect(await endpointState(idle.id)).toMatchObject({
+ last_error_code: "reclaim_cancelled",
+ reclaim_requested_at: null,
+ status: "error",
+ tunnel_id: idle.tunnel.id,
+ });
+ expect(cloudflare.tunnels.get(idle.state.tunnel_name)?.id).toBe(idle.tunnel.id);
+ expect(connectionCleanups(cloudflare, idle.tunnel.id)).toHaveLength(0);
+ expect(tunnelDeletes(cloudflare, idle.tunnel.id)).toHaveLength(1);
+ });
+
+ it("lets an owner delete an endpoint whose connector is still up", async () => {
+ const cloudflare = new FakeCloudflare();
+ const worker = createWorker(cloudflare.fetch);
+ const owner = await signIn(worker, "[email protected]");
+ const endpoint = await provisioned(worker, cloudflare, owner.token, "online-owner");
+ connected(endpoint.tunnel);
+ cloudflare.connectedTunnels.add(endpoint.tunnel.id);
+
+ const deleted = await call(worker, "/v1/installations/self/endpoint", { method: "DELETE", token: endpoint.credential });
+
+ expect(deleted.status).toBe(204);
+ expect(await endpointState(endpoint.id)).toMatchObject({ status: "deleted", tunnel_id: null });
+ expect(connectionCleanups(cloudflare, endpoint.tunnel.id)).toHaveLength(1);
+ });
+});
diff --git a/cloudflare/control-plane/vitest.config.ts b/cloudflare/control-plane/vitest.config.ts
index ab1b743ccb..6e2723a285 100644
--- a/cloudflare/control-plane/vitest.config.ts
+++ b/cloudflare/control-plane/vitest.config.ts
@@ -27,6 +27,13 @@ export default defineConfig({
ALLOWED_ORIGINS: "https://app.openmausbot.test",
// Production starts in observe (wrangler.jsonc); the suite exercises reclaiming.
OMB_TUNNEL_RECLAIM: "on",
+ // The tunnel release switches as the code defaults them (off), whatever wrangler.jsonc has live; the
+ // release and cutoff tests turn each one on themselves.
+ RELAY_TUNNEL_RELEASE_PERCENT: "0",
+ RELAY_TUNNEL_RELEASE_DAYS: "3",
+ TUNNEL_LEGACY_PHONE_CUTOFF_PERCENT: "0",
+ TUNNEL_MIN_APP_VERSION: "",
+ TUNNEL_REASON_MIN_VERSION: "",
TEST_MIGRATIONS: await readD1Migrations(`${root}migrations`),
},
// An empty database for migration tests that need data written by an
diff --git a/cloudflare/control-plane/wrangler.jsonc b/cloudflare/control-plane/wrangler.jsonc
index dbcc211efb..1e9c34f14e 100644
--- a/cloudflare/control-plane/wrangler.jsonc
+++ b/cloudflare/control-plane/wrangler.jsonc
@@ -87,7 +87,7 @@
// 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_PERCENT": "100",
"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
@@ -98,11 +98,11 @@
// 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": "",
+ "TUNNEL_MIN_APP_VERSION": "0.1.145",
// 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": ""
+ "TUNNEL_REASON_MIN_VERSION": "0.1.152"
},
"secrets": {
"required": ["BETTER_AUTH_SECRET", "CLOUDFLARE_API_TOKEN", "CLOUDFLARE_API_TOKEN_MAUSBOT_SI", "RELAY_TOKEN_SIGNING_KEY"]