graph_weaver 0.6.1 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. checksums.yaml +4 -4
  2. data/Gemfile +8 -0
  3. data/Gemfile.lock +153 -4
  4. data/README.md +45 -79
  5. data/docs/alternatives.md +195 -0
  6. data/docs/cassettes.md +61 -50
  7. data/docs/editors.md +32 -47
  8. data/docs/errors.md +360 -103
  9. data/docs/federation.md +692 -473
  10. data/docs/generated_modules.md +441 -314
  11. data/docs/getting_started.md +370 -194
  12. data/docs/i18n.md +171 -0
  13. data/docs/logging.md +197 -50
  14. data/docs/real_world.md +42 -27
  15. data/docs/scalars.md +307 -176
  16. data/docs/testing.md +473 -220
  17. data/docs/transports.md +224 -151
  18. data/docs/upgrading.md +258 -305
  19. data/examples/README.md +38 -0
  20. data/examples/countries.rb +39 -0
  21. data/examples/federation.rb +62 -0
  22. data/examples/github/generate.rb +20 -0
  23. data/examples/github/generated/star_mutation.rb +126 -0
  24. data/examples/github/generated/stargazers_query.rb +232 -0
  25. data/examples/github/generated/starred_query.rb +151 -0
  26. data/examples/github/queries/star.graphql +8 -0
  27. data/examples/github/queries/stargazers.graphql +22 -0
  28. data/examples/github/queries/starred.graphql +11 -0
  29. data/examples/github/run.rb +43 -0
  30. data/examples/github/setup.rb +18 -0
  31. data/examples/rick_and_morty.rb +57 -0
  32. data/graph_weaver.gemspec +19 -3
  33. data/lib/generators/graph_weaver/install_generator.rb +138 -4
  34. data/lib/graph_weaver/client.rb +69 -11
  35. data/lib/graph_weaver/codegen/aliases.rb +7 -5
  36. data/lib/graph_weaver/codegen/emit.rb +98 -29
  37. data/lib/graph_weaver/codegen/enum_type.rb +2 -1
  38. data/lib/graph_weaver/codegen/nodes.rb +39 -6
  39. data/lib/graph_weaver/codegen/registry.rb +175 -0
  40. data/lib/graph_weaver/codegen/scalar_type.rb +123 -30
  41. data/lib/graph_weaver/codegen/type_helpers.rb +56 -11
  42. data/lib/graph_weaver/codegen.rb +406 -195
  43. data/lib/graph_weaver/coerce.rb +155 -26
  44. data/lib/graph_weaver/context_seam.rb +54 -0
  45. data/lib/graph_weaver/errors.rb +284 -46
  46. data/lib/graph_weaver/federation.rb +129 -27
  47. data/lib/graph_weaver/graph.rb +315 -0
  48. data/lib/graph_weaver/hints.rb +100 -24
  49. data/lib/graph_weaver/in_process.rb +27 -15
  50. data/lib/graph_weaver/input_struct.rb +119 -32
  51. data/lib/graph_weaver/internal/endpoint.rb +80 -0
  52. data/lib/graph_weaver/internal/headers.rb +70 -0
  53. data/lib/graph_weaver/internal/overrides.rb +67 -5
  54. data/lib/graph_weaver/internal/planner.rb +45 -15
  55. data/lib/graph_weaver/internal/refusal.rb +49 -0
  56. data/lib/graph_weaver/internal/schemas.rb +23 -9
  57. data/lib/graph_weaver/internal/selection.rb +34 -0
  58. data/lib/graph_weaver/internal/server_input.rb +251 -0
  59. data/lib/graph_weaver/internal/test_clients.rb +276 -0
  60. data/lib/graph_weaver/internal/unused.rb +287 -0
  61. data/lib/graph_weaver/internal/values.rb +40 -4
  62. data/lib/graph_weaver/internal.rb +249 -14
  63. data/lib/graph_weaver/log_subscriber.rb +74 -0
  64. data/lib/graph_weaver/logging.rb +163 -19
  65. data/lib/graph_weaver/query_module.rb +44 -3
  66. data/lib/graph_weaver/railtie.rb +237 -17
  67. data/lib/graph_weaver/representation.rb +55 -17
  68. data/lib/graph_weaver/result_struct.rb +90 -0
  69. data/lib/graph_weaver/retry.rb +45 -13
  70. data/lib/graph_weaver/rspec.rb +404 -93
  71. data/lib/graph_weaver/schema_loader.rb +266 -56
  72. data/lib/graph_weaver/tasks.rb +380 -89
  73. data/lib/graph_weaver/testing/cassette.rb +34 -10
  74. data/lib/graph_weaver/testing/endpoint.rb +107 -0
  75. data/lib/graph_weaver/testing/failure.rb +69 -12
  76. data/lib/graph_weaver/testing/fake_client.rb +164 -45
  77. data/lib/graph_weaver/testing/router.rb +64 -13
  78. data/lib/graph_weaver/testing.rb +200 -58
  79. data/lib/graph_weaver/transport/faraday.rb +41 -8
  80. data/lib/graph_weaver/transport/http.rb +48 -6
  81. data/lib/graph_weaver/transport.rb +134 -27
  82. data/lib/graph_weaver/version.rb +1 -1
  83. data/lib/graph_weaver.rb +495 -106
  84. metadata +71 -3
  85. data/CHANGELOG.md +0 -2355
data/docs/scalars.md CHANGED
@@ -1,27 +1,34 @@
1
1
  # Custom scalars
2
2
 
3
- Teach the generator how a GraphQL custom scalar deserializes into a rich
4
- Ruby object (and serializes back when used as a variable). A field typed
5
- `Decimal` then generates `const :price, T.nilable(BigDecimal)` and casts with
6
- `BigDecimal(...)` inline — no runtime reflection:
3
+ Teach the generator how a GraphQL custom scalar deserializes into a rich Ruby
4
+ object, and serializes back when used as a variable. Three registrations cover
5
+ almost every app:
7
6
 
8
7
  ```ruby
9
- GraphWeaver.register_scalar("Decimal", BigDecimal)
8
+ GraphWeaver.register_scalar("Decimal", BigDecimal) # a stdlib class
9
+ GraphWeaver.register_scalar("Money", Money) # a value object of your own
10
+ GraphWeaver.register_enum("Species", PetKind) # a schema enum onto your T::Enum
10
11
  ```
11
12
 
12
- Two arguments: the scalar's name in your schema, and the Ruby type it means.
13
- The second is the only part the library can't work out — how a wire value
14
- becomes a `BigDecimal`, how one goes back on the wire, and the
15
- `require "bigdecimal"` the generated file needs are all inferred.
13
+ `register_scalar` takes the scalar's name in your schema and the Ruby type it
14
+ means. The type is the only part the library can't work out: a field typed
15
+ `Decimal` then generates `const :price, T.nilable(BigDecimal)` and casts with
16
+ `BigDecimal(...)` inline no runtime reflection and the wire spelling and the
17
+ `require "bigdecimal"` the generated file needs come with it.
16
18
 
17
19
  Registration is global and codegen-time: `rake graph_weaver:generate` reads the
18
- same registry an initializer writes, so register before you generate.
20
+ same registry an initializer writes, so register before you generate. A
21
+ registration that goes *missing* later — a reverted initializer line, a bad merge
22
+ — is loud at generate/verify time and silent forever after: code regenerated
23
+ without it casts the field to the plain wire type (a `String` where an `Email`
24
+ was) and nothing raises anywhere. [`verify_generated!`](generated_modules.md) in
25
+ CI is what protects a registration; no runtime assertion can.
19
26
 
20
27
  ## Already registered
21
28
 
22
29
  These names need no registration. graphql-ruby ships all but `DateTime` as its
23
- own scalars, and `DateTime` is what GitHub, Shopify and most hand-written
24
- schemas call an ISO 8601 timestamp.
30
+ own scalars, and `DateTime` is what GitHub, Shopify and most hand-written schemas
31
+ call an ISO 8601 timestamp.
25
32
 
26
33
  | scalar | Ruby type | on the wire |
27
34
  |---|---|---|
@@ -35,32 +42,45 @@ schemas call an ISO 8601 timestamp.
35
42
  | `BigInt` | `Integer` | the decimal string graphql-ruby writes; a JSON number is read too |
36
43
  | `JSON` | `T.untyped` | whatever it is, untouched |
37
44
 
38
- A date stays a `Date` and a timestamp a `Time`, deliberately: casting a date to
39
- `Time` invents a midnight the server never sent. A schema that means something
40
- else by one of these names fails loudly the cast raises, naming the field —
41
- and one `register_scalar` overrides it, like any other entry. Names that are
42
- *not* a convention (`Timestamp`, `UUID`, `URL`, `Decimal`, `Money`) are left to
43
- you, because guessing at one would be worse than asking.
45
+ **A date stays a `Date` and a timestamp a `Time`**, in both directions: casting a
46
+ date to `Time` invents a midnight the server never sent, and sending a `Time` for
47
+ a date variable drops the time of day. Give one for the other and it is refused,
48
+ naming the class `$on of Report: expected a Date, got a Time pass .to_date if
49
+ dropping the time of day is what you meant`. A `cast:` of your own doesn't change
50
+ that: a cast says how the object is *built*, not which values are right. The
51
+ refusal is about Ruby **objects**; a timestamp *string* given for a `Date` parses
52
+ and truncates to its date, as graphql-ruby's own `ISO8601Date` does.
53
+
54
+ A schema that means something else by one of these names fails loudly, and one
55
+ `register_scalar` overrides it like any other entry. Names that are *not* a
56
+ convention (`Timestamp`, `UUID`, `URL`, `Decimal`, `Money`) are left to you,
57
+ because guessing at one would be worse than asking.
44
58
 
45
59
  ## Registering a stdlib type
46
60
 
47
61
  Name the class and stop. What the library supplies is the part inference can't
48
- reach: the wire spelling (`BigDecimal#to_s` writes `"0.125e2"`, which is not
49
- what any server means by 12.5, and `Date.parse` reads far more than the ISO
50
- 8601 a `Date` scalar carries) and the file to require, so the generated source
51
- stands alone.
62
+ reach: the wire spelling (`BigDecimal#to_s` writes `"0.125e2"`, which is not what
63
+ any server means by 12.5) and the file to require, so the generated source stands
64
+ alone.
52
65
 
53
66
  | Ruby type | cast | serialize | require |
54
67
  |---|---|---|---|
55
68
  | `BigDecimal` | `BigDecimal(v)` | `v.to_s("F")` | `bigdecimal` |
56
- | `Date` | `Date.iso8601(v)` | `v.iso8601` | `date` |
57
- | `Time` | `Time.parse(v)` | `v.iso8601` | `time` |
58
- | `DateTime` | `DateTime.iso8601(v)` | `v.iso8601` | `date` |
59
-
60
- For a timestamp, reach for `Time`; Ruby's own `DateTime` is accepted if you
61
- register it, but never assumed. `BigDecimal(v)` is Ruby's own reader, so
62
- it takes what Ruby takes — `"12.5"`, `"1e3"`, a JSON number and refuses
63
- `"abc"` or `"$12.50"`, naming the field or the variable.
69
+ | `Float` | `GraphWeaver::Coerce.float(v)` | | |
70
+ | `Date` | `Date.iso8601(v)` | `v.strftime("%F")` | `date` |
71
+ | `Time` | `Time.parse(v)` | `GraphWeaver::Coerce.timestamp(v)` | `time` |
72
+ | `DateTime` | `DateTime.iso8601(v)` | `GraphWeaver::Coerce.timestamp(v)` | `date` |
73
+
74
+ For a timestamp reach for `Time`; Ruby's own `DateTime` is accepted if you
75
+ register it, but never assumed. `Time.parse` is the tolerant reader, and about 7×
76
+ the cost of a strict one noise until you are casting thousands of timestamps per
77
+ response, where `register_scalar("Timestamp", Time, cast: :iso8601)` is both
78
+ cheaper and narrower.
79
+
80
+ **A trailing zero doesn't survive the round trip.** A `BigDecimal` holds the
81
+ *number*, so `"10.00"` in comes back `"10.0"` — numerically identical, textually
82
+ different, which matters only where the bytes are: diffing a request body, or
83
+ hashing one for a signature.
64
84
 
65
85
  ## Registering a class of your own
66
86
 
@@ -73,98 +93,177 @@ deserialize side and pairing its serializer:
73
93
  | `.load` | `Type.load(v)` | `Type.dump(v)` |
74
94
  | `Kernel#Type` | `Type(v)` | — |
75
95
 
76
- so a value object with a `.parse` needs nothing more:
96
+ so a value object with a `.parse` needs nothing more than
97
+ `GraphWeaver.register_scalar("Money", Money)`.
98
+
99
+ **Give it `eql?` and `hash` too, not just `==`.** A result compares its props with
100
+ `eql?`, so a class that stops at `==` makes two results parsed from the same
101
+ response unequal, and useless as hash keys, while the `Money` inside them compares
102
+ fine. Registration warns when it spots one; `alias_method :eql?, :==` plus a
103
+ `hash` built from the same values is the whole fix.
104
+
105
+ A type defining none of those probes stays pass-through rather than getting
106
+ wrapped — every object has `#to_s`, so inferring a serializer off it would wrap
107
+ plain types too. Override explicitly when you need to:
108
+
109
+ - a `Symbol` method name: `cast: :load` → `Money.load(expr)`, `serialize: :to_json`
110
+ - an `Array`, for a method with arguments: `serialize: [:to_s, "F"]` →
111
+ `expr.to_s("F")`
112
+ - a `Proc` for anything a method name can't express:
113
+ `cast: ->(expr) { "Money.new(#{expr})" }` — it returns **source, not a value**,
114
+ since what comes back is inlined into `from_h`
115
+ - `:itself` to force pass-through, opting out of inference (rare)
116
+
117
+ The type also accepts a plain string (`"Money"`) when you'd rather not reference
118
+ the class, which **skips inference entirely** — there is no class in hand to
119
+ probe. `requires:` (a string or array) names files emitted as `require`s atop the
120
+ generated source so the cast and type resolve; where the type is a real class each
121
+ path is also `require`d at registration, so a typo fails now rather than in the
122
+ generated file.
123
+
124
+ **Register what your cast returns, not where the factory method lives.**
125
+ `register_scalar("URL", URI)` looks right and runs fine — `URI.parse` is a probe
126
+ hit — but `URI` is a *module*, and Sorbet's payload for it doesn't `include
127
+ Kernel`, so every call site fails `srb tc` with "Method `nil?` does not exist on
128
+ `URI`". The value is a `URI::Generic`:
77
129
 
78
130
  ```ruby
79
- GraphWeaver.register_scalar("Money", Money)
131
+ GraphWeaver.register_scalar("URL", URI::Generic, cast: ->(v) { "URI.parse(#{v})" })
80
132
  ```
81
133
 
82
- A type defining none of those stays pass-through rather than getting wrapped —
83
- every object has `#to_s`, so inferring a serializer off it would wrap plain
84
- types too. Override explicitly when you need to:
134
+ `URI.parse` is ASCII-only, so a server writing an un-escaped unicode path raises
135
+ `URI must be ascii only` a clean `CastError`, but a refusal of a URL that is
136
+ fine. Escape in the cast (`URI::DEFAULT_PARSER.escape(#{v})`), or register
137
+ [Addressable](https://github.com/sporkmonger/addressable) instead.
85
138
 
86
- - a `Symbol` method name, nothing to misspell: `cast: :load` → `Money.load(expr)`,
87
- `serialize: :to_json` → `expr.to_json`
88
- - an `Array`, for a method with arguments: `serialize: [:to_s, "F"]` → `expr.to_s("F")`
89
- - a `Proc` for anything a method name can't express: `cast: ->(expr) { "Money.new(#{expr})" }`
90
- - `:itself` to force pass-through, opting out of inference (rare)
139
+ ### When the wire shape decides the registration
91
140
 
92
- The type also accepts a plain string (`"Money"`) when you'd rather not
93
- reference the class. `requires:` (a string or array) names files emitted as
94
- `require`s atop the generated source so the cast/type resolve. When the type is
95
- a real class (so the runtime is loaded), each path is also `require`d at
96
- registration — a typo fails now, not in the generated file.
141
+ The money gem's `Money` is the honest hard case: it defines none of the probes,
142
+ and `Money.from_amount` needs a currency no amount of Ruby recovers if the
143
+ response didn't send one. **A cast can only use what the wire carries**, so the
144
+ scalar's shape decides what you write.
145
+
146
+ An **object** — `{"amount": "12.50", "currency": "EUR"}` — is read out in the cast
147
+ and written back by `serialize:`:
148
+
149
+ ```ruby
150
+ GraphWeaver.register_scalar("Money", Money,
151
+ cast: ->(v) { "Money.from_amount(BigDecimal(#{v}[\"amount\"]), #{v}[\"currency\"])" },
152
+ serialize: ->(v) { "{ \"amount\" => #{v}.amount.to_s(\"F\"), \"currency\" => #{v}.currency }" })
153
+ ```
154
+
155
+ **One string carrying both** — `"12.50 EUR"` — splits in the cast, with
156
+ `serialize: :to_s` writing it back. A **bare decimal string** carries no currency,
157
+ so the cast supplies one; reach for that only when the API really is
158
+ single-currency, and say so where the next reader will look:
159
+
160
+ ```ruby
161
+ # single-currency API: a Money in any other currency comes back mislabelled
162
+ GraphWeaver.register_scalar("Money", Money,
163
+ cast: ->(v) { "Money.from_amount(BigDecimal(#{v}), \"USD\")" },
164
+ serialize: :to_s)
165
+ ```
166
+
167
+ **An object type rather than a scalar** — `Money { amount currency }` — needs no
168
+ `register_scalar` at all: codegen types both fields, and
169
+ [`extend_type`](generated_modules.md#type-helpers) adds the conversion. Ask for
170
+ this shape if you get a vote; the currency is then in the schema, where a reader
171
+ finds it.
172
+
173
+ ```ruby
174
+ GraphWeaver.extend_type("Money") { def to_money = ::Money.from_amount(BigDecimal(amount), currency) }
175
+ ```
176
+
177
+ **One `serialize:` serves both directions** — the outbound variable *and* a
178
+ result's [`as_json`](generated_modules.md#anatomy), which is what makes
179
+ `from_h(JSON.parse(x.to_json)) == x` hold. So a scalar that sends an object and
180
+ accepts a string can't have both: `as_json` writes the string the cast can't read,
181
+ and the JSON round trip raises a `CastError` coming back (the wire itself is fine
182
+ in both directions). The same asymmetry decides the [`:fake` pin](testing.md#pins):
183
+ a pin stands in for a *result*, so pin what the server **sends**.
184
+
185
+ Any of this can also be flatly wrong: the *format* a `Money` string has to match
186
+ lives in the server's `coerce_input`, which no schema carries, so nothing before a
187
+ real request says whether the server wants `"12.50"`, `"12.50 USD"` or the object.
188
+ [Send one for real](#what-no-check-can-see).
97
189
 
98
190
  ## Overriding one field
99
191
 
100
- Pass a `Type.field` **coordinate** instead of a scalar name to override just
101
- that one field so the same scalar can deserialize as different Ruby types
102
- across fields:
192
+ Pass a `Type.field` **coordinate** instead of a scalar name to override just that
193
+ one field, so the same scalar can deserialize as different Ruby types across
194
+ fields — and so two servers that disagree about a `DateTime` can coexist in one
195
+ process:
103
196
 
104
197
  ```ruby
105
198
  GraphWeaver.register_scalar("Timestamp", Time) # the default, everywhere
106
199
  GraphWeaver.register_scalar("User.birthday", Date) # this field only
107
200
  ```
108
201
 
109
- A field override wins over the scalar-name registration — which is also how two
110
- servers that disagree about a `DateTime` coexist in one process.
111
-
112
- Registrations are validated against the schema you generate against, and only
113
- what that schema can **disprove** fails generation: a name it declares as
114
- something else (`register_scalar("Species")` where `Species` is an enum), or a
115
- coordinate whose field it declares as a composite. A name it simply can't match
116
- only warns one registry serves a whole graph, so that name may belong to the
117
- subgraph next door (see
118
- [federation](federation.md#generating-for-a-federated-graph)).
119
-
120
- The testing harness can't invent a wire value for a scalar registered as your
121
- own class only `Money.parse` knows what it accepts so it refuses rather than
122
- guess. Say it in test config, where that answer belongs: a pin for the type,
123
- `GraphWeaver::Testing.config.overrides = { "Money" => "12.00" }`, or per example
124
- ([testing pins](testing.md#pins)). A scalar registered as one of the types
125
- above `BigDecimal`, `Time`, `Date`, `Integer`, `Float`, `String`,
126
- `T::Boolean` — needs nothing.
202
+ A coordinate takes a **type string** too, which is how you narrow `JSON`: the
203
+ scalar can legally be any JSON value, so the registry's answer for the whole scalar
204
+ stays `T.untyped`, but where *you* know one field's shape, say it there —
205
+ `register_scalar("Settings.meta", "T::Hash[String, T.untyped]")`. `srb tc` then
206
+ sees a Hash at every call site, and a response carrying something else is refused
207
+ naming the struct rather than surfacing as a `NoMethodError` three layers on.
208
+ That's a trade: an array the scalar allowed becomes a hard failure, and the field
209
+ opts out of `:fake` fabrication, so pin it
210
+ (`overrides: { "Settings.meta" => { ... } }`).
211
+
212
+ ## What generation refuses, and what it only warns about
213
+
214
+ Registrations are validated against the schema you generate against, and only what
215
+ that schema can **disprove** fails generation: a name it declares as something else
216
+ (`register_scalar("Species")` where `Species` is an enum), or a coordinate whose
217
+ field it declares as a composite. A name it simply can't match only warns — one
218
+ registry serves a whole graph, so that name may belong to the subgraph next door
219
+ (see [federation](federation.md#generating-for-a-federated-graph)).
127
220
 
128
221
  A registration whose type is a class **JSON can't parse into**, with nothing to
129
222
  build one, is refused where a query reads that scalar back: the prop would be
130
- unsatisfiable for every response, and finding that out at runtime is worse.
131
- Generation names the field:
223
+ unsatisfiable for every response. The message names the field and which of the two
224
+ mistakes you made — `Wallet defines no .parse and no .load, and Kernel has no
225
+ Wallet conversion function, so there was nothing to infer`, or, for a type given
226
+ by name, that a name is never probed. A registration used only for a variable is
227
+ untouched: nothing casts it.
228
+
229
+ A scalar you never register is not an error — it generates as `T.untyped` and the
230
+ wire value passes through untouched. It is the one hole in an otherwise exact
231
+ result type, so generation names the holes; `rake graph_weaver:generate` and
232
+ `:verify` print them once for the run, and `GraphWeaver.parse` says the same at
233
+ `info`:
132
234
 
133
235
  ```
134
- register_scalar("Money", Wallet) has no cast, so nothing builds a Wallet
135
- out of the JSON at Product.price — give it one ...
136
- ```
137
-
138
- A registration used only for a variable is untouched: nothing casts it.
139
-
140
- `cast:` is also what a *variable* of this scalar coerces through, so the same
141
- registration gets you both directions with nothing to switch on:
142
-
143
- ```ruby
144
- GraphWeaver.register_scalar("Money", Money)
145
- StoreQuery.execute(budget: "12.00") # Money.parse("12.00") under the hood
146
- StoreQuery.execute(budget: Money.new(1200)) # already a Money — passed straight through
236
+ 3 unregistered custom scalars → T.untyped: CountryCode, FuzzyDateInt, Json (register with GraphWeaver.register_scalar)
147
237
  ```
148
238
 
149
- The kwarg is still typed `Money`, not `T.any(Money, String)`: `execute`'s sig
150
- stays as narrow as the schema and the conversion happens in its body (see
151
- [typed variables](generated_modules.md#variables-become-typed-kwargs)). So
152
- `budget: "12.00"` written literally in a `# typed:` file is still an `srb tc`
153
- error as it should be, since you have a `Money` right there while
154
- `budget: params[:budget]` typechecks and converts.
155
-
239
+ A scalar that is *meant* to be untyped belongs in the registry too —
240
+ `GraphWeaver.register_scalar("Json", "T.untyped")` says so once and leaves the
241
+ report. `JSON` is registered that way already.
242
+
243
+ The testing harness can't invent a wire value for a scalar registered as your own
244
+ class — only `Money.parse` knows what it accepts — so it refuses rather than
245
+ guess. Say it in test config: `Testing.config.overrides = { "Money" => "12.00" }`,
246
+ or per example ([testing → pins](testing.md#pins)). A scalar registered as one of
247
+ the stdlib types above needs nothing.
248
+
249
+ `GraphWeaver.reset_registrations!` is the clean slate between tests (built-in
250
+ scalars restored, enum mappings and type helpers dropped);
251
+ `GraphWeaver.reset_graphs!` is its twin for declared graphs, and
252
+ `GraphWeaver::Codegen` has the pieces for one registry rather than all of them —
253
+ `reset_scalars!`, `clear_scalars!`, `reset_enums!`, `reset_type_helpers!`. Scoping
254
+ registrations to one of several schemas is not what any of that is for: a
255
+ [graph](getting_started.md#more-than-one-schema) block does that, and holds both
256
+ sets at once instead of resetting between them.
156
257
 
157
258
  ## What the wire carries
158
259
 
159
- The rule is one sentence: **generated code takes every JSON spelling a
160
- spec-compliant server may write, and refuses the rest.** The tables below are
161
- the whole of it, and [`bin/round-trip`](../bin/round-trip) fuzzes both
162
- directions against them — the accepted spellings as real values, the refused
163
- ones under `--hostile`, where generated code has to name what it turned down.
260
+ One sentence: **generated code takes every JSON spelling a spec-compliant server
261
+ may write, and refuses the rest.** The tables below are the whole of it, and
262
+ [`bin/round-trip`](../bin/round-trip) fuzzes both directions against them.
164
263
 
165
- The one place "spec-compliant" is doing real work is `Float`. JSON has a single
264
+ The one place "spec-compliant" is doing real work is `Float`: JSON has a single
166
265
  number type and encoders write the shortest form, so `1.0` reaches Ruby as `1`
167
- from graphql-js and from Go. Nothing does the reverse: `2.0` for an `Int` is the
266
+ from graphql-js and from Go. Nothing does the reverse `2.0` for an `Int` is the
168
267
  server writing a non-integer where the spec says integer, so it is refused.
169
268
 
170
269
  ### Coming back — what `from_h` accepts
@@ -182,22 +281,19 @@ server writing a non-integer where the spec says integer, so it is refused.
182
281
  | an enum | a declared value, as a string | an undeclared value, a non-string |
183
282
  | `JSON`, or unregistered | anything — `T.untyped`, straight through | nothing |
184
283
 
185
- A refusal is a [`GraphWeaver::TypeError`](errors.md) naming the field and the
186
- generated struct (which names the query). Two refusals carry advice rather than
187
- only sorbet's words: an unquoted `ID`, and a registration with no cast (above).
188
-
189
- Numeric strings — here, and in the going-out table below are read as a wire
190
- format, not as Ruby source: `"010"` is ten, and `"0x1f"` and `"1_0"` are
191
- refused. `Kernel#Integer` and `Kernel#Float` accept all three as literals,
192
- which would let a zero-padded form field silently mean something else.
284
+ A refusal is a [`GraphWeaver::CastError`](errors.md) naming the field and the
285
+ generated struct (which names the query). Numeric strings here and in the table
286
+ below are read as a wire format, not as Ruby source: `"010"` is ten, and `"0x1f"`
287
+ and `"1_0"` are refused, where `Kernel#Integer` would take all three and let a
288
+ zero-padded form field silently mean something else.
193
289
 
194
290
  ### Going out — what a variable kwarg accepts
195
291
 
196
- The kwarg's **type** is what `srb tc` holds a call site to, and it is exactly
197
- what the schema says. The **value** reaching `execute` at runtime is coerced,
198
- because a Rails param is a String whatever the sig says (see
199
- [typed variables](generated_modules.md#variables-become-typed-kwargs) for why
200
- the sig is `.checked(:never)`).
292
+ The kwarg's **type** is what `srb tc` holds a call site to, and it is exactly what
293
+ the schema says. The **value** reaching `execute` at runtime is coerced, because a
294
+ Rails param is a String whatever the sig says (see
295
+ [typed variables](generated_modules.md#variables-become-typed-kwargs) for why the
296
+ sig is `.checked(:never)`).
201
297
 
202
298
  | scalar | kwarg is typed | also accepts, at runtime | on the wire |
203
299
  |---|---|---|---|
@@ -206,65 +302,104 @@ the sig is `.checked(:never)`).
206
302
  | `String` | `String` | nothing | the string |
207
303
  | `ID` | `String` | an `Integer` — `execute(id: user.id)` | the string |
208
304
  | `Boolean` | `true`/`false` | nothing | the boolean |
209
- | `Date` | `Date` | an ISO-8601 string | `iso8601` |
210
- | `Time` | `Time` | a string `Time.parse` takes | `iso8601` |
305
+ | `Date` | `Date` | an ISO-8601 string | `"2024-01-15"` |
306
+ | `Time` | `Time` | a string `Time.parse` takes, a `DateTime`, `Time.zone.now` | ISO 8601, with microseconds when the value carries a fraction |
211
307
  | `BigInt` | `Integer` | a decimal string | the decimal string, which is what the server writes |
212
308
  | an enum | the member **or** its wire value | — | the wire value |
213
309
  | an input object | the struct **or** a Hash | — | the wire hash |
214
310
  | a registered custom scalar | its Ruby type | whatever its cast takes | what its serialize writes |
215
311
  | `JSON`, or unregistered | `T.untyped` | anything | straight through |
216
312
 
217
- Two rows are judgment calls worth stating. **`ID` takes an `Integer`** because
218
- the GraphQL spec says an ID serializes as a string but accepts an integer input,
219
- and `execute(id: user.id)` off a model is the everyday call; `String` gets no
220
- such license, since an `Integer` where a `String` belongs is more often a bug
221
- than a spelling. **`Boolean` takes no string** Ruby has no `Kernel#Boolean`,
222
- so every rule for reading `"0"`, `"off"`, `"no"` is somebody's convention, and
223
- the library will not pick one for you; convert at the call site.
313
+ The **on the wire** column is also what a result's
314
+ [`#as_json`/`#to_json`](generated_modules.md#anatomy) writes, so a result read back
315
+ with `from_h` equals the one you rendered.
316
+
317
+ Three rows are judgment calls. **`ID` takes an `Integer`** because the spec says an
318
+ ID serializes as a string but accepts an integer input, and `execute(id: user.id)`
319
+ off a model is the everyday call; `String` gets no such license. **`Boolean` takes
320
+ no string**, because every rule for reading `"0"`, `"off"`, `"no"` is somebody's
321
+ convention. **A `Date` and a `Time` are not each other**, as above; what *is*
322
+ accepted for a `Time` is anything that already is one.
224
323
 
225
324
  Anything the table refuses raises `GraphWeaver::InputError` naming the variable,
226
- the operation and the value — `$count of Compute: expected an Int, got "lots"`
227
- which is the same [422 rescue point](errors.md) as a bad input-object field.
228
- Input-object fields go through this table too, so `{first: "20"}` inside a
229
- filter hash reads the same as `first: "20"` as a kwarg.
230
-
231
- `GraphWeaver.reset_registrations!` is the clean slate between tests, or between
232
- generations for different schemas: built-in scalars restored, enum mappings and
233
- type helpers dropped. To reset one registry rather than all of them,
234
- `GraphWeaver::Codegen` has the pieces
235
- `reset_scalars!` (restore the built-ins), `clear_scalars!` (empty the registry
236
- entirely), `reset_enums!`, `reset_type_helpers!`.
237
-
238
- A scalar you never register is not an error it generates as `T.untyped` and
239
- the wire value passes through untouched. It is, though, the one hole in an
240
- otherwise exact result type, so generation names the holes at `info` (see
241
- [logging](logging.md)):
325
+ the operation and the value — `$count of Compute: expected an Int, got "lots"`
326
+ which is the same [422 rescue point](errors.md) as a bad input-object field. The
327
+ type is named the way the **schema** names it, so a `register_scalar("Money",
328
+ BigDecimal)` field refuses a `Money`, in `#message` and in `#details[:type]` alike.
329
+ Input-object fields go through this table too, so `{first: "20"}` inside a filter
330
+ hash reads the same as `first: "20"` as a kwarg. When it is the **server's**
331
+ scalar that refuses, its `GraphQL::CoercionError` earns a specific
332
+ [`kind`](errors.md#what-an-inputerror-says-without-reading-english) only where its
333
+ message matches one of graphql-ruby's own explanations, or it raises with
334
+ `extensions: { "input" => … }`
335
+ ([the convention](errors.md#what-your-server-can-send)).
336
+
337
+ A custom scalar's `cast:` is what a *variable* of that scalar coerces through, so
338
+ one registration gets you both directions:
242
339
 
243
- ```
244
- 3 unregistered custom scalars → T.untyped: CountryCode, FuzzyDateInt, Json (register with GraphWeaver.register_scalar)
340
+ ```ruby
341
+ StoreQuery.execute(budget: "12.00") # Money.parse("12.00") under the hood
342
+ StoreQuery.execute(budget: Money.new(1200)) # already a Money — passed straight through
245
343
  ```
246
344
 
247
- A scalar that is *meant* to be untyped belongs in the registry too
248
- `GraphWeaver.register_scalar("Json", "T.untyped")` says so once, and it leaves
249
- the report. `JSON` is registered that way already.
345
+ The kwarg is still typed `Money`, not `T.any(Money, String)`: the sig stays as
346
+ narrow as the schema and the conversion happens in `execute`'s body. So
347
+ `budget: "12.00"` written literally in a `# typed:` file is still an `srb tc` error
348
+ — as it should be, since you have a `Money` right there — while
349
+ `budget: params[:budget]` typechecks and converts.
250
350
 
251
- ## Enums: map onto your own T::Enum
351
+ **Writing the scalar on the server too?** graphql-ruby calls a *nullable* scalar
352
+ argument's `coerce_input` with `nil` for an explicit `null` — only `NonNull`
353
+ short-circuits — so a coercer written like the examples above raises
354
+ `NoMethodError` on nil. Guard it, or `:in_process` will show it to you as a
355
+ `ServerError`.
356
+
357
+ ## What no check can see
252
358
 
253
- By default a schema enum generates one `T::Enum` per schema, shared by every
254
- query module that touches it (`GraphQLTypes::Species`, aliased as
255
- `AddPetMutation::Species`). That's fine until your app has its own domain
256
- enum, and then the boundary shuffle starts:
359
+ A custom scalar has two definitions that have to agree: the server's
360
+ `coerce_input`/`coerce_result`, and your `register_scalar`. **No schema carries the
361
+ first one.** A scalar's SDL is its name, a description and a `@specifiedBy` url —
362
+ the coercers are Ruby method bodies that never reach a dump — so a server
363
+ switching `coerce_result` from a decimal string to a JSON number, same scalar,
364
+ same name, moves nothing `verify`, `schema:diff` or `generate` reads. All three
365
+ stay green, and `BigDecimal` then takes the Float without complaint:
257
366
 
258
367
  ```ruby
259
- # your domain already speaks PetKind — it's in your models, your
260
- # ActiveRecord enum column, your case statements
261
- class PetKind < T::Enum
262
- enums { Cat = new("cat"); Dog = new("dog") }
368
+ BigDecimal(BigDecimal("123456789.123456789").to_f).to_s("F") # => "123456789.1234567"
369
+ ```
370
+
371
+ No `CastError`, no warning just totals quietly wrong past the seventh
372
+ significant figure, which is the precision a string-valued `Decimal` exists to
373
+ protect.
374
+
375
+ The check is a request that runs the real coercers: one `graphql: :in_process`
376
+ example per registered scalar, round-tripping a value through the schema class.
377
+
378
+ ```ruby
379
+ it "round-trips a Money through the real server", graphql: :in_process do
380
+ price = Money.from_amount(BigDecimal("12.50"), "EUR")
381
+ expect(EchoPriceQuery.execute!(price:).echo_price).to eq price
263
382
  end
383
+ ```
384
+
385
+ Four lines, and it fails the moment either side moves. **`graphql: :fake` cannot
386
+ stand in for it**: a fake fabricates from your *client* registration alone, so it
387
+ hands back a value the real server would never send and accepts one the real
388
+ server would reject. It is shape-correct, never rule-correct. A
389
+ [cassette](cassettes.md) recorded against `:in_process` carries the rules to a
390
+ suite that can't boot the schema class.
264
391
 
265
- # without a mapping, every call site converts by hand, in both directions
266
- kind = PetKind.deserialize(pet.species.serialize.downcase) # response -> domain
267
- AddPetMutation.execute!(species: kind.serialize.upcase) # domain -> wire
392
+ ## Enums: map onto your own T::Enum
393
+
394
+ By default a schema enum generates one `T::Enum` per schema, shared by every query
395
+ module that touches it (`GraphQLTypes::Species`, aliased as
396
+ `AddPetMutation::Species`). That's fine until your app has its own domain enum —
397
+ one that is persisted, or matched in business logic — and then every call site
398
+ converts by hand, in both directions:
399
+
400
+ ```ruby
401
+ kind = PetKind.deserialize(pet.species.serialize.downcase) # response -> domain
402
+ AddPetMutation.execute!(species: kind.serialize.upcase) # domain -> wire
268
403
  ```
269
404
 
270
405
  Register the mapping once and the seam disappears — generated code speaks your
@@ -273,40 +408,36 @@ enum everywhere, casting wire values in and serializing members out:
273
408
  ```ruby
274
409
  GraphWeaver.register_enum("Species", PetKind)
275
410
 
276
- pet.species # => PetKind::Dog — compare, case, persist directly
277
- pet.species == other_pet.species # same type across every query
411
+ pet.species # => PetKind::Dog — compare, case, persist directly
412
+ pet.species == other_pet.species # same type across every query
278
413
  AddPetMutation.execute!(species: PetKind::Cat) # or "CAT" — members and wire values both work
279
414
  ```
280
415
 
281
- **When to reach for it**: the enum has a life outside the API — it's
282
- persisted or matched in business logic. **When not to bother**: values you
283
- only read back out of responses; the generated enum is already one type
284
- across every query and needs zero setup.
416
+ For values you only ever read back out of responses, don't bother: the generated
417
+ enum is already one type across every query and needs zero setup.
285
418
 
286
419
  The mapping is inferred by name (`"CAT"` ↔ `PetKind::Cat`,
287
- case/underscore-insensitive against each member's serialized value), so
288
- aligned enums need only the one line. When names diverge, `map:` pins the
289
- exceptions and merges over inference:
290
-
291
- ```ruby
292
- GraphWeaver.register_enum("Species", PetKind, map: { "FELINE" => PetKind::Cat })
293
- ```
420
+ case/underscore-insensitive against each member's serialized value), so aligned
421
+ enums need only the one line. When names diverge, `map:` pins the exceptions and
422
+ merges over inference:
423
+ `GraphWeaver.register_enum("Species", PetKind, map: { "FELINE" => PetKind::Cat })`.
294
424
 
295
425
  Two safety properties do the real work:
296
426
 
297
- - **Exhaustiveness at generation**: every value the schema declares must
298
- resolve to a member, or generation fails naming the gaps
299
- (`PetKind has no member for Species value(s) DOG — add them, pin with
300
- map:, or absorb with fallback:`). Your enum drifting from the server's
301
- is caught at `rake graph_weaver:generate`, not in production.
302
- - **`fallback:` for forward-compat**: `fallback: PetKind::Unknown` makes
303
- *casting* absorb wire values the server added after you generated
304
- responses keep flowing instead of raising. Inputs stay strict either
305
- way: a typo'd input is your bug, not drift.
306
-
307
- The translation tables are emitted into the generated source
308
- (`SPECIES_FROM_WIRE` / `SPECIES_TO_WIRE`) — reviewable in the diff, no
309
- runtime registry.
427
+ - **Exhaustiveness at generation**: every value the schema declares must resolve to
428
+ a member, or generation fails naming the gaps (`PetKind has no member for
429
+ Species value(s) DOG — add them, pin with map:, or absorb with fallback:`), so
430
+ your enum drifting from the server's is caught by `rake graph_weaver:generate`,
431
+ not in production.
432
+ - **`fallback:` for forward-compat**: `fallback: PetKind::Unknown` makes *casting*
433
+ absorb wire values the server added after you generated, so responses keep
434
+ flowing instead of raising. Inputs stay strict either way: a typo'd input is your
435
+ bug, not drift. A union or interface absorbs the same drift with no registration
436
+ — a member added upstream lands in the catch-all `Other` its dispatch always
437
+ carries ([generated modules](generated_modules.md#abstract-types)).
438
+
439
+ The translation tables are emitted into the generated source (`SPECIES_FROM_WIRE` /
440
+ `SPECIES_TO_WIRE`) — reviewable in the diff, no runtime registry.
310
441
 
311
442
  Decorating a generated *struct* with your own methods is the sibling API —
312
443
  `extend_type`, in [generated modules](generated_modules.md#type-helpers).