mongo

package module
v3.0.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 20, 2026 License: MIT Imports: 7 Imported by: 0

README

socket.io-go-mongo

Go Reference Go Report Card

Description

A MongoDB adapter for Socket.IO server in Go, allowing to scale Socket.IO applications across multiple processes or servers using MongoDB Change Streams.

This adapter is compatible with the Node.js @socket.io/mongo-adapter package, enabling mixed Go and Node.js deployments.

Note: MongoDB must be configured as a Replica Set or Sharded Cluster to support Change Streams.

Installation

go get github.com/technance-foundation/socket.io/adapters/mongo/v3

Features

  • Multiple servers support via MongoDB Change Streams
  • Compatible with Node.js @socket.io/mongo-adapter for mixed deployments
  • Heartbeat-based node failure detection
  • Real-time communication between processes
  • Support for both capped collections and TTL indexes

How to use

Adapter
package main

import (
    "context"
    "fmt"
    "os"
    "os/signal"
    "syscall"

    "go.mongodb.org/mongo-driver/v2/mongo"
    "go.mongodb.org/mongo-driver/v2/mongo/options"
    mgadapter "github.com/technance-foundation/socket.io/adapters/mongo/v3/adapter"
    mgclient "github.com/technance-foundation/socket.io/adapters/mongo/v3"
    "github.com/technance-foundation/socket.io/servers/socket/v3"
)

func main() {
    client, err := mongo.Connect(options.Client().ApplyURI("mongodb://localhost:27017/?replicaSet=rs0"))
    if err != nil {
        panic(err)
    }
    defer client.Disconnect(context.Background())

    collection := client.Database("mydb").Collection("socket.io-adapter-events")

    mongoClient := mgclient.NewMongoClient(context.TODO(), collection)

    io := socket.NewServer(nil, nil)
    io.SetAdapter(&mgadapter.MongoAdapterBuilder{
        Mongo: mongoClient,
    })

    io.On("connection", func(args ...any) {
        s := args[0].(*socket.Socket)
        fmt.Printf("connect %s\n", s.Id())
    })

    exit := make(chan struct{})
    sig := make(chan os.Signal, 1)
    signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
    go func() {
        <-sig
        close(exit)
    }()
    <-exit
}
Emitter
package main

import (
    "context"

    "go.mongodb.org/mongo-driver/v2/mongo"
    "go.mongodb.org/mongo-driver/v2/mongo/options"
    mgclient "github.com/technance-foundation/socket.io/adapters/mongo/v3"
    mgemitter "github.com/technance-foundation/socket.io/adapters/mongo/v3/emitter"
)

func main() {
    client, err := mongo.Connect(options.Client().ApplyURI("mongodb://localhost:27017/?replicaSet=rs0"))
    if err != nil {
        panic(err)
    }
    defer client.Disconnect(context.Background())

    collection := client.Database("mydb").Collection("socket.io-adapter-events")

    mongoClient := mgclient.NewMongoClient(context.TODO(), collection)

    emitter := mgemitter.NewEmitter(mongoClient, nil)
    emitter.Emit("hello", "world")
    emitter.To("room1").Emit("hello", "world")
}

How it works

The adapter uses MongoDB Change Streams to detect new documents inserted into a shared collection. When a Socket.IO server needs to broadcast a message or perform a cross-node operation, it inserts a document into the MongoDB collection. All other servers watching the same collection via Change Streams will receive the notification and process the event accordingly.

Capped Collection vs TTL Index

You can use either a capped collection or a TTL index for automatic cleanup:

db.createCollection("socket.io-adapter-events", { capped: true, size: 1e6 })
TTL Index
db.collection("socket.io-adapter-events").createIndex(
    { createdAt: 1 },
    { expireAfterSeconds: 3600 }
)

When using a TTL index, set the AddCreatedAtField option to true:

opts := &mgadapter.MongoAdapterOptions{}
opts.SetAddCreatedAtField(true)

License

MIT

Documentation

Overview

Package mongo defines constants for MongoDB-based message types used in the Socket.IO adapter. These message types are used for inter-node communication in a clustered Socket.IO environment.

Package mongo provides MongoDB client wrapper for Socket.IO MongoDB adapter. This package offers a unified interface for MongoDB operations with event handling support using Change Streams for pub/sub communication.

Package mongo provides MongoDB-based adapter types and interfaces for Socket.IO clustering. These types define the message structures used for inter-node communication via MongoDB Change Streams.

Index

Constants

View Source
const (
	// SOCKETS requests a list of socket IDs from other nodes.
	SOCKETS adapter.MessageType = iota

	// ALL_ROOMS requests a list of all rooms from other nodes.
	ALL_ROOMS

	// REMOTE_JOIN instructs other nodes to join a socket to specified rooms.
	REMOTE_JOIN

	// REMOTE_LEAVE instructs other nodes to remove a socket from specified rooms.
	REMOTE_LEAVE

	// REMOTE_DISCONNECT instructs other nodes to disconnect a specific socket.
	REMOTE_DISCONNECT

	// REMOTE_FETCH requests detailed socket information from other nodes.
	REMOTE_FETCH

	// SERVER_SIDE_EMIT sends a server-side event to all other nodes.
	SERVER_SIDE_EMIT

	// BROADCAST broadcasts a message to all clients matching specified criteria.
	BROADCAST

	// BROADCAST_CLIENT_COUNT reports the number of matching clients from a node.
	BROADCAST_CLIENT_COUNT

	// BROADCAST_ACK sends a broadcast acknowledgment from a client.
	BROADCAST_ACK
)

Message types for Socket.IO MongoDB adapter inter-node communication. These constants define the different operations that can be performed across multiple Socket.IO server nodes using MongoDB as the message broker.

View Source
const VERSION = version.VERSION

Variables

View Source
var ErrNilMongoPacket = errors.New("cannot unmarshal into nil MongoPacket")

ErrNilMongoPacket indicates an attempt to unmarshal into a nil MongoPacket.

Functions

This section is empty.

Types

type AdapterEvent

type AdapterEvent struct {
	ID        bson.ObjectID       `bson:"_id,omitempty"`
	Uid       adapter.ServerId    `bson:"uid,omitempty"`
	Nsp       string              `bson:"nsp,omitempty"`
	Type      adapter.MessageType `bson:"type,omitempty"`
	Data      bson.RawValue       `bson:"data,omitempty"`
	CreatedAt bson.DateTime       `bson:"createdAt,omitempty"`
}

AdapterEvent represents a document stored in MongoDB for inter-node communication. This structure matches the Node.js @socket.io/mongo-adapter document format.

type MongoClient

type MongoClient struct {
	types.EventEmitter

	// Collection is the MongoDB collection used for pub/sub communication.
	// All adapter events are stored as documents in this collection.
	Collection *mongo.Collection

	// Context is the context used for MongoDB operations.
	// This context controls the lifecycle of subscriptions and operations.
	Context context.Context
}

MongoClient wraps a mongo.Collection and provides context management and event emitting capabilities for the Socket.IO MongoDB adapter.

The client uses a dedicated MongoDB collection for pub/sub communication. Documents are inserted for publishing and Change Streams are used for subscribing.

The client supports error event emission, which allows higher-level components to handle MongoDB-related errors gracefully.

func NewMongoClient

func NewMongoClient(ctx context.Context, collection *mongo.Collection) *MongoClient

NewMongoClient creates a new MongoClient with the given context and MongoDB collection.

Parameters:

  • ctx: The context that controls the lifecycle of MongoDB operations. When canceled, all subscriptions and pending operations will be terminated.
  • collection: A mongo.Collection instance that handles the actual MongoDB communication. The collection should be either a capped collection or have a TTL index.

Returns:

  • A pointer to the initialized MongoClient instance.

Example:

client, _ := mongo.Connect(options.Client().ApplyURI("mongodb://localhost:27017"))
collection := client.Database("mydb").Collection("socket.io-adapter-events")
mongoClient := NewMongoClient(context.Background(), collection)

Directories

Path Synopsis
Package adapter provides configuration options for the MongoDB-based Socket.IO adapter.
Package adapter provides configuration options for the MongoDB-based Socket.IO adapter.
Package emitter provides broadcast capabilities for Socket.IO via MongoDB.
Package emitter provides broadcast capabilities for Socket.IO via MongoDB.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL