# Poco::MongoDB

# class ReplicaSet

Library: MongoDB
Package: MongoDB
Header: Poco/MongoDB/ReplicaSet.h

## Description

Class for working with a MongoDB replica set.

This class provides comprehensive replica set support including: - Automatic topology discovery from seed servers - Primary election detection - Connection failover on errors - Read preference routing (primary, secondary, nearest, etc.) - Background topology monitoring - Server health checking

Usage example:

    ReplicaSet::Config config;
    config.seeds = {
        Net::SocketAddress("mongo1:27017"),
        Net::SocketAddress("mongo2:27017"),
        Net::SocketAddress("mongo3:27017")
    };
    config.setName = "rs0";
    config.readPreference = ReadPreference::primaryPreferred();

    ReplicaSet rs(config);
    Connection::Ptr conn = rs.getPrimaryConnection();
    // Use connection...

REQUIREMENTS: Requires MongoDB 5.1 or later. Earlier versions using the legacy isMaster command are not supported.

THREAD SAFETY: The ReplicaSet class is thread-safe. Multiple threads can call getConnection() and other methods concurrently. However, the returned Connection objects are NOT thread-safe and must be used by only one thread at a time, or protected by external synchronization.

For multi-threaded applications, use ReplicaSetConnection with connection pooling (PoolableObjectFactory pattern).

## Member Summary

Member Functions: configuration, getConnection, getPrimaryConnection, getSecondaryConnection, hasPrimary, readPreference, refreshTopology, setName, setReadPreference, setSocketFactory, startMonitoring, stopMonitoring, topology, waitForServerAvailability

## Nested Classes

### struct Config

Replica set configuration

## Constructors

### ReplicaSet

explicit ReplicaSet(
const Config & config
);

Creates a ReplicaSet with the given configuration. Performs initial topology discovery. Throws Poco::IOException if initial discovery fails.

### ReplicaSet

explicit ReplicaSet(
const std::vector < Net::SocketAddress > & seeds
);

Creates a ReplicaSet with default configuration and the given seed addresses. Performs initial topology discovery. Throws Poco::IOException if initial discovery fails.

### ReplicaSet

explicit ReplicaSet(
const std::string & uri
);

Creates a ReplicaSet from a MongoDB URI string. Format: mongodb://host1:port1,host2:port2,...?options

Supported URI options:

- replicaSet=name - Replica set name
- readPreference=mode - primary|primaryPreferred|secondary|secondaryPreferred|nearest
- connectTimeoutMS=ms - Connection timeout in milliseconds
- socketTimeoutMS=ms - Socket timeout in milliseconds
- heartbeatFrequencyMS=ms - Heartbeat frequency in milliseconds (default: 10000)
- reconnectRetries=n - Number of reconnection retries (default: 10)
- reconnectDelay=seconds - Delay between reconnection attempts in seconds (default: 1)

Example: mongodb://mongo1:27017,mongo2:27017,mongo3:27017/?replicaSet=rs0&readPreference=primaryPreferred

Throws Poco::SyntaxException if URI is invalid. Throws Poco::UnknownURISchemeException if scheme is not "mongodb".

### ReplicaSet

explicit ReplicaSet(
const ReplicaSetURI & uri
);

Creates a ReplicaSet from a ReplicaSetURI object. This allows for programmatic URI construction and modification before creating the replica set connection.

The ReplicaSetURI stores servers as strings without DNS resolution. This constructor resolves the server strings to SocketAddress objects. Servers that cannot be resolved are skipped and will be marked as unavailable during topology discovery.

Example:

    ReplicaSetURI uri;
    uri.addServer("host1:27017");
    uri.addServer("host2:27017");
    uri.setReplicaSet("rs0");
    uri.setReadPreference("primaryPreferred");
    ReplicaSet rs(uri);

Throws Poco::InvalidArgumentException if the URI contains no servers

    or if no servers can be resolved.

Throws Poco::IOException if initial discovery fails.

## Destructor

### ~ReplicaSet

virtual ~ReplicaSet();

Destroys the ReplicaSet and stops background monitoring.

## Member Functions

### configuration

[[nodiscard]]
Config configuration() const;

Returns a copy of replica set configuration.

### getConnection

Connection::Ptr getConnection(
const ReadPreference & readPref
);

Returns a connection to a server matching the read preference. Uses timeouts from Config. Returns null if no suitable server is available.

### getConnection

Connection::Ptr getConnection(
const ReadPreference & readPref,
const Poco::Timespan & connectTimeout,
const Poco::Timespan & socketTimeout
);

Returns a connection to a server matching the read preference, using the specified connect and socket timeouts instead of the values from Config. Returns null if no suitable server is available.

### getPrimaryConnection

Connection::Ptr getPrimaryConnection();

Returns a connection to the primary server. Returns null if no primary is available.

### getSecondaryConnection

Connection::Ptr getSecondaryConnection();

Returns a connection to a secondary server. Returns null if no secondary is available.

### hasPrimary

[[nodiscard]]
bool hasPrimary() const;

Returns true if a primary server is known.

### readPreference

[[nodiscard]]
ReadPreference readPreference() const;

Returns the default read preference.

### refreshTopology

void refreshTopology();

Forces an immediate topology refresh by querying all known servers.

### setName

[[nodiscard]]
std::string setName() const;

Returns the replica set name, or empty if not discovered.

### setReadPreference

void setReadPreference(
const ReadPreference & pref
);

Sets the default read preference.

### setSocketFactory

void setSocketFactory(
Connection::SocketFactory * factory
);

Sets the socket factory for creating connections. The factory can access timeout configuration via configuration().connectTimeoutSeconds and configuration().socketTimeoutSeconds.

Example:

    rs.setSocketFactory(&myCustomFactory);

### startMonitoring

void startMonitoring();

Starts the background monitoring thread if not already running.

### stopMonitoring

void stopMonitoring();

Stops the background monitoring thread.

### topology

[[nodiscard]]
TopologyDescription topology() const;

Returns a copy of the current topology description.

### waitForServerAvailability

Connection::Ptr waitForServerAvailability(
const ReadPreference & readPref
);

Waits for a server to become available for the given read preference. Uses timeouts from Config. This method coordinates waiting between multiple threads - only one thread performs the actual sleep and topology refresh, while others benefit from the refresh done by the first thread. Returns a connection if a server becomes available, or null if still unavailable. Thread-safe: uses internal synchronization to prevent redundant refresh attempts.

### waitForServerAvailability

Connection::Ptr waitForServerAvailability(
const ReadPreference & readPref,
const Poco::Timespan & connectTimeout,
const Poco::Timespan & socketTimeout
);

Waits for a server to become available for the given read preference, using the specified connect and socket timeouts instead of the values from Config. Returns a connection if a server becomes available, or null if still unavailable. Thread-safe: uses internal synchronization to prevent redundant refresh attempts.