techtools

load.ts

TypeScript · 232 рядків

1import { mkdirSync, writeFileSync } from 'node:fs';
2import { parseArgs } from 'node:util';
3import pg from 'pg';
4import { issueOrder, receiveLot, type IssueLine, type Lot } from './ops.ts';
5import { PT, WAREHOUSES } from './schema.ts';
6
7// Навантаження: 30 клієнтів на склад × 5 складів. Частки рядків: опт 50% (50–150 рядків), роздріб 30% (1–3),
8// переміщення 5% (150–350), приймання партій 15% (по одній партії на запит, потоварно).
9// --mode order: транзакція на замовлення; line: транзакція на кожен рядок. --rate: цільові рядки/с на всі склади (0 — максимум).
10const { values: opt } = parseArgs({
11  options: {
12    variant: { type: 'string', default: 'v1' },
13    mode: { type: 'string', default: 'order' },
14    clients: { type: 'string', default: '30' },   // на склад
15    seconds: { type: 'string', default: '300' },
16    rate: { type: 'string', default: '0' },
17    tag: { type: 'string', default: '' },
18    url: { type: 'string', default: 'postgres://postgres@127.0.0.1:55432' },
19  },
20});
21pg.types.setTypeParser(20, (v) => Number(v));       // bigint → number (id < 2^53)
22pg.types.setTypeParser(1082, (v) => v);             // date як рядок
23pg.types.setTypeParser(1184, (v) => v);             // timestamptz як рядок
24const CLIENTS = Number(opt.clients);
25const SECONDS = Number(opt.seconds);
26const RATE = Number(opt.rate);
27const TAG = `${opt.variant}-${opt.mode}${RATE ? `-r${RATE}` : '-max'}${opt.tag ? '-' + opt.tag : ''}`;
28const pool = new pg.Pool({ connectionString: `${opt.url}/wms_${opt.variant}`, max: CLIENTS * WAREHOUSES + 5 });
29
30// ---------- довідник у пам'яті ----------
31const meta = await pool.query(`SELECT string_agg(category_id::text, '' ORDER BY id) AS cats, max(id) AS n FROM wms.product`);
32const CATS: string = meta.rows[0].cats;
33const N = Number(meta.rows[0].n);
34const PACK: Record<number, { p1: number; t1: number; p2: number | null; t2: number | null; life: number }> = {};
35for (const r of (await pool.query('SELECT * FROM wms.category')).rows) PACK[r.id] = { p1: r.pack1, t1: r.pack1_type, p2: r.pack2, t2: r.pack2_type, life: Math.round((r.life_min + r.life_max) / 2) };
36
37// Ципф s=0.8 за рангом, ранг → товар через бієкцію (a·r + b) mod N.
38const S = 0.8;
39const A = 1_000_003;
40const zipfRank = () => Math.min(N - 1, Math.floor(Math.pow(1 + Math.random() * (Math.pow(N, 1 - S) - 1), 1 / (1 - S))) - 1);
41const pickProduct = () => ((zipfRank() * A + 17) % N) + 1;
42const rnd = (a: number, b: number) => a + Math.floor(Math.random() * (b - a + 1));
43
44// ---------- заміри ----------
45type Op = 'retail' | 'wholesale' | 'transfer' | 'receipt';
46const OPS: Op[] = ['retail', 'wholesale', 'transfer', 'receipt'];
47const stat = Object.fromEntries(OPS.map((o) => [o, { ms: [] as number[], lines: 0, issued: 0, short: 0, opened: 0, cut: 0, rows: 0, journal: 0, lockMs: [] as number[], retries: 0, errors: 0, statements: 0 }]));
48const timeline: { t: number; lines: number; ops: number }[] = [];
49let linesDone = 0;
50let opsDone = 0;
51let docSeq = 1;
52
53function lineQty(cat: number, op: Op): number {
54  const p = PACK[cat];
55  if (op === 'retail' || p.p1 === 1 && !p.p2) return op === 'retail' ? rnd(1, 3) : rnd(1, 6);
56  const r = Math.random();
57  if (op === 'transfer') return (p.p2 ?? p.p1) * rnd(1, 2);
58  if (r < 0.3) return rnd(1, 10);
59  return p.p1 * rnd(1, 3);
60}
61
62function buildLines(op: Op): IssueLine[] {
63  const n = op === 'retail' ? rnd(1, 3) : op === 'wholesale' ? rnd(50, 150) : rnd(150, 350);
64  const m = new Map<number, number>();
65  for (let i = 0; i < n; i++) {
66    const pid = pickProduct();
67    m.set(pid, (m.get(pid) ?? 0) + lineQty(Number(CATS[pid - 1]), op));
68  }
69  return [...m].map(([product_id, qty]) => ({ product_id, qty }));
70}
71
72function buildLot(): Lot {
73  const pid = pickProduct();
74  const p = PACK[Number(CATS[pid - 1])];
75  const mfg = new Date(Date.now() - rnd(0, 300) * 86_400_000);
76  const exp = new Date(mfg.getTime() + p.life * 86_400_000);
77  const d = (x: Date) => x.toISOString().slice(0, 10);
78  const base = { product_id: pid, mfg: d(mfg), expiry: d(exp), location: rnd(1, 200000) };
79  if (p.p2 && Math.random() < 0.05) {
80    return { ...base, container: { type: PT.bundle }, lines: [{ pack_type: p.t2!, pack_size: p.p2, pack_count: rnd(2, 6) }] };
81  }
82  const lines = [];
83  if (p.p1 > 1) lines.push({ pack_type: p.t1, pack_size: p.p1, pack_count: rnd(1, 5) });
84  if (p.p1 === 1 || Math.random() < 0.3) lines.push({ pack_type: PT.unit, pack_size: 1, pack_count: rnd(1, 20) });
85  return { ...base, lines };
86}
87
88// Ймовірності запитів так, щоб частки рядків були 50/30/5/15.
89const W: Record<Op, number> = { wholesale: 0.5 / 100, retail: 0.3 / 2, transfer: 0.05 / 250, receipt: 0.15 / 1 };
90const WSUM = OPS.reduce((s, o) => s + W[o], 0);
91const pickOp = (): Op => {
92  let x = Math.random() * WSUM;
93  for (const o of OPS) if ((x -= W[o]) < 0) return o;
94  return 'retail';
95};
96
97async function worker(wh: number, id: number, deadline: number, t0: number): Promise<void> {
98  const c = await pool.connect();
99  let myLines = 0;
100  const perClient = RATE / (CLIENTS * WAREHOUSES);
101  try {
102    while (performance.now() < deadline) {
103      const op = pickOp();
104      const s = stat[op];
105      const t = performance.now();
106      for (let attempt = 0; ; attempt++) {
107        try {
108          if (op === 'receipt') {
109            const r = await receiveLot(c, wh, buildLot(), docSeq++, id);
110            s.rows += r.rows;
111            s.lines += 1;
112            s.statements += 1;
113            myLines += 1;
114          } else {
115            const lines = buildLines(op);
116            const parts = opt.mode === 'line' ? lines.map((l) => [l]) : [lines];
117            const doc = docSeq++;
118            for (const part of parts) {
119              const r = await issueOrder(c, wh, part, doc, id);
120              s.issued += r.issued; s.short += r.short; s.opened += r.opened; s.cut += r.cut; s.rows += r.rows; s.journal += r.journal;
121              s.lockMs.push(r.lockMs);
122              s.statements += r.statements;
123            }
124            s.lines += lines.length;
125            myLines += lines.length;
126          }
127          break;
128        } catch (e: any) {
129          if ((e.code === '40P01' || e.code === '40001') && attempt < 5) { s.retries++; continue; }
130          s.errors++;
131          if (s.errors < 3) console.error(op, e.code, e.message);
132          break;
133        }
134      }
135      s.ms.push(performance.now() - t);
136      opsDone++;
137      linesDone = OPS.reduce((a, o) => a + stat[o].lines, 0);
138      if (perClient > 0) {
139        const wait = (myLines / perClient) * 1000 - (performance.now() - t0);
140        if (wait > 0) await new Promise((r) => setTimeout(r, Math.min(wait, deadline - performance.now())));
141      }
142    }
143  } finally {
144    c.release();
145  }
146}
147
148// ---------- прогін ----------
149const q1 = async (sql: string) => (await pool.query(sql)).rows[0];
150await pool.query('CREATE EXTENSION IF NOT EXISTS pg_stat_statements');
151await pool.query('SELECT pg_stat_statements_reset()');
152await pool.query('SELECT pg_stat_reset()');
153const pings: number[] = [];
154for (let i = 0; i < 200; i++) { const t = performance.now(); await pool.query('SELECT 1'); pings.push(performance.now() - t); }
155const before = await q1(`SELECT (SELECT wal_bytes FROM pg_stat_wal) AS wal, (SELECT count(*) FROM wms.inventory_transaction) AS tx,
156  (SELECT count(*) FROM wms.inventory_item) AS items, (SELECT count(*) FROM wms.inventory_item_archive) AS arch`);
157console.log(`${TAG}: ${CLIENTS * WAREHOUSES} клієнтів, ${SECONDS} с, RTT ping p50 ${pct(pings, 50).toFixed(2)} мс`);
158const t0 = performance.now();
159const deadline = t0 + SECONDS * 1000;
160const tick = setInterval(() => {
161  timeline.push({ t: Math.round((performance.now() - t0) / 1000), lines: linesDone, ops: opsDone });
162  const l = timeline.at(-1)!;
163  const p = timeline.at(-2);
164  if (l.t % 30 === 0) console.log(`  ${l.t} с: рядків ${l.lines}, запитів ${l.ops}, ${p ? ((l.lines - p.lines) / ((l.t - p.t) || 1)).toFixed(0) : '-'} рядків/с`);
165}, 5000);
166await Promise.all(Array.from({ length: WAREHOUSES * CLIENTS }, (_, i) => worker((i % WAREHOUSES) + 1, i, deadline, t0)));
167clearInterval(tick);
168const wall = (performance.now() - t0) / 1000;
169
170const db = (await pool.query(`SELECT xact_commit, xact_rollback, deadlocks, blks_hit, blks_read, tup_inserted, tup_updated, tup_deleted, temp_bytes
171  FROM pg_stat_database WHERE datname = current_database()`)).rows[0];
172const after = await q1(`SELECT (SELECT wal_bytes FROM pg_stat_wal) AS wal, (SELECT count(*) FROM wms.inventory_transaction) AS tx,
173  (SELECT count(*) FROM wms.inventory_item) AS items, (SELECT count(*) FROM wms.inventory_item_archive) AS arch`);
174const top = (await pool.query(`SELECT calls, round(total_exec_time::numeric, 0) AS total_ms, round(mean_exec_time::numeric, 3) AS mean_ms,
175  round((100 * total_exec_time / sum(total_exec_time) OVER ())::numeric, 1) AS pct, rows, shared_blks_hit, shared_blks_read,
176  left(regexp_replace(query, '\\s+', ' ', 'g'), 90) AS q FROM pg_stat_statements WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database())
177  ORDER BY total_exec_time DESC LIMIT 8`)).rows;
178
179// Узгодженість: кеш = сума записів (повний перегляд) і кеш = контрольна точка + журнал після неї (інкрементально).
180let t = performance.now();
181const bad1 = await q1(`SELECT count(*) AS n FROM wms.product_stock s
182  LEFT JOIN (SELECT warehouse_id, product_id, sum(quantity) q FROM wms.inventory_item WHERE NOT is_container GROUP BY 1, 2) i USING (warehouse_id, product_id)
183  WHERE s.quantity <> coalesce(i.q, 0)`);
184const fullItemsMs = performance.now() - t;
185t = performance.now();
186// Інкрементально: лише товари з рухами після контрольної точки (решта не могла змінитися через журнал).
187const bad2 = await q1(`SELECT count(*) AS n
188  FROM (SELECT warehouse_id, product_id, sum(qty_delta) q FROM wms.inventory_transaction
189        WHERE id > (SELECT v FROM wms.reconcile_meta WHERE k = 'tx') GROUP BY 1, 2) t
190  JOIN wms.product_stock s USING (warehouse_id, product_id)
191  LEFT JOIN wms.reconcile_checkpoint c USING (warehouse_id, product_id)
192  WHERE s.quantity <> coalesce(c.quantity, 0) + t.q`);
193const incrMs = performance.now() - t;
194t = performance.now();
195await q1(`SELECT count(*) FROM (SELECT warehouse_id, product_id, sum(qty_delta) FROM wms.inventory_transaction GROUP BY 1, 2) x`);
196const fullLedgerMs = performance.now() - t;
197await pool.end();
198
199function pct(a: number[], p: number) {
200  if (!a.length) return 0;
201  const s = Float64Array.from(a).sort();
202  return s[Math.min(s.length - 1, Math.floor((p / 100) * s.length))];
203}
204const res = {
205  tag: TAG, variant: opt.variant, mode: opt.mode, clients: CLIENTS * WAREHOUSES, seconds: wall, rateTarget: RATE,
206  pingP50: pct(pings, 50),
207  linesPerSec: linesDone / wall, opsPerSec: opsDone / wall,
208  ops: Object.fromEntries(OPS.map((o) => {
209    const s = stat[o];
210    return [o, { n: s.ms.length, lines: s.lines, p50: pct(s.ms, 50), p95: pct(s.ms, 95), p99: pct(s.ms, 99), max: s.ms.reduce((m, x) => Math.max(m, x), 0),
211      lockP50: pct(s.lockMs, 50), lockP99: pct(s.lockMs, 99), retries: s.retries, errors: s.errors, shortPct: s.issued + s.short ? (100 * s.short) / (s.issued + s.short) : 0,
212      rowsPerOp: s.rows / Math.max(1, s.ms.length), journalPerOp: s.journal / Math.max(1, s.ms.length), statementsPerOp: s.statements / Math.max(1, s.ms.length), opened: s.opened, cut: s.cut }];
213  })),
214  db: { commitsPerSec: Number(db.xact_commit) / wall, rollbacks: Number(db.xact_rollback), deadlocks: Number(db.deadlocks),
215    cacheHitPct: (100 * Number(db.blks_hit)) / (Number(db.blks_hit) + Number(db.blks_read)), walMBperSec: (Number(after.wal) - Number(before.wal)) / 2 ** 20 / wall,
216    walBytesPerLine: (Number(after.wal) - Number(before.wal)) / Math.max(1, linesDone),
217    txRowsAdded: Number(after.tx) - Number(before.tx), txRowsPerLine: (Number(after.tx) - Number(before.tx)) / Math.max(1, linesDone),
218    itemsDelta: Number(after.items) - Number(before.items), archiveAdded: Number(after.arch) - Number(before.arch) },
219  consistency: { stockVsItems: Number(bad1.n), stockVsLedgerIncremental: Number(bad2.n), fullItemsScanMs: fullItemsMs, incrementalLedgerMs: incrMs, fullLedgerMs },
220  topStatements: top,
221  timeline,
222};
223mkdirSync('out', { recursive: true });
224writeFileSync(`out/load-${TAG}.json`, JSON.stringify(res, null, 1));
225const f = (x: number) => x.toFixed(1);
226console.log(`\n${TAG}: ${f(res.linesPerSec)} рядків/с, ${f(res.opsPerSec)} запитів/с, комітів ${f(res.db.commitsPerSec)}/с, WAL ${f(res.db.walMBperSec)} МБ/с, кеш ${f(res.db.cacheHitPct)}%, deadlocks ${res.db.deadlocks}`);
227for (const o of OPS) {
228  const x = res.ops[o];
229  console.log(`  ${o.padEnd(9)} n=${x.n} p50 ${f(x.p50)} p95 ${f(x.p95)} p99 ${f(x.p99)} max ${f(x.max)} мс | lock p50 ${f(x.lockP50)} p99 ${f(x.lockP99)} | retry ${x.retries} err ${x.errors} | short ${f(x.shortPct)}%`);
230}
231console.log(`  узгодженість: кеш≠записи ${res.consistency.stockVsItems}, кеш≠журнал ${res.consistency.stockVsLedgerIncremental}; звірка: записи ${f(fullItemsMs)} мс, журнал інкр. ${f(incrMs)} мс, журнал повністю ${f(fullLedgerMs)} мс`);
232