techtools

run.ts

TypeScript · 347 рядків

1// Прогін за фазами. Лише логіка тесту й навантаження: усі операції з базою — через StockRepository.
2//   Фаза 1 — база й заливка: міграція, довідники, товари, початковий залишок (потоварні транзакції приймання).
3//   Фаза 2 — робота: щодня поповнення від попиту + паралельні пули опту, роздробу й переміщень;
4//            щотижня консолідація й архівація тижня журналу; щомісяця знімок.
5//   Фаза 3 — підсумок і report.md.
6import { mkdirSync, writeFileSync } from 'node:fs';
7import { loadConfig, type DemandProfile } from './config.ts';
8import { Faker } from './faker.ts';
9import { TxType, type ArchiveResult, type ConsolidationResult, type DocumentLine } from './models.ts';
10import { StockRepository } from './stock.ts';
11
12const cfg = loadConfig();
13mkdirSync(cfg.out, { recursive: true });
14const faker = new Faker(cfg.seed);
15const rng = faker.rng;
16const DAY = 86_400_000;
17const START = Date.parse(`${cfg.start}T00:00:00Z`);
18const iso = (ms: number) => new Date(ms).toISOString();
19const ymd = (ms: number) => iso(ms).slice(0, 10);
20const pct = (a: number[], p: number) => { if (!a.length) return 0; const s = Float64Array.from(a).sort(); return s[Math.min(s.length - 1, Math.floor((p / 100) * s.length))]; };
21const fmt = (x: number) => Math.round(x).toLocaleString('uk-UA');
22const f1 = (x: number) => x.toFixed(1);
23const log = (s: string) => console.log(s);
24
25// ---------- задачі й пули виконавців ----------
26
27type Role = 'receiving' | 'wholesale' | 'retail' | 'transfer';
28type Kind = 'fill' | 'replenish' | 'transfer_in' | 'wholesale' | 'retail' | 'transfer';
29const KINDS: Kind[] = ['fill', 'replenish', 'transfer_in', 'wholesale', 'retail', 'transfer'];
30interface Task { kind: Kind; wh: number; at: number; productId?: number; qty?: number; loose?: boolean; lines?: DocumentLine[]; dest?: number }
31
32class Queue {
33  private items: Task[] = [];
34  private head = 0;
35  push(t: Task) { this.items.push(t); }
36  pushAll(ts: Task[]) { for (const t of ts) this.items.push(t); }
37  shift(): Task | undefined {
38    if (this.head >= this.items.length) return undefined;
39    const t = this.items[this.head++];
40    if (this.head > 65_536 && this.head * 2 > this.items.length) { this.items = this.items.slice(this.head); this.head = 0; }
41    return t;
42  }
43  get length() { return this.items.length - this.head; }
44}
45
46const queues = new Map<string, Queue>();
47const q = (wh: number, role: Role) => { const k = `${wh}:${role}`; return queues.get(k) ?? queues.set(k, new Queue()).get(k)!; };
48
49interface Acc { n: number; lines: number; units: number; requested: number; issued: number; short: number; opened: number; cut: number; journal: number; errors: number; ms: number[] }
50const newAcc = (): Record<Kind, Acc> => Object.fromEntries(KINDS.map((k) => [k, { n: 0, lines: 0, units: 0, requested: 0, issued: 0, short: 0, opened: 0, cut: 0, journal: 0, errors: 0, ms: [] }])) as any;
51let acc = newAcc();
52let docSeq = 1;
53const issuedToday: Map<number, number>[] = Array.from({ length: cfg.warehouses }, () => new Map());
54
55const repo = await (async () => {
56  await StockRepository.createDatabase(cfg.db.server, cfg.db.name, cfg.db.recreate);
57  const perWh = cfg.workers.receiving + cfg.workers.wholesale + cfg.workers.retail + cfg.workers.transfer;
58  return StockRepository.open(`${cfg.db.server}/${cfg.db.name}`, perWh * cfg.warehouses + 4);
59})();
60
61async function execute(t: Task, user: number): Promise<void> {
62  const a = acc[t.kind];
63  const s = performance.now();
64  for (let attempt = 0; ; attempt++) {
65    try {
66      if (t.kind === 'fill' || t.kind === 'replenish' || t.kind === 'transfer_in') {
67        const cat = categoryOf[t.productId!];
68        const lot = faker.lot(cat, t.qty!, t.at, t.loose);
69        const r = await repo.receive({
70          warehouseId: t.wh, productId: t.productId!, lines: lot.lines, mfgDate: lot.mfgDate, expiryDate: lot.expiryDate,
71          locationId: pickLocation(t.wh, t.productId!), docId: docSeq++, userId: user, at: iso(t.at),
72          type: t.kind === 'transfer_in' ? TxType.TRANSFER_IN : TxType.RECEIVE,
73        });
74        a.units += r.units; a.lines += 1; a.journal += r.journalRows;
75      } else {
76        const r = await repo.issue({ warehouseId: t.wh, lines: t.lines!, docId: docSeq++, userId: user, at: iso(t.at), type: t.kind === 'transfer' ? TxType.TRANSFER_OUT : TxType.ISSUE });
77        a.lines += t.lines!.length; a.requested += r.requested; a.issued += r.issued; a.short += r.short;
78        a.opened += r.openedPacks; a.cut += r.cutContainers; a.journal += r.journalRows;
79        const day = issuedToday[t.wh - 1];
80        for (const p of r.products) day.set(p.productId, (day.get(p.productId) ?? 0) + p.qty);
81        if (t.kind === 'transfer') {
82          // склад-одержувач приймає потоварно, розсипом, через годину модельного часу
83          for (const p of r.products) q(t.dest!, 'receiving').push({ kind: 'transfer_in', wh: t.dest!, at: t.at + 3_600_000, productId: p.productId, qty: p.qty, loose: true });
84        }
85      }
86      break;
87    } catch (e: any) {
88      if ((e.code === '40P01' || e.code === '40001') && attempt < 5) continue;
89      a.errors++;
90      if (a.errors <= 3) console.error(t.kind, e.code ?? '', e.message);
91      break;
92    }
93  }
94  a.ms.push(performance.now() - s);
95  a.n++;
96}
97
98const ROLES: Role[] = ['receiving', 'wholesale', 'retail', 'transfer'];
99/** Наступна задача для виконавця: зі своєї черги або (shared) з будь-якої черги складу пропорційно до її довжини. */
100function nextTask(wh: number, role: Role | 'any'): Task | undefined {
101  if (role !== 'any') return q(wh, role).shift();
102  const qs = ROLES.map((r) => q(wh, r));
103  const total = qs.reduce((s, x) => s + x.length, 0);
104  if (!total) return undefined;
105  let x = rng.next() * total;
106  for (const qq of qs) if ((x -= qq.length) < 0) return qq.shift();
107  return qs.find((qq) => qq.length)?.shift();
108}
109
110/** Запустити пули виконавців і дочекатися, поки спорожніють усі черги. */
111async function drain(pools: { wh: number; role: Role | 'any'; workers: number; from?: Role }[]): Promise<void> {
112  let inflight = 0;
113  let user = 0;
114  await Promise.all(pools.flatMap((p) => Array.from({ length: p.workers }, async () => {
115    const id = ++user;
116    for (;;) {
117      const t = nextTask(p.wh, p.from ?? p.role);
118      if (t) { inflight++; await execute(t, id); inflight--; continue; }
119      if (inflight === 0 && [...queues.values()].every((x) => x.length === 0)) return;
120      await new Promise((r) => setTimeout(r, 2));
121    }
122  })));
123}
124
125const perWarehouse = cfg.workers.receiving + cfg.workers.wholesale + cfg.workers.retail + cfg.workers.transfer;
126const rolePools = (from?: Role) => Array.from({ length: cfg.warehouses }, (_, i) => i + 1).flatMap((wh) =>
127  cfg.workers.mode === 'shared' && !from
128    ? [{ wh, role: 'any' as const, workers: perWarehouse }]
129    : ROLES.map((role) => ({ wh, role, workers: cfg.workers[role], from })));
130
131// ---------- фаза 1: база й заливка ----------
132
133const t0 = performance.now();
134const migrated = await repo.migrate();
135await repo.ensurePartitions(ymd(START - 14 * DAY), ymd(START + (cfg.days + 21) * DAY));
136const categories = faker.categories();
137await repo.saveWarehouses(Array.from({ length: cfg.warehouses }, (_, i) => ({ id: i + 1, name: `Склад ${i + 1}` })));
138const brands = faker.brands(cfg.catalog.brands);
139await repo.saveBrands(brands);
140await repo.saveCategories(categories);
141const products = faker.products({ brands, skuMin: cfg.catalog.skuMin, skuMax: cfg.catalog.skuMax, categoriesPerBrand: cfg.catalog.categoriesPerBrand, sharedSkuShare: cfg.catalog.sharedSkuShare });
142const tCatalog = performance.now();
143const ids = await repo.insertProducts(products);
144const catalogMs = performance.now() - tCatalog;
145const categoryOf = new Int16Array(ids.length + 1);
146ids.forEach((id, i) => (categoryOf[id] = products[i].category_id));
147const N = ids.length;
148
149// адреса товару на складі (комірка відбору): стала для пари склад × товар
150const locations = Array.from({ length: cfg.warehouses }, () => new Map<number, number>());
151function pickLocation(wh: number, pid: number): number {
152  const m = locations[wh - 1];
153  let l = m.get(pid);
154  if (l == null) { l = faker.location(); m.set(pid, l); }
155  return l;
156}
157
158// популярність: глобальний ранг; на складі — товари в наявності за рангом
159const rank = rng.shuffle(Array.from({ length: N }, (_, i) => ids[i]));
160const stocked: Int32Array[] = [];
161const FILL_AT = START - DAY;
162const tFill = performance.now();
163for (let wh = 1; wh <= cfg.warehouses; wh++) {
164  const mine = rank.filter(() => rng.chance(cfg.initialStock.share));
165  stocked.push(Int32Array.from(mine));
166  const tasks: Task[] = [];
167  for (let i = 0; i < mine.length; i++) {
168    const qty = rng.int(cfg.initialStock.min, cfg.initialStock.max);
169    const at = FILL_AT + Math.floor((i / mine.length) * DAY);
170    const parts = rng.chance(cfg.initialStock.splitLotShare) && qty >= 10 ? [Math.floor(qty / 2), qty - Math.floor(qty / 2)] : [qty];
171    for (const p of parts) tasks.push({ kind: 'fill', wh, at, productId: mine[i], qty: p });
172  }
173  q(wh, 'receiving').pushAll(tasks);
174}
175await drain(rolePools('receiving'));
176const fillMs = performance.now() - tFill;
177const phase1 = {
178  migrated, products: N, brands: brands.length, categories: categories.length, names: faker.allNames().length,
179  catalogSeconds: catalogMs / 1000, fillSeconds: fillMs / 1000, totalSeconds: (performance.now() - t0) / 1000,
180  trucks: stocked.reduce((s, x) => s + Math.ceil(x.length / cfg.replenish.truckProducts), 0),
181  fill: { n: acc.fill.n, units: acc.fill.units, p50: pct(acc.fill.ms, 50), p95: pct(acc.fill.ms, 95), p99: pct(acc.fill.ms, 99), errors: acc.fill.errors },
182  warehouses: await repo.warehouseStock(), sizes: await repo.tableSizes(), items: await repo.itemStats(),
183};
184writeFileSync(`${cfg.out}/phase1.json`, JSON.stringify(phase1, null, 1));
185log(`ФАЗА 1: ${fmt(N)} товарів (${brands.length} брендів, ${categories.length} категорій, ${fmt(phase1.names)} назв); каталог ${f1(phase1.catalogSeconds)} с; заливка ${f1(phase1.fillSeconds)} с — ${fmt(acc.fill.n)} транзакцій приймання, p50 ${f1(phase1.fill.p50)} p99 ${f1(phase1.fill.p99)} мс`);
186for (const w of phase1.warehouses) log(`  склад ${w.warehouseId}: товарів ${fmt(w.products)}, одиниць ${fmt(w.units)}, сер. ${w.avgPerProduct}`);
187
188// ---------- фаза 2: робота ----------
189
190await repo.resetStatementStats();
191acc = newAcc();
192const zipf = (n: number) => Math.min(n - 1, Math.floor(Math.pow(1 + rng.next() * (Math.pow(n, 1 - cfg.popularity) - 1), 1 / (1 - cfg.popularity))) - 1);
193const pickProduct = (wh: number) => stocked[wh - 1][zipf(stocked[wh - 1].length)];
194const avgDemand = Array.from({ length: cfg.warehouses }, () => new Map<number, number>());
195
196function documents(wh: number, kind: 'wholesale' | 'retail' | 'transfer', p: DemandProfile, dayStart: number): Task[] {
197  return Array.from({ length: p.docsPerDay }, () => {
198    const m = new Map<number, number>();
199    const n = rng.int(p.lines[0], p.lines[1]);
200    for (let i = 0; i < n; i++) { const pid = pickProduct(wh); m.set(pid, (m.get(pid) ?? 0) + rng.int(p.qty[0], p.qty[1])); }
201    return { kind, wh, at: dayStart + Math.floor(rng.next() * 0.95 * DAY), lines: [...m].map(([productId, qty]) => ({ productId, qty })), dest: kind === 'transfer' ? (wh % cfg.warehouses) + 1 : undefined };
202  });
203}
204
205let replenish = { trucks: 0, lots: 0 };
206const weekly: { consolidation: ConsolidationResult; archived: ArchiveResult | null }[] = [];
207const months: any[] = [];
208let monthWall = performance.now();
209let monthTx = 0;
210const rp = cfg.replenish;
211
212for (let d = 0; d < cfg.days; d++) {
213  const dayStart = START + d * DAY;
214  for (let wh = 1; wh <= cfg.warehouses; wh++) {
215    // поповнення: поріг і кількість від середнього денного попиту
216    const avg = avgDemand[wh - 1];
217    const thresholds = rp.demandBased && avg.size
218      ? new Map([...avg].map(([pid, a]) => [pid, Math.max(rp.minReorderPoint, Math.ceil(a * rp.leadDays))]))
219      : rp.minReorderPoint;
220    const low = await repo.lowStock(wh, thresholds);
221    replenish.trucks += Math.ceil(low.length / rp.truckProducts);
222    replenish.lots += low.length;
223    q(wh, 'receiving').pushAll(low.map((r, i) => {
224      const a = avg.get(r.productId) ?? 0;
225      const base = rng.int(rp.lotQty[0], rp.lotQty[1]);
226      const qty = faker.roundToPack(categoryOf[r.productId], rp.demandBased ? Math.max(base, Math.ceil(a * rp.coverDays)) : base);
227      return { kind: 'replenish' as Kind, wh, at: dayStart + Math.floor((i / Math.max(1, low.length)) * 0.4 * DAY), productId: r.productId, qty };
228    }));
229    q(wh, 'wholesale').pushAll(documents(wh, 'wholesale', cfg.demand.wholesale, dayStart));
230    q(wh, 'retail').pushAll(documents(wh, 'retail', cfg.demand.retail, dayStart));
231    if (cfg.warehouses > 1) q(wh, 'transfer').pushAll(documents(wh, 'transfer', cfg.demand.transfer, dayStart));
232  }
233  await drain(rolePools());
234  // середній попит (експоненційне згладжування)
235  for (let wh = 1; wh <= cfg.warehouses; wh++) {
236    const avg = avgDemand[wh - 1];
237    const today = issuedToday[wh - 1];
238    for (const [pid, a] of avg) avg.set(pid, a * 0.9 + (today.get(pid) ?? 0) * 0.1);
239    for (const [pid, u] of today) if (!avg.has(pid)) avg.set(pid, u * 0.1);
240    today.clear();
241  }
242
243  // кінець тижня: консолідація, тиждень hotWeeks тому — в архів
244  if ((d + 1) % 7 === 0) {
245    const weekStart = dayStart - 6 * DAY;
246    const consolidation = await repo.consolidateWeek(ymd(weekStart));
247    const archived = await repo.archiveWeek(ymd(weekStart - 7 * cfg.archive.hotWeeks * DAY), cfg.archive.index);
248    weekly.push({ consolidation, archived });
249  }
250
251  // кінець місяця: знімок
252  const next = new Date(dayStart + DAY);
253  if (next.getUTCDate() === 1 || d === cfg.days - 1) {
254    const wall = (performance.now() - monthWall) / 1000;
255    const tx = KINDS.reduce((s, k) => s + acc[k].n, 0);
256    const ops = Object.fromEntries(KINDS.filter((k) => acc[k].n).map((k) => {
257      const a = acc[k];
258      return [k, { n: a.n, lines: a.lines, units: a.units, requested: a.requested, issued: a.issued, short: a.short, opened: a.opened, cut: a.cut,
259        journal: a.journal, errors: a.errors, p50: pct(a.ms, 50), p95: pct(a.ms, 95), p99: pct(a.ms, 99) }];
260    }));
261    const weeks = weekly.splice(0);
262    const m = {
263      month: ymd(dayStart).slice(0, 7), wallSeconds: wall, transactions: tx, ops, replenish: { ...replenish },
264      weeks: weeks.map((w) => ({ week: w.consolidation.weekStart, mismatches: w.consolidation.mismatches, advanced: w.consolidation.advanced,
265        consolidateMs: w.consolidation.ms, archived: w.archived })),
266      warehouses: await repo.warehouseStock(), sizes: await repo.tableSizes(), items: await repo.itemStats(),
267    };
268    months.push(m);
269    writeFileSync(`${cfg.out}/month-${m.month}.json`, JSON.stringify(m, null, 1));
270    const o: any = m.ops;
271    const sold = (o.wholesale?.issued ?? 0) + (o.retail?.issued ?? 0);
272    const opened = (o.wholesale?.opened ?? 0) + (o.retail?.opened ?? 0) + (o.transfer?.opened ?? 0);
273    const mism = m.weeks.reduce((s: number, w: any) => s + w.mismatches, 0);
274    log(`${m.month}: ${f1(wall)} с, транзакцій ${fmt(tx)} (${fmt(tx / wall)}/с), продано ${fmt(sold)} шт, фур ${replenish.trucks} (${fmt(replenish.lots)} партій), розкрито ${fmt(opened)}, записів на позицію ${f1(m.items.records / Math.max(1, m.items.positions))} | опт p50 ${f1(o.wholesale?.p50 ?? 0)} p95 ${f1(o.wholesale?.p95 ?? 0)} мс, роздріб p50 ${f1(o.retail?.p50 ?? 0)} мс | тижнів ${m.weeks.length}, розбіжн. ${mism}`);
275    acc = newAcc();
276    replenish = { trucks: 0, lots: 0 };
277    monthWall = performance.now();
278    monthTx += tx;
279  }
280}
281
282// ---------- фаза 3: підсумок ----------
283
284const top = await repo.topStatements(10);
285const finalSizes = await repo.tableSizes();
286const finalItems = await repo.itemStats();
287await repo.close();
288
289const sum = (k: Kind, f: string) => months.reduce((s, m) => s + (m.ops[k]?.[f] ?? 0), 0);
290const summary = {
291  config: cfg, phase1, totalMinutes: (performance.now() - t0) / 60_000, transactions: monthTx,
292  sold: sum('wholesale', 'issued') + sum('retail', 'issued'), requested: sum('wholesale', 'requested') + sum('retail', 'requested'),
293  transferred: sum('transfer', 'issued'), replenished: sum('replenish', 'units'), journalRows: KINDS.reduce((s, k) => s + sum(k, 'journal'), 0),
294  mismatches: months.reduce((s, m) => s + m.weeks.reduce((x: number, w: any) => x + w.mismatches, 0), 0),
295  finalSizes, finalItems, topStatements: top,
296};
297writeFileSync(`${cfg.out}/summary.json`, JSON.stringify(summary, null, 1));
298
299const row = (m: any) => {
300  const o = m.ops;
301  const sold = (o.wholesale?.issued ?? 0) + (o.retail?.issued ?? 0);
302  const req = (o.wholesale?.requested ?? 0) + (o.retail?.requested ?? 0);
303  const opened = (o.wholesale?.opened ?? 0) + (o.retail?.opened ?? 0) + (o.transfer?.opened ?? 0);
304  const size = (t: string) => m.sizes.find((s: any) => s.table === t)?.totalMB ?? 0;
305  const cons = m.weeks.map((w: any) => w.consolidateMs);
306  const arch = m.weeks.map((w: any) => w.archived?.organizeMs ?? 0);
307  return `| ${m.month} | ${f1(m.wallSeconds)} | ${fmt(m.transactions)} | ${fmt(sold)} | ${f1((100 * (req - sold)) / Math.max(1, req))}% | ${fmt(o.transfer?.issued ?? 0)} | ${m.replenish.trucks} / ${fmt(m.replenish.lots)} | ${fmt(opened)} | ${f1(m.items.records / Math.max(1, m.items.positions))} | ${f1(o.wholesale?.p50 ?? 0)} / ${f1(o.wholesale?.p95 ?? 0)} | ${f1(o.retail?.p50 ?? 0)} / ${f1(o.retail?.p95 ?? 0)} | ${f1(o.replenish?.p50 ?? 0)} | ${fmt(size('inventory_transaction'))} / ${fmt(size('inventory_transaction_archive'))} | ${fmt(size('inventory_item'))} | ${fmt(size('inventory_item_archive'))} | ${f1(Math.max(0, ...cons) / 1000)} / ${f1(Math.max(0, ...arch) / 1000)} | ${m.weeks.reduce((s: number, w: any) => s + w.mismatches, 0)} |`;
308};
309const md = `# Прогін stock-db (структура v4)
310
311Каталог: ${fmt(N)} товарів, ${brands.length} брендів, ${categories.length} категорій, ${fmt(phase1.names)} назв. Склади: ${cfg.warehouses}. Виконавців на склад (${cfg.workers.mode === 'shared' ? 'спільні, будь-яка задача' : 'за ролями'}): приймання ${cfg.workers.receiving}, опт ${cfg.workers.wholesale}, роздріб ${cfg.workers.retail}, переміщення ${cfg.workers.transfer}. Документів на склад на день: опт ${cfg.demand.wholesale.docsPerDay}, роздріб ${cfg.demand.retail.docsPerDay}, переміщення ${cfg.demand.transfer.docsPerDay}. Поповнення ${cfg.replenish.demandBased ? `від попиту (покриття ${cfg.replenish.coverDays} дн.)` : 'фіксоване'}; індекс архіву журналу: ${cfg.archive.index}.
312
313## Фаза 1
314
315Каталог ${f1(phase1.catalogSeconds)} с; заливка ${f1(phase1.fillSeconds)} с, ${fmt(phase1.fill.n)} транзакцій приймання, p50 ${f1(phase1.fill.p50)} / p95 ${f1(phase1.fill.p95)} / p99 ${f1(phase1.fill.p99)} мс.
316
317| склад | товарів | одиниць | середнє |
318|---|---|---|---|
319${phase1.warehouses.map((w) => `| ${w.warehouseId} | ${fmt(w.products)} | ${fmt(w.units)} | ${w.avgPerProduct} |`).join('\n')}
320
321## Фаза 2
322
323| місяць | час, с | транзакцій | продано | недостача | переміщено | фур / партій | розкрито | записів на позицію | опт p50/p95 мс | роздріб p50/p95 мс | партія p50 мс | журнал робочий / архів МБ | запас МБ | архів записів МБ | консолідація / архівація max, с | розбіжн. |
324|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
325${months.map(row).join('\n')}
326
327## Фаза 3
328
329Загалом ${f1(summary.totalMinutes)} хв; транзакцій ${fmt(summary.transactions)}; продано ${fmt(summary.sold)} з ${fmt(summary.requested)} запитаних; переміщено ${fmt(summary.transferred)}; поповнено ${fmt(summary.replenished)}; рядків журналу ${fmt(summary.journalRows)}; розбіжностей консолідації ${summary.mismatches}.
330
331Записи запасу: ${fmt(finalItems.records)} на ${fmt(finalItems.positions)} позицій (${f1(finalItems.records / Math.max(1, finalItems.positions))} на позицію), розсип ${fmt(finalItems.looseRecords)} (з нулем ${fmt(finalItems.looseZero)}).
332
333| записів на позицію | ${finalItems.recordsPerPosition.map((b) => b.bucket).join(' | ')} |
334|---|${finalItems.recordsPerPosition.map(() => '---').join('|')}|
335| позицій | ${finalItems.recordsPerPosition.map((b) => fmt(b.positions)).join(' | ')} |
336
337| таблиця | розділів | рядків | МБ | індекси МБ |
338|---|---|---|---|---|
339${finalSizes.map((s) => `| ${s.table} | ${s.partitions} | ${fmt(s.rows)} | ${fmt(s.totalMB)} | ${fmt(s.indexMB)} |`).join('\n')}
340
341| % часу бази | викликів | сер. мс | оператор |
342|---|---|---|---|
343${top.map((s) => `| ${f1(s.pct)} | ${fmt(s.calls)} | ${s.meanMs.toFixed(3)} | \`${s.query}\` |`).join('\n')}
344`;
345writeFileSync(`${cfg.out}/report.md`, md);
346log(`\nготово: ${f1(summary.totalMinutes)} хв; звіт ${cfg.out}/report.md`);
347