'use strict'; // HTTP 驱动与记录器:每次请求前把子进程时钟设为“当天起点 + 步数秒”,保证时间戳只取决于步骤顺序。 const { unzip } = require('./zip'); const SHANGHAI_OFFSET = 8 * 3600 * 1000; class Session { constructor({ base, server, startDate, startHour = 10 }) { this.base = base; this.server = server; this.cookies = {}; this.users = {}; this.entries = []; this.seq = 0; this.keySeq = 0; this.problems = []; this.secrets = []; this.dayStart = null; this.stepInDay = 0; this.startHour = startHour; this.date = null; if (startDate) this.pendingDay = startDate; } // 把业务“今天”切换到上海时区某日的 startHour 点,之后每次请求前进 1 秒。 async day(date, hour = this.startHour) { this.date = date; this.dayStart = Date.parse(date + 'T00:00:00Z') - SHANGHAI_OFFSET + hour * 3600 * 1000; this.stepInDay = 0; await this.server.setTime(this.dayStart); this.note('clock', { date, hour }); } note(kind, data) { this.entries.push({ seq: ++this.seq, note: kind, ...data }); } key(label = 'op') { this.keySeq++; return ( 'golden-' + String(this.keySeq).padStart(5, '0') + '-' + String(label) .replace(/[^A-Za-z0-9_-]/g, '') .slice(0, 40) ).padEnd(16, '0'); } async tickClock() { this.stepInDay++; await this.server.setTime(this.dayStart + this.stepInDay * 1000); } // 通用请求。opts: {body, key, headers, noOrigin, noXRW, origin, contentType, label, expect, record:'full'|'status'} async request(actor, method, path, opts = {}) { await this.tickClock(); const isPost = method === 'POST'; const headers = {}; const cookie = actor && this.cookies[actor]; if (cookie) headers.Cookie = cookie; let key = null; if (isPost) { if (!opts.noOrigin) headers.Origin = opts.origin || this.base; if (!opts.noXRW) headers['X-Requested-With'] = 'maimai-ledger'; headers['Content-Type'] = opts.contentType || 'application/json'; key = opts.key === undefined ? this.key(opts.label || path.split('/').filter(Boolean).slice(-1)[0]) : opts.key; if (key !== null) headers['Idempotency-Key'] = key; } Object.assign(headers, opts.headers || {}); const response = await fetch(this.base + path, { method, headers, ...(isPost ? { body: typeof opts.body === 'string' ? opts.body : JSON.stringify(opts.body ?? {}) } : {}), }); const type = response.headers.get('content-type') || ''; const buffer = Buffer.from(await response.arrayBuffer()); let body; if (opts.record === 'status') body = { omitted: true, bytes: buffer.length > 0 }; else if (type.includes('application/json')) { try { body = JSON.parse(buffer.toString('utf8')); } catch { body = { invalidJson: buffer.toString('utf8') }; } } else if (type.includes('spreadsheetml') || type.includes('zip')) { body = { zip: unzip(buffer).map(f => ({ name: f.name, text: f.data.toString('utf8') })) }; } else if (type.startsWith('text/')) body = { text: buffer.toString('utf8') }; else body = { binaryBytes: buffer.length }; const setCookie = response.headers.get('set-cookie'); if (setCookie && actor) { const token = setCookie.split(';')[0]; if (/mm_session=[0-9a-f]+/.test(token)) { this.cookies[actor] = token; this.secrets.push(token.slice(11)); } else if (/mm_session=;/.test(setCookie + ';')) delete this.cookies[actor]; } const entry = { seq: ++this.seq, label: opts.label || null, date: this.date, actor: actor || null, method, path, key, request: isPost ? { headers: { origin: headers.Origin ?? null, xrw: headers['X-Requested-With'] ?? null, contentType: headers['Content-Type'], }, body: opts.body ?? {}, } : undefined, status: response.status, contentType: type, disposition: response.headers.get('content-disposition'), setCookie: setCookie ? setCookie.replace(/mm_session=[0-9a-f]+/, 'mm_session=') : null, body, }; this.entries.push(entry); if (process.env.GOLDEN_PROBE && isPost && this.cookies.owner && !this.probeFailed) { // 调试用:每次写入后以老板身份读取指定地址,报告第一次失败的步骤(不计入记录)。 const probe = await fetch(this.base + process.env.GOLDEN_PROBE, { headers: { Cookie: this.cookies.owner } }); if (probe.status !== 200) { this.probeFailed = true; console.error('探测失败于 #' + entry.seq, actor, method, path, opts.label, await probe.text()); } } const expect = opts.expect ?? 200; if (expect !== 'any' && !(Array.isArray(expect) ? expect : [expect]).includes(response.status)) this.problems.push( `#${entry.seq} ${actor} ${method} ${path} 期望 ${expect} 实际 ${response.status} ${JSON.stringify(body).slice(0, 300)}`, ); return { status: response.status, body, json: type.includes('json') ? body : null, headers: response.headers }; } get(actor, path, opts) { return this.request(actor, 'GET', path, opts).then(r => r.json ?? r.body); } getRaw(actor, path, opts) { return this.request(actor, 'GET', path, opts); } post(actor, path, body, opts = {}) { return this.request(actor, 'POST', path, { ...opts, body }).then(r => r.json ?? r.body); } postRaw(actor, path, body, opts = {}) { return this.request(actor, 'POST', path, { ...opts, body }); } } module.exports = { Session };