From dc224e375b072536ca9fc2b4321ec6ef5f8b5283 Mon Sep 17 00:00:00 2001 From: Yuri Yaryshev Date: Wed, 18 Nov 2026 22:56:20 +0300 Subject: [PATCH] =?UTF-8?q?qbo=5Fauth:=20=D0=B8=D0=BD=D0=BA=D1=80=D0=B5?= =?UTF-8?q?=D0=BC=D0=B5=D0=BD=D1=82=D0=B0=D0=BB=D1=8C=D0=BD=D0=B0=D1=8F=20?= =?UTF-8?q?=D0=B7=D0=B0=D0=B3=D1=80=D1=83=D0=B7=D0=BA=D0=B0=20=D0=B7=D0=B5?= =?UTF-8?q?=D1=80=D0=BA=D0=B0=D0=BB=D0=B0=20=D1=87=D0=B5=D1=80=D0=B5=D0=B7?= =?UTF-8?q?=20QuickBooks=20CDC=20(=D0=BF=D0=BE=D0=BB=D0=BD=D0=B0=D1=8F=20?= =?UTF-8?q?=D1=80=D0=B0=D0=B7=20=D0=B2=207=20=D0=B4=D0=BD=D0=B5=D0=B9,=20?= =?UTF-8?q?=D0=BF=D1=80=D0=B8=20=D0=BF=D0=B5=D1=80=D0=B2=D0=BE=D0=BC=20?= =?UTF-8?q?=D0=B7=D0=B0=D0=BF=D1=83=D1=81=D0=BA=D0=B5,=20full=3D1=20=D0=B8?= =?UTF-8?q?=20=D0=BF=D0=B5=D1=80=D0=B5=D0=BF=D0=BE=D0=BB=D0=BD=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D0=B8=20=D0=BB=D0=B8=D0=BC=D0=B8=D1=82=D0=B0)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- packages/qbo_auth/src/http-api.ts | 2 +- packages/qbo_auth/src/sync.test.ts | 77 ++++++++++++++++++++++++++++++ packages/qbo_auth/src/sync.ts | 77 ++++++++++++++++++++++++++---- 3 files changed, 145 insertions(+), 11 deletions(-) diff --git a/packages/qbo_auth/src/http-api.ts b/packages/qbo_auth/src/http-api.ts index 1cc3e2d..9371858 100644 --- a/packages/qbo_auth/src/http-api.ts +++ b/packages/qbo_auth/src/http-api.ts @@ -50,7 +50,7 @@ export function buildApi(auth: QboAuth, token: string, sync?: QboSync): FastifyI if (!sync) return reply.code(501).send({ error: "sync_not_configured" }); if (sync.isRunning) return reply.code(409).send({ error: "already_running" }); try { - const r = await sync.run(); + const r = await sync.run({ full: (req.query as { full?: string } | undefined)?.full === "1" }); return reply.code(r.status === "ok" ? 200 : 502).send(r); } catch (e) { if (e instanceof ReauthNeeded) return reply.code(409).send({ error: "reauth_needed", message: e.message }); diff --git a/packages/qbo_auth/src/sync.test.ts b/packages/qbo_auth/src/sync.test.ts index 17f6ec3..d0b4017 100644 --- a/packages/qbo_auth/src/sync.test.ts +++ b/packages/qbo_auth/src/sync.test.ts @@ -119,3 +119,80 @@ describe("загрузка зеркала", () => { await first; }); }); + +/** Заглушка для режима CDC: история запусков и ответ cdc. */ +function setupCdc(opts: { lastAgoMs: number | null; fullAgoMs: number | null; cdc: unknown }) { + const sqls: Array<{ sql: string; params?: unknown[] }> = []; + const calls: string[] = []; + const now = Date.now(); + const q: Q = { + query: async (sql, params) => { + sqls.push({ sql, params }); + if (sql.startsWith("insert into qbo_sync_run")) return { rows: [{ id: "88" }] }; + if (sql.includes("max(started_at)") && sql.includes("'_full'")) return { rows: [{ t: opts.fullAgoMs === null ? null : new Date(now - opts.fullAgoMs).toISOString() }] }; + if (sql.includes("max(started_at)")) return { rows: [{ t: opts.lastAgoMs === null ? null : new Date(now - opts.lastAgoMs).toISOString() }] }; + return { rows: [] }; + }, + }; + const d: SyncDeps = { + tx: (fn) => fn(q), + query: q.query, + getToken: async () => ({ accessToken: "at", realmId: "R1", apiBase: "https://api.test" }), + fetchFn: async (url) => { + const u = decodeURIComponent(url); + calls.push(u); + if (u.includes("/cdc?")) return { ok: true, status: 200, json: async () => opts.cdc }; + return { ok: true, status: 200, json: async () => ({ QueryResponse: {} }) }; + }, + environment: "sandbox", + sleep: async () => undefined, + }; + return { sync: new QboSync(d), sqls, calls }; +} +const HOUR = 3600 * 1000; +const DAY = 24 * HOUR; + +describe("CDC (инкрементальная загрузка)", () => { + it("есть недавний запуск и полная загрузка: берёт только изменения с нахлёстом, удалённые убирает, полных запросов нет", async () => { + const cdc = { CDCResponse: [{ QueryResponse: [ + { Purchase: [{ Id: "144", TotalAmt: 7, Line: [{ Amount: 7, AccountBasedExpenseLineDetail: { AccountRef: { value: "1" } } }] }, { Id: "145", status: "Deleted", domain: "QBO" }] }, + { Vendor: [{ Id: "7", DisplayName: "V" }] }, + ] }] }; + const { sync, calls, sqls } = setupCdc({ lastAgoMs: 2 * HOUR, fullAgoMs: 2 * DAY, cdc }); + const r = await sync.run(); + expect(r.status).toBe("ok"); + expect(r.counts).toMatchObject({ _cdc: 1, Purchase: 1, Purchase_deleted: 1, Vendor: 1, Account: 0 }); + expect(r.counts._full).toBeUndefined(); + expect(calls.filter((c) => c.includes("/cdc?"))).toHaveLength(1); + expect(calls.find((c) => c.includes("/cdc?"))).toMatch(/entities=Account,Vendor,Customer,Purchase,Bill,Attachable&changedSince=/); + expect(calls.some((c) => c.includes("select * from"))).toBe(false); + const since = new Date(/changedSince=([^&]+)/.exec(calls.find((c) => c.includes("/cdc?"))!)![1]!).getTime(); + expect(Date.now() - since).toBeGreaterThan(2 * HOUR + 4 * 60 * 1000); + const text = sqls.map((s) => s.sql); + expect(text.some((s) => s.startsWith("delete from qbo_purchase where realm_id = $1 and id = any($2::text[])"))).toBe(true); + expect(text.some((s) => s.startsWith("delete from qbo_account where realm_id = $1 and not (id = any"))).toBe(false); + expect(text.some((s) => s.startsWith("insert into qbo_purchase_line"))).toBe(true); + }); + + it("первый запуск, давняя полная загрузка (> 7 дней), давний запуск (> 25 дней) и full=true - полная загрузка", async () => { + for (const o of [{ lastAgoMs: null, fullAgoMs: null }, { lastAgoMs: HOUR, fullAgoMs: 8 * DAY }, { lastAgoMs: 26 * DAY, fullAgoMs: 26 * DAY }, { lastAgoMs: HOUR, fullAgoMs: null }]) { + const { sync, calls } = setupCdc({ ...o, cdc: {} }); + const r = await sync.run(); + expect(r.counts._full, JSON.stringify(o)).toBe(1); + expect(calls.some((c) => c.includes("/cdc?"))).toBe(false); + } + const { sync, calls } = setupCdc({ lastAgoMs: HOUR, fullAgoMs: DAY, cdc: {} }); + expect((await sync.run({ full: true })).counts._full).toBe(1); + expect(calls.some((c) => c.includes("/cdc?"))).toBe(false); + }); + + it("CDC достиг лимита 1000 объектов на сущность - откат на полную загрузку", async () => { + const many = Array.from({ length: 1000 }, (_, i) => ({ Id: String(i), Name: "n" + i })); + const { sync, calls } = setupCdc({ lastAgoMs: HOUR, fullAgoMs: DAY, cdc: { CDCResponse: [{ QueryResponse: [{ Account: many }] }] } }); + const r = await sync.run(); + expect(r.counts._full).toBe(1); + expect(r.counts._cdc).toBeUndefined(); + expect(calls.some((c) => c.includes("/cdc?"))).toBe(true); + expect(calls.some((c) => c.includes("select * from Account"))).toBe(true); + }); +}); diff --git a/packages/qbo_auth/src/sync.ts b/packages/qbo_auth/src/sync.ts index ab81c20..392e3fc 100644 --- a/packages/qbo_auth/src/sync.ts +++ b/packages/qbo_auth/src/sync.ts @@ -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 { + /** Запись объектов в зеркало. incremental (CDC): только изменённые, удалённые убираются по списку id; иначе полная замена. */ + private async store(spec: EntitySpec, realmId: string, objects: any[], incremental?: { deleted: string[] }): Promise { 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 { + /** Change Data Capture: объекты, изменённые после since. null - лимит CDC достигнут, нужна полная загрузка. */ + private async fetchChanges(since: Date): Promise | 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(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 { 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 | 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 };