Download server/test-client.js from abr00kx/taper: direct link, hf CLI and curl.
- Browser
- Download file 5.98 kB
-
https://huggingface.co/abr00kx/taper/resolve/main/server/test-client.js
- Command line
-
hf download hf://abr00kx/taper/server/test-client.js
-
curl -L -o test-client.js https://huggingface.co/abr00kx/taper/resolve/main/server/test-client.js
5.98 kB
| // WebSocket test client for the Taper gateway, shared by the test files. | |
| import { solveChallenge } from '../client/pow.js'; | |
| import { parseBinaryFrame } from '../client/media.js'; | |
| import { padJson } from '../client/crypto.js'; | |
| import * as opaque from '../client/opaque.js'; | |
| // Minimal client: request/response by id, dispatch queue, close tracking. | |
| export class Client { | |
| // `open(url)` may return any WHATWG-style WebSocket, for example one that | |
| // goes through Tor (test-tor-live.js). | |
| // `timeoutMs` is the default wait for frames: raise it for slow transports (Tor). | |
| // `heartbeat` keeps the connection alive, as a real client does, for tests | |
| // that stay connected longer than the server's heartbeat timeout. | |
| static async connectTo(url, { open = (u) => new WebSocket(u), timeoutMs = 2000, heartbeat = false } = {}) { | |
| const c = new Client(); | |
| c.timeoutMs = timeoutMs; | |
| c.ws = open(url); | |
| c.nextId = 1; | |
| c.pending = new Map(); | |
| c.frames = []; | |
| c.waiters = []; | |
| c.handlers = []; | |
| c.downloads = new Map(); // download_id -> Map(index -> chunk), filled from binary frames | |
| c.ws.binaryType = 'arraybuffer'; | |
| c.closed = new Promise((resolve) => c.ws.addEventListener('close', (e) => resolve({ code: e.code, reason: e.reason }))); | |
| c.sizes = { text: [], binary: [] }; // byte length of every frame received | |
| c.ws.addEventListener('message', (e) => { | |
| if (typeof e.data === 'string') c.sizes.text.push(new TextEncoder().encode(e.data).length); | |
| else c.sizes.binary.push(e.data.byteLength); | |
| if (typeof e.data !== 'string') { | |
| const frame = parseBinaryFrame(new Uint8Array(e.data)); | |
| if (frame?.op === 2) c.downloads.get(frame.id)?.set(frame.index, frame.data.slice()); | |
| return; | |
| } | |
| const f = JSON.parse(e.data); | |
| if (f.op === 'response') { | |
| c.pending.get(f.id)?.(f); | |
| c.pending.delete(f.id); | |
| return; | |
| } | |
| if (f.op === 'hello') c.connectionId = f.body.connection_id; | |
| if (f.op === 'ready' || f.op === 'resumed') c.sessionId = f.body.session_id; | |
| if (c.handlers.some((h) => h(f))) return; | |
| c.frames.push(f); | |
| c.waiters = c.waiters.filter((w) => !w(f)); | |
| }); | |
| await new Promise((resolve, reject) => { | |
| c.ws.addEventListener('open', resolve, { once: true }); | |
| c.ws.addEventListener('error', reject, { once: true }); | |
| }); | |
| c.hello = await c.next((f) => f.op === 'hello'); | |
| if (heartbeat) { | |
| const timer = setInterval(() => c.send({ op: 'heartbeat' }), c.hello.body.heartbeat_interval_ms / 2); | |
| c.handlers.push((f) => f.op === 'heartbeat_ack'); | |
| c.closed.then(() => clearInterval(timer)); | |
| } | |
| return c; | |
| } | |
| send(frame) { | |
| const text = JSON.stringify(padJson(frame)); | |
| (this.sent ??= []).push(text); // every text frame sent, for leak checks | |
| this.ws.send(text); | |
| } | |
| sendBinary(bytes) { this.ws.send(bytes); } | |
| // Resolves with the response frame. Rejects if the connection closes first, | |
| // or (with a long timeoutMs, for slow transports) if no answer comes in time. | |
| request(method, body = {}, extra = {}) { | |
| const id = this.nextId++; | |
| return new Promise((resolve, reject) => { | |
| const fail = (err) => { this.pending.delete(id); reject(err); }; | |
| const timer = this.timeoutMs > 2000 ? setTimeout(() => fail(new Error(`${method}: no response in ${this.timeoutMs} ms`)), this.timeoutMs) : null; | |
| this.closed.then(() => { if (this.pending.has(id)) fail(new Error(`${method}: connection closed`)); }); | |
| this.pending.set(id, (f) => { clearTimeout(timer); resolve(f); }); | |
| this.send({ op: 'request', id, method, body, ...extra }); | |
| }); | |
| } | |
| // Like request(), but behaves as a real client does: waits out short rate | |
| // limits, and solves proof-of-work challenges. | |
| async call(method, body) { | |
| let extra = {}; | |
| for (let attempt = 0; ; attempt++) { | |
| const r = await this.request(method, body, extra); | |
| if (r.ok) return r.body; | |
| extra = {}; | |
| if (r.error?.errcode === 'T_LIMIT_EXCEEDED' && attempt < 5 && (r.error.retry_after_ms ?? 0) <= 5000) { | |
| await new Promise((resolve) => setTimeout(resolve, r.error.retry_after_ms ?? 100)); | |
| continue; | |
| } | |
| if (r.error?.errcode === 'T_CHALLENGE_REQUIRED' && attempt < 5) { | |
| extra = { challenge_response: await solveChallenge(r.error.challenge, this.sessionId ?? this.connectionId) }; | |
| continue; | |
| } | |
| throw new Error(`${method} failed: ${JSON.stringify(r.error)}`); | |
| } | |
| } | |
| // Resolve with the first (already received or future) frame matching `pred`. | |
| next(pred, timeoutMs = this.timeoutMs ?? 2000) { | |
| const idx = this.frames.findIndex(pred); | |
| if (idx !== -1) return Promise.resolve(this.frames.splice(idx, 1)[0]); | |
| return new Promise((resolve, reject) => { | |
| const t = setTimeout(() => reject(new Error('timed out waiting for frame')), timeoutMs); | |
| this.waiters.push((f) => { | |
| if (!pred(f)) return false; | |
| clearTimeout(t); | |
| this.frames.splice(this.frames.indexOf(f), 1); | |
| resolve(f); | |
| return true; | |
| }); | |
| }); | |
| } | |
| // OPAQUE registration and login, as a real client does them. | |
| register(username, password) { return opaque.register((m, b) => this.call(m, b), this.hello.body.server_name, username, password); } | |
| login(username, password) { return opaque.login((m, b) => this.call(m, b), this.hello.body.server_name, username, password); } | |
| reauth(username, password) { return opaque.reauth((m, b) => this.call(m, b), this.hello.body.server_name, username, password); } | |
| async identify(access_token) { | |
| this.send({ op: 'identify', body: { access_token } }); | |
| return (await this.next((f) => f.op === 'ready')).body; | |
| } | |
| close() { this.ws.close(); return this.closed; } | |
| } | |
| // A Client subclass whose connect() targets a fixed gateway URL. | |
| export function withUrl(url) { | |
| return class extends Client { | |
| static connect() { return Client.connectTo(url); } | |
| }; | |
| } | |