Skip to content
Closed
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
7 changes: 7 additions & 0 deletions scripts/bin-test/sources/esm-quoted-hyphen/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import * as functions from "firebase-functions/v1";

const func = functions.https.onRequest((req, resp) => {
resp.status(200).send("PASS");
});

export { func as "dummystore-bot" };
4 changes: 4 additions & 0 deletions scripts/bin-test/sources/esm-quoted-hyphen/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"name": "esm-quoted-hyphen",
"type": "module"
}
17 changes: 17 additions & 0 deletions scripts/bin-test/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,23 @@ describe("functions.yaml", function () {
extensions: {},
},
},
{
name: "quoted hyphen export",
modulePath: "./scripts/bin-test/sources/esm-quoted-hyphen",
expected: {
endpoints: {
"dummystore-bot": {
...DEFAULT_V1_OPTIONS,
platform: "gcfv1",
entryPoint: "dummystore-bot",
httpsTrigger: {},
},
},
requiredAPIs: [],
specVersion: "v1alpha1",
extensions: {},
},
},
];

for (const tc of testcases) {
Expand Down
28 changes: 28 additions & 0 deletions spec/runtime/loader.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,34 @@ describe("extractStack", () => {
});
});

it("preserves literal hyphens in the entry point for flat export names", () => {
const module = {
"dummystore-bot": httpFn,
grouped: {
fn: httpFn,
},
};

const endpoints: Record<string, ManifestEndpoint> = {};
const requiredAPIs: ManifestRequiredAPI[] = [];
const extensions: Record<string, ManifestExtension> = {};

loader.extractStack(module, endpoints, requiredAPIs, extensions);

expect(endpoints).to.be.deep.equal({
"dummystore-bot": {
...MINIMAL_V1_ENDPOINT,
entryPoint: "dummystore-bot",
...httpEndpoint,
},
"grouped-fn": {
...MINIMAL_V1_ENDPOINT,
entryPoint: "grouped.fn",
...httpEndpoint,
},
});
});

describe("with GCLOUD_PROJECT env var", () => {
const project = "my-project";
let prev;
Expand Down
83 changes: 73 additions & 10 deletions spec/v2/providers/https.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -677,24 +677,32 @@ describe("onCall", () => {

describe("onCallGenkit", () => {
it("calls with JSON requests", async () => {
let gotContext: any;
const flow = {
__action: {
name: "test",
},
run: sinon.stub(),
stream: sinon.stub(),
};
flow.run.withArgs("answer").returns({ result: 42 });
flow.run.callsFake((data, opts) => {
gotContext = opts.context;
expect(data).to.equal("answer");
return { result: 42 };
});
flow.stream.throws("Unexpected stream");

const f = https.onCallGenkit(flow);

const req = request({ data: "answer" });
const res = await runHandler(f, req);
expect(JSON.parse(res.body)).to.deep.equal({ result: 42 });
expect(gotContext[https.CALLABLE_RAW_REQUEST]).to.equal(req);
expect(gotContext[https.CALLABLE_RESPONSE_SIGNAL]).to.be.instanceOf(AbortSignal);
});

it("Streams with SSE requests", async () => {
it("forwards rawRequest and response signal into streaming Genkit action context", async () => {
let gotContext: any;
const flow = {
__action: {
name: "test",
Expand All @@ -703,25 +711,80 @@ describe("onCallGenkit", () => {
stream: sinon.stub(),
};
flow.run.onFirstCall().throws();
flow.stream.withArgs("answer").returns({
stream: (async function* () {
await Promise.resolve();
yield 1;
await Promise.resolve();
yield 2;
})(),
output: Promise.resolve(42),
flow.stream.callsFake((data, opts) => {
gotContext = opts.context;
expect(data).to.equal("answer");
return {
stream: (async function* () {
await Promise.resolve();
yield 1;
await Promise.resolve();
yield 2;
})(),
output: Promise.resolve(42),
};
});

const f = https.onCallGenkit(flow);

const req = request({ data: "answer", headers: { accept: "text/event-stream" } });
const res = await runHandler(f, req);
expect(gotContext[https.CALLABLE_RAW_REQUEST]).to.equal(req);
expect(gotContext[https.CALLABLE_RESPONSE_SIGNAL]).to.be.instanceOf(AbortSignal);
expect(res.body).to.equal(
['data: {"message":1}', 'data: {"message":2}', 'data: {"result":42}', ""].join("\n\n")
);
});

it("aborts the forwarded response signal when the client disconnects", async () => {
let capturedSignal: AbortSignal;
let resolveOutput: (value: number) => void;
const output = new Promise<number>((resolve) => {
resolveOutput = resolve;
});
let notifyStreamStarted: () => void;
const streamStarted = new Promise<void>((resolve) => {
notifyStreamStarted = resolve;
});
const flow = {
__action: {
name: "test",
},
run: sinon.stub(),
stream: sinon.stub(),
};
flow.run.onFirstCall().throws();
flow.stream.callsFake((_data, opts) => {
capturedSignal = opts.context[https.CALLABLE_RESPONSE_SIGNAL] as AbortSignal;
notifyStreamStarted();
return {
stream: (async function* () {
await output;
// This test intentionally doesn't emit any stream messages, but ESLint's `require-yield`
// rule requires at least one `yield` in a generator function.
return;
// eslint-disable-next-line no-unreachable
yield undefined;
})(),
Comment on lines +761 to +768
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Instead of using an unreachable yield statement and disabling the ESLint rule, you can use yield* [] to elegantly satisfy the require-yield rule. This avoids unreachable code and linter bypasses entirely.

        stream: (async function* () {
          await output;
          yield* [];
        })(),

output,
};
});

const f = https.onCallGenkit(flow);
const req = request({ data: "answer", headers: { accept: "text/event-stream" } });
const resPromise = runHandler(f, req);

await streamStarted;
expect(capturedSignal.aborted).to.equal(false);

req.emit("close");
expect(capturedSignal.aborted).to.equal(true);
resolveOutput(42);

const res = await resPromise;
expect(res.body).to.be.undefined;
});

it("Exports types that are compatible with the genkit library (compilation is success)", () => {
const ai = genkit({});
const flow = ai.defineFlow("test", () => 42);
Expand Down
10 changes: 10 additions & 0 deletions src/common/providers/https.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,16 @@ export const CALLABLE_AUTH_HEADER = "x-callable-context-auth";
export const ORIGINAL_AUTH_HEADER = "x-original-auth";
/** @internal */
export const DEFAULT_HEARTBEAT_SECONDS = 30;
/**
* Symbol key used by {@link https.onCallGenkit} to expose the underlying callable raw request
* inside the Genkit action context.
*/
export const CALLABLE_RAW_REQUEST = Symbol.for("firebase.callable.rawRequest");
/**
* Symbol key used by {@link https.onCallGenkit} to expose the callable disconnect signal
* inside the Genkit action context.
*/
export const CALLABLE_RESPONSE_SIGNAL = Symbol.for("firebase.callable.responseSignal");

/** An express request with the wire format representation of the request body. */
export interface Request extends express.Request {
Expand Down
19 changes: 14 additions & 5 deletions src/runtime/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,16 +65,18 @@ export function extractStack(
endpoints: Record<string, ManifestEndpoint>,
requiredAPIs: ManifestRequiredAPI[],
extensions: Record<string, ManifestExtension>,
prefix = ""
endpointIdPrefix = "",
entryPointPrefix = ""
) {
for (const [name, valAsUnknown] of Object.entries(module)) {
// We're introspecting untrusted code here. Any is appropraite
const val: any = valAsUnknown;
if (typeof val === "function" && val.__endpoint && typeof val.__endpoint === "object") {
const funcName = prefix + name;
endpoints[funcName] = {
const endpointId = endpointIdPrefix + name;
const entryPoint = entryPointPrefix + name;
endpoints[endpointId] = {
...val.__endpoint,
entryPoint: funcName.replace(/-/g, "."),
entryPoint,
};
if (val.__requiredAPIs && Array.isArray(val.__requiredAPIs)) {
requiredAPIs.push(...val.__requiredAPIs);
Expand All @@ -92,7 +94,14 @@ export function extractStack(
events: val.events || [],
};
} else if (isObject(val)) {
extractStack(val, endpoints, requiredAPIs, extensions, prefix + name + "-");
extractStack(
val,
endpoints,
requiredAPIs,
extensions,
endpointIdPrefix + name + "-",
entryPointPrefix + name + "."
);
}
}
}
Expand Down
9 changes: 8 additions & 1 deletion src/v2/providers/https.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ import { wrapTraceContext } from "../trace";
import { isDebugFeatureEnabled } from "../../common/debug";
import { ResetValue } from "../../common/options";
import {
CALLABLE_RAW_REQUEST,
CALLABLE_RESPONSE_SIGNAL,
type CallableRequest,
type CallableResponse,
type FunctionsErrorCode,
Expand All @@ -50,6 +52,7 @@ import { withInit } from "../../common/onInit";
import * as logger from "../../logger";

export type { Request, CallableRequest, CallableResponse, FunctionsErrorCode };
export { CALLABLE_RAW_REQUEST, CALLABLE_RESPONSE_SIGNAL };
export { HttpsError };

/**
Expand Down Expand Up @@ -604,8 +607,12 @@ export function onCallGenkit<A extends GenkitAction>(
const cloudFunction = onCall<ActionInput<A>, Promise<ActionOutput<A>>, ActionStream<A>>(
opts,
async (req, res) => {
const context: Omit<CallableRequest, "data" | "rawRequest" | "acceptsStreaming"> = {};
const context: Omit<CallableRequest, "data" | "rawRequest" | "acceptsStreaming"> & {
[key: symbol]: unknown;
} = {};
copyIfPresent(context, req, "auth", "app", "instanceIdToken");
context[CALLABLE_RAW_REQUEST] = req.rawRequest;
context[CALLABLE_RESPONSE_SIGNAL] = res?.signal;

if (!req.acceptsStreaming) {
const { result } = await action.run(req.data, { context });
Expand Down
Loading