GeezerVison is showing github.com — Split the gateway's server.ts into lifecycle managers and helper modules by henrychu04 · Pull Request #300 · henrychu04/t3code-coder
Conversation
Behavior-preserving refactor of apps/coder-gateway/src/server.ts (2,520 lines → 1,001). No functional change. Two commits:
29d6ea0c83 moves the top-level helpers out unchanged.
dfbaa40162 extracts the port-forward and workspace-connection state machines into factories.
Module map
| File |
Responsibility |
Lines |
server.ts |
makeLocalCoderGateway: config load and mutation queue, login dedup, Coder command defaults from options, manager wiring, every HTTP route, WebSocket upgrade, finalizer, listen and saved port. Re-exports CODER_GATEWAY_HOST, runCoderAuthStatus, CoderAuthenticationStatus |
~1,000 |
workspaceConnections.ts |
makeWorkspaceConnectionManager: workspace lifecycles, ensureWorkspaceConnection (with its AbortController cancel), closeWorkspaceConnection, runWorkspaceAction, connection diagnostics (MAX_WORKSPACE_DIAGNOSTIC_EVENTS) |
~690 |
portForwards.ts |
makePortForwardManager: port-forward lifecycles, ensurePortForward, stopPortForward, startConfiguredPortForwards({ retryFailed }) |
~430 |
lifecycleState.ts |
Lifecycle state and claim unions, WorkspaceConnection, DeferredPromise, WorkspaceActionConflictError, RunPromise/RunFork |
~150 |
coderCommands.ts |
Coder CLI login, auth status, workspace discovery and parsing, workspace actions, failWhenAborted, their byte and time limits |
~205 |
http.ts |
CODER_GATEWAY_HOST, indexHtml, sendText and security headers (CSP), static serving and manifest caching, readJsonBody, rejectWebSocketUpgrade, isServerNotRunningError |
~170 |
configChanges.ts |
CoderConfigConflictError, assertDeploymentUrlsUnchanged, workspaceConnectionIsCurrent, portForwardIsCurrent |
~60 |
portProbe.ts |
MAX_LOCAL_PORT_CANDIDATES, loopbackPortIsFree, findFreeForwardPort |
~40 |
savedPort.ts |
readSavedGatewayPort, saveGatewayPort |
~25 |
Moved unchanged vs adapted
Commit 1: moved unchanged. Blocks were copied from server.ts by line range with a script. Each block changed only by:
- an added
export;
- two signatures the formatter re-wrapped once
export made them longer than 100 columns (rejectWebSocketUpgrade, assertDeploymentUrlsUnchanged).
server.ts re-exports its old public names, so bin.ts, testUtils/gateway.ts and the tests import unchanged.
Commit 2: adapted. The manager bodies are dedented by 2 and otherwise moved as is, with these substitutions:
profileConfig → config(), a getter returning the gateway's live profileConfig at the same read point.
gatewayClosed → isClosed().
- The finalizer's two diagnostic
Map.clear() calls became one clearWorkspaceDiagnostics() call in the same spot.
Each factory takes its dependencies explicitly and destructures them into the original local names:
- Shared:
runPromise, runFork, gatewayScope, config, isClosed, coderInvocationOptions.
- Port forwards:
openPortForward, listWorkspaces.
- Workspaces:
hub, workspaceSockets (the same Map instance, typed read-only), portForwards (portForwardLifecycle/ensurePortForward/stopPortForward), openHelper, helperBundlePath, helperBundleHash, installHelper, runWorkspaceStart/Stop/Restart/Update.
The test hooks (connectHelper, installHelper, connectPortForward, listWorkspaces, the workspace action hooks) are still resolved from options in server.ts and passed in. The factories return the old local names (workspaceLifecycles, portForwardLifecycle, ensurePortForward, …), so route, upgrade and finalizer code is unchanged.
How I checked that the moves are equivalent:
- Ignoring whitespace and trailing commas, each manager body is token-identical to the original closure lines after the substitutions above.
- On the same basis, the rest of
server.ts is token-identical to its previous body, apart from the inserted manager wiring.
git diff --color-moved-ws=allow-indentation-change marks all but 375 of the 3,328 changed lines as moved. The rest are imports, exports, factory scaffolding, formatter re-flows after the dedent, and the substitutions.
All orderings, generation checks, error messages, timeouts and HTTP statuses are as before. Docs: sync.md now names http.ts for the CSP hash, and coder-only.md's lifecycle paragraph points at the new files. The boundary guard scans apps/coder-gateway/src recursively, so it covers the new files automatically.
Bugs noticed, not fixed
- The live harness is broken, which matters for the live run.
scripts/coder-live-test.mjs imports startLocalCoderGateway from apps/coder-gateway/src/server.ts in testPortForward() and serve(). server.ts has not exported it since 11b29073d9 (2026-09-05); it lives in src/testUtils/gateway.ts. Those two paths destructure undefined and throw before they reach the gateway. This predates this PR and is unchanged by it.
- Minor: when a config save removes a workspace, its lifecycle is deleted but its diagnostics events and attempt counter stay until the gateway stops. Each workspace is capped at
MAX_WORKSPACE_DIAGNOSTIC_EVENTS, so the memory involved is small.
Verification
node --test apps/coder-gateway/src/*.test.ts apps/coder-helper/src/*.test.ts packages/coder-cli/src/*.test.ts: 121/121 pass, the same count as the base. Run after each commit.
pnpm typecheck:gateway, pnpm typecheck:helper: pass. tsc --noUnusedLocals on the gateway reports nothing new.
pnpm test:knip: pass. knip --include files,dependencies --workspace apps/coder-gateway: clean.
vp fmt --check on the changed files and docs: clean.
node scripts/seams-check.mjs: pass.
pnpm build: pass.
- Test files are unchanged. The live Coder harness was not run; the parent runs it.
🤖 Generated with Claude Code
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Behavior-preserving: the helpers above makeLocalCoderGateway move unchanged
into http.ts (security headers, static files, JSON body, upgrade rejection),
coderCommands.ts (Coder CLI login, auth status, discovery, workspace actions),
configChanges.ts (config comparisons), portProbe.ts (free local port probe),
lifecycleState.ts (lifecycle state and claim types) and savedPort.ts. Each
gains only an `export`; server.ts re-exports its previous public names.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Behavior-preserving: the port-forward lifecycle (start, stop, configured
starts with `retryFailed`) moves to portForwards.ts and the workspace
connection lifecycle (connect with its cancel, close, workspace actions,
connection diagnostics) to workspaceConnections.ts. Each is built by a
factory that takes the gateway's runners, scope, config getter, closed flag,
hub, sockets, and injected Coder commands; the bodies move unchanged except
that `profileConfig` and `gatewayClosed` reads become `config()` and
`isClosed()`. Routes and the WebSocket upgrade stay in server.ts and use the
same names as before.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Reviewed: managers read live config and closed state through getters; the moved code is otherwise byte-identical. Rechecked: 121 node tests, gateway/helper typechecks, knip, seams-check, build. Live check on the local Coder harness: gateway checks (caching, helper stats, traffic counters, oversized frame closes only that socket, disconnect cancels an in-flight connect, reconnect), port discovery + Forward + stop + rule kept, drive.mjs (except the known persisted-project conflict), and the workspace helper exits when the gateway stops (1 → 0). The harness import noted in the body is a gitignored local script; the local copy already imports testUtils/gateway.ts.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Assignees
No one assigned
Milestone
No milestone
Development
Successfully merging this pull request may close these issues.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
|