Repository navigation
Feat/graphql subscriptions - #8788
ZaninAndrea wants to merge 8 commits into
Conversation
…cription-request Introduce the graphql-subscription-request item type across the type/validation layer: bruno-schema-types (GraphqlSubscriptionRequest, ItemType, ItemSettings), bruno-schema (Yup validation, noUnknown/strict), and the REQUEST_TYPES / PRESET_REQUEST_TYPES constants in bruno-app and bruno-electron.
… support Add graphql-subscription-request support to both persistence formats in lockstep: a new graphql:subscription / graphql:subscription:connection-params grammar pair in bruno-lang v2 (reusing the existing body:graphql blocks for query/variables), the matching bru/index.ts request-shape branch, a local OpenCollection-shaped type shim plus parse/stringify pair for the yml layer (since @opencollection/types has no subscription request kind yet), and the bruno-converters/bruno-cli/bruno-electron type-map wiring so the request round-trips through both formats and through OpenCollection import/export. Co-Authored-By: Claude Sonnet 5 <[email protected]>
Implement the graphql-transport-ws subprotocol directly over `ws` in bruno-requests: a pure protocol module (message encode/decode, close-code descriptions) and a GraphQLSubscriptionClient state machine that owns one socket per operation. Covers the full connection lifecycle — connection_init/ ack handshake with a timeout, protocol-violation guards, terminal-vs-partial error handling (top-level `error` vs `next.payload.errors`), server-complete vs user-unsubscribe (both leave the socket open), frame batching with a buffer cap and per-frame char cap, and eager connection eviction on disconnect/collection-close/app-quit mirroring WsClient's convention. Co-Authored-By: Claude Sonnet 5 <[email protected]>
Add graphql-subscription-event-handlers.js: prepareGraphQLSubscriptionRequest
(tree-path header/auth merge, OAuth2 grant support, api-key-in-query, dropping
any sec-websocket-protocol header the client itself owns, and — critically —
parsing query/variables/connectionParams only after interpolation, mirroring
the existing GraphQL variables guard) plus the renderer:gql-sub:{connect,
subscribe,unsubscribe,disconnect,connection-status,get-active-connections}
handlers and the main:gql-sub:* push channels via GraphQLSubscriptionClient.
Also fixes two adjacent WS bugs while touching this code:
- ws-event-handlers.js exported the `wsClient` binding by value, capturing
`undefined` at require-time — closeForCollection() was silently a no-op.
Both transports now export a getter, and ipc/collection.js's two
closeForCollection call sites use it (and now also tear down subscription
connections on collection close/removal).
- WS never registered app-lifecycle teardown; both transports now clear their
connections on window-all-closed and before-quit (the new client already
needed this — WS gets it here too for consistency).
Also excludes graphql-subscription-request (and, for the runner loop, the
already-unhandled ws-request) from bru.runRequest and the folder/collection
runner loop, mirroring the existing WS/gRPC skip.
Co-Authored-By: Claude Sonnet 5 <[email protected]>
Mirror the ws-request Redux/renderer wiring for graphql-subscription-request: - collections slice: initiatedGraphqlSubscriptionResponse, and reducers runGraphqlSubscriptionRequestEvent / graphqlSubscriptionResponseReceived (batched frames/operation-state variants of the ws reducers — raw wire frames feed WsResponsePane's Messages tab exactly like ws:message does, tagged incoming/outgoing by direction; operation-state drives isError/ statusText without duplicating frame content). - utils/network/graphql-subscription-event-listeners.js: useGraphqlSubscriptionEventListeners, mounted in pages/Bruno/index.js alongside the ws/gRPC listener hooks. - utils/network/index.js: connect/subscribe/unsubscribe/disconnect/status wrappers around the renderer:gql-sub:* IPC calls, plus the combined sendGraphqlSubscriptionRequest used by sendRequest. - collections/actions.js: sendRequest's type-branch, and newGraphqlSubscriptionRequest mirroring newWsRequest. - tabs.js / utils/collections#getDefaultRequestPaneTab: default to the query tab (reusing the graphql-request default) rather than the ws body tab. Local graphql-transport-ws close-code phrase map is duplicated here rather than imported from @usebruno/requests, since bruno-app's dependency boundary excludes bruno-requests. Co-Authored-By: Claude Sonnet 5 <[email protected]>
…ntry points Extend GraphQLRequestPane (rather than forking it) to derive its tab set from item.type: graphql-subscription-request gets Query/Headers/Auth/Connection/ Settings/Docs (no Script/Vars/Assert/Tests, mirroring WSRequestPane's reasoning that long-lived types never execute them), reusing QueryEditor, QueryBuilder, GraphQLVariables, WSAuth/WSAuthMode/AUTH_MODES_WS, WSSettingsPane, RequestHeaders and Documentation as-is. New thin pieces: ConnectionParams (a JSON CodeEditor mirroring GraphQLVariables) and GraphQLSubscriptionQueryUrl (Subscribe/ Unsubscribe, connection state read from Redux rather than WsQueryUrl's polling interval). WSResponsePane is reused entirely for the response side. Schema introspection runs over the subscription socket itself: a new renderer:gql-sub:introspect handler opens a short-lived throwaway GraphQLSubscriptionClient, subscribes with getIntrospectionQuery(), and resolves on the first `next`/`error` — useGraphqlSchema now takes the fetch function as a parameter so both GraphQL types share its cache/build/validate logic unchanged. RequestTabPanel routes the new type to all of the above plus URL validation and the DocExplorer mount gate; RequestMethod/RunConfigurationPanel/Timeline get a "sub" badge; Sidebar/NewRequest, CreateUntitledRequest, emptyStateRequest.js and CollectionSettings/Presets get the entry points; RequestTab disconnects the subscription on tab close, mirroring closeWsConnection. Co-Authored-By: Claude Sonnet 5 <[email protected]>
Extract the GraphQL schema into graphql/schema.js (createGraphQLSchema) so Yoga (HTTP) and the new subscriptions server share one schema, and add a Subscription root covering every client-side case: counter (infinite), countdown (finite, server-completes), ticker (object payload), failing (mid-stream throw — graphql-ws's reference server closes with 4500 for this, distinct from a validation error against a malformed query which correctly sends a per-operation `error` message and leaves the socket open), immediate (completes with zero next frames), fieldErrors (next carrying payload.errors, non-fatal), and flood (no artificial delay, to exercise the client's frame batching under load). graphql/subscriptions.js wires graphql-ws@5's useServer over a noServer:true WebSocketServer, driving ack-delay and init-rejection off connectionParams so one endpoint covers every lifecycle case reachable from a real Bruno request. It returns a plain handleUpgrade function rather than self-registering on 'upgrade' — src/index.js now owns a single upgrade dispatcher parsed by pathname (not startsWith, since wsRouter matches the raw URL including the query string) that routes /api/graphql to it and everything else to wsRouter, so the two upgrade handlers never race the same event. Manually verified end-to-end against the running server: ack/subscribe/next/ complete, fieldErrors staying non-fatal, the failing/immediate/flood edge cases, ackDelayMs and rejectInit connectionParams, introspection over the socket, and that the existing HTTP GraphQL and /ws routes are unaffected. Co-Authored-By: Claude Sonnet 5 <[email protected]>
…oss item-type whitelists Several hardcoded item-type whitelists across bruno-app and bruno-electron did not include the new graphql-subscription-request type, most critically isItemARequest (utils/tabs, utils/collections) which silently dropped subscription items from the sidebar tree, and transformRequestToSaveToFilesystem which would fail Yup validation or drop connectionParams on save.
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (72)
WalkthroughGraphQL subscription requests are introduced across Bruno’s schemas, file formats, OpenCollection converters, WebSocket transport, Electron IPC, Redux state, test fixtures, and application UI. ChangesGraphQL subscription support
Estimated code review effort: 5 (Critical) | ~120 minutes Possibly related PRs
Suggested labels: Suggested reviewers: Poem
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Pull request overview
Adds end-to-end support for GraphQL Subscription requests across Bruno’s request model, persistence formats (BRU/YML/OpenCollection), Electron IPC/network layer, app UI/state handling, and request/transport implementation (graphql-transport-ws), with accompanying tests and a testbench server fixture.
Changes:
- Introduces
graphql-subscription-requestas a first-class request/item type (schema + TS types + UI/tab handling). - Implements a
GraphQLSubscriptionClientandgraphql-transport-wsprotocol encoder/decoder in@usebruno/requests, plus Electron IPC handlers and app-side event listeners/state reducers. - Extends BRU/YML/OpenCollection import/export and bruno-lang v2 parsing/stringifying to persist subscription details (url/auth/body/connectionParams/settings/docs).
Reviewed changes
Copilot reviewed 72 out of 73 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| packages/bruno-tests/src/index.js | Testbench server now builds shared schema and routes /api/graphql upgrades to graphql-ws subscriptions handler. |
| packages/bruno-tests/src/graphql/subscriptions.js | Adds graphql-ws reference server upgrade handler fixture for subscription testing. |
| packages/bruno-tests/src/graphql/schema.js | Centralizes GraphQL schema with subscription fields and async generator fixtures. |
| packages/bruno-tests/src/graphql/index.js | Reuses prebuilt schema when setting up graphql-yoga endpoint. |
| packages/bruno-tests/package.json | Adds graphql-ws dependency for test fixtures. |
| packages/bruno-schema/src/collections/itemSchema.spec.js | Adds validation test for missing request on graphql-subscription-request. |
| packages/bruno-schema/src/collections/index.js | Adds Yup schemas for graphql-subscription-request and settings; wires into item schema. |
| packages/bruno-schema-types/src/requests/index.ts | Exports new GraphqlSubscriptionRequest types and extends Request union. |
| packages/bruno-schema-types/src/requests/graphql-subscription.ts | Adds TS interfaces for GraphQL subscription request shape. |
| packages/bruno-schema-types/src/collection/item.ts | Extends item type/settings unions for subscription requests. |
| packages/bruno-requests/src/index.ts | Exposes subscription client + protocol helpers from requests package. |
| packages/bruno-requests/src/graphql/graphql-transport-ws-protocol.spec.js | Tests encode/decode helpers for graphql-transport-ws protocol. |
| packages/bruno-requests/src/graphql/graphql-transport-ws-protocol.js | Adds pure protocol vocabulary + frame encode/decode helpers. |
| packages/bruno-requests/src/graphql/graphql-subscription-client.spec.js | Adds unit tests for client handshake, lifecycle, batching, and IPC payload contract. |
| packages/bruno-requests/src/graphql/graphql-subscription-client.js | Implements GraphQL subscription WebSocket client with buffering/batching and close semantics. |
| packages/bruno-lang/v2/tests/jsonToBru.spec.js | Adds BRU stringify coverage for graphql subscription blocks and connection params. |
| packages/bruno-lang/v2/tests/bruToJson.spec.js | Adds BRU parse coverage for graphql subscription and connection-params blocks. |
| packages/bruno-lang/v2/src/jsonToBru.js | Adds BRU emission for graphql:subscription and graphql:subscription:connection-params. |
| packages/bruno-lang/v2/src/bruToJson.js | Extends grammar/semantics to parse graphql subscription blocks and connection params. |
| packages/bruno-filestore/src/formats/yml/utils.ts | Adds graphqlSubscription to YAML block key ordering. |
| packages/bruno-filestore/src/formats/yml/types/graphql-subscription.ts | Adds local OpenCollection-compatible types for graphql subscriptions. |
| packages/bruno-filestore/src/formats/yml/stringifyItem.ts | Routes graphql-subscription-request to new YAML stringifier. |
| packages/bruno-filestore/src/formats/yml/stringifyItem.spec.ts | Adds YAML round-trip tests for graphql-subscription items. |
| packages/bruno-filestore/src/formats/yml/parseItem.ts | Adds YAML parsing route for graphql-subscription OpenCollection items. |
| packages/bruno-filestore/src/formats/yml/parseItem.spec.ts | Adds YAML parsing tests for graphql-subscription (incl. defaults). |
| packages/bruno-filestore/src/formats/yml/items/stringifyGraphQLSubscriptionRequest.ts | Implements YAML stringify for graphql-subscription requests. |
| packages/bruno-filestore/src/formats/yml/items/parseGraphQLSubscriptionRequest.ts | Implements YAML parse into Bruno graphql-subscription request/item shape. |
| packages/bruno-filestore/src/formats/bru/tests/graphql-subscription-request.spec.js | Adds BRU format parse/stringify tests for graphql-subscription-request. |
| packages/bruno-filestore/src/formats/bru/index.ts | Extends BRU parse/stringify mapping for graphql-subscription-request. |
| packages/bruno-electron/tests/network/prepare-graphql-subscription-request.spec.js | Adds tests for request preparation, interpolation, parsing, and header handling. |
| packages/bruno-electron/tests/network/interpolate-vars.spec.js | Adds interpolation coverage for subscription query/vars/connectionParams. |
| packages/bruno-electron/src/utils/constants.js | Extends request type allowlist with graphql-subscription-request. |
| packages/bruno-electron/src/utils/collection.js | Adds graphql-subscription mapping and various const/loop refactors while integrating new type. |
| packages/bruno-electron/src/ipc/network/ws-event-handlers.js | Adds teardown hooks; exports a getter for wsClient to avoid capturing undefined. |
| packages/bruno-electron/src/ipc/network/interpolate-vars.js | Adds interpolation for request.data.connectionParams in GraphQL-mode requests. |
| packages/bruno-electron/src/ipc/network/index.js | Registers new GraphQL subscription IPC handlers and runner skip messaging. |
| packages/bruno-electron/src/ipc/network/graphql-subscription-event-handlers.js | Adds IPC handlers for connect/subscribe/unsubscribe/disconnect/introspection and request preparation. |
| packages/bruno-electron/src/ipc/collection.js | Closes ws + graphql-subscription connections when collections move/unmount/delete. |
| packages/bruno-converters/tests/opencollection/graphql-subscription.spec.js | Adds OpenCollection round-trip tests for graphql-subscription items. |
| packages/bruno-converters/src/opencollection/items/index.ts | Adds OpenCollection routing for graphql-subscription items. |
| packages/bruno-converters/src/opencollection/items/graphql-subscription.ts | Implements OpenCollection ↔ Bruno conversion for graphql-subscription-request. |
| packages/bruno-cli/src/utils/bru.js | Extends CLI BRU parsing to understand graphql-subscription requests. |
| packages/bruno-app/src/utils/tabs/index.js | Treats graphql-subscription-request as a request item for tab logic. |
| packages/bruno-app/src/utils/snapshot/index.js | Includes graphql-subscription-request in snapshot/tab handling and default pane selection. |
| packages/bruno-app/src/utils/network/index.js | Adds GraphQL subscription connect/subscribe/unsubscribe/disconnect and introspection fetcher. |
| packages/bruno-app/src/utils/network/graphql-subscription-event-listeners.js | Adds renderer IPC listeners to drive Redux updates for subscription events. |
| packages/bruno-app/src/utils/common/constants.js | Adds graphql-subscription preset type and request type allowlist update. |
| packages/bruno-app/src/utils/collections/index.js | Adds save/export transforms and default-pane handling for graphql-subscription-request. |
| packages/bruno-app/src/utils/collections/export.js | Ensures graphql-subscription-request is mapped during export transformations. |
| packages/bruno-app/src/utils/collections/emptyStateRequest.js | Adds “GraphQL Subscription” option to empty-state menu. |
| packages/bruno-app/src/providers/ReduxStore/slices/tabs.js | Defaults graphql-subscription-request tabs to “query” like graphql-request. |
| packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js | Adds subscription response state initialization, reducers, and action exports. |
| packages/bruno-app/src/providers/ReduxStore/slices/collections/graphql-subscription-events.spec.js | Adds reducer tests for subscription event handling and response state transitions. |
| packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js | Adds newGraphqlSubscriptionRequest creation + sendRequest routing for subscription transport. |
| packages/bruno-app/src/pages/Bruno/index.js | Registers subscription IPC event listeners. |
| packages/bruno-app/src/components/Sidebar/NewRequest/index.js | Adds new request UI option for GraphQL Subscription and URL validation handling. |
| packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/RequestMethod/index.js | Adds “SUB” method label and styling for subscription items. |
| packages/bruno-app/src/components/ShareCollection/index.js | Flags GraphQL Subscriptions as non-exportable (like ws/grpc) for share flow. |
| packages/bruno-app/src/components/RunnerResults/RunConfigurationPanel/index.jsx | Disables runner selection for graphql-subscription-request. |
| packages/bruno-app/src/components/ResponsePane/Timeline/index.js | Treats subscriptions as long-lived transport (timeline auth resolution logic). |
| packages/bruno-app/src/components/RequestTabs/RequestTab/resolveNewRequestTarget.js | Adds graphql-subscription-request to request tab types. |
| packages/bruno-app/src/components/RequestTabs/RequestTab/index.js | Disconnects subscription sockets when closing tabs. |
| packages/bruno-app/src/components/RequestTabPanel/index.js | Adds subscription query URL component and routes panes/response for subscription items. |
| packages/bruno-app/src/components/RequestPane/GraphQLSubscriptionQueryUrl/StyledWrapper.js | Styles subscription URL bar and connection strip. |
| packages/bruno-app/src/components/RequestPane/GraphQLSubscriptionQueryUrl/index.js | Implements subscription-specific URL bar with Subscribe/Unsubscribe controls. |
| packages/bruno-app/src/components/RequestPane/GraphQLSchemaActions/useGraphqlSchema.js | Allows injecting alternate introspection fetcher (used by subscription). |
| packages/bruno-app/src/components/RequestPane/GraphQLRequestPane/index.js | Adds subscription tab set incl. Connection Params; uses subscription introspection fetcher. |
| packages/bruno-app/src/components/RequestPane/ConnectionParams/index.js | Adds editor for graphql subscription connection params (stored in draft). |
| packages/bruno-app/src/components/CreateUntitledRequest/index.js | Adds create-untitled action for GraphQL Subscription requests. |
| packages/bruno-app/src/components/CollectionSettings/Presets/index.js | Adds preset selection option for graphql-subscription request type. |
| packages/bruno-app/src/components/AppPreviewKeepAlive/index.js | Includes graphql-subscription-request in app-preview keep-alive allowlist. |
| packages/bruno-app/src/components/AiChatSidebar/index.js | Labels subscription tabs as “SUB” in chat context. |
| package-lock.json | Locks new graphql-ws dependency. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| const item = { | ||
| uid: uuid(), | ||
| name: requestName, | ||
| filename, | ||
| type: 'graphql-subscription-request', | ||
| isTransient: isTransient, | ||
| headers: headers ?? [], | ||
| request: { | ||
| url: requestUrl, | ||
| body: { | ||
| mode: 'graphql', | ||
| graphql: { | ||
| query: '', | ||
| variables: '' | ||
| } | ||
| }, | ||
| auth: auth ?? { | ||
| mode: 'inherit' | ||
| }, | ||
| connectionParams: null, | ||
| docs: null | ||
| } | ||
| }; |
| // Derived from Redux state already kept live by useGraphqlSubscriptionEventListeners | ||
| // off the main:gql-sub:* push events, rather than polling on an interval like WsQueryUrl does. | ||
| const isConnected = useSelector((state) => (state.collections.activeConnections || []).includes(item.uid)); | ||
| const statusText = item.response?.statusText; | ||
| const isSubscribed = isConnected && statusText === 'CONNECTED'; | ||
| const isConnecting = !isConnected && statusText === 'CONNECTING'; | ||
|
|
Summary by CodeRabbit