-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathcontroller.ts
More file actions
executable file
·1171 lines (1059 loc) · 40.8 KB
/
controller.ts
File metadata and controls
executable file
·1171 lines (1059 loc) · 40.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as clc from "colorette";
import * as fs from "fs";
import * as path from "path";
import * as fsConfig from "../firestore/fsConfig";
import * as proto from "../gcp/proto";
import { logger } from "../logger";
import { trackEmulator, trackGA4 } from "../track";
import * as utils from "../utils";
import { EmulatorRegistry } from "./registry";
import {
ALL_EMULATORS,
ALL_SERVICE_EMULATORS,
EmulatorInfo,
EmulatorInstance,
Emulators,
EMULATORS_SUPPORTED_BY_UI,
isEmulator,
} from "./types";
import { Constants, FIND_AVAILBLE_PORT_BY_DEFAULT } from "./constants";
import { EmulatableBackend, FunctionsEmulator } from "./functionsEmulator";
import { FirebaseError } from "../error";
import { getProjectId, getAliases, needProjectNumber } from "../projectUtils";
import * as commandUtils from "./commandUtils";
import { EmulatorHub } from "./hub";
import { ExportMetadata, HubExport } from "./hubExport";
import { EmulatorUI } from "./ui";
import { LoggingEmulator } from "./loggingEmulator";
import * as dbRulesConfig from "../database/rulesConfig";
import { EmulatorLogger, Verbosity } from "./emulatorLogger";
import { EmulatorHubClient } from "./hubClient";
import { confirm } from "../prompt";
import {
FLAG_EXPORT_ON_EXIT_NAME,
JAVA_DEPRECATION_WARNING,
MIN_SUPPORTED_JAVA_MAJOR_VERSION,
} from "./commandUtils";
import { fileExistsSync } from "../fsutils";
import { getStorageRulesConfig } from "./storage/rules/config";
import { getDefaultDatabaseInstance } from "../getDefaultDatabaseInstance";
import { getProjectDefaultAccount } from "../auth";
import { Options } from "../options";
import { ParsedTriggerDefinition } from "./functionsEmulatorShared";
import { ExtensionsEmulator } from "./extensionsEmulator";
import { normalizeAndValidate, requireLocal } from "../functions/projectConfig";
import { requiresJava } from "./downloadableEmulators";
import { prepareFrameworks } from "../frameworks";
import * as experiments from "../experiments";
import { EmulatorListenConfig, PortName, resolveHostAndAssignPorts } from "./portUtils";
import { Runtime, isRuntime } from "../deploy/functions/runtimes/supported";
import { AuthEmulator, SingleProjectMode } from "./auth";
import { DatabaseEmulator, DatabaseEmulatorArgs } from "./databaseEmulator";
import { EventarcEmulator } from "./eventarcEmulator";
import { DataConnectEmulator, DataConnectEmulatorArgs } from "./dataconnectEmulator";
import { FirestoreEmulator, FirestoreEmulatorArgs } from "./firestoreEmulator";
import { HostingEmulator } from "./hostingEmulator";
import { PubsubEmulator } from "./pubsubEmulator";
import { StorageEmulator } from "./storage";
import { readFirebaseJson } from "../dataconnect/load";
import { TasksEmulator } from "./tasksEmulator";
import { AppHostingEmulator } from "./apphosting";
import { sendVSCodeMessage, VSCODE_MESSAGE } from "../dataconnect/webhook";
import { dataConnectLocalConnString } from "../api";
import { AppHostingSingle } from "../firebaseConfig";
import { resolveProjectPath } from "../projectPath";
const START_LOGGING_EMULATOR = utils.envOverride(
"START_LOGGING_EMULATOR",
"false",
(val) => val === "true",
);
/**
* Exports emulator data on clean exit (SIGINT or process end)
* @param options
*/
export async function exportOnExit(options: Options): Promise<void> {
// Note: options.exportOnExit is coerced to a string before this point in commandUtils.ts#setExportOnExitOptions
const exportOnExitDir = options.exportOnExit as string;
if (exportOnExitDir) {
try {
utils.logBullet(
`Automatically exporting data using ${FLAG_EXPORT_ON_EXIT_NAME} "${exportOnExitDir}" ` +
"please wait for the export to finish...",
);
await exportEmulatorData(exportOnExitDir, options, /* initiatedBy= */ "exit");
} catch (e: unknown) {
utils.logWarning(`${e}`);
utils.logWarning(`Automatic export to "${exportOnExitDir}" failed, going to exit now...`);
}
}
}
/**
* Hook to do things when we're exiting cleanly (this does not include errors). Will be skipped on a second SIGINT
* @param options
*/
export async function onExit(options: any) {
await exportOnExit(options);
}
/**
* Hook to clean up on shutdown (includes errors). Will be skipped on a third SIGINT
* Stops all running emulators in parallel.
*/
export async function cleanShutdown(): Promise<void> {
EmulatorLogger.forEmulator(Emulators.HUB).logLabeled(
"BULLET",
"emulators",
"Shutting down emulators.",
);
await EmulatorRegistry.stopAll();
await sendVSCodeMessage({ message: VSCODE_MESSAGE.EMULATORS_SHUTDOWN });
}
/**
* Filters a list of emulators to only those specified in the config
* @param options
*/
export function filterEmulatorTargets(options: { only: string; config: any }): Emulators[] {
let targets = [...ALL_SERVICE_EMULATORS];
targets.push(Emulators.EXTENSIONS);
targets = targets.filter((e) => {
return options.config.has(e) || options.config.has(`emulators.${e}`);
});
// Extensions may not be initialized but we can have SDK defined extensions
if (targets.includes(Emulators.FUNCTIONS) && !targets.includes(Emulators.EXTENSIONS)) {
targets.push(Emulators.EXTENSIONS);
}
const onlyOptions: string = options.only;
if (onlyOptions) {
const only = onlyOptions.split(",").map((o) => {
return o.split(":")[0];
});
targets = targets.filter((t) => only.includes(t));
}
return targets;
}
/**
* Returns whether or not a specific emulator should start based on configuration and dependencies.
* @param options
* @param name
*/
export function shouldStart(options: Options, name: Emulators): boolean {
if (name === Emulators.HUB) {
// The emulator hub always starts.
return true;
}
const targets = filterEmulatorTargets(options);
const emulatorInTargets = targets.includes(name);
if (name === Emulators.UI) {
if (options.ui) {
return true;
}
if (options.config.src.emulators?.ui?.enabled === false) {
// Allow disabling UI via `{emulators: {"ui": {"enabled": false}}}`.
// Emulator UI is by default enabled if that option is not specified.
return false;
}
// Emulator UI only starts if we know the project ID AND at least one
// emulator supported by Emulator UI is launching.
return targets.some((target) => EMULATORS_SUPPORTED_BY_UI.includes(target));
}
// Don't start the functions emulator if we can't validate the functions config
if (name === Emulators.FUNCTIONS && emulatorInTargets) {
try {
normalizeAndValidate(options.config.src.functions);
return true;
} catch (err: unknown) {
const message = err instanceof Error ? err.message : String(err);
EmulatorLogger.forEmulator(Emulators.FUNCTIONS).logLabeled(
"ERROR",
"functions",
`Failed to start Functions emulator: ${message}`,
);
return false;
}
}
if (name === Emulators.HOSTING && emulatorInTargets && !options.config.get("hosting")) {
EmulatorLogger.forEmulator(Emulators.HOSTING).logLabeled(
"WARN",
"hosting",
`The hosting emulator is configured but there is no hosting configuration. Have you run ${clc.bold(
"firebase init hosting",
)}?`,
);
return false;
}
return emulatorInTargets;
}
function findExportMetadata(importPath: string): ExportMetadata | undefined {
const pathExists = fs.existsSync(importPath);
if (!pathExists) {
throw new FirebaseError(`Directory "${importPath}" does not exist.`);
}
const pathIsDirectory = fs.lstatSync(importPath).isDirectory();
if (!pathIsDirectory) {
return;
}
// If there is an export metadata file, we always prefer that
const importFilePath = path.join(importPath, HubExport.METADATA_FILE_NAME);
if (fileExistsSync(importFilePath)) {
return JSON.parse(fs.readFileSync(importFilePath, "utf8").toString()) as ExportMetadata;
}
const fileList = fs.readdirSync(importPath);
// The user might have passed a Firestore export directly
const firestoreMetadataFile = fileList.find((f) => f.endsWith(".overall_export_metadata"));
if (firestoreMetadataFile) {
const metadata: ExportMetadata = {
version: EmulatorHub.CLI_VERSION,
firestore: {
version: "prod",
path: importPath,
metadata_file: `${importPath}/${firestoreMetadataFile}`,
},
};
EmulatorLogger.forEmulator(Emulators.FIRESTORE).logLabeled(
"BULLET",
"firestore",
`Detected non-emulator Firestore export at ${importPath}`,
);
return metadata;
}
// The user might haved passed a directory containing RTDB json files
const rtdbDataFile = fileList.find((f) => f.endsWith(".json"));
if (rtdbDataFile) {
const metadata: ExportMetadata = {
version: EmulatorHub.CLI_VERSION,
database: {
version: "prod",
path: importPath,
},
};
EmulatorLogger.forEmulator(Emulators.DATABASE).logLabeled(
"BULLET",
"firestore",
`Detected non-emulator Database export at ${importPath}`,
);
return metadata;
}
}
interface EmulatorOptions extends Options {
extDevEnv?: Record<string, string>;
logVerbosity?: "DEBUG" | "INFO" | "QUIET" | "SILENT";
}
/**
* Start all emulators.
*/
export async function startAll(
options: EmulatorOptions,
showUI = true,
runningTestScript = false,
): Promise<{ deprecationNotices: string[] }> {
// Emulators config is specified in firebase.json as:
// "emulators": {
// "firestore": {
// "host": "localhost",
// "port": "9005"
// },
// // ...
// }
//
// The list of emulators to start is filtered two ways:
// 1) The service must have a top-level entry in firebase.json or an entry in the emulators{} object
// 2) If the --only flag is passed, then this list is the intersection
const targets = filterEmulatorTargets(options);
options.targets = targets;
const singleProjectModeEnabled =
options.config.src.emulators?.singleProjectMode === undefined ||
options.config.src.emulators?.singleProjectMode;
if (targets.length === 0) {
throw new FirebaseError(
`No emulators to start, run ${clc.bold("firebase init emulators")} to get started.`,
);
}
const deprecationNotices: string[] = [];
if (targets.some(requiresJava)) {
if ((await commandUtils.checkJavaMajorVersion()) < MIN_SUPPORTED_JAVA_MAJOR_VERSION) {
throw new FirebaseError(JAVA_DEPRECATION_WARNING);
}
}
if (options.logVerbosity) {
EmulatorLogger.setVerbosity(Verbosity[options.logVerbosity]);
}
const hubLogger = EmulatorLogger.forEmulator(Emulators.HUB);
hubLogger.logLabeled("BULLET", "emulators", `Starting emulators: ${targets.join(", ")}`);
const projectId = getProjectId(options) || EmulatorHub.MISSING_PROJECT_PLACEHOLDER;
const isDemoProject = Constants.isDemoProject(projectId);
if (isDemoProject) {
hubLogger.logLabeled(
"BULLET",
"emulators",
`Detected demo project ID "${projectId}", emulated services will use a demo configuration and attempts to access non-emulated services for this project will fail.`,
);
}
const onlyOptions: string = options.only;
if (onlyOptions) {
const requested: string[] = onlyOptions.split(",").map((o) => {
return o.split(":")[0];
});
const ignored = requested.filter((k) => !targets.includes(k as Emulators));
for (const name of ignored) {
if (isEmulator(name)) {
EmulatorLogger.forEmulator(name).logLabeled(
"WARN",
name,
`Not starting the ${clc.bold(name)} emulator, make sure you have run ${clc.bold(
"firebase init",
)}.`,
);
} else {
// this should not work:
// firebase emulators:start --only doesnotexist
throw new FirebaseError(
`${name} is not a valid emulator name, valid options are: ${JSON.stringify(
ALL_SERVICE_EMULATORS,
)}`,
{ exit: 1 },
);
}
}
}
const emulatableBackends: EmulatableBackend[] = [];
// Process extensions config early so that we have a better guess at whether
// the Functions emulator needs to start.
let extensionEmulator: ExtensionsEmulator | undefined = undefined;
if (shouldStart(options, Emulators.EXTENSIONS)) {
let projectNumber = Constants.FAKE_PROJECT_NUMBER;
if (!isDemoProject) {
try {
projectNumber = await needProjectNumber(options);
} catch (err: unknown) {
EmulatorLogger.forEmulator(Emulators.EXTENSIONS).logLabeled(
"ERROR",
Emulators.EXTENSIONS,
`Unable to look up project number for ${options.project}.\n` +
" If this is a real project, ensure that you are logged in and have access to it.\n" +
" If this is a fake project, please use a project ID starting with 'demo-' to skip production calls.\n" +
" Continuing with a fake project number - secrets and other features that require production access may behave unexpectedly.",
);
}
}
const aliases = getAliases(options, projectId);
extensionEmulator = new ExtensionsEmulator({
options,
projectId,
projectDir: options.config.projectDir,
projectNumber,
aliases,
extensions: options.config.get("extensions"),
});
const extensionsBackends = await extensionEmulator.getExtensionBackends();
const filteredExtensionsBackends =
extensionEmulator.filterUnemulatedTriggers(extensionsBackends);
emulatableBackends.push(...filteredExtensionsBackends);
trackGA4("extensions_emulated", {
number_of_extensions_emulated: filteredExtensionsBackends.length,
number_of_extensions_ignored: extensionsBackends.length - filteredExtensionsBackends.length,
});
}
const listenConfig = {} as Record<PortName, EmulatorListenConfig>;
if (emulatableBackends.length) {
// If we already know we need Functions (and Eventarc), assign them now.
listenConfig[Emulators.FUNCTIONS] = getListenConfig(options, Emulators.FUNCTIONS);
listenConfig[Emulators.EVENTARC] = getListenConfig(options, Emulators.EVENTARC);
listenConfig[Emulators.TASKS] = getListenConfig(options, Emulators.TASKS);
}
for (const emulator of ALL_EMULATORS) {
if (
emulator === Emulators.FUNCTIONS ||
emulator === Emulators.EVENTARC ||
emulator === Emulators.TASKS ||
// Same port as Functions, no need for separate assignment
emulator === Emulators.EXTENSIONS ||
(emulator === Emulators.UI && !showUI)
) {
continue;
}
if (
shouldStart(options, emulator) ||
(emulator === Emulators.LOGGING &&
((showUI && shouldStart(options, Emulators.UI)) || START_LOGGING_EMULATOR))
) {
const config = getListenConfig(options, emulator);
listenConfig[emulator] = config;
if (emulator === Emulators.FIRESTORE) {
const wsPortConfig = options.config.src.emulators?.firestore?.websocketPort;
listenConfig["firestore.websocket"] = {
host: config.host,
port: wsPortConfig || 9150,
portFixed: !!wsPortConfig,
};
}
if (emulator === Emulators.DATACONNECT && !dataConnectLocalConnString()) {
const pglitePortConfig = options.config.src.emulators?.dataconnect?.postgresPort;
listenConfig["dataconnect.postgres"] = {
host: config.host,
port: pglitePortConfig || 5432,
portFixed: !!pglitePortConfig,
};
}
}
}
let listenForEmulator = await resolveHostAndAssignPorts(listenConfig);
hubLogger.log("DEBUG", "assigned listening specs for emulators", { user: listenForEmulator });
function legacyGetFirstAddr(name: PortName): { host: string; port: number } {
const firstSpec = listenForEmulator[name][0];
return {
host: firstSpec.address,
port: firstSpec.port,
};
}
function startEmulator(instance: EmulatorInstance): Promise<void> {
const name = instance.getName();
// Log the command for analytics
void trackEmulator("emulator_run", {
emulator_name: name,
is_demo_project: String(isDemoProject),
});
return EmulatorRegistry.start(instance);
}
if (listenForEmulator.hub) {
const hub = new EmulatorHub({
projectId,
listen: listenForEmulator[Emulators.HUB],
listenForEmulator,
});
// Log the command for analytics, we only report this for "hub"
// since we originally mistakenly reported emulators:start events
// for each emulator, by reporting the "hub" we ensure that our
// historical data can still be viewed.
await startEmulator(hub);
}
// Parse export metadata
let exportMetadata: ExportMetadata = {
version: "unknown",
};
if (options.import) {
utils.assertIsString(options.import);
const importDir = path.resolve(options.import);
const foundMetadata = findExportMetadata(importDir);
if (foundMetadata) {
exportMetadata = foundMetadata;
void trackEmulator("emulator_import", {
initiated_by: "start",
emulator_name: Emulators.HUB,
});
} else {
hubLogger.logLabeled(
"WARN",
"emulators",
`Could not find import/export metadata file, ${clc.bold("skipping data import!")}`,
);
}
}
// TODO: turn this into hostingConfig.extract or hostingConfig.hostingConfig
// once those branches merge
const hostingConfig = options.config.get("hosting");
if (
Array.isArray(hostingConfig) ? hostingConfig.some((it) => it.source) : hostingConfig?.source
) {
experiments.assertEnabled("webframeworks", "emulate a web framework");
const emulators: EmulatorInfo[] = [];
for (const e of ALL_SERVICE_EMULATORS) {
// TODO(yuchenshi): Functions and Eventarc may be missing if they are not
// yet known to be needed and then prepareFrameworks adds extra functions.
if (listenForEmulator[e]) {
emulators.push({
name: e,
host: utils.connectableHostname(listenForEmulator[e][0].address),
port: listenForEmulator[e][0].port,
});
}
}
// This may add additional sources for Functions emulator and must be done before it.
await prepareFrameworks(
runningTestScript ? "test" : "emulate",
targets,
undefined,
options,
emulators,
);
}
const projectDir = (options.extDevDir || options.config.projectDir) as string;
if (shouldStart(options, Emulators.FUNCTIONS)) {
const functionsCfg = normalizeAndValidate(options.config.src.functions);
// Note: ext:dev:emulators:* commands hit this path, not the Emulators.EXTENSIONS path
utils.assertIsStringOrUndefined(options.extDevDir);
for (const cfg of functionsCfg) {
const localCfg = requireLocal(
cfg,
"Remote sources are not supported in the Functions emulator.",
);
const functionsDir = path.join(projectDir, localCfg.source);
const runtime = (options.extDevRuntime ?? cfg.runtime) as Runtime | undefined;
// N.B. (Issue #6965) it's OK for runtime to be undefined because the functions discovery process
// will dynamically detect it later.
// TODO: does runtime even need to be a part of EmultableBackend now that we have dynamic runtime
// detection? Might be an extensions thing.
if (runtime && !isRuntime(runtime)) {
throw new FirebaseError(
`Cannot load functions from ${functionsDir} because it has invalid runtime ${runtime as string}`,
);
}
const backend: EmulatableBackend = {
functionsDir,
runtime,
codebase: localCfg.codebase,
prefix: localCfg.prefix,
env: {
...options.extDevEnv,
},
secretEnv: [], // CF3 secrets are bound to specific functions, so we'll get them during trigger discovery.
// TODO(b/213335255): predefinedTriggers and nodeMajorVersion are here to support ext:dev:emulators:* commands.
// Ideally, we should handle that case via ExtensionEmulator.
predefinedTriggers: options.extDevTriggers as ParsedTriggerDefinition[] | undefined,
ignore: localCfg.ignore,
};
proto.convertIfPresent(backend, localCfg, "configDir", (cd) => path.join(projectDir, cd));
emulatableBackends.push(backend);
}
}
if (extensionEmulator) {
await startEmulator(extensionEmulator);
}
const account = getProjectDefaultAccount(options.projectRoot);
if (emulatableBackends.length) {
if (!listenForEmulator.functions || !listenForEmulator.eventarc || !listenForEmulator.tasks) {
// We did not know that we need Functions and Eventarc earlier but now we do.
listenForEmulator = await resolveHostAndAssignPorts({
...listenForEmulator,
functions: listenForEmulator.functions ?? getListenConfig(options, Emulators.FUNCTIONS),
eventarc: listenForEmulator.eventarc ?? getListenConfig(options, Emulators.EVENTARC),
tasks: listenForEmulator.eventarc ?? getListenConfig(options, Emulators.TASKS),
});
hubLogger.log("DEBUG", "late-assigned ports for functions and eventarc emulators", {
user: listenForEmulator,
});
}
const functionsLogger = EmulatorLogger.forEmulator(Emulators.FUNCTIONS);
const functionsAddr = legacyGetFirstAddr(Emulators.FUNCTIONS);
const inspectFunctions = commandUtils.parseInspectionPort(options);
if (inspectFunctions) {
// TODO(samstern): Add a link to documentation
functionsLogger.logLabeled(
"WARN",
"functions",
`You are running the Functions emulator in debug mode. This means that functions will execute in sequence rather than in parallel.`,
);
}
// Warn the developer that the Functions/Extensions emulator can call out to production.
const emulatorsNotRunning = ALL_SERVICE_EMULATORS.filter((e) => {
return e !== Emulators.FUNCTIONS && !listenForEmulator[e];
});
if (emulatorsNotRunning.length > 0 && !Constants.isDemoProject(projectId)) {
functionsLogger.logLabeled(
"WARN",
"functions",
`The following emulators are not running, calls to these services from the Functions emulator will affect production: ${clc.bold(
emulatorsNotRunning.join(", "),
)}`,
);
}
// TODO(b/213241033): Figure out how to watch for changes to extensions .env files & reload triggers when they change.
const functionsEmulator = new FunctionsEmulator({
projectId,
projectDir,
emulatableBackends,
account,
host: functionsAddr.host,
port: functionsAddr.port,
debugPort: inspectFunctions,
verbosity: options.logVerbosity,
projectAlias: options.projectAlias,
extensionsEmulator: extensionEmulator,
});
await startEmulator(functionsEmulator);
const eventarcAddr = legacyGetFirstAddr(Emulators.EVENTARC);
const eventarcEmulator = new EventarcEmulator({
host: eventarcAddr.host,
port: eventarcAddr.port,
});
await startEmulator(eventarcEmulator);
const tasksAddr = legacyGetFirstAddr(Emulators.TASKS);
const tasksEmulator = new TasksEmulator({
host: tasksAddr.host,
port: tasksAddr.port,
});
await startEmulator(tasksEmulator);
}
if (listenForEmulator.firestore) {
const firestoreLogger = EmulatorLogger.forEmulator(Emulators.FIRESTORE);
const firestoreAddr = legacyGetFirstAddr(Emulators.FIRESTORE);
const websocketPort = legacyGetFirstAddr("firestore.websocket").port;
const prodEdition = options.config.data.firestore?.edition;
const emulatorEdition = options.config.src.emulators?.firestore?.edition;
if (prodEdition !== emulatorEdition) {
firestoreLogger.logLabeled(
"WARN",
"firestore",
`The edition configured in your firebase.json#firestore and firebase.json#emulators.firestore do not match. The latter will be used to start up the Firestore emulator.`,
);
}
const edition = (emulatorEdition || prodEdition || "standard").toLowerCase();
if (edition !== "standard" && edition !== "enterprise") {
throw new FirebaseError(
"The Firestore emulator edition must be either 'standard' or 'enterprise'.",
{ exit: 1 },
);
}
const args: FirestoreEmulatorArgs = {
host: firestoreAddr.host,
port: firestoreAddr.port,
websocket_port: websocketPort,
"database-edition": edition,
project_id: projectId,
auto_download: true,
};
if (exportMetadata.firestore) {
utils.assertIsString(options.import);
const importDirAbsPath = path.resolve(options.import);
const exportMetadataFilePath = path.resolve(
importDirAbsPath,
exportMetadata.firestore.metadata_file,
);
firestoreLogger.logLabeled(
"BULLET",
"firestore",
`Importing data from ${exportMetadataFilePath}`,
);
args.seed_from_export = exportMetadataFilePath;
void trackEmulator("emulator_import", {
initiated_by: "start",
emulator_name: Emulators.FIRESTORE,
});
}
const config = options.config;
// emulator does not support multiple databases yet
// TODO(VicVer09): b/269787702
let rulesLocalPath;
let rulesFileFound;
const firestoreConfigs: fsConfig.ParsedFirestoreConfig[] = fsConfig.getFirestoreConfig(
projectId,
options,
);
if (!firestoreConfigs) {
firestoreLogger.logLabeled(
"WARN",
"firestore",
`Cloud Firestore config does not exist in firebase.json.`,
);
} else if (firestoreConfigs.length !== 1) {
firestoreLogger.logLabeled(
"WARN",
"firestore",
`Cloud Firestore Emulator does not support multiple databases yet.`,
);
} else if (firestoreConfigs[0].rules) {
rulesLocalPath = firestoreConfigs[0].rules;
}
if (rulesLocalPath) {
const rules: string = config.path(rulesLocalPath);
rulesFileFound = fs.existsSync(rules);
if (rulesFileFound) {
args.rules = rules;
} else {
firestoreLogger.logLabeled(
"WARN",
"firestore",
`Cloud Firestore rules file ${clc.bold(rules)} specified in firebase.json does not exist.`,
);
}
} else {
firestoreLogger.logLabeled(
"WARN",
"firestore",
"Did not find a Cloud Firestore rules file specified in a firebase.json config file.",
);
}
if (!rulesFileFound) {
firestoreLogger.logLabeled(
"WARN",
"firestore",
"The emulator will default to allowing all reads and writes. Learn more about this option: https://firebase.google.com/docs/emulator-suite/install_and_configure#security_rules_configuration.",
);
}
// undefined in the config defaults to setting single_project_mode.
if (singleProjectModeEnabled) {
args.single_project_mode = true;
args.single_project_mode_error = false;
}
const firestoreEmulator = new FirestoreEmulator(args);
await startEmulator(firestoreEmulator);
firestoreLogger.logLabeled(
"SUCCESS",
Emulators.FIRESTORE,
`Firestore Emulator was started in ${edition} edition.`,
);
firestoreLogger.logLabeled(
"SUCCESS",
Emulators.FIRESTORE,
`Firestore Emulator UI websocket is running on ${websocketPort}.`,
);
}
if (listenForEmulator.database) {
const databaseLogger = EmulatorLogger.forEmulator(Emulators.DATABASE);
const databaseAddr = legacyGetFirstAddr(Emulators.DATABASE);
const args: DatabaseEmulatorArgs = {
host: databaseAddr.host,
port: databaseAddr.port,
projectId,
auto_download: true,
// Only set the flag (at all) if singleProjectMode is enabled.
single_project_mode: singleProjectModeEnabled ? "Warning" : undefined,
};
// Try to fetch the default RTDB instance for a project, but don't hard-fail if we
// can't because the user may be using a fake project.
try {
if (!options.instance) {
options.instance = await getDefaultDatabaseInstance(projectId);
}
} catch (e: unknown) {
const message = e instanceof Error ? e.message : String(e);
databaseLogger.log("DEBUG", `Failed to retrieve default database instance: ${message}`);
}
const rc = dbRulesConfig.normalizeRulesConfig(
dbRulesConfig.getRulesConfig(projectId, options),
options,
);
logger.debug("database rules config: ", JSON.stringify(rc));
args.rules = rc;
if (rc.length === 0) {
databaseLogger.logLabeled(
"WARN",
"database",
"Did not find a Realtime Database rules file specified in a firebase.json config file. The emulator will default to allowing all reads and writes. Learn more about this option: https://firebase.google.com/docs/emulator-suite/install_and_configure#security_rules_configuration.",
);
} else {
for (const c of rc) {
const rules: string = c.rules;
if (!fs.existsSync(rules)) {
databaseLogger.logLabeled(
"WARN",
"database",
`Realtime Database rules file ${clc.bold(
rules,
)} specified in firebase.json does not exist.`,
);
}
}
}
const databaseEmulator = new DatabaseEmulator(args);
await startEmulator(databaseEmulator);
if (exportMetadata.database) {
utils.assertIsString(options.import);
const importDirAbsPath = path.resolve(options.import);
const databaseExportDir = path.resolve(importDirAbsPath, exportMetadata.database.path);
const files = fs.readdirSync(databaseExportDir).filter((f) => f.endsWith(".json"));
void trackEmulator("emulator_import", {
initiated_by: "start",
emulator_name: Emulators.DATABASE,
count: files.length,
});
for (const f of files) {
const fPath = path.join(databaseExportDir, f);
const ns = path.basename(f, ".json");
await databaseEmulator.importData(ns, fPath);
}
}
}
if (listenForEmulator.auth) {
const authAddr = legacyGetFirstAddr(Emulators.AUTH);
const authEmulator = new AuthEmulator({
host: authAddr.host,
port: authAddr.port,
projectId,
singleProjectMode: singleProjectModeEnabled
? SingleProjectMode.WARNING
: SingleProjectMode.NO_WARNING,
});
await startEmulator(authEmulator);
if (exportMetadata.auth) {
utils.assertIsString(options.import);
const importDirAbsPath = path.resolve(options.import);
const authExportDir = path.resolve(importDirAbsPath, exportMetadata.auth.path);
await authEmulator.importData(authExportDir, projectId, { initiatedBy: "start" });
}
}
if (listenForEmulator.pubsub) {
const pubsubAddr = legacyGetFirstAddr(Emulators.PUBSUB);
const pubsubEmulator = new PubsubEmulator({
host: pubsubAddr.host,
port: pubsubAddr.port,
projectId,
auto_download: true,
});
await startEmulator(pubsubEmulator);
}
if (listenForEmulator.dataconnect) {
const config = readFirebaseJson(options.config);
if (!config.length) {
throw new FirebaseError("No SQL Connect service found in firebase.json");
} else if (config.length > 1) {
logger.warn(
`TODO: Add support for multiple services in the SQL Connect emulator. Currently emulating first service ${config[0].source}`,
);
}
const args: DataConnectEmulatorArgs = {
listen: listenForEmulator.dataconnect,
projectId,
auto_download: true,
configDir: config[0].source,
config: options.config,
autoconnectToPostgres: true,
postgresListen: listenForEmulator["dataconnect.postgres"],
enable_output_generated_sdk: true, // TODO: source from arguments
enable_output_schema_extensions: true,
debug: options.debug,
account,
};
if (exportMetadata.dataconnect) {
utils.assertIsString(options.import);
const importDirAbsPath = path.resolve(options.import);
const exportMetadataFilePath = path.resolve(
importDirAbsPath,
exportMetadata.dataconnect.path,
);
const dataDirectory = options.config.get("emulators.dataconnect.dataDir");
if (exportMetadataFilePath && dataDirectory) {
EmulatorLogger.forEmulator(Emulators.DATACONNECT).logLabeled(
"WARN",
"dataconnect",
"'firebase.json#emulators.dataconnect.dataDir' is set and `--import` flag was passed. " +
"This will overwrite any data saved from previous runs.",
);
if (
!options.nonInteractive &&
!(await confirm({
message: `Do you wish to continue and overwrite data in ${dataDirectory}?`,
default: false,
}))
) {
await cleanShutdown();
throw new FirebaseError("Command aborted");
}
}
EmulatorLogger.forEmulator(Emulators.DATACONNECT).logLabeled(
"BULLET",
"dataconnect",
`Importing data from ${exportMetadataFilePath}`,
);
args.importPath = exportMetadataFilePath;
void trackEmulator("emulator_import", {
initiated_by: "start",
emulator_name: Emulators.DATACONNECT,
});
}
const dataConnectEmulator = new DataConnectEmulator(args);
await startEmulator(dataConnectEmulator);
}
if (listenForEmulator.storage) {
const storageAddr = legacyGetFirstAddr(Emulators.STORAGE);
const storageEmulator = new StorageEmulator({
host: storageAddr.host,
port: storageAddr.port,
projectId,
rules: getStorageRulesConfig(projectId, options),
});
await startEmulator(storageEmulator);
if (exportMetadata.storage) {
utils.assertIsString(options.import);
const importDirAbsPath = path.resolve(options.import);
const storageExportDir = path.resolve(importDirAbsPath, exportMetadata.storage.path);
storageEmulator.storageLayer.import(storageExportDir, { initiatedBy: "start" });
}
}
// Hosting emulator needs to start after all of the others so that we can detect
// which are running and call useEmulator in __init.js
if (listenForEmulator.hosting) {
const hostingAddr = legacyGetFirstAddr(Emulators.HOSTING);
const hostingEmulator = new HostingEmulator({
host: hostingAddr.host,
port: hostingAddr.port,
options,
});
await startEmulator(hostingEmulator);
}
/**
* Similar to the Hosting emulator, the App Hosting emulator should also
* start after the other emulators. This is because the service running on
* app hosting emulator may depend on other emulators (i.e auth, firestore,
* storage, etc).
*/
const apphostingEmulatorConfig = options.config.src.emulators?.[Emulators.APPHOSTING];
if (listenForEmulator.apphosting) {
const rootDirectory = apphostingEmulatorConfig?.rootDirectory;
const backendRoot = resolveProjectPath({}, rootDirectory ?? "./");
// It doesn't seem as though App Hosting emulator supports multiple backends, infer the correct one
// from the root directory.
let apphostingConfig: AppHostingSingle | undefined;
if (Array.isArray(options.config.src.apphosting)) {
const matchingAppHostingConfig = options.config.src.apphosting.filter(
(config) => resolveProjectPath({}, path.join(".", config.rootDir ?? "/")) === backendRoot,
);
if (matchingAppHostingConfig.length === 1) {
apphostingConfig = matchingAppHostingConfig[0];
}
} else {
apphostingConfig = options.config.src.apphosting;
}
const apphostingAddr = legacyGetFirstAddr(Emulators.APPHOSTING);
if (apphostingEmulatorConfig?.startCommandOverride) {
const apphostingLogger = EmulatorLogger.forEmulator(Emulators.APPHOSTING);