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
14 changes: 13 additions & 1 deletion docs/content/docs/web-client/generated-package.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,19 @@ If a type in your API is already called `Capability` or `OperationName`, the mod

Generated when the specification declares channels. They are `EventEmitter`-style clients with reconnection, heartbeat and connection-state management, and their public surface is unchanged by the cache runtime — `@forge-go/client-core` drives them rather than replacing them.

For a Forge server, channels reach the specification through `forge.WithWebSocketMessages(...)` (or `WithSSEMessages`), which is what puts message schemas in the AsyncAPI document. A channel with no declared messages produces no client.
For a Forge server, channels reach the specification through `forge.WithWebSocketMessages(...)` (or `WithSSEMessages`), which is what puts message schemas in the AsyncAPI document.

### Streams in an OpenAPI document

A route registered with `SSE`, `EventStream`, `WebSocket` or `WebTransport` also appears in `openapi.json`, because it is still a `GET`. Forge marks it there with `x-forge-protocol: sse` (or `websocket`, `webtransport`), declares an SSE route's response as `text/event-stream`, and declares a WebSocket route's response as `101 Switching Protocols`. A stream is therefore never generated as a REST call: you get no `query(...)` binding and no method in `rest.ts`.

The generator also recognizes a stream in a document Forge did not write, such as one from a gateway. An operation counts as a stream when every 2xx response it declares is `text/event-stream`, or when its only success response is `101`.

What happens to it depends on what else describes it:

- **AsyncAPI describes the same path.** The channel is the stream's one description, with its event schemas and stream bindings, and the OpenAPI operation is dropped.
- **Only OpenAPI describes it, and the path has no parameters.** It becomes a stream client of its kind with untyped events, built from the operation's path, summary, tags and security.
- **Only OpenAPI describes it, and the path has parameters.** It is left out, and `forge client generate` prints a warning naming it. The generated stream clients do not yet substitute path parameters, so a client for `/instances/{id}/logs/stream` would connect to a literal `{id}`. Declare the route's messages with `WithSSEMessages` and generate from the AsyncAPI document as well.

<Callout type="info">
Forge emits REST operations to `openapi.json` and stream bindings to `asyncapi.json`, so pass both to get both:
Expand Down
2 changes: 1 addition & 1 deletion docs/content/docs/web-client/not-yet-shipped.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ For balance, everything below is built, tested, and used by the examples in thes
- Entity inference from Go response types, with its refusal cases, including the entity behind an undeclared collection envelope
- `ForgeEntity`, `ForgeEnvelope`, the `forge:"id"` tag, `WithEntity`, `WithoutEntity`
- Derived same-entity invalidation, `WithInvalidates`, `WithoutInvalidation`
- Time-based freshness: `WithStaleTime` on a Go route, a per-call and cache-wide `staleTime`, and the `revalidateOnFocus`, `revalidateOnReconnect` and `poll` installers, with the strictest live subscriber winning when more than one is mounted
- Time-based freshness: `WithStaleTime` on a Go route, a per-call and cache-wide `staleTime`, the `revalidateOnFocus`, `revalidateOnReconnect` and `poll` installers, and a per-call `refetchInterval` in all three adapters, with the strictest live subscriber winning when more than one is mounted
- `WithStreamBinding` and `Emits[T]`, with intent inferred from message suffix
- `x-forge-*` extensions in OpenAPI and AsyncAPI, round-tripping through **JSON and YAML**
- Capability gating: scopes from `WithRequiredAuth` as a typed union, `can()`, `canCall()` and `missingCapabilities()`, a UX affordance and never a security boundary
Expand Down
16 changes: 15 additions & 1 deletion docs/content/docs/web-client/runtime.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,20 @@ const { data } = useQuery(useListOrders, undefined, { staleTime: 5_000 });

Every framework adapter exposes the same option, under the same name, for the same reason: it is the one knob that can only make a query refresh more eagerly, never less.

### Polling from a call site

`refetchInterval` refetches a query on a timer for as long as the call site is mounted. It takes the same values as TanStack Query's option of the same name, `false` included, so a call site moves over unchanged:

```tsx
const { data } = useQuery(useGetExecution, { path: { id } }, {
refetchInterval: isExecuting ? 3_000 : false,
});
```

`false`, `0` or leaving it out polls nothing. The timer is keyed on the query and the interval, never on the result, so a new response does not restart it. Each request starts one interval after the previous one started, not after it finished, so a three-second poll on a slow endpoint stays a three-second poll. A response slower than the interval is followed by the next request straight away, never overlapped by it. Polling pauses while the tab is hidden; pass `refetchIntervalInBackground: true` to keep it going.

Vue takes a ref or getter for both options, and Angular a signal or any function, the same way they take `live` and `staleTime`. Where an operation has a channel, `{ live: true }` is the better answer: a push costs nothing between changes, and a poll costs a request whether or not anything moved.

### Installing the triggers

`revalidateOnFocus` and `revalidateOnReconnect` both call `cache.revalidate()`, which refetches every mounted query that has actually gone stale and leaves the rest alone. `poll` does not: it calls `cache.refetch()` on its own interval, unconditionally, whether or not the query has gone stale and whether or not anyone is even watching it beyond the poll itself. Set `staleTime: 600_000` and poll every second, and you still get a request every second. If you use both on the same query, the shorter of the two wins: `poll`'s interval, not `staleTime`, decides how often the network gets hit.
Expand All @@ -167,7 +181,7 @@ revalidateOnReconnect(cache);
poll(cache, ops.listOrders, undefined, 10_000);
```

`revalidateOnFocus` listens for `visibilitychange`, not `focus`, on purpose: returning to a tab that never stopped being visible should not refetch data you were already looking at. `revalidateOnReconnect` listens for the browser's `online` event. `poll` refetches one query on an interval and pauses while the tab is hidden unless you pass `whileHidden: true`. All three return a disposer; call it on teardown to stop listening.
`revalidateOnFocus` listens for `visibilitychange`, not `focus`, on purpose: returning to a tab that never stopped being visible should not refetch data you were already looking at. `revalidateOnReconnect` listens for the browser's `online` event. `poll` refetches one query on an interval, holding its cadence the way `refetchInterval` does, and pauses while the tab is hidden unless you pass `whileHidden: true`. `refetchInterval` is this installer, owned by a call site. All three return a disposer; call it on teardown to stop listening.

### Precedence, and the strictest subscriber

Expand Down
2 changes: 1 addition & 1 deletion internal/client/extension_coverage_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ var extensionDecisions = map[string]struct {

"x-forge-id": {knownGap, "read in entity.go's isMarkedIdentityField, which takes no *APISpec and is reached through anyMatch. Threading a spec through that call chain is a wider change than the warning is worth today. A wrong type here comes only from a hand-written document, since the generator emits a bool."},

"x-forge-protocol": {knownGap, "read by isWebTransportChannel; a non-string value is treated as absent and the channel is classified as a socket or SSE stream by its messages, which is what it would have been before the marker existed. The value is generated, never hand-written."},
"x-forge-protocol": {knownGap, "read in two places. On an OpenAPI operation, resolveEndpointStream warns on anything but sse, websocket or webtransport and falls back to classifying the endpoint by its responses. On an AsyncAPI channel, isWebTransportChannel treats a non-string value as absent and the channel is classified as a socket or SSE stream by its messages, which is what it would have been before the marker existed; there the value is generated, never hand-written."},

"x-forge-type": {knownGap, "read by resolveStreamEntityNames to match a stream binding to a renamed component. A non-string value is treated as absent, and the binding then falls through to the bare-name lookup, whose miss registerStreamBindingEntities already reports; the value is generated, never hand-written."},
}
Expand Down
7 changes: 7 additions & 0 deletions internal/client/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,13 @@ func (g *Generator) Generate(ctx context.Context, spec *APISpec, config Generato
return nil, err
}

// Before Validate, because a spec whose only REST operations are streams
// is a streaming client, and before the language generator, so none of
// them binds a stream as a request. Here rather than in the parser because
// a stream and its AsyncAPI channel can come from two documents, and only
// the merged spec has both.
spec.SeparateStreamEndpoints()

// Validate spec for this language
if err := gen.Validate(generators.APISpec(spec)); err != nil {
return nil, fmt.Errorf("validate spec: %w", err)
Expand Down
201 changes: 201 additions & 0 deletions internal/client/generators/typescript/e2e_stream_endpoints_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
package typescript

import (
"context"
"encoding/json"
"slices"
"strings"
"testing"

"github.com/xraph/forge/internal/client"
"github.com/xraph/forge/internal/client/generators"
"github.com/xraph/forge/internal/router"
"github.com/xraph/forge/internal/shared"
)

// gatewayStreamDoc is the shape xraph/forge#106 reported: an OpenAPI document
// with no AsyncAPI beside it, where a log stream is an ordinary-looking GET.
// Written by something other than forge's router, so nothing carries
// x-forge-protocol; the response's media type is the only evidence.
const gatewayStreamDoc = `{
"openapi": "3.0.3",
"info": { "title": "Portal", "version": "1.0.0" },
"paths": {
"/admin/instances/{instanceId}": {
"get": {
"operationId": "getAdminInstance",
"parameters": [{ "name": "instanceId", "in": "path", "required": true, "schema": { "type": "string" } }],
"responses": { "200": { "description": "ok", "content": { "application/json": {
"schema": { "type": "object", "properties": { "id": { "type": "string" } } } } } } }
}
},
"/admin/instances/{instanceId}/logs/stream": {
"get": {
"operationId": "streamAdminInstanceLogs",
"parameters": [{ "name": "instanceId", "in": "path", "required": true, "schema": { "type": "string" } }],
"responses": { "200": { "description": "log lines", "content": { "text/event-stream": {
"schema": { "type": "string" } } } } }
}
},
"/admin/events/stream": {
"get": {
"operationId": "streamAdminEvents",
"responses": { "200": { "description": "events", "content": { "text/event-stream": {
"schema": { "type": "string" } } } } }
}
}
}
}`

// generateThroughEntryPoint drives client.Generator.Generate, the function the
// CLI calls, rather than the language generator directly: separating streams
// from requests happens there.
func generateThroughEntryPoint(t *testing.T, spec *client.APISpec, hooks bool) map[string]string {
t.Helper()

return generateWithWarnings(t, spec, hooks).Files
}

func generateWithWarnings(t *testing.T, spec *client.APISpec, hooks bool) *generators.GeneratedClient {
t.Helper()

gen := client.NewGenerator()
if err := gen.Register(NewGenerator()); err != nil {
t.Fatalf("Register: %v", err)
}

cfg := baseConfig()
cfg.Hooks = hooks

out, err := gen.Generate(context.Background(), spec, cfg)
if err != nil {
t.Fatalf("Generate: %v", err)
}

return out
}

func TestStreamEndpointIsNotBoundAsAQuery(t *testing.T) {
path := writeSpecFile(t, "openapi.json", gatewayStreamDoc)

parse := func() *client.APISpec {
spec, err := client.NewSpecParser().ParseFile(context.Background(), path)
if err != nil {
t.Fatalf("ParseFile: %v", err)
}

return spec
}

out := generateWithWarnings(t, parse(), true)
files := out.Files
ops, hooks := ClientManifestText(files), ClientHooksText(files)

if !strings.Contains(hooks, "useGetAdminInstance") {
t.Fatalf("the ordinary GET lost its hook; hooks:\n%s", hooks)
}

for name, text := range map[string]string{"ops": ops, "hooks": hooks} {
if strings.Contains(text, "/logs/stream") || strings.Contains(text, "/events/stream") ||
strings.Contains(strings.ToLower(text), "streamadmin") {
t.Errorf("%s still binds a stream as a request:\n%s", name, text)
}
}

all := joinFiles(files)

if !strings.Contains(all, "StreamAdminEventsSSEClient") {
t.Errorf("the stream only OpenAPI describes has no SSE client; files: %v", fileNames(files))
}

// The stream clients put a channel's path on the wire as written, so a
// client for the parameterized stream would connect to a literal
// `{instanceId}`. It is left out, and the generator says so.
if strings.Contains(all, "StreamAdminInstanceLogsSSEClient") {
t.Error("a client was generated for a parameterized stream it cannot address")
}

if !slices.ContainsFunc(out.Warnings, func(w string) bool {
return strings.Contains(w, "GET /admin/instances/{instanceId}/logs/stream")
}) {
t.Errorf("no warning names the parameterized stream; warnings: %v", out.Warnings)
}

// The stream client built from nothing but an operation has to compile.
// Without hooks, because they import @forge-go/client-core, which the
// type-check sandbox does not install.
dir := t.TempDir()
writeTree(t, dir, generateThroughEntryPoint(t, parse(), false))

if errs := typeCheck(t, dir); len(errs) > 0 {
t.Errorf("%d type error(s):\n%s", len(errs), strings.Join(errs, "\n"))
}
}

type streamE2ERequest struct{}

type streamE2EOrder struct {
ID string `json:"id"`
}

// The router writes an SSE route into both documents. Merged, the stream is
// described once, by its channel, and no request binding is left over.
// Unparameterized, so the AsyncAPI channel and the OpenAPI operation are the
// only two descriptions in play.
func TestRouterStreamRouteIsDescribedOnceAcrossBothDocuments(t *testing.T) {
r := router.NewRouter(
router.WithOpenAPI(router.OpenAPIConfig{Title: "Orders", Version: "1.0.0"}),
router.WithAsyncAPI(router.AsyncAPIConfig{Title: "Orders", Version: "1.0.0"}),
)

if err := r.GET("/orders/:id", func(ctx shared.Context, req *streamE2ERequest) (*streamE2EOrder, error) {
return &streamE2EOrder{}, nil
}); err != nil {
t.Fatal(err)
}

if err := r.SSE("/orders/stream", func(ctx router.Context) error { return nil }); err != nil {
t.Fatal(err)
}

openAPI, err := json.Marshal(r.OpenAPISpec())
if err != nil {
t.Fatal(err)
}

asyncAPI, err := json.Marshal(r.AsyncAPISpec())
if err != nil {
t.Fatal(err)
}

parser := client.NewSpecParser()

var specs []*client.APISpec

for name, doc := range map[string][]byte{"openapi.json": openAPI, "asyncapi.json": asyncAPI} {
spec, err := parser.ParseFileUnresolved(context.Background(), writeSpecFile(t, name, string(doc)))
if err != nil {
t.Fatalf("parse %s: %v", name, err)
}

specs = append(specs, spec)
}

merged := client.MergeSpecs(specs...)
client.ResolveEntityFields(merged)

files := generateThroughEntryPoint(t, merged, true)

if hooks := ClientHooksText(files); strings.Contains(hooks, "/stream") ||
strings.Count(hooks, "= query") != 1 {
t.Errorf("want exactly one query binding, for GET /orders/{id}; hooks:\n%s", hooks)
}

if ops := ClientManifestText(files); strings.Contains(ops, "/stream'") {
t.Errorf("ops.ts still carries the stream as an operation:\n%s", ops)
}

if got := strings.Count(joinFiles(files), "SSEClient extends EventEmitter {"); got != 1 {
t.Errorf("want one SSE client class, got %d", got)
}
}
8 changes: 8 additions & 0 deletions internal/client/introspector.go
Original file line number Diff line number Diff line change
Expand Up @@ -755,6 +755,7 @@ func (i *Introspector) operationToEndpoint(spec *APISpec, method, path string, o
resolveEndpointCacheMeta(spec, &endpoint, op.Extensions)
endpoint.Authorization = resolveEndpointAuthz(op.Extensions)
resolveEndpointIdempotent(spec, &endpoint, op.Extensions)
resolveEndpointStream(spec, &endpoint, op.Extensions)
collectSyncRoute(spec, endpointOrigin(&endpoint), endpoint.Path, "", op.Extensions)

return endpoint
Expand Down Expand Up @@ -924,6 +925,13 @@ func (i *Introspector) routeToEndpoint(route router.RouteInfo) Endpoint {
// Copy metadata
maps.Copy(endpoint.Metadata, route.Metadata)

// The route table knows outright what a document has to infer. A route
// registered through SSE, EventStream, WebSocket or WebTransport is a
// stream, whatever its method says.
if route.Kind.LongLived() {
endpoint.Stream = route.Kind.String()
}

return endpoint
}

Expand Down
7 changes: 7 additions & 0 deletions internal/client/ir.go
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,13 @@ type Endpoint struct {
// it describes the document, and describing it costs nothing when there is
// no entity beneath.
RootType string

// Stream is the protocol this endpoint holds its connection open over --
// StreamSSE, StreamWebSocket or StreamWebTransport -- or empty for an
// ordinary request. Read from x-forge-protocol, or from responses that are
// only text/event-stream or 101. Generator.Generate moves every endpoint
// with one set out of Endpoints; see APISpec.SeparateStreamEndpoints.
Stream string
}

// WebSocketEndpoint represents a WebSocket endpoint.
Expand Down
1 change: 1 addition & 0 deletions internal/client/spec_parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -576,6 +576,7 @@ func convertOperation(spec *APISpec, method, path string, op *shared.Operation)
resolveEndpointCacheMeta(spec, &endpoint, op.Extensions)
endpoint.Authorization = resolveEndpointAuthz(op.Extensions)
resolveEndpointIdempotent(spec, &endpoint, op.Extensions)
resolveEndpointStream(spec, &endpoint, op.Extensions)
collectSyncRoute(spec, endpointOrigin(&endpoint), endpoint.Path, "", op.Extensions)

return endpoint
Expand Down
Loading
Loading