Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix UniversalHandlers resolving the response before headers are complete #588

Merged
merged 5 commits into from
Apr 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
158 changes: 101 additions & 57 deletions packages/connect/src/protocol-connect/handler-factory.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,28 +12,30 @@
// See the License for the specific language governing permissions and
// limitations under the License.

import {
Int32Value,
Message,
MethodKind,
StringValue,
} from "@bufbuild/protobuf";
import type { MethodInfo, ServiceType } from "@bufbuild/protobuf";
import { Int32Value, MethodKind, StringValue } from "@bufbuild/protobuf";
import { createHandlerFactory } from "./handler-factory.js";
import type { MethodImpl } from "../implementation.js";
import { createMethodImplSpec } from "../implementation.js";
import type { HandlerContext, MethodImpl } from "../implementation.js";
import type { UniversalHandlerOptions } from "../protocol/index.js";
import { errorFromJsonBytes } from "./error-json.js";
import {
createAsyncIterable,
createUniversalHandlerClient,
pipeTo,
sinkAll,
} from "../protocol/index.js";
import { ConnectError } from "../connect-error.js";
import { Code } from "../code.js";
import { endStreamFromJson } from "./end-stream.js";
import {
createAsyncIterableBytes,
readAllBytes,
} from "../protocol/async-iterable-helper.spec.js";
import { Code } from "../code.js";
import { errorFromJsonBytes } from "./error-json.js";
import { endStreamFromJson } from "./end-stream.js";
import { createTransport } from "./transport.js";

describe("createHandlerFactory()", function () {
const testService: ServiceType = {
const testService = {
typeName: "TestService",
methods: {
timostamm marked this conversation as resolved.
Show resolved Hide resolved
foo: {
Expand All @@ -49,53 +51,91 @@ describe("createHandlerFactory()", function () {
kind: MethodKind.ServerStreaming,
},
},
} as const;
} satisfies ServiceType;

function stub<M extends MethodInfo>(
opt: {
service?: ServiceType;
method?: M;
impl?: MethodImpl<M>;
} & Partial<UniversalHandlerOptions>
function setupTestHandler<M extends MethodInfo>(
timostamm marked this conversation as resolved.
Show resolved Hide resolved
method: M,
opt: Partial<UniversalHandlerOptions>,
impl: MethodImpl<M>
) {
const method = opt.method ?? testService.methods.foo;
let implDefault: MethodImpl<M>;
switch (method.kind) {
case MethodKind.Unary:
// eslint-disable-next-line @typescript-eslint/require-await
implDefault = async function (req: Message, ctx: HandlerContext) {
ctx.responseHeader.set("stub-handler", "1");
return new ctx.method.O();
} as unknown as MethodImpl<M>;
break;
case MethodKind.ServerStreaming:
// eslint-disable-next-line @typescript-eslint/require-await
implDefault = async function* (req: Message, ctx: HandlerContext) {
ctx.responseHeader.set("stub-handler", "1");
yield new ctx.method.O();
} as unknown as MethodImpl<M>;
break;
case MethodKind.ClientStreaming:
case MethodKind.BiDiStreaming:
implDefault = (() => {
throw new Error("not implemented");
}) as unknown as MethodImpl<M>;
break;
}
const spec = createMethodImplSpec(
opt.service ?? testService,
method,
opt.impl ?? implDefault
const h = createHandlerFactory(opt)(
createMethodImplSpec(testService, method, impl)
);
const f = createHandlerFactory(opt);
return f(spec);
const t = createTransport({
httpClient: createUniversalHandlerClient([h]),
baseUrl: "https://example.com",
readMaxBytes: 0xffffff,
writeMaxBytes: 0xffffff,
compressMinBytes: 0xffffff,
useBinaryFormat: true,
interceptors: [],
acceptCompression: [],
sendCompression: null,
});
return {
service: testService,
method: method,
handler: h,
transport: t,
};
}

describe("returned handler", function () {
it("should surface headers for unary", async function () {
const { transport, service, method } = setupTestHandler(
testService.methods.foo,
{},
(req, ctx) => {
ctx.responseHeader.set("implementation-called", "yes");
return { value: req.value.toString(10) };
timostamm marked this conversation as resolved.
Show resolved Hide resolved
}
);
const r = await transport.unary(
service,
method,
undefined,
undefined,
undefined,
new Int32Value({ value: 123 })
);
expect(r.header.get("implementation-called")).toBe("yes");
expect(r.message.value).toBe("123");
});

it("should surface headers for server-streaming", async function () {
const { transport, service, method } = setupTestHandler(
testService.methods.bar,
{},
// eslint-disable-next-line @typescript-eslint/require-await
async function* (req, ctx) {
ctx.responseHeader.set("implementation-called", "yes");
yield { value: req.value.toString(10) };
}
);
const r = await transport.stream(
service,
method,
undefined,
undefined,
undefined,
createAsyncIterable([new Int32Value({ value: 123 })])
);
expect(r.header.get("implementation-called")).toBe("yes");
timostamm marked this conversation as resolved.
Show resolved Hide resolved
const all = await pipeTo(r.message, sinkAll());
expect(all.length).toBe(1);
expect(all[0].value).toBe("123");
});
});

describe("requireConnectProtocolHeader", function () {
describe("with unary RPC", function () {
const h = stub({ requireConnectProtocolHeader: true });
const { handler } = setupTestHandler(
testService.methods.foo,
{ requireConnectProtocolHeader: true },
(req) => ({ value: req.value.toString(10) })
);
it("should raise error for missing header", async function () {
const res = await h({
const res = await handler({
httpVersion: "1.1",
method: "POST",
url: new URL("https://example.com"),
Expand All @@ -116,7 +156,7 @@ describe("createHandlerFactory()", function () {
}
});
it("should raise error for wrong header", async function () {
const res = await h({
const res = await handler({
httpVersion: "1.1",
method: "POST",
url: new URL("https://example.com"),
Expand All @@ -141,12 +181,16 @@ describe("createHandlerFactory()", function () {
});
});
describe("with streaming RPC", function () {
const h = stub({
requireConnectProtocolHeader: true,
method: testService.methods.bar,
});
const { handler } = setupTestHandler(
testService.methods.bar,
{ requireConnectProtocolHeader: true },
// eslint-disable-next-line @typescript-eslint/require-await
async function* (req) {
yield { value: req.value.toString(10) };
}
);
it("should raise error for missing header", async function () {
const res = await h({
const res = await handler({
httpVersion: "1.1",
method: "POST",
url: new URL("https://example.com"),
Expand All @@ -166,7 +210,7 @@ describe("createHandlerFactory()", function () {
}
});
it("should raise error for wrong header", async function () {
const res = await h({
const res = await handler({
httpVersion: "1.1",
method: "POST",
url: new URL("https://example.com"),
Expand Down
7 changes: 5 additions & 2 deletions packages/connect/src/protocol-connect/handler-factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import {
transformPrepend,
transformSerializeEnvelope,
transformSplitEnvelope,
untilFirst,
uResponseMethodNotAllowed,
uResponseOk,
uResponseUnsupportedMediaType,
Expand Down Expand Up @@ -251,7 +252,6 @@ function createStreamHandler<I extends Message<I>, O extends Message<O>>(
serialization: MethodSerializationLookup<I, O>,
endStreamSerialization: Serialization<EndStreamResponse>
) {
// eslint-disable-next-line @typescript-eslint/require-await
return async function handle(
req: UniversalServerRequest
): Promise<UniversalServerResponse> {
Expand Down Expand Up @@ -327,7 +327,10 @@ function createStreamHandler<I extends Message<I>, O extends Message<O>>(
);
return {
...uResponseOk,
body: outputIt,
// We wait for the first response body bytes before resolving, so that
// implementations have a chance to add headers before an adapter commits
// them to the wire.
body: await untilFirst(outputIt),
timostamm marked this conversation as resolved.
Show resolved Hide resolved
header: context.responseHeader,
};
};
Expand Down
120 changes: 120 additions & 0 deletions packages/connect/src/protocol-grpc-web/handler-factory.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
// Copyright 2021-2023 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import type { MethodInfo, ServiceType } from "@bufbuild/protobuf";
import { Int32Value, MethodKind, StringValue } from "@bufbuild/protobuf";
import type { MethodImpl } from "../implementation.js";
import { createMethodImplSpec } from "../implementation.js";
import type { UniversalHandlerOptions } from "../protocol/index.js";
import {
createAsyncIterable,
createUniversalHandlerClient,
pipeTo,
sinkAll,
} from "../protocol/index.js";
import { createHandlerFactory } from "./handler-factory.js";
import { createTransport } from "./transport.js";

describe("createHandlerFactory()", function () {
const testService = {
typeName: "TestService",
methods: {
foo: {
name: "Foo",
I: Int32Value,
O: StringValue,
kind: MethodKind.Unary,
},
bar: {
name: "Bar",
I: Int32Value,
O: StringValue,
kind: MethodKind.ServerStreaming,
},
},
} satisfies ServiceType;
function setupTestHandler<M extends MethodInfo>(
method: M,
opt: Partial<UniversalHandlerOptions>,
impl: MethodImpl<M>
) {
const h = createHandlerFactory(opt)(
createMethodImplSpec(testService, method, impl)
);
const t = createTransport({
httpClient: createUniversalHandlerClient([h]),
baseUrl: "https://example.com",
readMaxBytes: 0xffffff,
writeMaxBytes: 0xffffff,
compressMinBytes: 0xffffff,
useBinaryFormat: true,
interceptors: [],
acceptCompression: [],
sendCompression: null,
});
return {
service: testService,
method: method,
handler: h,
transport: t,
};
}

describe("returned handler", function () {
it("should surface headers for unary", async function () {
timostamm marked this conversation as resolved.
Show resolved Hide resolved
const { transport, service, method } = setupTestHandler(
testService.methods.foo,
{},
(req, ctx) => {
ctx.responseHeader.set("implementation-called", "yes");
return { value: req.value.toString(10) };
}
);
const r = await transport.unary(
service,
method,
undefined,
undefined,
undefined,
new Int32Value({ value: 123 })
);
expect(r.header.get("implementation-called")).toBe("yes");
expect(r.message.value).toBe("123");
});

it("should surface headers for server-streaming", async function () {
const { transport, service, method } = setupTestHandler(
testService.methods.bar,
{},
// eslint-disable-next-line @typescript-eslint/require-await
async function* (req, ctx) {
ctx.responseHeader.set("implementation-called", "yes");
yield { value: req.value.toString(10) };
}
);
const r = await transport.stream(
service,
method,
undefined,
undefined,
undefined,
createAsyncIterable([new Int32Value({ value: 123 })])
);
expect(r.header.get("implementation-called")).toBe("yes");
const all = await pipeTo(r.message, sinkAll());
expect(all.length).toBe(1);
expect(all[0].value).toBe("123");
});
});
});
7 changes: 5 additions & 2 deletions packages/connect/src/protocol-grpc-web/handler-factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import {
transformSplitEnvelope,
transformCatchFinally,
transformInvokeImplementation,
untilFirst,
} from "../protocol/index.js";
import type { Serialization, EnvelopedMessage } from "../protocol/index.js";
import type {
Expand Down Expand Up @@ -99,7 +100,6 @@ function createHandler<I extends Message<I>, O extends Message<O>>(
opt.jsonOptions,
opt
);
// eslint-disable-next-line @typescript-eslint/require-await
return async function handle(
req: UniversalServerRequest
): Promise<UniversalServerResponse> {
Expand Down Expand Up @@ -175,7 +175,10 @@ function createHandler<I extends Message<I>, O extends Message<O>>(
);
return {
...uResponseOk,
body: outputIt,
// We wait for the first response body bytes before resolving, so that
// implementations have a chance to add headers before an adapter commits
// them to the wire.
body: await untilFirst(outputIt),
header: context.responseHeader,
};
};
Expand Down
Loading