manager.go
Overview
The `manager.go` file defines the `Manager` type which is responsible for managing WebSocket client connections within the system. It handles the registration and unregistration of client connections, maintains the current set of active connections, and integrates with Prometheus metrics to track the number of active WebSocket connections.
By centralizing connection management, this component facilitates clean lifecycle management and resource cleanup of WebSocket clients. It operates using Go channels to asynchronously receive registration and unregistration requests, ensuring thread-safe updates to the connection pool.
Types and Functions
type Manager
type Manager struct {
connections map[*Connection]bool
register chan *Connection
unregister chan *Connection
prometheus *metrics.Prometheus
}
**Description:** `Manager` is a struct that maintains a registry of active WebSocket connections and manages their lifecycle events.
**Fields:**
Field | Type | Description |
|---|---|---|
`connections` | `map[*Connection]bool` | A thread-unsafe map used to keep track of active connections. The keys are pointers to `Connection` objects; the values are booleans (always `true`). |
`register` | `chan *Connection` | Channel through which new connections are registered. |
`unregister` | `chan *Connection` | Channel through which connections are unregistered. |
`prometheus` | `*metrics.Prometheus` | Reference to Prometheus metrics collector to update WebSocket connection counts. |
func NewManager(prometheus *metrics.Prometheus) *Manager
**Description:** Constructor function that initializes and returns a new `Manager` instance.
**Parameters:**
Name | Type | Description |
|---|---|---|
`prometheus` | `*metrics.Prometheus` | A Prometheus metrics instance for monitoring. |
**Returns:** `*Manager` — a pointer to a new `Manager` instance.
**Usage Example:**
prom := metrics.NewPrometheus()
manager := NewManager(prom)
func (m *Manager) Start()
**Description:** Starts the manager's event loop, which continuously listens for connection registration and unregistration events on its channels. This method blocks indefinitely and should be run as a separate goroutine.
**Behavior:**
On receiving a connection on
registerchannel:Adds the connection to the
connectionsmap.Increments the
WebsocketCountmetric.
On receiving a connection on
unregisterchannel:Removes the connection from the
connectionsmap.Closes the connection's
doneChanto signal cleanup.Decrements the
WebsocketCountmetric.
**Usage Example:**
go manager.Start()
func (m *Manager) ConnectionCount() int
**Description:** Returns the current number of active WebSocket connections managed by this `Manager`.
**Returns:** `int` — the count of active connections.
**Usage Example:**
count := manager.ConnectionCount()
fmt.Printf("Active connections: %d\n", count)
Important Implementation Details
Concurrency Model:
TheManageruses Go channels (registerandunregister) to safely handle concurrent connection lifecycle events. This design avoids explicit locking mechanisms by serializing access to theconnectionsmap through the select loop inStart().Connection Tracking:
Active connections are stored in a map with pointers toConnectionstructs as keys. The boolean values are placeholders (alwaystrue) to represent set membership.Prometheus Integration:
The manager updates a Prometheus metricWebsocketCountto track real-time active connection counts, providing observability for monitoring and alerting.Cleanup Signaling:
When a connection is unregistered, the manager closes itsdoneChanchannel. This is presumably listened to by theConnectionitself or other components for graceful shutdown and resource cleanup.
Interaction with Other Components
ConnectionType:
TheManagerinteracts closely with theConnectiontype (not defined in this file). EachConnectionrepresents a WebSocket client session. Connections are sent over theregisterandunregisterchannels to be managed.Prometheus Metrics (
metrics.Prometheus):
TheManagerrequires a Prometheus metrics collector passed during construction. It uses theWebsocketCountmetric to increment and decrement the count as connections come and go.WebSocket Server / Client Components:
Other parts of the system managing WebSocket communication delegate connection lifecycle events to theManagerby sending connections on theregisterandunregisterchannels.
Visual Diagram
classDiagram
class Manager {
-connections map[*Connection]bool
-register chan *Connection
-unregister chan *Connection
-prometheus *metrics.Prometheus
+Start()
+ConnectionCount() int
}
Manager --> "0..*" Connection : manages >
Manager --> metrics.Prometheus : uses >
**Diagram Explanation:**
The
Managerclass holds a map of activeConnectioninstances.It exposes methods
Start()(runs the event loop to manage connections) andConnectionCount()(returns the count of active connections).The
Managerdepends on a Prometheus metrics instance to update WebSocket connection counts.
Summary
The `manager.go` file encapsulates the functionality necessary to asynchronously manage WebSocket client connections within the system. It provides a concurrency-safe mechanism via channels to register and unregister connections, tracks active connections internally, and integrates with Prometheus for monitoring purposes. This module is essential for maintaining the health and scalability of the WebSocket communication layer, ensuring connections are properly tracked and cleaned up.