Live-updates dot: connected only once an event arrives #73

Merged
jcoffey-dev merged 1 commits from fix/push-dot-honest into main 2026-11-15 00:39:04 +00:00
4 changed files with 90 additions and 6 deletions

No files matched your search

+3 -2
View File
@@ -6,7 +6,7 @@ import { compress } from "hono/compress";
import { request as httpRequest } from "node:http";
import { request as httpsRequest } from "node:https";
import { RESPONSE_ALREADY_SENT } from "@hono/node-server/utils/response";
import { attach as pushAttach, attachRelay as pushAttachRelay, prepare as pushPrepare, receive as pushReceive, pushStatus } from "./push.js";
import { ALIVE_FRAME, attach as pushAttach, attachRelay as pushAttachRelay, prepare as pushPrepare, receive as pushReceive, pushStatus } from "./push.js";
import { getConnInfo } from "@hono/node-server/conninfo";
import { config } from "./config.js";
import { fetchPermissions } from "./permissionSchema.js";
@@ -1127,7 +1127,7 @@ export function createApp(basePath = config.basePath): Hono<Env> {
if (accountId && pushAttach(session.username, accountId, session.authorization, out)) {
out.writeHead(200, SSE_HEADERS);
out.flushHeaders();
out.write(": subscribed\n\n");
out.write(": subscribed\n\n" + ALIVE_FRAME);
return RESPONSE_ALREADY_SENT;
}
if (config.rawPushRelay) return relayPushRaw(c, url, session.authorization, session.username);
@@ -1413,6 +1413,7 @@ export function relayPushRaw(c: Context<Env>, url: string, authorization: string
req.removeAllListeners();
req.on("error", () => {});
req.destroy();
out.write(ALIVE_FRAME);
};
if (username) pushAttachRelay(username, out, migrate);
req.on("response", (res) => {
+9
View File
@@ -53,6 +53,15 @@ const byKey = new Map<string, AccountPush>();
const byToken = new Map<string, AccountPush>();
let sweeper: NodeJS.Timeout | null = null;
/**
* An event the browser can see, sent when a stream is known to be live: at
* once on fan-out, and when a relayed tab moves to fan-out. The client shows
* "connected" only after an event arrives, not when the response opens --
* the relay answers before the upstream has (issue #71), so an open response
* alone proves nothing. Relayed tabs get the upstream's own first ping.
*/
export const ALIVE_FRAME = "event: ping\ndata: {}\n\n";
export function pushEnabled(): boolean {
return config.pushMode === "subscribe" && !!config.pushUrl;
}
+67
View File
@@ -0,0 +1,67 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { push, type PushState } from "../push";
/** Just enough of EventSource to drive PushManager by hand. */
class FakeEventSource {
static last: FakeEventSource | null = null;
onopen: (() => void) | null = null;
onerror: (() => void) | null = null;
private handlers = new Map<string, ((ev: MessageEvent) => void)[]>();
closed = false;
constructor(public url: string) { FakeEventSource.last = this; }
addEventListener(type: string, fn: (ev: MessageEvent) => void) {
this.handlers.set(type, [...(this.handlers.get(type) ?? []), fn]);
}
close() { this.closed = true; }
emit(type: string, data: string) {
for (const fn of this.handlers.get(type) ?? []) fn(new MessageEvent(type, { data }));
}
}
describe("push connection state (issue #71)", () => {
let states: PushState[];
let off: () => void;
beforeEach(() => {
vi.useFakeTimers();
vi.stubGlobal("EventSource", FakeEventSource);
states = [];
off = push.onConnection((s) => states.push(s));
push.start();
});
afterEach(() => {
off();
push.stop();
vi.unstubAllGlobals();
vi.useRealTimers();
});
it("an opened stream is not connected until an event arrives", () => {
const es = FakeEventSource.last!;
es.onopen?.();
expect(push.state).toBe("connecting");
es.emit("ping", '{"interval": 30}');
expect(push.state).toBe("connected");
});
it("a state change counts as proof of life too", () => {
const es = FakeEventSource.last!;
es.emit("state", JSON.stringify({ "@type": "StateChange", changed: {} }));
expect(push.state).toBe("connected");
});
it("a stream that opens and ends at once keeps backing off", () => {
const delays: number[] = [];
for (let i = 0; i < 4; i++) {
const es = FakeEventSource.last!;
es.onopen?.();
es.onerror?.();
const before = Date.now();
vi.advanceTimersToNextTimer();
delays.push(Date.now() - before);
}
expect(delays).toEqual([1000, 2000, 4000, 8000]);
expect(states).not.toContain("connected");
});
});
+11 -4
View File
@@ -74,11 +74,20 @@ class PushManager {
const url = withBase(`/api/events?types=*&closeafter=no&ping=30`);
const es = new EventSource(url, { withCredentials: true });
this.es = es;
es.onopen = () => {
/*
* Connected means an event has arrived, not that the response opened.
* The server answers before the mail server has (issue #71), so an
* open stream can still be one that never delivers anything. Every live
* stream sends a ping soon after it starts -- the mail server's own, or
* ours on fan-out -- so the first event is the proof. The backoff resets
* here too, so a stream that opens and ends at once keeps backing off.
*/
const alive = () => {
this.backoff = 1000;
this.setState("connected");
};
es.addEventListener("state", (ev) => {
alive();
try {
const data = JSON.parse((ev as MessageEvent).data as string) as StateChange;
if (data["@type"] !== "StateChange") return;
@@ -94,9 +103,7 @@ class PushManager {
/* ignore malformed */
}
});
es.addEventListener("ping", () => {
/* keepalive */
});
es.addEventListener("ping", alive);
es.onerror = () => {
es.close();
this.es = null;