Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Changelog

## 1.6.2 (2026-11-20)

### Fixed
- `OddsWebSocket` no longer stops for good when a reconnect handshake is refused with HTTP 500, 502, 503 or 504, such as the 503 the server sends while it restarts. These are retried with backoff like 429, and the wait honors the `Retry-After` header when the `ws` package is used. 400, 401, 403 and 426 stay fatal. After `maxReconnectAttempts` the error names the last HTTP status.

## 1.6.1 (2026-11-20)

### Docs
Expand Down
2 changes: 1 addition & 1 deletion CITATION.cff
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ cff-version: 1.2.0
message: "If you use this software, please cite it using the metadata from this file."
type: software
title: "odds-api-io: Official Node.js SDK for Odds-API.io"
version: 1.6.1
version: 1.6.2
date-released: "2026-11-20"
authors:
- name: "Outlier AS"
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ for await (const msg of feed) {

Events: `open`, `message`, one per message type (`welcome`, `created`, `updated`, `deleted`, `no_markets`, `score`, `status`, `resync_required`, `replay_complete`), `reconnecting`, `close` and `error`. `feed.close()` stops it; `feed.lastSeq` is the resume point to persist.

Close codes: 1012 (server restart) reconnects at once, 1013 (cooldown) waits at least 3 seconds, 1008 because a newer connection replaced this one stops instead of fighting it (two connections per key). A refused handshake (401, 403, 426) is not retried and rejects `connect()` / the iterator with `OddsWebSocketError`. Options: `reconnect` (default true), `maxReconnectAttempts`, `initialReconnectDelay`, `maxReconnectDelay`, `replayComplete` (default true) and `WebSocket` to pass your own implementation.
Close codes: 1012 (server restart) reconnects at once, 1013 (cooldown) waits at least 3 seconds, 1008 because a newer connection replaced this one stops instead of fighting it (two connections per key). A refused handshake with 400, 401, 403 or 426 is not retried and rejects `connect()` / the iterator with `OddsWebSocketError`. A 429 or 5xx (for example the 503 a server sends while it restarts) is retried with backoff, waiting at least as long as its `Retry-After` header asks (the header is read with the `ws` package). Options: `reconnect` (default true), `maxReconnectAttempts`, `initialReconnectDelay`, `maxReconnectDelay`, `replayComplete` (default true) and `WebSocket` to pass your own implementation.

## Historical odds and closing lines

Expand Down Expand Up @@ -482,5 +482,5 @@ This is the official SDK for Odds-API.io. This tool is for informational purpose
If you use this package in research or a publication, please cite it. Citation metadata is in [CITATION.cff](CITATION.cff) (GitHub renders a "Cite this repository" button from it) and Zenodo metadata is in `.zenodo.json`.

```
Outlier AS. odds-api-io: Official Node.js SDK for Odds-API.io (version 1.6.1). https://github.com/odds-api-io/odds-api-node
Outlier AS. odds-api-io: Official Node.js SDK for Odds-API.io (version 1.6.2). https://github.com/odds-api-io/odds-api-node
```
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "odds-api-io",
"version": "1.6.1",
"version": "1.6.2",
"description": "Official Node.js and TypeScript SDK for the Odds-API.io sports betting odds API: real-time odds API for 500+ bookmakers, REST and WebSocket",
"keywords": [
"odds api",
Expand Down Expand Up @@ -85,7 +85,8 @@
"devDependencies": {
"@types/node": "^22.0.0",
"tsx": "^4.21.0",
"typescript": "^5.6.0"
"typescript": "^5.6.0",
"ws": "^8.23.0"
},
"engines": {
"node": ">=18.0.0"
Expand Down
2 changes: 1 addition & 1 deletion src/version.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export const VERSION = '1.6.1';
export const VERSION = '1.6.2';
44 changes: 38 additions & 6 deletions src/websocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@ import type { Clock, CommaList, EventStatus, Market, MarketName, Score } from '.
import { OddsAPIError } from './errors.js';

const DEFAULT_WS_URL = 'wss://api.odds-api.io/v3/ws';
const MAX_TIMER_DELAY = 2 ** 31 - 1;

export type WsChannel = 'odds' | 'scores' | 'status';

/** The subset of the WebSocket API the helper uses; `ws` and the browser/Node global both fit. */
export interface WebSocketLike {
readyState: number;
/** Present on `ws` sockets; used to read the status and Retry-After of a refused handshake. */
on?: (event: string, listener: (...args: any[]) => void) => unknown;
onopen: ((event: any) => void) | null;
onmessage: ((event: { data: unknown }) => void) | null;
onerror: ((event: any) => void) | null;
Expand Down Expand Up @@ -181,6 +184,20 @@ function decode(data: unknown): string {
return String(data);
}

/** 429 and 5xx (a server restarting or draining) are worth retrying; other refused handshakes are not. */
function isRetryableStatus(status: number | undefined): boolean {
return status === 429 || (status !== undefined && status >= 500 && status < 600);
}

function parseRetryAfter(value: unknown): number | undefined {
const text = Array.isArray(value) ? value[0] : value;
if (typeof text !== 'string' || !text.trim()) return undefined;
const seconds = Number(text);
if (Number.isFinite(seconds)) return seconds >= 0 ? seconds * 1000 : undefined;
const date = Date.parse(text);
return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());
}

async function loadDefaultWebSocket(): Promise<WebSocketConstructor> {
const moduleName = 'ws';
try {
Expand Down Expand Up @@ -221,6 +238,7 @@ export class OddsWebSocket {
private resolveOpen?: () => void;
private rejectOpen?: (error: Error) => void;
private handshakeError?: OddsWebSocketError;
private retryAfterMs?: number;
private socketOpened = false;

private iterating = false;
Expand Down Expand Up @@ -328,9 +346,20 @@ export class OddsWebSocket {
this.ctor ??= this.options.WebSocket ?? (await loadDefaultWebSocket());
if (this.stopped) return;
this.handshakeError = undefined;
this.retryAfterMs = undefined;
const socket = new this.ctor(this.buildUrl());
this.socket = socket;

if (typeof socket.on === 'function') {
socket.on('unexpected-response', (_req: unknown, res: any) => {
if (socket !== this.socket) return;
this.handshakeError = this.handshakeFailure(Number(res?.statusCode));
this.retryAfterMs = parseRetryAfter(res?.headers?.['retry-after']);
res?.resume?.();
socket.close();
});
}

this.socketOpened = false;
socket.onopen = () => {
if (socket !== this.socket) return;
Expand All @@ -347,7 +376,7 @@ export class OddsWebSocket {
};

socket.onerror = (event: any) => {
if (socket !== this.socket || this.stopped) return;
if (socket !== this.socket || this.stopped || this.handshakeError) return;
const text: string = event?.message ?? event?.error?.message ?? '';
const status = /Unexpected server response: (\d{3})/.exec(text);
if (status) this.handshakeError = this.handshakeFailure(Number(status[1]));
Expand Down Expand Up @@ -408,22 +437,25 @@ export class OddsWebSocket {
return;
}

let fatal: OddsWebSocketError | undefined = this.handshakeError;
const refused = this.handshakeError;
let fatal: OddsWebSocketError | undefined = refused && !isRetryableStatus(refused.code) ? refused : undefined;
if (!fatal && code === 1008 && /newer connection/i.test(reason)) {
fatal = new OddsWebSocketError(`Connection replaced by a newer one on this key (${reason})`, code);
}
if (fatal && fatal.code === 429) fatal = undefined;

const reconnect = this.options.reconnect !== false;
const max = this.options.maxReconnectAttempts ?? Infinity;
if (fatal || !reconnect || this.attempts >= max) {
this.emit('close', { code, reason, willReconnect: false });
const error =
fatal ??
(!reconnect ? refused : undefined) ??
(reconnect
? new OddsWebSocketError(
`Gave up after ${this.attempts} reconnect attempts (last close ${code}${reason ? ` ${reason}` : ''})`,
code
`Gave up after ${this.attempts} reconnect attempts (last ${
refused ? `handshake refused with HTTP ${refused.code}` : `close ${code}${reason ? ` ${reason}` : ''}`
})`,
refused?.code ?? code
)
: code === 1000
? undefined
Expand Down Expand Up @@ -455,7 +487,7 @@ export class OddsWebSocket {
if (code === 1012) return jitter(Math.min(initial, 1000));
const backoff = Math.min(max, initial * 2 ** (this.attempts - 1));
if (code === 1013) return jitter(Math.max(backoff, 3000));
return jitter(backoff);
return Math.min(MAX_TIMER_DELAY, jitter(Math.max(backoff, this.retryAfterMs ?? 0)));
}

private fail(error: Error): void {
Expand Down
188 changes: 188 additions & 0 deletions test/websocket.test.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { test, describe } from 'node:test';
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { WebSocketServer } from 'ws';
import { OddsWebSocket, OddsWebSocketError } from 'odds-api-io';

/** A scripted stand-in for a WebSocket: tests drive open, messages and closes. */
Expand Down Expand Up @@ -38,6 +40,31 @@ class FakeSocket {
}
}

/** Mimics `ws`: a refused handshake is reported through 'unexpected-response' with the response headers. */
class FakeWsSocket extends FakeSocket {
constructor(url) {
super(url);
this.handlers = {};
}
on(event, listener) {
this.handlers[event] = listener;
}
refuse(statusCode, headers = {}) {
let resumed = false;
this.handlers['unexpected-response']?.({}, { statusCode, headers, resume: () => (resumed = true) });
this.resumed = resumed;
}
close(code = 1006, reason = '') {
if (this.readyState === 0) {
this.readyState = 3;
this.onerror?.({ message: 'WebSocket was closed before the connection was established' });
queueMicrotask(() => this.onclose?.({ code: 1006, reason: '' }));
return;
}
super.close(code, reason);
}
}

const tick = (ms = 0) => new Promise((r) => setTimeout(r, ms));

function feed(options = {}) {
Expand Down Expand Up @@ -179,6 +206,108 @@ describe('OddsWebSocket', () => {
await assert.rejects(p, (err) => err.code === 401);
});

for (const status of [500, 502, 503, 504]) {
test(`a ${status} handshake is retried with backoff`, async () => {
const ws = feed();
const errors = [];
const reconnecting = [];
ws.on('error', (e) => errors.push(e));
ws.on('reconnecting', (i) => reconnecting.push(i));
const p = ws.connect();
await tick();
FakeSocket.last().fail(`Unexpected server response: ${status}`);
await tick(40);
assert.equal(FakeSocket.instances.length, 2);
assert.equal(reconnecting.length, 1);
assert.equal(errors.length, 0);
FakeSocket.last().open();
await p;
ws.close();
});
}

test('a 503 with Retry-After waits at least that long', async () => {
FakeSocket.reset();
const ws = new OddsWebSocket({ apiKey: 'secret', markets: 'ML', WebSocket: FakeWsSocket, initialReconnectDelay: 5 });
const errors = [];
const reconnecting = [];
ws.on('error', (e) => errors.push(e));
ws.on('reconnecting', (i) => reconnecting.push(i));
ws.connect().catch(() => {});
await tick();
const first = FakeSocket.last();
first.refuse(503, { 'retry-after': '2' });
await tick();
assert.equal(first.resumed, true);
assert.equal(reconnecting.length, 1);
assert.ok(reconnecting[0].delay >= 2000 && reconnecting[0].delay <= 2400, `delay ${reconnecting[0].delay}`);
assert.equal(errors.length, 0);
ws.close();
});

test('a 403 reported through unexpected-response stays fatal', async () => {
FakeSocket.reset();
const ws = new OddsWebSocket({ apiKey: 'secret', markets: 'ML', WebSocket: FakeWsSocket, initialReconnectDelay: 5 });
const errors = [];
ws.on('error', (e) => errors.push(e));
const p = ws.connect();
await tick();
FakeSocket.last().refuse(403);
await assert.rejects(p, (err) => err instanceof OddsWebSocketError && err.code === 403 && /no WebSocket access/.test(err.message));
await tick(40);
assert.equal(FakeSocket.instances.length, 1);
assert.equal(errors.length, 1);
});

test('gives up on a refused handshake after maxReconnectAttempts and names the status', async () => {
const ws = feed({ maxReconnectAttempts: 1 });
ws.on('error', () => {});
const p = ws.connect();
await tick();
FakeSocket.last().fail('Unexpected server response: 503');
await tick(40);
FakeSocket.last().fail('Unexpected server response: 503');
await assert.rejects(p, (err) => err.code === 503 && /Gave up after 1 reconnect attempts \(last handshake refused with HTTP 503\)/.test(err.message));
});

test('with reconnect off, a refused 503 rejects with its HTTP status', async () => {
FakeSocket.reset();
const ws = new OddsWebSocket({ apiKey: 'secret', markets: 'ML', WebSocket: FakeWsSocket, reconnect: false });
ws.on('error', () => {});
const p = ws.connect();
await tick();
FakeSocket.last().refuse(503);
await assert.rejects(p, (err) => err instanceof OddsWebSocketError && err.code === 503 && err.status === 503);
});

test('a huge Retry-After stays within the timer limit', async () => {
FakeSocket.reset();
const ws = new OddsWebSocket({ apiKey: 'secret', markets: 'ML', WebSocket: FakeWsSocket });
const reconnecting = [];
ws.on('reconnecting', (i) => reconnecting.push(i));
ws.connect().catch(() => {});
await tick();
FakeSocket.last().refuse(503, { 'retry-after': '2592000' });
await tick();
assert.equal(reconnecting[0].delay, 2 ** 31 - 1);
ws.close();
});

test('network errors are retried', async () => {
const ws = feed();
const reconnecting = [];
ws.on('error', () => {});
ws.on('reconnecting', (i) => reconnecting.push(i));
const p = ws.connect();
await tick();
FakeSocket.last().fail('connect ECONNREFUSED 127.0.0.1:443');
await tick(40);
assert.equal(reconnecting.length, 1);
FakeSocket.last().open();
await p;
ws.close();
});

test('gives up after maxReconnectAttempts', async () => {
const ws = feed({ maxReconnectAttempts: 2 });
ws.on('error', () => {});
Expand Down Expand Up @@ -240,3 +369,62 @@ describe('OddsWebSocket', () => {
await assert.rejects(loop, (err) => err instanceof OddsWebSocketError && err.code === 1011);
});
});

describe('OddsWebSocket with the ws package', () => {
async function server(refusals) {
const wss = new WebSocketServer({ noServer: true, perMessageDeflate: true });
const http = createServer();
let upgrades = 0;
http.on('upgrade', (req, socket, head) => {
const refusal = refusals[upgrades++];
if (refusal) {
const headers = Object.entries(refusal.headers ?? {}).map(([k, v]) => `${k}: ${v}\r\n`).join('');
socket.end(`HTTP/1.1 ${refusal.status} Refused\r\n${headers}Content-Length: 0\r\nConnection: close\r\n\r\n`);
return;
}
wss.handleUpgrade(req, socket, head, (client) => client.send(JSON.stringify(welcome)));
});
await new Promise((r) => http.listen(0, '127.0.0.1', r));
return {
url: `ws://127.0.0.1:${http.address().port}/v3/ws`,
upgrades: () => upgrades,
stop: () => {
for (const c of wss.clients) c.terminate();
wss.close();
http.close();
},
};
}

test('a draining 503 with Retry-After reconnects after the advised wait', async (t) => {
const srv = await server([{ status: 503, headers: { 'Retry-After': '1' } }]);
t.after(srv.stop);
const ws = new OddsWebSocket({ apiKey: 'k', markets: 'ML', url: srv.url, initialReconnectDelay: 5 });
const errors = [];
const reconnecting = [];
ws.on('error', (e) => errors.push(e));
ws.on('reconnecting', (i) => reconnecting.push(i));
const welcomed = new Promise((r) => ws.once('welcome', r));
const started = Date.now();
await ws.connect();
await welcomed;
assert.ok(Date.now() - started >= 1000);
assert.equal(srv.upgrades(), 2);
assert.equal(reconnecting.length, 1);
assert.ok(reconnecting[0].delay >= 1000);
assert.deepEqual(errors, []);
ws.close();
});

test('a 401 is fatal', async (t) => {
const srv = await server([{ status: 401 }]);
t.after(srv.stop);
const ws = new OddsWebSocket({ apiKey: 'k', markets: 'ML', url: srv.url, initialReconnectDelay: 5 });
const errors = [];
ws.on('error', (e) => errors.push(e));
await assert.rejects(ws.connect(), (err) => err instanceof OddsWebSocketError && err.code === 401);
await tick(50);
assert.equal(srv.upgrades(), 1);
assert.equal(errors.length, 1);
});
});
Loading