Repository navigation
feat: Remote schemas - #29
Conversation
|
Warning Rate limit exceeded
Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 25 minutes and 11 seconds. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (7)
📝 WalkthroughWalkthroughAdds end-to-end remote GraphQL schema support: new Remote modules for discovery, HTTP fetch and introspection-to-SDL conversion; Schema macro compile-time validation and injection for remote configs; Mix tasks to fetch/check remote schemas; a RemoteNotFetchedError; tests, fixtures, docs, and small config updates. Changes
Sequence Diagram(s)sequenceDiagram
actor User
participant MixFetch as "mix graphql_query.schema.fetch"
participant Remote as "GraphqlQuery.Schema.Remote"
participant HttpClient as "Remote.HttpClient"
participant FS as "Filesystem"
User->>MixFetch: run(args)
MixFetch->>Remote: discover_remote_schemas()
Remote-->>MixFetch: [schema_info...]
loop each schema_info
MixFetch->>Remote: fetch_schema(schema_info)
Remote->>HttpClient: fetch/2 or introspect/2
HttpClient-->>Remote: {:ok, sdl} / {:error, reason}
alt {:ok, sdl}
Remote->>FS: save_schema(path, sdl)
FS-->>Remote: :ok
Remote-->>MixFetch: {:ok, path}
else {:error, reason}
Remote-->>MixFetch: {:error, reason}
end
end
MixFetch-->>User: summary (successes / failures)
sequenceDiagram
participant CompileTime as "Compile Time"
participant Macro as "GraphqlQuery.Schema Macro"
participant Generated as "Generated Module"
CompileTime->>Macro: use GraphqlQuery.Schema(remote: ...)
Macro->>Macro: validate options (reject invalid combos)
Macro->>Macro: resolve schemas_dir & schema_path
Macro->>Generated: inject build_request/1, schema/0, schema_path/0, metadata
Generated-->>CompileTime: module compiled
Generated->>Generated: at runtime, schema/0 reads file or raises RemoteNotFetchedError
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches✨ Simplify code
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 8
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
README.md (1)
844-850:⚠️ Potential issue | 🟡 MinorMove the completed roadmap item out of Planned.
Line 849 is checked off but still listed under
### Planned; move it to### Doneto keep the roadmap readable.📝 Proposed roadmap cleanup
### Planned - [ ] When validation error, try to detect if it's in a fragment, and if it's an "imported" fragment, print the error in the fragment's location -- [x] Configure schemas with remote URLs to fetch, and have a mix task to check if the content differs - [ ] Optional compile-time validation via Mix task - [ ] Fix line reporting on validation errors on gql on expanded code ### Done +- [x] Configure schemas with remote URLs to fetch, and have a mix task to check if the content differs - [x] Validate queries with sigil🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@README.md` around lines 844 - 850, The checked roadmap item "- [x] Configure schemas with remote URLs to fetch, and have a mix task to check if the content differs" should be moved out of the "### Planned" section and placed under a new or existing "### Done" section; update the README so that the "Planned" list no longer contains the completed "- [x] Configure schemas..." entry and add that exact line (including the checked box) under "### Done" to reflect completion.
🧹 Nitpick comments (9)
test/mix/tasks/graphql_query_schema_check_test.exs (1)
43-104: Integration tests don't actually exerciseSchema.Check.run/1.These three tests call
Remote.fetch_schema/1andRemote.schemas_match?/2directly rather than invoking the Check task, so they duplicateRemote-level coverage and don't verify the messages, exit behavior, or counting logic ofSchema.Check. Consider defining a module with__remote_config__/0+schema_path/0soRemote.discover_remote_schemas/0picks it up, then callCheck.run([])and assert on{:mix_shell, :info, ...}/{:mix_shell, :error, ...}messages like"Up to date","differs from remote", and theMix.raiseon drift.lib/graphql_query/schema/remote/introspection.ex (1)
440-448:indent/1is effectively a no-op.The function splits on
"\n", maps empty lines to""(unchanged) and non-empty lines to themselves, then rejoins with"\n"— the output equals the input. Either remove the wrapper and inline the string, or implement actual indentation of non-empty lines if that was the original intent. As it stands, the name is misleading and the call sites suggest indentation is being applied when it isn't.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/graphql_query/schema/remote/introspection.ex` around lines 440 - 448, The function indent/1 currently performs no indentation (it splits and rejoins lines unchanged); either remove the helper and inline the raw string at its call sites or change indent/1 to actually prefix non-empty lines (e.g., add a fixed number of spaces or a configurable prefix) so its name matches behavior; locate the helper (defp indent/1) and either delete calls to it and use the original text directly, or implement the intended transformation on non-empty lines so descriptions are truly indented.lib/graphql_query/schema.ex (1)
161-260: Compile-timefile_exists?branch can get out of sync with runtime state.
schema/0is generated at compile time based onFile.exists?(schema_path): if absent, it bakes in araise RemoteNotFetchedError; if present, it embeds agql_from_file/2call. You do declare@external_resource unquote(schema_path)at Line 218, which correctly invalidates compilation when the file is later created/modified/deleted — so this only bites if the user mutates the file outside the normal compile cycle or uses tooling that bypasses mtime checks.It may be simpler and more robust to always generate the "load from file if present, raise otherwise" check at runtime:
🔧 Suggested simplification
- schema_fn_ast = - if file_exists? do - quote do - `@impl` GraphqlQuery.Schema - def schema do - gql_from_file(unquote(schema_path), type: :schema) - end - end - else - quote do - `@impl` GraphqlQuery.Schema - def schema do - raise GraphqlQuery.Schema.RemoteNotFetchedError, - module: __MODULE__, - schema_path: unquote(schema_path) - end - end - end + schema_fn_ast = + quote do + `@impl` GraphqlQuery.Schema + def schema do + if File.exists?(unquote(schema_path)) do + gql_from_file(unquote(schema_path), type: :schema) + else + raise GraphqlQuery.Schema.RemoteNotFetchedError, + module: __MODULE__, + schema_path: unquote(schema_path) + end + end + endTradeoff: you lose compile-time validation of the SDL content for the fetched file (since
gql_from_filewould run at runtime), so keep the compile-time branching if that validation is important. In that case, consider a brief doc note on recompiling aftermix graphql_query.schema.fetch.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/graphql_query/schema.ex` around lines 161 - 260, The generated schema/0 currently bakes in a compile-time File.exists? decision in remote_ast, which can become stale; change remote_ast so it always emits a runtime check inside the generated schema/0: at call time, check File.exists?(unquote(schema_path)) and if present call gql_from_file(unquote(schema_path), type: :schema) else raise GraphqlQuery.Schema.RemoteNotFetchedError with module: __MODULE__ and schema_path: unquote(schema_path); keep the `@external_resource` unquote(schema_path) and the existing __remote_config__/0 and __schemas_dir__/0 helpers and leave build_request/1 and deoverridable as-is. This preserves compile-time resource tracking but ensures schema/0 reflects the current filesystem state.lib/graphql_query/schema/remote.ex (2)
240-246: Byte-exact comparison can flag spurious drift on trailing-newline/CRLF differences.
schemas_match?/2compares stored vs fetched SDL byte-for-byte. In practice this surfaces false positives formix graphql_query.schema.checkwhen:
- the server response body ends without a trailing newline but
File.write/2doesn't add one (or vice versa from a prior tool),- a proxy normalizes
\nto\r\n,- an editor auto-inserts a trailing newline on save.
Consider normalizing (at minimum
String.trim_trailing/1on both sides, and/orString.replace(..., "\r\n", "\n")) before comparing, so the check task only reports semantic drift. If strict byte equality is a deliberate choice, the docstring should call that out so users know why the check keeps failing after an editor touch.♻️ Suggested relaxation
- def schemas_match?(path, content) when is_binary(path) and is_binary(content) do - case File.read(path) do - {:ok, stored} -> stored == content - {:error, _} -> false - end - end + def schemas_match?(path, content) when is_binary(path) and is_binary(content) do + case File.read(path) do + {:ok, stored} -> normalize(stored) == normalize(content) + {:error, _} -> false + end + end + + defp normalize(s), do: s |> String.replace("\r\n", "\n") |> String.trim_trailing()🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/graphql_query/schema/remote.ex` around lines 240 - 246, The current schemas_match?/2 does a byte-exact equality check which causes false positives from trailing-newline or CRLF differences; update schemas_match?/2 to normalize both stored and content before comparing by reading the file (File.read/1) as now, then applying a normalization pipeline such as replacing "\r\n" with "\n" and trimming trailing whitespace/newlines (e.g., String.replace(..., "\r\n", "\n") |> String.trim_trailing()) to both the stored value and the fetched content, and then compare the normalized strings; keep the File.read error handling behavior but compare normalized_stored == normalized_content so only semantic drift is reported (or document the strict behavior if you deliberately want byte-exact matching).
194-207:resolve_url/1has no runtime fallback for malformed inputs.Any shape other than a binary or
{atom, atom}(e.g. a stale 3-tuple from a legacy config, or a string returned as a charlist) hits aFunctionClauseErrorinstead of a descriptiveArgumentError. Compile-time validation covers the common cases, but runtime URL resolution via{Module, :fun}can still produce an unexpected shape (e.g. the callback returns{mod, fun, arg}by mistake downstream). A catch-all clause keeps the error message consistent with the existing non-empty-string check.♻️ Suggested addition
def resolve_url({mod, fun}) when is_atom(mod) and is_atom(fun) do ... end + + def resolve_url(other) do + raise ArgumentError, + message: + "remote :url must be a non-empty string or a {Module, :function} tuple, got: #{inspect(other)}" + end🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/graphql_query/schema/remote.ex` around lines 194 - 207, Add a catch-all clause to resolve_url/1 that raises a descriptive ArgumentError for any input that is not a binary or a {module, fun} tuple; keep the existing binary head and the apply-based {mod, fun} head intact and, after them, implement def resolve_url(other) do raise ArgumentError, message: "resolve_url/1 expected a binary or {module, atom()}, got: #{inspect(other)}" end so malformed inputs (including charlists or unexpected tuples) produce a consistent, informative error instead of a FunctionClauseError.lib/graphql_query/schema/remote/http_client.ex (2)
110-119: Partial introspection results witherrorsare always rejected.
%{"errors" => errors} when is_list(errors) and errors != []treats any response containing anerrorsarray as a hard failure, even when"data"is fully populated (GraphQL spec allows both). For introspection in particular, most servers either return a cleandataor a cleanerrors, but some proxies/security layers will attach a non-fatal warning inerrorsalongside a valid schema. Currently that makes schema fetching impossible against those endpoints.Consider only erroring when
"data"is absent/nil, e.g.:- %{"errors" => errors} when is_list(errors) and errors != [] -> + %{"errors" => errors, "data" => data} when is_list(errors) and errors != [] and data in [nil] -> messages = Enum.map_join(errors, "; ", fn e -> e["message"] || inspect(e) end) {:error, "Introspection query returned errors: #{messages}"} + + %{"errors" => errors} when is_list(errors) and errors != [] and not is_map_key(body, "data") -> + messages = Enum.map_join(errors, "; ", fn e -> e["message"] || inspect(e) end) + {:error, "Introspection query returned errors: #{messages}"}Low priority — ignore if you prefer the strict behavior.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/graphql_query/schema/remote/http_client.ex` around lines 110 - 119, convert_introspection_response currently fails whenever an "errors" array exists, which rejects partial-but-valid introspection responses; change the logic in convert_introspection_response to only return an error if the "data" field is missing or nil (i.e., when body["data"] is nil/absent), otherwise proceed to call Introspection.to_sdl(body) even if errors are present so valid schema data is accepted; reference the convert_introspection_response function and Introspection.to_sdl to locate and update the check.
1-2: Indentation inconsistency inside the conditionaldefmodule.The
defmoduleon line 2 is indented 2 spaces underif Code.ensure_loaded?(Req) do, but the body (lines 3-141) is also indented only 2 spaces rather than 4, making the body visually at the same level as thedefmoduleheader. Purely a cosmetic nit —mix formatwill normalize this if you re-run it.Also applies to: 142-143
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/graphql_query/schema/remote/http_client.ex` around lines 1 - 2, The defmodule GraphqlQuery.Schema.Remote.HttpClient is nested inside if Code.ensure_loaded?(Req) do but its body indentation is inconsistent (header and body share the same 2-space level); fix by aligning the module body indentation to be nested under the defmodule (i.e., increase body indentation under GraphqlQuery.Schema.Remote.HttpClient) or simply run mix format to normalize formatting for the conditional block (also apply the same fix to the closing lines around 142-143).test/graphql_query/schema/remote/introspection_schema_equivalence_test.exs (1)
252-284:condshort-circuits so a dual SDL+schema mismatch only surfaces one side.When both
sdl_typeandschema_typediffer fromexpected, only the SDL mismatch is reported for that field; same forcheck_args. For test diagnostics it would be more useful to report both (and, once fixed, report whichever side actually diverges fromexpected). Minor, but it can make failure output misleading when both sides drift.♻️ Suggested refactor
- defp check_return_type(errors, sdl_line, schema_line, expected, prefix, type_name, field) do - sdl_type = field_return_type(sdl_line) - schema_type = field_return_type(schema_line) - - cond do - sdl_type != expected -> - ["#{prefix} #{type_name}.#{field}: SDL return type #{inspect(sdl_type)}, expected #{inspect(expected)}" | errors] - - schema_type != expected -> - ["#{prefix} #{type_name}.#{field}: schema return type #{inspect(schema_type)}, expected #{inspect(expected)}" | errors] - - true -> - errors - end - end + defp check_return_type(errors, sdl_line, schema_line, expected, prefix, type_name, field) do + sdl_type = field_return_type(sdl_line) + schema_type = field_return_type(schema_line) + + errors + |> maybe_add(sdl_type != expected, + "#{prefix} #{type_name}.#{field}: SDL return type #{inspect(sdl_type)}, expected #{inspect(expected)}") + |> maybe_add(schema_type != expected, + "#{prefix} #{type_name}.#{field}: schema return type #{inspect(schema_type)}, expected #{inspect(expected)}") + end + + defp maybe_add(errors, true, msg), do: [msg | errors] + defp maybe_add(errors, false, _msg), do: errors🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/graphql_query/schema/remote/introspection_schema_equivalence_test.exs` around lines 252 - 284, The cond in check_return_type/7 and check_args/7 short-circuits so only the SDL mismatch is reported when both SDL and schema differ; update both functions (check_return_type, check_args) to independently compare sdl_type vs expected and schema_type vs expected (and sdl_args vs expected and schema_args vs expected) and append one or both error messages to the errors list accordingly, returning the accumulated errors; use the existing helpers field_return_type and field_args and preserve the same message formats when adding each mismatch.test/graphql_query/schema/remote_test.exs (1)
43-53: Restore uses a truthy guard that misbehaves if env was explicitlyfalse/nil.
if original, do: Application.put_env(...)won't restore a value that was set tofalseornil. In this specific testdelete_envhappens first, so iforiginalwas previously set tofalseit'd be silently dropped on restore. Minor but easy to fix by checkingoriginal != nilagainst a separate "was set" flag (or by always callingput_env(original)whenoriginal != nil, matching the pattern used in the next test at lines 62-66).♻️ Suggested tweak
- try do - assert Remote.resolve_schemas_dir(nil) == "priv/graphql/schemas" - after - if original, do: Application.put_env(:graphql_query, :schemas_dir, original) - end + try do + assert Remote.resolve_schemas_dir(nil) == "priv/graphql/schemas" + after + if original != nil, do: Application.put_env(:graphql_query, :schemas_dir, original) + end🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/graphql_query/schema/remote_test.exs` around lines 43 - 53, The restore logic in the test uses a truthy guard (if original, do: ...) which drops legitimate false/nil values; change the setup to use Application.fetch_env(:graphql_query, :schemas_dir) to detect whether the env was set and capture the original value, then in the after block restore only when fetch returned {:ok, original_value} (calling Application.put_env(:graphql_query, :schemas_dir, original_value)); update the variables around the try/after in the test "returns default when nil and no app config" so the original env is correctly restored even if it was false or nil.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@docs/cheatsheet.cheatmd`:
- Around line 117-123: Update the cheatsheet snippet to warn that the remote
schema option requires the :req dependency; specifically mention adding {:req,
"~> 0.5"} to mix.exs when using use GraphqlQuery.Schema with remote: [...] so
the example for MyApp.ExternalApi.Schema compiles; reference the
GraphqlQuery.Schema usage and the mix.exs dependency requirement for clarity.
In `@lib/graphql_query/schema/remote/http_client.ex`:
- Around line 51-55: The code contains unreachable pattern matches for
Mint.TransportError in the error handling of the HTTP client functions (e.g.,
the clauses inside the functions handling Req.request results such as fetch/1
and introspect/2); remove the specific {:error, %Mint.TransportError{reason:
reason}} clause(s) and keep the generic {:error, reason} branch that already
handles Req.TransportError, ensuring the existing error message ("Failed to
fetch #{url}: #{inspect(reason)}") remains unchanged.
In `@lib/graphql_query/schema/remote/introspection.ex`:
- Around line 427-438: description_block/2 currently outputs triple-quoted block
strings verbatim and will produce invalid SDL if desc contains """; update
description_block/2 to escape any embedded triple-quote sequences inside desc
(replace occurrences of """ with an escaped form per GraphQL block-string rules,
e.g. backslash-escaping the quotes) before wrapping in the triple-quote branch,
and ensure prefixing/newline logic is preserved; also update render_deprecated/1
to escape backslashes before escaping double quotes (i.e., escape "\" characters
first, then escape '"' ) so deprecation reasons containing backslashes produce
valid SDL.
In `@lib/mix/tasks/graphql_query.schema.check.ex`:
- Around line 85-115: The check_schema/1 function currently fetches url with
Keyword.fetch!(remote, :url) and duplicates the :mode dispatch and HttpClient
calls; instead resolve the remote into its concrete remote_content by delegating
to Remote.fetch_schema(remote) (the same helper used by the Fetch task), use its
returned {:ok, remote_content} / {:error, reason} to decide
match/mismatch/error, and remove the mode case and direct
HttpClient.fetch/introspect calls; also stop interpolating the raw url tuple
(use the resolved remote URL or include context from Remote.fetch_schema on
errors) and drop the now-unused alias GraphqlQuery.Schema.Remote.HttpClient.
In `@lib/mix/tasks/graphql_query.schema.fetch.ex`:
- Around line 80-85: The task currently logs failures but still exits 0; update
the end of the run so that when the local variable failures > 0 you call
Mix.raise/1 (e.g., Mix.raise("Completed: #{successes} succeeded, #{failures}
failed.")) instead of only Mix.shell().error; locate the block that checks
failures (the if failures > 0 do ... else ... end) in the
Mix.Tasks.GraphqlQuery.Schema.Fetch task and replace the error-only branch with
a Mix.raise call that includes the same contextual message so the process
returns a non-zero exit on failure.
In `@README.md`:
- Around line 600-608: Update the "Remote Schemas" README section to note that
the optional :req dependency is required when using the remote: option;
specifically mention adding {:req, "~> 0.5"} to mix.exs so users won't hit the
compile-time error when defining modules that use GraphqlQuery.Schema with
remote: (e.g. the example MyApp.ExternalApi.Schema using use
GraphqlQuery.Schema, remote: [...]). Ensure the note appears near the example
and is concise about adding the dependency to the project dependencies.
In `@test/graphql_query/schema/remote_schema_integration_test.exs`:
- Around line 306-314: Rename the test and update its comment to accurately
reflect what's asserted: change the test description (the string in the test
block) from "raises when remote :url is a tuple with non-atom elements" to
something like "raises UndefinedFunctionError when {Module, :fun} references a
missing function", and update the explanatory comment that currently mentions
String.upcase/0 to instead describe that resolve_url/1 is being called with
{String, :nonexistent_fun_arity_zero} and therefore raises
UndefinedFunctionError because that function doesn't exist; ensure you reference
the test block that calls GraphqlQuery.Schema.Remote.resolve_url({String,
:nonexistent_fun_arity_zero}) so the name and comment match the actual
assertion.
In `@test/graphql_query/schema/remote_test.exs`:
- Around line 1-69: The tests mutate Application env in the describe
"resolve_schemas_dir/1" block which races with other async tests; remove the
race by disabling async for this test module or isolating that describe.
Specifically, edit the test module declaration (the line using ExUnit.Case with
async: true) to remove async: true (or change only the describe
"resolve_schemas_dir/1" to run synchronously), so
GraphqlQuery.Schema.Remote.resolve_schemas_dir/1 is exercised without concurrent
Application.put_env/delete_env interference.
---
Outside diff comments:
In `@README.md`:
- Around line 844-850: The checked roadmap item "- [x] Configure schemas with
remote URLs to fetch, and have a mix task to check if the content differs"
should be moved out of the "### Planned" section and placed under a new or
existing "### Done" section; update the README so that the "Planned" list no
longer contains the completed "- [x] Configure schemas..." entry and add that
exact line (including the checked box) under "### Done" to reflect completion.
---
Nitpick comments:
In `@lib/graphql_query/schema.ex`:
- Around line 161-260: The generated schema/0 currently bakes in a compile-time
File.exists? decision in remote_ast, which can become stale; change remote_ast
so it always emits a runtime check inside the generated schema/0: at call time,
check File.exists?(unquote(schema_path)) and if present call
gql_from_file(unquote(schema_path), type: :schema) else raise
GraphqlQuery.Schema.RemoteNotFetchedError with module: __MODULE__ and
schema_path: unquote(schema_path); keep the `@external_resource`
unquote(schema_path) and the existing __remote_config__/0 and __schemas_dir__/0
helpers and leave build_request/1 and deoverridable as-is. This preserves
compile-time resource tracking but ensures schema/0 reflects the current
filesystem state.
In `@lib/graphql_query/schema/remote.ex`:
- Around line 240-246: The current schemas_match?/2 does a byte-exact equality
check which causes false positives from trailing-newline or CRLF differences;
update schemas_match?/2 to normalize both stored and content before comparing by
reading the file (File.read/1) as now, then applying a normalization pipeline
such as replacing "\r\n" with "\n" and trimming trailing whitespace/newlines
(e.g., String.replace(..., "\r\n", "\n") |> String.trim_trailing()) to both the
stored value and the fetched content, and then compare the normalized strings;
keep the File.read error handling behavior but compare normalized_stored ==
normalized_content so only semantic drift is reported (or document the strict
behavior if you deliberately want byte-exact matching).
- Around line 194-207: Add a catch-all clause to resolve_url/1 that raises a
descriptive ArgumentError for any input that is not a binary or a {module, fun}
tuple; keep the existing binary head and the apply-based {mod, fun} head intact
and, after them, implement def resolve_url(other) do raise ArgumentError,
message: "resolve_url/1 expected a binary or {module, atom()}, got:
#{inspect(other)}" end so malformed inputs (including charlists or unexpected
tuples) produce a consistent, informative error instead of a
FunctionClauseError.
In `@lib/graphql_query/schema/remote/http_client.ex`:
- Around line 110-119: convert_introspection_response currently fails whenever
an "errors" array exists, which rejects partial-but-valid introspection
responses; change the logic in convert_introspection_response to only return an
error if the "data" field is missing or nil (i.e., when body["data"] is
nil/absent), otherwise proceed to call Introspection.to_sdl(body) even if errors
are present so valid schema data is accepted; reference the
convert_introspection_response function and Introspection.to_sdl to locate and
update the check.
- Around line 1-2: The defmodule GraphqlQuery.Schema.Remote.HttpClient is nested
inside if Code.ensure_loaded?(Req) do but its body indentation is inconsistent
(header and body share the same 2-space level); fix by aligning the module body
indentation to be nested under the defmodule (i.e., increase body indentation
under GraphqlQuery.Schema.Remote.HttpClient) or simply run mix format to
normalize formatting for the conditional block (also apply the same fix to the
closing lines around 142-143).
In `@lib/graphql_query/schema/remote/introspection.ex`:
- Around line 440-448: The function indent/1 currently performs no indentation
(it splits and rejoins lines unchanged); either remove the helper and inline the
raw string at its call sites or change indent/1 to actually prefix non-empty
lines (e.g., add a fixed number of spaces or a configurable prefix) so its name
matches behavior; locate the helper (defp indent/1) and either delete calls to
it and use the original text directly, or implement the intended transformation
on non-empty lines so descriptions are truly indented.
In `@test/graphql_query/schema/remote_test.exs`:
- Around line 43-53: The restore logic in the test uses a truthy guard (if
original, do: ...) which drops legitimate false/nil values; change the setup to
use Application.fetch_env(:graphql_query, :schemas_dir) to detect whether the
env was set and capture the original value, then in the after block restore only
when fetch returned {:ok, original_value} (calling
Application.put_env(:graphql_query, :schemas_dir, original_value)); update the
variables around the try/after in the test "returns default when nil and no app
config" so the original env is correctly restored even if it was false or nil.
In `@test/graphql_query/schema/remote/introspection_schema_equivalence_test.exs`:
- Around line 252-284: The cond in check_return_type/7 and check_args/7
short-circuits so only the SDL mismatch is reported when both SDL and schema
differ; update both functions (check_return_type, check_args) to independently
compare sdl_type vs expected and schema_type vs expected (and sdl_args vs
expected and schema_args vs expected) and append one or both error messages to
the errors list accordingly, returning the accumulated errors; use the existing
helpers field_return_type and field_args and preserve the same message formats
when adding each mismatch.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 3f553c75-ae11-4fb0-ba12-e45e0c8455a9
⛔ Files ignored due to path filters (1)
mix.lockis excluded by!**/*.lock
📒 Files selected for processing (33)
.dialyzer_ignore.exs.gitignoreCHANGELOG.mdREADME.mddocs/cheatsheet.cheatmdlib/graphql_query/schema.exlib/graphql_query/schema/remote.exlib/graphql_query/schema/remote/http_client.exlib/graphql_query/schema/remote/introspection.exlib/graphql_query/schema/remote_not_fetched_error.exlib/graphql_query/validator.exlib/mix/tasks/graphql_query.schema.check.exlib/mix/tasks/graphql_query.schema.fetch.exmix.exstest/fixtures/introspection.jsontest/fixtures/introspection_schema.graphqltest/fixtures/remote_schemas/explicit_path_schema.graphqltest/fixtures/remote_schemas/graphql_query/schema/remote_schema_integration_test/test_remote_basic.graphqltest/fixtures/remote_schemas/graphql_query/schema/remote_schema_integration_test/test_remote_build_req_multi.graphqltest/fixtures/remote_schemas/graphql_query/schema/remote_schema_integration_test/test_remote_build_req_override.graphqltest/fixtures/remote_schemas/graphql_query/schema/remote_schema_integration_test/test_remote_federation.graphqltest/fixtures/remote_schemas/graphql_query/schema/remote_schema_integration_test/test_remote_introspect_mode.graphqltest/fixtures/remote_schemas/graphql_query/schema/remote_schema_integration_test/test_remote_mfa_url.graphqltest/graphql_query/federation_test.exstest/graphql_query/schema/remote/http_client_test.exstest/graphql_query/schema/remote/introspection_schema_equivalence_test.exstest/graphql_query/schema/remote/introspection_test.exstest/graphql_query/schema/remote_schema_integration_test.exstest/graphql_query/schema/remote_test.exstest/graphql_query/schema_test.exstest/graphql_query/validator_test.exstest/mix/tasks/graphql_query_schema_check_test.exstest/mix/tasks/graphql_query_schema_fetch_test.exs
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (3)
test/mix/tasks/graphql_query_schema_check_test.exs (1)
1-12: Considerasync: false— setup mutates global state.
Mix.shell/1andReq.Test.stub/2are process/global-scoped. If a sibling non-async test (e.g.,graphql_query_schema_fetch_test.exs) runs concurrently and also swapsMix.shell/1,assert_receive {:mix_shell, ...}here can flake. Mirrorremote_sync_test.exsand declare the case non-async.🧰 Proposed fix
defmodule Mix.Tasks.GraphqlQuery.Schema.CheckTest do - use ExUnit.Case + use ExUnit.Case, async: false🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/mix/tasks/graphql_query_schema_check_test.exs` around lines 1 - 12, The test mutates global/process-scoped state (Mix.shell/1 and Req.Test.stub/2) so mark the case non-async: update the module declaration for Mix.Tasks.GraphqlQuery.Schema.CheckTest (the line using ExUnit.Case) to use ExUnit.Case, async: false so this test does not run concurrently with other tests that also swap Mix.shell or Req.Test stubs.lib/graphql_query/schema/remote.ex (1)
460-466: Compile-timevalid_url?/1accepts tuples whose first element is not an atom.
valid_url?({_mod, fun}) when is_atom(fun)permits e.g.{"not a module", :get}throughvalidate_config!/1, but at runtimeresolve_url/1guards onis_atom(mod) and is_atom(fun)and will raiseFunctionClauseErrorinstead of the nicerArgumentErrorpath. Tightening the compile check to also requireis_atom(mod)keeps error surfacing at compile time where it’s actionable. The comment about alias AST is correct for other macro contexts, but hereuse GraphqlQuery.Schema, remote: [url: {Mod, :fun}]has the module literal already resolved to an atom by the time__using__/1receives it.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/graphql_query/schema/remote.ex` around lines 460 - 466, valid_url?/1 currently allows tuples where the first element isn't an atom, causing resolve_url/1 to later raise a FunctionClauseError; update the clause def valid_url?({_mod, fun}) when is_atom(fun) to additionally require the module be an atom (e.g. when is_atom(mod) and is_atom(fun)) so validate_config!/1 surfaces invalid configs at compile time; check related callers (__using__/1 and resolve_url/1) still behave the same after tightening the guard.lib/mix/tasks/graphql_query.schema.check.ex (1)
112-121: PreferModule.concat/1over manual"Elixir." <> ...+String.to_atom.
Module.concat/1handles theElixir.prefix for you and is the idiomatic way to build a module atom from a CLI string.♻️ Proposed fix
defp parse_module_filter([]), do: nil -defp parse_module_filter([module_string | _]) do - module_string = - if String.starts_with?(module_string, "Elixir."), - do: module_string, - else: "Elixir." <> module_string - - String.to_atom(module_string) -end +defp parse_module_filter([module_string | _]) do + Module.concat([module_string]) +end🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/mix/tasks/graphql_query.schema.check.ex` around lines 112 - 121, In parse_module_filter, avoid manual "Elixir." prefixing and String.to_atom; instead split the incoming module string on "." into segments, convert each segment to an atom and call Module.concat on the list so the proper module atom is constructed idiomatically; replace the current body inside defp parse_module_filter([module_string | _]) (including the starts_with check and String.to_atom) with something like: split module_string by "." -> Enum.map(&String.to_atom/1) -> Module.concat(list) so parse_module_filter returns the module atom correctly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@lib/graphql_query/schema/remote.ex`:
- Around line 218-222: save_schema/2 currently uses Path.dirname() |>
File.mkdir_p!() which can raise File.Error contrary to the `@spec`; change it to
use File.mkdir_p/1 and handle its {:ok, _} | {:error, reason} return before
calling File.write/2 so the function returns {:ok, content_written_info} or
{:error, reason} instead of raising; specifically replace the File.mkdir_p! call
with File.mkdir_p(Path.dirname(path)), pattern-match on its result and propagate
{:error, reason} immediately, then call File.write(path, content) and return its
{:ok | :error} tuple so save_schema/2 conforms to the declared spec.
In `@lib/graphql_query/schema/remote/http_client.ex`:
- Around line 104-113: The convert_introspection_response function can crash
when an entry in the "errors" list is not a map because e["message"] invokes
Access; update the error-message extraction in convert_introspection_response to
safely handle non-map error entries by pattern-matching or checking types: for
each e in errors, if is_map(e) then use e["message"] || inspect(e) else use
inspect(e) (or to_string/inspect) so non-map values don’t raise and the real
GraphQL error text is preserved.
In `@test/graphql_query/schema/remote/introspection_schema_equivalence_test.exs`:
- Around line 30-34: The regex-based SDL parsers (e.g., extract_type_names/2)
currently ignore only the triple-quote delimiters so block-string contents can
be misidentified as type/field names; add a preprocessing step that strips
entire block-string descriptions (remove the """...""" spans, including
newlines) before running the existing Regex.scan logic, implement this as a
small helper (e.g., strip_block_string_descriptions) and call it from
extract_type_names/2 and the other SDL-extract helper functions in the test file
so all regex parsing works on SDL with block-string descriptions removed.
- Around line 277-299: The early-return clause in check_args (the head matching
expected == nil) prevents nil expected argument lists from being compared,
letting fields with actual args slip through; remove that clause so all calls
route to the main check_args/7 body which compares sdl_args and schema_args to
expected (use the existing field_args(sdl_line)/field_args(schema_line)
comparisons), allowing nil vs non-nil mismatches to be detected; ensure you only
remove or disable the defp check_args(errors, _sdl_line, _schema_line, nil,
_prefix, _type_name, _field) clause so the remaining check_args function
performs the equality checks.
- Around line 40-47: The current code uses byte offsets from Regex.run(...,
return: :index) and :binary.match/2 but calls String.slice/2 (grapheme-based),
causing wrong slices for SDL with non-ASCII text; replace those String.slice
calls with :binary.part/3 (or binary_part/3) using the original byte offsets and
lengths (use the start byte index and compute remaining length with
byte_size(sdl) - start) so that the subsequent logic in
find_matching_close(rest, ...) and the after_open slice use correct byte-aware
substrings; update both places where String.slice(sdl, start_pos..-1//1) and
String.slice(rest, (open_pos + 1)..-1//1) are used to use byte-based slicing and
preserve the variables used by find_matching_close.
---
Nitpick comments:
In `@lib/graphql_query/schema/remote.ex`:
- Around line 460-466: valid_url?/1 currently allows tuples where the first
element isn't an atom, causing resolve_url/1 to later raise a
FunctionClauseError; update the clause def valid_url?({_mod, fun}) when
is_atom(fun) to additionally require the module be an atom (e.g. when
is_atom(mod) and is_atom(fun)) so validate_config!/1 surfaces invalid configs at
compile time; check related callers (__using__/1 and resolve_url/1) still behave
the same after tightening the guard.
In `@lib/mix/tasks/graphql_query.schema.check.ex`:
- Around line 112-121: In parse_module_filter, avoid manual "Elixir." prefixing
and String.to_atom; instead split the incoming module string on "." into
segments, convert each segment to an atom and call Module.concat on the list so
the proper module atom is constructed idiomatically; replace the current body
inside defp parse_module_filter([module_string | _]) (including the starts_with
check and String.to_atom) with something like: split module_string by "." ->
Enum.map(&String.to_atom/1) -> Module.concat(list) so parse_module_filter
returns the module atom correctly.
In `@test/mix/tasks/graphql_query_schema_check_test.exs`:
- Around line 1-12: The test mutates global/process-scoped state (Mix.shell/1
and Req.Test.stub/2) so mark the case non-async: update the module declaration
for Mix.Tasks.GraphqlQuery.Schema.CheckTest (the line using ExUnit.Case) to use
ExUnit.Case, async: false so this test does not run concurrently with other
tests that also swap Mix.shell or Req.Test stubs.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 3ef9a7bd-aefb-41e0-ac46-d9eb860d336b
📒 Files selected for processing (17)
README.mddocs/cheatsheet.cheatmdlib/graphql_query/schema.exlib/graphql_query/schema/remote.exlib/graphql_query/schema/remote/http_client.exlib/graphql_query/schema/remote/introspection.exlib/mix/tasks/graphql_query.schema.check.exlib/mix/tasks/graphql_query.schema.fetch.exmix.exstest/graphql_query/schema/remote/introspection_schema_equivalence_test.exstest/graphql_query/schema/remote/introspection_test.exstest/graphql_query/schema/remote_schema_integration_test.exstest/graphql_query/schema/remote_sync_test.exstest/graphql_query/schema/remote_test.exstest/graphql_query/validator_test.exstest/mix/tasks/graphql_query_schema_check_test.exstest/mix/tasks/graphql_query_schema_fetch_test.exs
✅ Files skipped from review due to trivial changes (4)
- README.md
- test/graphql_query/schema/remote/introspection_test.exs
- mix.exs
- test/graphql_query/schema/remote_schema_integration_test.exs
🚧 Files skipped from review as they are similar to previous changes (7)
- docs/cheatsheet.cheatmd
- test/graphql_query/validator_test.exs
- lib/mix/tasks/graphql_query.schema.fetch.ex
- test/graphql_query/schema/remote_test.exs
- test/mix/tasks/graphql_query_schema_fetch_test.exs
- lib/graphql_query/schema.ex
- lib/graphql_query/schema/remote/introspection.ex
There was a problem hiding this comment.
Actionable comments posted: 5
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@lib/graphql_query/schema/remote.ex`:
- Around line 168-175: fetch_schema/1 currently calls resolve_url/1 which can
raise and thus crash instead of returning the promised {:error, reason} tuple;
wrap the resolve_url/1 invocation in a safe error-handling block (e.g.,
try/rescue or with/else) so any exception from resolve_url/1 is caught and
converted into {:error, reason} before calling HttpClient.fetch/2 or
HttpClient.introspect/2; ensure the function returns the same {:ok, schema} |
{:error, reason} contract and reference fetch_schema/1, resolve_url/1,
HttpClient.fetch/2 and HttpClient.introspect/2 when applying the change.
- Around line 190-191: The example for resolve_url/1 is invalid because it shows
calling Application.get_env with zero arity; update the doc example to use a
zero-arity provider (or an anonymous function) that actually exists.
Specifically, replace the {Application, :get_env} example with a callable that
accepts no args such as a zero-arity anonymous function or a module function
that is defined with arity 0 (e.g., &MyApp.Config.url/0) so that
GraphqlQuery.Schema.Remote.resolve_url/1 invokes the provider correctly with no
arguments.
- Around line 461-467: valid_url?/1 currently accepts tuples like {_mod, fun}
without ensuring the module is an atom, which is inconsistent with resolve_url/1
and allows invalid inputs; update the tuple clause in valid_url?/1 to require
both elements be atoms (change def valid_url?({_mod, fun}) when is_atom(fun) to
def valid_url?({mod, fun}) when is_atom(mod) and is_atom(fun)), and remove or
update the misleading comment about alias AST handling referenced from
validate_config!/1 so the documentation matches the runtime behavior.
In `@lib/graphql_query/schema/remote/http_client.ex`:
- Around line 48-56: The error branches in
lib/graphql_query/schema/remote/http_client.ex return the full url (e.g., in the
{:ok, %Req.Response{status}} -> and rescue -> cases), which may leak sensitive
info; update the function that logs/folds errors (the fetch/get function that
matches {:ok, %Req.Response{status: status}} and {:error, reason} and the rescue
clause using Exception.message(e)) to build and use a sanitized_url instead of
the raw url: parse the url with URI.parse, strip userinfo and sensitive query
parameters (or replace query with "<redacted>"), then interpolate sanitized_url
into the error tuples (e.g., {:error, "HTTP #{status} when fetching
#{sanitized_url}"} and {:error, "Failed to fetch #{sanitized_url}:
#{inspect(reason)}"}). Ensure both the main error paths and the rescue clause
use the same sanitizer function.
- Around line 106-111: In the %{"errors" => errors} branch in http_client.ex you
must avoid passing non-binary values to Enum.map_join; update the Enum.map_join
lambda (inside the messages assignment) to convert any non-binary e["message"]
into a string via inspect (e.g. if is_map(e) then case e["message"] do m when
is_binary(m) -> m; m -> inspect(m || e) end), and keep the fallback for non-map
errors as inspect(e); this ensures messages is always a binary and preserves the
upstream payload when e["message"] is not a string.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: d54bb55a-2d32-4a77-88c1-1f9deb2d9041
📒 Files selected for processing (3)
lib/graphql_query/schema/remote.exlib/graphql_query/schema/remote/http_client.extest/graphql_query/schema/remote/introspection_schema_equivalence_test.exs
Summary by CodeRabbit
New Features
Documentation
Tests
Chores
Bug Fix