从全量轮询到增量同步:用复合游标与软删除避开漏数边界
阅读华为云鸿蒙开发实践中心的「云同步待办清单:鸿蒙端云一体实战」案例时,案例在拓展实践里提到了一个非常典型的演进方向:把原本每 30 秒调用 GET /todo/pull 的全量拉取,升级为基于 updated_at 的增量同步,并保留软删除记录以便端侧感知删除。
在真实落地这一改造时,最容易踩坑的地方往往不是接口路径,而是游标条件与合并语义。如果只按单一时间戳做 updated_at > since 分页,同一秒内有多条任务被写入或批量更新时,翻页边界就会静默丢数据;而如果为了避免丢数据直接改写为 updated_at >= since,同一时间戳记录超过一页时又可能出现重复拉取甚至死循环。
下面用一段独立的 JavaScript 示例代码,把「复合游标 (updatedAt, id)」「软删除墓碑传播」「端侧幂等合并与旧数据防回退」这三个核心契约拆开验证。代码仅用于说明增量同步边界,不是官方案例源码的直接移植,也不代表原案例存在缺陷。
先看清三种常见写法的边界差异
| 策略 | 能解决什么 | 容易暴露的问题 |
|---|---|---|
单时间戳 updated_at > since 分页 |
写法最简单,无重复记录 | 同秒/同毫秒多条记录跨页时,后半段记录会被直接跳过 |
单时间戳 updated_at >= since 分页 |
不容易漏掉同时间戳记录 | 边界记录重复下发;若整页时间戳相同,游标无法前进 |
复合游标 (updated_at, id) + 软删除墓碑 |
严格全序翻页,不漏不重,可感知删除 | 需要保证排序与比较规则一致,并管理墓碑清理与兜底全量同步 |
可以看到,增量同步要同时满足两个不变式:
- 服务端拉取顺序是严格全序:按
(updatedAt ASC, id ASC)排序后,每次查询只返回满足(updatedAt > cursor.updatedAt) OR (updatedAt = cursor.updatedAt AND id > cursor.id)的记录,这样即使多条任务落在完全相同的时间戳上,也能稳定跨页推进。 - 删除事件必须作为状态变更下发:如果服务端直接物理删除行记录,增量查询看不到消失的行,其他端就会永久残留“僵尸任务”。采用软删除标记
deleted: true(同时推进updatedAt)后,删除和更新走同一条增量通道。
端侧合并为什么不能只删掉本地键
端侧拿到增量批次后,直观做法是看到 deleted: true 就直接 localMap.delete(id)。在理想的单链路有序拉取里这通常没问题,但一旦涉及弱网重试、离线队列补交或并发请求乱序到达,就会出现一个隐蔽问题:如果客户端先收到了 updatedAt = 1005 的删除墓碑并彻底清除了该 id,随后又收到一条迟到重放的 updatedAt = 1000, deleted = false 记录,本地就会把已经删掉的任务重新“复活”。
更稳妥的端侧数据结构,是在本地状态存储里保留带 updatedAt 与 deleted 的记录(展示层过滤 !record.deleted),合并时遵循两条规则:
- 新到达记录的
updatedAt小于本地记录时,直接判定为过期数据并跳过; - 同一
id在相同updatedAt下若本地已是删除墓碑,则忽略非删除覆盖,避免同时间戳乱序复活。
完整实现与本地断言验证
将下面代码保存为 incremental-sync-check.mjs,执行 node incremental-sync-check.mjs。脚本只使用 Node.js 内置的 node:assert/strict,无需安装任何第三方包。其中特意保留了一个最小反例 pullByTimestampOnly,用于在同一组测试数据上直观对比单一时间戳游标为何会漏掉 t-003。
import assert from 'node:assert/strict';
function compareCursor(a, b) {
if (a.updatedAt !== b.updatedAt) return a.updatedAt - b.updatedAt;
return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
}
function assertRecord(record) {
if (!record || typeof record !== 'object' ||
typeof record.id !== 'string' || record.id.length === 0 ||
!Number.isSafeInteger(record.updatedAt) || record.updatedAt < 0 ||
typeof record.deleted !== 'boolean') {
throw new TypeError('Invalid task record');
}
}
function assertCursor(cursor) {
if (cursor === null) return;
if (!cursor || typeof cursor !== 'object' ||
typeof cursor.id !== 'string' ||
!Number.isSafeInteger(cursor.updatedAt) || cursor.updatedAt < 0) {
throw new TypeError('Invalid sync cursor');
}
}
// Baseline anti-pattern: paging strictly by updatedAt > since drops same-timestamp ties.
function pullByTimestampOnly(records, since, limit) {
const ordered = records
.filter(r => r.updatedAt > since)
.sort(compareCursor);
const items = ordered.slice(0, limit);
const nextSince = items.length > 0 ? items.at(-1).updatedAt : since;
return { items, nextSince, hasMore: ordered.length > limit };
}
// Composite cursor pull: (updatedAt > cursor.updatedAt) OR (updatedAt === cursor.updatedAt && id > cursor.id).
function pullIncremental(records, cursor = null, limit = 50) {
if (!Array.isArray(records)) throw new TypeError('Expected records array');
if (!Number.isInteger(limit) || limit <= 0) throw new TypeError('Expected positive integer limit');
assertCursor(cursor);
const validated = records.map(r => {
assertRecord(r);
return { ...r };
});
validated.sort(compareCursor);
const filtered = cursor === null
? validated
: validated.filter(r => compareCursor(r, cursor) > 0);
const slice = filtered.slice(0, limit + 1);
const hasMore = slice.length > limit;
const items = slice.slice(0, limit);
const nextCursor = items.length > 0
? { updatedAt: items.at(-1).updatedAt, id: items.at(-1).id }
: cursor === null ? null : { ...cursor };
return { items, nextCursor, hasMore };
}
// Idempotent client merge retaining tombstones to block stale replay resurrection.
function applyDelta(localStore, items) {
if (!(localStore instanceof Map) || !Array.isArray(items)) {
throw new TypeError('Expected Map localStore and items array');
}
const next = new Map();
for (const [id, rec] of localStore.entries()) next.set(id, { ...rec });
let applied = 0;
let skippedStale = 0;
for (const item of items) {
assertRecord(item);
const prev = next.get(item.id);
if (prev && item.updatedAt < prev.updatedAt) {
skippedStale++;
continue;
}
if (prev && item.updatedAt === prev.updatedAt && prev.deleted && !item.deleted) {
skippedStale++;
continue;
}
next.set(item.id, { ...item });
applied++;
}
return { store: next, applied, skippedStale };
}
const activeIds = store => [...store.values()]
.filter(r => !r.deleted)
.sort(compareCursor)
.map(r => r.id);
// 1. Same-timestamp tie split across pages (page size = 2).
const server = [
{ id: 't-003', title: '核对部署日志', done: false, updatedAt: 1000, deleted: false },
{ id: 't-001', title: '初始化数据表', done: false, updatedAt: 1000, deleted: false },
{ id: 't-002', title: '发布 APIG 分组', done: false, updatedAt: 1000, deleted: false },
{ id: 't-004', title: '联调端侧列表', done: false, updatedAt: 1002, deleted: false },
];
const serverSnapshot = structuredClone(server);
// Naive timestamp-only cursor misses t-003 when page 1 ends at updatedAt = 1000.
const naiveP1 = pullByTimestampOnly(server, 0, 2);
const naiveP2 = pullByTimestampOnly(server, naiveP1.nextSince, 2);
assert.deepEqual(
[...naiveP1.items, ...naiveP2.items].map(r => r.id),
['t-001', 't-002', 't-004']
);
// Composite (updatedAt, id) cursor delivers all four records in deterministic order.
const p1 = pullIncremental(server, null, 2);
assert.deepEqual(p1.items.map(r => r.id), ['t-001', 't-002']);
assert.deepEqual(p1.nextCursor, { updatedAt: 1000, id: 't-002' });
assert.equal(p1.hasMore, true);
const p2 = pullIncremental(server, p1.nextCursor, 2);
assert.deepEqual(p2.items.map(r => r.id), ['t-003', 't-004']);
assert.deepEqual(p2.nextCursor, { updatedAt: 1002, id: 't-004' });
assert.equal(p2.hasMore, false);
// 2. Empty pull preserves cursor.
const pEmpty = pullIncremental(server, p2.nextCursor, 2);
assert.deepEqual(pEmpty.items, []);
assert.deepEqual(pEmpty.nextCursor, p2.nextCursor);
assert.equal(pEmpty.hasMore, false);
// 3. Client merge + soft-delete tombstone + in-place update.
const initial = new Map();
let state = applyDelta(initial, p1.items).store;
state = applyDelta(state, p2.items).store;
assert.deepEqual(activeIds(state), ['t-001', 't-002', 't-003', 't-004']);
assert.equal(initial.size, 0);
// Simulate soft delete on t-002 and edit on t-001 at newer timestamps.
const serverAfterEdit = server.map(r => {
if (r.id === 't-002') return { ...r, updatedAt: 1005, deleted: true };
if (r.id === 't-001') return { ...r, done: true, updatedAt: 1006 };
return r;
});
const p3 = pullIncremental(serverAfterEdit, p2.nextCursor, 10);
assert.deepEqual(p3.items.map(r => [r.id, r.deleted, r.done]), [
['t-002', true, false],
['t-001', false, true],
]);
state = applyDelta(state, p3.items).store;
assert.deepEqual(activeIds(state), ['t-003', 't-004', 't-001']);
assert.equal(state.get('t-001').done, true);
// 4. Stale replay from page 1 cannot resurrect deleted t-002 or revert t-001.
const replay = applyDelta(state, p1.items);
assert.equal(replay.applied, 0);
assert.equal(replay.skippedStale, 2);
assert.deepEqual(activeIds(replay.store), ['t-003', 't-004', 't-001']);
assert.equal(replay.store.get('t-001').done, true);
// 5. Same-timestamp tombstone dominates active record; server input remains immutable.
const sameTsDelete = applyDelta(
new Map([['t-009', { id: 't-009', title: '测试', done: false, updatedAt: 2000, deleted: false }]]),
[{ id: 't-009', title: '测试', done: false, updatedAt: 2000, deleted: true }]
);
const sameTsStaleActive = applyDelta(
sameTsDelete.store,
[{ id: 't-009', title: '测试', done: false, updatedAt: 2000, deleted: false }]
);
assert.equal(sameTsStaleActive.skippedStale, 1);
assert.equal(sameTsStaleActive.store.get('t-009').deleted, true);
assert.deepEqual(server, serverSnapshot);
// 6. Invalid input guards.
assert.throws(() => pullIncremental('bad', null, 2), TypeError);
assert.throws(() => pullIncremental(server, null, 0), TypeError);
assert.throws(() => pullIncremental(server, { updatedAt: -1, id: 'a' }, 2), TypeError);
assert.throws(() => pullIncremental([{ id: '', updatedAt: 1, deleted: false }]), TypeError);
console.log('PASS: tie-split, empty-pull, tombstone, update, stale-replay, immutability, validation');
export { compareCursor, pullIncremental, applyDelta };
验证结果与关键观察
上述脚本在本地 Node.js v24.22.1 环境中实际运行通过,控制台输出如下:
PASS: tie-split, empty-pull, tombstone, update, stale-replay, immutability, validation
这组断言重点验证了 6 类场景:
- 同时间戳跨页切分:
t-001、t-002、t-003同为updatedAt = 1000且每页limit = 2。反例pullByTimestampOnly在第一页结束后游标变成1000,第二页用updatedAt > 1000直接漏掉了t-003;而pullIncremental使用复合游标{ updatedAt: 1000, id: 't-002' },第二页准确衔接并返回t-003与t-004。 - 空拉取游标保持:无新增变更时返回空列表与
hasMore: false,并原样保留已有游标,避免游标被重置为空导致下一轮退化为全量拉取。 - 软删除与状态更新联动:
t-002软删除、t-001标记完成后,端侧增量合并立刻把t-002移出活跃列表,同时更新t-001.done。 - 旧批次重放保护:把第一页的旧数据重新喂给
applyDelta,两条过期记录均被计入skippedStale,既没有复活已删除的t-002,也没有覆盖t-001的完成状态。 - 不可变性与入参校验:服务端输入数组与客户端原始
Map均未被原地修改,非法分页大小、负时间戳游标和空id会直接抛出TypeError。
落地到云函数与 RDS MySQL 时还要补什么
本文代码验证的是内存模型下的核心逻辑,并没有直接连接 RDS MySQL 或完成 HarmonyOS 端侧编译联调。真正落到「APIG + FunctionGraph + RDS MySQL + ArkTS 端侧」架构中时,还需要补齐四项工程细节:
- 索引与排序规则一致:把原表上的
(user_id, updated_at)索引扩展为联合索引(user_id, updated_at, id),并确保id列的排序规则(如 ASCII UUID 搭配utf8mb4_bin)与查询条件(updated_at > ?) OR (updated_at = ? AND id > ?)语义一致,避免大小写不敏感 collation 引起排序跳变。 - 服务端统一授时与单调性:
updated_at必须由服务端或数据库写入时统一生成,不能信任客户端时钟;若业务并发较高且数据库仅使用秒级DATETIME,同一行在同秒内连续写入二次时,仍可能被已推进的游标错过,生产场景更建议使用毫秒时间戳或自增单调版本号(sync_seq)作为游标主序。 - 墓碑保留周期与兜底全量同步:软删除墓碑不能无限膨胀,通常按保留期(例如 30 天)定期物理清理;如果某台设备离线超过墓碑保留期,服务端应识别过旧游标并返回
needFullResync信号,引导端侧重建本地副本。 - 端侧列表刷新键:迁移到 ArkUI 的
ForEach渲染时,键值仍需包含影响 UI 的状态字段或配合@Observed/@ObjectLink,避免增量合并更新对象属性后界面未触发局部重绘。
案例参考与创作说明
- 案例介绍:云同步待办清单:鸿蒙端云一体实战
- 案例源码:鸿蒙开发实践中心 todo_list 仓库
本文为 AI 辅助创作的独立技术实验,正文与示例代码由 AI 辅助编写,文中全部断言已在本地 Node.js v24.22.1 环境实际执行并通过。引用官方案例仅用于交代学习与问题背景,原案例文档与源码权利归原作者所有。
- 点赞
- 收藏
- 关注作者
评论(0)