|
| 1 | +// Restart the gateway process on the same database. The HTTP client and its probe clock stay outside it. |
| 2 | +import assert from 'node:assert/strict'; |
| 3 | +import { fork } from 'node:child_process'; |
| 4 | +import { once } from 'node:events'; |
| 5 | +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; |
| 6 | +import os from 'node:os'; |
| 7 | +import path from 'node:path'; |
| 8 | +import { DatabaseSync } from 'node:sqlite'; |
| 9 | +import { pathToFileURL } from 'node:url'; |
| 10 | +import { setTimeout as delay } from 'node:timers/promises'; |
| 11 | +import { parseArgs } from 'node:util'; |
| 12 | + |
| 13 | +const { values } = parseArgs({ |
| 14 | + options: { |
| 15 | + accounts: { type: 'string', default: '8' }, |
| 16 | + rows: { type: 'string', default: '64000' }, |
| 17 | + restarts: { type: 'string', default: '8' }, |
| 18 | + uncapped: { type: 'boolean' }, |
| 19 | + compare: { type: 'string' }, |
| 20 | + out: { type: 'string' }, |
| 21 | + root: { type: 'string' }, |
| 22 | + round: { type: 'string' }, |
| 23 | + }, |
| 24 | +}); |
| 25 | +const accounts = Number(values.accounts), |
| 26 | + rows = Number(values.rows), |
| 27 | + restarts = Number(values.restarts); |
| 28 | +assert.ok(Number.isInteger(accounts) && accounts >= 2 && accounts <= 32); |
| 29 | +assert.ok(Number.isInteger(rows) && rows >= 0 && rows * accounts <= 4_194_304); |
| 30 | +assert.ok(Number.isInteger(restarts) && restarts >= 1 && restarts <= 64); |
| 31 | +const owner = (i: number) => 'cold-fixture-' + i; |
| 32 | +const token = (i: number) => 'test-cold-quota-local-fixture-only-' + i; |
| 33 | +const bytes = 77, |
| 34 | + content = 'x'.repeat(128), |
| 35 | + probes = 20, |
| 36 | + spacing = 2; |
| 37 | +async function seed(root: string) { |
| 38 | + const { Store } = await import('../src/store/store.js'); |
| 39 | + const s = new Store(root); |
| 40 | + try { |
| 41 | + const quiet = await s.addFile( |
| 42 | + owner(accounts), |
| 43 | + 'quiet', |
| 44 | + Buffer.from('quiet'), |
| 45 | + undefined, |
| 46 | + undefined, |
| 47 | + 'config:' + owner(accounts), |
| 48 | + ); |
| 49 | + s.db.exec('BEGIN IMMEDIATE'); |
| 50 | + const ins = s.prepare('INSERT INTO files(id,owner,subject,payload) VALUES(?,?,?,?)'); |
| 51 | + for (let j = 0; j < accounts; j++) { |
| 52 | + const o = owner(j); |
| 53 | + for (let i = 0; i < rows; i++) { |
| 54 | + const hex = (j * rows + i).toString(16), |
| 55 | + id = 'file_' + hex.padStart(32, '0'); |
| 56 | + ins.run( |
| 57 | + id, |
| 58 | + o, |
| 59 | + 'config:' + o, |
| 60 | + JSON.stringify({ |
| 61 | + id, |
| 62 | + owner: o, |
| 63 | + name: 'history', |
| 64 | + bytes, |
| 65 | + sha256: hex.padStart(64, '0'), |
| 66 | + createdAt: 1, |
| 67 | + }), |
| 68 | + ); |
| 69 | + } |
| 70 | + } |
| 71 | + s.db.exec('COMMIT'); |
| 72 | + return quiet.id; |
| 73 | + } finally { |
| 74 | + if (s.db.isTransaction) s.db.exec('ROLLBACK'); |
| 75 | + s.close(); |
| 76 | + } |
| 77 | +} |
| 78 | +async function gateway() { |
| 79 | + assert.ok(values.root); |
| 80 | + const round = Number(values.round); |
| 81 | + const { setup }: typeof import('../test/helpers.js') = values.compare |
| 82 | + ? await import(pathToFileURL(path.resolve(values.compare, 'test/helpers.js')).href) |
| 83 | + : await import('../test/helpers.js'); |
| 84 | + const keys = Array.from({ length: accounts + 1 }, (_, i) => { |
| 85 | + const tokenEnv = 'OAA_COLD_FIXTURE_' + i; |
| 86 | + process.env[tokenEnv] = token(i); |
| 87 | + return { name: owner(i), owner: owner(i), scopes: ['files'], tokenEnv, quota: { rpm: 100000 } }; |
| 88 | + }); |
| 89 | + const start = performance.now(); |
| 90 | + const s = await setup(undefined, { |
| 91 | + dataDir: values.root, |
| 92 | + keys, |
| 93 | + ...(!values.uncapped && { |
| 94 | + maxStoredBytesPerSubject: rows * bytes + (round + 1) * 2 * content.length, |
| 95 | + }), |
| 96 | + }); |
| 97 | + try { |
| 98 | + const disconnected = once(process, 'disconnect'); |
| 99 | + process.send!({ base: await s.listen(), ready: performance.now() - start }); |
| 100 | + await disconnected; |
| 101 | + } finally { |
| 102 | + await s.cleanup(); |
| 103 | + } |
| 104 | +} |
| 105 | +const stats = (times: number[]) => { |
| 106 | + const a = times.toSorted((x, y) => x - y), |
| 107 | + at = (p: number) => +a[Math.ceil(p * a.length) - 1]!.toFixed(2); |
| 108 | + return { count: a.length, p50: at(0.5), p95: at(0.95), p99: at(0.99), max: at(1) }; |
| 109 | +}; |
| 110 | +const sample = () => ({ |
| 111 | + uploads: [] as number[], |
| 112 | + quiet: [] as number[], |
| 113 | + lag: [] as number[], |
| 114 | + wave: [] as number[], |
| 115 | + quietGaps: [] as number[], |
| 116 | + lateProbes: 0, |
| 117 | +}); |
| 118 | +const measurements = () => ({ cold: sample(), warm: sample(), startup: [] as number[] }); |
| 119 | +async function measure() { |
| 120 | + const root = await mkdtemp(path.join(os.tmpdir(), 'oaa-cold-quota-')); |
| 121 | + try { |
| 122 | + const quietId = await seed(root), |
| 123 | + current = measurements(), |
| 124 | + prior = measurements(), |
| 125 | + ids = new Set<string>(); |
| 126 | + const processes = restarts * (values.compare ? 2 : 1); |
| 127 | + for (let round = 0; round < processes; round++) { |
| 128 | + // AB, BA: each version sees the first and second position equally often. |
| 129 | + const before = !!values.compare && (round % 4 === 0 || round % 4 === 3); |
| 130 | + const { cold, warm, startup } = before ? prior : current; |
| 131 | + const args = [ |
| 132 | + '--accounts', |
| 133 | + String(accounts), |
| 134 | + '--rows', |
| 135 | + String(rows), |
| 136 | + '--round', |
| 137 | + String(round), |
| 138 | + '--root', |
| 139 | + root, |
| 140 | + ]; |
| 141 | + if (values.uncapped) args.push('--uncapped'); |
| 142 | + if (before) args.push('--compare', values.compare!); |
| 143 | + const child = fork(import.meta.filename, args, { |
| 144 | + stdio: ['ignore', 'ignore', 'inherit', 'ipc'], |
| 145 | + }); |
| 146 | + const ended = once(child, 'exit'); |
| 147 | + try { |
| 148 | + const { base, ready } = await Promise.race([ |
| 149 | + once(child, 'message', { signal: AbortSignal.timeout(120000) }).then( |
| 150 | + ([m]) => m as { base: string; ready: number }, |
| 151 | + ), |
| 152 | + ended.then(() => { |
| 153 | + throw Error('Gateway exited before listening'); |
| 154 | + }), |
| 155 | + ]); |
| 156 | + startup.push(ready); |
| 157 | + const post = (i: number, payload = content) => |
| 158 | + fetch(base + '/v1/files', { |
| 159 | + method: 'POST', |
| 160 | + headers: { authorization: 'Bearer ' + token(i), 'content-type': 'application/json' }, |
| 161 | + body: JSON.stringify({ filename: 'burst', content: payload }), |
| 162 | + signal: AbortSignal.timeout(30000), |
| 163 | + }); |
| 164 | + const read = async () => { |
| 165 | + const r = await fetch(base + '/v1/files/' + quietId + '/content', { |
| 166 | + headers: { authorization: 'Bearer ' + token(accounts) }, |
| 167 | + signal: AbortSignal.timeout(30000), |
| 168 | + }); |
| 169 | + assert.equal(r.status, 200); |
| 170 | + assert.equal(await r.text(), 'quiet'); |
| 171 | + }; |
| 172 | + // Establish HTTP connections without checking any measured account's upload quota. |
| 173 | + await Promise.all(Array.from({ length: accounts + probes }, () => read())); |
| 174 | + for (const phase of [cold, warm]) { |
| 175 | + const start = performance.now(); |
| 176 | + let finished = Infinity; |
| 177 | + const arrivals: number[] = []; |
| 178 | + const probe = async () => { |
| 179 | + const at = performance.now(); |
| 180 | + await read(); |
| 181 | + const end = performance.now(); |
| 182 | + phase.quiet.push(end - at); |
| 183 | + arrivals.push(end); |
| 184 | + }; |
| 185 | + await Promise.all([ |
| 186 | + Promise.all( |
| 187 | + Array.from({ length: accounts }, async (_, i) => { |
| 188 | + const t = performance.now(), |
| 189 | + r = await post(i), |
| 190 | + j = await r.json(); |
| 191 | + assert.equal(r.status, 200, JSON.stringify(j)); |
| 192 | + assert.equal(j.bytes, content.length); |
| 193 | + assert.ok(typeof j.id === 'string' && !ids.has(j.id)); |
| 194 | + ids.add(j.id); |
| 195 | + phase.uploads.push(performance.now() - t); |
| 196 | + }), |
| 197 | + ).finally(() => { |
| 198 | + finished = performance.now(); |
| 199 | + phase.wave.push(finished - start); |
| 200 | + }), |
| 201 | + Promise.all( |
| 202 | + Array.from({ length: probes }, async (_, i) => { |
| 203 | + const target = start + (i + 1) * spacing; |
| 204 | + await delay(Math.max(0, target - performance.now())); |
| 205 | + const t = performance.now(); |
| 206 | + phase.lag.push(Math.max(0, t - target)); |
| 207 | + await probe(); |
| 208 | + }), |
| 209 | + ), |
| 210 | + (async () => { |
| 211 | + await delay(probes * spacing + spacing); |
| 212 | + // Cover slow disks and helper fallback after the initial open-loop burst, |
| 213 | + // without adding unbounded load when the gateway is unable to answer. |
| 214 | + while (finished === Infinity) { |
| 215 | + phase.lateProbes++; |
| 216 | + await probe(); |
| 217 | + await delay(5); |
| 218 | + } |
| 219 | + })(), |
| 220 | + ]); |
| 221 | + const points = [ |
| 222 | + start, |
| 223 | + ...arrivals.filter((n) => n < finished).sort((a, b) => a - b), |
| 224 | + finished, |
| 225 | + ]; |
| 226 | + phase.quietGaps.push(Math.max(...points.slice(1).map((n, i) => n - points[i]!))); |
| 227 | + } |
| 228 | + if (!values.uncapped) { |
| 229 | + for (let i = 0; i < accounts; i++) { |
| 230 | + const r = await post(i, 'x'); |
| 231 | + assert.equal(r.status, 413); |
| 232 | + assert.equal((await r.json()).error.code, 'storage_quota_exceeded'); |
| 233 | + } |
| 234 | + } |
| 235 | + } finally { |
| 236 | + if (child.connected) child.disconnect(); |
| 237 | + assert.equal((await ended)[0], 0); |
| 238 | + } |
| 239 | + } |
| 240 | + const db = new DatabaseSync(path.join(root, 'state.sqlite'), { readOnly: true }); |
| 241 | + try { |
| 242 | + const all = db.prepare( |
| 243 | + "SELECT count(*) AS n,sum(json_extract(payload,'$.bytes')) AS bytes FROM files WHERE owner=? AND subject=?", |
| 244 | + ); |
| 245 | + for (let i = 0; i < accounts; i++) { |
| 246 | + const r = all.get(owner(i), 'config:' + owner(i))!; |
| 247 | + assert.equal(r.n, rows + processes * 2); |
| 248 | + assert.equal(r.bytes, rows * bytes + processes * 2 * content.length); |
| 249 | + } |
| 250 | + assert.equal(db.prepare('SELECT count(*) AS n FROM oaa_inline_inputs').get()!.n, 0); |
| 251 | + } finally { |
| 252 | + db.close(); |
| 253 | + } |
| 254 | + const describe = (p: ReturnType<typeof sample>) => ({ |
| 255 | + upload_ms: stats(p.uploads), |
| 256 | + other_owner_read_ms: stats(p.quiet), |
| 257 | + wave_ms: stats(p.wave), |
| 258 | + client_timer_lag_ms: stats(p.lag), |
| 259 | + max_quiet_response_gap_per_wave_ms: stats(p.quietGaps), |
| 260 | + late_probes: p.lateProbes, |
| 261 | + wave_samples_ms: p.wave.map((n) => +n.toFixed(2)), |
| 262 | + }); |
| 263 | + const summarize = (x: ReturnType<typeof measurements>) => ({ |
| 264 | + ready_ms: stats(x.startup), |
| 265 | + cold: describe(x.cold), |
| 266 | + warm: describe(x.warm), |
| 267 | + }); |
| 268 | + const report = { |
| 269 | + fixture: |
| 270 | + 'Fresh gateway processes, same disk database; synthetic file history, actual HTTP uploads and reads. Host OS disk cache is not flushed. No model calls.', |
| 271 | + node: process.version, |
| 272 | + accounts, |
| 273 | + rows_per_account: rows, |
| 274 | + restarts, |
| 275 | + quota: !values.uncapped, |
| 276 | + per_wave_probes: probes, |
| 277 | + probe_interval_ms: spacing, |
| 278 | + verified_uploads: ids.size, |
| 279 | + verified_one_byte_rejections: values.uncapped ? 0 : accounts * processes, |
| 280 | + ...(values.compare |
| 281 | + ? { order: 'AB/BA, shared fixture', before: summarize(prior), after: summarize(current) } |
| 282 | + : summarize(current)), |
| 283 | + }; |
| 284 | + const data = JSON.stringify(report, null, 2) + '\n'; |
| 285 | + if (values.out) await writeFile(values.out, data, { flag: 'wx' }); |
| 286 | + process.stdout.write(data); |
| 287 | + } finally { |
| 288 | + await rm(root, { recursive: true, force: true }); |
| 289 | + } |
| 290 | +} |
| 291 | +if (process.send) await gateway(); |
| 292 | +else await measure(); |
0 commit comments