ISS live telemetry, STATION and LIVE sections, Tiangong model, drawn through the renderer's draw port

Builds on the ISS 3D model (PR #1690) and brings it onto main's renderer
seam: the station models are items of a `models` draw set, posed by
heading, pitch and roll from the station's flight axes
(`headingPitchRollOfAxes`), with the camera, canvas and clicks read from
the renderer's ports; no satellites file reaches Cesium. The joint drivers
write column-major matrices into node poses the model part keeps, for a
renderer that can pose nodes; until the draw contract has that member the
models draw rigid.

- ISS joints take their angles from NASA's ISSLive telemetry, relayed by
  the server behind ISS_TELEMETRY_ENABLED.
- STATION and LIVE sections of Context replace the floating command panel
  and player; both collapse like the Radio section.
- Cockpit rides the ISS from mounts on its model; the LIVE page in the
  Cockpit briefing.
- Tiangong as a second station model, with computed joints.
- Installations: a label-box click selects the site.
This commit is contained in:
Denis Groshev committed 2026-11-16 18:39:39 +01:00
1 parent fd3ca679ec
commit 9cc077964f
103 files changed
+12033 -1775

No files matched your search

+2
View File
@@ -1,6 +1,7 @@
import path from 'node:path';
import { openSkyProxy } from './aircraft/opensky.js';
import { celestrakProxy, rocketLaunchesProxy } from './space.js';
import { issTelemetryProxy } from './space/issTelemetry.js';
import { tomtomProxy } from './traffic.js';
import { firmsProxy } from './firms.js';
import { terrainHeightsProxy } from './terrain.js';
@@ -58,6 +59,7 @@ function localProviderPlugins({
return [
openSkyProxy(),
celestrakProxy(),
issTelemetryProxy(),
tomtomProxy(),
firmsProxy(),
rocketLaunchesProxy(),
+430
View File
@@ -0,0 +1,430 @@
import { createRequire } from 'node:module';
import { clientKey, makeRateLimiter } from '../common/rate-limit.js';
import { admitSameSiteKeyless } from '../common/same-site.js';
/**
* NASA's public ISS telemetry (the ISSLive feed), relayed as a small snapshot.
*
* The feed is a push stream served by Lightstreamer for NASA. This module
* holds ONE connection to it for the whole server and gives browsers the
* latest value of each joint item at `/api/iss-telemetry`, so many viewers
* cost the public server one subscriber.
*
* Off by default: the feed publishes no terms of use, so nothing here
* contacts it unless the operator sets `ISS_TELEMETRY_ENABLED=1`. Without the
* flag the route answers `{ configured: false }` and the browser stops asking.
* With it, the connection opens on the first request and closes again once
* nobody has asked for a while.
*/
/** The route browsers poll. */
export const ISS_TELEMETRY_ROUTE = '/api/iss-telemetry';
const FEED_URL = 'wss://push.lightstreamer.com/lightstreamer';
/** Lightstreamer's text protocol (TLCP), spoken directly over the socket. */
const FEED_PROTOCOL = 'TLCP-2.4.0.lightstreamer.com';
const FEED_ADAPTER_SET = 'ISSLIVE';
/** The client id Lightstreamer assigns to custom TLCP clients. */
const FEED_CLIENT_ID = 'mgQkwtwdysogQz2BJ4Ji%20kOj2Bg';
/** The station clock; it ticks only while the ground has signal. */
const SIGNAL_ITEM = 'TIME_000001';
/** `Status.Class` of an item received with signal. */
const SIGNAL_CLASS = '24';
/**
* The items relayed: the joints the ISS model can turn, plus the station
* clock that says whether the feed has signal.
*/
export const ISS_TELEMETRY_ITEMS = Object.freeze([
// Alpha joints (SARJ): port, starboard.
'S0000004',
'S0000003',
// Array beta joints (BGA): 2A, 4A, 2B, 4B, 1A, 3A, 1B, 3B.
'P4000007',
'P4000008',
'P6000008',
'P6000007',
'S4000007',
'S4000008',
'S6000008',
'S6000007',
// Radiator joints (TRRJ): port, starboard.
'S0000002',
'S0000001',
// Ku-band dish: elevation, cross-elevation, transmitting.
'Z1000014',
'Z1000015',
'Z1000013',
// Canadarm2: shoulder roll, yaw, pitch; elbow; wrist pitch, yaw, roll.
'CSASSRMS004',
'CSASSRMS005',
'CSASSRMS006',
'CSASSRMS007',
'CSASSRMS008',
'CSASSRMS009',
'CSASSRMS010',
SIGNAL_ITEM,
]);
const FEED_FIELDS = Object.freeze(['TimeStamp', 'Value', 'Status.Class']);
/** No station clock tick for this long means the signal is gone. */
const SIGNAL_STALE_MS = 20_000;
/** No frame at all for this long (the server probes every 5 s) recycles the socket. */
const SILENCE_MS = 30_000;
/** Nobody asking for this long closes the connection. */
const IDLE_MS = 120_000;
/** Waits between connection attempts, the last one repeating. */
const RETRY_LADDER_MS = Object.freeze([5_000, 15_000, 60_000, 300_000]);
/** A frame larger than this is not telemetry; it is dropped unread. */
const MAX_FRAME_BYTES = 64 * 1024;
const TICK_MS = 5_000;
/**
* Whether the operator switched the relay on. Only "1" does.
* @param {Record<string, string|undefined>} [env]
* @returns {boolean}
*/
export function issTelemetryEnabled(env = process.env) {
return String(env.ISS_TELEMETRY_ENABLED || '').trim() === '1';
}
/**
* The feed's time stamp as epoch milliseconds. The feed counts hours from the
* start of the day before January 1st (day of year × 24 + hours of the day),
* with no year; the year is taken from `nowMs`, stepping back one when that
* would put the stamp in the future (a value last sent in December, read in
* January).
* @param {number} hours
* @param {number} nowMs
* @returns {number|null}
*/
export function issTelemetryTimeMs(hours, nowMs) {
if (!Number.isFinite(hours) || hours < 0) return null;
const year = new Date(nowMs).getUTCFullYear();
const at = Date.UTC(year, 0, 0) + hours * 3_600_000;
// A day of slack for clock differences.
return at > nowMs + 86_400_000
? Date.UTC(year - 1, 0, 0) + hours * 3_600_000
: at;
}
/**
* Decode one TLCP update line, `U,<subscription>,<item>,<fields>`, against
* the item's previous field values. Fields are `|`-separated and
* percent-encoded: an empty field is unchanged, `#` is null, `$` is the empty
* string and `^n` stands for n unchanged fields.
* @param {string} line
* @param {(item: number) => Array<string|null>|undefined} previousOf
* @param {number} fieldCount
* @returns {{item: number, fields: Array<string|null>}|null} Null for a line
* that is not a well-formed update.
*/
export function parseTlcpUpdate(line, previousOf, fieldCount) {
if (!line.startsWith('U,')) return null;
const second = line.indexOf(',', 2);
const third = second < 0 ? -1 : line.indexOf(',', second + 1);
if (third < 0) return null;
const item = Number(line.slice(second + 1, third));
if (!Number.isInteger(item) || item < 1) return null;
const previous = previousOf(item) ?? [];
const fields = [];
for (const raw of line.slice(third + 1).split('|')) {
if (fields.length >= fieldCount) return null;
if (raw === '') fields.push(previous[fields.length] ?? null);
else if (raw === '#') fields.push(null);
else if (raw === '$') fields.push('');
else if (raw[0] === '^') {
const run = Number(raw.slice(1));
if (!Number.isInteger(run) || run < 1 || fields.length + run > fieldCount)
return null;
for (let i = 0; i < run; i++)
fields.push(previous[fields.length] ?? null);
} else {
try {
fields.push(decodeURIComponent(raw));
} catch {
return null;
}
}
}
return fields.length === fieldCount ? { item, fields } : null;
}
/**
* The relay: the connection's lifecycle and the snapshot it serves. It owns
* no timers; the caller drives `tick()` every few seconds.
* @param {{createSocket: () => object|null, now?: () => number}} options
* `createSocket` opens the feed and returns a `ws`-style socket (`on`,
* `send`, `terminate`), or null when no socket can be made.
*/
export function createIssTelemetryRelay({ createSocket, now = Date.now }) {
/** @type {Map<string, {value: number, at: number|null}>} */
const values = new Map();
/** Per item index, the raw field values the next update is decoded against. */
const fields = new Map();
let socket = null;
/** Bumped on every connect and dispose, so a dead socket's events are ignored. */
let generation = 0;
let lastDemandAt = null;
let lastFrameAt = null;
let signalAt = null;
let signalClass = null;
let failures = 0;
let retryAt = 0;
let unavailable = false;
function drop() {
generation += 1;
const old = socket;
socket = null;
fields.clear();
try {
old?.terminate?.();
} catch {
// A socket that will not terminate is abandoned; the generation guard
// keeps its events out.
}
}
function fail() {
drop();
const wait =
RETRY_LADDER_MS[Math.min(failures, RETRY_LADDER_MS.length - 1)];
failures += 1;
retryAt = now() + wait;
}
function onLine(line) {
if (line.startsWith('CONOK,')) {
socket?.send(
`control\r\nLS_reqId=1&LS_op=add&LS_subId=1&LS_mode=MERGE&LS_group=${encodeURIComponent(
ISS_TELEMETRY_ITEMS.join(' '),
)}&LS_schema=${encodeURIComponent(FEED_FIELDS.join(' '))}&LS_snapshot=true`,
);
return;
}
// The session was refused, ended, or asks to be re-bound: start over.
if (/^(CONERR|END|LOOP|REQERR),/.test(line)) {
fail();
return;
}
const update = parseTlcpUpdate(
line,
(item) => fields.get(item),
FEED_FIELDS.length,
);
if (!update) return;
const name = ISS_TELEMETRY_ITEMS[update.item - 1];
if (!name) return;
fields.set(update.item, update.fields);
failures = 0;
const [stamp, raw, statusClass] = update.fields;
const at = now();
if (name === SIGNAL_ITEM) {
signalAt = at;
signalClass = statusClass;
return;
}
const value = raw === null || raw === '' ? Number.NaN : Number(raw);
if (!Number.isFinite(value)) return;
values.set(name, { value, at: issTelemetryTimeMs(Number(stamp), at) });
}
function connect() {
let opened;
try {
opened = createSocket();
} catch {
opened = null;
}
if (!opened) {
unavailable = true;
return;
}
unavailable = false;
generation += 1;
const mine = generation;
socket = opened;
lastFrameAt = now();
opened.on('open', () => {
if (mine !== generation) return;
opened.send(
`create_session\r\nLS_adapter_set=${FEED_ADAPTER_SET}&LS_cid=${FEED_CLIENT_ID}&LS_send_sync=false&LS_cause=api`,
);
});
opened.on('message', (data) => {
if (mine !== generation) return;
// Nothing the feed sends may take the server down.
try {
if (data?.length > MAX_FRAME_BYTES) return;
lastFrameAt = now();
for (const line of String(data).split('\r\n')) {
if (mine !== generation) return;
if (line) onLine(line);
}
} catch {
fail();
}
});
const lost = () => {
if (mine === generation) fail();
};
opened.on('error', lost);
opened.on('close', lost);
}
/** Whether anyone asked recently enough to keep the connection. */
function wanted() {
return lastDemandAt !== null && now() - lastDemandAt < IDLE_MS;
}
/**
* Housekeeping, every few seconds: close when idle, recycle a silent
* socket, retry a failed one.
* @returns {boolean} False once there is nothing left to watch.
*/
function tick() {
if (!wanted()) {
dispose();
return false;
}
if (socket && now() - lastFrameAt > SILENCE_MS) fail();
if (!socket && !unavailable && now() >= retryAt) connect();
return true;
}
/** Record that a browser asked, opening the connection if it is closed. */
function demand() {
lastDemandAt = now();
if (!socket && !unavailable && now() >= retryAt) connect();
}
function status() {
if (unavailable) return 'unavailable';
if (!socket) return 'reconnecting';
if (signalAt === null) return 'connecting';
return signalClass === SIGNAL_CLASS && now() - signalAt < SIGNAL_STALE_MS
? 'live'
: 'no-signal';
}
/** The body served to browsers: each item's `[value, epoch ms it was true at]`. */
function snapshot() {
const items = {};
for (const [name, { value, at }] of values) items[name] = [value, at];
return { configured: true, status: status(), generatedAt: now(), items };
}
/** Close the connection and forget what it said. */
function dispose() {
drop();
values.clear();
lastDemandAt = null;
signalAt = null;
signalClass = null;
failures = 0;
retryAt = 0;
unavailable = false;
}
return { demand, tick, snapshot, dispose };
}
let webSocketImpl;
/**
* Load `ws` once, lazily: the vessel feed's socket library, so a missing
* optional dependency turns this relay off instead of breaking the server.
* @returns {Function|null}
*/
function loadWebSocket() {
if (webSocketImpl !== undefined) return webSocketImpl;
try {
webSocketImpl = createRequire(import.meta.url)('ws');
} catch {
webSocketImpl = null;
console.warn(
'[ISS telemetry] `ws` is unavailable; the telemetry relay is off.',
);
}
return webSocketImpl;
}
function json(res, status, body) {
res.writeHead(status, {
'Content-Type': 'application/json',
'Cache-Control': 'no-store',
});
res.end(JSON.stringify(body));
}
/**
* The Vite plugin that mounts the relay's route.
* @param {{env?: Record<string, string|undefined>, createSocket?: () => object|null,
* now?: () => number}} [options] Test seams; the defaults read the process
* environment at request time and open the real feed.
*/
export function issTelemetryProxy({
env,
createSocket = () => {
const WebSocket = loadWebSocket();
return WebSocket ? new WebSocket(FEED_URL, FEED_PROTOCOL) : null;
},
now = Date.now,
} = {}) {
const relay = createIssTelemetryRelay({ createSocket, now });
// A browser polls every few seconds; this leaves room for several tabs.
const allow = makeRateLimiter({ windowMs: 60_000, max: 60, globalMax: 1200 });
let timer = null;
function stop() {
if (timer) clearInterval(timer);
timer = null;
relay.dispose();
}
function watch() {
if (timer) return;
timer = setInterval(() => {
if (relay.tick()) return;
clearInterval(timer);
timer = null;
}, TICK_MS);
timer.unref?.();
}
function handle(req, res) {
if (admitSameSiteKeyless(req, res)) return;
if (req.method !== 'GET' && req.method !== 'HEAD') {
json(res, 405, { error: 'Method Not Allowed' });
return;
}
// Read per request: the environment is loaded after this module is.
if (!issTelemetryEnabled(env ?? process.env)) {
json(res, 200, { configured: false });
return;
}
if (!allow(clientKey(req))) {
json(res, 429, { error: 'Too Many Requests' });
return;
}
relay.demand();
watch();
json(res, 200, relay.snapshot());
}
function install(server) {
server.middlewares.use(ISS_TELEMETRY_ROUTE, handle);
// Vite restarts the server in-process while this module's state lives on.
server.httpServer?.on('close', stop);
}
return {
name: 'iss-telemetry-proxy',
configureServer: install,
configurePreviewServer: install,
// Middleware mode has no httpServer to hang 'close' on.
closeBundle: stop,
};
}
@@ -0,0 +1,350 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
ISS_TELEMETRY_ITEMS,
ISS_TELEMETRY_ROUTE,
createIssTelemetryRelay,
issTelemetryEnabled,
issTelemetryProxy,
issTelemetryTimeMs,
parseTlcpUpdate,
} from './issTelemetry.js';
/** A `ws`-shaped socket the test drives by hand. */
function fakeSocket() {
const handlers = {};
return {
sent: [],
terminated: false,
on(event, handler) {
handlers[event] = handler;
},
send(text) {
this.sent.push(text);
},
terminate() {
this.terminated = true;
},
emit(event, payload) {
handlers[event]?.(payload);
},
};
}
const index = (name) => ISS_TELEMETRY_ITEMS.indexOf(name) + 1;
/** A relay on a hand-moved clock, with every socket it opened. */
function relayAt(startMs) {
const clock = { ms: startMs };
const sockets = [];
const relay = createIssTelemetryRelay({
createSocket: () => {
const socket = fakeSocket();
sockets.push(socket);
return socket;
},
now: () => clock.ms,
});
return { relay, sockets, clock };
}
const NOV_13 = Date.UTC(2026, 10, 13, 11, 0, 0);
/** The feed's stamp for a moment: day of year × 24 + hours of that day. */
const stampOf = (ms) =>
(ms - Date.UTC(new Date(ms).getUTCFullYear(), 0, 0)) / 3_600_000;
test('only ISS_TELEMETRY_ENABLED=1 switches the relay on', () => {
assert.equal(issTelemetryEnabled({}), false);
assert.equal(issTelemetryEnabled({ ISS_TELEMETRY_ENABLED: '' }), false);
assert.equal(issTelemetryEnabled({ ISS_TELEMETRY_ENABLED: '0' }), false);
assert.equal(issTelemetryEnabled({ ISS_TELEMETRY_ENABLED: 'true' }), false);
assert.equal(issTelemetryEnabled({ ISS_TELEMETRY_ENABLED: ' 1 ' }), true);
});
test("the feed's stamp is hours from the day before January 1st", () => {
// 13 November 2026 is day 317: 317 × 24 + 11 hours.
assert.equal(issTelemetryTimeMs(317 * 24 + 11, NOV_13), NOV_13);
assert.equal(
issTelemetryTimeMs(stampOf(NOV_13 - 5000), NOV_13),
NOV_13 - 5000,
);
// A value last sent on 30 December, read on 2 January, belongs to last year.
const january = Date.UTC(2027, 0, 2, 0, 0, 0);
assert.equal(
issTelemetryTimeMs(364 * 24, january),
Date.UTC(2026, 11, 30, 0, 0, 0),
);
assert.equal(issTelemetryTimeMs(Number.NaN, NOV_13), null);
assert.equal(issTelemetryTimeMs(-1, NOV_13), null);
});
test('an update line decodes against the previous field values', () => {
const previous = new Map([[3, ['7000.5', '10.25', '24']]]);
const of = (item) => previous.get(item);
assert.deepEqual(parseTlcpUpdate('U,1,3,7000.6|11.5|24', of, 3), {
item: 3,
fields: ['7000.6', '11.5', '24'],
});
// Empty = unchanged, ^n = n unchanged, # = null, $ = empty string.
assert.deepEqual(parseTlcpUpdate('U,1,3,7000.7||', of, 3).fields, [
'7000.7',
'10.25',
'24',
]);
assert.deepEqual(parseTlcpUpdate('U,1,3,7000.8|^2', of, 3).fields, [
'7000.8',
'10.25',
'24',
]);
assert.deepEqual(parseTlcpUpdate('U,1,3,#|$|24', of, 3).fields, [
null,
'',
'24',
]);
assert.deepEqual(parseTlcpUpdate('U,1,3,a%7Cb|1|24', of, 3).fields[0], 'a|b');
// Not updates, or malformed ones.
for (const line of [
'PROBE',
'SUBOK,1,23,3',
'U,1',
'U,1,x,1|2|3',
'U,1,0,1|2|3',
'U,1,3,1|2',
'U,1,3,1|2|3|4',
'U,1,3,^9',
'U,1,3,%E0%A4%A|1|24',
])
assert.equal(parseTlcpUpdate(line, of, 3), null, line);
});
test('the relay opens on the first request, subscribes, and reports live values', () => {
const { relay, sockets, clock } = relayAt(NOV_13);
assert.equal(sockets.length, 0, 'nothing is contacted before a request');
relay.demand();
assert.equal(sockets.length, 1);
assert.equal(relay.snapshot().status, 'connecting');
const socket = sockets[0];
socket.emit('open');
assert.match(socket.sent[0], /^create_session\r\nLS_adapter_set=ISSLIVE&/);
socket.emit(
'message',
'CONOK,S1,50000,5000,*\r\nSERVNAME,x\r\nCLIENTIP,192.0.2.1',
);
assert.match(
socket.sent[1],
/^control\r\n.*LS_mode=MERGE.*LS_schema=TimeStamp%20Value%20Status\.Class/,
);
assert.ok(socket.sent[1].includes('S0000004%20S0000003'));
const stamp = stampOf(NOV_13 - 2000);
socket.emit(
'message',
`U,1,${index('S0000004')},${stamp}|346.12|24\r\nU,1,${index('TIME_000001')},${stamp}|123|24`,
);
let body = relay.snapshot();
assert.equal(body.configured, true);
assert.equal(body.status, 'live');
assert.deepEqual(body.items.S0000004, [346.12, NOV_13 - 2000]);
assert.equal(body.items.TIME_000001, undefined, 'the clock is not a joint');
assert.equal(JSON.stringify(body).includes('192.0.2.1'), false);
// A later update with an unchanged stamp field keeps the old stamp.
clock.ms += 1000;
socket.emit('message', `U,1,${index('S0000004')},|346.5|`);
body = relay.snapshot();
assert.deepEqual(body.items.S0000004, [346.5, NOV_13 - 2000]);
});
test('no station clock tick for 20 s, or a clock without signal, is no-signal', () => {
const { relay, sockets, clock } = relayAt(NOV_13);
relay.demand();
const socket = sockets[0];
socket.emit('open');
socket.emit('message', 'CONOK,S1,50000,5000,*');
const clockLine = (cls) =>
`U,1,${index('TIME_000001')},${stampOf(clock.ms)}|1|${cls}`;
socket.emit('message', clockLine('24'));
assert.equal(relay.snapshot().status, 'live');
clock.ms += 19_000;
socket.emit('message', 'PROBE');
assert.equal(relay.snapshot().status, 'live');
clock.ms += 2_000;
assert.equal(relay.snapshot().status, 'no-signal');
socket.emit('message', clockLine('1'));
assert.equal(relay.snapshot().status, 'no-signal');
socket.emit('message', clockLine('24'));
assert.equal(relay.snapshot().status, 'live');
});
test('a lost or silent connection is retried on a ladder, and stale events are ignored', () => {
const { relay, sockets, clock } = relayAt(NOV_13);
relay.demand();
const first = sockets[0];
first.emit('open');
first.emit('close');
assert.equal(first.terminated, true);
assert.equal(relay.snapshot().status, 'reconnecting');
// Not before 5 s.
clock.ms += 4_000;
relay.demand();
relay.tick();
assert.equal(sockets.length, 1);
clock.ms += 1_000;
relay.demand();
assert.equal(sockets.length, 2);
// The dead socket's late events change nothing.
first.emit('message', `U,1,${index('S0000004')},1|999|24`);
assert.equal(relay.snapshot().items.S0000004, undefined);
// A second failure waits 15 s.
sockets[1].emit('error', new Error('x'));
clock.ms += 14_000;
relay.demand();
assert.equal(sockets.length, 2);
clock.ms += 1_000;
relay.demand();
assert.equal(sockets.length, 3);
// A socket that goes silent for 30 s is recycled by the tick.
const third = sockets[2];
third.emit('open');
third.emit('message', 'CONOK,S1,50000,5000,*');
clock.ms += 29_000;
relay.demand();
relay.tick();
assert.equal(third.terminated, false);
clock.ms += 2_000;
relay.demand();
relay.tick();
assert.equal(third.terminated, true);
});
test('a refused or ended session starts over', () => {
for (const line of ['CONERR,2,x', 'END,31,x', 'LOOP,0', 'REQERR,1,17,x']) {
const { relay, sockets } = relayAt(NOV_13);
relay.demand();
sockets[0].emit('open');
sockets[0].emit('message', line);
assert.equal(sockets[0].terminated, true, line);
assert.equal(relay.snapshot().status, 'reconnecting', line);
}
});
test('with nobody asking for two minutes the connection closes and the values go', () => {
const { relay, sockets, clock } = relayAt(NOV_13);
relay.demand();
const socket = sockets[0];
socket.emit('open');
socket.emit('message', 'CONOK,S1,50000,5000,*');
socket.emit('message', `U,1,${index('S0000003')},${stampOf(clock.ms)}|14|24`);
clock.ms += 119_000;
socket.emit('message', 'PROBE');
assert.equal(relay.tick(), true);
assert.equal(socket.terminated, false);
clock.ms += 2_000;
assert.equal(relay.tick(), false);
assert.equal(socket.terminated, true);
assert.deepEqual(relay.snapshot().items, {});
// The next request opens a fresh connection.
relay.demand();
assert.equal(sockets.length, 2);
});
test('an oversized or malformed frame is dropped without taking the relay down', () => {
const { relay, sockets } = relayAt(NOV_13);
relay.demand();
const socket = sockets[0];
socket.emit('open');
socket.emit('message', 'CONOK,S1,50000,5000,*');
socket.emit('message', { length: 10_000_000 });
socket.emit('message', `U,1,${index('S0000004')},1|not-a-number|24`);
socket.emit('message', 'U,1,999,1|2|24');
assert.deepEqual(relay.snapshot().items, {});
assert.equal(socket.terminated, false);
});
test('without a socket library the relay says unavailable', () => {
const relay = createIssTelemetryRelay({ createSocket: () => null });
relay.demand();
assert.equal(relay.snapshot().status, 'unavailable');
});
/** Mount the plugin on a fake Connect stack and return a request function. */
function install(plugin, preview = false) {
const routes = new Map();
plugin[preview ? 'configurePreviewServer' : 'configureServer']({
middlewares: { use: (route, handler) => routes.set(route, handler) },
});
return (method = 'GET', headers = {}) => {
const res = {
headers: {},
writeHead(status, headers) {
Object.assign(this, { status, headers });
},
setHeader(name, value) {
this.headers[name] = value;
},
end(body) {
this.body = body;
this.status ??= this.statusCode;
},
};
routes.get(ISS_TELEMETRY_ROUTE)(
{ url: '/', method, headers, socket: {} },
res,
);
return res;
};
}
test('the route is off by default and never opens the feed', () => {
let opened = 0;
const plugin = issTelemetryProxy({
env: {},
createSocket: () => {
opened += 1;
return fakeSocket();
},
});
assert.equal(typeof plugin.configurePreviewServer, 'function');
for (const preview of [false, true]) {
const res = install(plugin, preview)();
assert.equal(res.status, 200);
assert.deepEqual(JSON.parse(res.body), { configured: false });
assert.equal(res.headers['Cache-Control'], 'no-store');
}
assert.equal(opened, 0);
});
test('switched on, the route opens the feed once and serves the snapshot', () => {
const sockets = [];
const plugin = issTelemetryProxy({
env: { ISS_TELEMETRY_ENABLED: '1' },
createSocket: () => {
const socket = fakeSocket();
sockets.push(socket);
return socket;
},
now: () => NOV_13,
});
const request = install(plugin);
try {
const first = JSON.parse(request().body);
assert.equal(first.configured, true);
assert.equal(first.status, 'connecting');
request();
assert.equal(sockets.length, 1, 'one connection for every request');
assert.equal(request('POST').status, 405);
assert.equal(
request('GET', { 'sec-fetch-site': 'cross-site' }).status,
403,
);
// Sixty requests a minute from one client, then 429.
let limited = 0;
for (let i = 0; i < 70; i++) if (request().status === 429) limited += 1;
assert.ok(limited > 0);
} finally {
plugin.closeBundle();
}
assert.equal(sockets[0].terminated, true);
});