games_app/backend/scripts/smoke-docker-realtime.js
2026-07-29 15:35:11 +02:00

249 lines
7.0 KiB
JavaScript

/**
* Docker smoke: engine liveness + /state ETag/304 + WebSocket subscribe.
* Usage (from host):
* node backend/scripts/smoke-docker-realtime.js [baseUrl] [token]
*/
const http = require('http');
const https = require('https');
const { URL } = require('url');
const baseUrl = (process.argv[2] || 'http://127.0.0.1:9080').replace(/\/$/, '');
const token = process.argv[3] || process.env.SMOKE_TOKEN || '';
const intervalMinutes = Number(process.env.SMOKE_INTERVAL || 1);
if (!token) {
console.error('Missing token. Pass as argv[3] or SMOKE_TOKEN');
process.exit(1);
}
function request(method, path, { headers = {}, body, timeoutMs = 15000 } = {}) {
return new Promise((resolve, reject) => {
const url = new URL(path, baseUrl);
const lib = url.protocol === 'https:' ? https : http;
const req = lib.request(
url,
{
method,
headers,
timeout: timeoutMs,
},
(res) => {
const chunks = [];
res.on('data', (c) => chunks.push(c));
res.on('end', () => {
const raw = Buffer.concat(chunks).toString('utf8');
let json = null;
try {
json = raw ? JSON.parse(raw) : null;
} catch {
/* ignore */
}
resolve({
status: res.statusCode || 0,
headers: res.headers,
raw,
json,
});
});
}
);
req.on('timeout', () => {
req.destroy(new Error(`timeout ${method} ${path}`));
});
req.on('error', reject);
if (body) req.write(body);
req.end();
});
}
function authHeaders(extra = {}) {
return {
Authorization: `Bearer ${token}`,
Accept: 'application/json',
...extra,
};
}
async function smokeState() {
const path = `/api/v1/games/candle-predict/state?intervalMinutes=${intervalMinutes}`;
const first = await request('GET', path, { headers: authHeaders() });
if (first.status !== 200) {
throw new Error(`/state first status=${first.status} body=${first.raw.slice(0, 300)}`);
}
const etag = String(first.headers.etag || '').trim();
const versions = String(first.headers['x-prediqo-state-versions'] || '').trim();
const round = first.json?.round;
console.log('[state] 200 ok');
console.log('[state] etag=', etag || '(none)');
console.log('[state] versions=', versions || '(none)');
console.log(
'[state] round=',
JSON.stringify({
id: round?.id,
status: round?.status,
candleOpenMs: round?.candleOpenMs,
secondsToClose: round?.secondsToClose,
})
);
if (!etag) {
throw new Error('Missing ETag on /state response');
}
const second = await request('GET', path, {
headers: authHeaders({ 'If-None-Match': etag }),
});
console.log('[state] second status=', second.status, 'etag=', String(second.headers.etag || ''));
if (second.status !== 304) {
throw new Error(`Expected 304 on matching If-None-Match, got ${second.status}`);
}
console.log('[state] 304 short-circuit OK');
const isVersionEtag = /^"cp-v-\d+-\d+-\d+-\d+-\d+-[01]"$/.test(etag);
const isFingerprint = etag.startsWith('"cp-state-');
console.log(
'[state] etagKind=',
isVersionEtag ? 'version' : isFingerprint ? 'fingerprint' : 'unknown'
);
return { etag, versions, round, etagKind: isVersionEtag ? 'version' : isFingerprint ? 'fingerprint' : 'unknown' };
}
async function smokeCandles(round) {
const path = `/api/v1/games/candle-predict/candles?intervalMinutes=${intervalMinutes}&limit=5`;
const res = await request('GET', path, { headers: authHeaders() });
if (res.status !== 200) {
throw new Error(`/candles status=${res.status}`);
}
const items = res.json?.items || [];
console.log('[candles] count=', items.length);
if (!items.length) {
console.warn('[candles] WARN empty — engine may still be warming up');
} else {
const last = items[items.length - 1];
console.log('[candles] last=', JSON.stringify({
time: last.time,
open: last.open,
close: last.close,
candleOpenMs: last.candleOpenMs,
}));
}
if (round?.status) {
console.log('[engine] round status observed via /state:', round.status);
}
return items.length;
}
async function smokeWs() {
let WebSocket;
try {
WebSocket = require('ws');
} catch {
// fallback: use API container's ws module via docker? Prefer local.
console.warn('[ws] local ws module missing, trying docker exec check only');
return { skipped: true };
}
const wsUrl = baseUrl.replace(/^http/, 'ws') + '/ws/v1/games/candle-predict';
console.log('[ws] connecting', wsUrl);
return new Promise((resolve, reject) => {
const ws = new WebSocket(wsUrl, {
headers: { Authorization: `Bearer ${token}` },
});
const got = { connected: false, subscribed: false, roundUpdated: false };
const timer = setTimeout(() => {
try {
ws.close();
} catch {
/* ignore */
}
reject(new Error(`WS timeout got=${JSON.stringify(got)}`));
}, 20000);
ws.on('open', () => {
console.log('[ws] open');
ws.send(JSON.stringify({ type: 'subscribe', intervalMinutes }));
});
ws.on('message', (data) => {
let msg;
try {
msg = JSON.parse(String(data));
} catch {
return;
}
console.log('[ws] message type=', msg.type);
if (msg.type === 'connected') got.connected = true;
if (msg.type === 'subscribed') {
got.subscribed = true;
console.log(
'[ws] snapshot round=',
JSON.stringify({
status: msg.snapshot?.round?.status,
id: msg.snapshot?.round?.id,
})
);
}
if (msg.type === 'round.updated' || msg.type === 'round.settled') {
got.roundUpdated = true;
console.log('[ws] realtime round event OK', msg.type);
}
// Success criteria: connected + subscribed. round.updated is bonus within timeout.
if (got.subscribed) {
clearTimeout(timer);
try {
ws.close();
} catch {
/* ignore */
}
resolve(got);
}
});
ws.on('error', (err) => {
clearTimeout(timer);
reject(err);
});
});
}
async function main() {
console.log('=== SMOKE Docker realtime ===');
console.log('baseUrl=', baseUrl);
console.log('intervalMinutes=', intervalMinutes);
const health = await request('GET', '/health');
console.log('[health]', health.status, health.json?.status, 'network=', health.json?.network);
const state = await smokeState();
const candleCount = await smokeCandles(state.round);
const ws = await smokeWs();
console.log('=== SUMMARY ===');
console.log(
JSON.stringify(
{
health: health.status === 200,
state200: true,
state304: true,
etagKind: state.etagKind,
versionsHeader: Boolean(state.versions),
candles: candleCount,
ws,
},
null,
2
)
);
if (!ws.skipped && !ws.subscribed) {
process.exitCode = 1;
}
}
main().catch((e) => {
console.error('SMOKE FAILED:', e.message || e);
process.exit(1);
});