diff --git a/AGENTS.md b/AGENTS.md index ed261be..13959fb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -50,6 +50,12 @@ JS workspace root is this repository (`packages/*` and `docs`). ` writes a blank pack from it for the chosen `--framework` (default Svelte). Gradle `generateKeelTypes` is the offline classpath scan. Actions are a Kotlin function `(In) -> Out`. +- Realtime is opt-in: `keel { realtime { } }` plus `install(SSE)` and/or + `install(WebSockets)` serves `/__keel/events` (SSE stream, WS upgrade, and + `POST` sends from SSE clients). Channels are host-owned strings; typed + `@KeelEvent` payloads are hints, the seed stays the only read model, and + `invalidate` rehydrates with a normal visit. No replay: reconnect means + resubscribe + reload. - Packs ship as `.feb` (zip of `manifest.json` + modules). Hosts load a `FrontendBundle` from a jar resource, a file, or an exploded directory. - Visits hit the real page URL with `X-Keel-Visit: true`. `/__keel/navigate` diff --git a/CHANGELOG.md b/CHANGELOG.md index 740a251..75b736f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,11 +7,49 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.2.1] - 2026-10-26 + +Realtime release: a typed event registry, SSE and WebSocket host transports +at `/__keel/events`, and the client `realtime` / `useKeelEvent` helpers. +Ktor is bumped to 3.5.2. + +### Added + +- Docs: new Realtime guide (host opt-in, typed events, invalidate, reconnect, + client surface), the wire-protocol envelope section, Typegen and + framework-adapter updates, refreshed llms.txt and agent skills. (#74) +- Harbor testbench now runs live: posts stream to `page:harbor.home` as + `harbor.message`, renames send an `invalidate`, and clients send + `harbor.typing` notices that the host echoes back. (#75) +- Realtime client: `realtime` from `@kolektiv/keel` connects over WebSocket + (SSE fallback) to `/__keel/events`, auto-holds `page:`, dispatches + typed events to `realtime.on`, rehydrates the seed on `invalidate`, + `POST`s sends by `sid` when streaming SSE, and reconnects with backoff and + resubscribe. Every adapter gains a lifecycle-aware + `useKeelEvent` / `injectKeelEvent` helper. (#73) +- Realtime host: opt-in `keel { realtime { } }` serves SSE and WebSocket + transports at `/__keel/events` when `install(SSE)` and/or + `install(WebSockets)` are present. Host-owned channels, session-cookie + auth via an `authorize` hook, typed `publish` / `invalidate` helpers on + `call.keelRealtime`, heartbeats, CSRF-protected HTTP sends, and a + documented no-replay reconnect story (resubscribe and rehydrate the + seed). (#71) +- Typed realtime event registry: `@KeelEvent` (payload classes and host + handler functions), `dev.kolektiv.keel.event.EventRegistry` / + `EventDiscovery`, and the versioned JSON envelope + (`KeelRealtimeEnvelope`) both transports speak. Typegen and + `keel-scaffold` emit the events section (`HarborEvents` / + `HarborEventId`) next to pages and actions. (#72) ## [0.1.2] - 2026-10-26 ### Changed - Republish on `repo.kolektiv.computer`; docs use `@kolektiv/common-docs-chrome` ^0.0.1 and `@kolektiv/themes` ^0.0.1. +- Maven group is now `computer.kolektiv.keel`: `Keel.GROUP`, the docs + install cite, and the CI Maven check all moved. Kotlin packages are + unchanged (`dev.kolektiv.keel.*`). (#81) +- Republish on `repo.kolektiv.computer`; docs use `@kolektiv/common-docs-chrome` ^0.0.1 and `@kolektiv/themes` ^0.0.1. + ## [0.1.1] - 2026-09-27 @@ -20,14 +58,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Publish Maven to `repo.kolektiv.computer` `maven-releases` / `maven-snapshots` only (dropped `keel-maven`). - Publish and consume npm via `npm-public` on `repo.kolektiv.computer` (dropped `keel-npm`). - Docs and consumer pins updated for the Kolektiv registry cut. - - -### Fixed - -- npm publishing now targets the `keel-npm` registry for the `@kolektiv` - scope: the publish script swaps the committed repo-root `.npmrc` - (`npm-public`) for the publish config and restores it afterwards. - ## [0.1.0] - 2026-09-14 ### Added @@ -104,7 +134,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- Docs and homepage tell the pack-at-render-time story: call-site pack +- Docs and homepage tell the pack-at-render-time story: c- Maven group is now `computer.kolektiv.keel`: `Keel.GROUP`, the docs + install cite, and the CI Maven check all moved. Kotlin packages are + unchanged (`dev.kolektiv.keel.*`). (#81) +- Republish on `repo.kolektiv.computer`; docs use `@kolektiv/common-docs-chrome` ^0.0.1 and `@kolektiv/themes` ^0.0.1.all-site pack selection, "Choosing a pack" replaces the theme-chain page, no resolver language (#11). - Refreshed the agent skill suite (`keel-host`, `keel-pack`, `keel-scaffold`) diff --git a/docs/src/content/docs/advanced/realtime.mdx b/docs/src/content/docs/advanced/realtime.mdx new file mode 100644 index 0000000..cdd4f20 --- /dev/null +++ b/docs/src/content/docs/advanced/realtime.mdx @@ -0,0 +1,247 @@ +--- +title: Realtime +description: Typed events and invalidations over SSE and WebSocket. The seed stays the read model. +category: advanced +order: 7 +--- + +import CodePair from "../../../components/CodePair.astro" +import FrameworkPanel from "../../../components/FrameworkPanel.astro" +import { path } from "../../../lib/paths" + +Realtime in Keel is **opt-in and advisory**. The seed is still the only read +model. A typed event says *something happened*; an `invalidate` says +*rehydrate with a normal visit*. Events missed while offline are not +replayed — the next visit always recovers the truth. That is what keeps +reconnect semantics small and the UI honest. + +One endpoint, two transports. `GET /__keel/events` streams SSE when the host +installed the Ktor `SSE` plugin; the same path upgrades to a WebSocket when +`WebSockets` is installed. SSE clients `POST` envelopes to the same path for +client-to-host sends (`sid` addresses the stream). Both transports speak the +same JSON envelope — see +Wire protocol. + +## Enable it on the host + +Install the plugins before `keel { }`, then opt in. Endpoints exist only when +the `realtime` block is present **and** at least one transport plugin is +installed. + +```kotlin +install(WebSockets) +install(SSE) + +keel { + realtime { + event("harbor.message", EventDirection.OUT) // host → pack + on("harbor.typing") { input -> // pack → host + call.keelRealtime.publish("page:harbor.home", "harbor.typing", input) + } + events(Board) // @KeelEvent functions + authorize = { call, channel -> // session cookies + channel.startsWith("page:") || call.request.cookies["harbor_uid"] != null + } + heartbeatSeconds = 25 + } +} +``` + +- `event(id, direction)` declares a typed payload without a handler. +- `on(id) { input -> … }` registers a handler for a client-sent event and + registers the binding as `IN` when it is not declared yet. +- `events(vararg hosts)` scans `@KeelEvent` functions the way `actions(hosts)` + scans `@KeelAction`; an `ApplicationCall.(Payload) -> Unit` extension gets + the handshake/POST call as `this`. +- `authorize` runs per channel at subscribe time. Channel ids are host-owned + strings; `page:…` and `user:…` are conventions, not built-ins. +- `heartbeatSeconds` sends `ping` envelopes (0 disables). Keepalives are how + dead SSE connections are noticed and reaped. + +Publish from anywhere a call is reachable — actions, page loaders, jobs — +with `call.keelRealtime` (or `application.keelRealtime`): + +```kotlin +@KeelAction("harbor.postMessage") +fun ApplicationCall.postMessage(input: PostMessageIn): PostMessageOut { + val item = Board.post(input.body) + keelRealtime.publish("page:harbor.home", "harbor.message", item) // flavor (a) + return PostMessageOut(item) +} + +@KeelAction("harbor.setName") +fun ApplicationCall.setName(input: SetNameIn): SetNameOut { + val user = Board.rename(input.displayName) + keelRealtime.invalidate("page:harbor.home", path = "/") // flavor (b) + return SetNameOut(user) +} +``` + +`publish` encodes with the registered serializer; unknown or `IN`-only ids +throw. `invalidate(channel, path, only, except)` sends the visit-shaped hint. +`send(sid, …)` targets one connection. + +## Subscribe in a pack + +`@KeelEvent` on a `@Serializable` class is the contract: Typegen emits the +payload into `Events` (`HarborEvents["harbor.message"]`). The client +side is the core `realtime` singleton plus one lifecycle helper per adapter. +`useKeelEvent` subscribes for the component's lifetime and keeps the latest +handler, so inline closures never resubscribe. + +([]) + +useKeelEvent("harbor.message", (item) => { + liveFeed = [item, ...liveFeed] +}) + +function announceTyping(displayName: string) { + void realtime.send("harbor.typing", { displayName }) +}`} + js={`import { realtime, useKeelEvent } from "@kolektiv/keel-svelte" + +let liveFeed = $state([]) + +useKeelEvent("harbor.message", (item) => { + liveFeed = [item, ...liveFeed] +}) + +function announceTyping(displayName) { + void realtime.send("harbor.typing", { displayName }) +}`} +/> + + +In React and Preact, `useKeelEvent` is a hook; the latest handler wins. + +```tsx +import { useKeelEvent } from "@kolektiv/keel-react" +import type { HarborEvents } from "../lib/page-types" + +useKeelEvent("harbor.message", (item) => { + setItems((current) => [item, ...current]) +}) +``` + + + +In Vue, `useKeelEvent` subscribes in the component scope and releases on +scope dispose. + +```vue + +``` + + + +Solid's `useKeelEvent` registers cleanup with the owner; read signals inside +the handler. + +```tsx +import { useKeelEvent } from "@kolektiv/keel-solid" +import type { HarborEvents } from "../lib/page-types" + +const [items, setItems] = createSignal([]) +useKeelEvent("harbor.message", (item) => { + setItems([item, ...items()]) +}) +``` + + + +Lit gets a `ReactiveController`; `useKeelEvent` is the convenience wrapper. + +```ts +import { useKeelEvent, type RealtimeMessage } from "@kolektiv/keel-lit" +import type { HarborEvents } from "../lib/page-types" + +export class HarborFeed extends LitElement { + constructor() { + super() + useKeelEvent(this, "harbor.message", (item) => { + this.items = [item, ...this.items] + }) + } +} +``` + + + +Angular injects the subscription and releases it with the injector. + +```ts +import { injectKeelEvent } from "@kolektiv/keel-angular" +import type { HarborEvents } from "../lib/page-types" + +injectKeelEvent("harbor.message", (item) => { + this.items.update((current) => [item, ...current]) +}) +``` + + +## Channels + +Channels are how the host targets traffic; the client only asks to listen. + +- The client automatically holds `page:` and follows the seed as it + changes. Disable with `realtime.configure({ autoChannels: false })` or add + your own with `channels`. +- `realtime.subscribe(channel)` returns a release function; ref-counted, so + several components can hold the same channel. +- `realtime.configure({ channels: (seed) => [...] })` adds seed-derived + channels. +- Every channel is authorized at subscribe time with the same session cookies + as visits. A denied channel means no events, not an error page. + +## Invalidate + +When an `invalidate` envelope arrives and no handler is registered, the +client reloads the current page with +`router.reload({ preserveState: true })` — path, `only`, and `except` from +the envelope are honored. Registering `realtime.onInvalidate(handler)` +takes over, which is how a pack can merge partial state without a visit. + +## Reconnect + +`realtime.connect()` is idempotent. With `transport: "auto"` the client tries +WebSocket, falls back to SSE, and reconnects with exponential backoff plus +jitter (`minReconnectDelayMs` 500, `maxReconnectDelayMs` 15000). On every +re-open it resubscribes the channel set. + +Because there is no replay, a reconnection that followed a live connection +also rehydrates: `router.reload({ preserveState: true })`. Set +`resyncOnReconnect: false` to opt out. A first connect never reloads — the +document seed is already fresh. + +## Client surface + +| Member | Effect | +| --- | --- | +| `realtime.configure(options)` | transport, `url`, channels, backoff, resync, `reloadOnInvalidate` | +| `realtime.connect()` / `disconnect()` | open or close the transport | +| `realtime.subscribe(channel)` | hold a channel; returns a release function | +| `realtime.on(event, handler)` | typed events; returns a release function | +| `realtime.onInvalidate(handler)` | take over invalidation handling | +| `realtime.send(event, data)` | client-to-host event (WebSocket frame or SSE `POST`) | +| `realtime.status()` / `onStatus(fn)` | `idle`, `connecting`, `open`, `reconnecting`, `closed` | +| `realtime.sid()` / `lastSeen()` | stream id, last envelope timestamp | + +`realtime` is re-exported from every adapter package; `Harbor` opens two +browser windows to show posts and typing notices streaming in. diff --git a/docs/src/content/docs/implementing/framework-adapters.mdx b/docs/src/content/docs/implementing/framework-adapters.mdx index 13f9913..1b515fd 100644 --- a/docs/src/content/docs/implementing/framework-adapters.mdx +++ b/docs/src/content/docs/implementing/framework-adapters.mdx @@ -18,15 +18,15 @@ how each framework expresses reactivity, forms, and DOM access. Svelte is the docs default. Sections for the other frameworks still apply when you pick them in the navbar. Scroll to that heading, or keep this page as the full matrix. -| Framework | Package | Page state | Action / query | Components / directives | Guards | Mount | -| --- | --- | --- | --- | --- | --- | --- | -| Svelte 5 | `@kolektiv/keel-svelte` | `page()` store | `@tanstack/svelte-query` | `Link`, `Form`, `Head`, `use:keel` | `useNavigationGuard`, `useUnloadGuard` | `createPage` | -| React 18/19 | `@kolektiv/keel-react` | `usePage()` | `@tanstack/react-query`: `useAction`, `useKeelPageQuery` | `Link`, `Form`, `Head`, `useKeelAnchor` | `useNavigationGuard`, `useUnloadGuard` | `createPage` (`createRoot`, `flushSync`) | -| Vue 3 | `@kolektiv/keel-vue` | `usePage()` shallow ref | `@tanstack/vue-query` | SFC `Link`, `Form`, `Head`, `useKeelAnchor` | `useNavigationGuard`, `useUnloadGuard` | `createPage` (`createApp().mount`) | -| Solid 1.9 | `@kolektiv/keel-solid` | `usePage()` accessor | `@tanstack/solid-query` | JSX `Link`, `Form`, `Head`, `useKeelAnchor` | `useNavigationGuard`, `useUnloadGuard` | `createPage` (`render` + dispose) | -| Preact 10 | `@kolektiv/keel-preact` | `usePage()` | `@tanstack/preact-query` | JSX `Link`, `Form`, `Head`, `useKeelAnchor` | `useNavigationGuard`, `useUnloadGuard` | `createPage` (`render` / `render(null)`) | -| Lit 3 | `@kolektiv/keel-lit` | `KeelElement.page` / `usePage` controller | `@tanstack/query-core` controllers: `KeelActionController`, `KeelPageQueryController` | ``, `form()` helper, ``, `keelAnchor` | controllers | `createPage` (`render`) | -| Angular 19 | `@kolektiv/keel-angular` | `injectKeelPage()` signal | `@tanstack/angular-query-experimental` | `[keelLink]`, `[keelAnchor]`, `[keelForm]`, `KeelHead` | `injectNavigationGuard`, `injectUnloadGuard` | `createPage` (`createApplication` + `createComponent`/`attachView`) | +| Framework | Package | Page state | Action / query | Components / directives | Guards | Realtime | Mount | +| --- | --- | --- | --- | --- | --- | --- | --- | +| Svelte 5 | `@kolektiv/keel-svelte` | `page()` store | `@tanstack/svelte-query` | `Link`, `Form`, `Head`, `use:keel` | `useNavigationGuard`, `useUnloadGuard` | `useKeelEvent`, `realtime` | `createPage` | +| React 18/19 | `@kolektiv/keel-react` | `usePage()` | `@tanstack/react-query`: `useAction`, `useKeelPageQuery` | `Link`, `Form`, `Head`, `useKeelAnchor` | `useNavigationGuard`, `useUnloadGuard` | `useKeelEvent`, `realtime` | `createPage` (`createRoot`, `flushSync`) | +| Vue 3 | `@kolektiv/keel-vue` | `usePage()` shallow ref | `@tanstack/vue-query` | SFC `Link`, `Form`, `Head`, `useKeelAnchor` | `useNavigationGuard`, `useUnloadGuard` | `useKeelEvent`, `realtime` | `createPage` (`createApp().mount`) | +| Solid 1.9 | `@kolektiv/keel-solid` | `usePage()` accessor | `@tanstack/solid-query` | JSX `Link`, `Form`, `Head`, `useKeelAnchor` | `useNavigationGuard`, `useUnloadGuard` | `useKeelEvent`, `realtime` | `createPage` (`render` + dispose) | +| Preact 10 | `@kolektiv/keel-preact` | `usePage()` | `@tanstack/preact-query` | JSX `Link`, `Form`, `Head`, `useKeelAnchor` | `useNavigationGuard`, `useUnloadGuard` | `useKeelEvent`, `realtime` | `createPage` (`render` / `render(null)`) | +| Lit 3 | `@kolektiv/keel-lit` | `KeelElement.page` / `usePage` controller | `@tanstack/query-core` controllers: `KeelActionController`, `KeelPageQueryController` | ``, `form()` helper, ``, `keelAnchor` | controllers | `KeelEventController`, `useKeelEvent`, `realtime` | `createPage` (`render`) | +| Angular 19 | `@kolektiv/keel-angular` | `injectKeelPage()` signal | `@tanstack/angular-query-experimental` | `[keelLink]`, `[keelAnchor]`, `[keelForm]`, `KeelHead` | `injectNavigationGuard`, `injectUnloadGuard` | `injectKeelEvent`, `realtime` | `createPage` (`createApplication` + `createComponent`/`attachView`) | The first adapter was Svelte 5. The other six bindings copy its contract rather than inventing a second one. @@ -49,6 +49,8 @@ subscription, refs, signals, controllers). `pageQueryKey(path)` (`["keel", "page", path]`). Actions invalidate the root key with `refetchType: "none"` because the follow-up visit rehydrates it. +**Realtime.** `realtime` (the core client) is re-exported from every adapter; the lifecycle helper is `useKeelEvent` everywhere except Angular's `injectKeelEvent` (Lit also exposes the underlying `KeelEventController`). Each helper subscribes for the host/component lifetime, keeps the latest handler, and releases on unmount. See Realtime. + **Visit interception.** `Link` and the anchor helpers intercept unmodified left-clicks only. Modified clicks, non-left buttons, `defaultPrevented`, and GET visits into `target="_blank"` fall through to the browser. Prefetch is diff --git a/docs/src/content/docs/implementing/host-adapter.mdx b/docs/src/content/docs/implementing/host-adapter.mdx index 5207f5d..c6a4ae6 100644 --- a/docs/src/content/docs/implementing/host-adapter.mdx +++ b/docs/src/content/docs/implementing/host-adapter.mdx @@ -91,6 +91,32 @@ the same behaviors however it likes. | `watchPacks` | `false` | Poll file/directory packs and swap on change | | `packWatchIntervalMs` | `500` | Watcher poll interval (minimum 50 ms); see Pack hot reload | +## Realtime + +Realtime is off until `keel { realtime { … } }` is present and the host +installed Ktor's `SSE` and/or `WebSockets` plugin. The same `/__keel/events` +path serves the SSE stream, the WebSocket upgrade, and the `POST` sends SSE +clients use. `call.keelRealtime` (or `application.keelRealtime`) publishes +typed events and invalidations; the client rehydrates through normal visits, +so a non-Ktor host only has to speak the envelope in +Wire protocol. + +```kotlin +install(WebSockets) +install(SSE) + +keel { + realtime { + event("harbor.message", EventDirection.OUT) + on("harbor.typing") { input -> call.keelRealtime.publish("page:harbor.home", "harbor.typing", input) } + authorize = { call, channel -> channel.startsWith("page:") || Board.viewer(call) != null } + heartbeatSeconds = 25 + } +} +``` + +Guides and knobs: Realtime. + ## CSRF Apply the diff --git a/docs/src/content/docs/implementing/protocol.mdx b/docs/src/content/docs/implementing/protocol.mdx index 5430ac5..8802f3a 100644 --- a/docs/src/content/docs/implementing/protocol.mdx +++ b/docs/src/content/docs/implementing/protocol.mdx @@ -90,6 +90,12 @@ the same `keel/1` JSON Typegen writes offline: "out": "SetNameOut" } }, + "events": { + "harbor.message": { + "direction": "out", + "type": "FeedItem" + } + }, "types": { "HomePage": { "kind": "object", @@ -109,6 +115,46 @@ See Typegen. `POST /__keel/action/{id}` with a JSON body. Success: `{ "data": … }`. Validation: 422 `{ "errors": … }`. Unknown id: 404. +## Realtime + +Opt-in. `GET /__keel/events` is an SSE stream when the host installed the +`SSE` plugin, and the same path upgrades to a WebSocket when `WebSockets` is +installed. `POST /__keel/events` carries the same envelope for SSE clients +(WebSocket clients use frames). Writes use the action CSRF policy. + +The envelope is boring JSON, versioned with `v: 1`: + +```json +{ + "v": 1, + "type": "event", + "sid": "rt-…", + "channel": "page:harbor.home", + "event": "harbor.message", + "data": { "id": "…", "body": "ahoy" }, + "id": "client-correlation" +} +``` + +| Field | Meaning | +| --- | --- | +| `type` | `ready`, `event`, `invalidate`, `error`, `ping` (host → client); `subscribe`, `unsubscribe`, `send`, `ping` (client → host) | +| `sid` | Stream id from `ready`; SSE clients echo it on `POST` | +| `channel` / `channels` | Routing unit / subscribe list | +| `event` / `data` | Event id and payload from the typed registry | +| `id` | Optional client correlation id | +| `error` | Server-reported rejection (unknown event, denied channel) | + +- `ready` lists the accepted channels; `error` reports a denied one without + dropping the connection. +- **Subscriptions are ephemeral.** Reconnect means resubscribe; events are + not replayed. `invalidate` tells the client to rehydrate the seed with a + normal visit, so no stream state is authoritative. +- Channel ids are host-owned strings (`page:…`, `user:…`, or anything else). + Authorization happens at subscribe time with the caller's cookies. +- Heartbeats are `ping` envelopes; hosts should keep them on so dead + connections are reaped. + ## Path grammar Owned by Keel, not inherited from a framework: diff --git a/docs/src/content/docs/implementing/typegen.mdx b/docs/src/content/docs/implementing/typegen.mdx index c1185ef..6568f14 100644 --- a/docs/src/content/docs/implementing/typegen.mdx +++ b/docs/src/content/docs/implementing/typegen.mdx @@ -26,8 +26,16 @@ export type HarborPageId = keyof HarborPages export interface HarborActions { "harbor.setName": { in: SetNameIn; out: SetNameOut } } +export interface HarborEvents { + "harbor.message": FeedItem +} +export type HarborEventId = keyof HarborEvents ``` +`@KeelEvent` classes and `@KeelEvent` host functions feed the events section; +directions (`in`, `out`, `both`) live in the JSON document because the +TypeScript payload map is direction-agnostic. + ## JSON `--emit-json path` writes a language-agnostic document another codegen @@ -53,6 +61,12 @@ at `GET /__keel/schema`. "out": "SetNameOut" } }, + "events": { + "harbor.message": { + "direction": "out", + "type": "FeedItem" + } + }, "types": { "HomePage": { "kind": "object", diff --git a/gradle.properties b/gradle.properties index c81d3fe..a838c95 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,5 +1,5 @@ group=computer.kolektiv.keel -version=0.1.2 +version=0.2.1 org.gradle.jvmargs=-Xmx1g -Dfile.encoding=UTF-8 org.gradle.daemon=false diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 006e103..6cd335b 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -3,7 +3,7 @@ kotlin = "2.2.21" serialization = "1.8.0" coroutines = "1.10.1" junit = "5.11.4" -ktor = "3.1.3" +ktor = "3.5.2" slf4j = "2.0.17" [libraries] @@ -15,6 +15,10 @@ junit-jupiter-engine = { module = "org.junit.jupiter:junit-jupiter-engine", vers ktor-server-core = { module = "io.ktor:ktor-server-core", version.ref = "ktor" } ktor-server-netty = { module = "io.ktor:ktor-server-netty", version.ref = "ktor" } ktor-server-test-host = { module = "io.ktor:ktor-server-test-host", version.ref = "ktor" } +ktor-server-sse = { module = "io.ktor:ktor-server-sse", version.ref = "ktor" } +ktor-server-websockets = { module = "io.ktor:ktor-server-websockets", version.ref = "ktor" } +ktor-client-websockets = { module = "io.ktor:ktor-client-websockets", version.ref = "ktor" } +ktor-client-cio = { module = "io.ktor:ktor-client-cio", version.ref = "ktor" } slf4j-simple = { module = "org.slf4j:slf4j-simple", version.ref = "slf4j" } [plugins] diff --git a/ktor/build.gradle.kts b/ktor/build.gradle.kts index 9592859..d908578 100644 --- a/ktor/build.gradle.kts +++ b/ktor/build.gradle.kts @@ -11,7 +11,12 @@ publishing { dependencies { api(project(":lib")) api(libs.ktor.server.core) + api(libs.ktor.server.sse) + api(libs.ktor.server.websockets) testImplementation(libs.ktor.server.test.host) + testImplementation(libs.ktor.server.netty) + testImplementation(libs.ktor.client.websockets) + testImplementation(libs.ktor.client.cio) testImplementation(libs.junit.jupiter) testRuntimeOnly(libs.junit.jupiter.engine) testRuntimeOnly("org.junit.platform:junit-platform-launcher") diff --git a/ktor/src/main/kotlin/dev/kolektiv/keel/ktor/KeelConfig.kt b/ktor/src/main/kotlin/dev/kolektiv/keel/ktor/KeelConfig.kt index df30c39..9f0256a 100644 --- a/ktor/src/main/kotlin/dev/kolektiv/keel/ktor/KeelConfig.kt +++ b/ktor/src/main/kotlin/dev/kolektiv/keel/ktor/KeelConfig.kt @@ -4,11 +4,15 @@ import dev.kolektiv.keel.Keel import dev.kolektiv.keel.action.ActionDiscovery import dev.kolektiv.keel.action.ActionRegistry import dev.kolektiv.keel.bundle.FrontendBundle +import dev.kolektiv.keel.event.EventRegistry +import dev.kolektiv.keel.ktor.realtime.RealtimeDsl +import dev.kolektiv.keel.ktor.realtime.RealtimeRequest import dev.kolektiv.keel.page.PageMethod import dev.kolektiv.keel.page.PageRegistry import dev.kolektiv.keel.security.CsrfPolicy import io.ktor.http.Parameters import io.ktor.server.application.ApplicationCall +import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject fun interface SharedProvider { @@ -92,6 +96,29 @@ class KeelConfig { internal val actionRegistry: ActionRegistry = ActionRegistry() @PublishedApi internal val actionHandlers: MutableMap Any> = linkedMapOf() + @PublishedApi + internal val eventRegistry: EventRegistry = EventRegistry() + @PublishedApi + internal val eventHandlers: MutableMap Unit> = linkedMapOf() + + @PublishedApi + internal var realtimeDsl: RealtimeDsl? = null + + /** + * Realtime transports (`GET`/`POST /__keel/events`, WebSocket upgrade on + * the same path). Null — the default — means realtime is off: no + * endpoints and no event registry entries. Enabling requires the host to + * `install(SSE)` and/or `install(WebSockets)` before `keel { }`. + */ + val realtime: RealtimeDsl? get() = realtimeDsl + + /** + * Opt in to realtime: declare typed events and client-sent handlers, + * authorize channels, tune the keepalive. + */ + fun realtime(block: RealtimeDsl.() -> Unit) { + realtimeDsl = RealtimeDsl(eventRegistry, eventHandlers).apply(block) + } fun pages(block: PagesDsl.() -> Unit) { PagesDsl(registry, handlers).block() diff --git a/ktor/src/main/kotlin/dev/kolektiv/keel/ktor/KeelEngine.kt b/ktor/src/main/kotlin/dev/kolektiv/keel/ktor/KeelEngine.kt index d54abec..fdcfd76 100644 --- a/ktor/src/main/kotlin/dev/kolektiv/keel/ktor/KeelEngine.kt +++ b/ktor/src/main/kotlin/dev/kolektiv/keel/ktor/KeelEngine.kt @@ -5,6 +5,8 @@ import dev.kolektiv.keel.KeelJson import dev.kolektiv.keel.bundle.BundleOrigin import dev.kolektiv.keel.bundle.FrontendBundle import dev.kolektiv.keel.bundle.UnknownPageInBundleException +import dev.kolektiv.keel.ktor.realtime.KeelRealtime +import dev.kolektiv.keel.ktor.realtime.installRealtime import dev.kolektiv.keel.page.PageBinding import dev.kolektiv.keel.page.PageMethod import dev.kolektiv.keel.page.PageRegistry @@ -83,12 +85,15 @@ class AmbiguousPackException(ids: List) : IllegalStateException( ) @PublishedApi -internal class KeelEngine(private val config: KeelConfig) { +internal class KeelEngine(internal val config: KeelConfig) { private val packPrefix: String = config.packUrlPrefix.trimEnd('/') private val bundleOrder = CopyOnWriteArrayList() private val configuredOrder = CopyOnWriteArrayList() private val bundlesById = ConcurrentHashMap() + /** Live realtime bus; non-null when `keel { realtime { } }` is configured. */ + internal var realtimeHub: KeelRealtime? = null + private val swapLock = Any() private val reloadMutex = Mutex() private val watchFingerprints = ConcurrentHashMap() @@ -133,6 +138,7 @@ internal class KeelEngine(private val config: KeelConfig) { } } } + installRealtime(application) startPackWatcher(application) } @@ -391,7 +397,7 @@ internal class KeelEngine(private val config: KeelConfig) { } private suspend fun respondSchema(call: ApplicationCall) { - val raw = Typegen.emitJson(config.registry, config.actionRegistry) + val raw = Typegen.emitJson(config.registry, config.actionRegistry, config.eventRegistry) call.respondText(raw, ContentType.Application.Json, HttpStatusCode.OK) } @@ -575,7 +581,7 @@ internal class KeelEngine(private val config: KeelConfig) { private fun csrfPolicy() = config.csrf ?: SameOriginCsrfPolicy(config.csrfAllowedOrigins) - private suspend fun guardCsrf(call: ApplicationCall): Boolean { + internal suspend fun guardCsrf(call: ApplicationCall): Boolean { val verdict = csrfPolicy().check( CsrfRequest( method = call.request.httpMethod.value, diff --git a/ktor/src/main/kotlin/dev/kolektiv/keel/ktor/realtime/KeelRealtime.kt b/ktor/src/main/kotlin/dev/kolektiv/keel/ktor/realtime/KeelRealtime.kt new file mode 100644 index 0000000..7b5346b --- /dev/null +++ b/ktor/src/main/kotlin/dev/kolektiv/keel/ktor/realtime/KeelRealtime.kt @@ -0,0 +1,304 @@ +package dev.kolektiv.keel.ktor.realtime + +import dev.kolektiv.keel.KeelJson +import dev.kolektiv.keel.event.EventDirectionException +import dev.kolektiv.keel.event.UnknownEventException +import dev.kolektiv.keel.realtime.KeelRealtimeEnvelope +import dev.kolektiv.keel.ktor.KeelConfig +import dev.kolektiv.keel.ktor.PageValidationException +import io.ktor.server.application.ApplicationCall +import io.ktor.server.application.log +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.channels.BufferOverflow +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.channels.ReceiveChannel +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlinx.serialization.KSerializer +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.decodeFromJsonElement +import java.util.Collections +import java.util.UUID +import java.util.concurrent.ConcurrentHashMap + +/** + * A live realtime connection: one WebSocket session, or one SSE stream + * addressed by [id] (the `sid` in the ready envelope). Channels are the + * routing unit; the outbound channel is bounded and drops the oldest + * envelope when a slow client falls behind, so publishing never blocks. + */ +internal class RealtimeConnection( + val id: String, + val call: ApplicationCall, + val transport: String, +) { + val channels: MutableSet = Collections.synchronizedSet(LinkedHashSet()) + + private val outbound = Channel( + capacity = 256, + onBufferOverflow = BufferOverflow.DROP_OLDEST, + ) + + val outgoing: ReceiveChannel get() = outbound + + fun offer(envelope: KeelRealtimeEnvelope): Boolean = outbound.trySend(envelope).isSuccess + + fun close() { + outbound.close() + } +} + +/** Channels a subscribe / unsubscribe request added and had rejected. */ +internal class SubscribeOutcome( + val channels: List, + val accepted: List, + val denied: List, +) + +/** + * Host-facing realtime bus. Publish typed events or invalidations from + * actions and loaders; the hub fans them out to every connection subscribed + * to the channel. Keel owns routing, auth, and reconnect semantics — clients + * subscribe by channel id and rehydrate through normal visits. + * + * Reach it from a call with `call.keelRealtime` or from the application with + * `application.keelRealtime`. + */ +class KeelRealtime internal constructor(private val config: KeelConfig) { + private val connections = ConcurrentHashMap() + + private val realtime: RealtimeDsl + get() = config.realtime + ?: throw IllegalStateException("realtime is not configured on this keel { } block") + + /** Number of live connections, optionally only those on [channel]. */ + fun connectionCount(channel: String? = null): Int = + if (channel == null) connections.size else connections.values.count { channel in it.channels } + + /** Stream ids (`sid`) of live connections. */ + fun connections(): Set = connections.keys.toSet() + + /** Every channel with at least one subscriber right now. */ + fun channels(): Set = connections.values.flatMap { it.channels }.toSet() + + /** + * Publishes a typed event to [channel]. [data] is encoded with the + * serializer registered for [event]; returns how many connections the + * envelope was queued for. Unknown or `IN`-only events throw + * [UnknownEventException] / [EventDirectionException]. + */ + fun publish(channel: String, event: String, data: Any? = null): Int { + val binding = config.eventRegistry.outgoing(event) + val payload = data?.let { encode(binding.payload, it) } + return broadcast(KeelRealtimeEnvelope.event(channel, event, payload)) + } + + /** + * Publishes an already-encoded payload to [channel]. The event must still + * be registered and publishable, so packs keep a typed contract. + */ + fun publishJson(channel: String, event: String, data: JsonElement? = null): Int { + config.eventRegistry.outgoing(event) + return broadcast(KeelRealtimeEnvelope.event(channel, event, data)) + } + + /** Publishes a typed event to one connection. Returns false for a stale sid. */ + fun send(sid: String, event: String, data: Any? = null): Boolean { + val connection = connections[sid] ?: return false + val binding = config.eventRegistry.outgoing(event) + val payload = data?.let { encode(binding.payload, it) } + return connection.offer(KeelRealtimeEnvelope.event(channel = "", event = event, data = payload)) + } + + /** + * Tells every connection subscribed to [channel] to rehydrate the seed + * with a normal visit. [path], [only], and [except] narrow the visit the + * way a visit request does. Returns the delivery count. + */ + fun invalidate( + channel: String, + path: String? = null, + only: List? = null, + except: List? = null, + ): Int = broadcast(KeelRealtimeEnvelope.invalidate(channel, path, only, except)) + + // --- transport plumbing --------------------------------------------- + + internal fun open(call: ApplicationCall, transport: String): RealtimeConnection { + val connection = RealtimeConnection( + id = "rt-${UUID.randomUUID().toString().take(12)}", + call = call, + transport = transport, + ) + connections[connection.id] = connection + return connection + } + + internal fun close(connection: RealtimeConnection) { + connections.remove(connection.id) + connection.close() + } + + internal fun ready(connection: RealtimeConnection): KeelRealtimeEnvelope = + KeelRealtimeEnvelope.ready(connection.id, connection.channels.toList()) + + internal fun startHeartbeat(scope: CoroutineScope, connection: RealtimeConnection): Job? { + val seconds = realtime.heartbeatSeconds + if (seconds <= 0) return null + return scope.launch { + while (isActive) { + delay(seconds * 1000) + connection.offer(KeelRealtimeEnvelope.ping()) + } + } + } + + /** Applies a subscribe request, authorizing each channel for [call]. */ + internal suspend fun subscribe( + connection: RealtimeConnection, + requested: List, + call: ApplicationCall, + ): SubscribeOutcome { + val accepted = mutableListOf() + val denied = mutableListOf() + for (channel in requested.distinct()) { + if (channel.isBlank()) continue + if (authorize(call, channel)) { + connection.channels.add(channel) + accepted.add(channel) + } else { + denied.add(channel) + } + } + return SubscribeOutcome(connection.channels.toList(), accepted, denied) + } + + internal fun unsubscribe(connection: RealtimeConnection, requested: List): List { + val removed = requested.filter { connection.channels.remove(it) } + return removed + } + + /** Handles a subscribe / unsubscribe / send envelope from a live stream. */ + internal suspend fun handle( + connection: RealtimeConnection, + envelope: KeelRealtimeEnvelope, + call: ApplicationCall, + ) { + when (envelope.type) { + KeelRealtimeEnvelope.PING -> connection.offer(KeelRealtimeEnvelope.ping()) + KeelRealtimeEnvelope.SUBSCRIBE -> { + val outcome = subscribe(connection, envelope.channels.orEmpty(), call) + acknowledge(connection, outcome) + } + KeelRealtimeEnvelope.UNSUBSCRIBE -> { + unsubscribe(connection, envelope.channels.orEmpty()) + connection.offer(ready(connection)) + } + KeelRealtimeEnvelope.SEND -> { + try { + invokeSend(call, envelope) + } catch (cancelled: CancellationException) { + throw cancelled + } catch (failure: Throwable) { + connection.offer(KeelRealtimeEnvelope.error(messageFor(failure), envelope.channel)) + } + } + else -> connection.offer( + KeelRealtimeEnvelope.error("unsupported envelope type '${envelope.type}'", envelope.channel), + ) + } + } + + /** Subscribe request over plain HTTP (SSE clients POST it). */ + internal suspend fun subscribeBySid( + call: ApplicationCall, + sid: String?, + channels: List, + ): SubscribeOutcome? { + val connection = sid?.let { connections[it] } ?: return null + val outcome = subscribe(connection, channels, call) + acknowledge(connection, outcome) + return outcome + } + + /** Unsubscribe request over plain HTTP (SSE clients POST it). Returns the remaining channels. */ + internal fun unsubscribeBySid(sid: String?, channels: List): List? { + val connection = sid?.let { connections[it] } ?: return null + unsubscribe(connection, channels) + connection.offer(ready(connection)) + return connection.channels.toList() + } + + /** + * Runs a client `send` envelope through the registered handler. Throws + * [UnknownEventException] / [EventDirectionException] for unregistered or + * inbound-forbidden events, [PageValidationException] for domain errors, + * and [IllegalArgumentException] for a missing event id. + */ + internal suspend fun invokeSend(call: ApplicationCall, envelope: KeelRealtimeEnvelope) { + val id = envelope.event?.takeIf { it.isNotBlank() } + ?: throw IllegalArgumentException("send envelope requires an event id") + config.eventRegistry.incoming(id) + val handler = config.eventHandlers[id] ?: throw UnknownEventException(id) + val payload = envelope.data ?: JsonNull + val request = RealtimeRequest( + call = call, + event = id, + channel = envelope.channel, + correlationId = envelope.id, + data = payload, + ) + RealtimeRequest.with(request) { + request.handler(payload) + } + } + + private fun acknowledge(connection: RealtimeConnection, outcome: SubscribeOutcome) { + connection.offer(ready(connection)) + for (channel in outcome.denied) { + connection.offer(KeelRealtimeEnvelope.error("not authorized for channel '$channel'", channel)) + } + } + + private suspend fun authorize(call: ApplicationCall, channel: String): Boolean { + val policy = realtime.authorize ?: return true + return try { + policy(call, channel) + } catch (cancelled: CancellationException) { + throw cancelled + } catch (failure: Throwable) { + call.application.log.warn("keel: realtime channel authorization failed for '$channel'", failure) + false + } + } + + private fun broadcast(envelope: KeelRealtimeEnvelope): Int { + var delivered = 0 + for (connection in connections.values) { + val channel = envelope.channel + if (channel != null && channel.isNotEmpty() && channel !in connection.channels) continue + connection.offer(envelope) + delivered += 1 + } + return delivered + } + + @Suppress("UNCHECKED_CAST") + private fun encode(serializer: KSerializer<*>, value: Any): JsonElement = + KeelJson.codec.encodeToJsonElement(serializer as KSerializer, value) + + private fun messageFor(failure: Throwable): String = when (failure) { + is PageValidationException -> failure.errors.entries.joinToString("; ") { (field, messages) -> + "$field: ${messages.joinToString(", ")}" + } + else -> failure.message ?: "realtime handler failed" + } + + internal fun closeAll() { + for (connection in connections.values) close(connection) + } +} diff --git a/ktor/src/main/kotlin/dev/kolektiv/keel/ktor/realtime/RealtimeDsl.kt b/ktor/src/main/kotlin/dev/kolektiv/keel/ktor/realtime/RealtimeDsl.kt new file mode 100644 index 0000000..c205528 --- /dev/null +++ b/ktor/src/main/kotlin/dev/kolektiv/keel/ktor/realtime/RealtimeDsl.kt @@ -0,0 +1,139 @@ +package dev.kolektiv.keel.ktor.realtime + +import dev.kolektiv.keel.KeelJson +import dev.kolektiv.keel.event.EventDirection +import dev.kolektiv.keel.event.EventDiscovery +import dev.kolektiv.keel.event.EventRegistry +import io.ktor.server.application.ApplicationCall +import kotlinx.coroutines.asContextElement +import kotlinx.coroutines.withContext +import kotlinx.serialization.KSerializer +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.decodeFromJsonElement +import kotlinx.serialization.serializer + +/** + * Context handed to a realtime event handler. Cookie/session state is on + * [call]; [channel] is the channel the client addressed (optional), and + * [correlationId] echoes the client's envelope id. + */ +class RealtimeRequest internal constructor( + val call: ApplicationCall, + val event: String, + val channel: String?, + val correlationId: String?, + val data: JsonElement?, +) { + /** The envelope payload as received; [JsonNull] when the client sent none. */ + fun receiveJson(): JsonElement = data ?: JsonNull + + /** The typed payload the registry declares for [data]. */ + inline fun decode(): T = + KeelJson.codec.decodeFromJsonElement(serializer(), receiveJson()) + + fun decode(serializer: KSerializer<*>): Any { + @Suppress("UNCHECKED_CAST") + return KeelJson.codec.decodeFromJsonElement(serializer as KSerializer, receiveJson()) + } + + companion object { + private val current = ThreadLocal() + + /** + * The realtime event currently running on this thread. Annotated + * `@KeelEvent` functions use this for cookies/session without taking + * [call] as an input field. + */ + fun current(): RealtimeRequest = + current.get() ?: error("not inside a Keel realtime event handler") + + internal suspend fun with(request: RealtimeRequest, block: suspend () -> T): T = + withContext(current.asContextElement(request)) { block() } + } +} + +/** + * Realtime opt-in for `keel { }`. Declares the typed events the host speaks + * and how connections are authorized. Endpoints only exist when this block is + * present and the host installed the matching Ktor plugins first. + */ +class RealtimeDsl @PublishedApi internal constructor( + @PublishedApi internal val registry: EventRegistry, + @PublishedApi internal val handlers: MutableMap Unit>, +) { + /** + * Channel authorization, evaluated at subscribe time with the call that + * asks (the handshake call for the query string, the POST call for + * `subscribe` envelopes). Default allows every channel. + */ + var authorize: (suspend (ApplicationCall, String) -> Boolean)? = null + + /** + * Server keepalive interval in seconds. `ping` envelopes keep proxies + * from closing idle streams and let clients notice dead connections. + * `0` disables. Default 25. + */ + var heartbeatSeconds: Long = 25 + + /** Declares a typed event payload without a handler (typically `OUT`). */ + inline fun event( + id: String, + direction: EventDirection = EventDirection.BOTH, + ) { + registry.event(id, direction) + } + + /** + * Registers a handler for client-sent events. Registers the binding as + * [EventDirection.IN] when the event is not declared yet; a declared + * `OUT` event is rejected. + */ + inline fun on( + id: String, + noinline handler: suspend RealtimeRequest.(I) -> Unit, + ) { + val existing = registry.find(id) + if (existing == null) { + registry.event(id, EventDirection.IN) + } else { + check(existing.direction != EventDirection.OUT) { + "event '$id' is declared OUT and cannot have a client handler; use IN or BOTH" + } + check(existing.payload.descriptor == serializer().descriptor) { + "event '$id' is declared with a different payload type" + } + } + handlers[id] = { element -> + @Suppress("UNCHECKED_CAST") + handler( + KeelJson.codec.decodeFromJsonElement( + registry.get(id).payload as KSerializer, + element, + ), + ) + } + } + + /** + * Registers `@KeelEvent` functions on [hosts] (objects or classes). Each + * function takes one payload and returns `Unit`; an + * `ApplicationCall.(Payload) -> Unit` extension gets [RealtimeRequest.call] + * as `this`. + */ + fun events(vararg hosts: Any) { + for (host in hosts) { + for (discovered in EventDiscovery.discover(host)) { + registry.register(discovered.binding) + handlers[discovered.id] = { element -> + @Suppress("UNCHECKED_CAST") + val payload = KeelJson.codec.decodeFromJsonElement( + discovered.payload as KSerializer, + element, + ) + discovered.invoke(payload, extension = call) + } + } + } + } +} diff --git a/ktor/src/main/kotlin/dev/kolektiv/keel/ktor/realtime/RealtimeRoutes.kt b/ktor/src/main/kotlin/dev/kolektiv/keel/ktor/realtime/RealtimeRoutes.kt new file mode 100644 index 0000000..bb00a2a --- /dev/null +++ b/ktor/src/main/kotlin/dev/kolektiv/keel/ktor/realtime/RealtimeRoutes.kt @@ -0,0 +1,268 @@ +package dev.kolektiv.keel.ktor.realtime + +import dev.kolektiv.keel.Keel +import dev.kolektiv.keel.KeelJson +import dev.kolektiv.keel.event.EventDirectionException +import dev.kolektiv.keel.event.UnknownEventException +import dev.kolektiv.keel.ktor.KeelEngine +import dev.kolektiv.keel.ktor.PageValidationException +import dev.kolektiv.keel.realtime.KeelRealtimeEnvelope +import io.ktor.http.ContentType +import io.ktor.http.HttpStatusCode +import io.ktor.server.application.Application +import io.ktor.server.application.ApplicationCall +import io.ktor.server.application.pluginOrNull +import io.ktor.server.request.receiveText +import io.ktor.server.response.respondText +import io.ktor.server.routing.post +import io.ktor.server.routing.routing +import io.ktor.server.sse.SSE +import io.ktor.server.sse.ServerSSESession +import io.ktor.server.sse.sse +import io.ktor.server.websocket.DefaultWebSocketServerSession +import io.ktor.server.websocket.WebSockets +import io.ktor.server.websocket.webSocket +import io.ktor.sse.ServerSentEvent +import io.ktor.util.AttributeKey +import io.ktor.websocket.Frame +import io.ktor.websocket.readText +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.launch +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonArray +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put + +/** `keel { realtime { } }` is configured but neither Ktor transport plugin is installed. */ +class KeelRealtimeMissingPluginException : IllegalStateException( + "keel { realtime { } } needs a transport: install(SSE) and/or install(WebSockets) before keel { }", +) + +/** `call.keelRealtime` was read on a host that never opted in. */ +class KeelRealtimeNotConfiguredException : IllegalStateException( + "realtime is not configured: add keel { realtime { } } and install(SSE) / install(WebSockets)", +) + +internal val KeelRealtimeKey = AttributeKey("KeelRealtime") + +/** The realtime bus for this application; throws when realtime is not configured. */ +val Application.keelRealtime: KeelRealtime + get() = attributes.getOrNull(KeelRealtimeKey) ?: throw KeelRealtimeNotConfiguredException() + +/** The realtime bus, reachable from actions and page loaders. */ +val ApplicationCall.keelRealtime: KeelRealtime get() = application.keelRealtime + +internal fun KeelEngine.installRealtime(application: Application) { + if (config.realtime == null) return + val webSockets = application.pluginOrNull(WebSockets) != null + val sse = application.pluginOrNull(SSE) != null + if (!webSockets && !sse) throw KeelRealtimeMissingPluginException() + val hub = KeelRealtime(config) + realtimeHub = hub + application.attributes.put(KeelRealtimeKey, hub) + val engine = this + application.routing { + if (webSockets) { + webSocket(Keel.REALTIME_PATH) { + engine.handleRealtimeSocket(hub, this) + } + } + if (sse) { + sse(Keel.REALTIME_PATH) { + engine.handleRealtimeSse(hub, this) + } + } + post(Keel.REALTIME_PATH) { + engine.respondRealtimePost(hub, call) + } + } +} + +private suspend fun KeelEngine.handleRealtimeSocket( + hub: KeelRealtime, + session: DefaultWebSocketServerSession, +) { + val call = session.call + val connection = hub.open(call, "ws") + openConnection(hub, connection, call) + val heartbeat = hub.startHeartbeat(session, connection) + val writer = session.launch { + for (envelope in connection.outgoing) { + session.send(Frame.Text(encode(envelope))) + } + } + try { + for (frame in session.incoming) { + if (frame !is Frame.Text) continue + val envelope = try { + KeelJson.codec.decodeFromString(KeelRealtimeEnvelope.serializer(), frame.readText()) + } catch (failure: Throwable) { + if (failure is CancellationException) throw failure + connection.offer(KeelRealtimeEnvelope.error("malformed envelope")) + continue + } + hub.handle(connection, envelope, call) + } + } finally { + heartbeat?.cancel() + writer.cancel() + hub.close(connection) + } +} + +private suspend fun KeelEngine.handleRealtimeSse(hub: KeelRealtime, session: ServerSSESession) { + val call = session.call + val connection = hub.open(call, "sse") + openConnection(hub, connection, call) + val heartbeat = hub.startHeartbeat(session, connection) + try { + for (envelope in connection.outgoing) { + session.send( + ServerSentEvent( + data = encode(envelope), + event = envelope.type, + ), + ) + } + } finally { + heartbeat?.cancel() + hub.close(connection) + } +} + +/** Subscribes the query-string channels and queues the ready envelope. */ +private suspend fun openConnection( + hub: KeelRealtime, + connection: RealtimeConnection, + call: ApplicationCall, +) { + val requested = parseChannels(call.request.queryParameters["channels"]) + val outcome = hub.subscribe(connection, requested, call) + connection.offer(hub.ready(connection)) + for (channel in outcome.denied) { + connection.offer(KeelRealtimeEnvelope.error("not authorized for channel '$channel'", channel)) + } +} + +private suspend fun KeelEngine.respondRealtimePost(hub: KeelRealtime, call: ApplicationCall) { + if (!guardCsrf(call)) return + val text = call.receiveText() + val envelope = try { + KeelJson.codec.decodeFromString( + KeelRealtimeEnvelope.serializer(), + if (text.isBlank()) "{}" else text, + ) + } catch (failure: Throwable) { + if (failure is CancellationException) throw failure + respondEnvelopeErrors(call, HttpStatusCode.BadRequest, "envelope", "malformed JSON envelope") + return + } + when (envelope.type) { + KeelRealtimeEnvelope.SUBSCRIBE -> { + val outcome = hub.subscribeBySid(call, envelope.sid, envelope.channels.orEmpty()) + if (outcome == null) { + respondEnvelopeErrors(call, HttpStatusCode.NotFound, "sid", "unknown stream") + return + } + respondAccepted(call, envelope.sid, outcome.channels, outcome.accepted, outcome.denied) + } + KeelRealtimeEnvelope.UNSUBSCRIBE -> { + val channels = hub.unsubscribeBySid(envelope.sid, envelope.channels.orEmpty()) + if (channels == null) { + respondEnvelopeErrors(call, HttpStatusCode.NotFound, "sid", "unknown stream") + return + } + respondAccepted(call, envelope.sid, channels, envelope.channels.orEmpty(), emptyList()) + } + KeelRealtimeEnvelope.SEND -> { + try { + hub.invokeSend(call, envelope) + } catch (invalid: PageValidationException) { + respondValidationErrors(call, invalid) + return + } catch (unknown: UnknownEventException) { + respondEnvelopeErrors(call, HttpStatusCode.NotFound, "event", unknown.message ?: "unknown event") + return + } catch (direction: EventDirectionException) { + respondEnvelopeErrors(call, HttpStatusCode.NotFound, "event", direction.message ?: "unknown event") + return + } catch (illegal: IllegalArgumentException) { + respondEnvelopeErrors(call, HttpStatusCode.BadRequest, "event", illegal.message ?: "invalid send") + return + } + respondOk(call) + } + KeelRealtimeEnvelope.PING -> respondOk(call) + else -> respondEnvelopeErrors( + call, + HttpStatusCode.BadRequest, + "type", + "unsupported envelope type '${envelope.type}'", + ) + } +} + +private suspend fun respondOk(call: ApplicationCall) { + call.respondText( + KeelJson.codec.encodeToString(JsonObject.serializer(), buildJsonObject { put("ok", true) }), + ContentType.Application.Json, + HttpStatusCode.Accepted, + ) +} + +private suspend fun respondAccepted( + call: ApplicationCall, + sid: String?, + channels: List, + accepted: List, + denied: List, +) { + val payload = buildJsonObject { + put("sid", sid) + put("channels", buildJsonArray { channels.forEach { add(JsonPrimitive(it)) } }) + put("accepted", buildJsonArray { accepted.forEach { add(JsonPrimitive(it)) } }) + put("denied", buildJsonArray { denied.forEach { add(JsonPrimitive(it)) } }) + } + call.respondText( + KeelJson.codec.encodeToString(JsonObject.serializer(), payload), + ContentType.Application.Json, + HttpStatusCode.Accepted, + ) +} + +private suspend fun respondEnvelopeErrors( + call: ApplicationCall, + status: HttpStatusCode, + field: String, + message: String, +) { + val errors = JsonObject(mapOf(field to JsonArray(listOf(JsonPrimitive(message))))) + val payload = JsonObject(mapOf("errors" to errors)) + call.respondText( + KeelJson.codec.encodeToString(JsonObject.serializer(), payload), + ContentType.Application.Json, + status, + ) +} + +private suspend fun respondValidationErrors(call: ApplicationCall, invalid: PageValidationException) { + val errors = JsonObject( + invalid.errors.mapValues { (_, messages) -> + JsonArray(messages.map { JsonPrimitive(it) }) + }, + ) + val payload = JsonObject(mapOf("errors" to errors)) + call.respondText( + KeelJson.codec.encodeToString(JsonObject.serializer(), payload), + ContentType.Application.Json, + HttpStatusCode.UnprocessableEntity, + ) +} + +private fun parseChannels(raw: String?): List = + raw?.split(',')?.map { it.trim() }?.filter { it.isNotEmpty() }?.distinct().orEmpty() + +private fun encode(envelope: KeelRealtimeEnvelope): String = + KeelJson.codec.encodeToString(KeelRealtimeEnvelope.serializer(), envelope) diff --git a/ktor/src/test/kotlin/dev/kolektiv/keel/ktor/RealtimeServerTest.kt b/ktor/src/test/kotlin/dev/kolektiv/keel/ktor/RealtimeServerTest.kt new file mode 100644 index 0000000..06fea78 --- /dev/null +++ b/ktor/src/test/kotlin/dev/kolektiv/keel/ktor/RealtimeServerTest.kt @@ -0,0 +1,287 @@ +package dev.kolektiv.keel.ktor + +import dev.kolektiv.keel.KeelJson +import dev.kolektiv.keel.bundle.FrontendBundle +import dev.kolektiv.keel.event.EventDirection +import dev.kolektiv.keel.ktor.realtime.KeelRealtime +import dev.kolektiv.keel.ktor.realtime.KeelRealtimeKey +import dev.kolektiv.keel.realtime.KeelRealtimeEnvelope +import io.ktor.client.HttpClient +import io.ktor.client.engine.cio.CIO +import io.ktor.client.plugins.sse.ClientSSESession +import io.ktor.client.plugins.sse.SSE as ClientSSE +import io.ktor.client.plugins.sse.sseSession +import io.ktor.client.request.post +import io.ktor.client.request.setBody +import io.ktor.client.statement.bodyAsText +import io.ktor.http.ContentType +import io.ktor.http.HttpStatusCode +import io.ktor.http.contentType +import io.ktor.server.application.install +import io.ktor.server.engine.EmbeddedServer +import io.ktor.server.engine.embeddedServer +import io.ktor.server.netty.Netty +import io.ktor.server.netty.NettyApplicationEngine +import io.ktor.server.sse.SSE +import io.ktor.server.websocket.WebSockets +import io.ktor.sse.ServerSentEvent +import kotlinx.coroutines.cancel +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.flow.collect +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.put +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Path +import kotlin.io.path.createDirectories +import kotlin.io.path.writeText + +/** + * SSE needs a real HTTP server: the test-host client buffers whole + * responses, so an open stream never reaches it. Netty on an ephemeral port + * plus the CIO client exercises the actual wire. + */ +class RealtimeServerTest { + + @Serializable + data class Home(val greeting: String) + + @Serializable + data class Tick(val at: Long) + + @Serializable + data class Shout(val text: String) + + @TempDir + lateinit var pack: Path + + private var server: EmbeddedServer? = null + private var port: Int = 0 + private var hub: KeelRealtime? = null + private val handled = mutableListOf() + + private fun writePack() { + val manifest = buildJsonObject { + put("format", "keel/1") + put("id", "harbor") + put("version", "0.1.0") + put("framework", "svelte") + put("host", "#__keel_root") + put( + "pages", + buildJsonObject { + put("home", buildJsonObject { put("module", "pages/home.js") }) + }, + ) + } + pack.resolve("manifest.json").writeText(manifest.toString()) + pack.resolve("bootstrap.js").writeText("export {}") + pack.resolve("pages").createDirectories() + pack.resolve("pages/home.js").writeText("export async function mount() {}") + } + + private fun start(sse: Boolean = true, webSockets: Boolean = true) { + writePack() + val launched = embeddedServer(Netty, port = 0, host = "127.0.0.1") { + if (sse) install(SSE) + if (webSockets) install(WebSockets) + keel { + bundle = FrontendBundle.fromDirectory(pack) + pages { + page("home", "/") { Home("hello") } + } + realtime { + heartbeatSeconds = 1 + event("demo.tick", EventDirection.OUT) + on("demo.shout") { input -> handled.add(input.text) } + } + } + hub = attributes.getOrNull(KeelRealtimeKey) + } + launched.start(wait = false) + server = launched + port = runBlocking { launched.engine.resolvedConnectors().first().port } + } + + private fun stop() { + server?.stop(100, 500) + server = null + } + + private fun base(): String = "http://127.0.0.1:$port" + + private fun client(): HttpClient = HttpClient(CIO) { install(ClientSSE) } + + private suspend fun decode(event: ServerSentEvent): KeelRealtimeEnvelope = + KeelJson.codec.decodeFromString(KeelRealtimeEnvelope.serializer(), event.data!!) + + @Test + fun `sse stream receives typed events and invalidations over the wire`() = runBlocking { + start() + val client = client() + try { + val events = Channel(Channel.UNLIMITED) + val session = client.sseSession("${base()}/__keel/events?channels=demo") + val reader = launch { session.incoming.collect { events.send(it) } } + try { + val ready = nextEnvelope(events) + assertEquals(KeelRealtimeEnvelope.READY, ready.type) + assertEquals(listOf("demo"), ready.channels) + assertTrue(ready.sid!!.startsWith("rt-")) + + hub!!.publish("demo", "demo.tick", Tick(9L)) + val event = nextEnvelope(events) + assertEquals("demo.tick", event.event) + assertEquals("9", event.data!!.jsonObject.getValue("at").jsonPrimitive.content) + + hub!!.invalidate("demo", path = "/") + val invalid = nextEnvelope(events) + assertEquals(KeelRealtimeEnvelope.INVALIDATE, invalid.type) + assertEquals("/", invalid.data!!.jsonObject.getValue("path").jsonPrimitive.content) + + assertEquals(1, hub!!.connectionCount()) + } finally { + reader.cancel() + session.cancel() + } + } finally { + awaitConnections(0) + client.close() + stop() + } + } + + @Test + fun `sse client subscribes and sends by sid over http`() = runBlocking { + start() + val client = client() + try { + val events = Channel(Channel.UNLIMITED) + val session = client.sseSession("${base()}/__keel/events") + val reader = launch { session.incoming.collect { events.send(it) } } + try { + val ready = nextEnvelope(events) + + val subscribed = client.post("${base()}/__keel/events") { + contentType(ContentType.Application.Json) + setBody( + encode(KeelRealtimeEnvelope.subscribe(listOf("demo"), sid = ready.sid)), + ) + } + assertEquals(HttpStatusCode.Accepted, subscribed.status) + val ack = nextEnvelope(events) + assertEquals(listOf("demo"), ack.channels) + + val sent = client.post("${base()}/__keel/events") { + contentType(ContentType.Application.Json) + setBody( + encode( + KeelRealtimeEnvelope.send( + "demo.shout", + buildJsonObject { put("text", "over sse") }, + ), + ), + ) + } + assertEquals(HttpStatusCode.Accepted, sent.status) + assertEquals(listOf("over sse"), handled) + + val unsubscribed = client.post("${base()}/__keel/events") { + contentType(ContentType.Application.Json) + setBody( + encode(KeelRealtimeEnvelope.unsubscribe(listOf("demo"), sid = ready.sid)), + ) + } + assertEquals(HttpStatusCode.Accepted, unsubscribed.status) + assertEquals(0, hub!!.connectionCount("demo")) + } finally { + reader.cancel() + session.cancel() + } + } finally { + client.close() + stop() + } + } + + @Test + fun `reconnect gets a fresh stream and resubscribes`() = runBlocking { + start() + val client = client() + try { + val firstEvents = Channel(Channel.UNLIMITED) + val firstSession = client.sseSession("${base()}/__keel/events?channels=demo") + val firstReader = launch { firstSession.incoming.collect { firstEvents.send(it) } } + val firstReady = nextEnvelope(firstEvents) + hub!!.publish("demo", "demo.tick", Tick(1L)) + assertEquals("demo.tick", nextEnvelope(firstEvents).event) + firstReader.cancel() + firstSession.cancel() + awaitConnections(0) + + val secondEvents = Channel(Channel.UNLIMITED) + val secondSession = client.sseSession("${base()}/__keel/events?channels=demo") + val secondReader = launch { secondSession.incoming.collect { secondEvents.send(it) } } + try { + val secondReady = nextEnvelope(secondEvents) + assertEquals(KeelRealtimeEnvelope.READY, secondReady.type) + assertTrue(secondReady.sid != firstReady.sid, "reconnect must not reuse the stream id") + assertEquals(listOf("demo"), secondReady.channels) + hub!!.publish("demo", "demo.tick", Tick(2L)) + assertEquals("2", nextEnvelope(secondEvents).data!!.jsonObject.getValue("at").jsonPrimitive.content) + } finally { + secondReader.cancel() + secondSession.cancel() + } + } finally { + client.close() + stop() + } + } + + @Test + fun `sse only host serves the stream`() = runBlocking { + start(webSockets = false) + val client = client() + try { + val events = Channel(Channel.UNLIMITED) + val session = client.sseSession("${base()}/__keel/events?channels=demo") + val reader = launch { session.incoming.collect { events.send(it) } } + try { + val ready = nextEnvelope(events) + assertEquals(KeelRealtimeEnvelope.READY, ready.type) + assertEquals(listOf("demo"), ready.channels) + } finally { + reader.cancel() + session.cancel() + } + } finally { + client.close() + stop() + } + } + + private suspend fun nextEnvelope(events: Channel): KeelRealtimeEnvelope { + while (true) { + val envelope = decode(withTimeout(5000) { events.receive() }) + if (envelope.type != KeelRealtimeEnvelope.PING) return envelope + } + } + + private suspend fun awaitConnections(expected: Int) { + withTimeout(10_000) { + while (hub!!.connectionCount() != expected) kotlinx.coroutines.delay(20) + } + } + + private fun encode(envelope: KeelRealtimeEnvelope): String = + KeelJson.codec.encodeToString(KeelRealtimeEnvelope.serializer(), envelope) +} diff --git a/ktor/src/test/kotlin/dev/kolektiv/keel/ktor/RealtimeTest.kt b/ktor/src/test/kotlin/dev/kolektiv/keel/ktor/RealtimeTest.kt new file mode 100644 index 0000000..6750e55 --- /dev/null +++ b/ktor/src/test/kotlin/dev/kolektiv/keel/ktor/RealtimeTest.kt @@ -0,0 +1,334 @@ +package dev.kolektiv.keel.ktor + +import dev.kolektiv.keel.KeelJson +import dev.kolektiv.keel.bundle.FrontendBundle +import dev.kolektiv.keel.event.EventDirection +import dev.kolektiv.keel.ktor.realtime.KeelRealtime +import dev.kolektiv.keel.ktor.realtime.KeelRealtimeKey +import dev.kolektiv.keel.ktor.realtime.KeelRealtimeMissingPluginException +import dev.kolektiv.keel.ktor.realtime.RealtimeDsl +import dev.kolektiv.keel.ktor.realtime.keelRealtime +import dev.kolektiv.keel.realtime.KeelRealtimeEnvelope +import io.ktor.client.plugins.websocket.DefaultClientWebSocketSession +import io.ktor.client.plugins.websocket.WebSockets as ClientWebSockets +import io.ktor.client.plugins.websocket.webSocket +import io.ktor.client.request.header +import io.ktor.client.request.post +import io.ktor.client.request.prepareGet +import io.ktor.client.request.setBody +import io.ktor.client.statement.bodyAsText +import io.ktor.http.ContentType +import io.ktor.http.HttpHeaders +import io.ktor.http.HttpStatusCode +import io.ktor.http.contentType +import io.ktor.server.application.Application +import io.ktor.server.application.install +import io.ktor.server.sse.SSE +import io.ktor.server.testing.testApplication +import io.ktor.server.websocket.WebSockets +import io.ktor.websocket.Frame +import io.ktor.websocket.readText +import kotlinx.coroutines.delay +import kotlinx.coroutines.withTimeout +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.put +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNotNull +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Path +import kotlin.io.path.createDirectories +import kotlin.io.path.writeText + +class RealtimeTest { + + @Serializable + data class Home(val greeting: String) + + @Serializable + data class Tick(val at: Long) + + @Serializable + data class Shout(val text: String) + + @TempDir + lateinit var pack: Path + + private val handled = mutableListOf() + private var hub: KeelRealtime? = null + private var published: Int = 0 + + private fun writePack() { + val manifest = buildJsonObject { + put("format", "keel/1") + put("id", "harbor") + put("version", "0.1.0") + put("framework", "svelte") + put("host", "#__keel_root") + put( + "pages", + buildJsonObject { + put("home", buildJsonObject { put("module", "pages/home.js") }) + }, + ) + } + pack.resolve("manifest.json").writeText(manifest.toString()) + pack.resolve("bootstrap.js").writeText("export {}") + pack.resolve("pages").createDirectories() + pack.resolve("pages/home.js").writeText("export async function mount() {}") + } + + private fun Application.installSample(configure: RealtimeDsl.() -> Unit = {}) { + writePack() + keel { + bundle = FrontendBundle.fromDirectory(pack) + pages { + page("home", "/") { Home("hello") } + } + realtime { + heartbeatSeconds = 0 + event("demo.tick", EventDirection.OUT) + on("demo.shout") { input -> handled.add(input.text) } + configure() + } + } + hub = attributes.getOrNull(KeelRealtimeKey) + } + + private fun Application.installTransports() { + install(SSE) + install(WebSockets) + } + + @Test + fun `websocket subscribe publish and send`() = testApplication { + application { + installTransports() + installSample() + } + val client = createClient { install(ClientWebSockets) } + client.webSocket("/__keel/events?channels=demo") { + val ready = nextEnvelope() + assertEquals(KeelRealtimeEnvelope.READY, ready.type) + assertEquals(listOf("demo"), ready.channels) + assertNotNull(ready.sid) + + hub!!.publish("demo", "demo.tick", Tick(7L)) + val event = nextEnvelope() + assertEquals(KeelRealtimeEnvelope.EVENT, event.type) + assertEquals("demo.tick", event.event) + assertEquals("7", event.data!!.jsonObject.getValue("at").jsonPrimitive.content) + + send( + Frame.Text( + encode(KeelRealtimeEnvelope.send("demo.shout", buildJsonObject { put("text", "ahoy") })), + ), + ) + withTimeout(5000) { + while (handled.isEmpty()) delay(10) + } + assertEquals(listOf("ahoy"), handled) + } + } + + @Test + fun `websocket client can subscribe and unsubscribe`() = testApplication { + application { + installTransports() + installSample() + } + val client = createClient { install(ClientWebSockets) } + client.webSocket("/__keel/events") { + assertEquals(KeelRealtimeEnvelope.READY, nextEnvelope().type) + send(Frame.Text(encode(KeelRealtimeEnvelope.subscribe(listOf("demo"))))) + var envelope = nextEnvelope() + assertEquals(KeelRealtimeEnvelope.READY, envelope.type) + assertEquals(listOf("demo"), envelope.channels) + + hub!!.publish("demo", "demo.tick", Tick(1L)) + assertEquals("demo.tick", nextEnvelope().event) + + send(Frame.Text(encode(KeelRealtimeEnvelope.unsubscribe(listOf("demo"))))) + assertEquals(emptyList(), nextEnvelope().channels) + assertEquals(0, hub!!.connectionCount("demo")) + } + withTimeout(5000) { + while (hub!!.connectionCount() != 0) delay(10) + } + } + + @Test + fun `post rejects unknown stream malformed envelope and unknown events`() = testApplication { + application { + installTransports() + installSample() + } + val unknownSid = client.post("/__keel/events") { + contentType(ContentType.Application.Json) + setBody(encode(KeelRealtimeEnvelope.subscribe(listOf("demo"), sid = "nope"))) + } + assertEquals(HttpStatusCode.NotFound, unknownSid.status) + + val malformed = client.post("/__keel/events") { + contentType(ContentType.Application.Json) + setBody("{") + } + assertEquals(HttpStatusCode.BadRequest, malformed.status) + + val unknownEvent = client.post("/__keel/events") { + contentType(ContentType.Application.Json) + setBody(encode(KeelRealtimeEnvelope.send("demo.nope"))) + } + assertEquals(HttpStatusCode.NotFound, unknownEvent.status) + + val outboundOnly = client.post("/__keel/events") { + contentType(ContentType.Application.Json) + setBody(encode(KeelRealtimeEnvelope.send("demo.tick"))) + } + assertEquals(HttpStatusCode.NotFound, outboundOnly.status) + } + + @Test + fun `authorize denies channels at handshake`() = testApplication { + application { + installTransports() + installSample { + authorize = { _, channel -> channel == "demo" } + } + } + val client = createClient { install(ClientWebSockets) } + client.webSocket("/__keel/events?channels=demo,secret") { + assertEquals(KeelRealtimeEnvelope.READY, nextEnvelope().type) + val denied = nextEnvelope() + assertEquals(KeelRealtimeEnvelope.ERROR, denied.type) + assertEquals("secret", denied.channel) + assertEquals(setOf("demo"), hub!!.channels()) + } + } + + @Test + fun `typed event published from a handler reaches the channel`() = testApplication { + application { + installTransports() + installSample { + on("demo.broadcast") { input -> + published = call.keelRealtime.publish("demo", "demo.tick", Tick(input.text.length.toLong())) + } + } + } + val client = createClient { install(ClientWebSockets) } + client.webSocket("/__keel/events?channels=demo") { + assertEquals(KeelRealtimeEnvelope.READY, nextEnvelope().type) + val response = client.post("/__keel/events") { + contentType(ContentType.Application.Json) + setBody( + encode( + KeelRealtimeEnvelope.send( + "demo.broadcast", + buildJsonObject { put("text", "four") }, + ), + ), + ) + } + assertEquals(HttpStatusCode.Accepted, response.status) + assertEquals(1, published) + val event = nextEnvelope() + assertEquals("demo.tick", event.event) + assertEquals("4", event.data!!.jsonObject.getValue("at").jsonPrimitive.content) + } + } + + @Test + fun `post enforces the same-origin csrf policy`() = testApplication { + application { + installTransports() + installSample() + } + val denied = client.post("/__keel/events") { + contentType(ContentType.Application.Json) + header(HttpHeaders.Origin, "https://evil.example") + setBody(encode(KeelRealtimeEnvelope.ping())) + } + assertEquals(HttpStatusCode.Forbidden, denied.status) + + val allowed = client.post("/__keel/events") { + contentType(ContentType.Application.Json) + header("Sec-Fetch-Site", "same-origin") + setBody(encode(KeelRealtimeEnvelope.ping())) + } + assertEquals(HttpStatusCode.Accepted, allowed.status, allowed.bodyAsText()) + } + + @Test + fun `websocket only hosts skip the sse route`() = testApplication { + application { + install(WebSockets) + installSample() + } + assertEquals(HttpStatusCode.NotFound, client.prepareGet("/__keel/events").execute { it.status }) + val client = createClient { install(ClientWebSockets) } + client.webSocket("/__keel/events?channels=demo") { + assertEquals(KeelRealtimeEnvelope.READY, nextEnvelope().type) + } + } + + @Test + fun `schema documents events`() = testApplication { + application { + installTransports() + installSample() + } + val schema = client.prepareGet("/__keel/schema").execute { it.bodyAsText() } + assertTrue(schema.contains("\"events\""), schema) + assertTrue(schema.contains("\"demo.tick\""), schema) + assertTrue(schema.contains("\"direction\": \"out\""), schema) + assertTrue(schema.contains("\"demo.shout\""), schema) + assertTrue(schema.contains("\"direction\": \"in\""), schema) + } + + @Test + fun `realtime without plugins fails the install`() { + val failure = assertThrows { + testApplication { + application { + keel { + realtime { heartbeatSeconds = 0 } + } + } + } + } + assertTrue(failure.message!!.contains("install(SSE)"), failure.message) + } + + @Test + fun `realtime routes do not exist without the opt-in`() = testApplication { + writePack() + application { + installTransports() + keel { + bundle = FrontendBundle.fromDirectory(pack) + pages { + page("home", "/") { Home("hello") } + } + } + hub = attributes.getOrNull(KeelRealtimeKey) + } + assertNull(hub) + assertEquals(HttpStatusCode.NotFound, client.prepareGet("/__keel/events").execute { it.status }) + } + + private suspend fun DefaultClientWebSocketSession.nextEnvelope(): KeelRealtimeEnvelope = + decode((withTimeout(5000) { incoming.receive() } as Frame.Text).readText()) + + private fun encode(envelope: KeelRealtimeEnvelope): String = + KeelJson.codec.encodeToString(KeelRealtimeEnvelope.serializer(), envelope) + + private fun decode(raw: String): KeelRealtimeEnvelope = + KeelJson.codec.decodeFromString(KeelRealtimeEnvelope.serializer(), raw) +} diff --git a/lib/src/main/kotlin/dev/kolektiv/keel/Keel.kt b/lib/src/main/kotlin/dev/kolektiv/keel/Keel.kt index 0fabbf5..3014969 100644 --- a/lib/src/main/kotlin/dev/kolektiv/keel/Keel.kt +++ b/lib/src/main/kotlin/dev/kolektiv/keel/Keel.kt @@ -16,6 +16,8 @@ object Keel { const val NAVIGATE_PATH: String = "/__keel/navigate" const val ACTION_PATH: String = "/__keel/action" const val SCHEMA_PATH: String = "/__keel/schema" + const val REALTIME_PATH: String = "/__keel/events" + const val REALTIME_VERSION: Int = 1 const val BUNDLE_EXTENSION: String = "feb" const val PACK_URL_PREFIX: String = "/__keel/pack" } \ No newline at end of file diff --git a/lib/src/main/kotlin/dev/kolektiv/keel/KeelEvent.kt b/lib/src/main/kotlin/dev/kolektiv/keel/KeelEvent.kt new file mode 100644 index 0000000..9dfc7a8 --- /dev/null +++ b/lib/src/main/kotlin/dev/kolektiv/keel/KeelEvent.kt @@ -0,0 +1,24 @@ +package dev.kolektiv.keel + +import dev.kolektiv.keel.event.EventDirection + +/** + * Marks a realtime event payload or a host event handler. + * + * On a `@Serializable` class, [value] is the event id (`harbor.message`). + * Empty uses the class simple name. + * + * On a host function, the function takes **one** value parameter (the + * payload), returns `Unit`, and handles client-sent events. It may be an + * extension so cookies/session are `this`. Empty uses the function name. + * + * Event ids are the contract keys packs subscribe to and send; they are not + * URLs. + */ +@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) +@Retention(AnnotationRetention.RUNTIME) +@MustBeDocumented +annotation class KeelEvent( + val value: String = "", + val direction: EventDirection = EventDirection.BOTH, +) diff --git a/lib/src/main/kotlin/dev/kolektiv/keel/event/EventDiscovery.kt b/lib/src/main/kotlin/dev/kolektiv/keel/event/EventDiscovery.kt new file mode 100644 index 0000000..af17fbd --- /dev/null +++ b/lib/src/main/kotlin/dev/kolektiv/keel/event/EventDiscovery.kt @@ -0,0 +1,110 @@ +package dev.kolektiv.keel.event + +import dev.kolektiv.keel.KeelEvent +import kotlinx.serialization.KSerializer +import kotlinx.serialization.serializer +import java.lang.reflect.InvocationTargetException +import kotlin.reflect.KFunction +import kotlin.reflect.KParameter +import kotlin.reflect.full.callSuspendBy +import kotlin.reflect.full.extensionReceiverParameter +import kotlin.reflect.full.findAnnotation +import kotlin.reflect.full.instanceParameter +import kotlin.reflect.jvm.kotlinFunction + +/** + * A `@KeelEvent` function the host can run when a client sends the event. + * [payload] describes the JSON the client must send. + */ +class DiscoveredEvent( + val id: String, + val direction: EventDirection, + val payload: KSerializer<*>, + val function: KFunction<*>, + val instance: Any?, +) { + val binding: EventBinding get() = EventBinding(id, direction, payload) + + suspend fun invoke(payload: Any, extension: Any? = null) { + val args = HashMap() + function.instanceParameter?.let { parameter -> + args[parameter] = instance ?: error("@KeelEvent '${function.name}' needs a host instance") + } + function.extensionReceiverParameter?.let { parameter -> + args[parameter] = extension + ?: error("@KeelEvent '${function.name}' needs an extension receiver") + } + args[valueParameter()] = payload + try { + if (function.isSuspend) { + function.callSuspendBy(args) + } else { + function.callBy(args) + } + } catch (error: InvocationTargetException) { + throw error.targetException ?: error + } + } + + private fun valueParameter(): KParameter { + val values = function.parameters.filter { it.kind == KParameter.Kind.VALUE } + require(values.size == 1) { + "@KeelEvent '${function.name}' must take exactly one value parameter, found ${values.size}" + } + return values.single() + } +} + +object EventDiscovery { + fun discover(host: Any): List { + val instance = if (host is Class<*>) host.kotlin.objectInstance else host + val kClass = when (host) { + is Class<*> -> host.kotlin + else -> host::class + } + return discover(kClass.java, instance) + } + + fun discover(clazz: Class<*>, instance: Any? = clazz.kotlin.objectInstance): List { + val seen = LinkedHashSet>() + val out = ArrayList() + for (method in clazz.declaredMethods) { + val function = method.kotlinFunction ?: continue + if (!seen.add(function)) continue + val annotation = function.findAnnotation() ?: continue + out.add(bind(annotation, function, instance)) + } + return out + } + + fun registry(vararg hosts: Any): EventRegistry { + val registry = EventRegistry() + for (host in hosts) { + for (event in discover(host)) { + registry.register(event.binding) + } + } + return registry + } + + private fun bind(annotation: KeelEvent, function: KFunction<*>, instance: Any?): DiscoveredEvent { + require(annotation.direction != EventDirection.OUT) { + "@KeelEvent '${function.name}' is OUT but handlers receive client events (use IN or BOTH)" + } + val values = function.parameters.filter { it.kind == KParameter.Kind.VALUE } + require(values.size == 1) { + "@KeelEvent '${function.name}' must take exactly one value parameter" + } + require(function.returnType.classifier == Unit::class) { + "@KeelEvent '${function.name}' must return Unit" + } + val id = annotation.value.ifBlank { function.name } + return DiscoveredEvent( + id = id, + direction = annotation.direction, + payload = serializer(values.single().type), + function = function, + instance = instance, + ) + } +} diff --git a/lib/src/main/kotlin/dev/kolektiv/keel/event/EventRegistry.kt b/lib/src/main/kotlin/dev/kolektiv/keel/event/EventRegistry.kt new file mode 100644 index 0000000..2c76078 --- /dev/null +++ b/lib/src/main/kotlin/dev/kolektiv/keel/event/EventRegistry.kt @@ -0,0 +1,100 @@ +package dev.kolektiv.keel.event + +import kotlinx.serialization.KSerializer +import kotlinx.serialization.serializer + +/** + * Which way an event may travel. + * + * [IN] is client to host, [OUT] is host to client, [BOTH] allows either + * direction. The wire value is lowercase (`in` / `out` / `both`). + */ +enum class EventDirection { + IN, + OUT, + BOTH, + ; + + val wireValue: String get() = name.lowercase() + + companion object { + fun fromWire(value: String): EventDirection = + entries.firstOrNull { it.wireValue == value.lowercase() } + ?: throw IllegalArgumentException("unknown event direction '$value' (expected in|out|both)") + } +} + +/** + * A realtime event the host knows how to encode. [id] is the contract key + * packs subscribe to or send; it is not a URL. [payload] is the JSON payload + * serializer. + */ +data class EventBinding( + val id: String, + val direction: EventDirection, + val payload: KSerializer<*>, +) + +class DuplicateEventException(id: String) : IllegalStateException("event '$id' is already registered") + +class UnknownEventException( + id: String, + message: String = "unknown event '$id'", +) : NoSuchElementException(message) { + val eventId: String = id +} + +class EventDirectionException( + id: String, + message: String, +) : IllegalStateException(message) { + val eventId: String = id +} + +/** + * Source of truth for event ids, directions, and payload serializers. + * + * A realtime host walks this registry to encode outgoing events and decode + * incoming ones; Typegen walks it to emit the event section of the contract. + * This module does not depend on Ktor. + */ +class EventRegistry { + private val byId = linkedMapOf() + + val events: Collection get() = byId.values + + fun ids(): Set = byId.keys + + fun register(binding: EventBinding): EventBinding { + require(binding.id.isNotBlank()) { "event id is required" } + if (byId.containsKey(binding.id)) throw DuplicateEventException(binding.id) + byId[binding.id] = binding + return binding + } + + inline fun event( + id: String, + direction: EventDirection = EventDirection.BOTH, + ): EventBinding = register(EventBinding(id, direction, serializer())) + + fun get(id: String): EventBinding = + byId[id] ?: throw UnknownEventException(id) + + fun find(id: String): EventBinding? = byId[id] + + /** Looks up an event the host may publish. [EventDirection.IN] is rejected. */ + fun outgoing(id: String): EventBinding = get(id).also { + if (it.direction == EventDirection.IN) { + throw EventDirectionException(id, "event '$id' is client-to-host only (IN)") + } + } + + /** Looks up an event the host may receive. [EventDirection.OUT] is rejected. */ + fun incoming(id: String): EventBinding = get(id).also { + if (it.direction == EventDirection.OUT) { + throw EventDirectionException(id, "event '$id' is host-to-client only (OUT)") + } + } +} + +fun events(block: EventRegistry.() -> Unit): EventRegistry = EventRegistry().apply(block) diff --git a/lib/src/main/kotlin/dev/kolektiv/keel/realtime/KeelRealtimeEnvelope.kt b/lib/src/main/kotlin/dev/kolektiv/keel/realtime/KeelRealtimeEnvelope.kt new file mode 100644 index 0000000..e94a0e3 --- /dev/null +++ b/lib/src/main/kotlin/dev/kolektiv/keel/realtime/KeelRealtimeEnvelope.kt @@ -0,0 +1,115 @@ +package dev.kolektiv.keel.realtime + +import dev.kolektiv.keel.Keel +import dev.kolektiv.keel.KeelJson +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.encodeToJsonElement + +/** + * The boring JSON envelope both realtime transports speak, in both + * directions. + * + * `type` is one of [READY], [EVENT], [INVALIDATE], [ERROR], [PING] from the + * host, or [SUBSCRIBE], [UNSUBSCRIBE], [SEND], [PING] from a client. + * `channel` scopes subscriptions and events; `channels` is the subscribe / + * ready list. `sid` names a server-created stream so a client can address it + * over plain HTTP (SSE sends go through `POST`). `id` is an optional client + * correlation id echoed on the matching event. + */ +@Serializable +data class KeelRealtimeEnvelope( + val v: Int = Keel.REALTIME_VERSION, + val type: String, + val sid: String? = null, + val channel: String? = null, + val channels: List? = null, + val event: String? = null, + val data: JsonElement? = null, + val id: String? = null, + val error: String? = null, +) { + companion object { + const val READY = "ready" + const val EVENT = "event" + const val INVALIDATE = "invalidate" + const val ERROR = "error" + const val PING = "ping" + const val SUBSCRIBE = "subscribe" + const val UNSUBSCRIBE = "unsubscribe" + const val SEND = "send" + + fun ready(sid: String, channels: List): KeelRealtimeEnvelope = + KeelRealtimeEnvelope( + type = READY, + sid = sid, + channels = channels, + ) + + fun event( + channel: String, + event: String, + data: JsonElement? = null, + id: String? = null, + ): KeelRealtimeEnvelope = + KeelRealtimeEnvelope( + type = EVENT, + channel = channel, + event = event, + data = data, + id = id, + ) + + fun invalidate( + channel: String, + path: String? = null, + only: List? = null, + except: List? = null, + ): KeelRealtimeEnvelope = + KeelRealtimeEnvelope( + type = INVALIDATE, + channel = channel, + data = KeelJson.codec.encodeToJsonElement( + KeelRealtimeInvalidate.serializer(), + KeelRealtimeInvalidate(path, only, except), + ), + ) + + fun error(message: String, channel: String? = null): KeelRealtimeEnvelope = + KeelRealtimeEnvelope(type = ERROR, channel = channel, error = message) + + fun ping(): KeelRealtimeEnvelope = KeelRealtimeEnvelope(type = PING) + + fun subscribe(channels: List, sid: String? = null): KeelRealtimeEnvelope = + KeelRealtimeEnvelope(type = SUBSCRIBE, sid = sid, channels = channels) + + fun unsubscribe(channels: List, sid: String? = null): KeelRealtimeEnvelope = + KeelRealtimeEnvelope(type = UNSUBSCRIBE, sid = sid, channels = channels) + + fun send( + event: String, + data: JsonElement? = null, + channel: String? = null, + id: String? = null, + ): KeelRealtimeEnvelope = + KeelRealtimeEnvelope( + type = SEND, + channel = channel, + event = event, + data = data, + id = id, + ) + } +} + +/** + * Payload of an [KeelRealtimeEnvelope.INVALIDATE] event: rehydrate the seed + * with a normal visit. [path] targets a specific page path, [only] / [except] + * limit the seed keys the way [dev.kolektiv.keel.visit.KeelHeaders.only] does. + */ +@Serializable +data class KeelRealtimeInvalidate( + val path: String? = null, + val only: List? = null, + val except: List? = null, +) diff --git a/lib/src/main/kotlin/dev/kolektiv/keel/typegen/Typegen.kt b/lib/src/main/kotlin/dev/kolektiv/keel/typegen/Typegen.kt index 849253d..dca5a1d 100644 --- a/lib/src/main/kotlin/dev/kolektiv/keel/typegen/Typegen.kt +++ b/lib/src/main/kotlin/dev/kolektiv/keel/typegen/Typegen.kt @@ -1,6 +1,7 @@ package dev.kolektiv.keel.typegen import dev.kolektiv.keel.action.ActionRegistry +import dev.kolektiv.keel.event.EventRegistry import dev.kolektiv.keel.page.PageMethod import dev.kolektiv.keel.page.PageRegistry import kotlinx.serialization.descriptors.PrimitiveKind @@ -27,8 +28,9 @@ object Typegen { fun emit( pages: PageRegistry, actions: ActionRegistry = ActionRegistry(), + events: EventRegistry = EventRegistry(), pagesName: String = "Pages", - ): String = emit(TypegenContract(pages.pages, actions.actions), pagesName) + ): String = emit(TypegenContract(pages.pages, actions.actions, events = events.events), pagesName) fun emit( contract: TypegenContract, @@ -38,8 +40,9 @@ object Typegen { fun emitJson( pages: PageRegistry, actions: ActionRegistry = ActionRegistry(), + events: EventRegistry = EventRegistry(), pagesName: String = "Pages", - ): String = emitJson(TypegenContract(pages.pages, actions.actions), pagesName) + ): String = emitJson(TypegenContract(pages.pages, actions.actions, events = events.events), pagesName) fun emitJson( contract: TypegenContract, @@ -61,6 +64,8 @@ private class Emitter( val pageIdName = pageIdName(pagesName) val actionsName = actionsName(pagesName) val actionIdName = actionIdName(pagesName) + val eventsName = eventsName(pagesName) + val eventIdName = eventIdName(pagesName) return buildString { appendLine("// Generated by dev.kolektiv.keel.typegen.Typegen. Do not edit.") appendLine() @@ -105,6 +110,16 @@ private class Emitter( appendLine() appendLine("export type $actionIdName = keyof $actionsName") } + if (contract.events.isNotEmpty()) { + appendLine() + appendLine("export interface $eventsName {") + for (binding in contract.events) { + appendLine(" \"${binding.id}\": ${tsType(binding.payload.descriptor)}") + } + appendLine("}") + appendLine() + appendLine("export type $eventIdName = keyof $eventsName") + } } } @@ -146,6 +161,20 @@ private class Emitter( } }, ) + put( + "events", + buildJsonObject { + for (binding in contract.events) { + put( + binding.id, + buildJsonObject { + put("direction", binding.direction.wireValue) + put("type", tsType(binding.payload.descriptor)) + }, + ) + } + }, + ) put( "types", buildJsonObject { @@ -191,6 +220,9 @@ private class Emitter( collect(binding.input.descriptor) collect(binding.output.descriptor) } + for (binding in contract.events) { + collect(binding.payload.descriptor) + } for (serializer in contract.types) { collect(serializer.descriptor) } @@ -292,3 +324,11 @@ private fun actionsName(pagesName: String): String = private fun actionIdName(pagesName: String): String = if (pagesName.endsWith("Pages")) pagesName.removeSuffix("Pages").ifBlank { "" } + "ActionId" else pagesName + "ActionId" + +private fun eventsName(pagesName: String): String = + if (pagesName.endsWith("Pages")) pagesName.removeSuffix("Pages").ifBlank { "" } + "Events" + else pagesName + "Events" + +private fun eventIdName(pagesName: String): String = + if (pagesName.endsWith("Pages")) pagesName.removeSuffix("Pages").ifBlank { "" } + "EventId" + else pagesName + "EventId" diff --git a/lib/src/main/kotlin/dev/kolektiv/keel/typegen/TypegenContract.kt b/lib/src/main/kotlin/dev/kolektiv/keel/typegen/TypegenContract.kt index 317691a..9855592 100644 --- a/lib/src/main/kotlin/dev/kolektiv/keel/typegen/TypegenContract.kt +++ b/lib/src/main/kotlin/dev/kolektiv/keel/typegen/TypegenContract.kt @@ -1,8 +1,11 @@ package dev.kolektiv.keel.typegen +import dev.kolektiv.keel.KeelEvent import dev.kolektiv.keel.KeelType import dev.kolektiv.keel.action.ActionBinding import dev.kolektiv.keel.action.ActionDiscovery +import dev.kolektiv.keel.event.EventBinding +import dev.kolektiv.keel.event.EventDiscovery import dev.kolektiv.keel.page.PageBinding import kotlinx.serialization.KSerializer import kotlinx.serialization.serializer @@ -12,13 +15,15 @@ import java.nio.file.Path import kotlin.reflect.full.starProjectedType /** - * Pages, actions, and extra serializers Typegen walks. Built from `@KeelType` - * / `@KeelAction` on the compile output, or from the runtime registries. + * Pages, actions, events, and extra serializers Typegen walks. Built from + * `@KeelType` / `@KeelAction` / `@KeelEvent` on the compile output, or from + * the runtime registries. */ class TypegenContract( val pages: Collection, val actions: Collection, val types: Collection> = emptyList(), + val events: Collection = emptyList(), ) object ClasspathContract { @@ -36,8 +41,10 @@ object ClasspathContract { val pages = ArrayList() val actions = ArrayList() val types = ArrayList>() + val events = ArrayList() val seenActions = HashSet() val seenPages = HashSet() + val seenEvents = HashSet() for (name in names) { val clazz = runCatching { Class.forName(name, false, classLoader) }.getOrNull() ?: continue val keelType = clazz.getAnnotation(KeelType::class.java) @@ -49,14 +56,27 @@ object ClasspathContract { pages.add(PageBinding(pageId, typegenPath(pageId), serializer)) } } + val keelEvent = clazz.getAnnotation(KeelEvent::class.java) + if (keelEvent != null) { + val serializer = serializerFor(clazz) ?: continue + types.add(serializer) + val eventId = keelEvent.value.ifBlank { clazz.simpleName } + if (seenEvents.add(eventId)) { + events.add(EventBinding(eventId, keelEvent.direction, serializer)) + } + } for (action in ActionDiscovery.discover(clazz)) { if (seenActions.add(action.id)) actions.add(action.binding) } + for (event in EventDiscovery.discover(clazz)) { + if (seenEvents.add(event.id)) events.add(event.binding) + } } return TypegenContract( pages.sortedBy { it.id }, actions.sortedBy { it.id }, types, + events.sortedBy { it.id }, ) } diff --git a/lib/src/test/kotlin/dev/kolektiv/keel/event/EventDiscoveryTest.kt b/lib/src/test/kotlin/dev/kolektiv/keel/event/EventDiscoveryTest.kt new file mode 100644 index 0000000..b09a298 --- /dev/null +++ b/lib/src/test/kotlin/dev/kolektiv/keel/event/EventDiscoveryTest.kt @@ -0,0 +1,88 @@ +package dev.kolektiv.keel.event + +import dev.kolektiv.keel.KeelEvent +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.Serializable +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test + +class EventDiscoveryTest { + + @Serializable + data class NoteIn(val text: String) + + object Host { + var seen: String? = null + + @KeelEvent("demo.note", EventDirection.IN) + fun note(input: NoteIn) { + seen = input.text + } + } + + @Test + fun `discovers an inbound handler and invokes it`() { + val discovered = EventDiscovery.discover(Host) + assertEquals(1, discovered.size) + assertEquals("demo.note", discovered.single().id) + assertEquals(EventDirection.IN, discovered.single().direction) + Host.seen = null + runBlocking { discovered.single().invoke(NoteIn("hi")) } + assertEquals("hi", Host.seen) + } + + @Test + fun `registry uses the function name when the id is omitted`() { + val registry = EventDiscovery.registry(UnnamedHost) + assertEquals(setOf("whisper"), registry.ids()) + } + + object UnnamedHost { + @KeelEvent + fun whisper(input: NoteIn) = Unit + } + + class Ctx(val prefix: String) + + object ExtensionHost { + var seen: String? = null + + @KeelEvent("demo.ctx") + fun Ctx.note(input: NoteIn) { + seen = prefix + input.text + } + } + + @Test + fun `extension receiver is passed at invoke`() { + val discovered = EventDiscovery.discover(ExtensionHost).single() + runBlocking { discovered.invoke(NoteIn("hi"), extension = Ctx("X")) } + assertEquals("Xhi", ExtensionHost.seen) + } + + @Test + fun `outbound-only handlers are rejected`() { + val error = assertThrows(IllegalArgumentException::class.java) { + EventDiscovery.discover(OutboundHost) + } + assertEquals(true, error.message!!.contains("is OUT"), error.message) + } + + object OutboundHost { + @KeelEvent("demo.out", EventDirection.OUT) + fun out(input: NoteIn) = Unit + } + + @Test + fun `handlers must return unit`() { + assertThrows(IllegalArgumentException::class.java) { + EventDiscovery.discover(ReturningHost) + } + } + + object ReturningHost { + @KeelEvent("demo.echo") + fun echo(input: NoteIn): NoteIn = input + } +} diff --git a/lib/src/test/kotlin/dev/kolektiv/keel/event/EventRegistryTest.kt b/lib/src/test/kotlin/dev/kolektiv/keel/event/EventRegistryTest.kt new file mode 100644 index 0000000..adcae03 --- /dev/null +++ b/lib/src/test/kotlin/dev/kolektiv/keel/event/EventRegistryTest.kt @@ -0,0 +1,57 @@ +package dev.kolektiv.keel.event + +import kotlinx.serialization.Serializable +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test + +class EventRegistryTest { + + @Serializable + data class Ping(val at: Long) + + @Test + fun `registers and looks up events`() { + val registry = events { + event("demo.ping", EventDirection.OUT) + } + assertEquals(setOf("demo.ping"), registry.ids()) + assertEquals(EventDirection.OUT, registry.get("demo.ping").direction) + assertEquals(Ping.serializer().descriptor, registry.outgoing("demo.ping").payload.descriptor) + } + + @Test + fun `duplicate ids are rejected`() { + val registry = events { event("demo.ping") } + assertThrows(DuplicateEventException::class.java) { + registry.register(EventBinding("demo.ping", EventDirection.BOTH, Ping.serializer())) + } + } + + @Test + fun `unknown ids are rejected`() { + val registry = EventRegistry() + val error = assertThrows(UnknownEventException::class.java) { registry.get("nope") } + assertEquals("nope", error.eventId) + } + + @Test + fun `direction guards publishing and receiving`() { + val registry = events { + event("client.only", EventDirection.IN) + event("host.only", EventDirection.OUT) + } + assertThrows(EventDirectionException::class.java) { registry.outgoing("client.only") } + assertThrows(EventDirectionException::class.java) { registry.incoming("host.only") } + assertEquals("host.only", registry.outgoing("host.only").id) + assertEquals("client.only", registry.incoming("client.only").id) + } + + @Test + fun `wire directions round trip`() { + for (direction in EventDirection.entries) { + assertEquals(direction, EventDirection.fromWire(direction.wireValue)) + } + assertThrows(IllegalArgumentException::class.java) { EventDirection.fromWire("sideways") } + } +} diff --git a/lib/src/test/kotlin/dev/kolektiv/keel/typegen/TypegenAnnotationTest.kt b/lib/src/test/kotlin/dev/kolektiv/keel/typegen/TypegenAnnotationTest.kt index 616a167..5aa2b48 100644 --- a/lib/src/test/kotlin/dev/kolektiv/keel/typegen/TypegenAnnotationTest.kt +++ b/lib/src/test/kotlin/dev/kolektiv/keel/typegen/TypegenAnnotationTest.kt @@ -1,7 +1,9 @@ package dev.kolektiv.keel.typegen import dev.kolektiv.keel.KeelAction +import dev.kolektiv.keel.KeelEvent import dev.kolektiv.keel.KeelType +import dev.kolektiv.keel.event.EventDirection import kotlinx.serialization.Serializable import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test @@ -18,9 +20,20 @@ data class DemoRenameIn(val name: String) @Serializable data class DemoRenameOut(val ok: Boolean) +@KeelEvent("demo.tick", EventDirection.OUT) +@Serializable +data class DemoTick(val at: Long) + +@KeelType +@Serializable +data class DemoNoteIn(val text: String) + object DemoActions { @KeelAction("demo.rename") fun rename(input: DemoRenameIn): DemoRenameOut = DemoRenameOut(true) + + @KeelEvent("demo.note", EventDirection.IN) + fun note(input: DemoNoteIn) = Unit } class TypegenAnnotationTest { @@ -35,4 +48,17 @@ class TypegenAnnotationTest { assertTrue(ts.contains("export type DemoActionId = keyof DemoActions"), ts) assertTrue(ts.contains("export interface DemoPages"), ts) } + + @Test + fun `emits events from annotations in both places`() { + val contract = ClasspathContract.scan(listOf("dev.kolektiv.keel.typegen")) + val ts = Typegen.emit(contract, pagesName = "DemoPages") + assertTrue(ts.contains("export interface DemoEvents {"), ts) + assertTrue(ts.contains("\"demo.tick\": DemoTick"), ts) + assertTrue(ts.contains("\"demo.note\": DemoNoteIn"), ts) + assertTrue(ts.contains("export type DemoEventId = keyof DemoEvents"), ts) + val json = Typegen.emitJson(contract, pagesName = "DemoPages") + assertTrue(json.contains("\"direction\": \"out\""), json) + assertTrue(json.contains("\"direction\": \"in\""), json) + } } diff --git a/lib/src/test/kotlin/dev/kolektiv/keel/typegen/TypegenTest.kt b/lib/src/test/kotlin/dev/kolektiv/keel/typegen/TypegenTest.kt index d553984..1f9f501 100644 --- a/lib/src/test/kotlin/dev/kolektiv/keel/typegen/TypegenTest.kt +++ b/lib/src/test/kotlin/dev/kolektiv/keel/typegen/TypegenTest.kt @@ -1,6 +1,8 @@ package dev.kolektiv.keel.typegen import dev.kolektiv.keel.action.actions +import dev.kolektiv.keel.event.EventDirection +import dev.kolektiv.keel.event.events import dev.kolektiv.keel.page.pages import dev.kolektiv.keel.typegen.TypegenContract import kotlinx.serialization.Serializable @@ -129,6 +131,30 @@ class TypegenTest { assertTrueContains(json, "\"kicker\": \"string\"") } + @Serializable + data class BoardEvent(val text: String) + + @Test + fun `emits event payloads and directions`() { + val registry = pages { + page("harbor.home", "/") + } + val events = events { + event("harbor.message", EventDirection.BOTH) + } + val ts = Typegen.emit(registry, events = events, pagesName = "HarborPages") + assertTrueContains(ts, "export interface BoardEvent {") + assertTrueContains(ts, "export interface HarborEvents {") + assertTrueContains(ts, "\"harbor.message\": BoardEvent") + assertTrueContains(ts, "export type HarborEventId = keyof HarborEvents") + + val json = Typegen.emitJson(registry, events = events, pagesName = "HarborPages") + assertTrueContains(json, "\"events\"") + assertTrueContains(json, "\"harbor.message\"") + assertTrueContains(json, "\"direction\": \"both\"") + assertTrueContains(json, "\"type\": \"BoardEvent\"") + } + private fun assertTrueContains(haystack: String, needle: String) { assertEquals(true, haystack.contains(needle), "expected to contain:\n$needle\n\nin:\n$haystack") } diff --git a/llms.txt b/llms.txt index 1509c22..064e755 100644 --- a/llms.txt +++ b/llms.txt @@ -27,13 +27,14 @@ Docs: https://keel.kolektiv.computer/ (Cloudflare Pages; local `pnpm dev` is ht - [Partial reloads](https://keel.kolektiv.computer/docs/advanced/partials/): `only` / `except` on visits; shallow merge - [Forms and 422s](https://keel.kolektiv.computer/docs/advanced/forms/): progressive enhancement over router.visit - [Mutate and rehydrate](https://keel.kolektiv.computer/docs/advanced/query/): action then reload; state reads subscribe, method reads do not +- [Realtime](https://keel.kolektiv.computer/docs/advanced/realtime/): opt-in typed events + `invalidate` over SSE/WebSocket; the seed stays the read model - [Pack hot reload](https://keel.kolektiv.computer/docs/advanced/pack-hot-reload/): watcher, `seed.build` / `X-Keel-Build`, client reload - [Navigation guards](https://keel.kolektiv.computer/docs/advanced/navigation-guards/): `beforeEach`, async guards, popstate, `force` -- [Wire protocol](https://keel.kolektiv.computer/docs/implementing/protocol/): seed JSON, headers, status codes, path grammar, CSRF, `/__keel/schema` -- [Host adapter](https://keel.kolektiv.computer/docs/implementing/host-adapter/): what a backend must implement, `KeelConfig` knobs +- [Wire protocol](https://keel.kolektiv.computer/docs/implementing/protocol/): seed JSON, headers, status codes, path grammar, CSRF, `/__keel/schema`, realtime envelope +- [Host adapter](https://keel.kolektiv.computer/docs/implementing/host-adapter/): what a backend must implement, `KeelConfig` knobs (including `realtime { }`) - [Pack adapter](https://keel.kolektiv.computer/docs/implementing/pack-adapter/): PageModule, .feb, RouterAdapter, manifest head/layout fields -- [Typegen](https://keel.kolektiv.computer/docs/implementing/typegen/): `.ts`, `.d.ts`, JSON contract -- [Framework adapters](https://keel.kolektiv.computer/docs/implementing/framework-adapters/): one pack contract across Svelte, React, Vue, Solid, Preact, Lit, and Angular — install, bootstrap, page state, forms, actions, components, guards, mount, and DX caveats +- [Typegen](https://keel.kolektiv.computer/docs/implementing/typegen/): `.ts`, `.d.ts`, JSON contract — pages, actions, typed events +- [Framework adapters](https://keel.kolektiv.computer/docs/implementing/framework-adapters/): one pack contract across Svelte, React, Vue, Solid, Preact, Lit, and Angular — install, bootstrap, page state, forms, actions, realtime helpers, components, guards, mount, and DX caveats - [AGENTS.md](https://github.com/KolektivComputer/keel/blob/main/AGENTS.md): how to work in this repository ## Optional diff --git a/packages/angular/package.json b/packages/angular/package.json index f51cecc..1ab8eeb 100644 --- a/packages/angular/package.json +++ b/packages/angular/package.json @@ -1,6 +1,6 @@ { "name": "@kolektiv/keel-angular", - "version": "0.1.2", + "version": "0.2.1", "description": "Keel Angular 19 bindings \u2014 signal page/form state, query/action injectables, link/form/head directives, and createPage.", "type": "module", "license": "Apache-2.0", diff --git a/packages/angular/src/event.ts b/packages/angular/src/event.ts new file mode 100644 index 0000000..3443213 --- /dev/null +++ b/packages/angular/src/event.ts @@ -0,0 +1,16 @@ +import { DestroyRef, inject } from "@angular/core" +import { realtime, type RealtimeMessage } from "@kolektiv/keel" + +/** + * Subscribes to a typed realtime event until the injection context (usually + * the component) is destroyed. The latest handler is used, so inline + * closures do not resubscribe. + */ +export function injectKeelEvent( + event: string, + handler: (data: T, message: RealtimeMessage) => void, +): void { + const latest = { current: handler } + const release = realtime.on(event, (data, message) => latest.current(data, message)) + inject(DestroyRef).onDestroy(release) +} diff --git a/packages/angular/src/index.ts b/packages/angular/src/index.ts index 2af95c8..dd58426 100644 --- a/packages/angular/src/index.ts +++ b/packages/angular/src/index.ts @@ -3,6 +3,7 @@ export { injectKeelContext, KeelContext } from "./context.js" export { injectKeelPage, type KeelPage } from "./page.js" export { injectKeelForm, type FormState } from "./form.js" export { injectNavigationGuard, injectUnloadGuard } from "./guards.js" +export { injectKeelEvent } from "./event.js" export { KeelHead } from "./head.js" export { applyHead, @@ -12,7 +13,7 @@ export { syncHead, type HeadInput, } from "./head.js" -export { router, ActionError } from "@kolektiv/keel" +export { realtime, router, ActionError, type RealtimeMessage } from "@kolektiv/keel" export type { GuardResult, NavigationGuard, NavigationTarget } from "@kolektiv/keel" export { getQueryClient, diff --git a/packages/angular/test/event.test.ts b/packages/angular/test/event.test.ts new file mode 100644 index 0000000..cf884a8 --- /dev/null +++ b/packages/angular/test/event.test.ts @@ -0,0 +1,59 @@ +import "./setup.ts" +import assert from "node:assert/strict" +import { test } from "node:test" +import { realtime, type RealtimeMessage } from "@kolektiv/keel" +import { injectKeelEvent } from "../dist/index.js" +import { createPage } from "../dist/mount.js" +import { context, host, jit } from "./helpers.ts" + +interface Captured { + event: string + handler: (data: unknown, message: RealtimeMessage) => void +} + +let probe: { seen: string[] } | undefined + +const EventProbe = jit({ + selector: "keel-test-event-probe", + template: `

probe

`, +})(class { + readonly seen: string[] = [] + + constructor() { + injectKeelEvent<{ text: string }>("harbor.message", (data) => { + this.seen.push(data.text) + }) + probe = this + } +}) + +test("injectKeelEvent releases when the injector is destroyed", async () => { + const captured: Captured[] = [] + let released = 0 + const originalOn = realtime.on + ;(realtime as { on: typeof realtime.on }).on = ((event: string, handler: never) => { + captured.push({ event, handler }) + return () => { + released += 1 + } + }) as typeof realtime.on + + try { + const element = host() + const page = createPage(EventProbe) + await page.mount(element, context("/")) + + assert.equal(captured.length, 1) + assert.equal(captured[0].event, "harbor.message") + captured[0].handler( + { text: "one" }, + { event: "harbor.message", channel: "page:harbor.home", data: { text: "one" }, id: null }, + ) + assert.deepEqual(probe?.seen, ["one"]) + + await page.unmount() + assert.equal(released, 1) + } finally { + ;(realtime as { on: typeof realtime.on }).on = originalOn + } +}) diff --git a/packages/core/package.json b/packages/core/package.json index 72b7369..b4f5850 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@kolektiv/keel", - "version": "0.1.2", + "version": "0.2.1", "description": "Keel host router \u2014 visits, seed, history, prefetch.", "type": "module", "license": "Apache-2.0", diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 961a882..52a10fe 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -4,6 +4,8 @@ export { KEEL_FORMAT, KEEL_HEADERS, KEEL_NAVIGATE_PATH, + KEEL_REALTIME_PATH, + KEEL_REALTIME_VERSION, KEEL_SCHEMA_PATH, KEEL_SEED_ELEMENT_ID, KEEL_SEED_VERSION, @@ -44,3 +46,11 @@ export { type FormStore, } from "./form.ts" export { KEEL_PAGE_QUERY_KEY, pageQueryKey } from "./query.ts" +export { + realtime, + type KeelRealtimeEnvelope, + type KeelRealtimeInvalidate, + type RealtimeMessage, + type RealtimeOptions, + type RealtimeStatus, +} from "./realtime.ts" diff --git a/packages/core/src/realtime.test.ts b/packages/core/src/realtime.test.ts new file mode 100644 index 0000000..a38d9b2 --- /dev/null +++ b/packages/core/src/realtime.test.ts @@ -0,0 +1,312 @@ +import assert from "node:assert/strict" +import { afterEach, beforeEach, test } from "node:test" +import { realtime } from "./realtime.ts" +import { router } from "./router.ts" +import { setPage } from "./store.ts" +import type { KeelRealtimeEnvelope, KeelSeed } from "./types.ts" + +class FakeSocket { + static instances: FakeSocket[] = [] + + readonly url: string + readyState = 0 + sent: string[] = [] + onopen: (() => void) | null = null + onmessage: ((event: { data: string }) => void) | null = null + onerror: (() => void) | null = null + onclose: (() => void) | null = null + + constructor(url: string) { + this.url = url + FakeSocket.instances.push(this) + } + + open(): void { + this.readyState = 1 + this.onopen?.() + } + + receive(envelope: KeelRealtimeEnvelope): void { + this.onmessage?.({ data: JSON.stringify(envelope) }) + } + + send(data: string): void { + this.sent.push(data) + } + + close(): void { + if (this.readyState === 3) return + this.readyState = 3 + this.onclose?.() + } + + sentEnvelopes(): KeelRealtimeEnvelope[] { + return this.sent.map((raw) => JSON.parse(raw) as KeelRealtimeEnvelope) + } +} + +class FakeController { + static current: FakeController | null = null + + private readonly controller: ReadableStreamDefaultController + readonly response: Response + + constructor(initial: KeelRealtimeEnvelope[] = []) { + const encoder = new TextEncoder() + const body = new ReadableStream({ + start: (controller) => { + this.controller = controller + for (const envelope of initial) this.push(envelope) + }, + }) + this.response = new Response(body, { + status: 200, + headers: { "Content-Type": "text/event-stream" }, + }) + FakeController.current = this + } + + push(envelope: KeelRealtimeEnvelope): void { + const payload = `data: ${JSON.stringify(envelope)}\n\n` + this.controller.enqueue(new TextEncoder().encode(payload)) + } +} + +const globals = globalThis as Record +const original = { + location: globals.location, + WebSocket: globals.WebSocket, + fetch: globals.fetch, +} +const originalReload = router.reload + +let fetchCalls: Array<{ url: string; init?: RequestInit }> = [] +let reloadCalls: Array | undefined> = [] +let fetchResponder: (url: string, init?: RequestInit) => Promise + +function seed(page = "harbor.home", path = "/"): KeelSeed { + return { + v: 1, + page, + path, + params: {}, + data: {}, + errors: {}, + theme: { id: "harbor", version: "1" }, + entry: "data:text/javascript,export%20function%20mount()%20%7B%7D", + css: [], + host: "#__keel_root", + } +} + +function installGlobals(options: { socket?: boolean } = {}): void { + globals.location = { href: "http://localhost/", protocol: "http:", host: "localhost" } + if (options.socket === false) delete globals.WebSocket + else globals.WebSocket = FakeSocket + globals.fetch = (async (input: unknown, init?: RequestInit) => { + const url = String(input) + fetchCalls.push({ url, init }) + return fetchResponder(url, init) + }) as unknown as typeof fetch +} + +function waitFor(predicate: () => boolean, timeoutMs = 2000): Promise { + const started = Date.now() + return new Promise((resolve, reject) => { + const tick = () => { + if (predicate()) return resolve() + if (Date.now() - started > timeoutMs) return reject(new Error("timed out waiting for condition")) + setTimeout(tick, 5) + } + tick() + }) +} + +function ready(channels: string[] = ["page:harbor.home"], sid = "rt-test"): KeelRealtimeEnvelope { + return { v: 1, type: "ready", sid, channels } +} + +beforeEach(() => { + FakeSocket.instances = [] + FakeController.current = null + fetchCalls = [] + reloadCalls = [] + fetchResponder = async () => new Response("{}", { status: 202 }) + ;(router as { reload: typeof router.reload }).reload = async (options) => { + reloadCalls.push(options as Record | undefined) + } + installGlobals() + realtime.reset() + realtime.configure({ minReconnectDelayMs: 1, maxReconnectDelayMs: 5 }) +}) + +afterEach(() => { + realtime.reset() + ;(router as { reload: typeof router.reload }).reload = originalReload + if (original.location === undefined) delete globals.location + else globals.location = original.location + if (original.WebSocket === undefined) delete globals.WebSocket + else globals.WebSocket = original.WebSocket + globals.fetch = original.fetch +}) + +test("connects over websocket and subscribes the page channel", async () => { + setPage(seed()) + realtime.connect() + const socket = FakeSocket.instances[0] + assert.ok(socket, "websocket opened") + assert.match(socket.url, /^ws:\/\/localhost\/__keel\/events\?channels=page%3Aharbor\.home$/) + socket.open() + assert.equal(realtime.status(), "connecting") + + socket.receive(ready()) + assert.equal(realtime.status(), "open") + assert.equal(realtime.sid(), "rt-test") + + // A later seed change diffs the page channel. + setPage(seed("harbor.user", "/u/1")) + const envelopes = socket.sentEnvelopes() + const subscribe = envelopes.filter((envelope) => envelope.type === "subscribe").at(-1) + const unsubscribe = envelopes.filter((envelope) => envelope.type === "unsubscribe").at(-1) + assert.deepEqual(subscribe?.channels, ["page:harbor.user"]) + assert.deepEqual(unsubscribe?.channels, ["page:harbor.home"]) +}) + +test("subscribe and unsubscribe diff channels", async () => { + setPage(seed()) + realtime.connect() + const socket = FakeSocket.instances[0] + socket.open() + socket.receive(ready()) + + const release = realtime.subscribe("user:42") + assert.deepEqual(socket.sentEnvelopes().at(-1), { + v: 1, + type: "subscribe", + channels: ["user:42"], + }) + + release() + assert.deepEqual(socket.sentEnvelopes().at(-1), { + v: 1, + type: "unsubscribe", + channels: ["user:42"], + }) +}) + +test("typed events reach handlers with channel and id", async () => { + setPage(seed()) + const seen: Array = [] + const release = realtime.on<{ text: string }>("harbor.message", (data, message) => { + seen.push({ data, channel: message.channel, id: message.id }) + }) + const socket = FakeSocket.instances[0] + socket.open() + socket.receive(ready()) + + socket.receive({ + v: 1, + type: "event", + channel: "page:harbor.home", + event: "harbor.message", + id: "c1", + data: { text: "ahoy" }, + }) + assert.deepEqual(seen, [{ data: { text: "ahoy" }, channel: "page:harbor.home", id: "c1" }]) + + release() + socket.receive({ v: 1, type: "event", event: "harbor.message", data: { text: "ignored" } }) + assert.equal(seen.length, 1) +}) + +test("invalidate reloads the page unless a handler is registered", async () => { + setPage(seed()) + realtime.connect() + const socket = FakeSocket.instances[0] + socket.open() + socket.receive(ready()) + + socket.receive({ v: 1, type: "invalidate", channel: "page:harbor.home", data: { path: "/" } }) + await waitFor(() => reloadCalls.length === 1) + assert.deepEqual(reloadCalls[0], { preserveState: true }) + + const seen: unknown[] = [] + realtime.onInvalidate((invalidate) => seen.push(invalidate)) + socket.receive({ + v: 1, + type: "invalidate", + channel: "page:harbor.home", + data: { path: "/", only: ["feed"] }, + }) + await waitFor(() => seen.length === 1) + assert.deepEqual(seen[0], { path: "/", only: ["feed"] }) + assert.equal(reloadCalls.length, 1) +}) + +test("sse fallback streams events and posts sends by sid", async () => { + installGlobals({ socket: false }) + const stream = new FakeController([ready(["page:harbor.home"])]) + fetchResponder = async (url, init) => { + if (init?.method === "POST") return new Response("{}", { status: 202 }) + return stream.response + } + realtime.configure({ transport: "sse" }) + setPage(seed()) + + const received: unknown[] = [] + realtime.on("harbor.message", (data) => received.push(data)) + await waitFor(() => realtime.status() === "open") + assert.equal(realtime.sid(), "rt-test") + + stream.push({ + v: 1, + type: "event", + channel: "page:harbor.home", + event: "harbor.message", + data: { text: "over sse" }, + }) + await waitFor(() => received.length === 1) + assert.deepEqual(received[0], { text: "over sse" }) + + await realtime.send("harbor.shout", { text: "hello" }) + const post = fetchCalls.find((call) => call.init?.method === "POST") + assert.ok(post, "send posted to the host") + const body = JSON.parse(String(post.init?.body)) as KeelRealtimeEnvelope + assert.equal(body.type, "send") + assert.equal(body.event, "harbor.shout") + assert.equal(body.sid, "rt-test") + + realtime.subscribe("user:7") + await waitFor(() => fetchCalls.filter((call) => call.init?.method === "POST").length === 2) + const subscribe = JSON.parse(String(fetchCalls.at(-1)?.init?.body)) as KeelRealtimeEnvelope + assert.equal(subscribe.type, "subscribe") + assert.deepEqual(subscribe.channels, ["user:7"]) +}) + +test("reconnects with backoff, resubscribes, and resyncs the seed", async () => { + setPage(seed()) + realtime.connect() + const first = FakeSocket.instances[0] + first.open() + first.receive(ready()) + + first.close() + assert.equal(realtime.status(), "reconnecting") + await waitFor(() => FakeSocket.instances.length === 2) + const second = FakeSocket.instances[1] + assert.match(second.url, /channels=page%3Aharbor\.home/) + second.open() + second.receive(ready()) + assert.equal(realtime.status(), "open") + await waitFor(() => reloadCalls.length === 1) + assert.deepEqual(reloadCalls[0], { preserveState: true }) +}) + +test("send before the stream is ready rejects", async () => { + installGlobals({ socket: false }) + fetchResponder = async () => new Response("{}", { status: 202 }) + realtime.configure({ transport: "sse", reconnect: false }) + setPage(seed()) + realtime.connect() + await assert.rejects(() => realtime.send("harbor.shout", {})) +}) diff --git a/packages/core/src/realtime.ts b/packages/core/src/realtime.ts new file mode 100644 index 0000000..5ce4c49 --- /dev/null +++ b/packages/core/src/realtime.ts @@ -0,0 +1,585 @@ +import { router } from "./router.ts" +import { peekPage, subscribe as subscribeSeed } from "./store.ts" +import { + KEEL_REALTIME_PATH, + KEEL_REALTIME_VERSION, + type KeelSeed, +} from "./types.ts" + +/** Connection lifecycle the client reports to [realtime.onStatus] listeners. */ +export type RealtimeStatus = "idle" | "connecting" | "open" | "reconnecting" | "closed" + +/** Envelope types both directions of the wire contract use. */ +export type RealtimeEnvelopeType = + | "ready" + | "event" + | "invalidate" + | "error" + | "ping" + | "subscribe" + | "unsubscribe" + | "send" + +/** + * The boring JSON envelope Keel realtime speaks. Server-to-client envelopes + * carry a `channel` and, for `event`, an `event` id and payload `data`. + * `sid` names a stream so SSE clients can address it over HTTP `POST`. + */ +export interface KeelRealtimeEnvelope { + v: number + type: RealtimeEnvelopeType + sid?: string | null + channel?: string | null + channels?: string[] | null + event?: string | null + data?: T + id?: string | null + error?: string | null +} + +/** Payload of an `invalidate` envelope: rehydrate the seed with a visit. */ +export interface KeelRealtimeInvalidate { + path?: string | null + only?: string[] | null + except?: string[] | null +} + +/** One typed domain event delivered to [realtime.on] handlers. */ +export interface RealtimeMessage { + event: string + channel: string | null + data: T + id: string | null +} + +export interface RealtimeOptions { + /** Realtime endpoint. Defaults to [KEEL_REALTIME_PATH] on this origin. */ + url?: string + /** + * `auto` (default) tries WebSocket and falls back to SSE. `websocket` and + * `sse` pin one transport. + */ + transport?: "auto" | "websocket" | "sse" + /** + * Extra channels to hold. A seed-derived default of `page:` is + * added unless [autoChannels] is `false`. + */ + channels?: string[] | ((seed: KeelSeed | null) => string[]) + /** Auto-subscribe to `page:` as the seed changes. Default true. */ + autoChannels?: boolean + /** Reconnect with backoff after a dropped transport. Default true. */ + reconnect?: boolean + /** First reconnect delay in ms. Default 500. */ + minReconnectDelayMs?: number + /** Reconnect delay ceiling in ms. Default 15000. */ + maxReconnectDelayMs?: number + /** + * Rehydrate the current page with `router.reload()` after a reconnect that + * followed a live connection, so events missed while offline are covered by + * a fresh seed. Default true. + */ + resyncOnReconnect?: boolean + /** + * Reload the current page when an `invalidate` envelope arrives on a + * subscribed channel and no `onInvalidate` handler is registered. Default + * true. + */ + reloadOnInvalidate?: boolean + /** Called on every status change. */ + onStatus?: (status: RealtimeStatus) => void +} + +type RealtimeEvent = (data: T, message: RealtimeMessage) => void +type InvalidateHandler = (invalidate: KeelRealtimeInvalidate) => void + +const DEFAULTS = { + url: KEEL_REALTIME_PATH, + transport: "auto" as const, + autoChannels: true, + reconnect: true, + minReconnectDelayMs: 500, + maxReconnectDelayMs: 15_000, + resyncOnReconnect: true, + reloadOnInvalidate: true, +} + +let options: RealtimeOptions = { ...DEFAULTS } +let status: RealtimeStatus = "idle" +let sid: string | null = null +let socket: WebSocket | null = null +let stream: AbortController | null = null +let reconnectTimer: ReturnType | null = null +let reconnectAttempt = 0 +let connectedOnce = false +let stopped = true +let lastSeen = 0 +let seedUnsubscribe: (() => void) | null = null + +const manualChannels = new Set() +const autoChannels = new Set() +const serverChannels = new Set() +const eventHandlers = new Map>() +const invalidateHandlers = new Set() +const statusListeners = new Set<(status: RealtimeStatus) => void>() + +function setStatus(next: RealtimeStatus): void { + if (status === next) return + status = next + options.onStatus?.(next) + for (const listener of statusListeners) listener(next) +} + +function desiredChannels(): string[] { + return [...new Set([...autoChannels, ...manualChannels])] +} + +function applySeedChannels(seed: KeelSeed | null): void { + const extra = typeof options.channels === "function" + ? options.channels(seed) + : options.channels ?? [] + const page = options.autoChannels === false || !seed ? [] : [`page:${seed.page}`] + autoChannels.clear() + for (const channel of [...page, ...extra]) autoChannels.add(channel) + syncChannels() +} + +function startSeedTracking(): void { + if (seedUnsubscribe) return + seedUnsubscribe = subscribeSeed((seed) => applySeedChannels(seed)) +} + +function endpoint(): string { + return options.url ?? DEFAULTS.url +} + +function absoluteEndpoint(): string { + const url = endpoint() + if (/^[a-z]+:\/\//i.test(url) || typeof location === "undefined") return url + return new URL(url, location.href).toString() +} + +function socketEndpoint(): string | null { + if (typeof WebSocket === "undefined") return null + const url = endpoint() + if (!/^[a-z]+:\/\//i.test(url) && typeof location === "undefined") return null + const resolved = new URL(url, typeof location === "undefined" ? undefined : location.href) + resolved.protocol = resolved.protocol === "https:" ? "wss:" : "ws:" + return resolved.toString() +} + +function withChannels(url: string, channels: string[]): string { + if (channels.length === 0) return url + const resolved = new URL(url) + resolved.searchParams.set("channels", channels.join(",")) + return resolved.toString() +} + +function parseEnvelope(raw: string): KeelRealtimeEnvelope | null { + try { + const parsed = JSON.parse(raw) as KeelRealtimeEnvelope + return typeof parsed?.type === "string" ? parsed : null + } catch { + return null + } +} + +function encode(envelope: KeelRealtimeEnvelope): string { + return JSON.stringify(envelope) +} + +// --- transport ------------------------------------------------------- + +/** Opens the connection if it is not already connecting or open. */ +function connect(): void { + stopped = false + startSeedTracking() + if (socket || stream || reconnectTimer) return + openTransport() +} + +function openTransport(): void { + const preferred = options.transport ?? "auto" + setStatus(connectedOnce ? "reconnecting" : "connecting") + if (preferred === "sse") { + void openSse() + return + } + openWebSocket(() => { + if (preferred === "websocket") { + scheduleReconnect() + } else { + void openSse() + } + }) +} + +function openWebSocket(onUnavailable: () => void): void { + const url = socketEndpoint() + if (!url) { + onUnavailable() + return + } + let ws: WebSocket + try { + ws = new WebSocket(withChannels(url, desiredChannels())) + } catch { + onUnavailable() + return + } + let opened = false + let settled = false + const unavailable = () => { + if (settled) return + settled = true + if (socket === ws) socket = null + onUnavailable() + } + socket = ws + ws.onopen = () => { + if (stopped) { + ws.close() + return + } + opened = true + settled = true + socket = ws + } + ws.onmessage = (event) => { + const envelope = parseEnvelope(String(event.data)) + if (envelope) handleEnvelope(envelope) + } + ws.onerror = () => { + if (!opened) unavailable() + } + ws.onclose = () => { + if (socket === ws) socket = null + if (!opened) { + unavailable() + return + } + if (stopped) { + setStatus("closed") + return + } + scheduleReconnect() + } +} + +async function openSse(): Promise { + if (stream) return + const controller = new AbortController() + stream = controller + try { + const response = await fetch(withChannels(absoluteEndpoint(), desiredChannels()), { + method: "GET", + headers: { Accept: "text/event-stream" }, + credentials: "same-origin", + signal: controller.signal, + }) + if (!response.ok || !response.body) { + throw new Error(`Keel realtime SSE failed (${response.status})`) + } + await readEvents(response.body, (envelope) => handleEnvelope(envelope)) + if (stopped || controller.signal.aborted) return + stream = null + scheduleReconnect() + } catch { + if (stopped || controller.signal.aborted) return + stream = null + scheduleReconnect() + } +} + +async function readEvents( + body: ReadableStream, + onEnvelope: (envelope: KeelRealtimeEnvelope) => void, +): Promise { + const reader = body.getReader() + const decoder = new TextDecoder() + let buffer = "" + let data = "" + for (;;) { + const { done, value } = await reader.read() + if (done) break + buffer += decoder.decode(value, { stream: true }) + let newline = buffer.indexOf("\n") + while (newline >= 0) { + const line = buffer.slice(0, newline).replace(/\r$/, "") + buffer = buffer.slice(newline + 1) + if (line === "") { + if (data) { + const envelope = parseEnvelope(data) + if (envelope) onEnvelope(envelope) + } + data = "" + } else if (line.startsWith("data:")) { + data += line.slice(5).trimStart() + } + newline = buffer.indexOf("\n") + } + } +} + +function closeTransport(): void { + const ws = socket + socket = null + if (ws) { + ws.onopen = null + ws.onmessage = null + ws.onerror = null + ws.onclose = null + try { + ws.close() + } catch { + // already closed + } + } + const controller = stream + stream = null + controller?.abort() + clearReconnectTimer() + sid = null + serverChannels.clear() +} + +function clearReconnectTimer(): void { + if (reconnectTimer !== null) { + clearTimeout(reconnectTimer) + reconnectTimer = null + } +} + +function scheduleReconnect(): void { + if (stopped || options.reconnect === false) { + setStatus("closed") + return + } + setStatus("reconnecting") + const min = options.minReconnectDelayMs ?? DEFAULTS.minReconnectDelayMs + const max = options.maxReconnectDelayMs ?? DEFAULTS.maxReconnectDelayMs + const base = Math.min(max, min * 2 ** reconnectAttempt) + const delay = Math.round(base * (0.5 + Math.random() * 0.5)) + reconnectAttempt += 1 + reconnectTimer = setTimeout(() => { + reconnectTimer = null + openTransport() + }, delay) +} + +// --- envelopes ------------------------------------------------------- + +function handleEnvelope(envelope: KeelRealtimeEnvelope): void { + lastSeen = Date.now() + switch (envelope.type) { + case "ready": { + sid = envelope.sid ?? null + serverChannels.clear() + for (const channel of envelope.channels ?? []) serverChannels.add(channel) + const reconnect = connectedOnce + connectedOnce = true + reconnectAttempt = 0 + setStatus("open") + syncChannels() + if (reconnect && options.resyncOnReconnect !== false) void router.reload({ preserveState: true }) + break + } + case "event": { + const event = envelope.event + if (!event) return + const message: RealtimeMessage = { + event, + channel: envelope.channel ?? null, + data: envelope.data, + id: envelope.id ?? null, + } + for (const handler of eventHandlers.get(event) ?? []) { + try { + handler(message.data, message) + } catch (error) { + reportHandlerError(error) + } + } + break + } + case "invalidate": { + const invalidate = (envelope.data ?? {}) as KeelRealtimeInvalidate + let handled = false + for (const handler of invalidateHandlers) { + handled = true + try { + handler(invalidate) + } catch (error) { + reportHandlerError(error) + } + } + if (!handled && options.reloadOnInvalidate !== false) { + const page = peekPage() + const path = invalidate.path + if (!path || !page || path === page.path || path.split("?")[0] === page.path.split("?")[0]) { + void router.reload({ + preserveState: true, + ...(invalidate.only?.length ? { only: invalidate.only } : {}), + ...(invalidate.except?.length ? { except: invalidate.except } : {}), + }) + } + } + break + } + case "error": + // Server-reported rejections (unknown event, denied channel) are not + // fatal; the connection stays up. + break + case "ping": + break + default: + break + } +} + +function reportHandlerError(error: unknown): void { + if (typeof console !== "undefined") console.error("Keel realtime handler failed", error) +} + +function sendEnvelope(envelope: KeelRealtimeEnvelope): void { + if (socket && socket.readyState === 1) { + socket.send(encode(envelope)) + return + } + if (sid) { + void postEnvelope({ ...envelope, sid }).catch(reportHandlerError) + } +} + +function postEnvelope(envelope: KeelRealtimeEnvelope): Promise { + return fetch(absoluteEndpoint(), { + method: "POST", + headers: { "Content-Type": "application/json", Accept: "application/json" }, + credentials: "same-origin", + body: encode(envelope), + }) +} + +function syncChannels(): void { + const desired = desiredChannels() + if (socket && socket.readyState === 1) { + const added = desired.filter((channel) => !serverChannels.has(channel)) + const removed = [...serverChannels].filter((channel) => !desired.includes(channel)) + if (added.length > 0) sendEnvelope({ v: KEEL_REALTIME_VERSION, type: "subscribe", channels: added }) + if (removed.length > 0) sendEnvelope({ v: KEEL_REALTIME_VERSION, type: "unsubscribe", channels: removed }) + for (const channel of added) serverChannels.add(channel) + for (const channel of removed) serverChannels.delete(channel) + return + } + // SSE subscribes through POST once the stream reported its sid. + if (sid) { + const added = desired.filter((channel) => !serverChannels.has(channel)) + const removed = [...serverChannels].filter((channel) => !desired.includes(channel)) + if (added.length > 0) { + void postEnvelope({ v: KEEL_REALTIME_VERSION, type: "subscribe", sid, channels: added }) + for (const channel of added) serverChannels.add(channel) + } + if (removed.length > 0) { + void postEnvelope({ v: KEEL_REALTIME_VERSION, type: "unsubscribe", sid, channels: removed }) + for (const channel of removed) serverChannels.delete(channel) + } + } +} + +// --- public surface -------------------------------------------------- + +function subscribe(channel: string): () => void { + manualChannels.add(channel) + connect() + syncChannels() + return () => { + manualChannels.delete(channel) + syncChannels() + } +} + +function on(event: string, handler: RealtimeEvent): () => void { + let handlers = eventHandlers.get(event) + if (!handlers) { + handlers = new Set() + eventHandlers.set(event, handlers) + } + handlers.add(handler as RealtimeEvent) + connect() + return () => { + handlers.delete(handler as RealtimeEvent) + if (handlers.size === 0) eventHandlers.delete(event) + } +} + +function onInvalidate(handler: InvalidateHandler): () => void { + invalidateHandlers.add(handler) + connect() + return () => { + invalidateHandlers.delete(handler) + } +} + +function onStatus(listener: (next: RealtimeStatus) => void): () => void { + statusListeners.add(listener) + return () => { + statusListeners.delete(listener) + } +} + +function send(event: string, data?: I): Promise { + connect() + if (socket && socket.readyState === 1) { + socket.send(encode({ v: KEEL_REALTIME_VERSION, type: "send", event, data })) + return Promise.resolve() + } + if (sid) { + return postEnvelope({ v: KEEL_REALTIME_VERSION, type: "send", sid, event, data }).then(() => undefined) + } + return Promise.reject(new Error("Keel realtime: not connected")) +} + +function disconnect(): void { + stopped = true + closeTransport() + setStatus("closed") +} + +/** Disconnect and drop handlers, subscriptions, and options (tests, SSR). */ +function reset(): void { + disconnect() + manualChannels.clear() + autoChannels.clear() + eventHandlers.clear() + invalidateHandlers.clear() + statusListeners.clear() + seedUnsubscribe?.() + seedUnsubscribe = null + reconnectAttempt = 0 + connectedOnce = false + options = { ...DEFAULTS } + status = "idle" +} + +/** + * Realtime client, sibling to visits and actions. Register handlers with + * [on], hold channels with [subscribe], send client events with [send], and + * let `invalidate` envelopes rehydrate the page. Connections resume with + * backoff; on reconnect the client resubscribes and (by default) reloads the + * current seed. + */ +export const realtime = { + configure(next: RealtimeOptions): void { + options = { ...options, ...next } + }, + connect, + disconnect, + reset, + subscribe, + on, + onInvalidate, + onStatus, + send, + status: (): RealtimeStatus => status, + sid: (): string | null => sid, + lastSeen: (): number => lastSeen, +} diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index 298378a..0dabc9d 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -5,6 +5,8 @@ export const KEEL_SEED_ELEMENT_ID = "__keel_seed" export const KEEL_NAVIGATE_PATH = "/__keel/navigate" export const KEEL_ACTION_PATH = "/__keel/action" export const KEEL_SCHEMA_PATH = "/__keel/schema" +export const KEEL_REALTIME_PATH = "/__keel/events" +export const KEEL_REALTIME_VERSION = 1 export const KEEL_HEADERS = { visit: "X-Keel-Visit", diff --git a/packages/lit/package.json b/packages/lit/package.json index 7c9a3f8..e5f30fc 100644 --- a/packages/lit/package.json +++ b/packages/lit/package.json @@ -1,6 +1,6 @@ { "name": "@kolektiv/keel-lit", - "version": "0.1.2", + "version": "0.2.1", "description": "Keel Lit 3 bindings \u2014 page/form/action controllers, link/form/head helpers, and createPage.", "type": "module", "license": "Apache-2.0", diff --git a/packages/lit/src/event.ts b/packages/lit/src/event.ts new file mode 100644 index 0000000..5eac850 --- /dev/null +++ b/packages/lit/src/event.ts @@ -0,0 +1,36 @@ +import type { ReactiveController, ReactiveControllerHost } from "lit" +import { realtime, type RealtimeMessage } from "@kolektiv/keel" + +/** + * Lit controller that holds one typed realtime subscription for the host's + * lifetime. Prefer {@link useKeelEvent}. + */ +export class KeelEventController implements ReactiveController { + private release: (() => void) | null = null + + constructor( + private readonly host: ReactiveControllerHost, + private readonly event: string, + private readonly handler: (data: T, message: RealtimeMessage) => void, + ) { + host.addController(this) + } + + hostConnected(): void { + this.release = realtime.on(this.event, (data, message) => this.handler(data, message)) + } + + hostDisconnected(): void { + this.release?.() + this.release = null + } +} + +/** Subscribes the host element to a typed realtime event. */ +export function useKeelEvent( + host: ReactiveControllerHost, + event: string, + handler: (data: T, message: RealtimeMessage) => void, +): KeelEventController { + return new KeelEventController(host, event, handler) +} diff --git a/packages/lit/src/index.ts b/packages/lit/src/index.ts index 8eeb0d8..c354380 100644 --- a/packages/lit/src/index.ts +++ b/packages/lit/src/index.ts @@ -10,7 +10,7 @@ export { } from "./guards.js" export type { GuardResult, NavigationGuard, NavigationTarget } from "@kolektiv/keel" export { applyHead, fromPageHead, setTitle, syncHead, type HeadInput } from "./head.js" -export { router, ActionError } from "@kolektiv/keel" +export { realtime, router, ActionError, type RealtimeMessage } from "@kolektiv/keel" export { getQueryClient, hydrateKeelQuery, @@ -21,6 +21,7 @@ export { useKeelPageQuery, type UseActionOptions, } from "./query.js" +export { KeelEventController, useKeelEvent } from "./event.js" export { Link } from "./Link.js" export { form, type FormOptions } from "./Form.js" export { Head } from "./HeadElement.js" diff --git a/packages/lit/test/event.test.ts b/packages/lit/test/event.test.ts new file mode 100644 index 0000000..cb32d05 --- /dev/null +++ b/packages/lit/test/event.test.ts @@ -0,0 +1,61 @@ +import "./setup.ts" +import assert from "node:assert/strict" +import { test } from "node:test" +import { realtime, type RealtimeMessage } from "@kolektiv/keel" +import { html, LitElement } from "lit" +import { useKeelEvent } from "../dist/index.js" +import { host } from "./helpers.ts" + +interface Captured { + event: string + handler: (data: unknown, message: RealtimeMessage) => void +} + +class EventProbe extends LitElement { + readonly seen: string[] = [] + + constructor() { + super() + useKeelEvent<{ text: string }>(this, "harbor.message", (data) => { + this.seen.push(data.text) + }) + } + + render() { + return html`probe` + } +} + +customElements.define("test-event-probe", EventProbe) + +test("useKeelEvent holds the subscription for the element lifetime", async () => { + const captured: Captured[] = [] + let released = 0 + const originalOn = realtime.on + ;(realtime as { on: typeof realtime.on }).on = ((event: string, handler: never) => { + captured.push({ event, handler }) + return () => { + released += 1 + } + }) as typeof realtime.on + + try { + const view = host() + const element = document.createElement("test-event-probe") as EventProbe + view.append(element) + await element.updateComplete + + assert.equal(captured.length, 1) + assert.equal(captured[0].event, "harbor.message") + captured[0].handler( + { text: "one" }, + { event: "harbor.message", channel: "page:harbor.home", data: { text: "one" }, id: null }, + ) + assert.deepEqual(element.seen, ["one"]) + + element.remove() + assert.equal(released, 1) + } finally { + ;(realtime as { on: typeof realtime.on }).on = originalOn + } +}) diff --git a/packages/pack/package.json b/packages/pack/package.json index 0a968ba..26aac72 100644 --- a/packages/pack/package.json +++ b/packages/pack/package.json @@ -1,6 +1,6 @@ { "name": "@kolektiv/keel-pack", - "version": "0.1.2", + "version": "0.2.1", "description": "Zip a Keel pack dist into a .feb archive, scaffold packs from /__keel/schema, and a Vite plugin to discover pages.", "type": "module", "license": "Apache-2.0", diff --git a/packages/pack/src/scaffold.test.ts b/packages/pack/src/scaffold.test.ts index 4266e79..bd67154 100644 --- a/packages/pack/src/scaffold.test.ts +++ b/packages/pack/src/scaffold.test.ts @@ -23,11 +23,15 @@ const schema = { actions: { "harbor.setName": { in: "SetNameIn", out: "SetNameOut" }, }, + events: { + "harbor.message": { direction: "out", type: "BoardEvent" }, + }, types: { HomePage: { kind: "object", fields: { greeting: "string" } }, NotFoundPage: { kind: "object", fields: { path: "string" } }, SetNameIn: { kind: "object", fields: { displayName: "string" } }, SetNameOut: { kind: "object", fields: { ok: "boolean" } }, + BoardEvent: { kind: "object", fields: { text: "string" } }, }, } @@ -141,6 +145,14 @@ test("emitTypescript writes pages and actions", () => { assert.match(ts, /"harbor.setName": \{ in: SetNameIn; out: SetNameOut \}/) }) +test("emitTypescript writes typed events", () => { + const ts = emitTypescript(schema, "HarborPages") + assert.match(ts, /export interface BoardEvent/) + assert.match(ts, /export interface HarborEvents/) + assert.match(ts, /"harbor.message": BoardEvent/) + assert.match(ts, /export type HarborEventId = keyof HarborEvents/) +}) + test("scaffoldPack writes svelte pages from a schema file", async () => { const root = mkdtempSync(join(tmpdir(), "keel-scaffold-")) const schemaFile = join(root, "schema.json") diff --git a/packages/pack/src/scaffold.ts b/packages/pack/src/scaffold.ts index bfd3c4d..fd18908 100644 --- a/packages/pack/src/scaffold.ts +++ b/packages/pack/src/scaffold.ts @@ -126,6 +126,12 @@ export function emitTypescript(schema: PackSchema, pagesName: string): string { const actionIdName = pagesName.endsWith("Pages") ? `${pagesName.slice(0, -5) || ""}ActionId` : `${pagesName}ActionId` + const eventsName = pagesName.endsWith("Pages") + ? `${pagesName.slice(0, -5) || ""}Events` + : `${pagesName}Events` + const eventIdName = pagesName.endsWith("Pages") + ? `${pagesName.slice(0, -5) || ""}EventId` + : `${pagesName}EventId` const lines = ["// Generated by keel-scaffold from GET /__keel/schema. Do not edit.", ""] for (const [name, type] of Object.entries(schema.types ?? {})) { lines.push(...emitType(name, type), "") @@ -143,6 +149,14 @@ export function emitTypescript(schema: PackSchema, pagesName: string): string { } lines.push("}", "", `export type ${actionIdName} = keyof ${actionsName}`) } + const events = schema.events ?? {} + if (Object.keys(events).length > 0) { + lines.push("", `export interface ${eventsName} {`) + for (const [id, event] of Object.entries(events)) { + lines.push(` ${JSON.stringify(id)}: ${event.type}`) + } + lines.push("}", "", `export type ${eventIdName} = keyof ${eventsName}`) + } return `${lines.join("\n")}\n` } diff --git a/packages/pack/src/schema.ts b/packages/pack/src/schema.ts index fa87f75..712e11f 100644 --- a/packages/pack/src/schema.ts +++ b/packages/pack/src/schema.ts @@ -11,6 +11,11 @@ export interface SchemaAction { out: string } +export interface SchemaEvent { + direction: "in" | "out" | "both" | string + type: string +} + export interface SchemaType { kind: "object" | "enum" | string fields?: Record @@ -22,6 +27,7 @@ export interface PackSchema { pagesName?: string pages: Record actions?: Record + events?: Record types?: Record } diff --git a/packages/preact/package.json b/packages/preact/package.json index d7c8c09..f2b54fd 100644 --- a/packages/preact/package.json +++ b/packages/preact/package.json @@ -1,6 +1,6 @@ { "name": "@kolektiv/keel-preact", - "version": "0.1.2", + "version": "0.2.1", "description": "Keel Preact 10 bindings \u2014 Link, Form, Head, usePage, useForm, useAction.", "type": "module", "license": "Apache-2.0", diff --git a/packages/preact/src/event.ts b/packages/preact/src/event.ts new file mode 100644 index 0000000..3d402e7 --- /dev/null +++ b/packages/preact/src/event.ts @@ -0,0 +1,18 @@ +import { useEffect, useRef } from "preact/hooks" +import { realtime, type RealtimeMessage } from "@kolektiv/keel" + +/** + * Subscribes to a typed realtime event for the component's lifetime. The + * latest handler is used, so inline closures do not resubscribe. + */ +export function useKeelEvent( + event: string, + handler: (data: T, message: RealtimeMessage) => void, +): void { + const latest = useRef(handler) + latest.current = handler + useEffect( + () => realtime.on(event, (data, message) => latest.current(data, message)), + [event], + ) +} diff --git a/packages/preact/src/index.ts b/packages/preact/src/index.ts index 119ac8c..62b6fa6 100644 --- a/packages/preact/src/index.ts +++ b/packages/preact/src/index.ts @@ -5,7 +5,7 @@ export { useForm, type FormState } from "./useForm.js" export { useNavigationGuard, useUnloadGuard } from "./guards.js" export type { GuardResult, NavigationGuard, NavigationTarget } from "@kolektiv/keel" export { applyHead, fromPageHead, setTitle, syncHead, type HeadInput } from "./head.js" -export { router, ActionError } from "@kolektiv/keel" +export { realtime, router, ActionError, type RealtimeMessage } from "@kolektiv/keel" export { getQueryClient, hydrateKeelQuery, @@ -18,3 +18,4 @@ export { Link, type LinkProps } from "./Link.js" export { Form, type FormProps } from "./Form.js" export { Head, type HeadProps } from "./Head.js" export { useKeelAnchor, type KeelAnchorParams, type KeelAnchorProps } from "./anchor.js" +export { useKeelEvent } from "./event.js" diff --git a/packages/preact/test/event.test.ts b/packages/preact/test/event.test.ts new file mode 100644 index 0000000..ba510db --- /dev/null +++ b/packages/preact/test/event.test.ts @@ -0,0 +1,48 @@ +import "./setup.ts" +import assert from "node:assert/strict" +import { test } from "node:test" +import { createElement } from "preact" +import { realtime, type RealtimeMessage } from "@kolektiv/keel" +import { useKeelEvent } from "../dist/index.js" +import { render } from "./helpers.ts" + +interface Captured { + event: string + handler: (data: unknown, message: RealtimeMessage) => void +} + +test("useKeelEvent subscribes on mount and releases on unmount", async () => { + const captured: Captured[] = [] + let released = 0 + const originalOn = realtime.on + ;(realtime as { on: typeof realtime.on }).on = ((event: string, handler: never) => { + captured.push({ event, handler }) + return () => { + released += 1 + } + }) as typeof realtime.on + + try { + const seen: string[] = [] + function Probe({ label }: { label: string }) { + useKeelEvent<{ text: string }>("harbor.message", (data) => { + seen.push(`${label}:${data.text}`) + }) + return createElement("span", null, label) + } + + const mounted = await render(createElement(Probe, { label: "a" })) + assert.equal(captured.length, 1) + assert.equal(captured[0].event, "harbor.message") + captured[0].handler( + { text: "one" }, + { event: "harbor.message", channel: "page:harbor.home", data: { text: "one" }, id: null }, + ) + assert.deepEqual(seen, ["a:one"]) + + await mounted.unmount() + assert.equal(released, 1) + } finally { + ;(realtime as { on: typeof realtime.on }).on = originalOn + } +}) diff --git a/packages/react/package.json b/packages/react/package.json index 84a71fb..b8e8ddf 100644 --- a/packages/react/package.json +++ b/packages/react/package.json @@ -1,6 +1,6 @@ { "name": "@kolektiv/keel-react", - "version": "0.1.2", + "version": "0.2.1", "description": "Keel React 18/19 bindings \u2014 Link, Form, Head, usePage, useForm, useAction.", "type": "module", "license": "Apache-2.0", diff --git a/packages/react/src/event.ts b/packages/react/src/event.ts new file mode 100644 index 0000000..a97eace --- /dev/null +++ b/packages/react/src/event.ts @@ -0,0 +1,24 @@ +import { useEffect, useRef } from "react" +import { realtime, type RealtimeMessage } from "@kolektiv/keel" + +/** + * Subscribes to a typed realtime event for the component's lifetime. The + * latest handler is used, so inline closures do not resubscribe. + * + * ```tsx + * useKeelEvent("harbor.message", (message) => { + * setFeed((feed) => [message, ...feed]) + * }) + * ``` + */ +export function useKeelEvent( + event: string, + handler: (data: T, message: RealtimeMessage) => void, +): void { + const latest = useRef(handler) + latest.current = handler + useEffect( + () => realtime.on(event, (data, message) => latest.current(data, message)), + [event], + ) +} diff --git a/packages/react/src/index.ts b/packages/react/src/index.ts index 119ac8c..62b6fa6 100644 --- a/packages/react/src/index.ts +++ b/packages/react/src/index.ts @@ -5,7 +5,7 @@ export { useForm, type FormState } from "./useForm.js" export { useNavigationGuard, useUnloadGuard } from "./guards.js" export type { GuardResult, NavigationGuard, NavigationTarget } from "@kolektiv/keel" export { applyHead, fromPageHead, setTitle, syncHead, type HeadInput } from "./head.js" -export { router, ActionError } from "@kolektiv/keel" +export { realtime, router, ActionError, type RealtimeMessage } from "@kolektiv/keel" export { getQueryClient, hydrateKeelQuery, @@ -18,3 +18,4 @@ export { Link, type LinkProps } from "./Link.js" export { Form, type FormProps } from "./Form.js" export { Head, type HeadProps } from "./Head.js" export { useKeelAnchor, type KeelAnchorParams, type KeelAnchorProps } from "./anchor.js" +export { useKeelEvent } from "./event.js" diff --git a/packages/react/test/event.test.ts b/packages/react/test/event.test.ts new file mode 100644 index 0000000..d47e331 --- /dev/null +++ b/packages/react/test/event.test.ts @@ -0,0 +1,58 @@ +import "./setup.ts" +import assert from "node:assert/strict" +import { test } from "node:test" +import { act, createElement } from "react" +import { realtime, type RealtimeMessage } from "@kolektiv/keel" +import { useKeelEvent } from "../dist/index.js" +import { render } from "./helpers.ts" + +interface Captured { + event: string + handler: (data: unknown, message: RealtimeMessage) => void +} + +const message = (text: string): RealtimeMessage<{ text: string }> => ({ + event: "harbor.message", + channel: "page:harbor.home", + data: { text }, + id: null, +}) + +test("useKeelEvent subscribes once, keeps the latest handler, and releases on unmount", async () => { + const captured: Captured[] = [] + let released = 0 + const originalOn = realtime.on + ;(realtime as { on: typeof realtime.on }).on = ((event: string, handler: never) => { + captured.push({ event, handler }) + return () => { + released += 1 + } + }) as typeof realtime.on + + try { + const seen: string[] = [] + function Probe({ label }: { label: string }) { + useKeelEvent<{ text: string }>("harbor.message", (data) => { + seen.push(`${label}:${data.text}`) + }) + return createElement("span", null, label) + } + + const mounted = await render(createElement(Probe, { label: "a" })) + assert.equal(captured.length, 1) + assert.equal(captured[0].event, "harbor.message") + captured[0].handler({ text: "one" }, message("one")) + + await act(async () => { + mounted.root.render(createElement(Probe, { label: "b" })) + }) + assert.equal(captured.length, 1) + captured[0].handler({ text: "two" }, message("two")) + assert.deepEqual(seen, ["a:one", "b:two"]) + + await mounted.unmount() + assert.equal(released, 1) + } finally { + ;(realtime as { on: typeof realtime.on }).on = originalOn + } +}) diff --git a/packages/solid/package.json b/packages/solid/package.json index e6eb09b..e3b7474 100644 --- a/packages/solid/package.json +++ b/packages/solid/package.json @@ -1,6 +1,6 @@ { "name": "@kolektiv/keel-solid", - "version": "0.1.2", + "version": "0.2.1", "description": "Keel Solid 1.9 bindings \u2014 Link, Form, Head, usePage, useForm, useAction.", "type": "module", "license": "Apache-2.0", diff --git a/packages/solid/src/event.ts b/packages/solid/src/event.ts new file mode 100644 index 0000000..86db9ec --- /dev/null +++ b/packages/solid/src/event.ts @@ -0,0 +1,13 @@ +import { onCleanup } from "solid-js" +import { realtime, type RealtimeMessage } from "@kolektiv/keel" + +/** + * Subscribes to a typed realtime event for the component's lifetime. The + * handler is invoked as-is; read reactive values inside it. + */ +export function useKeelEvent( + event: string, + handler: (data: T, message: RealtimeMessage) => void, +): void { + onCleanup(realtime.on(event, (data, message) => handler(data, message))) +} diff --git a/packages/solid/src/index.ts b/packages/solid/src/index.ts index 119ac8c..62b6fa6 100644 --- a/packages/solid/src/index.ts +++ b/packages/solid/src/index.ts @@ -5,7 +5,7 @@ export { useForm, type FormState } from "./useForm.js" export { useNavigationGuard, useUnloadGuard } from "./guards.js" export type { GuardResult, NavigationGuard, NavigationTarget } from "@kolektiv/keel" export { applyHead, fromPageHead, setTitle, syncHead, type HeadInput } from "./head.js" -export { router, ActionError } from "@kolektiv/keel" +export { realtime, router, ActionError, type RealtimeMessage } from "@kolektiv/keel" export { getQueryClient, hydrateKeelQuery, @@ -18,3 +18,4 @@ export { Link, type LinkProps } from "./Link.js" export { Form, type FormProps } from "./Form.js" export { Head, type HeadProps } from "./Head.js" export { useKeelAnchor, type KeelAnchorParams, type KeelAnchorProps } from "./anchor.js" +export { useKeelEvent } from "./event.js" diff --git a/packages/solid/test/event.test.ts b/packages/solid/test/event.test.ts new file mode 100644 index 0000000..e265d9e --- /dev/null +++ b/packages/solid/test/event.test.ts @@ -0,0 +1,47 @@ +import "./setup.ts" +import assert from "node:assert/strict" +import { test } from "node:test" +import { realtime, type RealtimeMessage } from "@kolektiv/keel" +import { useKeelEvent } from "../dist/index.js" +import { render } from "./helpers.ts" + +interface Captured { + event: string + handler: (data: unknown, message: RealtimeMessage) => void +} + +test("useKeelEvent subscribes on mount and cleans up on dispose", () => { + const captured: Captured[] = [] + let released = 0 + const originalOn = realtime.on + ;(realtime as { on: typeof realtime.on }).on = ((event: string, handler: never) => { + captured.push({ event, handler }) + return () => { + released += 1 + } + }) as typeof realtime.on + + try { + const seen: string[] = [] + const Probe = () => { + useKeelEvent<{ text: string }>("harbor.message", (data) => { + seen.push(data.text) + }) + return null + } + + const mounted = render(Probe) + assert.equal(captured.length, 1) + assert.equal(captured[0].event, "harbor.message") + captured[0].handler( + { text: "one" }, + { event: "harbor.message", channel: "page:harbor.home", data: { text: "one" }, id: null }, + ) + assert.deepEqual(seen, ["one"]) + + mounted.unmount() + assert.equal(released, 1) + } finally { + ;(realtime as { on: typeof realtime.on }).on = originalOn + } +}) diff --git a/packages/svelte/package.json b/packages/svelte/package.json index 5ad9872..fec890f 100644 --- a/packages/svelte/package.json +++ b/packages/svelte/package.json @@ -1,6 +1,6 @@ { "name": "@kolektiv/keel-svelte", - "version": "0.1.2", + "version": "0.2.1", "description": "Keel Svelte 5 bindings \u2014 Link, Form, Head, page(), useForm, useAction.", "type": "module", "license": "Apache-2.0", diff --git a/packages/svelte/src/event.svelte.ts b/packages/svelte/src/event.svelte.ts new file mode 100644 index 0000000..f11c455 --- /dev/null +++ b/packages/svelte/src/event.svelte.ts @@ -0,0 +1,25 @@ +import { realtime, type RealtimeMessage } from "@kolektiv/keel" + +/** + * Subscribes to a typed realtime event for the component's lifetime. Must be + * called during component initialisation; `event` is tracked, the handler is + * read through a closure so it may capture `$state`. + * + * ```svelte + * + * ``` + */ +export function useKeelEvent( + event: string, + handler: (data: T, message: RealtimeMessage) => void, +): void { + $effect(() => { + const release = realtime.on(event, (data, message) => handler(data, message)) + return () => release() + }) +} diff --git a/packages/svelte/src/index.ts b/packages/svelte/src/index.ts index 0351872..389f109 100644 --- a/packages/svelte/src/index.ts +++ b/packages/svelte/src/index.ts @@ -2,9 +2,10 @@ export { keel, type KeelActionParams } from "./action.js" export { page } from "./page.js" export { useForm, type FormState } from "./useForm.svelte.js" export { useNavigationGuard, useUnloadGuard } from "./guards.svelte.js" +export { useKeelEvent } from "./event.svelte.js" export type { GuardResult, NavigationGuard, NavigationTarget } from "@kolektiv/keel" export { applyHead, fromPageHead, setTitle, syncHead, type HeadInput } from "./head.js" -export { router } from "@kolektiv/keel" +export { realtime, router, type RealtimeMessage } from "@kolektiv/keel" export { bootstrap } from "./bootstrap.js" export { getQueryClient, diff --git a/packages/svelte/test/event.test.ts b/packages/svelte/test/event.test.ts new file mode 100644 index 0000000..8ff11b1 --- /dev/null +++ b/packages/svelte/test/event.test.ts @@ -0,0 +1,63 @@ +import assert from "node:assert/strict" +import { mkdirSync, readFileSync, writeFileSync } from "node:fs" +import { dirname, join } from "node:path" +import { fileURLToPath, pathToFileURL } from "node:url" +import { test } from "node:test" +import { compileModule } from "svelte/compiler" +import { effect_root } from "svelte/internal/client" +import { realtime, type RealtimeMessage } from "@kolektiv/keel" + +interface EventModule { + useKeelEvent: (event: string, handler: (data: unknown, message: RealtimeMessage) => void) => void +} + +async function loadEventModule(): Promise { + const source = readFileSync(new URL("../dist/event.svelte.js", import.meta.url), "utf8") + const compiled = compileModule(source, { filename: "event.svelte.js", generate: "client" }) + const dir = join(dirname(fileURLToPath(import.meta.url)), ".compiled") + mkdirSync(dir, { recursive: true }) + const out = join(dir, "event.js") + writeFileSync(out, compiled.js.code) + return (await import(`${pathToFileURL(out).href}?t=${Date.now()}`)) as EventModule +} + +async function flushEffects(): Promise { + await Promise.resolve() +} + +test("useKeelEvent subscribes in an effect and cleans up when the root is destroyed", async () => { + const { useKeelEvent } = await loadEventModule() + const captured: Array<{ event: string; handler: (data: unknown, message: RealtimeMessage) => void }> = [] + let released = 0 + const originalOn = realtime.on + ;(realtime as { on: typeof realtime.on }).on = ((event: string, handler: never) => { + captured.push({ event, handler }) + return () => { + released += 1 + } + }) as typeof realtime.on + + try { + const seen: string[] = [] + const destroy = effect_root(() => { + useKeelEvent("harbor.message", (data: { text: string }) => { + seen.push(data.text) + }) + }) + await flushEffects() + + assert.equal(captured.length, 1) + assert.equal(captured[0].event, "harbor.message") + captured[0].handler( + { text: "one" }, + { event: "harbor.message", channel: "page:harbor.home", data: { text: "one" }, id: null }, + ) + assert.deepEqual(seen, ["one"]) + + destroy() + await flushEffects() + assert.equal(released, 1) + } finally { + ;(realtime as { on: typeof realtime.on }).on = originalOn + } +}) diff --git a/packages/vue/package.json b/packages/vue/package.json index a9ee112..f8ba3e3 100644 --- a/packages/vue/package.json +++ b/packages/vue/package.json @@ -1,6 +1,6 @@ { "name": "@kolektiv/keel-vue", - "version": "0.1.2", + "version": "0.2.1", "description": "Keel Vue 3 bindings \u2014 Link, Form, Head, usePage, useForm, useAction.", "type": "module", "license": "Apache-2.0", diff --git a/packages/vue/src/event.ts b/packages/vue/src/event.ts new file mode 100644 index 0000000..67fd509 --- /dev/null +++ b/packages/vue/src/event.ts @@ -0,0 +1,18 @@ +import { onScopeDispose, shallowRef, watchEffect } from "vue" +import { realtime, type RealtimeMessage } from "@kolektiv/keel" + +/** + * Subscribes to a typed realtime event for the component's lifetime. The + * latest handler is used, so inline closures do not resubscribe. + */ +export function useKeelEvent( + event: string, + handler: (data: T, message: RealtimeMessage) => void, +): void { + const latest = shallowRef(handler) + watchEffect(() => { + latest.value = handler + }) + const release = realtime.on(event, (data, message) => latest.value(data, message)) + onScopeDispose(release) +} diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts index aa3b528..e0a81c6 100644 --- a/packages/vue/src/index.ts +++ b/packages/vue/src/index.ts @@ -5,7 +5,7 @@ export { useForm, type FormState } from "./useForm.js" export { useNavigationGuard, useUnloadGuard } from "./guards.js" export type { GuardResult, NavigationGuard, NavigationTarget } from "@kolektiv/keel" export { applyHead, fromPageHead, setTitle, syncHead, type HeadInput } from "./head.js" -export { router, ActionError } from "@kolektiv/keel" +export { realtime, router, ActionError, type RealtimeMessage } from "@kolektiv/keel" export { getQueryClient, hydrateKeelQuery, @@ -18,3 +18,4 @@ export { default as Link, type LinkProps } from "./Link.vue" export { default as Form, type FormProps } from "./Form.vue" export { default as Head, type HeadProps } from "./Head.vue" export { useKeelAnchor, type KeelAnchorParams, type KeelAnchorProps } from "./anchor.js" +export { useKeelEvent } from "./event.js" diff --git a/packages/vue/test/event.test.ts b/packages/vue/test/event.test.ts new file mode 100644 index 0000000..1c01ff6 --- /dev/null +++ b/packages/vue/test/event.test.ts @@ -0,0 +1,51 @@ +import "./setup.ts" +import assert from "node:assert/strict" +import { test } from "node:test" +import { defineComponent, h } from "vue" +import { realtime, type RealtimeMessage } from "@kolektiv/keel" +import { useKeelEvent } from "../dist/index.js" +import { render } from "./helpers.ts" + +interface Captured { + event: string + handler: (data: unknown, message: RealtimeMessage) => void +} + +test("useKeelEvent subscribes in scope and releases on unmount", async () => { + const captured: Captured[] = [] + let released = 0 + const originalOn = realtime.on + ;(realtime as { on: typeof realtime.on }).on = ((event: string, handler: never) => { + captured.push({ event, handler }) + return () => { + released += 1 + } + }) as typeof realtime.on + + try { + const seen: string[] = [] + const Probe = defineComponent({ + props: { label: { type: String, required: true } }, + setup(props) { + useKeelEvent<{ text: string }>("harbor.message", (data) => { + seen.push(`${props.label}:${data.text}`) + }) + return () => h("span", props.label) + }, + }) + + const mounted = await render(Probe, { label: "a" }) + assert.equal(captured.length, 1) + assert.equal(captured[0].event, "harbor.message") + captured[0].handler( + { text: "one" }, + { event: "harbor.message", channel: "page:harbor.home", data: { text: "one" }, id: null }, + ) + assert.deepEqual(seen, ["a:one"]) + + await mounted.unmount() + assert.equal(released, 1) + } finally { + ;(realtime as { on: typeof realtime.on }).on = originalOn + } +}) diff --git a/samples/harbor/README.md b/samples/harbor/README.md index 5bb41b6..266474f 100644 --- a/samples/harbor/README.md +++ b/samples/harbor/README.md @@ -26,6 +26,14 @@ pnpm --filter @kolektiv/harbor-pack build | `harbor.setName` | `{ displayName }` — cookie `harbor_uid` | | `harbor.postMessage` | `{ body }` — requires the cookie | +Realtime is on for the testbench: the host installs `WebSockets` + `SSE` and +`keel { realtime { … } }` declares the events. `harbor.postMessage` publishes +`harbor.message` on `page:harbor.home`; `harbor.setName` sends an +`invalidate` for the same channel. The pack subscribes with `useKeelEvent` +and sends `harbor.typing` with `realtime.send`, which the host echoes back to +the channel. Open two windows to watch posts and typing notices stream in. +Transport is `/__keel/events` (WebSocket upgrade, or SSE + `POST` sends). + Document GET writes `` / description / `og:*` from `seed.head` so crawlers that do not run JS still see the board. Visits (`X-Keel-Visit`) return JSON; they are not the SEO unit. Pack files are ids, not URLs. diff --git a/samples/harbor/build.gradle.kts b/samples/harbor/build.gradle.kts index 3b15d4d..0233577 100644 --- a/samples/harbor/build.gradle.kts +++ b/samples/harbor/build.gradle.kts @@ -49,6 +49,7 @@ dependencies { implementation(libs.ktor.server.netty) implementation(libs.slf4j.simple) testImplementation(libs.ktor.server.test.host) + testImplementation(libs.ktor.client.websockets) testImplementation(libs.junit.jupiter) testRuntimeOnly(libs.junit.jupiter.engine) testRuntimeOnly("org.junit.platform:junit-platform-launcher") diff --git a/samples/harbor/pack/src/lib/page-types.json b/samples/harbor/pack/src/lib/page-types.json index 227cdcc..9f3d8cc 100644 --- a/samples/harbor/pack/src/lib/page-types.json +++ b/samples/harbor/pack/src/lib/page-types.json @@ -34,6 +34,16 @@ "out": "SetNameOut" } }, + "events": { + "harbor.message": { + "direction": "out", + "type": "FeedItem" + }, + "harbor.typing": { + "direction": "both", + "type": "TypingNotice" + } + }, "types": { "UserRef": { "kind": "object", @@ -96,6 +106,12 @@ "fields": { "user": "UserRef" } + }, + "TypingNotice": { + "kind": "object", + "fields": { + "displayName": "string" + } } } } diff --git a/samples/harbor/pack/src/lib/page-types.ts b/samples/harbor/pack/src/lib/page-types.ts index 79af799..ad2da74 100644 --- a/samples/harbor/pack/src/lib/page-types.ts +++ b/samples/harbor/pack/src/lib/page-types.ts @@ -44,6 +44,10 @@ export interface SetNameOut { user: UserRef } +export interface TypingNotice { + displayName: string +} + export interface HarborPages { "harbor.home": HomePage "harbor.notFound": NotFoundPage @@ -58,3 +62,10 @@ export interface HarborActions { } export type HarborActionId = keyof HarborActions + +export interface HarborEvents { + "harbor.message": FeedItem + "harbor.typing": TypingNotice +} + +export type HarborEventId = keyof HarborEvents diff --git a/samples/harbor/pack/src/pages/harbor/home/+page.svelte b/samples/harbor/pack/src/pages/harbor/home/+page.svelte index 27c9a84..4ee3c58 100644 --- a/samples/harbor/pack/src/pages/harbor/home/+page.svelte +++ b/samples/harbor/pack/src/pages/harbor/home/+page.svelte @@ -1,6 +1,14 @@ <script lang="ts"> - import { ActionError, Link, page, useAction } from "@kolektiv/keel-svelte" - import type { HomePage, PostMessageIn, PostMessageOut, SetNameIn, SetNameOut } from "../../../lib/page-types" + import { ActionError, Link, page, realtime, useAction, useKeelEvent } from "@kolektiv/keel-svelte" + import type { + FeedItem, + HarborEvents, + HomePage, + PostMessageIn, + PostMessageOut, + SetNameIn, + SetNameOut, + } from "../../../lib/page-types" const ctx = page<HomePage>() const setName = useAction<SetNameIn, SetNameOut>("harbor.setName") @@ -8,12 +16,44 @@ let displayName = $state(ctx.data.viewer?.displayName ?? "") let body = $state("") + let liveFeed = $state<FeedItem[]>([]) + let typingBy = $state<string | null>(null) + + let typingTimer: ReturnType<typeof setTimeout> | undefined + let lastTypingSent = 0 + + // Typed push: new posts arrive without a visit. + useKeelEvent<HarborEvents["harbor.message"]>("harbor.message", (item) => { + if (!liveFeed.some((existing) => existing.id === item.id)) { + liveFeed = [item, ...liveFeed] + } + }) + + // Client-to-host send: "is typing" notices from everyone on the channel. + useKeelEvent<HarborEvents["harbor.typing"]>("harbor.typing", (notice) => { + typingBy = notice.displayName + clearTimeout(typingTimer) + typingTimer = setTimeout(() => { + typingBy = null + }, 4000) + }) + + const feed = $derived.by(() => { + const seen = new Set<string>() + return [...liveFeed, ...ctx.data.feed].filter((item) => { + if (seen.has(item.id)) return false + seen.add(item.id) + return true + }) + }) $effect(() => { const name = ctx.data.viewer?.displayName if (name) displayName = name }) + $effect(() => () => clearTimeout(typingTimer)) + function fieldError(error: unknown, field: string): string | undefined { if (error instanceof ActionError) return error.errors[field]?.join(" ") return undefined @@ -33,10 +73,19 @@ }) .catch(() => undefined) } + + function onTyping() { + const viewer = ctx.data.viewer + if (!viewer) return + const now = Date.now() + if (now - lastTypingSent < 1500) return + lastTypingSent = now + void realtime.send("harbor.typing", { displayName: viewer.displayName }).catch(() => undefined) + } </script> <h1>Harbor</h1> -<p class="lede">A message board. The seed is the read model. Actions write; visits rehydrate.</p> +<p class="lede">A message board. The seed is the read model. Actions write; visits rehydrate. Posts stream in live.</p> <form class="stack" onsubmit={onSetName}> <div class="field"> @@ -56,7 +105,7 @@ <form class="stack" onsubmit={onPost}> <div class="field"> <label for="body">Message</label> - <textarea id="body" name="body" bind:value={body} rows="4" maxlength="2000"></textarea> + <textarea id="body" name="body" bind:value={body} oninput={onTyping} rows="4" maxlength="2000"></textarea> {#if fieldError(postMessage.error, "body")} <p class="error">{fieldError(postMessage.error, "body")}</p> {/if} @@ -65,14 +114,17 @@ {postMessage.isPending ? "Posting…" : "Post"} </button> </form> + {#if typingBy} + <p class="meta">{typingBy} is typing…</p> + {/if} {/if} <h2>Recent</h2> -{#if ctx.data.feed.length === 0} +{#if feed.length === 0} <p class="lede">No messages yet. Set a display name and write the first one.</p> {:else} <ol class="feed"> - {#each ctx.data.feed as item (item.id)} + {#each feed as item (item.id)} <li> <Link href={`/u/${item.userId}`} prefetch="hover">{item.displayName}</Link> <p class="excerpt">{item.body}</p> diff --git a/samples/harbor/src/main/kotlin/dev/kolektiv/keel/samples/harbor/Board.kt b/samples/harbor/src/main/kotlin/dev/kolektiv/keel/samples/harbor/Board.kt index 7545dcc..2c43663 100644 --- a/samples/harbor/src/main/kotlin/dev/kolektiv/keel/samples/harbor/Board.kt +++ b/samples/harbor/src/main/kotlin/dev/kolektiv/keel/samples/harbor/Board.kt @@ -1,7 +1,10 @@ package dev.kolektiv.keel.samples.harbor import dev.kolektiv.keel.KeelAction +import dev.kolektiv.keel.KeelEvent +import dev.kolektiv.keel.event.EventDirection import dev.kolektiv.keel.ktor.PageValidationException +import dev.kolektiv.keel.ktor.realtime.keelRealtime import io.ktor.server.application.ApplicationCall import java.time.Instant import java.time.temporal.ChronoUnit @@ -74,6 +77,7 @@ object Board { ) created } + notifyNameChanged(this, user) return SetNameOut(user.toRef()) } @@ -101,9 +105,36 @@ object Board { at = timestamp(), ) messages.add(0, message) - return PostMessageOut(message.toFeedItem()) + val item = message.toFeedItem() + keelRealtime.publish(HOME_CHANNEL, "harbor.message", item) + return PostMessageOut(item) } + /** + * Client-sent typing notice: echo it to everyone watching the board. The + * handler is an `ApplicationCall` extension so cookies identify the + * author; the payload is the same `OUT`/`IN` type. + */ + @KeelEvent("harbor.typing", EventDirection.BOTH) + fun ApplicationCall.typing(input: TypingNotice) { + val author = viewer(this) ?: return + if (input.displayName.isNotBlank() && input.displayName != author.displayName) { + throw PageValidationException( + mapOf("displayName" to listOf("Not your display name.")), + Unit, + ) + } + keelRealtime.publish(HOME_CHANNEL, "harbor.typing", TypingNotice(author.displayName)) + } + + fun notifyNameChanged(call: ApplicationCall, user: User) { + // Flavor (b): tell home viewers to rehydrate the seed; renamed authors + // are then consistent everywhere. + call.keelRealtime.invalidate(HOME_CHANNEL, path = "/") + } + + const val HOME_CHANNEL: String = "page:harbor.home" + private fun newId(): String = UUID.randomUUID().toString() private fun timestamp(): String = Instant.now().truncatedTo(ChronoUnit.SECONDS).toString() diff --git a/samples/harbor/src/main/kotlin/dev/kolektiv/keel/samples/harbor/HarborApp.kt b/samples/harbor/src/main/kotlin/dev/kolektiv/keel/samples/harbor/HarborApp.kt index 3c8d0a2..fe25d6b 100644 --- a/samples/harbor/src/main/kotlin/dev/kolektiv/keel/samples/harbor/HarborApp.kt +++ b/samples/harbor/src/main/kotlin/dev/kolektiv/keel/samples/harbor/HarborApp.kt @@ -1,15 +1,21 @@ package dev.kolektiv.keel.samples.harbor import dev.kolektiv.keel.bundle.FrontendBundle +import dev.kolektiv.keel.event.EventDirection import dev.kolektiv.keel.ktor.CspPolicy import dev.kolektiv.keel.ktor.PageMissingException import dev.kolektiv.keel.ktor.SharedProvider import dev.kolektiv.keel.ktor.keel import io.ktor.server.application.Application +import io.ktor.server.application.install +import io.ktor.server.sse.SSE +import io.ktor.server.websocket.WebSockets import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put fun Application.harbor(bundle: FrontendBundle) { + install(WebSockets) + install(SSE) keel { this.bundle = bundle watchPacks = true @@ -45,5 +51,11 @@ fun Application.harbor(bundle: FrontendBundle) { } } actions(Board) + realtime { + // Typed board events the host pushes, plus the `@KeelEvent` + // handlers on Board for client-sent notices. + event<FeedItem>("harbor.message", EventDirection.OUT) + events(Board) + } } } diff --git a/samples/harbor/src/main/kotlin/dev/kolektiv/keel/samples/harbor/Pages.kt b/samples/harbor/src/main/kotlin/dev/kolektiv/keel/samples/harbor/Pages.kt index 5a6e81e..619c835 100644 --- a/samples/harbor/src/main/kotlin/dev/kolektiv/keel/samples/harbor/Pages.kt +++ b/samples/harbor/src/main/kotlin/dev/kolektiv/keel/samples/harbor/Pages.kt @@ -1,6 +1,8 @@ package dev.kolektiv.keel.samples.harbor +import dev.kolektiv.keel.KeelEvent import dev.kolektiv.keel.KeelType +import dev.kolektiv.keel.event.EventDirection import kotlinx.serialization.Serializable @KeelType @@ -10,6 +12,7 @@ data class UserRef( val displayName: String, ) +@KeelEvent("harbor.message", EventDirection.OUT) @KeelType @Serializable data class FeedItem( @@ -56,3 +59,8 @@ data class PostMessageIn(val body: String) @KeelType @Serializable data class PostMessageOut(val message: FeedItem) + +/** Client-sent "someone is writing" notice, echoed to the same channel. */ +@KeelEvent("harbor.typing", EventDirection.BOTH) +@Serializable +data class TypingNotice(val displayName: String) diff --git a/samples/harbor/src/test/kotlin/dev/kolektiv/keel/samples/harbor/HarborAppTest.kt b/samples/harbor/src/test/kotlin/dev/kolektiv/keel/samples/harbor/HarborAppTest.kt index b491e5f..bd9f9a8 100644 --- a/samples/harbor/src/test/kotlin/dev/kolektiv/keel/samples/harbor/HarborAppTest.kt +++ b/samples/harbor/src/test/kotlin/dev/kolektiv/keel/samples/harbor/HarborAppTest.kt @@ -3,10 +3,14 @@ package dev.kolektiv.keel.samples.harbor import dev.kolektiv.keel.Keel import dev.kolektiv.keel.KeelJson import dev.kolektiv.keel.bundle.FrontendBundle +import dev.kolektiv.keel.realtime.KeelRealtimeEnvelope import dev.kolektiv.keel.seed.KeelSeed import dev.kolektiv.keel.typegen.ClasspathContract import dev.kolektiv.keel.typegen.Typegen import dev.kolektiv.keel.visit.KeelHeaders +import io.ktor.client.plugins.websocket.DefaultClientWebSocketSession +import io.ktor.client.plugins.websocket.WebSockets as ClientWebSockets +import io.ktor.client.plugins.websocket.webSocket import io.ktor.client.request.get import io.ktor.client.request.header import io.ktor.client.request.post @@ -16,9 +20,13 @@ import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode import io.ktor.http.contentType import io.ktor.server.testing.testApplication +import io.ktor.websocket.Frame +import io.ktor.websocket.readText +import kotlinx.coroutines.withTimeout import kotlinx.serialization.json.add import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.put import kotlinx.serialization.json.putJsonArray import kotlinx.serialization.json.putJsonObject @@ -257,6 +265,70 @@ class HarborAppTest { assertTrue(missingPath.bodyAsText().contains("\"path\":\"/nope\"")) } + @Test + fun `postMessage streams a harbor message event to the home channel`() = testApplication { + writePack() + application { harbor(FrontendBundle.fromDirectory(pack)) } + val client = createClient { install(ClientWebSockets) } + val named = client.post("${Keel.ACTION_PATH}/harbor.setName") { + contentType(ContentType.Application.Json) + setBody("""{"displayName":"Ada"}""") + } + val cookie = cookieHeader(named.headers["Set-Cookie"]) + + client.webSocket("/__keel/events?channels=page:harbor.home", request = { header("Cookie", cookie) }) { + val ready = nextRealtimeEnvelope() + assertEquals(KeelRealtimeEnvelope.READY, ready.type) + assertEquals(listOf("page:harbor.home"), ready.channels) + + val posted = client.post("${Keel.ACTION_PATH}/harbor.postMessage") { + contentType(ContentType.Application.Json) + header("Cookie", cookie) + setBody("""{"body":"live from the pier"}""") + } + assertEquals(HttpStatusCode.OK, posted.status) + + val event = nextRealtimeEnvelope() + assertEquals(KeelRealtimeEnvelope.EVENT, event.type) + assertEquals("harbor.message", event.event) + assertEquals("page:harbor.home", event.channel) + val data = event.data!!.jsonObject + assertEquals("live from the pier", data.getValue("body").jsonPrimitive.content) + assertEquals("Ada", data.getValue("displayName").jsonPrimitive.content) + } + } + + @Test + fun `client typing notices round trip through the host`() = testApplication { + writePack() + application { harbor(FrontendBundle.fromDirectory(pack)) } + val client = createClient { install(ClientWebSockets) } + val named = client.post("${Keel.ACTION_PATH}/harbor.setName") { + contentType(ContentType.Application.Json) + setBody("""{"displayName":"Ada"}""") + } + val cookie = cookieHeader(named.headers["Set-Cookie"]) + + client.webSocket("/__keel/events?channels=page:harbor.home", request = { header("Cookie", cookie) }) { + assertEquals(KeelRealtimeEnvelope.READY, nextRealtimeEnvelope().type) + val envelope = KeelRealtimeEnvelope.send( + "harbor.typing", + buildJsonObject { put("displayName", "Ada") }, + ) + send(Frame.Text(KeelJson.codec.encodeToString(KeelRealtimeEnvelope.serializer(), envelope))) + + val event = nextRealtimeEnvelope() + assertEquals("harbor.typing", event.event) + assertEquals("Ada", event.data!!.jsonObject.getValue("displayName").jsonPrimitive.content) + } + } + + private suspend fun DefaultClientWebSocketSession.nextRealtimeEnvelope(): KeelRealtimeEnvelope = + KeelJson.codec.decodeFromString( + KeelRealtimeEnvelope.serializer(), + (withTimeout(5000) { incoming.receive() } as Frame.Text).readText(), + ) + @Test fun `generated page types stay in lockstep`() { val expected = Path.of("pack/src/lib/page-types.ts").readText() diff --git a/skills/keel-host/SKILL.md b/skills/keel-host/SKILL.md index 32c837b..b7260bb 100644 --- a/skills/keel-host/SKILL.md +++ b/skills/keel-host/SKILL.md @@ -3,9 +3,11 @@ name: keel-host description: > Implement or extend a Keel host (server). Use when adding pages, actions, CSRF, the live schema, pack loading and render-time pack choice, document - head, CSP, or pack hot reload, or for a non-Ktor backend that speaks Keel. + head, CSP, pack hot reload, or realtime events over SSE/WebSocket, or for a + non-Ktor backend that speaks Keel. Triggers: "keel host", "KeelEngine", "respondPage", "route.keel", - "FrontendBundle", "/__keel/schema", "@KeelAction", "page registry". + "FrontendBundle", "/__keel/schema", "@KeelAction", "@KeelEvent", + "call.keelRealtime", "realtime", "page registry". Slash: /keel-host. --- @@ -109,6 +111,44 @@ stripped. Visits get no nonce and no header. Default policy: `script-src 'nonce-…' 'strict-dynamic'; style-src 'self'; object-src 'none'; base-uri 'none'`. +## Realtime + +Off by default. Enable by installing the Ktor transport plugins the host wants +and adding a `realtime { }` block — endpoints exist only when both are true: + +```kotlin +install(WebSockets) // and/or install(SSE) +keel { + realtime { + event<FeedItem>("harbor.message", EventDirection.OUT) // typed payload + on<TypingNotice>("harbor.typing") { call.keelRealtime.publish("page:harbor.home", "harbor.typing", it) } + events(Board) // @KeelEvent functions + authorize = { call, channel -> channel.startsWith("page:") || Board.viewer(call) != null } + heartbeatSeconds = 25 + } +} +``` + +- `@KeelEvent("id")` on a `@Serializable` class declares the payload (Typegen + emits `<Pack>Events`); on a host function it registers a client-sent + handler the way `@KeelAction` registers writes. Directions: `IN`, `OUT`, + `BOTH`. +- One endpoint, `/__keel/events`: SSE stream, WebSocket upgrade, and `POST` + sends from SSE clients (`sid` addresses the stream). Same JSON envelope both + directions, `v: 1`. Writes use the action CSRF policy. +- Publish from a call: `call.keelRealtime.publish(channel, eventId, data)` + (typed) / `publishJson`; `invalidate(channel, path, only, except)` sends the + visit-shaped hint. `send(sid, …)` targets one stream. +- Channel ids are host-owned strings; `page:…`/`user:…` are conventions, not + built-ins. `authorize` runs per channel at subscribe time with the caller's + cookies. +- **No replay.** Subscriptions are ephemeral; `invalidate` tells the client + to rehydrate with a normal visit, and the client resubscribes with backoff. + Keep heartbeats on so dead connections are reaped. +- A non-Ktor host implements the envelope from + `docs/src/content/docs/implementing/protocol.mdx`; the reference is + `ktor/realtime/`. + ## Pack hot reload - `KeelConfig.watchPacks = true` and `packWatchIntervalMs` (default 500, diff --git a/skills/keel-pack/SKILL.md b/skills/keel-pack/SKILL.md index b974929..15eeaba 100644 --- a/skills/keel-pack/SKILL.md +++ b/skills/keel-pack/SKILL.md @@ -4,9 +4,10 @@ description: > Author or adapt a Keel frontend pack for Svelte, React, Vue, Solid, Preact, Lit, or Angular. Use when writing pages and +head templates, keelPack Vite config and .feb builds, typed contracts, navigation guards, - action/effect patterns, or a RouterAdapter. Triggers: "keel pack", - "+page.svelte", "+page.tsx", "+page.ts", "+head.html", "keelPack", - "PageModule", ".feb", "supportedFrameworks", "beforeEach". + action/effect patterns, realtime events, or a RouterAdapter. Triggers: + "keel pack", "+page.svelte", "+page.tsx", "+page.ts", "+head.html", + "keelPack", "PageModule", ".feb", "supportedFrameworks", "beforeEach", + "useKeelEvent", "realtime", "invalidate". Slash: /keel-pack. --- @@ -186,6 +187,43 @@ on success by default so `page()` and the query cache rehydrate; reads still come from the seed. `action(id, input)` is the same POST without the reactive wrapper. +## Realtime + +Only use it when the host opted in (`keel { realtime { } }`). `realtime` and +`useKeelEvent` come from the adapter package; payload types come from +generated `<Pack>Events` (`@KeelEvent` classes on the host). + +```svelte +import { realtime, useKeelEvent } from "@kolektiv/keel-svelte" +import type { HarborEvents } from "../lib/page-types" + +let liveFeed = $state<FeedItem[]>([]) + +useKeelEvent<HarborEvents["harbor.message"]>("harbor.message", (item) => { + liveFeed = [item, ...liveFeed] +}) + +// client → host; the host may echo or broadcast it back +void realtime.send("harbor.typing", { displayName }) +``` + +- `useKeelEvent(event, handler)` (Angular: `injectKeelEvent`; Lit: + `useKeelEvent(host, …)` or `KeelEventController`) subscribes for the + component lifetime and always calls the latest handler. Call it once + during component init; do not call it conditionally. +- The client auto-holds `page:<page id>` and follows seed changes. Add + channels with `realtime.subscribe(channel)`; `realtime.configure({ ... })` + customizes `channels`, transport, and backoff. +- An `invalidate` envelope reloads the current page by default + (`router.reload({ preserveState: true })`). `realtime.onInvalidate` takes + over when the page wants a merge instead of a visit. +- The seed is still the only read model: use events to patch *view* state + (toasts, presence, appends) or let `invalidate` rehydrate. Never treat an + event as the source of truth — no replay, and a reconnect resyncs by + reloading. +- `realtime.status()` / `realtime.onStatus` expose `idle`, `connecting`, + `open`, `reconnecting`, `closed` if a page wants a live indicator. + ## Navigation guards `router.beforeEach(guard)` runs before the inflight visit is aborted, before diff --git a/skills/keel-scaffold/SKILL.md b/skills/keel-scaffold/SKILL.md index d74b5a4..c15a7c5 100644 --- a/skills/keel-scaffold/SKILL.md +++ b/skills/keel-scaffold/SKILL.md @@ -78,6 +78,12 @@ Angular). When a page id ends in `.notFound` (or is `not-found`/`notFound`) it also sets `notFound:`. Type names come from `schema.pagesName`, else PascalCase(id) + `Pages`. +When the host's schema carries an `events` section (`@KeelEvent` payloads), +`page-types.ts` also emits `<Prefix>Events` / `<Prefix>EventId` maps so a +page can subscribe with `useKeelEvent<HarborEvents["harbor.message"]>(…)` +instead of stringly-typed payloads; the direction (`in`/`out`/`both`) lives +in `page-types.json`. + Framework-specific DX notes: - **Lit** — `tsconfig.json` sets `experimentalDecorators: true` and