Skip to content

feat: model shared manager namespace teardown - #264

Merged
electrohyun merged 3 commits into
mainfrom
feat/shared-manager-teardown
Aug 12, 2026
Merged

electrohyun merged 3 commits into
mainfrom
feat/shared-manager-teardown

Conversation

@electrohyun

@electrohyun electrohyun commented Aug 12, 2026 •

Copy link
Copy Markdown
Owner

Summary

Smocket previously exposed the Server object as every client socket's io identity and ignored the close argument of server-side socket.disconnect(close?). That was sufficient while disconnect was namespace-local, but it could not represent Socket.IO's actual boundary: several namespace sockets may share one client Manager while other sockets connected to the same server belong to independent Managers.

This PR introduces a host-neutral logical Manager and makes that identity observable through ClientSocket.io. It implements the grouping rules selected by ADR 0028, applies disconnect(true) to the connected and pending namespace sockets in that Manager, and preserves namespace-only behavior for disconnect(false). It models only observable namespace lifecycle and cleanup; it does not add Engine.IO transport, fallback, heartbeat, or automatic reconnection.

Socket.IO reference behavior

Socket.IO and socket.io-client 4.7.5 and 4.8.3 produced the same behavior in the paired probes.

Distinct namespaces on one normalized origin reused one cached Manager. A repeated namespace opened on an independent Manager, as did a connection using forceNew: true or multiplex: false. Closing a server socket with disconnect(true) affected only the namespace sockets on that Manager and left duplicate-namespace and opted-out Managers connected.

disconnect(false) closed only the addressed namespace. disconnect(true) fired each affected server socket's disconnecting and disconnect handlers synchronously, using server namespace disconnect, before returning. Namespace sockets were processed in connection order, and their clients subsequently observed io server disconnect in the same order.

The comparison also covers an admission that is still waiting in namespace middleware. If /auth is pending on a Manager shared with /, closing the root socket with disconnect(true) prevents /auth from connecting. Calling the saved middleware next() afterward produces neither connect nor connect_error, and any temporary membership created by that attempt is removed.

Manager identity and option forwarding

Each Smocket server now keeps one reusable Manager for its normalized origin. The first namespace claims that Manager, and later distinct namespaces reuse it. A namespace already claimed by the cached Manager receives a new Manager so two clients for the same namespace are not incorrectly collapsed into one connection group.

forceNew: true and multiplex: false bypass the cached Manager independently. ConnectOptions exposes both flags, and the public connect(url) path forwards them with auth and query data. The real and mock fixtures now forward the complete option object through both connectClient and the registration-free openClient path, so the same paired cases exercise option selection rather than a fixture-only approximation.

The Manager tracks client sockets by identity rather than using the Smocket Server as a group key. This is what allows one server to host a shared root/game group, a duplicate game connection, and explicit opt-out connections without one group's teardown affecting the others.

Disconnect lifecycle and ordering

disconnect(false) continues through the existing namespace teardown path. It synchronously clears the server socket's rooms and roster entry, emits the server lifecycle, and defers the corresponding client disconnect. A later disconnect(true) from that inactive server socket is a no-op, so it cannot close another namespace during the deferred client window.

disconnect(true) snapshots the Manager's connected clients in insertion order. Every affected server socket runs disconnecting, membership cleanup, and disconnect synchronously before the call returns. Client-side state changes remain behind the shared defer boundary, preserving the established server-before-client timing and the same cross-namespace order.

A server connection handler runs before the initiating client reaches its connect event and before that client is moved into the connected roster. Manager teardown therefore includes the active initiating server socket explicitly while deduplicating the ordinary connected path. This keeps disconnect(true) inside a connection handler connection-wide without changing client connect timing.

Ownership is checked against both server-socket identity and active lifecycle state. An old server socket retained across an explicit reconnect cannot close the new pairing, and a socket that already completed disconnect(false) cannot start a second Manager-wide teardown. The affected clients still clear their ids, rooms, roster entries, and pending client acknowledgements through the ordinary disconnect path. They may reconnect explicitly and receive fresh server sockets and id rooms; no automatic network reconnection is simulated.

Pending admission, cleanup, and reentrancy

The Manager now records a client when a connection attempt begins, not only after admission completes. That pending entry is settled on successful connection, middleware rejection, or cancellation. Manager-wide close cancels the remaining pending attempts after starting connected-socket teardown, while preserving the active connection-handler initiator described above.

Cancellation marks the attempt terminal, cleans the provisional server socket and any rooms joined by middleware, and removes the client from the Manager's pending roster. Every later auth, middleware, and deferred-completion boundary rechecks the same attempt identity, so a saved callback cannot revive a namespace after its Manager was closed.

The teardown paths are also safe under synchronous reentrancy. If a server disconnecting handler invokes client disconnects, the Manager's snapshot may still contain those clients, but the later entries observe their updated state and do not emit duplicate lifecycle events. The remaining markDisconnected callers all establish the connected-state precondition before changing client state, keeping the transition single-shot without a redundant unreachable guard.

Tests and documentation

src/manager-disconnect.test.ts adds nine paired cases covering namespace-only close, Manager-wide connection order and synchronous return timing, connection-handler initiation, pending middleware admission, reentrant client disconnects, duplicate and opted-out Manager isolation, acknowledgement and membership cleanup, explicit reconnect, and stale server sockets. Non-receipt is established with later marker deliveries rather than timeouts.

src/connect-url.test.ts separately pins Manager reuse for normalized origins and isolation for repeated namespaces, forceNew, and multiplex: false. The option-forwarding case opens clients through openClient; removing those forwarded flags makes the mock case fail on Manager identity, so the test covers the fixture seam as well as the core lookup implementation.

The conformance generator now publishes a Shared Manager disconnect area and records every paired case. ADR 0028 includes pending admission in the selected Manager boundary, and docs/differences.md no longer lists ignored disconnect(true) as an accidental gap. The Node dual run, Socket.IO 4.7 and 4.8 jobs, Chromium mock run, type checks, lint, formatting, coverage, package checks, and conformance drift check all pass. Codecov reports that every modified coverable line is exercised.

Related issue

Closes #254

Checklist

  • Tests added or updated
  • Behavior verified against real socket.io

@github-actions github-actions Bot added enhancement New feature or request 📏 l Pull request changes 200–999 lines labels Aug 12, 2026
@coderabbitai

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The PR adds Manager identity and reuse rules, models namespace-scoped and Manager-wide disconnect behavior, forwards connection options through mock and real fixtures, and adds tests and conformance coverage for teardown ordering, cleanup, reconnection, and stale sockets.

Changes

Shared Manager teardown

Layer / File(s) Summary
Connection options and forwarding
src/contract.ts, src/setup-mock-server.ts, src/setup-real-server.ts
ConnectOptions now supports forceNew and multiplex. Mock and real connection helpers forward these options.
Manager grouping and ownership
src/mock-server.ts, src/connect-url.test.ts
Connections reuse Managers by normalized origin unless the namespace is duplicated or Manager reuse is disabled. Client sockets expose and register with their Manager.
Manager-wide disconnect lifecycle
src/mock-server.ts, src/manager-disconnect.test.ts, docs/conformance.md, scripts/conformance-report.mjs
Disconnect handling tracks active ownership, performs synchronous server cleanup, defers client disconnect events, clears memberships, rejects pending acknowledgements, and supports explicit reconnects. Tests cover isolation and stale sockets.
Contract and known-gap documentation
src/contract.ts, docs/differences.md
The disconnect contract describes namespace-only and Manager-wide behavior. The obsolete known-gap entry is removed.

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

Sequence Diagram(s)

sequenceDiagram
  participant ClientSocket
  participant Manager
  participant ServerSocket
  participant Namespace
  ClientSocket->>Manager: request disconnect
  Manager->>ServerSocket: find active sockets in Manager
  ServerSocket->>Namespace: synchronously emit server lifecycle events
  ServerSocket-->>ClientSocket: emit client disconnect events
  ClientSocket->>Manager: unregister and clear connection state
Loading

Possibly related issues

Possibly related PRs

Suggested labels: test

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The implementation and tests address Manager grouping, disconnect lifecycle, option forwarding, cleanup, conformance updates, and linked issue #254 requirements.
Out of Scope Changes check ✅ Passed The documented changes support the linked issue objectives, with no unrelated code or documentation changes identified.
Title check ✅ Passed The title clearly and concisely identifies the main change: shared Manager namespace teardown.
Description check ✅ Passed The description directly explains the shared Manager behavior, disconnect lifecycle, option forwarding, tests, and documentation changes.

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.

@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 `@src/manager-disconnect.test.ts`:
- Around line 116-118: Extend the manager-selection coverage in the test around
openClient to create clients using both forceNew and multiplex: false, trigger
disconnect(true) on their shared Manager, and assert both opted-out clients
remain connected on the mock and real targets. Regenerate docs/conformance.md
after adding the dual-target case.
🪄 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: 1232f0db-1900-4536-8102-0fc743cfa349

📥 Commits

Reviewing files that changed from the base of the PR and between 6a17477 and 70e2422.

📒 Files selected for processing (9)
  • docs/conformance.md
  • docs/differences.md
  • scripts/conformance-report.mjs
  • src/connect-url.test.ts
  • src/contract.ts
  • src/manager-disconnect.test.ts
  • src/mock-server.ts
  • src/setup-mock-server.ts
  • src/setup-real-server.ts
💤 Files with no reviewable changes (1)
  • docs/differences.md

Comment thread src/manager-disconnect.test.ts Resolved
@codecov

codecov Bot commented Aug 12, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@electrohyun
electrohyun force-pushed the feat/shared-manager-teardown branch from 70e2422 to dd4f915 Compare August 12, 2026 12:50
@electrohyun
electrohyun merged commit 7fa7692 into main Aug 12, 2026
16 checks passed
@electrohyun
electrohyun deleted the feat/shared-manager-teardown branch August 12, 2026 13:05
@electrohyun electrohyun self-assigned this Aug 12, 2026
@github-project-automation github-project-automation Bot moved this to Done in smocket Aug 27, 2026
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: model shared-manager namespace teardown

1 participant