Skip to content

Commit

Permalink
Fix fetch customization, upgrade make-fetch-happen, more concurrency …
Browse files Browse the repository at this point in the history
…(`version-0.x`) (#1810)

* Fix fetch customization, upgrade make-fetch-happen, more concurrency (#1805)

UplinkFetcher and RemoteGraphQLDataSource both use `make-fetch-happen`
to execute HTTP requests and allow you to replace that implementation
with any compatible implementation of the web Fetch API.

But prior to this PR, this customization often did not work. For
example, prior to this PR, the version of `make-fetch-happen` used by
default was the outdated v8. If you wanted to use the current v10, you'd
think you could just install it in your project and pass its `fetch`
function to the appropriate `fetcher` parameter.

But surprisingly, this would not work for `RemoteGraphQLDataSource`! The
Fetch API is flexible and allows you to specify your request either as
plain JSON-style objects or as instances of the `Request` and `Headers`
classes defined in the Fetch API spec. `RemoteGraphQLDataSource` used a
`Headers` object in its requests. Specifically, it used a `Headers`
object imported at runtime from `apollo-server-env`, a package we wrote
that combines custom TypeScript types with `node-fetch` for runtime
behavior.

As it turns out, there's a behavior change in `make-fetch-happen` v9 as
to how it tells the difference between using its API with JSON-style
arguments or the `Requests`/`Headers` class. In the newer version,
`make-fetch-happen` uses an `instanceof` check to see if the provided
object is *its* `Headers` class. So when `RemoteGraphQLDataSource`
passes in the `node-fetch` `Headers` class, `make-fetch-happens` v9 gets
confused (and treats it as an empty JSON-style object instead).

The solution we've settled on is to avoid passing non-plain objects to
any `fetch` call that we intend to be customizable. We've published a
new package, `@apollo/utils.fetcher`, which provides TypeScript
definitions for a subset of the Fetch API that does not include the
dangerous feature of "passing in `Request` or `Headers` objects". This
PR changes both uses of `fetcher` in Gateway to use this new TypeScript
type and to invoke it in a more conservative way. (We're making a
similar change in the upcoming Apollo Server 4.)

This does affect the types passed to some `RemoteGraphQLDataSource`
methods, which are designed to be overridden. We feel reasonably sure
that this won't have any noticeable impact on subclasses, as the changed
types are intended to be very similar to the types they are replacing.

Semi-relatedly, we've changed the default fetcher used by
`RemoteGraphQLDataSource` to allow arbitrarily many parallel connections
to each subgraph rather than only 15. `maxSockets: 15` is the default
for `make-fetch-happen` (though not for the underlying `agentkeepalive`
or `http.Agent` libraries) and so this limit was unintentionally added
to Gateway when we switched from `node-fetch` to `make-fetch-happen`.
While this change is a few years old now, it was unintentional and we
doubt anyone is relying on this; on the contrary, it is causing real
performance problems for production users (#1647). So we are changing
the default to unlimited. If for some reason it is important to you that
your Gateway only be able to process 15 requests at a time, you can
restore the previous behavior:

    import fetcher from 'make-fetch-happen';
    const lowConcurrencyFetcher = fetcher.defaults({ maxSockets: 15 });
    const gateway = new ApolloGateway({
      buildService({ url }) {
        return new RemoteGraphQLDataSource({
          url,
          fetcher: lowConcurrencyFetcher,
        });
      },
    });

Fixes #1647.
Fixes #1287.

In more detail, this change consists of:

- Switch the TypeScript typings `fetcher` option to `new ApolloGateway`
  and `new RemoteGraphQLDataSource` from a function type defined in
  `apollo-server-env` to a new one defined in `@apollo/utils.fetcher`.
  This function type's return type is compatible with the return type of
  the old fetcher, but its argument types are restricted to a subset of
  the Fetch API that is actually used by these classes (and classes in
  Apollo Server 4). Specifically, they do not allow you to pass
  `Request` or `Headers` objects. Adjust all calls to pass only
  plain JSON objects rather than `Request`/`Headers` objects.

- In `RemoteGraphQLDataSource`, change the type of the "fetch request"
  argument to `parseBody` and `didEncounterError` (which are ignored by
  that class's implementations of the methods but could be examined by a
  subclass's implementations) from `apollo-server-env`'s `Request` type
  to `node-fetch`'s. This `Request` object is actually created at
  runtime by `RemoteGraphQLDataSource` and is always actually a
  `node-fetch` object, so reflecting that in the API seems to be
  reasonable. Note that this object is *not* actually sent to the
  `Fetcher`; it is only sent to these subclass-observable methods. This
  change makes the TypeScript type used for these parameters match the
  actual runtime type precisely so it should be a backwards-compatible
  change.

- In `RemoteGraphQLDataSource`, change the type of the "fetch response"
  argument to `parseBody`, `errorFromResponse`, and `didEncounterError`
  from `apollo-server-env`'s `Response` type to
  `@apollo/utils.fetcher`'s `FetcherResponse` type. This interface type
  was designed to contain all the fields of the `apollo-server-env` type
  so this should be a backwards-compatible change.

- Upgrade `make-fetch-happen` (the default fetcher used to talk to
  Uplink and to subgraphs) from v8 to v10. Stop preventing Renovate from
  upgrading it.

- Changing the `make-fetch-happen` fetcher used in
  `RemoteGraphQLDataSource` to not limit the number of concurrent active
  sockets. (The fetcher used by `UplinkFetcher` keeps its defaults, as
  that fetcher does not need to make concurrent fetches.)

- Remove the exported function `getDefaultFetcher`, as described in the
  CHANGELOG. None of the customizations we were making were actually
  still relevant for its use in `UplinkFetcher` so it seemed simpler to
  just remove the function rather than keep it around purely to allow
  people to simulate the way that an old version of `UplinkFetcher`
  fetched things by default. (We can add it back if there's a lot of
  protest, I suppose, although we'd be unlikely to make it continue to
  export `make-fetch-happen` v8!)

- Replace tests that use Jest mocking of `apollo-server-env` and
  `make-fetch-happen` with `nock` or explicitly passed-in fetchers.
  This simplifies the tests and makes them less tied to the particular
  fetch implementations. (These tests were written before we knew about
  nock.) Also remove some code in IntrospectAndCompose.test.ts that
  *disabled* this mocking so that nock would work.

- Remove the direct dependency on `apollo-server-env`. (Note that some
  types defined in `apollo-server-env` are still used indirectly in
  Gateway, because we still use `apollo-server-types` and types such as
  `GraphQLRequest` contain types from `apollo-server-env`.)

Paired with @trevor-scheer.

* Update PR #s

Co-authored-by: David Glasser <glasser@davidglasser.net>
  • Loading branch information
trevor-scheer and glasser authored Apr 30, 2022
1 parent 9d00005 commit 70db890
Show file tree
Hide file tree
Showing 25 changed files with 8,755 additions and 4,662 deletions.
2 changes: 1 addition & 1 deletion docs/source/api/apollo-gateway.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ This logger is automatically added to the `GraphQLRequestContext` object that's

###### `fetcher`

`typeof fetch`
[`Fetcher`](https://www.npmjs.com/package/@apollo/utils.fetcher)
</td>
<td>

Expand Down
1 change: 0 additions & 1 deletion federation-integration-testsuite-js/src/matchers/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import './toCallService';
import './toHaveBeenCalledBefore';
import './toHaveFetched';
import './toMatchAST';
import './toMatchQueryPlan';
82 changes: 0 additions & 82 deletions federation-integration-testsuite-js/src/matchers/toHaveFetched.ts

This file was deleted.

4 changes: 3 additions & 1 deletion gateway-js/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
This CHANGELOG pertains only to Apollo Federation packages in the `0.x` range. The Federation v2 equivalent for this package can be found [here](https://github.com/apollographql/federation/blob/main/gateway-js/CHANGELOG.md) on the `main` branch of this repo.

## vNEXT

> The changes noted within this `vNEXT` section have not been released yet. New PRs and commits which introduce changes should include an entry in this `vNEXT` section as part of their development. When a release is being prepared, a new header will be (manually)
- The `fetch` implementation used by default by `UplinkFetcher` and `RemoteGraphQLDataSource` is now imported from `make-fetch-happen` v10 instead of v8. The fetcher used by `RemoteGraphQLDataSource` no longer limits the number of simultaneous requests per subgraph to 15 by default; instead, there is no limit. (If you want to restore the previous behavior, install `make-fetch-happen`, import `fetcher` from it, and pass `new RemoteGraphQLDataSource({ fetcher: fetcher.defaults(maxSockets: 15)}))` in your `buildService` option.) [PR #1810](https://github.com/apollographql/federation/pull/1810)
- The ability to specify your own `fetcher` to `ApolloGateway` and `RemoteGraphQLDataSource` has been improved. An issue that meant that some implementations (such as `make-fetch-happen` v10) could not be used has been resolved. The TypeScript types for the `fetcher` options to those two constructors (as well as some arguments to the `didEncounterError`, `parseBody`, and `errorFromResponse` overridable `RemoteGraphQLDataSource` methods) have been slightly adjusted; we don't believe this should cause any compatibility issues but please file an issue if this created any unintentional problems for you. [PR #1810](https://github.com/apollographql/federation/pull/1810)
- We no longer export a `getDefaultFetcher` function. This function returned the default `fetch` implementation used to talk to Uplink (which is distinct from the default `fetch` implementation used by `RemoteGraphQLDataSource` to talk to subgraphs). It was the fetcher from `make-fetch-happen` v8 with some preset configuration relating to caching and request headers. However, the caching configuration was not actually being used when talking to Uplink (as we talk to Uplink over POST requests, and the Uplink protocol has an application-level mechanism for avoiding unnecessary large responses), and the request headers were already being provided explicitly by the Uplink client code. Since this release is also upgrading `make-fetch-happen`, it is impossible to promise that there would be no behavior change at all to the fetcher returned from `make-fetch-happen`, and as none of the preset configuration is actually relevant to the internal use of `getDefaultFetcher` (which now just uses `make-fetch-happens` without extra configuration), we have removed the function. If you were using this function, you can replace `const fetcher = getDefaultFetcher()` with `import fetcher from 'make-fetch-happen'`. [PR #1810](https://github.com/apollographql/federation/pull/1810)
- The `fetch` implementation returned by `getDefaultFetcher` no longer performs in-memory caching. This fetcher is currently only used by `@apollo/gateway` to make uncacheable `POST` requests to Uplink, so this is a no-op for Gateway's own behavior, but if you used the function returned `getDefaultFetcher` in your own code to perform `GET` requests against servers that return cache-related response headers, it will no longer cache results. You can use the underlying [`make-fetch-happen`](https://www.npmjs.com/package/make-fetch-happen) package directly to use its cache capabilities instead of using the function returned by `getDefaultFetcher`. [PR #1792](https://github.com/apollographql/federation/pull/1792)

## v0.50.2
Expand Down
4 changes: 2 additions & 2 deletions gateway-js/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,18 @@
"@apollo/query-planner": "file:../query-planner-js",
"@apollo/utils.createhash": "^1.0.0",
"@apollo/utils.logger": "^1.0.0",
"@apollo/utils.fetcher": "^1.0.0",
"@josephg/resolvable": "^1.0.1",
"@opentelemetry/api": "^1.0.1",
"@types/node-fetch": "2.6.1",
"apollo-reporting-protobuf": "^0.8.0 || ^3.0.0",
"apollo-server-caching": "^0.7.0 || ^3.0.0",
"apollo-server-core": "^2.23.0 || ^3.0.0",
"apollo-server-env": "^3.0.0 || ^4.0.0",
"apollo-server-errors": "^2.5.0 || ^3.0.0",
"apollo-server-types": "^0.9.0 || ^3.0.0",
"async-retry": "^1.3.3",
"loglevel": "^1.6.1",
"make-fetch-happen": "^8.0.0",
"make-fetch-happen": "^10.1.2",
"pretty-format": "^27.4.6"
},
"peerDependencies": {
Expand Down
56 changes: 0 additions & 56 deletions gateway-js/src/__mocks__/apollo-server-env.ts

This file was deleted.

57 changes: 0 additions & 57 deletions gateway-js/src/__mocks__/make-fetch-happen-fetcher.ts

This file was deleted.

Loading

0 comments on commit 70db890

Please sign in to comment.