run.ts
TypeScript · 242 рядків
1// Прогін через API: дні роботи складів у модельному часі — поповнення від попиту, продажі опт/роздріб, переміщення,
2// списання; щотижня — консолідація й архів журналу; наприкінці — ціна трасування, інваріанти, статистика бази, звіт.
3//
4// node scripts/run.ts [--url http://127.0.0.1:3001] [--days 14] [--start 2027-01-04] [--scale 0.1] [--workers 15]
5// [--index brin] [--trace-sample 300] [--out out/run]
6//
7// scale множить денний попит R-05 (опт 6 000, роздріб 2 000, переміщення 2 000 документів на склад). Без SQL — лише HTTP.
8import { mkdirSync, writeFileSync } from 'node:fs';
9import { join } from 'node:path';
10import { parseArgs } from 'node:util';
11import { Api } from './client.ts';
12import { Faker } from './faker.ts';
13import { Latency, fmt, int, latencyTable, pool, table } from './measure.ts';
14
15const { values: v } = parseArgs({
16 options: {
17 url: { type: 'string', default: 'http://127.0.0.1:3001' },
18 days: { type: 'string', default: '14' },
19 start: { type: 'string', default: '2027-01-04' },
20 scale: { type: 'string', default: '0.1' },
21 workers: { type: 'string', default: '15' },
22 index: { type: 'string', default: 'brin' },
23 'trace-sample': { type: 'string', default: '300' },
24 seed: { type: 'string', default: '7' },
25 out: { type: 'string', default: 'out/run' },
26 },
27});
28
29const DAY = 86_400_000;
30const scale = Number(v.scale);
31const days = Number(v.days);
32const start = Date.parse(`${v.start}T00:00:00Z`);
33const ymd = (ms: number) => new Date(ms).toISOString().slice(0, 10);
34const cfg = {
35 wholesale: { docs: Math.round(6000 * scale), lines: [1, 10], qty: [1, 10] },
36 retail: { docs: Math.round(2000 * scale), lines: [1, 3], qty: [1, 4] },
37 transfer: { docs: Math.round(2000 * scale), lines: [1, 10], qty: [1, 10] },
38 writeOff: { docs: Math.max(1, Math.round(100 * scale)), lines: [1, 1], qty: [1, 3] },
39 replenish: { lotQty: [15, 25], minRop: 10, leadDays: 2, coverDays: 7 },
40 popularity: 0.8,
41};
42
43const api = new Api(v.url!, 64);
44const f = new Faker(Number(v.seed));
45const lat = new Latency();
46const rng = f.rng;
47
48// ---------- підготовка ----------
49const meta = await api.get('/api/meta');
50const warehouses: number[] = meta.warehouses.map((w: any) => w.id);
51if (!meta.products) throw new Error('Каталог порожній: спершу npm run seed -- --url ' + v.url);
52const catalog: { id: number; categoryId: number }[] = [];
53for (let after = 0; ;) {
54 const page = await api.get<{ id: number; categoryId: number }[]>('/api/catalog/products', { afterId: after, limit: 50_000 });
55 if (!page.length) break;
56 catalog.push(...page);
57 after = page.at(-1)!.id;
58}
59const categoryOf = new Map(catalog.map((p) => [p.id, p.categoryId]));
60await api.post('/api/maintenance/partitions', { from: ymd(start - 14 * DAY), to: ymd(start + (days + 14) * DAY) });
61await api.post('/api/stats/reset').catch(() => {});
62const dbBefore = (await api.get('/api/stats', { top: 1 })).database;
63
64// Популярність за Ципфом: перемішаний каталог, вага 1/rank^s; вибір — бінарним пошуком по накопиченій вазі.
65const ranked = rng.shuffle(catalog.map((p) => p.id));
66const cum: number[] = [];
67ranked.reduce((s, _, i) => (cum[i] = s + 1 / (i + 1) ** cfg.popularity), 0);
68const pickProduct = () => {
69 const x = rng.next() * cum.at(-1)!;
70 let lo = 0, hi = cum.length - 1;
71 while (lo < hi) { const m = (lo + hi) >> 1; if (cum[m] < x) lo = m + 1; else hi = m; }
72 return ranked[lo];
73};
74const lines = (p: { lines: number[]; qty: number[] }) => {
75 const m = new Map<number, number>();
76 for (let i = rng.int(p.lines[0], p.lines[1]); i > 0; i--) m.set(pickProduct(), rng.int(p.qty[0], p.qty[1]));
77 return [...m].map(([productId, qty]) => ({ productId, qty }));
78};
79
80// попит на позицію (склад|товар) — для порогу й обсягу дозамовлення
81const demand = new Map<string, number>();
82const noteDemand = (w: number, l: { productId: number; qty: number }[]) => { for (const x of l) demand.set(`${w}|${x.productId}`, (demand.get(`${w}|${x.productId}`) ?? 0) + x.qty); };
83const totals = { requested: 0, issued: 0, short: 0, received: 0, transfers: 0, openedPacks: 0, cutContainers: 0, docs: 0, trucksLots: 0 };
84const daily: (string | number)[][] = [];
85const weekly: (string | number)[][] = [];
86let docSeq = 1;
87
88// ---------- дні ----------
89const t0 = performance.now();
90for (let d = 0; d < days; d++) {
91 const dayStart = start + d * DAY;
92 const tDay = performance.now();
93 const before = { ...totals };
94 const tasks: (() => Promise<unknown>)[] = [];
95
96 // поповнення: позиції з доступним ≤ порогу попиту → партія на cover днів
97 for (const w of warehouses) {
98 const rop = (pid: number) => Math.max(cfg.replenish.minRop, Math.ceil(((demand.get(`${w}|${pid}`) ?? 0) / Math.max(1, d)) * cfg.replenish.leadDays));
99 let maxRop = cfg.replenish.minRop;
100 for (const [key, q] of demand) if (key.startsWith(`${w}|`)) maxRop = Math.max(maxRop, Math.ceil((q / Math.max(1, d)) * cfg.replenish.leadDays));
101 const low = await lat.time('lowStock', () => api.get<{ productId: number; available: number }[]>('/api/stock/low', { warehouseId: w, max: maxRop }));
102 for (const x of low ?? []) {
103 if (x.available > rop(x.productId)) continue;
104 const perDay = (demand.get(`${w}|${x.productId}`) ?? 0) / Math.max(1, d);
105 const cat = categoryOf.get(x.productId)!;
106 const qty = f.roundToPack(cat, Math.max(rng.int(cfg.replenish.lotQty[0], cfg.replenish.lotQty[1]), Math.ceil(perDay * cfg.replenish.coverDays)));
107 const lot = f.lot(cat, qty, dayStart, { bundleShare: 0.03 });
108 const locationId = f.location();
109 totals.trucksLots++;
110 tasks.push(async () => {
111 const r = await lat.time('receive', () => api.post('/api/receipts', { warehouseId: w, productId: x.productId, locationId, docId: docSeq++, ...lot, at: atOf() }));
112 if (r) totals.received += r.units;
113 });
114 }
115 }
116 // документи
117 for (const w of warehouses) {
118 const other = warehouses.find((x) => x !== w) ?? w;
119 const sale = (op: string, p: typeof cfg.retail) => () => {
120 const l = lines(p);
121 noteDemand(w, l);
122 return lat.time(op, () => api.post('/api/issues', { warehouseId: w, kind: 'sale', lines: l, docId: docSeq++, at: atOf() })).then(count);
123 };
124 for (let i = 0; i < cfg.wholesale.docs; i++) tasks.push(sale('issue опт', cfg.wholesale));
125 for (let i = 0; i < cfg.retail.docs; i++) tasks.push(sale('issue роздріб', cfg.retail));
126 for (let i = 0; i < cfg.writeOff.docs; i++) {
127 tasks.push(() => lat.time('issue списання', () => api.post('/api/issues', { warehouseId: w, kind: 'write_off', lines: lines(cfg.writeOff), at: atOf() })).then(count));
128 }
129 if (other !== w) {
130 for (let i = 0; i < cfg.transfer.docs; i++) {
131 tasks.push(() => {
132 const l = lines(cfg.transfer);
133 noteDemand(w, l);
134 return lat.time('transfer', () => api.post('/api/transfers', { fromWarehouseId: w, toWarehouseId: other, toLocationId: f.location(), lines: l, docId: docSeq++, at: atOf() }))
135 .then((r: any) => { if (r) { count(r.shipped); totals.transfers += r.receivedUnits; } });
136 });
137 }
138 }
139 }
140 rng.shuffle(tasks);
141 // модельний час — рівномірно по робочому дню 08:00–18:00 у порядку виконання
142 let k = 0;
143 const atOf = () => new Date(dayStart + 8 * 3600_000 + Math.floor((k++ / tasks.length) * 10 * 3600_000)).toISOString();
144 await pool(Number(v.workers), tasks);
145 const sec = (performance.now() - tDay) / 1000;
146 const delta = (key: keyof typeof totals) => totals[key] - before[key];
147 daily.push([ymd(dayStart), int(tasks.length), int(delta('docs')), int(delta('trucksLots')), int(delta('issued')),
148 `${fmt((100 * delta('short')) / Math.max(1, delta('requested')))}%`, fmt(sec), int(tasks.length / sec)]);
149 console.log(`${ymd(dayStart)}: ${int(tasks.length)} запитів за ${fmt(sec)} с (${int(tasks.length / sec)}/с), нестача ${fmt((100 * delta('short')) / Math.max(1, delta('requested')))}%`);
150
151 // кінець тижня: консолідація до понеділка, потім архів попереднього тижня (у роботі — поточний + 1)
152 if ((d + 1) % 7 === 0) {
153 const weekEnd = dayStart + DAY;
154 const c = await lat.time('consolidate', () => api.post('/api/maintenance/consolidate', { until: new Date(weekEnd).toISOString() }));
155 const archiveStart = weekEnd - 14 * DAY;
156 const a = archiveStart >= start ? await lat.time('archiveWeek', () => api.post('/api/maintenance/archive-week', { weekStart: ymd(archiveStart), index: v.index })) : null;
157 weekly.push([ymd(weekEnd - 7 * DAY), int(c?.positions ?? 0), int(c?.mismatches ?? -1), int(c?.advanced ?? 0), fmt(c?.ms ?? 0, 0),
158 a?.archived ? `${a.partition}: ${int(a.rows)} рядків, ${fmt(a.detachMs + a.organizeMs + a.attachMs, 0)} мс` : '—']);
159 console.log(` консолідація: ${c?.positions} позицій, розбіжностей ${c?.mismatches}, ${fmt(c?.ms ?? 0, 0)} мс${a?.archived ? `; архів ${a.partition} ${int(a.rows)} рядків` : ''}`);
160 }
161}
162const totalSec = (performance.now() - t0) / 1000;
163
164function count(r: any) {
165 if (!r) return;
166 totals.docs++;
167 totals.requested += r.requested;
168 totals.issued += r.issued;
169 totals.short += r.short;
170 totals.openedPacks += r.openedPacks;
171 totals.cutContainers += r.cutContainers;
172}
173
174// ---------- ціна трасування: однакові документи з ?trace=1 і без ----------
175const traceLat = new Latency();
176const sampleN = Number(v['trace-sample']);
177for (let i = 0; i < sampleN; i++) {
178 const w = warehouses[i % warehouses.length];
179 const l = lines(cfg.wholesale);
180 const body = { warehouseId: w, kind: 'sale', lines: l, partial: true };
181 // dryRun в обох — стан бази не змінюється, порівнюються лише накладні трасування
182 await traceLat.time('issue (dryRun)', () => api.post('/api/issues?dryRun=1', body));
183 await traceLat.time('issue (dryRun + trace)', () => api.post('/api/issues?dryRun=1&trace=1', body));
184}
185
186// ---------- підсумок ----------
187const inv = await api.get('/api/invariants');
188const st = await api.get('/api/stats', { top: 8 });
189const allRequests = lat.summary().reduce((s, x) => s + x.n, 0);
190const deadlocks = st.database.deadlocks - dbBefore.deadlocks;
191const report = [
192 `# Прогін stock-lab через API`,
193 '',
194 `${ymd(start)} … ${ymd(start + (days - 1) * DAY)} (${days} дн.), ${warehouses.length} склади, каталог ${int(catalog.length)} товарів, ` +
195 `масштаб попиту ${scale} від R-05, ${v.workers} одночасних виконавців, архів журналу — ${v.index}.`,
196 '',
197 `**Разом:** ${int(allRequests)} запитів за ${fmt(totalSec)} с (${int(allRequests / totalSec)}/с); документів видачі ${int(totals.docs)}, ` +
198 `видано ${int(totals.issued)} од., нестача ${fmt((100 * totals.short) / Math.max(1, totals.requested))}%; партій поповнення ${int(totals.trucksLots)} (${int(totals.received)} од.); ` +
199 `переміщено ${int(totals.transfers)} од.; розкрито пакувань ${int(totals.openedPacks)}, розрізано спайок ${int(totals.cutContainers)}.`,
200 '',
201 `**Взаємні блокування за прогін:** ${int(deadlocks)} (платформа повторює транзакцію; кожне коштує ≥ deadlock_timeout очікування). ` +
202 `База: ${int(st.database.size_mb)} МБ.`,
203 '',
204 `**Інваріанти:** ${inv.ok ? 'усі виконано' : inv.violations.map((x: any) => `${x.code} ×${x.count}`).join(', ')} (${inv.checked.length} правил, ${fmt(inv.ms, 0)} мс).`,
205 '',
206 '## Затримка за операцією (клієнт, включно з HTTP)',
207 '',
208 latencyTable(lat),
209 '',
210 '## По днях',
211 '',
212 table(['день', 'запитів', 'документів', 'партій', 'видано', 'нестача', 'с', 'запитів/с'], daily),
213 '',
214 '## Тижнева консолідація й архів',
215 '',
216 table(['тиждень', 'позицій', 'розбіжностей', 'зсунуто', 'мс', 'архів'], weekly),
217 '',
218 `## Ціна трасування (?trace=1), ${sampleN} однакових пар документів`,
219 '',
220 latencyTable(traceLat),
221 '',
222 '## Таблиці',
223 '',
224 table(['таблиця', 'розділів', 'рядків', 'МБ', 'з них індекси'], st.tables.map((t: any) => [t.table, t.partitions, int(t.rows), fmt(t.total_mb), fmt(t.index_mb)])),
225 '',
226 `Записів запасу ${int(st.items.records)} на ${int(st.items.positions)} позицій (${fmt(st.items.records / Math.max(1, st.items.positions), 2)} на позицію), ` +
227 `контейнерів ${int(st.items.containers)}, постійного розсипу ${int(st.items.loose)} (з нулем ${int(st.items.loose_zero)}).`,
228 '',
229 '## Найдорожчі оператори (pg_stat_statements)',
230 '',
231 table(['виклики', 'усього, мс', 'середнє, мс', '% часу', 'оператор'], st.statements.map((s: any) => [int(s.calls), int(s.total_ms), fmt(s.mean_ms, 3), fmt(s.pct), `\`${s.query.replace(/\|/g, '\\|')}\``])),
232 '',
233];
234mkdirSync(v.out!, { recursive: true });
235writeFileSync(join(v.out!, 'report.md'), report.join('\n'));
236writeFileSync(join(v.out!, 'result.json'), JSON.stringify({ config: { ...v, cfg }, totals, latency: lat.summary(), trace: traceLat.summary(), invariants: inv, stats: st }, null, 2));
237console.log(`\nзвіт: ${join(v.out!, 'report.md')}`);
238console.log(latencyTable(lat));
239console.log(latencyTable(traceLat));
240console.log(`інваріанти: ${inv.ok ? 'OK' : JSON.stringify(inv.violations)}`);
241api.close();
242