From 2c199e7593a890221255e96f5e5c4f8b75790f7b Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:15:09 -0600 Subject: [PATCH 1/2] fix(client): stop generating stream endpoints as REST calls SSE, EventStream, WebSocket and WebTransport routes are registered as plain GETs, so they landed in openapi.json as `GET -> 200 Success`, which nothing can tell apart from a REST read. The TypeScript generator bound every one of them as `query(...)`, and calling that fetches an endpoint whose body never ends. The Go and Dart REST clients had the same trap. The router now marks those operations with x-forge-protocol (the marker AsyncAPI channels already carry for WebTransport), answers an SSE route's 200 as text/event-stream, and gives a WebSocket route a 101 when its only response is the generated default. On the client side the IR records Endpoint.Stream from that marker, or from responses that are only text/event-stream or only 101, so a document from a gateway is caught too. Generator.Generate then takes streams out of Endpoints after merge and filtering. A stream AsyncAPI already describes is dropped, a stream only OpenAPI knows about becomes a stream endpoint of its kind, and one whose path has parameters is left out with a warning, because the generated stream clients don't substitute path parameters yet. Refs #106 --- .../docs/web-client/generated-package.mdx | 14 +- internal/client/extension_coverage_test.go | 2 +- internal/client/generator.go | 7 + .../typescript/e2e_stream_endpoints_test.go | 201 ++++++++++++++ internal/client/introspector.go | 8 + internal/client/ir.go | 7 + internal/client/spec_parser.go | 1 + internal/client/stream_endpoints.go | 249 ++++++++++++++++++ internal/client/stream_endpoints_test.go | 134 ++++++++++ internal/router/openapi_generator.go | 67 +++++ internal/router/openapi_stream_test.go | 120 +++++++++ internal/router/testdata/openapi.json | 32 ++- internal/router/testdata/openapi.yaml | 17 +- 13 files changed, 841 insertions(+), 18 deletions(-) create mode 100644 internal/client/generators/typescript/e2e_stream_endpoints_test.go create mode 100644 internal/client/stream_endpoints.go create mode 100644 internal/client/stream_endpoints_test.go create mode 100644 internal/router/openapi_stream_test.go diff --git a/docs/content/docs/web-client/generated-package.mdx b/docs/content/docs/web-client/generated-package.mdx index dfe770257..fd10c6911 100644 --- a/docs/content/docs/web-client/generated-package.mdx +++ b/docs/content/docs/web-client/generated-package.mdx @@ -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. Forge emits REST operations to `openapi.json` and stream bindings to `asyncapi.json`, so pass both to get both: diff --git a/internal/client/extension_coverage_test.go b/internal/client/extension_coverage_test.go index d5f2958ee..6a673c007 100644 --- a/internal/client/extension_coverage_test.go +++ b/internal/client/extension_coverage_test.go @@ -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."}, } diff --git a/internal/client/generator.go b/internal/client/generator.go index 78ac6494c..463f619aa 100644 --- a/internal/client/generator.go +++ b/internal/client/generator.go @@ -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) diff --git a/internal/client/generators/typescript/e2e_stream_endpoints_test.go b/internal/client/generators/typescript/e2e_stream_endpoints_test.go new file mode 100644 index 000000000..297b49f56 --- /dev/null +++ b/internal/client/generators/typescript/e2e_stream_endpoints_test.go @@ -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) + } +} diff --git a/internal/client/introspector.go b/internal/client/introspector.go index 64e308fd3..2c509b542 100644 --- a/internal/client/introspector.go +++ b/internal/client/introspector.go @@ -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 @@ -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 } diff --git a/internal/client/ir.go b/internal/client/ir.go index 4435499c7..988902c5f 100644 --- a/internal/client/ir.go +++ b/internal/client/ir.go @@ -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. diff --git a/internal/client/spec_parser.go b/internal/client/spec_parser.go index 236c07f92..760406e4d 100644 --- a/internal/client/spec_parser.go +++ b/internal/client/spec_parser.go @@ -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 diff --git a/internal/client/stream_endpoints.go b/internal/client/stream_endpoints.go new file mode 100644 index 000000000..a96f083fb --- /dev/null +++ b/internal/client/stream_endpoints.go @@ -0,0 +1,249 @@ +package client + +import ( + "fmt" + "mime" + "strings" +) + +// Values of Endpoint.Stream, and of the x-forge-protocol extension on an +// OpenAPI operation. The same strings the router's RouteKind renders, so a +// route's kind, the document's marker and the IR's classification are one +// vocabulary. +const ( + StreamSSE = "sse" + StreamWebSocket = "websocket" + StreamWebTransport = "webtransport" +) + +func isStreamProtocol(v string) bool { + return v == StreamSSE || v == StreamWebSocket || v == StreamWebTransport +} + +// resolveEndpointStream records whether an OpenAPI operation holds its +// connection open rather than answering once. +// +// A streaming route reaches OpenAPI as an ordinary GET. Left there, every +// language generator binds it as a request: the TypeScript client emits +// `query(...)` over it, and calling that issues a plain fetch at an endpoint +// that never finishes its body, so it hangs or buffers the whole stream as one +// response. Nothing about the binding says it is not a query. +// +// The router marks the operations it knows stream with x-forge-protocol. A +// document written by something else gets the same treatment when its success +// responses say so in the only way OpenAPI can: every 2xx body is +// text/event-stream, or the only success is 101 Switching Protocols. +func resolveEndpointStream(spec *APISpec, ep *Endpoint, ext map[string]any) { + if raw, present := ext[protocolExtension]; present { + if v, ok := raw.(string); ok && isStreamProtocol(v) { + ep.Stream = v + + return + } + + unusable(spec, endpointOrigin(ep), protocolExtension, + fmt.Sprintf("one of %q, %q or %q", StreamSSE, StreamWebSocket, StreamWebTransport)) + } + + ep.Stream = streamFromResponses(ep) +} + +// streamFromResponses classifies an endpoint by what its success responses +// declare. Conservative on purpose: one 2xx response with a non-stream body +// means the endpoint can answer as an ordinary request, and it stays one. +func streamFromResponses(ep *Endpoint) string { + var sawSuccess, sawSSE, sawOther bool + + for code, resp := range ep.Responses { + if code < 200 || code > 299 { + continue + } + + sawSuccess = true + + if resp == nil { + continue + } + + for contentType := range resp.Content { + if isEventStream(contentType) { + sawSSE = true + } else { + sawOther = true + } + } + } + + if sawSSE && !sawOther { + return StreamSSE + } + + if !sawSuccess { + if _, upgrades := ep.Responses[101]; upgrades { + return StreamWebSocket + } + } + + return "" +} + +func isEventStream(contentType string) bool { + media, _, err := mime.ParseMediaType(contentType) + if err != nil { + media = strings.TrimSpace(strings.ToLower(contentType)) + } + + return media == "text/event-stream" +} + +// SeparateStreamEndpoints takes every streaming endpoint out of spec.Endpoints, +// so no generator binds it as a request. +// +// A stream the AsyncAPI side already describes is dropped from the REST list: +// the router writes every SSE, WebSocket and WebTransport route into both +// documents, and the AsyncAPI channel is the one carrying the event schemas +// and stream bindings. A stream only OpenAPI knows about -- a document from a +// gateway, a hand-written handler that declares text/event-stream -- becomes a +// stream endpoint of its kind with what the operation said about it, so the +// client still has a way to reach it and that way is the right one. +// +// Unless its path has parameters. The stream clients concatenate a channel's +// path onto the base URL as written, so a client built for +// `/instances/{id}/logs` would connect to a literal `{id}`. That stream is +// left out with a warning rather than generated broken; declaring it in +// AsyncAPI is the way to a client for it. +// +// Run by Generator.Generate, after any merge and filter, because a stream and +// its channel can arrive from two separate documents and only the merged spec +// has both. Idempotent: a second call finds nothing left to move. +func (s *APISpec) SeparateStreamEndpoints() { + if s == nil { + return + } + + known := make(map[string]bool, len(s.SSEs)+len(s.WebSockets)+len(s.WebTransports)) + + for i := range s.SSEs { + known[StreamSSE+" "+streamPathKey(s.SSEs[i].Path)] = true + } + + for i := range s.WebSockets { + known[StreamWebSocket+" "+streamPathKey(s.WebSockets[i].Path)] = true + } + + for i := range s.WebTransports { + known[StreamWebTransport+" "+streamPathKey(s.WebTransports[i].Path)] = true + } + + kept := make([]Endpoint, 0, len(s.Endpoints)) + + for i := range s.Endpoints { + ep := s.Endpoints[i] + + if ep.Stream == "" { + kept = append(kept, ep) + + continue + } + + key := ep.Stream + " " + streamPathKey(ep.Path) + if known[key] { + continue + } + + known[key] = true + + if strings.Contains(streamPathKey(ep.Path), "{}") { + s.Warnings = append(s.Warnings, fmt.Sprintf( + "client: %s streams (%s), so it is left out of the REST client; its path has parameters, "+ + "which the generated stream clients do not substitute, so no stream client is generated for it either. "+ + "Describe it in AsyncAPI to bind it as a stream.", + endpointOrigin(&ep), ep.Stream)) + + continue + } + + switch ep.Stream { + case StreamSSE: + s.SSEs = append(s.SSEs, SSEEndpoint{ + ID: streamEndpointID(&ep), + Path: ep.Path, + Summary: ep.Summary, + Description: ep.Description, + Tags: ep.Tags, + EventSchemas: map[string]*Schema{}, + Security: ep.Security, + Authorization: ep.Authorization, + Metadata: ep.Metadata, + }) + case StreamWebSocket: + s.WebSockets = append(s.WebSockets, WebSocketEndpoint{ + ID: streamEndpointID(&ep), + Path: ep.Path, + Summary: ep.Summary, + Description: ep.Description, + Tags: ep.Tags, + Parameters: ep.PathParams, + Security: ep.Security, + Authorization: ep.Authorization, + Metadata: ep.Metadata, + }) + case StreamWebTransport: + s.WebTransports = append(s.WebTransports, WebTransportEndpoint{ + ID: streamEndpointID(&ep), + Path: ep.Path, + Summary: ep.Summary, + Description: ep.Description, + Tags: ep.Tags, + Security: ep.Security, + Authorization: ep.Authorization, + Metadata: ep.Metadata, + }) + } + } + + s.Endpoints = kept +} + +// streamPathKey reduces a path to its shape, so `/logs/{id}` from OpenAPI and +// `/logs/:id` from a raw route or channel address name the same stream. +func streamPathKey(path string) string { + segments := strings.Split(strings.TrimSuffix(path, "/"), "/") + + for i, seg := range segments { + if strings.HasPrefix(seg, ":") || strings.HasPrefix(seg, "*") || + (strings.HasPrefix(seg, "{") && strings.HasSuffix(seg, "}")) { + segments[i] = "{}" + } + } + + return strings.Join(segments, "/") +} + +// streamEndpointID names a stream built from an operation: its operationId +// when it has one, otherwise its path in the shape the AsyncAPI generator gives +// a channel, so the class a generator derives from it reads like any other. +func streamEndpointID(ep *Endpoint) string { + if ep.OperationID != "" { + return ep.OperationID + } + + if ep.ID != "" { + return ep.ID + } + + parts := make([]string, 0, 8) + + for seg := range strings.SplitSeq(ep.Path, "/") { + seg = strings.Trim(seg, "{}:*") + if seg != "" { + parts = append(parts, seg) + } + } + + if len(parts) == 0 { + return "root" + } + + return strings.Join(parts, "-") +} diff --git a/internal/client/stream_endpoints_test.go b/internal/client/stream_endpoints_test.go new file mode 100644 index 000000000..e4f2d58f5 --- /dev/null +++ b/internal/client/stream_endpoints_test.go @@ -0,0 +1,134 @@ +package client + +import ( + "strings" + "testing" +) + +func eventStream() map[int]*Response { + return map[int]*Response{200: {Content: map[string]*MediaType{ + "text/event-stream; charset=utf-8": {Schema: &Schema{Type: "string"}}, + }}} +} + +func TestResolveEndpointStream(t *testing.T) { + cases := []struct { + name string + ext map[string]any + responses map[int]*Response + want string + }{ + {"marked sse", map[string]any{"x-forge-protocol": "sse"}, nil, StreamSSE}, + {"marked websocket", map[string]any{"x-forge-protocol": "websocket"}, nil, StreamWebSocket}, + {"marked webtransport", map[string]any{"x-forge-protocol": "webtransport"}, nil, StreamWebTransport}, + {"event-stream body", nil, eventStream(), StreamSSE}, + {"upgrade only", nil, map[int]*Response{101: {}}, StreamWebSocket}, + {"json body", nil, map[int]*Response{200: {Content: map[string]*MediaType{ + "application/json": {}, + }}}, ""}, + {"negotiated json or stream", nil, map[int]*Response{200: {Content: map[string]*MediaType{ + "application/json": {}, + "text/event-stream": {}, + }}}, ""}, + {"bare 200", nil, map[int]*Response{200: {Description: "Success"}}, ""}, + {"101 beside a 200", nil, map[int]*Response{101: {}, 200: {}}, ""}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + spec := &APISpec{} + ep := &Endpoint{Method: "GET", Path: "/x", Responses: tc.responses} + + resolveEndpointStream(spec, ep, tc.ext) + + if ep.Stream != tc.want { + t.Errorf("Stream = %q, want %q", ep.Stream, tc.want) + } + + if len(spec.Warnings) != 0 { + t.Errorf("unexpected warnings: %v", spec.Warnings) + } + }) + } +} + +func TestResolveEndpointStreamWarnsOnAnUnusableMarker(t *testing.T) { + for _, raw := range []any{"grpc", true} { + spec := &APISpec{} + ep := &Endpoint{Method: "GET", Path: "/logs", Responses: eventStream()} + + resolveEndpointStream(spec, ep, map[string]any{"x-forge-protocol": raw}) + + if len(spec.Warnings) != 1 || !strings.Contains(spec.Warnings[0], "x-forge-protocol") || + !strings.Contains(spec.Warnings[0], "GET /logs") { + t.Errorf("%v: warnings = %v, want one naming the extension and the endpoint", raw, spec.Warnings) + } + + // The marker is dropped, not the endpoint's other evidence. + if ep.Stream != StreamSSE { + t.Errorf("%v: Stream = %q, want sse from the response", raw, ep.Stream) + } + } +} + +func TestSeparateStreamEndpoints(t *testing.T) { + spec := &APISpec{ + Endpoints: []Endpoint{ + {Method: "GET", Path: "/orders"}, + // Described by AsyncAPI too, under the router's raw path syntax. + {Method: "GET", Path: "/instances/{id}/logs/stream", Stream: StreamSSE}, + // Only OpenAPI knows about these. + { + Method: "GET", Path: "/admin/health/stream", Stream: StreamSSE, + Summary: "Health", Tags: []string{"admin"}, + Security: []SecurityRequirement{{SchemeName: "bearer"}}, + }, + {Method: "GET", Path: "/ws/lobby", OperationID: "lobbySocket", Stream: StreamWebSocket}, + {Method: "GET", Path: "/wt", Stream: StreamWebTransport}, + // Only OpenAPI knows about it, and its path has a parameter the + // stream clients would not substitute. + {Method: "GET", Path: "/instances/{id}/usage/stream", Stream: StreamSSE}, + }, + SSEs: []SSEEndpoint{{ID: "logs", Path: "/instances/:id/logs/stream"}}, + } + + spec.SeparateStreamEndpoints() + + if len(spec.Endpoints) != 1 || spec.Endpoints[0].Path != "/orders" { + t.Fatalf("Endpoints = %+v, want only /orders", spec.Endpoints) + } + + if len(spec.SSEs) != 2 { + t.Fatalf("SSEs = %+v, want the AsyncAPI one plus the health stream", spec.SSEs) + } + + if spec.SSEs[0].ID != "logs" { + t.Errorf("the channel AsyncAPI described was replaced: %+v", spec.SSEs[0]) + } + + health := spec.SSEs[1] + if health.Path != "/admin/health/stream" || health.ID != "admin-health-stream" || + health.Summary != "Health" || len(health.Security) != 1 || len(health.Tags) != 1 { + t.Errorf("health stream = %+v, want the operation's path, a path-derived id, summary, tags and security", health) + } + + if len(spec.WebSockets) != 1 || spec.WebSockets[0].ID != "lobbySocket" { + t.Errorf("WebSockets = %+v, want lobbySocket", spec.WebSockets) + } + + if len(spec.WebTransports) != 1 || spec.WebTransports[0].Path != "/wt" { + t.Errorf("WebTransports = %+v, want /wt", spec.WebTransports) + } + + if len(spec.Warnings) != 1 || !strings.Contains(spec.Warnings[0], "GET /instances/{id}/usage/stream") { + t.Errorf("warnings = %v, want one naming the parameterized stream", spec.Warnings) + } + + // Idempotent. + spec.SeparateStreamEndpoints() + + if len(spec.Endpoints) != 1 || len(spec.SSEs) != 2 || len(spec.WebSockets) != 1 || len(spec.Warnings) != 1 { + t.Errorf("a second pass changed the spec: %d endpoints, %d SSEs, %d sockets, %d warnings", + len(spec.Endpoints), len(spec.SSEs), len(spec.WebSockets), len(spec.Warnings)) + } +} diff --git a/internal/router/openapi_generator.go b/internal/router/openapi_generator.go index 5d26b3eac..10fb777d9 100644 --- a/internal/router/openapi_generator.go +++ b/internal/router/openapi_generator.go @@ -421,6 +421,8 @@ func (g *openAPIGenerator) processRoute(spec *OpenAPISpec, route RouteInfo) erro } } + markStreamOperation(operation, route.Kind) + // Set operation on path item based on method g.setOperation(pathItem, route.Method, operation) @@ -1417,3 +1419,68 @@ func sortedUniqueStrings(v any) []string { return out } + +// markStreamOperation says, in the document, that a route holds its connection +// open. +// +// SSE, EventStream, WebSocket and WebTransport routes are registered as +// ordinary GETs, and the AsyncAPI document is where their messages live. In +// OpenAPI they used to come out as `GET -> 200 Success`, which no reader can +// tell apart from a REST read: the client generator bound each one as a query, +// and any other OpenAPI tool would have generated a plain request for it. +// +// x-forge-protocol carries the kind in the vocabulary the AsyncAPI channel +// already uses for WebTransport. The responses are corrected too, for readers +// that know nothing of x-forge-*: an SSE route answers text/event-stream, and a +// WebSocket route whose responses are only the generated default answers 101. +func markStreamOperation(op *Operation, kind RouteKind) { + if !kind.LongLived() { + return + } + + if op.Extensions == nil { + op.Extensions = make(map[string]any) + } + + op.Extensions["x-forge-protocol"] = kind.String() + + switch kind { + case KindSSE: + resp := op.Responses["200"] + if resp == nil { + resp = &Response{Description: "Event stream"} + op.Responses["200"] = resp + } + + // A schema a route declared for its 200 describes the events, not a + // JSON document, so it moves under the stream's media type rather than + // being thrown away. Content types are visited in sorted order so the + // choice between several is stable. + var schema *Schema + + for _, ct := range slices.Sorted(maps.Keys(resp.Content)) { + if media := resp.Content[ct]; media != nil && media.Schema != nil { + schema = media.Schema + + break + } + } + + if schema == nil { + schema = &Schema{Type: "string"} + } + + if resp.Description == "" || resp.Description == "Success" { + resp.Description = "Event stream" + } + + resp.Content = map[string]*MediaType{"text/event-stream": {Schema: schema}} + + case KindWebSocket: + if def, only := op.Responses["200"]; only && len(op.Responses) == 1 && + def.Description == "Success" && len(def.Content) == 0 { + delete(op.Responses, "200") + op.Responses["101"] = &Response{Description: "Switching Protocols"} + } + } +} diff --git a/internal/router/openapi_stream_test.go b/internal/router/openapi_stream_test.go new file mode 100644 index 000000000..23b5dbe11 --- /dev/null +++ b/internal/router/openapi_stream_test.go @@ -0,0 +1,120 @@ +package router + +import ( + "testing" + + "github.com/xraph/forge/internal/shared" +) + +type streamProbeRequest struct{} + +type streamProbeResponse struct { + ID string `json:"id"` +} + +// A streaming route used to reach OpenAPI as `GET -> 200 Success`, which no +// reader can tell from a REST read. The client generator bound every one of +// them as a query; see xraph/forge#106. +func TestStreamingRoutesAreMarkedInOpenAPI(t *testing.T) { + r := NewRouter(WithOpenAPI(OpenAPIConfig{Title: "Streams", Version: "1.0.0"})) + + if err := r.SSE("/logs/stream", func(ctx Context) error { return nil }); err != nil { + t.Fatal(err) + } + + if err := r.EventStream("/events", func(ctx Context, s Stream) error { return nil }); err != nil { + t.Fatal(err) + } + + if err := r.WebSocket("/ws", func(ctx Context, c Connection) error { return nil }); err != nil { + t.Fatal(err) + } + + if err := r.GET("/orders", func(ctx shared.Context, req *streamProbeRequest) (*streamProbeResponse, error) { + return &streamProbeResponse{}, nil + }); err != nil { + t.Fatal(err) + } + + spec := r.OpenAPISpec() + if spec == nil { + t.Fatal("no OpenAPI document") + } + + for _, path := range []string{"/logs/stream", "/events"} { + op := spec.Paths[path].Get + if op == nil { + t.Fatalf("%s: no GET operation", path) + } + + if got := op.Extensions["x-forge-protocol"]; got != "sse" { + t.Errorf("%s: x-forge-protocol = %v, want sse", path, got) + } + + resp := op.Responses["200"] + if resp == nil || resp.Content["text/event-stream"] == nil { + t.Errorf("%s: 200 does not answer text/event-stream: %+v", path, resp) + } else if len(resp.Content) != 1 { + t.Errorf("%s: 200 declares %d media types, want only text/event-stream", path, len(resp.Content)) + } + } + + ws := spec.Paths["/ws"].Get + if got := ws.Extensions["x-forge-protocol"]; got != "websocket" { + t.Errorf("/ws: x-forge-protocol = %v, want websocket", got) + } + + if _, ok := ws.Responses["101"]; !ok || len(ws.Responses) != 1 { + t.Errorf("/ws: responses = %v, want only 101", ws.Responses) + } + + rest := spec.Paths["/orders"].Get + if _, marked := rest.Extensions["x-forge-protocol"]; marked { + t.Error("/orders: an ordinary GET is marked as a stream") + } +} + +// A schema a route declared for its 200 describes the events, so it survives +// under the stream's media type instead of being replaced. +func TestMarkStreamOperationKeepsADeclaredEventSchema(t *testing.T) { + declared := &Schema{Ref: "#/components/schemas/LogLine"} + op := &Operation{Responses: map[string]*Response{ + "200": {Description: "Log lines", Content: map[string]*MediaType{ + "application/json": {Schema: declared}, + }}, + }} + + markStreamOperation(op, KindSSE) + + resp := op.Responses["200"] + if resp.Description != "Log lines" { + t.Errorf("description = %q, want the declared one kept", resp.Description) + } + + media := resp.Content["text/event-stream"] + if media == nil || media.Schema != declared { + t.Errorf("content = %+v, want the declared schema under text/event-stream", resp.Content) + } + + if _, ok := resp.Content["application/json"]; ok { + t.Error("application/json is still declared on a stream") + } +} + +// A WebSocket route that declared its own responses keeps them: only the +// generated default is rewritten to 101. +func TestMarkStreamOperationLeavesDeclaredWebSocketResponses(t *testing.T) { + op := &Operation{Responses: map[string]*Response{ + "200": {Description: "Upgraded"}, + }} + + markStreamOperation(op, KindWebSocket) + + if _, ok := op.Responses["200"]; !ok { + t.Error("a declared 200 was replaced") + } + + if op.Extensions["x-forge-protocol"] != "websocket" { + t.Errorf("x-forge-protocol = %v, want websocket", op.Extensions["x-forge-protocol"]) + } +} diff --git a/internal/router/testdata/openapi.json b/internal/router/testdata/openapi.json index e267457e4..0d6bc4198 100644 --- a/internal/router/testdata/openapi.json +++ b/internal/router/testdata/openapi.json @@ -402,13 +402,21 @@ }, "/sse/notifications": { "get": { - "summary": "Notification feed", "operationId": "notifications", "responses": { "200": { - "description": "Success" + "description": "Event stream", + "content": { + "text/event-stream": { + "schema": { + "type": "string" + } + } + } } - } + }, + "summary": "Notification feed", + "x-forge-protocol": "sse" } }, "/tenants/{tenantId}/items": { @@ -530,7 +538,6 @@ }, "/ws/orders/{roomId}": { "get": { - "summary": "Order room", "operationId": "orders", "parameters": [ { @@ -544,15 +551,16 @@ } ], "responses": { - "200": { - "description": "Success" + "101": { + "description": "Switching Protocols" } - } + }, + "summary": "Order room", + "x-forge-protocol": "websocket" } }, "/ws/trees/{treeId}": { "get": { - "summary": "Tree event stream", "operationId": "treeEvents", "parameters": [ { @@ -566,10 +574,12 @@ } ], "responses": { - "200": { - "description": "Success" + "101": { + "description": "Switching Protocols" } - } + }, + "summary": "Tree event stream", + "x-forge-protocol": "websocket" } } }, diff --git a/internal/router/testdata/openapi.yaml b/internal/router/testdata/openapi.yaml index 6315691c5..f82cdf83b 100644 --- a/internal/router/testdata/openapi.yaml +++ b/internal/router/testdata/openapi.yaml @@ -249,7 +249,12 @@ paths: operationId: notifications responses: "200": - description: Success + description: Event stream + content: + text/event-stream: + schema: + type: string + x-forge-protocol: sse /tenants/{tenantId}/items: get: summary: List tenant items @@ -332,8 +337,9 @@ paths: schema: type: string responses: - "200": - description: Success + "101": + description: Switching Protocols + x-forge-protocol: websocket /ws/trees/{treeId}: get: summary: Tree event stream @@ -346,8 +352,9 @@ paths: schema: type: string responses: - "200": - description: Success + "101": + description: Switching Protocols + x-forge-protocol: websocket components: schemas: BillingInvoice: From 2f41beefc15bba768f7938c53735c33722e3ccec Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:15:09 -0600 Subject: [PATCH 2/2] feat(client): add refetchInterval to useQuery and injectQuery Polling had to be written by hand at every call site, and the easy way to write it keys the timer on the result object, so it restarts on every response and a three second poll on a slow endpoint quietly becomes five. useQuery in React and Vue and injectQuery in Angular now take refetchInterval (number or false, as in TanStack Query) and refetchIntervalInBackground. The timer is keyed on the query and the two options, never on the result. Vue takes refs or getters and Angular signals or functions, the same way they take live and staleTime. All three run on the core's poll, which now holds its cadence too. It used to sleep the whole interval after each response, so the period was interval plus latency. It now waits the interval less the time the request took, starts the next request straight away when a response is slower than the interval, and never overlaps two. An interval that isn't a positive finite number polls nothing, where 0 used to spin. The freshness entry goes from 378 B to 451 B against its 500 B budget. Closes #100 --- .../docs/web-client/not-yet-shipped.mdx | 2 +- docs/content/docs/web-client/runtime.mdx | 16 +- .../__tests__/injectQuery.poll.test.ts | 109 ++++++++++++ packages/client-angular/src/injectQuery.ts | 82 +++++++++ packages/client-core/README.md | 3 +- .../client-core/__tests__/freshness.test.ts | 77 +++++++++ packages/client-core/src/freshness.ts | 38 ++++- .../__tests__/useQuery.poll.test.tsx | 159 ++++++++++++++++++ packages/client-react/src/useQuery.ts | 35 ++++ .../__tests__/useQuery.poll.test.ts | 84 +++++++++ packages/client-vue/src/useQuery.ts | 36 ++++ 11 files changed, 632 insertions(+), 9 deletions(-) create mode 100644 packages/client-angular/__tests__/injectQuery.poll.test.ts create mode 100644 packages/client-react/__tests__/useQuery.poll.test.tsx create mode 100644 packages/client-vue/__tests__/useQuery.poll.test.ts diff --git a/docs/content/docs/web-client/not-yet-shipped.mdx b/docs/content/docs/web-client/not-yet-shipped.mdx index 966ff3347..c23e25cf8 100644 --- a/docs/content/docs/web-client/not-yet-shipped.mdx +++ b/docs/content/docs/web-client/not-yet-shipped.mdx @@ -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 diff --git a/docs/content/docs/web-client/runtime.mdx b/docs/content/docs/web-client/runtime.mdx index 4abc74998..e2f25b822 100644 --- a/docs/content/docs/web-client/runtime.mdx +++ b/docs/content/docs/web-client/runtime.mdx @@ -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. @@ -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 diff --git a/packages/client-angular/__tests__/injectQuery.poll.test.ts b/packages/client-angular/__tests__/injectQuery.poll.test.ts new file mode 100644 index 000000000..11a100180 --- /dev/null +++ b/packages/client-angular/__tests__/injectQuery.poll.test.ts @@ -0,0 +1,109 @@ +import { + ChangeDetectionStrategy, + Component, + EnvironmentInjector, + createEnvironmentInjector, + signal, +} from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { injectQuery } from '../src'; +import { harness, useOrderList } from './harness'; +import type { Harness, Order } from './harness'; +import { configure, render, settle } from './harness-angular'; + +/** A transport whose every response takes `latency` ms of fake time. */ +function slowHarness(latency: number): Harness { + let total = 0; + + return harness(async () => { + await new Promise((resolve) => setTimeout(resolve, latency)); + total += 1; + + return [{ id: 1, total }]; + }); +} + +@Component({ + selector: 'app-polled', + changeDetection: ChangeDetectionStrategy.OnPush, + template: '{{ orders.data()?.[0]?.total ?? "-" }}', +}) +class Polled { + readonly interval = signal(false); + readonly orders = injectQuery(useOrderList, undefined, { + refetchInterval: () => this.interval(), + }); +} + +describe('injectQuery refetchInterval', () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it('polls on the interval, and stops when its injector is destroyed', async () => { + const fx = slowHarness(0); + + configure(fx); + + const injector = createEnvironmentInjector([], TestBed.inject(EnvironmentInjector)); + + injectQuery(useOrderList, undefined, { injector, refetchInterval: 1_000 }); + + await vi.advanceTimersByTimeAsync(0); + expect(fx.transport.calls).toHaveLength(1); + + await vi.advanceTimersByTimeAsync(3_000); + expect(fx.transport.calls).toHaveLength(4); + + injector.destroy(); + + await vi.advanceTimersByTimeAsync(3_000); + expect(fx.transport.calls).toHaveLength(4); + }); + + // A timer restarted by each response fires at interval + latency instead + // (xraph/forge#100). + it('holds its cadence on a slow endpoint', async () => { + const fx = slowHarness(400); + + configure(fx); + + const injector = createEnvironmentInjector([], TestBed.inject(EnvironmentInjector)); + + injectQuery(useOrderList, undefined, { injector, refetchInterval: 1_000 }); + + await vi.advanceTimersByTimeAsync(3_000); + expect(fx.transport.calls).toHaveLength(4); + + injector.destroy(); + }); + + it('reads false as off, and follows a signal', async () => { + const fx = slowHarness(0); + + configure(fx); + + const fixture = render(Polled); + + await settle(fixture); + await vi.advanceTimersByTimeAsync(5_000); + expect(fx.transport.calls).toHaveLength(1); + + fixture.componentInstance.interval.set(1_000); + await settle(fixture); + await vi.advanceTimersByTimeAsync(2_000); + expect(fx.transport.calls).toHaveLength(3); + + fixture.componentInstance.interval.set(false); + await settle(fixture); + await vi.advanceTimersByTimeAsync(5_000); + expect(fx.transport.calls).toHaveLength(3); + + fixture.destroy(); + }); +}); diff --git a/packages/client-angular/src/injectQuery.ts b/packages/client-angular/src/injectQuery.ts index 170acbdd3..63542fd07 100644 --- a/packages/client-angular/src/injectQuery.ts +++ b/packages/client-angular/src/injectQuery.ts @@ -1,5 +1,6 @@ import { DestroyRef, computed, effect, inject, runInInjectionContext, signal, untracked } from '@angular/core'; import type { Injector, Signal } from '@angular/core'; +import { poll } from '@forge-go/client-core'; import type { QueryBinding, QueryCache, @@ -61,6 +62,22 @@ export interface InjectQueryOptions { * that computes the value keeps whichever one it first rendered with. */ readonly staleTime?: number | (() => number | undefined); + /** + * Refetch this query every so many milliseconds until it is destroyed. + * `false`, `0` or absent polls nothing, so + * `refetchInterval: () => (executing() ? 3000 : false)` reads the way it does + * in TanStack Query. A value, or a function such as a signal, re-read when it + * changes. + * + * The cadence holds: each request starts one interval after the previous one + * started, and a response slower than the interval is followed by the next + * request rather than overlapped by it. Changing the value, or the query's + * arguments, restarts the timer; a new response does not. Paused while the + * tab is hidden unless `refetchIntervalInBackground` is set. + */ + readonly refetchInterval?: number | false | (() => number | false | undefined); + /** Keep polling while the tab is hidden. Defaults to false. */ + readonly refetchIntervalInBackground?: boolean | (() => boolean | undefined); } /** What `injectQuery` returns: the query's state as signals, plus the controls. */ @@ -223,6 +240,38 @@ function bind( attachLive(); + // Polling. Restarted by a change of query, interval or background flag, and + // by nothing else: a timer that restarts on every response drifts by the + // response time (xraph/forge#100). + const intervalOf = (): number | false | undefined => { + const declared = options?.refetchInterval; + + return typeof declared === 'function' ? declared() : declared; + }; + + const inBackgroundOf = (): boolean => { + const declared = options?.refetchIntervalInBackground; + + return (typeof declared === 'function' ? declared() : declared) === true; + }; + + let pollRelease: (() => void) | undefined; + + function attachPoll(): void { + const interval = intervalOf(); + + if (typeof interval === 'number') { + pollRelease = poll(client, op.meta, resolve(args), interval, { whileHidden: inBackgroundOf() }); + } + } + + function detachPoll(): void { + pollRelease?.(); + pollRelease = undefined; + } + + attachPoll(); + let stopWatching: (() => void) | undefined; // Reactive arguments, a reactive staleTime, or both. Either one changing has @@ -285,12 +334,42 @@ function bind( // channel both keys share is never actually closed. detachLive(); attachLive(); + + detachPoll(); + attachPoll(); }); }); stopWatching = () => watcher.destroy(); } + let stopPollWatch: (() => void) | undefined; + + if ( + typeof options?.refetchInterval === 'function' || + typeof options?.refetchIntervalInBackground === 'function' + ) { + let interval = intervalOf(); + let inBackground = inBackgroundOf(); + + const watcher = effect(() => { + const nextInterval = intervalOf(); + const nextInBackground = inBackgroundOf(); + + if (nextInterval === interval && nextInBackground === inBackground) return; + + interval = nextInterval; + inBackground = nextInBackground; + + untracked(() => { + detachPoll(); + attachPoll(); + }); + }); + + stopPollWatch = () => watcher.destroy(); + } + let stopLive: (() => void) | undefined; if (typeof declared === 'function') { @@ -348,8 +427,11 @@ function bind( stopWatching = undefined; stopLive?.(); stopLive = undefined; + stopPollWatch?.(); + stopPollWatch = undefined; detach(); detachLive(); + detachPoll(); } /** diff --git a/packages/client-core/README.md b/packages/client-core/README.md index 23fced64c..f7ea0e780 100644 --- a/packages/client-core/README.md +++ b/packages/client-core/README.md @@ -1040,7 +1040,8 @@ on a forty second cycle. Freshness landed on its own line. `revalidateOnFocus`, `revalidateOnReconnect` and `poll` filter to 378 B against 500 B, so an application that never imports -them does not carry them. The parts that could not stay out of the shared set +them does not carry them. Holding `poll` to its cadence, so a slow endpoint does +not stretch the period, took that to 451 B. The parts that could not stay out of the shared set moved two budgets while the feature was landing: `query engine and REST transport` from 8.9 kB to 9.32 kB in 428da9ed, and `core, REST only` from 9.2 kB to 9417 B in feb56ada. diff --git a/packages/client-core/__tests__/freshness.test.ts b/packages/client-core/__tests__/freshness.test.ts index ab1c33242..4e3f63b53 100644 --- a/packages/client-core/__tests__/freshness.test.ts +++ b/packages/client-core/__tests__/freshness.test.ts @@ -419,6 +419,83 @@ describe('poll', () => { expect(transport.calls).toHaveLength(3); }); + it('holds its cadence when the endpoint is slow', async () => { + const timers = manualClock(); + // Each response takes 400ms on the same clock the poll measures. + const transport = fakeTransport(async () => { + await timers.sleep(400); + + return [{ id: 7, total: 99 }]; + }); + const queries = new QueryCache({ transport, entities: schema }); + + const stop = poll(queries, orderList, undefined, 1_000, { + sleep: timers.sleep, + now: timers.now, + whileHidden: true, + }); + + await timers.advance(1_000); + expect(transport.calls).toHaveLength(1); + + // The first response lands at 1400. The next request is due at 2000, + // one interval after the first STARTED -- not at 2400, one interval after + // it finished, which is the drift xraph/forge#100 describes. + await timers.advance(400); + await timers.advance(599); + expect(transport.calls).toHaveLength(1); + + await timers.advance(1); + expect(transport.calls).toHaveLength(2); + + stop(); + }); + + it('never overlaps a response slower than the interval', async () => { + const timers = manualClock(); + const transport = fakeTransport(async () => { + await timers.sleep(1_500); + + return [{ id: 7, total: 99 }]; + }); + const queries = new QueryCache({ transport, entities: schema }); + + const stop = poll(queries, orderList, undefined, 1_000, { + sleep: timers.sleep, + now: timers.now, + whileHidden: true, + }); + + await timers.advance(1_000); + expect(transport.calls).toHaveLength(1); + + // Two intervals pass while the first request is still running: no second + // request starts underneath it. + await timers.advance(1_000); + expect(transport.calls).toHaveLength(1); + + // It lands at 2500 and the next goes out straight away. + await timers.advance(500); + await timers.advance(0); + expect(transport.calls).toHaveLength(2); + + stop(); + }); + + it('polls nothing for an interval that is not a positive number', async () => { + const { queries, transport } = cache(); + const timers = manualClock(); + + for (const interval of [0, -1, Number.NaN, Number.POSITIVE_INFINITY]) { + const stop = poll(queries, orderList, undefined, interval, { sleep: timers.sleep }); + + expect(timers.pending()).toBe(0); + stop(); + } + + expect(transport.calls).toHaveLength(0); + }); + it('keeps polling after a request fails', async () => { let call = 0; const transport = fakeTransport(() => { diff --git a/packages/client-core/src/freshness.ts b/packages/client-core/src/freshness.ts index 03d5e9528..1c02ec947 100644 --- a/packages/client-core/src/freshness.ts +++ b/packages/client-core/src/freshness.ts @@ -1,8 +1,8 @@ import type { QueryCache } from './cache.js'; import type { EventTargetLike } from './stream.js'; import type { TagContext } from './tags.js'; -import { realSleep } from './transport.js'; -import type { OperationMeta, Sleep } from './transport.js'; +import { realClock, realSleep } from './transport.js'; +import type { Clock, OperationMeta, Sleep } from './transport.js'; /** * Ambient revalidation: the browser telling the cache that time has passed in @@ -128,6 +128,11 @@ export function revalidateOnReconnect( export interface PollOptions { /** How a delay is taken. Defaults to `realSleep`. Tests pass a manual clock. */ readonly sleep?: Sleep; + /** + * Reads the clock the cadence is measured on. Defaults to `realClock`. A test + * passing a manual clock's `sleep` passes its `now` too. + */ + readonly now?: Clock; /** Keep polling while the document is hidden. Defaults to false. */ readonly whileHidden?: boolean; } @@ -137,12 +142,22 @@ export interface PollOptions { * * A loop over an injected `Sleep` rather than `setInterval`, which is the shape * `RestTransport` already uses for retry backoff and the reason a polling test - * can run on a manual clock instead of on wall time. It also cannot stack: - * the next delay begins after the previous request settled, so a slow endpoint - * spreads its polls out rather than queueing them. + * can run on a manual clock instead of on wall time. + * + * **It holds its cadence and cannot stack.** Each request starts one interval + * after the previous one *started*, not after it finished: the wait is the + * interval less however long the request took. Sleeping the whole interval + * after each response is the obvious loop and the wrong one, because it makes + * the period `interval + latency` -- a three second poll on a two second + * endpoint quietly becomes a five second one. A response slower than the + * interval is followed by the next request straight away, never overlapped by + * it, so a slow endpoint gets back-to-back requests and not a queue. * * Paused while the document is hidden, because polling a background tab spends * requests on a screen nobody is reading. + * + * An interval that is not a positive finite number polls nothing. Zero would + * otherwise be a request loop with no delay at all. */ export function poll( cache: QueryCache, @@ -151,21 +166,30 @@ export function poll( intervalMs: number, options: PollOptions = {}, ): () => void { + if (!(intervalMs > 0) || !Number.isFinite(intervalMs)) return () => undefined; + const sleep = options.sleep ?? realSleep; + const now = options.now ?? realClock; let stopped = false; void (async () => { + let wait = intervalMs; + while (!stopped) { - await sleep(intervalMs); + await sleep(wait); if (stopped) break; + wait = intervalMs; + if (options.whileHidden !== true) { const doc = (globalThis as { document?: VisibilityLike }).document; if (doc?.visibilityState === 'hidden') continue; } + const started = now(); + try { await cache.refetch(meta, args); } catch { @@ -173,6 +197,8 @@ export function poll( // its own `onError`, and a poll that dies on one failed request is a // poll that silently stops refreshing the screen. } + + wait = Math.max(0, intervalMs - (now() - started)); } })(); diff --git a/packages/client-react/__tests__/useQuery.poll.test.tsx b/packages/client-react/__tests__/useQuery.poll.test.tsx new file mode 100644 index 000000000..ca483c9cb --- /dev/null +++ b/packages/client-react/__tests__/useQuery.poll.test.tsx @@ -0,0 +1,159 @@ +import { useState } from 'react'; +import { act, render } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { ClientProvider, useQuery } from '../src'; +import { harness, useOrderList } from './harness'; +import type { Harness, Order } from './harness'; + +/** Move the fake clock, letting every request and render it releases settle. */ +async function advance(ms: number): Promise { + await act(async () => { + await vi.advanceTimersByTimeAsync(ms); + }); +} + +/** A transport whose every response takes `latency` ms of fake time. */ +function slowHarness(latency: number): Harness { + let total = 0; + + return harness(async () => { + await new Promise((resolve) => setTimeout(resolve, latency)); + total += 1; + + return [{ id: 1, total }]; + }); +} + +function setVisibility(state: 'visible' | 'hidden'): void { + Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => state }); +} + +describe('useQuery refetchInterval', () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.useRealTimers(); + setVisibility('visible'); + }); + + it('polls on the interval, and stops on unmount', async () => { + const h = slowHarness(0); + + function List() { + useQuery(useOrderList, undefined, { refetchInterval: 1_000 }); + + return null; + } + + const view = render( + + + , + ); + + await advance(0); + expect(h.transport.calls).toHaveLength(1); + + await advance(3_000); + expect(h.transport.calls).toHaveLength(4); + + view.unmount(); + + await advance(3_000); + expect(h.transport.calls).toHaveLength(4); + }); + + // The bug a hand-written hook keeps shipping: a timer keyed on the result + // object restarts on every response, so a three second poll on a slow + // endpoint becomes interval + latency (xraph/forge#100). + it('holds its cadence while each response re-renders the component', async () => { + const h = slowHarness(400); + let renders = 0; + + function List() { + renders++; + useQuery(useOrderList, undefined, { refetchInterval: 1_000 }); + + return null; + } + + render( + + + , + ); + + // Mount fetch at 0, polls at 1000, 2000 and 3000. A timer restarted by + // each response would fire at 1400 and 2800 instead. + await advance(3_000); + expect(h.transport.calls).toHaveLength(4); + expect(renders).toBeGreaterThan(4); + }); + + it('reads false as off, and starts and stops as the value changes', async () => { + const h = slowHarness(0); + let setInterval!: (value: number | false) => void; + + function List() { + const [interval, set] = useState(false); + setInterval = set; + useQuery(useOrderList, undefined, { refetchInterval: interval }); + + return null; + } + + render( + + + , + ); + + await advance(5_000); + expect(h.transport.calls).toHaveLength(1); + + await act(async () => { + setInterval(1_000); + }); + await advance(2_000); + expect(h.transport.calls).toHaveLength(3); + + await act(async () => { + setInterval(false); + }); + await advance(5_000); + expect(h.transport.calls).toHaveLength(3); + }); + + it('pauses while the tab is hidden unless asked to keep going', async () => { + setVisibility('hidden'); + + const paused = slowHarness(0); + const background = slowHarness(0); + + function List({ inBackground }: { inBackground: boolean }) { + useQuery(useOrderList, undefined, { + refetchInterval: 1_000, + refetchIntervalInBackground: inBackground, + }); + + return null; + } + + render( + <> + + + + + + + , + ); + + await advance(3_000); + expect(paused.transport.calls).toHaveLength(1); + expect(background.transport.calls).toHaveLength(4); + }); +}); diff --git a/packages/client-react/src/useQuery.ts b/packages/client-react/src/useQuery.ts index 4fde24a57..cc36e79ea 100644 --- a/packages/client-react/src/useQuery.ts +++ b/packages/client-react/src/useQuery.ts @@ -1,4 +1,5 @@ import { useCallback, useEffect, useMemo, useSyncExternalStore } from 'react'; +import { poll } from '@forge-go/client-core'; import type { QueryBinding, QueryCache, QueryState, TagContext } from '@forge-go/client-core'; import { useClient } from './context.js'; @@ -24,6 +25,22 @@ export interface UseQueryOptions { readonly live?: boolean; /** Milliseconds this call considers the result fresh for. See the core's `QueryOptions`. */ readonly staleTime?: number; + /** + * Refetch this query every so many milliseconds while the component is + * mounted. `false`, `0` or absent polls nothing, so + * `refetchInterval: isExecuting ? 3000 : false` reads the way it does in + * TanStack Query. + * + * The cadence holds: each request starts one interval after the previous one + * started, and a response slower than the interval is followed by the next + * request rather than overlapped by it. Changing the value restarts the + * timer; a new response does not. Paused while the tab is hidden unless + * `refetchIntervalInBackground` is set. Reach for `live` instead where the + * operation has a channel: a push costs nothing between changes. + */ + readonly refetchInterval?: number | false; + /** Keep polling while the tab is hidden. Defaults to false. */ + readonly refetchIntervalInBackground?: boolean; } /** What `useQuery` returns: the query's state, plus the manual refetch. */ @@ -180,6 +197,24 @@ export function useQuery( // eslint-disable-next-line react-hooks/exhaustive-deps -- `key` is `args`'s identity }, [client, op, key, options?.live]); + /** + * Polling, keyed the way the live effect above is: on the query's identity + * and the two options, never on the result. A dependency on `state` or on + * `refetch`'s result object would clear and restart the timer on every + * response, which is the bug every hand-written polling hook ends up with + * (xraph/forge#100). `args` is read from the closure for the reason the live + * effect gives. + */ + const refetchInterval = options?.refetchInterval; + const inBackground = options?.refetchIntervalInBackground === true; + + useEffect(() => { + if (typeof refetchInterval !== 'number') return; + + return poll(client, op.meta, args, refetchInterval, { whileHidden: inBackground }); + // eslint-disable-next-line react-hooks/exhaustive-deps -- `key` is `args`'s identity + }, [client, op, key, refetchInterval, inBackground]); + const refetch = useCallback(() => handle.refetch(), [handle]); // Memoised on the snapshot, so the returned object changes identity exactly diff --git a/packages/client-vue/__tests__/useQuery.poll.test.ts b/packages/client-vue/__tests__/useQuery.poll.test.ts new file mode 100644 index 000000000..4d99d1104 --- /dev/null +++ b/packages/client-vue/__tests__/useQuery.poll.test.ts @@ -0,0 +1,84 @@ +import { effectScope, nextTick, ref } from 'vue'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { useQuery } from '../src'; +import { harness, useOrderList } from './harness'; +import type { Harness, Order } from './harness'; + +/** A transport whose every response takes `latency` ms of fake time. */ +function slowHarness(latency: number): Harness { + let total = 0; + + return harness(async () => { + await new Promise((resolve) => setTimeout(resolve, latency)); + total += 1; + + return [{ id: 1, total }]; + }); +} + +describe('useQuery refetchInterval', () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it('polls on the interval, and stops when its scope is disposed', async () => { + const fx = slowHarness(0); + const scope = effectScope(); + + scope.run(() => useQuery(useOrderList, undefined, { client: fx.cache, refetchInterval: 1_000 })); + + await vi.advanceTimersByTimeAsync(0); + expect(fx.transport.calls).toHaveLength(1); + + await vi.advanceTimersByTimeAsync(3_000); + expect(fx.transport.calls).toHaveLength(4); + + scope.stop(); + + await vi.advanceTimersByTimeAsync(3_000); + expect(fx.transport.calls).toHaveLength(4); + }); + + // A timer restarted by each response fires at interval + latency instead + // (xraph/forge#100). + it('holds its cadence on a slow endpoint', async () => { + const fx = slowHarness(400); + const scope = effectScope(); + + scope.run(() => useQuery(useOrderList, undefined, { client: fx.cache, refetchInterval: 1_000 })); + + await vi.advanceTimersByTimeAsync(3_000); + expect(fx.transport.calls).toHaveLength(4); + + scope.stop(); + }); + + it('reads false as off, and follows a reactive value', async () => { + const fx = slowHarness(0); + const interval = ref(false); + const scope = effectScope(); + + scope.run(() => + useQuery(useOrderList, undefined, { client: fx.cache, refetchInterval: interval }), + ); + + await vi.advanceTimersByTimeAsync(5_000); + expect(fx.transport.calls).toHaveLength(1); + + interval.value = 1_000; + await nextTick(); + await vi.advanceTimersByTimeAsync(2_000); + expect(fx.transport.calls).toHaveLength(3); + + interval.value = false; + await nextTick(); + await vi.advanceTimersByTimeAsync(5_000); + expect(fx.transport.calls).toHaveLength(3); + + scope.stop(); + }); +}); diff --git a/packages/client-vue/src/useQuery.ts b/packages/client-vue/src/useQuery.ts index 69660e40b..b46a95754 100644 --- a/packages/client-vue/src/useQuery.ts +++ b/packages/client-vue/src/useQuery.ts @@ -1,5 +1,6 @@ import { computed, onScopeDispose, shallowRef, toValue, watch } from 'vue'; import type { ComputedRef, MaybeRefOrGetter, ShallowRef } from 'vue'; +import { poll } from '@forge-go/client-core'; import type { QueryBinding, QueryCache, @@ -44,6 +45,20 @@ export interface UseQueryOptions { * Read at construction and again whenever it changes. */ readonly staleTime?: MaybeRefOrGetter; + /** + * Refetch this query every so many milliseconds while its scope is alive. + * `false`, `0` or absent polls nothing, so `() => (executing.value ? 3000 : false)` + * reads the way it does in TanStack Query. + * + * The cadence holds: each request starts one interval after the previous one + * started, and a response slower than the interval is followed by the next + * request rather than overlapped by it. Changing the value, or the query's + * arguments, restarts the timer; a new response does not. Paused while the + * tab is hidden unless `refetchIntervalInBackground` is set. + */ + readonly refetchInterval?: MaybeRefOrGetter; + /** Keep polling while the tab is hidden. Defaults to false. */ + readonly refetchIntervalInBackground?: MaybeRefOrGetter; } /** What `useQuery` returns: the query's state as refs, plus the controls. */ @@ -238,9 +253,30 @@ export function useQuery( attach(); }); + /** + * Polling, keyed on the query's identity and the two options and never on + * `state`: a timer that restarts on every response drifts by the response + * time (xraph/forge#100). `immediate` so the first value starts it, and the + * watcher's cleanup stops the previous loop before the next one begins. + */ + const stopPolling = watch( + [ + key, + computed(() => toValue(options?.refetchInterval)), + computed(() => toValue(options?.refetchIntervalInBackground) === true), + ], + ([, interval, inBackground], _previous, onCleanup) => { + if (typeof interval !== 'number') return; + + onCleanup(poll(client, op.meta, toValue(args), interval, { whileHidden: inBackground })); + }, + { immediate: true }, + ); + function dispose(): void { stop(); stopLive?.(); + stopPolling(); detach(); detachLive(); }