From bbfeb8c56ca6f1d8ba0aadf4ec1b1497d48582e3 Mon Sep 17 00:00:00 2001 From: Wanda Mora Date: Thu, 12 Nov 2026 18:58:03 +0000 Subject: [PATCH] feat(functions): add GCFv2 generation upgrade API wrapper and types Adds GCF v2 generation upgrade API client wrappers, types, and backend endpoint mapping for upgrading GCF 1st Gen functions to 2nd Gen. Includes: - GCFv2 API wrappers for generation upgrade endpoints: `setupFunctionUpgradeConfig` (accepting `SetupFunctionUpgradeConfigOptions` for optional `triggerServiceAccount` and `buildConfigOverrides`), `redirectFunctionUpgradeTraffic`, `rollbackFunctionUpgradeTraffic`, `commitFunctionUpgradeAsGen2`, and `abortFunctionUpgrade`, preserving HTTP status codes in `FirebaseError`. - `UpgradeState` and `UpgradeInfo` type declarations matching GCF v2 API schemas. - `OutputCloudFunction.upgradeInfo` property and propagation to `backend.Endpoint.upgradeInfo`. - Unit test coverage in `src/gcp/cloudfunctionsv2.spec.ts`. - Unit tests verifying endpoint paths, payloads (including `SetupFunctionUpgradeConfigOptions`), and operation returns for all 5 upgrade RPC methods. - Unit tests verifying endpoint mapping propagates `upgradeInfo` from GCF v2 output. - Unit tests verifying `FirebaseError` wrapping preserves HTTP status, `original`, and `context`. - Full project compilation via `npm run test:compile`, lint via `npx eslint`, and formatting via `npx prettier --check`. - `npx mocha src/gcp/cloudfunctionsv2.spec.ts src/deploy/functions/backend.spec.ts` --- src/deploy/functions/backend.ts | 3 + src/gcp/cloudfunctionsv2.spec.ts | 124 +++++++++++++++++++++++++++++++ src/gcp/cloudfunctionsv2.ts | 97 +++++++++++++++++++++++- 3 files changed, 223 insertions(+), 1 deletion(-) diff --git a/src/deploy/functions/backend.ts b/src/deploy/functions/backend.ts index 464ca3f7db0..ac78816b9d2 100644 --- a/src/deploy/functions/backend.ts +++ b/src/deploy/functions/backend.ts @@ -419,6 +419,9 @@ export type Endpoint = TargetIds & baseImageUri?: string; command?: string[]; args?: string[]; + + // Upgrade metadata for functions undergoing V1 to V2 migration. + upgradeInfo?: gcfV2.UpgradeInfo; }; export interface RequiredAPI { diff --git a/src/gcp/cloudfunctionsv2.spec.ts b/src/gcp/cloudfunctionsv2.spec.ts index bd2698aa448..a4a6639d42e 100644 --- a/src/gcp/cloudfunctionsv2.spec.ts +++ b/src/gcp/cloudfunctionsv2.spec.ts @@ -7,6 +7,7 @@ import * as events from "../functions/events"; import * as projectConfig from "../functions/projectConfig"; import { BLOCKING_LABEL, CODEBASE_LABEL, HASH_LABEL } from "../functions/constants"; import { functionsV2Origin } from "../api"; +import { FirebaseError } from "../error"; describe("cloudfunctionsv2", () => { const FUNCTION_NAME: backend.TargetIds = { @@ -901,6 +902,24 @@ describe("cloudfunctionsv2", () => { }), ).to.deep.equal(expectedEndpoint); }); + + it("should copy upgradeInfo", () => { + const upgradeInfo: cloudfunctionsv2.UpgradeInfo = { + upgradeState: "SETUP_FUNCTION_UPGRADE_CONFIG_SUCCESSFUL", + }; + expect( + cloudfunctionsv2.endpointFromFunction({ + ...HAVE_CLOUD_FUNCTION_V2, + upgradeInfo, + }), + ).to.deep.equal({ + ...ENDPOINT, + platform: "gcfv2", + uri: GCF_URL, + httpsTrigger: {}, + upgradeInfo, + }); + }); }); describe("createFunction", () => { @@ -967,4 +986,109 @@ describe("cloudfunctionsv2", () => { expect(scope.isDone()).to.be.true; }); }); + + describe("setupFunctionUpgradeConfig", () => { + const functionName = "projects/project/locations/region/functions/id"; + const endpointPath = `/v2/${functionName}:setupFunctionUpgradeConfig`; + + it("should issue POST with empty body when options are omitted", async () => { + const scope = nock(functionsV2Origin()) + .post(endpointPath, {}) + .reply(200, { name: "operations/setup123", done: false }); + + const op = await cloudfunctionsv2.setupFunctionUpgradeConfig(functionName); + expect(op).to.deep.equal({ name: "operations/setup123", done: false }); + expect(scope.isDone()).to.be.true; + }); + + it("should include triggerServiceAccount and buildConfigOverrides when provided", async () => { + const scope = nock(functionsV2Origin()) + .post(endpointPath, { + triggerServiceAccount: "sa@project.iam.gserviceaccount.com", + buildConfigOverrides: { runtime: "nodejs22" }, + }) + .reply(200, { name: "operations/setup123", done: false }); + + const op = await cloudfunctionsv2.setupFunctionUpgradeConfig(functionName, { + triggerServiceAccount: "sa@project.iam.gserviceaccount.com", + buildConfigOverrides: { runtime: "nodejs22" }, + }); + expect(op).to.deep.equal({ name: "operations/setup123", done: false }); + expect(scope.isDone()).to.be.true; + }); + + it("should wrap API errors in FirebaseError while preserving HTTP status", async () => { + const scope = nock(functionsV2Origin()) + .post(endpointPath, {}) + .reply(429, { error: { message: "Quota exceeded" } }); + + const err = (await expect( + cloudfunctionsv2.setupFunctionUpgradeConfig(functionName), + ).to.be.rejectedWith( + FirebaseError, + `Failed to setup upgrade config for function ${functionName}`, + )) as FirebaseError; + expect(err.status).to.equal(429); + expect(err.original).to.be.instanceOf(FirebaseError); + expect(err.context).to.deep.equal({ function: functionName }); + expect(scope.isDone()).to.be.true; + }); + }); + + for (const { method, action, opName, errorVerb } of [ + { + method: cloudfunctionsv2.redirectFunctionUpgradeTraffic, + action: "redirectFunctionUpgradeTraffic", + opName: "operations/redirect123", + errorVerb: "redirect upgrade traffic", + }, + { + method: cloudfunctionsv2.rollbackFunctionUpgradeTraffic, + action: "rollbackFunctionUpgradeTraffic", + opName: "operations/rollback123", + errorVerb: "rollback upgrade traffic", + }, + { + method: cloudfunctionsv2.commitFunctionUpgradeAsGen2, + action: "commitFunctionUpgradeAsGen2", + opName: "operations/commit123", + errorVerb: "commit upgrade as Gen 2", + }, + { + method: cloudfunctionsv2.abortFunctionUpgrade, + action: "abortFunctionUpgrade", + opName: "operations/abort123", + errorVerb: "abort upgrade", + }, + ]) { + describe(action, () => { + const functionName = "projects/project/locations/region/functions/id"; + const endpointPath = `/v2/${functionName}:${action}`; + + it(`should issue POST to ${action}`, async () => { + const scope = nock(functionsV2Origin()) + .post(endpointPath, {}) + .reply(200, { name: opName, done: false }); + + const op = await method(functionName); + expect(op).to.deep.equal({ name: opName, done: false }); + expect(scope.isDone()).to.be.true; + }); + + it("should wrap API errors in FirebaseError while preserving HTTP status", async () => { + const scope = nock(functionsV2Origin()) + .post(endpointPath, {}) + .reply(503, { error: { message: "Service unavailable" } }); + + const err = (await expect(method(functionName)).to.be.rejectedWith( + FirebaseError, + `Failed to ${errorVerb} for function ${functionName}`, + )) as FirebaseError; + expect(err.status).to.equal(503); + expect(err.original).to.be.instanceOf(FirebaseError); + expect(err.context).to.deep.equal({ function: functionName }); + expect(scope.isDone()).to.be.true; + }); + }); + } }); diff --git a/src/gcp/cloudfunctionsv2.ts b/src/gcp/cloudfunctionsv2.ts index 7e347e1e9e9..05066778200 100644 --- a/src/gcp/cloudfunctionsv2.ts +++ b/src/gcp/cloudfunctionsv2.ts @@ -1,5 +1,5 @@ import { Client, ClientVerbOptions } from "../apiv2"; -import { FirebaseError } from "../error"; +import { FirebaseError, getErrStatus } from "../error"; import { functionsV2Origin } from "../api"; import { logger } from "../logger"; import { AUTH_BLOCKING_EVENTS } from "../functions/events/v1"; @@ -38,6 +38,23 @@ export type DirectVpcEgress = `VPC_EGRESS_${"UNSPECIFIED" | VpcConnectorEgressSe export type IngressSettings = "ALLOW_ALL" | "ALLOW_INTERNAL_ONLY" | "ALLOW_INTERNAL_AND_GCLB"; export type FunctionState = "ACTIVE" | "FAILED" | "DEPLOYING" | "DELETING" | "UNKONWN"; +export type UpgradeState = + | "UPGRADE_STATE_UNSPECIFIED" + | "ELIGIBLE_FOR_2ND_GEN_UPGRADE" + | "INELIGIBLE_FOR_UPGRADE_UNTIL_REDEPLOYMENT" + | "UPGRADE_OPERATION_IN_PROGRESS" + | "SETUP_FUNCTION_UPGRADE_CONFIG_SUCCESSFUL" + | "SETUP_FUNCTION_UPGRADE_CONFIG_ERROR" + | "REDIRECT_FUNCTION_UPGRADE_TRAFFIC_SUCCESSFUL" + | "REDIRECT_FUNCTION_UPGRADE_TRAFFIC_ERROR" + | "ROLLBACK_FUNCTION_UPGRADE_TRAFFIC_ERROR" + | "COMMIT_FUNCTION_UPGRADE_ERROR" + | "COMMIT_FUNCTION_UPGRADE_ERROR_ROLLBACK_SAFE" + // Deprecated in proto; backend signals completion via the LRO response instead. + | "COMMIT_FUNCTION_UPGRADE_AS_GEN2_SUCCESSFUL" + | "COMMIT_FUNCTION_UPGRADE_AS_GEN2_ERROR" + | "ABORT_FUNCTION_UPGRADE_ERROR"; + // Values allowed for the operator field in EventFilter export type EventFilterOperator = "match-path-pattern"; @@ -164,6 +181,14 @@ export interface EventTrigger { channel?: string; } +export interface UpgradeInfo { + buildConfig?: BuildConfig; + serviceConfig?: ServiceConfig; + eventTrigger?: EventTrigger; + // Omitted in proto3 JSON when UPGRADE_STATE_UNSPECIFIED (0). + upgradeState?: UpgradeState; +} + interface CloudFunctionBase { name: string; description?: string; @@ -178,6 +203,7 @@ export type OutputCloudFunction = CloudFunctionBase & { updateTime: Date; serviceConfig?: RequireKeys; url: string; + upgradeInfo?: UpgradeInfo; }; export type InputCloudFunction = CloudFunctionBase & { @@ -423,6 +449,74 @@ export async function deleteFunction(cloudFunction: string): Promise } } +export interface SetupFunctionUpgradeConfigOptions { + triggerServiceAccount?: string; + buildConfigOverrides?: { runtime?: supported.Runtime }; +} + +async function postUpgradeAction>( + name: string, + action: string, + errorVerb: string, + body: Req = {} as Req, +): Promise { + try { + const res = await client.post(`${name}:${action}`, body); + return res.body; + } catch (err: unknown) { + throw new FirebaseError(`Failed to ${errorVerb} for function ${name}`, { + original: err instanceof Error ? err : undefined, + status: getErrStatus(err), + context: { function: name }, + }); + } +} + +/** + * Sets up a 2nd Gen upgrade configuration for a 1st Gen Cloud Function. + */ +export async function setupFunctionUpgradeConfig( + name: string, + options: SetupFunctionUpgradeConfigOptions = {}, +): Promise { + const body: SetupFunctionUpgradeConfigOptions = {}; + if (options.triggerServiceAccount) { + body.triggerServiceAccount = options.triggerServiceAccount; + } + if (options.buildConfigOverrides?.runtime) { + body.buildConfigOverrides = { runtime: options.buildConfigOverrides.runtime }; + } + return postUpgradeAction(name, "setupFunctionUpgradeConfig", "setup upgrade config", body); +} + +/** + * Redirects traffic from 1st Gen to 2nd Gen for an upgrading Cloud Function. + */ +export function redirectFunctionUpgradeTraffic(name: string): Promise { + return postUpgradeAction(name, "redirectFunctionUpgradeTraffic", "redirect upgrade traffic"); +} + +/** + * Rolls back traffic from 2nd Gen to 1st Gen for an upgrading Cloud Function. + */ +export function rollbackFunctionUpgradeTraffic(name: string): Promise { + return postUpgradeAction(name, "rollbackFunctionUpgradeTraffic", "rollback upgrade traffic"); +} + +/** + * Commits a function upgrade as a managed 2nd Gen Cloud Function (deleting the 1st Gen resource). + */ +export function commitFunctionUpgradeAsGen2(name: string): Promise { + return postUpgradeAction(name, "commitFunctionUpgradeAsGen2", "commit upgrade as Gen 2"); +} + +/** + * Aborts an active function upgrade, dismantling the 2nd Gen copy and resetting upgrade state. + */ +export function abortFunctionUpgrade(name: string): Promise { + return postUpgradeAction(name, "abortFunctionUpgrade", "abort upgrade"); +} + /** * Generate a v2 Cloud Function API object from a versionless Endpoint object. */ @@ -809,5 +903,6 @@ export function endpointFromFunction(gcfFunction: OutputCloudFunction): backend. endpoint.hash = gcfFunction.labels[HASH_LABEL]; } proto.copyIfPresent(endpoint, gcfFunction, "state"); + proto.copyIfPresent(endpoint, gcfFunction, "upgradeInfo"); return endpoint; }