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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions docs/content/docs/web-client/adapters.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,46 @@ They also need a manifest whose `streams` table is populated, which today means
A channel served by `extensions/streaming` should also pass `decode: forgeStreamingDecoder()`. Its domain frames bind under the default decoder, but its transport frames — presence, typing, join — are reported as unknown messages without it. See [Which field carries the name](/docs/web-client/invalidation#which-field-carries-the-name).
</Callout>

### Wiring a stream runtime

The runtime opens nothing itself. You hand `SubscriptionManager` a `connect` function that returns an open connection for an endpoint, and one adapter per transport turns what the browser gives you into the connection the manager drives.

```ts
import {
channelMessages,
eventSourceConnection,
StreamBinder,
SubscriptionManager,
webSocketConnection,
webTransportConnection,
} from '@forge-go/client-core';
import { streams } from './generated';

const manager = new SubscriptionManager({
connect: ({ endpoint }) => {
if (endpoint.startsWith('/sse/')) {
// An EventSource delivers a named event only to a listener that asked
// for it by name, so the channel's message names come from the table.
return eventSourceConnection(new EventSource(endpoint), {
events: channelMessages(streams, endpoint),
});
}

if (endpoint.startsWith('/wt/')) {
return webTransportConnection(new WebTransport(`https://api.example.com${endpoint}`));
}

return webSocketConnection(new WebSocket(`wss://api.example.com${endpoint}`));
},
});

const binder = new StreamBinder({ cache, manager, streams });
```

`streams` is the generated `streams` table. Its rows are what tell the binder which entity each message carries, what the message does to the cache, and, under a renaming configuration, how to decode the payload before it is normalized. A channel served by `extensions/streaming` passes `decode: forgeStreamingDecoder()` to the binder as well.

The adapters take an already-open transport rather than a URL, so the same code runs wherever the application can construct one, including a server-side test with a fake. An error on an `EventSource` closes it and is reported as a drop, so the manager reconnects with its own backoff and the binder recovers the gap the way it does for a socket.

## Guarantees

- **One request per query, not per component.** Two components calling `useQuery(useListOrders)` are one cache entry, one registry mount and one request. They settle together.
Expand Down
33 changes: 29 additions & 4 deletions docs/content/docs/web-client/invalidation.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,10 @@ A tag naming a specific record needs a value from the request or the response. T

Prefer the explicit forms. A bare `{customerId}` is readable until two of those four sources have one, and then it silently resolves to whichever comes first.

Name the property as it appears on the wire. A snake_case API declares `Customer:{req.customer_id}`, and the generator renames the placeholder to whatever the client-side field is called under its naming configuration, so the emitted manifest reads `Customer:{req.customerId}` and resolves against the body the caller built and the response the codec decoded. Path and query parameters are the exception: they keep their wire names, because that is the key you pass them under. The runtime also accepts the wire spelling as a fallback, so a hand-written document, or a package generated before the rename existed, still resolves `{req.customer_id}` against a `customerId` field. An exact key always wins.

A collection read resolves its item template once per record returned, so `GET /orders` declaring `Order:{id}` registers `Order:7`, `Order:8` and so on. An empty list resolves to no item tags, which is not a failure.

<Callout type="warn">
A template that resolves to nothing invalidates nothing and reports nothing — it is the one failure in this system with no symptom at all. `@forge-go/client-devtools` surfaces it as `cause.unresolved`; see [Devtools](/docs/web-client/devtools).
</Callout>
Expand Down Expand Up @@ -161,13 +165,15 @@ That declaration produces this, in the AsyncAPI document:

```json
"x-forge-stream": [
{ "message": "order.created", "entityType": "Order", "intent": "upsert", "invalidates": ["Order[]"] },
{ "message": "order.updated", "entityType": "Order", "intent": "patch", "invalidates": null },
{ "message": "order.deleted", "entityType": "Order", "intent": "evict", "invalidates": ["Order[]"] },
{ "message": "order.fulfilled", "entityType": "Order", "intent": "patch", "invalidates": ["Shipment[]"] }
{ "message": "order.created", "entityType": "Order", "intent": "upsert", "invalidates": ["Order[]"], "type": "github.com/acme/shop.Order" },
{ "message": "order.updated", "entityType": "Order", "intent": "patch", "invalidates": null, "type": "github.com/acme/shop.Order" },
{ "message": "order.deleted", "entityType": "Order", "intent": "evict", "invalidates": ["Order[]"], "type": "github.com/acme/shop.Order" },
{ "message": "order.fulfilled", "entityType": "Order", "intent": "patch", "invalidates": ["Shipment[]"], "type": "github.com/acme/shop.Order" }
]
```

`entityType` is the Go type's bare name, which is also its component name until something contests it: a second `Order` in another package, a `schema:"..."` pin, a generic instantiation. A component that ended up under another name carries `x-forge-type` naming the Go type it came from, and the generator matches the binding to it on `type`. Nothing in the generated package changes shape; the `streams` table simply names the component the `entities` table holds.

`order.updated` costs no request: the payload is an `Order`, the normalizer patches `Order:7`, and every mounted view depending on it re-renders. Only `created` and `deleted` reach the network, and only for the collection.

<Callout type="info">
Expand All @@ -182,6 +188,23 @@ Forge parses each one, merges them, and emits a single package where `ops.ts` ca

`WithWebSocketMessages` is what puts message schemas in the AsyncAPI document. Without it the channel is declared but carries no message types, and no WebSocket client is generated for it.

A WebTransport route is described the same way, with `WithWebTransportMessages` naming a type per way a message travels: a datagram, and the send and receive halves of unidirectional and bidirectional streams. AsyncAPI has no WebTransport binding, so the channel is written with an `x-forge-protocol: webtransport` marker and messages named `datagram`, `uniSend`, `uniReceive`, `bidiSend` and `bidiReceive`. The generated `webtransport.ts` is typed from them, and `WithStreamBinding` on the route lands in the `streams` table exactly as it does for a socket, so a datagram carrying an `Order` takes part in the cache like any frame.

```go
_ = r.WebTransport("/wt/orders", ordersSession,
forge.WithWebTransportMessages(forge.WebTransportMessages{
Datagram: &OrderTick{},
BidiSend: &OrderCommand{},
BidiReceive: &Order{},
}),
forge.WithStreamBinding(forge.Emits[Order]("order.updated")),
)
```

### Frames are decoded before they are normalized

A REST response goes through the generated codec before it reaches the store, so under camelCase naming the store sees `customerId`. A frame now takes the same path: each row in the `streams` table whose entity is a component carries a `decode` built from that entity's codec, and the runtime runs it before normalizing the payload or reading its identity for an evict. Under `preserve` naming the wire shape is the client shape and no `decode` is emitted. A hand-written row without one is written to the store as the wire spelled it.

### Which field carries the name

`order.created` is what the binding is keyed on, but a binding matches a frame only if the client can find that name in the envelope — and Forge sends two envelopes.
Expand Down Expand Up @@ -212,5 +235,7 @@ It is a superset of the default decoder, not an alternative to it — it reads `
| `WithInvalidates` | `x-forge-invalidates` on the operation | OpenAPI |
| `WithoutInvalidation` | `x-forge-no-invalidation` on the operation | OpenAPI |
| `WithStreamBinding` | `x-forge-stream` on the channel | AsyncAPI |
| `WithWebTransportMessages` | `x-forge-protocol` on the channel, plus its messages | AsyncAPI |
| a component renamed at generation | `x-forge-type` on the schema | OpenAPI and AsyncAPI |

All of them round-trip through YAML as well as JSON.
4 changes: 3 additions & 1 deletion docs/content/docs/web-client/not-yet-shipped.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@ For balance, everything below is built, tested, and used by the examples in thes
- Optimistic overlays: a rebasing overlay stack, derived targets, and pending state in all three adapters
- React, Vue and Angular adapters
- Server rendering: `dehydrate` and `hydrate`, a reachability-closed payload, principal assertions on both sides, a hydration boundary in all three adapters, and `streamingDehydrator` for flushing a payload part-way through a stream
- A WebTransport binding, `webTransportConnection`
- Stream adapters for all three transports: `webSocketConnection`, `eventSourceConnection` and `webTransportConnection` turn an open socket, an `EventSource` or a WebTransport session into the connection the subscription manager drives, and `channelMessages` reads a channel's event names out of the `streams` table
- WebTransport routes described in the AsyncAPI document through `WithWebTransportMessages`, so `webtransport.ts` is typed per stream kind and the route's stream bindings reach the `streams` table
- Frames decoded through the entity's codec before normalization, so a live query under camelCase naming sees the same shape a response produces
- The devtools inspector

What is left is a handful of runtime edges and a freshness model that is deliberately narrow, not the core of the thing.
15 changes: 12 additions & 3 deletions extensions/streaming/contract/manifest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,15 @@ func TestEmbeddedManifest_LoadsAndValidates(t *testing.T) {
}
}

func TestRegister_BindsAllIntentsToTheDispatcher(t *testing.T) {
t.Skip("dispatcher.Dispatcher exercised via unit tests; full Register e2e is covered by the dashboard discovery loop integration test")
}
// Register is covered end to end by
// TestDashboardDiscovery_PublishesStreamingContract in the parent package,
// which boots a real Forge app with the real dashboard extension and asserts
// streaming-contract reaches the capabilities endpoint. It lives there rather
// than here because only a package outside contract/ can import the dashboard
// extension without a cycle.
//
// The distinction matters: the test above stops at loader.Validate, and
// contract.Registry.Register enforces rules the loader does not. A manifest
// that loads and validates here can still be rejected at registration, and the
// dashboard logs that rejection and carries on, so the only visible symptom
// is streaming-contract missing from /capabilities.
113 changes: 113 additions & 0 deletions extensions/streaming/dashboard_contract_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
package streaming

import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"

"github.com/xraph/forge"
"github.com/xraph/forge/extensions/dashboard"
)

// capabilitiesResponse is the shape the dashboard's discovery endpoint serves.
// Only the fields this test asserts on are modelled.
type capabilitiesResponse struct {
Contributors []struct {
Name string `json:"name"`
Intents []struct {
Name string `json:"name"`
} `json:"intents"`
} `json:"contributors"`
}

// TestDashboardDiscovery_PublishesStreamingContract boots a real Forge app with
// the real dashboard and streaming extensions, lets the dashboard's own
// auto-discovery loop register streaming's contract contributor, and asks the
// real capabilities endpoint what it ended up with.
//
// This covers a gap that unit-level manifest tests cannot: loader.Load and
// loader.Validate both accept a manifest that contract.Registry.Register then
// rejects, and the discovery loop logs that rejection and carries on. The
// visible symptom is not an error anywhere. It is streaming-contract quietly
// missing from /capabilities, with none of its intents reachable through the
// dispatcher. Asserting on the served capabilities is the only assertion that
// catches it.
func TestDashboardDiscovery_PublishesStreamingContract(t *testing.T) {
app := forge.New(
forge.WithAppName("streaming-contract-discovery-test"),
forge.WithAppVersion("1.0.0"),
forge.WithAppLogger(forge.NewNoopLogger()),
forge.WithConfig(forge.DefaultAppConfig()),
forge.WithExtensions(NewExtension(), dashboard.NewExtension()),
)

ctx := context.Background()
if err := app.Start(ctx); err != nil {
t.Fatalf("start app: %v", err)
}

t.Cleanup(func() {
if err := app.Stop(context.Background()); err != nil {
t.Errorf("stop app: %v", err)
}
})

req := httptest.NewRequest(http.MethodGet, "/dashboard/api/dashboard/v1/capabilities", nil)
w := httptest.NewRecorder()
app.Router().ServeHTTP(w, req)

if w.Code != http.StatusOK {
t.Fatalf("capabilities status = %d, body = %s", w.Code, w.Body)
}

var resp capabilitiesResponse
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatalf("unmarshal capabilities %s: %v", w.Body.Bytes(), err)
}

var streamingIntents []string

names := make([]string, 0, len(resp.Contributors))

for _, c := range resp.Contributors {
names = append(names, c.Name)

if c.Name != "streaming-contract" {
continue
}

for _, in := range c.Intents {
streamingIntents = append(streamingIntents, in.Name)
}
}

if streamingIntents == nil {
t.Fatalf("streaming-contract absent from capabilities; contributors = %v.\n"+
"The dashboard swallows contributor registration errors, so this is what a "+
"rejected manifest looks like from the outside. Check the dashboard's startup "+
"log for \"failed to register contract contributor\".", names)
}

// Every intent the manifest declares has to survive registration, not just
// the contributor name. A partial manifest would still produce a
// contributor entry here.
want := []string{
"stats", "connections.list", "rooms.list", "rooms.detail", "rooms.members",
"rooms.moderation", "channels.list", "presence.list", "config",
"rooms.create", "rooms.delete", "rooms.send-message", "presence.set",
"connections.kick",
}

got := make(map[string]bool, len(streamingIntents))
for _, in := range streamingIntents {
got[in] = true
}

for _, w := range want {
if !got[w] {
t.Errorf("intent %q missing from streaming-contract capabilities; got %v", w, streamingIntents)
}
}
}
15 changes: 15 additions & 0 deletions extensions/streaming/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@ require (

require (
github.com/BurntSushi/toml v1.6.0 // indirect
github.com/Oudwins/tailwind-merge-go v0.2.1 // indirect
github.com/a-h/templ v0.3.1001 // indirect
github.com/armon/go-metrics v0.4.1 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/dunglas/httpsfv v1.1.0 // indirect
Expand All @@ -26,6 +28,7 @@ require (
github.com/fxamacker/cbor/v2 v2.9.2 // indirect
github.com/gabriel-vasile/mimetype v1.4.15 // indirect
github.com/go-logr/logr v1.4.4 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-openapi/jsonpointer v1.0.0 // indirect
github.com/go-openapi/jsonreference v1.0.0 // indirect
github.com/go-openapi/swag v0.28.0 // indirect
Expand All @@ -48,6 +51,7 @@ require (
github.com/gobwas/pool v0.2.1 // indirect
github.com/gobwas/ws v1.4.0 // indirect
github.com/google/gnostic-models v0.7.1 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect
github.com/hashicorp/consul/api v1.34.4 // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
Expand Down Expand Up @@ -83,8 +87,15 @@ require (
github.com/xraph/forgeui v1.4.1 // indirect
github.com/xraph/go-utils v1.3.0 // indirect
github.com/yuin/gopher-lua v1.1.1 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/otel v1.44.0 // indirect
go.opentelemetry.io/otel/exporters/jaeger v1.17.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.43.0 // indirect
go.opentelemetry.io/otel/metric v1.44.0 // indirect
go.opentelemetry.io/otel/sdk v1.44.0 // indirect
go.opentelemetry.io/otel/trace v1.44.0 // indirect
go.opentelemetry.io/proto/otlp v1.10.0 // indirect
go.uber.org/atomic v1.11.0 // indirect
go.yaml.in/yaml/v2 v2.4.4 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
Expand All @@ -96,6 +107,9 @@ require (
golang.org/x/term v0.45.0 // indirect
golang.org/x/text v0.41.0 // indirect
golang.org/x/time v0.15.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect
google.golang.org/grpc v1.83.2 // indirect
google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af // indirect
gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
Expand All @@ -106,6 +120,7 @@ require (
k8s.io/klog/v2 v2.140.0 // indirect
k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad // indirect
k8s.io/utils v0.0.0-20260707023825-cf1189d6abe3 // indirect
nhooyr.io/websocket v1.8.17 // indirect
sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect
sigs.k8s.io/randfill v1.0.0 // indirect
sigs.k8s.io/structured-merge-diff/v6 v6.4.2 // indirect
Expand Down
Loading
Loading