-
Notifications
You must be signed in to change notification settings - Fork 959
/
functionsEmulator.ts
1889 lines (1708 loc) · 62.8 KB
/
functionsEmulator.ts
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 fs from "fs";
import * as path from "path";
import * as express from "express";
import * as clc from "colorette";
import * as http from "http";
import * as jwt from "jsonwebtoken";
import * as cors from "cors";
import * as semver from "semver";
import { URL } from "url";
import { EventEmitter } from "events";
import { Account } from "../types/auth";
import { logger } from "../logger";
import { trackEmulator } from "../track";
import { Constants } from "./constants";
import { EmulatorInfo, EmulatorInstance, Emulators, FunctionsExecutionMode } from "./types";
import * as chokidar from "chokidar";
import * as portfinder from "portfinder";
import * as spawn from "cross-spawn";
import { ChildProcess } from "child_process";
import {
EmulatedTriggerDefinition,
SignatureType,
EventSchedule,
EventTrigger,
formatHost,
FunctionsRuntimeFeatures,
getFunctionService,
getSignatureType,
HttpConstants,
ParsedTriggerDefinition,
emulatedFunctionsFromEndpoints,
emulatedFunctionsByRegion,
getSecretLocalPath,
toBackendInfo,
prepareEndpoints,
BlockingTrigger,
getTemporarySocketPath,
} from "./functionsEmulatorShared";
import { EmulatorRegistry } from "./registry";
import { EmulatorLogger, Verbosity } from "./emulatorLogger";
import { RuntimeWorker, RuntimeWorkerPool } from "./functionsRuntimeWorker";
import { PubsubEmulator } from "./pubsubEmulator";
import { FirebaseError } from "../error";
import { WorkQueue, Work } from "./workQueue";
import { allSettled, connectableHostname, createDestroyer, debounce, randomInt } from "../utils";
import { getCredentialPathAsync } from "../defaultCredentials";
import {
AdminSdkConfig,
constructDefaultAdminSdkConfig,
getProjectAdminSdkConfigOrCached,
} from "./adminSdkConfig";
import { functionIdsAreValid } from "../deploy/functions/validate";
import { Extension, ExtensionSpec, ExtensionVersion } from "../extensions/types";
import { accessSecretVersion } from "../gcp/secretManager";
import * as runtimes from "../deploy/functions/runtimes";
import * as backend from "../deploy/functions/backend";
import * as functionsEnv from "../functions/env";
import { AUTH_BLOCKING_EVENTS, BEFORE_CREATE_EVENT } from "../functions/events/v1";
import { BlockingFunctionsConfig } from "../gcp/identityPlatform";
import { resolveBackend } from "../deploy/functions/build";
import { setEnvVarsForEmulators } from "./env";
import { runWithVirtualEnv } from "../functions/python";
import { Runtime } from "../deploy/functions/runtimes/supported";
import { ExtensionsEmulator } from "./extensionsEmulator";
const EVENT_INVOKE_GA4 = "functions_invoke"; // event name GA4 (alphanumertic)
/*
* The Realtime Database emulator expects the `path` field in its trigger
* definition to be relative to the database root. This regex is used to extract
* that path from the `resource` member in the trigger definition used by the
* functions emulator.
*
* Groups:
* 1 - instance
* 2 - path
*/
const DATABASE_PATH_PATTERN = new RegExp("^projects/[^/]+/instances/([^/]+)/refs(/.*)$");
/**
* EmulatableBackend represents a group of functions to be emulated.
* This can be a CF3 module, or an Extension.
*/
export interface EmulatableBackend {
functionsDir: string;
env: Record<string, string>;
secretEnv: backend.SecretEnvVar[];
codebase: string;
predefinedTriggers?: ParsedTriggerDefinition[];
runtime?: Runtime;
bin?: string;
extensionInstanceId?: string;
extension?: Extension; // Only present for published extensions
extensionVersion?: ExtensionVersion; // Only present for published extensions
extensionSpec?: ExtensionSpec; // Only present for local extensions
ignore?: string[];
}
/**
* BackendInfo is an API type used by the Emulator UI containing info about an Extension or CF3 module.
*/
export interface BackendInfo {
directory: string;
env: Record<string, string>; // TODO: Consider exposing more information about where param values come from & if they are locally overwritten.
functionTriggers: ParsedTriggerDefinition[];
extensionInstanceId?: string;
extension?: Extension; // Only present for published extensions
extensionVersion?: ExtensionVersion; // Only present for published extensions
extensionSpec?: ExtensionSpec; // Only present for local extensions
labels?: Record<string, string>;
}
export interface FunctionsEmulatorArgs {
projectId: string;
projectDir: string;
emulatableBackends: EmulatableBackend[];
debugPort: number | boolean;
account?: Account;
port?: number;
host?: string;
verbosity?: "SILENT" | "QUIET" | "INFO" | "DEBUG";
disabledRuntimeFeatures?: FunctionsRuntimeFeatures;
remoteEmulators?: Record<string, EmulatorInfo>;
adminSdkConfig?: AdminSdkConfig;
projectAlias?: string;
extensionsEmulator?: ExtensionsEmulator;
}
/**
* IPC connection info of a Function Runtime.
*/
export class IPCConn {
constructor(readonly socketPath: string) {}
httpReqOpts(): http.RequestOptions {
return {
socketPath: this.socketPath,
};
}
}
/**
* TCP/IP connection info of a Function Runtime.
*/
export class TCPConn {
constructor(
readonly host: string,
readonly port: number,
) {}
httpReqOpts(): http.RequestOptions {
return {
host: this.host,
port: this.port,
};
}
}
export interface FunctionsRuntimeInstance {
process: ChildProcess;
// An emitter which sends our EmulatorLog events from the runtime.
events: EventEmitter;
// A cwd of the process
cwd: string;
// Communication info for the runtime
conn: IPCConn | TCPConn;
}
export interface InvokeRuntimeOpts {
nodeBinary: string;
extensionTriggers?: ParsedTriggerDefinition[];
ignore_warnings?: boolean;
}
interface RequestWithRawBody extends express.Request {
rawBody: Buffer;
}
interface EmulatedTriggerRecord {
backend: EmulatableBackend;
def: EmulatedTriggerDefinition;
enabled: boolean;
ignored: boolean;
url?: string;
}
export class FunctionsEmulator implements EmulatorInstance {
static getHttpFunctionUrl(
projectId: string,
name: string,
region: string,
info?: { host: string; port: number },
): string {
let url: URL;
if (info) {
url = new URL("http://" + formatHost(info));
} else {
url = EmulatorRegistry.url(Emulators.FUNCTIONS);
}
url.pathname = `/${projectId}/${region}/${name}`;
return url.toString();
}
private destroyServer?: () => Promise<void>;
private triggers: Record<string, EmulatedTriggerRecord> = {};
// Keep a "generation number" for triggers so that we can disable functions
// and reload them with a new name.
private triggerGeneration = 0;
private workerPools: Record<string, RuntimeWorkerPool>;
private workQueue: WorkQueue;
private logger = EmulatorLogger.forEmulator(Emulators.FUNCTIONS);
private multicastTriggers: { [s: string]: string[] } = {};
private adminSdkConfig: AdminSdkConfig;
private blockingFunctionsConfig: BlockingFunctionsConfig = {};
private staticBackends: EmulatableBackend[] = [];
private dynamicBackends: EmulatableBackend[] = [];
debugMode = false;
constructor(private args: FunctionsEmulatorArgs) {
this.staticBackends = args.emulatableBackends;
// TODO: Would prefer not to have static state but here we are!
EmulatorLogger.setVerbosity(
this.args.verbosity ? Verbosity[this.args.verbosity] : Verbosity["DEBUG"],
);
// When debugging is enabled, the "timeout" feature needs to be disabled so that
// functions don't timeout while a breakpoint is active.
if (this.args.debugPort) {
// N.B. Technically this will create false positives where there is a Node
// and a Python codebase, but there is no good place to check the runtime
// because that may not be present until discovery (e.g. node codebases
// return their runtime based on package.json if not specified in
// firebase.json)
const maybeNodeCodebases = this.staticBackends.filter(
(b) => !b.runtime || b.runtime.startsWith("node"),
);
if (maybeNodeCodebases.length > 1 && typeof this.args.debugPort === "number") {
throw new FirebaseError(
"Cannot debug on a single port with multiple codebases. " +
"Use --inspect-functions=true to assign dynamic ports to each codebase",
);
}
this.args.disabledRuntimeFeatures = this.args.disabledRuntimeFeatures || {};
this.args.disabledRuntimeFeatures.timeout = true;
this.debugMode = true;
}
this.adminSdkConfig = { ...this.args.adminSdkConfig, projectId: this.args.projectId };
const mode = this.debugMode ? FunctionsExecutionMode.SEQUENTIAL : FunctionsExecutionMode.AUTO;
this.workerPools = {};
for (const backend of this.staticBackends) {
const pool = new RuntimeWorkerPool(mode);
this.workerPools[backend.codebase] = pool;
}
this.workQueue = new WorkQueue(mode);
}
private async loadDynamicExtensionBackends(): Promise<void> {
// New extensions defined in functions codebase create new backends
if (this.args.extensionsEmulator) {
const unfilteredBackends = this.args.extensionsEmulator.getDynamicExtensionBackends();
this.dynamicBackends =
this.args.extensionsEmulator.filterUnemulatedTriggers(unfilteredBackends);
const mode = this.debugMode ? FunctionsExecutionMode.SEQUENTIAL : FunctionsExecutionMode.AUTO;
const credentialEnv = await this.getCredentialsEnvironment();
for (const backend of this.dynamicBackends) {
backend.env = { ...credentialEnv, ...backend.env };
if (this.workerPools[backend.codebase]) {
// Make sure we don't have stale workers.
if (this.debugMode) {
this.workerPools[backend.codebase].exit();
} else {
this.workerPools[backend.codebase].refresh();
}
} else {
const pool = new RuntimeWorkerPool(mode);
this.workerPools[backend.codebase] = pool;
}
// They need to be force loaded because otherwise
// changes in parameters that don't otherwise affect the
// trigger might be missed.
await this.loadTriggers(backend, /* force */ true);
}
}
}
private async getCredentialsEnvironment(): Promise<Record<string, string>> {
// Provide default application credentials when appropriate
const credentialEnv: Record<string, string> = {};
if (process.env.GOOGLE_APPLICATION_CREDENTIALS) {
this.logger.logLabeled(
"WARN",
"functions",
`Your GOOGLE_APPLICATION_CREDENTIALS environment variable points to ${process.env.GOOGLE_APPLICATION_CREDENTIALS}. Non-emulated services will access production using these credentials. Be careful!`,
);
} else if (this.args.account) {
const defaultCredPath = await getCredentialPathAsync(this.args.account);
if (defaultCredPath) {
this.logger.log("DEBUG", `Setting GAC to ${defaultCredPath}`);
credentialEnv.GOOGLE_APPLICATION_CREDENTIALS = defaultCredPath;
}
} else {
// TODO: It would be safer to set GOOGLE_APPLICATION_CREDENTIALS to /dev/null here but we can't because some SDKs don't work
// without credentials even when talking to the emulator: https://github.com/firebase/firebase-js-sdk/issues/3144
this.logger.logLabeled(
"WARN",
"functions",
"You are not signed in to the Firebase CLI. If you have authorized this machine using gcloud application-default credentials those may be discovered and used to access production services.",
);
}
return credentialEnv;
}
createHubServer(): express.Application {
// TODO(samstern): Should not need this here but some tests are directly calling this method
// because FunctionsEmulator.start() used to not be test safe.
this.workQueue.start();
const hub = express();
const dataMiddleware: express.RequestHandler = (req, res, next) => {
const chunks: Buffer[] = [];
req.on("data", (chunk: Buffer) => {
chunks.push(chunk);
});
req.on("end", () => {
(req as RequestWithRawBody).rawBody = Buffer.concat(chunks);
next();
});
};
// The URL for the function that the other emulators (Firestore, etc) use.
// TODO(abehaskins): Make the other emulators use the route below and remove this.
const backgroundFunctionRoute = `/functions/projects/:project_id/triggers/:trigger_name(*)`;
// The URL that the developer sees, this is the same URL that the legacy emulator used.
const httpsFunctionRoute = `/${this.args.projectId}/:region/:trigger_name`;
// The URL for events meant to trigger multiple functions
const multicastFunctionRoute = `/functions/projects/:project_id/trigger_multicast`;
// A trigger named "foo" needs to respond at "foo" as well as "foo/*" but not "fooBar".
const httpsFunctionRoutes = [httpsFunctionRoute, `${httpsFunctionRoute}/*`];
// The URL for the listBackends endpoint, which is used by the Emulator UI.
const listBackendsRoute = `/backends`;
const httpsHandler: express.RequestHandler = (req, res) => {
const work: Work = () => {
return this.handleHttpsTrigger(req, res);
};
work.type = `${req.path}-${new Date().toISOString()}`;
this.workQueue.submit(work);
};
const multicastHandler: express.RequestHandler = (req: express.Request, res) => {
const projectId = req.params.project_id;
const rawBody = (req as RequestWithRawBody).rawBody;
const event = JSON.parse(rawBody.toString());
let triggerKey: string;
if (req.headers["content-type"]?.includes("cloudevent")) {
triggerKey = `${this.args.projectId}:${event.type}`;
} else {
triggerKey = `${this.args.projectId}:${event.eventType}`;
}
if (event.data.bucket) {
triggerKey += `:${event.data.bucket}`;
}
const triggers = this.multicastTriggers[triggerKey] || [];
const { host, port } = this.getInfo();
triggers.forEach((triggerId) => {
const work: Work = () => {
return new Promise<void>((resolve, reject) => {
const trigReq = http.request({
host: connectableHostname(host),
port,
method: req.method,
path: `/functions/projects/${projectId}/triggers/${triggerId}`,
headers: req.headers,
});
trigReq.on("error", reject);
trigReq.write(rawBody);
trigReq.end();
resolve();
});
};
work.type = `${triggerId}-${new Date().toISOString()}`;
this.workQueue.submit(work);
});
res.json({ status: "multicast_acknowledged" });
};
const listBackendsHandler: express.RequestHandler = (req, res) => {
res.json({ backends: this.getBackendInfo() });
};
// The ordering here is important. The longer routes (background)
// need to be registered first otherwise the HTTP functions consume
// all events.
hub.get(listBackendsRoute, cors({ origin: true }), listBackendsHandler); // This route needs CORS so the Emulator UI can call it.
hub.post(backgroundFunctionRoute, dataMiddleware, httpsHandler);
hub.post(multicastFunctionRoute, dataMiddleware, multicastHandler);
hub.all(httpsFunctionRoutes, dataMiddleware, httpsHandler);
hub.all("*", dataMiddleware, (req, res) => {
logger.debug(`Functions emulator received unknown request at path ${req.path}`);
res.sendStatus(404);
});
return hub;
}
async sendRequest(trigger: EmulatedTriggerDefinition, body?: any) {
const record = this.getTriggerRecordByKey(this.getTriggerKey(trigger));
const pool = this.workerPools[record.backend.codebase];
if (!pool.readyForWork(trigger.id)) {
try {
await this.startRuntime(record.backend, trigger);
} catch (e: any) {
this.logger.logLabeled("ERROR", `Failed to start runtime for ${trigger.id}: ${e}`);
return;
}
}
const worker = pool.getIdleWorker(trigger.id)!;
if (this.debugMode) {
await worker.sendDebugMsg({
functionTarget: trigger.entryPoint,
functionSignature: getSignatureType(trigger),
});
}
const reqBody = JSON.stringify(body);
const headers = {
"Content-Type": "application/json",
"Content-Length": `${reqBody.length}`,
};
return new Promise((resolve, reject) => {
const req = http.request(
{
...worker.runtime.conn.httpReqOpts(),
path: `/`,
headers: headers,
},
resolve,
);
req.on("error", reject);
req.write(reqBody);
req.end();
});
}
async start(): Promise<void> {
const credentialEnv = await this.getCredentialsEnvironment();
for (const e of this.staticBackends) {
e.env = { ...credentialEnv, ...e.env };
}
if (Object.keys(this.adminSdkConfig || {}).length <= 1) {
const adminSdkConfig = await getProjectAdminSdkConfigOrCached(this.args.projectId);
if (adminSdkConfig) {
this.adminSdkConfig = adminSdkConfig;
} else {
this.logger.logLabeled(
"WARN",
"functions",
"Unable to fetch project Admin SDK configuration, Admin SDK behavior in Cloud Functions emulator may be incorrect.",
);
this.adminSdkConfig = constructDefaultAdminSdkConfig(this.args.projectId);
}
}
const { host, port } = this.getInfo();
this.workQueue.start();
const server = this.createHubServer().listen(port, host);
this.destroyServer = createDestroyer(server);
return Promise.resolve();
}
async connect(): Promise<void> {
for (const backend of this.staticBackends) {
this.logger.logLabeled(
"BULLET",
"functions",
`Watching "${backend.functionsDir}" for Cloud Functions...`,
);
const watcher = chokidar.watch(backend.functionsDir, {
ignored: [
/.+?[\\\/]node_modules[\\\/].+?/, // Ignore node_modules
/(^|[\/\\])\../, // Ignore files which begin the a period
/.+\.log/, // Ignore files which have a .log extension
/.+?[\\\/]venv[\\\/].+?/, // Ignore site-packages in venv
...(backend.ignore?.map((i) => `**/${i}`) ?? []),
],
persistent: true,
});
const debouncedLoadTriggers = debounce(() => this.loadTriggers(backend), 1000);
watcher.on("change", (filePath) => {
this.logger.log("DEBUG", `File ${filePath} changed, reloading triggers`);
return debouncedLoadTriggers();
});
await this.loadTriggers(backend, /* force= */ true);
}
await this.performPostLoadOperations();
return;
}
async stop(): Promise<void> {
try {
await this.workQueue.flush();
} catch (e: any) {
this.logger.logLabeled(
"WARN",
"functions",
"Functions emulator work queue did not empty before stopping",
);
}
this.workQueue.stop();
for (const pool of Object.values(this.workerPools)) {
pool.exit();
}
if (this.destroyServer) {
await this.destroyServer();
}
}
async discoverTriggers(
emulatableBackend: EmulatableBackend,
): Promise<EmulatedTriggerDefinition[]> {
if (emulatableBackend.predefinedTriggers) {
return emulatedFunctionsByRegion(
emulatableBackend.predefinedTriggers,
emulatableBackend.secretEnv,
);
} else {
const runtimeConfig = this.getRuntimeConfig(emulatableBackend);
const runtimeDelegateContext: runtimes.DelegateContext = {
projectId: this.args.projectId,
projectDir: this.args.projectDir,
sourceDir: emulatableBackend.functionsDir,
runtime: emulatableBackend.runtime,
};
const runtimeDelegate = await runtimes.getRuntimeDelegate(runtimeDelegateContext);
logger.debug(`Validating ${runtimeDelegate.language} source`);
await runtimeDelegate.validate();
logger.debug(`Building ${runtimeDelegate.language} source`);
await runtimeDelegate.build();
// Retrieve information from the runtime delegate.
emulatableBackend.runtime = runtimeDelegate.runtime;
emulatableBackend.bin = runtimeDelegate.bin;
// Don't include user envs when parsing triggers. Do include user envs when resolving parameter values
const firebaseConfig = this.getFirebaseConfig();
const environment = {
...this.getSystemEnvs(),
...this.getEmulatorEnvs(),
FIREBASE_CONFIG: firebaseConfig,
...emulatableBackend.env,
};
const userEnvOpt: functionsEnv.UserEnvsOpts = {
functionsSource: emulatableBackend.functionsDir,
projectId: this.args.projectId,
projectAlias: this.args.projectAlias,
isEmulator: true,
};
const userEnvs = functionsEnv.loadUserEnvs(userEnvOpt);
const discoveredBuild = await runtimeDelegate.discoverBuild(runtimeConfig, environment);
if (discoveredBuild.extensions && this.args.extensionsEmulator) {
await this.args.extensionsEmulator.addDynamicExtensions(
emulatableBackend.codebase,
discoveredBuild,
);
await this.loadDynamicExtensionBackends();
}
const resolution = await resolveBackend({
build: discoveredBuild,
firebaseConfig: JSON.parse(firebaseConfig),
userEnvOpt,
userEnvs,
nonInteractive: false,
isEmulator: true,
});
const discoveredBackend = resolution.backend;
const endpoints = backend.allEndpoints(discoveredBackend);
prepareEndpoints(endpoints);
for (const e of endpoints) {
e.codebase = emulatableBackend.codebase;
}
return emulatedFunctionsFromEndpoints(endpoints);
}
}
/**
* When a user changes their code, we need to look for triggers defined in their updates sources.
*
* TODO(b/216167890): Gracefully handle removal of deleted function definitions
*/
async loadTriggers(emulatableBackend: EmulatableBackend, force = false): Promise<void> {
let triggerDefinitions: EmulatedTriggerDefinition[] = [];
try {
triggerDefinitions = await this.discoverTriggers(emulatableBackend);
this.logger.logLabeled(
"SUCCESS",
"functions",
`Loaded functions definitions from source: ${triggerDefinitions
.map((t) => t.entryPoint)
.join(", ")}.`,
);
} catch (e) {
this.logger.logLabeled(
"ERROR",
"functions",
`Failed to load function definition from source: ${e}`,
);
return;
}
// Before loading any triggers we need to make sure there are no 'stale' workers
// in the pool that would cause us to run old code.
if (this.debugMode) {
// Kill the workerPool. This should clean up all inspectors connected to the debug port.
this.workerPools[emulatableBackend.codebase].exit();
} else {
this.workerPools[emulatableBackend.codebase].refresh();
}
// Remove any old trigger definitions
const toRemove = Object.keys(this.triggers).filter((recordKey) => {
const record = this.getTriggerRecordByKey(recordKey);
if (record.backend.codebase !== emulatableBackend.codebase) {
// Order is important here. This needs to go before any other checks.
// We are only loading one codebase, don't delete triggers from another.
return false;
}
if (force) {
return true; // We are going to load all of the triggers anyway, so we can remove everything
}
return !triggerDefinitions.some(
(def) =>
record.def.entryPoint === def.entryPoint &&
JSON.stringify(record.def.eventTrigger) === JSON.stringify(def.eventTrigger),
);
});
await this.removeTriggers(toRemove);
// When force is true we set up all triggers, otherwise we only set up
// triggers which have a unique function name
const toSetup = triggerDefinitions.filter((definition) => {
if (force) {
return true;
}
// We want to add a trigger if we don't already have an enabled trigger
// with the same entryPoint / trigger.
const anyEnabledMatch = Object.values(this.triggers).some((record) => {
const sameEntryPoint = record.def.entryPoint === definition.entryPoint;
// If they both have event triggers, make sure they match
const sameEventTrigger =
JSON.stringify(record.def.eventTrigger) === JSON.stringify(definition.eventTrigger);
if (sameEntryPoint && !sameEventTrigger) {
this.logger.log(
"DEBUG",
`Definition for trigger ${definition.entryPoint} changed from ${JSON.stringify(
record.def.eventTrigger,
)} to ${JSON.stringify(definition.eventTrigger)}`,
);
}
return record.enabled && sameEntryPoint && sameEventTrigger;
});
return !anyEnabledMatch;
});
for (const definition of toSetup) {
// Skip function with invalid id.
try {
// Note - in the emulator, functionId = {region}-{functionName}, but in prod, functionId=functionName.
// To match prod behavior, only validate functionName
functionIdsAreValid([{ ...definition, id: definition.name }]);
} catch (e: any) {
throw new FirebaseError(`functions[${definition.id}]: Invalid function id: ${e.message}`);
}
let added = false;
let url: string | undefined = undefined;
if (definition.httpsTrigger) {
added = true;
url = FunctionsEmulator.getHttpFunctionUrl(
this.args.projectId,
definition.name,
definition.region,
);
if (definition.taskQueueTrigger) {
added = await this.addTaskQueueTrigger(
this.args.projectId,
definition.region,
definition.name,
url,
definition.taskQueueTrigger,
);
}
} else if (definition.eventTrigger) {
const service: string = getFunctionService(definition);
const key = this.getTriggerKey(definition);
const signature = getSignatureType(definition);
switch (service) {
case Constants.SERVICE_FIRESTORE:
added = await this.addFirestoreTrigger(
this.args.projectId,
key,
definition.eventTrigger,
signature,
);
break;
case Constants.SERVICE_REALTIME_DATABASE:
added = await this.addRealtimeDatabaseTrigger(
this.args.projectId,
definition.id,
key,
definition.eventTrigger,
signature,
definition.region,
);
break;
case Constants.SERVICE_PUBSUB:
added = await this.addPubsubTrigger(
definition.name,
key,
definition.eventTrigger,
signature,
definition.schedule,
);
break;
case Constants.SERVICE_EVENTARC:
added = await this.addEventarcTrigger(
this.args.projectId,
key,
definition.eventTrigger,
);
break;
case Constants.SERVICE_AUTH:
added = this.addAuthTrigger(this.args.projectId, key, definition.eventTrigger);
break;
case Constants.SERVICE_STORAGE:
added = this.addStorageTrigger(this.args.projectId, key, definition.eventTrigger);
break;
case Constants.SERVICE_FIREALERTS:
added = await this.addFirealertsTrigger(
this.args.projectId,
key,
definition.eventTrigger,
);
break;
default:
this.logger.log("DEBUG", `Unsupported trigger: ${JSON.stringify(definition)}`);
break;
}
} else if (definition.blockingTrigger) {
url = FunctionsEmulator.getHttpFunctionUrl(
this.args.projectId,
definition.name,
definition.region,
);
added = this.addBlockingTrigger(url, definition.blockingTrigger);
} else {
this.logger.log(
"WARN",
`Unsupported function type on ${definition.name}. Expected either an httpsTrigger, eventTrigger, or blockingTrigger.`,
);
}
const ignored = !added;
this.addTriggerRecord(definition, { backend: emulatableBackend, ignored, url });
const triggerType = definition.httpsTrigger
? "http"
: Constants.getServiceName(getFunctionService(definition));
if (ignored) {
const msg = `function ignored because the ${triggerType} emulator does not exist or is not running.`;
this.logger.logLabeled("BULLET", `functions[${definition.id}]`, msg);
} else {
const msg = url
? `${clc.bold(triggerType)} function initialized (${url}).`
: `${clc.bold(triggerType)} function initialized.`;
this.logger.logLabeled("SUCCESS", `functions[${definition.id}]`, msg);
}
}
// In debug mode, we eagerly start the runtime processes to allow debuggers to attach
// before invoking a function.
if (this.debugMode) {
if (!emulatableBackend.runtime?.startsWith("node")) {
this.logger.log("WARN", "--inspect-functions only supported for Node.js runtimes.");
} else {
// Since we're about to start a runtime to be shared by all the functions in this codebase,
// we need to make sure it has all the secrets used by any function in the codebase.
emulatableBackend.secretEnv = Object.values(
triggerDefinitions.reduce(
(acc: Record<string, backend.SecretEnvVar>, curr: EmulatedTriggerDefinition) => {
for (const secret of curr.secretEnvironmentVariables || []) {
acc[secret.key] = secret;
}
return acc;
},
{},
),
);
try {
await this.startRuntime(emulatableBackend);
} catch (e: any) {
this.logger.logLabeled(
"ERROR",
`Failed to start functions in ${emulatableBackend.functionsDir}: ${e}`,
);
}
}
}
}
// Currently only cleans up eventarc and firealerts triggers
async removeTriggers(toRemove: string[]) {
for (const triggerKey of toRemove) {
const definition = this.triggers[triggerKey].def;
const service = getFunctionService(definition);
const key = this.getTriggerKey(definition);
switch (service) {
case Constants.SERVICE_EVENTARC:
await this.removeEventarcTrigger(
this.args.projectId,
key,
definition.eventTrigger as EventTrigger,
);
delete this.triggers[key];
break;
case Constants.SERVICE_FIREALERTS:
await this.removeFirealertsTrigger(
this.args.projectId,
key,
definition.eventTrigger as EventTrigger,
);
delete this.triggers[key];
break;
default:
break;
}
}
}
async addEventarcTrigger(
projectId: string,
key: string,
eventTrigger: EventTrigger,
): Promise<boolean> {
if (!EmulatorRegistry.isRunning(Emulators.EVENTARC)) {
return false;
}
const bundle = {
eventTrigger: {
...eventTrigger,
service: "eventarc.googleapis.com",
},
};
logger.debug(`addEventarcTrigger`, JSON.stringify(bundle));
try {
await EmulatorRegistry.client(Emulators.EVENTARC).post(
`/emulator/v1/projects/${projectId}/triggers/${key}`,
bundle,
);
return true;
} catch (err: unknown) {
this.logger.log("WARN", "Error adding Eventarc function: " + err);
}
return false;
}
async removeEventarcTrigger(
projectId: string,
key: string,
eventTrigger: EventTrigger,
): Promise<boolean> {
if (!EmulatorRegistry.isRunning(Emulators.EVENTARC)) {
return Promise.resolve(false);
}
const bundle = {
eventTrigger: {
...eventTrigger,
service: "eventarc.googleapis.com",
},
};
logger.debug(`removeEventarcTrigger`, JSON.stringify(bundle));
try {
await EmulatorRegistry.client(Emulators.EVENTARC).post(
`/emulator/v1/remove/projects/${projectId}/triggers/${key}`,
bundle,
);
return true;
} catch (err: unknown) {
this.logger.log("WARN", "Error removing Eventarc function: " + err);
}
return false;
}
async addFirealertsTrigger(
projectId: string,
key: string,
eventTrigger: EventTrigger,
): Promise<boolean> {
if (!EmulatorRegistry.isRunning(Emulators.EVENTARC)) {
return false;
}
const bundle = {
eventTrigger: {
...eventTrigger,
service: "firebasealerts.googleapis.com",
},
};
logger.debug(`addFirealertsTrigger`, JSON.stringify(bundle));
try {
await EmulatorRegistry.client(Emulators.EVENTARC).post(
`/emulator/v1/projects/${projectId}/triggers/${key}`,
bundle,
);
return true;
} catch (err: unknown) {
this.logger.log("WARN", "Error adding FireAlerts function: " + err);
}
return false;
}
async removeFirealertsTrigger(
projectId: string,
key: string,
eventTrigger: EventTrigger,
): Promise<boolean> {
if (!EmulatorRegistry.isRunning(Emulators.EVENTARC)) {
return false;
}
const bundle = {
eventTrigger: {
...eventTrigger,
service: "firebasealerts.googleapis.com",
},
};
logger.debug(`removeFirealertsTrigger`, JSON.stringify(bundle));
try {
await EmulatorRegistry.client(Emulators.EVENTARC).post(
`/emulator/v1/remove/projects/${projectId}/triggers/${key}`,
bundle,
);
return true;
} catch (err: unknown) {
this.logger.log("WARN", "Error removing FireAlerts function: " + err);
}
return false;
}
async performPostLoadOperations(): Promise<void> {
if (
!this.blockingFunctionsConfig.triggers &&
!this.blockingFunctionsConfig.forwardInboundCredentials
) {
return;
}
if (!EmulatorRegistry.isRunning(Emulators.AUTH)) {
return;
}
const path = `/identitytoolkit.googleapis.com/v2/projects/${this.getProjectId()}/config?updateMask=blockingFunctions`;
try {
const client = EmulatorRegistry.client(Emulators.AUTH);
await client.patch(
path,
{ blockingFunctions: this.blockingFunctionsConfig },
{
headers: { Authorization: "Bearer owner" },
},
);
} catch (err) {
this.logger.log(
"WARN",
"Error updating blocking functions config to the auth emulator: " + err,
);