From 7ee15075b2f35fac92790885c02f5a0edba9a76a Mon Sep 17 00:00:00 2001 From: Bouke van der Bijl Date: Fri, 24 Nov 2023 02:58:45 +0100 Subject: [PATCH] fix: Don't close client if we've already aborted (#968) --- integration/grpc-web-abort-signal/example.ts | 18 ++++++--- integration/grpc-web/example.ts | 4 +- src/generate-grpc-web.ts | 39 +++++++++++--------- 3 files changed, 35 insertions(+), 26 deletions(-) diff --git a/integration/grpc-web-abort-signal/example.ts b/integration/grpc-web-abort-signal/example.ts index 00cf13280..206a4c715 100644 --- a/integration/grpc-web-abort-signal/example.ts +++ b/integration/grpc-web-abort-signal/example.ts @@ -1081,17 +1081,23 @@ export class GrpcWebImpl { } }, }); - observer.add(() => { - if (!abortSignal || !abortSignal.aborted) { - return client.close(); - } - }); if (abortSignal) { - abortSignal.addEventListener("abort", () => { + const abort = () => { observer.error(abortSignal.reason); client.close(); + }; + abortSignal.addEventListener("abort", abort); + observer.add(() => { + if (abortSignal.aborted) { + return; + } + + abortSignal.removeEventListener("abort", abort); + client.close(); }); + } else { + observer.add(() => client.close()); } }); upStream(); diff --git a/integration/grpc-web/example.ts b/integration/grpc-web/example.ts index 6a4f4afe0..1df53b05e 100644 --- a/integration/grpc-web/example.ts +++ b/integration/grpc-web/example.ts @@ -1028,9 +1028,7 @@ export class GrpcWebImpl { } }, }); - observer.add(() => { - return client.close(); - }); + observer.add(() => client.close()); }); upStream(); }).pipe(share()); diff --git a/src/generate-grpc-web.ts b/src/generate-grpc-web.ts index 5097fe32c..6bbe4f09b 100644 --- a/src/generate-grpc-web.ts +++ b/src/generate-grpc-web.ts @@ -336,14 +336,6 @@ function createInvokeMethod(ctx: Context) { const { options } = ctx; const { useAbortSignal } = options; - const maybeAbortSignal = useAbortSignal - ? ` - if (abortSignal) abortSignal.addEventListener("abort", () => { - observer.error(abortSignal.reason); - client.close(); - });` - : ""; - return code` invoke( methodDesc: T, @@ -380,16 +372,29 @@ function createInvokeMethod(ctx: Context) { } }, }); - observer.add(() => { - ${ - !useAbortSignal - ? `return client.close();` - : `if (!abortSignal || !abortSignal.aborted) - return client.close();` - } - }); + ${ + useAbortSignal + ? ` + if (abortSignal) { + const abort = () => { + observer.error(abortSignal.reason); + client.close(); + }; + abortSignal.addEventListener("abort", abort); + observer.add(() => { + if (abortSignal.aborted) { + return; + } - ${maybeAbortSignal} + abortSignal.removeEventListener('abort', abort); + client.close(); + }); + } else { + observer.add(() => client.close()); + } + ` + : `observer.add(() => client.close());` + } }); upStream(); }).pipe(${share}());