Skip to content
Open
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
3 changes: 3 additions & 0 deletions src/deploy/functions/backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@
return allMemoryOptions.includes(mem as MemoryOptions);
}

export function isValidEgressSetting(egress: unknown): egress is VpcEgressSettings {

Check warning on line 198 in src/deploy/functions/backend.ts

View workflow job for this annotation

GitHub Actions / lint (24)

Missing JSDoc comment
return egress === "PRIVATE_RANGES_ONLY" || egress === "ALL_TRAFFIC";
}

Expand Down Expand Up @@ -419,6 +419,9 @@
baseImageUri?: string;
command?: string[];
args?: string[];

// Upgrade metadata for functions undergoing V1 to V2 migration.
upgradeInfo?: gcfV2.UpgradeInfo;
};

export interface RequiredAPI {
Expand Down Expand Up @@ -465,7 +468,7 @@
}

/**

Check warning on line 471 in src/deploy/functions/backend.ts

View workflow job for this annotation

GitHub Actions / lint (24)

Expected JSDoc block to be aligned
* A helper utility to create an empty backend.
* Tests that verify the behavior of one possible resource in a Backend can use
* this method to avoid compiler errors when new fields are added to Backend.
Expand Down Expand Up @@ -670,8 +673,8 @@
existingBackend.endpoints[endpoint.region][endpoint.id] = endpoint;
}
}
} catch (err: any) {

Check warning on line 676 in src/deploy/functions/backend.ts

View workflow job for this annotation

GitHub Actions / lint (24)

Unexpected any. Specify a different type
logger.debug(`Error loading Cloud Run services: ${err.message}`);

Check warning on line 677 in src/deploy/functions/backend.ts

View workflow job for this annotation

GitHub Actions / lint (24)

Unsafe member access .message on an `any` value

Check warning on line 677 in src/deploy/functions/backend.ts

View workflow job for this annotation

GitHub Actions / lint (24)

Invalid type "any" of template literal expression
unreachableRegions.run = ["unknown"];
}
}
Expand Down Expand Up @@ -852,7 +855,7 @@
logger.info(
`Function name ${httpsFunc.id} is too long to have a deterministic Cloud Run URI. Printing the non-deterministic URI instead.`,
);
return httpsFunc.uri!;

Check warning on line 858 in src/deploy/functions/backend.ts

View workflow job for this annotation

GitHub Actions / lint (24)

Forbidden non-null assertion
}
return `https://${serviceName}-${projectNumber}.${httpsFunc.region}.run.app`;
}
124 changes: 124 additions & 0 deletions src/gcp/cloudfunctionsv2.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
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 = {
Expand Down Expand Up @@ -325,7 +326,7 @@
serviceConfig: {
...HAVE_CLOUD_FUNCTION_V2.serviceConfig,
directVpcNetworkInterface: [{ network: "my-net" }],
directVpcEgress: "ALL_TRAFFIC" as any,

Check warning on line 329 in src/gcp/cloudfunctionsv2.spec.ts

View workflow job for this annotation

GitHub Actions / lint (24)

Unexpected any. Specify a different type

Check warning on line 329 in src/gcp/cloudfunctionsv2.spec.ts

View workflow job for this annotation

GitHub Actions / lint (24)

Unsafe assignment of an `any` value
uri: RUN_URI,
service: "service",
},
Expand All @@ -339,7 +340,7 @@
serviceConfig: {
...HAVE_CLOUD_FUNCTION_V2.serviceConfig,
directVpcNetworkInterface: [{ network: "my-net" }],
directVpcEgress: "VPC_EGRESS_UNSPECIFIED" as any,

Check warning on line 343 in src/gcp/cloudfunctionsv2.spec.ts

View workflow job for this annotation

GitHub Actions / lint (24)

Unexpected any. Specify a different type

Check warning on line 343 in src/gcp/cloudfunctionsv2.spec.ts

View workflow job for this annotation

GitHub Actions / lint (24)

Unsafe assignment of an `any` value
uri: RUN_URI,
service: "service",
},
Expand Down Expand Up @@ -901,6 +902,24 @@
}),
).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", () => {
Expand Down Expand Up @@ -967,4 +986,109 @@
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;
});
});
}
});
97 changes: 96 additions & 1 deletion src/gcp/cloudfunctionsv2.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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";

Expand Down Expand Up @@ -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;
Expand All @@ -178,6 +203,7 @@ export type OutputCloudFunction = CloudFunctionBase & {
updateTime: Date;
serviceConfig?: RequireKeys<ServiceConfig, "service" | "uri">;
url: string;
upgradeInfo?: UpgradeInfo;
};

export type InputCloudFunction = CloudFunctionBase & {
Expand Down Expand Up @@ -423,6 +449,74 @@ export async function deleteFunction(cloudFunction: string): Promise<Operation>
}
}

export interface SetupFunctionUpgradeConfigOptions {
triggerServiceAccount?: string;
buildConfigOverrides?: { runtime?: supported.Runtime };
}

async function postUpgradeAction<Req extends object = Record<string, never>>(
name: string,
action: string,
errorVerb: string,
body: Req = {} as Req,
): Promise<Operation> {
try {
const res = await client.post<Req, Operation>(`${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<Operation> {
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<Operation> {
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<Operation> {
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<Operation> {
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<Operation> {
return postUpgradeAction(name, "abortFunctionUpgrade", "abort upgrade");
}

/**
* Generate a v2 Cloud Function API object from a versionless Endpoint object.
*/
Expand Down Expand Up @@ -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;
}
Loading