From e9e69c705b28a69fe0c85d602d8250e9e9a89483 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 29 Sep 2022 19:13:39 +0000 Subject: [PATCH] build(deps): bump github.com/hasura/go-graphql-client Bumps [github.com/hasura/go-graphql-client](https://github.com/hasura/go-graphql-client) from 0.6.3 to 0.8.1. - [Release notes](https://github.com/hasura/go-graphql-client/releases) - [Commits](https://github.com/hasura/go-graphql-client/compare/v0.6.3...v0.8.1) --- updated-dependencies: - dependency-name: github.com/hasura/go-graphql-client dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- go.mod | 7 +- go.sum | 31 +- .../graph-gophers/graphql-go/README.md | 54 ++- .../graph-gophers/graphql-go/SECURITY.md | 17 + .../example/starwars/introspect.json | 27 ++ .../graph-gophers/graphql-go/go.mod | 8 +- .../graph-gophers/graphql-go/go.sum | 29 +- .../graph-gophers/graphql-go/graphql.go | 31 +- .../graphql-go/internal/exec/exec.go | 4 +- .../internal/exec/resolvable/meta.go | 18 + .../internal/exec/selected/selected.go | 11 + .../graphql-go/internal/schema/meta.go | 4 + .../graphql-go/internal/schema/schema.go | 55 ++- .../internal/validation/validation.go | 5 + .../graphql-go/introspection/introspection.go | 13 + .../graphql-go/trace/noop/trace.go | 24 ++ .../graph-gophers/graphql-go/trace/trace.go | 96 ------ .../graphql-go/trace/tracer/tracer.go | 34 ++ .../graphql-go/trace/validation_trace.go | 25 -- .../graphql-go/types/directive.go | 11 +- .../graph-gophers/graphql-go/types/schema.go | 1 + .../hasura/go-graphql-client/.gitignore | 1 + .../hasura/go-graphql-client/README.md | 246 ++++++++++++-- .../hasura/go-graphql-client/doc.go | 6 +- .../hasura/go-graphql-client/go.mod | 5 +- .../hasura/go-graphql-client/go.sum | 25 +- .../hasura/go-graphql-client/graphql.go | 313 +++++++++++++----- .../hasura/go-graphql-client/query.go | 123 +++++-- .../hasura/go-graphql-client/scalar.go | 61 +++- .../hasura/go-graphql-client/subscription.go | 282 ++++++++++------ .../hasura/go-graphql-client/type.go | 15 + .../opentracing/opentracing-go/.gitignore | 1 - .../opentracing/opentracing-go/.travis.yml | 20 -- .../opentracing/opentracing-go/CHANGELOG.md | 46 --- .../opentracing/opentracing-go/LICENSE | 201 ----------- .../opentracing/opentracing-go/Makefile | 20 -- .../opentracing/opentracing-go/README.md | 171 ---------- .../opentracing/opentracing-go/ext/tags.go | 210 ------------ .../opentracing-go/globaltracer.go | 42 --- .../opentracing/opentracing-go/gocontext.go | 60 ---- .../opentracing/opentracing-go/noop.go | 64 ---- .../opentracing/opentracing-go/propagation.go | 176 ---------- .../opentracing/opentracing-go/span.go | 189 ----------- .../opentracing/opentracing-go/tracer.go | 304 ----------------- vendor/modules.txt | 11 +- 45 files changed, 1121 insertions(+), 1976 deletions(-) create mode 100644 vendor/github.com/graph-gophers/graphql-go/SECURITY.md create mode 100644 vendor/github.com/graph-gophers/graphql-go/trace/noop/trace.go delete mode 100644 vendor/github.com/graph-gophers/graphql-go/trace/trace.go create mode 100644 vendor/github.com/graph-gophers/graphql-go/trace/tracer/tracer.go delete mode 100644 vendor/github.com/graph-gophers/graphql-go/trace/validation_trace.go create mode 100644 vendor/github.com/hasura/go-graphql-client/.gitignore create mode 100644 vendor/github.com/hasura/go-graphql-client/type.go delete mode 100644 vendor/github.com/opentracing/opentracing-go/.gitignore delete mode 100644 vendor/github.com/opentracing/opentracing-go/.travis.yml delete mode 100644 vendor/github.com/opentracing/opentracing-go/CHANGELOG.md delete mode 100644 vendor/github.com/opentracing/opentracing-go/LICENSE delete mode 100644 vendor/github.com/opentracing/opentracing-go/Makefile delete mode 100644 vendor/github.com/opentracing/opentracing-go/README.md delete mode 100644 vendor/github.com/opentracing/opentracing-go/ext/tags.go delete mode 100644 vendor/github.com/opentracing/opentracing-go/globaltracer.go delete mode 100644 vendor/github.com/opentracing/opentracing-go/gocontext.go delete mode 100644 vendor/github.com/opentracing/opentracing-go/noop.go delete mode 100644 vendor/github.com/opentracing/opentracing-go/propagation.go delete mode 100644 vendor/github.com/opentracing/opentracing-go/span.go delete mode 100644 vendor/github.com/opentracing/opentracing-go/tracer.go diff --git a/go.mod b/go.mod index a6b3579b2..24ed8b898 100644 --- a/go.mod +++ b/go.mod @@ -5,15 +5,12 @@ go 1.12 require ( github.com/gin-gonic/gin v1.7.7 github.com/golang/protobuf v1.4.2 // indirect - github.com/graph-gophers/graphql-go v1.3.0 + github.com/graph-gophers/graphql-go v1.4.0 github.com/hashicorp/go-version v1.5.0 github.com/hashicorp/logutils v1.0.0 - github.com/hasura/go-graphql-client v0.6.3 - github.com/inconshreveable/mousetrap v1.0.0 // indirect + github.com/hasura/go-graphql-client v0.8.1 github.com/json-iterator/go v1.1.10 // indirect github.com/klauspost/compress v1.14.2 // indirect - github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect - github.com/modern-go/reflect2 v1.0.1 // indirect github.com/spf13/cobra v1.1.3 github.com/stretchr/testify v1.7.4 golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect diff --git a/go.sum b/go.sum index 4a5c7d5ae..5524b69e3 100644 --- a/go.sum +++ b/go.sum @@ -51,6 +51,10 @@ github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9 github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= @@ -60,8 +64,11 @@ github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GO github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE= github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee h1:s+21KNqlpePfkah2I+gwHF8xmJWRjooY+5248k6m4A0= github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo= +github.com/gobwas/pool v0.2.0 h1:QEmUOlnSjWtnpRGHF3SauEiOsy82Cup83Vf2LcMlnc8= github.com/gobwas/pool v0.2.0/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= +github.com/gobwas/ws v1.0.2 h1:CoAavW/wd/kulfZmSIBt6p24n4j7tHgNVCjsfHVNUbo= github.com/gobwas/ws v1.0.2/go.mod h1:szmBTxLgaFppYjEmNtny/v3w89xOydFnnZMcgRRu/EM= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= @@ -90,6 +97,8 @@ github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMyw github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.7 h1:81/ik6ipDQS2aGcBfIN5dHDB36BwrStyeAQquSYCV4o= +github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= @@ -101,10 +110,12 @@ github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+ github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= -github.com/graph-gophers/graphql-go v1.2.0/go.mod h1:9CQHMSxwO4MprSdzoIEobiHpoLtHm77vfxsvsIN5Vuc= -github.com/graph-gophers/graphql-go v1.3.0 h1:Eb9x/q6MFpCLz7jBCiP/WTxjSDrYLR1QY41SORZyNJ0= -github.com/graph-gophers/graphql-go v1.3.0/go.mod h1:9CQHMSxwO4MprSdzoIEobiHpoLtHm77vfxsvsIN5Vuc= +github.com/graph-gophers/graphql-go v1.4.0 h1:JE9wveRTSXwJyjdRd6bOQ7Ob5bewTUQ58Jv4OiVdpdE= +github.com/graph-gophers/graphql-go v1.4.0/go.mod h1:YtmJZDLbF1YYNrlNAuiO5zAStUWc3XZT07iGsVqe1Os= +github.com/graph-gophers/graphql-transport-ws v0.0.2 h1:DbmSkbIGzj8SvHei6n8Mh9eLQin8PtA8xY9eCzjRpvo= +github.com/graph-gophers/graphql-transport-ws v0.0.2/go.mod h1:5BVKvFzOd2BalVIBFfnfmHjpJi/MZ5rOj8G55mXvZ8g= github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= @@ -131,8 +142,8 @@ github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= -github.com/hasura/go-graphql-client v0.6.3 h1:WO9iSR79LA6y/lEgwCvGcOxGxsNBmIBqV7aE2WaClos= -github.com/hasura/go-graphql-client v0.6.3/go.mod h1:kvaJsDhxGbkIJ1jgebkrnt9EDIELZHpsAMint56v+2I= +github.com/hasura/go-graphql-client v0.8.1 h1:yU4888urgkW4L47cs+QQDXl3YfVaNraUqym5qsJ41Ms= +github.com/hasura/go-graphql-client v0.8.1/go.mod h1:NVifIwv+YFIUYGLQ7SM2/vBbzS/9rFP4vmIf/vf/zXM= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= @@ -150,8 +161,10 @@ github.com/klauspost/compress v1.14.2 h1:S0OHlFk/Gbon/yauFJ4FfJJF5V0fc5HbBTJazi2 github.com/klauspost/compress v1.14.2/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= @@ -178,8 +191,7 @@ github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9 github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= -github.com/opentracing/opentracing-go v1.1.0 h1:pWlfV3Bxv7k65HYwkikxat0+s3pV4bsqf19k25Ur8rU= -github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= +github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= @@ -223,6 +235,7 @@ github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSS github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.4 h1:wZRexSlwd7ZXfKINDLsO4r7WBt3gTKONc6K/VesHvHM= github.com/stretchr/testify v1.7.4/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= @@ -236,6 +249,8 @@ github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= +go.opentelemetry.io/otel v1.6.3/go.mod h1:7BgNga5fNlF/iZjG06hM3yofffp0ofKCDwSXx1GC4dI= +go.opentelemetry.io/otel/trace v1.6.3/go.mod h1:GNJQusJlUgZl9/TQBPKU/Y/ty+0iVB5fjhKeJGZPGFs= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= @@ -334,6 +349,7 @@ golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= @@ -371,6 +387,7 @@ google.golang.org/protobuf v1.25.0 h1:Ejskq+SyPohKW+1uil0JJMtmHCgJPJ/qWTxr8qp+R4 google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= diff --git a/vendor/github.com/graph-gophers/graphql-go/README.md b/vendor/github.com/graph-gophers/graphql-go/README.md index 87b020c13..121f66ef3 100644 --- a/vendor/github.com/graph-gophers/graphql-go/README.md +++ b/vendor/github.com/graph-gophers/graphql-go/README.md @@ -11,7 +11,7 @@ safe for production use. - minimal API - support for `context.Context` -- support for the `OpenTracing` standard +- support for the `OpenTelemetry` and `OpenTracing` standards - schema type-checking against resolvers - resolvers are matched to the schema based on method sets (can resolve a GraphQL schema with a Go interface or Go struct). - handles panics in resolvers @@ -26,8 +26,9 @@ Feedback is welcome and appreciated. ## (Some) Documentation -### Basic Sample +### Getting started +In order to run a simple GraphQL server locally create a `main.go` file with the following content: ```go package main @@ -54,12 +55,12 @@ func main() { log.Fatal(http.ListenAndServe(":8080", nil)) } ``` - -To test: +Then run the file with `go run main.go`. To test: ```sh curl -XPOST -d '{"query": "{ hello }"}' localhost:8080/query ``` +For more realistic usecases check our [examples section](https://github.com/graph-gophers/graphql-go/wiki/Examples). ### Resolvers @@ -107,8 +108,7 @@ func (r *helloWorldResolver) Hello(ctx context.Context) (string, error) { - `UseFieldResolvers()` specifies whether to use struct field resolvers. - `MaxDepth(n int)` specifies the maximum field nesting depth in a query. The default is 0 which disables max depth checking. - `MaxParallelism(n int)` specifies the maximum number of resolvers per request allowed to run in parallel. The default is 10. -- `Tracer(tracer trace.Tracer)` is used to trace queries and fields. It defaults to `trace.OpenTracingTracer`. -- `ValidationTracer(tracer trace.ValidationTracer)` is used to trace validation errors. It defaults to `trace.NoopValidationTracer`. +- `Tracer(tracer trace.Tracer)` is used to trace queries and fields. It defaults to `noop.Tracer`. - `Logger(logger log.Logger)` is used to log panics during query execution. It defaults to `exec.DefaultLogger`. - `PanicHandler(panicHandler errors.PanicHandler)` is used to transform panics into errors during query execution. It defaults to `errors.DefaultPanicHandler`. - `DisableIntrospection()` disables introspection queries. @@ -164,6 +164,48 @@ Which could produce a GraphQL error such as: } ``` +### Tracing + +By default the library uses `noop.Tracer`. If you want to change that you can use the OpenTelemetry or the OpenTracing implementations, respectively: + +```go +// OpenTelemetry tracer +package main + +import ( + "github.com/graph-gophers/graphql-go" + "github.com/graph-gophers/graphql-go/example/starwars" + otelgraphql "github.com/graph-gophers/graphql-go/trace/otel" + "github.com/graph-gophers/graphql-go/trace/tracer" +) +// ... +_, err := graphql.ParseSchema(starwars.Schema, nil, graphql.Tracer(otelgraphql.DefaultTracer())) +// ... +``` +Alternatively you can pass an existing trace.Tracer instance: +```go +tr := otel.Tracer("example") +_, err = graphql.ParseSchema(starwars.Schema, nil, graphql.Tracer(&otelgraphql.Tracer{Tracer: tr})) +``` + + +```go +// OpenTracing tracer +package main + +import ( + "github.com/graph-gophers/graphql-go" + "github.com/graph-gophers/graphql-go/example/starwars" + "github.com/graph-gophers/graphql-go/trace/opentracing" + "github.com/graph-gophers/graphql-go/trace/tracer" +) +// ... +_, err := graphql.ParseSchema(starwars.Schema, nil, graphql.Tracer(opentracing.Tracer{})) + +// ... +``` + + ### [Examples](https://github.com/graph-gophers/graphql-go/wiki/Examples) ### [Companies that use this library](https://github.com/graph-gophers/graphql-go/wiki/Users) diff --git a/vendor/github.com/graph-gophers/graphql-go/SECURITY.md b/vendor/github.com/graph-gophers/graphql-go/SECURITY.md new file mode 100644 index 000000000..f79511db1 --- /dev/null +++ b/vendor/github.com/graph-gophers/graphql-go/SECURITY.md @@ -0,0 +1,17 @@ +# Security Policy + +## Supported Versions + +We always try to maintain the library secure and suggest our users to upgrade to the latest stable version. We realize that sometimes this is not possible. + +| Version | Supported | +| ------- | ------------------ | +| 1.x | :white_check_mark: | +| < 1.0 | :x: | + +## MaxDepth +If you are using the `graphql.MaxDepth` schema option, make sure that you upgrade to version v1.3.0 or higher due to a bug causing security vulnerability in earlier versions. + +## Reporting a Vulnerability + +If you find a security vulnerability with this library, please, DO NOT submit a pull request right away. Please, report the issue to @pavelnikolov and/or @tony in the Gophers Slack in a private message. diff --git a/vendor/github.com/graph-gophers/graphql-go/example/starwars/introspect.json b/vendor/github.com/graph-gophers/graphql-go/example/starwars/introspect.json index 2b955ee9c..89ed5a3f2 100644 --- a/vendor/github.com/graph-gophers/graphql-go/example/starwars/introspect.json +++ b/vendor/github.com/graph-gophers/graphql-go/example/starwars/introspect.json @@ -1231,6 +1231,33 @@ "name": "String", "possibleTypes": null }, + { + "description": null, + "enumValues": null, + "fields": [ + { + "args": [], + "deprecationReason": null, + "description": null, + "isDeprecated": false, + "name": "sdl", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "SCALAR", + "name": "String", + "ofType": null + } + } + } + ], + "inputFields": null, + "interfaces": [], + "kind": "OBJECT", + "name": "_Service", + "possibleTypes": null + }, { "description": "A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.\n\nIn some cases, you need to provide options to alter GraphQL's execution behavior\nin ways field arguments will not suffice, such as conditionally including or\nskipping a field. Directives provide this by describing additional information\nto the executor.", "enumValues": null, diff --git a/vendor/github.com/graph-gophers/graphql-go/go.mod b/vendor/github.com/graph-gophers/graphql-go/go.mod index 2c814b0be..423043e84 100644 --- a/vendor/github.com/graph-gophers/graphql-go/go.mod +++ b/vendor/github.com/graph-gophers/graphql-go/go.mod @@ -1,5 +1,9 @@ module github.com/graph-gophers/graphql-go -require github.com/opentracing/opentracing-go v1.1.0 - go 1.13 + +require ( + github.com/opentracing/opentracing-go v1.2.0 + go.opentelemetry.io/otel v1.6.3 + go.opentelemetry.io/otel/trace v1.6.3 +) diff --git a/vendor/github.com/graph-gophers/graphql-go/go.sum b/vendor/github.com/graph-gophers/graphql-go/go.sum index 71fd021b0..b987a5d21 100644 --- a/vendor/github.com/graph-gophers/graphql-go/go.sum +++ b/vendor/github.com/graph-gophers/graphql-go/go.sum @@ -1,2 +1,27 @@ -github.com/opentracing/opentracing-go v1.1.0 h1:pWlfV3Bxv7k65HYwkikxat0+s3pV4bsqf19k25Ur8rU= -github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= +github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.2.3 h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0= +github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/google/go-cmp v0.5.7 h1:81/ik6ipDQS2aGcBfIN5dHDB36BwrStyeAQquSYCV4o= +github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= +github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs= +github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +go.opentelemetry.io/otel v1.6.3 h1:FLOfo8f9JzFVFVyU+MSRJc2HdEAXQgm7pIv2uFKRSZE= +go.opentelemetry.io/otel v1.6.3/go.mod h1:7BgNga5fNlF/iZjG06hM3yofffp0ofKCDwSXx1GC4dI= +go.opentelemetry.io/otel/trace v1.6.3 h1:IqN4L+5b0mPNjdXIiZ90Ni4Bl5BRkDQywePLWemd9bc= +go.opentelemetry.io/otel/trace v1.6.3/go.mod h1:GNJQusJlUgZl9/TQBPKU/Y/ty+0iVB5fjhKeJGZPGFs= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/vendor/github.com/graph-gophers/graphql-go/graphql.go b/vendor/github.com/graph-gophers/graphql-go/graphql.go index 76a6434d5..0758aa8bf 100644 --- a/vendor/github.com/graph-gophers/graphql-go/graphql.go +++ b/vendor/github.com/graph-gophers/graphql-go/graphql.go @@ -16,7 +16,8 @@ import ( "github.com/graph-gophers/graphql-go/internal/validation" "github.com/graph-gophers/graphql-go/introspection" "github.com/graph-gophers/graphql-go/log" - "github.com/graph-gophers/graphql-go/trace" + "github.com/graph-gophers/graphql-go/trace/noop" + "github.com/graph-gophers/graphql-go/trace/tracer" "github.com/graph-gophers/graphql-go/types" ) @@ -27,7 +28,7 @@ func ParseSchema(schemaString string, resolver interface{}, opts ...SchemaOpt) ( s := &Schema{ schema: schema.New(), maxParallelism: 10, - tracer: trace.OpenTracingTracer{}, + tracer: noop.Tracer{}, logger: &log.DefaultLogger{}, panicHandler: &errors.DefaultPanicHandler{}, } @@ -36,10 +37,10 @@ func ParseSchema(schemaString string, resolver interface{}, opts ...SchemaOpt) ( } if s.validationTracer == nil { - if tracer, ok := s.tracer.(trace.ValidationTracerContext); ok { - s.validationTracer = tracer + if t, ok := s.tracer.(tracer.ValidationTracer); ok { + s.validationTracer = t } else { - s.validationTracer = &validationBridgingTracer{tracer: trace.NoopValidationTracer{}} + s.validationTracer = &validationBridgingTracer{tracer: tracer.LegacyNoopValidationTracer{}} //nolint:staticcheck } } @@ -75,8 +76,8 @@ type Schema struct { maxDepth int maxParallelism int - tracer trace.Tracer - validationTracer trace.ValidationTracerContext + tracer tracer.Tracer + validationTracer tracer.ValidationTracer logger log.Logger panicHandler errors.PanicHandler useStringDescriptions bool @@ -122,16 +123,16 @@ func MaxParallelism(n int) SchemaOpt { } } -// Tracer is used to trace queries and fields. It defaults to trace.OpenTracingTracer. -func Tracer(tracer trace.Tracer) SchemaOpt { +// Tracer is used to trace queries and fields. It defaults to tracer.Noop. +func Tracer(t tracer.Tracer) SchemaOpt { return func(s *Schema) { - s.tracer = tracer + s.tracer = t } } -// ValidationTracer is used to trace validation errors. It defaults to trace.NoopValidationTracer. -// Deprecated: context is needed to support tracing correctly. Use a Tracer which implements trace.ValidationTracerContext. -func ValidationTracer(tracer trace.ValidationTracer) SchemaOpt { //nolint:staticcheck +// ValidationTracer is used to trace validation errors. It defaults to tracer.LegacyNoopValidationTracer. +// Deprecated: context is needed to support tracing correctly. Use a Tracer which implements tracer.ValidationTracer. +func ValidationTracer(tracer tracer.LegacyValidationTracer) SchemaOpt { //nolint:staticcheck return func(s *Schema) { s.validationTracer = &validationBridgingTracer{tracer: tracer} } @@ -296,10 +297,10 @@ func (s *Schema) validateSchema() error { } type validationBridgingTracer struct { - tracer trace.ValidationTracer //nolint:staticcheck + tracer tracer.LegacyValidationTracer //nolint:staticcheck } -func (t *validationBridgingTracer) TraceValidation(context.Context) trace.TraceValidationFinishFunc { +func (t *validationBridgingTracer) TraceValidation(context.Context) func([]*errors.QueryError) { return t.tracer.TraceValidation() } diff --git a/vendor/github.com/graph-gophers/graphql-go/internal/exec/exec.go b/vendor/github.com/graph-gophers/graphql-go/internal/exec/exec.go index 6b478487b..e9056c53e 100644 --- a/vendor/github.com/graph-gophers/graphql-go/internal/exec/exec.go +++ b/vendor/github.com/graph-gophers/graphql-go/internal/exec/exec.go @@ -14,14 +14,14 @@ import ( "github.com/graph-gophers/graphql-go/internal/exec/selected" "github.com/graph-gophers/graphql-go/internal/query" "github.com/graph-gophers/graphql-go/log" - "github.com/graph-gophers/graphql-go/trace" + "github.com/graph-gophers/graphql-go/trace/tracer" "github.com/graph-gophers/graphql-go/types" ) type Request struct { selected.Request Limiter chan struct{} - Tracer trace.Tracer + Tracer tracer.Tracer Logger log.Logger PanicHandler errors.PanicHandler SubscribeResolverTimeout time.Duration diff --git a/vendor/github.com/graph-gophers/graphql-go/internal/exec/resolvable/meta.go b/vendor/github.com/graph-gophers/graphql-go/internal/exec/resolvable/meta.go index 02d5e262f..aafe9acdf 100644 --- a/vendor/github.com/graph-gophers/graphql-go/internal/exec/resolvable/meta.go +++ b/vendor/github.com/graph-gophers/graphql-go/internal/exec/resolvable/meta.go @@ -12,8 +12,10 @@ type Meta struct { FieldSchema Field FieldType Field FieldTypename Field + FieldService Field Schema *Object Type *Object + Service *Object } func newMeta(s *types.Schema) *Meta { @@ -32,6 +34,12 @@ func newMeta(s *types.Schema) *Meta { panic(err) } + metaService := s.Types["_Service"].(*types.ObjectTypeDefinition) + sv, err := b.makeObjectExec(metaService.Name, metaService.Fields, nil, false, reflect.TypeOf(&introspection.Service{})) + if err != nil { + panic(err) + } + if err := b.finish(); err != nil { panic(err) } @@ -60,11 +68,21 @@ func newMeta(s *types.Schema) *Meta { TraceLabel: "GraphQL field: __type", } + fieldService := Field{ + FieldDefinition: types.FieldDefinition{ + Name: "_service", + Type: s.Types["_Service"], + }, + TraceLabel: "GraphQL field: _service", + } + return &Meta{ FieldSchema: fieldSchema, FieldTypename: fieldTypename, FieldType: fieldType, + FieldService: fieldService, Schema: so, Type: t, + Service: sv, } } diff --git a/vendor/github.com/graph-gophers/graphql-go/internal/exec/selected/selected.go b/vendor/github.com/graph-gophers/graphql-go/internal/exec/selected/selected.go index 9b96d2b62..868dc1e98 100644 --- a/vendor/github.com/graph-gophers/graphql-go/internal/exec/selected/selected.go +++ b/vendor/github.com/graph-gophers/graphql-go/internal/exec/selected/selected.go @@ -121,6 +121,17 @@ func applySelectionSet(r *Request, s *resolvable.Schema, e *resolvable.Object, s }) } + case "_service": + if !r.DisableIntrospection { + flattenedSels = append(flattenedSels, &SchemaField{ + Field: s.Meta.FieldService, + Alias: field.Alias.Name, + Sels: applySelectionSet(r, s, s.Meta.Service, field.SelectionSet), + Async: true, + FixedResult: reflect.ValueOf(introspection.WrapService(r.Schema)), + }) + } + default: fe := e.Fields[field.Name.Name] diff --git a/vendor/github.com/graph-gophers/graphql-go/internal/schema/meta.go b/vendor/github.com/graph-gophers/graphql-go/internal/schema/meta.go index 9f5bba56d..2268b7e75 100644 --- a/vendor/github.com/graph-gophers/graphql-go/internal/schema/meta.go +++ b/vendor/github.com/graph-gophers/graphql-go/internal/schema/meta.go @@ -200,4 +200,8 @@ var metaSrc = ` # Indicates this type is a non-null. ` + "`" + `ofType` + "`" + ` is a valid field. NON_NULL } + + type _Service { + sdl: String! + } ` diff --git a/vendor/github.com/graph-gophers/graphql-go/internal/schema/schema.go b/vendor/github.com/graph-gophers/graphql-go/internal/schema/schema.go index fb301c46b..da37fe1f4 100644 --- a/vendor/github.com/graph-gophers/graphql-go/internal/schema/schema.go +++ b/vendor/github.com/graph-gophers/graphql-go/internal/schema/schema.go @@ -161,6 +161,8 @@ func Parse(s *types.Schema, schemaString string, useStringDescriptions bool) err } } + s.SchemaString = schemaString + return nil } @@ -408,19 +410,19 @@ func parseObjectDef(l *common.Lexer) *types.ObjectTypeDefinition { continue } - if l.Peek() == scanner.Ident { - l.ConsumeKeyword("implements") + if l.Peek() != scanner.Ident { + break + } - for l.Peek() != '{' && l.Peek() != '@' { - if l.Peek() == '&' { - l.ConsumeToken('&') - } + l.ConsumeKeyword("implements") - object.InterfaceNames = append(object.InterfaceNames, l.ConsumeIdent()) + for l.Peek() != '{' && l.Peek() != '@' { + if l.Peek() == '&' { + l.ConsumeToken('&') } - continue - } + object.InterfaceNames = append(object.InterfaceNames, l.ConsumeIdent()) + } } l.ConsumeToken('{') object.Fields = parseFieldsDef(l) @@ -511,10 +513,21 @@ func parseDirectiveDef(l *common.Lexer) *types.DirectiveDefinition { l.ConsumeToken(')') } - l.ConsumeKeyword("on") + switch x := l.ConsumeIdent(); x { + case "on": + // no-op; Go doesn't fallthrough by default + case "repeatable": + d.Repeatable = true + l.ConsumeKeyword("on") + default: + l.SyntaxError(fmt.Sprintf(`unexpected %q, expecting "on" or "repeatable"`, x)) + } for { loc := l.ConsumeIdent() + if _, ok := legalDirectiveLocationNames[loc]; !ok { + l.SyntaxError(fmt.Sprintf("%q is not a legal directive location (options: %v)", loc, legalDirectiveLocationNames)) + } d.Locations = append(d.Locations, loc) if l.Peek() != '|' { break @@ -584,3 +597,25 @@ func parseFieldsDef(l *common.Lexer) types.FieldsDefinition { } return fields } + +var legalDirectiveLocationNames = map[string]struct{}{ + "SCHEMA": {}, + "SCALAR": {}, + "OBJECT": {}, + "FIELD_DEFINITION": {}, + "ARGUMENT_DEFINITION": {}, + "INTERFACE": {}, + "UNION": {}, + "ENUM": {}, + "ENUM_VALUE": {}, + "INPUT_OBJECT": {}, + "INPUT_FIELD_DEFINITION": {}, + "QUERY": {}, + "MUTATION": {}, + "SUBSCRIPTION": {}, + "FIELD": {}, + "FRAGMENT_DEFINITION": {}, + "FRAGMENT_SPREAD": {}, + "INLINE_FRAGMENT": {}, + "VARIABLE_DEFINITION": {}, +} diff --git a/vendor/github.com/graph-gophers/graphql-go/internal/validation/validation.go b/vendor/github.com/graph-gophers/graphql-go/internal/validation/validation.go index e36726388..0f07e3497 100644 --- a/vendor/github.com/graph-gophers/graphql-go/internal/validation/validation.go +++ b/vendor/github.com/graph-gophers/graphql-go/internal/validation/validation.go @@ -327,6 +327,11 @@ func validateSelection(c *opContext, sel types.Selection, t types.NamedType) { }, Type: c.schema.Types["__Type"], } + case "_service": + f = &types.FieldDefinition{ + Name: "_service", + Type: c.schema.Types["_Service"], + } default: f = fields(t).Get(fieldName) if f == nil && t != nil { diff --git a/vendor/github.com/graph-gophers/graphql-go/introspection/introspection.go b/vendor/github.com/graph-gophers/graphql-go/introspection/introspection.go index a0a2fa9bb..3df660554 100644 --- a/vendor/github.com/graph-gophers/graphql-go/introspection/introspection.go +++ b/vendor/github.com/graph-gophers/graphql-go/introspection/introspection.go @@ -310,3 +310,16 @@ func (r *Directive) Args() []*InputValue { } return l } + +type Service struct { + schema *types.Schema +} + +// WrapService is only used internally. +func WrapService(schema *types.Schema) *Service { + return &Service{schema} +} + +func (r *Service) SDL() string { + return r.schema.SchemaString +} diff --git a/vendor/github.com/graph-gophers/graphql-go/trace/noop/trace.go b/vendor/github.com/graph-gophers/graphql-go/trace/noop/trace.go new file mode 100644 index 000000000..c304c4f2b --- /dev/null +++ b/vendor/github.com/graph-gophers/graphql-go/trace/noop/trace.go @@ -0,0 +1,24 @@ +// Package noop defines a no-op tracer implementation. +package noop + +import ( + "context" + + "github.com/graph-gophers/graphql-go/errors" + "github.com/graph-gophers/graphql-go/introspection" +) + +// Tracer is a no-op tracer that does nothing. +type Tracer struct{} + +func (Tracer) TraceQuery(ctx context.Context, queryString string, operationName string, variables map[string]interface{}, varTypes map[string]*introspection.Type) (context.Context, func([]*errors.QueryError)) { + return ctx, func(errs []*errors.QueryError) {} +} + +func (Tracer) TraceField(ctx context.Context, label, typeName, fieldName string, trivial bool, args map[string]interface{}) (context.Context, func(*errors.QueryError)) { + return ctx, func(err *errors.QueryError) {} +} + +func (Tracer) TraceValidation(context.Context) func([]*errors.QueryError) { + return func(errs []*errors.QueryError) {} +} diff --git a/vendor/github.com/graph-gophers/graphql-go/trace/trace.go b/vendor/github.com/graph-gophers/graphql-go/trace/trace.go deleted file mode 100644 index 8d5d8a712..000000000 --- a/vendor/github.com/graph-gophers/graphql-go/trace/trace.go +++ /dev/null @@ -1,96 +0,0 @@ -package trace - -import ( - "context" - "fmt" - - "github.com/graph-gophers/graphql-go/errors" - "github.com/graph-gophers/graphql-go/introspection" - opentracing "github.com/opentracing/opentracing-go" - "github.com/opentracing/opentracing-go/ext" - "github.com/opentracing/opentracing-go/log" -) - -type TraceQueryFinishFunc func([]*errors.QueryError) -type TraceFieldFinishFunc func(*errors.QueryError) - -type Tracer interface { - TraceQuery(ctx context.Context, queryString string, operationName string, variables map[string]interface{}, varTypes map[string]*introspection.Type) (context.Context, TraceQueryFinishFunc) - TraceField(ctx context.Context, label, typeName, fieldName string, trivial bool, args map[string]interface{}) (context.Context, TraceFieldFinishFunc) -} - -type OpenTracingTracer struct{} - -func (OpenTracingTracer) TraceQuery(ctx context.Context, queryString string, operationName string, variables map[string]interface{}, varTypes map[string]*introspection.Type) (context.Context, TraceQueryFinishFunc) { - span, spanCtx := opentracing.StartSpanFromContext(ctx, "GraphQL request") - span.SetTag("graphql.query", queryString) - - if operationName != "" { - span.SetTag("graphql.operationName", operationName) - } - - if len(variables) != 0 { - span.LogFields(log.Object("graphql.variables", variables)) - } - - return spanCtx, func(errs []*errors.QueryError) { - if len(errs) > 0 { - msg := errs[0].Error() - if len(errs) > 1 { - msg += fmt.Sprintf(" (and %d more errors)", len(errs)-1) - } - ext.Error.Set(span, true) - span.SetTag("graphql.error", msg) - } - span.Finish() - } -} - -func (OpenTracingTracer) TraceField(ctx context.Context, label, typeName, fieldName string, trivial bool, args map[string]interface{}) (context.Context, TraceFieldFinishFunc) { - if trivial { - return ctx, noop - } - - span, spanCtx := opentracing.StartSpanFromContext(ctx, label) - span.SetTag("graphql.type", typeName) - span.SetTag("graphql.field", fieldName) - for name, value := range args { - span.SetTag("graphql.args."+name, value) - } - - return spanCtx, func(err *errors.QueryError) { - if err != nil { - ext.Error.Set(span, true) - span.SetTag("graphql.error", err.Error()) - } - span.Finish() - } -} - -func (OpenTracingTracer) TraceValidation(ctx context.Context) TraceValidationFinishFunc { - span, _ := opentracing.StartSpanFromContext(ctx, "Validate Query") - - return func(errs []*errors.QueryError) { - if len(errs) > 0 { - msg := errs[0].Error() - if len(errs) > 1 { - msg += fmt.Sprintf(" (and %d more errors)", len(errs)-1) - } - ext.Error.Set(span, true) - span.SetTag("graphql.error", msg) - } - span.Finish() - } -} - -func noop(*errors.QueryError) {} - -type NoopTracer struct{} - -func (NoopTracer) TraceQuery(ctx context.Context, queryString string, operationName string, variables map[string]interface{}, varTypes map[string]*introspection.Type) (context.Context, TraceQueryFinishFunc) { - return ctx, func(errs []*errors.QueryError) {} -} - -func (NoopTracer) TraceField(ctx context.Context, label, typeName, fieldName string, trivial bool, args map[string]interface{}) (context.Context, TraceFieldFinishFunc) { - return ctx, func(err *errors.QueryError) {} -} diff --git a/vendor/github.com/graph-gophers/graphql-go/trace/tracer/tracer.go b/vendor/github.com/graph-gophers/graphql-go/trace/tracer/tracer.go new file mode 100644 index 000000000..ddebc8b34 --- /dev/null +++ b/vendor/github.com/graph-gophers/graphql-go/trace/tracer/tracer.go @@ -0,0 +1,34 @@ +package tracer + +import ( + "context" + + "github.com/graph-gophers/graphql-go/errors" + "github.com/graph-gophers/graphql-go/introspection" +) + +type QueryFinishFunc = func([]*errors.QueryError) +type FieldFinishFunc = func(*errors.QueryError) +type ValidationFinishFunc = func([]*errors.QueryError) + +type Tracer interface { + TraceQuery(ctx context.Context, queryString string, operationName string, variables map[string]interface{}, varTypes map[string]*introspection.Type) (context.Context, QueryFinishFunc) + TraceField(ctx context.Context, label, typeName, fieldName string, trivial bool, args map[string]interface{}) (context.Context, FieldFinishFunc) +} + +type ValidationTracer interface { + TraceValidation(ctx context.Context) ValidationFinishFunc +} + +// Deprecated: use ValidationTracerContext instead. +type LegacyValidationTracer interface { + TraceValidation() func([]*errors.QueryError) +} + +// Deprecated: use a Tracer which implements ValidationTracerContext. +type LegacyNoopValidationTracer struct{} + +// Deprecated: use a Tracer which implements ValidationTracerContext. +func (LegacyNoopValidationTracer) TraceValidation() func([]*errors.QueryError) { + return func(errs []*errors.QueryError) {} +} diff --git a/vendor/github.com/graph-gophers/graphql-go/trace/validation_trace.go b/vendor/github.com/graph-gophers/graphql-go/trace/validation_trace.go deleted file mode 100644 index bce7a9a4f..000000000 --- a/vendor/github.com/graph-gophers/graphql-go/trace/validation_trace.go +++ /dev/null @@ -1,25 +0,0 @@ -package trace - -import ( - "context" - - "github.com/graph-gophers/graphql-go/errors" -) - -type TraceValidationFinishFunc = TraceQueryFinishFunc - -// Deprecated: use ValidationTracerContext. -type ValidationTracer interface { - TraceValidation() TraceValidationFinishFunc -} - -type ValidationTracerContext interface { - TraceValidation(ctx context.Context) TraceValidationFinishFunc -} - -type NoopValidationTracer struct{} - -// Deprecated: use a Tracer which implements ValidationTracerContext. -func (NoopValidationTracer) TraceValidation() TraceValidationFinishFunc { - return func(errs []*errors.QueryError) {} -} diff --git a/vendor/github.com/graph-gophers/graphql-go/types/directive.go b/vendor/github.com/graph-gophers/graphql-go/types/directive.go index 0f8a4b993..7b62d51e3 100644 --- a/vendor/github.com/graph-gophers/graphql-go/types/directive.go +++ b/vendor/github.com/graph-gophers/graphql-go/types/directive.go @@ -14,11 +14,12 @@ type Directive struct { // // http://spec.graphql.org/draft/#sec-Type-System.Directives type DirectiveDefinition struct { - Name string - Desc string - Locations []string - Arguments ArgumentsDefinition - Loc errors.Location + Name string + Desc string + Repeatable bool + Locations []string + Arguments ArgumentsDefinition + Loc errors.Location } type DirectiveList []*Directive diff --git a/vendor/github.com/graph-gophers/graphql-go/types/schema.go b/vendor/github.com/graph-gophers/graphql-go/types/schema.go index 06811a97f..349c112b0 100644 --- a/vendor/github.com/graph-gophers/graphql-go/types/schema.go +++ b/vendor/github.com/graph-gophers/graphql-go/types/schema.go @@ -35,6 +35,7 @@ type Schema struct { Unions []*Union Enums []*EnumTypeDefinition Extensions []*Extension + SchemaString string } func (s *Schema) Resolve(name string) Type { diff --git a/vendor/github.com/hasura/go-graphql-client/.gitignore b/vendor/github.com/hasura/go-graphql-client/.gitignore new file mode 100644 index 000000000..9f11b755a --- /dev/null +++ b/vendor/github.com/hasura/go-graphql-client/.gitignore @@ -0,0 +1 @@ +.idea/ diff --git a/vendor/github.com/hasura/go-graphql-client/README.md b/vendor/github.com/hasura/go-graphql-client/README.md index 96b88370c..9dadc9fa3 100644 --- a/vendor/github.com/hasura/go-graphql-client/README.md +++ b/vendor/github.com/hasura/go-graphql-client/README.md @@ -1,7 +1,7 @@ go-graphql-client ======= -[![Build Status](https://travis-ci.org/hasura/go-graphql-client.svg?branch=master)](https://travis-ci.org/hasura/go-graphql-client.svg?branch=master) [![GoDoc](https://godoc.org/github.com/hasura/go-graphql-client?status.svg)](https://pkg.go.dev/github.com/hasura/go-graphql-client) +[![Unit tests](https://github.com/hasura/go-graphql-client/actions/workflows/test.yml/badge.svg)](https://github.com/hasura/go-graphql-client/actions/workflows/test.yml) **Preface:** This is a fork of `https://github.com/shurcooL/graphql` with extended features (subscription client, named operation) @@ -13,6 +13,8 @@ For more information, see package [`github.com/shurcooL/githubv4`](https://githu **Status:** In active early research and development. The API will change when opportunities for improvement are discovered; it is not yet frozen. +**Note**: Before v0.8.0, `QueryRaw`, `MutateRaw` and `Subscribe` methods return `*json.RawMessage`. This output type is redundant to be decoded. From v0.8.0, the output type is changed to `[]byte`. + - [go-graphql-client](#go-graphql-client) - [Installation](#installation) - [Usage](#usage) @@ -20,27 +22,33 @@ For more information, see package [`github.com/shurcooL/githubv4`](https://githu - [Simple Query](#simple-query) - [Arguments and Variables](#arguments-and-variables) - [Custom scalar tag](#custom-scalar-tag) + - [Skip GraphQL field](#skip-graphql-field) - [Inline Fragments](#inline-fragments) + - [Specify GraphQL type name](#specify-graphql-type-name) - [Mutations](#mutations) - [Mutations Without Fields](#mutations-without-fields) - [Subscription](#subscription) - [Usage](#usage-1) - [Subscribe](#subscribe) + - [Stop the subscription](#stop-the-subscription) - [Authentication](#authentication-1) - [Options](#options) - [Events](#events) + - [Custom HTTP Client](#custom-http-client) - [Custom WebSocket client](#custom-websocket-client) - [Options](#options-1) + - [Execute pre-built query](#execute-pre-built-query) - [With operation name (deprecated)](#with-operation-name-deprecated) - [Raw bytes response](#raw-bytes-response) - [Multiple mutations with ordered map](#multiple-mutations-with-ordered-map) + - [Debugging and Unit test](#debugging-and-unit-test) - [Directories](#directories) - [References](#references) - [License](#license) ## Installation -`go-graphql-client` requires Go version 1.13 or later. +`go-graphql-client` requires Go version 1.16 or later. For older Go versions, downgrade the library version below v0.7.1. ```bash go get -u github.com/hasura/go-graphql-client @@ -91,7 +99,7 @@ You can define this variable: ```Go var query struct { Me struct { - Name graphql.String + Name string } } ``` @@ -128,8 +136,8 @@ You can define this variable: ```Go var q struct { Human struct { - Name graphql.String - Height graphql.Float `graphql:"height(unit: METER)"` + Name string + Height float64 `graphql:"height(unit: METER)"` } `graphql:"human(id: \"1000\")"` } ``` @@ -154,8 +162,8 @@ However, that'll only work if the arguments are constant and known in advance. O ```Go var q struct { Human struct { - Name graphql.String - Height graphql.Float `graphql:"height(unit: $unit)"` + Name string + Height float64 `graphql:"height(unit: $unit)"` } `graphql:"human(id: $id)"` } ``` @@ -215,6 +223,22 @@ struct { // { viewer } ``` +### Skip GraphQL field + +```go +struct { + Viewer struct { + ID interface{} `graphql:"-"` + Login string + CreatedAt time.Time `graphql:"-"` + DatabaseID int + } +} + +// Output +// {viewer{login,databaseId}} +``` + ### Inline Fragments Some GraphQL queries contain inline fragments. You can use the `graphql` struct field tag to express them. @@ -240,12 +264,12 @@ You can define this variable: ```Go var q struct { Hero struct { - Name graphql.String + Name string Droid struct { - PrimaryFunction graphql.String + PrimaryFunction string } `graphql:"... on Droid"` Human struct { - Height graphql.Float + Height float64 } `graphql:"... on Human"` } `graphql:"hero(episode: \"JEDI\")"` } @@ -256,16 +280,16 @@ Alternatively, you can define the struct types corresponding to inline fragments ```Go type ( DroidFragment struct { - PrimaryFunction graphql.String + PrimaryFunction string } HumanFragment struct { - Height graphql.Float + Height float64 } ) var q struct { Hero struct { - Name graphql.String + Name string DroidFragment `graphql:"... on Droid"` HumanFragment `graphql:"... on Human"` } `graphql:"hero(episode: \"JEDI\")"` @@ -289,6 +313,31 @@ fmt.Println(q.Hero.Height) // 0 ``` +### Specify GraphQL type name + +The GraphQL type is automatically inferred from Go type by reflection. However, it's cumbersome in some use cases, e.g lowercase names. In Go, a type name with a first lowercase letter is considered private. If we need to reuse it for other packages, there are 2 approaches: type alias or implement `GetGraphQLType` method. + +```go +type UserReviewInput struct { + Review string + UserID string +} + +// type alias +type user_review_input UserReviewInput +// or implement GetGraphQLType method +func (u UserReviewInput) GetGraphQLType() string { return "user_review_input" } + +variables := map[string]interface{}{ + "input": UserReviewInput{} +} + +//query arguments without GetGraphQLType() defined +//($input: UserReviewInput!) +//query arguments with GetGraphQLType() defined:w +//($input: user_review_input!) +``` + ### Mutations Mutations often require information that you can only find out by performing a query first. Let's suppose you've already done that. @@ -316,15 +365,15 @@ You can define: ```Go var m struct { CreateReview struct { - Stars graphql.Int - Commentary graphql.String + Stars int + Commentary string } `graphql:"createReview(episode: $ep, review: $review)"` } variables := map[string]interface{}{ "ep": starwars.Episode("JEDI"), "review": starwars.ReviewInput{ - Stars: graphql.Int(5), - Commentary: graphql.String("This is a great movie!"), + Stars: 5, + Commentary: "This is a great movie!", }, } ``` @@ -370,8 +419,8 @@ var m struct { variables := map[string]interface{}{ "ep": starwars.Episode("JEDI"), "review": starwars.ReviewInput{ - Stars: graphql.Int(5), - Commentary: graphql.String("This is a great movie!"), + Stars: 5, + Commentary: "This is a great movie!", }, } ``` @@ -424,7 +473,7 @@ You can define this variable: ```Go var subscription struct { Me struct { - Name graphql.String + Name string } } ``` @@ -432,7 +481,7 @@ var subscription struct { Then call `client.Subscribe`, passing a pointer to it: ```Go -subscriptionId, err := client.Subscribe(&query, nil, func(dataValue *json.RawMessage, errValue error) error { +subscriptionId, err := client.Subscribe(&query, nil, func(dataValue []byte, errValue error) error { if errValue != nil { // handle error // if returns error, it will failback to `onError` event @@ -444,13 +493,30 @@ subscriptionId, err := client.Subscribe(&query, nil, func(dataValue *json.RawMes fmt.Println(query.Me.Name) // Output: Luke Skywalker + return nil +}) + +if err != nil { + // Handle error. +} +``` + +#### Stop the subscription + +You can programmatically stop the subscription while the client is running by using the `Unsubscribe` method, or returning a special error to stop it in the callback. + +```Go +subscriptionId, err := client.Subscribe(&query, nil, func(dataValue []byte, errValue error) error { + // ... + // return this error to stop the subscription in the callback + return graphql.ErrSubscriptionStopped }) if err != nil { // Handle error. } -// you can unsubscribe the subscription while the client is running +// unsubscribe the subscription while the client is running with the subscription ID client.Unsubscribe(subscriptionId) ``` @@ -491,7 +557,7 @@ client. // OnConnected event is triggered when the websocket connected to GraphQL server sucessfully client.OnConnected(fn func()) -// OnDisconnected event is triggered when the websocket server was stil down after retry timeout +// OnDisconnected event is triggered when the websocket client was disconnected client.OnDisconnected(fn func()) // OnConnected event is triggered when there is any connection error. This is bottom exception handler level @@ -500,6 +566,19 @@ client.OnDisconnected(fn func()) client.OnError(onError func(sc *SubscriptionClient, err error) error) ``` +#### Custom HTTP Client + +Use `WithWebSocketOptions` to customize the HTTP client which is used by the subscription client. + +```go +client.WithWebSocketOptions(WebsocketOptions{ + HTTPClient: &http.Client{ + Transport: http.DefaultTransport, + Timeout: time.Minute, + } +}) +``` + #### Custom WebSocket client By default the subscription client uses [nhooyr WebSocket client](https://github.com/nhooyr/websocket). If you need to customize the client, or prefer using [Gorilla WebSocket](https://github.com/gorilla/websocket), let's follow the Websocket interface and replace the constructor with `WithWebSocket` method: @@ -601,6 +680,56 @@ func (cd cachedDirective) String() string { client.Query(ctx, &q, variables, graphql.OperationName("MyQuery"), cachedDirective{}) ``` +### Execute pre-built query + +The `Exec` function allows you to executing pre-built queries. While using reflection to build queries is convenient as you get some resemblance of type safety, it gets very cumbersome when you need to create queries semi-dynamically. For instance, imagine you are building a CLI tool to query data from a graphql endpoint and you want users to be able to narrow down the query by passing cli flags or something. + +```Go +// filters would be built dynamically somehow from the command line flags +filters := []string{ + `fieldA: {subfieldA: {_eq: "a"}}`, + `fieldB: {_eq: "b"}`, + ... +} + +query := "query{something(where: {" + strings.Join(filters, ", ") + "}){id}}" +res := struct { + Somethings []Something +}{} + +if err := client.Exec(ctx, query, &res, map[string]any{}); err != nil { + panic(err) +} + +subscription := "subscription{something(where: {" + strings.Join(filters, ", ") + "}){id}}" +subscriptionId, err := subscriptionClient.Exec(subscription, nil, func(dataValue []byte, errValue error) error { + if errValue != nil { + // handle error + // if returns error, it will failback to `onError` event + return nil + } + data := query{} + err := json.Unmarshal(dataValue, &data) + // ... +}) +``` + +If you prefer decoding JSON yourself, use `ExecRaw` instead. + +```Go +query := `query{something(where: { foo: { _eq: "bar" }}){id}}` +var res struct { + Somethings []Something `json:"something"` +} + +raw, err := client.ExecRaw(ctx, query, map[string]any{}) +if err != nil { + panic(err) +} + +err = json.Unmarshal(raw, &res) +``` + ### With operation name (deprecated) Operation name is still on API decision plan https://github.com/shurcooL/graphql/issues/12. However, in my opinion separate methods are easier choice to avoid breaking changes @@ -610,7 +739,7 @@ func (c *Client) NamedQuery(ctx context.Context, name string, q interface{}, var func (c *Client) NamedMutate(ctx context.Context, name string, q interface{}, variables map[string]interface{}) error -func (sc *SubscriptionClient) NamedSubscribe(name string, v interface{}, variables map[string]interface{}, handler func(message *json.RawMessage, err error) error) (string, error) +func (sc *SubscriptionClient) NamedSubscribe(name string, v interface{}, variables map[string]interface{}, handler func(message []byte, err error) error) (string, error) ``` ### Raw bytes response @@ -618,13 +747,13 @@ func (sc *SubscriptionClient) NamedSubscribe(name string, v interface{}, variabl In the case we developers want to decode JSON response ourself. Moreover, the default `UnmarshalGraphQL` function isn't ideal with complicated nested interfaces ```Go -func (c *Client) QueryRaw(ctx context.Context, q interface{}, variables map[string]interface{}) (*json.RawMessage, error) +func (c *Client) QueryRaw(ctx context.Context, q interface{}, variables map[string]interface{}) ([]byte, error) -func (c *Client) MutateRaw(ctx context.Context, q interface{}, variables map[string]interface{}) (*json.RawMessage, error) +func (c *Client) MutateRaw(ctx context.Context, q interface{}, variables map[string]interface{}) ([]byte, error) -func (c *Client) NamedQueryRaw(ctx context.Context, name string, q interface{}, variables map[string]interface{}) (*json.RawMessage, error) +func (c *Client) NamedQueryRaw(ctx context.Context, name string, q interface{}, variables map[string]interface{}) ([]byte, error) -func (c *Client) NamedMutateRaw(ctx context.Context, name string, q interface{}, variables map[string]interface{}) (*json.RawMessage, error) +func (c *Client) NamedMutateRaw(ctx context.Context, name string, q interface{}, variables map[string]interface{}) ([]byte, error) ``` ### Multiple mutations with ordered map @@ -651,7 +780,7 @@ You can define: ```Go type CreateUser struct { - Login graphql.String + Login string } m := [][2]interface{}{ {"createUser(login: $login1)", &CreateUser{}}, @@ -659,12 +788,65 @@ m := [][2]interface{}{ {"createUser(login: $login3)", &CreateUser{}}, } variables := map[string]interface{}{ - "login1": graphql.String("grihabor"), - "login2": graphql.String("diman"), - "login3": graphql.String("indigo"), + "login1": "grihabor", + "login2": "diman", + "login3": "indigo", +} +``` + +### Debugging and Unit test + +Enable debug mode with the `WithDebug` function. If the request is failed, the request and response information will be included in `extensions[].internal` property. + +```json +{ + "errors": [ + { + "message":"Field 'user' is missing required arguments: login", + "extensions": { + "internal": { + "request": { + "body":"{\"query\":\"{user{name}}\"}", + "headers": { + "Content-Type": ["application/json"] + } + }, + "response": { + "body":"{\"errors\": [{\"message\": \"Field 'user' is missing required arguments: login\",\"locations\": [{\"line\": 7,\"column\": 3}]}]}", + "headers": { + "Content-Type": ["application/json"] + } + } + } + }, + "locations": [ + { + "line":7, + "column":3 + } + ] + } + ] } ``` +Because the GraphQL query string is generated in runtime using reflection, it isn't really safe. To assure the GraphQL query is expected, it's necessary to write some unit test for query construction. + +```go +// ConstructQuery build GraphQL query string from struct and variables +func ConstructQuery(v interface{}, variables map[string]interface{}, options ...Option) (string, error) + +// ConstructQuery build GraphQL mutation string from struct and variables +func ConstructMutation(v interface{}, variables map[string]interface{}, options ...Option) (string, error) + +// ConstructSubscription build GraphQL subscription string from struct and variables +func ConstructSubscription(v interface{}, variables map[string]interface{}, options ...Option) (string, error) + +// UnmarshalGraphQL parses the JSON-encoded GraphQL response data and stores +// the result in the GraphQL query data structure pointed to by v. +func UnmarshalGraphQL(data []byte, v interface{}) error +``` + Directories ----------- diff --git a/vendor/github.com/hasura/go-graphql-client/doc.go b/vendor/github.com/hasura/go-graphql-client/doc.go index 69ec4e038..a2015327f 100644 --- a/vendor/github.com/hasura/go-graphql-client/doc.go +++ b/vendor/github.com/hasura/go-graphql-client/doc.go @@ -1,11 +1,9 @@ // Package graphql provides a GraphQL client implementation. // -// For more information, see package github.com/shurcooL/githubv4, -// which is a specialized version targeting GitHub GraphQL API v4. -// That package is driving the feature development. +// For more information, see package github.com/hasura/go-graphql-client // // Status: In active early research and development. The API will change when // opportunities for improvement are discovered; it is not yet frozen. // // For now, see README for more details. -package graphql // import "github.com/shurcooL/graphql" +package graphql diff --git a/vendor/github.com/hasura/go-graphql-client/go.mod b/vendor/github.com/hasura/go-graphql-client/go.mod index 3491aa5dc..426741df3 100644 --- a/vendor/github.com/hasura/go-graphql-client/go.mod +++ b/vendor/github.com/hasura/go-graphql-client/go.mod @@ -1,9 +1,10 @@ module github.com/hasura/go-graphql-client -go 1.14 +go 1.16 require ( github.com/google/uuid v1.3.0 - github.com/graph-gophers/graphql-go v1.2.0 + github.com/graph-gophers/graphql-go v1.4.0 + github.com/graph-gophers/graphql-transport-ws v0.0.2 nhooyr.io/websocket v1.8.7 ) diff --git a/vendor/github.com/hasura/go-graphql-client/go.sum b/vendor/github.com/hasura/go-graphql-client/go.sum index 195d0d255..011da91ce 100644 --- a/vendor/github.com/hasura/go-graphql-client/go.sum +++ b/vendor/github.com/hasura/go-graphql-client/go.sum @@ -5,7 +5,9 @@ github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= github.com/gin-gonic/gin v1.6.3 h1:ahKqKTFpO5KTPHxWZjEdPScmYaGtLo8Y4DMHoEsnp14= github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M= -github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= @@ -22,15 +24,18 @@ github.com/gobwas/ws v1.0.2/go.mod h1:szmBTxLgaFppYjEmNtny/v3w89xOydFnnZMcgRRu/E github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= github.com/golang/protobuf v1.3.5 h1:F768QJ1E9tib+q5Sc8MkdJi1RxLTbRcTf8LJV56aRls= github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= -github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.7 h1:81/ik6ipDQS2aGcBfIN5dHDB36BwrStyeAQquSYCV4o= +github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gorilla/websocket v1.4.1 h1:q7AeDBpnBk8AogcD4DSag/Ukw/KV+YhzLj2bP5HvKCM= github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= -github.com/graph-gophers/graphql-go v1.2.0 h1:j3tCG0UcE+3f84OAw/4/6YQKyTr+r0yuUKtnxiu5OH4= -github.com/graph-gophers/graphql-go v1.2.0/go.mod h1:9CQHMSxwO4MprSdzoIEobiHpoLtHm77vfxsvsIN5Vuc= +github.com/graph-gophers/graphql-go v1.4.0 h1:JE9wveRTSXwJyjdRd6bOQ7Ob5bewTUQ58Jv4OiVdpdE= +github.com/graph-gophers/graphql-go v1.4.0/go.mod h1:YtmJZDLbF1YYNrlNAuiO5zAStUWc3XZT07iGsVqe1Os= +github.com/graph-gophers/graphql-transport-ws v0.0.2 h1:DbmSkbIGzj8SvHei6n8Mh9eLQin8PtA8xY9eCzjRpvo= +github.com/graph-gophers/graphql-transport-ws v0.0.2/go.mod h1:5BVKvFzOd2BalVIBFfnfmHjpJi/MZ5rOj8G55mXvZ8g= github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns= github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/klauspost/compress v1.10.3 h1:OP96hzwJVBIHYU52pVTI6CczrxPvrGfgqF9N5eTO0Q8= @@ -43,18 +48,21 @@ github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OH github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/opentracing/opentracing-go v1.1.0 h1:pWlfV3Bxv7k65HYwkikxat0+s3pV4bsqf19k25Ur8rU= -github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= +github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo= github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs= github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= +go.opentelemetry.io/otel v1.6.3/go.mod h1:7BgNga5fNlF/iZjG06hM3yofffp0ofKCDwSXx1GC4dI= +go.opentelemetry.io/otel/trace v1.6.3/go.mod h1:GNJQusJlUgZl9/TQBPKU/Y/ty+0iVB5fjhKeJGZPGFs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42 h1:vEOn+mP2zCOVzKckCZy6YsCtDblrpj/w7B9nxGNELpg= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= @@ -62,10 +70,11 @@ golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxb golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= nhooyr.io/websocket v1.8.7 h1:usjR2uOr/zjjkVMy0lW+PPohFok7PCow5sDjLgX4P4g= nhooyr.io/websocket v1.8.7/go.mod h1:B70DZP8IakI65RVQ51MsWP/8jndNma26DVA/nFSCgW0= diff --git a/vendor/github.com/hasura/go-graphql-client/graphql.go b/vendor/github.com/hasura/go-graphql-client/graphql.go index 2bfea639e..ae863ded8 100644 --- a/vendor/github.com/hasura/go-graphql-client/graphql.go +++ b/vendor/github.com/hasura/go-graphql-client/graphql.go @@ -6,6 +6,7 @@ import ( "context" "encoding/json" "fmt" + "io" "io/ioutil" "net/http" "strings" @@ -22,6 +23,7 @@ type Client struct { url string // GraphQL server URL. httpClient *http.Client requestModifier RequestModifier + debug bool } // NewClient creates a GraphQL client targeting the specified GraphQL server URL. @@ -69,13 +71,13 @@ func (c *Client) NamedMutate(ctx context.Context, name string, m interface{}, va // with a query derived from q, populating the response into it. // q should be a pointer to struct that corresponds to the GraphQL schema. // return raw bytes message. -func (c *Client) QueryRaw(ctx context.Context, q interface{}, variables map[string]interface{}, options ...Option) (*json.RawMessage, error) { +func (c *Client) QueryRaw(ctx context.Context, q interface{}, variables map[string]interface{}, options ...Option) ([]byte, error) { return c.doRaw(ctx, queryOperation, q, variables, options...) } // NamedQueryRaw executes a single GraphQL query request, with operation name // return raw bytes message. -func (c *Client) NamedQueryRaw(ctx context.Context, name string, q interface{}, variables map[string]interface{}, options ...Option) (*json.RawMessage, error) { +func (c *Client) NamedQueryRaw(ctx context.Context, name string, q interface{}, variables map[string]interface{}, options ...Option) ([]byte, error) { return c.doRaw(ctx, queryOperation, q, variables, append(options, OperationName(name))...) } @@ -83,32 +85,36 @@ func (c *Client) NamedQueryRaw(ctx context.Context, name string, q interface{}, // with a mutation derived from m, populating the response into it. // m should be a pointer to struct that corresponds to the GraphQL schema. // return raw bytes message. -func (c *Client) MutateRaw(ctx context.Context, m interface{}, variables map[string]interface{}, options ...Option) (*json.RawMessage, error) { +func (c *Client) MutateRaw(ctx context.Context, m interface{}, variables map[string]interface{}, options ...Option) ([]byte, error) { return c.doRaw(ctx, mutationOperation, m, variables, options...) } // NamedMutateRaw executes a single GraphQL mutation request, with operation name // return raw bytes message. -func (c *Client) NamedMutateRaw(ctx context.Context, name string, m interface{}, variables map[string]interface{}, options ...Option) (*json.RawMessage, error) { +func (c *Client) NamedMutateRaw(ctx context.Context, name string, m interface{}, variables map[string]interface{}, options ...Option) ([]byte, error) { return c.doRaw(ctx, mutationOperation, m, variables, append(options, OperationName(name))...) } -// do executes a single GraphQL operation. -// return raw message and error -func (c *Client) doRaw(ctx context.Context, op operationType, v interface{}, variables map[string]interface{}, options ...Option) (*json.RawMessage, error) { +// buildAndRequest the common method that builds and send graphql request +func (c *Client) buildAndRequest(ctx context.Context, op operationType, v interface{}, variables map[string]interface{}, options ...Option) ([]byte, *http.Response, io.Reader, Errors) { var query string var err error switch op { case queryOperation: - query, err = constructQuery(v, variables, options...) + query, err = ConstructQuery(v, variables, options...) case mutationOperation: - query, err = constructMutation(v, variables, options...) + query, err = ConstructMutation(v, variables, options...) } if err != nil { - return nil, err + return nil, nil, nil, Errors{newError(ErrGraphQLEncode, err)} } + return c.request(ctx, query, variables, options...) +} + +// Request the common method that send graphql request +func (c *Client) request(ctx context.Context, query string, variables map[string]interface{}, options ...Option) ([]byte, *http.Response, io.Reader, Errors) { in := struct { Query string `json:"query"` Variables map[string]interface{} `json:"variables,omitempty"` @@ -117,14 +123,19 @@ func (c *Client) doRaw(ctx context.Context, op operationType, v interface{}, var Variables: variables, } var buf bytes.Buffer - err = json.NewEncoder(&buf).Encode(in) + err := json.NewEncoder(&buf).Encode(in) if err != nil { - return nil, err + return nil, nil, nil, Errors{newError(ErrGraphQLEncode, err)} } - request, err := http.NewRequestWithContext(ctx, http.MethodPost, c.url, &buf) + reqReader := bytes.NewReader(buf.Bytes()) + request, err := http.NewRequestWithContext(ctx, http.MethodPost, c.url, reqReader) if err != nil { - return nil, fmt.Errorf("problem constructing request: %w", err) + e := newError(ErrRequestError, fmt.Errorf("problem constructing request: %w", err)) + if c.debug { + e = e.withRequest(request, reqReader) + } + return nil, nil, nil, Errors{e} } request.Header.Add("Content-Type", "application/json") @@ -133,113 +144,144 @@ func (c *Client) doRaw(ctx context.Context, op operationType, v interface{}, var } resp, err := c.httpClient.Do(request) + + if c.debug { + reqReader.Seek(0, io.SeekStart) + } + if err != nil { - return nil, err + e := newError(ErrRequestError, err) + if c.debug { + e = e.withRequest(request, reqReader) + } + return nil, nil, nil, Errors{e} } defer resp.Body.Close() + + r := resp.Body + + if resp.Header.Get("Content-Encoding") == "gzip" { + gr, err := gzip.NewReader(r) + if err != nil { + return nil, nil, nil, Errors{newError(ErrJsonDecode, fmt.Errorf("problem trying to create gzip reader: %w", err))} + } + defer gr.Close() + r = gr + } + if resp.StatusCode != http.StatusOK { body, _ := ioutil.ReadAll(resp.Body) - return nil, fmt.Errorf("non-200 OK status code: %v body: %q", resp.Status, body) + err := newError(ErrRequestError, fmt.Errorf("%v; body: %q", resp.Status, body)) + + if c.debug { + err = err.withRequest(request, reqReader) + } + return nil, nil, nil, Errors{err} } + var out struct { Data *json.RawMessage Errors Errors } - err = json.NewDecoder(resp.Body).Decode(&out) - if err != nil { - // TODO: Consider including response body in returned error, if deemed helpful. - return nil, err - } - if len(out.Errors) > 0 { - return out.Data, out.Errors + // copy the response reader for debugging + var respReader *bytes.Reader + if c.debug { + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, nil, nil, Errors{newError(ErrJsonDecode, err)} + } + respReader = bytes.NewReader(body) + r = io.NopCloser(respReader) } - return out.Data, nil -} + err = json.NewDecoder(r).Decode(&out) -// do executes a single GraphQL operation and unmarshal json. -func (c *Client) do(ctx context.Context, op operationType, v interface{}, variables map[string]interface{}, options ...Option) error { - var query string - var err error - switch op { - case queryOperation: - query, err = constructQuery(v, variables, options...) - case mutationOperation: - query, err = constructMutation(v, variables, options...) + if c.debug { + respReader.Seek(0, io.SeekStart) } if err != nil { - return err + we := newError(ErrJsonDecode, err) + if c.debug { + we = we.withRequest(request, reqReader). + withResponse(resp, respReader) + } + return nil, nil, nil, Errors{we} } - in := struct { - Query string `json:"query"` - Variables map[string]interface{} `json:"variables,omitempty"` - }{ - Query: query, - Variables: variables, - } - var buf bytes.Buffer - err = json.NewEncoder(&buf).Encode(in) - if err != nil { - return err + var rawData []byte + if out.Data != nil && len(*out.Data) > 0 { + rawData = []byte(*out.Data) } - request, err := http.NewRequestWithContext(ctx, http.MethodPost, c.url, &buf) - if err != nil { - return fmt.Errorf("problem constructing request: %w", err) - } - request.Header.Add("Content-Type", "application/json") + if len(out.Errors) > 0 { + if c.debug && (out.Errors[0].Extensions == nil || out.Errors[0].Extensions["request"] == nil) { + out.Errors[0] = out.Errors[0]. + withRequest(request, reqReader). + withResponse(resp, respReader) + } - if c.requestModifier != nil { - c.requestModifier(request) + return rawData, resp, respReader, out.Errors } - resp, err := c.httpClient.Do(request) - if err != nil { - return err - } - defer resp.Body.Close() + return rawData, resp, respReader, nil +} - r := resp.Body - if resp.Header.Get("Content-Encoding") == "gzip" { - r, err = gzip.NewReader(r) - if err != nil { - return fmt.Errorf("problem trying to create gzip reader: %w", err) - } - defer r.Close() +// do executes a single GraphQL operation. +// return raw message and error +func (c *Client) doRaw(ctx context.Context, op operationType, v interface{}, variables map[string]interface{}, options ...Option) ([]byte, error) { + data, _, _, err := c.buildAndRequest(ctx, op, v, variables, options...) + if len(err) > 0 { + return data, err } + return data, nil +} - if resp.StatusCode != http.StatusOK { - body, _ := ioutil.ReadAll(r) - return fmt.Errorf("non-200 OK status code: %v body: %q", resp.Status, body) - } - var out struct { - Data *json.RawMessage - Errors Errors - } +// do executes a single GraphQL operation and unmarshal json. +func (c *Client) do(ctx context.Context, op operationType, v interface{}, variables map[string]interface{}, options ...Option) error { + data, resp, respBuf, errs := c.buildAndRequest(ctx, op, v, variables, options...) + return c.processResponse(v, data, resp, respBuf, errs) +} - err = json.NewDecoder(r).Decode(&out) - if err != nil { - // TODO: Consider including response body in returned error, if deemed helpful. - return err +// Executes a pre-built query and unmarshals the response into v. Unlike the Query method you have to specify in the query the +// fields that you want to receive as they are not inferred from v. This method is useful if you need to build the query dynamically. +func (c *Client) Exec(ctx context.Context, query string, v interface{}, variables map[string]interface{}, options ...Option) error { + data, resp, respBuf, errs := c.request(ctx, query, variables, options...) + return c.processResponse(v, data, resp, respBuf, errs) +} + +// Executes a pre-built query and returns the raw json message. Unlike the Query method you have to specify in the query the +// fields that you want to receive as they are not inferred from the interface. This method is useful if you need to build the query dynamically. +func (c *Client) ExecRaw(ctx context.Context, query string, variables map[string]interface{}, options ...Option) ([]byte, error) { + data, _, _, errs := c.request(ctx, query, variables, options...) + if len(errs) > 0 { + return data, errs } - if out.Data != nil { - err := jsonutil.UnmarshalGraphQL(*out.Data, v) + return data, nil +} + +func (c *Client) processResponse(v interface{}, data []byte, resp *http.Response, respBuf io.Reader, errs Errors) error { + if len(data) > 0 { + err := jsonutil.UnmarshalGraphQL(data, v) if err != nil { - // TODO: Consider including response body in returned error, if deemed helpful. - return err + we := newError(ErrGraphQLDecode, err) + if c.debug { + we = we.withResponse(resp, respBuf) + } + errs = append(errs, we) } } - if len(out.Errors) > 0 { - return out.Errors + + if len(errs) > 0 { + return errs } + return nil } // Returns a copy of the client with the request modifier set. This allows you to reuse the same -// TCP connection for multiple slghtly different requests to the same server +// TCP connection for multiple slightly different requests to the same server // (i.e. different authentication headers for multitenant applications) func (c *Client) WithRequestModifier(f RequestModifier) *Client { return &Client{ @@ -249,32 +291,121 @@ func (c *Client) WithRequestModifier(f RequestModifier) *Client { } } +// WithDebug enable debug mode to print internal error detail +func (c *Client) WithDebug(debug bool) *Client { + return &Client{ + url: c.url, + httpClient: c.httpClient, + requestModifier: c.requestModifier, + debug: debug, + } +} + // errors represents the "errors" array in a response from a GraphQL server. // If returned via error interface, the slice is expected to contain at least 1 element. // // Specification: https://facebook.github.io/graphql/#sec-Errors. -type Errors []struct { - Message string - Extensions map[string]interface{} +type Errors []Error + +type Error struct { + Message string `json:"message"` + Extensions map[string]interface{} `json:"extensions"` Locations []struct { - Line int - Column int - } + Line int `json:"line"` + Column int `json:"column"` + } `json:"locations"` +} + +// Error implements error interface. +func (e Error) Error() string { + return fmt.Sprintf("Message: %s, Locations: %+v", e.Message, e.Locations) } // Error implements error interface. func (e Errors) Error() string { b := strings.Builder{} for _, err := range e { - b.WriteString(fmt.Sprintf("Message: %s, Locations: %+v", err.Message, err.Locations)) + b.WriteString(err.Error()) } return b.String() } +func (e Error) getInternalExtension() map[string]interface{} { + if e.Extensions == nil { + return make(map[string]interface{}) + } + + if ex, ok := e.Extensions["internal"]; ok { + return ex.(map[string]interface{}) + } + + return make(map[string]interface{}) +} + +func newError(code string, err error) Error { + return Error{ + Message: err.Error(), + Extensions: map[string]interface{}{ + "code": code, + }, + } +} + +func (e Error) withRequest(req *http.Request, bodyReader io.Reader) Error { + internal := e.getInternalExtension() + bodyBytes, err := ioutil.ReadAll(bodyReader) + if err != nil { + internal["error"] = err + } else { + internal["request"] = map[string]interface{}{ + "headers": req.Header, + "body": string(bodyBytes), + } + } + + if e.Extensions == nil { + e.Extensions = make(map[string]interface{}) + } + e.Extensions["internal"] = internal + return e +} + +func (e Error) withResponse(res *http.Response, bodyReader io.Reader) Error { + internal := e.getInternalExtension() + bodyBytes, err := ioutil.ReadAll(bodyReader) + if err != nil { + internal["error"] = err + } else { + internal["response"] = map[string]interface{}{ + "headers": res.Header, + "body": string(bodyBytes), + } + } + + e.Extensions["internal"] = internal + return e +} + +// UnmarshalGraphQL parses the JSON-encoded GraphQL response data and stores +// the result in the GraphQL query data structure pointed to by v. +// +// The implementation is created on top of the JSON tokenizer available +// in "encoding/json".Decoder. +// This function is re-exported from the internal package +func UnmarshalGraphQL(data []byte, v interface{}) error { + return jsonutil.UnmarshalGraphQL(data, v) +} + type operationType uint8 const ( queryOperation operationType = iota mutationOperation // subscriptionOperation // Unused. + + ErrRequestError = "request_error" + ErrJsonEncode = "json_encode_error" + ErrJsonDecode = "json_decode_error" + ErrGraphQLEncode = "graphql_encode_error" + ErrGraphQLDecode = "graphql_decode_error" ) diff --git a/vendor/github.com/hasura/go-graphql-client/query.go b/vendor/github.com/hasura/go-graphql-client/query.go index 84d60b846..5c862a93c 100644 --- a/vendor/github.com/hasura/go-graphql-client/query.go +++ b/vendor/github.com/hasura/go-graphql-client/query.go @@ -43,8 +43,12 @@ func constructOptions(options []Option) (*constructOptionsOutput, error) { return output, nil } -func constructQuery(v interface{}, variables map[string]interface{}, options ...Option) (string, error) { - query := query(v) +// ConstructQuery build GraphQL query string from struct and variables +func ConstructQuery(v interface{}, variables map[string]interface{}, options ...Option) (string, error) { + query, err := query(v) + if err != nil { + return "", err + } optionsOutput, err := constructOptions(options) if err != nil { @@ -62,8 +66,12 @@ func constructQuery(v interface{}, variables map[string]interface{}, options ... return fmt.Sprintf("query %s%s%s", optionsOutput.operationName, optionsOutput.OperationDirectivesString(), query), nil } -func constructMutation(v interface{}, variables map[string]interface{}, options ...Option) (string, error) { - query := query(v) +// ConstructQuery build GraphQL mutation string from struct and variables +func ConstructMutation(v interface{}, variables map[string]interface{}, options ...Option) (string, error) { + query, err := query(v) + if err != nil { + return "", err + } optionsOutput, err := constructOptions(options) if err != nil { return "", err @@ -79,8 +87,12 @@ func constructMutation(v interface{}, variables map[string]interface{}, options return fmt.Sprintf("mutation %s%s%s", optionsOutput.operationName, optionsOutput.OperationDirectivesString(), query), nil } -func constructSubscription(v interface{}, variables map[string]interface{}, options ...Option) (string, error) { - query := query(v) +// ConstructSubscription build GraphQL subscription string from struct and variables +func ConstructSubscription(v interface{}, variables map[string]interface{}, options ...Option) (string, error) { + query, err := query(v) + if err != nil { + return "", err + } optionsOutput, err := constructOptions(options) if err != nil { return "", err @@ -96,7 +108,7 @@ func constructSubscription(v interface{}, variables map[string]interface{}, opti // queryArguments constructs a minified arguments string for variables. // -// E.g., map[string]interface{}{"a": Int(123), "b": NewBoolean(true)} -> "$a:Int!$b:Boolean". +// E.g., map[string]interface{}{"a": int(123), "b": true} -> "$a:Int!$b:Boolean!". func queryArguments(variables map[string]interface{}) string { // Sort keys in order to produce deterministic output for testing purposes. // TODO: If tests can be made to work with non-deterministic output, then no need to sort. @@ -129,19 +141,37 @@ func writeArgumentType(w io.Writer, t reflect.Type, value bool) { return } + if t.Implements(graphqlTypeInterface) { + graphqlType, ok := reflect.Zero(t).Interface().(GraphQLType) + if ok { + io.WriteString(w, graphqlType.GetGraphQLType()) + if value { + // Value is a required type, so add "!" to the end. + io.WriteString(w, "!") + } + return + } + } + switch t.Kind() { case reflect.Slice, reflect.Array: // List. E.g., "[Int]". io.WriteString(w, "[") writeArgumentType(w, t.Elem(), true) 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") + case reflect.Float32, reflect.Float64: + io.WriteString(w, "Float") + case reflect.Bool: + io.WriteString(w, "Boolean") default: - // Named type. E.g., "Int". - name := t.Name() - if name == "string" { // HACK: Workaround for https://github.com/shurcooL/githubv4/issues/12. - name = "ID" + n := t.Name() + if n == "string" { + n = "String" } - io.WriteString(w, name) + io.WriteString(w, n) } if value { @@ -153,33 +183,49 @@ func writeArgumentType(w io.Writer, t reflect.Type, value bool) { // query uses writeQuery to recursively construct // a minified query string from the provided struct v. // -// E.g., struct{Foo Int, BarBaz *Boolean} -> "{foo,barBaz}". -func query(v interface{}) string { +// E.g., struct{Foo Int, BarBaz *bool} -> "{foo,barBaz}". +func query(v interface{}) (string, error) { var buf bytes.Buffer - writeQuery(&buf, reflect.TypeOf(v), reflect.ValueOf(v), false) - return buf.String() + err := writeQuery(&buf, reflect.TypeOf(v), reflect.ValueOf(v), false) + if err != nil { + return "", fmt.Errorf("failed to write query: %w", err) + } + return buf.String(), nil } // writeQuery writes a minified query for t to w. // If inline is true, the struct fields of t are inlined into parent struct. -func writeQuery(w io.Writer, t reflect.Type, v reflect.Value, inline bool) { +func writeQuery(w io.Writer, t reflect.Type, v reflect.Value, inline bool) error { switch t.Kind() { case reflect.Ptr: - writeQuery(w, t.Elem(), ElemSafe(v), false) + err := writeQuery(w, t.Elem(), ElemSafe(v), false) + if err != nil { + return fmt.Errorf("failed to write query for ptr `%v`: %w", t, err) + } case reflect.Struct: // If the type implements json.Unmarshaler, it's a scalar. Don't expand it. if reflect.PtrTo(t).Implements(jsonUnmarshaler) { - return + return nil + } + if t.AssignableTo(idType) { + return nil } if !inline { io.WriteString(w, "{") } + iter := 0 for i := 0; i < t.NumField(); i++ { - if i != 0 { - io.WriteString(w, ",") - } f := t.Field(i) value, ok := f.Tag.Lookup("graphql") + // Skip this field if the tag value is hyphen + if value == "-" { + continue + } + if iter != 0 { + io.WriteString(w, ",") + } + iter++ + inlineField := f.Anonymous && !ok if !inlineField { if ok { @@ -192,20 +238,25 @@ func writeQuery(w io.Writer, t reflect.Type, v reflect.Value, inline bool) { if isTrue(f.Tag.Get("scalar")) { continue } - writeQuery(w, f.Type, FieldSafe(v, i), inlineField) + err := writeQuery(w, f.Type, FieldSafe(v, i), inlineField) + if err != nil { + return fmt.Errorf("failed to write query for struct field `%v`: %w", f.Name, err) + } } if !inline { io.WriteString(w, "}") } case reflect.Slice: if t.Elem().Kind() != reflect.Array { - writeQuery(w, t.Elem(), IndexSafe(v, 0), false) - return + err := writeQuery(w, t.Elem(), IndexSafe(v, 0), false) + if err != nil { + return fmt.Errorf("failed to write query for slice item `%v`: %w", t, err) + } + return nil } // handle [][2]interface{} like an ordered map if t.Elem().Len() != 2 { - err := fmt.Errorf("only arrays of len 2 are supported, got %v", t.Elem()) - panic(err.Error()) + return fmt.Errorf("only arrays of len 2 are supported, got %v", t.Elem()) } sliceOfPairs := v _, _ = io.WriteString(w, "{") @@ -214,14 +265,22 @@ func writeQuery(w io.Writer, t reflect.Type, v reflect.Value, inline bool) { // it.Value() returns interface{}, so we need to use reflect.ValueOf // to cast it away key, val := pair.Index(0), reflect.ValueOf(pair.Index(1).Interface()) - _, _ = io.WriteString(w, key.Interface().(string)) - writeQuery(w, val.Type(), val, false) + keyString, ok := key.Interface().(string) + if !ok { + return fmt.Errorf("expected pair (string, %v), got (%v, %v)", + val.Type(), key.Type(), val.Type()) + } + _, _ = io.WriteString(w, keyString) + err := writeQuery(w, val.Type(), val, false) + if err != nil { + return fmt.Errorf("failed to write query for pair[1] `%v`: %w", val.Type(), err) + } } _, _ = io.WriteString(w, "}") case reflect.Map: - err := fmt.Errorf("type %v is not supported, use [][2]interface{} instead", t) - panic(err.Error()) + return fmt.Errorf("type %v is not supported, use [][2]interface{} instead", t) } + return nil } func IndexSafe(v reflect.Value, i int) reflect.Value { @@ -246,6 +305,8 @@ func FieldSafe(valStruct reflect.Value, i int) reflect.Value { } var jsonUnmarshaler = reflect.TypeOf((*json.Unmarshaler)(nil)).Elem() +var idType = reflect.TypeOf(ID("")) +var graphqlTypeInterface = reflect.TypeOf((*GraphQLType)(nil)).Elem() func isTrue(s string) bool { b, _ := strconv.ParseBool(s) diff --git a/vendor/github.com/hasura/go-graphql-client/scalar.go b/vendor/github.com/hasura/go-graphql-client/scalar.go index 0f7ceea5e..ffd8363da 100644 --- a/vendor/github.com/hasura/go-graphql-client/scalar.go +++ b/vendor/github.com/hasura/go-graphql-client/scalar.go @@ -1,51 +1,78 @@ package graphql -// Note: These custom types are meant to be used in queries for now. -// But the plan is to switch to using native Go types (string, int, bool, time.Time, etc.). -// See https://github.com/shurcooL/githubv4/issues/9 for details. -// -// These custom types currently provide documentation, and their use -// is required for sending outbound queries. However, native Go types -// can be used for unmarshaling. Once https://github.com/shurcooL/githubv4/issues/9 -// is resolved, native Go types can completely replace these. +import ( + "fmt" + "reflect" +) + +// Note: These custom types are kept for backwards compatability. Native +// types for queries and responses are supported, with the exception of the ID. type ( // Boolean represents true or false values. + // Deprecated. Boolean bool // Float represents signed double-precision fractional values as // specified by IEEE 754. + // Deprecated. Float float64 - // ID represents a unique identifier that is Base64 obfuscated. It - // is often used to refetch an object or as key for a cache. The ID - // type appears in a JSON response as a String; however, it is not - // intended to be human-readable. When expected as an input type, - // any string (such as "VXNlci0xMA==") or integer (such as 4) input - // value will be accepted as an ID. - ID interface{} - // Int represents non-fractional signed whole numeric values. // Int can represent values between -(2^31) and 2^31 - 1. + // Deprecated. Int int32 // String represents textual data as UTF-8 character sequences. // This type is most often used by GraphQL to represent free-form // human-readable text. + // Deprecated. String string ) +// ID represents a unique identifier that is Base64 obfuscated. It +// is often used to refetch an object or as key for a cache. The ID +// type appears in a JSON response as a String; however, it is not +// intended to be human-readable. When expected as an input type, +// any string (such as "VXNlci0xMA==") or integer (such as 4) input +// value will be accepted as an ID. +type ID string + // NewBoolean is a helper to make a new *Boolean. +// Deprecated. func NewBoolean(v Boolean) *Boolean { return &v } // NewFloat is a helper to make a new *Float. +// Deprecated. func NewFloat(v Float) *Float { return &v } // NewID is a helper to make a new *ID. -func NewID(v ID) *ID { return &v } +func NewID(v interface{}) *ID { + rv := ToID(v) + return &rv +} + +// ToID is a helper for if you need to get the string version of an integer or +// a string for the id. +func ToID(v interface{}) ID { + var s string + switch reflect.TypeOf(v).Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + s = fmt.Sprintf("%d", v) + if s == "0" { + s = "" + } + case reflect.String: + s = v.(string) + } + return ID(s) +} // NewInt is a helper to make a new *Int. +// Deprecated. func NewInt(v Int) *Int { return &v } // NewString is a helper to make a new *String. +// Deprecated. func NewString(v String) *String { return &v } diff --git a/vendor/github.com/hasura/go-graphql-client/subscription.go b/vendor/github.com/hasura/go-graphql-client/subscription.go index 6c35e0d43..67350dd32 100644 --- a/vendor/github.com/hasura/go-graphql-client/subscription.go +++ b/vendor/github.com/hasura/go-graphql-client/subscription.go @@ -3,8 +3,10 @@ package graphql import ( "context" "encoding/json" + "errors" "fmt" "io" + "net/http" "strings" "sync" "sync/atomic" @@ -49,6 +51,10 @@ const ( GQL_INTERNAL OperationMessageType = "internal" ) +// ErrSubscriptionStopped a special error which forces the subscription stop +var ErrSubscriptionStopped = errors.New("subscription stopped") + +// OperationMessage represents a subscription operation message type OperationMessage struct { ID string `json:"id,omitempty"` Type OperationMessageType `json:"type"` @@ -74,11 +80,11 @@ type WebsocketConn interface { SetReadLimit(limit int64) } -type handlerFunc func(data *json.RawMessage, err error) error +type handlerFunc func(data []byte, err error) error type subscription struct { query string variables map[string]interface{} - handler func(data *json.RawMessage, err error) + handler func(data []byte, err error) started Boolean } @@ -87,6 +93,7 @@ type SubscriptionClient struct { url string conn WebsocketConn connectionParams map[string]interface{} + websocketOptions WebsocketOptions context context.Context subscriptions map[string]*subscription cancel context.CancelFunc @@ -138,6 +145,12 @@ func (sc *SubscriptionClient) WithWebSocket(fn func(sc *SubscriptionClient) (Web return sc } +// WithWebSocketOptions provides options to the websocket client +func (sc *SubscriptionClient) WithWebSocketOptions(options WebsocketOptions) *SubscriptionClient { + sc.websocketOptions = options + return sc +} + // WithConnectionParams updates connection params for sending to server through GQL_CONNECTION_INIT event // It's usually used for authentication handshake func (sc *SubscriptionClient) WithConnectionParams(params map[string]interface{}) *SubscriptionClient { @@ -189,7 +202,7 @@ func (sc *SubscriptionClient) OnConnected(fn func()) *SubscriptionClient { return sc } -// OnDisconnected event is triggered when the websocket server was still down after retry timeout +// OnDisconnected event is triggered when the websocket client was disconnected func (sc *SubscriptionClient) OnDisconnected(fn func()) *SubscriptionClient { sc.onDisconnected = fn return sc @@ -237,12 +250,19 @@ func (sc *SubscriptionClient) init() error { } return err } - sc.printLog(err.Error()+". retry in second....", GQL_INTERNAL) + sc.printLog(fmt.Sprintf("%s. retry in second...", err.Error()), "client", GQL_INTERNAL) time.Sleep(time.Second) } } -func (sc *SubscriptionClient) printLog(message interface{}, opType OperationMessageType) { +func (sc *SubscriptionClient) writeJSON(v interface{}) error { + if sc.conn != nil { + return sc.conn.WriteJSON(v) + } + return nil +} + +func (sc *SubscriptionClient) printLog(message interface{}, source string, opType OperationMessageType) { if sc.log == nil { return } @@ -252,7 +272,7 @@ func (sc *SubscriptionClient) printLog(message interface{}, opType OperationMess } } - sc.log(message) + sc.log(message, source) } func (sc *SubscriptionClient) sendConnectionInit() (err error) { @@ -271,31 +291,37 @@ func (sc *SubscriptionClient) sendConnectionInit() (err error) { Payload: bParams, } - sc.printLog(msg, GQL_CONNECTION_INIT) - return sc.conn.WriteJSON(msg) + sc.printLog(msg, "client", GQL_CONNECTION_INIT) + return sc.writeJSON(msg) } // Subscribe sends start message to server and open a channel to receive data. // The handler callback function will receive raw message data or error. If the call return error, onError event will be triggered // The function returns subscription ID and error. You can use subscription ID to unsubscribe the subscription -func (sc *SubscriptionClient) Subscribe(v interface{}, variables map[string]interface{}, handler func(message *json.RawMessage, err error) error, options ...Option) (string, error) { +func (sc *SubscriptionClient) Subscribe(v interface{}, variables map[string]interface{}, handler func(message []byte, err error) error, options ...Option) (string, error) { return sc.do(v, variables, handler, options...) } // NamedSubscribe sends start message to server and open a channel to receive data, with operation name // // Deprecated: this is the shortcut of Subscribe method, with NewOperationName option -func (sc *SubscriptionClient) NamedSubscribe(name string, v interface{}, variables map[string]interface{}, handler func(message *json.RawMessage, err error) error, options ...Option) (string, error) { +func (sc *SubscriptionClient) NamedSubscribe(name string, v interface{}, variables map[string]interface{}, handler func(message []byte, err error) error, options ...Option) (string, error) { return sc.do(v, variables, handler, append(options, OperationName(name))...) } // SubscribeRaw sends start message to server and open a channel to receive data, with raw query -func (sc *SubscriptionClient) SubscribeRaw(query string, variables map[string]interface{}, handler func(message *json.RawMessage, err error) error) (string, error) { +// Deprecated: use Exec instead +func (sc *SubscriptionClient) SubscribeRaw(query string, variables map[string]interface{}, handler func(message []byte, err error) error) (string, error) { return sc.doRaw(query, variables, handler) } -func (sc *SubscriptionClient) do(v interface{}, variables map[string]interface{}, handler func(message *json.RawMessage, err error) error, options ...Option) (string, error) { - query, err := constructSubscription(v, variables, options...) +// Exec sends start message to server and open a channel to receive data, with raw query +func (sc *SubscriptionClient) Exec(query string, variables map[string]interface{}, handler func(message []byte, err error) error) (string, error) { + return sc.doRaw(query, variables, handler) +} + +func (sc *SubscriptionClient) do(v interface{}, variables map[string]interface{}, handler func(message []byte, err error) error, options ...Option) (string, error) { + query, err := ConstructSubscription(v, variables, options...) if err != nil { return "", err } @@ -303,7 +329,7 @@ func (sc *SubscriptionClient) do(v interface{}, variables map[string]interface{} return sc.doRaw(query, variables, handler) } -func (sc *SubscriptionClient) doRaw(query string, variables map[string]interface{}, handler func(message *json.RawMessage, err error) error) (string, error) { +func (sc *SubscriptionClient) doRaw(query string, variables map[string]interface{}, handler func(message []byte, err error) error) (string, error) { id := uuid.New().String() sub := subscription{ @@ -352,8 +378,8 @@ func (sc *SubscriptionClient) startSubscription(id string, sub *subscription) er Payload: payload, } - sc.printLog(msg, GQL_START) - if err := sc.conn.WriteJSON(msg); err != nil { + sc.printLog(msg, "client", GQL_START) + if err := sc.writeJSON(msg); err != nil { return err } @@ -361,8 +387,8 @@ func (sc *SubscriptionClient) startSubscription(id string, sub *subscription) er return nil } -func (sc *SubscriptionClient) wrapHandler(fn handlerFunc) func(data *json.RawMessage, err error) { - return func(data *json.RawMessage, err error) { +func (sc *SubscriptionClient) wrapHandler(fn handlerFunc) func(data []byte, err error) { + return func(data []byte, err error) { if errValue := fn(data, err); errValue != nil { sc.errorChan <- errValue } @@ -386,95 +412,121 @@ func (sc *SubscriptionClient) Run() error { sc.subscribersMu.Unlock() sc.setIsRunning(true) - - for atomic.LoadInt64(&sc.isRunning) > 0 { - select { - case <-sc.context.Done(): - return nil - case e := <-sc.errorChan: - if sc.onError != nil { - if err := sc.onError(sc, e); err != nil { - return err - } - } - default: - - var message OperationMessage - if err := sc.conn.ReadJSON(&message); err != nil { - // manual EOF check - if err == io.EOF || strings.Contains(err.Error(), "EOF") { - return sc.Reset() - } - closeStatus := websocket.CloseStatus(err) - if closeStatus == websocket.StatusNormalClosure { - // close event from websocket client, exiting... - return nil - } - if closeStatus != -1 { - sc.printLog(fmt.Sprintf("%s. Retry connecting...", err), GQL_INTERNAL) - return sc.Reset() + go func() { + for atomic.LoadInt64(&sc.isRunning) > 0 { + select { + case <-sc.context.Done(): + return + default: + if sc.conn == nil { + return } - if sc.onError != nil { - if err = sc.onError(sc, err); err != nil { - return err + var message OperationMessage + if err := sc.conn.ReadJSON(&message); err != nil { + // manual EOF check + if err == io.EOF || strings.Contains(err.Error(), "EOF") { + if err = sc.Reset(); err != nil { + sc.errorChan <- err + return + } + } + closeStatus := websocket.CloseStatus(err) + if closeStatus == websocket.StatusNormalClosure { + // close event from websocket client, exiting... + return + } + if closeStatus != -1 { + sc.printLog(fmt.Sprintf("%s. Retry connecting...", err), "client", GQL_INTERNAL) + if err = sc.Reset(); err != nil { + sc.errorChan <- err + return + } } - } - continue - } - switch message.Type { - case GQL_ERROR: - sc.printLog(message, GQL_ERROR) - fallthrough - case GQL_DATA: - sc.printLog(message, GQL_DATA) - id, err := uuid.Parse(message.ID) - if err != nil { + if sc.onError != nil { + if err = sc.onError(sc, err); err != nil { + return + } + } continue } - sc.subscribersMu.Lock() - sub, ok := sc.subscriptions[id.String()] - sc.subscribersMu.Unlock() + switch message.Type { + case GQL_ERROR: + sc.printLog(message, "server", GQL_ERROR) + fallthrough + case GQL_DATA: + sc.printLog(message, "server", GQL_DATA) + id, err := uuid.Parse(message.ID) + if err != nil { + continue + } - if !ok { - continue - } - var out struct { - Data *json.RawMessage - Errors Errors - } + sc.subscribersMu.Lock() + sub, ok := sc.subscriptions[id.String()] + sc.subscribersMu.Unlock() - err = json.Unmarshal(message.Payload, &out) - if err != nil { - go sub.handler(nil, err) - continue - } - if len(out.Errors) > 0 { - go sub.handler(nil, out.Errors) - continue + if !ok { + continue + } + var out struct { + Data *json.RawMessage + Errors Errors + } + + err = json.Unmarshal(message.Payload, &out) + if err != nil { + go sub.handler(nil, err) + continue + } + if len(out.Errors) > 0 { + go sub.handler(nil, out.Errors) + continue + } + + var outData []byte + if out.Data != nil && len(*out.Data) > 0 { + outData = *out.Data + } + + go sub.handler(outData, nil) + case GQL_CONNECTION_ERROR: + sc.printLog(message, "server", GQL_CONNECTION_ERROR) + case GQL_COMPLETE: + sc.printLog(message, "server", GQL_COMPLETE) + sc.Unsubscribe(message.ID) + case GQL_CONNECTION_KEEP_ALIVE: + sc.printLog(message, "server", GQL_CONNECTION_KEEP_ALIVE) + case GQL_CONNECTION_ACK: + sc.printLog(message, "server", GQL_CONNECTION_ACK) + if sc.onConnected != nil { + sc.onConnected() + } + default: + sc.printLog(message, "server", GQL_UNKNOWN) } + } + } + }() - go sub.handler(out.Data, nil) - case GQL_CONNECTION_ERROR: - sc.printLog(message, GQL_CONNECTION_ERROR) - case GQL_COMPLETE: - sc.printLog(message, GQL_COMPLETE) - sc.Unsubscribe(message.ID) - case GQL_CONNECTION_KEEP_ALIVE: - sc.printLog(message, GQL_CONNECTION_KEEP_ALIVE) - case GQL_CONNECTION_ACK: - sc.printLog(message, GQL_CONNECTION_ACK) - if sc.onConnected != nil { - sc.onConnected() + for atomic.LoadInt64(&sc.isRunning) > 0 { + select { + case <-sc.context.Done(): + return nil + case e := <-sc.errorChan: + // stop the subscription if the error has stop message + if e == ErrSubscriptionStopped { + return nil + } + + if sc.onError != nil { + if err := sc.onError(sc, e); err != nil { + return err } - default: - sc.printLog(message, GQL_UNKNOWN) } } } - // if the running status is false, stop retrying if atomic.LoadInt64(&sc.isRunning) == 0 { return nil @@ -495,7 +547,17 @@ func (sc *SubscriptionClient) Unsubscribe(id string) error { } delete(sc.subscriptions, id) - return sc.stopSubscription(id) + err := sc.stopSubscription(id) + if err != nil { + return err + } + + // close the client if there is no running subscription + if len(sc.subscriptions) == 0 { + sc.printLog("no running subscription. exiting...", "client", GQL_INTERNAL) + return sc.Close() + } + return nil } func (sc *SubscriptionClient) stopSubscription(id string) error { @@ -506,8 +568,8 @@ func (sc *SubscriptionClient) stopSubscription(id string) error { Type: GQL_STOP, } - sc.printLog(msg, GQL_STOP) - if err := sc.conn.WriteJSON(msg); err != nil { + sc.printLog(msg, "server", GQL_STOP) + if err := sc.writeJSON(msg); err != nil { return err } @@ -517,14 +579,14 @@ func (sc *SubscriptionClient) stopSubscription(id string) error { } func (sc *SubscriptionClient) terminate() error { - if sc.conn != nil { - // send terminate message to the server - msg := OperationMessage{ - Type: GQL_CONNECTION_TERMINATE, - } + // send terminate message to the server + msg := OperationMessage{ + Type: GQL_CONNECTION_TERMINATE, + } - sc.printLog(msg, GQL_CONNECTION_TERMINATE) - return sc.conn.WriteJSON(msg) + if sc.conn != nil { + sc.printLog(msg, "client", GQL_CONNECTION_TERMINATE) + return sc.writeJSON(msg) } return nil @@ -556,18 +618,20 @@ func (sc *SubscriptionClient) Reset() error { // Close closes all subscription channel and websocket as well func (sc *SubscriptionClient) Close() (err error) { sc.setIsRunning(false) - for id := range sc.subscriptions { if err = sc.Unsubscribe(id); err != nil { sc.cancel() - return err + return } } + _ = sc.terminate() if sc.conn != nil { - _ = sc.terminate() err = sc.conn.Close() sc.conn = nil + if sc.onDisconnected != nil { + sc.onDisconnected() + } } sc.cancel() @@ -602,7 +666,9 @@ func newWebsocketConn(sc *SubscriptionClient) (WebsocketConn, error) { options := &websocket.DialOptions{ Subprotocols: []string{"graphql-ws"}, + HTTPClient: sc.websocketOptions.HTTPClient, } + c, _, err := websocket.Dial(sc.GetContext(), sc.GetURL(), options) if err != nil { return nil, err @@ -614,3 +680,9 @@ func newWebsocketConn(sc *SubscriptionClient) (WebsocketConn, error) { timeout: sc.GetTimeout(), }, nil } + +// WebsocketOptions allows implementation agnostic configuration of the websocket client +type WebsocketOptions struct { + // HTTPClient is used for the connection. + HTTPClient *http.Client +} diff --git a/vendor/github.com/hasura/go-graphql-client/type.go b/vendor/github.com/hasura/go-graphql-client/type.go new file mode 100644 index 000000000..c5e91385d --- /dev/null +++ b/vendor/github.com/hasura/go-graphql-client/type.go @@ -0,0 +1,15 @@ +package graphql + +// GraphQLType interface is used to specify the GraphQL type associated +// with a particular type. If a type implements this interface, the name of +// the variable used while creating the GraphQL query will be the output of +// the function defined below. +// +// In the current implementation, the GetGraphQLType function is applied to +// the zero value of the type to get the GraphQL type. So those who are +// implementing the function should avoid referencing the value of the type +// inside the function. Further, by this design, the output of the GetGraphQLType +// function will be a constant. +type GraphQLType interface { + GetGraphQLType() string +} diff --git a/vendor/github.com/opentracing/opentracing-go/.gitignore b/vendor/github.com/opentracing/opentracing-go/.gitignore deleted file mode 100644 index c57100a59..000000000 --- a/vendor/github.com/opentracing/opentracing-go/.gitignore +++ /dev/null @@ -1 +0,0 @@ -coverage.txt diff --git a/vendor/github.com/opentracing/opentracing-go/.travis.yml b/vendor/github.com/opentracing/opentracing-go/.travis.yml deleted file mode 100644 index 8d5b75e41..000000000 --- a/vendor/github.com/opentracing/opentracing-go/.travis.yml +++ /dev/null @@ -1,20 +0,0 @@ -language: go - -matrix: - include: - - go: "1.11.x" - - go: "1.12.x" - - go: "tip" - env: - - LINT=true - - COVERAGE=true - -install: - - if [ "$LINT" == true ]; then go get -u golang.org/x/lint/golint/... ; else echo 'skipping lint'; fi - - go get -u github.com/stretchr/testify/... - -script: - - make test - - go build ./... - - if [ "$LINT" == true ]; then make lint ; else echo 'skipping lint'; fi - - if [ "$COVERAGE" == true ]; then make cover && bash <(curl -s https://codecov.io/bash) ; else echo 'skipping coverage'; fi diff --git a/vendor/github.com/opentracing/opentracing-go/CHANGELOG.md b/vendor/github.com/opentracing/opentracing-go/CHANGELOG.md deleted file mode 100644 index 7c14febe1..000000000 --- a/vendor/github.com/opentracing/opentracing-go/CHANGELOG.md +++ /dev/null @@ -1,46 +0,0 @@ -Changes by Version -================== - -1.1.0 (2019-03-23) -------------------- - -Notable changes: -- The library is now released under Apache 2.0 license -- Use Set() instead of Add() in HTTPHeadersCarrier is functionally a breaking change (fixes issue [#159](https://github.com/opentracing/opentracing-go/issues/159)) -- 'golang.org/x/net/context' is replaced with 'context' from the standard library - -List of all changes: - -- Export StartSpanFromContextWithTracer (#214) -- Add IsGlobalTracerRegistered() to indicate if a tracer has been registered (#201) -- Use Set() instead of Add() in HTTPHeadersCarrier (#191) -- Update license to Apache 2.0 (#181) -- Replace 'golang.org/x/net/context' with 'context' (#176) -- Port of Python opentracing/harness/api_check.py to Go (#146) -- Fix race condition in MockSpan.Context() (#170) -- Add PeerHostIPv4.SetString() (#155) -- Add a Noop log field type to log to allow for optional fields (#150) - - -1.0.2 (2017-04-26) -------------------- - -- Add more semantic tags (#139) - - -1.0.1 (2017-02-06) -------------------- - -- Correct spelling in comments -- Address race in nextMockID() (#123) -- log: avoid panic marshaling nil error (#131) -- Deprecate InitGlobalTracer in favor of SetGlobalTracer (#128) -- Drop Go 1.5 that fails in Travis (#129) -- Add convenience methods Key() and Value() to log.Field -- Add convenience methods to log.Field (2 years, 6 months ago) - -1.0.0 (2016-09-26) -------------------- - -- This release implements OpenTracing Specification 1.0 (https://opentracing.io/spec) - diff --git a/vendor/github.com/opentracing/opentracing-go/LICENSE b/vendor/github.com/opentracing/opentracing-go/LICENSE deleted file mode 100644 index f0027349e..000000000 --- a/vendor/github.com/opentracing/opentracing-go/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2016 The OpenTracing Authors - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/opentracing/opentracing-go/Makefile b/vendor/github.com/opentracing/opentracing-go/Makefile deleted file mode 100644 index 62abb63f5..000000000 --- a/vendor/github.com/opentracing/opentracing-go/Makefile +++ /dev/null @@ -1,20 +0,0 @@ -.DEFAULT_GOAL := test-and-lint - -.PHONY: test-and-lint -test-and-lint: test lint - -.PHONY: test -test: - go test -v -cover -race ./... - -.PHONY: cover -cover: - go test -v -coverprofile=coverage.txt -covermode=atomic -race ./... - -.PHONY: lint -lint: - go fmt ./... - golint ./... - @# Run again with magic to exit non-zero if golint outputs anything. - @! (golint ./... | read dummy) - go vet ./... diff --git a/vendor/github.com/opentracing/opentracing-go/README.md b/vendor/github.com/opentracing/opentracing-go/README.md deleted file mode 100644 index 6ef1d7c9d..000000000 --- a/vendor/github.com/opentracing/opentracing-go/README.md +++ /dev/null @@ -1,171 +0,0 @@ -[![Gitter chat](http://img.shields.io/badge/gitter-join%20chat%20%E2%86%92-brightgreen.svg)](https://gitter.im/opentracing/public) [![Build Status](https://travis-ci.org/opentracing/opentracing-go.svg?branch=master)](https://travis-ci.org/opentracing/opentracing-go) [![GoDoc](https://godoc.org/github.com/opentracing/opentracing-go?status.svg)](http://godoc.org/github.com/opentracing/opentracing-go) -[![Sourcegraph Badge](https://sourcegraph.com/github.com/opentracing/opentracing-go/-/badge.svg)](https://sourcegraph.com/github.com/opentracing/opentracing-go?badge) - -# OpenTracing API for Go - -This package is a Go platform API for OpenTracing. - -## Required Reading - -In order to understand the Go platform API, one must first be familiar with the -[OpenTracing project](https://opentracing.io) and -[terminology](https://opentracing.io/specification/) more specifically. - -## API overview for those adding instrumentation - -Everyday consumers of this `opentracing` package really only need to worry -about a couple of key abstractions: the `StartSpan` function, the `Span` -interface, and binding a `Tracer` at `main()`-time. Here are code snippets -demonstrating some important use cases. - -#### Singleton initialization - -The simplest starting point is `./default_tracer.go`. As early as possible, call - -```go - import "github.com/opentracing/opentracing-go" - import ".../some_tracing_impl" - - func main() { - opentracing.SetGlobalTracer( - // tracing impl specific: - some_tracing_impl.New(...), - ) - ... - } -``` - -#### Non-Singleton initialization - -If you prefer direct control to singletons, manage ownership of the -`opentracing.Tracer` implementation explicitly. - -#### Creating a Span given an existing Go `context.Context` - -If you use `context.Context` in your application, OpenTracing's Go library will -happily rely on it for `Span` propagation. To start a new (blocking child) -`Span`, you can use `StartSpanFromContext`. - -```go - func xyz(ctx context.Context, ...) { - ... - span, ctx := opentracing.StartSpanFromContext(ctx, "operation_name") - defer span.Finish() - span.LogFields( - log.String("event", "soft error"), - log.String("type", "cache timeout"), - log.Int("waited.millis", 1500)) - ... - } -``` - -#### Starting an empty trace by creating a "root span" - -It's always possible to create a "root" `Span` with no parent or other causal -reference. - -```go - func xyz() { - ... - sp := opentracing.StartSpan("operation_name") - defer sp.Finish() - ... - } -``` - -#### Creating a (child) Span given an existing (parent) Span - -```go - func xyz(parentSpan opentracing.Span, ...) { - ... - sp := opentracing.StartSpan( - "operation_name", - opentracing.ChildOf(parentSpan.Context())) - defer sp.Finish() - ... - } -``` - -#### Serializing to the wire - -```go - func makeSomeRequest(ctx context.Context) ... { - if span := opentracing.SpanFromContext(ctx); span != nil { - httpClient := &http.Client{} - httpReq, _ := http.NewRequest("GET", "http://myservice/", nil) - - // Transmit the span's TraceContext as HTTP headers on our - // outbound request. - opentracing.GlobalTracer().Inject( - span.Context(), - opentracing.HTTPHeaders, - opentracing.HTTPHeadersCarrier(httpReq.Header)) - - resp, err := httpClient.Do(httpReq) - ... - } - ... - } -``` - -#### Deserializing from the wire - -```go - http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { - var serverSpan opentracing.Span - appSpecificOperationName := ... - wireContext, err := opentracing.GlobalTracer().Extract( - opentracing.HTTPHeaders, - opentracing.HTTPHeadersCarrier(req.Header)) - if err != nil { - // Optionally record something about err here - } - - // Create the span referring to the RPC client if available. - // If wireContext == nil, a root span will be created. - serverSpan = opentracing.StartSpan( - appSpecificOperationName, - ext.RPCServerOption(wireContext)) - - defer serverSpan.Finish() - - ctx := opentracing.ContextWithSpan(context.Background(), serverSpan) - ... - } -``` - -#### Conditionally capture a field using `log.Noop` - -In some situations, you may want to dynamically decide whether or not -to log a field. For example, you may want to capture additional data, -such as a customer ID, in non-production environments: - -```go - func Customer(order *Order) log.Field { - if os.Getenv("ENVIRONMENT") == "dev" { - return log.String("customer", order.Customer.ID) - } - return log.Noop() - } -``` - -#### Goroutine-safety - -The entire public API is goroutine-safe and does not require external -synchronization. - -## API pointers for those implementing a tracing system - -Tracing system implementors may be able to reuse or copy-paste-modify the `basictracer` package, found [here](https://github.com/opentracing/basictracer-go). In particular, see `basictracer.New(...)`. - -## API compatibility - -For the time being, "mild" backwards-incompatible changes may be made without changing the major version number. As OpenTracing and `opentracing-go` mature, backwards compatibility will become more of a priority. - -## Tracer test suite - -A test suite is available in the [harness](https://godoc.org/github.com/opentracing/opentracing-go/harness) package that can assist Tracer implementors to assert that their Tracer is working correctly. - -## Licensing - -[Apache 2.0 License](./LICENSE). diff --git a/vendor/github.com/opentracing/opentracing-go/ext/tags.go b/vendor/github.com/opentracing/opentracing-go/ext/tags.go deleted file mode 100644 index 52e889582..000000000 --- a/vendor/github.com/opentracing/opentracing-go/ext/tags.go +++ /dev/null @@ -1,210 +0,0 @@ -package ext - -import "github.com/opentracing/opentracing-go" - -// These constants define common tag names recommended for better portability across -// tracing systems and languages/platforms. -// -// The tag names are defined as typed strings, so that in addition to the usual use -// -// span.setTag(TagName, value) -// -// they also support value type validation via this additional syntax: -// -// TagName.Set(span, value) -// -var ( - ////////////////////////////////////////////////////////////////////// - // SpanKind (client/server or producer/consumer) - ////////////////////////////////////////////////////////////////////// - - // SpanKind hints at relationship between spans, e.g. client/server - SpanKind = spanKindTagName("span.kind") - - // SpanKindRPCClient marks a span representing the client-side of an RPC - // or other remote call - SpanKindRPCClientEnum = SpanKindEnum("client") - SpanKindRPCClient = opentracing.Tag{Key: string(SpanKind), Value: SpanKindRPCClientEnum} - - // SpanKindRPCServer marks a span representing the server-side of an RPC - // or other remote call - SpanKindRPCServerEnum = SpanKindEnum("server") - SpanKindRPCServer = opentracing.Tag{Key: string(SpanKind), Value: SpanKindRPCServerEnum} - - // SpanKindProducer marks a span representing the producer-side of a - // message bus - SpanKindProducerEnum = SpanKindEnum("producer") - SpanKindProducer = opentracing.Tag{Key: string(SpanKind), Value: SpanKindProducerEnum} - - // SpanKindConsumer marks a span representing the consumer-side of a - // message bus - SpanKindConsumerEnum = SpanKindEnum("consumer") - SpanKindConsumer = opentracing.Tag{Key: string(SpanKind), Value: SpanKindConsumerEnum} - - ////////////////////////////////////////////////////////////////////// - // Component name - ////////////////////////////////////////////////////////////////////// - - // Component is a low-cardinality identifier of the module, library, - // or package that is generating a span. - Component = stringTagName("component") - - ////////////////////////////////////////////////////////////////////// - // Sampling hint - ////////////////////////////////////////////////////////////////////// - - // SamplingPriority determines the priority of sampling this Span. - SamplingPriority = uint16TagName("sampling.priority") - - ////////////////////////////////////////////////////////////////////// - // Peer tags. These tags can be emitted by either client-side of - // server-side to describe the other side/service in a peer-to-peer - // communications, like an RPC call. - ////////////////////////////////////////////////////////////////////// - - // PeerService records the service name of the peer. - PeerService = stringTagName("peer.service") - - // PeerAddress records the address name of the peer. This may be a "ip:port", - // a bare "hostname", a FQDN or even a database DSN substring - // like "mysql://username@127.0.0.1:3306/dbname" - PeerAddress = stringTagName("peer.address") - - // PeerHostname records the host name of the peer - PeerHostname = stringTagName("peer.hostname") - - // PeerHostIPv4 records IP v4 host address of the peer - PeerHostIPv4 = ipv4Tag("peer.ipv4") - - // PeerHostIPv6 records IP v6 host address of the peer - PeerHostIPv6 = stringTagName("peer.ipv6") - - // PeerPort records port number of the peer - PeerPort = uint16TagName("peer.port") - - ////////////////////////////////////////////////////////////////////// - // HTTP Tags - ////////////////////////////////////////////////////////////////////// - - // HTTPUrl should be the URL of the request being handled in this segment - // of the trace, in standard URI format. The protocol is optional. - HTTPUrl = stringTagName("http.url") - - // HTTPMethod is the HTTP method of the request, and is case-insensitive. - HTTPMethod = stringTagName("http.method") - - // HTTPStatusCode is the numeric HTTP status code (200, 404, etc) of the - // HTTP response. - HTTPStatusCode = uint16TagName("http.status_code") - - ////////////////////////////////////////////////////////////////////// - // DB Tags - ////////////////////////////////////////////////////////////////////// - - // DBInstance is database instance name. - DBInstance = stringTagName("db.instance") - - // DBStatement is a database statement for the given database type. - // It can be a query or a prepared statement (i.e., before substitution). - DBStatement = stringTagName("db.statement") - - // DBType is a database type. For any SQL database, "sql". - // For others, the lower-case database category, e.g. "redis" - DBType = stringTagName("db.type") - - // DBUser is a username for accessing database. - DBUser = stringTagName("db.user") - - ////////////////////////////////////////////////////////////////////// - // Message Bus Tag - ////////////////////////////////////////////////////////////////////// - - // MessageBusDestination is an address at which messages can be exchanged - MessageBusDestination = stringTagName("message_bus.destination") - - ////////////////////////////////////////////////////////////////////// - // Error Tag - ////////////////////////////////////////////////////////////////////// - - // Error indicates that operation represented by the span resulted in an error. - Error = boolTagName("error") -) - -// --- - -// SpanKindEnum represents common span types -type SpanKindEnum string - -type spanKindTagName string - -// Set adds a string tag to the `span` -func (tag spanKindTagName) Set(span opentracing.Span, value SpanKindEnum) { - span.SetTag(string(tag), value) -} - -type rpcServerOption struct { - clientContext opentracing.SpanContext -} - -func (r rpcServerOption) Apply(o *opentracing.StartSpanOptions) { - if r.clientContext != nil { - opentracing.ChildOf(r.clientContext).Apply(o) - } - SpanKindRPCServer.Apply(o) -} - -// RPCServerOption returns a StartSpanOption appropriate for an RPC server span -// with `client` representing the metadata for the remote peer Span if available. -// In case client == nil, due to the client not being instrumented, this RPC -// server span will be a root span. -func RPCServerOption(client opentracing.SpanContext) opentracing.StartSpanOption { - return rpcServerOption{client} -} - -// --- - -type stringTagName string - -// Set adds a string tag to the `span` -func (tag stringTagName) Set(span opentracing.Span, value string) { - span.SetTag(string(tag), value) -} - -// --- - -type uint32TagName string - -// Set adds a uint32 tag to the `span` -func (tag uint32TagName) Set(span opentracing.Span, value uint32) { - span.SetTag(string(tag), value) -} - -// --- - -type uint16TagName string - -// Set adds a uint16 tag to the `span` -func (tag uint16TagName) Set(span opentracing.Span, value uint16) { - span.SetTag(string(tag), value) -} - -// --- - -type boolTagName string - -// Add adds a bool tag to the `span` -func (tag boolTagName) Set(span opentracing.Span, value bool) { - span.SetTag(string(tag), value) -} - -type ipv4Tag string - -// Set adds IP v4 host address of the peer as an uint32 value to the `span`, keep this for backward and zipkin compatibility -func (tag ipv4Tag) Set(span opentracing.Span, value uint32) { - span.SetTag(string(tag), value) -} - -// SetString records IP v4 host address of the peer as a .-separated tuple to the `span`. E.g., "127.0.0.1" -func (tag ipv4Tag) SetString(span opentracing.Span, value string) { - span.SetTag(string(tag), value) -} diff --git a/vendor/github.com/opentracing/opentracing-go/globaltracer.go b/vendor/github.com/opentracing/opentracing-go/globaltracer.go deleted file mode 100644 index 4f7066a92..000000000 --- a/vendor/github.com/opentracing/opentracing-go/globaltracer.go +++ /dev/null @@ -1,42 +0,0 @@ -package opentracing - -type registeredTracer struct { - tracer Tracer - isRegistered bool -} - -var ( - globalTracer = registeredTracer{NoopTracer{}, false} -) - -// SetGlobalTracer sets the [singleton] opentracing.Tracer returned by -// GlobalTracer(). Those who use GlobalTracer (rather than directly manage an -// opentracing.Tracer instance) should call SetGlobalTracer as early as -// possible in main(), prior to calling the `StartSpan` global func below. -// Prior to calling `SetGlobalTracer`, any Spans started via the `StartSpan` -// (etc) globals are noops. -func SetGlobalTracer(tracer Tracer) { - globalTracer = registeredTracer{tracer, true} -} - -// GlobalTracer returns the global singleton `Tracer` implementation. -// Before `SetGlobalTracer()` is called, the `GlobalTracer()` is a noop -// implementation that drops all data handed to it. -func GlobalTracer() Tracer { - return globalTracer.tracer -} - -// StartSpan defers to `Tracer.StartSpan`. See `GlobalTracer()`. -func StartSpan(operationName string, opts ...StartSpanOption) Span { - return globalTracer.tracer.StartSpan(operationName, opts...) -} - -// InitGlobalTracer is deprecated. Please use SetGlobalTracer. -func InitGlobalTracer(tracer Tracer) { - SetGlobalTracer(tracer) -} - -// IsGlobalTracerRegistered returns a `bool` to indicate if a tracer has been globally registered -func IsGlobalTracerRegistered() bool { - return globalTracer.isRegistered -} diff --git a/vendor/github.com/opentracing/opentracing-go/gocontext.go b/vendor/github.com/opentracing/opentracing-go/gocontext.go deleted file mode 100644 index 08c00c04e..000000000 --- a/vendor/github.com/opentracing/opentracing-go/gocontext.go +++ /dev/null @@ -1,60 +0,0 @@ -package opentracing - -import "context" - -type contextKey struct{} - -var activeSpanKey = contextKey{} - -// ContextWithSpan returns a new `context.Context` that holds a reference to -// `span`'s SpanContext. -func ContextWithSpan(ctx context.Context, span Span) context.Context { - return context.WithValue(ctx, activeSpanKey, span) -} - -// SpanFromContext returns the `Span` previously associated with `ctx`, or -// `nil` if no such `Span` could be found. -// -// NOTE: context.Context != SpanContext: the former is Go's intra-process -// context propagation mechanism, and the latter houses OpenTracing's per-Span -// identity and baggage information. -func SpanFromContext(ctx context.Context) Span { - val := ctx.Value(activeSpanKey) - if sp, ok := val.(Span); ok { - return sp - } - return nil -} - -// StartSpanFromContext starts and returns a Span with `operationName`, using -// any Span found within `ctx` as a ChildOfRef. If no such parent could be -// found, StartSpanFromContext creates a root (parentless) Span. -// -// The second return value is a context.Context object built around the -// returned Span. -// -// Example usage: -// -// SomeFunction(ctx context.Context, ...) { -// sp, ctx := opentracing.StartSpanFromContext(ctx, "SomeFunction") -// defer sp.Finish() -// ... -// } -func StartSpanFromContext(ctx context.Context, operationName string, opts ...StartSpanOption) (Span, context.Context) { - return StartSpanFromContextWithTracer(ctx, GlobalTracer(), operationName, opts...) -} - -// StartSpanFromContextWithTracer starts and returns a span with `operationName` -// using a span found within the context as a ChildOfRef. If that doesn't exist -// it creates a root span. It also returns a context.Context object built -// around the returned span. -// -// It's behavior is identical to StartSpanFromContext except that it takes an explicit -// tracer as opposed to using the global tracer. -func StartSpanFromContextWithTracer(ctx context.Context, tracer Tracer, operationName string, opts ...StartSpanOption) (Span, context.Context) { - if parentSpan := SpanFromContext(ctx); parentSpan != nil { - opts = append(opts, ChildOf(parentSpan.Context())) - } - span := tracer.StartSpan(operationName, opts...) - return span, ContextWithSpan(ctx, span) -} diff --git a/vendor/github.com/opentracing/opentracing-go/noop.go b/vendor/github.com/opentracing/opentracing-go/noop.go deleted file mode 100644 index 0d32f692c..000000000 --- a/vendor/github.com/opentracing/opentracing-go/noop.go +++ /dev/null @@ -1,64 +0,0 @@ -package opentracing - -import "github.com/opentracing/opentracing-go/log" - -// A NoopTracer is a trivial, minimum overhead implementation of Tracer -// for which all operations are no-ops. -// -// The primary use of this implementation is in libraries, such as RPC -// frameworks, that make tracing an optional feature controlled by the -// end user. A no-op implementation allows said libraries to use it -// as the default Tracer and to write instrumentation that does -// not need to keep checking if the tracer instance is nil. -// -// For the same reason, the NoopTracer is the default "global" tracer -// (see GlobalTracer and SetGlobalTracer functions). -// -// WARNING: NoopTracer does not support baggage propagation. -type NoopTracer struct{} - -type noopSpan struct{} -type noopSpanContext struct{} - -var ( - defaultNoopSpanContext = noopSpanContext{} - defaultNoopSpan = noopSpan{} - defaultNoopTracer = NoopTracer{} -) - -const ( - emptyString = "" -) - -// noopSpanContext: -func (n noopSpanContext) ForeachBaggageItem(handler func(k, v string) bool) {} - -// noopSpan: -func (n noopSpan) Context() SpanContext { return defaultNoopSpanContext } -func (n noopSpan) SetBaggageItem(key, val string) Span { return defaultNoopSpan } -func (n noopSpan) BaggageItem(key string) string { return emptyString } -func (n noopSpan) SetTag(key string, value interface{}) Span { return n } -func (n noopSpan) LogFields(fields ...log.Field) {} -func (n noopSpan) LogKV(keyVals ...interface{}) {} -func (n noopSpan) Finish() {} -func (n noopSpan) FinishWithOptions(opts FinishOptions) {} -func (n noopSpan) SetOperationName(operationName string) Span { return n } -func (n noopSpan) Tracer() Tracer { return defaultNoopTracer } -func (n noopSpan) LogEvent(event string) {} -func (n noopSpan) LogEventWithPayload(event string, payload interface{}) {} -func (n noopSpan) Log(data LogData) {} - -// StartSpan belongs to the Tracer interface. -func (n NoopTracer) StartSpan(operationName string, opts ...StartSpanOption) Span { - return defaultNoopSpan -} - -// Inject belongs to the Tracer interface. -func (n NoopTracer) Inject(sp SpanContext, format interface{}, carrier interface{}) error { - return nil -} - -// Extract belongs to the Tracer interface. -func (n NoopTracer) Extract(format interface{}, carrier interface{}) (SpanContext, error) { - return nil, ErrSpanContextNotFound -} diff --git a/vendor/github.com/opentracing/opentracing-go/propagation.go b/vendor/github.com/opentracing/opentracing-go/propagation.go deleted file mode 100644 index b0c275eb0..000000000 --- a/vendor/github.com/opentracing/opentracing-go/propagation.go +++ /dev/null @@ -1,176 +0,0 @@ -package opentracing - -import ( - "errors" - "net/http" -) - -/////////////////////////////////////////////////////////////////////////////// -// CORE PROPAGATION INTERFACES: -/////////////////////////////////////////////////////////////////////////////// - -var ( - // ErrUnsupportedFormat occurs when the `format` passed to Tracer.Inject() or - // Tracer.Extract() is not recognized by the Tracer implementation. - ErrUnsupportedFormat = errors.New("opentracing: Unknown or unsupported Inject/Extract format") - - // ErrSpanContextNotFound occurs when the `carrier` passed to - // Tracer.Extract() is valid and uncorrupted but has insufficient - // information to extract a SpanContext. - ErrSpanContextNotFound = errors.New("opentracing: SpanContext not found in Extract carrier") - - // ErrInvalidSpanContext errors occur when Tracer.Inject() is asked to - // operate on a SpanContext which it is not prepared to handle (for - // example, since it was created by a different tracer implementation). - ErrInvalidSpanContext = errors.New("opentracing: SpanContext type incompatible with tracer") - - // ErrInvalidCarrier errors occur when Tracer.Inject() or Tracer.Extract() - // implementations expect a different type of `carrier` than they are - // given. - ErrInvalidCarrier = errors.New("opentracing: Invalid Inject/Extract carrier") - - // ErrSpanContextCorrupted occurs when the `carrier` passed to - // Tracer.Extract() is of the expected type but is corrupted. - ErrSpanContextCorrupted = errors.New("opentracing: SpanContext data corrupted in Extract carrier") -) - -/////////////////////////////////////////////////////////////////////////////// -// BUILTIN PROPAGATION FORMATS: -/////////////////////////////////////////////////////////////////////////////// - -// BuiltinFormat is used to demarcate the values within package `opentracing` -// that are intended for use with the Tracer.Inject() and Tracer.Extract() -// methods. -type BuiltinFormat byte - -const ( - // Binary represents SpanContexts as opaque binary data. - // - // For Tracer.Inject(): the carrier must be an `io.Writer`. - // - // For Tracer.Extract(): the carrier must be an `io.Reader`. - Binary BuiltinFormat = iota - - // TextMap represents SpanContexts as key:value string pairs. - // - // Unlike HTTPHeaders, the TextMap format does not restrict the key or - // value character sets in any way. - // - // For Tracer.Inject(): the carrier must be a `TextMapWriter`. - // - // For Tracer.Extract(): the carrier must be a `TextMapReader`. - TextMap - - // HTTPHeaders represents SpanContexts as HTTP header string pairs. - // - // Unlike TextMap, the HTTPHeaders format requires that the keys and values - // be valid as HTTP headers as-is (i.e., character casing may be unstable - // and special characters are disallowed in keys, values should be - // URL-escaped, etc). - // - // For Tracer.Inject(): the carrier must be a `TextMapWriter`. - // - // For Tracer.Extract(): the carrier must be a `TextMapReader`. - // - // See HTTPHeadersCarrier for an implementation of both TextMapWriter - // and TextMapReader that defers to an http.Header instance for storage. - // For example, Inject(): - // - // carrier := opentracing.HTTPHeadersCarrier(httpReq.Header) - // err := span.Tracer().Inject( - // span.Context(), opentracing.HTTPHeaders, carrier) - // - // Or Extract(): - // - // carrier := opentracing.HTTPHeadersCarrier(httpReq.Header) - // clientContext, err := tracer.Extract( - // opentracing.HTTPHeaders, carrier) - // - HTTPHeaders -) - -// TextMapWriter is the Inject() carrier for the TextMap builtin format. With -// it, the caller can encode a SpanContext for propagation as entries in a map -// of unicode strings. -type TextMapWriter interface { - // Set a key:value pair to the carrier. Multiple calls to Set() for the - // same key leads to undefined behavior. - // - // NOTE: The backing store for the TextMapWriter may contain data unrelated - // to SpanContext. As such, Inject() and Extract() implementations that - // call the TextMapWriter and TextMapReader interfaces must agree on a - // prefix or other convention to distinguish their own key:value pairs. - Set(key, val string) -} - -// TextMapReader is the Extract() carrier for the TextMap builtin format. With it, -// the caller can decode a propagated SpanContext as entries in a map of -// unicode strings. -type TextMapReader interface { - // ForeachKey returns TextMap contents via repeated calls to the `handler` - // function. If any call to `handler` returns a non-nil error, ForeachKey - // terminates and returns that error. - // - // NOTE: The backing store for the TextMapReader may contain data unrelated - // to SpanContext. As such, Inject() and Extract() implementations that - // call the TextMapWriter and TextMapReader interfaces must agree on a - // prefix or other convention to distinguish their own key:value pairs. - // - // The "foreach" callback pattern reduces unnecessary copying in some cases - // and also allows implementations to hold locks while the map is read. - ForeachKey(handler func(key, val string) error) error -} - -// TextMapCarrier allows the use of regular map[string]string -// as both TextMapWriter and TextMapReader. -type TextMapCarrier map[string]string - -// ForeachKey conforms to the TextMapReader interface. -func (c TextMapCarrier) ForeachKey(handler func(key, val string) error) error { - for k, v := range c { - if err := handler(k, v); err != nil { - return err - } - } - return nil -} - -// Set implements Set() of opentracing.TextMapWriter -func (c TextMapCarrier) Set(key, val string) { - c[key] = val -} - -// HTTPHeadersCarrier satisfies both TextMapWriter and TextMapReader. -// -// Example usage for server side: -// -// carrier := opentracing.HTTPHeadersCarrier(httpReq.Header) -// clientContext, err := tracer.Extract(opentracing.HTTPHeaders, carrier) -// -// Example usage for client side: -// -// carrier := opentracing.HTTPHeadersCarrier(httpReq.Header) -// err := tracer.Inject( -// span.Context(), -// opentracing.HTTPHeaders, -// carrier) -// -type HTTPHeadersCarrier http.Header - -// Set conforms to the TextMapWriter interface. -func (c HTTPHeadersCarrier) Set(key, val string) { - h := http.Header(c) - h.Set(key, val) -} - -// ForeachKey conforms to the TextMapReader interface. -func (c HTTPHeadersCarrier) ForeachKey(handler func(key, val string) error) error { - for k, vals := range c { - for _, v := range vals { - if err := handler(k, v); err != nil { - return err - } - } - } - return nil -} diff --git a/vendor/github.com/opentracing/opentracing-go/span.go b/vendor/github.com/opentracing/opentracing-go/span.go deleted file mode 100644 index 0d3fb5341..000000000 --- a/vendor/github.com/opentracing/opentracing-go/span.go +++ /dev/null @@ -1,189 +0,0 @@ -package opentracing - -import ( - "time" - - "github.com/opentracing/opentracing-go/log" -) - -// SpanContext represents Span state that must propagate to descendant Spans and across process -// boundaries (e.g., a tuple). -type SpanContext interface { - // ForeachBaggageItem grants access to all baggage items stored in the - // SpanContext. - // The handler function will be called for each baggage key/value pair. - // The ordering of items is not guaranteed. - // - // The bool return value indicates if the handler wants to continue iterating - // through the rest of the baggage items; for example if the handler is trying to - // find some baggage item by pattern matching the name, it can return false - // as soon as the item is found to stop further iterations. - ForeachBaggageItem(handler func(k, v string) bool) -} - -// Span represents an active, un-finished span in the OpenTracing system. -// -// Spans are created by the Tracer interface. -type Span interface { - // Sets the end timestamp and finalizes Span state. - // - // With the exception of calls to Context() (which are always allowed), - // Finish() must be the last call made to any span instance, and to do - // otherwise leads to undefined behavior. - Finish() - // FinishWithOptions is like Finish() but with explicit control over - // timestamps and log data. - FinishWithOptions(opts FinishOptions) - - // Context() yields the SpanContext for this Span. Note that the return - // value of Context() is still valid after a call to Span.Finish(), as is - // a call to Span.Context() after a call to Span.Finish(). - Context() SpanContext - - // Sets or changes the operation name. - // - // Returns a reference to this Span for chaining. - SetOperationName(operationName string) Span - - // Adds a tag to the span. - // - // If there is a pre-existing tag set for `key`, it is overwritten. - // - // Tag values can be numeric types, strings, or bools. The behavior of - // other tag value types is undefined at the OpenTracing level. If a - // tracing system does not know how to handle a particular value type, it - // may ignore the tag, but shall not panic. - // - // Returns a reference to this Span for chaining. - SetTag(key string, value interface{}) Span - - // LogFields is an efficient and type-checked way to record key:value - // logging data about a Span, though the programming interface is a little - // more verbose than LogKV(). Here's an example: - // - // span.LogFields( - // log.String("event", "soft error"), - // log.String("type", "cache timeout"), - // log.Int("waited.millis", 1500)) - // - // Also see Span.FinishWithOptions() and FinishOptions.BulkLogData. - LogFields(fields ...log.Field) - - // LogKV is a concise, readable way to record key:value logging data about - // a Span, though unfortunately this also makes it less efficient and less - // type-safe than LogFields(). Here's an example: - // - // span.LogKV( - // "event", "soft error", - // "type", "cache timeout", - // "waited.millis", 1500) - // - // For LogKV (as opposed to LogFields()), the parameters must appear as - // key-value pairs, like - // - // span.LogKV(key1, val1, key2, val2, key3, val3, ...) - // - // The keys must all be strings. The values may be strings, numeric types, - // bools, Go error instances, or arbitrary structs. - // - // (Note to implementors: consider the log.InterleavedKVToFields() helper) - LogKV(alternatingKeyValues ...interface{}) - - // SetBaggageItem sets a key:value pair on this Span and its SpanContext - // that also propagates to descendants of this Span. - // - // SetBaggageItem() enables powerful functionality given a full-stack - // opentracing integration (e.g., arbitrary application data from a mobile - // app can make it, transparently, all the way into the depths of a storage - // system), and with it some powerful costs: use this feature with care. - // - // IMPORTANT NOTE #1: SetBaggageItem() will only propagate baggage items to - // *future* causal descendants of the associated Span. - // - // IMPORTANT NOTE #2: Use this thoughtfully and with care. Every key and - // value is copied into every local *and remote* child of the associated - // Span, and that can add up to a lot of network and cpu overhead. - // - // Returns a reference to this Span for chaining. - SetBaggageItem(restrictedKey, value string) Span - - // Gets the value for a baggage item given its key. Returns the empty string - // if the value isn't found in this Span. - BaggageItem(restrictedKey string) string - - // Provides access to the Tracer that created this Span. - Tracer() Tracer - - // Deprecated: use LogFields or LogKV - LogEvent(event string) - // Deprecated: use LogFields or LogKV - LogEventWithPayload(event string, payload interface{}) - // Deprecated: use LogFields or LogKV - Log(data LogData) -} - -// LogRecord is data associated with a single Span log. Every LogRecord -// instance must specify at least one Field. -type LogRecord struct { - Timestamp time.Time - Fields []log.Field -} - -// FinishOptions allows Span.FinishWithOptions callers to override the finish -// timestamp and provide log data via a bulk interface. -type FinishOptions struct { - // FinishTime overrides the Span's finish time, or implicitly becomes - // time.Now() if FinishTime.IsZero(). - // - // FinishTime must resolve to a timestamp that's >= the Span's StartTime - // (per StartSpanOptions). - FinishTime time.Time - - // LogRecords allows the caller to specify the contents of many LogFields() - // calls with a single slice. May be nil. - // - // None of the LogRecord.Timestamp values may be .IsZero() (i.e., they must - // be set explicitly). Also, they must be >= the Span's start timestamp and - // <= the FinishTime (or time.Now() if FinishTime.IsZero()). Otherwise the - // behavior of FinishWithOptions() is undefined. - // - // If specified, the caller hands off ownership of LogRecords at - // FinishWithOptions() invocation time. - // - // If specified, the (deprecated) BulkLogData must be nil or empty. - LogRecords []LogRecord - - // BulkLogData is DEPRECATED. - BulkLogData []LogData -} - -// LogData is DEPRECATED -type LogData struct { - Timestamp time.Time - Event string - Payload interface{} -} - -// ToLogRecord converts a deprecated LogData to a non-deprecated LogRecord -func (ld *LogData) ToLogRecord() LogRecord { - var literalTimestamp time.Time - if ld.Timestamp.IsZero() { - literalTimestamp = time.Now() - } else { - literalTimestamp = ld.Timestamp - } - rval := LogRecord{ - Timestamp: literalTimestamp, - } - if ld.Payload == nil { - rval.Fields = []log.Field{ - log.String("event", ld.Event), - } - } else { - rval.Fields = []log.Field{ - log.String("event", ld.Event), - log.Object("payload", ld.Payload), - } - } - return rval -} diff --git a/vendor/github.com/opentracing/opentracing-go/tracer.go b/vendor/github.com/opentracing/opentracing-go/tracer.go deleted file mode 100644 index 715f0cedf..000000000 --- a/vendor/github.com/opentracing/opentracing-go/tracer.go +++ /dev/null @@ -1,304 +0,0 @@ -package opentracing - -import "time" - -// Tracer is a simple, thin interface for Span creation and SpanContext -// propagation. -type Tracer interface { - - // Create, start, and return a new Span with the given `operationName` and - // incorporate the given StartSpanOption `opts`. (Note that `opts` borrows - // from the "functional options" pattern, per - // http://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis) - // - // A Span with no SpanReference options (e.g., opentracing.ChildOf() or - // opentracing.FollowsFrom()) becomes the root of its own trace. - // - // Examples: - // - // var tracer opentracing.Tracer = ... - // - // // The root-span case: - // sp := tracer.StartSpan("GetFeed") - // - // // The vanilla child span case: - // sp := tracer.StartSpan( - // "GetFeed", - // opentracing.ChildOf(parentSpan.Context())) - // - // // All the bells and whistles: - // sp := tracer.StartSpan( - // "GetFeed", - // opentracing.ChildOf(parentSpan.Context()), - // opentracing.Tag{"user_agent", loggedReq.UserAgent}, - // opentracing.StartTime(loggedReq.Timestamp), - // ) - // - StartSpan(operationName string, opts ...StartSpanOption) Span - - // Inject() takes the `sm` SpanContext instance and injects it for - // propagation within `carrier`. The actual type of `carrier` depends on - // the value of `format`. - // - // OpenTracing defines a common set of `format` values (see BuiltinFormat), - // and each has an expected carrier type. - // - // Other packages may declare their own `format` values, much like the keys - // used by `context.Context` (see https://godoc.org/context#WithValue). - // - // Example usage (sans error handling): - // - // carrier := opentracing.HTTPHeadersCarrier(httpReq.Header) - // err := tracer.Inject( - // span.Context(), - // opentracing.HTTPHeaders, - // carrier) - // - // NOTE: All opentracing.Tracer implementations MUST support all - // BuiltinFormats. - // - // Implementations may return opentracing.ErrUnsupportedFormat if `format` - // is not supported by (or not known by) the implementation. - // - // Implementations may return opentracing.ErrInvalidCarrier or any other - // implementation-specific error if the format is supported but injection - // fails anyway. - // - // See Tracer.Extract(). - Inject(sm SpanContext, format interface{}, carrier interface{}) error - - // Extract() returns a SpanContext instance given `format` and `carrier`. - // - // OpenTracing defines a common set of `format` values (see BuiltinFormat), - // and each has an expected carrier type. - // - // Other packages may declare their own `format` values, much like the keys - // used by `context.Context` (see - // https://godoc.org/golang.org/x/net/context#WithValue). - // - // Example usage (with StartSpan): - // - // - // carrier := opentracing.HTTPHeadersCarrier(httpReq.Header) - // clientContext, err := tracer.Extract(opentracing.HTTPHeaders, carrier) - // - // // ... assuming the ultimate goal here is to resume the trace with a - // // server-side Span: - // var serverSpan opentracing.Span - // if err == nil { - // span = tracer.StartSpan( - // rpcMethodName, ext.RPCServerOption(clientContext)) - // } else { - // span = tracer.StartSpan(rpcMethodName) - // } - // - // - // NOTE: All opentracing.Tracer implementations MUST support all - // BuiltinFormats. - // - // Return values: - // - A successful Extract returns a SpanContext instance and a nil error - // - If there was simply no SpanContext to extract in `carrier`, Extract() - // returns (nil, opentracing.ErrSpanContextNotFound) - // - If `format` is unsupported or unrecognized, Extract() returns (nil, - // opentracing.ErrUnsupportedFormat) - // - If there are more fundamental problems with the `carrier` object, - // Extract() may return opentracing.ErrInvalidCarrier, - // opentracing.ErrSpanContextCorrupted, or implementation-specific - // errors. - // - // See Tracer.Inject(). - Extract(format interface{}, carrier interface{}) (SpanContext, error) -} - -// StartSpanOptions allows Tracer.StartSpan() callers and implementors a -// mechanism to override the start timestamp, specify Span References, and make -// a single Tag or multiple Tags available at Span start time. -// -// StartSpan() callers should look at the StartSpanOption interface and -// implementations available in this package. -// -// Tracer implementations can convert a slice of `StartSpanOption` instances -// into a `StartSpanOptions` struct like so: -// -// func StartSpan(opName string, opts ...opentracing.StartSpanOption) { -// sso := opentracing.StartSpanOptions{} -// for _, o := range opts { -// o.Apply(&sso) -// } -// ... -// } -// -type StartSpanOptions struct { - // Zero or more causal references to other Spans (via their SpanContext). - // If empty, start a "root" Span (i.e., start a new trace). - References []SpanReference - - // StartTime overrides the Span's start time, or implicitly becomes - // time.Now() if StartTime.IsZero(). - StartTime time.Time - - // Tags may have zero or more entries; the restrictions on map values are - // identical to those for Span.SetTag(). May be nil. - // - // If specified, the caller hands off ownership of Tags at - // StartSpan() invocation time. - Tags map[string]interface{} -} - -// StartSpanOption instances (zero or more) may be passed to Tracer.StartSpan. -// -// StartSpanOption borrows from the "functional options" pattern, per -// http://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis -type StartSpanOption interface { - Apply(*StartSpanOptions) -} - -// SpanReferenceType is an enum type describing different categories of -// relationships between two Spans. If Span-2 refers to Span-1, the -// SpanReferenceType describes Span-1 from Span-2's perspective. For example, -// ChildOfRef means that Span-1 created Span-2. -// -// NOTE: Span-1 and Span-2 do *not* necessarily depend on each other for -// completion; e.g., Span-2 may be part of a background job enqueued by Span-1, -// or Span-2 may be sitting in a distributed queue behind Span-1. -type SpanReferenceType int - -const ( - // ChildOfRef refers to a parent Span that caused *and* somehow depends - // upon the new child Span. Often (but not always), the parent Span cannot - // finish until the child Span does. - // - // An timing diagram for a ChildOfRef that's blocked on the new Span: - // - // [-Parent Span---------] - // [-Child Span----] - // - // See http://opentracing.io/spec/ - // - // See opentracing.ChildOf() - ChildOfRef SpanReferenceType = iota - - // FollowsFromRef refers to a parent Span that does not depend in any way - // on the result of the new child Span. For instance, one might use - // FollowsFromRefs to describe pipeline stages separated by queues, - // or a fire-and-forget cache insert at the tail end of a web request. - // - // A FollowsFromRef Span is part of the same logical trace as the new Span: - // i.e., the new Span is somehow caused by the work of its FollowsFromRef. - // - // All of the following could be valid timing diagrams for children that - // "FollowFrom" a parent. - // - // [-Parent Span-] [-Child Span-] - // - // - // [-Parent Span--] - // [-Child Span-] - // - // - // [-Parent Span-] - // [-Child Span-] - // - // See http://opentracing.io/spec/ - // - // See opentracing.FollowsFrom() - FollowsFromRef -) - -// SpanReference is a StartSpanOption that pairs a SpanReferenceType and a -// referenced SpanContext. See the SpanReferenceType documentation for -// supported relationships. If SpanReference is created with -// ReferencedContext==nil, it has no effect. Thus it allows for a more concise -// syntax for starting spans: -// -// sc, _ := tracer.Extract(someFormat, someCarrier) -// span := tracer.StartSpan("operation", opentracing.ChildOf(sc)) -// -// The `ChildOf(sc)` option above will not panic if sc == nil, it will just -// not add the parent span reference to the options. -type SpanReference struct { - Type SpanReferenceType - ReferencedContext SpanContext -} - -// Apply satisfies the StartSpanOption interface. -func (r SpanReference) Apply(o *StartSpanOptions) { - if r.ReferencedContext != nil { - o.References = append(o.References, r) - } -} - -// ChildOf returns a StartSpanOption pointing to a dependent parent span. -// If sc == nil, the option has no effect. -// -// See ChildOfRef, SpanReference -func ChildOf(sc SpanContext) SpanReference { - return SpanReference{ - Type: ChildOfRef, - ReferencedContext: sc, - } -} - -// FollowsFrom returns a StartSpanOption pointing to a parent Span that caused -// the child Span but does not directly depend on its result in any way. -// If sc == nil, the option has no effect. -// -// See FollowsFromRef, SpanReference -func FollowsFrom(sc SpanContext) SpanReference { - return SpanReference{ - Type: FollowsFromRef, - ReferencedContext: sc, - } -} - -// StartTime is a StartSpanOption that sets an explicit start timestamp for the -// new Span. -type StartTime time.Time - -// Apply satisfies the StartSpanOption interface. -func (t StartTime) Apply(o *StartSpanOptions) { - o.StartTime = time.Time(t) -} - -// Tags are a generic map from an arbitrary string key to an opaque value type. -// The underlying tracing system is responsible for interpreting and -// serializing the values. -type Tags map[string]interface{} - -// Apply satisfies the StartSpanOption interface. -func (t Tags) Apply(o *StartSpanOptions) { - if o.Tags == nil { - o.Tags = make(map[string]interface{}) - } - for k, v := range t { - o.Tags[k] = v - } -} - -// Tag may be passed as a StartSpanOption to add a tag to new spans, -// or its Set method may be used to apply the tag to an existing Span, -// for example: -// -// tracer.StartSpan("opName", Tag{"Key", value}) -// -// or -// -// Tag{"key", value}.Set(span) -type Tag struct { - Key string - Value interface{} -} - -// Apply satisfies the StartSpanOption interface. -func (t Tag) Apply(o *StartSpanOptions) { - if o.Tags == nil { - o.Tags = make(map[string]interface{}) - } - o.Tags[t.Key] = t.Value -} - -// Set applies the tag to an existing Span. -func (t Tag) Set(s Span) { - s.SetTag(t.Key, t.Value) -} diff --git a/vendor/modules.txt b/vendor/modules.txt index 55c247ab9..e6b95a357 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -19,7 +19,7 @@ github.com/go-playground/validator/v10 github.com/golang/protobuf/proto # github.com/google/uuid v1.3.0 github.com/google/uuid -# github.com/graph-gophers/graphql-go v1.3.0 +# github.com/graph-gophers/graphql-go v1.4.0 github.com/graph-gophers/graphql-go github.com/graph-gophers/graphql-go/decode github.com/graph-gophers/graphql-go/errors @@ -35,13 +35,14 @@ github.com/graph-gophers/graphql-go/internal/validation github.com/graph-gophers/graphql-go/introspection github.com/graph-gophers/graphql-go/log github.com/graph-gophers/graphql-go/relay -github.com/graph-gophers/graphql-go/trace +github.com/graph-gophers/graphql-go/trace/noop +github.com/graph-gophers/graphql-go/trace/tracer github.com/graph-gophers/graphql-go/types # github.com/hashicorp/go-version v1.5.0 github.com/hashicorp/go-version # github.com/hashicorp/logutils v1.0.0 github.com/hashicorp/logutils -# github.com/hasura/go-graphql-client v0.6.3 +# github.com/hasura/go-graphql-client v0.8.1 github.com/hasura/go-graphql-client github.com/hasura/go-graphql-client/ident github.com/hasura/go-graphql-client/internal/jsonutil @@ -59,10 +60,6 @@ github.com/mattn/go-isatty github.com/modern-go/concurrent # github.com/modern-go/reflect2 v1.0.1 github.com/modern-go/reflect2 -# github.com/opentracing/opentracing-go v1.1.0 -github.com/opentracing/opentracing-go -github.com/opentracing/opentracing-go/ext -github.com/opentracing/opentracing-go/log # github.com/pmezard/go-difflib v1.0.0 github.com/pmezard/go-difflib/difflib # github.com/spf13/cobra v1.1.3