僕はリモートマシンでエージェントを動かすシステムを作っていて、スマホのアプリとマシンをリレー越しの WebSocket でつないでいます。あるとき、相手側で資格情報が更新されたあと、アプリに返信が届かなくなりました。エラーも、ログも、クラッシュもありません。画面を開き直すと直ります。
原因は、後始末をソケットの close イベントに任せていたことでした。資格情報が更新されると、アプリは自分でソケットを閉じ、close を待ってから、ストリームの持ち主に終了を伝えていました。問題の React Native の環境では、アプリ自身が閉じたソケットがこのイベントを届けませんでした。誰にも終了が伝わらず、再購読も起きず、接続オブジェクトとストリームの登録だけが残りました。
この件で分かったのは、WebSocket の close イベントや readyState は、ソケットが最後に教えてくれたことにすぎない、ということです。接続が生きているかは、アプリが自分で決めて、自分で確かめます。場面は3つあります。
1. 閉じると決めたら、その場で後始末する
イベントは、自分に起きたこと(相手が閉じた、ネットワークが落ちた)を知るには正しい場所です。自分で下した決定を記録する場所ではありません。仕様でも、自分から閉じたときの close はクロージングハンドシェイクが終わるか接続が破棄された後に来るもので(WHATWG の仕様)、相手が消えていれば長くかかります。問題の環境でイベントが来なかったことは観測した挙動で、文書化された保証ではありません。どちらにしても、結論は同じです。
後始末を1つの冪等な関数にまとめ、イベントからも、自分で閉じるときの end() からも呼びます。
// Settle what rode the socket the moment we decide to close it.
// The socket's close event is a report we may or may not get.
export class Connection {
pending = new Map(); // request id -> { reject }
streams = new Map(); // stream id -> onFrame
#settled = false;
constructor(socket) {
this.socket = socket;
// Still the path for closes we did not start: peer, network, server.
socket.addEventListener("close", this.#settle);
socket.addEventListener("error", this.#settle);
}
// Idempotent: every path may call it, only the first does anything.
#settle = () => {
if (this.#settled) return;
this.#settled = true;
const pending = [...this.pending.values()];
const streams = [...this.streams.values()];
this.pending.clear(); // empty the tables before anyone is told
this.streams.clear();
for (const p of pending) guard(() => p.reject(new Error("connection closed")));
for (const onFrame of streams) guard(() => onFrame({ closed: true }));
};
// Every way of ending the connection goes through here.
end(code, reason) {
try {
this.socket.close(code, reason);
} finally {
this.#settle();
}
}
}
function guard(fn) {
try { fn(); } catch (e) { console.error(e); } // one bad listener must not silence the rest
}
要点は3つです。
- 冪等にする。 イベントを届ける環境では、
end()のあとにイベントも来ます。2回目は何もしません。 finallyで呼ぶ。close()は不正なコードなどで例外を投げることがあります。後ろに並べただけだと、その経路で後始末が飛びます。- 通知の前にテーブルを空にする。 持ち主は終了を受けて新しい接続を始めるかもしれません。そのとき古いテーブルが中途半端に残っていると壊れます。
テストでは、close() を呼んでもイベントを出さないソケットの代役を使います。元のバグも、あえて失敗する形でテストに残しました。
test("the old code: close the socket and wait for the event", async () => {
const sock = new FakeSocket(false);
const frames = subscribe(new Connection(sock));
sock.close();
await tick();
assert.deepEqual(frames, []); // nobody was told, so nobody resubscribes
});
test("end() settles even if close never fires", () => {
const conn = new Connection(new FakeSocket(false));
const frames = subscribe(conn);
conn.end(1000, "renew");
assert.deepEqual(frames, [{ closed: true }]);
});
直したのは end() を足したことだけではありません。更新、期限切れ、ハートビートのタイムアウト、不正なフレームなど、接続を終えるすべての経路を end() に通したことです。1か所でも生の socket.close() が残ると、その原因でまた黙って止まります。
2. 静かな接続だけを、アプリ層の ping で確かめる
相手が何も言わずに消えた TCP 接続は、書き込みが失敗するかタイマーが切れるまで、開いたままに見えます。カーネルがどれだけ気づかないかは、死んだTCPの相手に気づくまでの実験で測りました。読むだけの側は無期限に待ちます。アプリには自前のタイマーが要ります。
ブラウザや React Native の WebSocket には、プロトコルの ping を送って pong を待つ API がありません。React Native のソース(0.87.1)には ping() がありますが、pong を受け取るイベントは見つかりませんでした。なので生存確認は、相手のアプリが答えるメッセージになります。それは本物のメッセージで、受信メッセージに課金されるリレーではお金がかかります。
そこで、受け取ったフレームはどれも生存の証拠として数えます。確認を送るのは、一定時間なにも届かなかったときだけです。確認の期限は、送った時点から測ります。
// Called from a fixed-interval tick. Any frame from the peer counts as proof
// of life, so only a quiet connection is probed, and a probe's deadline is
// fixed at the moment it was sent.
export function heartbeatAction(lastReceivedAt, pendingPingAt, now, intervalMs, timeoutMs) {
if (pendingPingAt !== null) {
return now - pendingPingAt >= timeoutMs ? "close" : "wait"; // never extended
}
return now - lastReceivedAt >= intervalMs ? "ping" : "wait";
}
タイムスタンプだけの関数なので、偽のタイマーなしでテストできます。フレームを受け取るたびに lastReceivedAt を更新し、pendingPingAt を null に戻します。数秒おきに何かが届く接続には、確認を1つも送りません。
間隔と同じ周期で tick すると、最悪の検知時間は「間隔2つ分とタイムアウト」になります。間隔10秒、タイムアウト25秒(説明用の値)で、tick の1ミリ秒後にフレームが届いたとします。次の tick では静かな時間が9.999秒なので送らず、その次の tick(20秒)で送り、45秒で閉じます。もっと短くしたいなら、tick を間隔より細かくします。
test("traffic just after a tick delays the ping, not the deadline", () => {
const received = 1; // a frame arrived 1 ms after the tick at 0
assert.equal(act(received, null, 10_000, I, T), "wait"); // only 9.999 s quiet
assert.equal(act(received, null, 20_000, I, T), "ping");
const pingAt = 20_000;
for (const now of [30_000, 40_000, 44_999]) assert.equal(act(received, pingAt, now, I, T), "wait");
assert.equal(act(received, pingAt, 45_000, I, T), "close"); // 2 intervals + timeout after the last frame
});
テストの全体(connection.test.mjs、heartbeat.test.mjs)。`node --test` で動きます
import { test } from "node:test";
import assert from "node:assert/strict";
import { Connection } from "./connection.mjs";
// A socket that can be told never to fire "close" after close().
class FakeSocket {
listeners = {};
constructor(emitsClose) { this.emitsClose = emitsClose; }
addEventListener(type, l) { (this.listeners[type] ??= []).push(l); }
close() { if (this.emitsClose) queueMicrotask(() => this.listeners.close?.forEach((l) => l())); }
}
const subscribe = (conn) => { const frames = []; conn.streams.set("s1", (f) => frames.push(f)); return frames; };
const tick = () => new Promise((r) => setTimeout(r, 10));
test("the old code: close the socket and wait for the event", async () => {
const sock = new FakeSocket(false);
const frames = subscribe(new Connection(sock));
sock.close();
await tick();
assert.deepEqual(frames, []); // nobody was told, so nobody resubscribes
});
test("end() settles even if close never fires", () => {
const conn = new Connection(new FakeSocket(false));
const frames = subscribe(conn);
conn.end(1000, "renew");
assert.deepEqual(frames, [{ closed: true }]);
});
test("a late close event does not notify twice", async () => {
const conn = new Connection(new FakeSocket(true));
const frames = subscribe(conn);
conn.end(1000, "renew");
await tick();
assert.equal(frames.length, 1);
});
test("settles even when close() throws", () => {
const sock = new FakeSocket(false);
sock.close = () => { throw new SyntaxError("bad code"); };
const conn = new Connection(sock);
const frames = subscribe(conn);
assert.throws(() => conn.end(999, "x"), SyntaxError);
assert.deepEqual(frames, [{ closed: true }]);
});
import { test } from "node:test";
import assert from "node:assert/strict";
import { heartbeatAction as act } from "./heartbeat.mjs";
const I = 10_000, T = 25_000; // illustration values, not a recommendation
test("traffic just after a tick delays the ping, not the deadline", () => {
const received = 1; // a frame arrived 1 ms after the tick at 0
assert.equal(act(received, null, 10_000, I, T), "wait"); // only 9.999 s quiet
assert.equal(act(received, null, 20_000, I, T), "ping");
const pingAt = 20_000;
for (const now of [30_000, 40_000, 44_999]) assert.equal(act(received, pingAt, now, I, T), "wait");
assert.equal(act(received, pingAt, 45_000, I, T), "close"); // 2 intervals + timeout after the last frame
});
test("a busy connection is never probed", () => {
for (let now = 0; now < 120_000; now += 1_000) assert.equal(act(now - 3_000, null, now, I, T), "wait");
});
now には壁時計ではなく performance.now() のような単調増加の時計を使います。アプリが一時停止しているあいだはタイマーが動かないので、復帰後の最初の tick が、ずっと前に送った確認を見つけることがあります。そのときはすぐに閉じます。一時停止をまたいだ接続は、死んでいる可能性のほうが高いからです。
3. フォアグラウンドに戻ったら、確かめて、作り直して、取り戻す
Apple のアーカイブのネットワークガイドには、バックグラウンドのアプリは「一時停止され、ネットワークのトラフィックを処理できなくなることがある」「既存の接続が閉じられることさえある」とあります(Apple)。Android の Doze は「ネットワークアクセスを停止」します(Android)。どちらも、何秒後に起きるかは書いていません。
止まっているあいだ、アプリのコードは動きません。確実に分かるのは、フォアグラウンドに戻った瞬間だけです。そのときの readyState === 1(OPEN)は、最後に処理したイベントの時点の記憶です。
Linux で、クライアントのプロセスを SIGSTOP で凍結して、サーバーから何が見えるかを試しました。OS がアプリを止めることの代役で、同じものではありません。カーネルと TCP は生きていて、止まるのはコードだけです。サーバーは500ミリ秒ごとにメッセージと ping を送り、3秒 pong がなければ切ります。
[ 1.1s] server: sent=2 handed-to-kernel=1 bufferedAmount=0 quiet-for=496 ms readyState=1
[ 2.0s] >>> SIGSTOP the client process
[ 2.1s] server: sent=4 handed-to-kernel=3 bufferedAmount=0 quiet-for=499 ms readyState=1
[ 3.1s] server: sent=6 handed-to-kernel=5 bufferedAmount=0 quiet-for=1501 ms readyState=1
[ 4.1s] server: sent=8 handed-to-kernel=7 bufferedAmount=0 quiet-for=2502 ms readyState=1
[ 4.6s] server: no pong for 3002 ms -> declare the client gone, terminate()
[ 4.7s] server: close event
[ 9.0s] >>> SIGCONT the client process
client: close event, code 1006, messages seen: 9
凍結中もサーバーの send() は成功し続け、bufferedAmount は0のままでした。異常を示したのは pong が来ないことだけです。凍結したクライアントは、再開してからカーネルにたまっていた9件を処理し、そのあとで接続が閉じられたことを1006として知りました。それまでは、ソケットは OPEN に見えていたはずです。
freeze_lab.mjs(凍結の実験)
// What does a server see when the client process is frozen (SIGSTOP) but its kernel and network are fine?
// Linux stand-in for "the OS suspended the app". Run: node freeze_lab.mjs
import { WebSocketServer } from "ws";
import { spawn } from "node:child_process";
const t0 = Date.now(); const at = () => `[${((Date.now() - t0) / 1000).toFixed(1).padStart(4)}s]`;
const wss = new WebSocketServer({ port: 0 });
await new Promise((r) => wss.on("listening", r));
const port = wss.address().port;
const client = spawn(process.execPath, ["-e", `
const WebSocket = require("ws"); let n = 0;
const ws = new WebSocket("ws://127.0.0.1:${port}");
ws.on("message", () => n++);
ws.on("close", (c) => { console.log("client: close event, code " + c + ", messages seen: " + n); process.exit(0); });
ws.on("error", (e) => console.log("client: error " + e.code));
`], { stdio: "inherit", cwd: process.cwd() });
wss.on("connection", (ws) => {
let seq = 0, lastPong = Date.now(), sent = 0, acked = 0;
ws.on("pong", () => { lastPong = Date.now(); });
const tick = setInterval(() => {
ws.send(`m${++seq}`, () => acked++); // callback = handed to the kernel
sent++;
ws.ping();
const quiet = Date.now() - lastPong;
if (seq % 2 === 0) console.log(`${at()} server: sent=${sent} handed-to-kernel=${acked} bufferedAmount=${ws.bufferedAmount} quiet-for=${quiet} ms readyState=${ws.readyState}`);
if (quiet > 3000) {
console.log(`${at()} server: no pong for ${quiet} ms -> declare the client gone, terminate()`);
clearInterval(tick); ws.terminate();
}
}, 500);
ws.on("close", () => console.log(`${at()} server: close event`));
});
setTimeout(() => { console.log(`${at()} >>> SIGSTOP the client process`); client.kill("SIGSTOP"); }, 2000);
setTimeout(() => { console.log(`${at()} >>> SIGCONT the client process`); client.kill("SIGCONT"); }, 9000);
setTimeout(() => process.exit(0), 11000);
なので、アクティブになるたびに、期限つきのアプリ層の ping を送ります。答えがなければ、閉じて、再接続し、離れていたあいだの出来事を取り戻します。再接続だけでは、そのあいだのメッセージが黙って失われます。
// On "active": do not trust readyState. Prove the socket is alive, otherwise rebuild it and catch up.
export function keepFresh({ lifecycle, connect, catchUp, probeMs = 2000, log = () => {} }) {
let socket = null, busy = null;
const probe = (ws) => new Promise((resolve) => { // a round trip that the peer *application* must answer
if (!ws || ws.readyState !== 1) return resolve(false);
const done = (ok) => { clearTimeout(timer); ws.removeEventListener("message", onMessage); resolve(ok); };
const onMessage = (e) => { if (e.data === "pong") done(true); };
const timer = setTimeout(() => done(false), probeMs);
ws.addEventListener("message", onMessage);
try { ws.send("ping"); } catch { done(false); }
});
async function ensure(reason) {
if (busy) return busy; // "active" can fire repeatedly
return (busy = (async () => {
if (await probe(socket)) { log(`${reason}: socket proved alive, nothing to do`); return; }
log(`${reason}: socket is ${socket ? "readyState " + socket.readyState : "missing"} or silent -> rebuild`);
try { socket?.close(); } catch {}
socket = await connect();
await catchUp(); // whatever was missed while we were away
})().finally(() => { busy = null; }));
}
lifecycle.addEventListener("change", (state) => { if (state === "active") ensure("foreground"); });
return { start: () => ensure("start"), get socket() { return socket; } };
}
lifecycle には React Native の AppState と同じ形のものを渡します。busy は、続けて来た active を1回の確認にまとめます。プローブは OPEN でないソケットにも false を返すので、「死んでいる」と「黙っている」を同じ道で扱えます。
偽の AppState と本物の ws サーバーで4つの場合を動かしました(プローブの期限は500ミリ秒)。
[ 516 ms] --- case 2: the connection silently died while we were away (server stops reading, so no pong)
[ 517 ms] client still thinks: readyState=1 (1 = OPEN)
[ 1017 ms] foreground: socket is readyState 1 or silent -> rebuild
[ 1418 ms] connects=2 catchUps=2
[ 1418 ms] --- case 3: the server closed it while we were away
[ 1520 ms] foreground: socket is readyState 3 or silent -> rebuild
[ 1820 ms] connects=3 catchUps=3
[ 1821 ms] --- case 4: three 'active' events in a row
[ 1822 ms] foreground: socket proved alive, nothing to do
[ 2121 ms] connects=3 catchUps=3
場合2では、クライアントは readyState=1 と言い続けましたが、プローブが期限切れになり、作り直して取り戻しました。readyState を見るだけの確認は、これを見逃します。場合4では、3回の active が1回のプローブになりました。場合1(問題のない接続)は、プローブが通って何もしませんでした。
test.mjs(4つの場合)
import { WebSocketServer, WebSocket } from "ws";
import { EventEmitter } from "node:events";
import { keepFresh } from "./keep_fresh.mjs";
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const wss = new WebSocketServer({ port: 0 }); await new Promise((r) => wss.on("listening", r));
const serverSide = [];
wss.on("connection", (ws) => { serverSide.push(ws); ws.on("message", (m) => { if (m.toString() === "ping") ws.send("pong"); }); });
const url = `ws://127.0.0.1:${wss.address().port}`;
class FakeAppState extends EventEmitter { addEventListener(t, f) { this.on(t, f); } } // same shape as React Native's AppState.addEventListener
const lifecycle = new FakeAppState();
let catchUps = 0, connects = 0;
const t0 = Date.now(); const log = (m) => console.log(`[${String(Date.now() - t0).padStart(5)} ms] ${m}`);
const app = keepFresh({
lifecycle, log, probeMs: 500,
connect: async () => { connects++; const c = new WebSocket(url); await new Promise((r) => c.on("open", r)); c.on("error", () => {}); return c; },
catchUp: async () => { catchUps++; },
});
await app.start(); await sleep(100);
log(`connects=${connects} catchUps=${catchUps}`);
log("--- case 1: app goes background and comes back; connection is fine");
lifecycle.emit("change", "background"); await sleep(100); lifecycle.emit("change", "active"); await sleep(300);
log(`connects=${connects} catchUps=${catchUps}`);
log("--- case 2: the connection silently died while we were away (server stops reading, so no pong)");
serverSide.at(-1)._socket.pause();
log(`client still thinks: readyState=${app.socket.readyState} (1 = OPEN)`);
lifecycle.emit("change", "active"); await sleep(900);
log(`connects=${connects} catchUps=${catchUps}`);
log("--- case 3: the server closed it while we were away");
serverSide.at(-1).terminate(); await sleep(100);
lifecycle.emit("change", "active"); await sleep(300);
log(`connects=${connects} catchUps=${catchUps}`);
log("--- case 4: three 'active' events in a row");
lifecycle.emit("change", "active"); lifecycle.emit("change", "active"); lifecycle.emit("change", "active"); await sleep(300);
log(`connects=${connects} catchUps=${catchUps}`);
process.exit(0);
サーバー側にも、凍結したクライアントを見限る期限が要ります。凍結したクライアントは、閉じたクライアントではありません。期限が短いと通信が悪いだけのクライアントも追い出し、長いと死んだクライアントの状態を持ち続けます。
よくある失敗
- 自分で閉じたあと、
closeイベントで後始末する。 イベントが来ない環境では、エラーなしで止まります。 - 後始末を2回走らせる。 持ち主が2回通知され、2回再購読します。
- 忙しい接続にも定期的に ping を送る。 データフレームも生存の証拠です。
- 確認の期限を tick ごとに延ばす。 死んだ接続がいつまでも閉じません。
- 復帰後に
readyStateを信じる。 UI は「接続中」なのに何も届きません。 - 取り戻さずに再接続する。 エラーは出ないのに、離れていたあいだのメッセージがありません。取り戻すには、最後に見た位置から読み直せるサーバーの API が要ります(再開できるストリーム)。
使わないほうがよい場合
- 両端がサーバー同士で、プロトコルの ping/pong を使えるなら、それを使います。アプリ層の確認は、ブラウザのスクリプトから ping を送れないためのものです。
- 数秒で終わる接続には、確認の仕組みは要りません。
- バックグラウンドのあいだの出来事も知る必要があるなら、プッシュ通知で知らせ、戻ったらこのルーチンを走らせます。
ソケットの状態は、最後に聞いた話
ソケットの状態は、ソケットから最後に聞いた話です。閉じると決めたら自分で後始末し、静かになったら自分で聞き、戻ってきたら確かめてから使います。