qbo_auth: инкрементальная загрузка зеркала через QuickBooks CDC (полная раз в 7 дней, при первом запуске, full=1 и переполнении лимита)
All checks were successful
ci / test (push) Successful in 42s
ci / deploy (push) Successful in 2m45s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 22:56:20 +03:00
parent 28cce78169
commit dc224e375b
3 changed files with 145 additions and 11 deletions

View File

@@ -21,6 +21,14 @@ const PAGE = 1000;
const CHUNK = 100;
/** QuickBooks по умолчанию отдаёт только активные счета/вендоров/клиентов. */
const WITH_INACTIVE = new Set(["Account", "Vendor", "Customer"]);
/** Полная перезагрузка не реже раз в столько дней (страховка от пропусков CDC). */
const FULL_EVERY_DAYS = 7;
/** CDC хранит изменения не более 30 дней; берём запас. */
const CDC_MAX_DAYS = 25;
/** Нахлёст окна CDC, чтобы не потерять изменения на границе запусков. */
const CDC_OVERLAP_MS = 5 * 60 * 1000;
/** CDC отдаёт не более 1000 объектов на сущность: при достижении лимита - полная загрузка. */
const CDC_LIMIT = 1000;
export interface SyncResult {
runId: number;
@@ -88,26 +96,61 @@ export class QboSync {
}
}
private async store(spec: EntitySpec, realmId: string, objects: any[]): Promise<number> {
/** Запись объектов в зеркало. incremental (CDC): только изменённые, удалённые убираются по списку id; иначе полная замена. */
private async store(spec: EntitySpec, realmId: string, objects: any[], incremental?: { deleted: string[] }): Promise<number> {
const rows = objects.map((o) => spec.map(o));
const ids = rows.map((r) => r.id as string);
await this.d.tx(async (q) => {
await this.insertRows(q, spec.table, spec.columns, rows, { realm_id: realmId }, "realm_id, id");
// исчезнувшие в QuickBooks объекты убираем из зеркала
await q.query(`delete from ${spec.table} where realm_id = $1 and not (id = any($2::text[]))`, [realmId, ids]);
if (incremental) {
if (incremental.deleted.length) {
await q.query(`delete from ${spec.table} where realm_id = $1 and id = any($2::text[])`, [realmId, incremental.deleted]);
if (spec.lines) await q.query(`delete from ${spec.lines.table} where realm_id = $1 and ${spec.lines.parentColumn} = any($2::text[])`, [realmId, incremental.deleted]);
}
} else {
// исчезнувшие в QuickBooks объекты убираем из зеркала
await q.query(`delete from ${spec.table} where realm_id = $1 and not (id = any($2::text[]))`, [realmId, ids]);
}
if (spec.lines) {
const l = spec.lines;
await q.query(`delete from ${l.table} where realm_id = $1 and ${l.parentColumn} = any($2::text[])`, [realmId, ids]);
const lineRows = objects.flatMap((o, i) => l.map(o, ids[i]!));
await this.insertRows(q, l.table, [l.parentColumn, ...l.columns], lineRows, { realm_id: realmId }, `realm_id, ${l.parentColumn}, line_no`);
await q.query(`delete from ${l.table} where realm_id = $1 and not (${l.parentColumn} = any($2::text[]))`, [realmId, ids]);
if (!incremental) await q.query(`delete from ${l.table} where realm_id = $1 and not (${l.parentColumn} = any($2::text[]))`, [realmId, ids]);
}
});
return rows.length;
}
/** Полная перезагрузка зеркала. Одновременно выполняется только одна. */
async run(): Promise<SyncResult> {
/** Change Data Capture: объекты, изменённые после since. null - лимит CDC достигнут, нужна полная загрузка. */
private async fetchChanges(since: Date): Promise<Map<string, { changed: any[]; deleted: string[] }> | null> {
const entities = SPECS.map((s) => s.entity);
const j = await this.get(`cdc?entities=${entities.join(",")}&changedSince=${encodeURIComponent(since.toISOString())}`);
const out = new Map<string, { changed: any[]; deleted: string[] }>(entities.map((e) => [e, { changed: [], deleted: [] }]));
for (const qr of j?.CDCResponse?.[0]?.QueryResponse ?? []) {
for (const e of entities) {
const arr: any[] = qr?.[e] ?? [];
if (arr.length >= CDC_LIMIT) return null;
for (const o of arr) (o?.status === "Deleted" ? out.get(e)!.deleted.push(String(o.Id)) : out.get(e)!.changed.push(o));
}
}
return out;
}
/** Полная загрузка или инкремент? Инкремент: есть успешный запуск, полная загрузка была не позже FULL_EVERY_DAYS, окно CDC в пределах лимита. */
private async chooseMode(realmId: string, forceFull: boolean): Promise<{ since: Date } | null> {
if (forceFull) return null;
const last = (await this.d.query("select max(started_at) as t from qbo_sync_run where realm_id = $1 and status = 'ok'", [realmId])).rows[0]?.t;
const full = (await this.d.query("select max(started_at) as t from qbo_sync_run where realm_id = $1 and status = 'ok' and counts ? '_full'", [realmId])).rows[0]?.t;
if (!last || !full) return null;
const day = 24 * 3600 * 1000;
if (Date.now() - new Date(full).getTime() > FULL_EVERY_DAYS * day) return null;
if (Date.now() - new Date(last).getTime() > CDC_MAX_DAYS * day) return null;
return { since: new Date(new Date(last).getTime() - CDC_OVERLAP_MS) };
}
/** Загрузка зеркала: по умолчанию инкремент через CDC (изменения с прошлого запуска), полная перезагрузка при первом запуске, раз в неделю, при full=true и при переполнении CDC. Одновременно выполняется только одна. */
async run(opts: { full?: boolean } = {}): Promise<SyncResult> {
if (this.running) throw new Error("загрузка зеркала QuickBooks уже выполняется");
this.running = true;
const started = Date.now();
@@ -119,10 +162,24 @@ export class QboSync {
realmId = t.realmId;
const ins = await this.d.query("insert into qbo_sync_run (realm_id, environment) values ($1, $2) returning id", [realmId, this.d.environment]);
runId = Number(ins.rows[0].id);
for (const spec of SPECS) {
const objects = await this.fetchAll(spec.entity);
counts[spec.entity] = await this.store(spec, realmId, objects);
this.d.log?.("qbo sync", { entity: spec.entity, count: counts[spec.entity] });
let changes: Map<string, { changed: any[]; deleted: string[] }> | null = null;
const mode = await this.chooseMode(realmId, opts.full === true);
if (mode) changes = await this.fetchChanges(mode.since);
if (changes) {
counts._cdc = 1;
for (const spec of SPECS) {
const c = changes.get(spec.entity)!;
counts[spec.entity] = await this.store(spec, realmId, c.changed, { deleted: c.deleted });
if (c.deleted.length) counts[spec.entity + "_deleted"] = c.deleted.length;
this.d.log?.("qbo sync cdc", { entity: spec.entity, changed: c.changed.length, deleted: c.deleted.length });
}
} else {
counts._full = 1;
for (const spec of SPECS) {
const objects = await this.fetchAll(spec.entity);
counts[spec.entity] = await this.store(spec, realmId, objects);
this.d.log?.("qbo sync", { entity: spec.entity, count: counts[spec.entity] });
}
}
await this.d.query("update qbo_sync_run set status = 'ok', finished_at = now(), counts = $2 where id = $1", [runId, JSON.stringify(counts)]);
return { runId, realmId, status: "ok", counts, durationMs: Date.now() - started };