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 2 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
2 changes: 1 addition & 1 deletion src/emulator/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,20 +69,20 @@

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

Check warning on line 72 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 74 in src/emulator/controller.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Missing return type on function

Check warning on line 74 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 75 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 75 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 79 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 82 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 83 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 84 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 85 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 @@ -305,7 +305,7 @@
}

const hubLogger = EmulatorLogger.forEmulator(Emulators.HUB);
hubLogger.logLabeled("BULLET", "emulators", `Starting emulators: ${targets.join(", ")}`);
hubLogger.logLabeled("BULLET", "emulators", `LINKED: Starting emulators: ${targets.join(", ")}`);

const projectId: string = getProjectId(options) || ""; // TODO: Next breaking change, consider making this fall back to demo project.
const isDemoProject = Constants.isDemoProject(projectId);
Expand Down
4 changes: 2 additions & 2 deletions src/emulator/downloadableEmulators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@
joinArgs: true,
shell: true,
},
ui: {
ui: { // FIXME

Check failure on line 283 in src/emulator/downloadableEmulators.ts

View workflow job for this annotation

GitHub Actions / unit (18)

Insert `⏎···`

Check failure on line 283 in src/emulator/downloadableEmulators.ts

View workflow job for this annotation

GitHub Actions / unit (20)

Insert `⏎···`

Check failure on line 283 in src/emulator/downloadableEmulators.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Insert `⏎···`

Check failure on line 283 in src/emulator/downloadableEmulators.ts

View workflow job for this annotation

GitHub Actions / unit (18)

Insert `⏎···`
binary: "node",
args: [getExecPath(Emulators.UI)],
optionalArgs: [],
Expand Down Expand Up @@ -527,7 +527,7 @@
*/
export function getDownloadDetails(emulator: DownloadableEmulators): EmulatorDownloadDetails {
const details = DownloadDetails[emulator];
const pathOverride = process.env[`${emulator.toUpperCase()}_EMULATOR_BINARY_PATH`];
const pathOverride = process.env[`${emulator.toUpperCase()}_EMULATOR_BINARY_PATH`]; // FIXME care about this for UI?
if (pathOverride) {
const logger = EmulatorLogger.forEmulator(emulator);
logger.logLabeled(
Expand Down
42 changes: 25 additions & 17 deletions src/emulator/ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@
import * as downloadableEmulators from "./downloadableEmulators";
import { EmulatorRegistry } from "./registry";
import { FirebaseError } from "../error";
import { EmulatorLogger } from "./emulatorLogger";

Check failure on line 5 in src/emulator/ui.ts

View workflow job for this annotation

GitHub Actions / unit (18)

'EmulatorLogger' is defined but never used

Check failure on line 5 in src/emulator/ui.ts

View workflow job for this annotation

GitHub Actions / unit (20)

'EmulatorLogger' is defined but never used

Check failure on line 5 in src/emulator/ui.ts

View workflow job for this annotation

GitHub Actions / lint (20)

'EmulatorLogger' is defined but never used

Check failure on line 5 in src/emulator/ui.ts

View workflow job for this annotation

GitHub Actions / unit (18)

'EmulatorLogger' is defined but never used
import { Constants } from "./constants";
import { emulatorSession } from "../track";
import { ExpressBasedEmulator } from "./ExpressBasedEmulator";
import { createApp } from "./ui/server";
import { ALL_EXPERIMENTS, ExperimentName, isEnabled } from "../experiments";
import { createDestroyer } from "../utils";

export interface EmulatorUIOptions {
listen: ListenSpec[];
Expand All @@ -14,42 +17,47 @@
}

export class EmulatorUI implements EmulatorInstance {
constructor(private args: EmulatorUIOptions) {}

Check failure on line 20 in src/emulator/ui.ts

View workflow job for this annotation

GitHub Actions / unit (18)

Delete `⏎`

Check failure on line 20 in src/emulator/ui.ts

View workflow job for this annotation

GitHub Actions / unit (20)

Delete `⏎`

Check failure on line 20 in src/emulator/ui.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Delete `⏎`

Check failure on line 20 in src/emulator/ui.ts

View workflow job for this annotation

GitHub Actions / unit (18)

Delete `⏎`
start(): Promise<void> {
private destroyServer?: () => Promise<void>;
constructor(private args: EmulatorUIOptions) { }

Check failure on line 22 in src/emulator/ui.ts

View workflow job for this annotation

GitHub Actions / unit (18)

Delete `·`

Check failure on line 22 in src/emulator/ui.ts

View workflow job for this annotation

GitHub Actions / unit (20)

Delete `·`

Check failure on line 22 in src/emulator/ui.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Delete `·`

Check failure on line 22 in src/emulator/ui.ts

View workflow job for this annotation

GitHub Actions / unit (18)

Delete `·`

async start(): Promise<void> {
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 session = emulatorSession();
if (session) {
env[Constants.FIREBASE_GA_SESSION] = JSON.stringify(session);
}
const { projectId } = this.args;

const enabledExperiments = (Object.keys(ALL_EXPERIMENTS) as Array<ExperimentName>).filter(
// FIXME Question: do we need GCLOUD_PROJECT: projectId, for anything?
const enabledExperiments: Array<ExperimentName> = (Object.keys(ALL_EXPERIMENTS) as Array<ExperimentName>).filter(

Check failure on line 35 in src/emulator/ui.ts

View workflow job for this annotation

GitHub Actions / unit (18)

Replace `Object.keys(ALL_EXPERIMENTS)·as·Array<ExperimentName>).filter(⏎······(experimentName)·=>·isEnabled(experimentName),⏎····` with `⏎······Object.keys(ALL_EXPERIMENTS)·as·Array<ExperimentName>⏎····).filter((experimentName)·=>·isEnabled(experimentName)`

Check failure on line 35 in src/emulator/ui.ts

View workflow job for this annotation

GitHub Actions / unit (20)

Replace `Object.keys(ALL_EXPERIMENTS)·as·Array<ExperimentName>).filter(⏎······(experimentName)·=>·isEnabled(experimentName),⏎····` with `⏎······Object.keys(ALL_EXPERIMENTS)·as·Array<ExperimentName>⏎····).filter((experimentName)·=>·isEnabled(experimentName)`

Check failure on line 35 in src/emulator/ui.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Replace `Object.keys(ALL_EXPERIMENTS)·as·Array<ExperimentName>).filter(⏎······(experimentName)·=>·isEnabled(experimentName),⏎····` with `⏎······Object.keys(ALL_EXPERIMENTS)·as·Array<ExperimentName>⏎····).filter((experimentName)·=>·isEnabled(experimentName)`

Check failure on line 35 in src/emulator/ui.ts

View workflow job for this annotation

GitHub Actions / unit (18)

Replace `Object.keys(ALL_EXPERIMENTS)·as·Array<ExperimentName>).filter(⏎······(experimentName)·=>·isEnabled(experimentName),⏎····` with `⏎······Object.keys(ALL_EXPERIMENTS)·as·Array<ExperimentName>⏎····).filter((experimentName)·=>·isEnabled(experimentName)`
(experimentName) => isEnabled(experimentName),
);
env[Constants.FIREBASE_ENABLED_EXPERIMENTS] = JSON.stringify(enabledExperiments);
const downloadDetails = downloadableEmulators.DownloadDetails[Emulators.UI]; // FIXME Question: use getDownloadDetails to re-use path override? idk
await downloadableEmulators.downloadIfNecessary(Emulators.UI);

const server = await createApp(
downloadDetails.unzipDir!!,
projectId,
EmulatorRegistry.url(Emulators.HUB).host,
emulatorSession(),
ExpressBasedEmulator.listenOptionsFromSpecs(this.args.listen),
enabledExperiments);

Check failure on line 47 in src/emulator/ui.ts

View workflow job for this annotation

GitHub Actions / unit (18)

Replace `);` with `,`

Check failure on line 47 in src/emulator/ui.ts

View workflow job for this annotation

GitHub Actions / unit (20)

Replace `);` with `,`

Check failure on line 47 in src/emulator/ui.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Replace `);` with `,`

Check failure on line 47 in src/emulator/ui.ts

View workflow job for this annotation

GitHub Actions / unit (18)

Replace `);` with `,`
this.destroyServer = createDestroyer(server);

Check failure on line 48 in src/emulator/ui.ts

View workflow job for this annotation

GitHub Actions / unit (18)

Replace `······this.destroyServer·=·createDestroyer(server);⏎` with `····);⏎····this.destroyServer·=·createDestroyer(server);`

Check failure on line 48 in src/emulator/ui.ts

View workflow job for this annotation

GitHub Actions / unit (20)

Replace `······this.destroyServer·=·createDestroyer(server);⏎` with `····);⏎····this.destroyServer·=·createDestroyer(server);`

Check failure on line 48 in src/emulator/ui.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Replace `······this.destroyServer·=·createDestroyer(server);⏎` with `····);⏎····this.destroyServer·=·createDestroyer(server);`

Check failure on line 48 in src/emulator/ui.ts

View workflow job for this annotation

GitHub Actions / unit (18)

Replace `······this.destroyServer·=·createDestroyer(server);⏎` with `····);⏎····this.destroyServer·=·createDestroyer(server);`

return downloadableEmulators.start(Emulators.UI, { auto_download: autoDownload }, env);
}

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

stop(): Promise<void> {
return downloadableEmulators.stop(Emulators.UI);
if (this.destroyServer) {
return this.destroyServer();
}
return Promise.resolve();
}

getInfo(): EmulatorInfo {
Expand Down
124 changes: 124 additions & 0 deletions src/emulator/ui/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
/**
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { createServer } from 'http';

Check failure on line 17 in src/emulator/ui/server.ts

View workflow job for this annotation

GitHub Actions / unit (18)

Replace `'http'` with `"http"`

Check failure on line 17 in src/emulator/ui/server.ts

View workflow job for this annotation

GitHub Actions / unit (20)

Replace `'http'` with `"http"`

Check failure on line 17 in src/emulator/ui/server.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Replace `'http'` with `"http"`

Check failure on line 17 in src/emulator/ui/server.ts

View workflow job for this annotation

GitHub Actions / unit (18)

Replace `'http'` with `"http"`
import type { ListenOptions } from 'net';

Check failure on line 18 in src/emulator/ui/server.ts

View workflow job for this annotation

GitHub Actions / unit (18)

Replace `'net'` with `"net"`

Check failure on line 18 in src/emulator/ui/server.ts

View workflow job for this annotation

GitHub Actions / unit (20)

Replace `'net'` with `"net"`

Check failure on line 18 in src/emulator/ui/server.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Replace `'net'` with `"net"`

Check failure on line 18 in src/emulator/ui/server.ts

View workflow job for this annotation

GitHub Actions / unit (18)

Replace `'net'` with `"net"`
import * as path from 'path';

Check failure on line 19 in src/emulator/ui/server.ts

View workflow job for this annotation

GitHub Actions / unit (18)

Replace `'path'` with `"path"`

Check failure on line 19 in src/emulator/ui/server.ts

View workflow job for this annotation

GitHub Actions / unit (20)

Replace `'path'` with `"path"`

Check failure on line 19 in src/emulator/ui/server.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Replace `'path'` with `"path"`

Check failure on line 19 in src/emulator/ui/server.ts

View workflow job for this annotation

GitHub Actions / unit (18)

Replace `'path'` with `"path"`

import * as express from "express";
import fetch from 'node-fetch';
import { AnalyticsSession } from "../../track";
import { ExperimentName } from "../../experiments";
import * as http from "http";

/*
This file defines Node.js server-side logic for the Emulator UI.

During development, the express app is loaded into the Vite dev server
(configured via ./vite.config.ts) and exposes the /api/* endpoints below.

For production, this file serves as an entry point and runs additional logic
(see `import.meta.env.PROD` below) to start the server on a port which serves
static assets in addition to APIs.

This file may NOT import any front-end code or types from src/.
*/
// FIXME note that this is a facsimile class, and some items are passed in rather than fetched on purpose to keep logic similar to the local instance.
export async function createApp(
zipDirPath: string,
projectId: string,
hubHost: string,
emulatorGaSession: AnalyticsSession | undefined,
listenOptions: ListenOptions[],
experiments: Array<ExperimentName>): Promise<http.Server> {

const app = express();
// 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',
jsonHandler(async () => {
const hubDiscoveryUrl = new URL(`http://${hubHost}/emulators`);
const emulatorsRes = await fetch(hubDiscoveryUrl.toString());
Fixed Show fixed Hide fixed
const emulators = (await emulatorsRes.json()) as any;

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 (experiments) {
json.experiments = experiments;
}

return json;
})
);

const webDir = path.join(zipDirPath, 'client');
app.use(express.static(webDir));
// Required for the router to work properly.
app.get('*', function (_, res) {
res.sendFile(path.join(webDir, 'index.html'));
});
Fixed Show fixed Hide fixed

if(listenOptions.length == 0) {
console.error(`Failed to start UI server, listenOptions empty`);
process.exit(1);
christhompsongoogle marked this conversation as resolved.
Show resolved Hide resolved
}
var server = null;
for (const opts of listenOptions) {
server = createServer(app).listen(opts);
christhompsongoogle marked this conversation as resolved.
Show resolved Hide resolved
server.once('listening', () => {
console.log(`Web / API server started at ${opts.host}:${opts.port}`);
christhompsongoogle marked this conversation as resolved.
Show resolved Hide resolved
});
server.once('error', (err) => {
console.error(`Failed to start server at ${opts.host}:${opts.port}`);
console.error(err);
if (opts === listenOptions[0]) {
// If we failed to listen on the primary address, surface the error.
process.exit(1);
}
});
}

return server!!
}

function jsonHandler(
handler: (req: express.Request) => Promise<object>
): express.Handler {
return (req, res) => {
handler(req).then(
(body) => {
res.status(200).json(body);
},
(err) => {
console.error(err);
res.status(500).json({
message: err.message,
stack: err.stack,
raw: err,
});
}
);
};
}
Loading