Files
punktfunk/sdk/src/sse.ts
T
enricobuehler 87114ab186
apple / swift (push) Successful in 1m15s
apple / screenshots (push) Successful in 4m21s
ci / web (push) Successful in 52s
ci / docs-site (push) Successful in 1m0s
android / android (push) Has been cancelled
arch / build-publish (push) Has been cancelled
ci / rust (push) Has been cancelled
ci / bench (push) Has been cancelled
deb / build-publish (push) Has been cancelled
decky / build-publish (push) Has been cancelled
docker / build-push (--build-arg FEDORA_VERSION=44, ci, ci/fedora-rpm.Dockerfile, punktfunk-fedora44-rpm) (push) Successful in 18s
docker / build-push (., web/Dockerfile, punktfunk-web) (push) Successful in 15s
docker / build-push (ci, ci/fedora-rpm.Dockerfile, punktfunk-fedora-rpm) (push) Successful in 14s
docker / build-push (ci, ci/rust-ci.Dockerfile, punktfunk-rust-ci) (push) Successful in 16s
docker / build-push (docs-site, docs-site/Dockerfile, punktfunk-docs) (push) Successful in 13s
rpm / build-publish (44, fedora-44, punktfunk-fedora44-rpm) (push) Successful in 14m56s
rpm / build-publish (43, bazzite, punktfunk-fedora-rpm) (push) Successful in 19m42s
docker / deploy-docs (push) Successful in 26s
feat(sdk): @punktfunk/host — the Effect TypeScript SDK (M3)
New top-level sdk/ package (RFC §7): a typed management-API client plus
the lifecycle event stream, built on Effect, two surfaces over one core:

- @punktfunk/host — the Promise facade front door: connect() resolves
  URL/token/TLS pin from the host's own files (zero config on the box),
  fails fast on bad credentials, pf.events.on() with typed callbacks
  (exact kinds, domain.* prefixes, "*", "dropped", "unknown"),
  pf.request() for the REST surface. Effect never required.
- @punktfunk/host/effect — the PunktfunkHost service + PunktfunkHostLive
  layer, Stream-based events()/eventsRaw(), typed errors
  (AuthError | ApiError | TransportError | VersionSkew — a 2xx that
  fails its schema is a typed skew, not undefined later), and every
  wire shape as an effect/Schema: REST generated via orval
  client:'effect' from api/openapi.json (S3 spike: works well; the
  text/event-stream payload is out of its reach), events hand-mirrored
  from the host's snapshot-tested wire format as a kind-discriminated
  union.

One reconnecting SSE core under both surfaces: spec-shaped parser,
exponential+jittered backoff (capped, resets after a healthy
connection), Last-Event-ID resume, 401 terminal. Default is LIVE tail
only — a fresh notify script must not re-fire on the host's replayed
ring (since: 0 opts into full replay).

TLS: the pin trusts exactly the host's self-signed identity cert
(chain-verified; hostname check waived — the cert is deliberately
CN-only for fingerprint pinning). Bun via fetch tls, Node via an undici
dispatcher (optionalDependency).

definePlugin() accepts both main shapes (async fn | Effect requiring
PunktfunkHost). Examples in both styles; README carries the compat
contract + systemd/Task Scheduler templates.

11 bun tests green (wire decode against the Rust snapshot strings,
SSE parser/reconnect/Last-Event-ID/401, both surfaces vs a mock host).
Live-verified against a real host on Bun AND Node through the pinned
loopback hop: connect → REST mutate → live event received → resume
cursor advanced; a wrong CA is rejected. npm publish + CI wiring
deferred (npm org = RFC open question 1).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-17 00:14:39 +02:00

173 lines
5.8 KiB
TypeScript

// The SSE half of the SDK: a spec-shaped parser plus one shared reconnecting frame source both
// surfaces consume — the Effect `Stream` wraps it, the Promise facade iterates it directly, so
// there is exactly one implementation of connect/parse/resume (RFC §7: "two surfaces, one
// core"). Reconnects carry `Last-Event-ID` (the host replays from its ring); backoff is
// exponential + jittered, capped, and resets after a healthy connection.
import type { ResolvedConfig } from "./config.js";
/** One parsed SSE frame. */
export interface SseFrame {
/** The `event:` name — an event kind, or `dropped`, or `message` when absent. */
event: string;
/** The joined `data:` payload. */
data: string;
/** The `id:` field (the host sets it to the event's `seq`). */
id?: string;
}
/** Incremental SSE parser (the WHATWG dispatch rules the host's frames need). */
export class SseParser {
private buf = "";
private event = "";
private data: string[] = [];
private id: string | undefined;
/** Feed a chunk; returns the frames it completed. */
push(chunk: string): SseFrame[] {
this.buf += chunk;
const frames: SseFrame[] = [];
for (;;) {
const nl = this.buf.indexOf("\n");
if (nl < 0) break;
let line = this.buf.slice(0, nl);
this.buf = this.buf.slice(nl + 1);
if (line.endsWith("\r")) line = line.slice(0, -1);
if (line.length === 0) {
// Blank line = dispatch.
if (this.data.length > 0 || this.event.length > 0) {
frames.push({
event: this.event.length > 0 ? this.event : "message",
data: this.data.join("\n"),
id: this.id,
});
}
this.event = "";
this.data = [];
continue;
}
if (line.startsWith(":")) continue; // comment (the host's keep-alives)
const colon = line.indexOf(":");
const field = colon < 0 ? line : line.slice(0, colon);
let value = colon < 0 ? "" : line.slice(colon + 1);
if (value.startsWith(" ")) value = value.slice(1);
switch (field) {
case "event":
this.event = value;
break;
case "data":
this.data.push(value);
break;
case "id":
this.id = value;
break;
default: // unknown fields are ignored per spec (retry: handled by our own backoff)
}
}
return frames;
}
}
export interface EventStreamOptions {
/**
* Resume cursor (`?since=`); reconnects use the newer `Last-Event-ID` automatically.
* **Omitted = live tail only** (events from now on — a fresh notify script must not
* re-fire on the host's replayed history); `0` = replay the host's full ring first;
* `N` = resume after seq N.
*/
since?: number;
/** Server-side kind filter (`["stream.*", "pairing.pending"]`). */
kinds?: string[];
/** Called on transient trouble (reconnects, decode warnings). Default: console.warn. */
onWarning?: (message: string) => void;
}
/**
* The "live tail only" cursor: beyond any realistic seq, so the host's catch-up is empty and
* (being > 0 yet ≥ the ring head) it never trips the `dropped` marker. The first received
* frame's real id replaces it for reconnects.
*/
const LIVE_ONLY_CURSOR = Number.MAX_SAFE_INTEGER;
/** Thrown when the stream cannot ever work (bad credentials) — retrying would loop 401s. */
export class SseAuthError extends Error {
readonly _tag = "SseAuthError";
}
const BACKOFF_INITIAL_MS = 500;
const BACKOFF_CAP_MS = 15_000;
/** A connection that lived this long resets the backoff (it was healthy, not flapping). */
const HEALTHY_MS = 30_000;
/**
* The shared frame source: connect → parse → yield frames, forever — reconnecting with
* `Last-Event-ID` on any hiccup. Ends only by consumer break/return (both surfaces cancel by
* dropping the iterator, which aborts the in-flight request) or throws [`SseAuthError`].
*/
export async function* sseFrames(
cfg: ResolvedConfig,
opts: EventStreamOptions = {},
): AsyncGenerator<SseFrame> {
const warn = opts.onWarning ?? ((m) => console.warn(`[punktfunk] ${m}`));
let lastId: number = opts.since ?? LIVE_ONLY_CURSOR;
let backoff = BACKOFF_INITIAL_MS;
const abort = new AbortController();
try {
for (;;) {
const url = new URL(`${cfg.url}/api/v1/events`);
if (opts.kinds && opts.kinds.length > 0)
url.searchParams.set("kinds", opts.kinds.join(","));
const headers: Record<string, string> = {
authorization: `Bearer ${cfg.token}`,
accept: "text/event-stream",
};
if (lastId !== 0) headers["last-event-id"] = String(lastId);
const connectedAt = Date.now();
try {
const resp = await cfg.fetch(url, {
headers,
signal: abort.signal,
});
if (resp.status === 401) throw new SseAuthError("invalid credentials");
if (!resp.ok || !resp.body)
throw new Error(`event stream HTTP ${resp.status}`);
const reader = resp.body.getReader();
const decoder = new TextDecoder();
const parser = new SseParser();
try {
for (;;) {
const { done, value } = await reader.read();
if (done) break; // server closed (slow-consumer cut / shutdown) → reconnect
for (const frame of parser.push(
decoder.decode(value, { stream: true }),
)) {
if (frame.id !== undefined) {
const id = Number(frame.id);
if (Number.isFinite(id)) lastId = id;
}
yield frame;
}
}
} finally {
reader.cancel().catch(() => {});
}
throw new Error("event stream ended");
} catch (e) {
if (e instanceof SseAuthError) throw e;
if (abort.signal.aborted) return;
if (Date.now() - connectedAt >= HEALTHY_MS) backoff = BACKOFF_INITIAL_MS;
const jittered = backoff * (0.5 + Math.random());
warn(
`event stream reconnecting in ${Math.round(jittered)}ms (${
e instanceof Error ? e.message : String(e)
})`,
);
await new Promise((r) => setTimeout(r, jittered));
backoff = Math.min(backoff * 2, BACKOFF_CAP_MS);
}
}
} finally {
abort.abort(); // consumer went away — tear down any in-flight request
}
}