# Component: SessionManager

## Purpose

Tracks active client sessions, mapping session IDs to client metadata. Provides session creation, validation, and termination for the gRPC service layer.

## Location

`src/ZB.MOM.WW.LmxProxy.Host/Sessions/SessionManager.cs`

## Responsibilities

- Create new sessions with unique identifiers when clients connect.
- Validate session IDs on every data operation.
- Track session metadata (client ID, API key, connection time, last activity).
- Terminate sessions on client disconnect.
- Provide session listing for monitoring and status reporting.

## 1. Session Storage

- Sessions are stored in a `ConcurrentDictionary<string, SessionInfo>` (lock-free, thread-safe).
- Session state is in-memory only — all sessions are lost on service restart.
- `ActiveSessionCount` property returns the current count of tracked sessions.

## 2. Session Lifecycle

### 2.1 Creation

`CreateSession(clientId, apiKey)`:
- Generates a unique session ID: `Guid.NewGuid().ToString("N")` (32-character lowercase hex string, no hyphens).
- Creates a `SessionInfo` record with `ConnectedAt` and `LastActivity` set to `DateTime.UtcNow`.
- Stores the session in the dictionary.
- Returns the session ID to the client.

### 2.2 Validation

`ValidateSession(sessionId)`:
- Looks up the session ID in the dictionary.
- If found, updates `LastActivity` to `DateTime.UtcNow` and returns `true`.
- If not found, returns `false`.

### 2.3 Termination

`TerminateSession(sessionId)`:
- Removes the session from the dictionary.
- Returns `true` if the session existed, `false` otherwise.

### 2.4 Query

- `GetSession(sessionId)` — Returns `SessionInfo` or `null` if not found.
- `GetAllSessions()` — Returns `IReadOnlyList<SessionInfo>` snapshot of all active sessions.

## 3. SessionInfo

| Field | Type | Description |
|-------|------|-------------|
| SessionId | string | 32-character hex GUID |
| ClientId | string | Client-provided identifier |
| ApiKey | string | API key used for authentication |
| ConnectedAt | DateTime | UTC time of session creation |
| LastActivity | DateTime | UTC time of last operation (updated on each validation) |
| ConnectedSinceUtcTicks | long | `ConnectedAt.Ticks` for gRPC response serialization |

## 4. Disposal

`Dispose()` clears all sessions from the dictionary. No notifications are sent to connected clients.

## Dependencies

None. SessionManager is a standalone in-memory store with no external dependencies.

## Interactions

- **GrpcServer** calls `CreateSession` on Connect, `ValidateSession` on every data operation, and `TerminateSession` on Disconnect.
- **HealthAndMetrics** reads `ActiveSessionCount` for health check data.
- **StatusReportService** reads session information for the status dashboard.
