diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 1c8aa37..2e8080b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,7 +1,6 @@ name: Unit tests on: - pull_request: push: paths: - "**.go" @@ -16,13 +15,17 @@ jobs: runs-on: ubuntu-20.04 permissions: pull-requests: write + # Required: allow read access to the content for analysis. + contents: read + # Optional: Allow write access to checks to allow the action to annotate code in the PR. + checks: write steps: - name: Checkout - uses: actions/checkout@v3 - - uses: actions/setup-go@v4 + uses: actions/checkout@v4 + - uses: actions/setup-go@v5 with: go-version: "1.20" - - uses: actions/cache@v3 + - uses: actions/cache@v4 with: path: | ~/go/pkg/mod @@ -42,14 +45,22 @@ jobs: run: | cd ./example/hasura docker-compose up -d + - name: Lint + uses: golangci/golangci-lint-action@v3 + with: + version: latest + only-new-issues: true + skip-cache: false - name: Run Go unit tests run: go test -v -race -timeout 3m -coverprofile=coverage.out ./... - name: Go coverage format + if: ${{ github.event_name == 'pull_request' }} run: | go get github.com/boumenot/gocover-cobertura go install github.com/boumenot/gocover-cobertura gocover-cobertura < coverage.out > coverage.xml - name: Code Coverage Summary Report + if: ${{ github.event_name == 'pull_request' }} uses: irongut/CodeCoverageSummary@v1.3.0 with: filename: coverage.xml @@ -63,7 +74,7 @@ jobs: thresholds: "60 80" - name: Add Coverage PR Comment uses: marocchino/sticky-pull-request-comment@v2 - if: ${{ github.event_name == 'pull_request_target' }} + if: ${{ github.event_name == 'pull_request' }} with: path: code-coverage-results.md - name: Dump docker logs on failure diff --git a/README.md b/README.md index f0d699d..9cb43c4 100644 --- a/README.md +++ b/README.md @@ -571,6 +571,16 @@ client := graphql.NewSubscriptionClient("wss://example.com/graphql"). }) ``` +Some servers validate custom auth tokens on the header instead. To authenticate with headers, use `WebsocketOptions`: + +```go +client := graphql.NewSubscriptionClient(serverEndpoint). + WithWebSocketOptions(graphql.WebsocketOptions{ + HTTPHeader: http.Header{ + "Authorization": []string{"Bearer random-secret"}, + }, + }) +``` #### Options diff --git a/example/graphql-ws-bc/README.md b/example/graphql-ws-bc/README.md new file mode 100644 index 0000000..0d8a762 --- /dev/null +++ b/example/graphql-ws-bc/README.md @@ -0,0 +1,33 @@ +# Subscription example with graphql-ws backwards compatibility + +The example demonstrates the subscription client with the native graphql-ws Node.js server, using [ws server usage with subscriptions-transport-ws backwards compatibility](https://the-guild.dev/graphql/ws/recipes#ws-server-usage-with-subscriptions-transport-ws-backwards-compatibility) and [custom auth handling](https://the-guild.dev/graphql/ws/recipes#server-usage-with-ws-and-custom-auth-handling) recipes. The client authenticates with the server via HTTP header. + +```go +client := graphql.NewSubscriptionClient(serverEndpoint). + WithWebSocketOptions(graphql.WebsocketOptions{ + HTTPHeader: http.Header{ + "Authorization": []string{"Bearer random-secret"}, + }, + }) +``` + +## Get started + +### Server + +Requires Node.js and npm + +```bash +cd server +npm install +npm start +``` + +The server will be hosted on `localhost:4000`. + +### Client + +```bash +go run ./client +``` + diff --git a/example/graphql-ws-bc/client/main.go b/example/graphql-ws-bc/client/main.go new file mode 100644 index 0000000..f8aaee1 --- /dev/null +++ b/example/graphql-ws-bc/client/main.go @@ -0,0 +1,85 @@ +// subscription is a test program currently being used for developing graphql package. +// It performs queries against a local test GraphQL server instance. +// +// It's not meant to be a clean or readable example. But it's functional. +// Better, actual examples will be created in the future. +package main + +import ( + "flag" + "log" + "net/http" + + graphql "github.com/hasura/go-graphql-client" +) + +func main() { + protocol := graphql.GraphQLWS + protocolArg := flag.String("protocol", "graphql-ws", "The protocol is used for the subscription") + flag.Parse() + + if protocolArg != nil { + switch *protocolArg { + case "graphql-ws": + case "": + case "ws": + protocol = graphql.SubscriptionsTransportWS + default: + panic("invalid protocol. Accept [ws, graphql-ws]") + } + } + + if err := startSubscription(protocol); err != nil { + panic(err) + } +} + +const serverEndpoint = "http://localhost:4000" + +func startSubscription(protocol graphql.SubscriptionProtocolType) error { + log.Printf("start subscription with protocol: %s", protocol) + client := graphql.NewSubscriptionClient(serverEndpoint). + WithWebSocketOptions(graphql.WebsocketOptions{ + HTTPHeader: http.Header{ + "Authorization": []string{"Bearer random-secret"}, + }, + }). + WithLog(log.Println). + WithProtocol(protocol). + WithoutLogTypes(graphql.GQLData, graphql.GQLConnectionKeepAlive). + OnError(func(sc *graphql.SubscriptionClient, err error) error { + log.Print("err", err) + return err + }) + + defer client.Close() + + /* + subscription { + greetings + } + */ + var sub struct { + Greetings string `graphql:"greetings"` + } + + _, err := client.Subscribe(sub, nil, func(data []byte, err error) error { + + if err != nil { + log.Println(err) + return nil + } + + if data == nil { + return nil + } + log.Printf("hello: %+v", string(data)) + return nil + }) + + if err != nil { + panic(err) + } + + return client.Run() +} diff --git a/example/graphql-ws-bc/server/.gitignore b/example/graphql-ws-bc/server/.gitignore new file mode 100644 index 0000000..b512c09 --- /dev/null +++ b/example/graphql-ws-bc/server/.gitignore @@ -0,0 +1 @@ +node_modules \ No newline at end of file diff --git a/example/graphql-ws-bc/server/index.ts b/example/graphql-ws-bc/server/index.ts new file mode 100644 index 0000000..3194644 --- /dev/null +++ b/example/graphql-ws-bc/server/index.ts @@ -0,0 +1,86 @@ +// The example is copied from ws server usage with subscriptions-transport-ws backwards compatibility example +// https://the-guild.dev/graphql/ws/recipes#ws-server-usage-with-subscriptions-transport-ws-backwards-compatibility + +import http from "http"; +import { WebSocketServer } from "ws"; // yarn add ws +// import ws from 'ws'; yarn add ws@7 +// const WebSocketServer = ws.Server; +import { execute, subscribe } from "graphql"; +import { GRAPHQL_TRANSPORT_WS_PROTOCOL } from "graphql-ws"; +import { useServer } from "graphql-ws/lib/use/ws"; +import { SubscriptionServer, GRAPHQL_WS } from "subscriptions-transport-ws"; +import { schema } from "./schema"; + +// extra in the context +interface Extra { + readonly request: http.IncomingMessage; +} + +// your custom auth +class Forbidden extends Error {} +function handleAuth(request: http.IncomingMessage) { + // do your auth on every subscription connect + const token = request.headers["authorization"]; + + // or const { iDontApprove } = session(request.cookies); + if (token !== "Bearer random-secret") { + // throw a custom error to be handled + throw new Forbidden(":("); + } +} + +// graphql-ws +const graphqlWs = new WebSocketServer({ noServer: true }); +useServer( + { + schema, + onConnect: async (ctx) => { + // do your auth on every connect (recommended) + await handleAuth(ctx.extra.request); + }, + }, + graphqlWs +); + +// subscriptions-transport-ws +const subTransWs = new WebSocketServer({ noServer: true }); +SubscriptionServer.create( + { + schema, + execute, + subscribe, + }, + subTransWs +); + +// create http server +const server = http.createServer(function weServeSocketsOnly(_, res) { + res.writeHead(404); + res.end(); +}); + +// listen for upgrades and delegate requests according to the WS subprotocol +server.on("upgrade", (req, socket, head) => { + // extract websocket subprotocol from header + const protocol = req.headers["sec-websocket-protocol"]; + const protocols = Array.isArray(protocol) + ? protocol + : protocol?.split(",").map((p) => p.trim()); + + // decide which websocket server to use + const wss = + protocols?.includes(GRAPHQL_WS) && // subscriptions-transport-ws subprotocol + !protocols.includes(GRAPHQL_TRANSPORT_WS_PROTOCOL) // graphql-ws subprotocol + ? subTransWs + : // graphql-ws will welcome its own subprotocol and + // gracefully reject invalid ones. if the client supports + // both transports, graphql-ws will prevail + graphqlWs; + wss.handleUpgrade(req, socket, head, (ws) => { + wss.emit("connection", ws, req); + }); +}); + +const port = 4000; +console.log(`listen server on localhost:${port}`); +server.listen(port); diff --git a/example/graphql-ws-bc/server/package-lock.json b/example/graphql-ws-bc/server/package-lock.json new file mode 100644 index 0000000..ce9c413 --- /dev/null +++ b/example/graphql-ws-bc/server/package-lock.json @@ -0,0 +1,326 @@ +{ + "name": "server", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "server", + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "graphql": "^16.8.1", + "graphql-ws": "^5.14.3", + "subscriptions-transport-ws": "^0.11.0", + "ws": "^8.16.0" + }, + "devDependencies": { + "@types/ws": "^8.5.10", + "ts-node": "^10.9.2", + "typescript": "^5.3.3" + } + }, + "node_modules/@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "dev": true, + "dependencies": { + "@jridgewell/trace-mapping": "0.3.9" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz", + "integrity": "sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.4.15", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", + "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==", + "dev": true + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "dev": true, + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "node_modules/@tsconfig/node10": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.9.tgz", + "integrity": "sha512-jNsYVVxU8v5g43Erja32laIDHXeoNvFEpX33OK4d6hljo3jDhCBDhx5dhCCTMWUojscpAagGiRkBKxpdl9fxqA==", + "dev": true + }, + "node_modules/@tsconfig/node12": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz", + "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==", + "dev": true + }, + "node_modules/@tsconfig/node14": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz", + "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==", + "dev": true + }, + "node_modules/@tsconfig/node16": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz", + "integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==", + "dev": true + }, + "node_modules/@types/node": { + "version": "20.11.16", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.16.tgz", + "integrity": "sha512-gKb0enTmRCzXSSUJDq6/sPcqrfCv2mkkG6Jt/clpn5eiCbKTY+SgZUxo+p8ZKMof5dCp9vHQUAB7wOUTod22wQ==", + "dev": true, + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/@types/ws": { + "version": "8.5.10", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.10.tgz", + "integrity": "sha512-vmQSUcfalpIq0R9q7uTo2lXs6eGIpt9wtnLdMv9LVpIjCA/+ufZRozlVoVelIYixx1ugCBKDhn89vnsEGOCx9A==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/acorn": { + "version": "8.11.3", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.3.tgz", + "integrity": "sha512-Y9rRfJG5jcKOE0CLisYbojUjIrIEE7AGMzA/Sm4BslANhbS+cDMpgBdcPT91oJ7OuJ9hYJBx59RjbhxVnrF8Xg==", + "dev": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-walk": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.2.tgz", + "integrity": "sha512-cjkyv4OtNCIeqhHrfS81QWXoCBPExR/J62oyEqepVw8WaQeSqpW2uhuLPh1m9eWhDuOo/jUXVTlifvesOWp/4A==", + "dev": true, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/arg": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", + "dev": true + }, + "node_modules/backo2": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/backo2/-/backo2-1.0.2.tgz", + "integrity": "sha512-zj6Z6M7Eq+PBZ7PQxl5NT665MvJdAkzp0f60nAJ+sLaSCBPMwVak5ZegFbgVCzFcCJTKFoMizvM5Ld7+JrRJHA==" + }, + "node_modules/create-require": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", + "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", + "dev": true + }, + "node_modules/diff": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", + "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", + "dev": true, + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/eventemitter3": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-3.1.2.tgz", + "integrity": "sha512-tvtQIeLVHjDkJYnzf2dgVMxfuSGJeM/7UCG17TT4EumTfNtF+0nebF/4zWOIkCreAbtNqhGEboB6BWrwqNaw4Q==" + }, + "node_modules/graphql": { + "version": "16.8.1", + "resolved": "https://registry.npmjs.org/graphql/-/graphql-16.8.1.tgz", + "integrity": "sha512-59LZHPdGZVh695Ud9lRzPBVTtlX9ZCV150Er2W43ro37wVof0ctenSaskPPjN7lVTIN8mSZt8PHUNKZuNQUuxw==", + "engines": { + "node": "^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0" + } + }, + "node_modules/graphql-ws": { + "version": "5.14.3", + "resolved": "https://registry.npmjs.org/graphql-ws/-/graphql-ws-5.14.3.tgz", + "integrity": "sha512-F/i2xNIVbaEF2xWggID0X/UZQa2V8kqKDPO8hwmu53bVOcTL7uNkxnexeEgSCVxYBQUTUNEI8+e4LO1FOhKPKQ==", + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "graphql": ">=0.11 <=16" + } + }, + "node_modules/iterall": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/iterall/-/iterall-1.3.0.tgz", + "integrity": "sha512-QZ9qOMdF+QLHxy1QIpUHUU1D5pS2CG2P69LF6L6CPjPYA/XMOmKV3PZpawHoAjHNyB0swdVTRxdYT4tbBbxqwg==" + }, + "node_modules/make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", + "dev": true + }, + "node_modules/subscriptions-transport-ws": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/subscriptions-transport-ws/-/subscriptions-transport-ws-0.11.0.tgz", + "integrity": "sha512-8D4C6DIH5tGiAIpp5I0wD/xRlNiZAPGHygzCe7VzyzUoxHtawzjNAY9SUTXU05/EY2NMY9/9GF0ycizkXr1CWQ==", + "deprecated": "The `subscriptions-transport-ws` package is no longer maintained. We recommend you use `graphql-ws` instead. For help migrating Apollo software to `graphql-ws`, see https://www.apollographql.com/docs/apollo-server/data/subscriptions/#switching-from-subscriptions-transport-ws For general help using `graphql-ws`, see https://github.com/enisdenjo/graphql-ws/blob/master/README.md", + "dependencies": { + "backo2": "^1.0.2", + "eventemitter3": "^3.1.0", + "iterall": "^1.2.1", + "symbol-observable": "^1.0.4", + "ws": "^5.2.0 || ^6.0.0 || ^7.0.0" + }, + "peerDependencies": { + "graphql": "^15.7.2 || ^16.0.0" + } + }, + "node_modules/subscriptions-transport-ws/node_modules/ws": { + "version": "7.5.9", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.9.tgz", + "integrity": "sha512-F+P9Jil7UiSKSkppIiD94dN07AwvFixvLIj1Og1Rl9GGMuNipJnV9JzjD6XuqmAeiswGvUmNLjr5cFuXwNS77Q==", + "engines": { + "node": ">=8.3.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": "^5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/symbol-observable": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/symbol-observable/-/symbol-observable-1.2.0.tgz", + "integrity": "sha512-e900nM8RRtGhlV36KGEU9k65K3mPb1WV70OdjfxlG2EAuM1noi/E/BaW/uMhL7bPEssK8QV57vN3esixjUvcXQ==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ts-node": { + "version": "10.9.2", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz", + "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==", + "dev": true, + "dependencies": { + "@cspotcode/source-map-support": "^0.8.0", + "@tsconfig/node10": "^1.0.7", + "@tsconfig/node12": "^1.0.7", + "@tsconfig/node14": "^1.0.0", + "@tsconfig/node16": "^1.0.2", + "acorn": "^8.4.1", + "acorn-walk": "^8.1.1", + "arg": "^4.1.0", + "create-require": "^1.1.0", + "diff": "^4.0.1", + "make-error": "^1.1.1", + "v8-compile-cache-lib": "^3.0.1", + "yn": "3.1.1" + }, + "bin": { + "ts-node": "dist/bin.js", + "ts-node-cwd": "dist/bin-cwd.js", + "ts-node-esm": "dist/bin-esm.js", + "ts-node-script": "dist/bin-script.js", + "ts-node-transpile-only": "dist/bin-transpile.js", + "ts-script": "dist/bin-script-deprecated.js" + }, + "peerDependencies": { + "@swc/core": ">=1.2.50", + "@swc/wasm": ">=1.2.50", + "@types/node": "*", + "typescript": ">=2.7" + }, + "peerDependenciesMeta": { + "@swc/core": { + "optional": true + }, + "@swc/wasm": { + "optional": true + } + } + }, + "node_modules/typescript": { + "version": "5.3.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.3.3.tgz", + "integrity": "sha512-pXWcraxM0uxAS+tN0AG/BF2TyqmHO014Z070UsJ+pFvYuRSq8KH8DmWpnbXe0pEPDHXZV3FcAbJkijJ5oNEnWw==", + "dev": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "5.26.5", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", + "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==", + "dev": true + }, + "node_modules/v8-compile-cache-lib": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", + "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==", + "dev": true + }, + "node_modules/ws": { + "version": "8.16.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.16.0.tgz", + "integrity": "sha512-HS0c//TP7Ina87TfiPUz1rQzMhHrl/SG2guqRcTOIUYD2q8uhUdNHZYJUaQ8aTGPzCh+c6oawMKW35nFl1dxyQ==", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/yn": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", + "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", + "dev": true, + "engines": { + "node": ">=6" + } + } + } +} diff --git a/example/graphql-ws-bc/server/package.json b/example/graphql-ws-bc/server/package.json new file mode 100644 index 0000000..827fa39 --- /dev/null +++ b/example/graphql-ws-bc/server/package.json @@ -0,0 +1,21 @@ +{ + "name": "server", + "version": "1.0.0", + "description": "graphql-ws backward compatibility server example", + "main": "index.ts", + "scripts": { + "start": "ts-node index.ts" + }, + "license": "MIT", + "dependencies": { + "graphql": "^16.8.1", + "graphql-ws": "^5.14.3", + "subscriptions-transport-ws": "^0.11.0", + "ws": "^8.16.0" + }, + "devDependencies": { + "@types/ws": "^8.5.10", + "ts-node": "^10.9.2", + "typescript": "^5.3.3" + } +} diff --git a/example/graphql-ws-bc/server/schema.ts b/example/graphql-ws-bc/server/schema.ts new file mode 100644 index 0000000..801c10d --- /dev/null +++ b/example/graphql-ws-bc/server/schema.ts @@ -0,0 +1,36 @@ +import { GraphQLSchema, GraphQLObjectType, GraphQLString } from "graphql"; + +/** + * Construct a GraphQL schema and define the necessary resolvers. + * + * type Query { + * hello: String + * } + * type Subscription { + * greetings: String + * } + */ +export const schema = new GraphQLSchema({ + query: new GraphQLObjectType({ + name: "Query", + fields: { + hello: { + type: GraphQLString, + resolve: () => "world", + }, + }, + }), + subscription: new GraphQLObjectType({ + name: "Subscription", + fields: { + greetings: { + type: GraphQLString, + subscribe: async function* () { + for (const hi of ["Hi", "Bonjour", "Hola", "Ciao", "Zdravo"]) { + yield { greetings: hi }; + } + }, + }, + }, + }), +}); diff --git a/example/graphql-ws-bc/server/tsconfig.json b/example/graphql-ws-bc/server/tsconfig.json new file mode 100644 index 0000000..3642e31 --- /dev/null +++ b/example/graphql-ws-bc/server/tsconfig.json @@ -0,0 +1,109 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ + // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ + // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ + // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ + // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ + + /* Language and Environment */ + "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "jsx": "preserve", /* Specify what JSX code is generated. */ + // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ + // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ + // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ + // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ + // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ + // "types": [], /* Specify type package names to be included without being referenced in a source file. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ + // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ + // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ + // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ + // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ + // "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ + + /* JavaScript Support */ + // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + // "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ + // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ + // "outDir": "./", /* Specify an output folder for all emitted files. */ + // "removeComments": true, /* Disable emitting comments. */ + // "noEmit": true, /* Disable emitting files from a compilation. */ + // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ + // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ + // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ + // "newLine": "crlf", /* Set the newline character for emitting files. */ + // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ + // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ + // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ + // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ + // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ + // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ + + /* Interop Constraints */ + // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ + // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ + // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": false, /* Enable all strict type-checking options. */ + // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ + // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ + // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ + // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ + // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ + // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ + // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ + + /* Completeness */ + // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ + } +} diff --git a/example/hasura/client/graphql-ws/client.go b/example/hasura/client/graphql-ws/client.go index f544ccd..3cc696f 100644 --- a/example/hasura/client/graphql-ws/client.go +++ b/example/hasura/client/graphql-ws/client.go @@ -20,7 +20,9 @@ const ( func main() { go insertUsers() - startSubscription() + if err := startSubscription(); err != nil { + panic(err) + } } func startSubscription() error { diff --git a/example/hasura/client/subscriptions-transport-ws/client.go b/example/hasura/client/subscriptions-transport-ws/client.go index cba1648..c627d5c 100644 --- a/example/hasura/client/subscriptions-transport-ws/client.go +++ b/example/hasura/client/subscriptions-transport-ws/client.go @@ -19,7 +19,9 @@ const ( func main() { go insertUsers() - startSubscription() + if err := startSubscription(); err != nil { + panic(err) + } } func startSubscription() error { @@ -73,7 +75,7 @@ func startSubscription() error { // automatically unsubscribe after 10 seconds go func() { time.Sleep(10 * time.Second) - client.Unsubscribe(subId) + _ = client.Unsubscribe(subId) }() return client.Run() diff --git a/example/realworld/main.go b/example/realworld/main.go index 1bd8949..cd8a446 100644 --- a/example/realworld/main.go +++ b/example/realworld/main.go @@ -5,8 +5,6 @@ import ( "encoding/json" "flag" "log" - "net/http" - "net/http/httptest" "os" graphql "github.com/hasura/go-graphql-client" @@ -61,15 +59,3 @@ func print(v interface{}) { panic(err) } } - -// localRoundTripper is an http.RoundTripper that executes HTTP transactions -// by using handler directly, instead of going over an HTTP connection. -type localRoundTripper struct { - handler http.Handler -} - -func (l localRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { - w := httptest.NewRecorder() - l.handler.ServeHTTP(w, req) - return w.Result(), nil -} diff --git a/example/subscription/client.go b/example/subscription/client.go index 49e9a23..7a5e3ed 100644 --- a/example/subscription/client.go +++ b/example/subscription/client.go @@ -66,7 +66,7 @@ func startSubscription() error { // automatically unsubscribe after 10 seconds go func() { time.Sleep(10 * time.Second) - client.Unsubscribe(subId) + _ = client.Unsubscribe(subId) }() return client.Run() diff --git a/example/subscription/main.go b/example/subscription/main.go index c5f610e..0c453f5 100644 --- a/example/subscription/main.go +++ b/example/subscription/main.go @@ -8,5 +8,7 @@ package main func main() { go startServer() go startSendHello() - startSubscription() + if err := startSubscription(); err != nil { + panic(err) + } } diff --git a/example/tibber/client.go b/example/tibber/client.go index 716e1d5..94f99ec 100644 --- a/example/tibber/client.go +++ b/example/tibber/client.go @@ -16,7 +16,9 @@ const ( ) func main() { - startSubscription() + if err := startSubscription(); err != nil { + panic(err) + } } // the subscription uses the Real time subscription demo diff --git a/graphql.go b/graphql.go index a045743..2113214 100644 --- a/graphql.go +++ b/graphql.go @@ -154,7 +154,7 @@ func (c *Client) request(ctx context.Context, query string, variables map[string resp, err := c.httpClient.Do(request) if c.debug { - reqReader.Seek(0, io.SeekStart) + _, _ = reqReader.Seek(0, io.SeekStart) } if err != nil { @@ -206,7 +206,7 @@ func (c *Client) request(ctx context.Context, query string, variables map[string err = json.NewDecoder(r).Decode(&out) if c.debug { - respReader.Seek(0, io.SeekStart) + _, _ = respReader.Seek(0, io.SeekStart) } if err != nil { @@ -344,7 +344,7 @@ func (e Error) Error() string { func (e Errors) Error() string { b := strings.Builder{} for _, err := range e { - b.WriteString(err.Error()) + _, _ = b.WriteString(err.Error()) } return b.String() } diff --git a/pkg/jsonutil/graphql_test.go b/pkg/jsonutil/graphql_test.go index 9b48714..f88e4d4 100644 --- a/pkg/jsonutil/graphql_test.go +++ b/pkg/jsonutil/graphql_test.go @@ -416,13 +416,17 @@ func TestUnmarshalGraphQL_unexportedField(t *testing.T) { type query struct { foo *string } - err := jsonutil.UnmarshalGraphQL([]byte(`{"foo": "bar"}`), new(query)) + q := new(query) + err := jsonutil.UnmarshalGraphQL([]byte(`{"foo": "bar"}`), q) if err == nil { t.Fatal("got error: nil, want: non-nil") } if got, want := err.Error(), "struct field for \"foo\" doesn't exist in any of 1 places to unmarshal"; got != want { t.Errorf("got error: %v, want: %v", got, want) } + if q.foo != nil { + t.Errorf("expected foo = nil, got: %v", q.foo) + } } func TestUnmarshalGraphQL_multipleValues(t *testing.T) { diff --git a/query.go b/query.go index 1ee9d7c..dfd6edc 100644 --- a/query.go +++ b/query.go @@ -140,9 +140,9 @@ func queryArguments(variables map[string]interface{}) string { var buf bytes.Buffer for _, k := range keys { - io.WriteString(&buf, "$") - io.WriteString(&buf, k) - io.WriteString(&buf, ":") + _, _ = io.WriteString(&buf, "$") + _, _ = io.WriteString(&buf, k) + _, _ = io.WriteString(&buf, ":") writeArgumentType(&buf, reflect.TypeOf(variables[k]), variables[k], true) // Don't insert a comma here. // Commas in GraphQL are insignificant, and we want minified output. @@ -168,10 +168,10 @@ func writeArgumentType(w io.Writer, t reflect.Type, v interface{}, value bool) { graphqlType, ok = reflect.Zero(t).Interface().(GraphQLType) } if ok { - io.WriteString(w, graphqlType.GetGraphQLType()) + _, _ = io.WriteString(w, graphqlType.GetGraphQLType()) if value { // Value is a required type, so add "!" to the end. - io.WriteString(w, "!") + _, _ = io.WriteString(w, "!") } return } @@ -186,27 +186,27 @@ func writeArgumentType(w io.Writer, t reflect.Type, v interface{}, value bool) { switch t.Kind() { case reflect.Slice, reflect.Array: // List. E.g., "[Int]". - io.WriteString(w, "[") + _, _ = io.WriteString(w, "[") writeArgumentType(w, t.Elem(), nil, true) - io.WriteString(w, "]") + _, _ = io.WriteString(w, "]") case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - io.WriteString(w, "Int") + _, _ = io.WriteString(w, "Int") case reflect.Float32, reflect.Float64: - io.WriteString(w, "Float") + _, _ = io.WriteString(w, "Float") case reflect.Bool: - io.WriteString(w, "Boolean") + _, _ = io.WriteString(w, "Boolean") default: n := t.Name() if n == "string" { n = "String" } - io.WriteString(w, n) + _, _ = io.WriteString(w, n) } if value { // Value is a required type, so add "!" to the end. - io.WriteString(w, "!") + _, _ = io.WriteString(w, "!") } } @@ -241,7 +241,7 @@ func writeQuery(w io.Writer, t reflect.Type, v reflect.Value, inline bool) error return nil } if !inline { - io.WriteString(w, "{") + _, _ = io.WriteString(w, "{") } iter := 0 for i := 0; i < t.NumField(); i++ { @@ -252,16 +252,16 @@ func writeQuery(w io.Writer, t reflect.Type, v reflect.Value, inline bool) error continue } if iter != 0 { - io.WriteString(w, ",") + _, _ = io.WriteString(w, ",") } iter++ inlineField := f.Anonymous && !ok if !inlineField { if ok { - io.WriteString(w, value) + _, _ = io.WriteString(w, value) } else { - io.WriteString(w, ident.ParseMixedCaps(f.Name).ToLowerCamelCase()) + _, _ = io.WriteString(w, ident.ParseMixedCaps(f.Name).ToLowerCamelCase()) } } // Skip writeQuery if the GraphQL type associated with the filed is scalar @@ -274,7 +274,7 @@ func writeQuery(w io.Writer, t reflect.Type, v reflect.Value, inline bool) error } } if !inline { - io.WriteString(w, "}") + _, _ = io.WriteString(w, "}") } case reflect.Slice: if t.Elem().Kind() != reflect.Array { diff --git a/subscription.go b/subscription.go index 19ce18d..7a58178 100644 --- a/subscription.go +++ b/subscription.go @@ -885,7 +885,7 @@ func (sc *SubscriptionClient) reset() { continue } if sub.status == SubscriptionRunning { - sc.protocol.Unsubscribe(subContext, sub) + _ = sc.protocol.Unsubscribe(subContext, sub) } // should restart subscriptions with new id @@ -1063,8 +1063,12 @@ func (wh *WebsocketHandler) GetCloseStatus(err error) int32 { func newWebsocketConn(sc *SubscriptionClient) (WebsocketConn, error) { options := &websocket.DialOptions{ - Subprotocols: sc.protocol.GetSubprotocols(), - HTTPClient: sc.websocketOptions.HTTPClient, + Subprotocols: sc.protocol.GetSubprotocols(), + HTTPClient: sc.websocketOptions.HTTPClient, + HTTPHeader: sc.websocketOptions.HTTPHeader, + Host: sc.websocketOptions.Host, + CompressionMode: sc.websocketOptions.CompressionMode, + CompressionThreshold: sc.websocketOptions.CompressionThreshold, } c, _, err := websocket.Dial(sc.GetContext(), sc.GetURL(), options) @@ -1082,5 +1086,26 @@ func newWebsocketConn(sc *SubscriptionClient) (WebsocketConn, error) { // WebsocketOptions allows implementation agnostic configuration of the websocket client type WebsocketOptions struct { // HTTPClient is used for the connection. + // Its Transport must return writable bodies for WebSocket handshakes. + // http.Transport does beginning with Go 1.12. HTTPClient *http.Client + + // HTTPHeader specifies the HTTP headers included in the handshake request. + HTTPHeader http.Header + + // Host optionally overrides the Host HTTP header to send. If empty, the value + // of URL.Host will be used. + Host string + + // CompressionMode controls the compression mode. + // Defaults to CompressionDisabled. + // + // See docs on CompressionMode for details. + CompressionMode websocket.CompressionMode + + // CompressionThreshold controls the minimum size of a message before compression is applied. + // + // Defaults to 512 bytes for CompressionNoContextTakeover and 128 bytes + // for CompressionContextTakeover. + CompressionThreshold int } diff --git a/subscription_graphql_ws_test.go b/subscription_graphql_ws_test.go index 051e8e6..2b37132 100644 --- a/subscription_graphql_ws_test.go +++ b/subscription_graphql_ws_test.go @@ -137,7 +137,7 @@ func TestGraphqlWS_Subscription(t *testing.T) { go func() { if err := subscriptionClient.Run(); err == nil || err.Error() != "exit" { - (*t).Fatalf("got error: %v, want: exit", err) + t.Errorf("got error: %v, want: exit", err) } stop <- true }() @@ -236,7 +236,7 @@ func TestGraphqlWS_SubscriptionRerun(t *testing.T) { go func() { if err := subscriptionClient.Run(); err != nil { - (*t).Fatalf("got error: %v, want: nil", err) + t.Errorf("got error: %v, want: nil", err) } }() @@ -280,11 +280,11 @@ func TestGraphqlWS_SubscriptionRerun(t *testing.T) { time.Sleep(2 * time.Second) go func() { time.Sleep(2 * time.Second) - subscriptionClient.Unsubscribe(subId1) + _ = subscriptionClient.Unsubscribe(subId1) }() if err := subscriptionClient.Run(); err != nil { - (*t).Fatalf("got error: %v, want: nil", err) + t.Fatalf("got error: %v, want: nil", err) } } @@ -351,7 +351,7 @@ func TestGraphQLWS_OnError(t *testing.T) { go func() { if err := subscriptionClient.Run(); err == nil || websocket.CloseStatus(err) != 4400 { - (*t).Fatalf("got error: %v, want: 4400", err) + t.Errorf("got error: %v, want: 4400", err) } stop <- true }() diff --git a/subscription_test.go b/subscription_test.go index 5add1f2..e9cdafc 100644 --- a/subscription_test.go +++ b/subscription_test.go @@ -79,7 +79,10 @@ func testSubscription_LifeCycleEvents(t *testing.T, syncMode bool) { }() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - defer server.Shutdown(ctx) + defer func() { + _ = server.Shutdown(ctx) + }() + defer cancel() subscriptionClient = subscriptionClient. @@ -161,7 +164,8 @@ func testSubscription_LifeCycleEvents(t *testing.T, syncMode bool) { } err := client.Mutate(context.Background(), &q, variables, OperationName("SayHello")) if err != nil { - (*t).Fatalf("got error: %v, want: nil", err) + t.Errorf("got error: %v, want: nil", err) + return } time.Sleep(2 * time.Second) @@ -274,7 +278,7 @@ func TestSubscription_WithRetryStatusCodes(t *testing.T) { go func() { if err := subscriptionClient.Run(); err != nil && websocket.CloseStatus(err) == 4400 { - (*t).Fatalf("should not get error 4400, got error: %v, want: nil", err) + t.Errorf("should not get error 4400, got error: %v, want: nil", err) } }() @@ -390,13 +394,13 @@ func TestSubscription_closeThenRun(t *testing.T) { go func() { if err := subscriptionClient.Run(); err != nil { - (*t).Fatalf("got error: %v, want: nil", err) + t.Errorf("got error: %v, want: nil", err) } }() time.Sleep(3 * time.Second) if err := subscriptionClient.Close(); err != nil { - (*t).Fatalf("got error: %v, want: nil", err) + t.Fatalf("got error: %v, want: nil", err) } bulkSubscribe() @@ -404,23 +408,23 @@ func TestSubscription_closeThenRun(t *testing.T) { go func() { length := subscriptionClient.getContext().GetSubscriptionsLength(nil) if length != 2 { - (*t).Fatalf("unexpected subscription client. got: %d, want: 2", length) + t.Errorf("unexpected subscription client. got: %d, want: 2", length) + return } waitingLen := subscriptionClient.getContext().GetSubscriptionsLength([]SubscriptionStatus{SubscriptionWaiting}) if waitingLen != 2 { - (*t).Fatalf("unexpected waiting subscription client. got: %d, want: 2", waitingLen) + t.Errorf("unexpected waiting subscription client. got: %d, want: 2", waitingLen) } if err := subscriptionClient.Run(); err != nil { - (*t).Fatalf("got error: %v, want: nil", err) - panic(err) + t.Errorf("got error: %v, want: nil", err) } }() time.Sleep(3 * time.Second) length := subscriptionClient.getContext().GetSubscriptionsLength(nil) if length != 2 { - (*t).Fatalf("unexpected subscription client after restart. got: %d, want: 2, subscriptions: %+v", length, subscriptionClient.context.subscriptions) + t.Fatalf("unexpected subscription client after restart. got: %d, want: 2, subscriptions: %+v", length, subscriptionClient.context.subscriptions) } if err := subscriptionClient.Close(); err != nil { t.Fatalf("got error: %v, want: nil", err) diff --git a/subscriptions_transport_ws_test.go b/subscriptions_transport_ws_test.go index 9baaa78..ce3c2c9 100644 --- a/subscriptions_transport_ws_test.go +++ b/subscriptions_transport_ws_test.go @@ -183,7 +183,9 @@ func TestTransportWS_basicTest(t *testing.T) { }() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - defer server.Shutdown(ctx) + defer func() { + _ = server.Shutdown(ctx) + }() defer cancel() subscriptionClient. @@ -232,7 +234,7 @@ func TestTransportWS_basicTest(t *testing.T) { go func() { if err := subscriptionClient.Run(); err == nil || err.Error() != "exit" { - (*t).Fatalf("got error: %v, want: exit", err) + t.Errorf("got error: %v, want: exit", err) } stop <- true }() @@ -279,7 +281,9 @@ func TestTransportWS_exitWhenNoSubscription(t *testing.T) { }() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - defer server.Shutdown(ctx) + defer func() { + _ = server.Shutdown(ctx) + }() defer cancel() subscriptionClient = subscriptionClient. @@ -392,12 +396,13 @@ func TestTransportWS_exitWhenNoSubscription(t *testing.T) { } err = client.Mutate(context.Background(), &q, variables, OperationName("SayHello")) if err != nil { - (*t).Fatalf("got error: %v, want: nil", err) + t.Errorf("got error: %v, want: nil", err) + return } time.Sleep(2 * time.Second) - subscriptionClient.Unsubscribe(subId1) - subscriptionClient.Unsubscribe(subId2) + _ = subscriptionClient.Unsubscribe(subId1) + _ = subscriptionClient.Unsubscribe(subId2) }() defer subscriptionClient.Close() @@ -535,7 +540,8 @@ func TestTransportWS_ResetClient(t *testing.T) { err = client.Mutate(context.Background(), &q, variables, OperationName("InsertUser")) if err != nil { - (*t).Fatalf("got error: %v, want: nil", err) + t.Errorf("got error: %v, want: nil", err) + return } time.Sleep(2 * time.Second) @@ -543,32 +549,38 @@ func TestTransportWS_ResetClient(t *testing.T) { // test subscription ids sub1 := subscriptionClient.getContext().GetSubscription(subId1) if sub1 == nil { - (*t).Fatalf("subscription 1 not found: %s", subId1) + t.Errorf("subscription 1 not found: %s", subId1) + return } else { if sub1.key != subId1 { - (*t).Fatalf("subscription key 1 not equal, got %s, want %s", subId1, sub1.key) + t.Errorf("subscription key 1 not equal, got %s, want %s", subId1, sub1.key) + return } if sub1.id != subId1 { - (*t).Fatalf("subscription id 1 not equal, got %s, want %s", subId1, sub1.id) + t.Errorf("subscription id 1 not equal, got %s, want %s", subId1, sub1.id) + return } } sub2 := subscriptionClient.getContext().GetSubscription(subId2) if sub2 == nil { - (*t).Fatalf("subscription 2 not found: %s", subId2) + t.Errorf("subscription 2 not found: %s", subId2) + return } else { if sub2.key != subId2 { - (*t).Fatalf("subscription id 2 not equal, got %s, want %s", subId2, sub2.key) + t.Errorf("subscription id 2 not equal, got %s, want %s", subId2, sub2.key) + return } if sub2.id != subId2 { - (*t).Fatalf("subscription id 2 not equal, got %s, want %s", subId2, sub2.id) + t.Errorf("subscription id 2 not equal, got %s, want %s", subId2, sub2.id) + return } } // reset the subscription log.Printf("resetting the subscription client...") if err := subscriptionClient.Run(); err != nil { - (*t).Fatalf("failed to reset the subscription client. got error: %v, want: nil", err) + t.Errorf("failed to reset the subscription client. got error: %v, want: nil", err) } log.Printf("the second run was stopped") stop <- true @@ -580,30 +592,30 @@ func TestTransportWS_ResetClient(t *testing.T) { // test subscription ids sub1 := subscriptionClient.getContext().GetSubscription(subId1) if sub1 == nil { - (*t).Fatalf("subscription 1 not found: %s", subId1) + t.Errorf("subscription 1 not found: %s", subId1) } else { if sub1.key != subId1 { - (*t).Fatalf("subscription key 1 not equal, got %s, want %s", subId1, sub1.key) + t.Errorf("subscription key 1 not equal, got %s, want %s", subId1, sub1.key) } if sub1.id == subId1 { - (*t).Fatalf("subscription id 1 should equal, got %s, want %s", subId1, sub1.id) + t.Errorf("subscription id 1 should equal, got %s, want %s", subId1, sub1.id) } } sub2 := subscriptionClient.getContext().GetSubscription(subId2) if sub2 == nil { - (*t).Fatalf("subscription 2 not found: %s", subId2) + t.Errorf("subscription 2 not found: %s", subId2) } else { if sub2.key != subId2 { - (*t).Fatalf("subscription id 2 not equal, got %s, want %s", subId2, sub2.key) + t.Errorf("subscription id 2 not equal, got %s, want %s", subId2, sub2.key) } if sub2.id == subId2 { - (*t).Fatalf("subscription id 2 should equal, got %s, want %s", subId2, sub2.id) + t.Errorf("subscription id 2 should equal, got %s, want %s", subId2, sub2.id) } } - subscriptionClient.Unsubscribe(subId1) - subscriptionClient.Unsubscribe(subId2) + _ = subscriptionClient.Unsubscribe(subId1) + _ = subscriptionClient.Unsubscribe(subId2) }() defer subscriptionClient.Close() @@ -670,7 +682,7 @@ func TestTransportWS_onDisconnected(t *testing.T) { // run client go func() { - subscriptionClient.Run() + _ = subscriptionClient.Run() }() defer subscriptionClient.Close() @@ -754,7 +766,7 @@ func TestTransportWS_OnError(t *testing.T) { err := subscriptionClient.Run() if err == nil || err.Error() != unauthorizedErr { - (*t).Errorf("got error: %v, want: %s", err, unauthorizedErr) + t.Errorf("got error: %v, want: %s", err, unauthorizedErr) } stop <- true }()