Skip to content

Commit

Permalink
Address potential memory leaks in FragmentRegistry (#11356)
Browse files Browse the repository at this point in the history
  • Loading branch information
phryneas committed Nov 29, 2023
1 parent a815873 commit cc4ac7e
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 9 deletions.
5 changes: 5 additions & 0 deletions .changeset/clean-items-smash.md
@@ -0,0 +1,5 @@
---
"@apollo/client": patch
---

Fix a potential memory leak in `FragmentRegistry.transform` and `FragmentRegistry.findFragmentSpreads` that would hold on to passed-in `DocumentNodes` for too long.
14 changes: 5 additions & 9 deletions src/cache/inmemory/fragmentRegistry.ts
Expand Up @@ -6,7 +6,6 @@ import type {
} from "graphql";
import { visit } from "graphql";

import type { OptimisticWrapperFunction } from "optimism";
import { wrap } from "optimism";

import type { FragmentMap } from "../../utilities/index.js";
Expand Down Expand Up @@ -66,15 +65,12 @@ class FragmentRegistry implements FragmentRegistryAPI {
private invalidate(name: string) {}

public resetCaches() {
this.invalidate = (this.lookup = this.cacheUnaryMethod(this.lookup)).dirty; // This dirty function is bound to the wrapped lookup method.
this.transform = this.cacheUnaryMethod(this.transform);
this.findFragmentSpreads = this.cacheUnaryMethod(this.findFragmentSpreads);
}

private cacheUnaryMethod<F extends (arg: any) => any>(originalMethod: F) {
return wrap<Parameters<F>, ReturnType<F>>(originalMethod.bind(this), {
const proto = FragmentRegistry.prototype;
this.invalidate = (this.lookup = wrap(proto.lookup.bind(this), {
makeCacheKey: (arg) => arg,
}) as OptimisticWrapperFunction<Parameters<F>, ReturnType<F>> & F;
})).dirty; // This dirty function is bound to the wrapped lookup method.
this.transform = wrap(proto.transform.bind(this));
this.findFragmentSpreads = wrap(proto.findFragmentSpreads.bind(this));
}

public lookup(fragmentName: string): FragmentDefinitionNode | null {
Expand Down

0 comments on commit cc4ac7e

Please sign in to comment.