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

Moving the emulator UI server to firebase-tools. #7897

Merged
merged 16 commits into from
Nov 13, 2024
Merged
Show file tree
Hide file tree
Changes from 11 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
1 change: 0 additions & 1 deletion src/emulator/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,20 +70,20 @@

/**
* Exports emulator data on clean exit (SIGINT or process end)
* @param options

Check warning on line 73 in src/emulator/controller.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Missing JSDoc @param "options" description
*/
export async function exportOnExit(options: any) {

Check warning on line 75 in src/emulator/controller.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Missing return type on function

Check warning on line 75 in src/emulator/controller.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unexpected any. Specify a different type
const exportOnExitDir = options.exportOnExit;

Check warning on line 76 in src/emulator/controller.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe assignment of an `any` value

Check warning on line 76 in src/emulator/controller.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe member access .exportOnExit on an `any` value
if (exportOnExitDir) {
try {
utils.logBullet(
`Automatically exporting data using ${FLAG_EXPORT_ON_EXIT_NAME} "${exportOnExitDir}" ` +

Check warning on line 80 in src/emulator/controller.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Invalid type "any" of template literal expression
"please wait for the export to finish...",
);
await exportEmulatorData(exportOnExitDir, options, /* initiatedBy= */ "exit");

Check warning on line 83 in src/emulator/controller.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe argument of type `any` assigned to a parameter of type `string`
} catch (e: any) {

Check warning on line 84 in src/emulator/controller.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unexpected any. Specify a different type
utils.logWarning(e);

Check warning on line 85 in src/emulator/controller.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe argument of type `any` assigned to a parameter of type `string`
utils.logWarning(`Automatic export to "${exportOnExitDir}" failed, going to exit now...`);

Check warning on line 86 in src/emulator/controller.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Invalid type "any" of template literal expression
}
}
}
Expand Down Expand Up @@ -964,7 +964,6 @@
if (listenForEmulator.ui) {
const ui = new EmulatorUI({
projectId: projectId,
auto_download: true,
listen: listenForEmulator[Emulators.UI],
});
await startEmulator(ui);
Expand Down
4 changes: 2 additions & 2 deletions src/emulator/downloadableEmulators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -281,8 +281,8 @@ const Commands: { [s in DownloadableEmulators]: DownloadableEmulatorCommand } =
shell: true,
},
ui: {
binary: "node",
args: [getExecPath(Emulators.UI)],
binary: "",
args: [],
optionalArgs: [],
joinArgs: false,
shell: false,
Expand Down
1 change: 1 addition & 0 deletions src/emulator/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export type DownloadableEmulators =
| Emulators.UI
| Emulators.STORAGE
| Emulators.DATACONNECT;

export const DOWNLOADABLE_EMULATORS = [
Emulators.FIRESTORE,
Emulators.DATABASE,
Expand Down
107 changes: 76 additions & 31 deletions src/emulator/ui.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { EmulatorInstance, EmulatorInfo, Emulators, ListenSpec } from "./types";
import * as express from "express";
import * as path from "path";
import fetch from "node-fetch";
import { Emulators, ListenSpec } from "./types";
import * as downloadableEmulators from "./downloadableEmulators";
import { EmulatorRegistry } from "./registry";
import { FirebaseError } from "../error";
import { EmulatorLogger } from "./emulatorLogger";
import { Constants } from "./constants";
import { emulatorSession } from "../track";
import { ExpressBasedEmulator } from "./ExpressBasedEmulator";
Expand All @@ -10,58 +14,99 @@ import { ALL_EXPERIMENTS, ExperimentName, isEnabled } from "../experiments";
export interface EmulatorUIOptions {
listen: ListenSpec[];
projectId: string;
auto_download?: boolean;
}

export class EmulatorUI implements EmulatorInstance {
constructor(private args: EmulatorUIOptions) {}
export class EmulatorUI extends ExpressBasedEmulator {
constructor(private args: EmulatorUIOptions) {
super({
listen: args.listen,
});
}

override async start(): Promise<void> {
await super.start();
christhompsongoogle marked this conversation as resolved.
Show resolved Hide resolved
}

start(): Promise<void> {
protected override async createExpressApp(): Promise<express.Express> {
if (!EmulatorRegistry.isRunning(Emulators.HUB)) {
throw new FirebaseError(
`Cannot start ${Constants.description(Emulators.UI)} without ${Constants.description(
Emulators.HUB,
)}!`,
);
}
const { auto_download: autoDownload, projectId } = this.args;
const env: Partial<NodeJS.ProcessEnv> = {
LISTEN: JSON.stringify(ExpressBasedEmulator.listenOptionsFromSpecs(this.args.listen)),
GCLOUD_PROJECT: projectId,
[Constants.FIREBASE_EMULATOR_HUB]: EmulatorRegistry.url(Emulators.HUB).host,
};
const app = await super.createExpressApp();
const { projectId } = this.args;
const enabledExperiments: Array<ExperimentName> = (
Object.keys(ALL_EXPERIMENTS) as Array<ExperimentName>
).filter((experimentName) => isEnabled(experimentName));
const emulatorGaSession = emulatorSession();

const session = emulatorSession();
if (session) {
env[Constants.FIREBASE_GA_SESSION] = JSON.stringify(session);
}
await downloadableEmulators.downloadIfNecessary(Emulators.UI);
const downloadDetails = downloadableEmulators.getDownloadDetails(Emulators.UI);
const webDir = path.join(downloadDetails.unzipDir!!, "client");

christhompsongoogle marked this conversation as resolved.
Show resolved Hide resolved
// Exposes the host and port of various emulators to facilitate accessing
// them using client SDKs. For features that involve multiple emulators or
// hard to accomplish using client SDKs, consider adding an API below.
app.get(
"/api/config",
this.jsonHandler(async () => {
const hubDiscoveryUrl = new URL(
`http://${EmulatorRegistry.url(Emulators.HUB).host}/emulators`,
);
const emulatorsRes = await fetch(hubDiscoveryUrl.toString());
const emulators = (await emulatorsRes.json()) as any;
Fixed Show fixed Hide fixed
christhompsongoogle marked this conversation as resolved.
Show resolved Hide resolved

yuchenshi marked this conversation as resolved.
Show resolved Hide resolved
const json = { projectId, experiments: [], ...emulators };

// Googlers: see go/firebase-emulator-ui-usage-collection-design?pli=1#heading=h.jwz7lj6r67z8
// for more detail
if (emulatorGaSession) {
json.analytics = emulatorGaSession;
}

// pick up any experiments enabled with `firebase experiment:enable`
if (enabledExperiments) {
json.experiments = enabledExperiments;
}

const enabledExperiments = (Object.keys(ALL_EXPERIMENTS) as Array<ExperimentName>).filter(
(experimentName) => isEnabled(experimentName),
return json;
}),
);
env[Constants.FIREBASE_ENABLED_EXPERIMENTS] = JSON.stringify(enabledExperiments);

return downloadableEmulators.start(Emulators.UI, { auto_download: autoDownload }, env);
app.use(express.static(webDir));
// Required for the router to work properly.
app.get("*", (_, res) => {
res.sendFile(path.join(webDir, "index.html"));
});

Dismissed Show dismissed Hide dismissed
return app;
}

connect(): Promise<void> {
return Promise.resolve();
}

stop(): Promise<void> {
return downloadableEmulators.stop(Emulators.UI);
getName(): Emulators {
return Emulators.UI;
}

getInfo(): EmulatorInfo {
return {
name: this.getName(),
host: this.args.listen[0].address,
port: this.args.listen[0].port,
pid: downloadableEmulators.getPID(Emulators.UI),
jsonHandler(handler: (req: express.Request) => Promise<object>): express.Handler {
return (req, res) => {
handler(req).then(
(body) => {
res.status(200).json(body);
},
(err) => {
EmulatorLogger.forEmulator(Emulators.UI).log("ERROR", err);
res.status(500).json({
message: err.message,
stack: err.stack,
raw: err,
});
},
);
};
}

getName(): Emulators {
return Emulators.UI;
}
}
Loading