Skip to content

feat: add server close lifecycle - #200

Merged
electrohyun merged 4 commits into
mainfrom
feat/server-close
Aug 10, 2026
Merged

electrohyun merged 4 commits into
mainfrom
feat/server-close

Conversation

@electrohyun

@electrohyun electrohyun commented Aug 10, 2026 •

Copy link
Copy Markdown
Owner

Summary

new Server(url) registers itself in smocket's module-level origin registry, but there was no inverse operation. Constructing another server for the same origin did replace the registry entry, so new clients reached the replacement, but the old object and every lifecycle it had already started remained alive. Tests could create a fresh server in beforeEach; they could not explicitly shut that server down in afterEach.

This adds io.close(callback?). It marks the server and its namespaces closed before teardown starts, closes every namespace socket, completes the server-side disconnect lifecycle, disconnects the paired clients, and removes the server from the origin registry. A connection started immediately before close is rejected instead of being admitted on the next tick after close has resolved. The returned Promise<void> is shared by repeated calls, while the optional callback keeps the call shape accepted by socket.io 4.7 and 4.8.

What socket.io actually does

The behavior was measured on a real server before the mock was changed. The first implementation pinned the 4.8 promise return, and the 4.7 CI job exposed that the supported versions differ there. The common lifecycle is now tested through the callback; ServerContract carries the common void | Promise<void> return while smocket's concrete Server.close() keeps the 4.8 promise. The contract was also typechecked locally against the actual 4.7.5 packages. #201 tracks making that version-specific typecheck permanent in CI.

Observation socket.io behavior reproduced here
server socket lifecycle disconnecting, then disconnect, both with server shutting down
client lifecycle disconnect with transport close
connection started immediately before close never reaches connection; the client observes connect_error
pending client emitWithAck rejects with socket has been disconnected
pending server emitWithAck remains pending
armed server acknowledgement timeout remains armed and reports operation has timed out
completion API callback in 4.7 and 4.8; void in 4.7, Promise<void> in 4.8
later callback receives ERR_SERVER_NOT_RUNNING; the 4.8 promise still resolves

One measurement corrected the issue's original motivation. A faithful close() does not disarm an acknowledgement timeout that was already armed. Real socket.io lets that timer fire after close, so cancelling it in smocket would invent a different lifecycle and would also require inventing how the abandoned callback or promise settles. The test-runner guide now says that a test which arms such a timeout must settle it before teardown or drive it with fake timers. ADR 0020 records that decision instead of leaving close() described as a timer-reset API.

Smocket-specific lifecycle

The origin registry has no socket.io counterpart. Leaving the closed server registered would let a later connect(url) activate an object whose lifecycle had ended, so close removes its entry. The deletion is conditional on that server still owning the origin: closing an older object after new Server(url) installed a replacement cannot unregister the replacement. With no replacement, a later connect follows the existing missing-server behavior and emits connect_error.

Namespace and server-socket teardown share their first close promise, so concurrent or repeated shutdown paths do not fire the disconnect lifecycle twice. The closed state is visible at every asynchronous pairing boundary, so a delayed auth callback, middleware completion, or next-tick registration cannot revive the server after teardown. Closing a namespace also discards unclaimed connections. The mock test harness now awaits server.close() in afterEach, which makes the documented fresh-server recipe close the previous clients and then create a new adapter for the next test.

Tests and documentation

src/server-close.test.ts runs against both real socket.io and smocket. It covers the callback and repeated-close error, a connection started in the same turn as close, every-namespace teardown and reasons, both pending acknowledgement directions, and the armed timeout. The pending server acknowledgement uses close completion plus a microtask as its lifecycle marker; it does not prove non-settlement with a wall-clock timeout.

src/connect-url.test.ts separately pins the smocket-only registry rules: close returns the 4.8-style promise, a closed origin reports a missing server, and an old server cannot remove its replacement. The conformance report has a Server close area, and the lifecycle and test-runner consequences are documented in ADR 0020 and the integration guide.

Related issue

Closes #193

Follow-up tooling guard: #201

Checklist

  • Tests added or updated. The dual run, Chromium target, coverage, distribution tests, package checks, smoke test, chat-room example, and conformance check pass.
  • Behavior verified against real socket.io. The lifecycle runs against both socket.io 4.7 and 4.8 in CI.
  • Documentation updated. ADR 0020, the decision index, the test-runner guide, and the generated conformance report describe the final behavior.

@github-actions github-actions Bot added the enhancement New feature or request label Aug 10, 2026
@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

The PR adds Server.close(): Promise<void> with idempotent shutdown. It disconnects sockets, closes namespaces, conditionally removes the current registry entry, preserves armed acknowledgement timers, updates test cleanup, and adds conformance documentation and coverage.

Server close lifecycle

Layer / File(s) Summary
Close contract and teardown
src/contract.ts, src/mock-server.ts
The public contract adds close(). Server, namespace, and socket teardown become asynchronous and idempotent. Closing a server conditionally removes its registry entry and notifies paired clients.
Close validation and test integration
src/server-close.test.ts, src/connect-url.test.ts, src/setup-mock-server.ts
Tests cover promise reuse, namespace disconnection, reasons, rooms, acknowledgement behavior, timeouts, registry removal, replacement servers, and awaited test cleanup.
Close documentation and conformance
docs/conformance.md, docs/decisions/0020-close-follows-socket-lifecycle.md, docs/decisions/README.md, docs/test-runner-integration.md, scripts/conformance-report.mjs
Documentation records the close lifecycle, test-runner requirements, acknowledgement timer behavior, and the new conformance area.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Test
  participant Server
  participant Namespace
  participant ServerSocket
  participant ClientSocket
  Test->>Server: close()
  Server->>Namespace: close()
  Namespace->>ServerSocket: closeFromServer()
  ServerSocket->>ClientSocket: disconnect with transport close
  Server-->>Test: resolve shared close promise
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The implementation addresses issue #193 requirements for asynchronous close, socket teardown, acknowledgements, timeouts, registry ownership, and post-close connections.
Out of Scope Changes check ✅ Passed The changes remain within issue #193 scope and support the server close lifecycle, related tests, conformance reporting, and documentation.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Title check ✅ Passed The title clearly and concisely identifies the main change: adding the server close lifecycle.
Description check ✅ Passed The description directly explains the server close API, lifecycle behavior, registry handling, tests, and documentation changes.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch

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.

@codecov

codecov Bot commented Aug 10, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.09524% with 5 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/mock-server.ts 88.09% 0 Missing and 5 partials ⚠️

📢 Thoughts on this report? Let us know!

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/test-runner-integration.md`:
- Around line 125-128: Update the lifecycle explanation around the
beforeEach/afterEach flow to state that afterEach calls io.close(),
disconnecting clients and closing the old server, while beforeEach creates a new
Server with a new adapter. Remove claims that clients from the previous server
remain usable or that empty rooms result only from server replacement, and align
the wording with the behavior covered by server-close.test.ts.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: d117f7c9-33ea-47dc-8498-a9ce4545fbd4

📥 Commits

Reviewing files that changed from the base of the PR and between 7d41180 and 9563b78.

📒 Files selected for processing (10)
  • docs/conformance.md
  • docs/decisions/0020-close-follows-socket-lifecycle.md
  • docs/decisions/README.md
  • docs/test-runner-integration.md
  • scripts/conformance-report.mjs
  • src/connect-url.test.ts
  • src/contract.ts
  • src/mock-server.ts
  • src/server-close.test.ts
  • src/setup-mock-server.ts

Comment thread docs/test-runner-integration.md Resolved
@electrohyun
electrohyun force-pushed the feat/server-close branch 2 times, most recently from ce5fd23 to d6b6ba5 Compare August 10, 2026 04:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request 📏 l Pull request changes 200–999 lines

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

feat: give a server a way to shut down

1 participant