21#include "cbl/CBLReplicator.h"
22#include "cbl/CBLDefaults.h"
28#include <unordered_map>
48 internal::check(endpoint, error);
49 return Endpoint(endpoint);
52#ifdef COUCHBASE_ENTERPRISE
68 _ref = std::shared_ptr<CBLEndpoint>(
ref, [](
auto r) {
73 std::shared_ptr<CBLEndpoint> _ref;
86 static Authenticator
sessionAuthenticator(std::string_view sessionId, std::optional<std::string_view> cookieName =std::nullopt) {
88 if ( cookieName ) cname = *cookieName;
101 _ref = std::shared_ptr<CBLAuthenticator>(
ref, [](
auto r) {
106 std::shared_ptr<CBLAuthenticator> _ref;
117#ifdef COUCHBASE_ENTERPRISE
136 fleece::slice collection,
137 fleece::slice documentID,
138 fleece::Dict properties,
139 fleece::slice keyPath,
140 fleece::slice input)>;
146 fleece::slice collection,
147 fleece::slice documentID,
148 fleece::Dict properties,
149 fleece::slice keyPath,
151 std::optional<std::string_view> algorithm,
152 std::optional<std::string_view> keyID)>;
170 fleece::MutableArray
channels = fleece::MutableArray::newArray();
173 fleece::MutableArray
documentIDs = fleece::MutableArray::newArray();
207 std::vector<CollectionConfiguration>
collections()
const {
return _collections;}
238 #ifdef __CBL_REPLICATOR_NETWORK_INTERFACE__
242 std::string networkInterface;
251 fleece::MutableDict
headers = fleece::MutableDict::newDict();
270#ifdef COUCHBASE_ENTERPRISE
276#ifdef COUCHBASE_ENTERPRISE
303 #ifdef __CBL_REPLICATOR_NETWORK_INTERFACE__
304 if (!networkInterface.empty())
305 conf.networkInterface =
slice(networkInterface);
311#ifdef COUCHBASE_ENTERPRISE
319 std::vector<CollectionConfiguration> _collections;
335 _context = std::make_shared<ReplicatorContext>();
341 std::vector<CBLCollectionConfiguration> colConfigs;
342 for (
int i = 0; i < collections.size(); i++) {
361 auto ctx = (ReplicatorContext*)context;
362 return ctx->collectionMap.find(doc.collection())->second.pushFilter(doc, flags);
371 auto ctx = (ReplicatorContext*)context;
372 return ctx->collectionMap.find(doc.collection())->second.pullFilter(doc, flags);
382 auto localDoc =
Document(cLocalDoc);
383 auto remoteDoc =
Document(cRemoteDoc);
384 auto collection = localDoc ? localDoc.collection() : remoteDoc.collection();
386 auto ctx = (ReplicatorContext*)context;
387 auto resolved = ctx->collectionMap.find(collection)->second.
388 conflictResolver((std::string_view)
slice(docID), localDoc, remoteDoc);
390 auto ref = resolved.ref();
391 if (
ref &&
ref != cLocalDoc &&
ref != cRemoteDoc) {
397 colConfigs.push_back(colConfig);
398 _context->collectionMap.insert({col.
collection(), col});
403 c_config.
context = _context.get();
405#ifdef COUCHBASE_ENTERPRISE
418 auto ctx = (ReplicatorContext*)context;
419 auto r = ctx->encryptor(scope, collection, documentID, properties, keyPath, input);
420 if (error) *error = r.error;
439 auto ctx = (ReplicatorContext*)context;
440 auto toOpt = [](
FLString s) -> std::optional<std::string_view> {
441 return s.buf ? std::optional<std::string_view>{{(
const char*)s.buf, s.size}} : std::nullopt;
443 auto r = ctx->decryptor(scope, collection, documentID, properties, keyPath, input,
444 toOpt(algorithm), toOpt(keyID));
445 if (error) *error = r.error;
453 internal::check(_ref, error);
503 internal::check(result !=
nullptr, error);
518 internal::check(pending || error.
code == 0, error);
542 const std::vector<CBLReplicatedDocument>>;
564 unsigned numDocuments,
567 std::vector<CBLReplicatedDocument> docs(&documents[0], &documents[numDocuments]);
571 using CollectionToReplCollectionMap = std::unordered_map<Collection, CollectionConfiguration>;
573 struct ReplicatorContext {
574 CollectionToReplCollectionMap collectionMap;
575#ifdef COUCHBASE_ENTERPRISE
580 std::shared_ptr<ReplicatorContext> _context;
590 ,_context(other._context)
596 :RefCounted((RefCounted&&)other)
597 ,_context(std::move(other._context))
604 RefCounted::operator=(other);
605 _context = other._context;
613 RefCounted::operator=((RefCounted&&)other);
614 _context = std::move(other._context);
#define CBL_REFCOUNTED_WITHOUT_COPY_MOVE_BOILERPLATE(CLASS, SUPER, C_TYPE)
Definition Base.hh:140
#define CBL_ASSUME_NONNULL_END
#define CBL_ASSUME_NONNULL_BEGIN
Authentication credentials for a remote server.
Definition Replicator.hh:77
friend class ReplicatorConfiguration
Definition Replicator.hh:93
CBLAuthenticator *_Nullable ref() const
Definition Replicator.hh:95
static Authenticator basicAuthenticator(std::string_view username, std::string_view password)
Creates a basic authenticator authenticator using username/password credentials.
Definition Replicator.hh:80
static Authenticator sessionAuthenticator(std::string_view sessionId, std::optional< std::string_view > cookieName=std::nullopt)
Creates a sesssion authenticator using a Couchbase Sync Gateway login session identifier,...
Definition Replicator.hh:86
A collection to replicate, along with its collection-specific replication settings such as filters an...
Definition Replicator.hh:157
fleece::MutableArray documentIDs
Optional set of document IDs to replicate.
Definition Replicator.hh:173
Collection collection() const
The collection.
Definition Replicator.hh:166
ReplicationFilter pushFilter
Optional callback to filter which docs are pushed.
Definition Replicator.hh:176
fleece::MutableArray channels
Optional set of channels to pull from.
Definition Replicator.hh:170
ReplicationFilter pullFilter
Optional callback to filter which docs are pulled.
Definition Replicator.hh:179
CollectionConfiguration(Collection collection)
Creates CollectionConfiguration with the collection.
Definition Replicator.hh:160
ConflictResolver conflictResolver
Optional conflict-resolver callback.
Definition Replicator.hh:183
A Collection is a container for documents within a database.
Definition Collection.hh:131
CBLCollection *_Nullable ref() const
Returns a pointer to the underlying C object (CBLCollection), or NULL if this is a null reference.
Definition Collection.hh:373
A Couchbase Lite database, which is a container for collections of documents.
Definition Database.hh:147
CBLDatabase *_Nullable ref() const
Returns a pointer to the underlying C object (CBLDatabase), or NULL if this is a null reference.
Definition Database.hh:411
An immutable, in-memory copy of a document read from a collection.
Definition Document.hh:33
The replication endpoint representing the location of a database to replicate with.
Definition Replicator.hh:36
static Endpoint databaseEndpoint(Database db)
Creates a database endpoint with another local database.
Definition Replicator.hh:54
friend class ReplicatorConfiguration
Definition Replicator.hh:60
static Endpoint urlEndpoint(std::string_view url)
Creates a URL endpoint with a given URL.
Definition Replicator.hh:45
CBLEndpoint *_Nullable ref() const
Definition Replicator.hh:62
A token representing a registered listener; instances are returned from the various methods that regi...
Definition Base.hh:177
static void call(void *_Nullable context, Args... args)
Definition Base.hh:228
std::function< void(Args...)> Callback
Definition Base.hh:180
The configuration of a replicator.
Definition Replicator.hh:194
CBLReplicatorType replicatorType
Replicator type : Push, pull or both.
Definition Replicator.hh:214
std::string pinnedServerCertificate
An X.509 cert (PEM or DER) to "pin" for TLS connections.
Definition Replicator.hh:267
unsigned maxAttempts
Max retry attempts where the initial connect to replicate counts toward the given value.
Definition Replicator.hh:228
Authenticator authenticator
Authentication credentials, if needed.
Definition Replicator.hh:247
unsigned heartbeat
The heartbeat interval in seconds.
Definition Replicator.hh:236
ReplicatorConfiguration(std::vector< CollectionConfiguration >collections, Endpoint endpoint)
Creates a config with a list of collections and per-collection configurations to replicate and an end...
Definition Replicator.hh:199
unsigned maxAttemptWaitTime
Max wait time between retry attempts in seconds.
Definition Replicator.hh:231
std::string trustedRootCertificates
Set of anchor certs (PEM format).
Definition Replicator.hh:269
CBLProxySettings *_Nullable proxy
HTTP client proxy settings.
Definition Replicator.hh:249
Endpoint endpoint() const
Returns the configured endpoint.
Definition Replicator.hh:210
friend class Replicator
Definition Replicator.hh:285
bool acceptParentDomainCookies
The option to remove the restriction that does not allow the replicator to save the parent-domain coo...
Definition Replicator.hh:262
bool continuous
Continuous replication or single-shot replication.
Definition Replicator.hh:216
std::vector< CollectionConfiguration > collections() const
Returns the configured collections.
Definition Replicator.hh:207
PropertyDecryptor documentPropertyDecryptor
Optional callback to decrypt encrypted properties during pull replication.
Definition Replicator.hh:281
bool acceptOnlySelfSignedServerCertificate
Accept only self-signed server certificates; any other certificates are rejected.
Definition Replicator.hh:273
fleece::MutableDict headers
Extra HTTP headers to add to the WebSocket request.
Definition Replicator.hh:251
PropertyEncryptor documentPropertyEncryptor
Optional callback to encrypt encryptable properties during push replication.
Definition Replicator.hh:279
bool enableAutoPurge
Enabled auto-purge or not.
Definition Replicator.hh:222
void stop()
Stops a running replicator, asynchronously.
Definition Replicator.hh:468
Replicator(Replicator &&other) noexcept
Move constructor.
Definition Replicator.hh:595
cbl::ListenerToken< Replicator, bool, const std::vector< CBLReplicatedDocument > > DocumentReplicationListener
A document replication listener that notifies you when documents are replicated.
Definition Replicator.hh:541
CBLReplicatorStatus status() const
Returns the replicator's current status.
Definition Replicator.hh:485
Replicator() noexcept
Constructs a null reference (one that points to no object).
Definition Replicator.hh:582
Replicator(const Replicator &other) noexcept
Copy constructor.
Definition Replicator.hh:588
DocumentReplicationListener addDocumentReplicationListener(DocumentReplicationListener::Callback callback)
Registers a listener that will be called when documents are replicated.
Definition Replicator.hh:547
bool isDocumentPending(std::string_view docID, Collection &collection) const
Indicates whether the document with the given ID in the given collection has local changes that have ...
Definition Replicator.hh:515
Replicator & operator=(Replicator &&other) noexcept
Move assignment.
Definition Replicator.hh:612
void setHostReachable(bool r)
Informs the replicator whether it's considered possible to reach the remote host with the current net...
Definition Replicator.hh:475
Replicator & operator=(const Replicator &other) noexcept
Copy assignment.
Definition Replicator.hh:603
void setSuspended(bool s)
Puts the replicator in or out of "suspended" state.
Definition Replicator.hh:482
cbl::ListenerToken< Replicator, const CBLReplicatorStatus & > ChangeListener
A change listener that notifies you when the replicator's status changes.
Definition Replicator.hh:526
void clear()
Releases the underlying C CBLReplicator and drops the C++ collection-configuration map.
Definition Replicator.hh:621
void start(bool resetCheckpoint=false)
Starts a replicator, asynchronously.
Definition Replicator.hh:463
Replicator(const ReplicatorConfiguration &config)
Creates a new replicator using the specified config.
Definition Replicator.hh:326
ChangeListener addChangeListener(ChangeListener::Callback callback)
Registers a listener that will be called when the replicator's status changes.
Definition Replicator.hh:531
fleece::Dict pendingDocumentIDs(Collection &collection) const
Indicates which documents in the given collection have local changes that have not yet been pushed to...
Definition Replicator.hh:500
std::string correlationID() const
Returns the ID used to correlate the replication session with the remote endpoint.
Definition Replicator.hh:490
CBLReplicator *_Nullable ref() const
Returns a pointer to the underlying C object (CBLReplicator), or NULL if this is a null reference.
Definition Replicator.hh:582
FLSliceResult FLStringResult
CBL_PUBLIC const bool kCBLDefaultReplicatorAcceptParentCookies
CBLINLINE const CBLDocument * CBLDocument_Retain(const CBLDocument *_cbl_nullable t)
struct CBLDocument CBLDocument
struct CBLRefCounted CBLRefCounted
struct CBLAuthenticator CBLAuthenticator
_cbl_warn_unused CBLAuthenticator * CBLAuth_CreateSession(FLString sessionID, FLString cookieName)
struct CBLEndpoint CBLEndpoint
void CBLReplicator_Start(CBLReplicator *replicator, bool resetCheckpoint)
_cbl_warn_unused CBLAuthenticator * CBLAuth_CreatePassword(FLString username, FLString password)
FLDict _cbl_nullable CBLReplicator_PendingDocumentIDs(CBLReplicator *, const CBLCollection *collection, CBLError *_cbl_nullable outError)
bool CBLReplicator_IsDocumentPending(CBLReplicator *repl, FLString docID, const CBLCollection *collection, CBLError *_cbl_nullable outError)
void CBLReplicator_Stop(CBLReplicator *)
struct CBLReplicator CBLReplicator
_cbl_warn_unused CBLReplicator *_cbl_nullable CBLReplicator_Create(const CBLReplicatorConfiguration *, CBLError *_cbl_nullable outError)
_cbl_warn_unused FLStringResult CBLReplicator_CorrelationID(CBLReplicator *)
CBLReplicatorStatus CBLReplicator_Status(CBLReplicator *)
void CBLEndpoint_Free(CBLEndpoint *_cbl_nullable)
_cbl_warn_unused CBLListenerToken * CBLReplicator_AddChangeListener(CBLReplicator *, CBLReplicatorChangeListener, void *_cbl_nullable context)
void CBLAuth_Free(CBLAuthenticator *_cbl_nullable)
void CBLReplicator_SetSuspended(CBLReplicator *repl, bool suspended)
void CBLReplicator_SetHostReachable(CBLReplicator *, bool reachable)
_cbl_warn_unused CBLEndpoint * CBLEndpoint_CreateWithLocalDB(CBLDatabase *)
_cbl_warn_unused CBLListenerToken * CBLReplicator_AddDocumentReplicationListener(CBLReplicator *, CBLDocumentReplicationListener, void *_cbl_nullable context)
_cbl_warn_unused CBLEndpoint *_cbl_nullable CBLEndpoint_CreateWithURL(FLString url, CBLError *_cbl_nullable outError)
kCBLReplicatorTypePushAndPull
const struct _FLDict * FLDict
fleece::slice slice
Convenience alias for fleece::slice, a non-owning view of a byte range.
Definition Base.hh:49
std::function< Document(std::string_view docID, const Document localDoc, const Document remoteDoc)> ConflictResolver
Replication Conflict Resolver Function Callback.
Definition Replicator.hh:113
std::function< EncryptionResult( fleece::slice scope, fleece::slice collection, fleece::slice documentID, fleece::Dict properties, fleece::slice keyPath, fleece::slice input)> PropertyEncryptor
Property Encryptor Function Callback.
Definition Replicator.hh:134
std::function< bool(Document, CBLDocumentFlags flags)> ReplicationFilter
Replication Filter Function Callback.
Definition Replicator.hh:110
CollectionConfiguration ReplicationCollection
Deprecated alias for backward compatibility.
Definition Replicator.hh:191
std::function< DecryptionResult( fleece::slice scope, fleece::slice collection, fleece::slice documentID, fleece::Dict properties, fleece::slice keyPath, fleece::slice input, std::optional< std::string_view > algorithm, std::optional< std::string_view > keyID)> PropertyDecryptor
Property Decryptor Function Callback.
Definition Replicator.hh:144
CBLConflictResolver _cbl_nullable conflictResolver
CBLCollection * collection
CBLReplicationFilter _cbl_nullable pullFilter
FLArray _cbl_nullable documentIDs
FLArray _cbl_nullable channels
CBLReplicationFilter _cbl_nullable pushFilter
void *_cbl_nullable context
unsigned maxAttemptWaitTime
const CBLProxySettings *_cbl_nullable proxy
CBLCollectionConfiguration * collections
CBLReplicatorType replicatorType
FLSlice pinnedServerCertificate
bool acceptParentDomainCookies
FLDict _cbl_nullable headers
CBLAuthenticator *_cbl_nullable authenticator
CBLDocumentPropertyEncryptor _cbl_nullable documentPropertyEncryptor
CBLDocumentPropertyDecryptor _cbl_nullable documentPropertyDecryptor
FLSlice trustedRootCertificates
bool acceptOnlySelfSignedServerCertificate
Result returned by a PropertyDecryptor callback.
Definition Replicator.hh:127
fleece::alloc_slice plaintext
Decrypted data. Empty = leave property in encrypted form.
Definition Replicator.hh:128
CBLError error
Optional error. Non-zero aborts replication for this doc.
Definition Replicator.hh:129
Result returned by a PropertyEncryptor callback.
Definition Replicator.hh:119
std::optional< std::string > keyID
Optional key identifier.
Definition Replicator.hh:122
fleece::alloc_slice ciphertext
Encrypted data. Empty = skip (results in a crypto error).
Definition Replicator.hh:120
CBLError error
Optional error. Non-zero aborts replication for this doc.
Definition Replicator.hh:123
std::optional< std::string > algorithm
Optional algorithm name. Default: "CB_MOBILE_CUSTOM".
Definition Replicator.hh:121