跳到主要内容

SyncManager

Defined in: rxdb-plugin-sync/src/SyncManager.ts:50

同步管理器

负责整库与单仓库两个粒度的推拉同步:

  • pull / push / sync:整库
  • pullRepository / pushRepository / syncRepository / bulkSync:按仓库
  • getRepositorySyncStatus / checkRepositoryUpdates / cleanupExpired:状态与清理
  • getRepositoryDependencyGraph / getRepositorySyncOrder:依赖图与同步顺序

Remarks​

US-025 阶段 D 之前这些入口挂在 @aiao/rxdb-plugin-history 的 VersionManager 上。 切开的理由是两件事的生命周期本就不同:撤销重做要在第一条 rxdb_change 之前就位, 推拉同步则只在配了远端时才有意义。

切开之后仍有一条单向耦合:一次同步往返结束时 undo 边界要作废、待拉计数要结算, 而那些状态的主人是历史侧。它经 SyncHistoryBridge 这一张窄接口相遇 —— 本插件 inject: ['plugin:history'],历史插件则对本包一无所知。

Properties​

history​

readonly history: SyncHistoryBridge;

Defined in: rxdb-plugin-sync/src/SyncManager.ts:74

历史侧借来的那一小块面,由 rxdb.versionManager.syncBridge 提供


rxdb​

readonly rxdb: RxDB;

Defined in: rxdb-plugin-sync/src/SyncManager.ts:73

宿主实例

Accessors​

pushInFlight​

Get Signature​

get pushInFlight(): PushInFlightRegistry;

Defined in: rxdb-plugin-sync/src/SyncManager.ts:64

Internal

「哪些变更此刻正在飞往远端」的登记处。

Remarks​

push 与 undo 唯一的会合点,实例的主人在历史侧(rxdb.versionManager.pushInFlight)。 两边读的必须是同一个,见 PushInFlightRegistry:push 在远端往返之前认领区间, undo 把认领区间当成已推 —— 各持一份,往返窗口内的一次撤销就会造成永久分叉。

Returns​

PushInFlightRegistry

Methods​

bulkSync()​

bulkSync(options?): Promise<BulkSyncResult>;

Defined in: rxdb-plugin-sync/src/SyncManager.ts:563

批量同步多个 Repository

在单次操作中同步多个 Repository,支持顺序或并发执行。

Parameters​

ParameterTypeDescription
options?BulkSyncOptions批量同步选项

Returns​

Promise<BulkSyncResult>

批量同步结果(包含成功/失败计数)

Example​

// 顺序同步所有已启用的 Repository
const result = await rxdb.syncManager.bulkSync();
console.log(`成功: ${result.succeeded},失败: ${result.failed}`);

// 同步指定 Repository
const result = await rxdb.syncManager.bulkSync({
repositories: [
{ namespace: 'public', entity: 'Todo' },
`{ namespace: 'public', entity: 'User' }`
]
});

// 并发模式仅 pull
const result = await rxdb.syncManager.bulkSync({
concurrent: true,
concurrency: 3,
push: false
});

// 检查每项结果
for (const item of result.results) {
if (item.success) {
console.log(`${item.repository.entity}: 已拉取 ${item.result?.pullResult.pulled ?? 0} 条`);
} else {
console.error(`${item.repository.entity}: ${item.error.message}`);
}
}

checkRepositoryUpdates()​

checkRepositoryUpdates(namespace, entity): Promise<CheckRepositoryUpdatesResult>;

Defined in: rxdb-plugin-sync/src/SyncManager.ts:450

检查远程是否有更新,不下载数据

仅查询远程有多少新变更,不实际拉取数据。 适用于显示「有 N 条远程更新」提示,节省带宽和时间。

Parameters​

ParameterTypeDescription
namespacestring实体命名空间(如 "public")
entitystring实体名称(如 "Todo")

Returns​

Promise<CheckRepositoryUpdatesResult>

更新检查结果

Example​

// 检查 Todo 是否有远程更新
const result = await rxdb.syncManager.checkRepositoryUpdates('public', 'Todo');
if (result.hasUpdates) {
console.log(`有 ${result.pendingCount} 条更新可拉取`);
// 用户点击「更新」按钮后再调用 pullRepository()
}

cleanupExpired()​

cleanupExpired(
namespace,
entity,
options?
): Promise<CleanupExpiredResult>;

Defined in: rxdb-plugin-sync/src/SyncManager.ts:422

清理不再满足过滤条件的本地过期数据

用于 SyncType.Filter 场景,删除不满足 filter 条件的本地数据 例如:清理超过 30 天的订单数据

Parameters​

ParameterTypeDescription
namespacestring实体命名空间
entitystring实体名称
options?CleanupExpiredOptions清理选项

Returns​

Promise<CleanupExpiredResult>

清理结果

Example​

const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
const { removed } = await rxdb.syncManager.cleanupExpired('public', 'Order', {
filter: {
combinator: 'and',
rules: [{ field: 'updatedAt', operator: '>=', value: thirtyDaysAgo }]
}
});
console.log(`Removed ${removed} expired records`);

destroy()​

destroy(): void;

Defined in: rxdb-plugin-sync/src/SyncManager.ts:85

拆掉 init 装上的全部监听与订阅

Returns​

void


getAllRepositorySyncStatus()​

getAllRepositorySyncStatus(filter?): Promise<RepositorySyncStatus[]>;

Defined in: rxdb-plugin-sync/src/SyncManager.ts:503

获取所有 Repository 的同步状态

返回所有已注册实体的状态,支持可选过滤。

Parameters​

ParameterTypeDescription
filter?GetAllRepositorySyncStatusFilter可选过滤条件

Returns​

Promise<RepositorySyncStatus[]>

Repository 同步状态数组

Example​

// 获取全部状态
const statuses = await rxdb.syncManager.getAllRepositorySyncStatus();

// 仅获取有待处理变更的 Repository
const pending = await rxdb.syncManager.getAllRepositorySyncStatus({
hasPendingChanges: true
});

// 仅获取已启用的全量同步 Repository
const fullSync = await rxdb.syncManager.getAllRepositorySyncStatus({
syncType: ['full'],
enabled: true
});

getCurrentBranch()​

getCurrentBranch(): Promise<RxDBBranch>;

Defined in: rxdb-plugin-sync/src/SyncManager.ts:113

取当前分支;没有激活分支时激活(或新建)main。

Returns​

Promise<RxDBBranch>

Remarks​

同步链路里每条远端事件都要调它(sync-listeners 的 filterByBranch), 热路径不开事务,见 getCurrentBranch。


getLocalRepositories()​

getLocalRepositories(): Promise<{
adapter: LocalRxDBAdapter;
branchRepository: LocalRxDBBranchRepository;
changeRepository: LocalRxDBChangeRepository;
}>;

Defined in: rxdb-plugin-sync/src/SyncManager.ts:97

取本地适配器上的系统表仓库

Returns​

Promise<{ adapter: LocalRxDBAdapter; branchRepository: LocalRxDBBranchRepository; changeRepository: LocalRxDBChangeRepository; }>


getRemoteRepositories()​

getRemoteRepositories(): Promise<{
adapter: RemoteRxDBAdapter;
branchRepository: RemoteRxDBBranchRepository;
changeRepository: RemoteRxDBChangeRepository;
}>;

Defined in: rxdb-plugin-sync/src/SyncManager.ts:102

取远端适配器上的系统表仓库

Returns​

Promise<{ adapter: RemoteRxDBAdapter; branchRepository: RemoteRxDBBranchRepository; changeRepository: RemoteRxDBChangeRepository; }>


getRepositoryDependencyGraph()​

getRepositoryDependencyGraph(): DependencyGraph;

Defined in: rxdb-plugin-sync/src/SyncManager.ts:601

获取所有 Repository 的依赖图

分析实体关系(MANY_TO_ONE、ONE_TO_ONE)以构建依赖图, 展示各 Repository 之间的依赖关系。

Returns​

DependencyGraph

包含依赖关系的依赖图

Example​

const graph = rxdb.syncManager.getRepositoryDependencyGraph();

// 遍历依赖关系
for (const [key, dep] of graph) {
console.log(`${key} 依赖:`, dep.dependsOn);
console.log(`${key} 被依赖:`, dep.requiredBy);
}

getRepositorySyncOrder()​

getRepositorySyncOrder(direction): RepositoryIdentifier[];

Defined in: rxdb-plugin-sync/src/SyncManager.ts:625

根据依赖关系获取 Repository 的同步顺序

通过拓扑排序确定基于依赖关系的正确同步顺序。

Parameters​

ParameterTypeDescription
directionSortDirection排序方向:'pull'(父节点优先)或 'push'(子节点优先)

Returns​

RepositoryIdentifier[]

有序的 Repository 列表

Example​

// 获取 pull 顺序(父节点优先)
const pullOrder = rxdb.syncManager.getRepositorySyncOrder('pull');
// [User, Todo, Comment]

// 获取 push 顺序(子节点优先)
const pushOrder = rxdb.syncManager.getRepositorySyncOrder('push');
// [Comment, Todo, User]

getRepositorySyncStatus()​

getRepositorySyncStatus(namespace, entity): Promise<RepositorySyncStatus>;

Defined in: rxdb-plugin-sync/src/SyncManager.ts:474

获取单个 Repository 的同步状态

返回完整的同步状态信息,包括:

  • syncType(full/remote/local/disabled)
  • pushableCount(待推送的本地变更数)
  • pullableCount(可拉取的远程变更数)
  • 最近同步时间戳

Parameters​

ParameterTypeDescription
namespacestring实体命名空间(如 "public")
entitystring实体名称(如 "Todo")

Returns​

Promise<RepositorySyncStatus>

Repository 同步状态

Example​

const status = await rxdb.syncManager.getRepositorySyncStatus('public', 'Todo');
console.log(`同步类型: ${status.syncType}`);
console.log(`待推送: ${status.pushableCount},可拉取: ${status.pullableCount}`);

init()​

init(): void;

Defined in: rxdb-plugin-sync/src/SyncManager.ts:78

装上 connected$ 自动回推与远端事件计数两条链路

Returns​

void


pull()​

pull(options?): Promise<PullResult>;

Defined in: rxdb-plugin-sync/src/SyncManager.ts:154

从远程拉取变更并应用到本地数据库

当 autoSync=false 时,会先应用 Realtime 缓存的变更,再拉取远程变更。

Parameters​

ParameterTypeDescription
options?PullOptions可选配置

Returns​

Promise<PullResult>

拉取结果

Example​

// 基本用法
const result = await rxdb.syncManager.pull();
console.log(`Pulled ${result.pulled} changes`);

// 拉取所有数据
const result = await rxdb.syncManager.pull({ fetchAll: true });

pullRepository()​

pullRepository(
namespace,
entity,
options?
): Promise<PullRepositoryResult>;

Defined in: rxdb-plugin-sync/src/SyncManager.ts:286

拉取指定 Repository 的远程变更

提供实体类型级别的精细同步控制,支持级联同步以自动拉取关联实体。

Parameters​

ParameterTypeDescription
namespacestring实体命名空间(如 "public")
entitystring实体名称(如 "Todo")
options?PullRepositoryOptions拉取选项

Returns​

Promise<PullRepositoryResult>

拉取结果

Example​

// 拉取 Todo 并级联拉取依赖
const result = await rxdb.syncManager.pullRepository('public', 'Todo', {
includeRelated: true // 默认:若 Todo 有外键则自动拉取 User
});

// 不级联拉取
const result = await rxdb.syncManager.pullRepository('public', 'Todo', {
includeRelated: false // 仅拉取 Todo,可能引发外键错误
});

push()​

push(options?): Promise<PushResult>;

Defined in: rxdb-plugin-sync/src/SyncManager.ts:202

将本地未同步的变更推送到远程数据库

推送时会自动:

  1. 查询 lastPushedChangeId 之后的新变更
  2. 过滤已撤销的变更(revertChangeId != null)
  3. 压缩变更(INSERT→DELETE 丢弃,INSERT→UPDATE* 合并为 INSERT)
  4. 批量推送到远程
  5. 更新 lastPushedChangeId 和 lastPushedAt

Parameters​

ParameterTypeDescription
options?PushOptions可选配置

Returns​

Promise<PushResult>

推送结果

Example​

// 基本用法
const result = await rxdb.syncManager.push();
console.log(`Pushed ${result.pushed} changes`);

// 自定义批量大小
const result = await rxdb.syncManager.push({ batchSize: 500 });

pushRepository()​

pushRepository(
namespace,
entity,
options?
): Promise<PushRepositoryResult>;

Defined in: rxdb-plugin-sync/src/SyncManager.ts:335

推送指定 Repository 的本地变更

提供实体类型级别的精细同步控制,支持级联同步以自动推送依赖实体。

Parameters​

ParameterTypeDescription
namespacestring实体命名空间(如 "public")
entitystring实体名称(如 "User")
options?PushRepositoryOptions推送选项

Returns​

Promise<PushRepositoryResult>

推送结果

Example​

// 推送 User 并级联推送依赖方
const result = await rxdb.syncManager.pushRepository('public', 'User', {
includeRelated: true // 默认:若 Post 引用 User 则自动推送 Post
});

// 不级联推送
const result = await rxdb.syncManager.pushRepository('public', 'User', {
includeRelated: false // 仅推送 User,依赖数据可能不完整
});

refreshPullableCount()​

refreshPullableCount(): Promise<number>;

Defined in: rxdb-plugin-sync/src/SyncManager.ts:516

按各仓库持久化的远端水位线重新计算待拉变更数

Returns​

Promise<number>

当前远端待拉变更总数

Remarks​

远程适配器在实时订阅恢复后调用。若刷新期间又收到实时事件,保留两者中的较大值, 避免把查询快照之后到达的通知覆盖掉。


sync()​

sync(options?): Promise<SyncResult>;

Defined in: rxdb-plugin-sync/src/SyncManager.ts:231

执行完整的同步操作(先 pull 再 push)

推荐在重连后使用此方法,确保:

  1. 先获取远程最新变更(避免覆盖他人数据)
  2. 再推送本地变更

Parameters​

ParameterTypeDescription
options?{ pull?: PullOptions; push?: PushOptions; }可选配置
options.pull?PullOptions-
options.push?PushOptions-

Returns​

Promise<SyncResult>

同步结果(包含 pull 和 push 结果)

Example​

// 基本用法
const result = await rxdb.syncManager.sync();
console.log(`Pulled ${result.pullResult.pulled}, Pushed ${result.pushResult.pushed}`);

syncBranches()​

syncBranches(): Promise<SyncBranchesResult>;

Defined in: rxdb-plugin-sync/src/SyncManager.ts:132

从远程同步所有分支信息到本地

远程新分支 → 在本地创建(local: false, remote: true) 本地已有的远程分支 → 更新 remote 标记为 true 纯本地分支 → 不受影响

Returns​

Promise<SyncBranchesResult>

同步结果

Example​

const result = await rxdb.syncManager.syncBranches();
console.log(`新增 ${result.created},更新 ${result.updated}`);

syncRepository()​

syncRepository(
namespace,
entity,
options?
): Promise<SyncRepositoryResult>;

Defined in: rxdb-plugin-sync/src/SyncManager.ts:374

同步指定 Repository(先 pull 再 push)

将单个 Repository 的 pull 和 push 合并为一次操作,保证正确的执行顺序。 推荐在需要确保特定实体类型数据一致性时使用。

Parameters​

ParameterTypeDescription
namespacestring实体命名空间(如 "public")
entitystring实体名称(如 "Todo")
options?SyncRepositoryOptions同步选项(分别配置 pull 和 push)

Returns​

Promise<SyncRepositoryResult>

同步结果(包含 pull 和 push 结果)

Example​

// 基本用法
const result = await rxdb.syncManager.syncRepository('public', 'Todo');
console.log(`Pulled ${result.pullResult.pulled}, Pushed ${result.pushResult.pushed}`);

// 自定义 pull 和 push 选项
const result = await rxdb.syncManager.syncRepository('public', 'Todo', {
pull: { limit: 500, fetchAll: true },
push: `{ batchSize: 100 }`
});