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 4 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
6 changes: 3 additions & 3 deletions src/emulator/downloadableEmulators.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const lsofi = require("lsofi");

Check warning on line 1 in src/emulator/downloadableEmulators.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe assignment of an `any` value

Check warning on line 1 in src/emulator/downloadableEmulators.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Require statement not part of import statement
import {
Emulators,
DownloadableEmulators,
Expand Down Expand Up @@ -274,15 +274,15 @@
shell: false,
},
pubsub: {
binary: `${getExecPath(Emulators.PUBSUB)!}`,

Check warning on line 277 in src/emulator/downloadableEmulators.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Forbidden non-null assertion
args: [],
optionalArgs: ["port", "host"],
joinArgs: true,
shell: true,
},
ui: {
binary: "node",
args: [getExecPath(Emulators.UI)],
binary: "",
args: [],
optionalArgs: [],
joinArgs: false,
shell: false,
Expand Down Expand Up @@ -310,7 +310,7 @@
}

/**
* @param name

Check warning on line 313 in src/emulator/downloadableEmulators.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Missing JSDoc @param "name" description
*/
export function getLogFileName(name: string): string {
return `${name}-debug.log`;
Expand All @@ -323,7 +323,7 @@
*/
export function _getCommand(
emulator: DownloadableEmulators,
args: { [s: string]: any },

Check warning on line 326 in src/emulator/downloadableEmulators.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unexpected any. Specify a different type
): DownloadableEmulatorCommand {
const baseCmd = Commands[emulator];
const defaultPort = Constants.getDefaultPort(emulator);
Expand All @@ -336,7 +336,7 @@
if (
baseCmd.binary === "java" &&
utils.isRunningInWSL() &&
(!args.host || !args.host.includes(":"))

Check warning on line 339 in src/emulator/downloadableEmulators.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe member access .includes on an `any` value

Check warning on line 339 in src/emulator/downloadableEmulators.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe call of an `any` typed value
) {
// HACK(https://github.com/firebase/firebase-tools-ui/issues/332): Force
// Java to use IPv4 sockets in WSL (unless IPv6 address explicitly used).
Expand All @@ -355,7 +355,7 @@
}

const argKey = "--" + key;
const argVal = args[key];

Check warning on line 358 in src/emulator/downloadableEmulators.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe assignment of an `any` value

if (argVal === undefined) {
logger.log("DEBUG", `Ignoring empty arg for key: ${key}`);
Expand All @@ -364,9 +364,9 @@

// Sigh ... RTDB emulator needs "--arg val" and PubSub emulator needs "--arg=val"
if (baseCmd.joinArgs) {
cmdLineArgs.push(`${argKey}=${argVal}`);

Check warning on line 367 in src/emulator/downloadableEmulators.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Invalid type "any" of template literal expression
} else {
cmdLineArgs.push(argKey, argVal);

Check warning on line 369 in src/emulator/downloadableEmulators.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe argument of type `any` assigned to a parameter of type `string`
}
});

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
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
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 / 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

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 / lint (20)

Delete `⏎`

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 (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 / lint (20)

Delete `·`

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 (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 / 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)`

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 / 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 `,`

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 / 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);`

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
118 changes: 118 additions & 0 deletions src/emulator/ui/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/**
* Copyright 2024 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 / 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"`

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 / 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"`

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 / 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"`

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';

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

View workflow job for this annotation

GitHub Actions / lint (20)

Replace `'node-fetch'` with `"node-fetch"`

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

View workflow job for this annotation

GitHub Actions / unit (18)

Replace `'node-fetch'` with `"node-fetch"`

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

View workflow job for this annotation

GitHub Actions / unit (18)

Replace `'node-fetch'` with `"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.

It is a facsimile class of the local server in firebase-tools-ui/server.ts. For that reason,
values that were previously environment variables are passed in rather than fetched/derived
in the class itself.
*/
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