Skip to content
Open
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
12b9257
adds listServices fn and adds trigger to endpointFromService fn
brittanycho Oct 31, 2025
0a30722
updates functions-list to use listServices to use cloud run api instead
brittanycho Oct 31, 2025
df189ee
adds listServices tests
brittanycho Oct 31, 2025
66cf473
fix linting errors
brittanycho Oct 31, 2025
3af536c
Merge branch 'master' into fr/cloud-run-fns-list
brittanycho Oct 31, 2025
f6ef8c0
Update src/commands/functions-list.ts
brittanycho Nov 3, 2025
d9fd843
Update src/gcp/runv2.ts
brittanycho Nov 3, 2025
84725cf
corrects import error
brittanycho Nov 3, 2025
6a45457
add relevant labelSelectors
brittanycho Nov 4, 2025
9cedf12
adding v1 fns in
brittanycho Nov 5, 2025
481d02f
adding in deduplication
brittanycho Nov 5, 2025
0362303
Merge branch 'master' into fr/cloud-run-fns-list
brittanycho Nov 5, 2025
d4ed0f9
Update src/gcp/runv2.ts
brittanycho Nov 5, 2025
2de426f
linting
brittanycho Nov 5, 2025
7cb75d8
Merge branch 'master' into fr/cloud-run-fns-list
brittanycho Nov 6, 2025
4d06024
Merge branch 'master' into fr/cloud-run-fns-list
brittanycho Nov 8, 2025
3712d0c
Merge branch 'master' into fr/cloud-run-fns-list
brittanycho Nov 10, 2025
d1986ac
follow-up on feedback: move parts of implementation to backend.ts, ad…
brittanycho Nov 11, 2025
8f1c06d
correct lint error
brittanycho Nov 11, 2025
1cef2a6
Update src/commands/functions-list.ts
brittanycho Nov 11, 2025
0de7514
addressing feedback on parsing
brittanycho Nov 11, 2025
66e5d6f
feat: upgrade functions::list to use Cloud Run API and bump version t…
brittanycho Nov 11, 2025
c1f2e7b
adjust how v2 functions are being called from listServices
brittanycho Nov 11, 2025
bd8ea09
add updated tests to backend.spec.ts
brittanycho Nov 11, 2025
86ef3f6
addresses feedback from code review
brittanycho Nov 12, 2025
9287590
updates changelog
brittanycho Nov 12, 2025
896d3a1
Merge branch 'master' into fr/cloud-run-fns-list
brittanycho Nov 12, 2025
a38b669
Merge branch 'master' into fr/cloud-run-fns-list
brittanycho Nov 12, 2025
c253ae9
addresses feedback
brittanycho Nov 13, 2025
0779bff
Merge branch 'master' into fr/cloud-run-fns-list
brittanycho Nov 13, 2025
a36e9d9
Merge remote-tracking branch 'origin/fr/cloud-run-fns-list' into fr/c…
brittanycho Nov 13, 2025
5acc3cf
Update src/gcp/runv2.ts
brittanycho Nov 13, 2025
812fda9
correct linting errors
brittanycho Nov 13, 2025
4ebc27b
Update src/deploy/functions/backend.spec.ts
brittanycho Nov 14, 2025
369c402
updates error handling and tests
brittanycho Nov 15, 2025
963ff16
Merge branch 'master' into fr/cloud-run-fns-list
brittanycho Nov 17, 2025
1ba7368
will add in changelog back in at the end
brittanycho Nov 17, 2025
536c3d8
updated based on feedback
brittanycho Nov 18, 2025
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Upgraded functions::list command to use cloud run api (#9425)
52 changes: 43 additions & 9 deletions src/commands/functions-list.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,72 @@
import { Command } from "../command";
import * as args from "../deploy/functions/args";
import { needProjectId } from "../projectUtils";
import { Options } from "../options";
import { requirePermissions } from "../requirePermissions";
import * as backend from "../deploy/functions/backend";
import { logger } from "../logger";
import * as Table from "cli-table3";
import { Options } from "../options";
import { FunctionsPlatform } from "../deploy/functions/backend";

type PLATFORM_DISPLAY_NAME = "v1" | "v2" | "run";
const PLATFORM_TO_DISPLAY_NAME: Record<FunctionsPlatform, PLATFORM_DISPLAY_NAME> = {
gcfv1: "v1",
gcfv2: "v2",
run: "run",
};

export const command = new Command("functions:list")
.description("list all deployed functions in your Firebase project")
.before(requirePermissions, ["cloudfunctions.functions.list"])
.before(requirePermissions, ["cloudfunctions.functions.list", "run.services.list"])
.action(async (options: Options) => {
const projectId = needProjectId(options);
const context = {
projectId: needProjectId(options),
projectId,
} as args.Context;
const existing = await backend.existingBackend(context);
const endpointsList = backend.allEndpoints(existing).sort(backend.compareFunctions);

let v1Endpoints: backend.Endpoint[] = [];
try {
const existing = await backend.existingBackend(context);
v1Endpoints = backend.allEndpoints(existing);
} catch (err: any) {

Check warning on line 31 in src/commands/functions-list.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unexpected any. Specify a different type
logger.debug(`Failed to list v1 functions:`, err);
logger.warn(
`Failed to list v1 functions. Ensure you have the Cloud Functions API enabled and the necessary permissions.`,
);
}

const endpointMap = new Map<string, backend.Endpoint>();
for (const endpoint of v1Endpoints) {
const key = `${endpoint.region}/${endpoint.id}`;
endpointMap.set(key, endpoint);
}

const endpoints = Array.from(endpointMap.values());
endpoints.sort(backend.compareFunctions);

if (endpoints.length === 0) {
logger.info(`No functions found in project ${projectId}.`);
return [];
}

const table = new Table({

Check warning on line 52 in src/commands/functions-list.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe assignment of an `any` value
head: ["Function", "Version", "Trigger", "Location", "Memory", "Runtime"],
style: { head: ["yellow"] },
});
for (const endpoint of endpointsList) {
}) as any;

Check warning on line 55 in src/commands/functions-list.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unexpected any. Specify a different type

for (const endpoint of endpoints) {
const trigger = backend.endpointTriggerType(endpoint);
const availableMemoryMb = endpoint.availableMemoryMb || "---";
const entry = [
endpoint.id,
endpoint.platform === "gcfv2" ? "v2" : "v1",
PLATFORM_TO_DISPLAY_NAME[endpoint.platform] || "v1",
trigger,
endpoint.region,
availableMemoryMb,
endpoint.runtime,
];
table.push(entry);

Check warning on line 68 in src/commands/functions-list.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe call of an `any` typed value

Check warning on line 68 in src/commands/functions-list.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe member access .push on an `any` value
}
logger.info(table.toString());

Check warning on line 70 in src/commands/functions-list.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe call of an `any` typed value

Check warning on line 70 in src/commands/functions-list.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe member access .toString on an `any` value

Check warning on line 70 in src/commands/functions-list.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe argument of type `any` assigned to a parameter of type `Error`
return endpointsList;
return endpoints;
});
19 changes: 19 additions & 0 deletions src/deploy/functions/backend.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import * as backend from "./backend";
import * as gcf from "../../gcp/cloudfunctions";
import * as gcfV2 from "../../gcp/cloudfunctionsv2";
import * as runv2 from "../../gcp/runv2";
import * as utils from "../../utils";
import * as projectConfig from "../../functions/projectConfig";

Expand Down Expand Up @@ -126,17 +127,20 @@
describe("existing backend", () => {
let listAllFunctions: sinon.SinonStub;
let listAllFunctionsV2: sinon.SinonStub;
let listServices: sinon.SinonStub;
let logLabeledWarning: sinon.SinonSpy;

beforeEach(() => {
listAllFunctions = sinon.stub(gcf, "listAllFunctions").rejects("Unexpected call");
listAllFunctionsV2 = sinon.stub(gcfV2, "listAllFunctions").rejects("Unexpected v2 call");
listServices = sinon.stub(runv2, "listServices").resolves([]);
logLabeledWarning = sinon.spy(utils, "logLabeledWarning");
});

afterEach(() => {
listAllFunctions.restore();
listAllFunctionsV2.restore();
listServices.restore();
logLabeledWarning.restore();
});

Expand Down Expand Up @@ -318,6 +322,21 @@

expect(have).to.deep.equal(want);
});

it("should list services with correct filter", async () => {
listAllFunctions.onFirstCall().resolves({
functions: [],
unreachable: [],
});
listAllFunctionsV2.onFirstCall().resolves({
functions: [],
unreachable: [],
});

await backend.existingBackend(newContext());

expect(listServices).to.have.been.calledWith(sinon.match.any, "goog-managed-by=cloudfunctions");

Check failure on line 338 in src/deploy/functions/backend.spec.ts

View workflow job for this annotation

GitHub Actions / unit (22)

Replace `sinon.match.any,·"goog-managed-by=cloudfunctions"` with `⏎··········sinon.match.any,⏎··········"goog-managed-by=cloudfunctions",⏎········`

Check failure on line 338 in src/deploy/functions/backend.spec.ts

View workflow job for this annotation

GitHub Actions / unit (20)

Replace `sinon.match.any,·"goog-managed-by=cloudfunctions"` with `⏎··········sinon.match.any,⏎··········"goog-managed-by=cloudfunctions",⏎········`

Check failure on line 338 in src/deploy/functions/backend.spec.ts

View workflow job for this annotation

GitHub Actions / unit (22)

Replace `sinon.match.any,·"goog-managed-by=cloudfunctions"` with `⏎··········sinon.match.any,⏎··········"goog-managed-by=cloudfunctions",⏎········`

Check failure on line 338 in src/deploy/functions/backend.spec.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Replace `sinon.match.any,·"goog-managed-by=cloudfunctions"` with `⏎··········sinon.match.any,⏎··········"goog-managed-by=cloudfunctions",⏎········`
});
});

describe("checkAvailability", () => {
Expand Down
16 changes: 16 additions & 0 deletions src/deploy/functions/backend.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as gcf from "../../gcp/cloudfunctions";
import * as gcfV2 from "../../gcp/cloudfunctionsv2";
import { listServices, endpointFromService } from "../../gcp/runv2";
import * as utils from "../../utils";
import { Runtime } from "./runtimes/supported";
import { FirebaseError } from "../../error";
Expand Down Expand Up @@ -551,14 +552,29 @@
existingBackend.endpoints[endpoint.region][endpoint.id] = endpoint;
}
unreachableRegions.gcfV2 = gcfV2Results.unreachable;
} catch (err: any) {

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

View workflow job for this annotation

GitHub Actions / lint (20)

Unexpected any. Specify a different type
if (err.status === 404 && err.message?.toLowerCase().includes("method not found")) {

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

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe member access .status on an `any` value
// customer has preview enabled without allowlist set
} else {
throw err;
}
}

try {
const runServices = await listServices(ctx.projectId, "goog-managed-by=cloudfunctions");
for (const service of runServices) {
const endpoint = endpointFromService(service);
existingBackend.endpoints[endpoint.region] = existingBackend.endpoints[endpoint.region] || {};
existingBackend.endpoints[endpoint.region][endpoint.id] = endpoint;
}
} catch (err: any) {
utils.logLabeledWarning(
"functions",
`Failed to list Cloud Run services: ${err.message}. Ensure you have the Cloud Run Admin API enabled and the necessary permissions.`,
);
unreachableRegions.run = ["unknown"]; // Indicate that Run services could not be listed
Copy link
Contributor

Choose a reason for hiding this comment

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

this is a bit surprising. does the Run API not return list of unreacheable regions?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Hmm I couldn't find anything in the services.list Service object or in other Cloud Run documentation through a google search but I could definitely be missing something - I will follow-up and ask in the Cloud Run Space

Copy link
Contributor Author

@brittanycho brittanycho Nov 12, 2025

Choose a reason for hiding this comment

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

Update on above here: https://chat.google.com/room/AAAA8PjxsIE/mgFct9F0k9I/mgFct9F0k9I?cls=10

Discussed further offline with Daniel and decided to move forward with this PR without unreachable regions and will add it back in later when it is fully deployed by cloud run

}

ctx.existingBackend = existingBackend;
ctx.unreachableRegions = unreachableRegions;
return ctx.existingBackend;
Expand Down
85 changes: 81 additions & 4 deletions src/gcp/runv2.spec.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { expect } from "chai";
import * as sinon from "sinon";

import * as runv2 from "./runv2";
import * as backend from "../deploy/functions/backend";
import { latest } from "../deploy/functions/runtimes/supported";
import { CODEBASE_LABEL } from "../functions/constants";
import { Client } from "../apiv2";
import { FirebaseError } from "../error";

describe("runv2", () => {
const PROJECT_ID = "project-id";
Expand Down Expand Up @@ -201,13 +204,11 @@ describe("runv2", () => {
const service: Omit<runv2.Service, runv2.ServiceOutputFields> = {
...BASE_RUN_SERVICE,
name: `projects/${PROJECT_ID}/locations/${LOCATION}/services/${SERVICE_ID}`,
labels: {
[runv2.RUNTIME_LABEL]: latest("nodejs"),
},
annotations: {
...BASE_RUN_SERVICE.annotations,
[runv2.FUNCTION_ID_ANNOTATION]: FUNCTION_ID, // Using FUNCTION_ID_ANNOTATION as primary source for id
[runv2.FUNCTION_TARGET_ANNOTATION]: "customEntryPoint",
[runv2.TRIGGER_TYPE_ANNOTATION]: "HTTP_TRIGGER",
},
template: {
containers: [
Expand Down Expand Up @@ -239,6 +240,7 @@ describe("runv2", () => {
httpsTrigger: {},
labels: {
[runv2.RUNTIME_LABEL]: latest("nodejs"),
[runv2.CLIENT_NAME_LABEL]: "firebase-functions",
},
environmentVariables: {},
secretEnvironmentVariables: [],
Expand All @@ -259,6 +261,7 @@ describe("runv2", () => {
...BASE_RUN_SERVICE.annotations,
[runv2.FUNCTION_ID_ANNOTATION]: FUNCTION_ID, // Using FUNCTION_ID_ANNOTATION as primary source for id
[runv2.FUNCTION_TARGET_ANNOTATION]: "customEntryPoint",
[runv2.TRIGGER_TYPE_ANNOTATION]: "HTTP_TRIGGER",
},
template: {
containers: [
Expand Down Expand Up @@ -442,7 +445,7 @@ describe("runv2", () => {
entryPoint: SERVICE_ID, // No FUNCTION_TARGET_ANNOTATION
availableMemoryMb: 128,
cpu: 0.5,
httpsTrigger: {},
eventTrigger: { eventType: "unknown", retry: false },
labels: {},
environmentVariables: {},
secretEnvironmentVariables: [],
Expand All @@ -452,4 +455,78 @@ describe("runv2", () => {
expect(runv2.endpointFromService(service)).to.deep.equal(expectedEndpoint);
});
});

describe("listServices", () => {
let sandbox: sinon.SinonSandbox;
let getStub: sinon.SinonStub;

beforeEach(() => {
sandbox = sinon.createSandbox();
getStub = sandbox.stub(Client.prototype, "get");
});

afterEach(() => {
sandbox.restore();
});

it("should return a list of services", async () => {
const mockServices = [{ name: "service1" }, { name: "service2" }];
getStub.resolves({ status: 200, body: { services: mockServices } });

const services = await runv2.listServices(PROJECT_ID);

expect(services).to.deep.equal(mockServices);
expect(getStub).to.have.been.calledOnceWithExactly(
`/projects/${PROJECT_ID}/locations/-/services`,
{ queryParams: {} },
);
});

it("should handle pagination", async () => {
const mockServices1 = [{ name: "service1" }];
const mockServices2 = [{ name: "service2" }];
getStub
.onFirstCall()
.resolves({ status: 200, body: { services: mockServices1, nextPageToken: "nextPage" } });
getStub.onSecondCall().resolves({ status: 200, body: { services: mockServices2 } });

const services = await runv2.listServices(PROJECT_ID);

expect(services).to.deep.equal([...mockServices1, ...mockServices2]);
expect(getStub).to.have.been.calledTwice;
expect(getStub.firstCall).to.have.been.calledWithExactly(
`/projects/${PROJECT_ID}/locations/-/services`,
{ queryParams: {} },
);
expect(getStub.secondCall).to.have.been.calledWithExactly(
`/projects/${PROJECT_ID}/locations/-/services`,
{ queryParams: { pageToken: "nextPage" } },
);
});

it("should throw an error if the API call fails", async () => {
getStub.resolves({ status: 500, body: "Internal Server Error" });

try {
await runv2.listServices(PROJECT_ID);
expect.fail("Should have thrown an error");
} catch (err: any) {
expect(err).to.be.instanceOf(FirebaseError);
expect(err.message).to.contain('Failed to list services: 500 "Internal Server Error"');
}
});

it("should filter by labelSelector", async () => {
const mockServices = [{ name: "service1" }];
getStub.resolves({ status: 200, body: { services: mockServices } });

const services = await runv2.listServices(PROJECT_ID, "foo=bar");

expect(services).to.deep.equal(mockServices);
expect(getStub).to.have.been.calledOnceWithExactly(
`/projects/${PROJECT_ID}/locations/-/services`,
{ queryParams: { filter: 'labels."foo"="bar"' } },
);
});
});
});
43 changes: 40 additions & 3 deletions src/gcp/runv2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,38 @@ export async function updateService(service: Omit<Service, ServiceOutputFields>)
return svc;
}

export async function listServices(projectId: string, filter?: string): Promise<Service[]> {
const allServices: Service[] = [];
let pageToken: string | undefined = undefined;

do {
const queryParams: Record<string, string> = {};
if (pageToken) {
queryParams["pageToken"] = pageToken;
}
if (filter) {
const parts = filter.split("=");
queryParams["filter"] = `labels."${parts[0]}"="${parts[1]}"`;
}

const res = await client.get<{ services?: Service[]; nextPageToken?: string }>(
`/projects/${projectId}/locations/-/services`,
{ queryParams },
);

if (res.status !== 200) {
throw new FirebaseError(`Failed to list services: ${res.status} ${JSON.stringify(res.body)}`);
}

if (res.body.services) {
allServices.push(...res.body.services);
}
pageToken = res.body.nextPageToken;
} while (pageToken);

return allServices;
}

// TODO: Replace with real version:
function functionNameToServiceName(id: string): string {
return id.toLowerCase().replace(/_/g, "-");
Expand Down Expand Up @@ -487,9 +519,14 @@ export function endpointFromService(service: Omit<Service, ServiceOutputFields>)
service.annotations?.[FUNCTION_TARGET_ANNOTATION] ||
service.annotations?.[FUNCTION_ID_ANNOTATION] ||
id,

// TODO: trigger types.
httpsTrigger: {},
...(service.annotations?.[TRIGGER_TYPE_ANNOTATION] === "HTTP_TRIGGER"
? { httpsTrigger: {} }
: {
eventTrigger: {
eventType: service.annotations?.[TRIGGER_TYPE_ANNOTATION] || "unknown",
retry: false,
Copy link
Contributor

Choose a reason for hiding this comment

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

why is retry always false here?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

iiuc, I don't think the Cloud Run Service object stores info on retry policies so I don't think we'd be able to know the actual retry setting for a trigger? I didn't see any related fields in https://cloud.google.com/run/docs/reference/rest/v2/projects.locations.services#resource:-service

},
}),
};
proto.renameIfPresent(endpoint, service.template, "concurrency", "containerConcurrency");
proto.renameIfPresent(endpoint, service.labels || {}, "codebase", CODEBASE_LABEL);
Expand Down
Loading