Skip to content

Relay worker micro-optimizations: socket-state caching, /prewarm, DO placement - #946

Merged
arul28 merged 3 commits into
mainfrom
ade/pr3-relay-worker-micro-a77196dc
Jul 29, 2026
Merged

Relay worker micro-optimizations: socket-state caching, /prewarm, DO placement#946
arul28 merged 3 commits into
mainfrom
ade/pr3-relay-worker-micro-a77196dc

Conversation

@arul28

@arul28 arul28 commented Jul 29, 2026

Copy link
Copy Markdown
Owner

ADE   Open in ADE  ·  ade/pr3-relay-worker-micro-a77196dc branch  ·  PR #946

Summary by CodeRabbit

  • New Features

    • Added a prewarm endpoint to wake tunnel infrastructure and report host-control availability.
    • Improved Durable Object placement based on request geography for claim and host connections.
    • Added safeguards for tunnel pairing, hibernation recovery, and connection cleanup.
  • Bug Fixes

    • Improved handling when tunnel partners disconnect or become unavailable.
    • Prevented prewarming unknown machines from creating persistent state.
    • Clarified health-check behavior and ensured prewarm requests remain read-only.

arul28 and others added 3 commits July 29, 2026 13:52
Three additive, independently-deployable improvements to the tunnel relay
Worker. All are backward compatible with deployed desktop and iOS clients:
no auth, close-code, protocol, framing, or buffer-limit changes.

- Cache each socket's attachment and its paired partner in instance memory.
  `normalizedAttachment()` deserialized on every frame and `partnerOf()`
  rescanned the connection tag on every frame; both now read from a WeakMap.
  Hibernation drops instance memory, so both caches fall back to the durable
  attachment (or the tag scan) and repopulate themselves after a wake, and a
  single write-through helper is now the only writer of an attachment so the
  cache cannot drift. The partner entry is only ever a hint, re-checked
  against the same predicate the scan uses.

- Add `GET /prewarm/:machineKey`, returning `{ok, control}`. Reaching the
  object is the point: it un-hibernates it before a client needs the tunnel.
  Inert by construction — no storage, no alarm, no attachment migration, no
  signal to the host. Same auth stance as `/connect`. `/health` is answered
  by the Worker and never reaches a DO, so it could not serve this.

- Derive a `locationHint` from `request.cf` on `claim` and `/host` only, so a
  new machine's object is created near the machine rather than near whichever
  request happened to arrive first. `/connect`, `/prewarm`, and `/pipe` never
  carry a hint — a travelling phone must not place a machine's object.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Applied /quality dual-review findings. All behavior-preserving:

- partnerOf: the cache-hit path and the tag scan now share isPartnerOf, so
  the "re-checked against the same predicate" invariant is structural rather
  than coincidental. Drops two guards verified dead — a self-entry cannot be
  inserted, and a stale reverse entry self-heals on its own next read.
- handlePrewarm: expressed as .some(), still reading the raw attachment so it
  cannot trigger a migration write.
- RelayLocationHint aliases Cloudflare's DurableObjectLocationHint instead of
  re-enumerating it, so the union cannot drift.
- parseLongitude: an empty longitude is missing data, not the prime meridian.
  Number("") is 0, which read as a real coordinate and picked "me" for Asia.
- Renamed the caches cachedAttachments/cachedPartners: the socket's own
  attachment stays authoritative, and the names now say so.
- Tests: establishEpochV2 delegates to openTunnel, so the {t:"open"} shape is
  now asserted for every tunnel opened. Adds the empty-longitude case and one
  test pinning the socket-identity premise the caches rest on.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@vercel

vercel Bot commented Jul 29, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
ade Ignored Ignored Jul 29, 2026 6:15pm

@coderabbitai

coderabbitai Bot commented Jul 29, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: e3e5db51-304d-41a1-9d74-c376665af34a

📥 Commits

Reviewing files that changed from the base of the PR and between 5be23f3 and 2664be2.

⛔ Files ignored due to path filters (1)
  • docs/features/sync-and-multi-device/README.md is excluded by !docs/**
📒 Files selected for processing (5)
  • apps/tunnel-relay/README.md
  • apps/tunnel-relay/src/relay.ts
  • apps/tunnel-relay/src/tunnelDo.ts
  • apps/tunnel-relay/test/relay.test.ts
  • apps/tunnel-relay/test/relay.workerd.test.ts

📝 Walkthrough

Walkthrough

Adds a prewarm endpoint, geography-based Durable Object placement hints, centralized WebSocket attachment caching, safer partner lifecycle handling, and unit/integration coverage for routing, placement, hibernation, pairing, and prewarm behavior.

Changes

Tunnel relay behavior

Layer / File(s) Summary
Routing and placement hints
apps/tunnel-relay/src/relay.ts, apps/tunnel-relay/test/relay.test.ts
Adds /prewarm/:machineKey routing and maps request geography to Durable Object location hints for claim and host routes.
Prewarm probe handling
apps/tunnel-relay/src/tunnelDo.ts, apps/tunnel-relay/test/relay.workerd.test.ts, apps/tunnel-relay/README.md
Adds read-only GET/HEAD prewarm handling that reports control-socket status without persisting state, and documents the endpoint behavior.
Socket cache and pairing lifecycle
apps/tunnel-relay/src/tunnelDo.ts, apps/tunnel-relay/test/relay.workerd.test.ts
Centralizes attachment writes, validates cached partners, clears caches on terminal socket events, and tests pairing and forwarding across hibernation.

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related PRs

  • arul28/ADE#864: Both changes update Durable Object WebSocket teardown and close-handling paths.

Suggested labels: docs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main changes: socket-state caching, the /prewarm endpoint, and Durable Object placement hints.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch ade/pr3-relay-worker-micro-a77196dc

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@arul28
arul28 merged commit cd1bb24 into main Jul 29, 2026
3 checks passed
@arul28
arul28 deleted the ade/pr3-relay-worker-micro-a77196dc branch July 29, 2026 18:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant