# Socket Domain Module Guide

> Purpose: migrate Socket.IO ownership into domain adapters without changing event
> names, rooms, acknowledgements, payloads, authentication, or reconnect behavior.

## 1. Current state

The active Socket runtime lives under `listeners/socketManger/`:

- `socket.js` is a 1,077-line central registrar/state holder;
- auction, live, chat, and call helpers contain business orchestration;
- validation is split across domain folders and one shared handshake validator;
- `socketForService` lets HTTP/cron code emit through the same server;
- persisted models and notification services are imported directly by listeners.

This is active high-risk runtime. No listener file is a dead-code candidate simply
because an event is hard to exercise locally.

## 2. Target structure

```text
src/modules/<domain>/interfaces/socket/
  <domain>.socket.js
  <domain>.socket.events.js
  <domain>.socket.dto.js
  <domain>.socket.policy.js

src/modules/shared/sockets/
  socket-server.js
  socket-context.js
  room-names.js
  ack.js
  registration-guard.js
```

Business orchestration remains in the owning domain service/repository. Shared socket
infrastructure knows Socket.IO transport concepts but not Product, Auction, Order, or
Chat business states.

## 3. Public contracts that must not drift

- inbound event names;
- outbound event names;
- room naming (`user:*`, `chat:*`, `auction:*`, and any live rooms);
- handshake requirements and actor identity resolution;
- payload field names and localization behavior;
- acknowledgement success/error shapes;
- viewer/participant counting semantics;
- reconnect, leave, and disconnect cleanup behavior;
- notification side effects;
- event ordering relied upon by mobile/web clients.

Typos or legacy aliases in event names are still contracts until an explicit deprecation
plan exists.

## 4. Responsibilities

### Shared socket transport

- owns `io` attachment and exactly-once server initialization;
- builds a safe socket context from the authenticated handshake;
- owns generic room/ack helpers and listener-registration guards;
- exposes an emit port for HTTP/cron services;
- never queries business models.

### Domain socket adapter

- registers a domain's inbound event names exactly once;
- validates transport payload and creates plain service input;
- calls the domain service/use-case;
- maps results through the socket DTO;
- emits/acks the existing contract;
- contains no raw Mongoose query.

### Socket policy

- decides whether the actor can enter, publish, bid, message, answer, or finish;
- uses domain constants/enums;
- has no Socket.IO or database dependency;
- is unit-tested as a decision matrix.

### Socket DTO

- returns a stable safe payload;
- does not return raw documents, password/auth fields, internal errors, or stacks;
- preserves current field names during migration.

## 5. Migration sequence

### Wave S0 — contract inventory

Capture every inbound/outbound event, room, ack, validator, helper, model/service
dependency, and disconnect side effect. Add a registrar snapshot test.

### Wave S1 — pure constants and DTOs

Extract event/room constants and pure payload mappers while the old registrar still owns
registration.

### Wave S2 — shared handshake and registration guard

Extract only the transport-neutral authentication context and ensure repeated
initialization cannot attach duplicate handlers.

### Wave S3 — chat/call adapters

Move chat then call registration behind public domain functions. Preserve all event
aliases and payload tests.

### Wave S4 — auction/live adapters

Move auction bidding and live streaming separately. These flows interact with cron,
payments, subscriptions, viewer caps, and notifications and therefore remain last.

### Wave S5 — compatibility registrar removal

Remove old registration code only after all event families delegate through domain
adapters and full socket QA is green.

## 6. Required tests

- handshake accepts/rejects the same inputs;
- unauthorized actors receive the same safe error behavior;
- every expected listener is registered once;
- initializing twice does not duplicate handlers;
- event-name and room-name snapshots;
- ack and emitted payload snapshots;
- no sensitive fields in payloads/logs;
- join/leave/disconnect idempotency;
- duplicate bid/message handling according to the existing contract;
- reconnect cleanup and participant/viewer counts;
- HTTP/cron emit bridge compatibility;
- focused socket tests, full `npm test`, syntax and Git checks.

## 7. Logging and errors

Listener code must use the shared redacting logger as it migrates. Do not log full
payloads, tokens, device identifiers, call credentials, or user secrets. Client-facing
errors remain localized and safe; internal stacks remain server-only.

The current audit found runtime `console.log` calls in socket handlers. They are a
cleanup target only when the corresponding domain adapter is migrated and covered by
tests; a global deletion pass is not approved.

## 8. Rollback

For every socket wave, the original `SocketEvents.socketConfig()` remains the public
entry and delegates to the extracted registrar. Rollback replaces that single delegation
with the prior inline registration. Event names and models never move in the same patch
as registration unless model compatibility has already been proven independently.

